qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
1,103,653
So I have a spreadsheet with a bunch of little mini-charts as seen below. The numbers in blue are user entered, and they are all added together in the chart with the gray cells on the top left. Right now, I do this by having a basic sum formula. The real spreadsheet is much much larger, but in the example C3 would be =sum(J3+C13+J13), D3 would have =sum(K3+D13+K13), and so forth. As you can imagine, it is a PITA to add new charts or remove existing ones. What I would like is a way to make this happen automatically without having to add up individual cells, so I could add or remove as many charts as I want while still having the numbers added up. So it would be like, cell E5 would count all cells in a sheet where a number is three cells below III and three cells to the right of N/A. Or something that accomplishes the same thing. Is there a way to accomplish this without changing the layout of my spreadsheet? (ignore the N/As, I just copied and pasted to make a simpler example picture without modifying formulas that broke when I did that). [![enter image description here](https://i.stack.imgur.com/gj07S.png)](https://i.stack.imgur.com/gj07S.png)
2016/07/21
[ "https://superuser.com/questions/1103653", "https://superuser.com", "https://superuser.com/users/34463/" ]
When you add a new program to the path, you need to type ``` rehash ``` For it to be known to the shell.
As a fast fix you can make an alias. Add to you `~/.bashrc` file this: ``` alias main='/home/user/Downloads/program/./main' ``` then run `exec bash` in your terminal and it should work. If you're not using bash something similar would work for other shells. For example writing to the file `~/.zshrc` for the `zsh` shell.
543,130
I have some old Java 2D code I want to reuse, but was wondering, is this the best way to get the highest quality images? ``` public static BufferedImage getScaled(BufferedImage imgSrc, Dimension dim) { // This code ensures that all the pixels in the image are loaded. Image scaled = imgSrc.getScaledInstance( dim.width, dim.height, Image.SCALE_SMOOTH); // This code ensures that all the pixels in the image are loaded. Image temp = new ImageIcon(scaled).getImage(); // Create the buffered image. BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null), temp.getHeight(null), BufferedImage.TYPE_INT_RGB); // Copy image to buffered image. Graphics g = bufferedImage.createGraphics(); // Clear background and paint the image. g.setColor(Color.white); g.fillRect(0, 0, temp.getWidth(null),temp.getHeight(null)); g.drawImage(temp, 0, 0, null); g.dispose(); // j2d's image scaling quality is rather poor, especially when // scaling down an image to a much smaller size. We'll post filter // our images using a trick found at // http://blogs.cocoondev.org/mpo/archives/003584.html // to increase the perceived quality.... float origArea = imgSrc.getWidth() * imgSrc.getHeight(); float newArea = dim.width * dim.height; if (newArea <= (origArea / 2.)) { bufferedImage = blurImg(bufferedImage); } return bufferedImage; } public static BufferedImage blurImg(BufferedImage src) { // soften factor - increase to increase blur strength float softenFactor = 0.010f; // convolution kernel (blur) float[] softenArray = { 0, softenFactor, 0, softenFactor, 1-(softenFactor*4), softenFactor, 0, softenFactor, 0}; Kernel kernel = new Kernel(3, 3, softenArray); ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null); return cOp.filter(src, null); } ```
2009/02/12
[ "https://Stackoverflow.com/questions/543130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22801/" ]
Chris Campbell has an excellent and detailed write-up on scaling images - see **[this article](http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html)**. Chet Haase and Romain Guy also have a detailed and very informative write-up of image scaling in their book, **[Filthy Rich Clients](http://filthyrichclients.org/)**.
Adding some clarifying information here. No, that isn't the *best* way to get a good looking scaled image in Java. Use of getScaledInstance and the underlying AreaAveragingScaleFilter are deprecated by the Java2D team in favor of some more advanced methods. If you are just trying to get a good-looking thumbnail, using Chris Campbell's method as suggested by David is the way to go. For what it's worth, I have implemented that algorithm along with 2 other faster methods in a Java image-scaling library called [imgscalr](http://www.thebuzzmedia.com/software/imgscalr-java-image-scaling-library/) (Apache 2 license). The point of the library was to specifically address this question in a highly tuned library that is easy to use: ``` BufferedImage thumbnail = Scalr.resize(srcImg, 150); ``` To get the best-looking scaled instance possible in Java, the method call would look something like this: ``` BufferedImage scaledImg = Scalr.resize(img, Method.QUALITY, 150, 100, Scalr.OP_ANTIALIAS); ``` The library will scale the original image using the incremental-scaling approach recommended by the Java2D team and then to make it look even nicer a very mild convolveop is applied to the image, effectively anti-aliasing it slightly. This is really nice for small thumbnails, not so important for huge images. If you haven't worked with convolveops before, it's a LOT of work just to get the perfect looking kernel for the op to look good in all use-cases. The OP constant defined on the Scalr class is the result of a week of collaboration with a social networking site in Brazil that had rolled out imgscalr to process profile pictures for it's members. We went back and forth and tried something like 10 different kernels until we found one that was subtle enough not to make the image look soft or fuzzy but still smooth out the transitions between pixel values so the image didn't look "sharp" and noisey at small sizes. If you want the *best looking* scaled image regardless of speed, go with Juha's suggestion of using the java-image-scaling library. It is a very comprehensive collection of Java2D Ops and includes support for the [Lanczsos algorithm](http://en.wikipedia.org/wiki/Lanczos_algorithm) which will give you the best-looking result. I would stay away from JAI, not because it's bad, but because it is just a different/broader tool than what you are trying to solve. Any of the previous 3 approaches mentioned will give you great looking thumbnails without needing to add a whole new imaging platform to your project in fewer lines of code.
47,053,727
Say I have a UIView, ``` class CleverView: UIView ``` In the custom class, I want to do this: ``` func changeWidth() { let c = ... find my own layout constraint, for "width" c.constant = 70 * Gameinfo.ImportanceOfEnemyFactor } ``` Similarly I wanna be able to "find" like that, the constraint (or I guess, all constraints, there could be more than one) attached to one of the four edges. So, to look through all the constraints attached to me, and find any width/height ones, or indeed any relevant to a given (say, "left") edge. Any ideas? It's perhaps worth noting [this question](https://stackoverflow.com/questions/47239151/can-you-actually-link-constraints-to-utterly-different-view-controllers) --- Please, note that (obviously) I am asking how to do this dynamically/programmatically. (Yes, you can say "link to the constraint" or "use an ID" - the whole point of the QA is how to find them on the fly and work dynamically.) If you are new to constraints, note that `.constraints` just gives you the ends stored "there".
2017/11/01
[ "https://Stackoverflow.com/questions/47053727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/294884/" ]
There are really two cases: 1. Constraints regarding a view's size or relations to descendant views are saved in itself 2. Constraints between two views are saved in the views' lowest common ancestor **To repeat. For constraints which are between two views. iOS does, in fact, always store them in the lowest common ancestor.** Thus, a constraint of a view can always be found by searching all ancestors of the view. Thus, we need to check the view itself and all its superviews for constraints. One approach could be: ``` extension UIView { // retrieves all constraints that mention the view func getAllConstraints() -> [NSLayoutConstraint] { // array will contain self and all superviews var views = [self] // get all superviews var view = self while let superview = view.superview { views.append(superview) view = superview } // transform views to constraints and filter only those // constraints that include the view itself return views.flatMap({ $0.constraints }).filter { constraint in return constraint.firstItem as? UIView == self || constraint.secondItem as? UIView == self } } } ``` You can apply all kinds of filters after getting all constraints about a view, and I guess that's the most difficult part. Some examples: ``` extension UIView { // Example 1: Get all width constraints involving this view // We could have multiple constraints involving width, e.g.: // - two different width constraints with the exact same value // - this view's width equal to another view's width // - another view's height equal to this view's width (this view mentioned 2nd) func getWidthConstraints() -> [NSLayoutConstraint] { return getAllConstraints().filter( { ($0.firstAttribute == .width && $0.firstItem as? UIView == self) || ($0.secondAttribute == .width && $0.secondItem as? UIView == self) } ) } // Example 2: Change width constraint(s) of this view to a specific value // Make sure that we are looking at an equality constraint (not inequality) // and that the constraint is not against another view func changeWidth(to value: CGFloat) { getAllConstraints().filter( { $0.firstAttribute == .width && $0.relation == .equal && $0.secondAttribute == .notAnAttribute } ).forEach( {$0.constant = value }) } // Example 3: Change leading constraints only where this view is // mentioned first. We could also filter leadingMargin, left, or leftMargin func changeLeading(to value: CGFloat) { getAllConstraints().filter( { $0.firstAttribute == .leading && $0.firstItem as? UIView == self }).forEach({$0.constant = value}) } } ``` // edit: Enhanced examples and clarified their explanations in comments
[`stakri`'s answer](https://stackoverflow.com/a/47113933/2463616) is OK, but we can do better by using [`sequence(first:next:)`](https://developer.apple.com/documentation/swift/sequence(first:next:)): ``` extension UIView { var allConstraints: [NSLayoutConstraint] { sequence(first: self, next: \.superview) .flatMap(\.constraints) .lazy .filter { constraint in constraint.firstItem as? UIView == self || constraint.secondItem as? UIView == self } } } ``` Then, if we check both implementations by [swift-benchmark](https://github.com/google/swift-benchmark) by Google we can see that `Sequence` implementation is much faster (almost +50k iterations for the ±same time). ``` running Find All Constraints: Stakri... done! (1778.86 ms) running Find All Constraints: Sequence... done! (1875.20 ms) name time std iterations --------------------------------------------------------------- Find All Constraints.Stakri 3756.000 ns ± 96.67 % 291183 Find All Constraints.Sequence 3727.000 ns ± 117.42 % 342261 ```
23,776,715
I am very new to Android & now I am having weird problem in my Application. It doesn't give me any error in console but it says in emulator that the stopwatch has stopped working... my MainActivity.java ``` import android.os.Bundle; import android.os.SystemClock; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.Chronometer; public class MainActivity extends ActionBarActivity { Chronometer chrono = new Chronometer(this); Button strt, stop, reset; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); chrono=(Chronometer)findViewById(R.id.chronometer1); strt=(Button)findViewById(R.id.button1); stop=(Button)findViewById(R.id.button2); reset=(Button)findViewById(R.id.button3); strt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub chrono.start(); } }); stop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub chrono.stop(); } }); reset.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub chrono.setBase(SystemClock.elapsedRealtime()); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } } ``` fragment\_main.xml ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.stopwatch.MainActivity$PlaceholderFragment" > <Chronometer android:id="@+id/chronometer1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="61dp" android:text="Chronometer" android:textSize="@dimen/abc_action_bar_stacked_max_height" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/chronometer1" android:layout_centerHorizontal="true" android:layout_marginTop="28dp" android:text="Start" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/button1" android:layout_below="@+id/button1" android:layout_marginTop="37dp" android:text="Stop" /> <Button android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/button2" android:layout_below="@+id/button2" android:layout_marginTop="40dp" android:text="Reset" /> </RelativeLayout> ``` activity\_main.xml ``` <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.stopwatch.MainActivity" tools:ignore="MergeRootFrame" /> ``` when I run the application in emulator the log cat shows this... ``` 05-21 03:08:54.440: D/AndroidRuntime(1368): Shutting down VM 05-21 03:08:54.440: W/dalvikvm(1368): threadid=1: thread exiting with uncaught exception (group=0xb2a92ba8) 05-21 03:08:54.460: E/AndroidRuntime(1368): FATAL EXCEPTION: main 05-21 03:08:54.460: E/AndroidRuntime(1368): Process: com.example.stopwatch, PID: 1368 05-21 03:08:54.460: E/AndroidRuntime(1368): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.stopwatch/com.example.stopwatch.MainActivity}: java.lang.NullPointerException 05-21 03:08:54.460: E/AndroidRuntime(1368): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2121) 05-21 03:08:54.460: E/AndroidRuntime(1368): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 05-21 03:08:54.460: E/AndroidRuntime(1368): at android.app.ActivityThread.access$800(ActivityThread.java:135) 05-21 03:08:54.460: E/AndroidRuntime(1368): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 05-21 03:08:54.460: E/AndroidRuntime(1368): at android.os.Handler.dispatchMessage(Handler.java:102) 05-21 03:08:54.460: E/AndroidRuntime(1368): at android.os.Looper.loop(Looper.java:136) 05-21 03:08:54.460: E/AndroidRuntime(1368): at android.app.ActivityThread.main(ActivityThread.java:5017) 05-21 03:08:54.460: E/AndroidRuntime(1368): at java.lang.reflect.Method.invokeNative(Native Method) 05-21 03:08:54.460: E/AndroidRuntime(1368): at java.lang.reflect.Method.invoke(Method.java:515) 05-21 03:08:54.460: E/AndroidRuntime(1368): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 05-21 03:08:54.460: E/AndroidRuntime(1368): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 05-21 03:08:54.460: E/AndroidRuntime(1368): at dalvik.system.NativeStart.main(Native Method) 05-21 03:08:54.460: E/AndroidRuntime(1368): Caused by: java.lang.NullPointerException 05-21 03:08:54.460: E/AndroidRuntime(1368): at android.content.ContextWrapper.getResources(ContextWrapper.java:89) 05-21 03:08:54.460: E/AndroidRuntime(1368): at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:78) 05-21 03:08:54.460: E/AndroidRuntime(1368): at android.view.View.<init>(View.java:3438) 05-21 03:08:54.460: E/AndroidRuntime(1368): at android.view.View.<init>(View.java:3505) 05-21 03:08:54.460: E/AndroidRuntime(1368): at android.widget.TextView.<init>(TextView.java:623) 05-21 03:08:54.460: E/AndroidRuntime(1368): at android.widget.Chronometer.<init>(Chronometer.java:100) 05-21 03:08:54.460: E/AndroidRuntime(1368): at android.widget.Chronometer.<init>(Chronometer.java:84) 05-21 03:08:54.460: E/AndroidRuntime(1368): at com.example.stopwatch.MainActivity.<init>(MainActivity.java:13) 05-21 03:08:54.460: E/AndroidRuntime(1368): at java.lang.Class.newInstanceImpl(Native Method) 05-21 03:08:54.460: E/AndroidRuntime(1368): at java.lang.Class.newInstance(Class.java:1208) 05-21 03:08:54.460: E/AndroidRuntime(1368): at android.app.Instrumentation.newActivity(Instrumentation.java:1061) 05-21 03:08:54.460: E/AndroidRuntime(1368): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2112) 05-21 03:08:54.460: E/AndroidRuntime(1368): ... 11 more 05-21 03:13:55.020: I/Process(1368): Sending signal. PID: 1368 SIG: 9 ``` I don't know what's the problem is. So if anyone could help me out I would be thankful.
2014/05/21
[ "https://Stackoverflow.com/questions/23776715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3659612/" ]
The issue happen right after I changed the V1\_2\_\_books.sql ddl file, There should be a better way to force flyway to recognize the new changes!!! I tried to run mvn flyway:repair but it did not work, I ended up changing the schema url in the application.properties file [datasource.flyway.url] to books2 I removed the below files as well (books is my old schema name ) ``` ~ @~:rm books.mv.db ~ @~:rm -r books.trace.db ``` ```js datasource.flyway.url=jdbc:h2:file:~/books2 datasource.flyway.username=sa datasource.flyway.password= datasource.flyway.driver-class-name=org.h2.Driver ``` I ran the application and BINGO :)
There is yet another solution. You can drop your migration from **schema\_version** table.
68,022,698
I have a list `sample_list` like this: ``` [ { "Meta": { "ID": "1234567", "XXX": "XXX" }, "bbb": { "color":red" }, { "Meta": { "ID": "78945612", "XXX": "XXX" }, "bbb": { "color":"blue" } ] ``` now I want to extract the field "ID" and the values then put them in a `dict` object, I tried: ``` init_dict = {} for item in sample_list: init_dict['ID'] = item['Meta']['ID'] print(init_dict) ``` This returns: ``` {'ID': '1234567'} {'ID': '78945612'} ``` Seems like the second value overwrite the first one, if I print from outside of the iteration: ``` init_dict = {} for item in sample_list: init_dict['ID'] = item['Meta']['ID'] print(init_dict) ``` This only return the last value: ``` {'ID': '78945612'} ``` Combining with the comment below, I realise the logic here is wrong, since the key name is always 'ID', I'VE updated the example in the question, can we take the value for `ID` as the new key and taking the value for `color` as the new value? Expected output is something like ``` {'1234567':'red', '78945612':'blue'} ``` can someone help please? Thanks.
2021/06/17
[ "https://Stackoverflow.com/questions/68022698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10581944/" ]
The problem is in the second line of a for loop. What you are doing is that you are creating a dictionary in this forloop. In any other language, you would get a syntax error, because you are trying to access un-initialised variable (in this case `init_dict`) (in this case, if sample\_list is empty, you will get an error that init\_dict does not exist) ``` for item in sample_list: init_dict = {} // here init_dict['ID'] = item['Meta']['ID'] print(init_dict) ``` Simple fix is to move it outside of a for loop ``` init_dict = {} for item in sample_list: init_dict['ID'] = item['Meta']['ID'] print(init_dict) ``` color edit: ``` init_dict = {} for item in sample_list: init_dict[item['Meta']['ID']] = item['bbb']['color'] print(init_dict) ``` Here you can see that you can use anything as a key, but be careful, the key has to unique, so in this case, ID is a very good key, but if there is a chance that you can get a duplicate ID, I recommend you to find a better key. Also, if you do not need the dictionary in first place, I recommend using just a list of tuples (i.e -> `[(key, val), (key2, val2), (key3, val3)]`. The list has no problem with duplicities
You need to append to your dictionary. The line `init_dict = {}` resets your dictionary. Instead you should do: ``` init_dict = {'ID':[]} for item in sample_list: init_dict['ID'].append(item['Meta']['ID']) print(init_dict) ``` To satisfy the request you made in a comment, you can do this to use the value as a key and then add a colour: ``` init_dict = {} for item in sample_list: init_dict[item['Meta']['ID']] = "red" ```
92,804
I am developing a service that will involve the direct debit of customers' accounts on a routine (weekly, monthly, etc.) basis, and so I'll need to store their information (BSB/routing number and account number) in my database. I am very concerned about security, and so my first thought was to not store this information, but after reading through many other questions about this topic, I have come up with a solution that I think will work - but I would like to run it past you guys to make sure I haven't left open any security holes. When a user registers to the service, it will create a public/private key pair with the private key having a passphrase that the user provides (their account password). The password is hashed with bcrypt, and the public and private keys are stored alongside the password hash in the user table. I will also establish a single admin public/private key pair which will be used when we need to process a direct debit. The public key will be known to the application and database, but the private key will be kept off of the server, so that the data can only be downloaded when encrypted, and then processed elsewhere. An alternative to downloading when encrypted would be to instead upload the private key to the application, decrypt the data for that request only, and then delete the uploaded private key - is this a security hole? When a user registers for direct debit, the service will take the user's public key, and the admin's public key, and encrypt them using [GPG's multiple recipients feature](http://laurent.bachelier.name/2013/03/gpg-encryption-to-multiple-recipients/). To the best of my knowledge this covers the following situations: * If the user wants to view the data, they will need to provide their password to decrypt the information. * If the user wants to add more data, they won't need to provide their password as I just use their public key. * If the admin wants to view the data, they will need to download the information and decrypt it, or else upload their private key (see above). * If the user changes their password, I will just need to update their private key. If they have forgotten their password, the only way I could decrypt their data would be through the admin private key, but as this is kept off-site the data should be deleted. Will there be any concerns if the admin key pair ever becomes compromised (apart from the obvious) and I needed to generate a new admin key pair and then re-encrypt all of the stored data? Are there any security holes in this design? I am admittedly no expert but I've tried to do my best with researching this, and would now love to get some input. I have also looked in to services like [Authorize.net's Customer Information Manager (CIM)](http://developer.authorize.net/api/cim/) but as far as I can see you need to be using their service to collect payments, when instead we have already established our own merchant to do this at a cheaper rate, and so we just need a secure information storage service. The service will be using HTTPS, and running on Ubuntu 12.04, with PHP and MySQL, if that helps. Any advice you can give will be greatly appreciated! Thanks
2015/07/01
[ "https://security.stackexchange.com/questions/92804", "https://security.stackexchange.com", "https://security.stackexchange.com/users/79882/" ]
> > The password is hashed with bcrypt, and the public and private keys > are stored alongside the password hash in the user table. > > > Storing the private key means a compromise of the database would allow attacker to decrypt the bank information. You might as well store the bank information in plain text. Why exactly would the bank information need to be encrypted by the user's key anyways? Is the user going to request that information "please tell me the bank account I told you about earlier"?
Yes, use these functions to encrypt & decrypt the data from the DB. ``` static function encrypt($s) { $keyHex = getenv('APP_KEY'); if (!$keyHex) { Yii::error ("Could not retrieve environment variable APP_KEY"); return null; } $key = pack('H*', $keyHex); $iv = mcrypt_create_iv(256/8); // 256 bit / 8 bit/byte = 32 $cipherText = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $s, 'cbc', $iv); $cipherText64 = base64_encode($iv.$cipherText); return $cipherText64; } static function decrypt($s) { $keyHex = getenv('APP_KEY'); if (!$keyHex) { Yii::error ("Could not retrieve environment variable APP_KEY"); return null; } $key = pack('H*', $keyHex); $cipher = base64_decode($s); $iv = substr($cipher, 0, 256/8); $cipher = substr($cipher, 256/8); // strip off IV from front $text = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $cipher, "cbc", $iv); $text = rtrim($text, "\0"); // mcrypt leaves null padding on the text return $text; } ``` They currently get the key from an environment variable, so you will have to modify them to get the key from the user. I assume you will want to have the user type in the password each & every time they access their bank details. You don't have to use public/private encryption. That is only good for small values, but bank account numbers are probably small enough. The key should be a 64 character hex string, or a 32 byte key, or a 256 bit key. It has to be securely random though. If you let the user supply a password and turn it into a key with a password-based-key-derivation-function (PBKDF), then someone could brute force attack the database.
7,878,420
I created function for my blog. Model - ``` public function get_article($nosaukums) { $query = DB::query(Database::SELECT, 'SELECT * FROM ieraksti WHERE virsraksts = :nosaukums') ->parameters(array(':nosaukums' => $nosaukums))->execute(); return $query; } ``` Controller - ``` public function action_article() { Route::set('article', 'article/(name)', array('name' => '.+')) ->defaults(array( 'controller' => 'index', 'action' => 'article', )); $this->template->content = View::factory('index/article') ->set('query', Model::factory('index')->get_article($nosaukums)); } ``` and view - ``` <?php foreach($nosaukums as $article) { echo '<h3>'.$article['virsraksts'].'</h3>'; } ?> ``` I want to url - domain.com/article/name\_of\_article, but domain.com/article is not working - error `HTTP_Exception_404 [ 404 ]: The requested URL article was not found on this server.` Why I get this error?
2011/10/24
[ "https://Stackoverflow.com/questions/7878420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/914143/" ]
Probably the easiest way to do this is to use [`scipy.interpolate.interp2d()`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp2d.html): ``` # construct interpolation function # (assuming your data is in the 2-d array "data") x = numpy.arange(data.shape[1]) y = numpy.arange(data.shape[0]) f = scipy.interpolate.interp2d(x, y, data) # extract values on line from r1, c1 to r2, c2 num_points = 100 xvalues = numpy.linspace(c1, c2, num_points) yvalues = numpy.linspace(r1, r2, num_points) zvalues = f(xvalues, yvalues) ```
Here is a method without using scipy package(s). It should run much faster and is easy to understand. Basically, any pair of coordinates between point 1 (pt1) and point 2 (pt2) can be converted to x- and y- pixel integers, so we don't need any interpolation. ``` import numpy as np from PIL import Image import matplotlib.pyplot as plt def euclideanDistance(coord1,coord2): return np.sqrt((coord1[0]-coord2[0])**2+(coord1[1]-coord2[1])**2) def getLinecut(image,X,Y,pt1,pt2): row_col_1, row_col_2 = getRowCol(pt1,X,Y), getRowCol(pt2,X,Y) row1,col1 = np.asarray(row_col_1).astype(float) row2,col2 = np.asarray(row_col_2).astype(float) dist = np.sqrt((pt1[0]-pt2[0])**2+(pt1[1]-pt2[1])**2) N = int(euclideanDistance(row_col_1,row_col_2))#int(np.sqrt((row1-row2)**2+(col1-col2)**2)) rowList = [int(row1 + (row2-row1)/N*ind) for ind in range(N)] colList = [int(col1 + (col2-col1)/N*ind) for ind in range(N)] distList = [dist/N*ind for ind in range(N)] return distList,image[rowList,colList]#rowList,colList def getRowCol(pt,X,Y): if X.min()<=pt[0]<=X.max() and Y.min()<=pt[1]<=Y.max(): pass else: raise ValueError('The input center is not within the given scope.') center_coord_rowCol = (np.argmin(abs(Y-pt[1])),np.argmin(abs(X-pt[0]))) return center_coord_rowCol image = np.asarray(Image.open('./Picture1.png'))[:,:,1] image_copy = image.copy().astype(float) X = np.linspace(-27,27,np.shape(image)[1])#[::-1] Y = np.linspace(-15,15,np.shape(image)[0])[::-1] pt1, pt2 = (-12,-14), (20,13) distList, linecut = getLinecut(image_copy,X,Y,pt1,pt2) plt.plot(distList, linecut) plt.figure() plt.pcolormesh(X,Y,image_copy) plt.plot([pt1[0],pt2[0]],[pt1[1],pt2[1]],color='red') plt.gca().set_aspect(1) ``` [![enter image description here](https://i.stack.imgur.com/95fJ9.png)](https://i.stack.imgur.com/95fJ9.png) Picture1.png figure used: [![enter image description here](https://i.stack.imgur.com/oAgTi.png)](https://i.stack.imgur.com/oAgTi.png) See here for more details: <https://github.com/xuejianma/fastLinecut_radialLinecut> There is another function of the code: taking an average of several angle-evenly-spaced lines. [![enter image description here](https://i.stack.imgur.com/ITmzk.png)](https://i.stack.imgur.com/ITmzk.png)
1,316,983
Does OpenID improve the user experience? **Edit** Not to detract from the other comments, but I got one really good reply below that outlined 3 advantages of OpenID in a rational bottom line kind of way. I've also heard some whisperings in other comments that you can get access to some details on the user through OpenID (name? email? what?) and that using that it might even be able to simplify the registration process by not needing to gather as much information. Things that definitely need to be gathered in a checkout process: * Full name * Email (I'm pretty sure I'll have to ask for these myself) * Billing address * Shipping address * Credit card info There may be a few other things that are interesting from a marketing point of view, but I wouldn't ask the user to manually enter anything not absolutely required during the checkout process. So what's possible in this regard? **/Edit** (You may have noticed stackoverflow uses OpenID) It seems to me it is easier and faster for the user to simply enter a username and password in a signup form they have to go through anyway. I mean you don't avoid entering a username and password either with OpenID. But you avoid the confusion of choosing a OpenID provider, and the trip out to and back from and external site. With Microsoft making Live ID an OpenID provider ([More Info](http://winliveid.spaces.live.com/blog/cns!AEE1BB0D86E23AAC!1745.entry)), bringing on several hundred million additional accounts to those provided by Google, Yahoo, and others, this question is more important than ever. I have to require new customers to sign up during the checkout process, and it is absolutely critical that the experience be as easy and smooth as possible, every little bit harder it becomes translates into lost sales. No geek factor outweighs cold hard cash at the end of the day :) OpenID seems like a nice idea, but the implementation is of questionable value. What are the advantages of OpenID and is it really worth it in my scenario described above?
2009/08/22
[ "https://Stackoverflow.com/questions/1316983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/152580/" ]
It's great not having to make too many user accounts all around. All those passwords.... then again, I far prefer a solution like 1Password for the Mac. OpenID is better for sites I'll return to than a separate username, though
I would agree with you that ease of use for your users is something to heavily consider. Your audience is another thing to consider. As OpenID becomes more accepted this will be less and less of an issue. If you are working on a project where you know the majority of your users will not even know what OpenID is then perhaps you should steer away from it. Stackoverflow was my first intro into OpenID and I'm a geek.... I created the account after avoiding it for a few days and reading up on it. I finally jumped in but I would venture to say non-geek types would perhaps not. Now, I love the idea and would love to see it everywhere also. If you can do both your own and OpenID, offer both. I think that would be the best of both worlds. You could point users to the goodness of OpenID but still let them go the other way. If you see a high adoption rate with OpenID you could eventually only offer it.
19,352,934
These two function ares in my Python programming book, and I just can't quite get why they're doing what they're doing. I really wanna understand, so any explanation would be great. ``` def example(aString, index): if index == len(aString): return "" else: return aString[index] + example(aString, index + 1) ``` and... ``` def example(aString, index): if index < len(aString): example(aString, index +1) print(aString[index], end="") ```
2013/10/14
[ "https://Stackoverflow.com/questions/19352934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2877503/" ]
First, calculate the distance you will travel based on your current speed and your known time interval ("next time"): ``` distance = speed * time ``` Then you can use this formula to calculate your new position (lat2/lon2): ``` lat2 =asin(sin(lat1)*cos(d)+cos(lat1)*sin(d)*cos(tc)) dlon=atan2(sin(tc)*sin(d)*cos(lat1),cos(d)-sin(lat1)*sin(lat2)) lon2=mod( lon1-dlon +pi,2*pi )-pi ``` For an implementation in Javascript, see the function `LatLon.prototype.destinationPoint` on [this page](http://www.movable-type.co.uk/scripts/latlong.html) **Update** for those wishing a more fleshed-out implementation of the above, here it is in Javascript: ``` /** * Returns the destination point from a given point, having travelled the given distance * on the given initial bearing. * * @param {number} lat - initial latitude in decimal degrees (eg. 50.123) * @param {number} lon - initial longitude in decimal degrees (e.g. -4.321) * @param {number} distance - Distance travelled (metres). * @param {number} bearing - Initial bearing (in degrees from north). * @returns {array} destination point as [latitude,longitude] (e.g. [50.123, -4.321]) * * @example * var p = destinationPoint(51.4778, -0.0015, 7794, 300.7); // 51.5135°N, 000.0983°W */ function destinationPoint(lat, lon, distance, bearing) { var radius = 6371e3; // (Mean) radius of earth var toRadians = function(v) { return v * Math.PI / 180; }; var toDegrees = function(v) { return v * 180 / Math.PI; }; // sinφ2 = sinφ1·cosδ + cosφ1·sinδ·cosθ // tanΔλ = sinθ·sinδ·cosφ1 / cosδ−sinφ1·sinφ2 // see mathforum.org/library/drmath/view/52049.html for derivation var δ = Number(distance) / radius; // angular distance in radians var θ = toRadians(Number(bearing)); var φ1 = toRadians(Number(lat)); var λ1 = toRadians(Number(lon)); var sinφ1 = Math.sin(φ1), cosφ1 = Math.cos(φ1); var sinδ = Math.sin(δ), cosδ = Math.cos(δ); var sinθ = Math.sin(θ), cosθ = Math.cos(θ); var sinφ2 = sinφ1*cosδ + cosφ1*sinδ*cosθ; var φ2 = Math.asin(sinφ2); var y = sinθ * sinδ * cosφ1; var x = cosδ - sinφ1 * sinφ2; var λ2 = λ1 + Math.atan2(y, x); return [toDegrees(φ2), (toDegrees(λ2)+540)%360-180]; // normalise to −180..+180° } ```
Based on the answer of @clody96 and @mike, here is an implementation in **R** using a data.frame with **velocity** and **timesteps** instead of distance: ``` points = data.frame( lon = seq(11, 30, 1), lat = seq(50, 59.5, 0.5), bea = rep(270, 20), time = rep(60,20), vel = runif(20,1000, 3000) ) ## lat, lng in degrees. Bearing in degrees. Distance in m calcPosBear = function(df) { earthR = 6371000; ## Units meter, seconds and meter/seconds df$dist = df$time * df$vel lat2 = asin(sin( pi / 180 * df$lat) * cos(df$dist / earthR) + cos(pi / 180 * df$lat) * sin(df$dist / earthR) * cos(pi / 180 * df$bea)); lon2 = pi / 180 * df$lon + atan2(sin( pi / 180 * df$bea) * sin(df$dist / earthR) * cos( pi / 180 * df$lat ), cos(df$dist / earthR) - sin( pi / 180 * df$lat) * sin(lat2)); df$latR = (180 * lat2) / pi df$lonR = (180 * lon2) / pi return(df); }; df = calcPosBear(points) plot(df$lon, df$lat) points(df$lonR, df$latR, col="red") ``` --- Which brings the same result as for @clody96: ``` points = data.frame( lon = 25, lat = 60, bea = 30, time = 1000, vel = 1 ) df = calcPosBear(points) df ``` > > > ``` > lon lat bea time vel dist latR lonR > 1 25 60 30 1000 1 1000 60.00778805 25.00899533 > > ``` > >
47,344,571
I am able to draw checkbox in Github README.md lists using ``` - [ ] (for unchecked checkbox) - [x] (for checked checkbox) ``` But this is not working in table. Does anybody know how to implement checkbox or checkmark in GitHub Markdown table?
2017/11/17
[ "https://Stackoverflow.com/questions/47344571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8253993/" ]
``` |checked|unchecked|crossed| |---|---|---| |&check;|_|&cross;| |&#x2611;|&#x2610;|&#x2612;| ``` | checked | unchecked | crossed | | --- | --- | --- | | ✓ | \_ | ✗ | | ☑ | ☐ | ☒ | Where * ✓ via [HTML Entity Code](https://www.toptal.com/designers/htmlarrows/symbols/check-mark) * ✗ via [HTML Entity Code](https://www.toptal.com/designers/htmlarrows/symbols/ballot-x/) * \_ via underscore character * ☑, ☐ and ☒ via [HTML ballot box codes](https://www.toptal.com/designers/htmlarrows/symbols/) * table via markdown [table syntax](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet#tables).
Following is how I draw a checkbox in a table! ``` | Checkbox Experiments | [ ] unchecked header | [x] checked header | | ---------------------|:---------------------:|:-------------------:| | checkbox | [ ] row | [x] row | ``` Displays like this: [![enter image description here](https://i.stack.imgur.com/UsnDw.png)](https://i.stack.imgur.com/UsnDw.png)
17,745,148
I can understand simple recursion, such as: ``` def count(n): if n <= 0: return else: print n count(n-1) count(3) ``` However, when faced with more complicated code, such as, an implementation of Koch snowflake: ``` def koch(order, size): if order == 0: t.forward(size) else: koch(order-1, size/3) t.left(60) koch(order-1, size/3) t.right(120) koch(order-1, size/3) t.left(60) koch(order-1, size/3) koch(1, 100) ``` I get confused. I do not understand how to follow these multiple recursive function calls.
2013/07/19
[ "https://Stackoverflow.com/questions/17745148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1539759/" ]
Your Koch snowflake example is a good one. What does the snowflake consist of? In the first iteration (`order == 0`), it starts out as a simple line. This is the base case. ``` ________ ``` Now, for the next level of recursion (`order == 1`), that base case is split into four sub-lines that form an inverted `V`. To achieve this `V`, you need to build four lines at the appropriate angles to each other (for which you need the `t.left(60)` and similar commands). Each of these lines is (regarded by itself) an instance of the base case, again. It's just three times smaller. That's what you see in `koch(order-1, size/3)`. ``` /\ __/ \__ ``` Now imagine the next level of recursion - each line is again split up into four sublines. The pattern continues...
The python tutor web site can help in visualising program flows <http://www.pythontutor.com/>
45,497,031
If the total *content height* of the parent is 10,000px but the `overflow: auto` element is *rendered* with a height of 700px how do I force the `aside` child element to dynamically render as 10,000px *instead* of the default 700px? You can see the white background the moment you begin to scroll [the Fiddle](https://jsfiddle.net/4m1L2tLh/). * May not add any more elements (`::after` and `::before` are acceptable though). * The `aside` element must have it's content scroll with `main` element's content via the `#body` element (no `position: fixed;`). * The `aside` element must have it's `background-color` stretch from the very top at 0px to the very bottom (e.g. 5,000px or 10,000px) far *below* the initial visible fold. * The `aside` element must not have it's own `overflow: auto;`. * Dynamic (for the lesser knowledged) implies we can *not* set a static `height`, e.g. `height: 10000px` as we will *not* know what the rendered height will be. In my example the moment you begin to scroll the green `background-color` ends, I want to make the `aside` element stretch all the way to the content bottom. ```html <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>Overflow Flex Box Issue</title> <style type="text/css"> * {border: 0; margin: 0; padding: 0;} aside { background-color: #afa; order: 2; width: 20%; } body { display: flex; flex-direction: column; height: 100%; } body > header { align-self: stretch; background-color: #faa; flex: 0 1 auto; min-height: 56px; order: 1; } body > footer { align-self: auto; background-color: #aaf; flex: 0 1 auto; min-height: 36px; order: 2; } html {height: 100%;} main { background-color: #cfc; order: 1; width: 80%; } #body { display: flex; order: 2; overflow: auto; } </style> </head> <body> <div id="body"> <main> <article> <p>article</p> <p>article</p> <p>article</p> <div style="height: 10000px;">10,000px</div> </article> </main> <aside><p>&#60;aside&#62;, 100% height only of visible area, it <em>should</em> be <em>100% of total parent height</em>.</p></aside> </div> <header>The body &#62; header element; element 2, order: 1;.</header> <footer>The body &#62; footer element; element 3, order: 3;.</footer> </body> </html> ```
2017/08/04
[ "https://Stackoverflow.com/questions/45497031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/606371/" ]
This is *not* the way I intended to achieve the result as I would like to set `background-image` on the `#body` in many cases though it may be acceptable subjective to how I handle things, here is the [Fiddle](https://jsfiddle.net/4m1L2tLh/2/). I'm certain that this issue will be resolved at some point in the future. ```css #body { background-image: linear-gradient(to right, #cfc 0%, #cfc 79%, #afa calc(79% + 4px), #afa 100%); } ``` ```html <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>Overflow Flexbox Issue</title> <style type="text/css"> * {border: 0; margin: 0; padding: 0; scroll-behavior: smooth;} aside { background-color: ; order: 2; width: 20%; } body { display: flex; flex-direction: column; height: 100%; overflow: hidden; } body > header { align-self: stretch; background-color: #faa; flex: 0 1 auto; min-height: 56px; order: 1; } body > footer { align-self: auto; background-color: #aaf; flex: 0 1 auto; min-height: 36px; order: 2; } html {height: 100%;} main { order: 1; width: 80%; } #body { background-image: linear-gradient(to right, #cfc 0%, #cfc 79%, #afa calc(79% + 4px), #afa 100%); display: flex; order: 2; overflow: auto; } </style> </head> <body> <div id="body"> <main> <article> <p>article</p> <p>article</p> <p>article</p> <div style="height: 10000px;">10,000px</div> </article> </main> <aside><p>&#60;aside&#62;, 100% height only of visible area, it <em>should</em> be <em>100% of total parent height</em>.</p></aside> </div> <header>The body &#62; header element; element 2, order: 1;.</header> <footer>The body &#62; footer element; element 3, order: 3;.</footer> </body> </html> ```
Actually, there's a pretty simple solution with just CSS and without touching the markup. * `display:table-cell` for the `aside` and the `main` * omit the display flex on the `#body` Here's a fully functional snippet: ```html <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>Overflow Flex Box Issue</title> <style type="text/css"> * {border: 0; margin: 0; padding: 0;} aside { background-color: #afa; order: 2; width: 20%; display: table-cell; } body { display: flex; flex-direction: column; height: 100%; } body > header { align-self: stretch; background-color: #faa; flex: 0 1 auto; min-height: 56px; order: 1; } body > footer { align-self: auto; background-color: #aaf; flex: 0 1 auto; min-height: 36px; order: 2; } html {height: 100%;} main { background-color: #cfc; order: 1; width: 80%; display: table-cell; } #body { order: 2; overflow: auto; } </style> </head> <body> <div id="body"> <main> <article> <p>article</p> <p>article</p> <p>article</p> <div style="height: 10000px;">10,000px</div> </article> </main> <aside><p>&#60;aside&#62;, 100% height only of visible area, it <em>should</em> be <em>100% of total parent height</em>.</p></aside> </div> <header>The body &#62; header element; element 2, order: 1;.</header> <footer>The body &#62; footer element; element 3, order: 3;.</footer> </body> </html> ```
9,312
Is there an existing plugin or a built-in way of adding an "add me to mailing list" button to a contact form? Not just that it gets stored in the database as a lightswitch, but so it actually subscribes them (or at least sends them a sign-up confirmation email)?
2015/04/20
[ "https://craftcms.stackexchange.com/questions/9312", "https://craftcms.stackexchange.com", "https://craftcms.stackexchange.com/users/642/" ]
If you're using a Craft Client or Craft Pro, you can save your entry as a draft and review it later. ![enter image description here](https://i.stack.imgur.com/CH23G.png) This isn't foolproof either. If you wanted to really try to restrict yourself, you could set up another user account that doesn't have privileges to "Publish live changes." ![enter image description here](https://i.stack.imgur.com/rwUrR.png) But again, this would require either a Craft Client or Craft Pro license.
There's no setting to define a default master status for entries, but there's locale specific statuses that can be set to a default in the section's settings. This requires Craft Pro and more than one locale configured though.
26,808,657
I have a date in YYYY.MM.DD HH:SS format (e.g. 2014.02.14 13:30). I'd like to convert it in seconds since epoch using the date command. The command date -d"2014.02.14 13:30" +%s won't work, because of the dots separation. Any Ideas?
2014/11/07
[ "https://Stackoverflow.com/questions/26808657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3762096/" ]
Why don't you make the date format acceptable? Just replace dots with dashes: ``` $ date --date="`echo '2014.02.14 13:30' | sed 's/\./-/g'`" +%s 1392370200 ``` Here I first change the format: ``` $ echo '2014.02.14 13:30' | sed 's/\./-/g' 2014-02-14 13:30 ``` and then use the result as a parameter for `date`. Note that the result depends on your timezone.
Perl: does not require you to munge the string ``` d="2014.02.14 13:30" epoch_time=$(perl -MTime::Piece -E 'say Time::Piece->strptime(shift, "%Y.%m.%d %H:%M")->epoch' "$d") echo $epoch_time ``` ``` 1392384600 ``` Timezone: Canada/Eastern
28,284,608
I have a DialogFragment which I want to show in fullscreen. I do however still want a StatusBar present, and the hardware buttons at the bottom. I also want to set a background color of the StatusBar (for Lollipop). My problem is that if I set the following flags in the DialogFragment: ``` getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); ``` Both the StatusBar and Hardware keyboard becomes translucent, and the DialogFragment stretches behind these. Here is the code, which has been greatly reduced to become readable: ``` public class CardDetailsDialog extends DialogFragment { Setup parameters... public static CardDetailsDialog newInstance(final long cardId, final long projectId){ CardDetailsDialog frag = new CardDetailsDialog(); frag.setStyle(DialogFragment.STYLE_NORMAL, R.style.CardDetailsDialogStyle); return frag; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if(getDialog() != null) { getDialog().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); getDialog().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); getDialog().getWindow().getAttributes().windowAnimations = R.style.DialogSlideAnimation; getDialog().getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); getDialog().getWindow().setStatusBarColor(Color.RED); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view = inflater.inflate(R.layout.card_details, container, false); Handle everything that happens inside the view... return view; } } ``` Here is the referred theme: ``` <style name="CardDetailsDialogStyle" parent="@style/Theme.AppCompat.Light.Dialog" > <item name="android:windowBackground">@null</item> <item name="android:windowNoTitle">true</item> <item name="android:windowFrame">@null</item> <item name="android:windowIsFloating">true</item> <item name="android:windowContentOverlay">@null</item> <item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item> <item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item> </style> ``` And the style of the fragment: ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/pp.whiteBackgroundColor" > <android.support.v7.widget.Toolbar xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/card_details_toolbar" android:layout_height="wrap_content" android:layout_width="match_parent" android:layout_alignParentTop="true" app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" app:popupTheme="@style/PopupMenutheme"> </android.support.v7.widget.Toolbar> <ScrollView android:id="@+id/details_scrollview" android:layout_height="wrap_content" android:layout_width="match_parent"> All subview elements here... </ScrollView> </RelativeLayout> ``` This is the result: ![Screenshot](https://i.stack.imgur.com/cppoj.png) As you can see, the ToolBar extends over the StatusBar and hardware buttons. I don't know if I am approaching this correctly. Am I missing something? **EDIT** This is what the same view look likes when I remove ``` getDialog().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); ``` ![enter image description here](https://i.stack.imgur.com/HiSv9.png)
2015/02/02
[ "https://Stackoverflow.com/questions/28284608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4066691/" ]
You have to set fitsystemwindows = true. Other way is to add a Space with 0dp and change its height to 25dp when the dialog is going to show. To change the space size, use layout params, check this post: [How to create a RelativeLayout programmatically with two buttons one on top of the other?](https://stackoverflow.com/questions/4979212/programmatically-creating-a-relativelayout-in-android)
``` <style name="DialogTheme" parent="Theme.AppCompat.Light.NoActionBar"> <item name="android:windowTranslucentStatus">true</item> <item name="android:windowNoTitle">true</item> <item name="android:windowFullscreen">true</item> <item name="android:windowIsFloating">false</item> </style> ```
59,265,908
I need a little help getting to display my ngFor data in a new container div when the length gets to four. hard coding the data in several div is easier, but using ngFor displays the data in a single container div. the code below there is supposed to be four **book-section-subGrid DIV** in a **book-section-grid DIV** **My attempt** ``` <div class="book-section-grid"> <div *ngFor="let book of books" class="book-section-subGrid"> <img src="assets/images/book1-1.png" alt=""> <h4>{{book?.title}}</h4> <span>by <a href="#">Michael Freeman</a></span> </div> </div> ``` **What i want to achieve** ```css .book-section-grid { display: flex; margin-bottom: 100px; } ``` ```html <!-- 1st Section --> <div class="book-section-grid"> <div class="book-section-subGrid"> <img height="50" width="50" src="https://images.pexels.com/photos/1226302/pexels-photo-1226302.jpeg" alt=""> <h4>Photographer’s trouble shooter</h4> <span>by <a href="#">Michael Freeman</a></span> </div> <div class="book-section-subGrid"> <img height="50" width="50" src="https://images.pexels.com/photos/1226302/pexels-photo-1226302.jpeg" alt=""> <h4>Photographer’s trouble shooter</h4> <span>by <a href="#">Michael Freeman</a></span> </div> <div class="book-section-subGrid"> <img height="50" width="50" src="https://images.pexels.com/photos/1226302/pexels-photo-1226302.jpeg" alt=""> <h4>Photographer’s trouble shooter</h4> <span>by <a href="#">Michael Freeman</a></span> </div> <div class="book-section-subGrid"> <img height="50" width="50" src="https://images.pexels.com/photos/1226302/pexels-photo-1226302.jpeg" alt=""> <h4>Photographer’s trouble shooter</h4> <span>by <a href="#">Michael Freeman</a></span> </div> </div> <!-- 2nd Section --> <div class="book-section-grid"> <div class="book-section-subGrid"> <img height="100" width="100" src="https://images.pexels.com/photos/1226302/pexels-photo-1226302.jpeg" alt=""> <h4>Photographer’s trouble shooter</h4> <span>by <a href="#">Michael Freeman</a></span> </div> <div class="book-section-subGrid"> <img height="100" width="100" src="https://images.pexels.com/photos/1226302/pexels-photo-1226302.jpeg" alt=""> <h4>Photographer’s trouble shooter</h4> <span>by <a href="#">Michael Freeman</a></span> </div> <div class="book-section-subGrid"> <img height="100" width="100" src="https://images.pexels.com/photos/1226302/pexels-photo-1226302.jpeg" alt=""> <h4>Photographer’s trouble shooter</h4> <span>by <a href="#">Michael Freeman</a></span> </div> <div class="book-section-subGrid"> <img height="100" width="100" src="https://images.pexels.com/photos/1226302/pexels-photo-1226302.jpeg" alt=""> <h4>Photographer’s trouble shooter</h4> <span>by <a href="#">Michael Freeman</a></span> </div> </div> ```
2019/12/10
[ "https://Stackoverflow.com/questions/59265908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10008455/" ]
Try like this ``` <div class="book-section-grid"> <div *ngFor="let book of books; let index = index;" class="book-section-subGrid"> <div *ngIf="index < 5; else elseBlock"> <h4>{{book?.title}}</h4> <img height="100" width="100" src="https://images.pexels.com/photos/1226302/pexels-photo-1226302.jpeg" alt=""> <span>by <a href="#">Michael Freeman</a></span> </div> <ng-template #elseBlock> <h1>{{book?.title}}</h1> <img height="50" width="50"src="https://images.pexels.com/photos/1226302/pexels-photo-1226302.jpeg" alt=""> <span>by <a href="#">Michael Freeman</a></span> </ng-template> </div> </div> ```
I think you can make use of angular [slice pipe](https://angular.io/api/common/SlicePipe). You can find a sample implementation [here](https://angular.io/api/common/SlicePipe).
43,455,380
``` class Base rand bit b; // constraint c1 { every 5th randomization should have b =0;} endclass ``` I know I can make a static count variable and update that count variable and then, in constraint I can check if count%5 is zero, then make b=0, but is there a better way to do that? Thanks.
2017/04/17
[ "https://Stackoverflow.com/questions/43455380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7595813/" ]
There's no need to make count static, just non-random. ``` class Base; rand bit b; int count; constraint c1 { count%5 -> b==0;} function post_randomize(); count++; endfunction endclass ```
If you know the upper limit of `b`, then you can write a constraint like follow. ``` constraint abc { b dist {0:=20, 1:=80} } ``` This will make weight of `0` to `20` and, weight of `1` to `80`. So in this way, 0 will occur once in every 5 randomization.
64,485,104
Get this error on our Domino server log: PROTON: Handshake failed with fatal error SSL\_ERROR\_SSL: error:100000f7:SSL routines:OPENSSL\_internal:WRONG\_VERSION\_NUMBER. [D:\jenkins\workspace\domino-app-dev\fed-protected\grpc\grpc\src\core\tsi\ssl\_transport\_security.cc:1233] I am taking the 3CUG courses in google classroom. When I try to test the code on localhost:3002/api/dql (as per instructions) I get the error above and this returned to the browser: {"message":"gRPC client error","code":"ERR\_INTERNAL\_ERROR","cause":{"name":"GrpcError","cause":{"code":2,"metadata":{"\_internal\_repr":{},"flags":0},"details":"Stream removed"}},"stack":"Error\n at new DominoDbError (C:\Users\XXXX\Documents\SourceTree\proton\_test\node\_modules\@domino\domino-db\src\domino-db-error.js:6:16)\n at wrapError (C:\Users\XXXX\Documents\SourceTree\proton\_test\node\_modules\@domino\domino-db\src\requests\grpc\utils\grpc-helpers.js:157:10)\n at C:\Users\XXXX\Documents\SourceTree\proton\_test\node\_modules\@domino\domino-db\src\requests\grpc\utils\bulk-document.js:210:18\n at Object.onReceiveStatus (C:\Users\XXXX\Documents\SourceTree\proton\_test\node\_modules\grpc\src\client\_interceptors.js:1210:9)\n at InterceptingListener.\_callNext (C:\Users\XXXX\Documents\SourceTree\proton\_test\node\_modules\grpc\src\client\_interceptors.js:568:42)\n at InterceptingListener.onReceiveStatus (C:\Users\XXXX\Documents\SourceTree\proton\_test\node\_modules\grpc\src\client\_interceptors.js:618:8)\n at callback (C:\Users\XXXX\Documents\SourceTree\proton\_test\node\_modules\grpc\src\client\_interceptors.js:847:24)"} Any ideas as to what is causing this?
2020/10/22
[ "https://Stackoverflow.com/questions/64485104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3470383/" ]
This ususally is a problem with the server config missing the secure flag like so, please check if you have set the flag and import the certificates correctly: ``` const serverConfig = { hostName: config.protonHostName, // DNS (!) Host name of your server connection: { port: config.protonHostPort, // Proton port on your server secure: true, }, credentials: { rootCertificate, clientCertificate, clientKey } }; ```
If this problem is related to lection 404 of the course, you have to turn off SSL for the proton task. If you're using AppDevPack 1.0.6 or higher you can do this in the `adpconfig.nsf` file. SSL will be configured in chapter 5. For turning off ssl for the proton task open adpconfig.nsf. Then open the configuration document for your server. [![enter image description here](https://i.stack.imgur.com/SkJqS.png)](https://i.stack.imgur.com/SkJqS.png) Double click into the document to edit. Uncheck ssl and click save & exit. After that a prompt asks to restart proton click yes and wait for the proton task to be restarted. [![Edit proton config](https://i.stack.imgur.com/TGk1I.png)](https://i.stack.imgur.com/TGk1I.png)
8,882,104
I have a pointer array defined declared as ``` char (*c)[20] ``` When allocating memory using malloc ``` c=malloc(sizeof(char)*20); ``` or ``` c=(char*)malloc(sizeof(char)*20); ``` I get a warning as "Suspicious pointer conversion" Why?
2012/01/16
[ "https://Stackoverflow.com/questions/8882104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/553406/" ]
First of all, make sure you have `stdlib.h` included. Secondly, try rewriting it as ``` c = malloc(sizeof *c); ``` I suspect you're getting the diagnostic on the second case because `char *` and `char (*)[20]` are not compatible types. Don't know why the first case would complain (at compile-time, anyway) unless you don't have `stdlib.h` included. **edit** Remember that you will have to dereference the pointer before applying the subscript; that is, your expressions will have to be ``` (*c)[i] = val; printf("%c", (*c)[j]); ``` etc. Alternately you could write `c[0][i]` in place of `(*c)[i]`, but that's probably *more* confusing if `c` isn't supposed to act like a 2-d array.
For an array of 20 characters, counting the NUL terminator, you don't need a pointer ``` char array[20]; ``` for a pointer to char, you don't need an array ``` char *pointer; ``` A pointer to char can point to an array ``` pointer = array; ``` to part of the array (assuming no 'funny' business with the NUL terminator) ``` pointer = &array[10]; ``` or to a bunch of bytes allocated with malloc ``` pointer = malloc(20); ```
10,193,978
I'm trying to compare column a in Sheet 1 with column a in Sheet 2, then copy corresponding values in column b from sheet 1 to column b in Sheet 2 (where the column a values match). I've been trying to read up on how to do this, but I'm not sure if I should be trying to create a macro, or if there's a simpler way to do this, maybe VLOOKUP or MATCH? I'm really not familiar with how these functions work though. Also, if it makes a difference, there will be repeated values in column b of Sheet 2. Sheet 1 ``` 12AT8001 1 12AT8002 2 12AT8003 3 12AT8004 4 12AT8005 5 12AT8006 6 ``` Sheet 2 ``` 12AT8001 12AT8001 12AT8001 12AT8001 12AT8001 12AT8002 12AT8002 12AT8002 12AT8002 12AT8002 12AT8003 12AT8003 12AT8003 12AT8003 12AT8003 ```
2012/04/17
[ "https://Stackoverflow.com/questions/10193978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/431060/" ]
As kmcamara discovered, this is exactly the kind of problem that VLOOKUP is intended to solve, and using vlookup is arguably the simplest of the alternative ways to get the job done. In addition to the three parameters for lookup\_value, table\_range to be searched, and the column\_index for return values, VLOOKUP takes an optional fourth argument that the Excel documentation calls the "range\_lookup". Expanding on deathApril's explanation, if this argument is set to TRUE (or 1) or omitted, the table range must be sorted in ascending order of the values in the first column of the range for the function to return what would typically be understood to be the "correct" value. Under this default behavior, the function will return a value based upon an exact match, if one is found, or an approximate match if an exact match is not found. If the match is approximate, the value that is returned by the function will be based on the next largest value that is less than the lookup\_value. For example, if "12AT8003" were missing from the table in Sheet 1, the lookup formulas for that value in Sheet 2 would return '2', since "12AT8002" is the largest value in the lookup column of the table range that is less than "12AT8003". (VLOOKUP's default behavior makes perfect sense if, for example, the goal is to look up rates in a tax table.) However, if the fourth argument is set to FALSE (or 0), VLOOKUP returns a looked-up value only if there is an exact match, and an error value of #N/A if there is not. It is now the usual practice to wrap an exact VLOOKUP in an IFERROR function in order to catch the no-match gracefully. Prior to the introduction of IFERROR, no matches were checked with an IF function using the VLOOKUP formula once to check whether there was a match, and once to return the actual match value. Though initially harder to master, deusxmach1na's proposed solution is a variation on a powerful set of alternatives to VLOOKUP that can be used to return values for a column or list to the *left* of the lookup column, expanded to handle cases where an exact match on more than one criterion is needed, or modified to incorporate OR as well as AND match conditions among multiple criteria. Repeating kcamara's chosen solution, the VLOOKUP formula for this problem would be: ``` =VLOOKUP(A1,Sheet1!A$1:B$600,2,FALSE) ```
Make a truth table and use SUMPRODUCT to get the values. Copy this into cell B1 on Sheet2 and copy down as far as you need: `=SUMPRODUCT(--($A1 = Sheet1!$A:$A), Sheet1!$B:$B)` the part that creates the truth table is: `--($A1 = Sheet1!$A:$A)` This returns an array of 0's and 1's. 1 when the values match and a 0 when they don't. Then the comma after that will basically do what I call "funny" matrix multiplication and will return the result. I may have misunderstood your question though, are there duplicate values in Column A of Sheet1?
54,999,533
Hello im having error on browser and i don't know how to resolve this. thanks for the future help[![enter image description here](https://i.stack.imgur.com/UJMnF.png)](https://i.stack.imgur.com/UJMnF.png)
2019/03/05
[ "https://Stackoverflow.com/questions/54999533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10539385/" ]
The easiest, and with best browser support might actually be SVG. You can set up approximately the same thing you did with the ::before, with the difference that the background stroked version can have a mask, which will let only the outer-line visible. From there, you can simply append a copy of the same text over, and you'll be able to apply the opacity as you wish, both on the stroke and the fill: ```css body{ background-image:url(https://picsum.photos/800/200?image=1051); font-family: sans-serif; } svg { font-size: 40px; font-weight: bold; } .textStroke { stroke: black; stroke-width: 12px; stroke-linejoin: round; } .visibleText { fill: rgba(186, 218, 85, 1); transition: fill-opacity .5s linear; } .visibleText:hover { fill-opacity: 0; } ``` ```html <svg width="350"> <defs> <!-- we type it only once --> <text x="10" y="55" id="txt">Text with outline</text> <mask id="mymask"> <!-- white => visible, black => tansparent --> <rect x="0" y="0" width="450" height="70" fill="#FFF"></rect> <use xlink:href="#txt" fill="#000"/> </mask> </defs> <!-- our stroked text, with the mask --> <use xlink:href="#txt" mask="url(#mymask)" class="textStroke"/> <!-- fill version --> <use xlink:href="#txt" class="visibleText"/> </svg> ```
Solution using SVG filters -------------------------- To get a stroke around the text, you can use a combined SVG filter consisting of successively applied filters: `feMorphology`, `feComposite` and `feColorMatrix`. ```css body{ background-image:url(https://picsum.photos/800/800?image=1061); background-size:cover; font-family: serif; } ``` ```html <svg viewBox="0 0 350 350" > <defs> <filter id="groupborder" filterUnits="userSpaceOnUse" x="-20%" y="-20%" width="300" height="300"> <feMorphology operator="dilate" in="SourceAlpha" radius="5" result="e1" /> <feMorphology operator="dilate" in="SourceAlpha" radius="2" result="e2" /> <feComposite in="e1" in2="e2" operator="xor" result="outline"/> <feColorMatrix type="matrix" in="outline" values="0 0 0 0 0.1 0 0 0 0 0.2 0 0 0 0 0.2 0 0 0 1 0" result="outline2"/> <feComposite in="outline2" in2="SourceGraphic" operator="over" result="output"/> </filter> </defs> <g id="group" filter="url(#groupborder)"> <text x="10" y="100" stroke-width="1" fill="#1D3A56" font-family="serif" font-size="30" font-weight="700" > Text with outline </text> </g> </svg> ```
25,103
Sometimes, people use a colloquial phrase of "it figures" or "go figure", which is kind of an acknowledgement of the correctness of a fact, or something like that. It's also sometimes abbreviated even further to just "Figures" or "Go fig", depending on the speaker. Examples of the phrase in context: > > **It figures**, this site doesn't have a question about this phrase yet. > > > **Go figure**, the answer was right under my nose the entire time. > > > What is the origin of this phrase, and what exactly does it mean? What is being figured, and into what?
2011/05/12
[ "https://english.stackexchange.com/questions/25103", "https://english.stackexchange.com", "https://english.stackexchange.com/users/8566/" ]
Just spitballing here, but could 'it figures' in the sense of to draw a conclusion or "stands to reason" or "figure out" be related to the sense of "figure" in a categorical syllogism. Once you determine the figure and the mood of a syllogism you can understand it's form and can determine if it is a valid form or not. So in this analyst part of determining whether the form of a syllogism is valid or not you have to "figure it" out. see: <https://www.oed.com/view/Entry/70079?rskey=5bn5Xv&result=1#eid> Etymology: < French figure (= Provencal, Spanish, Italian figura ), < Latin figūra , < \*fig- short stem of fingĕre : see feign v. The Latin word was the ordinary rendering of Greek σχῆμα (see scheme n.1) in its many technical uses; several of the senses below are traceable, wholly or in part, to Greek philosophy.
As others have indicated, it means pretty much the same as "*Go figure it out*", "*Go compute it*", or "*Do the math*". This comes directly from the literal, math meaning of the verb "*figure*" as "calculate". That's the origin. Sometimes it is used sarcastically, to indicate that there is really **nothing** difficult to figure out, that is, that the thing in question is obvious. In this use it means about the same thing as "*Duh!*", as @alexisclayton indicate.
3,687
How do I set keyboard shortcuts for `Home`, `End`, `PageDown`, and `PageUp` on a 13" MacBook Pro? Are there default keyboard shortcuts? Or can I do it with Automator (and if so, how)? I want them to work the same way that `Home` and `End` do on all Windows apps. --- I also want general solution I get that [Kyle Cronin♦](https://apple.stackexchange.com/questions/3687/home-end-pagedown-pageup-on-a-macbook-pro/3688#3688) was do the same in some apps, but what about others? is there any tricky solution?
2010/11/04
[ "https://apple.stackexchange.com/questions/3687", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/15/" ]
You can do page up/down and home/end on a Macbook keyboard by using the `fn` and the arrow keys: `fn`+`↑` is `PageUp` `fn`+`↓` is `PageDown` `fn`+`←` is `Home` `fn`+`→` is `End`
`⌘`+`→` works like a PC's `End` (moves the cursor to the end of the line). `⌘`+`←` works like a PC's `Home` (moves to the beginning of the line). `ctrl`+`A` and `ctrl`+`E` (Emacs-style keybindings) work in most OS X applications as well.
66,945,035
I have a string of words and mathematical/programmatically used symbols. For example, something like this: ```swift let source = "a + b + 3 == c" ``` (Note: you cannot rely on spaces) I also have an array of strings that I need to filter out of the source string: ```swift let symbols = ["+", "-", "==", "!="] ``` Now, I need to **create an array of the matching items** (**with duplicates**). In this case that would be `["+", "+", "=="]`. From what I've tried, `==` is two characters, so I **cannot** do the following: ```swift let source = "a + b + 3 == c" let symbols = CharacterSet(charactersIn: "+-=≠") // not '==' and '!=', but '=' and '≠' due to it being a CharacterSet let operations = source .map { String($0) } .filter { char in symbols.contains(UnicodeScalar(char)!) } print(operations) // Output: ["+", "+", "=", "="] // Needed: ["+", "+", "=="] ``` Any help is much appreciated
2021/04/04
[ "https://Stackoverflow.com/questions/66945035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10531223/" ]
so when I experiment on my own system, this is how I see the path variable once I added the globstar pattern: `...:./path1:./**/` - which is not reading all the paths (perhaps pattern matching is not part of PATH, dont know) * If you are not creating new subdirectories all the time and just want "all subdirectories that currently exist to PATH variable", then a for loop to upgrade your PATH variable would suffice (like is mentioned here: <https://unix.stackexchange.com/questions/17715/how-can-i-set-all-subdirectories-of-a-directory-into-path/17856#17856>) * but if you want to achieve objective "add all future subdirectories to my PATH"; then in that same answer link, there is a mention of <http://www.gnu.org/software/stow/> which seems like its solving your usecase
You can try something like this. Just name the file `file.txt` ``` add_path() { declare -a new_path local IFS=: mapfile -t new_path < <(find /usr/local/bin/ -type f -name '*.py') NEW_PATH=${new_path[*]%/*} export PATH="$PATH:$NEW_PATH" } add_path ``` Just source that file. ``` source ./file.txt ``` Then try to execute your python scripts without the absolute paths.
13
No.2 on <http://blog.stackoverflow.com/2010/07/the-7-essential-meta-questions-of-every-beta/>
2010/11/12
[ "https://security.meta.stackexchange.com/questions/13", "https://security.meta.stackexchange.com", "https://security.meta.stackexchange.com/users/33/" ]
With the increasing use of social media mining tools such as Maltego we should be stressing that people should think carefully about what they are asking questions on. Especially if they are asking questions about their companies security posture or configuration. If I was going to do a profile of a company there could be some rich pickings in this site as it develops.
I think we should have something in there specifically around not posting requests for ways to hack a device/app/database/OS. Haven't yet thought of appropriate wording (It is 1am and it has been a long day) but after having to close a couple of questions on this topic I think it is worth having a standard FAQ answer.
70,251,636
I have a dataframe where I would like to maintain all columns in my original dataset and create a new pivoted column based on existing dataset. **Data** ``` stat1 stat2 id q122con q122av q122con q122av q222con q222av q222con q222av 50 1000 aa 40 10 900 100 50 0 1000 0 100 2000 bb 50 50 1500 500 75 25 1900 100 ``` **Desired** ``` stat1 stat2 id date con av con av 50 1000 aa q122 40 10 900 100 50 1000 aa q222 50 0 1000 0 100 2000 bb q122 50 50 1500 500 100 2000 bb q222 75 25 1900 100 ``` **Doing** ``` df.pivot(index="id", columns="date", values=["con", "av"]) ``` However, I am not obtaining the full columns within my dataset. Any suggestion is appreciated.
2021/12/06
[ "https://Stackoverflow.com/questions/70251636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5942100/" ]
Lot of your issues here is dealing with duplicate column names: ``` import pandas as pd # Duplicating input dataframe with clipboard and remove dot numbers assign for duplicate column headers df = pd.read_clipboard() df.columns = df.columns.str.split('.').str[0] # Set index to move first three columns into index df = df.set_index(['stat1','stat2','id']) # Use groupby and cumcount to get order of duplicate column headers cols = df.groupby(df.columns, axis=1).cumcount().rename('No').reset_index() # Use str.extract to split "dates" from av and con with regex cols = cols['index'].str.extract('(q\d{3})(.*)').join(cols).drop('index', axis=1) # Create a new multiIndex column header df.columns = pd.MultiIndex.from_frame(cols, names=['date','av','con']) # Reshape dataframe by stacking the outer most column header to the dataframe index # And moved those columns from the index back into the dataframe with reset_index df_out = df.stack(0).reset_index() # Flatten headers back to one level df_out.columns = [f'{i}_{j}' if j else f'{i}' for i, j in df_out.columns] # And print print(df_out) ``` Output: ``` stat1 stat2 id date av av_1 con con_1 0 50 1000 aa q122 10 100 40 900 1 50 1000 aa q222 0 0 50 1000 2 100 2000 bb q122 50 500 50 1500 3 100 2000 bb q222 25 100 75 1900 ```
It's not as pretty as the other solutions but it works: ``` out = df.set_index(['stat1','stat2','id']).stack() idx = pd.DataFrame(out.index.tolist()) count = idx.groupby(idx.columns.tolist()).cumcount().tolist() idx = (idx.iloc[:,:-1] .merge(idx.iloc[:,-1].str.extract('(q\d{3})(.*)'), left_index=True, right_index=True)) out.index = pd.MultiIndex.from_frame(idx, names=['stat1','stat2','id','date','val']) out = (out .to_frame() .assign(count=count) .groupby(['count','val','stat1','stat2','id','date']) .first() .unstack(level=[0,1]) .droplevel([0,1], axis=1) .reset_index() ) print(out) ``` Output: ``` val stat1 stat2 id date av con av con 0 50 1000 aa q122 10 40 100 900 1 50 1000 aa q222 0 50 0 1000 2 100 2000 bb q122 50 50 500 1500 3 100 2000 bb q222 25 75 100 1900 ``` Figured out a simpler way. Moreover, the above produces duplicate columns: ``` df = pd.read_clipboard() out = df.set_index(['stat1', 'stat2', 'id']) out.columns = out.columns.str.split("((av)|(con))", expand = True).droplevel([-2,-3]) out = out.stack(level=0) out.columns = [''.join(col) for col in out.columns] out = out.reset_index().rename(columns={'level_3':'date'}) ``` Output: ``` stat1 stat2 id date av av.1 con con.1 0 50 1000 aa q122 10 100 40 900 1 50 1000 aa q222 0 0 50 1000 2 100 2000 bb q122 50 500 50 1500 3 100 2000 bb q222 25 100 75 1900 ```
22,054,679
I have a set of items that have information on them. These items are defined by me, the programmer, and the user do not ever need to change them, they will never need to change based on configuration, and the only time they might change is in a future version of my application. I know before hand how many of these items there should be, and what their exact data is. An enum, is a great programming construct that let's me predefine a group of keys available in my application and group them under a logical Type. What I need now, is a construct that let's me predefine a group of keys that have extra information attached to them. Example: This is a standard enum: ``` public enum PossibleKeys { Key1, Key2, Key3 } ``` This is the enum I would need: ``` public enum PossibleItems { Item1 { Name = "My first item", Description = "The first of my possible items." }, Item2 { Name = "My second item", Description = "The second of my possible items." }, Item3 { Name = "My third item", Description = "The third of my possible items." } } ``` I know this kind of enum does not exist. What I'm asking is: How can I, in C#, hard code a set of predefined items whose data is set in code? What would be the best way to do this? EDIT: I don't necessarily want a solution that uses enums, just a solution that allows me to have this behaviour, which is to know all possible items in my application, and the info that each of them has. EDIT 2: It's important for me to be able to get all existing items at runtime. So being able to query all items and to iterate over them is required. Just like I could with an enum.
2014/02/26
[ "https://Stackoverflow.com/questions/22054679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/172272/" ]
If it's purely for description you can use the built-in `DescriptionAttribute` as stated in some of the other answers. If you need functionality that an attribute can't supply, however, you can create a lookup with some sort of metadata object. Something like this: ``` public enum PossibleKeys { Key1, Key2, Key3 } public class KeyMetadata { public PossibleKeys Id { get; set; } public string Description { get; set; } public SomeOtherClass SomethingAttributesCantHandle { get; set; } } private static readonly IReadOnlyDictionary<PossibleKeys, KeyMetadata> KeyMetadataLookup; static EnumContainerClass() { Dictionary<PossibleKeys, KeyMetadata> metadata = new Dictionary<PossibleKeys, KeyMetadata>(); metadata.Add(PossibleKeys.Key1, new KeyMetadata { Id = PossibleKeys.Key1, Description = "First Item" }); metadata.Add(PossibleKeys.Key2, new KeyMetadata { Id = PossibleKeys.Key2, Description = "Second Item" }); metadata.Add(PossibleKeys.Key3, new KeyMetadata { Id = PossibleKeys.Key3, Description = "Third Item" }); KeyMetadataLookup = new ReadOnlyDictionary<PossibleKeys, KeyMetadata>(metadata); } ``` Then to retrieve: ``` KeyMetadataLookup[PossibleKeys.Key1].Description ``` Note that I'd only use this if there was something attributes couldn't handle. If it's all primitive types you can also simply make your own custom attribute. You're not limited to simply the built-in ones. Your own custom attribute would end up like: ``` [System.AttributeUsage(System.AttributeTargets.Field)] public class CustomDataAttribute : System.Attribute { public string Name { get; set; } public string Description { get; set; } } ``` Then in use: ``` public enum PossibleItems { [CustomData(Name = "My first item", Description = "The first of my possible items.")] Item1, [CustomData(Name = "My second item", Description = "The second of my possible items.")] Item2, [CustomData(Name = "My third item", Description = "The third of my possible items.")] Item3 } ```
Another alternative can be using *Java style enums* ``` public class PossibleItems { public string Name { private set; get; } public string Description { private set; get; } public static PossibleItems Item1 = new PossibleItems() { Name = "My first item", Description = "The first of my possible items" }; public static PossibleItems Item2 = new PossibleItems() { Name = "My second item", Description = "The second of my possible items" }; private PossibleItems() { } public override int GetHashCode() { return (Name + ";" + Description).GetHashCode(); } public override bool Equals(object obj) { if(!(obj is PossibleItems)) return false; var other = obj as PossibleItems; return other.Name == Name && other.Description == Description; } } ``` --- ``` bool eq = PossibleItems.Item1 == PossibleItems.Item1; Console.WriteLine(PossibleItems.Item1.Name); ```
4,451,662
How is this mechanism realized, I mean, having some layouts and changing them when user scrolls the screen? I need it to look like the Samsung Galaxy S main menu, or Angry Birds Seasons level menu. Thanks in advance.
2010/12/15
[ "https://Stackoverflow.com/questions/4451662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/543539/" ]
By the way, `Thread.Sleep` is probably never a good idea. A basic problem with `Thread.Sleep` that people are usually not aware of, is that the internal implementation of `Thread.Sleep` *does not pump STA messages*. The best and easiest alternative, if you have to wait a given time and can't use a kernel sync object, is to replace `Thread.Sleep` with `Thread.Join` on the current thread, with the wanted timeout. `Thread.Join` will behave the same, i.e. the thread would wait the wanted time, but in the meantime STA objects will be pumped. Why this is important (some detailed explanatiopn follows)? Sometimes, without you even knowing, one of your threads may have created an STA COM object. (For example this sometimes happens behind the scenes when you use Shell APIs). Now suppose a thread of yours has created an STA COM object, and is now in a call to `Thread.Sleep`. If at sometime the COM object has to be deleted (which can happen at an unexpected time by the GC), then the Finalizer thread will try calling the object's distruvtor. This call will be marshalled to the object's STA thread, which will be blocked. Now, in fact, you will have a blocked Finalizer thread. In this situations objects can't be freed from memory, and bad things will follow. So the bottom line: `Thread.Sleep`=bad. `Thread.Join`=reasonable alternative.
You don't provide a lot of background on why you're doing this, or what you're trying to accomplish, but if its possible, you might want to look into creating a windows service.
264,154
How can I fetch more than 1000 record from data store and put all in one single list to pass to django?
2008/11/05
[ "https://Stackoverflow.com/questions/264154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20683/" ]
Fetching though the remote api still has issues when more than 1000 records. We wrote this tiny function to iterate over a table in chunks: ``` def _iterate_table(table, chunk_size = 200): offset = 0 while True: results = table.all().order('__key__').fetch(chunk_size+1, offset = offset) if not results: break for result in results[:chunk_size]: yield result if len(results) < chunk_size+1: break offset += chunk_size ```
JJG: your solution above is awesome, except that it causes an infinite loop if you have 0 records. (I found this out while testing some of my reports locally). I modified the start of the while loop to look like this: ``` while count % 1000 == 0: current_count = query.count() if current_count == 0: break ```
169,987
In C/C++ it is in general possible to do `strcpy`(`argv[0]`, "new process name"). It's a hack used in malicous software to hide real process name. Is such operation possible via shell? What I want to do is: change `$1`, `$2`, ... so that the script can make certain information easily available to user. For example, if the script is processing file `This_is_file_nr12456.txt`, it can "publish" this by changing `argv[1]` making it instantly available to user by simple `ps ax`.
2014/11/26
[ "https://unix.stackexchange.com/questions/169987", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/92616/" ]
With recent Linux, `printf foo > /proc/$$/comm` will change the executable name (the `ps -p` thing) provided "noclobber" isn't set (and the wind is in the right direction). In zsh, `printf foo >! /proc/$$/comm` works regardless of clobbering state.
You could make your script recursive this way: ``` #! /bin/sh - do-something-with "$1" shift [ "$#" -eq 0 ] || exec "$0" "$@" ``` Then when running `your-script a b c`, the `ps` output would show in turn: ``` your-script a b c your-script a b your-script a ```
136,670
I have a some what strange problem (which could have an easy and obvious solution for all I know). My problem is that when I've booted ubuntu (now 10.4 but same problem with 9.10) and turns it off it starts sending a HUGE amount of data via the ethernet cable, so much in fact that my router can't handle it and stops responding. As far as I can tell the computer is completely turned off with no fans spinning. I can add that if I boot windows I do not have this problem, just when exiting ubuntu. There are two "fixes" for my problem: * Pull the ethernet cable until the next boot * Turn off power to the PSU and wait for the capacitors to unload Is there anyone who knows what could be going on? I'd be happy to post some logs or conf-files. Currently I'm using the ethernet port on my motherboard which is a Asus P6T Deluxe V2 with an updated version of the BIOS (maybe not the latest but since it only happens when I've been in ubuntu I don't wanna mess with the BIOS too much). Regards Nicklas ---------Update 1---------- The router is a D-Link DIR 655 with the latest firmware. ---------Update 2---------- I've now reinstalled ubuntu (with 10.4) and I still experience the same problem. ---------Update 3---------- Well I still haven't found a solution to this problem :(
2010/05/01
[ "https://superuser.com/questions/136670", "https://superuser.com", "https://superuser.com/users/35756/" ]
What is indicating that your Ubuntu-shutting-down computer is sending data to your router? I mean, do you have any other things to show that there was data being sent? (for example, you might put a hub in the path and capture data on it while the shutdown is in progress... does that show such transfers?) A simpler reason could be a driver malfunction causing the router to crash/stall. Towards that end, it might help to publish your router specs too. --- Update on your comment: * I am a little surprised with your problem. Do you by any-chance have a Wake-up-on-LAN configuration enabled in your PC-BIOS? * If you want to capture data between the router and the PC you will need another piece of hardware called a Hub which lets you 'tap' the wire between the PC and the Router (3 ethernet wires: 1 from PC, 1 from Router and a 3rd to a different PC capturing packets). Alternatively, if your router has more Ethernet ports and supports 'port-mirroring' you can pickup captures with that setup.
It could be a faulty Ethernet cable that sends out noise as the signal is coming down. Try a different cable.
57,295,193
I want to solve the following problem. I have variable data\_json which contain json data of following structure ``` data_json = "api": {"results": 402, "fixtures": [{"fixture_id": 127807, "league_id": 297, "round": "Clausura - Semi-finals", "statusShort": "FT", "elapsed": 90, "venue": "Estadio Universitario de N)", "referee": null, "homeTeam": {"team_id": 2279, "team_name": "Tigres UANL", "logo": "url"}, "awayTeam": {"team_id": 2282, "team_name": "Monterrey", "logo": "url1"}, "goalsHomeTeam": 1, "goalsAwayTeam": 0, "score": {"halftime": "1-0", "fulltime": "1-0", "extratime": null, "penalty": null}}, ....... another fixture-ids } } the same piece of data in another fixture_id ``` I need to extract values of each key:value pairs and save extracted values to variables. I need the following output ``` var fixture_id = fixture_id[value] var league_id = league_id[value] var round = round[value] var statusshort = statusShort[value] var elapsed = elapsed[value] var venue = venue[value] var referee = referee[value] var home_team_id = homeTeam.team_id[value] var home_team_name = homeTeam.team_name[value] var home_team_logo = homeTeam.logo[value] ##the same for awayTeam dictionary ``` I tried looping on my json by following code ``` data_json_looping_on = data_json["api"]["fixtures"] for id in data_json_looping_on: fixture_id = id["fixture_id"] league_id = id["league_id"] the same logic for each simple key value pairs. But when looping go up on dictionariy i tried following loop for item in id["homeTeam"] home_team_id = item["team_id"] ``` Here is Traceback of above code ``` ------------------------------------------------ TypeError Traceback (most recent call last) <ipython-input-8-958a38c41236> in <module> 18 venue = item["venue"] 19 referee = item["referee"] ---> 20 for item in id["homeTeam"]: 21 home_team_id = item["team_id"] 22 print(home_team_id) TypeError: string indices must be integers ------------------------------------------------------ ``` I tried another method ``` data_json_looping_on = data_json["api"]["fixtures"] for id in data_json_looping_on: fixture_id = id["fixture_id"] league_id = id["league_id"] #the same for logic for each simple key value pairs. But when go up on home_team_id = id["homeTeam"]["team_id"] print(home_team_id) ``` Python arrise the following error ``` ------------------------------------------------ TypeError Traceback (most recent call last) <ipython-input-5-1fe42572d5ae> in <module> 18 venue = item["venue"] 19 referee = item["referee"] ---> 20 home_team_id = id["homeTeam"] ["team_id"] 21 print(home_team_id) TypeError: string indices must be integers ``` How i can extract values of homeTeam and awayTeam dictionaries? If you have another logic of extracting give me your advise Here is my real code ``` date_fixt = open("../forecast/endpoints/date_fixtures.txt", "r") date_fixt_json = json.load(date_fixt) data_json = date_fixt_json["api"]["fixtures"] for item in data_json: fixture_id = item["fixture_id"] league_id = item["league_id"] event_date = item["event_date"] event_timestamp = item["event_timestamp"] firstHalfStart = item["firstHalfStart"] secondHalfStart = item["secondHalfStart"] round_count = item["round"] status = item["status"] statusShort = item["statusShort"] elapsed = item["elapsed"] venue = item["venue"] referee = item["referee"] for item in id["homeTeam"]: home_team_id = item["team_id"] print(home_team_id) ```
2019/07/31
[ "https://Stackoverflow.com/questions/57295193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11363452/" ]
`id["homeTeam"]` and `id["awayTeam"]` aren't lists (there are no square brackets around them), they're just single dictionaries. So you don't need to loop over them. ``` date_fixt = open("../forecast/endpoints/date_fixtures.txt", "r") date_fixt_json = json.load(date_fixt) data_json = date_fixt_json["api"]["fixtures"] for item in data_json: fixture_id = item["fixture_id"] league_id = item["league_id"] event_date = item["event_date"] event_timestamp = item["event_timestamp"] firstHalfStart = item["firstHalfStart"] secondHalfStart = item["secondHalfStart"] round_count = item["round"] status = item["status"] statusShort = item["statusShort"] elapsed = item["elapsed"] venue = item["venue"] referee = item["referee"] home_team_id = item["homeTeam"]["team_id"] print(home_team_id) away_team_id = item["awayTeam"]["team_id"] print(away_team_id) ```
Your json may be formatted improperly if it is thinking that "homeTeam" is reference to a string and not a dictionary. try: ``` import json data_json = json.loads(data_json) home_team_id = id["homeTeam"]["team_id"] away_team_id = id["awayTeam"]["team_id"] ``` The second issue may be that it's failing at: ``` fixture_id = id["fixture_id"] ``` because "fixtures" references a list. So you should also try: ``` fixture_id = data_json_looping_on[0]["fixture_id"] ```
15,859
My digital piano (Roland FP 80) can transpose the existing MIDI file at most five semitones up or at most six semitones down (does not allow to select more). Has it been done for my convenience ("too many features") or there are some fundamental reasons making transposition by arbitrary range more difficult than appears?
2014/03/02
[ "https://music.stackexchange.com/questions/15859", "https://music.stackexchange.com", "https://music.stackexchange.com/users/8737/" ]
Why would you need more than that? Five semitones up and six down can make every possible key: Let's say the original MIDI file was in C major. Up 5 semitones and you can get C C# D D# E and F. Down 6 semitones and you can get C B Bb A Ab G Gb. I am aware that you cannot transpose to a different octave using that but for practical purpose that is easily sufficient. I imagine, that that function was designed to allow the pianist to transpose to better meet a singer's vocal range so a total span of 11 semitones is perfect.
Look for a separate Octave Shift function. As David has already said above, there are two different functions, transpose, which shifts by semi-tones and octave shift which does the same thing by a whole octave. If you just want to shift the pitch by a whole number of octaves you need to use that function, if you then need to adjust by a few tones you need to select transpose as well. So Audrius needs to transpose down to Fm and then also shift up one octave to get the desired result.
80,643
I'm going to be running *Curse of Strahd* for my regular group. I'm usually a player and have only DM'd once to give our usual DM a break. This is my first time with a published adventure. I finished reading the campaign book through, and I'm now assembling notes and thinking deeper about how I want to run the game. Without spoiling too much: > > Early in the campaign, the players can get a Tarroka reading, much like a Tarot card reading. This sets the location of certain critical items, sets the location of Strahd, and identifies a potential ally in the fight against Strahd. > > > It's also a notable hook into the adventure, since the characters are given some sense of what they are in Ravenloft to undertake. I'm looking for help from those experienced running the campaign on how to spice up this moment. Here's a few things I've considered: * Letting the players keep the cards after they've drawn them. * Giving them verbatim notes on what the teller's hints were. * Drawing the cards beforehand so I can work on my acting/telling of the results, and using sleight of hand to re-draw the same cards. * Drawing the cards on gameday, and doing my best to roleplay the Teller's reaction genuinely. Given the potential impact, what is the best way to make the card reading dramatic, memorable, and fun for the players (and myself)?
2016/05/25
[ "https://rpg.stackexchange.com/questions/80643", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/28283/" ]
Having studied the book, you have some idea of what each Tarokka result can entail, and you can let this "foreknowledge" inform Madam Eva's reactions to the cards as they appear. If you draw > > the 7 of Coins, you can hint that the location of the treasure isn't very far away; if you draw the 9 of Coins, Madam Eva might shake her head despondently and say "Maybe save this one for last." > > > It's easy to want to add merely emotional clues, to add color without giving too much away: "It is in a place of dread;" "I feel the presence of mournful spirits near this item;" "This place is cold and silent." But there's so little emotional contrast in Barovia that sentences like these can easily fade into the background noise of doom and gloom. Specific information will make your players' ears perk up, and if your goal is to create a memorable experience, you can afford to drop a few extra hints. For example: Many of the speeches for cards that clue > > locations in Castle Ravenloft don't actually refer to the castle ("We know it's in a crypt. Do we know where a crypt is?"), but Eva can add something about "beneath the Devil's tower" or glance nervously in its direction. > > > If the players feel like gabbing it up with Madam Eva about each card, trying to pry hints out of her, go ahead and respond according to the character you've built in your performance—but to add emotional texture to the scene, make her insist on total silence before she turns over the next card. The use of a real deck is so effective because everyone loves props. The description of Madam Eva's tent provides a lot of inspiration for additional props: Mysterious lights, a crystal ball, and a black velvet cloth. I think this cloth is a good thing to focus on because you can slowly unroll it before you lay the cards down, which is a very evocative and almost ritualistic action. Even if your players forget what cards you drew, they will remember the appearance of that cloth unrolling across the table. If you can't get a piece of black velvet, use whatever spooky-looking fabric you can get your hands on, and then *change the words "black velvet"* to whatever you're using when you read the description, so that the players will think you are following the details in the book exactly. (On the subject of > > Strahd's Enemy: Some of the results are more interesting than others. The book gives you the choice between NPC A and NPC B for some results, apparently according to what kind of Challenge Rating you want for the party's ally. Obviously you want to figure out your choices in this regard ahead of time. But for my purposes, I didn't really want my players to end up with either version of the Broken One, the Horseman, or the Innocent, so I just removed those cards from the deck. If you're not comfortable with the full range of randomness in the book, you can create "massaged randomness" without the players finding out.) > > >
Strahd's a vampire -- he can peer into other realms. He sees that there is some kind of seance or party sitting around a table thinking about him in Ravenloft (your D&D group ;^>). Here's an unorthodox suggestion. Figure out a way to associate different cards with different questions about the player's themselves. Make it subtle at first and up the ante of "breaking the fourth wall" dependent on how Strahd is relating to them. The more antagonistic and paranoid Strahd is, the more the cards can reveal very personal traits about the players. Make sure you present it as Strahd, not as your personal self, of course. You can't make it personal at all in order to pull it off. Perhaps, through continued interaction, he figures out that you are some kind of "adventuring party" set out to kill his were-beasts and attack him in some kind of "game". He may figure out that the player called "Catherine" is really a man (you have a player playing a different-gendered PC) or that perhaps they're odd-looking (yes?) or anti-social and should get on with their lives. Go meta -- if at least one of the player's doesn't get freaked out and leave the table, you haven't done it right.
3,629,545
Is it redundant to run `git add .` and then `git commit -am "commit message"`? Can I just run `git add .` and then `git commit -m "commit message"` or, alternatively, just `git commit -am "commit message"`?
2010/09/02
[ "https://Stackoverflow.com/questions/3629545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/168286/" ]
`Git add` + `git commit -m` will just commit those files you've added (new and previously tracked), but `git commit -am` will commit all changes on tracked files, but it doesn't add new files.
I think some of the previous answers did not see the period after `git add` (your original question and some of the answers have since been edited to make the period more clear). `git add .` will add all files in the current directory (and any subdirectories) to the index (except those being ignored by `.gitignore`). The `-a` option to `git commit` will include all changes to files that are already being tracked by git, even if those changes have not been added to the index yet. Consequently, if all of the files are already being tracked by git, then the two approaches have the same effect. On the other hand, if new files have been created, then `git add .; git commit` will add them to the repository, while `git commit -a` will not. `git add .; git commit -a` is indeed redundant. All changes have already been added to the index, so the `-a` does nothing.
191,747
I have a PDF of a Ph.D. thesis in mechanical engineering, so there are lots of equations. No PDF app that I've tried on OS X (Preview.app,Adobe Reader, Skim, PDFPen) can show the equations properly; some symbols are missing (particularly integral signs). However, when I open the file in Windows (with PDF X-Change) the equations all appear right. I don't know how the file was generated. Any idea of the cause of this issue?
2015/06/15
[ "https://apple.stackexchange.com/questions/191747", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/132077/" ]
Try the following: 1. Open the "Keyboard" preferences pane 2. In the "Keyboard" tab, turn on the "Show Keyboard and Character Viewers in menu bar" checkbox 3. Go to the new menu (it looks like a box with a command key clover-leaf in it) and choose "Show Keyboard Viewer" You'll now see a window shaped like your keyboard, with every key shown, and each pressed key highlighted. Try out all the keys, especially the "t" and modifiers. Note that holding down "shift" will change the key display to capitals, and holding down "option" will change the key display to alternate characters. This should let you track down the problem, if it's in hardware.
I happen to have run into this today though probably for an unrelated reason, but maybe this will help someone else. I had recently installed Snap Camera and bound Shift-T and Shift-O to actions in the app. What I didn't realize was that the app stayed open in the background (with a menubar icon) and was capturing those keystrokes as long as it was running. Holding down the Fn key is a good way to test for a hardware issue because the Shift-T and Shift-O keystrokes worked perfectly when holding down Fn. It's likely this could happen for other apps that are doing systemwide keyboard capture of a specific keystroke. Note to self: Always add modifier keys like Command, Option, Control when binding keys in something that's going to be listening in the background.
3,682,019
I have a question - If a player rolls $4$ dice, and the maximum result is the highest number he gets (for example he tosses and gets $1$,$2$,$4$,$6$ the maximum result is $6$). His opponent rolls a single die and if the player's result is higher than his opponent's, he wins. What is the chance of the player to to lose? So, I can't seem to compute this in my mind and can't see which distribution this is since I don't know what are the results on each die when the player rolls them.
2020/05/19
[ "https://math.stackexchange.com/questions/3682019", "https://math.stackexchange.com", "https://math.stackexchange.com/users/778899/" ]
Find:$$P(D\_1,D\_2,D\_3,D\_4\leq D\_5)=\sum\_{k=1}^6P(D\_1,\dots,D\_4\leq D\_5\mid D\_5=k)P(D\_5=k)$$where the $D\_i$ denote the results of 5 independent die rolls. Here $P(D\_1,\dots,D\_4\leq D\_5\mid D\_5=k)=P(D\_1,\dots,D\_4\leq k)$ on base of independence.
If Player 1 (P1) rolling one die rolls a 6, i'm assuming he wins and Player 2 rolling the 4 dice loses even if manages a 6 in his grouping, if so... If P1 rolls 6 - then P1 wins 100% of time; 5 - P1 wins 48.2% of time (5x5x5x5 / 6x6x6x6 = 625/1296) 4 - P1 wins 9.87% of time (4x4x4x4 / 6x6x6x6 = 128/1296) 3 - P1 wins 6.25% of time (3x3x3x3 / 6x6x6x6 = 81 /1296) 2 - P1 wins 1.2% of time (2x2x2x2 / 6x6x6x6 = 16 /1296) 1 - P1 wins 1 in 1296. So assigning each of these a 1/6th chance of happening and then adding those products together, P1 has a 1/6 + 8.03% + 1.64% + 1.04% + .2% + .013% chance of winning, which is about a 27.6% chance of winning.
202,457
Bones can be not quite enough sometimes, and for my secret military organization, every possible advantage is given to the soldiers. Including reinforcing bones. But...where do I put the metal? Material specifics: * Handwavium Material X * Will not cause blood poisoning/other effects once in place * No ill effects during placement by nanites * At least as strong as steel The material will be placed while the bones are shattered, so there is easy access to anywhere in/on the bones. Once the material is in place the soldier is given some Skele-Gro to fix the bones together in about five minutes. The metal as well as calluses(which remain thanks to a slight modification in the SkeleGro) make for very strong bones. In theory. Assuming the material can be placed easily, where do I put Material X for maximum bone reinforcement? If it uses less that's great too, but I don't think it will be very easy to measure how much your method uses without actually trying it. Below is just a bunch of information not in the original question from the comments I'm just putting here so everything is in the same spot. * Looking more for blunt force protection than bullet proof bones. If they can be tossed around and then get back up whereas most people would be waiting for an ambulance, that's more what I'm looking for. * Don't worry about ligaments, just bones at the moment. * Try to keep mostly bones rather than completely replace the bones. Keep at least a 50-50 bone-metal ratio. More bone is better. * Doesn't necessarily have to be metal, anything that strengthens will be acceptable.
2021/05/11
[ "https://worldbuilding.stackexchange.com/questions/202457", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/77168/" ]
### On the outside Of the body that is. It's generally a bad idea to have anything in the body that the body can't repair. The metal is going to get bent and broken, it's going to need repair. It seems you have some solid medical technology going on here, but if you need to replace the bent metal in someone's leg that's a major operation you've set yourself up for. Better to let the bones be bones and give the troops power armour.
**Drag those supersoldiers into the millenium!** Metal, schmetal. Schmetal, I tell you! What are you, patching up Steve Austin? **Carbon fiber** is how one reinforces bones these days. [![carbon fiber augmentation](https://i.stack.imgur.com/fmwmO.png)](https://i.stack.imgur.com/fmwmO.png) <https://www.podiatrytoday.com/exploring-carbon-fiber-fixation-lower-extremity> > > Carbon fiber technology provides strength and durability with ease of > placement in comparison to stainless steel and titanium. The modulus > of elasticity of the carbon fiber technology is closer to that of > cortical bone than stainless steel or titanium implants, allowing the > surrounding bone to function without undue stress from the internal > fixation. The implants are composed of longitudinal and > diagonally-oriented fibers of carbon, allowing for strength in > multiple planes. > > > That xray is a little retro with the metal nails; those can be carbon fiber too. You don't need to shatter the bones. Slip the carbon fiber rod down the middle and sheathe the outside where you need it. The carbon fiber rod can flex like bone and if the bone breaks the rod will hold the pieces in place while your supersoldier chugs some of that Skelegro you did not need to use. Carbon fiber rods and plates in bones is not fiction.
14,117,962
My problem is I am trying to get some testimonials from the database and need to echo them in a div. The DIV has created with fix width and height values. In this case I need to display every testimonials with a link of 'read more' to full one. Here in the DIV I want to limit to only 50 words from the testimonials... can any body tell me how I can do this...
2013/01/02
[ "https://Stackoverflow.com/questions/14117962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1942155/" ]
you can do like this- ``` echo wordwrap(substr($str, 50), 20, "<br />\n"); ```
If the container has fixed height and width values, then limiting the amount of text by character is only fool-proof if you're using a monospaced typeface. Why not do it the CSS way? ``` .truncated { text-overflow: ellipsis; white-space: nowrap; overflow: hidden; } ``` [Browser support](http://caniuse.com/#feat=text-overflow): IE 6+, Safari 4+, Firefox 7+, Opera 11+ and Chrome 10+.
1,434,166
I've created a simple REST service that serves data as XML. I've managed to enable XML, JS and RSS format but I can not find the way to enable JSON format. Is JS == JSON? Guess not :). How can I enable this in version 1.2/1.3? Thx!!
2009/09/16
[ "https://Stackoverflow.com/questions/1434166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/132257/" ]
Router::parseExtensions('json');
just add this line of code in your controller or AppController ``` var $components = array('RequestHandler'); function beforeFilter() { $this->RequestHandler->setContent('json', 'text/x-json'); } ``` and run it into internet explorer.
62,070,024
Good afternoon. Announced the ADX indicator function (link Python: Average Directional Index (ADX) 2 Directional Movement System Calculation - <https://www.youtube.com/watch?v=joOWm-GcHTw>). An error occurs during operation - "TypeError: 'builtin\_function\_or\_method' object is not subscriptable". on this line - TRDate,TrueRange = TR(date[x],closep[x],highp[x],lowp[x],openp[x],closep[x-1]) TypeError: 'builtin\_function\_or\_method' object is not subscriptable I will be glad of any help. Thank. The code is below. ``` def TR(d,c,h,l,o,yc): x = h-l y = abs(h-yc) z = abs(l-yc) if y <= x >= z: TR = x elif x <= y >= z: TR = y elif x <= z >= y: TR = z return d, TR def DM(d,o,h,l,c,yo,yh,yl,yc): moveUp = h-yh moveDown = yl-l if 0 < moveUp > moveDown: PDM = moveUp else: PDM = 0 if 0 < moveDown > moveUp: NDM = moveDown else: NDM = 0 return d,PDM,NDM def calcDIs(date,openp,highp,lowp,closep,openpy,highpy,lowpy,closepy,tf): x = 1 TRDates = [] TrueRanges = [] PosDMs = [] NegDMs = [] while x < len(date): TRDate,TrueRange = TR(date[x],closep[x],highp[x],lowp[x],openp[x],closep[x-1]) << error TRDates.append(TRDate) TrueRanges.append(TrueRange) DMdate,PosDM,NegDM = DM(date[x],openp[x],highp[x],lowp[x],closep[x],openp[x-1],highp[x-1],lowp[-1],closep[x-1]) << I assume that there will be the same error PosDMs.append(PosDM) NegDMs.append(NegDM) x +=1 expPosDM = ExpMovingAverage(PosDMs,14) expNegDM = ExpMovingAverage(NegDMs,14) ATR = ExpMovingAverage(TrueRanges,14) xx = 0 PDIs = [] NDIs = [] while xx < len(ATR): PDI = 100*(expPosDM[xx]/ATR[xx]) PDIs.append(PDI) NDI = 100*(expNegDM[xx]/ATR[xx]) NDIs.append(NDI) xx +=1 return PDIs,NDIs ```
2020/05/28
[ "https://Stackoverflow.com/questions/62070024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13635936/" ]
``` output = [[item[0] for item in order] for order in orders] display(output) [['Fries'], ['Burger', 'Milkshake', 'Cola'], ['Cola', 'Nuggets', 'Onion Rings'], ['Fries'], ['Big Burger', 'Nuggets']] ```
You can isolate the keys by zipping up each order and returning the first index of each zip result. **The following gives you a list of tuples:** ``` orders2 = [list(zip(*order))[0] for order in orders] ``` **If you need a list of lists, use this:** ``` orders2 = [list(a) for a in [list(zip(*order))[0] for order in orders]] ``` **Code Example** ``` orders = [[('Fries', 9)], [('Burger', 6), ('Milkshake', 2), ('Cola', 2)], [('Cola', 2), ('Nuggets', 3), ('Onion Rings', 5)], [('Fries', 9)], [('Big Burger', 7), ('Nuggets', 3)]] # For a list of tuples orders2 = [list(zip(*order))[0] for order in orders] print(*orders2) # ('Fries',) ('Burger', 'Milkshake', 'Cola') ('Cola', 'Nuggets', 'Onion Rings') ('Fries',) ('Big Burger', 'Nuggets') # If you need a list of lists orders2 = [list(a) for a in [list(zip(*order))[0] for order in orders]] print(*orders2) # ['Fries'] ['Burger', 'Milkshake', 'Cola'] ['Cola', 'Nuggets', 'Onion Rings'] ['Fries'] ['Big Burger', 'Nuggets'] ``` Live Code -> <https://onlinegdb.com/SklIG1q6iU>
11,830,351
First, here is the code: ``` <form action="FirstServlet" method="Post"> Last Name: <input type="text" name="lastName" size="20"> <br><br> <input type="submit" value="FirstServlet"> <input type="submit"value="SecondServlet"> </form> ``` I'd like to understand how to send information in case the `FirstServlet button` was pressed to `FirstServlet` and in case the `SecondServlet button` was pressed to `SecondServlet`. **important:** I want to do it in the same form so the same information would be transered to both the servlets. (of course, in the servlets I'll use the info accordingly)
2012/08/06
[ "https://Stackoverflow.com/questions/11830351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1403516/" ]
In addition to the previous response, the best option to submit a form with different buttons without language problems is actually using a **button** tag. ``` <form> ... <button type="submit" name="submit" value="servlet1">Go to 1st Servlet</button> <button type="submit" name="submit" value="servlet2">Go to 2nd Servlet</button> </form> ```
``` function gotofirst(){ window.location = "firstServelet.java"; } function gotosecond(){ window.location = "secondServelet.java"; } ``` ```html <form action="FirstServlet" method="Post"> Last Name: <input type="text" name="lastName" size="20"> <br><br> <input type="submit" onclick="gotofirst()" value="FirstServlet"> <input type="submit" onclick="gotosecond()" value="SecondServlet"> </form> ```
39,159,065
This is the `JSON` Response I'm getting,I unable to parse,Please help me. ``` { "features": [{ "attributes": { "OBJECTID": 1, "schcd": "29030300431", "schnm": "UNAIDED GENITALIA LIPS DALMATIA RS" }, "geometry": { "x": 8449476.63052563, "y": 1845072.4204768054 } }] } ```
2016/08/26
[ "https://Stackoverflow.com/questions/39159065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3728743/" ]
You should use `IsPostBack` on Page load to prevent every time page load on button click. You can check every time on `Page_Load`. **Sample Code** ``` protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { // First Time Load When User Come } else { // Every Time Load When Any click button in page } ```
Try to Add `OnClientClick="return false;"` ``` <asp:Button ID="btnApprove" runat="server" Text="Approve" CssClass="button" OnClick="btnApprove_Click" OnClientClick="return false;"/> ```
54,113,724
I am checking some code and I am wondering if this expression could ever be `false`: ``` !isset($_POST['foo']) || $_POST['foo'] ``` Context: ``` $bar = (!isset($_POST['foo']) || $_POST['foo']) ? 1 : 0; ```
2019/01/09
[ "https://Stackoverflow.com/questions/54113724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/248959/" ]
According to a quick test below, it is indeed possible ``` $trueVar = true; // Or 1 $falseVar = false; // Or 0 $nullVar = null; $emptyVar = ""; $result1 = (!isset($trueVar) || $trueVar) ? 1 : 0; $result2 = (!isset($falseVar) || $falseVar) ? 1 : 0; $result3 = (!isset($nullVar) || $nullVar) ? 1 : 0; $result4 = (!isset($emptyVar) || $emptyVar) ? 1 : 0; Output: result1 = 1 result2 = 0 result3 = 1 result4 = 0 ``` Note: Why don't you just simply do `$bar = isset($_POST['foo'])` and adquire if it's empty or not? Edit: Funk Forty Niner is correctt isset($\_POST) will always return true because it's always set due to being a global variable, `empty()` should be used instead or another approach <https://3v4l.org/EtWn0>
You could think of the following cases: * **$\_POST['foo'] doesn't exist** $bar = (true || null) ? 1 : 0 => 1 * **$\_POST['foo'] exists and value is anything but 0, false or empty string** $bar = (false || true) ? 1 : 0 => 1 * **$\_POST['foo'] exists and value is 0, false, empty string** $bar = (false || false) ? 1 : 0 => 0 * **$\_POST['foo'] exists and value is null** $bar = (true || false) ? 1 : 0 => 1 I think you should read this [In php, is 0 treated as empty?](https://stackoverflow.com/questions/2220519/in-php-is-0-treated-as-empty)
16,924,120
We're facing a formatting issue with publishing PDF output from XML content. In table columns, text in a table cell contains some text (model numbers) for example, AD150, OP834, HT78J, QW09T, OL560, **PQ** **UW**, AG800, XN280 as highlighted, the model names mentioned are split into two lines if there is a space in the name ("PQ UW"). This happens even if enough cell width is available to accomodate the text after the space. However, in case when there is no space, the text splits at regular column width. Please suggest the solution to fix this, so that the text always appear in the same line (without breaking into a new line) even if there is a space within them. Text should break at regular cell width only.
2013/06/04
[ "https://Stackoverflow.com/questions/16924120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2452560/" ]
The sample XSL provided will work well if the input XML has separate tags for each model number. If it does not and the source XML is something like this: <modellist>OL560, PQ UW, AG800</modellist> Then you would write a recursive template to process through each character in the list, writing the output into a variable (search for recursive XSL template for splitting for an example). It would be not that difficult to do. You would output any space character that follows a "," normally but replace any space character not following a "," as above (with a non-breaking space). Start here for some inspiration: [Breaking long lines](https://stackoverflow.com/questions/4350788/xsl-fo-force-wrap-on-table-entries)
One cheap thing to try: when you render the model names, change blanks to character U+00A0, non-breaking space. Something like this: ``` <xsl:template match="model-name"> <xsl:value-of select="translate(.,' ','&#xA0;')"/> </xsl:template> ```
23,314,652
How do I solve this error? ``` Can't locate Switch.pm in @INC (you may need to install the Switch module) (@INC contains: /etc/perl /usr/local/lib/perl/5.18.2 /usr/local/share/perl/5.18.2 /usr/lib/perl5 /usr/share/perl5 /usr/lib/perl/5.18 /usr/share/perl/5.18 /usr/local/lib/site_perl .) at external/webkit/Source/WebCore/make-hash-tools.pl line 23. BEGIN failed--compilation aborted at external/webkit/Source/WebCore/make-hash-tools.pl line 23. make: *** [out/target/product/generic/obj/STATIC_LIBRARIES/libwebcore_intermediates/Source/WebCore/html/DocTypeStrings.cpp] Error 2 ```
2014/04/26
[ "https://Stackoverflow.com/questions/23314652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7946951/" ]
You are getting this error because you don't have the Switch.pm perl module installed on your system. There are two ways to install it and both of them work on Ubuntu 14.04 as well. 1. Install it through the Ubuntu repositories. 2. Install the .pm through CPAN. Installing Switch.pm using the Ubuntu repositories: --------------------------------------------------- From the command-line, the installation can be completed by running the following command from the terminal (Ctrl-Alt-t): ``` sudo apt-get install libswitch-perl ``` Installing Switch.pm using CPAN: -------------------------------- If you would prefer to install this via cpan, follow these instructions: ``` Open a terminal(Ctrl-Alt-t). Enter the command cpan. At the prompt cpan[1]>, type install Switch. Once completed, Type exit. ``` Credits: [Kevin Bowen](https://askubuntu.com/questions/204481/how-to-install-perl-switch-pm-module-required-to-build-webkit-gtk)
You can resolve this error by installing "perl-Switch" for **Amazon Linux** / **Redhat** / **Centos** / etc: ``` sudo yum install -y perl-Switch ``` for **Ubuntu**: ``` sudo apt-get install -y libswitch-perl ```
7,975,444
I have a WCF service that needs to be called via SOAP (working) and via JSON (not working). My C# code: ``` [ServiceContract] public interface IService1 { [OperationContract] [WebGet(ResponseFormat=WebMessageFormat.Json)] string Foo(); } public class Service1 : IService1 { public string Foo() { return "woohooo"; } } ``` And here's my config: ``` <?xml version="1.0"?> <configuration> <system.web> <compilation debug="true" targetFramework="4.0" /> </system.web> <system.serviceModel> <services> <service name="Service1"> <endpoint address="soap" binding="basicHttpBinding" contract="DummyService.IService1"/> <endpoint address="json" binding="webHttpBinding" behaviorConfiguration="jsonBehavior" contract="DummyService.IService1"/> </service> </services> <behaviors> <serviceBehaviors> <behavior> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="true"/> </behavior> </serviceBehaviors> <endpointBehaviors> <behavior name="jsonBehavior"> <enableWebScript/> <webHttp/> </behavior> </endpointBehaviors> </behaviors> <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> </system.serviceModel> <system.webServer> <modules runAllManagedModulesForAllRequests="true"/> </system.webServer> </configuration> ``` And here's my Javascript: ``` $.getJSON("/Service1.svc/Foo") .success(function (result) { alert("success! " + result); }) .fail(function (result) { console.log("failed!"); console.log(result); }); ``` The response I get is "400 Bad Request". What am I doing wrong? I've followed the advice in [REST / SOAP endpoints for a WCF service](https://stackoverflow.com/questions/186631/rest-soap-endpoints-for-a-wcf-service), but it still-a-no-worksies. :-) Help!
2011/11/02
[ "https://Stackoverflow.com/questions/7975444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/536/" ]
Your problem is that you are calling `spaced` with a non-numeric string and then trying to convert that to an integer: ``` >>> int("Blusson Hall") Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: 'Blusson Hall' ``` If you want a range based on the length of the string, you can use something like: ``` for i in range(len(s)): ``` as in: ``` >>> s = "Busson Hall" >>> for i in range(len(s)): ... print i ... 0 1 2 3 4 5 6 7 8 9 10 ``` And, as some extra assistance, you would use `s[i]` to get the `i`'th (zero being the first one, of course) character of `s`. In addition, you probably want to start with an empty string and then append individual characters to it (from the original string and whatever spaces you want added) to gradually build it up before returning it. For example, this snippet duplicates every character with a colon between them: ``` >>> s = "paxdiablo" >>> s2 = "" >>> for i in range(len(s)): ... s2 = "%s%s:%s:" % (s2, s[i], s[i]) ... >>> print s2 p:p:a:a:x:x:d:d:i:i:a:a:b:b:l:l:o:o: ``` Short of writing the code for you (which, intelligently, you decided against asking for), that's probably all the help I can give (though feel free to ask any questions you want and I'll offer further advice).
You can't convert a string to an integer, and that's what you try to do when you type: ``` n = int(s) ``` spaced only takes one argument, 's', and you pass in a string, then try to convert it to an integer. I think what you want is probably ``` n = len(s) ``` But really, you don't even need that. Since strings are iterable, you can just loop over it like: ``` for ch in s: ...do stuff here... ``` And if the index within s for each char is helpful/easier, enumerate() will do that for you: ``` for idx, ch in enumerate(s): ...do stuff here... ``` Just so you know, you don't actually need a for loop at all. Since strings are iterable and 'join()' takes an iterable as an argument, you can replace almost all of your code with this: ``` ' '.join(s) ``` That looks odd if you haven't done much with Python before. I've created a string ' ', and join() is a method that all strings have available. Join takes some iterable object (like a list, or even another string) and puts the string that is the object of the join between each element of the iterable. So, in this case, it puts ' ' between each element of the string 's'.
424,736
Im a student of class 11th and right now my schools teaching atomic structure , can anybody tell me that why do we need high voltage and low pressure in discharge tube in cathode ray experiment?
2018/08/25
[ "https://physics.stackexchange.com/questions/424736", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/204848/" ]
If the cathode ray experiment has a beam of electrons hitting a fluorescent screen which glows then: * You need the low pressure in the tube so that the passage of the beam of electrons is not impeded very much by collision with air molecules. * You need a reasonably high accelerating voltage to give the electrons enough kinetic energy to make the fluorescent screen glow when the electrons hit the screen. If the cathode ray experiment uses a discharge tube which emits light then the electrons must be accelerated enough (obtain enough kinetic energy) between collision with the gas molecules in the tube to excite/ionise the gas molecules on collision with them. So a low pressure ensures that the distance between collision is sufficiently large to enable the electron to cause excitation/ionisation of the gas molecules. On the other hand if there are too few gas molecules the intensity of the emitted would be too small to observe the emitted light. This means that the gas pressure must not to be too low thus decreasing the distance the electrons travel between collisions with the gas molecules. Having a high voltage across the tube means that an electron can gain more kinetic energy between collisions with the air molecules and thus a smaller distance between gas molecules (not quite so low a pressure) can be used. So there is a compromise between the values of voltage and pressure. Modern cathode ray tubes use a hot cathode source whereas the older types use a cold cathode which generally require higher voltages to operate. However, such tubes must not be used with too high a voltage because if they are the electrons on impact with the glass / fluorescent screen would produce a potential health hazard - X-rays.
Why high voltage? To break the molecules of the gas into atoms and to remove the electrons from the outermost orbitals. Why low pressure? To allow the rays to move freely from one electrode to another and the possibility of collisions between rays and moleculess are minized.
108,796
It seems like Azure is getting a lot of buzz lately, but it's doesn't seems to make sense for us. Here are our basic details * Primarily .NET/Microsoft * Primarily intranet applications, but also have a public company website * Have a full time IT staff and manage our own servers * Offices in 4 major cities * Internet traffic is localized around those major cities Is there any reason for us to move to or even consider moving to Azure? It seems like total cost of ownership for Azure would be a lot higher, without any real benefit. I would love to here reasons for or against us considerting Azure or even another cloud provider
2010/02/02
[ "https://serverfault.com/questions/108796", "https://serverfault.com", "https://serverfault.com/users/14121/" ]
Since you already have a bunch of servers, making them useless by moving to Azure (or EC2) will not pay. But when the time comes to replace or add hardware you should consider a hosted (i.e. "cloud") environment, or even directly hosted solutions. Your supposition of higher TCO for Azure/EC2 is far from certain. If fact, it is more likely that the reverse is true. How does your cost structure change if you don't own server and storage hardware? The monthly cost has to be **much** higher than you think for server ownership to be cost effective. The compelling bigger issue is whether your company will trust Microsoft/Amazon and is willing to **not** have the servers and data on site. These issues are a problem for many companies - personally I am on the fence. A couple of podcasts ago Jeff and Joel talked to the guys from DocType who run on EC2. Reasons to consider the cloud .. 1- Money. No hardware is owned, you just pay per month for usage. Lower "TCO". 2- Less Administration. No hardware, no obsolescence, no failures, etc. Fewer people. 3- Flexibility. Capacity is fluid, not discrete, and can be changed on the fly. 4- Availability. When is the list time Amazon has been down? Reasons to not consider the cloud .. a- Security. You have to trust the cloud provider. b- Money. You are paying monthly. Some companies don't like that. c- Availability. The apps are down if the internet connection is down. d- Comfort. Some people/companies like to have the infrastructure under their control. Other issues anyone?
Do you have an existing DR solution? It could be used for that.
59,035,731
Write an SQL query to find all those hostnames that have encountered multiple logs “init failure” on any given day at 5 min interval. Also provide count of such log instance. ``` //Hostlogs //date, time, hostname, logs //may 20, 2019 8:00 abc init failure //may 20, 2019 8:01 abc init failure //may 20, 2019 8:02 abc init failure //may 20, 2019 8:03 abc init failure //may 20, 2019 8:04 abc init failure //may 20, 2019 8:12 abc init failure //may 20, 2019 8:13 abc init failure //may 20, 2019 8:00 xyz init failure //may 20, 2019 8:20 xyz init failure //may 20, 2019 8:30 xyz init failure //may 20, 2019 8:30 xyz wxyz ```
2019/11/25
[ "https://Stackoverflow.com/questions/59035731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12430420/" ]
This is caused because of a broken setuptools package, you just need to reinstall it. For most operating systems: `pip install setuptools` Linux: `apt-get install python-setuptools` or `yum install python-setuptools`
Stumbled uppon this answer first on google when searching for this error code, so for future reference ill just leave a link to this issue that solved my problem: <https://stackoverflow.com/a/59979390/10565375> tldr: ``` pyinstaller --hidden-import=pkg_resources.py2_warn example.py ```
60,441,236
Given the following C code: ``` #include <stdio.h> #include <string.h> typedef struct a { char name[10]; } a; typedef struct b { char name[10]; } b; void copy(a *source, b *destination) { strcpy(destination->name, source->name); } ``` This main function below runs successfully: ``` int main() { a first; b second; strcpy(first.name, "hello"); copy(&first, &second); printf("%s\n", second.name); printf("Finished\n"); return 1; } ``` While this main function results in a segmentation fault: ``` int main() { a *first; b *second; strcpy(first->name, "hello"); copy(first, second); printf("%s\n", second->name); printf("Finished\n"); return 1; } ``` From my understanding of C, both implementations should run identically. What are the differences between the implementations and how can I adjust the second implementation to successfully run to completion?
2020/02/27
[ "https://Stackoverflow.com/questions/60441236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12100328/" ]
They don't run identically because you don't allocate memory for `first` and `second` in the second example. To do that, you can allocate them using `malloc`: ``` a *first = malloc(sizeof(*first)); b *second = malloc(sizeof(*second)); ``` If you allocate using `malloc`, make sure to check if the pointers are `NULL` before using them. If they are `NULL`, you should return an error or (in `main`) exit the program. In a non-trivial program, you should also call `free` on these pointers after you're done using them. Alternatively, you can allocate them on the stack: ``` a first[1]; b second[1]; ``` This does not require you to call `free`. I recommend this form.
The program are not identical because in the second program the declared pointers ``` a *first; b *second; ``` are not initialized, have indeterminate values and do not point tfo valid objects of the types a and b. You have to define objects of the types a and be to which the pointers will point to. For this purpose you could use for example the compound literal. Here is a demonstrative program ``` #include <stdio.h> #include <string.h> typedef struct a { char name[10]; } a; typedef struct b { char name[10]; } b; void copy(a *source, b *destination) { strcpy(destination->name, source->name); } int main(void) { a *first = &( a ){ 0 }; b *second = &( b ) { 0 }; strcpy(first->name, "hello"); copy(first, second); printf("%s\n", second->name); printf("Finished\n"); return 0; } ``` The program output is ``` hello Finished ```
81,102
[![enter image description here](https://i.stack.imgur.com/6mfUa.jpg)](https://i.stack.imgur.com/6mfUa.jpg) I am using Illustrator CS6 and when I want to make a rectangle's corners round by using the direct selection tool and doing it manually, there is no option for that. So how to do so?
2016/12/02
[ "https://graphicdesign.stackexchange.com/questions/81102", "https://graphicdesign.stackexchange.com", "https://graphicdesign.stackexchange.com/users/72298/" ]
Since this functionality was not made available until later versions of illustrator, your only option is to do it through a plugin: * [VectorScribe](http://astutegraphics.com/software/vectorscribe/), from AstuteGraphics has not only live (rounded) corners, but TONS of functionality to edit paths. It is a must for all serious AI users. * [XtreamPath](http://www.cvalley.com/products/xtreampath/movies/) is also a multi-function plugin that has rounded corners by dragging.
[![enter image description here](https://i.stack.imgur.com/EfbV0.png)](https://i.stack.imgur.com/EfbV0.png) I am using Illustrator CS5. I always do it like this. Then if I need to adjust further I use the Direct Selection tool and adjust it.
21,975,920
I'm creating an API using peewee as the ORM and I need the ability to convert a peewee model object into a JSON object to send to the user. Does anyone know of a good way to do this?
2014/02/23
[ "https://Stackoverflow.com/questions/21975920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1438754/" ]
I had this very same problem and ended up defining my own parser extension for JSON types that could not be automatically serialized. I'm fine for now in using strings as data represented (although you could possibly use different datatypes, but beware of approximation using floating points! In the following example, I put this in a file called `json_serialize.py` inside a `utils` folder: ``` from decimal import Decimal import datetime try: import uuid _use_uuid = True except ImportError: _use_uuid = False datetime_format = "%Y/%m/%d %H:%M:%S" date_format = "%Y/%m/%d" time_format = "%H:%M:%S" def set_datetime_format(fmt_string): datetime_format = fmt_string def set_date_format(fmt_string): date_format = fmt_string def set_time_format(fmt_string): time_format = fmt_string def more(obj): if isinstance(obj, Decimal): return str(obj) if isinstance(obj, datetime.datetime): return obj.strftime(datetime_format) if isinstance(obj, datetime.date): return obj.strftime(date_format) if isinstance(obj, datetime.time): return obj.strftime(time_format) if _use_uuid and isinstance(obj, uuid.UUID): return str(obj.db_value()) raise TypeError("%r is not JSON serializable" % obj) ``` Then, in my app: ``` import json from utils import json_serialize ... json.dumps(model_to_dict(User.get()), default=json_serialize.more) ``` edit just to add: this is very largely inspired by `json_utils.default` module found in mongodb but mainly relies on the `json` module and needs no import of mongodb own bson/json\_utils module. Usually I update it to support new types as soon as my app raises the `TypeError` for it found a type not able to serialize
I usually implement the model to dict and dict to model functions, for maximum security and understanding of the inner workings of the code. Peewee does a lot of magic and you want to be in control over it. The most obvious argument for why you should not iterate on the fields but rather explicitly specify them is because of security considerations. Not all fields can be exposed to the user, and I assume you need this functionality to implement some sort of REST API. So - you should do something like this: ``` class UserData(db.Model): user = db.ForeignKeyField(User) data = db.CharField() def serialize(): # front end does not need user ID here return { 'data': self.data } @classmethod def from_json(cls, json_data): UserData.create( # we enforce user to be the current user user=current_user, data=json_data['data'] ) ```
66,672,754
I have a generic method that takes List (extend Person) and should result a new List S(extend Student). The teacher said I am not allowed to cast (S)t as I did in my code. Student class extends Person class ``` // Main List<Person> people = new ArrayList<>(); people.add(new Person()); people.add(new Student()); List<Person> students = new ArrayList<>(getStudent(people)); System.out.println(students); // Method Below Main public static <T extends Person, S extends Student> List<S> getStudent2(List<T> list) { List<S> students = new ArrayList<>(); for (T t : list) { if (t instanceof Student) students.add((S) t); } return students; } ``` Is there a better way to get a generic List of Superclass Person and result in a new list of its subClass Student?
2021/03/17
[ "https://Stackoverflow.com/questions/66672754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11866427/" ]
It is unclear what exactly you assignment is or your return type `(List<Student> vs List<Person>)`. But you can do the following: ``` List<? extends Person> students = getStudent(people); ``` By making the following changes: * return type is `List<? extends T>` * put the Students in a `List<T>` * remove the type designation `S extends Student` ``` public static <T extends Person> List<? extends T> getStudent(List<T> list) { List<T> students = new ArrayList<>(); for (T t : list) { if (t instanceof Student) students.add(t); } return students; } ``` The problem here is that if you want to use the list as a list of `Student` along with the methods of the Student class then you must cast `Person to Student` where appropriate. Otherwise you will need to return a bounded list which will be subject to the `get and put principal` of [contravariant](https://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)) data structures like Lists.
I think the best way, is using abstraction concept, here the example, hope its help ``` public static <T extends Person, S extends Student> List<People> getStudent2(List<T> list) { List<People> students = new ArrayList<>(); for (People t : list){ if (t instanceof Student){ students.add(t); } } return students; } static class Person implements People { } static class Student implements People { } interface People { } ``` //main ``` List<People> people = new ArrayList<>(); people.add(new Person()); people.add(new Student()); List<People> students = new ArrayList<>(getStudent(people)); System.out.println(students); ```
11,030,757
Is it possible to change object's value not directly? For example ``` a = {x: 5} b = a.x b = 100 a.x // => 5 ``` I'd like to get 100, but actually, `a.x` is still 5.
2012/06/14
[ "https://Stackoverflow.com/questions/11030757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/792549/" ]
Just use the number as object, and not as literal: ``` a = {x: {v: 5}} b = a.x b.v = 100 a.x​​.v // => 100 ```
It's impossible to achieve this in JavaScript. 5 is of a Number type and it's a value type. There is no way to access it through reference unlike Function, Object or Array.
19,767,826
I am trying to limit the input of a textbox of a very simple Web Application so that the user can only input numbers. Im having trouble doing this without using 20 lines of code, any help at all is appreciated! ``` protected void Button1_Click(object sender, EventArgs e) { { int input = int.Parse(InputBox.Text); if (input > 15) { String hot; hot = "hot"; Result.Text = hot; Result.BackColor = System.Drawing.Color.Red; } else if (input <= 15) { String cold; cold = "cold"; Result.Text = cold; Result.BackColor = System.Drawing.Color.Blue; } } } ``` Thank you!
2013/11/04
[ "https://Stackoverflow.com/questions/19767826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2929497/" ]
following is the javascript code to validate numeric value. ``` <script type="text/javascript"> function ValidateTextBox() { var value = document.getElementById("txtprice").value; if (!isNumber(value)) { alert("Please Enter Numeric Value "); return false; } else { return true; } } function isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); } </script> ``` ASPX Page:- ``` <asp:Button ID="Button1" runat="server" OnClientClick="return ValidateTextBox();" Text="Button" OnClick="Button1_Click" /> ```
Try adding the following markup to your Web Application next to your TextBox : ``` <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Input must be a number!" ValidationExpression="^[1-9]\d*$" ControlToValidate="InputBox"></asp:RegularExpressionValidator> ``` This will validate the control "InputBox" on every postback to ensure it matches the regular expression `^[1-9]\d*$`, which only allows Integer values. If you only want a specific postback to validate the input look at [Validation Groups](http://msdn.microsoft.com/en-us/library/ms227424(v=vs.100).aspx). Also if you require decimal values or need to allow other numeric values see the following questions Answer : <https://stackoverflow.com/a/2811058/1941466>
20,541,788
I'm combining two C programs using a header file. first program ``` #include<explore.h> int main() { int a =10; explore(); } ``` explore program ``` #include<stdio.h> int explore() { // I want to use the value of a. Can I use it? How can sue it? } ``` I want to use the value of `a` in `explore()` in explore program file. Can I use it? How can use it, is possible?
2013/12/12
[ "https://Stackoverflow.com/questions/20541788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2971609/" ]
Ok, first off. With the code as it stands now, you won't be able to use the int `a` anywhere, except in the `main` function, since it's a local variable to that function. Either pass it as an argument, or declare it as a global (and an *extern* for that matter). Either way, I'd opt to pass it as an argument, if `a` will be changed by the function `explore`, you can do 1 of 2 things: ``` int explore( int val) { //do stuff return new_val; } //call: a = explore(a);//assigns return int to a ``` Or, if the returned int signals a status of some kind, pass a pointer to `a`. This may, if you're new to pointers, seem like a sure way to over-complicate things, but it's very common, and very useful (added note on why this is useful to the bottom): ``` int explore(int *val) { *val += 123;//add 123 to val's value //this is NOT the same as val += 123, because that's shifting the pointer! return 0; } //call: int return_val = explore(&a);//pass &[address-of]a ``` Now, linking two source files is easy, but you say you're using a header file, all well and good, but you don't seem to be including it anywhere, nor are you showing what it looks like. I suspect you're having trouble compiling your code... if so, show us what you've tried (how you're compiling the code), and what errors you're getting. If you need a basic example of how to manually link 2 source files: [Here's a previous answer of mine that shows, step by step, how to link 2 files](https://stackoverflow.com/questions/19927802/how-to-use-a-header-file-in-c/19928924#19928924) *Why pointers?:* Many reasons, really. Here's just a few: * limit memory usage: If you're passing big structs *by value* all over the place (ie, copying the same data over and over), your code will be slow, and your stack might end up cluttered with the same value. (recursion induced stack overflow) * C can allocate heap memory, which can only be accessed through pointers, you can't turn a pointer variable into a non-pointer. * Return values are often ways to notify you of an error that may have occurred. The last point is crucial. If you're passing `a` to `explore` for some complex computation, changing the value of `a` along the way. If, half way down the function, something goes pear-shaped, how do you notify the caller that the value of `a` is no longer reliable? Simple: ``` int complex_function( int *val) { _Bool negative = *val > 0 ? false : true; //do all sorts of magic stuff //val wasn't negative, but is now, possible maxed int? if (negative == false && *val < 0) return -1;//notify using -1 return 0;//usually, 0 means everything went well ok } //call like so: if ((complex_function(&a)) != 0) exit( EXIT_FAILURE);//it's all gone wrong //else, continue ``` Now that's where pointers are very useful. It doesn't require you to mess about with all too many temp variables, creating copies of values all over the place, and compare those to get to the same conclusion.
Call `explore` with `a` as parameter. Nevertheless, you don't really seem to have two "programs". You have two source files in one program. So another way to use `a` in both parts could be to define `a` in main.c and declare it as "extern" in explore.h. Keep in mind, though, that `a` is somewhat "global" to your program then.
13,164,218
What is the difference between class A and class B? What's wrong with self? Why do I need to declare self line by line? ``` class A(dict): def __init__(self): self={1:"you", 2:"and me"} print "inside of class A",self class B(dict): def __init__(self): self[1]="you" self[2]="and me" print "inside of class B",self a=A() print "outside of class A",a b=B() print "outside of class B",b ``` **result:** ``` inside of class A {1: 'you', 2: 'and me'} outside of class A {} inside of class B {1: 'you', 2: 'and me'} outside of class B {1: 'you', 2: 'and me'} ```
2012/10/31
[ "https://Stackoverflow.com/questions/13164218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1789431/" ]
In class A, you are assigning to the local `self` variable. When `__init__` is called, `self` contains a reference so the constructed object. You are reassigning it to something else completely; *this does not change the instance of class A at all*. In fact, if you define a new method on class A you will notice that the dict you've assigned to `self` isn't even visible there. It became unreferenced the moment `__init__` returned.
just adding to the other good answers. you can see the difference in the Byte-code: **Byte-code of `A`:** ``` Disassembly of __init__: 3 0 BUILD_MAP 2 3 LOAD_CONST 1 ('you') 6 LOAD_CONST 2 (1) 9 STORE_MAP 10 LOAD_CONST 3 ('and me') 13 LOAD_CONST 4 (2) 16 STORE_MAP 17 STORE_FAST 0 (self) # stores values in local variable # i.e not changing the object at all 4 20 LOAD_CONST 5 ('inside of class A') 23 PRINT_ITEM 24 LOAD_FAST 0 (self) 27 PRINT_ITEM 28 PRINT_NEWLINE 29 LOAD_CONST 0 (None) 32 RETURN_VALUE None ``` **Byte-code of `B`:** ``` Disassembly of __init__: 8 0 LOAD_CONST 1 ('you') 3 LOAD_FAST 0 (self) #loads self, i.e instance of dict 6 LOAD_CONST 2 (1) 9 STORE_SUBSCR #store value in it 9 10 LOAD_CONST 3 ('and me') 13 LOAD_FAST 0 (self) 16 LOAD_CONST 4 (2) 19 STORE_SUBSCR 10 20 LOAD_CONST 5 ('inside of class B') 23 PRINT_ITEM 24 LOAD_FAST 0 (self) 27 PRINT_ITEM 28 PRINT_NEWLINE 29 LOAD_CONST 0 (None) 32 RETURN_VALUE None ```
16,629,979
In short, how do I let alert(1) run first: ``` $.post('example.php', function() { alert(1); }) alert(2); alert(3); alert(4); ``` But jquery ajax call seem like run in asynchronous method. So JavaScript will run everything below first, alert(2) to alert(4), then back to the post method, alert(1). Certainly I can just put the code in the ajax function, but this make no sense when I have dozens of functions, then I would have to add the code to all functions. ``` $.post('example.php', function() { alert(1); example(); }) function example() { alert(2); alert(3); alert(4); } ``` I want to get some json data from an ajax call, and use it later. So is there any smart solution? --- 2021-08-25 after 8 years, introduction of **async / await** is awesome, i don't really use jquery anymore, so i didn't test the code ``` await Promise.resolve($.post('example.php', function() { alert(1); example(); })); alert(2); alert(3); alert(4); ```
2013/05/18
[ "https://Stackoverflow.com/questions/16629979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2292614/" ]
> > *"Certainly I can just put the code in the ajax function, but this make no sense when I have dozens of functions, then I would have to add the code to all functions."* > > > There are many patters that can make this easier, but if you're saying that dozens of functions may need to call this post, you could just put the post in a function, and have the function receive a callback. ``` function myPost(callback) { $.post('example.php', function(data) { alert(1); callback(data); }) } // These are your "dozens of functions" function a2() { alert(2); } function a3() { alert(3); } function a4() { alert(4); } // These would be at various places in your application myPost(a1); myPost(a2); myPost(a3); ``` Ultimately the best approach depends on what you mean by "dozens of functions", but certainly you won't need to do the hard coding that you seem to imply. Passing functions as arguments is often the way to go, but there are other patterns as well that will set up a queue if that's what's needed.
The reason the `alert`s are firing in that order is because the "**A**" in AJAX stands for **Asynchronous**. Here is how the code executes: * The `post` method sends a request to the server, the second parameter is a callback function which will be called later once the request is returned by the server. * It then proceeds to the next line of code after the `post` call, firing `alert(2);` * Then the next line firing `alert(3);` * Then the next line firing `alert(4);` * This block of code is done running so control returns to the event loop * Once the server returns the Ajax request, the callback function is called firing `alert(1)` The best way to solve this would probably be to just move all of the code inside of the callback, that way it will only run once the request has been returned. ``` $.post('example.php', function() { alert(1); alert(2); alert(3); alert(4); }) ``` There probably isn't a need to put it in another function and call it as you suggested at the end of your question. I would avoid "synchronous" Ajax requests, aside from being an oxymoron, they run counter to the whole purpose of using Ajax. Using Ajax should make your application more responsive, using synchronous requests does the opposite, it can cause the browser to lock up if a request timesout or takes a longtime to return from the server.
22,175,369
If I want to display images in a template, the path I specify is relative to the static folder in my app directory. But if I want to load a file from a view function, then the path I specify seems to be relative to the project directory. Should these files all be in the same directory? Or is it typical to separate them out in this way? Is a file loaded by a view function (such as a text file containing human-readable settings) considered to be "static" in the same sense as image, css and js files for rendering my template?
2014/03/04
[ "https://Stackoverflow.com/questions/22175369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3320135/" ]
Emacs autosave files are ignored with ``` \#*# ```
To suppress the temporary Emacs files appearing on `git status` globally, you can do the following: 1. **Configure git to use a global excludesfile** Since this is a common problem, `git` has a [specific solution](https://git-scm.com/docs/gitignore) to that: > > Patterns which a user wants Git to ignore in all situations (e.g., backup or temporary files generated by the user’s editor of choice) generally go into a file specified by core.excludesFile in the user’s ~/.gitconfig > > > ``` git config --global core.excludesfile ~/.gitignore_global ``` 2. **Create the respective file** ``` cd touch .gitignore_global ``` 3. **Paste the following [template](https://github.com/github/gitignore/blob/master/Global/Emacs.gitignore) into the file** ``` # -*- mode: gitignore; -*- *~ \#*\# /.emacs.desktop /.emacs.desktop.lock *.elc auto-save-list tramp .\#* # Org-mode .org-id-locations *_archive # flymake-mode *_flymake.* # eshell files /eshell/history /eshell/lastdir # elpa packages /elpa/ # reftex files .rel # AUCTeX auto folder /auto/ # cask packages .cask/ dist/ # Flycheck flycheck_*.el # server auth directory /server/ # projectiles files .projectile # directory configuration .dir-locals.el # network security /network-security.data ``` 4. **Watch git do its magic! :)**
27,259,858
I don't know much about HTML, basically only what I've taught myself (so if you answer please don't speak in developer language hehe). I need the entire below styled button to be clickable, not just the text. I've been researching all over google but can't work it out. Also the corners only appear rounded in some browsers and square in others, is there a way to get it to appear rounded in most if not all browsers? ``` <tbody> <tr> <td> <table style="background-color: #434242; border: 4px solid #ffffff; border-radius: 30px; -moz-border radius: 30px -webkit-border-radius: 30px;" border="0" width="20%" cellspacing="0" cellpadding="0"> <td style="color: #ffffff; font-family: Helvetica, Arial, sans-serif; font-size: 12px; letter-spacing: -.20px; line-height: 100%; padding: 8px 8px 8px 8px;" align="center" valign="middle"><a style="color: #ffffff; text-decoration: none;" href="http://www.myurl.com">MY SITE</a></td> </tr> </tbody> </table> </td> ```
2014/12/02
[ "https://Stackoverflow.com/questions/27259858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4317650/" ]
VBScript has 5 windows into the .NET world: 1. By doing HTTP POST/GET to a .NET handler of some kind (such as a .aspx, HTTP handler, MVC or WebAPI controller). 2. By writing data to a file or a database for a .NET process to pick up. 3. By [exposing a .NET assembly (class library) as a COM object](http://msdn.microsoft.com/en-us/library/zsfww439%28v=vs.110%29.aspx) and adding the appropriate entries in the Windows Registry (either manually or using command utilities) so it can be called directly from VBScript. See [this article](http://www.codeproject.com/Articles/79314/How-to-call-a-NET-DLL-from-a-VBScript). 4. Making an executable file with .NET that is run directly from VBScript. 5. Using [PowerShell to call into a .NET assembly](https://stackoverflow.com/questions/3079346/how-to-reference-net-assemblies-using-powershell) and using [VBScript to call PowerShell](http://blogs.technet.com/b/heyscriptingguy/archive/2012/07/18/how-to-use-vbscript-to-run-a-powershell-script.aspx). The most straightforward option on a website is to use a GET or POST because you will steer clear of the mine fields of ACL and COM registration, but if you must go down another road I would say that PowerShell is your best bet, followed by COM interop as a third choice.
You need to mark your assembly as COM visible by setting the COMVisibleAttribute to true (either at assembly level or at class level if you want to expose only a single type). Next you register it with: ``` regasm /codebase MyAssembly.dll ``` and finally call it from VBScript: ``` dim myObj Set myObj = CreateObject("MyNamespace.MyObject") ``` This Answer Originally Posted By [Darin Dimitrov](https://stackoverflow.com/users/29407/darin-dimitrov) [Here](https://stackoverflow.com/questions/769332/how-to-call-c-sharp-dll-function-from-vbscript).
31,345,754
I am working my way through "Java - A beginners guide by Herbert Schildt". I hope this question is not way too ridiculous. It is about a while loop condition, where the while loop is located inside a for loop. The code example is this one: ``` public static void main(String[] args) { int e; int result; for (int i = 0; i < 10; i++) { result = 1; e = i; while (e > 0) { result *= 2; e--; } System.out.println("2 to the " + i + " power is " + result); } } ``` I don't understand the decrementing of e, within the scope that is written after `while (e > 0)`. Since e = i, and i is incremented, i believe e should be larger than 0 after the for loop has been performed the first time. If e is not decremented, the program will not run properly. Why is decrementing e necessary in this example?
2015/07/10
[ "https://Stackoverflow.com/questions/31345754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5103623/" ]
If you do not do `e--` you will get stuck in an endless `while loop`. Look at it like this: Let's go into a random iteration of the `for` loop. Let's say `i=5`. Then `e=i` so `e=5`. We now jump into the `while` loop. ``` while (e >0) { result*=2; e--; } ``` If we did NOT do `e--`, `e` would always stay at 5 and the `while` loop would never terminate. By doing `e--`, `e` will start at 5, then 4, .... then 0 where the `while` loop will terminate and we will jump back into the `for` loop, raise `i` (and consequently `e`) and repeat the whole process.
**Simple word explanation** : > > In while loop you need such a statement because of which the while > condition becomes false and program control comes out of the while > loop and it will help to avoid endless lopping problem. > > > **You have asked why decrementing e is important in this program?** **Answer** : If you don't decrement e then while(e > 0) will always return true value and program will get into an endless loop(will always be in while loop). Sample Iteration 2 when i = 2: result = 1 e = i = 2 while(e > 0) evaluates to true so result = 1 \* 2 = 2 e-- : e = 1 Again while(e > 0) evaluates to true because e=1 > 0 result = 2 \* 2 = 4 e-- : e = 0 Now Again check while(e > 0) and it will evaluates to false and while loop ends. For more information with few samples refer below link : <https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html>
13,717
I think to learn a language including Chinese, you would need to first learn the fundamentals, such as the vocabulary, pronunciation and grammar. After that, native speakers go their own way to develop into a more proficient speaker/writer/communicator. This process takes time and results are uncertain (maybe). Any suggestions about more effective ways to improve Chinese for beginner and intermediate levels?
2015/05/28
[ "https://chinese.stackexchange.com/questions/13717", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/4640/" ]
Thanks for everyone's comments. I think I got some answer to this question. To improve Chinese beyond intermediate level, one can "use the language in context". Single-person activities include * Reading Chinese in cartoon book with a topic you are interested in or familiar with * Watch Chinese drama/movies or translated drama/movies with Chinese voice/subtitles * Play Chinese RPG games in which you would see how the language is used in practice, and how people with different social status address each other. * Switch your phone or computer to Chinese language, and you can learn some new words and sentences. (though I think this one is intermediate level). Multi-person activities: * Talk and interact with other learners or native speakers.
Many young people in China use the APP like QQ or WeChat chat on the Internet,so you can find someone to be your friend.It is a funny way to learn Chinese.![APP QQ and WeChat](https://i.stack.imgur.com/Cwe12.jpg)
3,283,901
I'm working on a project that already contains the [gzip](http://www.gzip.org/) library as follows: ``` zlib\zlib.h zlib\zlib.lib zlib\zconf.h ``` I would like to use the gzip functions from this .lib but am getting the following [errors](http://msdn.microsoft.com/en-us/library/f6xx1b1z%28VS.71%29.aspx): ``` Compress.cpp Linking... Compress.obj : error LNK2001: unresolved external symbol _gzclose Compress.obj : error LNK2001: unresolved external symbol _gzerror Compress.obj : error LNK2001: unresolved external symbol _gzwrite Compress.obj : error LNK2001: unresolved external symbol _gzopen .\Debug/files.exe : fatal error LNK1120: 4 unresolved externals Error executing link.exe. ``` The link settings include: Object/library modules: zlib.lib Project Options: zlib.lib In the file using the gzX() functions, it ``` #include "zlib/zlib.h" ``` What else needs to be done here to use these functions? Thank You. **EDIT**: Using Visual Studio 6.0 C++ **EDIT2**: It turned out the static library I was using had the gz() functions taken out of them. The header file still had them which was misleading.
2010/07/19
[ "https://Stackoverflow.com/questions/3283901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/52256/" ]
you also need to add zlib.lib to your project's libraries: Project properties->Linker->Input->Additional Dependencies.
It turned out the static library I was using had the gz() functions taken out of them. The header file still had them which was misleading.
49,852,532
In my Postgresql 9.3 database I have a table `stock_rotation`: ``` +----+-----------------+---------------------+------------+---------------------+ | id | quantity_change | stock_rotation_type | article_id | date | +----+-----------------+---------------------+------------+---------------------+ | 1 | 10 | PURCHASE | 1 | 2010-01-01 15:35:01 | | 2 | -4 | SALE | 1 | 2010-05-06 08:46:02 | | 3 | 5 | INVENTORY | 1 | 2010-12-20 08:20:35 | | 4 | 2 | PURCHASE | 1 | 2011-02-05 16:45:50 | | 5 | -1 | SALE | 1 | 2011-03-01 16:42:53 | +----+-----------------+---------------------+------------+---------------------+ ``` Types: * `SALE` has negative `quantity_change` * `PURCHASE` has positive `quantity_change` * `INVENTORY` resets the actual number in stock to the given value In this implementation, to get the current value that an article has in stock, you need to sum up all quantity changes since the latest `INVENTORY` for the specific article (including the inventory value). I do not know why it is implemented this way and unfortunately it would be quite hard to change this now. My question now is how to do this for more than a single article at once. My latest attempt was this: ``` WITH latest_inventory_of_article as ( SELECT MAX(date) FROM stock_rotation WHERE stock_rotation_type = 'INVENTORY' ) SELECT a.id, sum(quantity_change) FROM stock_rotation sr INNER JOIN article a ON a.id = sr.article_id WHERE sr.date >= (COALESCE( (SELECT date FROM latest_inventory_of_article), '1970-01-01' )) GROUP BY a.id ``` But the date for the latest `stock_rotation` of type `INVENTORY` can be different for every article. I was trying to avoid looping over multiple article ids to find this date.
2018/04/16
[ "https://Stackoverflow.com/questions/49852532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9651587/" ]
In this case I would use a different internal query to get the max inventory per article. You are effectively using stock\_rotation twice but it should work. If it's too big of a table you can try something else: ``` SELECT sr.article_id, sum(quantity_change) FROM stock_rotation sr LEFT JOIN ( SELECT article_id, MAX(date) AS date FROM stock_rotation WHERE stock_rotation_type = 'INVENTORY' GROUP BY article_id) AS latest_inventory ON latest_inventory.article_id = sr.article_id WHERE sr.date >= COALESCE(latest_inventory.date, '1970-01-01') GROUP BY sr.article_id ```
You can use `DISTINCT ON` together with `ORDER BY` to get the latest `INVENTORY` row for each `article_id` in the `WITH` clause. Then you can join that with the original table to get all later rows and add the values: ``` WITH latest_inventory as ( SELECT DISTINCT ON (article_id) id, article_id, date FROM stock_rotation WHERE stock_rotation_type = 'INVENTORY' ORDER BY article_id, date DESC ) SELECT article_id, sum(sr.quantity_change) FROM stock_rotation sr JOIN latest_inventory li USING (article_id) WHERE sr.date >= li.date GROUP BY article_id; ```
34,466,205
I have this snippet that counts the number rows and returns the number of rows found in a MySQL table. This is the code, in which I have used underscore.js's `_.each` to iterate. ``` var all_rows = Noder.query('SELECT count(*) as erow from crud ', function(err, the_rows) { _.each(the_rows, function (corndog) { var trows = corndog.erow; console.log("All rows", trows); }); // var das_rows = trows; // var total_pages = Math.ceil(das_rows / per_page); // console.log("Pages",total_pages); res.view('noder/orm', { layout: 'layout', js:the_rows, post:results, title: 'This is the hi page title. Gandalf The great.' }); }); ``` I want to use `trows` to calculate the number of pages are to be created for my paging code. However, I cannot access the variable `trows`. This is the output of `console.log(the_rows);` ``` [ RowDataPacket { erow: 12 } ] ``` Is there another way I can do this to make `trows` available to the rest of my code?
2015/12/25
[ "https://Stackoverflow.com/questions/34466205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4567032/" ]
While Jonathan and Ilya have already given practical solutions to your specific problem, let me provide a generic answer to the question in the title: The simplest way to replace `_.each()` is to iterate over the array using a plain [`for`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for) loop: ``` for (var i = 0; i < the_rows.length; i++) { var row = the_rows[i]; console.log( "In loop: row = the_rows[" + i + "] =", row ); } console.log( "After loop: row =", row ); ``` or, in ES6 or later, a [`for`...`of`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of) loop: ``` for (var row of the_rows) { console.log( "In loop: row =", row ); } console.log( "After loop: row =", row ); ``` (You *could* also use a [`for`...`in`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) loop, but [you probably shouldn't.](https://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea)) Since these are built-in looping constructs, and do not involve an inner function like `_.each()` does, any variables defined in them will retain their last value after the loop ends. --- Another way to replace `_.each` is using the built-in [`.forEach()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) method of JS arrays: ``` the_rows.forEach( function (row, i) { console.log( "In loop: row = the_rows[" + i + "] =", row ); } ); ``` or, if you want to use this method to loop over something that looks like an array but isn't actually one (such as, say, a DOM [NodeList](https://developer.mozilla.org/en-US/docs/Web/API/NodeList)): ``` Array.prototype.forEach.call( the_rows, function (row, i) { console.log( "In loop: row = the_rows[" + i + "] =", row ); } ); ``` However, since `.forEach()` does require wrapping the loop body in an inner function, just like `_.each()`, any variables declared using `var` inside it will not be available outside the loop. However, variables declared outside the loop function *are* visible inside in it, so you can do e.g. this: ``` var last_row; the_rows.forEach( function (row, i) { last_row = row; // <-- no "var"! console.log( "In loop: last_row = row = the_rows[" + i + "] =", row ); } ); console.log( "After loop: last_row =", last_row ); ```
Declare `trows` outside of the loop: ``` var trows = 0; _.each(the_rows, function (corndog) { trows += corndog.erow; console.log("All rows",trows); }); ```
81,635
We recieved the following e-mail with from one of the UI developers > > When we browser site with IP: <http://x.x.x.x/>, it doesn’t > redirect to <http://www.our_website_name.com>. This could cause duplicate > content problems if a search engine indexes site under both its IP and > domain name. > > > Can we set redirection from IP to domain? > > > Now, I don't see that any of the search engines have indexed our IP address and I believe that the chances of a search engine indexing an IP address is close to nil if there are no links floating around in the internet with the IP address instead of the domain name. My question is: From a security point of view, is it safe to redirect an http request for direct IP address to the domain name? I know how to deny/block or redirect if the request is for direct IP address and I see dozens of instructions online how to do it, but why do people do that? Can I go ahead and set up this redirection (IP address to domain name) with no security concerns?
2015/02/14
[ "https://security.stackexchange.com/questions/81635", "https://security.stackexchange.com", "https://security.stackexchange.com/users/58761/" ]
It's not a security problem, but it's a bit of a strange thing to do. It complicates your configuration, and is prone to errors if the IP address were to change, or you wanted to move to cloud based services. AFAIK this it isn't standard practice to redirect IP address lookups to a domain.
As an employee of a company that does hosting I can tell you we do the following for our hosting servers. We have a 'base' (or catch-all) (virtual-) host configurations that refer to a quick to load page without any real content. (like a banner with our logo and a link to our corporate website). This approach has several advantages. * if a end-user enters the wrong url name he/she gets a fast loading website. Anyone harvesting URL's will not take to much of the servers resources * Attackers that try to harvest usign just the IP will get nowhere since the site beeing hosted is not a CMS/web app (that could be vulnerable).
21,942,349
How do I center the text horizontally and vertically for a TextView in Android? How do I center the alignment of a TextView?
2014/02/21
[ "https://Stackoverflow.com/questions/21942349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In Linear Layouts use ``` android:layout_gravity="center" ``` In Relative Layouts ``` android:layout_centerInParent="true" ``` Above Code will center the textView in layout To center the text in TextView ``` android:textAlignment="center" android:gravity="center" ```
It depends on how you have declared the height and width. If you used wrap\_content, then the textview is just big enough in that direction to hold the text, so the gravity attribute will not apply. android:gravity affects the location of the text Within the space allocated for the textview. layout\_xx attributes affect the location of the view within it's parent. SO if you set the size of the textview, then use gravity to position the text within the textview area, if you used wrap\_content, then use the layout\_xx attributes to position the textview within it's parent
5,749,807
Given a Perforce changelist number, I want to find the local path of all files in that pending changelist. * **p4 describe changelist** -- gets me the depot path for files in the changelist (method 1) * **p4 opened -c changelist** -- gets me the depot path for files in the changelist (method 2) * **p4 have** -- gets me the depot path and local path for all files that have previously been submitted Using a combination of **p4 describe** and **p4 have**, I can find the local paths for all files in the changelist that have previously been submitted to Perforce (and are opened for **delete** or **edit**). But what about files that are opened for **add**? **p4 have** does not know anything about files that are opened for **add**. Given a pending Perforce changelist, how do I find the local path for files that are about to be added to Perforce?
2011/04/21
[ "https://Stackoverflow.com/questions/5749807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/175/" ]
To output the local path of all pending adds of a changelist you can use: ``` p4 opened -c changelist | grep -w add | sed 's/#.*//' \ | p4 -x - where | awk '/^\// {print $3}' ``` This does the same without grep but is a bit more obscure: ``` p4 opened -c changelist | sed -n 's/\(.*\)#.*- add .*/\1/p' \ | p4 -x - where | awk '/^\// {print $3}' ```
Local path for all files in a pending changelist without any external or platform-specific tools: ``` p4 -F %clientFile% fstat -Ro -F action=add [-e CHANGE] //... ``` Remove the '-F action=add' if you want to get files opened for all actions.
1,132,927
Note: This is a long winded question and requires a good understanding of the MVVM "design pattern", JSON and jQuery.... So I have a theory/claim that MVVM in DHTML is **possible** and **viable** and want to know if you agree/disagree with me and why. Implementing MVVM in DHTML revolves around using ajax calls to a server entity that returns JSON and then using html manipulation via javascript to control the html. So to break it down. Lets say I'm building a search page that searches for People in a database..... The **View** would look something like this: ``` <body **viewmodel="SearchViewModel"**> Search:<br /> <input type="text" **bindto="SearchString"** /><br /> <input type="button" value="Search" **command="Search"** /> <br /> <table **bindto="SearchResults"**> <thead> <tr> <th>First Name</th> <th>Last Name</th> </tr> </thead> <tbody> <tr> <td>${FirstName}</td> <td>${LastName}</td> </tr> </tbody> </table> </body> ``` Using some non standard attributes on my html elements, I have declaritively defined a **View** and how it will interact with my **ViewModel**. I've created a **MVVM parser in javascript** that interprets the non-standard attributes and associates the View with a JSON object that represents the ViewModel. The **ViewModel** would be a JSON object: ``` //View Model SearchViewModel would be assocaited with View because of <body **viewmodel="SearchViewModel"**> var SearchViewModel = { //SearchString variable has a TwoWay binding //to <input type="text" **bindto="SearchString"** />< //if a user types into the text box, the SearchString property will "auto-magically" be updated //because of the two way binding and how the element was interpreted via my **MVVM parser** SearchString: '', //SearchResults has a OneWay binding to <table **bindto="SearchResults"**> SearchResults: new Array(), //Search function will get "auto-magically" get called because of //the command binding to <input type="button" **command="Search"** /> Search: function() { //using jquery to call into the server asynchronously //when the server call is completed, the PopulateSearchResults method will be called $.getJSON("www.example.com/SearchForPerson", { searchString: SearchViewModel.SearchString }, SearchViewModel.PopulateSearchResults); } PopulateSearchResults: function(data) { //set the JSON array SearchViewModel.SearchResults = data; //**simulate INotifyPropertyChanged using the MVVM parser** mvvmParser.notifyPropertyChanged("SearchResults"); } } ``` The **Model** can be any server side asset that returns JSON...in this example, I used asp MVC as a restful facade: ``` public JsonResult SearchForPerson(string searchString) { PersonDataContext personDataContext = new PersonDataContext(); //linq to sql..... //search for person List<Person> results = personDataContext.Persons .Where(p => p.FirstName.Contains(searchString) || p.LastName.Contains(searchString)) .ToList(); return Json(results); } ``` So, again the question: **Is MVVM possible/viable in a DHTML RIA application (no Silverlight/WPF) or have I lost my mind?** **Could this "MVVM framework" be a good idea?** **Proof of Concept: [kaboom.codeplex.com](http://kaboom.codeplex.com).**
2009/07/15
[ "https://Stackoverflow.com/questions/1132927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40914/" ]
This would probably be a good time to link to [knockout JS](http://knockoutjs.com/), which is a javascript mvvm framework. You may also want to look at [backbone](http://documentcloud.github.com/backbone/), a javascript MVC framework:
Take a look at the ASP.NET data binding features in .NET 4.0 - comes out with Visual Studio 2010. This is exactly what you are looking for if you are ok with MS technology. [Blog that details the feature](http://blogs.visoftinc.com/archive/2009/05/27/ASP.NET-4.0-AJAX-Preview-4-Data-Binding.aspx) Community technology preview on [codeplex](http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=24645) Theoretically you could just include the ASP.NET AJAX js file from your HTML files & make the solution cross-platform. So to directly answer your question - it absolutely is a viable solution to the problem of creating maintainable, loosely coupled web user interfaces. And yes, the server side of your application is doing less - it becomes more of a true service layer, where all it deals with is data exchange. This is actually a good thing, b/c it promotes reuse across clients. Imagine your WPF app and your web app using the same middle tier server to send/receive data? Clients have a lot of available processing power anyway - why not leverage it to make you solution more scalable (the less the server is doing, the more work your clients are doing, which is distributed across ALL clients) The tricky part is two way binding - where you hook into the event that some object had changed, and the event that something in the user interface has changed (user typed something into an input control, for example). One way binding would still be useful. It seems like Microsoft is the only company right now building a full solution in the pattern you want. Yahoo's YUI library does do data binding that is semi-coherent, but not in the same pattern as WPF/Silverlight like you have built.
273,148
I have been trying to incorporate CCD linear array into my circuit. However, I have never dealt with electric shutter functions which are necessary to operate the CCD. Here is the link to the datasheet (pg 2,6-8): http //oceanoptics.com/wp-content/uploads/Toshiba-TCD1304AP-CCD-array.pdf Here are the parts that I'm struggling with. From the figure shown below, I know I need to have some sort of "function generation" for three inputs. [![enter image description here](https://i.stack.imgur.com/KpaMU.png)](https://i.stack.imgur.com/KpaMU.png) Here is the waveform as a function of time, which has to be maintained. [![enter image description here](https://i.stack.imgur.com/mHYvS.png)](https://i.stack.imgur.com/mHYvS.png) Well, I have never done anything as complicated as before, I don't know where to start, any pointers would be good. I'm hoping to do this in raspberry pi 3.
2016/12/05
[ "https://electronics.stackexchange.com/questions/273148", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/132139/" ]
At first - two basic considerations: * The impulse response is a **closed-loop** test in the **TIME** domain (and can give you some rough "impression" regarding the degree of stability); * The BODE diagram is an analysis of the **loop gain** (loop open) in the **FREQUENCY** domain (and can give you some figures for phase and/or gain margin). Hence, at first sight, both test are not related to each other. However, the term "stability" has the same meaning in both cases - and the mathematical tools of the system theory connect both domains to each other. **EDIT (UPDATE)**: Here is the desired answer to your update: Regarding stabiliy there is, In principle, no difference between control systems and electronic (opamp based) applications. The DEFINITION of stability is in the TIME domain (BIBO: bounded input gives bounded output), however, the exact proof of stability properties (expressed in terms of stability margins) is conveniently done in the FREQUENCY domain (loop gain analysis). Note that this is one of the main reasons for introducing the frequency domain and the complex frequency variable s.
What you are referring to is more related to a root locus plot rather than phase/gain margin. It will show how the system will react to an impulse ( including oscillation ) and whether the system is underdamped or overdamped. However this is different than gain and phase margin. The system could meet root locus stability criteria but have poor gain and phase margin. Gain/Phase show just how close a system is too having positive feed back. For example: If the thermostat for my office was located far away and it took me to 10min. to walk there and back *AND* the temperature change also took >10min. I would be constantly walking back and forth trying to get the temperature right because I the temperature I would 'sense' would not necessarily be what I just set on the thermostat. If I were to add enough overshoot the temperate would go unstable. This poor phase margin.
11,141,293
So I'm hoping somebody can just explain to my why when I run the following code, it prints ".link/output" at both the beginning and end of the line. I was trying to get it to print only at the end of the line. Any thoughts? ``` #!/usr/local/bin/perl use warnings; use strict; my $logfiles = $ARGV[0]; #file containing the list of all the log file names my @logf = (); my $i; open (F2, "<", $logfiles); while(<F2>){ @logf = $_; foreach $i(@logf){ print $_.".link/output"; } } close F2; ``` So for example, if the file I'm reading in is: ``` cat dog ``` I want to see: ``` cat.link/output dog.link/output ``` But isntead I am getting: ``` .link/outputcat.link/output .link/outputdog.link/output ``` Could anybody please explain to me why this is happening and/or how to fix it? Thank you.
2012/06/21
[ "https://Stackoverflow.com/questions/11141293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1440061/" ]
you have an empty element at the beginning of your list. simply `shift @logf`
I don't see what `@logf` does. Couldn't you just do this: ``` #!/usr/bin/env perl use warnings; use strict; my $logfiles = $ARGV[0]; #file containing the list of all the log file names #open(my $f2, "<", $logfiles); # FOR TESTING, use above in your code my $f2 = \*DATA; # =========== while(<$f2>){ chomp; print "$_.link/output\n"; } __DATA__ cat dog ```
275,797
I have questions about security of my computer, digital or informational security, for which there is an [Information Security](https://security.stackexchange.com/) site. The questions are also about security in a Linux Operating System, for which there is a [Stack Exchange community](https://unix.stackexchange.com/) and for Ubuntu which also has a [Stack Exchange site](https://askubuntu.com/). Where to ask them?
2016/02/17
[ "https://meta.stackexchange.com/questions/275797", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/303078/" ]
[Nathan's](https://meta.stackexchange.com/a/275807/155160) and [Robert's](https://meta.stackexchange.com/a/275800/155160) answers are on point, but also... Who do you want to hear from? Security experts or Linux experts? Tailoring your question to the right audience may get you better responses. Posting to both sites is also fine, provided you rephrase appropriately to stress the points relevant to each community. It's a "help them help you" kind of deal - the more you tailor to the site audience, the better the answer you're gonna get.
There's a good chance your question will fit well on any of the sites listed. Ask Ubuntu, if I'm not mistaken, caters a little more toward the GUI-friendly, end-user crowd than Unix & Linux, which is more goatees and CLI hacks that work across multiple distros. InfoSec handles things from a perhaps more generalized security standpoint, but it's still practical (as opposed to Crypto's theoretical approach), so the real question is which experts you expect to get the best answers from, keeping in mind that many users are active on two or three of those sites. If you like, you can ask the same basic question on multiple sites at once; however, there are two strong caveats to this. First is that you have to customize the question to focus on the particular site's strengths; cross-posting identical questions will likely get you downvotes or closevotes on some or all of the sites once someone finds out what you're doing. (If you don't know what the sites' strengths are well enough, this is probably impractical, and you shouldn't even try.) Second, be clear that this is what you're doing; seeming to hide a cross-post just makes people less friendly toward your posts, and you.
16,810,634
I'm working on Windows 8 and I want to try to disable the default edge gesture behaviors when my desktop app is fullscreen. I've found this [page](http://msdn.microsoft.com/en-us/library/windows/desktop/jj553591%28v=vs.85%29.aspx) which explains how to do it in C++. My app is a WPF/C# application and I've found the [Windows Code API Pack](http://archive.msdn.microsoft.com/WindowsAPICodePack) and the [SetWindowProperty](http://archive.msdn.microsoft.com/WindowsAPICodePack/WorkItem/View.aspx?WorkItemId=59) method to to the job. **Problem** I don't know how to pass the right parameter, which is a boolean : > > PropertyKey key = new > PropertyKey("32CE38B2-2C9A-41B1-9BC5-B3784394AA44", 2); > WindowProperties.SetWindowProperty(this, key, "true"); > > > PropertyKey key = new > PropertyKey("32CE38B2-2C9A-41B1-9BC5-B3784394AA44", 2); > WindowProperties.SetWindowProperty(this, key, "-1"); > > > PropertyKey key = new > PropertyKey("32CE38B2-2C9A-41B1-9BC5-B3784394AA44", 2); > WindowProperties.SetWindowProperty(this, key, "VARIANT\_TRUE"); > > > As you can see, the parameter has to be a string but no one works. If someone has an idea, thanks in advance !
2013/05/29
[ "https://Stackoverflow.com/questions/16810634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1520279/" ]
An easier solution would be using [Windows API Code Pack](https://www.nuget.org/packages/WindowsAPICodePack-Shell/). The code setting **System.AppUserModel.PreventPinning** property would be as easy as: ``` public static void PreventPinning(Window window) { var preventPinningProperty = new PropertyKey(new Guid("9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3"), 9); WindowProperties.SetWindowProperty(window, preventPinningProperty, "1"); } ```
> > I don't know how to pass the right parameter, which is a boolean. As you can see, the parameter has to be a string but no one works. > > > Pass the string `"1"` for `true`, or `"0"` for `false`.
19,126,370
I am using a cluster with [environment modules](http://modules.sourceforge.net/). This means that I must specifically load any R version other than the default (2.13) so to load R 3.0.1, I have to specify ``` module load R/3.0.1 R ``` I have added `module load R/3.0.1` to `.bashrc`, so that if I ssh into the server and load R, it opens 3.0.1 by default. But when I open R on the server (`M-x R`, starting data directory: `/ssh:myserver`), it loads the default R installation (2.13). This question is similar to previous questions except that I am accessing R on a server using a local installation of emacs. ([ESS to call different installations of R](https://stackoverflow.com/questions/5906909/ess-to-call-different-installations-of-r) and [How can I specify the R version opened by ESS session in emacs?](https://stackoverflow.com/questions/12574738/how-can-i-specify-the-r-version-opened-by-ess-session-in-emacs))
2013/10/01
[ "https://Stackoverflow.com/questions/19126370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/199217/" ]
**TL;DR** 1. Identify path of R module: `module show R/3.0.1` 2. add to your .emacs: `(add-to-list 'tramp-remote-path "/path/to/R-3.0.1/bin")` --- bash called by TRAMP via ssh does execute its initialization files but which files ultimately get executed depends on several things. You can check if your `~/.bashrc` gets executed at all when you use TRAMP to connect to the server by adding something like `echo "bashrc here"` to the file. Then set variable ``` (setq tramp-verbose 9) ``` and try connecting. Now see if you can spot that message in a buffer called `*debug tramp/ssh...*`. If you don't have any additional settings, TRAMP calls remote shell as `/bin/sh` (<http://www.gnu.org/software/tramp/#Remote-shell-setup>) so `bash` will execute `/etc/profile` and `~/.profile` (<http://www.gnu.org/software/bash/manual/html_node/Bash-Startup-Files.html#Bash-Startup-Files>). You can also see how the shell is called in that `*debug tramp/ssh...*` buffer, the relevant line will be ``` tramp-open-shell (5) # Opening remote shell `/bin/sh'...done ``` Try adding the `module load R/3.0.1` to `~/.profile` first. If that does not help, try forcing TRAMP to call `bash` by its proper name by setting ``` (setq explicit-shell-file-name "bash") (setq shell-file-name "bash") ``` UPDATE: If all else fails, you can just open shell `M-x shell`, then ssh to you server which should take care of the proper modules initialization (because you mentioned that interactive ssh connection works as expected). Once on the server, launch R and then do `M-x ess-remote` to make ESS aware of existing R session. This way you don't rely on TRAMP at all.
When TRAMP runs a shell command on the remote host, it calls `/bin/sh -c`. There doesn't seem to be a way to tell `sh` to source any files at initialization when it is called like that. So let's instead configure TRAMP to call `/bin/bash -c`. Then `bash` will source `BASH_ENV`, which we can point at a custom file that configures the modules. So, first, configure TRAMP to use `/bin/bash`. To do this, we need to modify the `tramp-methods` variable. It's an alist, where the keys are strings denoting the connection type. I use the `"scpx"` connection type, but you can change that to a whichever connection type you use. ``` (let ((scpx-method (cdr (assoc "scpx" tramp-methods)))) (add-to-list 'scpx-method '(tramp-remote-shell "/bin/bash")) (add-to-list 'tramp-methods (cons "scpx" scpx-method))) ``` Then, we can configure `tramp-remote-process-environment` to point at a file that will contain our module configuration. ``` (add-to-list 'tramp-remote-process-environment "BASH_ENV=~/.bash_env") ``` Then, open up the `~/.bash_env` file on the remote machine. You'll need to source the files that set up your module system. We use a different module system, so I'm not entirely sure what file you'll need, but perhaps you'll find it in `/etc/profile.d`. Here's what my file contains: ``` source /etc/profile.d/z00_lmod.sh module -q restore ``` Again, I'm not familiar with your module system, but that second line simply loads up my default set of modules. Lastly, since the module system configures your `PATH`, we need to get TRAMP to use it. By default, TRAMP just uses the contents of `tramp-remote-path`. But if you add `tramp-own-remote-path`, it will pull in the contents of `PATH`. ``` (add-to-list 'tramp-remote-path 'tramp-own-remote-path) ```
12,480
Suppose that I know [how an NPN transistor works](https://electronics.stackexchange.com/questions/12477/how-bjt-transistors-work-in-saturated-state). How different is a PNP transistor? What are the operational differences between a PNP and a NPN?
2011/04/03
[ "https://electronics.stackexchange.com/questions/12480", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/3411/" ]
PNP transistors work the same way as NPNs do but all voltages and currents are reversed. You connect the emitter to the higher potential, source current from the base and the main current flows into the emitter and then exits through the collector. \$V\_\rm{BE}\$ will be \$-0.7\,\rm{V}\$ but it's magnitude should be the same in both PNP and NPN if you use complementary parts.
NPN and PNP transistors are different. Electrons are more mobile than Holes Which means that PNP is not as good as NPN. For Si BJTs the PNP types are behind when it comes to breakdown voltage and really high power. For general purpose devices like BC337 / BC327 things for all intent and purpose are the same but if you wanted to do a off line SMPS it wouldnt be easy or practical at 1KW. For germanium the NPN is supposed to be better but it is not. This is due to manufacturing issues. The AC127 is not nearly as good as the AC128 and the AD161 is not as good as the AD162 and yes these devices were sold as matched pairs. The ratio of electron to hole mobility is a determining factor in how close the PNP will be to the NPN. This is much worse for SiC so one would expect lousey PNP BJTs so they probably wont bother making them. For some reason PNPs have lower noise so they are favoured in diff pair input stages. The abundance of highside driver chips is proof that PNP is not as good as NPN.
6,666,617
<http://dabbler.org/home/asdf/scrolling/test.html> Does anyone see anything wrong with this code? I can't figure out what is wrong with it, but my intentions are such that when the user hits the bottom of the page, the page scrolls to the top. Thanks.
2011/07/12
[ "https://Stackoverflow.com/questions/6666617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/839160/" ]
Your question can be solved a few different ways, so let's break it down and look at the individual requirements you've laid out: 1. Writes - It sounds like the bulk of what you're doing is append only writes at a relatively low volume (80 writes/second). Just about any product on the market with a reasonable storage backend is going to be able to handle this. You're looking at 50-500 "words" of data being saved. I'm not sure what constitutes a word, but for the sake of argument let's assume that a word is an average of 8 characters, so your data is going to be some kind of metadata, a key/timestamp/whatever plus 400-4000 bytes of words. Barring implementation specific details of different RDBMSes, this is still pretty normal, we're probably writing at most (including record overhead) 4100 bytes per record. This maxes out at 328,000 bytes per second or, as I like to put it, not a lot of writing. 2. Deletes - You also need the ability to delete your data. There's not a lot I can say about that. Deletes are deletes. 3. Reading - Here's where things get tricky. You mention that it's mostly primary keys and reads are being done on fresh data. I'm not sure what either of these mean, but I don't think that it matters. If you're doing key only lookups (e.g. I want record 8675309), then life is good and you can use just about anything. 4. Joins - If you need the ability to write actual joins where the database handles them, you've written yourself out of the major non-relational database products. 5. Data size/Data life - This is where things get fun. You've estimated your writes at 80/second and I guess at 4100 bytes per record or 328,000 bytes per second. There are 86400 seconds in a day, which gives us 28,339,200,000 bytes. Terrifying! That's 3,351,269.53125 KB, 27,026 MB, or roughly 26 GB / day. Even if you're keeping your data for 1 year, that's 9633 GB, or 10TB of data. You can lease 1 TB of data from a cloud hosting provider for around $250 per month or buy it from a SAN vendor like EqualLogic for about $15,000. Conclusion: I can only think of a few databases that *couldn't* handle this load. 10TB is getting a bit tricky and requires a bit of administration skill, and you might need to look at certain data lifecycle management techniques, but almost any RDBMS should be up to this task. Likewise, almost any non-relational/NoSQL database should be up to this task. In fact, almost any database of any sort should be up to the task. If you (or your team members) already have skills in a particular product, just stick with that. If there's a specific product that excels in your problem domain, use that. This isn't the type of problem that requires any kind of distributed magical unicorn powder.
Ok for MySQL I would advice you to use InnoDB without any indexes, expect on primary keys, even then, if you can skip them it would be good, in order to make input flow uninterrupted. Indexes optimize reading, but descrease the writing capabilities. You also may use PostgreSQL. Where you also need to skip indexes as well but you wont have a engine selection and its capabilities are also very strong for writing. This approach you want is actually used in some solutions, but with two db servers, or at least two databases. The first is receiving a lot of new data (your case), while the second communicates with the first and store it in a well-structured database (with indexes, rules, etc). And then when you need to read or make a snapshot of the data you refer the second server (or second database), where you can use transactions and so on. You should take a look and refer at Oracle Express (I think this was its name) and SQL Server Express Edition. The last two have better performance, but also some limitations. To have more detailed picture.
5,913,177
I have a new question for WCF gurus. So, I have a class `User` which is close to the 'User' representation from the DB which I use for database operations. Now, I would like to have 2 different service contracts that use this class as data contract, but each in their own way... I mean, ``` public class DBLayer { void InsertUsers(List<User> userList) { // both 'PropertyVisibleForService1' and 'PropertyVisibleForService2' // are used HERE to be inserted into their columns } } [DataContract] public class User { [DataMember] public string PropertyVisibleOnlyForService1{...} [DataMember] public string PropertyVisibleOnlyForService2{...} } [ServiceContract] public interface IService1 { List<User> GetUsers(); // user with 'PropertyVisibleOnlyForService1' inside } [ServiceContract] public interface IService2 { List<User> GetUsers(); // user with 'PropertyVisibleOnlyForService2' inside } ``` So, the idea is that each service will get a different kind of user, subset of `'User'`. Keeping in mind that I want to use the `'User'` as is for DB operations, what would be my options to achieve this? Do I really need to create different data contracts or is there another smarter way? Best would be to not only give me the solution, but also to explain me some best practices and alternatives. Thank you in advance. EDIT1: I added a dummy DBLayer class here for a better overview and why I think the inheritance may not be good in this case. A solution would be of having another '`UserForService1`' and '`UserForService2`' as data contracts which would map at the end from/into an '`User`' but I wanted some other points of view. EDIT2: Very good article which helped me in this case: <http://bloggingabout.net/blogs/vagif/archive/2009/03/29/iextensibledataobject-is-not-only-for-backward-compatibility.aspx>
2011/05/06
[ "https://Stackoverflow.com/questions/5913177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/208696/" ]
You could create separate DTO's for each service but your case would actually be ideal for a [Decorator pattern](http://en.wikipedia.org/wiki/Decorator_pattern): ``` [DataContract] public class UserForService1 : User { private User mUser; public UserForService1(User u) { mUser = u; } //expose only properties you'd like the user of this data contract to see [DataMember] public string SomeProperty { get { //always call into the 'wrapped' object return mUser.SomeProperty; } set { mUser.SomeProperty = value; } } // etc... } ``` and for Service2 similar code, that exposes only what you care for there...
As suggested in the comment, you can have two classes deriving from a base User then using [Data Contract Known Types](http://msdn.microsoft.com/en-us/library/ms730167.aspx), you can accomplish your desired goal. See the following links for more examples. <http://www.freddes.se/2010/05/19/wcf-knowntype-attribute-example/> <http://footheory.com/blogs/bennie/archive/2007/07/28/handling-data-contract-object-hierarchies-in-wcf.aspx>
21,578
I've been working as a web developer for almost a year now. Before this I spent 3 years in university on a bachelor degree, which included mostly practical tasks instead of theoretical exams. During the past 4 years, I've come to acknowledge that I work rather fast compared to my colleagues, but in exchange, my attention span is much shorter and I require more breaktime. For example, if someone spends 4 hours on a project, I could probably do it in 2 hours, but require a 2 hour break afterwards. While this is great for working on personal projects (quoted per project, not working hours), this is a bit troubling for my full-time job. I'm having a lot of trouble to actually focus on my work for 8 hours. I know I would perform a lot better if I could take breaks whenever I need them, but I can't just open up a game during work. My colleague in the office already is suspicious about what I do the entire day, as it often looks like I'm doing nothing (and I am, because I've lost my focus). How do I communicate to my colleague and/or boss how I feel about my own working pace? I think I would perform better if I could manage my own breaks and actually just open up a game during work, without stressing or having to worry about "being caught not-working" by my colleague. But I can hardly justify my boss paying me full-time while I'm working only half of it. For the record: Since I started here, I've always kept to all deadlines, and usually get praised for the quality of projects I deliver. I don't have any negative feedback from my boss, although my colleague in the office has expressed complaints about how I seem to "slack off".
2014/03/28
[ "https://workplace.stackexchange.com/questions/21578", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/18085/" ]
I work in bursts like this as well. Not only in terms of hours per day, but also in terms of weeks. I might go a couple weeks of doing very little, and then a couple with very high productivity. Over an average 8 hour day, I may only be actually 'coding' 2-3 hours. I've just learned to understand thats just how I operate. One habit I've adopted is to always get *something* done. Be it a new feature, a bug fix, whatever. This way I always have some concrete item of production I can demonstrate (even when its just to myself). Doing this may help mitigate the impression that you are slacking off at work (when you aren't actually slacking off, what you are really doing is thinking), which in turn should help you when dealing with those who might question your pace.
Following up to my own question as it's been 2 years now: I've tried following the advice here and also switched jobs 3 times since then, and the short answer to the question is: There is *very little* chance that your workplace is going to accomodate to your own working pace. Companies work with a 8h/day schedule, and that's it. You just need to learn to live with it. Now you can, however, try to make it more bearable for yourself. Working at a slower pace than what you are used to allows you to keep working for a longer time. As long as you keep your workpace matched to your colleagues, there should be no issues from your workplace out, even if this is slower than what you're used to. The advice from the other answers here also helps. For me personally, altering my workpace to the expectations of the company was very mentally exhausting though. If this is the case for you too, I can only suggest to find a place that allows working from home, or start as a freelancer if this is at all possible. That way, you can decide your own workpace and this certainly saves a lot of stress.
19,358,419
I would like to only have single checkbox selected at a time. My program reads from a textfile and creates checkboxes according to how many "answers" there are in the textfile. Does anyone know what is wrong with the code? ``` public partial class Form1 : Form { string temp = "questions.txt"; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { StreamReader sr = new StreamReader(temp); string line = ""; List<string> enLista = new List<string>(); while ((line = sr.ReadLine()) != null) { string[] myarray = line.Split('\r'); enLista.Add(myarray[0]); } sr.Close(); for (int i = 0; i < enLista.Count; i++) { if (enLista[i].Contains("?")) { Label lbl = new Label(); lbl.Text = enLista[i].ToString(); lbl.AutoSize = true; flowLayoutPanel1.Controls.Add(lbl); } else if (enLista[i] == "") { } else { CheckBox chk = new CheckBox(); chk.Text = enLista[i].ToString(); flowLayoutPanel1.Controls.Add(chk); chk.Click += chk_Click; } } } private void chk_Click(object sender, EventArgs e) { CheckBox activeCheckBox = sender as CheckBox; foreach (Control c in Controls) { CheckBox checkBox = c as CheckBox; if (checkBox != null) { if (!checkBox.Equals(activeCheckBox)) { checkBox.Checked = !activeCheckBox.Checked; } else { checkBox.Checked = true; } } } } } ```
2013/10/14
[ "https://Stackoverflow.com/questions/19358419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2752375/" ]
It's so simple to achieve what you want, however it's also so **strange**: ``` //We need this to hold the last checked CheckBox CheckBox lastChecked; private void chk_Click(object sender, EventArgs e) { CheckBox activeCheckBox = sender as CheckBox; if(activeCheckBox != lastChecked && lastChecked!=null) lastChecked.Checked = false; lastChecked = activeCheckBox.Checked ? activeCheckBox : null; } ```
1. Put the checkbox inside the groupbox control. 2. Loop the control enclosed on the groupbox 3. Find the checkbox name in the loop, if not match make the checkbox unchecked else checked the box. See Sample code: ``` //Event CheckedChanged of checkbox: private void checkBox6_CheckedChanged(object sender, EventArgs e) { CheckBox cb = (CheckBox)sender; if (cb.CheckState == CheckState.Checked) { checkboxSelect(cb.Name); } } //Function that will check the state of all checkbox inside the groupbox private void checkboxSelect(string selectedCB) { foreach (Control ctrl in groupBox1.Controls) { if (ctrl.Name != selectedCB) { CheckBox cb = (CheckBox)ctrl; cb.Checked = false; } } } ```
26,908,220
I want to create this layout: ![enter image description here](https://i.stack.imgur.com/i5GbK.png) ``` <div class="row"> <div class="col-md-4 col-sm-4 col-xs-4 line"></div> <div class="col-md-4 col-sm-4 col-xs-4"><img src="http://placepic.me/profiles/160-160" width="160" height="160" class="img-circle"></div> <div class="col-md-4 col-sm-4 col-xs-4 line"></div> </div> .line { width:460px; height:2px; background:#CCC; } .img-circle { border-radius: 50%; } ``` <http://jsfiddle.net/y8kcsr31/> I have even out the columns in the row but it still doesn't work. EDIT: Sorry, I trying to achieve this <https://www.dropbox.com/s/bjg2z5wud4yzy4d/Screenshot%202014-11-13%2011.49.49.png?dl=0>
2014/11/13
[ "https://Stackoverflow.com/questions/26908220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4247634/" ]
Your fiddle is not referencing bootstrap. Have a look now. [Updated Demo](http://jsfiddle.net/y8kcsr31/6/) and ``` .line { height:2px; background:#CCC; } ``` is enough. EDIT: You can try something like this : - <http://jsfiddle.net/y8kcsr31/10/>
The OP has a design pattern like this: ![enter image description here](https://i.stack.imgur.com/ocQXn.png) Using the grid system to accomplish this is not the correct way to get the desired result. Since there is no design pattern precisely like this in Bootstrap, let's find something similar: `.panel` Will work. *Learn more: <http://getbootstrap.com/components/#panels>* DEMO: <http://jsbin.com/yenade> ------------------------------- ![enter image description here](https://i.stack.imgur.com/UUsBi.png) **HTML very clean:** ``` <div class="panel panel-default panel-profile"> <div class="panel-heading text-center clearfix"> <h4>Name of Person</h4> <img src="http://placepic.me/profiles/50-50" class="img-circle"> <a href="#">Edit Profile</a> </div> <div class="panel-body"> Panel content </div> </div> ``` **CSS:** ``` .panel-profile .panel-heading { position: relative; } .panel-profile .panel-heading h4 { margin: 10px 0 20px; font-weight: normal; } .panel-profile .panel-heading img { margin: 0 auto 10px; display: block; border: 1px solid #ddd; background: #fff; } @media (min-width:400px) { .panel-profile .panel-heading a { font-size: .75em; float: right; } .panel-profile .panel-heading { margin-bottom: 30px; } .panel-profile .panel-heading img { position: absolute; margin: 0; display: inline; bottom: -25px; } } ```
56,434,820
Im trying to run a python3 application in a docker container using CentOS 7 as the base image. So if I'm just playing with it interactively, I type `scl enable rh-python36 bash` That obviously switches my standard python2 environment to the python3.6 environment I install earlier(in the Dockerfile) Now, earlier in the dockerfile I run the following: `SHELL ["scl", "enable", "rh-python36"]` (and many variations of this) This enables me to do all of my pip installations in this python3 environment. However, when I actually want to run my app.py with CMD, it defaults to the python2. I've tried playing with ENTRYPOINT and variations of CMD, but I cant seem to make the python3 environment active when the container finally runs. How can I get this running correctly with python3? Here's the dockerfile: ``` FROM centos:7 RUN mkdir -p /usr/src/app && \ yum install -y centos-release-scl && \ yum install -y rh-python36 && \ yum install -y rh-python36-python-tkinter SHELL ["scl", "enable", "rh-python36"] WORKDIR /usr/src/app COPY . . WORKDIR /usr/src/app/codeBase RUN pip install --no-cache-dir -r /usr/src/app/codeBase/requirements.txt EXPOSE 9000 CMD ["python", "run.py"] ``` I've also tried the alias solution, but I'm afraid it doesnt change the python exe for the CMD: Here's the totally runnable version with that that still prints out python 2.7.5: ``` FROM centos:7 RUN mkdir -p /usr/src/app && \ yum install -y centos-release-scl && \ yum install -y rh-python36 && \ yum install -y rh-python36-python-tkinter WORKDIR /usr/src/app RUN alias python=$(find / -type f -name "python*" | grep "python3.6$") CMD ["python", "-V"] ``` It just seems as though none of this persists in the new shell created with CMD
2019/06/03
[ "https://Stackoverflow.com/questions/56434820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7113104/" ]
So I figured this out thanks to the answer from C.Nivs and an answer [here](https://stackoverflow.com/questions/36388465/how-to-set-bash-aliases-for-docker-containers-in-dockerfile). The alias works in an interactive shell, but not for the CMD. What I ended up doing was similar, only in my case I'm creating a new executable in /usr/bin that calls the special python36 exe: ``` RUN echo -e '#!/bin/bash\n$(find / -type f -name "python*" | grep "python3.6$") "$@"' > /usr/bin/py3 && \ chmod +x /usr/bin/py3 CMD ["py3", "-V"] ``` now py3 runs a script calling the python3 install specifically with whatever argument
Configuring the shell environment variables by overriding them all to use scl\_source, as seen from following "Method #2" from Austin Dewey's [blog](https://austindewey.com/2019/03/26/enabling-software-collections-binaries-on-a-docker-image/) works for me. ``` FROM centos:7 SHELL ["/usr/bin/env", "bash", "-c"] RUN \ yum install -y centos-release-scl && \ yum install -y rh-python38-python-devel ENV \ BASH_ENV="/usr/bin/scl_enable" \ ENV="/usr/bin/scl_enable" \ PROMPT_COMMAND=". /usr/bin/scl_enable" RUN echo -e "\n\ unset BASH_ENV PROMPT_COMMAND ENV\n\ source scl_source enable rh-python38\n\ " > /usr/bin/scl_enable RUN \ python3 -m ensurepip && \ python3 -m pip install --upgrade pip && \ python3 -m pip install setuptools wheel ``` ```sh docker build --tag python:3.8-centos7 - < Dockerfile docker run --rm -i -t python:3.8-centos7 python3 --version ``` > > Python 3.8.11 > > > **NOTE:** This does not work when giving `python3 --version` as command. I have not been able to figure out a work-around. ```sh docker run --rm -i -t python:3.8-centos7 python3 --version ```
11,756,693
> > **Possible Duplicate:** > > [C++: Delete this?](https://stackoverflow.com/questions/3150942/c-delete-this) > > [Object-Oriented Suicide or delete this;](https://stackoverflow.com/questions/3959634/object-oriented-suicide-or-delete-this) > > > I wonder if the code below is run safely: ``` #include <iostream> using namespace std; class A { public: A() { cout << "Constructor" << endl; } ~A() { cout << "Destructor" << endl; } void deleteMe() { delete this; cout << "I was deleted" << endl; } }; int main() { A *a = new A(); a->deleteMe(); cout << "Exit ..."; return 0; } ``` Output is: ``` Constructor Destructor I was deleted Exit ... ``` and program exit normally, but are there some memory access violents here?
2012/08/01
[ "https://Stackoverflow.com/questions/11756693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1433300/" ]
It's ok to `delete this` in case no one will use the object after that call. And in case the object was allocated on a heap of course For example `cocos2d-x` game engine does so. It uses the same memory management scheme as `Objective-C` and here is a method of base object: ``` void CCObject::release(void) { CCAssert(m_uReference > 0, "reference count should greater than 0"); --m_uReference; if (m_uReference == 0) { delete this; } } ``` I don't think it's a `c++` way of managing memory, but it's possible
Absolutelly, you just run destructor. Methods does not belongs to object, so it runs ok. In external context object (\*a) will be destroyed.
236,968
We can use CORS to restrict API calls to a specific host in a web app. How to do the same for native mobile app? I want to restrict API calls from my app alone. Is it possible to do so?
2020/08/12
[ "https://security.stackexchange.com/questions/236968", "https://security.stackexchange.com", "https://security.stackexchange.com/users/79154/" ]
CORS doesn't prevent anything, and it doesn't protect the server. It simply tells a *conforming* client (a browser) what is permitted for the protection of the browser's *user*; CORS is a way to carefully make holes in the browser's **Same-Origin Policy**. Additionally, CORS headers are advisory, in that they don't actually prevent anything from happening. They make it so that a malicious attacker can't fool an innocent victim's browser into making certain requests (or, more often, using the responses to such requests) that the user wouldn't want the browser to make. A browser's user could, if it was wanted, open up the browser's dev console and make the request anyhow. Similarly, the user could export the request (cookies and all) to `curl` and - potentially after making more changes - send it from there. Any non-conforming client (such as in a mobile app, or just a shell script invoking `curl`), can and usually will completely ignore CORS. Such clients don't have a Same-Origin Policy to begin with, so there's nothing for CORS to make holes in and therefore it does nothing.
This is not possible using http headers alone. CORS only applies to browsers, not to any other clients. If you want to restrict api calls to your app, you need to implement some form of authentication. However, if your app is publicly available you have no way of keeping an api-key or something similar a secret if it is not unique per app installation.
27,969,891
I have a List and I'm looping through it removing items in the List if there is a match. I'm using i = -1 if the item in the List is removed. But it loops through from the beginning again. Is there a better way to do this? ``` private List<String> populateList(List<String> listVar) { List<String> list = new ArrayList<String>(); list.add("2015-01-13 09:30:00"); list.add("2015-01-13 06:22:12"); list.add("2015-01-12 05:45:10"); list.add("2015-01-12 01:52:40"); list.add("2015-01-12 02:23:45"); return list; } private void removeItems() { List<String> list = new ArrayList<String>(); list = populateList(list); System.out.println("List before modification : "+list); for (int i = 0; i < list.size(); i++) { String dateNoTime = list.get(i).split(" ")[0]; System.out.println(" Going over : "+list.get(i)); if(!dateNoTime.equalsIgnoreCase("2015-01-13")) { System.out.println(" Removing : "+list.get(i)); list.remove(i); i = -1; //This is making the loop start from scratch. Is there a better way? } } System.out.println("List after modification: "+list+"\n\n"); } ```
2015/01/15
[ "https://Stackoverflow.com/questions/27969891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1629109/" ]
Java's `List<T>` provides a better way of removing items from it by using `ListIterator<T>`: ``` ListIterator<String> iter = list.listIterator(); while (iter.hasNext()) { String s = iter.next(); String dateNoTime = s.split(" ")[0]; if(!dateNoTime.equalsIgnoreCase("2015-01-13")) { iter.remove(); } } ```
Or you can use guava API to achieve it. ``` FluentIterable .from(list) .transform(new Function<String, String>(){ @Override public void apply(String input){ return input.split(" ")[0]; } }).filter(new Predicate<String>(){ @Override public boolean apply(String input){ return input.equalsIgnoreCase("2015-01-13"); } }).toList(); ```
524,392
I'm trying to do this, and failing. Is there any reason why it wouldn't work in Django template syntax? I'm using the latest version of Django. ``` {% ifequal entry.created_at|timesince "0 minutes" %} ```
2009/02/07
[ "https://Stackoverflow.com/questions/524392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/326176/" ]
`{% ifequal %}` tag doesn't support filter expressions as arguments. It treats whole `entry.created_at|timesince` as identifier of the variable. Quik workaround: introduce intermediate variable with expresion result using `{% with %}` like this: ``` {% with entry.created_at|timesince as delta %} {% ifequal delta "0 minutes" %} .... {% endifequal %} {% endwith %} ```
See [ticket #5756](http://code.djangoproject.com/ticket/5756) and links in its comments for more information. A patch for Django in [ticket #7295](http://code.djangoproject.com/ticket/7295) implements this functionality. A broader refactoring of the template system based on [#7295](http://code.djangoproject.com/ticket/7295) is proposed in [ticket #7806](http://code.djangoproject.com/ticket/7806), and it would fix this issue among others. I don't think making such comparisons to work would be against the design philosophy of Django templates.
11,138,788
I have a Webview that is embedded inside a scrollview. The Webview itself has areas that are vertical scrollable. Now if I try to scroll inside the webview, the scrollview intercepts the touchevent and scrolls the whole webview instead that only the small scrollable div is moved. How can I make the scrollview work only if the webview does not want to scroll?
2012/06/21
[ "https://Stackoverflow.com/questions/11138788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/114066/" ]
In my case, I have a webview within a scrollview container, and the scrollview and webview are full screen. I was able to fix this by overriding the onTouch event in my webView touchListener. ``` scrollView = (ScrollView)findViewById(R.id.scrollview); webView.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { scrollView.requestDisallowInterceptTouchEvent(true); return false; } } ```
Our solution uses a Javascript callback through the [Javascript Interface](http://developer.android.com/reference/android/webkit/WebView.html#addJavascriptInterface%28java.lang.Object,%20java.lang.String%29). Every time a part of the UI that is scrollable inside the WebView is touched a listener is called through java script and this listener calls [requestDisallowInterceptTouchEvent](http://developer.android.com/reference/android/view/ViewParent.html#requestDisallowInterceptTouchEvent%28boolean%29) on the WebViews parent. This is not optimal but the nicest solution found at the moment. If the user scrolls very fast the layer in the WebView won't scroll but at a normal scroll rate it works fine.
2,678,504
How many solutions are there for $x^x=y^y$? I believe they are uncountable, but what is the proof? I have an example stating that $\frac{1}{2}^{\frac{1}{2}}=\frac{1}{4}^{\frac{1}{4}}$. What other examples and proofs of this are there?
2018/03/05
[ "https://math.stackexchange.com/questions/2678504", "https://math.stackexchange.com", "https://math.stackexchange.com/users/537797/" ]
The function $x^x$ has a single global minimum at $x = \frac{1}{e}$. You will notice that it is strictly decreasing from $x = 0$ to $x = \frac{1}{e}$ and strictly increasing from $x = \frac{1}{e}$ to infinity. Moreover it is continuous, so you can use the Intermediate Value Theorem to deduce how many times the function can take on certain values.
The example is *one* solution. What about $x = \frac12,$ $y = \frac12$? Is that a solution too? Why or why not? Can you come up with any other solutions? For how many values of $x$ can you find a solution?
25,750,240
Supposing that we have a array C with all element in C > 0 A pair of indices `(a, b)` is multiplicative if `0 ≤ a < b < N` and `C[a] * C[b] ≥ C[a] + C[b]`. with the time-complexity is O ( n ) * expected worst-case time complexity is O(N); I appreciate your help in supporting this case. Thanks.
2014/09/09
[ "https://Stackoverflow.com/questions/25750240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3737020/" ]
As always with competition problems, you have to solve the problem before you code it. In this case you'll need some basic algebra. I'll ignore the strange formatting of numbers and operate only on `C`. So, given a non-negative number `a`, what non-negative number `b` would yield `a * b >= a + b`? `a * b >= a + b` => `b * (a-1) >= a` Now, we have 4 cases: 1. 0 < a < 1. In this case the next step is `b <= a / (a-1)`. Note that the RHS is negative, while `b` is non-negative. Hence **there are no such `b`** 2. a == 0. Next step is `-b >= 0`, hence, since b is non-negative, **b == 0** 3. a == 1. Next step is `b * 0 >= 1` which simplifies to *false*. Hence, **there are no such `b`** 4. 1 < a. Next step is `b >= a / (a-1)`. This is the only non-trivial case. This, in itself, already gives you an O(N\* log(N)) algorithm: Iterate through the array keeping the sum. For each number, if it is 0, find the number of 0s in the array and add them to the sum. If it is 0 < `num` <= 1, add 0. If it is > 1, add the number of values >= `num / (num-1)`. **Since the array is ascending you can use binary search to find those values in `log(N)` time**, giving you a total `N * log(N)` worstcase runtime (And `O(N)` best runtime, in case all values are the noops - between 0 and 1) To make the last step to optimize the algorithm even further to O(N) you need to observe how the function `x / (x-1)` behaves when x > 1 and x is growing (i.e. what will your search target be as you iterate through the array).
The following condition: > > A pair of indices (P, Q) is multiplicative if 0 ≤ P < Q < N and C[P] \* C[Q] ≥ C[P] + C[Q]. > > > Combined with the presorted arrays: > > 4. real numbers created from arrays are sorted in non-decreasing order. > > > Allows a O(n) solution. Perhaps if you debug through your solution you'll see a pattern.
106,766
A common task in programs I've been working on lately is modifying a text file in some way. (Hey, I'm on Linux. Everything's a file. And I do large-scale system admin.) But the file the code modifies may not exist on my desktop box. And I probably don't want to modify it if it IS on my desktop. I've read about unit testing in Dive Into Python, and it's pretty clear what I want to do when testing an app that converts decimal to Roman Numerals (the example in DintoP). The testing is nicely self-contained. You don't need to verify that the program PRINTS the right thing, you just need to verify that the functions are returning the right output to a given input. In my case, however, we need to test that the program is modifying its environment correctly. Here's what I've come up with: 1) Create the "original" file in a standard location, perhaps /tmp. 2) Run the function that modifies the file, passing it the path to the file in /tmp. 3) Verify that the file in /tmp was changed correctly; pass/fail unit test accordingly. This seems kludgy to me. (Gets even kludgier if you want to verify that backup copies of the file are created properly, etc.) Has anyone come up with a better way?
2008/09/20
[ "https://Stackoverflow.com/questions/106766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19207/" ]
You're talking about testing too much at once. If you start trying to attack a testing problem by saying "Let's verify that it modifies its environment correctly", you're doomed to failure. Environments have dozens, maybe even millions of potential variations. Instead, look at the pieces ("units") of your program. For example, are you going to have a function that determines where the files are that have to be written? What are the inputs to that function? Perhaps an environment variable, perhaps some values read from a config file? Test that function, and don't actually do anything that modifies the filesystem. Don't pass it "realistic" values, pass it values that are easy to verify against. Make a temporary directory, populate it with files in your test's `setUp` method. Then test the code that writes the files. Just make sure it's writing the right contents file contents. Don't even write to a real filesystem! You don't need to make "fake" file objects for this, just use Python's handy `StringIO` modules; they're "real" implementations of the "file" interface, they're just not the ones that your program is actually going to be writing to. Ultimately you will have to test the final, everything-is-actually-hooked-up-for-real top-level function that passes the real environment variable and the real config file and puts everything together. But don't worry about that to get started. For one thing, you will start picking up tricks as you write individual tests for smaller functions and creating test mocks, fakes, and stubs will become second nature to you. For another: even if you can't quite figure out how to test that one function call, you will have a very high level of confidence that everything which it is calling works perfectly. Also, you'll notice that test-driven development forces you to make your APIs clearer and more flexible. For example: it's much easier to test something that calls an `open()` method on an object that came from somewhere abstract, than to test something that calls `os.open` on a string that you pass it. The `open` method is flexible; it can be faked, it can be implemented differently, but a string is a string and `os.open` doesn't give you any leeway to catch what methods are called on it. You can also build testing tools to make repetitive tasks easy. For example, twisted provides facilities for creating temporary files for testing [built right into its testing tool](http://twistedmatrix.com/documents/8.1.0/api/twisted.trial.unittest.TestCase.html#mktemp). It's not uncommon for testing tools or larger projects with their own test libraries to have functionality like this.
You might want to setup the test so that it runs inside a chroot jail, so you have all the environment the test needs, even if paths and file locations are hardcoded in the code [not really a good practice, but sometimes one gets the file locations from other places...] and then check the results via the exit code.
1,084,256
Is there a way that I can see when a Bluetooth device was last connected to my Windows 10 laptop?
2016/06/04
[ "https://superuser.com/questions/1084256", "https://superuser.com", "https://superuser.com/users/495177/" ]
Try the log file `%SystemRoot%\inf\setupapi.dev.log` for connection logs. Or use tools like [BluetoothView](http://www.nirsoft.net/utils/bluetooth_viewer.html) or [BluetoothLogView](http://www.nirsoft.net/utils/bluetooth_log_view.html) for monitoring Bluetooth devices in the vicinity of your laptop. There's timestamps and device states (like install, initiate, ...). If you cannot identify the device (should be BTH something for Bluetooth), connect the same device once more and look at the tail of the log to find the device ID.
If you go in "Devices and printers" and select a paired device, you may be able to find the last connection time there. Go in the hardware tab, click "Properties", then "Details" and choose the property called "Bluetooth last connected time". In my case, the time appears to be shifted in the future of two hours, but the minutes are correct. ![Device property window](https://i.stack.imgur.com/rhYAe.png)
46,441,922
I'm using > > php artisan storage:link to store the images to database. As expected Images are storing in database. But I've problem in retrieving the images and displaying them on the view.I tried different type of methods but not working. This is my code to get the records. > > > ```html public function show($id) { $Attendees=Attendee::where('event_id',$id)->OrderBy('first_name','ASC')->get(); return view('Attendee',['Attendees'=>$Attendees,'id'=>$id]); } ``` This is my code to display data on view. ```html <div class="col-sm-10" style="margin:0px 0px 0px 225px"> <a href="{{url('attendeeAdd',[$id])}}" style="float:right">Add Attendee</a> @foreach($Attendees as $deligate) <img src="{{ asset('images/$deligate->id') }}"> <h4><span>{{$deligate->first_name}}</span> <span>{{$deligate->last_name}}</span></h4> @endforeach </div> ``` can anyone help me on this please???
2017/09/27
[ "https://Stackoverflow.com/questions/46441922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8119147/" ]
If you *use* the MongoClient for any operation that contacts the MongoDB server, then the MongoClient must create connections and background threads. Once this has happened it is no longer safe to use it in a forked subprocess. For example, this is unsafe: ``` client = MongoClient(connect=False) client.admin.command('ping') # The client now connects. if not os.fork(): client.admin.command('ping') # This will print the warning. ``` Make sure that you aren't doing anything with the client before the fork that causes it to connect. Better yet, don't create the client before forking at all. Create your client after the fork, in the subprocess.
I had the same problem but with slightly different setup. For me it was Flask app and `MongoClient` was created via `flask_mongoengine`. Here is my [answer](https://stackoverflow.com/questions/51139089/mongoclient-opened-before-fork-create-mongoclient-only-flask/56474420#56474420)
162,691
I have about 1700 contacts in my google account. When I try to sync on my android it gets to 938 and then stops. The last sync date shows for about a month ago, and there's always a black sync icon next to it. I tried removing and re-adding the account to no avail. I even did a complete factory reset. No luck. What gives? Is there some error log somewhere where i might glean something? Thanks a million FWIW: There were a few days that showed 939 or 940 contacts, but most of the time it's 938. **UPDATE** I managed to find aLogcat for viewing logs. I tried to resync while the log was running. I'm pasting the log here, though I can't seem to find anything relevant. ===LOG START=== ``` W/IInputConnectionWrapper(22844): showStatusIcon on inactive InputConnection I/Timeline(22844): Timeline: Activity_idle id: android.os.BinderProxy@364c5b66 time:1222199 I/Timeline(22844): Timeline: Activity_idle id: android.os.BinderProxy@364c5b66 time:1235668 I/Timeline(22844): Timeline: Activity_idle id: android.os.BinderProxy@364c5b66 time:1267336 D/ViewRootImpl(22844): ViewPostImeInputStage ACTION_DOWN V/BitmapFactory(22844): DecodeImagePath(decodeResourceStream3) : res/drawable-xxhdpi-v4/ic_media_play.png D/ViewRootImpl(22844): ViewPostImeInputStage ACTION_DOWN D/ViewRootImpl(22844): ViewPostImeInputStage ACTION_DOWN D/ViewRootImpl(22844): ViewPostImeInputStage ACTION_DOWN D/ViewRootImpl(22844): ViewPostImeInputStage ACTION_DOWN V/BitmapFactory(22844): DecodeImagePath(decodeResourceStream3) : res/drawable-xxhdpi-v4/ic_menu_share.png V/BitmapFactory(22844): DecodeImagePath(decodeResourceStream3) : res/drawable-xxhdpi-v4/ic_menu_save.png V/BitmapFactory(22844): DecodeImagePath(decodeResourceStream3) : res/drawable-xxhdpi-v4/ic_menu_preferences.png D/AbsListView(22844): Get MotionRecognitionManager D/ViewRootImpl(22844): ViewPostImeInputStage ACTION_DOWN I/Timeline(22844): Timeline: Activity_launch_request id:org.jtb.alogcat time:1298449 E/ViewRootImpl(22844): sendUserActionEvent() mView == null V/BitmapFactory(22844): DecodeImagePath(decodeResourceStream3) : res/drawable-xxhdpi-v4/sym_def_app_icon.png D/AbsListView(22844): Get MotionRecognitionManager D/AbsListView(22844): Get MotionRecognitionManager D/Activity(22844): performCreate Call secproduct feature valuefalse D/Activity(22844): performCreate Call debug elastic valuetrue I/Timeline(22844): Timeline: Activity_idle id: android.os.BinderProxy@35c53605 time:1298728 D/ViewRootImpl(22844): ViewPostImeInputStage ACTION_DOWN D/AbsListView(22844): Get MotionRecognitionManager W/InputEventReceiver(22844): Attempted to finish an input event but the input event receiver has already been disposed. E/ViewRootImpl(22844): sendUserActionEvent() mView == null D/ViewRootImpl(22844): ViewPostImeInputStage ACTION_DOWN D/AbsListView(22844): Get MotionRecognitionManager D/ViewRootImpl(22844): ViewPostImeInputStage ACTION_DOWN W/InputEventReceiver(22844): Attempted to finish an input event but the input event receiver has already been disposed. E/ViewRootImpl(22844): sendUserActionEvent() mView == null D/ViewRootImpl(22844): ViewPostImeInputStage ACTION_DOWN D/ViewRootImpl(22844): ViewPostImeInputStage ACTION_DOWN I/Timeline(22844): Timeline: Activity_idle id: android.os.BinderProxy@364c5b66 time:1321370 D/ViewRootImpl(22844): ViewPostImeInputStage ACTION_DOWN D/ViewRootImpl(22844): ViewPostImeInputStage ACTION_DOWN D/ViewRootImpl(22844): ViewPostImeInputStage ACTION_DOWN D/ViewRootImpl(22844): ViewPostImeInputStage ACTION_DOWN D/AbsListView(22844): Get MotionRecognitionManager V/BitmapFactory(22844): DecodeImagePath(decodeResourceStream3) : res/drawable-xxhdpi-v4/ic_media_previous.png V/BitmapFactory(22844): DecodeImagePath(decodeResourceStream3) : res/drawable-xxhdpi-v4/ic_media_next.png D/ViewRootImpl(22844): ViewPostImeInputStage ACTION_DOWN W/InputEventReceiver(22844): Attempted to finish an input event but the input event receiver has already been disposed. W/InputEventReceiver(22844): Attempted to finish an input event but the input event receiver has already been disposed. E/ViewRootImpl(22844): sendUserActionEvent() mView == null --------- beginning of system W/ViewRootImpl(22844): Dropping event due to root view being removed: MotionEvent { action=ACTION_MOVE, id[0]=0, x[0]=543.0, y[0]=501.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=1336367, downTime=1336357, deviceId=9, source=0x1002 } D/ViewRootImpl(22844): ViewPostImeInputStage ACTION_DOWN D/AbsListView(22844): Get MotionRecognitionManager D/ViewRootImpl(22844): ViewPostImeInputStage ACTION_DOWN E/ViewRootImpl(22844): sendUserActionEvent() mView == null I/Timeline(22844): Timeline: Activity_idle id: android.os.BinderProxy@364c5b66 time:1389772 D/ViewRootImpl(22844): ViewPostImeInputStage ACTION_DOWN D/AbsListView(22844): Get MotionRecognitionManager D/ViewRootImpl(22844): ViewPostImeInputStage ACTION_DOWN W/InputEventReceiver(22844): Attempted to finish an input event but the input event receiver has already been disposed. E/ViewRootImpl(22844): sendUserActionEvent() mView == null D/ViewRootImpl(22844): ViewPostImeInputStage ACTION_DOWN D/AbsListView(22844): Get MotionRecognitionManager D/ViewRootImpl(22844): ViewPostImeInputStage ACTION_DOWN W/InputEventReceiver(22844): Attempted to finish an input event but the input event receiver has already been disposed. E/ViewRootImpl(22844): sendUserActionEvent() mView == null D/ViewRootImpl(22844): ViewPostImeInputStage ACTION_DOWN D/AbsListView(22844): Get MotionRecognitionManager D/ViewRootImpl(22844): ViewPostImeInputStage ACTION_DOWN I/Timeline(22844): Timeline: Activity_launch_request id:org.jtb.alogcat time:1403435 W/InputEventReceiver(22844): Attempted to finish an input event but the input event receiver has already been disposed. E/ViewRootImpl(22844): sendUserActionEvent() mView == null V/BitmapFactory(22844): DecodeImagePath(decodeResourceStream3) : res/drawable-xxhdpi-v4/sym_def_app_icon.png D/AbsListView(22844): Get MotionRecognitionManager D/AbsListView(22844): Get MotionRecognitionManager D/Activity(22844): performCreate Call secproduct feature valuefalse D/Activity(22844): performCreate Call debug elastic valuetrue I/Timeline(22844): Timeline: Activity_idle id: android.os.BinderProxy@e740a46 time:1403642 D/ViewRootImpl(22844): ViewPostImeInputStage ACTION_DOWN I/Timeline(22844): Timeline: Activity_idle id: android.os.BinderProxy@364c5b66 time:1406873 ``` ===LOG END===
2016/11/20
[ "https://android.stackexchange.com/questions/162691", "https://android.stackexchange.com", "https://android.stackexchange.com/users/145911/" ]
After short google search I found something that suppose to help: <https://play.google.com/store/apps/details?id=ru.ivary.ContactsSyncFix> try using it . if not, then you could do something like this : 1. Go to Google Contacts and Extract ALL contacts in CSV 2. Delete the contacts (Note that Google contacts has a recovery tool in case one messes up!) 3. Import the contacts in Google Contacts from the CSV file
in the end the solution was a combination of 2 steps: 1. i deleted all the contacts in the browser as suggested by @br0k3ngl255 , then i reran my sync function, and it was basically ok. 2. actually my sync function also had an issue, that a single contact had more then 1000 email addresses, which had kept the sync from running due to an over quota issue. now that both these issues were resolved, everything is working ok Thanks!
18,468,021
Background ---------- I am creating a video gallery using the ShadowBox jQuery plugin. To do this, I am creating rows of inline images using `display:inline-block`. The user will be able to upload a video as well as thumbnail images to accompany the video. The thumbnail's max size is 240x160 pixels. What I want to do is have a black border around each gallery thumbnail "slot" with the user's uploaded thumbnail residing inside of that "slot", so if the user uploads a 240x160 thumbnail, the thumbnail will fill up the "slot" completely, and if they upload a smaller image, the thumbnail will still be in the "slot" with some extra spacing around it. Here's an example of where I am right now: <http://jsfiddle.net/shaunp/HvZ5p/> The problem is that there is extra spacing below my thumbnails and I'm not sure why. If you inspect the code you will see that there is an extra 5 pixels lurking below the image and I'm not sure where it's coming from. The grey part below the image should be directly BEHIND the image so that in the case the user uploads a smaller thumbnail, there will be grey-background space around it, but for some reason it is too tall. Any suggestions? HTML ---- ``` <div class="inline"> <div class="bg-thumb"> <div class="cell-thumb"> <a href="#" rev="#nvcCaption#" class="shadow"> <img src="http://farm9.staticflickr.com/8330/8135703920_f2302b8415_m.jpg" class="thumbImg" alt="Thumb" /> </a> </div> </div> <div class="vcCaption">Caption</div> </div> <div class="inline"> <div class="bg-thumb"> <div class="cell-thumb"> <a href="#" rev="#nvcCaption#" class="shadow"> <img src="http://farm9.staticflickr.com/8330/8135703920_f2302b8415_m.jpg" class="thumbImg" alt="Thumb" /> </a> </div> </div> <div class="vcCaption">Caption</div> </div> ``` CSS --- ``` body { overflow:hidden; margin:0 50px 0 50px; } .vcCaption { text-align:center; font-family:"HelveticaNeue-Light","Helvetica Neue",Helvetica,Arial,sans-serif; font-size:14px; color:#000; margin-bottom:5px; } .inline { display:inline-block; } .bg-thumb { width:250px; height:170px; } .bg-thumb { text-align:center; display:table; margin-bottom:5px; } .cell-thumb { display:table-cell; vertical-align:middle; border:5px solid #000; background-color:#7f7f7f; } .thumbImg { max-width:240px; max-height:160px; } ```
2013/08/27
[ "https://Stackoverflow.com/questions/18468021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2657386/" ]
Add `vertical-align:top` to your thumbnails: ``` .thumbImg { max-width:240px; max-height:160px; vertical-align:top; } ``` **[jsFiddle example](http://jsfiddle.net/j08691/HvZ5p/1/)** The default value of [`vertical-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align) is `baseline`, but for your needs you'll want the images to align to the top. Another option would be to set the font size to zero on the containing div like: ``` .cell-thumb { display:table-cell; vertical-align:middle; border:5px solid #000; background-color:#7f7f7f; font-size:0; } ``` **[jsFiddle example](http://jsfiddle.net/j08691/HvZ5p/8/)**
Adding `vertical-align: middle;` to your image will solve that. ``` .thumbImg { vertical-align: middle; max-width:240px; max-height:160px; } ```
27,500,957
I'm trying to make a simple iOS game to learn programming in swift. The user inputs a 4 digits number in a text field (keyboard type number pad if that matters) and my program should take that 4 digits number and put each digit in an array. basically I want something like ``` userInput = "1234" ``` to become ``` inputArray = [1,2,3,4] ``` I know converting a string to an array of characters is very easy in swift ``` var text : String = "BarFoo" var arrayText = Array(text) //returns ["B","a","r","F","o","o"] ``` my problem is I need my array to be filled with Integers, not characters. If I convert the user input to an Int, it becomes a single number so if user enters "1234" the array gets populated by [1234] and not [1,2,3,4] So I tried to treat the user input as a string, make an array of its characters and, then loop through the elements of that array, convert them to Ints and put them into a second array, like: ``` var input : String = textField.text var inputArray = Array(input) var intsArray = [Int]() for var i = 0; i < inputArray.count ; i++ { intsArray[i] = inputArray[i].toInt() } ``` but it doesn't compile and gives me the error: `'Character' does not have a member named 'toint'` What am I doing wrong?
2014/12/16
[ "https://Stackoverflow.com/questions/27500957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1667981/" ]
Here is a much simpler solution for future users ``` let text : String = "12345" var digits = [Int]() for element in text.characters { digits.append(Int(String(element))!) } ```
**Convert String into [Int] extension - Swift Version** I put below extensions which allow you to convert `String` into `[Int]`. It's long version, where you can see what happen in each line with your string. ``` extension String { func convertToIntArray() -> [Int]? { var ints = [Int]() for char in self.characters { if let charInt = char.convertToInt() { ints.append(charInt) } else { return nil } } return ints } } extension Character { func convertToInt() -> Int? { return Int(String(self)) ?? nil } } ```
986,590
My laptop—a Toshiba Satellite C55-B5101—does not turn on anymore. This laptop contains many critical information. I tried a new power supply as that was the primary suspect, but still there is no indication of power. I have no clear idea how to connect internal hard drive to my desktop. How do I know what size of enclosure I need? based on Google there are 2.5 inch and 3.5 inch sizes. Also is this an easy thing to do? I never removed an internal hard drive for a laptop.
2015/10/14
[ "https://superuser.com/questions/986590", "https://superuser.com", "https://superuser.com/users/250045/" ]
RMarkwald's suggestion is a great way to go, especially if you only need a short-term hookup. You won't need to worry about getting the proper size enclosure. If you plan on leaving it attached long-term, an enclosure will provide more protection for it. Your drive is SATA and 2.5". Your laptop specs say it shipped with a 500GB drive, so it probably isn't a "slim" one (you can measure it; the thickness is usually stated in millimeters). Some enclosures will hold only a slim drive, so check the enclosure specs for the maximum thickness drive that will fit. There's heavy competition for dirt cheap enclosures, and the quality varies. Some have a high percentage that are DOA. Amazon is a good source and they have a big selection. More important, they have reviews. Pick an enclosure with a low percentage of bad reviews. As far as difficulty, I'm not familiar with your specific model, but on most laptops, the hard drive sits in an accessible compartment with a cover. The cover either slides off or is held closed with a screw. The drive just sits inside, plugged into a connector (it generally isn't fastened in). Once you remove the drive, you either plug the USB adapter onto its connector or install it in an enclosure. The enclosures are just a case with a connector at one end that you plug the drive into. So installation is basically following instructions to open the case, plug in the drive, and close the case (the case is usually held together with a few screws).
<https://m.wikihow.com/Recover-Data-from-the-Hard-Drive-of-a-Dead-Laptop> This link provides plenty of information. Getting the hard drive out is generally pretty easy. Good luck!
10,569
It seems that some rules of writing code are in direct contradiction with the rules of human writing. For example in code it's advisable to define each piece of information in only one place and in writing for humans it's normal to repeat important points (though usually phrased differently). **What rules of writing good code contradict the rules of good writing?**
2010/10/08
[ "https://softwareengineering.stackexchange.com/questions/10569", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/4422/" ]
``` Indentation rules (most coding standards impose) really contradict rules of good writing, the way people perceive information, and the grammar rules. Making things (that group naturally, but not syntactically) inside parenthesis also contradicts how texts are usually typed. If (you try to type text that way) you'll face misunderstanding even (if programmers read you) otherwise your text will be easy to read, and your writing will be productive ! ```
1. capitalizationIsUsuallyAtTheBeginning 2. underlines\_are\_usually\_under\_the\_words\_not\_the\_spaces 3. subject.verb(noun,noun)
171,720
I like to know it when I do or see something wrong. So I really like our flagging history (*x* moderator attention flags, *y* deemed helpful, *z* declined, etc.) I specifically find the declined / disputed flags interesting, because one can learn from his faults. However, now you have to scroll through *all* your good flags, to see your few bad flags. Can't we have a function to select only the helpful, only the declined or only the disputed? I also consider [blahdiblah's answer](https://meta.stackexchange.com/a/171730/205264) to be a very good idea: sort on flag type ('not an answer', 'spam', etc.) too.
2013/03/13
[ "https://meta.stackexchange.com/questions/171720", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/205264/" ]
I think it's just the great idea. I made a script which will load all of your helpful/ declined/ disputed flags. To use, first go to your flags history (`http://{some-se-site-there}.stackexchange.com/users/flag-summary/your-id`). Then run one of the following scripts. To show declined: ``` javascript:var pn=parseInt($(".pager.fr > a:nth-last-child(2)").attr("href").replace("?page=",""));$("#mainbar").text("");for(var i=1;i<pn+2;i++){$("#mainbar").append('<div id="mainbar'+i+'"></div>');$("#mainbar"+i).load(location.href+"?page="+i+" #mainbar > .flagged-post:has(span.Declined)", function(){$(".pager.fr").remove()});} ``` To show helpful: ``` javascript:var pn=parseInt($(".pager.fr > a:nth-last-child(2)").attr("href").replace("?page=",""));$("#mainbar").text("");for(var i=1;i<pn+2;i++){$("#mainbar").append('<div id="mainbar'+i+'"></div>');$("#mainbar"+i).load(location.href+"?page="+i+" #mainbar > .flagged-post:has(span.Helpful)", function(){$(".pager.fr").remove()});} ``` To show disputed: ``` javascript:var pn=parseInt($(".pager.fr > a:nth-last-child(2)").attr("href").replace("?page=",""));$("#mainbar").text("");for(var i=1;i<pn+2;i++){$("#mainbar").append('<div id="mainbar'+i+'"></div>');$("#mainbar"+i).load(location.href+"?page="+i+" #mainbar > .flagged-post:has(span.Disputed)", function(){$(".pager.fr").remove()});} ``` --- Also: the following one just loads all of your flags on one page, so you can use your browser search to find your flags of different types (e.g. type "not an answer" in your browser search to easily navigate between your NAA flags): ``` javascript:var pn=parseInt($(".pager.fr > a:nth-last-child(2)").attr("href").replace("?page=",""));$("#mainbar").text("");for(var i=1;i<pn+2;i++){$("#mainbar").append('<div id="mainbar'+i+'"></div>');$("#mainbar"+i).load(location.href+"?page="+i+" #mainbar", function(){$(".pager.fr").remove()});} ```
I'm fairly certain I got two declined flags last night. However, I was only able to find one of them. Because my flag history currently has pending flags that go back at least 15 pages (most of them have been handled, but not all), trying to find the rare exception among a huge list of helpful NAA and/or comment flags is really challenging. How can I decide to delete vote an answer that a mod declined? How can I learn from a mistake if the declined flag is buried? Perhaps I'm even remembering wrong about what my flag count was before I went to sleep? The high volume flaggers need this feature, which makes it, in my mind, a priority. There should be more rewards for the users who work hard to keep their Stacks clean.
13,979,371
I want to create a ListView in c++. My code so far: ``` InitCommonControls(); // Force the common controls DLL to be loaded. HWND list; // window is a handle to my window that is already created. list = CreateWindowEx(0, (LPCSTR) WC_LISTVIEWW, NULL, WS_VISIBLE | WS_CHILD | WS_BORDER | LVS_SHOWSELALWAYS | LVS_REPORT, 0, 0, 250, 400, window, NULL, NULL, NULL); LVCOLUMN lvc; lvc.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM; lvc.iSubItem = 0; lvc.pszText = "Title"; lvc.cx = 50; lvc.fmt = LVCFMT_LEFT; ListView_InsertColumn(list, 0, &lvc); ``` But if I compile and execute the code, just a blank window is beeing showed. Compiler: MinGW on Windows 7 (x86). Can anybody help me showing the listview properly?
2012/12/20
[ "https://Stackoverflow.com/questions/13979371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1432545/" ]
Here is the link to original MSDN sample code of [ListView control](http://csdata.iblogger.org/programming/CodeSamples/) written in Windows API and C. It compiles in VC++ 2010.
`WC_LISTVIEWW` (notice the extra W on the end) is a `wchar_t*`, but you are type-casting it to a `char*`. That will only compile if `UNICODE` is not defined, making the generic `CreateWindowEx()` map to `CreateWindowExA()`. Which means you are trying to create a Unicode window with the Ansi version of `CreateWindowEx()`. That will not work. You need to either: 1. use the generic `WC_LISTVIEW` so it matches the generic `CreateWindowEx`(), and get rid of the type-cast: ``` list = CreateWindowEx(..., WC_LISTVIEW, ...); ``` 2. keep using `WC_LISTVIEWW`, but call `CreateWindowExW()` instead: ``` list = CreateWindowExW(..., WC_LISTVIEWW, ...); ```
67,849,986
There are these two applications: * WordPress-site with REST-API. Let's call this **Brandon**. * Another system, using the REST-API. Let's call this **Jeremy**. I know about the WordPress Stack Exchange, but this is more a PHP question than it is a WordPress question (I think). --- The problem ----------- Jeremy creates and updates 'atoms' on Brandon. Whenever Jeremy updates an atom on Brandon, then immediately after, an operation called `BuildMolecules()` runs, that bulks the atoms into groups and updates electron-, neutron- and proton-information on the molecules on Brandon. But currently, this is being done on Jeremy's thread. This means that if Jeremy updates an atom, then it has to wait for the `BuildMolecules()` to finish, before it returns its response. And even worse, if something goes wrong, while BuildMolecules() runs, then Jeremy receives an error, which is wrong (Since the atom got updated as it should). This last thing could and should be solved with try/catch-statements, but still... How do I make a function that runs immediately after Jeremy updates an atom, without doing it on Jeremy's thread? --- Solution attempts and considerations ------------------------------------ **CRON-job** I considered running a cron-job every 5-10 seconds, checking if an atom was updated. And if so, then run an update operation. It just feels kind of naughty, since I would have to run this very often, to achieve a smooth integration between Jeremy and Brandon. But this should work. And if the run takes longer than the 5-10 seconds, then I would have to account for that, setting status or something, stopping `BuildMolecules()` to run twice, where it should only have been run once. **A new thread** Even if I could set up a new thread (I've never done anything like that), then I can read in this post here: [Creating new thread(?) in PHP](https://stackoverflow.com/a/8148586/1766219) that I shouldn't try to do it. **If WordPress offers a function for it** I looked into [WordPress' REST-documentation](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/), but couldn't find anything that could help me.
2021/06/05
[ "https://Stackoverflow.com/questions/67849986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1766219/" ]
Would a simple set of trigger mechanisms help? Jeremy updates an atom -> this triggers a request to be sent to Brandon to `BuildMolecule()`, sent in a curl request that doesn't need to wait for a response. That request has a `callback` parameter ``` $url = 'https://brandon.com/buildMolecule.php'; $curl = curl_init(); $post['callback'] = 'https://jeremy.com/onBuiltMolecule.php'; curl_setopt($curl, CURLOPT_URL, $url); curl_setopt ($curl, CURLOPT_POST, TRUE); curl_setopt ($curl, CURLOPT_POSTFIELDS, $post); curl_setopt($curl, CURLOPT_TIMEOUT, 1); curl_setopt($curl, CURLOPT_HEADER, 0); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_FORBID_REUSE, true); curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 1); curl_setopt($curl, CURLOPT_DNS_CACHE_TIMEOUT, 10); curl_setopt($curl, CURLOPT_FRESH_CONNECT, true); curl_exec($curl); curl_close($curl); ``` Brandon's machine runs BuildMolecule() but knows to grab the `$_POST['callback']` ``` function onCompleteBuildMolecule($moleculeDataArray) { $url = $_POST['callback']; $curl = curl_init(); $post['data'] = $moleculeDataArray; // the rest same as above's cURL ``` If this whole setup is too rudimentary, you can also utilize amazon's [SNS service](https://aws.amazon.com/sns/?whats-new-cards.sort-by=item.additionalFields.postDateTime&whats-new-cards.sort-order=desc) (which provides a more robust wrapper for the same type of interaction)
It depends on how you are calling the REST APIs. Is JavaScript involved? If so you could send the atom modification request and not call the build molecules on completion but instead just respond ok. Upon receipt of this "ok" you can send a background ajax request to rebuild the molecules. If this is a server to server relationship where JavaScript is not available, you can set a setting in the database that the molecules need rebuilding, and have this performed on a regular cron job. Lastly you could use the PHP CLI via the system function. ``` <?php system("nohup php -f /path/to/rebuild_molecules.php >/dev/null 2>&1 &"); ``` PHP will begin executing the rebuild\_molecules script but it will not wait for completion. <https://linux.die.net/man/1/nohup> Edit: If you use PHPFPM you can also use `fastcgi_finish_request` ``` echo 'ok'; fastcgi_finish_request(); do_build_molecules(); ``` <https://www.php.net/manual/en/function.fastcgi-finish-request.php>