id
stringlengths
3
6
prompt
stringlengths
100
55.1k
response_j
stringlengths
30
18.4k
236071
I'm trying to determine the best way to structure my application so that I don't get a lot of javascript splattered all over the place. I have an ASP.NET MVC application with a view which loads a sllooooowwwww partial view using Michael Kennedy's approach to [Improve perceived performance of ASP.NET MVC websites with asynchronous partial views](http://blog.michaelckennedy.net/2012/11/13/improve-perceived-performance-of-asp-net-mvc-websites-with-async-partialviews/). The partial view itself is rendering a [DataTables](http://datatables.net) grid (which has its own CSS/JS files), as well as Javascript-based configuration for the grid itself (column formatting, sorting defaults, editor configuration, etc). My question is what is a clean way to structure and maintain all this? I have at least 3 varieties of scripts (CSS and/or JS) involved here: 1. The JS on the main view which loads the partial view. 2. The CSS/JSfiles for DataTables 3. The JS inside the partial view which runs on `$(document).ready()` and configures that particular grid. I can control (on the main view) where the CSS/JS are rendered using Razor's `@section` for scripts/styles (Item #1 above). However, a partial view can't take advantage of the `@section` functionality, so any CSS/JS in a partial view gets injected into the middle of the page. That doesn't really set well with me, because then the rendered HTML looks all nasty with CSS/JS showing up in the middle of the main view. I know things like [Cassette](http://getcassette.net) can help with Item #2 when the CSS/JS are all stored in external files. But what about Item #3 where I have CSS/JS which is very specific to that partial view? It may be things as small as attaching click event handlers for the view or configuring JQuery plugins, but does that mean I should separate that out into another JS file? I don't like separating these things if I don't need to, especially the grid configuration for each partial view. In my case, I have an application with several views containing these partial views which render grids, and none of the grids contain the same set of columns - so the JS configuration for each grid is different which runs on `$(document).ready()`.
I would consider not using partial views at all, for the reasons that you mentioned. Instead of loading partial views with ajax, load json data from controller. Use JavaScript template like handlebars.js to get the razor effect on the client side. Much cleaner. Smaller http payload.
236702
I have a digraph which I've set to "rankdir=LR;" so that "rank=same" will be top-to-bottom. I decided to add a few clusters to this graph, but as a result "rank=same" has now become bottom-to-top. A minimal example shows the problem: ``` digraph graph { graph [ rankdir=LR; nodesep = "0.5 equally", newrank = true; ]; /* Guide Nodes */ rank1 [style=dotted]; rank2 [style=dotted]; rank1 -> rank2 [style=dotted]; /* Node Clusters */ subgraph cluster1 { A; B; C; } /* Node Hierarchy */ A -> Z; B -> Z; C -> Z; /* Node Rank */ { rank=same; rank1 -> A -> B -> C [style=dotted]; } } /* Closes the digraph */ ``` The result that I want is to have from top to bottom: rank1, A, B, C. The result that I get is from top to bottom: C, B, A, rank1 --- as seen in the picture below. [![enter image description here](https://i.stack.imgur.com/QhqoM.png)](https://i.stack.imgur.com/QhqoM.png) How can I get the correct order back? * Option 1: Just don't use clusters. * Option 2: Rewrite the "rank=same" line to fit the bottom-to-top direction. Given the size of my graph, option 2 is simply too much work for too little gain. Is there another option? EDIT: The answer that marapet gave, does most of what I wanted. However, that solution doesn't work with the following minimal problem: ``` digraph g { graph [ rankdir=LR; nodesep = "0.5 equally", newrank = true; ]; /* Node Clusters */ subgraph cluster1 { subgraph cluster2 { A; B; C; } P; subgraph cluster4 { D; E; F; } Z; } /* Guide Nodes */ rank1 [style=dotted]; rank2 [style=dotted]; /* Guide Nodes Hierarchy */ rank1 -> rank2 [style=dotted]; /* Node Hierarchy */ A -> Z; B -> Z; C -> Z; P -> Z; D -> Z; E -> Z; F -> Z; /* Rank Constraints */ rank1 -> A -> B -> C -> P -> D -> E -> F [style=dotted, constraint=false]; } /* Closes the digraph */ ``` This results in the following picture: [![enter image description here](https://i.stack.imgur.com/WDbuH.png)](https://i.stack.imgur.com/WDbuH.png) I can only conclude that the issue I'm having is the result of mixing clusters and non-clusters in the same-rank-edges.
Testcontainers uses the self-typing mechanism: ```java class GenericContainer<SELF extends GenericContainer<SELF>> implements Container<SELF> { ... } ``` This was a decision to make fluent methods work even if the class is being extended: ```java class GenericContainer<SELF extends GenericContainer<SELF>> implements Container<SELF> { public SELF withExposedPorts(Integer... ports) { this.setExposedPorts(newArrayList(ports)); return self(); } } ``` Now, even if there is a child class, it will return the final type, not just `GenericContainer`: ```java class MyContainer extends GenericContainer< MyContainer> { } MyContainer container = new MyContainer() .withExposedPorts(12345); // <- without SELF, it would return "GenericContainer" ``` FYI it is scheduled for Testcontainers 2.0 to change the approach, you will find more info in the following presentation: <https://speakerdeck.com/bsideup/geecon-2019-testcontainers-a-year-in-review?slide=74>
236741
It's my first time trying out this package and I followed the installation guide at <https://laravel.com/docs/8.x/passport> but when this code block in my controller signup action it throws the error: ``` $token = $user->createToken('authToken')->accessToken; ``` Here's the code for my signup action: ``` public function signup(Request $request){ $request->validate([ 'name' => 'required', 'email' => 'required|string|email:rfc,dns|unique:users', 'password' => 'required|string|confirmed' ]); $user = new User([ 'name' => $request->name, 'email' => $request->email, 'password' => bcrypt($request->password) ]); $user->save(); $token = $user->createToken('authToken')->accessToken; return response()->json([ 'message' => 'Successfully created user!', 'access_token' => $token ], 201); } ``` * Passport Version: 10.0 * Laravel Version: 8.16.1 * PHP Version: 7.4.13 * Database Driver & Version: MySQL 5.7.24
I found the solution on: <https://github.com/laravel/passport/issues/1381>. In composer.json just add "lcobucci/jwt": "3.3.3" and execute composer update.
236912
I've added a few jars from the Factual API, my project builds fine, and the jars can be accessed from my main module. However, when I run the app I'm getting 'java.lang.verify' error as follows: ``` 11-05 13:18:07.094 4612-4612/com.example.nickm.tddeals E/AndroidRuntime﹕ FATAL EXCEPTION: main java.lang.VerifyError: com/factual/driver/Factual at com.example.nickm.tddeals.Map.onCreate(Map.java:38) at android.app.Activity.performCreate(Activity.java:5104) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) at android.app.ActivityThread.access$600(ActivityThread.java:141) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:5041) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) at dalvik.system.NativeStart.main(Native Method) ``` My main activity uses a google map (that is working without the Factual instantiation) and eventually attempts to instantiate a Factual object, where the error is thrown. ``` import android.location.Location; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import com.factual.driver.Factual; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; public class Map extends FragmentActivity { private GoogleMap mMap; // Might be null if Google Play services APK is not available. private Factual factual; private double myLatitude; private double myLongitude; private GPSService gpsService; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_map); setUpMapIfNeeded(); updateLocation(); LatLng latLng = new LatLng(gpsService.getLatitude(), gpsService.getLongitude()); CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 17); mMap.animateCamera(cameraUpdate); factual = new Factual("snip", "snip"); } @Override protected void onResume() { super.onResume(); setUpMapIfNeeded(); } /** * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly * installed) and the map has not already been instantiated.. This will ensure that we only ever * call {@link #setUpMap()} once when {@link #mMap} is not null. * <p> * If it isn't installed {@link SupportMapFragment} (and * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to * install/update the Google Play services APK on their device. * <p> * A user can return to this FragmentActivity after following the prompt and correctly * installing/updating/enabling the Google Play services. Since the FragmentActivity may not * have been completely destroyed during this process (it is likely that it would only be * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this * method in {@link #onResume()} to guarantee that it will be called. */ private void setUpMapIfNeeded() { // Do a null check to confirm that we have not already instantiated the map. if (mMap == null) { // Try to obtain the map from the SupportMapFragment. mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) .getMap(); // Check if we were successful in obtaining the map. if (mMap != null) { setUpMap(); } } } /** * This is where we can add markers or lines, add listeners or move the camera. In this case, we * just add a marker near Africa. * <p> * This should only be called once and when we are sure that {@link #mMap} is not null. */ private void setUpMap() { mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker")); } private void updateLocation(){ gpsService = new GPSService(getApplicationContext()); Location location = gpsService.getLocation(); while(!gpsService.isLocationAvailable) { location = gpsService.getLocation(); } } } ``` Main module gradle: ``` apply plugin: 'com.android.application' android { compileSdkVersion 21 buildToolsVersion '20.0.0' defaultConfig { applicationId "com.example.nickm.tddeals" minSdkVersion 15 targetSdkVersion 21 versionCode 1 versionName "1.0" } buildTypes { release { runProguard false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.google.android.gms:play-services:6.1.11' compile 'com.android.support:appcompat-v7:21.0.0' compile project(':factual-java-driver-1.8.7') compile project(':factual-java-driver-1.8.7-javadoc') compile project(':factual-java-driver-1.8.7-sources') } ``` Doing some searching on this error seems to bring up obscure answers. What could be the problem?
In requiring something similar, where the usual text selection behavior is required on an element which should otherwise respond to `ngClick`, I wrote the following directive, which may be of use: ``` .directive('selectableText', function($window, $timeout) { var i = 0; return { restrict: 'A', priority: 1, compile: function (tElem, tAttrs) { var fn = '$$clickOnNoSelect' + i++, _ngClick = tAttrs.ngClick; tAttrs.ngClick = fn + '($event)'; return function(scope) { var lastAnchorOffset, lastFocusOffset, timer; scope[fn] = function(event) { var selection = $window.getSelection(), anchorOffset = selection.anchorOffset, focusOffset = selection.focusOffset; if(focusOffset - anchorOffset !== 0) { if(!(lastAnchorOffset === anchorOffset && lastFocusOffset === focusOffset)) { lastAnchorOffset = anchorOffset; lastFocusOffset = focusOffset; if(timer) { $timeout.cancel(timer); timer = null; } return; } } lastAnchorOffset = null; lastFocusOffset = null; // delay invoking click so as to watch for user double-clicking // to select words timer = $timeout(function() { scope.$eval(_ngClick, {$event: event}); timer = null; }, 250); }; }; } }; }); ``` Plunker: <http://plnkr.co/edit/kkfXfiLvGXqNYs3N6fTz?p=preview>
237051
I am making a registration system with an e-mail verifier. Your typical "use this code to verify" type of thing. I want a session variable to be stored, so that when people complete their account registration on the registration page and somehow navigate back to the page on accident, it reminds them that they need to activate their account before use. What makes this problem so hard to diagnose is that I have used many other session variables in similar ways, but this one is not working at all. Here's my approach: ``` /* This is placed after the mail script and account creation within the same if statement. Things get executed after it, so I know it's placed correctly. */ $_SESSION['registrationComplete'] = TRUE; // I've tried integer 1 and 'Yes' as alternatives. ``` Now to check for the variable, I placed this at the top of the page. ``` echo $_SESSION['registrationComplete']; // To see if it's setting. This gives the // undefined index notice. if (isset($_SESSION['registrationComplete'])) { // Alternatively, I have nested another if that simply tests if it's TRUE. echo $_SESSION['registrationComplete']; // When echo'd here, it displays nothing. echo '<p>Congratulations, Foo! Go to *link to Bar*.</p>'; } ``` Now, I used to have the page redirect to a new page, but I took that out to test it. When the page reloads from submit, my message in the if statement above appears and then I get an `Notice: Undefined index: registrationComplete blah blah` from the echoing of the session var! Then if I ever go back to the page, it ignores the if statement all together. I have tested for typos and everything, clearing session variables in case old ones from testing were interfering, but I am having no luck. A lot of Googling just shows people suppressing these errors, but that sounds insane! Not only that, but I am not getting the same persistence of session variables elsewhere on my site. Can someone point out if I'm doing something blatantly wrong? Help! Thanks! FYI, I read several related questions and I am also a beginner, so I may not know how to utilize certain advice without explanation. **As requested, more code, heavily annotated to keep it brief** ``` var_dump($_SESSION); // It's here to analyze that index message. I guess it's not important. echo $_SESSION['registrationComplete']; if (isset($_SESSION['registrationComplete'])) { // The golden ticket! This is what I want to appear so badly. echo 'Congratulations, Foo! Go to *link to Bar*.'; } // Explanation: I don't want logged in users registering. // The else statement basically executes the main chunk of code. if (isset($_SESSION['user_id'])) { echo 'You are logged in as someone already.'; } else { if (isset($_POST['submitRegister'])) { // Code: Database connection and parsing variables from the form. if (!empty($email) && !empty($email2) && $email == $email2 && !empty($displayName) && !empty($password) && !empty($password2) && $password == $password2) { // Code: Query to retrieve data for comparison. if (mysqli_num_rows($registrationData) == 0) { // Code: Generates the salt and verification code. // Code: Password hashing and sending data to verify database. // E-mail the verification code. $_SESSION['registrationComplete'] = 'yes'; } else { // Some error handling is here. $registerError = 'The e-mail address you entered is already in use.'; } } // the elseif, elseif, and else are more error handling. elseif ($email != $email2) { $registerError = 'Your e-mails did not match'; } elseif ($password != $password2) { $registerError = 'Passwords didn\'t match.'; } else { $registerError = 'Filled out completely?'; } // If the registration was submitted, but had errors, this will print the form again. if (!isset($_SESSION['registrationComplete'])) { require_once REF_DIR . REF_REGISTERFORM; } // IMPORTANT! it turns out my code did not work, I forgot I had the same statement elsewhere. else { echo 'Congratulations, Foo! Go to *link to Bar*.'; } } // Creates form. else { require_once REF_DIR . REF_REGISTERFORM; } } ```
This came down to the basics of debugging/troubleshooting. 1. Understand as much as you can about the technique/library/function/whatever that you're trying to use. 2. Inspect the salient bits and make sure that they are what you expect or what they should be. (There's a slight difference between those two, depending on the situation.) 3. If that doesn't bring you towards a solution, step back and make sure you're understanding the situation. This may mean simplifying things so that you're only dealing with the issue at hand, i.e. create a separate, simpler test case which exposes the same problem. Or, it may simply mean that you stop coding and work through the flow of your code to make sure it is really doing what you think it is doing. A typical issue with sessions not working is forgetting to use `session_start()` (near or at the top) of any page which uses sessions. One of my favorite snippets of PHP code, for debugging: ``` print '<pre>'; var_dump($some_variable); print '</pre>'; ``` I try to use `print` for debugging and `echo` for regular output. It makes it easier to spot debugging code, once it's goes beyond a few trivial bits of output. Meanwhile, `var_dump` will print a bit more info about the variable, like it's type and size. It's important to wrap it in `<pre></pre>` so that it's easier to read the output.
237671
My current code looks like this ``` void XXX::waitForUpdates() { boost::unique_lock<boost::mutex> lock(mutex_agentDone); while(!allAgentUpdatesDone()) { COND_VAR_AGENT_DONE.wait(lock); } } void XXX::onAgentUpdate(YYY argums){ Agent * target = const_cast<Agent*>(argums.GetAgent()); boost::unique_lock<boost::mutex> lock(mutex_agentDone); REGISTERED_AGENTS.setDone(target,true); COND_VAR_AGENT_DONE.notify_all(); } ``` everything is fine, except when `onAgentUpdate` is called about a million times every 1 second, I have to worry about performance and optimization. So I figured if I change the `wait(lock)` to `timed_wait` version that does the `allAgentUpdatesDone()` check, I can skip `.notify()`s which is otherwise invoked in the order of hundreds of thousands every second! Don't gasp, this is a simulation framework :) Then I asked myseld: what do I need the `mutex_agentDone` for? I can modify the two functions like this: ``` void XXX::waitForUpdates() { //this lock will become practically useless, coz there is no other // mutex_agentDone being locked in any other function. boost::unique_lock<boost::mutex> lock(mutex_agentDone); while(!allAgentUpdatesDone()) { COND_VAR_AGENT_DONE.timed_wait(lock,some_time_interval); } } void XXX::onAgentUpdate(YYY argums){ Agent * target = const_cast<Agent*>(argums.GetAgent()); REGISTERED_AGENTS.setDone(target,true) } ``` The question is: is this safe? thank you A small note: Assume that the rest of operations in the two functions are already safeguarded by their own mutex (`REGISTERED_AGENTS` is a class object having a `container` and its own `mutex` being invoked in every accessor and iteration method, so `allAgentUpdatesDone()` is iterating through the same `container` using same `mutex` as REGISTERED\_AGENTS)
Just quit the Xcode. Reset your simulator content and settings. Clean and build your project again and you are ready to go. **Edited** * delete the Derived Data in the Organizer under Projects or directly in ~/Library/Developer/Xcode/DerivedData * clean the Build Folder by choosing "Product" in the MenuBar and click while you press the Alt-key on "Clean Build Folder" * Restart Xcode Then delete the app from your simulator if it is. Reset your simulator's content and settings. Now clean and build your project. It should work fine.
237913
I want to display 24 unique id's but he is only giving me 1: This is my php ``` <?php $sql = "SELECT id FROM 15players ORDER BY RAND() LIMIT 24"; $result = mysql_query($sql) or die('Query failed: ' . mysql_error()); $row = mysql_fetch_array($result); echo $row['id']; ?> ``` But if I execute this SQL in phpmyadmin, It returns me 24 id's So what am I doing wrong? EDIT: Got the right answer! ``` <?php $sql = "SELECT id FROM 15players ORDER BY RAND() LIMIT 0,24"; $result = mysql_query($sql) or die('Query failed: ' . mysql_error()); while($row = mysql_fetch_array($result)) { echo $row['id']; } ?> ```
`mysql_fetch_array` only returns 1 row you need to loop through the results. ``` while($row = mysql_fetch_array($result)) { echo $row['id']; } ```
237983
The way I know it's deffintely DBNull is when I use String.IsNullOrEmpty it errors out with 'Cant convert type DBNull to type String' I'm using an ODBCDataReader with the following ODBCCommand to transfer from a Quickbooks Desktop company file to a SQL database via LINQ; not sure if this is a quirk of ODBC or something as this is the first time I've used it: ``` SELECT id, string0, string1, string2, string3, int FROM Table1 WHERE (IsActive = 1) ``` To process the result I'm using: ``` IIf(IsDBNull(e(3)) Or IsNothing(e(3)), String.Empty, e(3)) ``` The table I'm transfering to does not allow NULLs. I've tried using Not and swapping the resulting options around, I've tried using Is Nothing and DBNull.Value.Equals() and of course, IsNullOrEmpty. When I don't have IsNullOrEmpty in the statement I get a 'Cannot insert NULL into Table' I've also tried swapping Or with OrElse. As mentioned below I should be using OrElse anyway. Now, with another table in the same company file this code works perfectly with DBNulls. I copied the code directly and I've tried every combination of things I can think of. What could possibly be wrong with this instance that would cause it to not recognize the field type? If you can point me in the right direction, I'd greatly appreciate it.
This is undefined behavior because `ivec` has size `4` yet you are indexing elements such as `4`, `5`, and `9` which are out of bounds. ``` for(auto i : ivec){ cout << ivec[i] << endl; } ``` Instead you should be printing the elements themselves ``` for(auto i : ivec){ cout << i << endl; } ``` To be clear, in your range-based `for` loop `i` is the actual element *not* the index of the element. If you wanted to use indices you would not use a range-based `for` loop ``` for(std::size_t i = 0; i < ivec.size(); ++i){ cout << ivec[i] << endl; } ```
238031
I have a database containing all orders I can connect to and query. Also, I have a text file containing the orders of the last database query I can connect to and query. I need to be able to left join the two in VBA. I don't have any problems with the database as it is in the connection string, but I can't seem to pass the text file path to the SQL string without getting and invalid object error. I am new to SQL and connecting to files. Any help would be appreciated. I am trying to do the following: ``` Sub Comp2TablesFrom2Databases() Dim rs As ADODB.Recordset Dim strSQL As String, strCon As String Set rs = New ADODB.Recordset rs.CursorLocation = adUseClient strCon = "Connection string to database" 'works fine in test code that only connects to the database strSQL = "SELECT * " _ & "FROM Database LEFT JOIN [TextFilePath] " _ & "ON Database.[Order No] = [TextFilePath].[Order No] " _ & "WHERE [TextFilePath].[Order No] IS NULL;" rs.Open strSQL, strCon 'do stuff rs.Close Set rs = Nothing End Sub ```
The mobile registration page allows for users to signup without an email address: <http://touch.facebook.com/r.php>
238313
I've tried almost everything on stack overflow, but to no avail. I've tried it all, but still nothing, so I'm here. I'm simply just trying to set the title to a white color and then set the title to "Terms of Service". Here's what I have: ``` #import <UIKit/UIKit.h> @interface TOCViewController : UINavigationController @end ``` // ``` #import "TOCViewController.h" @interface TOCViewController () @end @implementation TOCViewController - (void)viewDidLoad { [super viewDidLoad]; [self.view setBackgroundColor:[UIColor whiteColor]]; self.navigationBar.barTintColor = [UIColor colorWithRed:52.0/255.0 green:170.0/255.0 blue:220.0/255.0 alpha:1.0]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } @end ```
To set title in `UINavigationBar` set `UIViewController` title ``` - (void)viewDidLoad { [super viewDidLoad]; [self setTitle:@"Terms of Service"]; } ``` For title color you need to set text attributes of `UINavigationBar`. ``` - (void) viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName : [UIColor whiteColor]}; [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]]; } ```
238609
I have a custom content type with a file field. I am trying to attach a file uploaded through a custom form to the custom content type. I am able to load the node and update all the other values of the node except the file field. I found [Realityloop: Programmatically attach files to a node in Drupal 8](https://mzlizz.mit.edu/realityloop-programmatically-attach-files-node-drupal-8), but it doesn't seem to work. This was what was suggested in the above link ``` $node = Node::create([ 'type' => 'article', 'title' => 'Druplicon test', 'field_image' => [ 'target_id' => $file->id(), ], ]); $node->save(); ``` This is what I have tried inside `submitForm` ``` $fid = $form_state->getValue('file_field_name')[0]; $file = File::load($fid); $file->setPermanent(); $file->save(); $node = Node::load($nid); $node->set('file_field_in_node', $file->id); $node->save(); ``` That was setting the file as permanent in the files table but the node did not have the file. I also tried to save with ``` $node->set('file_field_in_node', $file); ``` That did not help either. I am also curious as to which is the file/function that handles the set function for the file field. **UPDATE:** [SOLVED] Not sure what was wrong earlier. Both the approaches seems to be working correctly now. So setting the file\_id or the file object into the file field for the node seem to be saving the node correctly with the file attached to it.
If you use media core module to manage files, you have already uploaded your file, and you want to attached it to filed eg `field_file` ``` $node = Node::load(NID); $node->set('field_file' , ['target_id' => FID]); $node->save(); ``` Note: `FID` is your file id.
238800
I want to print name and salary amount of the employee which has highest salary, till now its okay but if there are multiple records than print all. There are two table given :- EMPLOYEE TABLE :- [![enter image description here](https://i.stack.imgur.com/BuAoV.jpg)](https://i.stack.imgur.com/BuAoV.jpg) SALARY TABLE:- [![salary table](https://i.stack.imgur.com/bvqxM.jpg)](https://i.stack.imgur.com/bvqxM.jpg) my query is: - ```sql SELECT E.NAME, S.AMOUNT FROM `salary` S, employee E WHERE S.EMPLOYEE_ID = E.ID and S.AMOUNT = (SELECT max(`AMOUNT`) FROM `salary`) ``` is there any better way to find out the solution ?
It is "with ties" functionality what you're trying to achieve. Unfortunately mySQL doesn't support that (in the [docs](https://dev.mysql.com/doc/refman/8.0/en/select.html) there is nothing to add to the "LIMIT" part of the query), so you have no other option rather than looking for max salary first and filter records afterwards. So, your solution is fine for that case. Alternatively, if you're on version 8 and newer, you may move the subquery to the with clause ``` with max_sal as ( select max(amount) ms from salary ) SELECT E.NAME, S.AMOUNT FROM salary S JOIN employee E ON S.EMPLOYEE_ID = E.ID JOIN max_sal ms ON S.AMOUNT = ms.ms ``` or search for it in the join directly ``` SELECT E.NAME, S.AMOUNT FROM salary S JOIN employee E ON S.EMPLOYEE_ID = E.ID JOIN (select max(amount) ms from salary) ms ON S.AMOUNT = ms.ms ``` But I'm sure it won't get you any better performance
238876
I have a classifieds website. The website is **php** based, and uses a **mysql** database. Today, I have a sitemap which I have to update using an external php script. This php script takes all classifieds from the database and creates an xml sitemap, fresh. Problem is I have to do this manually, by first opening the php script, then waiting for it to complete, then submitting the sitemap to google again (even though the last step is optional I still do it). I must also point out that even though I do submit this to google, it still isn't indexed (doesn't come up in the search results), **which I want it to.** I want the classifieds to show up in **google SERPS as soon as possible**. Currently this is taking too long... Like a week or so. Anyways, I need to know how to improve this method I have. Should I open and write to the xml file on every new classified? I hesitat to do that because this means the file is open almost all the time, because new classifieds are frequent, and sometimes there are several new classifieds at the same time, so how would this impact the opening and writing to file if the file is already in use etc etc... Is there any other method, like submitting a php sitemap to google, and whenever google accesses this php file, a new xml is dynamically created? Need some ideas on how to do this in best way please... **Also, question 2**: If I dont have any links to a specific page on my server, except for a link in a sitemap, will this page be indexed anyways? Thanks
You are asking too much from Google. They aren't magic. Indexing the whole internet is a big task. And they aren't out there to do what you want. However, there are ways to get the google to notice things fasterish and also ways to get more up-to-the-moment searching through other means. Step one. The xml sitemap is good, but it still helps to have a legit html everything-everywhere link list/map. This is because links are in general of higher importance than a site map. So many search engines get to them faster. On that note, not being the only dood linking to your stuff is a HUGE help. The way indexing works means that getting on the list sooner means being updated in the google sooner. More links from outside means more points of entry. Also, the way google determines how important your site is comes, in part, from how much others link to you. More importance means being crawled for new info more often. Now, about real time search. The 'next big thing' in search is using real time items to get more relevant results. Google already is doing some of this for certain things. Sports, big events like the recent spacex launch, so on. They are using Buzz and Twitter. Others are using facebook and a few other services. Encouraging your users to tweet/like your items can make you more real-time search-able. So the moment a new listing comes out, a bunch of links may show up on twitter, and then they are more likely to show up in a real-time search.
238913
I am trying to install yarn through npm on Mac by referring the documentation given here: <https://classic.yarnpkg.com/lang/en/docs/install/#mac-stable> ``` npm install --global yarn ``` However when I run this command in terminal, I am getting the following error and the package is not being installed ``` npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead. ``` I also ran this command but nothing happened. I am also seeing messages like - this operation was rejected by your operating system. I haven't used yarn in a year, and everything was working fine, but suddenly I am running into all this. Would love to know what I am doing wrong here and how I can resolve this. This the error message that comes ``` The operation was rejected by your operating system. npm ERR! It is likely you do not have the permissions to access this file as the current user npm ERR! npm ERR! If you believe this might be a permissions issue, please double-check the npm ERR! permissions of the file and its containing directories, or try running npm ERR! the command again as root/Administrator. ```
You can put all the ages into a list up front by calling `input()` in a loop instead of copying and pasting it eight times: ``` ages = [int(input(f"Enter the age of guest {i}(in years): ")) for i in range(1, 9)] ``` I'd suggest having your `getCost` function just return the cost for a single age (hint: make this simpler by arranging the age brackets in ascending order, and eliminating them one at a time according to their upper bound): ``` def getCost(age): if age < 3: return 0 elif age < 12: return 14 elif age < 65: return 23 else: return 18 ``` This makes the job of `getCost` much easier -- then after you've gotten `ages` you can compute the total cost just by calling `getCost(age)` for each `age` and taking the `sum` of the result: ``` print(sum(getCost(age) for age in ages)) ``` Splitting the logic into parts like this makes it easy to do other things with the costs; for example, you could show how the total was computed by `join`ing the costs before you `sum` them: ``` print( " + ".join(str(getCost(age)) for age in ages), "=", sum(getCost(age) for age in ages) ) ``` ``` Enter the age of guest 1(in years): 2 Enter the age of guest 2(in years): 9 Enter the age of guest 3(in years): 13 Enter the age of guest 4(in years): 27 Enter the age of guest 5(in years): 44 Enter the age of guest 6(in years): 52 Enter the age of guest 7(in years): 66 Enter the age of guest 8(in years): 81 0 + 14 + 23 + 23 + 23 + 23 + 18 + 18 = 142 ```
238917
The trend of halide nucleophilicity in polar protic solvents is $$\ce{I- > Br- > Cl- > F-}$$ The reasons given by Solomons and Fryhle[1], and by Wade[2] are basically as follows. 1. Smaller anions are more solvated than bigger ones because of their 'charge to size ratio'. Thus, smaller ions are strongly held by the hydrogen bonds of the solvent. 2. Larger atoms/ions are more polarizable. Thus, larger nucleophilic atoms/ions can donate a greater degree of electron density to the substrate than a smaller nucleophile whose electrons are more tightly held. This helps to lower the energy of the transition state. Clayden et al.[3] give the reason that in SN2 reactions, the HOMO–LUMO interaction is more important than the electrostatic attraction. The lone pairs of a bigger anion are higher in energy compared to a smaller anion. So, the lone pairs of a bigger anion interact more effectively with the LUMO σ\*. Thus, soft nucleophiles react well with saturated carbon. What I don't understand is the trend of halide nucleophilicity in polar aprotic solvents. $$\ce{F- > Cl- > Br- > I-}$$ In aprotic solvents, only the solvation factor is absent. Bigger anions are still more polarizable and can interact in a better way with the LUMO. Then, what is the reason for the trend reversal in aprotic solvents? Solomons and Fryhle[1] say > > In these[aprotic] solvents anions are unencumbered by a layer of solvent molecules and they are therefore poorly stabilized by solvation. These “naked” anions are highly reactive both as bases and nucleophiles. In DMSO, for example, the relative order of reactivity of halide ions is opposite to that in protic solvents, and it follows the same trend as their relative basicity. > > > **Shouldn't the orbital interactions matter more than the electrostatic attractions even in polar aprotic solvents? Why does nucleophilicity follow the basicity trend in polar aprotic solvents?** References: 1. Solomons, T. W. Graham; Fryhle, C. B. *Organic Chemistry*, 10th ed.; Wiley: Hoboken, NJ, 2011; pp. 258–260. 2. Wade, L. G. *Organic Chemistry*, 8th ed.; Pearson Education: Glenview, IL, 2013; pp. 237–240. 3. Clayden, J.; Greeves, N.; Warren, S. *Organic Chemistry*, 2nd ed.; Oxford UP: Oxford, U.K., 2012; pp. 355–357.
This is a rather intellectually-stimulating question and one that is also very difficult to answer. You have constructed a very good case for why the nucleophilicity order would not be expected to reverse in polar aprotic solvents, i.e. the order of intrinsic nucleophilicities of the halide ions should be $\ce {I^- > Br^- > Cl^- > F^-}$, based on the concepts of frontier molecular orbital interactions, as well as electronegativity and polarisability of the nucleophilic atom. **Affirming your viewpoint** Admittedly, the saturated carbon atom is a soft centre and based on electronegativity considerations, the energy of the $\ce {HOMO}$ of the halide ions should increase from $\ce {F^-}$ to $\ce {I^-}$, i.e. the hardness of the the halide ions as nucleophiles decreases from $\ce {F^-}$ to $\ce {I^-}$. Based on the hard-soft acid-base (HSAB) principle, we would expect the the strength of the interaction between the halide ion and the carbon centre to increase from $\ce {F^-}$ to $\ce {I^-}$. We can provide more quantitative justification for this using the Klopman-Salem equation$\ce {^1}$: $$\Delta E=\frac{Q\_{\text{Nu}}Q\_{\text{El}}}{\varepsilon R}+\frac{2(c\_{\text{Nu}}c\_{\text{El}}\beta)^2}{E\_{\text{HOMO}(\text{Nu})}\pm E\_{\text{LUMO}(\text{El})}}$$ The first term is indicative of the strength of the Coulombic interaction while the second term is indicative of the strength of the orbital interactions. In the reaction with the soft saturated carbon, it is actually expected for the reactivity to increase from $\ce {F^-}$ to $\ce {I^-}$ (ref 1, p. 117). At the moment, all the evidence presented points us towards the conclusion that you have posited. However, we have overlooked the importance of a thermodynamic factor - the strength of the $\ce {C-X}$ bond. **A not-particularly-relevant add-on** Actually, if you think about it the considerations made in the Klopman-Salem equation are essentially kinetic considerations. We cannot conclude anything about reaction energetics from such considerations. The strength of the $\ce {HOMO-LUMO}$ interaction or that of the Coulombic attraction tells us nothing about how the electrons would organise themselves subsequently, what would be the strength of the resultant bonds etc. **A comment made on this by Olmstead & Brauman (1977)** On this topic of explaining the relative order of intrinsic nucleophilicity of the halide ions, Olmstead & Brauman (1977) had this to say$\ce {^2}$: > > The intrinsic nucleophilicities follow the reverse order of the polarizabilities (e.g., $\ce {CH3O^-}$ > $\ce {CH3S^-}$ and $\ce {F^-}$ > $\ce {Cl^-}$ > $\ce {Br^-}$). This could be due to a stronger interaction between the more concentrated molecular orbitals of the anion with the carbon center. It could also be simply a reflection of the greater thermodynamic methyl cation affinities of the smaller anions. > > > It is important to note that Olmstead & Brauman are merely postulating the reasons. However, I do feel that the point on thermodynamics leads us on the right track to answering this question. On the other point of "more concentrated MOs", I am unclear of how it can be interpreted. Let us focus now on this point. **How does thermodynamics even influence kinetics?** Well... It certainly does here. What are we concerned with when dealing with nucleophilicity? As it is a [kinetic phenomenon](https://chemistry.stackexchange.com/questions/20061/whats-the-difference-between-a-nucleophile-and-a-base), we are essentially concerned with the rate of the substitution reaction. This makes the consideration of the activation energy ($E\_\mathrm{a}$) a particularly important one because [the higher the $E\_\mathrm{a}$, the lower the rate of the substitution reaction](https://en.wikipedia.org/wiki/Arrhenius_equation). Here, the $E\_\mathrm{a}$ can be taken to be the difference in energy between the reactants and the transition state. Thus, we can decrease the $E\_\mathrm{a}$ by either raising the energy level of reactants or decreasing the energy level of the transition state. The reaction energy profile for an $\ce {S\_N2}$ reaction is shown below, taken from ref. 3 (p. 394). [![enter image description here](https://i.stack.imgur.com/ifTDT.png)](https://i.stack.imgur.com/ifTDT.png) There are two ways to see how the strength of the $\ce {C-X}$ bond can affect the $E\_\mathrm{a}$. I am not sure if they may be considered equivalent perspectives. Nonetheless, I will present both. The first perspective is well-explained by Francis & Sundberg (2007) with regard to the $\ce {S\_N2}$ reaction$\ce {^3}$: > > Because the $\ce {S\_N2}$ process is concerted, the strength of the partially formed new bond is reflected in the TS. A stronger bond between the nucleophilic atom and carbon atom results in a more stable TS and a reduced activation energy. > > > Another perspective (which may be somewhat similar to the first, or even possibly the same) is that the transition state structure bears resemblance to the product structure, based on the [Hammond's postulate](https://en.wikipedia.org/wiki/Hammond%27s_postulate). However, this would be more applicable for an endothermic $\ce {S\_N2}$ reaction where the transition state structure does indeed bear more resemblance to the product. When the product is more stable, i.e. has bonds that form more exothermically, the energy of the transition state would thus be lowered, and the $E\_\mathrm{a}$ would also decrease, although not necessarily proportionally. **Conclusion** The argument you have presented failed to consider the important thermodynamics factor. Thus, it resulted in the predicted reactivity of the halide ions in the reversed order. The takeaway here is that the application of the $\ce {HSAB}$ concept alone does not always produce the correct prediction. **Additional information** More examples are cited for which the HSAB concept fails. These include: * The favourable combination of $\ce {H^+}$, a hard acid, and $\ce {H^-}$, a soft base (discussed [here](https://chemistry.stackexchange.com/questions/75769/why-does-strong-lewis-acid-strong-lewis-base-interactions-prevail-over-hard-soft) as well) (ref. 4). * The fact that the rate of reaction between $\ce {Ag^+}$, soft acid, and an alkene, soft base, is slower than that between $\ce {Ag^+}$ and $\ce {OH^-}$, a hard base (ref. 1, p. 110) --- **References** 1. Fleming, I. Molecular Orbitals and Organic Chemical Reactions (Student Edition). John Wiley & Sons, Ltd. United Kingdom, **2009**. 2. Olmstead, W. N.; Brauman, J. I. Gas-phase nucleophilic displacement reactions. *J. Am. Chem. Soc.* **1977**, *99*(13), 4219–4228. 3. Carey, F. A.; Sundberg, R. J. Advanced Organic Chemistry Part A. Structure and Mechanisms (5th ed.). Springer, **2007**. 4. Pearson, R. G.; Songstad, J. Application of the Principle of Hard and Soft Acids and Bases to Organic Chemistry. *J. Am. Chem. Soc.* **1967**, *89*(8), 1827-1836.
239006
I have a field that sometimes has one value and sometimes 2 values separated by a comma.I need to split the values into two columns. I have seen solutions using functions, but i need to add it to a view. Here is what I have been trying to do for the first column ``` SELECT CASE WHEN EXISTS(SELECT reportto FROM dbo.placement WHERE reportto like '%,%') THEN (Select Substring(reportTo, 1,Charindex(',', reportTo)-1) as [Primary OTS Approver] from placement) ELSE (SELECT reportto as [Primary OTS Approver] FROM dbo.placement) END ```
You don't need subselects in your `CASE` statemant, you can work with the columns directly: ``` SELECT CASE WHEN CHARINDEX(',', reportto) > 0 THEN SUBSTRING(reportto, 1, CHARINDEX(',', reportto) -1) ELSE reportto END AS [Primary OTS Approver] FROM placement; ```
239055
Here is my SQL code. I have selected the price of each row and the milestone of each row and the id to join the tables, but I have only the result of one row. PHP code to do multiple filters: ``` if($i==0) { if($fc == "projet") { $filtre_bdd .= "AND p.$fc = '$fv' "; } else { $filtre_bdd .= "AND cible.$fc = '$fv' "; $i= $i + 2; } } ``` SQL query: ``` SELECT cible.prix,a.valeur,a.idroute,cible.id,p.id, SUM(DISTINCT a.valeur) AS total_avances, /* the milestone sum the unique one */ SUM(a.valeur) AS total_avance, /* the milestone sum of each row */ SUM(cible.prix) AS total_prix /* the price sum */ FROM avances AS a,routes AS cible,projets AS p WHERE a.idroute = cible.id AND p.id = cible.idprojet $filtre_bdd /* the conditions to join the tables and do the filter */ GROUP BY cible.id, a.idroute HAVING total_avances <> cible.prix AND cible.prix - total_avances >- 1 ``` Now how can I get the totals of the prices and the total of the milestones with all those conditions? The targeted table contains the id of the project and the id of the milestones. We have to do the sum of the milestones for each row and sum of the sums and compare it to the project price.
The *creation* might be the cause of your confusion. In fact, you are right: Two string instances are involved in the line ``` String summer = new String("Summer"); ``` As there are two string instances involved, they must have been created somwhere and sometime. The creation time is the big difference. The `"Summer"` is a constant which is loaded into the internal string pool when loading the class that contains this constant. So this *internal* string instance is created while loading the class. The string object that the variable `summer` refers to is created while running the code that contains this line. That's it.
239227
I have to execute the following `cmd` commands of Windows in Java. **The `cmd` commands:** ``` Microsoft Windows [Version 6.1.7600] Copyright (c) 2009 Microsoft Corporation. All rights reserved. //First i have to change my default directory// C:\Users\shubh>D: //Then move to a specific folder in the D drive.// D:\>cd MapForceServer2017\bin\ //then execute the .mfx file from there. D:\MapForceServer2017\bin>mapforceserver run C:\Users\shubh\Desktop\test1.mfx ``` **Result of the execution** ``` Output files: library: C:\Users\shubh\Documents\Altova\MapForce2017\MapForceExamples\Tutorial\library.xml Execution successful. ```
I suggest using <https://commons.apache.org/proper/commons-exec/> for executing o/s command from within Java because it deals with various issues you may encounter later. You can use: ``` CommandLine cmdLine = CommandLine.parse("cmd /c d: && cd MapForceServer2017\\bin\\ && mapforceserver run ..."); DefaultExecutor executor = new DefaultExecutor(); int exitValue = executor.execute(cmdLine); ```
239326
I am trying to parse iTunes top movies (top songs, albums etc) RSS feed, using PHP. Is there a library that I can use to parse them, without writing too much XML code (or using simplexml)? I tried [simplepie](http://simplepie.org/), but it gave me some inconsistent results, and it is no longer maintained.
Here is a good overview: <http://www.webresourcesdepot.com/php-rss-parsers/>
239499
I made an edit on a low-quality answer (pretty much as a side effect while I was checking the answer for stealthy spam links and comparing it to other answers). But [a user rejected it](https://gaming.stackexchange.com/review/suggested-edits/194250) (edit has now been approved overall) because he thinks the post is not long for this world! : [![reject reason](https://i.stack.imgur.com/Sa8vJ.png)](https://i.stack.imgur.com/Sa8vJ.png) **Can we please not reject edits that improve posts** -- even if the post may be ill fated? --- Related: [Highest scoring answer from a similar question on Meta SE](https://meta.stackexchange.com/a/155963)
I'm not going to comment on the post that motivated this question. I didn't even look at it, and it sounds like the edit was accepted eventually, anyway. I'll address the actual issue, instead: Just because an answer should be deleted as it stands doesn't mean that any and all possible future versions of the answer would be deleted as well. Therefore, until the answer is deleted, any effort that anyone has gone to to improve the answer should not be discarded. **If it's a good edit, approve the edit.** However, that advice is for reviewers, after the edit has been suggested. For potential editors, it's not worth your time trying to improve a post that you're sure is going to get deleted. If the basic premise is a perfectly good answer, but it lacks details, then that might be worth your time, but some answers simply can't be saved.
240089
I need to add a small strip in between items of a RecyclerView. This strip can come after different number of items in a list. This needs to be done dynamically. I need to implement something like what FitBit has done:[![enter image description here](https://i.stack.imgur.com/pLl7t.jpg)](https://i.stack.imgur.com/pLl7t.jpg) I also need the first row i.e. the one saying "This Week" to stick on top even if the page scrolls down.
You should use the concept of different view types using [getItemViewType(int)](https://developer.android.com/intl/pt-br/reference/android/support/v7/widget/RecyclerView.Adapter.html#getItemViewType(int)). Then on [onCreateViewHolder(ViewGroup, int)](https://developer.android.com/intl/pt-br/reference/android/support/v7/widget/RecyclerView.Adapter.html#onCreateViewHolder(android.view.ViewGroup,%20int)) you can check which type you should inflate/create. Example: ``` @Override public int getItemViewType(int position) { // you should return the view type, based on your own dynamic logic } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { switch (viewType) { // handle each view type accordingly } } ```
240177
I keep receiving this error for my mobile navigation: > > Uncaught TypeError: Cannot set property 'onclick' of null > > > I cannot find the cause. The error is referring to the last 3/4 lines of code. ``` var theToggle = document.getElementById('toggle'); function hasClass(elem, className) { return new RegExp(' ' + className + ' ').test(' ' + elem.className + ' '); } function addClass(elem, className) { if (!hasClass(elem, className)) { elem.className += ' ' + className; } } function removeClass(elem, className) { var newClass = ' ' + elem.className.replace( /[\t\r\n]/g, ' ') + ' '; if (hasClass(elem, className)) { while (newClass.indexOf(' ' + className + ' ') >= 0 ) { newClass = newClass.replace(' ' + className + ' ', ' '); } elem.className = newClass.replace(/^\s+|\s+$/g, ''); } } function toggleClass(elem, className) { var newClass = ' ' + elem.className.replace( /[\t\r\n]/g, " " ) + ' '; if (hasClass(elem, className)) { while (newClass.indexOf(" " + className + " ") >= 0 ) { newClass = newClass.replace( " " + className + " " , " " ); } elem.className = newClass.replace(/^\s+|\s+$/g, ''); } else { elem.className += ' ' + className; } } theToggle.onclick = function() { toggleClass(this, 'on'); return false; } ```
Looks like Your .js loaded before DOM was initialized, and `document.getElementById('toggle')` found nothing, as there is no element with this id yet. Place this `<script>` in the end of HTML.
240448
(On Mac OS X 10.6, Apache 2.2.11) Following the oft-repeated googled advice, I've set up mod\_proxy on my Mac to act as a forward proxy for http requests. My httpd.conf contains this: ``` <IfModule mod_proxy> ProxyRequests On ProxyVia On <Proxy *> Allow from all </Proxy> ``` (Yes, I realize that's not ideal, but I'm behind a firewall trying to figure out why the thing doesn't work at all) So, when I point my browser's proxy settings to the local server (ip\_address:80), here's what happens: 1. I browse to <http://www.cnn.com> 2. I see via sniffer that this is sent to Apache on the Mac 3. Apache responds with its default home page ("It works!" is all this page says) So... Apache is not doing as expected -- it is not forwarding my browser's request out onto the Internet to cnn. Nothing in the logfile indicates an error or problem, and Apache returns a 200 header to the browser. Clearly there is some very basic configuration step I'm not understanding... but what?
> > State: 1 > > > is a generic state which is always returned to the client to prevent information disclosure to unauthenticated clients. You should find a similar error message in your server log ("C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\LOG\ERRORLOG") with an accurate state. More information regarding this, and a list of possible states can be found [here](http://blogs.msdn.com/sql_protocols/archive/2006/02/21/536201.aspx).
240699
Let's say I get a directory listing of .jpg files and then want to display them ``` const fs = require('fs'); fs.readDirSync(someAbsolutePathToFolder) .filter(f => f.endsWith('.jpg')) .forEach(filename => { const img = new Image(); const filepath = path.join(someAbsolutePathToFolder, filename); img.src = `file://${filepath.replace(/\\/g, '/')}`; document.body.appendChild(img); }); ``` This will fail. As just one example, if the listing I got had names like ``` #001-image.jpg #002-image.jpg ``` the code above results in URLs like ``` file://some/path/#001-image.jpg ``` Which you can see is a problem. The URL will be cut at the `#`. [This answer](https://stackoverflow.com/questions/4540753/should-i-use-encodeuri-or-encodeuricomponent-for-encoding-urls) claims I should be using `encodeURI` but that also fails as it leaves the `#` unescaped. Using `encodeURIComponent` also does not work. It replaces `/` and `:` and space and Electron does not find the file, at least not on Windows. Up until this point I had something like this ``` const filepath = path.join(someAbsolutePathToFolder, filename).replace(/\\/g, '/'); img.src = `file://${filepath.split('/').map(encodeURIComponent).join('/')}`; ``` but that also fails on windows because drive letters get convert from `c:\dir\file` to `c%3a\dir\file` which then appears to be a relative path to electron. So I have more special cases trying to check for `[a-z]:` at at the beginning of the path as well as `\\` for UNC paths. Today I ran into the `#` issue mentioned above and I'm expecting more time bombs are waiting for me so I'm asking... What is the correct way to convert a filename to a URL in a cross platform way? Or to be more specific, how to solve the problem above. Given a directory listing of absolute paths of image files on the local platform generate URLs that will load those images if assigned to the `src` property of an image.
You can use Node's (v10+) `pathToFileURL`: ``` import { pathToFileURL } from 'url'; const url = pathToFileURL('/some/path/#001-image.jpg'); img.src = url.href; ``` See: <https://nodejs.org/api/url.html#url_url_pathtofileurl_path>
240770
My goal is to have a computer stream the video from a usb webcam to my own android app. On the PC I'm running VLC which streams the capture device (webcam) over RTSP on port 8554, with the following settings: ``` Video Codec: H.264 Video Resolution: 1600x1200 x 0.25= 400 x 300 px Video Frame Rate: 12 fps Video Bitrate: 56 Kbps and NO audio ``` I picked very low settings to see if it would improve lag but had little to no effect on lag. This is the generated output stream string VLC gives me: ``` :sout=#transcode{vcodec=h264,vb=56,fps=12,scale=0.25,acodec=none}:rtp{sdp=rtsp://:8554/} :sout-keep ``` On android side in the onCreate Method I have: ``` String url = "rtsp://192.168.1.103:8554/"; vid = (VideoView) findViewById(R.id.videoView1); mc = new MediaController(this); vid.setMediaController(mc); vid.setVideoURI(Uri.parse(url)); vid.requestFocus(); vid.setOnPreparedListener(new OnPreparedListener(){ @Override public void onPrepared(MediaPlayer mp) { // TODO Auto-generated method stub vid.start(); } }); ``` Results: When the app loads up VideoView is all black for about 10-20 seconds while two messages pop up in LogCat: ``` Tag Text MediaPlayer Couldn't open file on client side, trying server side MediaPlayer getMetadata ``` once the video is displayed, there's about 20 seconds of lag and after about 30-60 seconds the video remains frozen. These messages also come up once the video starts playing: ``` Tag Text MediaPlayer info/warning (3, 0) MediaPlayer Info (3, 0) ``` I also tried capturing the stream from another PC on the same network with VLC, it seems that the lag is still there as well however it never freezes. Not sure whether I should use a different RTSP server, such as Darwin? use a different protocol, HTTP or RTP? or if something needs to be changed on the android side?
Try http stream from VLC. You can never remove all the lag when transcoding, but should be able to get it down to < 10 seconds.
240961
We have a domain based on Gmail. This question is for the within domain users. Whenever a certain user replies to my email, it mostly creates a new thread of its own. For example, if I start an email chain with > > subject: Hello World > > > Now, if this specific user replies to the email, then it mostly creates following new chain with the previous body inlined: > > subject: Re: Hello World > > > My expectation is that the email should have remained clubbed as it happens for all the other users. BTW, this behaviour is consistent. Sometimes it happens after certain email replies. In my Gmail > Settings > General > Conversation view is ON. How to prevent this unwanted individual replies?
Nowadays, as September 2019, Google Sheets doesn't include a way to hide the active owner/editors selection on the regular spreadsheet view. Please submit your feedback to Google using [Google Feedback](https://www.google.com/tools/feedback/intl/en/).
241469
I have a simple script that should Update variable in a column where user login equals some login. ``` <?PHP $login = $_POST['login']; $column= $_POST['column']; $number = $_POST['number']; $link = mysqli_connect("localhost", "id3008526_root", "12345", "id3008526_test"); $ins = mysqli_query($link, "UPDATE test_table SET '$column' = '$number' WHERE log = '$login'"); if ($ins) die ("TRUE"); else die ("FALSE"); ?> ``` but it doesn't work. It gives me - FALSE. One of my columns name is w1 and if I replace '$column' in the code with w1 it works fine. Any suggestions?
Simply remove quotes: `'$column' =` should be `$column =` --- Your code is open for SQL Injection, use prepared statements.
241547
I am currently working on a wordpress site, I am using a form that the user can modify so that it updates the database : Here's the HTML/PHP code : ``` echo '<form class="form-verifdoc" target="noredirect" method = "post">'; echo '<label class="label-verifdoc" style="float:left;margin-top:10px;margin-right:10px;"for="'.$name_input_verifdoc.'">'.$label_element.'</label><textarea style="float:right;margin-bottom:10px;vertical-align:middle!important;border-left: 5px solid black;resize:vertical;" rows="1" type="text" name="variables['.$name_input_verifdoc.']">'.$contenu_input_verifdoc.'</textarea>'; echo'<input name="idchamps['.$id_input_verifdoc.']" type="hidden" value="'.$id_input_verifdoc.'">'; echo '<div class="div_edit_verifdoc">'; echo '<input type="submit" id="'.$id_input_verifdoc.'" class="bouton-edit-champ-doc" onclick="return confirm(\'Voulez-vous vraiment modifier les informations de ce champ ?\') && AlertQuery()" name="bouton-envoi-editform" value="Editer le champ"/>'; echo '</div>'; echo '<iframe name="noredirect" style="display:none;"></iframe>'; echo '</form>'; ``` I use a confirm so that the user has to confirm that he wants to update the data. And here's the script that use the wpdb query to update the MySQL data : ``` <script> <?php if (isset($_POST['bouton-envoi-editform']) && !empty($_POST['bouton-envoi-editform'])) { foreach($_POST['variables'] as $variableName => $variable){ $ValeurChampModif = $variable; } foreach($_POST['idchamps'] as $champid => $idchamp){ $Champ_id = $idchamp; } $modif_doc_bdd = $wpdb->query($wpdb->prepare("UPDATE `mod114_frmt_form_entry_meta_copie` SET `meta_value` = '$ValeurChampModif' WHERE `mod114_frmt_form_entry_meta_copie`.`meta_id` = $Champ_id;")); } else { } ?> function AlertQuery($modif_doc_bdd){ <?php if( $modif_doc_bdd ){ ?> alert('Les modifications ont bien été enregistrées.'); <?php }else{ ?> alert('⚠ ERREUR, les modifications n\'ont pas pu être enregistrées. Veuillez ré-essayer.'); <?php } ?> } </script> ``` I am trying to get the function AlertQuery to make a popup alert if the wpdb query was successful or not when updating the data. But I can't seem to grab the response of the $wpdb query... I have tried to put the function to have everything inside but that didn't work as it wouldn't prompt the popup.
Your expected output needs to be wrapped in curly braces in order to be a valid JSON object. That said, use `from_entries` to create an object from an array of key-value pairs, which can be produced by accordingly `map`ping the input object's `Objects` array. ``` .Objects | map({key: .ElementName, value: .ElementArray}) | from_entries ``` ```json { "Test1": [ "abc", "bcd" ], "Test2": [ "abc", "bcde" ] } ``` [Demo](https://jqplay.org/s/BKtNFKWEJs)
241704
**Objective:** Pass an array of information from tableview to another tableview using the data created. **Problem:** Couldn't access the array information from TableViewController in preparingForSegue **Result:** TableViewController contains employee names, and when click on each of the employee, it goes to the details of showing arrays of information. 1) Employee.swift (model for data) ``` struct Employee { var name: String var food: [String] var ingredients: [String] init(name: String, food: [String], ingredients: [String]) { self.name = name self.food = food self.ingredients = ingredients } } ``` 2) TableViewController.swift (shows the name of the employee) Everything is working well here with the codes, the only thing that I am struggling here is passing the information to the next viewcontroller. In the comment section is where I tried typing **destination.food = lists[indexPath.row].food**. This didn't work as expected. I am trying to retrieve the array information. ``` class VillageTableViewController: UITableViewController { var lists : [Employee] = [ Employee(name: "Adam" , food: ["Fried Rice","Fried Noodles"], ingredients: ["Insert oil, cook","Insert oil, cook"])] override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showVillages" { if let indexPath = self.tableView.indexPathsForSelectedRows { let destination = segue.destination as? DetailsViewController // pass array of information to the next controller } } } ``` 3) DetailsTableViewController.swift (shows an array of information) Code is working fine. I have the idea of creating an empty array and the information will be passed from TableViewController. In the comment section, I will then write **cell.textLabel?.text = food[indexPath.row]** and **cell.subtitle?.text = ingredients[indexPath.row]** ``` class DetailsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { var food:[String] = [] var ingredients:[String] = [] func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! DetailsTableViewCell //this is where I will get the information passed from the array return cell } ``` Please advise. I've been researching for the past few hours and couldn't figure it out yet. Bear in mind that all the code works fine here and I've only struggling in accessing the array information. Edit: I am looking for arrays to be accessed and to be displayed on DetailsTableViewController.
According to your question you are going to pass **one** item (the employee) to the detail view controller, not an array. Do that: * In `VillageTableViewController` replace `prepare(for` with ``` override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showVillages", let indexPath = self.tableView.indexPathForSelectedRow { let employee = lists[indexPath.row] let destination = segue.destination as! DetailsViewController destination.employee = employee } } ``` * In `DetailsViewController` create a property `employee` ``` var employee : Employee! ``` Now you can access all properties of the `employee` in the detail view controller, for example using its `food` array as data source ``` func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return employee.food.count } ``` and ``` func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! DetailsTableViewCell cell.textLabel.text = employee.food[indexPath.row] return cell } ``` --- PS: Rather than separate arrays for food (names) and ingredients I recommend to use a second struct (in this case you don't need to write any initializers in both structs) ``` struct Food { let name : String let ingredients: [String] } struct Employee { let name: String let food: [Food] } var lists : [Employee] = [ Employee(name: "Adam" , food: [Food(name: "Fried Rice", ingredients:["Insert oil, cook"]), Food(name: "Fried Noodles", ingredients: ["Insert oil, cook"])]) ``` The benefit is you can easily use sections in the detail view controller. ``` func numberOfSections(in tableView: UITableView) -> Int { return return employee.food.count } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let food = employee.food[section] return return food.name } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let food = employee.food[section] return food.ingredients.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! DetailsTableViewCell let food = employee.food[indexPath.section] cell.textLabel.text = food.ingredients[indexPath.row] return cell } ```
241742
On Code Review, I've noticed that there is a blind upvoting of posts. People judge the question by the heading, not by the effort. Is this a proper way of upvoting posts?
As one of this site's [top voters](https://codereview.stackexchange.com/users?tab=Voters&filter=all) and with one of my former display names being @lol.upvote, I feel somewhat obligated to post an answer here. This site has been in public beta for well over 3 years (today is beta day #[1254](http://area51.stackexchange.com/proposals/11464/code-review)). The **only** reason for this, boils down to **people not voting enough**. Feel free to browse the [beta-progress](/questions/tagged/beta-progress "show questions tagged 'beta-progress'") meta posts on this site for more details. [user-retention](/questions/tagged/user-retention "show questions tagged 'user-retention'") has been identified as the newest *most pressing concern*, because when you don't get rewarded for putting effort in a thorough review, it's kind of pointless. But that's mostly about *answer* votes. *Question* votes are different, in the sense that a lot of questions asked, are posted by drive-by users that are asking their very first question on the site, and *might* come back with another question in a couple of weeks or months, *depending on their CR experience*. By giving a new user/asker 3 upvotes, we unlock their "upvote" privilege and allow them to upvote answers they're getting. ### Any answerable on-topic question with less than 3 votes is therefore under-voted. --- With **over 20K visitors every day**, how do you explain that **we hardly ever have more than [40-some voters any given week](https://codereview.stackexchange.com/users?tab=Voters&filter=week)**? (that list excludes users that have less than 11 total votes spent). Out of all askers that *do* get the 3 upvotes to be able to spend some votes, a given fraction will upvote *some* of the answers *on their question* - and that's where it ends. What boggles me, is how *reviewers* can answer a question that they didn't even upvote. **If you can answer a question, that question is worthy of your upvote.** Or *at the very least*, of a comment explaining what the question is missing to get your upvote. --- Is it "ok" to upvote a question solely based on its title? *Of course it's not!* **But** a question with a good catchy title will draw *views* and attract reviewers; a couple of answers and a bunch of votes within a certain given amount of time is all it takes for the question to become a "hot network question", and from there, *anything can happen*. So should you upvote a question *just because it has a good title?* No. You may *view* a question for that reason, but then you'll upvote it... * If it's clear what the code is doing * (and/or) If the question is well formatted * (and/or) If you read the code and think "hmm *this*, I'd do like *that*" Notice "and/or" - I can upvote a [php](https://codereview.stackexchange.com/questions/tagged/php "show questions tagged 'php'") question even if I don't know jacksquat about [php](https://codereview.stackexchange.com/questions/tagged/php "show questions tagged 'php'"). How? If no one has cast a "non-working code" close vote and the question is well-written and well-formatted and *reviewers interested in PHP should get their eyes on that one*, I'll upvote it. --- Since the middle of May 2014, there's been more comments than question votes on the site. Recent activity (last 60 weeks) doesn't seem to agree with your assertion that "people vote blindly": [![site's activity graph, last 60 days (as of 2014-06-27)](https://i.stack.imgur.com/zmiWG.png)](http://data.stackexchange.com/codereview/query/161411/site-activity-and-votegraph#graph) If anything, people are voting *sparingly*. And that's hurting us. 1402 answer votes and 1060 question votes in a week with 20K visits/day means **hardly 1.76% of visitors spend ONE vote**, on average. VOTE. Then VOTE AGAIN. And then VOTE SOME MORE. ===============================================
241817
I'm building an iPhone app using the Titanium framework. I need a 5-star rating control in my app, just like the one found in the app store. As a temporary solution I'm using the slider for adding a rating. Most of the examples I found on the web are in objective C. can somebody guide me on achieving this using titanium. Regards
You just need to create a `view` and populate it with the number of buttons you want then assign a click event to them. ``` var rateView = Ti.UI.createView(), max = 5, min = 1; // used in the flexMin and flexMax function rate(v) { // rate code storage goes here // your choice on if you want to have separate images of each rating or run a loop // based on the value passed in to change a set number of stars to their alternate // image } var flexMin = Ti.UI.createButton({ systemButton: Ti.UI.iPhone.SystemButton.FLEXIBLE_SPACE, top: 0, left: 0, height: rateView.height }); flexMin.addEventListener('click', function(e) { rate(min); }); var flexMax = Ti.UI.createButton({ systemButton: Ti.UI.iPhone.SystemButton.FLEXIBLE_SPACE top: 0, right: 0, height: rateView.height }); flexMax.addEventListener('click', function(e) { rate(max); }); rateView.add(flexMin); rateView.add(flexMax); var stars = []; for(var i=1;i<max;i++) { stars[i] = Ti.UI.createButton({ // styling including the darker or light colored stars you choose, 'rating': i }); stars[i].addEventListener('click', function(e) { rate(e.source.i); }); } ``` Using that logic approach above you should be able to change `max` to set the number of stars you want and simply setup the `rate(v)` to do one of the two options in the comments above. Keep in mind that you need to add the `stars[i]` to the view with a `left` or some type of positing that increments based on the number of stars available. Hope this helps.
241854
This is probably a dumb question(and I can't find a previous iteration of this question), but... How do I rigorously show that $\Bbb Q$ and $\Bbb R$ are not isomorphic? I mean there is a notion of $\Bbb Q$ being smaller than $\Bbb R$, and perhaps it has something to do with $\sqrt{2}$ being in $\Bbb R$ and not in $\Bbb Q$ which makes me think of roots of polynomials, but I don't know how to rigorously show it at all. I suppose my question is two fold, how does one show that $\Bbb Q$ and $\Bbb R$ aren't isomorphic, but more generally, what are 'field' isomorphism invariants? What properties can one use to determine immediately that two fields aren't isomorphic? Take $\Bbb R$ and $\Bbb C$ as well.
Well, if you have a field isomorphism $\phi: F\to K$, then if we have a polynomial equation $$ x^n + a\_{n-1} x^{n-1}+ \ldots + a\_0 = 0, $$ with coefficients in $F$, we get an equation $$ x^n + \phi(a\_{n-1})x^{n-1} + \ldots \phi(a\_0) = 0 $$ with coefficients in $K$. Then if $\alpha$ is a solution to our equation with coefficients in $K$, $\phi^{-1}(\alpha)$ solves the equation in $F$. Then we can use this to see that $\mathbb{Q}$, $\mathbb{R}$ and $\mathbb{C}$ are all non-isomorphic, since if we have a field isomorphism $\phi$ from $\mathbb{Q}$ to $\mathbb{R}$ or $\mathbb{R}$ to $\mathbb{C}$ then surely $\phi(2) = 2$ and $\phi(-1)= -1$. But then the equations $x^2 -2=0$ and$x^2 + 1=0$ would have solutions in all the fields, and we can see that this isn't the case. So, looking at equations which have solutions in some fields but not others can be used to show that fields are not isomorphic.
243335
Im trying to access a enum from a model class to write a switch case to perform a segue. Here is my code: ``` class LandingViewController: UIViewController { // MARK: Private Structs. private struct SegueIdentifier { static let forcedUpdate = "forcedUpdate" static let optionalUpdate = "optionalUpdate" } // MARK: Private variables. private let updateType: StartupManager.UpdateType // MARK: LifeCycle Methods. override func viewDidLoad() { super.viewDidLoad() StartupManager.setupForLanding() var segueIdentifier: String switch updateType { case .ForcedUpdate: segueIdentifier = SegueIdentifier.forcedUpdate case .OptionalUpdate: segueIdentifier = SegueIdentifier.optionalUpdate } performSegueWithIdentifier(segueIdentifier, sender: nil) } ``` The `setupForLanding()` is used to check the startUpManager model class to see which of the enums is triggered. ``` class StartupManager: NSObject { enum UpdateType { case OptionalUpdate case ForcedUpdate } // code to perform a check if isForceUpdate { completion(.ForcedUpdate) } else { completion(.OptionalUpdate) } ``` But I keep getting an error that reads `LandingViewController has no initialisers`. How do I check in the start up manager which case is called and then perform the segue in the landingViewController?
yes, u can use the same text box added in the `ViewController` in `DerivedViewController`, for this u add one more `textbox` in the `DerivedViewController's` scene and connect the `IBOutlet` to `ViewController 's` `textbox` no need to create a new outlet for `textbox` in the `DerivedViewController` this way u can inherit the `textbook`. Edit 1: if u subclass the `ViewController` all the outlet connections are available in `DerivedViewController` subclass. for example,in `DerivedViewController` just drag from `files owner` to your view component it will show the superview's (ViewController's) outlet name edit 2: u are declaring the private properties, so make it available for other classes also by declaring in `.h` file, **ViewController.h** ``` #import <UIKit/UIKit.h> #import "ViewController.h> @interface DerivedViewController : ViewController @property (weak, nonatomic) IBOutlet UITextField *firstTB; @property (weak, nonatomic) IBOutlet UITextField *secondTB; @property (weak, nonatomic) IBOutlet UILabel *symbolLabel; @property (weak, nonatomic) IBOutlet UITextField *find; @end ``` **ViewController.m** ``` #import "ViewController.h" @interface ViewController () @end @implementation ViewController int resultValue=0; - (IBAction)saveResult:(id)sender { //other codes } //other methods @end ```
243595
I am trying to extract a string between two patterns from another string in C++. > > Example of input: "C++ is not that easy" > > > Pattern1: "C++" > > > Pattern2: "that" > > > Result: " is not " > > > I would like to loop this operation to extract all matching strings from binary file later.
The best way for this is to use regular expressions. You can read more about it [here](http://msdn.microsoft.com/en-us/library/4384yce9%28v=vs.80%29.aspx)
243996
I have a table with 11 columns and 5 rows The Columns are labelled in this manner A ,1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10 ,ADD CLA is a Manual Input Cell CL1 is always equal to CLA. A, being the cell that already contains an input in the form of single number. Given, first row contains a random arrangement of numbers from 0-9 In the next row macro must copy the above row , CL1 to CL0, then it must consider the value in CL1, MATCH it through the same row , if match is found, delete the matched cell and move the cells to left. The Value of CL1 must now be macthed with above row and its address must be reported into ADD column. Address means Column label of the matched cell in the above column. Then Move to next row. First CLA CL1 CL2 CL3 CL4 CL5 CL6 CL7 CL8 CL9 CL10 ADD ``` 1 2 3 4 5 6 7 8 9 0 3 3 1 2 4 5 6 7 8 9 0 CL3 ``` Then I Input Value in CLA in next row (Manual Input) , 3 in this case .Always cl1 = cla ) It must do this untill all CLA'S Are done with. CLA's are pre filled and cl1's are prefilled too. EXAMPLE STEPS TO HOW IT MUST BE DONE **Start -> Copy The Above Row from CL1 TO CL10** CLA CL1 CL2 CL3 CL4 CL5 CL6 CL7 CL8 CL9 CL10 ADD ``` 1 2 3 4 5 6 7 8 9 0 3 3 1 2 4 5 6 7 8 9 0 CL3 6 ``` **-> Put them in CL2 ( I will Input CLA and CL1 has this prefilled formula =CL1=CLA** CLA CL1 CL2 CL3 CL4 CL5 CL6 CL7 CL8 CL9 CL10 ADD ``` 1 2 3 4 5 6 7 8 9 0 3 3 1 2 4 5 6 7 8 9 0 CL3 6 6 3 1 2 4 5 6 7 8 9 0 ( Copied from above in CL2 ) ``` **-> Match the CL1 value in the copied row and delete that cell and move cells left.** CLA CL1 CL2 CL3 CL4 CL5 CL6 CL7 CL8 CL9 CL10 ADD ``` 1 2 3 4 5 6 7 8 9 0 3 3 1 2 4 5 6 7 8 9 0 CL3 6 6 3 1 2 4 5 7 8 9 0 ( 6 is deleted because it matches with cl1 in same row ) ``` **-> Now go to ADD column and match CL1 In in the above row, and Report the Column of the Matching cell. ADD is CL4 in this case because 3 , which is CL1 In present row, was on CL4 in the above row.** CLA CL1 CL2 CL3 CL4 CL5 CL6 CL7 CL8 CL9 CL10 ADD ``` 1 2 3 4 5 6 7 8 9 0 3 3 1 2 4 5 6 7 8 9 0 CL4 6 6 3 1 2 4 5 7 8 9 0 CL7 ( Add is CL7 because 6 was in CL7 IN THE ABOVE ROW) ```
Usually, I use something like this: ``` <table> <td align="center"> <div class="round-button"> <a href="viewStatus.php"> <img name="myImg" src="images/City.png" alt="Home" onClick='Func'/> </a> </div> </td> </table> <script type="text/javascript"> function Func() { $.ajax({ type: "GET", url: "file.php", success:function(json){}, error:function(){} }) } </script> ```
244100
``` $ie = New-Object -com internetexplorer.application ``` Everytime i open a new website with this object(ie every time when script runs) it is opened in a new IE window and i don't want it to do that. I want it to be opened in a new tab but that too in a previously opened IE window. I want to reuse this object when the script runs next time. I don't want to create a new object So is there any way like to check for the instances of internet explorer and to reuse its instance ??? **I tried this as a solution:** First you have to attach to the already running Internet Explorer instance: ``` $ie = (New-Object -COM "Shell.Application").Windows() ` | ? { $_.Name -eq "Windows Internet Explorer" } ``` Then you Navigate to the new URL. Where that URL is opened is controlled via the Flags parameter: ``` $ie.Navigate("http://www.google.com/", 2048) ``` but am not able to call `navigate` method on this newly created object `$ie`.
You can use `Start-Process` to open the URL. If a browser window is already open, it will open as a tab. ``` Start-Process 'http://www.microsoft.com' ```
244457
I want to use a `case "name"` . ``` char arg1[256]; one_argument(argument, arg1, sizeof(arg1)); if(*arg1) { switch(LOWER(*arg1)) { case 'anime': { } break; } } ``` When i call command `do_reload anime` not work. `do_reload` is main function and `'anime'` is case. If i use `case 'a'` it works perfect but when i use `case 'anime'` nothing happen. Why this ?
As others have stated, you can't use text literals with `case` statements. Your alternatives are: 1. Lookup table with text and function pointers. 2. `std::map` with function pointers. 3. The if/else-if/else ladder. *Note: One issue with `std::map` or lookup table is that all function must have the same signature. The C++ language doesn't allow for different types of function pointers in a `std::map` or structure (lookup table).*
244638
I have a script which gets all the files from particular location.But I need to fetch the files which are lates. The script should give the latest files which are present at that location. eg.I have a location at whcih there are some files named as below ``` DataLogs_20141125_AP.CSV DataLogs_20141125_UK_EARLY.CSV DataLogs_20141125_CAN.CSV DataLogs_20141125_US.CSV DataLogs_20141125_EUR.CSV DataLogs_20141125_US_2.CSV DataLogs_20141126_AP.CSV DataLogs_20141126_UK_EARLY.CSV DataLogs_20141126_CAN.CSV DataLogs_20141126_US.CSV DataLogs_20141126_EUR.CSV DataLogs_20141126_US_2.CSV ``` I want to fetch the files which are the latest. eg.the files matching "20141126" pattern are the latest ones. I tried with match but it gives me all the files. ``` filematch ='DataLogs_2014_*.CSV' ```
You could do this: 1. Get the latest date by splitting individual file names and taking the first element from reverse sorted. 2. From the latest date, get all the files which contain latest date ``` fileList = ['DataLogs_20141125_AP.CSV', 'DataLogs_20141125_UK_EARLY.CSV', 'DataLogs_20141125_CAN.CSV', 'DataLogs_20141125_US.CSV', 'DataLogs_20141125_EUR.CSV', 'DataLogs_20141125_US_2.CSV', 'DataLogs_20141126_AP.CSV', 'DataLogs_20141126_UK_EARLY.CSV','DataLogs_20141126_CAN.CSV', 'DataLogs_20141126_US.CSV','DataLogs_20141126_EUR.CSV', 'DataLogs_20141126_US_2.CSV'] latest = sorted(map(lambda x:x.split('_')[1],fileList), reverse=True)[1] print filter(lambda x:x.find(latest)!=-1, fileList) ``` Output: ``` ['DataLogs_20141126_AP.CSV', 'DataLogs_20141126_UK_EARLY.CSV', 'DataLogs_20141126_CAN.CSV', 'DataLogs_20141126_US.CSV', 'DataLogs_20141126_EUR.CSV', 'DataLogs_20141126_US_2.CSV'] ```
244845
I have created a timer which is not synchronizing on multiple browsers. On inactive tabs of browsers or even on devices timer is running faster or slower.. There is difference of 3-4 seconds on different tabs.. How to sync them? This is my module code: ``` import { Observable, BehaviorSubject, Subscription } from 'rxjs'; export class RAFTimer { public currentFrameId: number; public startTime: number; public numbers: BehaviorSubject<number>; constructor() { this._raf(); this.numbers = new BehaviorSubject<number>(0); this.startTime = 0; } private _raf() { this.currentFrameId = requestAnimationFrame(timestamp => this._nextFrame(timestamp)); } private _nextFrame(timestamp: number) { if ( this.startTime == 0) { this.startTime = timestamp; } const diff: number = timestamp - this.startTime; if ( diff > 100) { const n: number = Math.round(diff / 100); this.startTime = timestamp; this.numbers.next(n); } this._raf(); } cancel() { cancelAnimationFrame(this.currentFrameId); this.currentFrameId = null; } } ``` This is the component code: ``` import { Component, Input, OnInit, OnDestroy } from '@angular/core'; import { RAFTimer } from './raftimer'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit{ title = 'app'; public timeInterval:number=10; public timeLeft:number=10000; constructor(private timer:RAFTimer) { } ngOnInit() { let countNumber=1; let auctiontimer = this.timer.numbers.subscribe( (val) => { countNumber = countNumber+val; if(countNumber >= this.timeInterval) { this.timeLeft = this.timeLeft-countNumber/this.timeInterval; if(this.timeLeft<0) { this.timeLeft= 0; } countNumber=1; } }); } } ``` Please run this url on two different tabs together and you will note the difference in few seconds or within 1 minute.. <https://angular-timer-raf.stackblitz.io/> If you want you can also edit these lines of code by opening this url==> URL [https://stackblitz.com/edit/angular-timer-raf](https://stackblitz.com/edit/angular-timer-raf?file=src%2Fapp%2Fapp.component.ts) I also know that when browser becomes inactive then timer goes slow, I have searched many things but none is working for me. But I need to synchronize timer any how.
You made an external (I hope either global or auction-specific) service for getting the time left and you get an observable from that service. Good, I would do the same! But I think you should remove that "RequestAnimationFrame" from the service. My guess is that you are using it to update the view. You should not do that. RequestAnimationFrame, just like "setTimeout()" is a method that relies on the JS-engine to call that method asynchronously at some time. And before that happens, the thread might be blocked by some View-layer operations. So instead you should let Angular itself handle View-updates, for example like this: `<div>Time: {{timer.numbers | async}}</div>` (async pipe automatically triggers changedetection on every new value). If this doesn't help (is not precise enough), you might consider moving the timer-service on a completely different thread (a WebWorker in the browser) You can also utilize a backend to synchronize your RAFTimer-Service every ... seconds. With REST, you would do that by making a request every ... seconds asking for the current time and other auction information; I assume you are making an auction/bidding app. With websockets you would do that by making the backend-service push that information to the client on every update/interval.
244966
Hi I am working on a school project and I am having a hard time with a particular function. I have been working on it for a while, I would appreciate any type of input. We have to use this function: ``` bool movieLibrary::readMovieInfo(ifstream& inFile) { inFile>>rank>>year>>votes>>nationality; getline(inFile,nameMovie); if (rank < 1) return false; else return true; } ``` My main function keeps giving the wrong output: ``` #include "movieLibrary.h" #include <iostream> #include <fstream> using namespace std; int main() { movieLibrary myMovie[5]; ifstream inFile("myMovieLibrary.txt"); int i =0; //my issue is here while (myMovie[i].readMovieInfo(inFile)) { i++; myMovie[i].readMovieInfo(inFile); } for (int i=0;i<5;++i) { myMovie[i].printMovieInfo("printList.txt"); } return 0; } ``` Here is the output,which should be the same as the input, but here is what I am getting: ``` 3 2000 24446 b Snatch 2 2008 1902 b RocknRolla 5 2007 25510 a American Gangster -1 -858993460 -858993460 Ì -858993460 -858993460 -858993460 Ì ``` Here is the input: myMovieLibrary.txt ``` 3 2000 24446 b Snatch 2 2004 2872 b Layer Cake 2 2008 1902 b RocknRolla 4 1999 7661 b Lock,Stock and Two Smoking Barrels 5 2007 25510 a American Gangster -1 rank year votes Nationality (b:british; a:american) name ``` Here is the MovieLibrary specification file: ``` #include <string> class movieLibrary { public: movieLibrary(); ~movieLibrary(); //void readMovieInfo(std::ifstream&); bool readMovieInfo(std::ifstream&); void printMovieInfo(char*); char getNationality(); int getRank(); bool operator>=(movieLibrary) const; bool operator<(movieLibrary) const; private: int rank; //rank I gave to the movie in my library int year; //year the movie came out int votes; //the number of votes that yahoo users gave the movie std::string nameMovie; //the name of the movie char nationality; //nationality of movie: b for british and a for american }; ``` and the implementation class for MovieLibrary: ``` #include "movieLibrary.h" #include <fstream> #include <string> using namespace std; // here you can use that. movieLibrary::movieLibrary() { } movieLibrary::~movieLibrary() { } bool movieLibrary::readMovieInfo(ifstream& inFile) { inFile>>rank>>year>>votes>>nationality; getline(inFile,nameMovie); if (rank < 1) return false; else return true; } void movieLibrary::printMovieInfo(char* outFileName) { std::ofstream outFile; if(!outFile.is_open()) outFile.open(outFileName, std::ios::app); outFile<<rank<<" "<<year<<" "<<votes<<" "<<nationality<<" "<<nameMovie<<std::endl; } int movieLibrary::getRank() { return rank; } char movieLibrary::getNationality() { return nationality; } ```
Since you call `readMovieInfo` in your loop condition, *and also* in the body of your loop, you'll call it twice for each index except 0. Since you increment `i` before the second call in each iteration, you'll overwrite the second element with the third, the fourth with the fifth, and so on: you'll lose every other movie from the input file. This is reflected in your output: the second and fourth movies disappear. Remember that your loop condition is tested at *each iteration*, so you need to be careful of any side-effects from the condition test. You could address this by removing one or the other calls to `readMovieInfo` (as an exercise try to do it both ways), but I'd prefer to see you write your `while` condition without calling `readMovieInfo`; once you've done this, consider whether a *do/while* loop might be better, and why. Finally, note that you should also check that you're not reading more elements than your array can hold. When you do this, your loop condition becomes a more complicated.
244995
Summary: I have close to 500 \*.csv files that I need to merge into one csv file where during the merge process the filename for each csv needs to be added in each row in a new column. I have read many threads here on stackoverflow and beyond. I am attempting to do this in Terminal (not a script that I run in terminal). Here is what I have so far. When I run this Terminal it returns "for quote>" and does not complete. I am hoping that someone can guide me easily. ``` for f in *.csv; do awk -f ' { x=1 ; if ( x == NR ) { print "date,ProductNumber,Brand,Description,Size,UnitType,Pack,UPC,Available,Status,Delivery Due Date" } else { gsub(".csv","",FILENAME); print FILENAME","$0 } } “$f” > “output$f”; done ``` Each csv file is structured the same and here is some sample data: ``` ProductNumber,Brand,Description,Size,UnitType,Pack,UPC,Available,Status,Delivery Due Date ="0100503","BARNEY BUTTER","ALMOND BTR,SMOOTH","16 OZ ","CS"," 6",="0094922553584"," 99","Active"," " ="0100701","NATRALIA","BODY LOTION,DRY SKIN","8.45 FZ ","EA"," 1",="0835787000765"," 33","Active"," " ="0101741","SAN PELLEGRINO","SPRKLNG BEV,ARANCIATA,ROS","6/11.15F","CS"," 4",="0041508300360"," 0","Active"," " ```
```sh awk -v OFS=, ' FNR == 1 { print "date,ProductNumber,Brand,Description,Size,UnitType,Pack,UPC,Available,Status,Delivery Due Date" file = FILENAME sub(/.csv$/, "", file) } {print file, $0} ' *.csv > out.csv ``` If the list of file is too long, then ```sh find . -name '*.csv' -print0 | xargs -0 awk '...' > out.csv ```
245186
I created a Google sheet for my team and we needed to attach files on it. I found a code which i thought worked well. I haven't coded for sometime nor used google script before. But from looking at it not working it must be the script or the onclick= on submit? The google drive ID is fine , and i checked for all the <> and ;.....but cant seem get to my head around it to upload the file and run the functions..... I am using the code from <https://blackstormdesign.com/how-to-upload-a-file-to-google-drive-through-google-sheets/> Script: Upload\_files ``` Folder_Id = '1dsUl22eeCPSE7-Lpa7VGkR3Jx5TaLc5z' function onOpen(e){ var ss = SpreadsheetApp.getActiveSpreadsheet() var menuEntries = []; menuEntries.push({name: "File", functionName: "doGet"}); ss.addMenu("Attach", menuEntries); } function upload(obj) { var file = DriveApp.getFolderById(Folder_Id).createFile(obj.upload); var activeSheet = SpreadsheetApp.getActiveSheet(); var File_name = file.getName() var value = 'hyperlink("' + file.getUrl() + '";"' + File_name + '")' var activeSheet = SpreadsheetApp.getActiveSheet(); var selection = activeSheet.getSelection(); var cell = selection.getCurrentCell() cell.setFormula(value) return { fileId: file.getId(), mimeType: file.getMimeType(), fileName: file.getName(), }; } function doGet(e) { var activeSheet = SpreadsheetApp.getActiveSheet(); var selection = activeSheet.getSelection(); var cell = selection.getCurrentCell(); var html = HtmlService.createHtmlOutputFromFile('upload'); SpreadsheetApp.getUi().showModalDialog(html, 'Upload File'); } html file with it <!DOCTYPE html> <html> <head> <base target="_top"> <link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css"> </head> <body> <form> <!-- Modified --> <div id="progress" ></div> <input type="file" name="upload" id="file"> <input type="button" value="Submit" class="action" onclick="form_data(this.parentNode)" > <input type="button" value="Close" onclick="google.script.host.close()" /> </form> <script> function form_data(obj){ // Modified google.script.run.withSuccessHandler(closeIt).upload(obj); }; function closeIt(e){ // Modified console.log(e); google.script.host.close(); }; </script> </body> </html> ``` once again thank you so much!
```r n_df <- 20 df_rows <- sample(1:50000, n_df) df_list <- lapply(1:n_df, function(x){ data.frame(z = rnorm(df_rows[[x]])) }) ``` You can also do this without pre-sampling the number of rows in each (if desired): ```r df_list <- lapply(1:n_df, function(x){ data.frame(z = rnorm(sample(1:50000, 1))) }) ``` As Onyambu suggested below, this can be further simplified to: ```r df_list <- lapply(df_rows, function(x){ data.frame(z = rnorm(x)) }) ```
245187
The last few failing builds pass fine on my computer, but I am having trouble getting them to pass on travis. The problem is coming from there few lines in the tests (and other similar operations): <https://github.com/garth5689/pyd2l/blob/master/test/pyd2l_test.py#L15-L20> In my tests, since I have complicated data to test against, I have pickled this data to easily open it back up again and not have to hit the website I'm scraping multiple times every time I test. (Feel free to discuss the merits of this test strategy, but that's not the topic of the question.) ``` class PyD2LMethodsTest(unittest.TestCase): def setUp(self): with open('./soup_1899_pickle.pkl', 'rb') as soup_pickle: self.soup = pickle.load(soup_pickle) with open('./soup_1899_details_pickle.pkl', 'rb') as details_pickle: self.test_details = pickle.load(details_pickle) with open('./test_Match_1899_pickle.pkl', 'rb') as test_Match_pickle: self.test_match = pickle.load(test_Match_pickle) ``` This results in the following series of errors in my travis build: ``` ====================================================================== ERROR: test_calculate_reward_rounded_ceil (pyd2l_test.MatchTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/travis/build/garth5689/pyd2l/test/pyd2l_test.py", line 70, in setUp with open('./test_Match_1899_pickle.pkl', 'rb') as test_Match_pickle: self.test_= pickle.load( FileNotFoundError: [Errno 2] No such file or directory: './test_Match_1899_pickle.pkl' ``` Here is the directory structure ``` pyd2l (repo) |-- pyd2l | |-- (actual source files) | +-- test |-- pyd2l_test.py |-- soup_1899_details_pickle.pkl |-- soup_1899_pickle.pkl |-- soup_404_pickle.pkl +-- test_Match_1899_pickle.pkl ``` The tests all run fine on my local machine. (I added the `./` to the file name during my testing to see if I could get it to work on my own. I think there might be something in the environment variables that I need to work with, but I'm not sure. There might also be the possibility that travis doesn't allow pickling/unpickling, but I couldn't find anything to that effect. Any help is appreciated. Travis builds: <https://travis-ci.org/garth5689/pyd2l/builds>
`./` is redundant; the path to the file is already relative to your current working directory. The problem is that you want it to instead be relative to your test directory, so: ``` import os # ... with open(os.path.join(os.path.dirname(__file__), 'soup_1899_pickle.pkl'), 'rb') as soup_pickle: ```
245406
I have a following mysql query to update my `tblcem_appraisal_log` table ``` UPDATE tblcem_appraisal_log AS tblog INNER JOIN ( SELECT ta.id FROM tblcem_appraisal_log AS ta INNER JOIN tblcem_master_appraisal AS tm ON tm.id = ta.master_app_id ORDER BY ta.id DESC LIMIT 1) AS source ON source.id = tblog.id SET tblog.quarter1 = tblcem_master_appraisal.quarter1 WHERE tblog.master_app_id=8; ``` I am getting an error `unknown column tblcem_master_appraisal.quarter1` though column `quarter1` is present in both tables. What exactly need to put in `SET` to update value from `tblcem_master_appraisal` table.
You have to select the column in your subselect and use the alias of that table: ``` UPDATE tblcem_appraisal_log AS tblog INNER JOIN ( SELECT ta.id, tm.quarter1 FROM tblcem_appraisal_log AS ta INNER JOIN tblcem_master_appraisal AS tm ON tm.id = ta.master_app_id ORDER BY ta.id DESC LIMIT 1) AS source ON source.id = tblog.id SET tblog.quarter1 = source.quarter1 WHERE tblog.master_app_id=8; ```
245954
I've been trying to retrieve some of my e-mails in order to have them as data in R. In case it is needed, it is on a Microsoft Exchange Server. ``` require(RDCOMClient) folderName = 'ElastAlerts' #creating the outlook object OutApp <- COMCreate('Outlook.Application') outlookNameSpace <- OutApp$GetNameSpace("MAPI") folder <- outlookNameSpace$Folders(1)$Folders(folderName) ``` But the final line shows me the following error: ``` <checkErrorInfo> 80020009 No support for InterfaceSupportsErrorInfo checkErrorInfo -2147352567 Error: Exception occurred ``` Thank you.
I was facing the same issue and resolved it after playing around it. Possible solutions, In `folder <- outlookNameSpace$Folders(1)$Folders(folderName)` This instead of using "1" try using "2" or "3", it works for me. Don't know why it is changing folder index.
245979
I am having trouble reading in data from a JSON file. I have gone through the other reading JSON questions on Stack Overflow and the JSON docs to no avail. I am trying to read in data to be displayed in Three.js. The following snippet works: ``` var obj = { "points" : [ { "vertex":[0.0,0.0,0.0] }, { "vertex":[200.0,0.0,0.0] }, { "vertex":[-200.0,0.0,0.0] }, { "vertex":[0.0,100.0,0.0] }, { "vertex":[0.0,-100.0,0.0] }, { "vertex":[0.0,0.0,300.0] }, { "vertex":[0.0,0.0,-300.0] }, { "vertex":[75.0,75.0,75.0] }, { "vertex":[50.0,50.0,50.0] }, { "vertex":[25.0,25.0,25.0] } ]}; var geometry = new THREE.Geometry(); for (var i=0;i<10;i++) { var vertex = new THREE.Vector3(); vertex.x = obj.points[i].vertex[0]; vertex.y = obj.points[i].vertex[1]; vertex.z = obj.points[i].vertex[2]; geometry.vertices.push( vertex ); } ``` It reads in the points and the points are rendered further down the line. I have a file next to the index.html named > > test.json > > > it contains the following: ``` { "points" : [ { "vertex":[0.0,0.0,0.0] }, { "vertex":[200.0,0.0,0.0] }, { "vertex":[-200.0,0.0,0.0] }, { "vertex":[0.0,100.0,0.0] }, { "vertex":[0.0,-100.0,0.0] }, { "vertex":[0.0,0.0,300.0] }, { "vertex":[0.0,0.0,-300.0] }, { "vertex":[75.0,75.0,75.0] }, { "vertex":[50.0,50.0,50.0] }, { "vertex":[25.0,25.0,25.0] } ]} ``` My problem is that the following doesn't work (i.e. doesn't display the points): ``` var geometry = new THREE.Geometry(); var obj2 = jQuery.getJSON('test.json'); for (var i=0;i<10;i++) { var vertex = new THREE.Vector3(); vertex.x = obj2.points[i].vertex[0]; vertex.y = obj2.points[i].vertex[1]; vertex.z = obj2.points[i].vertex[2]; geometry.vertices.push( vertex ); } ``` The files are in the public folder of my dropbox and viewed from the public link, even so, just in case i'm running chrome with the --allow-files-access-from-files flag. UPDATE My key mistake was not processing the vertices in the callback of the getJSON function. My secondary mistake was assuming that adding the vertices to the geometry stack in the callback was enough. In fact I had to create the object from the geometry and add it to the scene for it to work. Many thanks for everyones help. ``` $.getJSON('test.json', function(obj2) { var geometry = new THREE.Geometry(); for (var i=0;i<10;i++) { var vertex = new THREE.Vector3(); vertex.x = obj2.points[i].vertex[0]; vertex.y = obj2.points[i].vertex[1]; vertex.z = obj2.points[i].vertex[2]; geometry.vertices.push( vertex ); } vc1 = geometry.vertices.length; object = new THREE.ParticleSystem( geometry, shaderMaterial ); object.dynamic = true; var vertices = object.geometry.vertices; var values_size = attributes.size.value; var values_color = attributes.ca.value; for( var v = 0; v < vertices.length; v ++ ) { values_size[ v ] = 50; values_color[ v ] = new THREE.Color( 0xffffff ); } scene.add( object ); }); ```
Read the docs for [getJSON](http://api.jquery.com/jQuery.getJSON/), it is an asynchronous call! You need to put the for loop in in the callback.
246066
Given a number \$n ≥ 2\$, a [blackbox function](https://codegolf.meta.stackexchange.com/a/13706/100664) \$f\$ that takes no arguments and returns a random integer in the range 0...n-1 inclusive, and a number \$m ≥ n\$, your challenge is to generate a random integer in the range 0...m-1 inclusive. You may not use any nondeterministic builtins or behaviour, your only source of randomisation is \$f\$. The number you produce must be uniformly random. \$m\$ is not limited to powers of \$n\$. One way to do this could be to generate \$\operatorname{ceil}(\log\_n(m))\$ random numbers, convert these from base \$n\$ to an integer, and reject-and-try-again if the result's greater than or equal to \$m\$. For example, the following JS could do this: ``` function generate(n,m,f){ let amountToGenerate = Math.ceil(Math.log(m)/Math.log(n)) // Calculating the amount of times we need to call f let sumSoFar = 0; for(let i = 0; i < amountToGenerate; i++){ // Repeat that many times... sumSoFar *= n; // Multiply the cumulative sum by n sumSoFar += f() // And add a random number } if(sumSoFar >= m){ // If it's too big, try again return generate(n,m,f); } else { // Else return the number regenerated return sumSoFar } } ``` An *invalid* solution could look something like this: ``` function generate(n,m,f){ let sumSoFar = 0; for(let i = 0; i < m/n; i++){ // m/n times... sumSoFar += f() // add a random number to the cumulative sum } return sumSoFar } ``` This is invalid because it takes the sum of \$\frac{m}{n}\$ calls of f, so the randomness is not uniform, as higher/lower numbers have a smaller chance of being returned. \$f\$ is guranteed to produce uniformly random integers, and can be independently sampled as many times as you want. Instead of taking \$f\$ as a function, you may also take it as a stream or iterator of values, or an arbitrarily long list of values. The ranges may be 1...n instead of 0...n-1. Scoring ------- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins!
[Jelly](https://github.com/DennisMitchell/jelly), ~~6~~ 5 bytes =============================================================== ``` ÇÐṀḊ¿ ``` [Try it online!](https://tio.run/##AR0A4v9qZWxsef81WOKAmf/Dh8OQ4bmA4biKwr////8yNw "Jelly – Try It Online") A monadic link taking `m` as its argument and expecting the blackbox function to be in the previous link (e.g. header on TIO). Thanks to @JonathanAllan for pointing this out as per [this meta post](https://codegolf.meta.stackexchange.com/a/13707/53748) and also for saving a byte with a suggested switch to 1 indexing! Explanation ----------- ``` | Implicit range 1..m Ḋ¿ | While list length > 1 (literally while the list with its first member removed is non-empty): ÐṀ | - Take the list member(s) that are maximal when: Ç | - The supplied function is run for each list member ``` --- If the function had to be provided as an argument, here is an alternative: [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ========================================================= ``` ṛ⁴V$ÐṀḊ¿ ``` [Try it online!](https://tio.run/##ASQA2/9qZWxsef//4bmb4oG0ViTDkOG5gOG4isK/////Mjf/NVjigJk "Jelly – Try It Online") A full program taking `m` and the Jelly code for `f` as its two arguments. If it’s mandatory to also take `n`, this can be provided as an (unused) third argument. Explanation ----------- ``` | Implicit range 1..m Ḋ¿ | While list length > 1 (literally while the list with its first member removed is non-empty): $ÐṀ | - Take the list member(s) that are maximal when: ṛ⁴V | - The supplied function is run for each list member ``` --- Previous answer: [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes =========================================================================== ``` ³lĊ⁵V¤€ḅʋ⁴¤<³¬$¿ ``` [Try it online!](https://tio.run/##ATQAy/9qZWxsef//wrNsxIrigbVWwqTigqzhuIXKi@KBtMKkPMKzwqwkwr////83Mv84/zhY4oCZ "Jelly – Try It Online") A full program that takes `n`, `m` and the Jelly code for `f` as its arguments and prints the resulting random number to STDOUT. Explanation ----------- ``` <³¬$¿ | While not < m: ³ ʋ⁴¤ | - Do the following, taking m as the left argument and n as the right: l | - m log n Ċ | - Ceiling ⁵V¤€ | - Execute f that many times ḅ | - Convert from base n ```
246651
I see this question out there. but the answer doesn't work for me. I created an empty asp.net website. .NET 4.5 I installed the sample in nuget via Install-Package Microsoft.AspNet.Identity.Sample -pre I could not get the initializer to run. so i the did the following ``` public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false) { Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer()); this.Database.Initialize(true); } static ApplicationDbContext() { // Set the database intializer which is run once during application start // This seeds the database with admin user credentials and admin role // }` ` public static ApplicationDbContext Create() { return new ApplicationDbContext(); } } ``` The Rolemanager is always null. I tried the other answers but they never worked. I did not change the sample other than what is shown above. So why doesn't it work? the db and the tables are created tho. the rolemanager is used below and is null. ``` public static void InitializeIdentityForEF(ApplicationDbContext db) { var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>(); var roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>(); const string name = "admin@example.com"; const string password = "Admin@123456"; const string roleName = "Admin"; //Create Role Admin if it does not exist var role = roleManager.FindByName(roleName); if (role == null) ```
I try this, and problem is solved. in 「App\_Start\Startup.Auth.cs」 ``` public partial class Startup { // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { // Configure the db context, user manager and role manager to use a single instance per request app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create); app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create); ... } } ``` just ref [HttpContext.GetOwinContext().GetUserManager<AppRoleManager>() return null](https://stackoverflow.com/questions/26347582/httpcontext-getowincontext-getusermanagerapprolemanager-return-null)
246691
I'm new to numpy and have been tasked with the following situation: I need to create two numpy arrays of random integers (between 0 + 1). One numpy array represents the x-coordinates and the other one represents the y-coordinates. I then need to check to see if the points fall inside a circle of radius one by using squareroot(x^2 + y^2) < 1. I'm currently just trying to square my arrays and add them together. What is probably a very simple task is giving me no ends of trouble. ``` import matplotlib.pyplot as plt import numpy as np plots = 100 dataOne = np.random.random(size = plots) dataTwo = np.random.random(size = plots) circle = plt.Circle((0,0), 1, alpha = 0.1) plt.gca().add_patch(circle) plt.xlim(0, 5) plt.ylim(0, 5) plt.show() squareDataOne = dataOne ** 2 squareDataTwo = dataTwo ** 2 if squareDataOne + squareDataTwo < 1: print("Now check square-root!") ``` I keep receiving an error message: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all(). Could anyone explain why Python/Numpy does not like this? I've been told to try and use a Boolean expression to slice the array. Can anyone provide suggestions on the best way to incorporate this into my given code? Any suggestions or tips for a newbie are appreciated.
**squareDataOne** looks like this: ``` [7.43871942e-02 2.73007883e-01 5.23115388e-03 6.57541340e-01 3.08779564e-01 1.24098667e-02 5.08258990e-01 6.52590269e-01 8.90656103e-02 3.76389212e-02 2.12513661e-01 2.79683875e-01 7.76233370e-01 6.48353342e-02 8.01663208e-01 8.69331480e-01 4.34903542e] ``` **squareData2** looks similar. The expression in your **if** statement: ``` squareDataOne + squareDataTwo < 1 ``` produces this array: ``` [ True False True True True True True True False False True False True False False True True True True True False True False False True True False True True True True True True True True True True True False False True False] ``` So your **if** statement is expecting a **True** or **False** value, and is getting this array. The error message is telling you that Python doesn't know how to turn this array into a single **True** or **False** value. I don't understand the logic of your code well enough to know what you need to do to fix this. Clearly you have a lot of data, and yet you expect to decide a binary event; if you should print "Now check square-root!" or not. I have no idea how you should do that.
246706
**AN OVERBROAD PATENT ON ELECTRONIC COLLECTION OF ITEMS** - This patent claims the idea of... an electronic collection of items! 10 minutes of your time can help narrow US patent applications before they become patents. [Follow @askpatents](https://twitter.com/AskPatents) on twitter to help. **QUESTION** - Have you seen anything that was **published before Dec 3, 2003** that discusses the elements described in the claim below: **TITLE: COMPUTING DEVICE FOR SEARCHING, IDENTIFYING, AND DISPLAYING ITEMS IN A COLLECTION** Patent **[US7363309](http://www.google.com/patents/us7363309)** "Method and system for portable and desktop computing devices to allow searching, identification and display of items in a collection" seems to be a dangerous patent. Programmers do this kind of thing regularly. **Claim 1** requires each and every step below: > > A field-useable guide in the form of a portable computer device for identifying natural items observed by a user from a collection of natural items, comprising: > > > * a housing for the portable computer device, the housing containing a programmed microprocessor, data storage, a display screen and a user input, > * means in the microprocessor and data storage for displaying to the user a series of selectable attributes which vary among natural items in the collection of natural items, each attribute having one or more data types in which a plurality of values for the attribute are stored in the data storage, the values for the series of selectable attributes being in a plurality of the following data types stored in the storage for presentation to the user in a search conducted by the user: > > (a) descriptive text, > > (b) number values, > > (c) color images of natural items in the collection of natural items, > > (d) sounds produced by natural items, in the case of a group of animals as the collection of natural items, > > (e) moving pictures of natural items, in the case of animals as the natural items of the collection, > > (f) color samples for matching to a feature of an observed natural item of a collection of natural items, > > (g) silhouettes representative of groups of natural items within a collection of natural items, and > * search means associated with the microprocessor for enabling and prompting the user, on the display screen, to perform a step-by-step elimination search to identify a natural item observed in the field by selecting one of said attributes, reviewing the various values presented by the portable computer device as possible values under the subject selected attribute for the natural item observed in the field, then selecting one said value for the selected attribute, then selecting another of said attributes, reviewing the values presented as possible values for said another selected attribute and selecting one of the values, and continuing the stepwise elimination search to further reduce the number of possible natural items in the natural items of the collection, the search means progressively eliminating non-matches from a list of possible natural items in the natural items of the collection, > > and including elimination means associated with the microprocessor for eliminating further said attributes which become irrelevant or redundant after selection by a user of a particular value for a said attribute, and further including means associated with the microprocessor for eliminating certain of the values under particular said attributes which values become irrelevant or redundant as choices due to prior selection of particular aid values under one or more previously selected said attributes, > > whereby the elimination means, in the step-by-step elimination search, assures against a null result of the search. > > >
A successive process of elimination using the attributes of a collection of images is the basis of the board game "Guess Who?" which has been sold by Milton Bradley since 1979. In this game players try to identify a selected face in a collection, by questioning each other about facial attributes and eliminating faces from the collection based on the answers. <http://boardgamegeek.com/boardgame/4143/guess-who> <http://en.wikipedia.org/wiki/Guess_Who%3F> The word "plurality" in the patent application seems to be an attempt to obfuscate the simple concept of a "list". Searching lists based on characteristics of items in the list is a common programming practice, central to every database application in existence.
247061
So right now trying to test out the new Visual Studio Code on OS X, but running into a myriad of issues. Right now been sort out the issue with the dnu command, but now having issues with: `dnx . kestrel` This would be in relation to the **Commands with Ease** section from the [Visual Studio Code](https://code.visualstudio.com/Docs/ASPnet5) and having the following error message shown in my terminal. So far followed everything step by step and still having issues. ``` System.InvalidOperationException: No service for type 'Microsoft.Framework.Runtime.IApplicationEnvironment' has been registered. at Microsoft.Framework.DependencyInjection.ServiceProviderExtensions.GetRequiredService (IServiceProvider provider, System.Type serviceType) [0x00000] in <filename unknown>:0 at Microsoft.Framework.DependencyInjection.ServiceProviderExtensions.GetRequiredService[IApplicationEnvironment] (IServiceProvider provider) [0x00000] in <filename unknown>:0 at Microsoft.AspNet.Hosting.HostingEngine..ctor (IServiceProvider fallbackServices) [0x00000] in <filename unknown>:0 at Microsoft.AspNet.Hosting.Program.Main (System.String[] args) [0x00000] in <filename unknown>:0 at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&) at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000] in <filename unknown>:0 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x00000] in <filename unknown>:0 at Microsoft.Framework.Runtime.Common.EntryPointExecutor.Execute (System.Reflection.Assembly assembly, System.String[] args, IServiceProvider serviceProvider) [0x00000] in <filename unknown>:0 at Microsoft.Framework.ApplicationHost.Program.ExecuteMain (Microsoft.Framework.Runtime.DefaultHost host, System.String applicationName, System.String[] args) [0x00000] in <filename unknown>:0 at Microsoft.Framework.ApplicationHost.Program.Main (System.String[] args) [0x00000] in <filename unknown>:0 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x00000] in <filename unknown>:0 at Microsoft.Framework.Runtime.Common.EntryPointExecutor.Execute (System.Reflection.Assembly assembly, System.String[] args, IServiceProvider serviceProvider) [0x00000] in <filename unknown>:0 at dnx.host.Bootstrapper.RunAsync (System.Collections.Generic.List`1 args) [0x00000] in <filename unknown>:0 ``` Hope you guys can help.
I had a similar issue when trying to run from the \samples\latest folder instead of \samples\1.0.0-beta4 folder. Simply trying again from where I was supposed to be worked.
247086
[![What My new screen does...](https://i.stack.imgur.com/bPxyl.jpg)](https://i.stack.imgur.com/bPxyl.jpg) So a week ago i purchased a 7" MAKIBES touchscreen for my raspberry pi 2 I went on this website for help with setting this screen up: <http://www.waveshare.com/wiki/7inch_HDMI_LCD_(B)#Rev1.1_LCD_Images_for_Raspberry_Pi> Unfortunately the screen didn't work. I plug the pi into my normal monitor to fiddle with the config and install what i think are the right drivers but it still isn't working. Some people on the Amazon reviews said that the issue could be NOOBS but I don't know about that. I don't really need the touchscreen part of the screen so if its an issue with that and a solution is available that means i get no touch screen I don't mind. I wanted to prove to my family that computers can be fun and I can build my own tiny computer but in the process have made myself look like an idiot. Please help me ;-; **Thanks**
Based on everything you've described in the comments, it sounds like your issue is directly related to your power supply. The Raspberry Pi Foundation [recommends](https://www.raspberrypi.org/help/faqs/#powerReqs) a minimum of a `1.8`. According to your comment, you have a `.5 A`. > > .., is there a suitable charger on Amazon for my pi? Will any micro usb charger do? > > > That is actually one of the best parts about the USB standard. USB stands for *Universal Serial Bus*; what works for one, should work for any. I have two of [these](http://rads.stackoverflow.com/amzn/click/B00M26DQBK) and have been very happy with them. But again, anything with the proper power output will work.
247157
I want to log user's actions in my Ruby on Rails application. So far, I have a model observer that inserts logs to the database after updates and creates. In order to store which user performed the action that was logged, I require access to the session but that is problematic. Firstly, it breaks the MVC model. Secondly, techniques range from the hackish to the outlandish, perhaps maybe even tying the implementation to the Mongrel server. What is the right approach to take?
Hrm, this is a sticky situation. You pretty much HAVE to violate MVC to get it working nicely. I'd do something like this: ``` class MyObserverClass < ActiveRecord::Observer cattr_accessor :current_user # GLOBAL VARIABLE. RELIES ON RAILS BEING SINGLE THREADED # other logging code goes here end class ApplicationController before_filter :set_current_user_for_observer def set_current_user_for_observer MyObserverClass.current_user = session[:user] end end ``` It is a bit hacky, but it's no more hacky than many other core rails things I've seen. All you'd need to do to make it threadsafe (this only matters if you run on jruby anyway) is to change the cattr\_accessor to be a proper method, and have it store it's data in thread-local storage
247447
I'm trying to remove date properties from Article schema generated by the Yoast SEO plugin. In their developer [docs](https://developer.yoast.com/features/schema/api/#change-a-graph-pieces-data) the `wpseo_schema_article` filter is set as an example for manipulating with Article graph piece. However even with this `type="application/ld+json"`: ```html <script type="application/ld+json"> { "@context":"https://schema.org", "@type":"Article", "mainEntityOfPage":{ "@type":"WebPage", "@id":"https://www.myproscooter.com/etwow-electric-scooters-review/" }, "headline":"E-Twow Electric Scooters 2021 Review", "image":{ "@type":"ImageObject", "url":"https://www.myproscooter.com/wp-content/uploads/2020/12/elek-scoot.jpg", "width":700, "height":400 }, "datePublished":"2020-12-08T08:52:13", "dateModified":"2021-01-12T11:30:10", "author":{ "@type":"Person", "name":"Jason" }, "publisher":{ "@type":"Organization", "name":"MyProScooter", "logo":{ "@type":"ImageObject", "url":"https://www.myproscooter.com/wp-content/uploads/2021/01/MPS-Logo-228x60.png" } } } </script> ``` When I try to access and manipulate data like this: ``` add_filter( 'wpseo_schema_article', 'remove_article_dates' ); function remove_article_dates( $data ) { file_put_contents(WP_CONTENT_DIR.'/helper-seo.txt','DATA PRE FILTER: '.print_r($data,true),FILE_APPEND); unset($data['datePublished']); unset($data['dateModified']); return $data; } ``` Nothing gets logged into helper-seo.txt nor do dates get unset in the Article schema; as if the filter is ignored totally. What's more confusing is that manipulation with dates in Webpage Schema works and is similar to the above: ``` add_filter( 'wpseo_schema_webpage', 'remove_webpage_dates'); function remove_webpage_dates( $data ) { unset($data['datePublished']); unset($data['dateModified']); return $data; } ``` The other stuff I've tried include: ``` add_filter( 'wpseo_schema_article_date_published', '__return_false' ); add_filter( 'wpseo_schema_article_date_modified', '__return_false' ); ``` Which isn't reflecting into Article schema at all. **How to remove these properties sucessfully?**
Use [`numpy broadcasting`](https://numpy.org/doc/stable/user/basics.broadcasting.html), (`[:, None]`), to compare each date with all rows in contracts to check if the date is inbetween, then sum the number of contracts where this is `True`. First create a DataFrame of your dates then we do the comparison. ``` df = pd.DataFrame({'date': pd.date_range('2016-01-01', '2021-01-01', freq='D')}) df['active'] = ((df['date'].to_numpy() >= contracts['initial_date'].to_numpy()[:, None]) & (df['date'].to_numpy() <= contracts['end_date'].to_numpy()[:, None])).sum(axis=0) ``` --- **Verification** ``` df.set_index('date').plot() ``` [![enter image description here](https://i.stack.imgur.com/dfsra.png)](https://i.stack.imgur.com/dfsra.png)
247510
I have done almost everything from numerous tutorials to get the RTC to work, but when I run `sudo hwclock -r`, i still get the following error. > > hwclock: Cannot access the Hardware Clock via any known method. > hwclock: Use the --debug option to see the details of our search for > an access method. > > > My sudo i2cdetect -y 1 is detecting the RTC DS3231 as below: ``` pi@raspberrypi:~ $ sudo i2cdetect -y 1 0 1 2 3 4 5 6 7 8 9 a b c d e f 00: -- -- -- -- -- -- -- -- -- -- -- -- -- 10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 50: -- -- -- -- -- -- -- 57 -- -- -- -- -- -- -- -- 60: -- -- -- -- -- -- -- -- 68 -- -- -- -- -- -- -- 70: -- -- -- -- -- -- -- -- ``` EDIT: What I have done till now Connected the RTC to the RasPi 3. Enabled i2c in sudo raspi-config My /etc/modules is now ``` snd-bcm2835 i2c-bcm2835 i2c-bcm2708 i2c-dev rtc-ds1307 ``` Added the following lines to /boot/config.txt ``` # Support for rtc ds3231 dtoverlay=i2c-rtc,ds3231 dtoverlay=i2c-rtc,ds1307 dtparam=i2c_arm=on dtparam=i2c1=on device_tree= ``` My /etc/rc.local has the following lines ``` echo ds3231 0x68 > /sys/class/i2c-adapter/i2c-1/new_device hwclock -s ``` But i do get an INVALID ARGUMENT ERROR when i run `sudo echo ds3231 0x68 > /sys/class/i2c-adapter/i2c-1/new_device`. At the end, sudo hwclock or hwclock gives the error : `hwclock: Cannot access the Hardware Clock via any known method. hwclock: Use the --debug option to see the details of our search for an access method.` Can somebody suggest me on a fix for this. EDIT: Tried the fix suggested on a fresh install of NOOBS v1.9.2 after sudo apt-get update and sudo apt-get dist-upgrade Same issue remain.[![enter image description here](https://i.stack.imgur.com/N6TGt.png)](https://i.stack.imgur.com/N6TGt.png) ADDED on 03.Oct.2016 As per inputs from joan and Milliways, I have added `dtoverlay=i2c-rtc,ds3231` only, and got the hwclock to give date and time, bu the problem is that hwclock runs like internal clock now, it doesn't keep time across reboots. Any inputs?
You should be using device tree now. I suggest the following changes. Remove the following lines from `/etc/modules' ```none snd-bcm2835 i2c-bcm2835 i2c-bcm2708 rtc-ds1307 ``` I.e. `/etc/modules` should only contain ```none i2c-dev ``` Remove the following line from `/etc/rc.local` ```none echo ds3231 0x68 > /sys/class/i2c-adapter/i2c-1/new_device hwclock -s ``` **I'm not sure if `hwclock -s` is needed or not.** Remove the following lines from `/boot/config.txt` ```none # Support for rtc ds3231 dtoverlay=i2c-rtc,ds1307 dtparam=i2c1=on device_tree= ``` I.e. of those lines only leave ```none dtparam=i2c_arm=on dtoverlay=i2c-rtc,ds3231 ``` See `/boot/overlays/README` for general information.
247687
I have created a modal box called sectors. Within my modal box I have created a line of code where the text will change color on click, but I want the original text color to be blue. I have tried setting the original font color to blue; but then the text does not change color on click. ```html <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script> <!-- Remember to include jQuery :) --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script> <!-- jQuery Modal --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.css" /> </head> <style> .onlyThese{ cursor:pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } input[type="checkbox"] { display: none } input[type="checkbox"]:checked+label { color:red } } input[type="checkbox"] { display: none } input[type="checkbox"]:checked+label { color:red } input:focus{ outline: none; } </style> <body> <p> <a class="btn" href="#ex5">Sectors </a> </p> <div id="ex5"; class="modal"; style="background-color:white"> <div style="float:left;"> <p> <input type="checkbox" id="group1"> <label for="group1" class="onlyThese">Publication </label> </p> </div> <div> <p style="float:right"> <a href="#" rel="modal:close"; class="onlyThese;"> <b>Apply</b> </a> </p> </div> </div> <script> $('a[href="#ex5"]').click(function(event) { event.preventDefault(); $(this).modal({ escapeClose: false, clickClose: false, showClose: false, }); }); </script> ``` The text will change color from blue to red and when its red the checkbox will be checked. When it is blue the checkbox will be un-checked. The checkbox is invisible but the color of the text signals whether it is checked or not.
There are a couple of issues: 1. The draw options aren't quite right. This isn't actually causing the error, though. 2. There's a bug leaflet-draw that causes the exception you're seeing. Leaflet Draw Options -------------------- `square` is not a draw option. The correct option is `rectangle`. Additionally, all of the handlers are enabled by default. So, you only need to turn off the ones you don't want. So, I think what you want is in your `app.component.ts` file: ``` public drawOptions = { position: 'topright', draw: { marker: { icon: L.icon({ iconSize: [25, 41], iconAnchor: [13, 41], iconUrl: 'assets/marker-icon.png', shadowUrl: 'assets/marker-shadow.png' }) }, polygon: false, circlemarker: false } }; ``` The above will make sure that marker, circle, rectangle, and polyline are enabled and the others are disabled. You want to make sure to add the leaflet assets png files to the list of assets being exported by Angular CLI in your `angular.json` file. Identifying and Fixing The Error -------------------------------- There's something weird about leaflet-draw's build that's causing the source maps to not work. To get them working, I had to directly import the `leaflet.draw-src.js` file. At the top of `app.component.ts`, I added: ``` import * as L from 'leaflet'; import '../../node_modules/leaflet-draw/dist/leaflet.draw-src.js'; // add this ``` That allows you to put a breakpoint in the leaflet-draw code to figure out what's going on. Upon doing that, it looks like there's a variable called `type` that isn't declared before it's assigned to. The code is being run in strict mode, so this will throw an exception. This looks to be a bug in leaflet-draw. ### Solution 1: Disable ShowArea First, you can disable `showArea`, which will prevent the problem code from running. To do this, modify the `drawOptions`: ``` public drawOptions = { position: 'topright', draw: { marker: { icon: L.icon({ iconSize: [25, 41], iconAnchor: [13, 41], iconUrl: 'assets/marker-icon.png', shadowUrl: 'assets/marker-shadow.png' }) }, rectangle: { showArea: false }, // disable showArea polyline: true, polygon: false, circlemarker: false } }; ``` This isn't a great solution, cause you lose the showArea functionality. ### Solution 2: Disable Strict Mode The other solution is to disable strict mode for the Typescript compiler. To do this, edit your `tsconfig.json` and `tsconfig.app.json` files, adding `"noImplicitUseStrict": true` under the `compilerOptions` property. This solves the problem, but now you're not running your code in strict mode, which can lead to other issues.
248234
This isn't a duplication of [Submit code during interview](https://softwareengineering.stackexchange.com/questions/98619/submit-code-during-interview), it's more a specific case. Let me tell how the situation developed. I was contacted by a small company(<50) in Europe. I am located in South America. I spoke with the HR person, and they requested some code samples, so I linked them to some samples from my GitHub account. The CTO liked my profile and I had a lengthy video call with him. Everything went smooth, he told me the salary, the conditions, he send them by mail, etc. Then he said that he would send me a test project in the following days, and if I pass the test I would go there for a trial period before being a full time employee. This is expected, companies usually review possible future employees, and like to see their way of working before hiring them. But when the test arrived, the specs requested it to be reusable to several projects and to use [the Unlicense](https://unlicense.org/). The project itself is a generic module that could be used in all the projects the company has, requesting it to be reusable raises some flags, but, requesting such a specific license, raised even more flags of this being a typical case of free work. I had emailed the CTO with my doubts, and saying that I want to use a different license (MPL 2.0), having no problem in changing it in the case the I get accepted. I refuse to use such a license with no guarantees. This isn't a normal practice in Europe, right? Am I right to be careful? I have a lot of experience with interviews and scams, and I didn't notice any trace of malice in the video call, so I kind of assume that the employer maybe isn't aware of the flags he triggered, at the same time I had the whole normal interview process and spoke with him for two hours. The scams that I have been sent, were more of an automated process, with minimal interaction from the employer. This is why I give them the benefit of the doubt. For now I'm waiting for a reply, but, as asked above, I'm okay to be cautious?
Yes, be cautious. They don't need the license to **code written on your time**. In order to use the code, they would just need surrender language *in your employment offer*. It isn't a traditional scam - as you said, scammers don't spend two hours with a mark. **But** it does sound like *they intended to use your code whether they hire you or not*. I wouldn't be comfortable with that.
248247
Hello everyone I'm trying to setup my hp laserjet 4100n printer, but ubuntu 11.10 doesn't recognize it. I try to install the HPLIP or linux drivers, but then when it says to restart your computer when you have a parallel port printer nothing happens once you restart it. I try the installation 3 times ignoring the step where it says to restart, but then it says your printer is not recognize please help. I'm using a parallel to usb converter and I know it works because I try it in windows and the printer works like a charm.Please Help anyone? * I also try installing it in my sisters ubuntu 11.04 and it recognize it and prints. * Also when I share the printer in my sister computers it works on mine like a network printer,but it has to be connected to my sisters computer in order for me to print. * I also forgot to mention that I have another printer connected to this computer, I try deleting and disconnecting my other printer, but it still doesn't detect my laserjet 4100n. This is what I get and the printer is connected ``` note: Defaults for each question are maked with a '*'. Press <enter> to accept the default. INSTALLATION MODE ----------------- Automatic mode will install the full HPLIP solution with the most common options. Custom mode allows you to choose installation options to fit specific requirements. Please choose the installation mode (a=automatic*, c=custom, q=quit) : a Initializing. Please wait... INTRODUCTION ------------ This installer will install HPLIP version 3.11.10 on your computer. Please close any running package management systems now (YaST, Adept, Synaptic, Up2date, etc). DISTRO/OS CONFIRMATION ---------------------- Distro appears to be Ubuntu 11.10. Is "Ubuntu 11.10" your correct distro/OS and version (y=yes*, n=no, q=quit) ? y ENTER USER PASSWORD ------------------- Please enter the user (jab)'s password: Password accepted INSTALLATION NOTES ------------------ Enable the universe/multiverse repositories. Also be sure you are using the Ubuntu "Main" Repositories. See: https://help.ubuntu.com/community/Repositories/Ubuntu for more information. Disable the CD-ROM/DVD source if you do not have the Ubuntu installation media inserted in the drive. During the install process you will be added to the lp and lpadmin group, please quit the installer before the setup stage, log out, log back in, and run hp-setup to complete the install. Please read the installation notes. Press <enter> to continue or 'q' to quit: RUNNING PRE-INSTALL COMMANDS ---------------------------- OK CHECKING FOR NETWORK CONNECTION ------------------------------- Network connection present. RUNNING PRE-PACKAGE COMMANDS ---------------------------- sudo dpkg --configure -a (Pre-depend step 1) sudo apt-get install --yes --force-yes -f (Pre-depend step 2) sudo apt-get update (Pre-depend step 3) OK DEPENDENCY AND CONFLICT RESOLUTION ---------------------------------- warning: A previous install of HPLIP is installed and/or running. sudo apt-get remove --assume-yes hplip hpijs hplip-cups hplip-data libhpmud0 foomatic-db-hpijs (Removing old HPLIP version) warning: HPLIP removal failed. The previous install may have been installed using a tarball or this installer. warning: Continuing to run installer - this installation should overwrite the previous one. RUNNING POST-PACKAGE COMMANDS ----------------------------- OK RE-CHECKING DEPENDENCIES ------------------------ OK PRE-BUILD COMMANDS ------------------ OK BUILD AND INSTALL ----------------- Running './configure --with-hpppddir=/usr/share/ppd/HP --libdir=/usr/lib64 --prefix=/usr --enable-udev-acl-rules --enable-qt4 --enable-doc-build --disable-cups-ppd-install --disable-foomatic-drv-install --disable-foomatic-ppd-install --disable-hpijs-install --disable-policykit --enable-cups-drv-install --enable-hpcups-install --enable-network-build --enable-dbus-build --enable-scan-build --enable-fax-build' Please wait, this may take several minutes... Command completed successfully. Running 'make clean' Please wait, this may take several minutes... Command completed successfully. Running 'make' Please wait, this may take several minutes... Command completed successfully. Running 'sudo make install' Please wait, this may take several minutes... Command completed successfully. Build complete. POST-BUILD COMMANDS ------------------- sudo /usr/sbin/usermod -a -Glp,lpadmin jab (Post-build step 1) CLOSE HP_SYSTRAY ---------------- Sending close message to hp-systray (if it is currently running)... RESTART OR RE-PLUG IS REQUIRED ------------------------------ If you are installing a USB connected printer, and the printer was plugged in when you started this installer, you will need to either restart your PC or unplug and re-plug in your printer (USB cable only). If you choose to restart, run this command after restarting: hp-setup (Note: If you are using a parallel connection, you will have to restart your PC. If you are using network/wireless, you can ignore and continue). Restart or re-plug in your printer (r=restart, p=re-plug in*, i=ignore/continue, q=quit) : p Please unplug and re-plugin your printer now. Press <enter> to continue or 'q' to quit: PRINTER SETUP ------------- Please make sure your printer is connected and powered on at this time. error: hp-setup failed. Please run hp-setup manually. ```
Try this link. It's the HP linux driver for your printer. <http://h20000.www2.hp.com/bizsupport/TechSupport/SoftwareIndex.jsp?lang=en&cc=us&prodNameId=29118&prodTypeId=18972&prodSeriesId=83436&swLang=8&swEnvOID=2020>
248248
I have a MySQL database-table with the following colums ``` ID status (can contain values 0, 1, 2) timepstamp text note owner ``` I'd like to obtain the following information about the entries of aspecific owner from the table: ``` number of entries number of entries where status=0 number of entries where status=1 number of entries where status=2 number of entries where LENGTH(note)>0 minimum timestamp maximum timestamp ``` I used to read the complete datasets and then evaluate them with PHP using ``` SELECT status, timestamp, LENGTH(note)>0 WHERE owner="name"; ``` I have the problem that some users have so many entries, that that I frequently get an out of memory error if I read the data to PHP. I thought that letting MySQL evaluating the data should be more performat. I could not manage to write a query that could fulfill this task. ``` SELECT MIN(timestamp) AS mintime, MAX(timestamp) AS maxtime, COUNT(*) AS number, ... WHERE owner="name" ``` Is it somehow possible to obtain the result in one go? For example with a nested WHERE or IFwithin a COUNT? ``` COUNT(WHERE status=0) AS inactive COUNT(IF(status=1)) AS active ... ``` How would you solve the problem?
Give this a try - ``` SELECT COUNT(*) AS total, SUM(IF(status=0, 1, 0)) AS stat0, SUM(IF(status=1, 1, 0)) AS stat1, SUM(IF(status=2, 1, 0)) AS stat2, SUM(IF(LENGTH(note)>0, 1, 0)) AS notes, MIN(timestamp) AS mintime, MAX(timestamp) AS maxtime FROM tbl_name WHERE owner="name" GROUP BY owner ```
248341
I want to have a same URL throughout my website. Whatever the user clicks on the web page, the redirected link should not display in the address bar in order to avoid the user to bookmark that page. Whatever it is, the user have to come from the home page and should follow the link to proceed further. Any help???
There are couple of options- 1. build your site with flash / silverlight or something like that. 2. put all your site in a IFrame, and navigate through it. 3. put a single http endpoint and put all your data in the http request data (with an post body or a session or cookie). for 2 and 3 users might sniff the traffic and jump to specific page. but can you please explain more on why you need it? I don't it's really what you want to do.
248425
I received an app, and e-shop of sorts, that I'm supposed to try to run and then modify a bit. I run it with Jetty on my local machine and went to <http://localhost:8080/etnshop/> (the 'welcome screen'), which seemed to work alright. However, after clicking on a button that's supposed to connect to a database, I received the following error message and stacktrace: ``` HTTP ERROR 500 Problem accessing /etnshop/product/list. Reason: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.SQLGrammarException: Could not open connection Caused by: org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.SQLGrammarException: Could not open connection at org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:544) at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373) at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:463) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:276) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207) at com.sun.proxy.$Proxy76.getProducts(Unknown Source) at cz.etn.etnshop.controller.ProductController.list(ProductController.java:22) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857) at javax.servlet.http.HttpServlet.service(HttpServlet.java:707) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842) at javax.servlet.http.HttpServlet.service(HttpServlet.java:820) at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511) at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:390) at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216) at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182) at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765) at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:440) at org.mortbay.jetty.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:230) at org.mortbay.jetty.handler.HandlerCollection.handle(HandlerCollection.java:114) at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152) at org.mortbay.jetty.Server.handle(Server.java:326) at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542) at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:926) at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:549) at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:212) at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404) at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:410) at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582) Caused by: org.hibernate.exception.SQLGrammarException: Could not open connection at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:80) at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49) at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126) at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112) at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:235) at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:171) at org.hibernate.internal.SessionImpl.connection(SessionImpl.java:450) at org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:450) ... 42 more Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown database 'etnshop' at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at com.mysql.jdbc.Util.handleNewInstance(Util.java:408) at com.mysql.jdbc.Util.getInstance(Util.java:383) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1062) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4226) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4158) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:926) at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1748) at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1288) at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2508) at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2541) at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2323) at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:832) at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at com.mysql.jdbc.Util.handleNewInstance(Util.java:408) at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:417) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:344) at java.sql.DriverManager.getConnection(Unknown Source) at java.sql.DriverManager.getConnection(Unknown Source) at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:153) at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:144) at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:155) at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:120) at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:139) at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:380) at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:228) ... 45 more Caused by: org.hibernate.exception.SQLGrammarException: Could not open connection at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:80) at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49) at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126) at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112) at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:235) at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:171) at org.hibernate.internal.SessionImpl.connection(SessionImpl.java:450) at org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:450) at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373) at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:463) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:276) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207) at com.sun.proxy.$Proxy76.getProducts(Unknown Source) at cz.etn.etnshop.controller.ProductController.list(ProductController.java:22) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857) at javax.servlet.http.HttpServlet.service(HttpServlet.java:707) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842) at javax.servlet.http.HttpServlet.service(HttpServlet.java:820) at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511) at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:390) at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216) at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182) at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765) at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:440) at org.mortbay.jetty.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:230) at org.mortbay.jetty.handler.HandlerCollection.handle(HandlerCollection.java:114) at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152) at org.mortbay.jetty.Server.handle(Server.java:326) at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542) at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:926) at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:549) at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:212) at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404) at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:410) at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582) Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown database 'etnshop' at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at com.mysql.jdbc.Util.handleNewInstance(Util.java:408) at com.mysql.jdbc.Util.getInstance(Util.java:383) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1062) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4226) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4158) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:926) at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1748) at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1288) at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2508) at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2541) at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2323) at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:832) at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at com.mysql.jdbc.Util.handleNewInstance(Util.java:408) at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:417) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:344) at java.sql.DriverManager.getConnection(Unknown Source) at java.sql.DriverManager.getConnection(Unknown Source) at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:153) at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:144) at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:155) at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:120) at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:139) at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:380) at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:228) ... 45 more Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown database 'etnshop' at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at com.mysql.jdbc.Util.handleNewInstance(Util.java:408) at com.mysql.jdbc.Util.getInstance(Util.java:383) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1062) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4226) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4158) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:926) at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1748) at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1288) at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2508) at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2541) at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2323) at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:832) at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at com.mysql.jdbc.Util.handleNewInstance(Util.java:408) at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:417) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:344) at java.sql.DriverManager.getConnection(Unknown Source) at java.sql.DriverManager.getConnection(Unknown Source) at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:153) at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:144) at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:155) at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:120) at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:139) at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:380) at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:228) at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:171) at org.hibernate.internal.SessionImpl.connection(SessionImpl.java:450) at org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:450) at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373) at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:463) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:276) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207) at com.sun.proxy.$Proxy76.getProducts(Unknown Source) at cz.etn.etnshop.controller.ProductController.list(ProductController.java:22) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857) at javax.servlet.http.HttpServlet.service(HttpServlet.java:707) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842) at javax.servlet.http.HttpServlet.service(HttpServlet.java:820) at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511) at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:390) at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216) at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182) at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765) at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:440) at org.mortbay.jetty.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:230) at org.mortbay.jetty.handler.HandlerCollection.handle(HandlerCollection.java:114) at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152) at org.mortbay.jetty.Server.handle(Server.java:326) at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542) at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:926) at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:549) at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:212) at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404) at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:410) at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582) Powered by Jetty:// ``` What's wrong? MySQL is installed, the name and pass are the same as in the application.properties file, and the MySQL service is running, which are about all the causes I found for this. What's causing this? There are some similar question here already, but I have no idea where to even begin to see the similarity between those problems and this one.
I have solved my problem with this code. ``` private Bitmap getBitmap(Drawable vectorDrawable) { Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); vectorDrawable.draw(canvas); return bitmap; } ``` Thanks everyone!
248442
**This question is based on** [*this other question*](https://stackoverflow.com/questions/1145228/) **of mine, and uses all of the same basic info. That link shows my table layouts and the basic gist of the simple join.** I would like to write another query that would select EVERY record from ***Table1***, and simply sort them by whether or not Value is less than the linked Threshold. Again, I appreciate anyone who is willing to take a stab at this. Databases have never been a strong point of mine.
``` SELECT t1.LogEntryID, t1.Value, t1.ThresholdID, case when t1.Value < t2.threshold then 1 else 0 end as Rank FROM Table1 t1 INNER JOIN Table2 t2 ON t1.ThresholdID = t2.ThresholdID ORDER By Rank ``` You can add `DESC` after `ORDER By Rank` if you want the reverse order.
248487
i'm working with laravel 5.1 (ecommerce), i passed some variables to my view: My variable "$price\_coupon" con be "0" OR ">0" for example 10,20 etc... I would like HIDE this: ``` <tr class="cart-subtotal" id="coupon"> <th>Coupon:</th> <td> <span class="amount">€{{ number_format($price_coupon, 2) }}</span> </td> </tr> ``` IF $price\_coupon = 0 AND show IF $price\_coupon > 0. I think that this is feature for javascript right? how can do it? Thank you for your help! This is all the table of my view: order-detail.php ``` <table> <tbody> <tr class="cart-subtotal"> <th>Subtotale:</th> <td><span class="amount">€{{ number_format($total, 2) }}</span></td> </tr> <tr class="cart-subtotal" id="coupon"> <th>Coupon:</th> <td><span class="amount">€{{ number_format($price_coupon, 2) }}</span></td> </tr> <tr class="shipping"> <th>shipping:</th> <td>€<input type="text" id="price_ship" name="price_ship" class="price_ship" disabled /></td> </tr> <tr class="order-total"> <th>Totale Ordine:</th> <td><strong><span class="amount"> €<input type="text" id="total_ship" name="total_ship" class="total_ship" disabled /> </span></strong> </td> </tr> </tbody> </table> ``` i corrected this question: I'm using also blade template.
All you're trying to do here is to compare the date to just *one* of your "3 or more" dates: you just have to work out which one that is, and then compare two dates. Since `Date` implements `Comparable<Date>`, you can use `Collections.min` and `Collections.max` to find the earliest and latest of them: ``` Date earliest = Collections.min(Arrays.asList(date1, date2, date3)); Date latest = Collections.max(Arrays.asList(date1, date2, date3)); ``` Then: ``` boolean beforeEarliest = date.before(earliest); boolean afterLatest = date.after(latest); ``` etc.
248591
I'm new to Python, and pretty much programming/scripting. I'm just looking for someone to critique my methods and tell me if there are more efficient ways to do things. ``` #!/usr/bin/env python3 # # # A quick script to create a civil war game ############################ # DECLARE GLOBAL VARIABLES # ############################ ### Armies = [Inf,Cav,Art] ### global compdefmult global compattmult global compchoice global userdefmult global userattmult global userchoice comparmy = [100,50,10] userarmy = [100,50,10] ################## # IMPORT MODULES # ################## import os from random import randint ########################## # DEFINE GLOBAL FUNCTIONS # ########################### def clearscreen(): os.system('clear') def newstart(): clearscreen() print (''' CCCC IIIII V V IIIII L W W W AA RRRR C I V V I L W W W A A R R C I VV I L W W W AAAA RRRR CCCC IIIII VV IIIII LLLL WW WW A A R R This is Civil War! You will have Infantry, Calvary and Artillery to win the battles you need to turn the tide of the war. Now, General, take your place in history! ''') def printstatus(): print ('Your total Infantry are:' , userarmy[0]) print ('Your total Calvary are:' , userarmy[1]) print ('Your total Artillery are:' , userarmy[2]) print ('') print ('Computers total Infantry are:' , comparmy[0]) print ('Computers total Calvary are:' , comparmy[1]) print ('Computers total Artillery are:' , comparmy[2]) print ('') mainmenu() #################### # MAIN BATTLE CODE # #################### def compdigger(): global compchoice global compdefmult global compattmult compchoice = randint(1,3) if compchoice == 1: if comparmy[0] == 0: compdigger() else: compchoice = "Infantry" compdefmult = 3 compattmult = 3 elif compchoice == 2: if comparmy[1] == 0: compdigger() else: compchoice = "Calvary" compdefmult = 4 compattmult = 2 else: if comparmy[2] == 0: compdigger() else: compchoice = "Artillery" compdefmult = 2 compattmult = 4 return compchoice return compdefmult return compattmult def takeaction(): print ('Infantry have an offensive multiplier of 3 and a defensive multiplier of 3') print ('Calvary have an offensive multiplier of 2 and a defensive multiplier of 4') print ('Artillery have an offensive multiplier of 4 and a defensive multiplier of 2') print ('') print (''' Do you want to use: 1) Infantry 2) Calvary 3) Artillery ''') print ("") action = input ("Choose one -> : "); if action == "1": userchoice = "Infantry" print ("") if userarmy[0] == 0: print ("You don't have any more infantry! Please choose another troop set!") takeaction() else: print ("MAAAAARRRRCH!!!!!") defmult = 3 attmult = 3 print ("") elif action == "2": userchoice = "Calvary" print ("") if userarmy[1] == 0: print ("You don't have any more calvary! Please choose another troop set!") takeaction() else: print ("CHAAAAARRRGE!!!!!!") defmult = 4 attmult = 2 print ("") elif action == "3": userchoice = "Artillery" print ("") if userarmy[2] == 0: print ("You don't have any more artillery! Please choose another troop set!") takeaction() else: print ("FIIIIIIIRE!!!!!!") defmult = 2 attmult = 4 print ("") else: print ("") print ("You did not choose 1,2 or 3. Please choose a valid answer") print ("") takeaction() print ("") userdefroll = randint(1,12) userattroll = randint(1,12) print ("Your defensive roll was ", userdefroll) print ("Your attack roll was " , userattroll) compdefroll = randint(1,12) compattroll = randint(1,12) print ("") print ("Computers defensive roll was " , compdefroll) print ("Computers attack roll was " , compattroll) print ("") userattack = int(attmult) * int(userattroll) userdefense = int(defmult) * int(userdefroll) print ("") print ("Defense total is multiplier %s times roll %s which has a total of %s " % (defmult, userdefroll , userdefense)) print ("Attack total is miltiplier %s times roll %s which has a total of %s " % (attmult, userattroll, userattack)) print ("") compdigger() compdefense = int(compdefmult) * int(compdefroll) compattack = int(compattmult) * int(compattroll) print ("") print ("The computer chose ", compchoice) print ("") print ("Computers total Defense multiplier is %s times it's roll %s which has a total of %s " % (compdefmult, compdefroll, compdefense)) print ("Computers total Attack multiplier is %s times it's roll %s which has a total of %s " % (compattmult, compattroll, compattack)) print ("") print ("") if compdefense >= userattack: print ("The computer defended your attack without troop loss") else: userdiff = int(userattack) - int(compdefense) print ("Computer lost %s %s " % (userdiff , compchoice)) if compchoice == "Infantry": comparmy[0] -= int(userdiff) if comparmy[0] < 0: comparmy[0] = 0 elif compchoice == "Calvary": comparmy[1] -= int(userdiff) if comparmy[1] < 0: comparmy[1] = 0 else: comparmy[2] -= int(userdiff) if comparmy[2] < 0: comparmy[2] = 0 if userdefense >= compattack: print ("You defended the computers attack without troop loss") else: compdiff = int(compattack) - int(userdefense) print ("You lost %s %s " % (compdiff , userchoice)) if userchoice == "Infantry": userarmy[0] -= int(compdiff) if userarmy[0] < 0: userarmy[0] = 0 elif userchoice == "Calvary": userarmy[1] -= int(compdiff) if userarmy[1] < 0: userarmy[1] = 0 else: userarmy[2] -= int(compdiff) if userarmy[2] < 0: userarmy[2] = 0 if userarmy[0] == 0 and userarmy[1] == 0 and userarmy[2] == 0: print ("Your army has been decemated! RETREAT!") exit(0) if comparmy[0] == 0 and comparmy[1] == 0 and comparmy[2] ==0: print ("The computers army has been decemated! VICTORY!") exit(0) print ("") mainmenu() def mainmenu(): print (''' MAIN MENU --------- 1) Print out army status 2) ATTACK! 3) Save game (not implemented yet) 4) Load game (not implemented yet) 5) Quit ''') menuaction = input ("Please choose an option -> : "); if menuaction == "1": printstatus() elif menuaction == "2": takeaction() elif menuaction == "3": print ("Not implemented yet!") mainmenu() elif menuaction == "4": print ("Not implemented yet!") mainmenu() elif menuaction == "5": print ("Good bye!") exit (0) else: print ("You did not choose 1,2,3 or 4. Please choose a valid option!") mainmenu() newstart() mainmenu() ```
As mentioned by [@abarnert](https://codereview.stackexchange.com/users/27320/abarnert), you're using infinite recursion to *"repeat forever"*. By default, after you've recursed more than 1000 times, your program will throw an error. The better way to do this would be to use a `while condition` loop. In this case, your `takeaction` function would become this: ``` def take_action() -> None: """ Add a description of take_action here. """ while True: ... ``` --- You can also use a dictionary of functions containing actions rather than chaining `if condition` statements. Usually it's looks better. Here's a basic example of what that could look like: ``` def my_action() -> None: """ Description """ ... actions = { "action": my_action } user_input = raw_input() if user_input in actions: actions[user_input]() ``` --- I'd also recommend using [docstrings](https://www.python.org/dev/peps/pep-0257/) to document how your code works. They're very important, because they describe how your code works. Without them, code can be understandable, but can be very hard to understand. Here's an example: ``` def my_function(args) -> None: """ Add a description of the function here. """ ... ``` --- Your `clearscreen()` function isn't very portable, and will only work on linux-based systems. I'd recommend using something like this instead: ``` def clear_screen(): os.system("cls" if os.name == "nt" else "clear") ``` --- Finally, I'd recommend reading [PEP8](https://www.python.org/dev/peps/pep-0008/), Python's official style guide. It essentially tells you how your code should be formatted, and how it should look. If you want to check your code for PEP8 issues, you can use [this online checker.](http://pep8online.com/)
248612
Visiting the lost mansion of a conjurer, where portals were opening for a few seconds, a sorcerer tried to keep open one that led to the Elemental Plane of Fire blocking it with an [Immovable Rod](https://www.dndbeyond.com/magic-items/4662-immovable-rod). I'm interested in what would happen in order to preserve an internal coherence regarding physical/magical laws that govern the world. Here are some thoughts that may explain what I mean: * The object may just remain on one side, and occupy the space that it would have occupied without the portal (e.g. if the portal was lying on a wall, the the rod would have been stuck in the wall). However, this raises another question: on which side of the portal would the object end up? * The object may just split together with spacetime as the portal closes, so each part would remain on the side of the portal where it was, effectively cutting the object. In my opinion, however, this mechanic would provide an easy way to cut objects that where supposed not to easily break. * I may imagine a pressure-like force that acts on objects near/in the portal, inversely proportional to the surface of the portal, so that objects are eventually pushed/sucked onto one side. This is an incremental version of the first idea, and it's my favourite at the moment. So the question is the following: what would happen if I put an Immovable Rod (or in general an object) into a closing portal?
Taking a look at the description from 5e spells that open portals to other planes such as the 9th level conjuration spell *Gate*: > > The portal has a front and a back on each plane where it appears. > Travel through the portal is possible only by moving through its > front. Anything that does so is instantly transported to the other > plane, appearing in the unoccupied space nearest to the portal. > > > It is apparent that objects can't stay inside the portal aperture. An **Immovable Rod** would end up the same way. You would have to position the **Immovable Rod** initially by sticking it into the portal before pressing the button, but the portal would not give you the chance to do so and would immediately transport the **Immovable Rod** (and quite possibly you) to the plane on the other side.
249124
I get this response from a service I am calling. I wish to write an assertion in Soap-UI to validate the value of the `<Result>` tag. ``` <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> <s:Body> <ServiceResponse> <!--Issue happens here when xmlns attribute is present--> <ServiceResult xmlns:a="http://schemas.datacontract.org/2004/07/services.api.DataContracts" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <AdditionalInfo i:nil="true"/> <ErrorMessage/> <ErrorMessageId i:nil="true"/> <ErrorMessages xmlns:b="http://schemas.microsoft.com/2003/10/Serialization/Arrays"/> <InternalId>0</InternalId> <RecordsAffected>0</RecordsAffected> <Result>false</Result> <WarningMessages xmlns:b="http://schemas.microsoft.com/2003/10/Serialization/Arrays"/> <a:ReturnBase> </a:ReturnBase> </ServiceResult> </ServiceResponse> </s:Body> </s:Envelope> ``` I used the [Xpath Testing tool online](http://www.xpathtester.com/xpath) to find a correct path. When I remove the xmlns attribute on the `<ServiceResponse>` tag, the XPATH works as expected. However when I have the `xmlns="http://schema.Services"` on the `<ServiceResponse>` tag, XPath fails to return an item. I also tried to find this in Notepad++ with the XML Tools Plugin and it throws an exception when I have the `<ServiceResponse xmlns="http://schema.Services">` in there. How can I go about writing this assertion in soap-UI?
`myList[0]` is not an identifier. It is an [array access expression](http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.10.3). The identifier in this case is `myList`.
249356
I Am correctly using my own way to achieve this, but I don't know if it is efficient or not , so this is the function : ``` public SqlDataReader GetArticlesByPage(int pageNum, int pageSize) { if (pageNum == 0) pageNum = 1; SqlDataReader dr = SqlHelper.ExecuteReader(string.Format("SELECT TOP {0} Des, Id, Title, Icon FROM Threads ORDER BY Id DESC", pageSize * pageNum)); int div = pageNum - 1; div = pageSize * div; for (int i = 0; i < div; i++) dr.Read(); return dr; } ``` It works fine but as you see the code, when I need to take the articles of page 10 when the page size e.g 10 per page I select the top 10\*10 result then skip the unwanted results by using FOR statement . Any suggestions , thanks in advance .
You can do all the paging at sql server. For example, see <http://blogs.x2line.com/al/archive/2005/11/18/1323.aspx> If you don't want to do it this way and insist on using `TOP`, then skipping the rows at start is pretty all you can do and it's ok. (from above link) ``` DECLARE @PageNum AS INT; DECLARE @PageSize AS INT; SET @PageNum = 2; SET @PageSize = 10; WITH OrdersRN AS ( SELECT ROW_NUMBER() OVER(ORDER BY OrderDate, OrderID) AS RowNum ,OrderID ,OrderDate ,CustomerID ,EmployeeID FROM dbo.Orders ) SELECT * FROM OrdersRN WHERE RowNum BETWEEN (@PageNum - 1) * @PageSize + 1 AND @PageNum * @PageSize ORDER BY OrderDate ,OrderID; ```
249357
I am trying to write tests for my nodejs server application and by now everything worked fine. I can compile my code from typescript to javascript without error and everything but when I try to run mocha tests the typescript pre-compilation fails due to not finding my self defined typings in `typings.d.ts`. Here are my declarations inside the `typings.d.ts` ``` import {User} from "./users/user.model"; import {MainDatabase} from "./core/models/database.model"; import {Translation} from "./core/services/i18n"; import {LanguageDefinition} from "./core/models/language.model"; import {Reminder} from "./core/services/schedule/schedule.model"; import {UserProfileModel} from "./core/database/models/user_profile"; import {UserClientModel} from "./core/database/models/user_client"; import {PhoneNumberModel} from "./core/database/models/phone_number"; import {CountryModel} from "./core/database/models/country"; import {CustomerTypeModel} from "./core/database/models/customer/customer_type"; import {CustomerModel} from "./core/database/models/customer/customer"; import {ReminderModel} from "./core/database/models/reminder_options"; import {Customer} from "./customers/customer.model"; import {IUserAccount} from "./core/database/models/user_account"; import {UserAccountModel} from "./core/database/models/user_account"; import {MailModel} from "./core/services/mail/mail.model"; import {Request} from "express"; import {Models} from "sequelize"; declare global { module NodeJS { interface Global { translation: Translation; db: MainDatabase; /*Classes to be reach through the global object*/ User: User; Reminder: Reminder; Customer: Customer; Mailer: MailModel; } } } declare module "Express"{ export interface Request { user?: IUserAccount; authenticated: boolean; locals: { files?: File[]; }; locale?: LanguageDefinition; info?:{ userAgent?: string; ip?: string; } } } // extending the original sequelize interfaces declare module "sequelize" { /** * Database models * only list SEQUELIZE Models here not classes * */ interface Models { UserProfile: UserProfileModel; UserAccount: UserAccountModel; UserClient: UserClientModel; Reminder: ReminderModel; PhoneNumber: PhoneNumberModel, CustomerType: CustomerTypeModel, Customer: CustomerModel, Country: CountryModel } } ``` And in my `app.ts` I'm using those types by importing the original interface / type from the original package ``` //omitted for brevity /** * Setup all globals that do not belong to the database * */ private setupServerGlobals() { try { global.Mailer = new MailModel(); } catch (e) { console.error('setupServerGlobals', e); } } private setupTranslation(): Observable<any> { // create translation const translation = new Translation({ language: { language: 'de', fullLanguage: 'de' }, }); return translation.init().pipe( tap(() => { global.translation = translation; }), ); } ``` Now when I run `tsc --watch & nodemon ./dist/src/app.js` all files are compiled successfully and the server starts without any problems. My global defined typings inside `typings.d.ts` are seen by the compiler due my tsconfig.json configuration. But when I run `tsc & mocha` it throws this error: ``` /Users/user/Documents/Project/subfolder/project-name/node_modules/ts-node/src/index.ts:261 return new TSError(diagnosticText, diagnosticCodes) ^ TSError: ⨯ Unable to compile TypeScript: src/app.ts(60,14): error TS2339: Property 'Mailer' does not exist on type 'Global'. src/app.ts(78,11): error TS2339: Property 'info' does not exist on type 'Request'. src/app.ts(156,16): error TS2339: Property 'translation' does not exist on type 'Global'. ``` My setup looks like this: + I have all test files next to each to-be-tested file + I have an test folder where my `mocha.opts` file is in Here the contents of my `mocha.opts` file: ``` src/**/*.spec.ts --require ts-node/register --recursive ``` And finally here is my `tsconfig.json` file: ``` { "compilerOptions": { "target": "es6", "module": "commonjs", "moduleResolution": "node", "allowSyntheticDefaultImports": true, "allowJs": true, "importHelpers": true, "jsx": "react", "alwaysStrict": true, "sourceMap": true, "forceConsistentCasingInFileNames": true, "noFallthroughCasesInSwitch": true, "noImplicitReturns": true, "noUnusedLocals": false, "noUnusedParameters": false, "noImplicitAny": false, "noImplicitThis": false, "strictNullChecks": false, "outDir": "dist" }, "include": ["**/*.ts"] } ``` Expectation =========== To run my tests like it runs the server, without compiling problems. I appreciate every help. Edit ==== I could solve my problem by just importing the typings from `typings.d.ts` like so in my `app.ts` file ``` import * as typings from './typings'; ``` But for me that just don't seem to be a good solution for this problem because in every file I'll use the `global` variable I'll need to reimport the typings like above. Still feel free to solve this issue if you know how to.
In my case, I inserted the following into `tsconfig.json` ``` { "ts-node": { "transpileOnly": true }, "compilerOptions": { ... } } ``` and it works.
249472
I am trying to do a basic search feature but I am having a small issue. When I go to the template that has the search form, it is displaying all the items before I even try to search. Is there a way to show a blank template until the user has put in a search term and hit the search button? Example: [Search field][Button] 1 2 3 etc views.py ``` def view_player_home(request): if request.method == 'GET': form = searchPlayerForm(request.GET) if form.is_valid(): string = form.cleaned_data.get('text') players = Player.objects.filter(Q(first_name__icontains = string)|Q(last_name__icontains = string)) return render_to_response('player/player.html', {'form': form, 'players':players}, context_instance=RequestContext(request)) else: form = searchPlayerForm() return render_to_response('player/player.html', {'form': form}, context_instance=RequestContext(request)) ``` forms.py ``` class searchPlayerForm(forms.Form): text = forms.CharField(label = "Search") def __init__(self, *args, **kwargs): super(searchPlayerForm, self).__init__(*args, **kwargs) self.fields['text'].required = False ``` template ``` {% extends "base.html" %} {% block content %} <h5>Find Player</h5> <form method="GET" action=""> {% csrf_token %} {{ form.as_table }} <input type="submit" value="Submit"/> </form> {% if players %} {% for p in players %} {{ p.first_name }} {{ p.last_name }} {% endfor %} {% else %} No Players {% endif %} {% endblock %} ```
This would be an example of covariant return types: ``` class Food {} class Fruit : Food {} class FoodEater { public virtual Food GetFavouriteFood() { ... } } class FruitEater : FoodEater { public override Fruit GetFavouriteFood() { ... } } ``` In languages that support return type covariance, this would be legal. That is *a method that returns a Food can be overridden by a method that returns a Fruit, because Fruit is a kind of Food*. It is called "covariance" because the "variance" is in the *same direction*: ``` A Fruit may be used as a Food, therefore: A Fruit-returning-method may be used as a Food-returning-method ``` See how the variance is *in the same direction*? Contrast that with parameter type contravariance: ``` class Food {} class Fruit : Food {} class Apple : Fruit {} class Orange : Fruit {} class Cake : Food {} class FruitComparer { public virtual bool Compare(Fruit f1, Fruit f2) { ... } } class FoodComparer : FruitComparer { public override bool Compare(Food f1, Food f2) { ... } } ``` A FruitComparer can compare Apples to Oranges. A FoodComparer can also compare Apples to Oranges, but can compare even more -- it can compare Apples to Cakes, or Cakes to Oranges, or whatever. In languages that support parameter type contravariance, this is legal. See how the variance directions are now *reversed*: ``` A Fruit may be used as a Food, therefore A Food-taking-method may be used as a Fruit-taking-method ``` Now the relationship has gone *backwards*, so it is *contravariant*. C# supports neither kind of method variance *for virtual overloading*. Virtual method overrides must match exactly. However, C# does support both kinds of method variance for *method group to delegate conversions*, and for *generic delegate type conversions*.
249711
I got a table View and collection view on the each cell. When I tapped the cell, following code will be invoked in cell's `didSelectRowAt:IndexPath` method. ``` func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { navigationController?.pushViewController(anotherViewController(), animated: true) } ``` The `anotherViewController` is an empty view controller on storyboard for now. It only print "I'm coming" in `viewDidLoad()`. **Here is the problem:** When I touched the cell, the push animation seems got stuck, pleas check the following GIF. I'm really confused in what's happend. Feel free to give any Advice. The following Image shows the view hierarchy. Cells on the table view. Collection view and other components on the cell's content view. At the end, image views on the collection view's content view. [![View Hierarchy](https://i.stack.imgur.com/E1nVl.png)](https://i.stack.imgur.com/E1nVl.png) [![](https://i.stack.imgur.com/CXu2e.gif)](https://i.stack.imgur.com/CXu2e.gif)
I suspect the problem rests in the `anotherViewController()` reference. I was even able to reproduce the problem when I pushed to a `UIViewController` instance: ``` navigationController?.pushViewController(UIViewController(), animated: true) ``` But when I instantiate a scene from a storyboard, that worked fine. Obviously, you need a scene with the appropriate storyboard identifier: ``` let controller = storyboard!.instantiateViewController(withIdentifier: "Details") navigationController?.pushViewController(controller, animated: true) ``` Or, if I defined segue between the two view controllers and performed the segue, that also worked: ``` performSegue(withIdentifier: "DetailsSegue", sender: self) ```
249748
I'm new to PHP, and I need some help. I can't seem to get the right score for a student. The scenario: * Input answers (answer key) for an exam with corresponding points * Input student-answer for that exam * Get total score of the student. My PHP code: ``` for ($count = 1; $count <= $num_ans; $count++) { $answer = $_POST['answer'][($count + 1) - 1]; $sqlB = "SELECT * FROM paper WHERE id=$count and test_name = '$test_name' and subject='$subject'"; $qryB = mysql_query($sqlB); $rowB = mysql_fetch_array($qryB); $anskey = $rowB['answer']; } if ($answer = $anskey) { $sqlA = "SELECT points FROM paper WHERE test_name = '$test_name' and subject='$subject' and answer='$answer'"; $qryA = mysql_query($sqlA); while ($rowA = mysql_fetch_array($qryA)) { $correctAns += $rowA['points']; } } ```
I don't like the design, I believe you should not inherit (this, for example, makes your type not be an aggregate), and that there are better approaches to serialization/deserialization than checking the size of the entity. That being said, after you force the initialization you can just assign. The implicitly declared copy constructor will be defined and the members will be copied: ``` data d = { 1, 2 }; // Can use this as it is an aggregate data1 d1 = data1(); d1 = d; ``` Again, I would avoid this altogether... If instead of inheritance you used composition, then you could use aggregate initialization and avoid the double initialization of the base in `data1`: ``` struct data1 { data base; int extra; }; data d = { 1, 2 }; data1 d1 = { d, 5 }; // or { d, 0 } ``` > > I've thought of putting a constructor in data to copy from a data1, but then that breaks the free value-initialization I get (I'd have to implement my own copy & default constructors at that point). > > > Not completely true. You will need to provide a default constructor, as the presence of the constructor taking `data` will inhibit the implicit declaration of a default constructor. But the copy constructor will still be implicitly generated.
249968
I follow below steps to deploy my custom jar 1)- I created on docker image through the below docker file ``` FROM openjdk:8-jre-alpine3.9 LABEL MAINTAINER DINESH LABEL version="1.0" LABEL description="First image with Dockerfile & DINESH." RUN mkdir /app COPY LoginService-0.0.1-SNAPSHOT.jar /app WORKDIR /app CMD ["java", "-jar", "LoginService-0.0.1-SNAPSHOT.jar"] ``` 2)- Deploy on kubernetes with the below deployment file ``` apiVersion: apps/v1 kind: Deployment metadata: labels: app.kubernetes.io/name: load-balancer-example name: hello-world spec: replicas: 2 selector: matchLabels: app.kubernetes.io/name: load-balancer-example template: metadata: labels: app.kubernetes.io/name: load-balancer-example spec: containers: - image: localhost:5000/my-image:latest name: hello-world ports: - containerPort: 8000 ``` 3)- Exposed as service with the below command ``` minikube tunnel kubectl expose deployment hello-world --type=LoadBalancer --name=my-service --port=8000 --target-port=8000 ``` 4)- Output of the kubectl describe svc my-service ``` <strong> Name: my-service<br> Namespace: default<br> Labels: app.kubernetes.io/name=load-balancer-example<br> Annotations: <none><br> Selector: app.kubernetes.io/name=load-balancer-example<br> Type: LoadBalancer<br> IP: 10.96.142.93<br> LoadBalancer Ingress: 10.96.142.93<br> Port: <unset> 8000/TCP<br> TargetPort: 8000/TCP<br> NodePort: <unset> 31284/TCP<br> Endpoints: 172.18.0.7:8000,172.18.0.8:8000<br> Session Affinity: None<br> External Traffic Policy: Cluster<br> Events: <none><br> </strong> ``` POD is in running state I m trying to access the pod using "10.96.142.93" as given in the <http://10.96.142.93:8090> my loginservice is started on 8090 PORT, BUT i am unable to access pod plz help
Try to access on nodeport `localhost:31284` and please use service type as `NodePort` instead of `LoadBalancer` because loadbalancer service type mostly used on cloud level. and Use Target-Port as same port you configured on pod definition yaml file. so your url should be `http://10.96.142.93:8000` or another way you can be by using port-forward `kubectl port-forward pod_name 80:8000` this will map pod port to localhost port Then access it on `http://localhost:80`
250649
I'm trying to make a set of views (*that include several textviews and buttons - all in **different parent layouts**, but in the same activity*) invisible if a particular condition is evaluated to false. The conventional way to do that would be: ``` findViewById(R.id.myview).setVisibility(View.INVISIBLE); ``` My question is, will I have to do this for all the views one by one that I want to be invisible, And then toggle them back when I want them visible? Or, is there a way to avoid the code-repetition?
If the `View`s are in different parents , you can't do it directly, but you can implement a method to change the visibility of a bunch of `View`s if you want to keep your code clean: ``` List<View> relatedViews = new ArrayList<>(); // ... relatedViews.add(view1); relatedViews.add(view2); relatedViews.add(view3); // ... changeVisibility(relatedViews, View.INVISIBLE); // ... private void changeVisibility(List<View> views, int visibility) { for (View view : views) { view.setVisibility(visibility); } } ``` As a side note, you may want to change the visibility to `View.GONE` instead of `View.INVISIBLE` so it doesn't take any space in the layout.
251241
I have a table form with some rows, that are controlled by user. Meaning they can add as more as they want. Let's pretend user requested 5 rows and i need to check if they all have values. ``` function validateForm() { var lastRowInserted = $("#packageAdd tr:last input").attr("name"); // gives me "packageItemName5" var lastCharRow = lastRowInserted.substr(lastRowInserted.length - 1); // gives me 5 var i; for (i = 1; i <= lastCharRow; i++) { var nameValidate[] = document.forms["packageForm"]["packageItemName"].value; if(nameValidate[i].length<1){ alert('Please fill: '+nameValidate[i]); return false; } } } ``` How can i receive packageItemName1 to 5 values in a loop so then I can use to validate them. Want the loop to process this code ``` var nameValidate[] = document.forms["packageForm"]["packageItemName1"].value; var nameValidate[] = document.forms["packageForm"]["packageItemName2"].value; var nameValidate[] = document.forms["packageForm"]["packageItemName3"].value; var nameValidate[] = document.forms["packageForm"]["packageItemName4"].value; var nameValidate[] = document.forms["packageForm"]["packageItemName5"].value; ```
Like this ```js const validatePackageItems = () => { const nameValidate = $("form[name=packageForm] input[name^=packageItemName]"); // all fields with name starting with packageItemName const vals = nameValidate.map(function() { return this.value }).get(); // all values const filled = vals.filter(val => val.trim() !== ""); // all values not empty console.log("Filled", filled, "= ", filled.length, "filled of", vals.length) return filled.length === vals.length }; $("[name=packageForm]").on("submit",(e) => { if (!validatePackageItems()) { alert("not valid"); e.preventDefault(); } }) ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form name="packageForm"> <input type="text" name="packageItemName1" value="one" /><br/> <input type="text" name="packageItemName2" value="two" /><br/> <input type="text" name="packageItemName3" value="" /><br/> <input type="text" name="packageItemName4" value="four" /><br/> <input type="submit"> </form> ```
251503
I'm developing an ASP.NET application where I have to send an PDF based on a Table created dinamically on the page as attachment on a email. So I have a function that creates the PDF as iTextSharp Document and returns it. If i try just to save this document, it works fine but I'm having a bad time trying to make it as Stream. I tried several things already, but I always get stuck at some point. I tried to serialize it, but appears that Document is not serializable. Then I tried to work with PdfCopy, but I couldn't find out how to use this to my problem in specific. The code right now is like this: ``` //Table,string,string,Stream //This document returns fine Document document = Utils.GeneratePDF(table, lastBook, lastDate, Response.OutputStream); using (MemoryStream ms = new MemoryStream()) { PdfCopy copy = new PdfCopy(document, ms); //Need something here to copy from one to another! OR to make document as Stream ms.Position = 0; //Email, Subject, Stream Utils.SendMail(email, lastBook + " - " + lastDate, ms); } ```
Try to avoid passing the native iTextSharp objects around. Either pass streams, files or bytes. I don't have an IDE in front of me right now but you should be able to do something like this: ``` byte[] Bytes; using(MemoryStream ms = new MemoryStream()){ Utils.GeneratePDF(table, lastBook, lastDate, ms); Bytes = ms.ToArray(); } ``` Then you can either change your `Utils.SendMail()` to accept a byte array or just [wrap it in another stream](https://stackoverflow.com/q/4736155/231316). **EDIT** You *might* also be able to just do something like this in your code: ``` using(MemoryStream ms = new MemoryStream()){ Utils.GeneratePDF(table, lastBook, lastDate, ms); ms.Position = 0; Utils.SendMail(email, lastBook + " - " + lastDate, ms); } ```
251701
I am trying to do the following. I have several spreadsheets that are named something like "ITT\_198763" where the ITT part stays the same but the number changes. I also have one tab called program where the 6 digit number is imported on row 40 (hence the RngToSearch below). I need the program to 1) find the "ITT" sheet for a certain 6 digit number, 2) identify the corresponding row in the "Program" tab, and copy information from the "ITT" tab to row 41 of the identified column. I will be copying more information from the ITT sheet to the specified column, but for now I am just trying to get it to work once. From the MsgBox, I know it identifies the correct prjNumber (the 6 digit number), but I get the runtime 1004 error on the line Set RngDest. Any help will be appreciated! ``` Sub Summary_Table() Dim wks As Worksheet Dim RngToSearch As Range, RngDest As Range Dim foundColumn As Variant Dim prjNumber For Each wks In ActiveWorkbook.Worksheets If ((Left(wks.Name, 3) = "ITT")) Then prjNumber = Right(wks.Name, 6) MsgBox (prjNumber) Set RngToSearch = Sheets("Program").Range("C40:q40") foundColumn = Sheets("Program").Application.Match(prjNumber, RngToSearch, False) With Sheets("Program") Set RngDest = .Range(1, foundColumn) 'Project Name End With If Not IsError(foundColumn) Then wks.Range("E2").Copy RngDest End If End If Next wks End Sub ``` I tried the .cell instead with the following code (all else is the same) and now get runtime error 13 on the Set RngDest line: ``` Set RngToSearch = Sheets("Program").Range("C40:q48") foundColumn = Sheets("Program").Application.Match(prjNumber, RngToSearch.Rows(1), False) With Sheets("Program") Set RngDest = RngToSearch.Cells(1, foundColumn) 'Project Name End With ```
Yuo are getting that error because `foundColumn` has an invalid value. Step through the code and see what is the value of `foundColumn` Here is an example which works. ``` Sub Sample() Dim RngDest As Range, RngToSearch As Range foundColumn = 1 Set RngToSearch = Sheets("Program").Range("C40:q40") Set RngDest = RngToSearch.Cells(1, foundColumn) Debug.Print RngDest.Address End Sub ``` Add `MsgBox foundColumn` before the line `Set RngDest = RngToSearch.Cells(1, foundColumn)` and see what value do you get. I guess the line `foundColumn = Sheets("Program").Application.Match(prjNumber, RngToSearch, False)` is not giving you the desired value. Here is the way to reproduce the error. ![enter image description here](https://i.stack.imgur.com/AeMHy.png) **EDIT (Solution)** You need to handle the situation when no match is found. Try something like this ``` Sub Sample() Dim RngDest As Range, RngToSearch As Range Set RngToSearch = Sheets("Program").Range("C40:q40") foundcolumn = Sheets("Program").Application.Match(1, RngToSearch, False) If CVErr(foundcolumn) = CVErr(2042) Then MsgBox "Match Not Found" Else Set RngDest = RngToSearch.Cells(1, foundcolumn) ' '~~> Rest of the code ' End If End Sub ```
251777
I'm trying to setup a rewrite/redirect rule on a **web.config** file. I have little to no experience with IIS servers so I've been looking through solutions online, here at StackOverflow and other forums, and already tried a number of them without success. I must point out that I only have FTP access to the server so I can't say for sure how it has been setup (in case server setup has any influence on this). Here are the requirements: 1. The page being redirected **can have or not ".php"**, i.e., it can either be "my-page" or "my-page.php". 2. The destination of the redirect is in a **different domain/sub-domain** 3. The page URL itself has to be quite specific (besides ".php"). For example, I have two pages, "my-page.php" and "my-page-extra.php", but I only want to redirect "my-page.php". 4. The query string present in the original can have multiple parameters in different order (or none at all) 5. I want the query string to be passed as is to the destination. So, a typical redirect would go like this: The visitor tries to reach: ``` https://my-domain.com/my-page.php?id=myid&param=myparam ``` or ``` https://my-domain.com/mypage?id=myid&param=myparam ``` And I want it redirected to: ``` https://my-sub-domain.my-new-domain.com/?id=myid&param=myparam ``` I have two solutions that work partially: Solution 1: the URL works but the query string is not being passed ``` <rule name="My Redirect" stopProcessing="true"> <match url="^my-page-slug(|\.php)(|\?.*)$" /> <conditions logicalGrouping="MatchAll"> <add input="{QUERY_STRING}" pattern="(.*)" /> </conditions> <action type="Redirect" url="https://my-sub-domain.my-new-domain.com/{C:1}" redirectType="Permanent" /> </rule> ``` Solution 2: the query string is passed but the URL is not as strict so it doesn't work ``` <rule name="My redirect" stopProcessing="true"> <match url="^(.*)my-page-slug(.*)$" ignoreCase="true" /> <action type="Redirect" url="https://my-sub-domain.my-new-domain.com/{R:1}" redirectType="Permanent" /> </rule> ``` Any help would be highly appreciated. Thanks.
How about this: ``` #include <stdio.h> int main() { double number = 612.216; char number_as_string[20]; snprintf(number_as_string,"%lf", number); for(int i = 0; number_as_string[i] != '\0'; i++) if(number_as_string[i] != '.') printf("%c", number_as_string[i]); return 0; } ``` The downside is the statically allocated array. You can use snprintf to convert the `double` into an `array of chars`.
252015
An overview of what I've done: I've inherited `System.Windows.Forms.TextBox` and added a few properties to help me out in creating forms that generate SQL statements. I use to create a large function that would check for changes in the `TextBox` compared to a string. Then it would take text and concatenate it to a SQL statement. Now it's simple and easier to use. I've added four properties: * A String property to hold the default string that the textbox is initially set to and will reset back if the text is left empty. * A String property to hold the text's associated SQL statement. * A Boolean to check if the text has changed from the default. * Finally, an Integer to hold an ID if there is a reason to need one, such as saving and loading text from a file by the ID. I have not fully implemented the new textbox in my code, but I am working on it. It may only be slightly modified, but it should cut down my code from 500+ lines of code down to less than +-30 if ran in a for-loop. **SQLTextBox.vb** ``` Public Class ModifiedTextBox Inherits System.Windows.Forms.TextBox Private _strDefaultText As String Private _strSqlText As String Private _nID As Integer Private _bModified As Boolean = False Property ID() Set(nID) _nID = nID End Set Get Return _nID End Get End Property Property TextModified() Set(bModified) _bModified = bModified End Set Get Return _bModified End Get End Property Property SqlText() Set(strSqlText) _strSqlText = strSqlText End Set Get Return _strSqlText End Get End Property Property DefaultText() Set(strDefaultText) _strDefaultText = strDefaultText Me.Text = _strDefaultText End Set Get Return _strDefaultText End Get End Property End Class ``` I've pulled an excerpt from my code. It's not much, but here is the new textbox vs the old one. In the SQL text, I have something like ""Material Type"" in('INSERTTEXT'). `SQLTextBox.Modified` gets set when the user leaves the textbox (set to false b default). ``` 'This should run every new textbox (untested) For i As Integer = 0 To Me._icControls.txtMain.Length - 1 If Me._icControls.txtMain(i).Modified = True Then sqlWhere += " AND " + Me._icControls.txtMain(i).SqlText Replace(sqlWhere, "INSERTTEXT", Me._icControls.txtMain(i).Text) End If Next 'Old, long way around where I had split up 'the textboxes into 7 groups they belonged too. If Me._icControls.txtMaterial(0).Text.ToString() <> DefaultStrings.Material(0) Then sqlWhere += " AND ""Material Type"" in('" + Me._icControls.txtMaterial(0).Text.ToString() + "')" End If If Me._icControls.txtMaterial(4).Text.ToString() <> DefaultStrings.Material(4) Then sqlWhere += " AND ""Grade"" in('" + Me._icControls.txtMaterial(4).Text.ToString() + "')" End If If Me._icControls.txtMaterial(5).Text.ToString() <> DefaultStrings.Material(5) Then sqlWhere += " AND ""PIW"" in('" + Me._icControls.txtMaterial(5).Text.ToString() + "')" End If ``` I went from 200 lines of code to 6, with a minor change. That does not include the lines spent setting up the default text. Let me know what you think of this. I'm not sure if it's really anything someone could use, but it's been very useful to me.
There's not much to review here really. I'd be more interested in reviewing the code that's actually doing the work, but here goes. 1. Lose the Systems Hungarian notation. The IDE/Code tells me what the data type is. That is if you... 2. Declare the data types of the properties 3. Use auto properties. There's *way* too much code here for how simple this is. --- ``` Public Class ModifiedTextBox Inherits System.Windows.Forms.TextBox Property ID() As Integer Property TextModified() As Boolean Property SqlText() As String Property DefaultText() As String Set(strDefaultText) _strDefaultText = strDefaultText Me.Text = _strDefaultText End Set Get Return _strDefaultText End Get End Property End Class ```
252108
I am learning how to program apps in ios. Anyone out there know of a recent tutorial that shows how to push a new instance of a table view controller object on top of the stack without the need to create and hookup new nib? I found an old tutorial at iphone SDK Articles dated 3/2009. The website does not exist anymore as its domain expired. But the article, using a pre-packaged 2009 "Navigation-Based Application" in xcode, shows how to drill down a table using the same view controller rather than incorporate a new nib file. In the article, the view controller is identified as a "rootview" controller. I have managed to modify the code to populate the data from the plist to a table cell using a UIViewController class with UITableViewDelegate and UI TableViewDataSource. This was not difficult to do. However, my problems begin when a cell is activated with the didSelectRowAtIndexPath method. The tutorial's code creates a new instance of the same table view controller class, updates the cell data and pushes it to the top of the stack to effect the "drill down." When I apply the same method to my controller class, xcode throws an error. Admittedly, my ignorance is the likely cause of the problem. That is why I am looking for help. The tutorial code implementing the didSelectRowAtIndexPath: ``` //RootViewController.m - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { //Get the dictionary of the selected data source. NSDictionary *dictionary = [self.tableDataSource objectAtIndex:indexPath.row]; //Get the children of the present item. NSArray *Children = [dictionary objectForKey:@"Children"]; if([Children count] == 0) { DetailViewController *dvController = [[DetailViewController alloc] initWithNibName:@"DetailView" bundle:[NSBundle mainBundle]]; [self.navigationController pushViewController:dvController animated:YES]; [dvController release]; } else { //Prepare to tableview. RootViewController *rvController = [[RootViewController alloc] initWithNibName:@"RootViewController" bundle:[NSBundle mainBundle]]; //Increment the Current View rvController.CurrentLevel += 1; //Set the title; rvController.CurrentTitle = [dictionary objectForKey:@"Title"]; //Push the new table view on the stack [self.navigationController pushViewController:rvController animated:YES]; rvController.tableDataSource = Children; [rvController release]; } } ```
On the line where your begin the UIGraphicsImageContext, use `UIGraphicsBeginImageContextWithOptions` instead of `UIGraphicsBeginImageContext`. Try something like this: ``` UIGraphicsBeginImageContextWithOptions(targetSize, NO, 0.0) ``` Notice the three parameters passed above, I'll go through them in order: 1. `targetSize` is the size of the image measured in points (not pixels) 2. `NO` is a BOOL value (could be YES or NO) that indicates whether the image is 100% opaque or not. Setting this to NO will preserve transparency and create an alpha channel to handle transparency. 3. The **most important** part of the above code is the final parameter, `0.0`. This is the image scale factor that will be applied. Specifying the value to `0.0` sets the scale factor of the current device's screen. This means that the quality will be preserved, and look especially good on Retina Displays. Here's the [Apple Documentation](http://developer.apple.com/library/ios/documentation/UIKit/Reference/UIKitFunctionReference/Reference/reference.html#//apple_ref/doc/uid/TP40006894-CH3-SW59) on `UIGraphicsBeginImageContextWithOptions`.
252127
I am running into an issue that I cannot seem to wrap my head around. I am using Razor Pages and have two objects that can be bound. ``` [BindProperty] public MeetingMinuteInputDto MeetingToCreate { get; set; } [BindProperty] public MeetingMinuteUpdateDto MeetingToUpdate { get; set; } ``` Above two are separate dto for creating/updating a base entity in my database. I have two separate dto because I allow only specific items for update (to prevent overposting). Both classes have a `Name`, `Date`, and `Reminder`. The `MeetingMinuteUpdateDto` only allows the `Date` to be changed. The **Name** property is required and cannot be null. The reason I have both objects in the same page/controller is because I am using modals to create/update and I would rather not create multiple pages just to create/edit objects. I have two forms that users can fill out - one for editing and one for creating. Each one binds the values to a specific object (i.e. the create form will bind its posted form values to the `MeetingMinuteInputDto`). ``` <div class="form-group"> <div class="col-md-10"> <label asp-for="MeetingToCreate.Name" class="control-label"></label> <input asp-for="MeetingToCreate.Name" class="form-control" /> <span asp-validation-for="MeetingToCreate.Name" class="text-danger"></span> </div> </div> ``` Above is a sample of my form for the creating a new meeting. I checked to see that when the form is submitted, only the `MeetingMinuteInputDto` value is being bound to. The other object (`MeetingMinuteUpdateDto`) has null values for all its properties. But when I check the model state, MVC throws an error on the "Name" property saying that it is null. I looked at the results of the model state and there is a key named "Name" which is not tied to any object that fails validation. If I remove the other object (i.e. I remove `MeetingMinuteUpdateDto`) from the page and do model binding, everything works correctly. How do I prevent the model validation from trying to validate an objects that is not relevant for the current action? I want the Create action to only validate the create object and vice versa. I tried doing `TryValidateModel(MeetingToCreate)` but that also provides a false for model validation. [![enter image description here](https://i.stack.imgur.com/13HWt.png)](https://i.stack.imgur.com/13HWt.png) **Note**: I can't just place the object properties outside as I have other pages where I need to do this in which the update/create objects have 10+ properties that are shared/not shared. --- **Update** - I can manually remove the validation error from the model state dictionary. But I don't really like that approach as I don't want to have to iterate through all the properties for the incorrect keys and remove them. --- **Update 2**: Here is more detail on when this issue is occurring: ``` public class MeetingMinuteInputDto: MeetingMinuteManipulationDto { public string AdditionalInfo { get; set; } } public class MeetingMinuteUpdateDto : MeetingMinuteManipulationDto { } public class MeetingMinuteManipulationDto { [Required] public string Name { get; set; } public IFormFile FileToUpload { get; set; } } ``` In my Razor Page, I have both of these properties with the bind property attribute: ``` public class MeetingMinutesModel : PageModel { [BindProperty] public MeetingMinuteInputDto MeetingToCreate { get; set; } [BindProperty] public MeetingMinuteUpdateDto MeetingToUpdate { get; set; } //...stuff } ``` My form on the create/edit page looks as such: ``` <form asp-page="/MeetingMinute/MeetingMinutes" asp-page-handler="CreateMeeting"> <div class="form-group"> <div class="col-md-10"> <label asp-for="MeetingToCreate.Name" class="control-label"></label> <input asp-for="MeetingToCreate.Name" class="form-control" /> <span asp-validation-for="MeetingToCreate.Name" class="text-danger"></span> </div> </div> //other inputs and label for rest of the properties <button type="submit" class="btn btn-danger">Submit</button> </form> ``` The input for the form is set to bind specifically to the **MeetingToCreate** property. When I submit the form, the form values are correctly bound. But at the same time, I am getting ModelState errors for the `MeetingToUpdate` property (as it shares some fields with `MeetingToCreate`). I am assuming that in a Razor Page, model state validation is validating the **MeetingMinutesModel** and not the individual `MeetingToCreate/MeetingToUpdate` properties. In MVC, I assume this might be different as actions need to have parameters as opposed to open-ended properties on the page model in razor pages.
I was doing something similar. Searching for any solution, I find your question, but not a solution I share the solution. I implement multiple BindProperty and multiple Actions OnPost, and the solution I find is to do some in the Asp.Net MVC, using the [Bind] property. In your case, it would be. ``` public class MeetingMinutesModel : PageModel { //[BindProperty] remove it public MeetingMinuteInputDto MeetingToCreate { get; set; } //[BindProperty] remove it public MeetingMinuteUpdateDto MeetingToUpdate { get; set; } //...stuff } public IActionResult OnPost([Bind("Name, FileToUpload, AdditionalInfo")] MeetingMinuteInputDto MeetingToCreate) { //Do somthing } ```
252479
1. I need help with the prototype. 2. I need help with the caller. 3. I need help with the function header. I don't know how much more detail this site wants me to add, but the code speaks for itself, I am having trouble with the top three items but for some reason the site wants more context? ``` #include <iostream> using namespace std; void fillArray(int salesSheet[][COLSIZE], int rowSize); // I dont know how to create prototype for 2d array int main() { const int ROWSIZE = 5, COLSIZE = 6; int salesSheet[ROWSIZE][COLSIZE], a, rowSize; fillArray(a[][COLSIZE], int rowSize); // I don't know where I messed this up // I messed up the caller too, help? return 0; } void fillArray(int salesSheet[][COLSIZE], int rowSize) { int r, c; cout <<"Enter sales report for each quarter, for your branch." << endl; for (c = 0; c < COLSIZE; c++) { for (r = 0; r < rowSize; r++) cout << "\nBranch " << c+1 << " quarterly sales figures:" cin >> salesSheet[r][c]; } } ```
The `\w` is `0-9a-zA-Z_`\* you need to allow the `#` as well, you can use an alteration or a character class. ``` [#\w]+ ``` or ``` (?:#|\w)+ ``` Full example: ``` [#\w]+(?:\s*(\([^()]*+(?:(?1)[^()]*)*+\)))? ``` Demo: <https://3v4l.org/75eGQ> Regex demo: <https://regex101.com/r/1PYvpO/1/> > > \w stands for "word character". It always matches the ASCII characters [A-Za-z0-9\_]. Notice the inclusion of the underscore and digits. In most flavors that support Unicode, \w includes many characters from other scripts. There is a lot of inconsistency about which characters are actually included. Letters and digits from alphabetic scripts and ideographs are generally included. Connector punctuation other than the underscore and numeric symbols that aren't digits may or may not be included. XML Schema and XPath even include all symbols in \w. > > > \*<https://www.regular-expressions.info/shorthand.html>
252519
I am trying to repair my wipers, there is no voltage in the wires that connects to the wiper motor. I checked the fuses and current is passing through them, so they are ok. I think the Wiper Relay (or wiper control module) went bad, but I do not know where it is located. Can someone help me?
Though I may not be correct, have you tried opening your hood and using a spray bottle of water on your spark plug wires? Lightly mist around where the wires connect on both ends of the wires, and maybe a few squirts around on the wires themselves. If the vehicle stutters, it may just be that the wires need to be replaced...
252867
i want make my button visible after matching some pattern into url every thing is going fine but it does not set visibility of my button to true i am trying this ``` try { sleep((int)(Math.random() * 1000)); btn = (Button) findViewById(R.id.My_btn); btn.requestFocus(); btn.setVisibility(0); //here btn.setvisibility(View.VISIBLE) also not working } ``` this is my logcate for button ``` 05-04 10:30:12.212: WARN/InputManagerService(52): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@437da3e8 05-04 10:30:13.673: WARN/InputManagerService(52): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@4379d170 05-04 10:30:16.054: INFO/NotificationService(52): enqueueToast pkg=android.com.MobiintheMorning callback=android.app.ITransientNotification$Stub$Proxy@4376ae30 duration=0 05-04 10:30:16.064: INFO/System.out(677): button founded 05-04 10:30:16.629: WARN/dalvikvm(677): threadid=31: thread exiting with uncaught exception (group=0x4001aa28) 05-04 10:30:16.629: ERROR/AndroidRuntime(677): Uncaught handler: thread Thread-17 exiting due to uncaught exception 05-04 10:30:16.634: ERROR/AndroidRuntime(677): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. 05-04 10:30:16.634: ERROR/AndroidRuntime(677): at android.view.ViewRoot.checkThread(ViewRoot.java:2629) 05-04 10:30:16.634: ERROR/AndroidRuntime(677): at android.view.ViewRoot.focusableViewAvailable(ViewRoot.java:1519) 05-04 10:30:16.634: ERROR/AndroidRuntime(677): at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:448) 05-04 10:30:16.634: ERROR/AndroidRuntime(677): at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:448) 05-04 10:30:16.634: ERROR/AndroidRuntime(677): at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:448) 05-04 10:30:16.634: ERROR/AndroidRuntime(677): at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:448) 05-04 10:30:16.634: ERROR/AndroidRuntime(677): at android.view.View.setFlags(View.java:4270) 05-04 10:30:16.634: ERROR/AndroidRuntime(677): at android.view.View.setVisibility(View.java:2964) 05-04 10:30:16.634: ERROR/AndroidRuntime(677): at android.com.MobiintheMorning.MobiintheMorningActivity.btnvisibility(MobiintheMorningActivity.java:307) 05-04 10:30:16.634: ERROR/AndroidRuntime(677): at android.com.MobiintheMorning.MobiintheMorningActivity$temp.run(MobiintheMorningActivity.java:277) 05-04 10:30:16.644: INFO/Process(52): Sending signal. PID: 677 SIG: 3 05-04 10:30:16.644: INFO/dalvikvm(677): threadid=7: reacting to signal 3 05-04 10:30:16.644: ERROR/dalvikvm(677): Unable to open stack trace file '/data/anr/traces.txt': Permission denied 05-04 10:33:50.293: DEBUG/AndroidRuntime(893): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<< 05-04 10:33:50.293: DEBUG/AndroidRuntime(893): CheckJNI is ON 05-04 10:33:50.494: DEBUG/AndroidRuntime(893): --- registering native functions --- 05-04 10:33:50.494: INFO/jdwp(893): received file descriptor 20 from ADB 05-04 10:33:50.693: DEBUG/ddm-heap(893): Got feature list request 05-04 10:33:51.133: DEBUG/PackageParser(52): Scanning package: /data/app/vmdl65231.tmp 05-04 10:33:51.314: INFO/PackageManager(52): Removing non-system package:android.com.MobiintheMorning 05-04 10:33:51.314: DEBUG/PackageManager(52): Removing package android.com.MobiintheMorning 05-04 10:33:51.314: DEBUG/PackageManager(52): Activities: android.com.MobiintheMorning.MobiintheMorningActivity android.com.MobiintheMorning.FindFilesByType android.com.MobiintheMorning.EmailAct android.com.MobiintheMorning.DisplaySong 05-04 10:33:51.373: DEBUG/PackageManager(52): Scanning package android.com.MobiintheMorning 05-04 10:33:51.373: INFO/PackageManager(52): /data/app/vmdl65231.tmp changed; unpacking 05-04 10:33:51.383: DEBUG/installd(32): DexInv: --- BEGIN '/data/app/vmdl65231.tmp' --- 05-04 10:33:51.744: DEBUG/dalvikvm(900): DexOpt: load 36ms, verify 187ms, opt 2ms 05-04 10:33:51.774: DEBUG/installd(32): DexInv: --- END '/data/app/vmdl65231.tmp' (success) --- 05-04 10:33:51.774: DEBUG/PackageManager(52): Activities: android.com.MobiintheMorning.MobiintheMorningActivity android.com.MobiintheMorning.FindFilesByType android.com.MobiintheMorning.EmailAct android.com.MobiintheMorning.DisplaySong 05-04 10:33:51.793: DEBUG/ActivityManager(52): Uninstalling process android.com.MobiintheMorning 05-04 10:33:51.793: DEBUG/ActivityManager(52): Force removing process ProcessRecord{438e6a48 677:android.com.MobiintheMorning/10022} (android.com.MobiintheMorning/10022) 05-04 10:33:51.803: INFO/Process(52): Sending signal. PID: 677 SIG: 9 05-04 10:33:51.892: WARN/UsageStats(52): Unexpected resume of com.android.launcher while already resumed in android.com.MobiintheMorning 05-04 10:33:51.934: INFO/WindowManager(52): WIN DEATH: Window{438462b8 android.com.MobiintheMorning/android.com.MobiintheMorning.MobiintheMorningActivity paused=false} 05-04 10:33:51.943: DEBUG/ActivityManager(52): Received spurious death notification for thread android.os.BinderProxy@43845d50 05-04 10:33:51.963: WARN/InputManagerService(52): Got RemoteException sending setActive(false) notification to pid 677 uid 10022 05-04 10:33:52.194: INFO/installd(32): move /data/dalvik-cache/data@app@vmdl65231.tmp@classes.dex -> /data/dalvik-cache/data@app@android.com.MobiintheMorning.apk@classes.dex 05-04 10:33:52.204: DEBUG/PackageManager(52): New package installed in /data/app/android.com.MobiintheMorning.apk 05-04 10:33:52.284: DEBUG/AndroidRuntime(893): Shutting down VM 05-04 10:33:52.284: DEBUG/dalvikvm(893): DestroyJavaVM waiting for non-daemon threads to exit 05-04 10:33:52.294: DEBUG/ActivityManager(52): Uninstalling process android.com.MobiintheMorning 05-04 10:33:52.303: DEBUG/dalvikvm(893): DestroyJavaVM shutting VM down 05-04 10:33:52.303: DEBUG/dalvikvm(893): HeapWorker thread shutting down 05-04 10:33:52.303: DEBUG/dalvikvm(893): HeapWorker thread has shut down 05-04 10:33:52.303: DEBUG/jdwp(893): JDWP shutting down net... 05-04 10:33:52.303: DEBUG/jdwp(893): Got wake-up signal, bailing out of select 05-04 10:33:52.303: INFO/dalvikvm(893): Debugger has detached; object registry had 1 entries 05-04 10:33:52.313: DEBUG/dalvikvm(893): VM cleaning up 05-04 10:33:52.354: DEBUG/dalvikvm(893): LinearAlloc 0x0 used 665236 of 4194304 (15%) 05-04 10:33:52.454: WARN/ResourceType(52): No package identifier when getting value for resource number 0x7f060000 05-04 10:33:52.464: WARN/ResourceType(52): No package identifier when getting value for resource number 0x7f060001 05-04 10:33:52.643: DEBUG/dalvikvm(95): GC freed 131 objects / 5400 bytes in 231ms 05-04 10:33:52.643: DEBUG/HomeLoaders(95): application intent received: android.intent.action.PACKAGE_REMOVED, replacing=true 05-04 10:33:52.643: DEBUG/HomeLoaders(95): --> package:android.com.MobiintheMorning 05-04 10:33:52.653: DEBUG/HomeLoaders(95): application intent received: android.intent.action.PACKAGE_ADDED, replacing=true 05-04 10:33:52.653: DEBUG/HomeLoaders(95): --> package:android.com.MobiintheMorning 05-04 10:33:52.653: DEBUG/HomeLoaders(95): --> update package android.com.MobiintheMorning 05-04 10:33:52.813: DEBUG/dalvikvm(52): GC freed 10887 objects / 620232 bytes in 335ms 05-04 10:33:52.983: WARN/ResourceType(52): No package identifier when getting value for resource number 0x7f060000 05-04 10:33:53.012: WARN/ResourceType(52): No package identifier when getting value for resource number 0x7f060001 05-04 10:33:53.363: DEBUG/AndroidRuntime(907): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<< 05-04 10:33:53.363: DEBUG/AndroidRuntime(907): CheckJNI is ON 05-04 10:33:53.543: DEBUG/AndroidRuntime(907): --- registering native functions --- 05-04 10:33:53.543: INFO/jdwp(907): received file descriptor 20 from ADB 05-04 10:33:53.734: DEBUG/ddm-heap(907): Got feature list request 05-04 10:33:54.154: INFO/ActivityManager(52): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=android.com.MobiintheMorning/.MobiintheMorningActivity } 05-04 10:33:54.183: DEBUG/AndroidRuntime(907): Shutting down VM 05-04 10:33:54.183: DEBUG/dalvikvm(907): DestroyJavaVM waiting for non-daemon threads to exit 05-04 10:33:54.223: DEBUG/dalvikvm(907): DestroyJavaVM shutting VM down 05-04 10:33:54.223: DEBUG/dalvikvm(907): HeapWorker thread shutting down 05-04 10:33:54.223: DEBUG/dalvikvm(907): HeapWorker thread has shut down 05-04 10:33:54.233: DEBUG/jdwp(907): JDWP shutting down net... 05-04 10:33:54.233: DEBUG/jdwp(907): +++ peer disconnected 05-04 10:33:54.233: INFO/dalvikvm(907): Debugger has detached; object registry had 1 entries 05-04 10:33:54.243: DEBUG/dalvikvm(907): VM cleaning up 05-04 10:33:54.253: INFO/ActivityManager(52): Start proc android.com.MobiintheMorning for activity android.com.MobiintheMorning/.MobiintheMorningActivity: pid=915 uid=10022 gids={3003, 1015} 05-04 10:33:54.313: DEBUG/dalvikvm(907): LinearAlloc 0x0 used 676828 of 4194304 (16%) 05-04 10:33:54.423: INFO/jdwp(915): received file descriptor 20 from ADB 05-04 10:33:54.473: DEBUG/ddm-heap(915): Got feature list request 05-04 10:33:55.513: INFO/ActivityManager(52): Displayed activity android.com.MobiintheMorning/.MobiintheMorningActivity: 1312 ms (total 1312 ms) 05-04 10:34:05.163: DEBUG/dalvikvm(237): GC freed 43 objects / 2088 bytes in 54ms 05-04 10:34:10.253: DEBUG/dalvikvm(95): GC freed 2943 objects / 167248 bytes in 96ms 05-04 10:34:14.213: DEBUG/dalvikvm(915): GC freed 2995 objects / 320496 bytes in 79ms 05-04 10:34:16.112: WARN/InputManagerService(52): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@4394c950 05-04 10:34:17.414: WARN/InputManagerService(52): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@4394d7b8 05-04 10:34:19.334: INFO/NotificationService(52): enqueueToast pkg=android.com.MobiintheMorning callback=android.app.ITransientNotification$Stub$Proxy@4394d9f0 duration=0 05-04 10:34:19.344: INFO/System.out(915): button founded 05-04 10:34:19.778: WARN/dalvikvm(915): threadid=31: thread exiting with uncaught exception (group=0x4001aa28) 05-04 10:34:19.778: ERROR/AndroidRuntime(915): Uncaught handler: thread Thread-17 exiting due to uncaught exception 05-04 10:34:19.783: ERROR/AndroidRuntime(915): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. 05-04 10:34:19.783: ERROR/AndroidRuntime(915): at android.view.ViewRoot.checkThread(ViewRoot.java:2629) 05-04 10:34:19.783: ERROR/AndroidRuntime(915): at android.view.ViewRoot.focusableViewAvailable(ViewRoot.java:1519) 05-04 10:34:19.783: ERROR/AndroidRuntime(915): at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:448) 05-04 10:34:19.783: ERROR/AndroidRuntime(915): at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:448) 05-04 10:34:19.783: ERROR/AndroidRuntime(915): at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:448) 05-04 10:34:19.783: ERROR/AndroidRuntime(915): at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:448) 05-04 10:34:19.783: ERROR/AndroidRuntime(915): at android.view.View.setFlags(View.java:4270) 05-04 10:34:19.783: ERROR/AndroidRuntime(915): at android.view.View.setVisibility(View.java:2964) 05-04 10:34:19.783: ERROR/AndroidRuntime(915): at android.com.MobiintheMorning.MobiintheMorningActivity$temp.run(MobiintheMorningActivity.java:277) 05-04 10:34:19.793: INFO/Process(52): Sending signal. PID: 915 SIG: 3 05-04 10:34:19.793: INFO/dalvikvm(915): threadid=7: reacting to signal 3 05-04 10:34:19.793: ERROR/dalvikvm(915): Unable to open stack trace file '/data/anr/traces.txt': Permission denied ```
You're getting the error: > > 05-04 10:34:19.783: > ERROR/AndroidRuntime(915): > android.view.ViewRoot$CalledFromWrongThreadException: > Only the original thread that created > a view hierarchy can touch its > views.05 > > > This suggests that you're attempting to make the button visible from a non-ui thread. If so, then you need to do something like this, to get the UI thread to change the visibility of the button: ``` try{ btn.post(new Runnable() { public void run() { btn.requestFocus(); btn.setVisibility(0); // Or: btn.setVisibility(View.VISIBLE) }}); }catch (Exception e) { Log.d("test", e.toString()); } ```
253102
When I try to install Python 3.8 terminal says it is done, but when I run `python --version` it says Python 3.7. ```none (base) user@admin:~$ sudo apt-get install python3.8 Reading package lists... Done Building dependency tree Reading state information... Done python3.8 is already the newest version (3.8.2-1ubuntu1.2). The following packages were automatically installed and are no longer required: libllvm9 libllvm9:i386 Use 'sudo apt autoremove' to remove them. 0 upgraded, 0 newly installed, 0 to remove and 38 not upgraded. ``` ```none (base) user@admin:~$ python --version Python 3.7.6 ```
As per the instructions on [How to Install Python 3.8 on Ubuntu, Debian and LinuxMint – TecAdmin](https://tecadmin.net/install-python-3-8-ubuntu/), try the following: ### Prerequisites: Install [and or update] the following packages; build-essential, checkinstall, libreadline-gplv2-dev, libncursesw5-dev, libssl-dev, libsqlite3-dev, tk-dev, libgdbm-dev, libc6-dev, libbz2-dev, libffi-dev, zlib1g-dev. ``` sudo apt install build-essential checkinstall sudo apt-get install libreadline-gplv2-dev libncursesw5-dev libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev libffi-dev zlib1g-dev ``` Thereafter, change directory (`cd`) to your `opt` folder [or any convenient folder] and download the python source code from python's server: ### First change directory (cd) to the 'opt' folder: ``` cd /opt/ ``` ### Download the source code ``` sudo wget https://www.python.org/ftp/python/3.8.3/Python-3.8.3.tgz ``` ### Extract the [downloaded] source code files ``` sudo tar xzf Python-3.8.3.tgz ``` ### Change directory (`cd`) the Python Folder [created after the extraction] ``` cd Python-3.8.3 ``` ### Compile the source code ``` sudo ./configure --enable-optimizations ``` then ``` sudo make altinstall ``` Once the compilation is completed, you can confirm that Python 3.8 has been installed successfully with: ``` python3.8 -V ``` You should see the response `Python-3.8.3`. However, to precisely answer your question, python 3.8 isn't available via ubuntu official repos. You would have to add a PPA to get python 3.8 using `sudo apt install [python3.x.x]`. The process is described on [How to Install Python 3.8 on Ubuntu 18.04 | Linuxize](https://linuxize.com/post/how-to-install-python-3-8-on-ubuntu-18-04/) Hope this helps and I hope I answered your question adequately.
253158
I am currently handed over a php project which was hosted by a different company before.My core domain is Java so everything related to PHP is new to me.When I run the project its difficult to know which PHP file the browser is showing since the URL does not show actual PHP filename due to 'URL rewriting'.I tried to remove the URL rewriting rules form .htaccess file but then application stopped working as I did dome mistake.In order to get the flow of project I just need to know which file is currently shown by the browser.Please help me achieving this.
``` echo __FILE__; $included = get_included_files(); var_dump($included); ```
254132
I am building an activity model, somewhat similar to this [package](https://github.com/justquick/django-activity-stream). It has an actor, verb and the target. ``` class Activity(models.Model): actor_type = models.ForeignKey(ContentType, related_name='actor_type_activities') actor_id = models.PositiveIntegerField() actor = GenericForeignKey('actor_type', 'actor_id') verb = models.CharField(max_length=10) target_type = models.ForeignKey(ContentType, related_name='target_type_activities') target_id = models.PositiveIntegerField() target = GenericForeignKey('target_type', 'target_id') pub_date = models.DateTimeField(default=timezone.now) ``` Now whenever a new object of whichever models (Tender, Job and News) is created, a new Activity object is created, with the `target` being the objects of any of these three models. > > eg. user (actor) published (verb) title (target) > > > ``` class Tender(models.Model): title = models.CharField(max_length=256) description = models.TextField() class Job(models.Model): title = models.CharField(max_length=256) qualification = models.CharField(max_length=256) class News(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) title = models.CharField(max_length=150) ``` To get this data I am making an API which will get me the required json data. I am using [django-rest-framework](http://www.django-rest-framework.org/) for this and very new with it. ``` class ActorSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('id', 'username', 'email') class ActivitySerializer(serializers.HyperlinkedModelSerializer): actor = ActorSerializer() class Meta: model = Activity fields = ('url', 'actor', 'verb', 'pub_date') ``` In the above serializers, I knew that `actor` will be the User. And so I used the User model for the `ActorSerializer` class. But as for the `target`, it can be any of these three models (News/Job/Tender). How can I make a serializer (eg. `TargetSerialier` class) for the ContentType object so that I can use the `target` in the `ActivitySerializer` class field?
Okay so answering my own question here. I had some help with zymud's answer. So, apparently in the [documentation](http://www.django-rest-framework.org/api-guide/relations/#generic-relationships), there is a way to serialize the Generic relation. So, all I had to do was create a custom field and associate that field in the serializer itself: ``` class ActivityObjectRelatedField(serializers.RelatedField): def to_representation(self, value): if isinstance(value, User): return 'User: ' + value.username elif isinstance(value, News): return 'News: ' + value.title elif isinstance(value, Job): return 'Job: ' + value.title elif isinstance(value, Tender): return 'Tender: ' + value.title raise Exception('Unexpected type of tagged object') class ActivitySerializer(serializers.HyperlinkedModelSerializer): actor = ActivityObjectRelatedField(read_only=True) target = ActivityObjectRelatedField(read_only=True) class Meta: model = Activity fields = ('url', 'actor', 'verb', 'target', 'pub_date') ```
254533
I am new to Kotlin. I have an android project which I opted to convert to kotlin. This is my piece of code. ``` import com.beardedhen.androidbootstrap.BootstrapButton class EndTrip : AppCompatActivity(){ internal var endtrip: BootstrapButton ?= null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_end_trip) endtrip.setOnClickListener(View.OnClickListener { //Some code here } } } ``` But I get this error on the endtrip > > Smart cast to BootsrapButton is impossible because endtrip is mutable > property that have changed by this time > > > A similar question has been answered [here](https://stackoverflow.com/questions/44595529/smart-cast-to-type-is-impossible-because-variable-is-a-mutable-property-tha) but i cant figure out the solution. I am using [beardedhen Android Bootstrap Library](https://github.com/Bearded-Hen/Android-Bootstrap). Thank you.
The error tell you that you cannot guarantee that `endtrip` is not null at that line of code. The reason is that `endtrip` is a `var`. It can be mutated by other thread, even if you do a null check just before you use that variable. Here is the [official document's](https://kotlinlang.org/docs/reference/typecasts.html) explanation: > > Note that smart casts do not work when the compiler cannot guarantee that the variable cannot change between the check and the usage. More specifically, smart casts are applicable according to the following rules: > > > * **val** local variables - always; > * **val** properties - if the property is private or internal or the check is performed in the same module where the property is declared. Smart casts aren't applicable to open properties or properties that have custom getters; > * **var** local variables - if the variable is not modified between the check and the usage and is not captured in a lambda that modifies it; > * **var** properties - never (because the variable can be modified at any time by other code). > > > The simplest solution is to use safe call operator `?.` ``` endtrip?.setOnClickListener(View.OnClickListener { //Some code here } ``` Suggested reading: [In Kotlin, what is the idiomatic way to deal with nullable values, referencing or converting them](https://stackoverflow.com/questions/34498562/in-kotlin-what-is-the-idiomatic-way-to-deal-with-nullable-values-referencing-o)
254784
I have set up Google Analytics v2 beta on a test project as bellow **MainActivity.java** ``` public class MainActivity extends Activity { Context context; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); context = this; // Set Context to Google Analytics EasyTracker.getInstance().setContext(context); } @Override protected void onStart() { super.onStart(); EasyTracker.getInstance().activityStart(this); EasyTracker.getInstance(); Tracker myTracker = EasyTracker.getTracker(); myTracker.sendView("harsha"); } @Override protected void onStop() { super.onStop(); EasyTracker.getInstance().activityStop(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } } ``` analytics.xml ``` <?xml version="1.0" encoding="utf-8"?> <resources xmlns:tools="https://schemas.android.com/tools" tools:ignore="TypographyDashes"> <!-- Replace placeholder ID with your tracking ID --> <string name="ga_trackingId">UA&#8211;37418075&#8211;1</string> <!-- Enable automatic activity tracking --> <bool name="ga_autoActivityTracking">true</bool> <!-- Enable automatic exception tracking --> <bool name="ga_reportUncaughtExceptions">true</bool> <bool name="ga_debug">true</bool> <!-- The screen names that will appear in your reporting --> <string name="com.m7.google_analytics_v2.BaseActivity">Home</string> </resources> ``` I have been trying to send the tracking to Google Analytics Server but not able to find any hits or activity of any kind. Does it take time for it to reflect ? I find this in the Log Cat ``` 01-13 15:16:52.360: I/GAV2(23176): Thread[GAThread,5,main]: putHit called 01-13 15:16:52.360: I/GAV2(23176): Thread[GAThread,5,main]: Sending hit to store 01-13 15:16:52.440: I/GAV2(23176): Thread[GAThread,5,main]: putHit called 01-13 15:16:52.440: I/GAV2(23176): Thread[GAThread,5,main]: Sending hit to store 01-13 15:16:53.825: I/GAV2(23176): Thread[GAThread,5,main]: putHit called 01-13 15:16:53.825: I/GAV2(23176): Thread[GAThread,5,main]: Sending hit to store 01-13 15:16:53.905: I/GAV2(23176): Thread[GAThread,5,main]: putHit called 01-13 15:16:53.905: I/GAV2(23176): Thread[GAThread,5,main]: Sending hit to store 01-13 15:16:57.840: I/GAV2(23176): Thread[GAThread,5,main]: putHit called 01-13 15:16:57.840: I/GAV2(23176): Thread[GAThread,5,main]: Sending hit to store 01-13 15:16:57.945: I/GAV2(23176): Thread[GAThread,5,main]: putHit called 01-13 15:16:57.945: I/GAV2(23176): Thread[GAThread,5,main]: Sending hit to store ```
This doesn't look good: ``` <string name="ga_trackingId">UA&#8211;37418075&#8211;1</string> ``` `&#8211;` (–) is `&ndash`; which is a different character from the ASCII - (-) (`&#45`). I'm pretty sure GA just expects ASCII in the tracking Id. Unless that was just inserted when pasting into stack overflow.
254956
I want to enable the tab menu after the the data is found (dt1.Rows.Count is not null) .In the HTML code below all the tabs are disable HTML ``` <div id="Tabs" role="tabpanel" style="background-color: #CCCCCC; " > <ul class="nav nav-tabs" > <li id="result1" class="active disabled" style="left: 0px; top: 0px; width: 210px" ><a href="#AddResult1" aria-controls="AddResult1" role="tab" data-toggle="tab" class="auto-style235" style="color: #0000FF"><strong><em>Add Result Type1</em></strong></a></li> <li id="result2" class="disabled" style="left: 0px; top: 0px; width: 210px" ><a href="#AddResult12" aria-controls="AddResult2" role="tab" data-toggle="tab" class="auto-style235" style="color: #0000FF"><strong><em>Add Result Type2</em></strong></a></li> <li id="result3" class="disabled" style="left: 0px; top: 0px; width: 210px" ><a href="#AddResult3" aria-controls="AddResult3" role="tab" data-toggle="tab" class="auto-style235" style="color: #0000FF"><strong><em>Add Result Type3</em></strong></a></li> <li id="report" class="disabled" style="left: 0px; top: 0px; width: 230px" ><a href="#ResultReport" aria-controls="ResultReport" role="tab" data-toggle="tab" class="auto-style235" style="color: #0000FF"><strong><em>All Test Result Report</em></strong></a></li> <li class="disabled" style="left: 0px; top: 0px; width: 230px"><a href="#CreateSampleBranch" aria-controls="CreateSampleBranch" role="tab" data-toggle="tab" class="auto-style235" spellcheck="False"> <strong><em>Create Sample Branch</em></strong></a></li> </ul> <div> ``` C# ``` using (SqlCommand cmd1 = new SqlCommand(@"SELECT * FROM SampleBranch WHERE SampleID=@SampleID", con)) { cmd1.Parameters.AddWithValue("@SampleID", lblSampleID.Text); DataTable dt1 = new DataTable(); SqlDataAdapter da1 = new SqlDataAdapter(cmd1); da1.Fill(dt1); if (dt1 != null && dt1.Rows.Count > 0) { GridviewSampleBranch.DataSource = dt1; GridviewSampleBranch.DataBind(); // Enable Tab Menu here } } ```
In your **aspx** file add `id` and `runat="server"` to the `ul` and its `li` tags. That way they will be visible from C# code. ``` <ul id="TabList" runat="server" class="nav nav-tabs"> <li id="result1" runat="server" class="disabled" ..... /> ........ </ul> ``` Now in your **C# code** you can set attributes for these controls, for example: ``` this.result1.Attributes["class"] = "enabled"; this.result2.Attributes["class"] = "enabled"; this.result3.Attributes["class"] = "enabled"; ``` But we can do it for all children of *TabList* control with this code. ``` foreach (Control control in this.TabList.Controls) { if (control.GetType()==typeof(HtmlGenericControl)) { var tab = (HtmlGenericControl)control; tab.Attributes["class"] = tab.Attributes["class"].Replace("disabled", ""); } } ```
255032
I have an activities table like below (also contains some other columns): ``` +------------------+---------------+------------+ | data | event | logged_on | +------------------+---------------+------------+ | 12345 | File | 2015-04-08 | | 25232 | Bulletin | 2015-04-08 | | 7890 | File | 2015-04-08 | | youtube | Search | 2015-04-07 | | 13568 | Bulletin | 2015-04-07 | | 25232 | Bulletin | 2015-04-07 | | 7890 | File | 2015-04-07 | +------------------+---------------+------------+ ``` I want to fetch unique data values for latest date. So the required result would be: ``` +------------------+---------------+------------+ | data | event | logged_on | +------------------+---------------+------------+ | 12345 | File | 2015-04-08 | | 25232 | Bulletin | 2015-04-08 | | 7890 | File | 2015-04-08 | | youtube | Search | 2015-04-07 | | 13568 | Bulletin | 2015-04-07 | +------------------+---------------+------------+ ``` But a select distinct on all the three columns above returns the same value of data for different dates. I cannot remove logged\_on from the select query as it's required elsewhere. In MySQL, i tried using the following query: ``` SELECT DISTINCT data, event, MAX(logged_on) AS latest_log_date FROM activites WHERE username = %%(username)s GROUP BY data ORDER BY id DESC, latest_log_date DESC LIMIT %%(limit)s ; ``` But this does not seem to work. I'm getting the some result, which looks like it's correct, but it isn't. And i'm not able to reason about it. Any ideas?
Use `NOT EXISTS` to return only rows that has no later with same data/event. ``` SELECT data, event, logged_on AS latest_log_date from activites a1 where not exists (select 1 from activites a2 where a1.data = a2.data and a1.event = a2.event and a2.logged_on > a1.logged_on) ``` I'm not quite sure if this is what you want. Perhaps you need to remove `and a1.event = a2.event` from the sub-query.
255682
I have several JSON files that look like this ``` { "$schema": "someURL", "id": "someURL", "type": "object", "properties": { "copyright": { "id": "someURL", "type": "object", "description": "Setup for copyright link", "properties": { "translation": { "id": "someURL", "type": "string", "description": "someString" }, "url": { "id": "someURL", "type": "string", "description": "someString" } }... ``` what I need to do is add a `removable` and `appendable` attribute to each item inside every instance of `properties` and set them to true. so the output should look like this: ``` { "$schema": "someURL", "id": "someURL", "type": "object", "properties": { "copyright": { "removable": true, "appendable": true, "id": "someURL", "type": "object", "description": "Setup for copyright link", "properties": { "translation": { "removable": true, "appendable": true, "id": "someURL", "type": "string", "description": "someString" }, "url": { "removable": true, "appendable": true, "id": "someURL", "type": "string", "description": "someString" } }... ``` Is there a way to automate this? as in write a script that automatically adds these fields right below each item in properties?
I have find the solution. Now HTTPRuntime class doesnt have CacheInternal Property.So to achive the above task I have created a global list adding sessions in that list in Session\_Start and removing the sessions in Sessions\_end functions of Global.asax.
255835
I'm writing a ncurses based chat program. At first, I wrote just networking stuff (without ncurses) and everything worked fine, but after adding graphics I can't get the client app to work properly. The main problem is reading from stdin and socket at the same time. In ncurses-less version I've used pthread and it worked like charm. Alas, it seems that pthread and ncurses don't go together very well, so I had to find another solution. I thought that select() would do, but it still only reads from stdin and completely ignores the socket. Here is the whole code: [code](http://paste.org/pastebin/view/32486/) The interesting part is: ``` char message[1024]; fd_set master; fd_set read_fds; FD_ZERO(&master); FD_ZERO(&read_fds); FD_SET(0,&master); FD_SET(s,&master); // s is a socket descriptor while(true){ read_fds = master; if (select(2,&read_fds,NULL,NULL,NULL) == -1){ perror("select:"); exit(1); } // if there are any data ready to read from the socket if (FD_ISSET(s, &read_fds)){ n = read(s,buf,max); buf[n]=0; if(n<0) { printf("Blad odczytu z gniazdka"); exit(1); } mvwprintw(output_window,1,1,"%s\n",buf); } // if there is something in stdin if (FD_ISSET(0, &read_fds)){ getstr(message); move(CURS_Y++,CURS_X); if (CURS_Y == LINES-2){ CURS_Y = 1; } n = write(s,message,strlen(message)); if (n < 0){ perror("writeThread:"); exit(1); } } } ``` It's possible that I don't fully understand how select() works, or maybe I shouldn't have connect()ed the socket.. I'm lost here. I would appreciate any help! Thanks.
Your problem is in the `select()`. The first parameter is **not** the number of file descriptors you are passing in *read\_fds*, but it's the highest socket ID + 1. From the man page: > > The first nfds descriptors are checked in each set; i.e., the > descriptors from 0 through nfds-1 in the descriptor sets are examined. (Example: If you have set two file descriptors "4" and "17", nfds should not be "2", but rather "17 + 1" or "18".) > > > So in your code, instead of '2', try passing 's+1'.
256364
For $a,b \in \mathbb{R}$ define $a \sim b$ if $a - b \in \mathbb{Z}$ I don't understand how I'm suppose to prove this: Prove that $\sim$ defines an equivalence relation on $\mathbb{Z}$ Also can you help me with finding the equivalence class of 5. In other words what I'm trying to describe is the set $[5]$ = {$y : 5 \sim y$}. And $[5]$ is just the name of the set. Edit: Please read my comment below (an attempt to solve this problem) does it make any sense? I'm sorry if I sound really dumb I'm new to this stuff.
You need to check 3 things : 1. Reflexivity : $a\sim a$ because $a-a = 0 \in \mathbb{Z}$ 2. Symmetry : $a\sim b$ implies that $a-b\in \mathbb{Z}$, and so $b-a\in \mathbb{Z}$ and hence $b\sim a$ 3. Transitivity : If $a\sim b$ and $b\sim c$, then $a-b, b-c\in \mathbb{Z}$, and hence $$ a-c = a-b + b-c \in \mathbb{Z} $$ So $\sim$ is an equivalence relation. Now, $[5] = \{a \in \mathbb{Z} : 5-a\in \mathbb{Z}\} = ?$
256390
I have a table that populates data from Postgres. I am able to populate the data. I have written a method to delete data from my mat-table. but when I click on the delete button then all data goes off from the screen and the data that I clicked remains. After I refresh the page manually and then I see that the data that I deleted is deleted and rest are there. Example: I have a table with the below row: ``` Roll name Action 1 rtr Del 2 were Del <----- I am clicking delete here 3 kjk Del 4 hgt Del ``` I get the below table when I click the `Del` for `Roll 2`. ``` Roll name Action 2 were Del //all data is not visible but only the data that I clicked for delete is visible ``` Now I refresh the page manually and I get the updated table: ``` Roll name Action 1 rtr Del 3 kjk Del 4 hgt Del ``` **is there any way that I can get the updated fields without refreshing???** My codes so far: ``` <mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8"> <!-- title Column --> <ng-container matColumnDef="textareaValue"> <mat-header-cell *matHeaderCellDef > Name </mat-header-cell> <mat-cell *matCellDef="let element"> {{element.textareaValue}} </mat-cell> </ng-container> <!-- difficulty Column --> <ng-container matColumnDef="difficulty"> <mat-header-cell *matHeaderCellDef > Difficulty </mat-header-cell> <mat-cell *matCellDef="let element"> {{element.difficulty}} </mat-cell> </ng-container> <ng-container matColumnDef="action"> <mat-header-cell *matHeaderCellDef > Action </mat-header-cell> <mat-cell *matCellDef="let element"> <button mat-raised-button color="primary"> <mat-icon (click)="deleteQuestionSet(element)">Delete</mat-icon></button> </mat-cell> </ng-container> <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row> <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row> </mat-table> ``` **My .ts file :** ``` deleteQuestionSet(row) { this.dataSource.data = <QuestionSetInterface>this.dataSource.data.filter(i => i == row) ; this.httpClient.post('http://localhost:8080/mylearning/deletequestionSet',this.dataSource.data[0],{ responseType: "text" }) .subscribe(response => console.log(response) ); this.isDeleted =true; } ``` Please assist me. **Is there any way that I can get the updated fields without refreshing???**
You have to Create a function for get Data you delete ! **.ts** ``` deleteQuestionSet(row) { this.dataSource.data = <QuestionSetInterface>this.dataSource.data.filter(i => i == row) ; this.httpClient.post('http://localhost:8080/mylearning/deletequestionSet',this.dataSource.data[0],{ responseType: "text" }) .subscribe(response => console.log(response) ); this.getData(); <------- make a function for get Updated Data this.isDeleted =true; } getData() { this.httpClient.post('API FOR GET DATA'{ responseType: "text" }) .subscribe(response => console.log(response) ); } ```
256518
I've defined this function: ``` // retrieves zip of package manifest supplied var retrieveZip = function(metadataClient, args, callback) { metadataClient.retrieve(args, function(err, result) { metadataClient.checkRetrieveStatus({id: result.result.id, includeZip: 'true'}, function(err, result) { if(result.result.done) { return callback(result); } // else check again!(how??) }); }); } retrieveZip(metadataClient, args, function(result) { console.log(result); }); ``` The idea is that the client will attempt to retrieve a zip file based on the metadata supplied in args. The API documentation (Salesforce SOAP API) requires the id supplied in the result of the retrieve method to be passed into a check status function. However the problem is this: 1. On the first check, if the result is 'done' then just return to the callback the result object from `checkRetreiveStatus` (contains the result) 2. BUT if the result isn't done, I need to call `checkRetrieveStatus` again... from inside `checkRetrieveStatus` 3. The naive approach would be to pass the parameters from the original `checkRetrieveStatus` call into a new instance of `checkRetrieveStatus` but obviously it's impossible to know how many times this would be invoked. It sounds like I need a recursive solution to this? Would using a while-loop would introduce problems with asynchronous calls?
From your description, it sounds like you just want to call `checkRetrieveStatus` until it's done, *not* `retrieve` *and* `checkRetrieveStatus`. Is that correct? If so, the thing to do is to extract the status check out into your own function that can recursively call itself, like this: ``` var checkStatus = function(metadataClient, id, callback) { metadataClient.checkRetrieveStatus({ id: id, includeZip: 'true' }, function(err, result) { if (result.result.done) { callback(result); } else { checkStatus(metadataClient, id, callback); } }); }; var retrieveZip = function(metadataClient, args, callback) { metadataClient.retrieve(args, function(err, result) { checkStatus(metadataClient, result.result.id, callback); }); } retrieveZip(metadataClient, args, function(result) { console.log(result); }); ``` And if you're worried about hogging system resources while it repeatedly polls the result, you can include a delay between checks: ``` var checkStatus = function(metadataClient, id, callback) { metadataClient.checkRetrieveStatus({ id: id, includeZip: 'true' }, function(err, result) { if (result.result.done) { callback(result); } else { setTimeout(function () { checkStatus(metadataClient, id, callback); }, 100); } }); }; var retrieveZip = function(metadataClient, args, callback) { metadataClient.retrieve(args, function(err, result) { checkStatus(metadataClient, result.result.id, callback); }); } retrieveZip(metadataClient, args, function(result) { console.log(result); }); ```
256805
In the last few days I already posted two alternative proofs ([here](https://math.stackexchange.com/questions/1455348/proof-that-if-phi-in-mathbbrx-is-continuous-then-x-mid-phix-ge) and the other available link) of the basic result in metric spaces that, given a continuous function $\phi \in \mathbb{R}^X$, the set $\{ x \ | \ \phi(x) \geq \alpha \}$ is closed for **any** $\alpha \in \mathbb{R}$. As explained there, I am doing the following because I realized my grasp of metric spaces and continuity arguments there is really not as it should be. In the book I am studying, I found as a natural extension of that proposition the following point: ***the continuity of $\phi$ is necessary for the proposition to hold.*** Hence, here there is the "proof" I came up with. *I am particularly interested about feedback concerning it, because I framed it as an existential proof, and this is another topic I am really (really!) bad at, both in terms of intuition and writing skills.* Of course, it would be nice to know overall if – beyond the proof itself – the strategy behind this specific proof is correct, or basically it is just all wrong. Concerning the **notation**, $\delta (\varepsilon, x)$, for an arbitrary $x \in X$ denotes a $\delta$ that can possibly depend on $\varepsilon$ and $x$, while $N\_{\varepsilon, X} (x)$ denotes the $\varepsilon$-nhood of $x \in X$. > > **Proposition:** In an arbitrary metric space $X$, if the function $\phi \in \mathbb{R}^X$ is not continuous, then the set $\{ x \ | \ \phi(x) \geq \alpha \}$ is not necessarily closed. > > > *Proof:* > > We prove that the set $G:= \{ x \ | \ \phi(x) < \alpha \}$ is not open. Hence, we have to show that there is a $\alpha \in \mathbb{R}$ and a $\bar{x} \in G$ such that, for all $\bar{\delta} >0$, there is a $w \in N\_{\bar{\delta}, X} (\bar{x})$ such that $w \notin G$. > > Let $\bar{\delta} >0$ be arbitrary. By assumption, $\phi \in \mathbb{R}^X$ is not continuous, hence there is a $z^\* \in X$ and a $\varepsilon^\* > 0$ such that for every $\delta (\varepsilon^\*, z^\*) >0$ there is a $y \in \phi (N\_{ \delta, X} (z^\*))$ such that $y \notin N\_{\varepsilon^\*, \mathbb{R}} (\phi (z^\*))$. This is equivalent to write that there is a $t \in N\_{ \delta, X} (z^\*)$ such that $t \notin \phi^{-1} ( N\_{\varepsilon^\*, \mathbb{R}} (\phi (z^\*)) )$. > > By setting $\delta ( \varepsilon^\*, z^\*)=\bar{\delta}$, $\alpha = \phi (z^\*) + 2\varepsilon^\*$, $\bar{x} = z^\*$, and $w = t$ the result follows. $\square$ > > > I am really looking forward to any feedback concerning this proof, because I have some points that still leave me a bit insecure. As always thank you for your time.
At the end of your proof, you set $\alpha = \phi(\bar{z}) - \epsilon$, $x^\*=\bar{z}$, but $x^\* \not\in G : = \{ \phi(x) < \phi(\bar{z}) - \epsilon\}$. **Edit:** I believe you want to set $\alpha = \phi(z) + \epsilon$, that way at least $z=x\in G$ and for each $B\_\delta(x)$, there exists $t\in B\_\delta(x)$ such that $$\phi(t) \not\in (\phi(z) - \epsilon, \phi(z) + \epsilon)$$ However, we can not say $t\not\in G$ since we still can have $\phi(t) <\phi(z) - \epsilon$, and have $t\in G$.
256847
Using SQL Server 2008, without using full-text indexing or CLR integration, is there a better way to search a table column for arbitrary text than the following: ``` declare @SubString nvarchar(max) = 'Desired substring may contain any special character such as %^_[]' select * from Items where Name like '%' + replace( replace( replace( replace( replace( replace( @SubString ,';',';;') ,'%',';%') ,'[',';[') ,']',';]') ,'^',';^') ,'_',';_') + '%' escape ';' ``` That works, but it seems unnecessarily barbaric. Is there any simpler, clearer, or more efficient way, given the above limitations? There are no constraints on what the `Name` column might contain, nor what the SubString we're searching for might contain.
Your form is trying to POST data to the server. This is a HTTP POST request. You define GET and SET methods in your view. You need to use POST there. ``` @app.route('/new_action', methods=['GET', 'POST']) # Changed SET to POST here @login_required def new_action(): # ... what ever... ``` You should go through this [RFC](http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.1) for HTTP. There is no SET-method.
256935
I would like to prove that $\alpha = \frac{1}{2\pi} \frac{xdy-ydx}{x^2+y^2}$ is a closed differential form on $\mathbb{R}^2-\{0\}$ . However when I apply the external derivative to this expression (and ignore the $\frac{1}{2\pi}\cdot\frac{1}{x^2+y^2}$ factor ), I get: \begin{equation} d \alpha = \frac{\partial x}{\partial x}dx\wedge dy + \frac{\partial x}{\partial y}dy\wedge dy - \frac{\partial y}{\partial x}dx\wedge dx - \frac{\partial y}{\partial y}dy\wedge dx \end{equation} \begin{equation} d \alpha = dx\wedge dy - dy\wedge dx \end{equation} \begin{equation} d \alpha = 2 dx\wedge dy \end{equation} Which is not closed on $\mathbb{R}^2-\{0\}$. Where is my mistake ?
Well, let us write $\alpha=f\cdot \omega $ with $f(x,y)=\frac{1}{x^2+y^2}$ and $\omega=xdy-ydx$. Then \begin{align} d\alpha=df\wedge \omega+fd\omega&=-\frac{1}{(x^2+y^2)^2}\left(2xdx+2ydy\right)\wedge\omega+ \frac{1}{x^2+y^2}2dx\wedge dy=\\ &=-\frac{1}{(x^2+y^2)^2}\left(2x^2 dx\wedge dy-2y^2dy\wedge dx\right)+ \frac{1}{x^2+y^2}2dx\wedge dy=\\ &=-\frac{1}{(x^2+y^2)^2}\cdot 2\left(x^2+y^2\right) dx\wedge dy+ \frac{1}{x^2+y^2}2dx\wedge dy= \\ &=0. \end{align}
257176
I have no intent to post a duplicated thread here. I'm interested in an offline version of Stack Overflow where I can study on the run as my job is an interstate courier that does not always have an Internet connection. Using 3G data is very expensive though. Is there a way to download an offline dump from the Stack Overflow for a specific programming language, for example, I'm learning [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29). Download the whole site seems not reasonable as it is too big and not necessary. How do I browse it alike the "Outlook" style, for example, the title column and content panel?
I have created several books (physical and eBooks). I've update the Python eBook with data from the latest data dump (June 2016) and generated a Python physical book if you want that. While not exactly what you're after (it's not quite "outlook style"), both books have links (eBook has hyperlinks, physical book as page numbers) between sections / tags so that you can read questions by tag, even if the book doesn't group the questions into the tag you want to read (because a more dominant tag exists for the question). I've put a free promotion on the eBook for 5 days starting today. eBook: [https://www.amazon.com/Python-Programming-Questions-George-Duckett-ebook/dp/B00RY621J6](http://rads.stackoverflow.com/amzn/click/B00RY621J6) Physical Book: [https://www.amazon.com/Python-Programming-Questions-George-Duckett/dp/1535352752](http://rads.stackoverflow.com/amzn/click/1535352752) Hope you find one/them useful!
257567
I'm trying to send faxes with a .NET (C#) program using Crystal Reports and Unimessage Pro (or any other fax program). My problem is that Unimessage Pro (and other fax programs) uses printer fonts for the fax commands. Since .NET doesn't support printer fonts the fax commands in the report are converted to Courier New. The result of this is that the fax program doesn't recognize the fax commands but sees them as plain text and the fax isn't sent. How do I send a fax with Crystal Reports and .NET?
I got this answer from WordCraft (company behind Unimessage Pro) > > 1. Create a file named WilCapAX.INI in the main Windows folder, e.g. > C:\Windows\WilCapAX.INI The file > should contain the following: > [WilCapAX] > Commands=C:\Commands.DAT Where "C:\Commands.DAT" is the name of > a text file you are going to create > in your .NET application to pass the > > embedded commands to Unimessage Pro. > You can edit the path if necessary, > but keep to short form file and > > folder names. > 2. In your .NET application when you have something to send via > > Unimessage Pro you then need to: > > > 2.1 Create a text file named, depending on the name defined > in WilCapAX.INI, C:\Commands.DAT containing: > > > > ``` > BLANK LINE > [[TO=Fax Number or Email address]] > [[SUBJECT=Whatever you want the subject to be]] > > ``` > > The first line of the file must either be blank or contain > something other than an embedded command - it will be > skipped. The other lines in the C:\Commands.DAT file > should each contain an embedded command. > > > 2.2 Print ONE message to the Unimessage Pro printer - the > Unimessage Pro printer accept the print job and will > look for the file specified in WilCapAX.INI. If the > file specified in WilCapAX.INI (C:\Commands.DAT) is > found, embedded commands are extracted from it and > then the "C:\Commands.DAT" file is deleted and the > print capture processed together with the command > extracted from the C:\Commands.DAT file. > > > 2.3 Wait for the C:\Commands.DAT file to disappear > (indicating that it has been processed by the > Unimessage Pro printer) and then repeat as necessary. > > > This solved the problem! :)