qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
31,541,814
There are topics online that are discussing this problem however, I couldn't find any tidy explanation of the problem or any solid answers for the question. What I am trying to achieve is connecting Laravel 5.1 to MySQL Database of MAMP. --- In my ***config>app.php:*** ``` 'default' => env('DB_CONNECTION', 'mysql'), 'mysql' => [ 'driver' => 'mysql', 'host' => 'localhost:8889', 'database' => 'test', 'username' => 'root', 'password' => 'root', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'unix_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock', 'prefix' => '', 'strict' => false, ], ``` In my ***.env:*** ``` DB_HOST=localhost DB_DATABASE=test DB_USERNAME=root DB_PASSWORD=root ``` I also have ***.env.example:*** (which I believe has no functionality) ``` DB_HOST=localhost DB_DATABASE=homestead DB_USERNAME=homestead DB_PASSWORD=secret ``` I also have `create_users_table.php` and `create_password_resets_table.php` in my ***database>migrations*** (even though I did not run any migration:make) --- MAMP is directing and running the server successfully as it loads the project on localhost. --- Here is my MAMP settings: [![](https://i.imgur.com/T3KczgP.png "source: imgur.com")](https://imgur.com/T3KczgP) [![](https://i.imgur.com/wbySSkJ.png "source: imgur.com")](https://imgur.com/wbySSkJ) And the `test` database is created (with tables in it which I have previously created and used in my other projects, not Laravel.) [![](https://i.imgur.com/4V2r913.png "source: imgur.com")](https://imgur.com/4V2r913) --- Even though everything seems correct to me, when trying to submit Auth form, I am getting this error: > > ### PDOException in Connector.php line 50: > could not find driver > > > 1. in Connector.php line 50 > 2. at PDO->\_\_construct ('mysql:unix\_socket=/Applications/MAMP/tmp/mysql/mysql.sock;dbname=test', 'root', 'root', array('0', '2', '0', false, false)) in Connector.php line 50 > 3. at Connector->createConnection('mysql:unix\_socket=/Applications/MAMP/tmp/mysql/mysql.sock;dbname=test', array('driver' => 'mysql', 'host' => 'localhost:8889', 'database' => 'test', 'username' => 'root', 'password' => 'root', 'charset' => 'utf8', 'collation' => 'utf8\_unicode\_ci', 'unix\_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock', 'prefix' => '', 'strict' => false, 'name' => 'mysql'), array('0', '2', '0', false, false)) in MySqlConnector.php line 22 > > > and so on... > > >
2015/07/21
[ "https://Stackoverflow.com/questions/31541814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4705339/" ]
On mac or unix you have to include the socket path in the configuration database.php file i.e `'unix_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock',`
The most important thing for me was defining the UNIX socket. Because I have another MYSQL on my machine - Laravel was trying to connect to a database in that MYSQL process. Defining the UNIX for the MAMP database to be used worked perfectly. Try adding this to your MYSQL configuration in database.php ``` 'mysql' => [ 'driver' => 'mysql', 'host' => env('DB_HOST', '127.0.0.1'), 'port' => env('DB_PORT', '3306'), 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', ''), 'unix_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock', 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'prefix' => '', 'strict' => true, 'engine' => null, ], ```
31,541,814
There are topics online that are discussing this problem however, I couldn't find any tidy explanation of the problem or any solid answers for the question. What I am trying to achieve is connecting Laravel 5.1 to MySQL Database of MAMP. --- In my ***config>app.php:*** ``` 'default' => env('DB_CONNECTION', 'mysql'), 'mysql' => [ 'driver' => 'mysql', 'host' => 'localhost:8889', 'database' => 'test', 'username' => 'root', 'password' => 'root', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'unix_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock', 'prefix' => '', 'strict' => false, ], ``` In my ***.env:*** ``` DB_HOST=localhost DB_DATABASE=test DB_USERNAME=root DB_PASSWORD=root ``` I also have ***.env.example:*** (which I believe has no functionality) ``` DB_HOST=localhost DB_DATABASE=homestead DB_USERNAME=homestead DB_PASSWORD=secret ``` I also have `create_users_table.php` and `create_password_resets_table.php` in my ***database>migrations*** (even though I did not run any migration:make) --- MAMP is directing and running the server successfully as it loads the project on localhost. --- Here is my MAMP settings: [![](https://i.imgur.com/T3KczgP.png "source: imgur.com")](https://imgur.com/T3KczgP) [![](https://i.imgur.com/wbySSkJ.png "source: imgur.com")](https://imgur.com/wbySSkJ) And the `test` database is created (with tables in it which I have previously created and used in my other projects, not Laravel.) [![](https://i.imgur.com/4V2r913.png "source: imgur.com")](https://imgur.com/4V2r913) --- Even though everything seems correct to me, when trying to submit Auth form, I am getting this error: > > ### PDOException in Connector.php line 50: > could not find driver > > > 1. in Connector.php line 50 > 2. at PDO->\_\_construct ('mysql:unix\_socket=/Applications/MAMP/tmp/mysql/mysql.sock;dbname=test', 'root', 'root', array('0', '2', '0', false, false)) in Connector.php line 50 > 3. at Connector->createConnection('mysql:unix\_socket=/Applications/MAMP/tmp/mysql/mysql.sock;dbname=test', array('driver' => 'mysql', 'host' => 'localhost:8889', 'database' => 'test', 'username' => 'root', 'password' => 'root', 'charset' => 'utf8', 'collation' => 'utf8\_unicode\_ci', 'unix\_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock', 'prefix' => '', 'strict' => false, 'name' => 'mysql'), array('0', '2', '0', false, false)) in MySqlConnector.php line 22 > > > and so on... > > >
2015/07/21
[ "https://Stackoverflow.com/questions/31541814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4705339/" ]
The most important thing for me was defining the UNIX socket. Because I have another MYSQL on my machine - Laravel was trying to connect to a database in that MYSQL process. Defining the UNIX for the MAMP database to be used worked perfectly. Try adding this to your MYSQL configuration in database.php ``` 'mysql' => [ 'driver' => 'mysql', 'host' => env('DB_HOST', '127.0.0.1'), 'port' => env('DB_PORT', '3306'), 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', ''), 'unix_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock', 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'prefix' => '', 'strict' => true, 'engine' => null, ], ```
As far as I am concerned it doesn't make any sense to set in **database.php** as many of them suggested. Since this change would be mostly required in the **development mode**. So the proper way of setting the **unix\_socket** is as below file: **.env** ``` DB_SOCKET='/Applications/MAMP/tmp/mysql/mysql.sock' ``` By doing the above way already **.env** is included in **.gitignore** and won't create any other problem while your project is remotely deployed. > > NOTE: I have tested this setting in Laravel 5.7 and above versions > > >
31,541,814
There are topics online that are discussing this problem however, I couldn't find any tidy explanation of the problem or any solid answers for the question. What I am trying to achieve is connecting Laravel 5.1 to MySQL Database of MAMP. --- In my ***config>app.php:*** ``` 'default' => env('DB_CONNECTION', 'mysql'), 'mysql' => [ 'driver' => 'mysql', 'host' => 'localhost:8889', 'database' => 'test', 'username' => 'root', 'password' => 'root', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'unix_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock', 'prefix' => '', 'strict' => false, ], ``` In my ***.env:*** ``` DB_HOST=localhost DB_DATABASE=test DB_USERNAME=root DB_PASSWORD=root ``` I also have ***.env.example:*** (which I believe has no functionality) ``` DB_HOST=localhost DB_DATABASE=homestead DB_USERNAME=homestead DB_PASSWORD=secret ``` I also have `create_users_table.php` and `create_password_resets_table.php` in my ***database>migrations*** (even though I did not run any migration:make) --- MAMP is directing and running the server successfully as it loads the project on localhost. --- Here is my MAMP settings: [![](https://i.imgur.com/T3KczgP.png "source: imgur.com")](https://imgur.com/T3KczgP) [![](https://i.imgur.com/wbySSkJ.png "source: imgur.com")](https://imgur.com/wbySSkJ) And the `test` database is created (with tables in it which I have previously created and used in my other projects, not Laravel.) [![](https://i.imgur.com/4V2r913.png "source: imgur.com")](https://imgur.com/4V2r913) --- Even though everything seems correct to me, when trying to submit Auth form, I am getting this error: > > ### PDOException in Connector.php line 50: > could not find driver > > > 1. in Connector.php line 50 > 2. at PDO->\_\_construct ('mysql:unix\_socket=/Applications/MAMP/tmp/mysql/mysql.sock;dbname=test', 'root', 'root', array('0', '2', '0', false, false)) in Connector.php line 50 > 3. at Connector->createConnection('mysql:unix\_socket=/Applications/MAMP/tmp/mysql/mysql.sock;dbname=test', array('driver' => 'mysql', 'host' => 'localhost:8889', 'database' => 'test', 'username' => 'root', 'password' => 'root', 'charset' => 'utf8', 'collation' => 'utf8\_unicode\_ci', 'unix\_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock', 'prefix' => '', 'strict' => false, 'name' => 'mysql'), array('0', '2', '0', false, false)) in MySqlConnector.php line 22 > > > and so on... > > >
2015/07/21
[ "https://Stackoverflow.com/questions/31541814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4705339/" ]
On mac or unix you have to include the socket path in the configuration database.php file i.e `'unix_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock',`
As far as I am concerned it doesn't make any sense to set in **database.php** as many of them suggested. Since this change would be mostly required in the **development mode**. So the proper way of setting the **unix\_socket** is as below file: **.env** ``` DB_SOCKET='/Applications/MAMP/tmp/mysql/mysql.sock' ``` By doing the above way already **.env** is included in **.gitignore** and won't create any other problem while your project is remotely deployed. > > NOTE: I have tested this setting in Laravel 5.7 and above versions > > >
21,328,507
I want to generate sequential outcomes for a 3X5 slot machine. I have 5 reels of different length, e.g: ``` reel1 = [1,2,3,4,5], reel2 = [2,3,4,5,6,7], reel3 = [3,4,5,6,7,8,9], reel4 = [4,5,6,7,8,9,0,1], reel5 = [0,1,2]. ``` Right now I'm using Python for loop to generate the result, but I think it may not be an effective way as in total I need 5 for loops and if the reel length is very long, then it will take quite long time to do sequential generation. I think there may be a more effective way to do this using Python. Anyone have any ideas?~
2014/01/24
[ "https://Stackoverflow.com/questions/21328507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2774993/" ]
If you want random outcomes, you can use [`random.choice`](http://docs.python.org/2.7/library/random.html#random.choice): ``` from random import choice reels = [reel1, reel2, ...] outcome = [choice(reel) for reel in reels] ``` If you want all outcomes, use [`itertools.product`](http://docs.python.org/2/library/itertools.html#itertools.product): ``` from itertools import product for outcome in product(*reels): # use outcome ``` --- With your clarification that you want sets of three numbers, I would generate the positions up-front: ``` reelpos = [] for reel in reels: reelpos.append(list(zip(reel, reel[1:] + reel[:1], reel[2:] + reel[:2]))) ``` You can then apply `choice` or `product` to `reelpos`, which looks like: ``` [[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 1), (5, 1, 2)], [(2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7), (6, 7, 2), (7, 2, 3)], [(3, 4, 5), (4, 5, 6), (5, 6, 7), (6, 7, 8), (7, 8, 9), (8, 9, 3), (9, 3, 4)], [(4, 5, 6), (5, 6, 7), (6, 7, 8), (7, 8, 9), (8, 9, 0), (9, 0, 1), (0, 1, 4), (1, 4, 5)], [(0, 1, 2), (1, 2, 0), (2, 0, 1)]] ```
Not sure what you call "to generate sequential outcomes". If what you have in mind is the enumeration of all possible outcomes, keep using the five loops: there will be 5 x 6 x 7 x 8 x 3 = 5040 different combinations, not such a big number. Even 5 reels of 20 digits would remain quite manageable using Python (3200000 combinations).
1,191,444
I'd like to ask if there's a way to make chrome extension ONLY activated in incognito mode. I only want the extension activated in incognito mode and disabled in normal browsing. I do hope there's a way and thanks in advance.
2017/03/23
[ "https://superuser.com/questions/1191444", "https://superuser.com", "https://superuser.com/users/710152/" ]
You can't do exactly this. Closest way is to create a separate Chrome Profile and install extensions there.
You can do this but for that you require Opera Browser. Activating Extensions Only in Incognito is not possible in Chrome, Switch to Opera.
5,862,229
I have an application that displays the contents of messages in an MSMQ message queue. There is a problem with MSMQ on Windows 7 not preserving the true object type of the data in the message body. In the example, I send a byte[], and then later when I receive it, it's no longer a byte array, but the wrapped XML container document. In Windows XP I have never had this problem, and the Message.Body property has always correctly been set to a byte[]. Here is the compression code: ``` public void SendWithCompression(string Message) { try { // Compress the message data in memory. byte[] UncompressedData = Encoding.UTF8.GetBytes(Message); byte[] CompressedData = null; MemoryStream s = new MemoryStream(); using (GZipStream z = new GZipStream(s, CompressionMode.Compress)) { z.Write(UncompressedData, 0, UncompressedData.Length); } CompressedData = s.ToArray(); if (_Transaction != null) { _Transaction.Begin(); base.Send(CompressedData, _Transaction); _Transaction.Commit(); } else { base.Send(CompressedData); } } catch (Exception ex) { Console.WriteLine(ex.Message); } } ``` --- Here is the message contents for a test message. It ends up as an XML document that wraps the encoded binary data.: `<?xml version="1.0"?>..<base64Binary>H4sIAAAAAAAEAO29B2AcSZYlJi9tynt/SvVK1+B0oQiAYBMk2JBAEOzBiM3mkuwdaUcjKasqgcplVmVdZhZAzO2dvPfee++999577733ujudTif33/8/XGZkAWz2zkrayZ4hgKrIHz9+fB8/Ih63edMefTsvy2rv8V3+4/8ByygBlxMAAAA=</base64Binary>` --- Here is the decompression code it uses: ``` String Data; //Get message and format XML System.Messaging.Message m = MessagesList[ListIndex].Tag; m.Formatter = new XmlMessageFormatter(new Type[] { typeof(string), // Send raw plain strings typeof(byte[]), // Array of binary data typeof(XmlNode) // Xml document }); m.BodyStream.Position = 0; Data = m.Body.ToString(); if (m.Body.GetType() == typeof(byte[])) { try { // The message body is an array of binary data. // Assume it is a GZIP stream of compressed data. byte[] CompressedData = (byte[])m.Body; byte[] UncompressedData = null; // Decompress it. MemoryStream s = new MemoryStream(CompressedData); using (GZipStream z = new GZipStream(s, CompressionMode.Decompress)) { UncompressedData = MyExtensions.ReadRemainingBytes(z); } // Turn the bytes back into a string. Data = Encoding.UTF8.GetString(UncompressedData); } catch { Data = "Unknown binary data: " + BitConverter.ToString((byte[])m.Body, 0); } } if (m.Body.GetType() == typeof(XmlElement)) { XmlElement el = (XmlElement)m.Body; if (el.Name == "string") Data = el.InnerText; else Data = el.OuterXml; } ``` --- I would like to point out that I am setting the Formatter of the message, which is the first step to getting the body to automatically "box" and "unbox" in the queue. In Windows XP, m.Body.GetType() == byte[], like expected. But, in Windows 7, m.Body.GetType() == XmlElement, i.e. the wrapper XML. It no longer "unboxes" the message. Do we need to do something differently? We have worked around it once for sending strings, as you can see at the end of the receive function, but I would like to find a real answer for why this code behaves differently on Windows 7.
2011/05/02
[ "https://Stackoverflow.com/questions/5862229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/735072/" ]
Use the Message.BodyStream property if you want to send an array of bytes: ``` System.Messaging.MessageQueue queue = new MessageQueue(queueFormatName, false, true, QueueAccessMode.Send); System.Messaging.Message msg = new System.Messaging.Message(); msg.BodyStream = new MemoryStream(buffer); queue.Send(msg, MessageQueueTransactionType.Single); ```
Use `Message.BodyStream` property for sending and receiving message, take a look at code below you can send and receive `byte[]` using it. ``` public void SendMessage() { MessageQueue myQueue = new MessageQueue(".\\QUEUE"); byte[] msg = new byte[2]; msg[0] = 29; // Send the array to the queue. Message msg1 = new Message(); msg1.BodyStream = new MemoryStream(msg); messageQueue.Send(msg1); } public void ReceiveMessage() { MessageQueue myQueue = new MessageQueue(".\\QUEUE"); Message myMessage =myQueue.Receive(); byte[] msg = ReadFully(myMessage.BodyStream); } public static byte[] ReadFully(Stream input) { byte[] buffer = new byte[16 * 1024]; using (MemoryStream ms = new MemoryStream()) { int read; while ((read = input.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } return ms.ToArray(); } } ```
9,997,550
I have seen several post regarding making a build in Jenkins fail if the unit test execution fail (e.g. this [one](https://stackoverflow.com/questions/6681880/how-to-make-jenkins-display-fail-if-one-of-the-ant-tests-fail)). It turns out that by default Jenkins reports builds with failing tests as `unstable` and some people do not like that. This, however, will be perfectly fine for me. I just want to be able to easily differentiate builds with passing tests from such with failing tests. And here is the catch: **I am developing for Android** so my build is configured following [this page](https://wiki.jenkins-ci.org/display/JENKINS/Building+an+Android+app+and+test+project). Basically the tests are run with the following command: ``` ant all clean emma debug install test ``` As result coverage report is generated and published in Jenkins. All posts I have read about configuring the Jenkins result according to tests results were dealing with ant task manipulation. However, if we look at the android `build.xml` the Android tests are run with adb command: `adb shell am instrument ...`. I don't know how to configure this command to print the tests results. It can be configured to print the coverage report. I have already done that, but was never able to make the build fail according to the coverage report. I hope somebody else also faced the same problem and managed to solve it. Any guidance will be most appreciated.
2012/04/03
[ "https://Stackoverflow.com/questions/9997550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1108032/" ]
You have two options: Either use the `AsyncTask`'s method `get(long timeout, TimeUnit unit)` like that: ``` task.get(1000, TimeUnit.MILLISECONDS); ``` This will make your main thread wait for the result of the `AsyncTask` at most 1000 milliseconds (as per @user1028741 comment: actually there is also infinetly waiting method - [`AsyncTask#get()`](http://developer.android.com/reference/android/os/AsyncTask.html#get%28%29) which might also do the work for you in some cases). Alternatively you can show a progress dialog in the async task until it finishes. See this [thread](https://stackoverflow.com/a/4538370/1108032) (No need for me to copy past the code). Basically a progress dialog is shown while the async task runs and is hidden when it finishes. You have even third option:" if `Thread` is sufficient for your needs you can just use its `join` method. However, if the task is taking a long while you will still need to show a progress dialog, otherwise you will get an exception because of the main thread being inactive for too long.
``` intent = new Intent(this, OrdineCreaActivity.class); context.startActivityForResult(intent, R.id.buttonPagamenti); ``` Write the above lines in onPostExecute() of you AysncTask. Because if we are using AsyncTask it wont wait there until the task complete.
9,997,550
I have seen several post regarding making a build in Jenkins fail if the unit test execution fail (e.g. this [one](https://stackoverflow.com/questions/6681880/how-to-make-jenkins-display-fail-if-one-of-the-ant-tests-fail)). It turns out that by default Jenkins reports builds with failing tests as `unstable` and some people do not like that. This, however, will be perfectly fine for me. I just want to be able to easily differentiate builds with passing tests from such with failing tests. And here is the catch: **I am developing for Android** so my build is configured following [this page](https://wiki.jenkins-ci.org/display/JENKINS/Building+an+Android+app+and+test+project). Basically the tests are run with the following command: ``` ant all clean emma debug install test ``` As result coverage report is generated and published in Jenkins. All posts I have read about configuring the Jenkins result according to tests results were dealing with ant task manipulation. However, if we look at the android `build.xml` the Android tests are run with adb command: `adb shell am instrument ...`. I don't know how to configure this command to print the tests results. It can be configured to print the coverage report. I have already done that, but was never able to make the build fail according to the coverage report. I hope somebody else also faced the same problem and managed to solve it. Any guidance will be most appreciated.
2012/04/03
[ "https://Stackoverflow.com/questions/9997550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1108032/" ]
You have two options: Either use the `AsyncTask`'s method `get(long timeout, TimeUnit unit)` like that: ``` task.get(1000, TimeUnit.MILLISECONDS); ``` This will make your main thread wait for the result of the `AsyncTask` at most 1000 milliseconds (as per @user1028741 comment: actually there is also infinetly waiting method - [`AsyncTask#get()`](http://developer.android.com/reference/android/os/AsyncTask.html#get%28%29) which might also do the work for you in some cases). Alternatively you can show a progress dialog in the async task until it finishes. See this [thread](https://stackoverflow.com/a/4538370/1108032) (No need for me to copy past the code). Basically a progress dialog is shown while the async task runs and is hidden when it finishes. You have even third option:" if `Thread` is sufficient for your needs you can just use its `join` method. However, if the task is taking a long while you will still need to show a progress dialog, otherwise you will get an exception because of the main thread being inactive for too long.
try using ``` if (AppHelper.isOnline(this)) { while(!task.isCancelled()){ // waiting until finished protected String[] doInBackground(Void... params) } intent = new Intent(this, OrdineCreaActivity.class); this.startActivityForResult(intent, R.id.buttonPagamenti); } ``` For more information read <http://developer.android.com/reference/android/os/AsyncTask.html>
9,997,550
I have seen several post regarding making a build in Jenkins fail if the unit test execution fail (e.g. this [one](https://stackoverflow.com/questions/6681880/how-to-make-jenkins-display-fail-if-one-of-the-ant-tests-fail)). It turns out that by default Jenkins reports builds with failing tests as `unstable` and some people do not like that. This, however, will be perfectly fine for me. I just want to be able to easily differentiate builds with passing tests from such with failing tests. And here is the catch: **I am developing for Android** so my build is configured following [this page](https://wiki.jenkins-ci.org/display/JENKINS/Building+an+Android+app+and+test+project). Basically the tests are run with the following command: ``` ant all clean emma debug install test ``` As result coverage report is generated and published in Jenkins. All posts I have read about configuring the Jenkins result according to tests results were dealing with ant task manipulation. However, if we look at the android `build.xml` the Android tests are run with adb command: `adb shell am instrument ...`. I don't know how to configure this command to print the tests results. It can be configured to print the coverage report. I have already done that, but was never able to make the build fail according to the coverage report. I hope somebody else also faced the same problem and managed to solve it. Any guidance will be most appreciated.
2012/04/03
[ "https://Stackoverflow.com/questions/9997550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1108032/" ]
You have two options: Either use the `AsyncTask`'s method `get(long timeout, TimeUnit unit)` like that: ``` task.get(1000, TimeUnit.MILLISECONDS); ``` This will make your main thread wait for the result of the `AsyncTask` at most 1000 milliseconds (as per @user1028741 comment: actually there is also infinetly waiting method - [`AsyncTask#get()`](http://developer.android.com/reference/android/os/AsyncTask.html#get%28%29) which might also do the work for you in some cases). Alternatively you can show a progress dialog in the async task until it finishes. See this [thread](https://stackoverflow.com/a/4538370/1108032) (No need for me to copy past the code). Basically a progress dialog is shown while the async task runs and is hidden when it finishes. You have even third option:" if `Thread` is sufficient for your needs you can just use its `join` method. However, if the task is taking a long while you will still need to show a progress dialog, otherwise you will get an exception because of the main thread being inactive for too long.
Rafiq's response did not work for me - the app hung. I think the reason has to do with the nature of isCancelled(): "Returns true if this task was cancelled before it completed normally." If the task completes normally (i.e. is not cancelled) then `while(!task.isCancelled()) { }` will loop forever. To solve this create a Boolean flag that you instatiate to `false` and then flip to `true` in `task.onPostExecute()`. Then do `while(!flag) { }` before switching Activities. Additionally, if you'd like to give the main thread a 'break' to let the AsyncTask process a little faster, you can do try this: ``` while (!flag) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } ``` It seems to be working well for me.
9,997,550
I have seen several post regarding making a build in Jenkins fail if the unit test execution fail (e.g. this [one](https://stackoverflow.com/questions/6681880/how-to-make-jenkins-display-fail-if-one-of-the-ant-tests-fail)). It turns out that by default Jenkins reports builds with failing tests as `unstable` and some people do not like that. This, however, will be perfectly fine for me. I just want to be able to easily differentiate builds with passing tests from such with failing tests. And here is the catch: **I am developing for Android** so my build is configured following [this page](https://wiki.jenkins-ci.org/display/JENKINS/Building+an+Android+app+and+test+project). Basically the tests are run with the following command: ``` ant all clean emma debug install test ``` As result coverage report is generated and published in Jenkins. All posts I have read about configuring the Jenkins result according to tests results were dealing with ant task manipulation. However, if we look at the android `build.xml` the Android tests are run with adb command: `adb shell am instrument ...`. I don't know how to configure this command to print the tests results. It can be configured to print the coverage report. I have already done that, but was never able to make the build fail according to the coverage report. I hope somebody else also faced the same problem and managed to solve it. Any guidance will be most appreciated.
2012/04/03
[ "https://Stackoverflow.com/questions/9997550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1108032/" ]
try using ``` if (AppHelper.isOnline(this)) { while(!task.isCancelled()){ // waiting until finished protected String[] doInBackground(Void... params) } intent = new Intent(this, OrdineCreaActivity.class); this.startActivityForResult(intent, R.id.buttonPagamenti); } ``` For more information read <http://developer.android.com/reference/android/os/AsyncTask.html>
``` intent = new Intent(this, OrdineCreaActivity.class); context.startActivityForResult(intent, R.id.buttonPagamenti); ``` Write the above lines in onPostExecute() of you AysncTask. Because if we are using AsyncTask it wont wait there until the task complete.
9,997,550
I have seen several post regarding making a build in Jenkins fail if the unit test execution fail (e.g. this [one](https://stackoverflow.com/questions/6681880/how-to-make-jenkins-display-fail-if-one-of-the-ant-tests-fail)). It turns out that by default Jenkins reports builds with failing tests as `unstable` and some people do not like that. This, however, will be perfectly fine for me. I just want to be able to easily differentiate builds with passing tests from such with failing tests. And here is the catch: **I am developing for Android** so my build is configured following [this page](https://wiki.jenkins-ci.org/display/JENKINS/Building+an+Android+app+and+test+project). Basically the tests are run with the following command: ``` ant all clean emma debug install test ``` As result coverage report is generated and published in Jenkins. All posts I have read about configuring the Jenkins result according to tests results were dealing with ant task manipulation. However, if we look at the android `build.xml` the Android tests are run with adb command: `adb shell am instrument ...`. I don't know how to configure this command to print the tests results. It can be configured to print the coverage report. I have already done that, but was never able to make the build fail according to the coverage report. I hope somebody else also faced the same problem and managed to solve it. Any guidance will be most appreciated.
2012/04/03
[ "https://Stackoverflow.com/questions/9997550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1108032/" ]
Rafiq's response did not work for me - the app hung. I think the reason has to do with the nature of isCancelled(): "Returns true if this task was cancelled before it completed normally." If the task completes normally (i.e. is not cancelled) then `while(!task.isCancelled()) { }` will loop forever. To solve this create a Boolean flag that you instatiate to `false` and then flip to `true` in `task.onPostExecute()`. Then do `while(!flag) { }` before switching Activities. Additionally, if you'd like to give the main thread a 'break' to let the AsyncTask process a little faster, you can do try this: ``` while (!flag) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } ``` It seems to be working well for me.
``` intent = new Intent(this, OrdineCreaActivity.class); context.startActivityForResult(intent, R.id.buttonPagamenti); ``` Write the above lines in onPostExecute() of you AysncTask. Because if we are using AsyncTask it wont wait there until the task complete.
16,377
My cat catches a lot of mice and birds. It always leaves the heart, perfectly intact. My question is, what about the tails of the mice, the feathers of the birds? I sometimes find some feathers but never all of them. Does the cat eat it, and why does it leave the heart?
2017/02/10
[ "https://pets.stackexchange.com/questions/16377", "https://pets.stackexchange.com", "https://pets.stackexchange.com/users/-1/" ]
Cats are very picky with what they eat. Although hearts have a lot of good nutrients for cats, if a cat doesnt like the texture or taste, it might just reject it. Cats most likely won't eat the feathers or the tails, as they are harder to digest, but might occasionally eat a few. Although this is unrelated, and not a current issue for you, it will prevent future stress. Remember to get your cat regularily checked up on by the vet. Mice and birds can carry diseases.
Maybe the hearts are too tough to eat even with their sharp teeth, or maybe they are actually poisonous and therefore inedible. If either is the case, the cat knows, and therefore leaves it alone. As for the feathers, I think they are discarded since they're most likely as useless to the cat as the hearts.
16,377
My cat catches a lot of mice and birds. It always leaves the heart, perfectly intact. My question is, what about the tails of the mice, the feathers of the birds? I sometimes find some feathers but never all of them. Does the cat eat it, and why does it leave the heart?
2017/02/10
[ "https://pets.stackexchange.com/questions/16377", "https://pets.stackexchange.com", "https://pets.stackexchange.com/users/-1/" ]
Cats remove the feathers by licking them, and they’ll inevitably swallow some of them in the process; their mouth structure doesn’t really allow spitting stuff out like ours does. If it’s “your” cat, I assume you feed them? If so, they hunt primarily because their instincts tell them to, not for nutrition. They may eat the tastiest/easiest parts of their prey, but they’ll leave the less tasty or more difficult parts. Feral or stray cats will usually eat the entire prey, including bones, because they *need* to.
Maybe the hearts are too tough to eat even with their sharp teeth, or maybe they are actually poisonous and therefore inedible. If either is the case, the cat knows, and therefore leaves it alone. As for the feathers, I think they are discarded since they're most likely as useless to the cat as the hearts.
16,377
My cat catches a lot of mice and birds. It always leaves the heart, perfectly intact. My question is, what about the tails of the mice, the feathers of the birds? I sometimes find some feathers but never all of them. Does the cat eat it, and why does it leave the heart?
2017/02/10
[ "https://pets.stackexchange.com/questions/16377", "https://pets.stackexchange.com", "https://pets.stackexchange.com/users/-1/" ]
Cats are very picky with what they eat. Although hearts have a lot of good nutrients for cats, if a cat doesnt like the texture or taste, it might just reject it. Cats most likely won't eat the feathers or the tails, as they are harder to digest, but might occasionally eat a few. Although this is unrelated, and not a current issue for you, it will prevent future stress. Remember to get your cat regularily checked up on by the vet. Mice and birds can carry diseases.
Cats remove the feathers by licking them, and they’ll inevitably swallow some of them in the process; their mouth structure doesn’t really allow spitting stuff out like ours does. If it’s “your” cat, I assume you feed them? If so, they hunt primarily because their instincts tell them to, not for nutrition. They may eat the tastiest/easiest parts of their prey, but they’ll leave the less tasty or more difficult parts. Feral or stray cats will usually eat the entire prey, including bones, because they *need* to.
21,289,637
Hello I am trying to insert into a database and I am getting the error: ``` SQL Exception: java.sql.SQLException: Parameter index out of range (6 > number of parameters, which is 5). ``` The code causing this is: ``` PreparedStatement st = connection.prepareStatement("INSERT INTO Members VALUES ('?','?','?','?','?','?','?','?','?','?','?','?','?','?'','?','?','?','?','?'"); st.setString(1, username); st.setString(2, id); st.setString(3, firstName); st.setString(4, lastName); st.setString(5, address); st.setString(6, phone); st.setString(7, email); st.setInt(8, age); st.setString(9, String.valueOf(sex)); st.setDouble(10, height); st.setInt(11, kgs); st.setDouble(12, stone); st.setInt(13, targetWeightKgs); st.setDouble(14, bmi); st.setString(15, medicalHistory); st.setString(16, extraHistory); st.setBoolean(17, smoker); st.setBoolean(18, usernameCompleted); st.setString(19, myNotes); st.executeUpdate(); ```
2014/01/22
[ "https://Stackoverflow.com/questions/21289637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3211740/" ]
You should not quote your `?` placeholders, even if they represent string data. Quoted question marks will be intrepreted as literal `'?'` strings. It's probably interpreted as 5 parameters because your 6th to last parameter has two `'` characters, so your last 5 `?`s are interpreted as outside of single-quotes. Try ``` connection.prepareStatement("INSERT INTO Members VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); ``` **UPDATE** There was a closing ")" missing in the insert statement, that I have now added.
You do not need the `'` surrounding the `?`'s. ``` PreparedStatement st = connection.prepareStatement("INSERT INTO Members VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?"); ``` `BUT` the real problem here is you double single quoted one of the `?` to look like :`'?'',`
21,289,637
Hello I am trying to insert into a database and I am getting the error: ``` SQL Exception: java.sql.SQLException: Parameter index out of range (6 > number of parameters, which is 5). ``` The code causing this is: ``` PreparedStatement st = connection.prepareStatement("INSERT INTO Members VALUES ('?','?','?','?','?','?','?','?','?','?','?','?','?','?'','?','?','?','?','?'"); st.setString(1, username); st.setString(2, id); st.setString(3, firstName); st.setString(4, lastName); st.setString(5, address); st.setString(6, phone); st.setString(7, email); st.setInt(8, age); st.setString(9, String.valueOf(sex)); st.setDouble(10, height); st.setInt(11, kgs); st.setDouble(12, stone); st.setInt(13, targetWeightKgs); st.setDouble(14, bmi); st.setString(15, medicalHistory); st.setString(16, extraHistory); st.setBoolean(17, smoker); st.setBoolean(18, usernameCompleted); st.setString(19, myNotes); st.executeUpdate(); ```
2014/01/22
[ "https://Stackoverflow.com/questions/21289637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3211740/" ]
You should not quote your `?` placeholders, even if they represent string data. Quoted question marks will be intrepreted as literal `'?'` strings. It's probably interpreted as 5 parameters because your 6th to last parameter has two `'` characters, so your last 5 `?`s are interpreted as outside of single-quotes. Try ``` connection.prepareStatement("INSERT INTO Members VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); ``` **UPDATE** There was a closing ")" missing in the insert statement, that I have now added.
There is a mistake in your sample code at line `preparedStatement` if you have done the same mistake in your original code then it will not work! Check out the question marks and `'` you don't need `'`
21,289,637
Hello I am trying to insert into a database and I am getting the error: ``` SQL Exception: java.sql.SQLException: Parameter index out of range (6 > number of parameters, which is 5). ``` The code causing this is: ``` PreparedStatement st = connection.prepareStatement("INSERT INTO Members VALUES ('?','?','?','?','?','?','?','?','?','?','?','?','?','?'','?','?','?','?','?'"); st.setString(1, username); st.setString(2, id); st.setString(3, firstName); st.setString(4, lastName); st.setString(5, address); st.setString(6, phone); st.setString(7, email); st.setInt(8, age); st.setString(9, String.valueOf(sex)); st.setDouble(10, height); st.setInt(11, kgs); st.setDouble(12, stone); st.setInt(13, targetWeightKgs); st.setDouble(14, bmi); st.setString(15, medicalHistory); st.setString(16, extraHistory); st.setBoolean(17, smoker); st.setBoolean(18, usernameCompleted); st.setString(19, myNotes); st.executeUpdate(); ```
2014/01/22
[ "https://Stackoverflow.com/questions/21289637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3211740/" ]
You should not quote your `?` placeholders, even if they represent string data. Quoted question marks will be intrepreted as literal `'?'` strings. It's probably interpreted as 5 parameters because your 6th to last parameter has two `'` characters, so your last 5 `?`s are interpreted as outside of single-quotes. Try ``` connection.prepareStatement("INSERT INTO Members VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); ``` **UPDATE** There was a closing ")" missing in the insert statement, that I have now added.
replace '?' by ? ``` INSERT INTO Members VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?); ```
30,746,586
I have some scala futures. I can easily run them in parallel with `Future.sequence`. I can also run them one-after-another with something like this: ``` def serFut[A, B](l: Iterable[A])(fn: A ⇒ Future[B]) : Future[List[B]] = l.foldLeft(Future(List.empty[B])) { (previousFuture, next) ⇒ for { previousResults ← previousFuture next ← fn(next) } yield previousResults :+ next } ``` (Described [here](http://www.michaelpollmeier.com/execute-scala-futures-in-serial-one-after-the-other-non-blocking/)). Now suppose that I want to run them *slightly* in parallel - ie with the constraint that at most `m` of them are running at once. The above code does this for the special case of `m=1`. Is there a nice scala-idiomatic way of doing it for general `m`? Then for extra utility, what's the most elegant way to implement a kill-switch into the routine? And could I change `m` on the fly? My own solutions to this keep leading me back to procedural code, which feels rather wimpy next to scala elegance.
2015/06/10
[ "https://Stackoverflow.com/questions/30746586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/662694/" ]
You should accumulate the results in a dictionary. You should use the values of 'a' and 'b' to form a key of this dictionary Here, I have used a `defaultdict` to accumulate the entries ``` l1 = [{'a': 1, 'b': 2, 'c': 3, 'd': 4}, {'a': 5, 'b': 6, 'c': 7, 'd': 8}] l2 = [{'a': 5, 'b': 6, 'e': 100}, {'a': 1, 'b': 2, 'e': 101}] from collections import defaultdict D = defaultdict(dict) for lst in l1, l2: for item in lst: key = item['a'], item['b'] D[key].update(item) l3 = D.values() print l3 ``` output: ``` [{'a': 1, 'c': 3, 'b': 2, 'e': 101, 'd': 4}, {'a': 5, 'c': 7, 'b': 6, 'e': 100, 'd': 8}] ```
My approach is to sort the the combined list by the *key*, which is keys `a` + `b`. After that, for each group of dictionaries with similar key, combine them: ``` from itertools import groupby def ab_key(dic): return dic['a'], dic['b'] def combine_lists_of_dicts(list_of_dic1, list_of_dic2, keyfunc): for key, dic_of_same_key in groupby(sorted(list_of_dic1 + list_of_dic2, key=keyfunc), keyfunc): combined_dic = {} for dic in dic_of_same_key: combined_dic.update(dic) yield combined_dic l1 = [{'a': 1, 'b': 2, 'c': 3, 'd': 4}, {'a': 5, 'b': 6, 'c': 7, 'd': 8}] l2 = [{'a': 5, 'b': 6, 'e': 100}, {'a': 1, 'b': 2, 'e': 101}] for dic in combine_lists_of_dicts(l1, l2, ab_key): print dic ``` Discussion ========== * The function `ab_key` returns a tuple of value for key `a` and `b`, used for sorting a groupping * The `groupby` function groups all the dictionaries with similar keys together * This solution is less efficient than that of John La Rooy, but should work fine for small lists
30,746,586
I have some scala futures. I can easily run them in parallel with `Future.sequence`. I can also run them one-after-another with something like this: ``` def serFut[A, B](l: Iterable[A])(fn: A ⇒ Future[B]) : Future[List[B]] = l.foldLeft(Future(List.empty[B])) { (previousFuture, next) ⇒ for { previousResults ← previousFuture next ← fn(next) } yield previousResults :+ next } ``` (Described [here](http://www.michaelpollmeier.com/execute-scala-futures-in-serial-one-after-the-other-non-blocking/)). Now suppose that I want to run them *slightly* in parallel - ie with the constraint that at most `m` of them are running at once. The above code does this for the special case of `m=1`. Is there a nice scala-idiomatic way of doing it for general `m`? Then for extra utility, what's the most elegant way to implement a kill-switch into the routine? And could I change `m` on the fly? My own solutions to this keep leading me back to procedural code, which feels rather wimpy next to scala elegance.
2015/06/10
[ "https://Stackoverflow.com/questions/30746586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/662694/" ]
You should accumulate the results in a dictionary. You should use the values of 'a' and 'b' to form a key of this dictionary Here, I have used a `defaultdict` to accumulate the entries ``` l1 = [{'a': 1, 'b': 2, 'c': 3, 'd': 4}, {'a': 5, 'b': 6, 'c': 7, 'd': 8}] l2 = [{'a': 5, 'b': 6, 'e': 100}, {'a': 1, 'b': 2, 'e': 101}] from collections import defaultdict D = defaultdict(dict) for lst in l1, l2: for item in lst: key = item['a'], item['b'] D[key].update(item) l3 = D.values() print l3 ``` output: ``` [{'a': 1, 'c': 3, 'b': 2, 'e': 101, 'd': 4}, {'a': 5, 'c': 7, 'b': 6, 'e': 100, 'd': 8}] ```
Simple list operations would do the thing for you as well: ``` l1 = [{'a': 1, 'b': 2, 'c': 3, 'd': 4}, {'a': 5, 'b': 6, 'c': 7, 'd': 8}] l2 = [{'a': 5, 'b': 6, 'e': 100}, {'a': 1, 'b': 2, 'e': 101}] l3 = [] for i in range(len(l1)): for j in range(len(l2)): if l1[i]['a'] == l2[j]['a'] and l1[i]['b'] == l2[j]['b']: l3.append(dict(l1[i])) l3[i].update(l2[j]) ```
30,746,586
I have some scala futures. I can easily run them in parallel with `Future.sequence`. I can also run them one-after-another with something like this: ``` def serFut[A, B](l: Iterable[A])(fn: A ⇒ Future[B]) : Future[List[B]] = l.foldLeft(Future(List.empty[B])) { (previousFuture, next) ⇒ for { previousResults ← previousFuture next ← fn(next) } yield previousResults :+ next } ``` (Described [here](http://www.michaelpollmeier.com/execute-scala-futures-in-serial-one-after-the-other-non-blocking/)). Now suppose that I want to run them *slightly* in parallel - ie with the constraint that at most `m` of them are running at once. The above code does this for the special case of `m=1`. Is there a nice scala-idiomatic way of doing it for general `m`? Then for extra utility, what's the most elegant way to implement a kill-switch into the routine? And could I change `m` on the fly? My own solutions to this keep leading me back to procedural code, which feels rather wimpy next to scala elegance.
2015/06/10
[ "https://Stackoverflow.com/questions/30746586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/662694/" ]
You should accumulate the results in a dictionary. You should use the values of 'a' and 'b' to form a key of this dictionary Here, I have used a `defaultdict` to accumulate the entries ``` l1 = [{'a': 1, 'b': 2, 'c': 3, 'd': 4}, {'a': 5, 'b': 6, 'c': 7, 'd': 8}] l2 = [{'a': 5, 'b': 6, 'e': 100}, {'a': 1, 'b': 2, 'e': 101}] from collections import defaultdict D = defaultdict(dict) for lst in l1, l2: for item in lst: key = item['a'], item['b'] D[key].update(item) l3 = D.values() print l3 ``` output: ``` [{'a': 1, 'c': 3, 'b': 2, 'e': 101, 'd': 4}, {'a': 5, 'c': 7, 'b': 6, 'e': 100, 'd': 8}] ```
One can achieve a nice and quick solution using pandas. ``` l1 = [{'a': 1, 'b': 2, 'c': 3, 'd': 4}, {'a': 5, 'b': 6, 'c': 7, 'd': 8}] l2 = [{'a': 5, 'b': 6, 'e': 100}, {'a': 1, 'b': 2, 'e': 101}] import pandas as pd pd.DataFrame(l1).merge(pd.DataFrame(l2), on=['a','b']).to_dict('records') ```
30,746,586
I have some scala futures. I can easily run them in parallel with `Future.sequence`. I can also run them one-after-another with something like this: ``` def serFut[A, B](l: Iterable[A])(fn: A ⇒ Future[B]) : Future[List[B]] = l.foldLeft(Future(List.empty[B])) { (previousFuture, next) ⇒ for { previousResults ← previousFuture next ← fn(next) } yield previousResults :+ next } ``` (Described [here](http://www.michaelpollmeier.com/execute-scala-futures-in-serial-one-after-the-other-non-blocking/)). Now suppose that I want to run them *slightly* in parallel - ie with the constraint that at most `m` of them are running at once. The above code does this for the special case of `m=1`. Is there a nice scala-idiomatic way of doing it for general `m`? Then for extra utility, what's the most elegant way to implement a kill-switch into the routine? And could I change `m` on the fly? My own solutions to this keep leading me back to procedural code, which feels rather wimpy next to scala elegance.
2015/06/10
[ "https://Stackoverflow.com/questions/30746586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/662694/" ]
Simple list operations would do the thing for you as well: ``` l1 = [{'a': 1, 'b': 2, 'c': 3, 'd': 4}, {'a': 5, 'b': 6, 'c': 7, 'd': 8}] l2 = [{'a': 5, 'b': 6, 'e': 100}, {'a': 1, 'b': 2, 'e': 101}] l3 = [] for i in range(len(l1)): for j in range(len(l2)): if l1[i]['a'] == l2[j]['a'] and l1[i]['b'] == l2[j]['b']: l3.append(dict(l1[i])) l3[i].update(l2[j]) ```
My approach is to sort the the combined list by the *key*, which is keys `a` + `b`. After that, for each group of dictionaries with similar key, combine them: ``` from itertools import groupby def ab_key(dic): return dic['a'], dic['b'] def combine_lists_of_dicts(list_of_dic1, list_of_dic2, keyfunc): for key, dic_of_same_key in groupby(sorted(list_of_dic1 + list_of_dic2, key=keyfunc), keyfunc): combined_dic = {} for dic in dic_of_same_key: combined_dic.update(dic) yield combined_dic l1 = [{'a': 1, 'b': 2, 'c': 3, 'd': 4}, {'a': 5, 'b': 6, 'c': 7, 'd': 8}] l2 = [{'a': 5, 'b': 6, 'e': 100}, {'a': 1, 'b': 2, 'e': 101}] for dic in combine_lists_of_dicts(l1, l2, ab_key): print dic ``` Discussion ========== * The function `ab_key` returns a tuple of value for key `a` and `b`, used for sorting a groupping * The `groupby` function groups all the dictionaries with similar keys together * This solution is less efficient than that of John La Rooy, but should work fine for small lists
30,746,586
I have some scala futures. I can easily run them in parallel with `Future.sequence`. I can also run them one-after-another with something like this: ``` def serFut[A, B](l: Iterable[A])(fn: A ⇒ Future[B]) : Future[List[B]] = l.foldLeft(Future(List.empty[B])) { (previousFuture, next) ⇒ for { previousResults ← previousFuture next ← fn(next) } yield previousResults :+ next } ``` (Described [here](http://www.michaelpollmeier.com/execute-scala-futures-in-serial-one-after-the-other-non-blocking/)). Now suppose that I want to run them *slightly* in parallel - ie with the constraint that at most `m` of them are running at once. The above code does this for the special case of `m=1`. Is there a nice scala-idiomatic way of doing it for general `m`? Then for extra utility, what's the most elegant way to implement a kill-switch into the routine? And could I change `m` on the fly? My own solutions to this keep leading me back to procedural code, which feels rather wimpy next to scala elegance.
2015/06/10
[ "https://Stackoverflow.com/questions/30746586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/662694/" ]
My approach is to sort the the combined list by the *key*, which is keys `a` + `b`. After that, for each group of dictionaries with similar key, combine them: ``` from itertools import groupby def ab_key(dic): return dic['a'], dic['b'] def combine_lists_of_dicts(list_of_dic1, list_of_dic2, keyfunc): for key, dic_of_same_key in groupby(sorted(list_of_dic1 + list_of_dic2, key=keyfunc), keyfunc): combined_dic = {} for dic in dic_of_same_key: combined_dic.update(dic) yield combined_dic l1 = [{'a': 1, 'b': 2, 'c': 3, 'd': 4}, {'a': 5, 'b': 6, 'c': 7, 'd': 8}] l2 = [{'a': 5, 'b': 6, 'e': 100}, {'a': 1, 'b': 2, 'e': 101}] for dic in combine_lists_of_dicts(l1, l2, ab_key): print dic ``` Discussion ========== * The function `ab_key` returns a tuple of value for key `a` and `b`, used for sorting a groupping * The `groupby` function groups all the dictionaries with similar keys together * This solution is less efficient than that of John La Rooy, but should work fine for small lists
One can achieve a nice and quick solution using pandas. ``` l1 = [{'a': 1, 'b': 2, 'c': 3, 'd': 4}, {'a': 5, 'b': 6, 'c': 7, 'd': 8}] l2 = [{'a': 5, 'b': 6, 'e': 100}, {'a': 1, 'b': 2, 'e': 101}] import pandas as pd pd.DataFrame(l1).merge(pd.DataFrame(l2), on=['a','b']).to_dict('records') ```
30,746,586
I have some scala futures. I can easily run them in parallel with `Future.sequence`. I can also run them one-after-another with something like this: ``` def serFut[A, B](l: Iterable[A])(fn: A ⇒ Future[B]) : Future[List[B]] = l.foldLeft(Future(List.empty[B])) { (previousFuture, next) ⇒ for { previousResults ← previousFuture next ← fn(next) } yield previousResults :+ next } ``` (Described [here](http://www.michaelpollmeier.com/execute-scala-futures-in-serial-one-after-the-other-non-blocking/)). Now suppose that I want to run them *slightly* in parallel - ie with the constraint that at most `m` of them are running at once. The above code does this for the special case of `m=1`. Is there a nice scala-idiomatic way of doing it for general `m`? Then for extra utility, what's the most elegant way to implement a kill-switch into the routine? And could I change `m` on the fly? My own solutions to this keep leading me back to procedural code, which feels rather wimpy next to scala elegance.
2015/06/10
[ "https://Stackoverflow.com/questions/30746586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/662694/" ]
Simple list operations would do the thing for you as well: ``` l1 = [{'a': 1, 'b': 2, 'c': 3, 'd': 4}, {'a': 5, 'b': 6, 'c': 7, 'd': 8}] l2 = [{'a': 5, 'b': 6, 'e': 100}, {'a': 1, 'b': 2, 'e': 101}] l3 = [] for i in range(len(l1)): for j in range(len(l2)): if l1[i]['a'] == l2[j]['a'] and l1[i]['b'] == l2[j]['b']: l3.append(dict(l1[i])) l3[i].update(l2[j]) ```
One can achieve a nice and quick solution using pandas. ``` l1 = [{'a': 1, 'b': 2, 'c': 3, 'd': 4}, {'a': 5, 'b': 6, 'c': 7, 'd': 8}] l2 = [{'a': 5, 'b': 6, 'e': 100}, {'a': 1, 'b': 2, 'e': 101}] import pandas as pd pd.DataFrame(l1).merge(pd.DataFrame(l2), on=['a','b']).to_dict('records') ```
58,947,053
I am confused about what is business logic. I assume that it is written in Controller but then I search it on internet but i found that many person say that it refers to model. I am highly confused. And somee community meembers give me suggestions that my question is same but you are doing mistake. I am confused by the answers in those questions. Someone says model is business logic but I assume that Controller is business logic. So Please understand my doubt.
2019/11/20
[ "https://Stackoverflow.com/questions/58947053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12302811/" ]
You can use `array_filter` with `callback` to return only type which is checkbox. ``` $filtered = array_filter($array, function($v){return $v['type'] == 'checkbox' && $v['is_active'] == 1;}); ``` Working example :- <https://3v4l.org/idAR4>
Edit of answer @Rakesh Jakhar One more condition added as per the question ``` <?php // Your code here! $actions = array( array( 'type' => 'checkbox', 'id' => 'f0', 'is_active' => 1 ), array( 'type' => 'checkbox', 'id' => 'f1', 'is_active' => 0 ), array( 'type' => 'radio', 'id' => 'f2', 'is_active' => 0 ), array( 'type' => 'checkbox', 'id' => 'f3', 'is_active' => 1 ), array( 'type' => 'text', 'id' => 'f4', 'is_active' => 1 ), array( 'type' => 'checkbox', 'id' => 'f5', 'is_active' => 0 ), array( 'type' => 'checkbox', 'id' => 'f6', 'is_active' => 1 ) ); $filtered = array_filter($actions, function($v){return $v['type'] == 'checkbox' && $v['is_active']==1 ;}); print_r($filtered); ?> ```
58,947,053
I am confused about what is business logic. I assume that it is written in Controller but then I search it on internet but i found that many person say that it refers to model. I am highly confused. And somee community meembers give me suggestions that my question is same but you are doing mistake. I am confused by the answers in those questions. Someone says model is business logic but I assume that Controller is business logic. So Please understand my doubt.
2019/11/20
[ "https://Stackoverflow.com/questions/58947053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12302811/" ]
You can use `array_filter` with `callback` to return only type which is checkbox. ``` $filtered = array_filter($array, function($v){return $v['type'] == 'checkbox' && $v['is_active'] == 1;}); ``` Working example :- <https://3v4l.org/idAR4>
You also can sue `array_reduce`, [Demo](https://3v4l.org/CnX47) ``` $filtered = array_reduce($array, function($a,$b){ if($b['type'] == 'checkbox' && $b['is_active'] == 1){ $a[] = $b; return $a; }else{ return $a; }},[]); print_r($filtered); ```
58,947,053
I am confused about what is business logic. I assume that it is written in Controller but then I search it on internet but i found that many person say that it refers to model. I am highly confused. And somee community meembers give me suggestions that my question is same but you are doing mistake. I am confused by the answers in those questions. Someone says model is business logic but I assume that Controller is business logic. So Please understand my doubt.
2019/11/20
[ "https://Stackoverflow.com/questions/58947053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12302811/" ]
Edit of answer @Rakesh Jakhar One more condition added as per the question ``` <?php // Your code here! $actions = array( array( 'type' => 'checkbox', 'id' => 'f0', 'is_active' => 1 ), array( 'type' => 'checkbox', 'id' => 'f1', 'is_active' => 0 ), array( 'type' => 'radio', 'id' => 'f2', 'is_active' => 0 ), array( 'type' => 'checkbox', 'id' => 'f3', 'is_active' => 1 ), array( 'type' => 'text', 'id' => 'f4', 'is_active' => 1 ), array( 'type' => 'checkbox', 'id' => 'f5', 'is_active' => 0 ), array( 'type' => 'checkbox', 'id' => 'f6', 'is_active' => 1 ) ); $filtered = array_filter($actions, function($v){return $v['type'] == 'checkbox' && $v['is_active']==1 ;}); print_r($filtered); ?> ```
You also can sue `array_reduce`, [Demo](https://3v4l.org/CnX47) ``` $filtered = array_reduce($array, function($a,$b){ if($b['type'] == 'checkbox' && $b['is_active'] == 1){ $a[] = $b; return $a; }else{ return $a; }},[]); print_r($filtered); ```
11,424
Me and my sister in law bought a house. We asked her help to acquire the loan. She signed the mortgage loan for a 5 year contract, and we got the house. Me and my wife paid all the expenses and down payment for the house, my sister in law never gave a single cent for acquiring the house. The title stated she has 5% share and 95% for me. We all live in the same house and she is paying me 600 a month because she came to live with us with her two kids and with the 600 everything is inclusive down to utilities. Something went wrong and now she wants her name out of the mortgage and she is claiming her 5% share. Me and my wife are paying the mortgage and never had any default, we pay property taxes, insurance and all the utilities, my wife maintains the house and we renovated the house significantly without any help from her. Do I have the right to refuse her demand to remove her name since I believe I cannot stand alone yet on the mortgage?
2016/07/07
[ "https://law.stackexchange.com/questions/11424", "https://law.stackexchange.com", "https://law.stackexchange.com/users/-1/" ]
I can't help with the relationship issues: here are the legal issues. 1. She legally owns 5% of the house and you own 95% 2. I presume that the loan agreement is a contract between you, her and the lender so removing her name from the loan is at the discretion of the lender, not you or her. I would be very surprised if the lender would allow this without totally refinancing the loan. 3. Whatever arrangements you had with your sister are *probably* not enforceable because the presumption is that arrangements between family members are *not* legally enforceable contracts. Unless you can provide evidence that both of you intended to create legally binding obligations for what you assert (like a signed document) then what you say is just hot air. Legally, neither of you have the power to get her name off the loan. As a co-owner she is entitled to live in the property rent free. Each of you is jointly (i.e. together) and severally (i.e. individually) liable for making the loan repayments - in what proportion that should be done is a matter for you two to sort out - the lender doesn't care who pays so long as they get paid. <https://www.law.cornell.edu/wex/tenancy_in_common>
You don't need to do anything - (or I won't) let her move to perfect her claimed interest. You have facts to show pattern of payment (600 that sets a contract) and other facts which would result in minimum costs - 1st get a comparable value of the house -in order to determine what 5% represents - let's say, the house needs work -new roof etc., that would subtract from comparable value - personally, I sit back and let her try to enforce the 5% but I be happy to take her name off it - then (if you want) give her a promissory note (that is allows for your discretion to pay) for the 5% (without interest) to be paid when ever the house is no longer under your control -which includes inheritance to wit: controlled by you still when transferred to your heirs - having 5% of something versus enforcing it is a whole other creature - given I see no power to enforce - in other words, seems like you are sitting in a good position - via you have no obligation to determine what the 5% represents and the ability to reduce an amount if she every comes up with a number - and no obligation to pay it once it is determined and even then, take her name off and pay her down the road- though, be careful if you give her a promissory note as to no enforcement time even specify up to your discretion
950,794
I am running Gnome Shell with a 4k monitor and there are a few applications that I use that don't scale at all with the high resolution. Here is an example of LMMS, an application that hasn't yet been ported Qt 5, so it doesn't have high dpi scaling capabilities: [![Screenshot](https://i.stack.imgur.com/Af0Vr.jpg)](https://i.stack.imgur.com/Af0Vr.jpg) (Click images to enlarge) Is there any way to scale a specific X window without changing the display resolution? My current solution is to half the dimensions of my display resolution, but this degrades the resolution of every other application that supports proper dpi scaling: [![Screenshot](https://i.stack.imgur.com/fJVFL.jpg)](https://i.stack.imgur.com/fJVFL.jpg)
2015/08/04
[ "https://superuser.com/questions/950794", "https://superuser.com", "https://superuser.com/users/61024/" ]
Without seeing the exact problem that you are running into I would suggest using ``` GDK_SCALE=x ``` or ``` GDK_DPI_SCALE=x ``` Before starting each application. You will likely have to manually change `.desktop` files or run from your shell prefixing the commands with `GDK_SCALE=x` `GDK_SCALE` only allow interger values however `GDK_DPI_SCALE=x` allow for decimal values like i.e.`GDK_DPI_SCALE=0.66` For other SDK based applications there are likely similar settings for respective kits. However since your problem is with gnome desktop I will provide this solution. I haven't tried with a 4k monitor, but running `GDK_DPI_SCALE=1.66 gnome-calculator` will demo the solution. Source: <https://developer.gnome.org/gtk3/stable/gtk-x11.html>
[Vncdesk](https://github.com/feklee/vncdesk "VNCdesk") gives you a solution based on a local VNC client-server (see [here](https://unix.stackexchange.com/questions/192493/how-to-use-xfig-on-high-dpi-screen)) It is not a complete solution for me because it gives some problems if the app need a window manager.
950,794
I am running Gnome Shell with a 4k monitor and there are a few applications that I use that don't scale at all with the high resolution. Here is an example of LMMS, an application that hasn't yet been ported Qt 5, so it doesn't have high dpi scaling capabilities: [![Screenshot](https://i.stack.imgur.com/Af0Vr.jpg)](https://i.stack.imgur.com/Af0Vr.jpg) (Click images to enlarge) Is there any way to scale a specific X window without changing the display resolution? My current solution is to half the dimensions of my display resolution, but this degrades the resolution of every other application that supports proper dpi scaling: [![Screenshot](https://i.stack.imgur.com/fJVFL.jpg)](https://i.stack.imgur.com/fJVFL.jpg)
2015/08/04
[ "https://superuser.com/questions/950794", "https://superuser.com", "https://superuser.com/users/61024/" ]
I finally managed to find a solution that scales old applications without any noticeable visual or performance degradation. Thanks to kaueraal, you can now scale old applications using `run_scaled`. You can obtain the script from either his [GitHub page](https://github.com/kaueraal/run_scaled) or as part of the `xpra` package if you are running Arch Linux. Here is an example of two applications running side by side: * Firefox with HiDPI support on the left * LMMS running with `run_scaled` on the right [![enter image description here](https://i.stack.imgur.com/VwIjQ.jpg)](https://i.stack.imgur.com/VwIjQ.jpg) I discovered this script through the [Arch Linux Wiki](https://wiki.archlinux.org/index.php?title=HiDPI&oldid=468803#Unsupported_applications).
Without seeing the exact problem that you are running into I would suggest using ``` GDK_SCALE=x ``` or ``` GDK_DPI_SCALE=x ``` Before starting each application. You will likely have to manually change `.desktop` files or run from your shell prefixing the commands with `GDK_SCALE=x` `GDK_SCALE` only allow interger values however `GDK_DPI_SCALE=x` allow for decimal values like i.e.`GDK_DPI_SCALE=0.66` For other SDK based applications there are likely similar settings for respective kits. However since your problem is with gnome desktop I will provide this solution. I haven't tried with a 4k monitor, but running `GDK_DPI_SCALE=1.66 gnome-calculator` will demo the solution. Source: <https://developer.gnome.org/gtk3/stable/gtk-x11.html>
950,794
I am running Gnome Shell with a 4k monitor and there are a few applications that I use that don't scale at all with the high resolution. Here is an example of LMMS, an application that hasn't yet been ported Qt 5, so it doesn't have high dpi scaling capabilities: [![Screenshot](https://i.stack.imgur.com/Af0Vr.jpg)](https://i.stack.imgur.com/Af0Vr.jpg) (Click images to enlarge) Is there any way to scale a specific X window without changing the display resolution? My current solution is to half the dimensions of my display resolution, but this degrades the resolution of every other application that supports proper dpi scaling: [![Screenshot](https://i.stack.imgur.com/fJVFL.jpg)](https://i.stack.imgur.com/fJVFL.jpg)
2015/08/04
[ "https://superuser.com/questions/950794", "https://superuser.com", "https://superuser.com/users/61024/" ]
Without seeing the exact problem that you are running into I would suggest using ``` GDK_SCALE=x ``` or ``` GDK_DPI_SCALE=x ``` Before starting each application. You will likely have to manually change `.desktop` files or run from your shell prefixing the commands with `GDK_SCALE=x` `GDK_SCALE` only allow interger values however `GDK_DPI_SCALE=x` allow for decimal values like i.e.`GDK_DPI_SCALE=0.66` For other SDK based applications there are likely similar settings for respective kits. However since your problem is with gnome desktop I will provide this solution. I haven't tried with a 4k monitor, but running `GDK_DPI_SCALE=1.66 gnome-calculator` will demo the solution. Source: <https://developer.gnome.org/gtk3/stable/gtk-x11.html>
I have an application that spawns many windows, and I cannot at the moment use `xpra` as is required by the accepted run\_scaled solution. I also can't tolerate gnome-tweak-tool's 2x scaling. Too huge. Need 1.5x. I have discovered that the tigerVNC java client supports client-side display scaling of 150%. So I start a vncserver with 2/3rds size and a minimal windows manager: `vncserver -geometry 2520x1380 -xstartup ~/.vnc/xstartup-mwm` I then connect with [TigerVNC's v1.7 java client](https://bintray.com/tigervnc/stable/tigervnc/1.7.0) (1.8.0 consistently crashes for me): `java -jar VncViewer-1.7.0.jar -ScalingFactor=150` Other than the commandline, you can hit `F8` to get the VNC Viewer Options. Screen->Scaling Factor->150%. This scales the resolution from 2/3rds of 4k to 4k. [![enter image description here](https://i.stack.imgur.com/FldGV.png)](https://i.stack.imgur.com/FldGV.png) Archaic MWM in VNC with 150% scaling on the left. Fancy Gnome desktop (native) on the right, no scaling. You'll notice the tiny icons. Gnome is otherwise adjusted for 4k with 1.5x Font Scaling in gnome-tweak-tool, but the icons don't scale. This is just an example application -- the icons and scaling in the application that is pushing me this way are far worse. Unfortunately this is an entire 1.5x scaled desktop with a separate window manager. It creates a nice walled-off area for my multiwindow app, but it's annoying to have a second window manager. Nonetheless VNC is something I'm familiar with from longtime use, and this does kick over to the laptop pretty easily, so perhaps this is usable.
950,794
I am running Gnome Shell with a 4k monitor and there are a few applications that I use that don't scale at all with the high resolution. Here is an example of LMMS, an application that hasn't yet been ported Qt 5, so it doesn't have high dpi scaling capabilities: [![Screenshot](https://i.stack.imgur.com/Af0Vr.jpg)](https://i.stack.imgur.com/Af0Vr.jpg) (Click images to enlarge) Is there any way to scale a specific X window without changing the display resolution? My current solution is to half the dimensions of my display resolution, but this degrades the resolution of every other application that supports proper dpi scaling: [![Screenshot](https://i.stack.imgur.com/fJVFL.jpg)](https://i.stack.imgur.com/fJVFL.jpg)
2015/08/04
[ "https://superuser.com/questions/950794", "https://superuser.com", "https://superuser.com/users/61024/" ]
Without seeing the exact problem that you are running into I would suggest using ``` GDK_SCALE=x ``` or ``` GDK_DPI_SCALE=x ``` Before starting each application. You will likely have to manually change `.desktop` files or run from your shell prefixing the commands with `GDK_SCALE=x` `GDK_SCALE` only allow interger values however `GDK_DPI_SCALE=x` allow for decimal values like i.e.`GDK_DPI_SCALE=0.66` For other SDK based applications there are likely similar settings for respective kits. However since your problem is with gnome desktop I will provide this solution. I haven't tried with a 4k monitor, but running `GDK_DPI_SCALE=1.66 gnome-calculator` will demo the solution. Source: <https://developer.gnome.org/gtk3/stable/gtk-x11.html>
I think I've found a GPU-accelerated solution! Install `weston` and run this: ``` weston --xwayland --scale=2 DISPLAY=:1 your_app ``` That's it! Tuning ------ Note 1: You may have noticed a magical number has been used, `DISPLAY=:1`. The underlying assumption here was that your main xorg display is `:0`. If it's not, adjust accordingly. Note 2: You may have noticed that `weston` has a top panel by default. You may want to remove it. To do that, create a `weston.ini` file: ``` [core] idle-time=0 [shell] panel-position=none locking=false ``` And use it when starting weston `weston --config=/path/to/weston.ini`. You can also place it to `~/.config/weston.ini` for it to be picked up by weston automatically, please refer to `man weston.ini` for further details. EDIT: I've also documented the newly found approach here: <https://wiki.archlinux.org/title/HiDPI#Unsupported_applications,_via_weston>
950,794
I am running Gnome Shell with a 4k monitor and there are a few applications that I use that don't scale at all with the high resolution. Here is an example of LMMS, an application that hasn't yet been ported Qt 5, so it doesn't have high dpi scaling capabilities: [![Screenshot](https://i.stack.imgur.com/Af0Vr.jpg)](https://i.stack.imgur.com/Af0Vr.jpg) (Click images to enlarge) Is there any way to scale a specific X window without changing the display resolution? My current solution is to half the dimensions of my display resolution, but this degrades the resolution of every other application that supports proper dpi scaling: [![Screenshot](https://i.stack.imgur.com/fJVFL.jpg)](https://i.stack.imgur.com/fJVFL.jpg)
2015/08/04
[ "https://superuser.com/questions/950794", "https://superuser.com", "https://superuser.com/users/61024/" ]
I finally managed to find a solution that scales old applications without any noticeable visual or performance degradation. Thanks to kaueraal, you can now scale old applications using `run_scaled`. You can obtain the script from either his [GitHub page](https://github.com/kaueraal/run_scaled) or as part of the `xpra` package if you are running Arch Linux. Here is an example of two applications running side by side: * Firefox with HiDPI support on the left * LMMS running with `run_scaled` on the right [![enter image description here](https://i.stack.imgur.com/VwIjQ.jpg)](https://i.stack.imgur.com/VwIjQ.jpg) I discovered this script through the [Arch Linux Wiki](https://wiki.archlinux.org/index.php?title=HiDPI&oldid=468803#Unsupported_applications).
[Vncdesk](https://github.com/feklee/vncdesk "VNCdesk") gives you a solution based on a local VNC client-server (see [here](https://unix.stackexchange.com/questions/192493/how-to-use-xfig-on-high-dpi-screen)) It is not a complete solution for me because it gives some problems if the app need a window manager.
950,794
I am running Gnome Shell with a 4k monitor and there are a few applications that I use that don't scale at all with the high resolution. Here is an example of LMMS, an application that hasn't yet been ported Qt 5, so it doesn't have high dpi scaling capabilities: [![Screenshot](https://i.stack.imgur.com/Af0Vr.jpg)](https://i.stack.imgur.com/Af0Vr.jpg) (Click images to enlarge) Is there any way to scale a specific X window without changing the display resolution? My current solution is to half the dimensions of my display resolution, but this degrades the resolution of every other application that supports proper dpi scaling: [![Screenshot](https://i.stack.imgur.com/fJVFL.jpg)](https://i.stack.imgur.com/fJVFL.jpg)
2015/08/04
[ "https://superuser.com/questions/950794", "https://superuser.com", "https://superuser.com/users/61024/" ]
[Vncdesk](https://github.com/feklee/vncdesk "VNCdesk") gives you a solution based on a local VNC client-server (see [here](https://unix.stackexchange.com/questions/192493/how-to-use-xfig-on-high-dpi-screen)) It is not a complete solution for me because it gives some problems if the app need a window manager.
I think I've found a GPU-accelerated solution! Install `weston` and run this: ``` weston --xwayland --scale=2 DISPLAY=:1 your_app ``` That's it! Tuning ------ Note 1: You may have noticed a magical number has been used, `DISPLAY=:1`. The underlying assumption here was that your main xorg display is `:0`. If it's not, adjust accordingly. Note 2: You may have noticed that `weston` has a top panel by default. You may want to remove it. To do that, create a `weston.ini` file: ``` [core] idle-time=0 [shell] panel-position=none locking=false ``` And use it when starting weston `weston --config=/path/to/weston.ini`. You can also place it to `~/.config/weston.ini` for it to be picked up by weston automatically, please refer to `man weston.ini` for further details. EDIT: I've also documented the newly found approach here: <https://wiki.archlinux.org/title/HiDPI#Unsupported_applications,_via_weston>
950,794
I am running Gnome Shell with a 4k monitor and there are a few applications that I use that don't scale at all with the high resolution. Here is an example of LMMS, an application that hasn't yet been ported Qt 5, so it doesn't have high dpi scaling capabilities: [![Screenshot](https://i.stack.imgur.com/Af0Vr.jpg)](https://i.stack.imgur.com/Af0Vr.jpg) (Click images to enlarge) Is there any way to scale a specific X window without changing the display resolution? My current solution is to half the dimensions of my display resolution, but this degrades the resolution of every other application that supports proper dpi scaling: [![Screenshot](https://i.stack.imgur.com/fJVFL.jpg)](https://i.stack.imgur.com/fJVFL.jpg)
2015/08/04
[ "https://superuser.com/questions/950794", "https://superuser.com", "https://superuser.com/users/61024/" ]
I finally managed to find a solution that scales old applications without any noticeable visual or performance degradation. Thanks to kaueraal, you can now scale old applications using `run_scaled`. You can obtain the script from either his [GitHub page](https://github.com/kaueraal/run_scaled) or as part of the `xpra` package if you are running Arch Linux. Here is an example of two applications running side by side: * Firefox with HiDPI support on the left * LMMS running with `run_scaled` on the right [![enter image description here](https://i.stack.imgur.com/VwIjQ.jpg)](https://i.stack.imgur.com/VwIjQ.jpg) I discovered this script through the [Arch Linux Wiki](https://wiki.archlinux.org/index.php?title=HiDPI&oldid=468803#Unsupported_applications).
I have an application that spawns many windows, and I cannot at the moment use `xpra` as is required by the accepted run\_scaled solution. I also can't tolerate gnome-tweak-tool's 2x scaling. Too huge. Need 1.5x. I have discovered that the tigerVNC java client supports client-side display scaling of 150%. So I start a vncserver with 2/3rds size and a minimal windows manager: `vncserver -geometry 2520x1380 -xstartup ~/.vnc/xstartup-mwm` I then connect with [TigerVNC's v1.7 java client](https://bintray.com/tigervnc/stable/tigervnc/1.7.0) (1.8.0 consistently crashes for me): `java -jar VncViewer-1.7.0.jar -ScalingFactor=150` Other than the commandline, you can hit `F8` to get the VNC Viewer Options. Screen->Scaling Factor->150%. This scales the resolution from 2/3rds of 4k to 4k. [![enter image description here](https://i.stack.imgur.com/FldGV.png)](https://i.stack.imgur.com/FldGV.png) Archaic MWM in VNC with 150% scaling on the left. Fancy Gnome desktop (native) on the right, no scaling. You'll notice the tiny icons. Gnome is otherwise adjusted for 4k with 1.5x Font Scaling in gnome-tweak-tool, but the icons don't scale. This is just an example application -- the icons and scaling in the application that is pushing me this way are far worse. Unfortunately this is an entire 1.5x scaled desktop with a separate window manager. It creates a nice walled-off area for my multiwindow app, but it's annoying to have a second window manager. Nonetheless VNC is something I'm familiar with from longtime use, and this does kick over to the laptop pretty easily, so perhaps this is usable.
950,794
I am running Gnome Shell with a 4k monitor and there are a few applications that I use that don't scale at all with the high resolution. Here is an example of LMMS, an application that hasn't yet been ported Qt 5, so it doesn't have high dpi scaling capabilities: [![Screenshot](https://i.stack.imgur.com/Af0Vr.jpg)](https://i.stack.imgur.com/Af0Vr.jpg) (Click images to enlarge) Is there any way to scale a specific X window without changing the display resolution? My current solution is to half the dimensions of my display resolution, but this degrades the resolution of every other application that supports proper dpi scaling: [![Screenshot](https://i.stack.imgur.com/fJVFL.jpg)](https://i.stack.imgur.com/fJVFL.jpg)
2015/08/04
[ "https://superuser.com/questions/950794", "https://superuser.com", "https://superuser.com/users/61024/" ]
I finally managed to find a solution that scales old applications without any noticeable visual or performance degradation. Thanks to kaueraal, you can now scale old applications using `run_scaled`. You can obtain the script from either his [GitHub page](https://github.com/kaueraal/run_scaled) or as part of the `xpra` package if you are running Arch Linux. Here is an example of two applications running side by side: * Firefox with HiDPI support on the left * LMMS running with `run_scaled` on the right [![enter image description here](https://i.stack.imgur.com/VwIjQ.jpg)](https://i.stack.imgur.com/VwIjQ.jpg) I discovered this script through the [Arch Linux Wiki](https://wiki.archlinux.org/index.php?title=HiDPI&oldid=468803#Unsupported_applications).
I think I've found a GPU-accelerated solution! Install `weston` and run this: ``` weston --xwayland --scale=2 DISPLAY=:1 your_app ``` That's it! Tuning ------ Note 1: You may have noticed a magical number has been used, `DISPLAY=:1`. The underlying assumption here was that your main xorg display is `:0`. If it's not, adjust accordingly. Note 2: You may have noticed that `weston` has a top panel by default. You may want to remove it. To do that, create a `weston.ini` file: ``` [core] idle-time=0 [shell] panel-position=none locking=false ``` And use it when starting weston `weston --config=/path/to/weston.ini`. You can also place it to `~/.config/weston.ini` for it to be picked up by weston automatically, please refer to `man weston.ini` for further details. EDIT: I've also documented the newly found approach here: <https://wiki.archlinux.org/title/HiDPI#Unsupported_applications,_via_weston>
950,794
I am running Gnome Shell with a 4k monitor and there are a few applications that I use that don't scale at all with the high resolution. Here is an example of LMMS, an application that hasn't yet been ported Qt 5, so it doesn't have high dpi scaling capabilities: [![Screenshot](https://i.stack.imgur.com/Af0Vr.jpg)](https://i.stack.imgur.com/Af0Vr.jpg) (Click images to enlarge) Is there any way to scale a specific X window without changing the display resolution? My current solution is to half the dimensions of my display resolution, but this degrades the resolution of every other application that supports proper dpi scaling: [![Screenshot](https://i.stack.imgur.com/fJVFL.jpg)](https://i.stack.imgur.com/fJVFL.jpg)
2015/08/04
[ "https://superuser.com/questions/950794", "https://superuser.com", "https://superuser.com/users/61024/" ]
I have an application that spawns many windows, and I cannot at the moment use `xpra` as is required by the accepted run\_scaled solution. I also can't tolerate gnome-tweak-tool's 2x scaling. Too huge. Need 1.5x. I have discovered that the tigerVNC java client supports client-side display scaling of 150%. So I start a vncserver with 2/3rds size and a minimal windows manager: `vncserver -geometry 2520x1380 -xstartup ~/.vnc/xstartup-mwm` I then connect with [TigerVNC's v1.7 java client](https://bintray.com/tigervnc/stable/tigervnc/1.7.0) (1.8.0 consistently crashes for me): `java -jar VncViewer-1.7.0.jar -ScalingFactor=150` Other than the commandline, you can hit `F8` to get the VNC Viewer Options. Screen->Scaling Factor->150%. This scales the resolution from 2/3rds of 4k to 4k. [![enter image description here](https://i.stack.imgur.com/FldGV.png)](https://i.stack.imgur.com/FldGV.png) Archaic MWM in VNC with 150% scaling on the left. Fancy Gnome desktop (native) on the right, no scaling. You'll notice the tiny icons. Gnome is otherwise adjusted for 4k with 1.5x Font Scaling in gnome-tweak-tool, but the icons don't scale. This is just an example application -- the icons and scaling in the application that is pushing me this way are far worse. Unfortunately this is an entire 1.5x scaled desktop with a separate window manager. It creates a nice walled-off area for my multiwindow app, but it's annoying to have a second window manager. Nonetheless VNC is something I'm familiar with from longtime use, and this does kick over to the laptop pretty easily, so perhaps this is usable.
I think I've found a GPU-accelerated solution! Install `weston` and run this: ``` weston --xwayland --scale=2 DISPLAY=:1 your_app ``` That's it! Tuning ------ Note 1: You may have noticed a magical number has been used, `DISPLAY=:1`. The underlying assumption here was that your main xorg display is `:0`. If it's not, adjust accordingly. Note 2: You may have noticed that `weston` has a top panel by default. You may want to remove it. To do that, create a `weston.ini` file: ``` [core] idle-time=0 [shell] panel-position=none locking=false ``` And use it when starting weston `weston --config=/path/to/weston.ini`. You can also place it to `~/.config/weston.ini` for it to be picked up by weston automatically, please refer to `man weston.ini` for further details. EDIT: I've also documented the newly found approach here: <https://wiki.archlinux.org/title/HiDPI#Unsupported_applications,_via_weston>
57,059,368
I have a pointer `uvw(:,:)` which is two-dimensional, and I got a 1d buffer array `x(:)`. Now I need to point `uvw(1,:)=>x(1:ncell)` and `uvw(2,:)=>x(ncell+1:ncell*2)` etc. I made a very simple example. I know that array of pointers does not work, but does anybody have an idea how this can be worked around? PS: For a pragmatic reason I do not want to wrap my uvw with a declared type. ( i am changing some bit of code, and need uvw as 2D pointer. Currently is an array, and my idea is to avoid changing the way uvw is being used as it being used thousands of times) ``` program test real, allocatable,target :: x(:) real, pointer :: ptr(:,:) allocate(x(100) ) x = 1. ptr(1,:) => x(1:10) end program ``` The error message says: > > `error #8524: The syntax of this data pointer assignment is incorrect: > either 'bound spec' or 'bound remapping' is expected in this context. > [1] > > > ptr(1,:) => x(1:10) > > > ----^` > > >
2019/07/16
[ "https://Stackoverflow.com/questions/57059368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8889824/" ]
You are trying to perform *pointer bounds remapping*, but you have the incorrect syntax and approach. Pointer bounds remapping is a way to have the shape of the pointer different from that of the target. In particular, the rank of the pointer and target may differ. However, in such an assignment it is necessary to explicitly specify the lower and upper bounds of the remapping; it isn't sufficient to use `:` by itself. Also, you'll need to assign the whole pointer in one go. That is, you can't have "the first ten elements point to this slice, the next ten to this slice" and so on in multiple statements. The assignment statement would be ``` ptr(1:10,1:10) => x ``` Note, that this also means that you can't actually have what you want. You are asking for the elements `ptr(1,1:10)` to correspond to `x(1:10)` and `ptr(2,2:10)` to correspond to `x(11:20)`. That isn't possible: the array elements must match in order: `ptr(1:10,1)` being the first ten elements of `ptr` must instead be associated with the first ten elements `x(1:10)`. The corrected pointer assignment above has this.
If you prefer avoiding a pointer, then the UNION/MAP is an option depending on compiler. It was added to gfortran a while ago... then you can think of the array as a rank=2 but also use the vector (Rank=1) for SIMD operations. All this assumes that one wants to avoid pointers...
30,893,505
I've been making a game with Corona SDK. I'm trying display an image in the middle of the screen, but it displays in the random location. Image that I'm trying to display is circle.png. Please help me if you can. Here is the code: local composer = require( "composer" ) ``` strong textlocal scene = composer.newScene() local widget = require "widget" widget.setTheme ("widget_theme_ios") local score local scoreEarn = 1 local lives = {} local livesCount = 1 local balls = {} local ballsCount = 0 local ballsSendSpeed = 65 local ballsTravelSpeed = 3500 local ballsIncrementSpeed = 1.5 local ballsMaxSendSpeed = 30 local timer_Counter local onGameOver, gameOverBox, gameoverBackground, btn_returnToMenu -- ------------------------------------------------------------------------------- -- "scene:create()" function scene:create( event ) local sceneGroup = self.view -- Initialize the scene here. -- Example: add display objects to "sceneGroup", add touch listeners, etc. local function ballTap(event) end local function ballDrag() end local function ballSend () end local function ballsCollision () end local function onCollision (event) end local function circleDamage () end function gameOver () end local background = display.newImageRect(sceneGroup, "images/gamescreen/background.png", 1600, 1200) background.x = _CX background.y = _CY local cirlce = display.newImageRect(sceneGroup, "images/gamescreen/circle.png", 184, 179) cirlce.x = _CX cirlce.y = _CY end -- "scene:show()" function scene:show( event ) local sceneGroup = self.view local phase = event.phase if ( phase == "will" ) then -- Called when the scene is still off screen (but is about to come on screen). elseif ( phase == "did" ) then -- Called when the scene is now on screen. -- Insert code here to make the scene come alive. -- Example: start timers, begin animation, play audio, etc. end end -- "scene:hide()" function scene:hide( event ) local sceneGroup = self.view local phase = event.phase if ( phase == "will" ) then -- Called when the scene is on screen (but is about to go off screen). -- Insert code here to "pause" the scene. -- Example: stop timers, stop animation, stop audio, etc. elseif ( phase == "did" ) then -- Called immediately after scene goes off screen. end end -- "scene:destroy()" function scene:destroy( event ) local sceneGroup = self.view -- Called prior to the removal of scene's view ("sceneGroup"). -- Insert code here to clean up the scene. -- Example: remove display objects, save state, etc. end -- ------------------------------------------------------------------------------- -- Listener setup scene:addEventListener( "create", scene ) scene:addEventListener( "show", scene ) scene:addEventListener( "hide", scene ) scene:addEventListener( "destroy", scene ) -- ------------------------------------------------------------------------------- return scene ```
2015/06/17
[ "https://Stackoverflow.com/questions/30893505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5019687/" ]
Just try this , ``` local cirlce = display.newImageRect(sceneGroup, "images/gamescreen/circle.png", 184, 179) cirlce.x = display.viewableContentWidth/2 cirlce.y = display.viewableContentHeight/2 ```
Give This a try. ``` local cirlce = display.newImageRect("images/gamescreen/circle.png", 184, 179) cirlce.x = centerX cirlce.y = centerY ```
82,435
When I train a neural network, I observe an increasing validation loss, while at the same time, the validation accuracy is also increased. I have read explanations related to the phenomenon, and it seems an increasing validation loss and validation accuracy signifies an overfitted model. However, I have not really grokked the reasons why an increasing validation loss and validation accuracy signifies an overfitting. Could you please give the explanations behind this phenomenon?
2020/10/01
[ "https://datascience.stackexchange.com/questions/82435", "https://datascience.stackexchange.com", "https://datascience.stackexchange.com/users/103610/" ]
Consider a simple example where the cost function to be a parabola $y=x^2$ which is convex(ideal case) with a one global minima at $x=0$ Here your $y$ is the independent variable and $x$ is the dependent variable, analogus to the weights of model that you are trying to learn. This is how it would look like. [![enter image description here](https://i.stack.imgur.com/5zcMe.png)](https://i.stack.imgur.com/5zcMe.png) Let's apply gradient descent to this particular cost function(parabola) to find it's minima. From calculus it is clear that $dy/dx = 2\*x$. So that means that the gradients are positive in the $1^{st}$ quadrant and negative in the $2^{nd}$. That means for every **positive** small step in x that we take, we move away from origin in the $1^{st}$ quadrant and move towards the origin in the $2^{nd}$ quadrant(step is still positive). In the update rule of gradient descent the '-' negative sign basically negates the gradient and hence always moves towards the local minima. * $1^{st}$ quadrant -> gradient is positive, but if you use this as it is you move away from origin or minima. So, the negative sign helps here. * $2^{nd}$ quadrant -> gradient is negative, but if you use this as it is you move away from origin or minima(addition of two negative values). So, the negative sign helps here. Here is a small python code to make things clearer- ```py import numpy as np import matplotlib.pyplot as plt x = np.linspace(-4, 4, 200) y = x**2 plt.xlabel('x') plt.ylabel('y = x^2') plt.plot(x, y) # learning rate lr = 0.1 np.random.seed(20) x_start = np.random.normal(0, 2, 1) dy_dx_old = 2 * x_start dy_dx_new = 0 tolerance = 1e-2 # stop once the value has converged while abs(dy_dx_new - dy_dx_old) > tolerance: dy_dx_old = dy_dx_new x_start = x_start - lr * dy_dx_old dy_dx_new = 2 * x_start plt.scatter(x_start, x_start**2) plt.pause(0.5) plt.show() ``` [![enter image description here](https://i.stack.imgur.com/APPGu.png)](https://i.stack.imgur.com/APPGu.png)
Computing the gradient gives you the direction where the function increases the most. Consider f: x -> x^2 , the gradient in x=1 is 2, if you want to minimize the function you need to go in the direction of -2, same with x=-1 as the gradient is -2. And as gradients are usually vectors, I don't know what a positive or negative gradient would be if gradient is something like (-1, 1). <https://builtin.com/data-science/gradient-descent>
82,435
When I train a neural network, I observe an increasing validation loss, while at the same time, the validation accuracy is also increased. I have read explanations related to the phenomenon, and it seems an increasing validation loss and validation accuracy signifies an overfitted model. However, I have not really grokked the reasons why an increasing validation loss and validation accuracy signifies an overfitting. Could you please give the explanations behind this phenomenon?
2020/10/01
[ "https://datascience.stackexchange.com/questions/82435", "https://datascience.stackexchange.com", "https://datascience.stackexchange.com/users/103610/" ]
Consider a simple example where the cost function to be a parabola $y=x^2$ which is convex(ideal case) with a one global minima at $x=0$ Here your $y$ is the independent variable and $x$ is the dependent variable, analogus to the weights of model that you are trying to learn. This is how it would look like. [![enter image description here](https://i.stack.imgur.com/5zcMe.png)](https://i.stack.imgur.com/5zcMe.png) Let's apply gradient descent to this particular cost function(parabola) to find it's minima. From calculus it is clear that $dy/dx = 2\*x$. So that means that the gradients are positive in the $1^{st}$ quadrant and negative in the $2^{nd}$. That means for every **positive** small step in x that we take, we move away from origin in the $1^{st}$ quadrant and move towards the origin in the $2^{nd}$ quadrant(step is still positive). In the update rule of gradient descent the '-' negative sign basically negates the gradient and hence always moves towards the local minima. * $1^{st}$ quadrant -> gradient is positive, but if you use this as it is you move away from origin or minima. So, the negative sign helps here. * $2^{nd}$ quadrant -> gradient is negative, but if you use this as it is you move away from origin or minima(addition of two negative values). So, the negative sign helps here. Here is a small python code to make things clearer- ```py import numpy as np import matplotlib.pyplot as plt x = np.linspace(-4, 4, 200) y = x**2 plt.xlabel('x') plt.ylabel('y = x^2') plt.plot(x, y) # learning rate lr = 0.1 np.random.seed(20) x_start = np.random.normal(0, 2, 1) dy_dx_old = 2 * x_start dy_dx_new = 0 tolerance = 1e-2 # stop once the value has converged while abs(dy_dx_new - dy_dx_old) > tolerance: dy_dx_old = dy_dx_new x_start = x_start - lr * dy_dx_old dy_dx_new = 2 * x_start plt.scatter(x_start, x_start**2) plt.pause(0.5) plt.show() ``` [![enter image description here](https://i.stack.imgur.com/APPGu.png)](https://i.stack.imgur.com/APPGu.png)
Let $F : \mathbb{R}^{n} \rightarrow \mathbb{R}$ be a continuous differentiable function and $d \in \mathbb{R}^{n}$. Then $d$ is called a descent direction at position $p \in \mathbb{R}^{n}$, if there is a $R > 0 $ such that $F(p+rd) < F(p)$ for all $r \in (0,R)$. In simple terms: If we move $p$ in direction of $d$ we can reduce the value of $F$. Now $d$ is a descent direction at $p$, if $\nabla F(p)^T rd < 0 $ since by definition of gradient $F(p+rd) - F(p) = \nabla F(p)^Trd$ and in order to reduce the function value, we need to have $\nabla F(p)^T rd < 0 $: For $f(r):= F(p+rd)$ we have $f'(t) = \nabla F(p+rd)^T d$. By assumption, $f'(0) < 0$ holds. Since $f'(0) = \lim\_{h \rightarrow 0} \frac{f(h)-f(0)}{h}$, we conclude that $d$ must be descent direction. Therefore, setting $d := -\nabla F(p)$, we have $\nabla F(p)^T (-\nabla F(p)) = - ||\nabla F(p)||\_{2}^{2} < 0 $, if $p$ is not a stationary point. In particular, we can choose an $p' = p + r'd$ with $F(p') < F(p)$. This shows that using the negative gradient makes sense.
82,435
When I train a neural network, I observe an increasing validation loss, while at the same time, the validation accuracy is also increased. I have read explanations related to the phenomenon, and it seems an increasing validation loss and validation accuracy signifies an overfitted model. However, I have not really grokked the reasons why an increasing validation loss and validation accuracy signifies an overfitting. Could you please give the explanations behind this phenomenon?
2020/10/01
[ "https://datascience.stackexchange.com/questions/82435", "https://datascience.stackexchange.com", "https://datascience.stackexchange.com/users/103610/" ]
Let $F : \mathbb{R}^{n} \rightarrow \mathbb{R}$ be a continuous differentiable function and $d \in \mathbb{R}^{n}$. Then $d$ is called a descent direction at position $p \in \mathbb{R}^{n}$, if there is a $R > 0 $ such that $F(p+rd) < F(p)$ for all $r \in (0,R)$. In simple terms: If we move $p$ in direction of $d$ we can reduce the value of $F$. Now $d$ is a descent direction at $p$, if $\nabla F(p)^T rd < 0 $ since by definition of gradient $F(p+rd) - F(p) = \nabla F(p)^Trd$ and in order to reduce the function value, we need to have $\nabla F(p)^T rd < 0 $: For $f(r):= F(p+rd)$ we have $f'(t) = \nabla F(p+rd)^T d$. By assumption, $f'(0) < 0$ holds. Since $f'(0) = \lim\_{h \rightarrow 0} \frac{f(h)-f(0)}{h}$, we conclude that $d$ must be descent direction. Therefore, setting $d := -\nabla F(p)$, we have $\nabla F(p)^T (-\nabla F(p)) = - ||\nabla F(p)||\_{2}^{2} < 0 $, if $p$ is not a stationary point. In particular, we can choose an $p' = p + r'd$ with $F(p') < F(p)$. This shows that using the negative gradient makes sense.
Computing the gradient gives you the direction where the function increases the most. Consider f: x -> x^2 , the gradient in x=1 is 2, if you want to minimize the function you need to go in the direction of -2, same with x=-1 as the gradient is -2. And as gradients are usually vectors, I don't know what a positive or negative gradient would be if gradient is something like (-1, 1). <https://builtin.com/data-science/gradient-descent>
44,971,813
Code: ``` int x = 2; int* pointerone = &x; int* pointertwo = pointerone; ``` So the address of `pointerone` is assigned to `pointertwo`, but is the copy constructor being called and the object that holds the address is copied into the address object of the other pointer, like all the default copy constructors on other types performing a shallow copy. If it is as I expect, how does the copy constructor of a pointer look like?
2017/07/07
[ "https://Stackoverflow.com/questions/44971813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
There are no constructors involved here. In fact this code is pure C code. ``` int x = 2; // pointerone points to the memory address of x int* pointerone = &x; // pointertwo points to the same address than pointerone, // therefore it points also to the memory address of x int* pointertwo = pointerone; ``` That's all. And even in C++, pointers don't have constructors, exactly as the `int` type doesn't have a constructor.
You could pretend, for symmetry, that the pointer's copy constructor is being invoked (and this would involve the copying of a single numerical "memory address"). In reality, pointers are of a built-in type and don't have constructors *per se*. The compiler has built-in logic that tells it what to make the program do.
44,971,813
Code: ``` int x = 2; int* pointerone = &x; int* pointertwo = pointerone; ``` So the address of `pointerone` is assigned to `pointertwo`, but is the copy constructor being called and the object that holds the address is copied into the address object of the other pointer, like all the default copy constructors on other types performing a shallow copy. If it is as I expect, how does the copy constructor of a pointer look like?
2017/07/07
[ "https://Stackoverflow.com/questions/44971813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
There are no constructors involved here. In fact this code is pure C code. ``` int x = 2; // pointerone points to the memory address of x int* pointerone = &x; // pointertwo points to the same address than pointerone, // therefore it points also to the memory address of x int* pointertwo = pointerone; ``` That's all. And even in C++, pointers don't have constructors, exactly as the `int` type doesn't have a constructor.
When you initialize a pointer with the value of another pointer you are just making another variable for the same memory address, as @Michael just said. But be careful doing this. If you delete one of the pointer and you dereference the other one in another point of the program, it will raise an exception, and if not handled properly will crash your program. Take this as an example: ``` int *ptr1 { new int(15) }; int *ptr2 { ptr1 }; // ptr2 points to same memory address as ptr1 // ... Some cool code goes here delete ptr1; // Free the memory of ptr1 cout << *ptr2; // Raises an exception because the address // has been removed from the effective // memory of the program. ```
21,289,707
I'm using Backbone together with require.js and jQuery. What I'm trying to do is to simply bind an event to a container which should show (mouseover) or hide (mouseout) a video. The event fires but unfortunately too many times (I've several children inside `.intro-content`). I tried using `ev.stopPropagation()` (as seen in the code) and `ev.stopImmediatePropagation` but this doesn't prevent the bubbling. What am I doing wrong? View: ``` define([ 'jquery', 'underscore', 'backbone', 'global' ], function($, _, Backbone, Global){ var VideoView = Backbone.View.extend({ el: $('#splitlayout'), events: { 'mouseover .side-left .intro-content': 'checkVideoState', 'mouseout .side-left .intro-content': 'checkVideoState' }, render: function(){ this.playVideo('video', '0GsrOOV0gQM'); this.delegateEvents(); }, initialize: function() { _.bindAll(this); this.render(); }, checkVideoState: function(ev) { ev.stopPropagation(); if(!$('#video').hasClass('active') && ev.type == 'mouseover') { this.showVideo(); } else if($('#video').hasClass('active') && ev.type == 'mouseout') { this.hideVideo(); } }, showVideo: function() { console.log('test'); $('#video').addClass('active'); player.playVideo(); }, hideVideo: function() { console.log('test'); $('#video').removeClass('active'); player.pauseVideo(); }, playVideo: function(container, videoId) { var self = this; if (typeof(YT) == 'undefined' || typeof(YT.Player) == 'undefined') { window.onYouTubeIframeAPIReady = function() { self.loadPlayer(container, videoId); }; $.getScript('//www.youtube.com/iframe_api'); } else { self.loadPlayer(container, videoId); } }, loadPlayer: function(container, videoId) { player = new YT.Player(container, { videoId: videoId, playerVars: { controls: 0, loop: 1, modestbranding: 0, rel: 0, showinfo: 0 }, events: { 'onReady': this.onPlayerReady } }); }, onPlayerReady: function() { player.setPlaybackQuality('hd720'); player.seekTo(8,false); player.pauseVideo(); } }); return VideoView; }); ```
2014/01/22
[ "https://Stackoverflow.com/questions/21289707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/529585/" ]
You're definitely along the right lines, but you can simplify your loop and use [.each()](http://api.jquery.com/jquery.each/) function to iterate over all of the `$('.content-block')` elements on your page. You're alos only setting the random colour once, so you can move that into the each function: ``` $('.content-block').each(function(i, el) { var randomColor = Math.floor(Math.random()*background.length); $(el).addClass(background[randomColor]); }); ``` I've also just realised that you might want each `$('.content-block')` to be a different colour from the other. In which case, you want to remove the colour from `colors` each time you've assigned a colour: ``` function getRandomColour() { var randomNumber = Math.floor(Math,random()*colors.length(); var randomColour = colors[randomNumber]; var colourPosition = colors.indexOf(randomColour); colours.splice(colourPosition, 1); // Remove colour from array return randomColour; } $('.content-block').each(function(i, el) { $(el).addClass(background[randomColor]); }); ```
change this `contentBlock.addClass(colors[randomColor]);` to this: ``` contentBlock[i].addClass(colors[randomColor]); ``` Hope it helps.
21,289,707
I'm using Backbone together with require.js and jQuery. What I'm trying to do is to simply bind an event to a container which should show (mouseover) or hide (mouseout) a video. The event fires but unfortunately too many times (I've several children inside `.intro-content`). I tried using `ev.stopPropagation()` (as seen in the code) and `ev.stopImmediatePropagation` but this doesn't prevent the bubbling. What am I doing wrong? View: ``` define([ 'jquery', 'underscore', 'backbone', 'global' ], function($, _, Backbone, Global){ var VideoView = Backbone.View.extend({ el: $('#splitlayout'), events: { 'mouseover .side-left .intro-content': 'checkVideoState', 'mouseout .side-left .intro-content': 'checkVideoState' }, render: function(){ this.playVideo('video', '0GsrOOV0gQM'); this.delegateEvents(); }, initialize: function() { _.bindAll(this); this.render(); }, checkVideoState: function(ev) { ev.stopPropagation(); if(!$('#video').hasClass('active') && ev.type == 'mouseover') { this.showVideo(); } else if($('#video').hasClass('active') && ev.type == 'mouseout') { this.hideVideo(); } }, showVideo: function() { console.log('test'); $('#video').addClass('active'); player.playVideo(); }, hideVideo: function() { console.log('test'); $('#video').removeClass('active'); player.pauseVideo(); }, playVideo: function(container, videoId) { var self = this; if (typeof(YT) == 'undefined' || typeof(YT.Player) == 'undefined') { window.onYouTubeIframeAPIReady = function() { self.loadPlayer(container, videoId); }; $.getScript('//www.youtube.com/iframe_api'); } else { self.loadPlayer(container, videoId); } }, loadPlayer: function(container, videoId) { player = new YT.Player(container, { videoId: videoId, playerVars: { controls: 0, loop: 1, modestbranding: 0, rel: 0, showinfo: 0 }, events: { 'onReady': this.onPlayerReady } }); }, onPlayerReady: function() { player.setPlaybackQuality('hd720'); player.seekTo(8,false); player.pauseVideo(); } }); return VideoView; }); ```
2014/01/22
[ "https://Stackoverflow.com/questions/21289707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/529585/" ]
You're definitely along the right lines, but you can simplify your loop and use [.each()](http://api.jquery.com/jquery.each/) function to iterate over all of the `$('.content-block')` elements on your page. You're alos only setting the random colour once, so you can move that into the each function: ``` $('.content-block').each(function(i, el) { var randomColor = Math.floor(Math.random()*background.length); $(el).addClass(background[randomColor]); }); ``` I've also just realised that you might want each `$('.content-block')` to be a different colour from the other. In which case, you want to remove the colour from `colors` each time you've assigned a colour: ``` function getRandomColour() { var randomNumber = Math.floor(Math,random()*colors.length(); var randomColour = colors[randomNumber]; var colourPosition = colors.indexOf(randomColour); colours.splice(colourPosition, 1); // Remove colour from array return randomColour; } $('.content-block').each(function(i, el) { $(el).addClass(background[randomColor]); }); ```
It will work 100% and it is made of pure Javascript. ```js for (var i = 0; i <= 5; i++) { var r = Math.floor(Math.random()*255); var g = Math.floor(Math.random()*255); var b = Math.floor(Math.random()*255); var div = document.getElementsByClassName("div")[i].style.backgroundColor = "rgb("+r+","+g+","+b+")"; } ``` ```css div { width: 200px; height:200px; display: inline; float: left; margin: 15px; background-color: red; } ``` ```html <div class="div"></div> <div class="div"></div> <div class="div"></div> <div class="div"></div> <div class="div"></div> <div class="div"></div> ```
21,289,707
I'm using Backbone together with require.js and jQuery. What I'm trying to do is to simply bind an event to a container which should show (mouseover) or hide (mouseout) a video. The event fires but unfortunately too many times (I've several children inside `.intro-content`). I tried using `ev.stopPropagation()` (as seen in the code) and `ev.stopImmediatePropagation` but this doesn't prevent the bubbling. What am I doing wrong? View: ``` define([ 'jquery', 'underscore', 'backbone', 'global' ], function($, _, Backbone, Global){ var VideoView = Backbone.View.extend({ el: $('#splitlayout'), events: { 'mouseover .side-left .intro-content': 'checkVideoState', 'mouseout .side-left .intro-content': 'checkVideoState' }, render: function(){ this.playVideo('video', '0GsrOOV0gQM'); this.delegateEvents(); }, initialize: function() { _.bindAll(this); this.render(); }, checkVideoState: function(ev) { ev.stopPropagation(); if(!$('#video').hasClass('active') && ev.type == 'mouseover') { this.showVideo(); } else if($('#video').hasClass('active') && ev.type == 'mouseout') { this.hideVideo(); } }, showVideo: function() { console.log('test'); $('#video').addClass('active'); player.playVideo(); }, hideVideo: function() { console.log('test'); $('#video').removeClass('active'); player.pauseVideo(); }, playVideo: function(container, videoId) { var self = this; if (typeof(YT) == 'undefined' || typeof(YT.Player) == 'undefined') { window.onYouTubeIframeAPIReady = function() { self.loadPlayer(container, videoId); }; $.getScript('//www.youtube.com/iframe_api'); } else { self.loadPlayer(container, videoId); } }, loadPlayer: function(container, videoId) { player = new YT.Player(container, { videoId: videoId, playerVars: { controls: 0, loop: 1, modestbranding: 0, rel: 0, showinfo: 0 }, events: { 'onReady': this.onPlayerReady } }); }, onPlayerReady: function() { player.setPlaybackQuality('hd720'); player.seekTo(8,false); player.pauseVideo(); } }); return VideoView; }); ```
2014/01/22
[ "https://Stackoverflow.com/questions/21289707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/529585/" ]
It looks like the problem might be with how you are incrementing your random color: ``` colors[randomColor]++ ``` That isn't the correct way. You probably just want to increment the index in the array: ``` randomColor++ ``` You also need to make sure you are staying within the bounds of your color array. I would suggest using mod (%) for that: ``` randomColor = (randomColor + 1) % colors.length ``` Using jQuery to loop, you would have somethign like: ``` $(".content-block").each(function () { $(this).addClass(colors[randomColor]); // assign the color randomColor = (randomColor + 1) % colors.length; // step to the next color; this will loop to the beginning thanks to mod }); ```
change this `contentBlock.addClass(colors[randomColor]);` to this: ``` contentBlock[i].addClass(colors[randomColor]); ``` Hope it helps.
21,289,707
I'm using Backbone together with require.js and jQuery. What I'm trying to do is to simply bind an event to a container which should show (mouseover) or hide (mouseout) a video. The event fires but unfortunately too many times (I've several children inside `.intro-content`). I tried using `ev.stopPropagation()` (as seen in the code) and `ev.stopImmediatePropagation` but this doesn't prevent the bubbling. What am I doing wrong? View: ``` define([ 'jquery', 'underscore', 'backbone', 'global' ], function($, _, Backbone, Global){ var VideoView = Backbone.View.extend({ el: $('#splitlayout'), events: { 'mouseover .side-left .intro-content': 'checkVideoState', 'mouseout .side-left .intro-content': 'checkVideoState' }, render: function(){ this.playVideo('video', '0GsrOOV0gQM'); this.delegateEvents(); }, initialize: function() { _.bindAll(this); this.render(); }, checkVideoState: function(ev) { ev.stopPropagation(); if(!$('#video').hasClass('active') && ev.type == 'mouseover') { this.showVideo(); } else if($('#video').hasClass('active') && ev.type == 'mouseout') { this.hideVideo(); } }, showVideo: function() { console.log('test'); $('#video').addClass('active'); player.playVideo(); }, hideVideo: function() { console.log('test'); $('#video').removeClass('active'); player.pauseVideo(); }, playVideo: function(container, videoId) { var self = this; if (typeof(YT) == 'undefined' || typeof(YT.Player) == 'undefined') { window.onYouTubeIframeAPIReady = function() { self.loadPlayer(container, videoId); }; $.getScript('//www.youtube.com/iframe_api'); } else { self.loadPlayer(container, videoId); } }, loadPlayer: function(container, videoId) { player = new YT.Player(container, { videoId: videoId, playerVars: { controls: 0, loop: 1, modestbranding: 0, rel: 0, showinfo: 0 }, events: { 'onReady': this.onPlayerReady } }); }, onPlayerReady: function() { player.setPlaybackQuality('hd720'); player.seekTo(8,false); player.pauseVideo(); } }); return VideoView; }); ```
2014/01/22
[ "https://Stackoverflow.com/questions/21289707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/529585/" ]
It looks like the problem might be with how you are incrementing your random color: ``` colors[randomColor]++ ``` That isn't the correct way. You probably just want to increment the index in the array: ``` randomColor++ ``` You also need to make sure you are staying within the bounds of your color array. I would suggest using mod (%) for that: ``` randomColor = (randomColor + 1) % colors.length ``` Using jQuery to loop, you would have somethign like: ``` $(".content-block").each(function () { $(this).addClass(colors[randomColor]); // assign the color randomColor = (randomColor + 1) % colors.length; // step to the next color; this will loop to the beginning thanks to mod }); ```
It will work 100% and it is made of pure Javascript. ```js for (var i = 0; i <= 5; i++) { var r = Math.floor(Math.random()*255); var g = Math.floor(Math.random()*255); var b = Math.floor(Math.random()*255); var div = document.getElementsByClassName("div")[i].style.backgroundColor = "rgb("+r+","+g+","+b+")"; } ``` ```css div { width: 200px; height:200px; display: inline; float: left; margin: 15px; background-color: red; } ``` ```html <div class="div"></div> <div class="div"></div> <div class="div"></div> <div class="div"></div> <div class="div"></div> <div class="div"></div> ```
302,220
I saw that a chatroom event is going to be held. What is special about chatroom events? Aren't they just the same as the usual chatting? I went to the FAQ and the Help Center, but I see no useful information there.
2015/08/11
[ "https://meta.stackoverflow.com/questions/302220", "https://meta.stackoverflow.com", "https://meta.stackoverflow.com/users/5133585/" ]
Chatroom events are just easy ways for moderators of a room to communicate a scheduled function. They can be created with any purpose in mind, much like their real life counterparts. In the StackOverflow Python chat, we typically schedule our [room meetings as events](https://chat.stackoverflow.com/rooms/info/6/python?tab=schedule) so that everyone is reminded of the occurrence outside of having pinned messages in the starred/pinned messages area of the interface. Finally, the StackOverflow dev team was nice enough to make the events exportable, meaning it's easy to get "official" reminders in whatever calendar solution the user chooses.
They're just like real-life meetings, which are ultimately just people talking as they usually would. The difference is that the people are talking about something specific, in a pre-determined place, at a pre-determined time. If you didn't do that, you would not be able to guarantee that all interested parties were present at the same time in the same place, and your event wouldn't be very successful.
33,067,964
I need to write a program in C++ where the user can do some computation, and when the computation is done, the program will ask the user if he wants to do another computation. I know how to write this in Python: ``` more = "y" while (more == "y"): // computation code print "Do you want to do another computation? y/n " more = input() ``` I created a char variable and used it in the head of the loop, but I don't know how to implement the "input" function in C++. I tried using the cin.get(char\_variable) function but the program seems to skip it entirely.
2015/10/11
[ "https://Stackoverflow.com/questions/33067964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3906984/" ]
You can use `cin >> char_variable;` to get the value. Don't forget: ``` #include <iostream> using namespace std; ```
Your program is quite simple & easy. It goes like this :- ``` #include <iostream> using namespace std; int main() { char ch='y'; do { // compute.... cout<<"do you want to continue ?: "<<flush; cin>>ch; }while (ch=='y' || ch=='Y'); // don't for get the semicolon return 0; } ``` If you want to use `while loop` instead of `do while`, your code will be :- ``` #include <iostream> using namespace std; int main() { char ch='y'; while (ch=='y' || ch=='Y') { // compute.... cout<<"do you want to continue ?: "<<flush; cin>>ch; } // no semicolon needed as in `do while` return 0; } ``` Simple ! Hope your code works.
33,067,964
I need to write a program in C++ where the user can do some computation, and when the computation is done, the program will ask the user if he wants to do another computation. I know how to write this in Python: ``` more = "y" while (more == "y"): // computation code print "Do you want to do another computation? y/n " more = input() ``` I created a char variable and used it in the head of the loop, but I don't know how to implement the "input" function in C++. I tried using the cin.get(char\_variable) function but the program seems to skip it entirely.
2015/10/11
[ "https://Stackoverflow.com/questions/33067964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3906984/" ]
You can use `cin >> char_variable;` to get the value. Don't forget: ``` #include <iostream> using namespace std; ```
If you used cin.get, you probably had the following problem. If you run this code: ``` cout << "give a number:"; int n; cin >> n; cout << "give a char:"; char c; cin.get(c); cout << "number=" << n << endl; ``` you'll get the scenario ``` give a number:12 give a char:number=12 ``` where it seems the `cin.get()` was ignored. In fact it was not. It read the "end-of-line" you typed after the number. You'll see it by adding ``` cout << "char code=" << (int) c << endl; ``` to see the numeric value of the char. --- you'd better use `cin >> c;` instead because it waits for the first non-white char.
33,067,964
I need to write a program in C++ where the user can do some computation, and when the computation is done, the program will ask the user if he wants to do another computation. I know how to write this in Python: ``` more = "y" while (more == "y"): // computation code print "Do you want to do another computation? y/n " more = input() ``` I created a char variable and used it in the head of the loop, but I don't know how to implement the "input" function in C++. I tried using the cin.get(char\_variable) function but the program seems to skip it entirely.
2015/10/11
[ "https://Stackoverflow.com/questions/33067964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3906984/" ]
You can use `cin >> char_variable;` to get the value. Don't forget: ``` #include <iostream> using namespace std; ```
I wrote it this way. I used `cin` for get `char` value from user. ``` #include <iostream> using namespace std ; int main () { char more; cout<<"Do you want to do another computation? y/n "; cin>>more; while(more=='y'){ cout<<"Do you want to do another computation? y/n "; cin>>more; } } ```
33,067,964
I need to write a program in C++ where the user can do some computation, and when the computation is done, the program will ask the user if he wants to do another computation. I know how to write this in Python: ``` more = "y" while (more == "y"): // computation code print "Do you want to do another computation? y/n " more = input() ``` I created a char variable and used it in the head of the loop, but I don't know how to implement the "input" function in C++. I tried using the cin.get(char\_variable) function but the program seems to skip it entirely.
2015/10/11
[ "https://Stackoverflow.com/questions/33067964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3906984/" ]
You can use a do-while loop, which basically runs the loop *at least* once. It runs, then checks the conditional, unlike the plain while loop which checks the conditional then runs. Example: ``` bool playAgain; //conditional of the do-while loop char more; //Choice to play again: 'y' or 'n' string input; /*In this example program, they enter their name, and it outputs "Hello, name" */ do{ //input/output cout << "Enter your name: "; cin >> input; cout << "Hello, " << input << endl << endl; //play again input cout << "Do you want to play again?(y/n): "; cin >> more; cout << endl; //Sets bool playAgain to either true or false depending on their choice if (more == 'y') playAgain = true; else if (more == 'n') playAgain = false; //You can add validation here as well (if they enter something else) } while (playAgain == true); //if they want to play again then run the loop again ```
Your program is quite simple & easy. It goes like this :- ``` #include <iostream> using namespace std; int main() { char ch='y'; do { // compute.... cout<<"do you want to continue ?: "<<flush; cin>>ch; }while (ch=='y' || ch=='Y'); // don't for get the semicolon return 0; } ``` If you want to use `while loop` instead of `do while`, your code will be :- ``` #include <iostream> using namespace std; int main() { char ch='y'; while (ch=='y' || ch=='Y') { // compute.... cout<<"do you want to continue ?: "<<flush; cin>>ch; } // no semicolon needed as in `do while` return 0; } ``` Simple ! Hope your code works.
33,067,964
I need to write a program in C++ where the user can do some computation, and when the computation is done, the program will ask the user if he wants to do another computation. I know how to write this in Python: ``` more = "y" while (more == "y"): // computation code print "Do you want to do another computation? y/n " more = input() ``` I created a char variable and used it in the head of the loop, but I don't know how to implement the "input" function in C++. I tried using the cin.get(char\_variable) function but the program seems to skip it entirely.
2015/10/11
[ "https://Stackoverflow.com/questions/33067964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3906984/" ]
You can use a do-while loop, which basically runs the loop *at least* once. It runs, then checks the conditional, unlike the plain while loop which checks the conditional then runs. Example: ``` bool playAgain; //conditional of the do-while loop char more; //Choice to play again: 'y' or 'n' string input; /*In this example program, they enter their name, and it outputs "Hello, name" */ do{ //input/output cout << "Enter your name: "; cin >> input; cout << "Hello, " << input << endl << endl; //play again input cout << "Do you want to play again?(y/n): "; cin >> more; cout << endl; //Sets bool playAgain to either true or false depending on their choice if (more == 'y') playAgain = true; else if (more == 'n') playAgain = false; //You can add validation here as well (if they enter something else) } while (playAgain == true); //if they want to play again then run the loop again ```
If you used cin.get, you probably had the following problem. If you run this code: ``` cout << "give a number:"; int n; cin >> n; cout << "give a char:"; char c; cin.get(c); cout << "number=" << n << endl; ``` you'll get the scenario ``` give a number:12 give a char:number=12 ``` where it seems the `cin.get()` was ignored. In fact it was not. It read the "end-of-line" you typed after the number. You'll see it by adding ``` cout << "char code=" << (int) c << endl; ``` to see the numeric value of the char. --- you'd better use `cin >> c;` instead because it waits for the first non-white char.
33,067,964
I need to write a program in C++ where the user can do some computation, and when the computation is done, the program will ask the user if he wants to do another computation. I know how to write this in Python: ``` more = "y" while (more == "y"): // computation code print "Do you want to do another computation? y/n " more = input() ``` I created a char variable and used it in the head of the loop, but I don't know how to implement the "input" function in C++. I tried using the cin.get(char\_variable) function but the program seems to skip it entirely.
2015/10/11
[ "https://Stackoverflow.com/questions/33067964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3906984/" ]
You can use a do-while loop, which basically runs the loop *at least* once. It runs, then checks the conditional, unlike the plain while loop which checks the conditional then runs. Example: ``` bool playAgain; //conditional of the do-while loop char more; //Choice to play again: 'y' or 'n' string input; /*In this example program, they enter their name, and it outputs "Hello, name" */ do{ //input/output cout << "Enter your name: "; cin >> input; cout << "Hello, " << input << endl << endl; //play again input cout << "Do you want to play again?(y/n): "; cin >> more; cout << endl; //Sets bool playAgain to either true or false depending on their choice if (more == 'y') playAgain = true; else if (more == 'n') playAgain = false; //You can add validation here as well (if they enter something else) } while (playAgain == true); //if they want to play again then run the loop again ```
I wrote it this way. I used `cin` for get `char` value from user. ``` #include <iostream> using namespace std ; int main () { char more; cout<<"Do you want to do another computation? y/n "; cin>>more; while(more=='y'){ cout<<"Do you want to do another computation? y/n "; cin>>more; } } ```
33,067,964
I need to write a program in C++ where the user can do some computation, and when the computation is done, the program will ask the user if he wants to do another computation. I know how to write this in Python: ``` more = "y" while (more == "y"): // computation code print "Do you want to do another computation? y/n " more = input() ``` I created a char variable and used it in the head of the loop, but I don't know how to implement the "input" function in C++. I tried using the cin.get(char\_variable) function but the program seems to skip it entirely.
2015/10/11
[ "https://Stackoverflow.com/questions/33067964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3906984/" ]
If you used cin.get, you probably had the following problem. If you run this code: ``` cout << "give a number:"; int n; cin >> n; cout << "give a char:"; char c; cin.get(c); cout << "number=" << n << endl; ``` you'll get the scenario ``` give a number:12 give a char:number=12 ``` where it seems the `cin.get()` was ignored. In fact it was not. It read the "end-of-line" you typed after the number. You'll see it by adding ``` cout << "char code=" << (int) c << endl; ``` to see the numeric value of the char. --- you'd better use `cin >> c;` instead because it waits for the first non-white char.
Your program is quite simple & easy. It goes like this :- ``` #include <iostream> using namespace std; int main() { char ch='y'; do { // compute.... cout<<"do you want to continue ?: "<<flush; cin>>ch; }while (ch=='y' || ch=='Y'); // don't for get the semicolon return 0; } ``` If you want to use `while loop` instead of `do while`, your code will be :- ``` #include <iostream> using namespace std; int main() { char ch='y'; while (ch=='y' || ch=='Y') { // compute.... cout<<"do you want to continue ?: "<<flush; cin>>ch; } // no semicolon needed as in `do while` return 0; } ``` Simple ! Hope your code works.
33,067,964
I need to write a program in C++ where the user can do some computation, and when the computation is done, the program will ask the user if he wants to do another computation. I know how to write this in Python: ``` more = "y" while (more == "y"): // computation code print "Do you want to do another computation? y/n " more = input() ``` I created a char variable and used it in the head of the loop, but I don't know how to implement the "input" function in C++. I tried using the cin.get(char\_variable) function but the program seems to skip it entirely.
2015/10/11
[ "https://Stackoverflow.com/questions/33067964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3906984/" ]
I wrote it this way. I used `cin` for get `char` value from user. ``` #include <iostream> using namespace std ; int main () { char more; cout<<"Do you want to do another computation? y/n "; cin>>more; while(more=='y'){ cout<<"Do you want to do another computation? y/n "; cin>>more; } } ```
Your program is quite simple & easy. It goes like this :- ``` #include <iostream> using namespace std; int main() { char ch='y'; do { // compute.... cout<<"do you want to continue ?: "<<flush; cin>>ch; }while (ch=='y' || ch=='Y'); // don't for get the semicolon return 0; } ``` If you want to use `while loop` instead of `do while`, your code will be :- ``` #include <iostream> using namespace std; int main() { char ch='y'; while (ch=='y' || ch=='Y') { // compute.... cout<<"do you want to continue ?: "<<flush; cin>>ch; } // no semicolon needed as in `do while` return 0; } ``` Simple ! Hope your code works.
4,631,569
How would you go about opening an .xml file that is within a .jar and edit it? I know that you can do... ``` InputStream myStream = this.getClass().getResourceAsStream("xmlData.xml"); ``` But how would you open the xmlData.xml, edit the file, and save it in the .jar? I would find this useful to know and don't want to edit a file outside of the .jar... **and the application needs to stay running the entire time!** Thank you!
2011/01/08
[ "https://Stackoverflow.com/questions/4631569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/516664/" ]
Jar files are just .zip files with different file suffix, and naming convention for contents. So use classes from under `java.util.zip` to read and/or write contents. Modifying contents is not guaranteed (or even likely) to effect running system, as class loader may cache contents as it sees fit. So it might be good to know more about what you are actually trying to achieve with this. Modifying contents of a jar on-the-fly sounds like complicated and error-prone approach...
If you app. has a GUI and you have access to a web site/server, JWS might be the answer. The JNLP API that is available to JWS apps. provides services such as the PersistenceService. Here is a small [demo. of the PersistenceService](http://pscode.org/jws/api.html#ps). The idea would be to check for the XML in the JWS persistence store. If it is not there, write it there, otherwise use the cached version. If it changes, write a new version to the store. The demo. writes to the store at shut-down, and reads at start-up. But there is no reason it could not be called by a menu item, timer etc.
6,234,333
I want to display "goodbye" for 1 second, fade it out, replace it with "hello", and then fade back in. Why doesn't this snippetwork? (jQuery is loaded): ``` <div id="foo">x</div> <script type="text/javascript"> $('#foo').fadeOut().html('goodbye').fadeIn().delay(1000).fadeOut().html('hello').fadeIn(); </script> ``` I'm using the queue correctly, so these commands occur in order (not asynchronously), right? Full version: <http://test.barrycarter.info/stacked1.html> EDIT: Thanks to everyone who answered! I appreciate the alternate suggestions. I guess my real question was "why doesn't my code work?" I'm learning jQuery, and figuring out where my code goes wrong would really help me!
2011/06/04
[ "https://Stackoverflow.com/questions/6234333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have tried your code.just look at this fiddle:<http://jsfiddle.net/anish/cZf6g/>
try putting your statement in ``` $(document).ready(function(){ /*code here*/ }); ``` or putting it in a function then calling that function
6,234,333
I want to display "goodbye" for 1 second, fade it out, replace it with "hello", and then fade back in. Why doesn't this snippetwork? (jQuery is loaded): ``` <div id="foo">x</div> <script type="text/javascript"> $('#foo').fadeOut().html('goodbye').fadeIn().delay(1000).fadeOut().html('hello').fadeIn(); </script> ``` I'm using the queue correctly, so these commands occur in order (not asynchronously), right? Full version: <http://test.barrycarter.info/stacked1.html> EDIT: Thanks to everyone who answered! I appreciate the alternate suggestions. I guess my real question was "why doesn't my code work?" I'm learning jQuery, and figuring out where my code goes wrong would really help me!
2011/06/04
[ "https://Stackoverflow.com/questions/6234333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You want to make the `fadeIn` part of the callback function of `fadeOut`. So... ``` $('#foo').fadeOut('slow', function(){ $('#foo').fadeIn('slow').html('Hello'); }); ``` Change `slow` to `1000` for 1 second or whatever is desired. <http://jsfiddle.net/qK26W/>
try putting your statement in ``` $(document).ready(function(){ /*code here*/ }); ``` or putting it in a function then calling that function
6,234,333
I want to display "goodbye" for 1 second, fade it out, replace it with "hello", and then fade back in. Why doesn't this snippetwork? (jQuery is loaded): ``` <div id="foo">x</div> <script type="text/javascript"> $('#foo').fadeOut().html('goodbye').fadeIn().delay(1000).fadeOut().html('hello').fadeIn(); </script> ``` I'm using the queue correctly, so these commands occur in order (not asynchronously), right? Full version: <http://test.barrycarter.info/stacked1.html> EDIT: Thanks to everyone who answered! I appreciate the alternate suggestions. I guess my real question was "why doesn't my code work?" I'm learning jQuery, and figuring out where my code goes wrong would really help me!
2011/06/04
[ "https://Stackoverflow.com/questions/6234333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You want to make the `fadeIn` part of the callback function of `fadeOut`. So... ``` $('#foo').fadeOut('slow', function(){ $('#foo').fadeIn('slow').html('Hello'); }); ``` Change `slow` to `1000` for 1 second or whatever is desired. <http://jsfiddle.net/qK26W/>
I have tried your code.just look at this fiddle:<http://jsfiddle.net/anish/cZf6g/>
42,038,334
Excuse me if this has been answered previously, but I can't seem to find an answer. How do I convert a string of numbers (e.g "50") into a single char with an ASCII value of the same number, in this case '2'. Is there a way to do this conversion? Alternatively, could I do the same by converting the string to an int first?
2017/02/04
[ "https://Stackoverflow.com/questions/42038334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7501819/" ]
Here for some languages: C/C++ ``` int i = 65; char c = i; printf("%c", c); // prints A ``` JS ``` var c = String.fromCharCode(66); console.log(c); // prints B ``` C#/Java ``` char c = (char)67; // For Java use System.out.println(c) Console.WriteLine(c) // prints C ``` Python ``` c = chr(68) # for Python 2 use c = str(unichr(68)) print(c) # Prints D ```
``` String s = "50"; try { char c = (char) Integer.valueOf(s); ... c } catch (NumberFormatException e) { ... } ``` With catching the NumberFormatException and checking the integer range the code might be made rock-solid.
69,372,101
I want to do something like this: ``` ArrayList<String> strings = new ArrayList<>(); //build a collection of Strings callMethod(strings); ``` The "callMethod" is legacy (in a legacy project), so I cannot change it. It's signature is this: ``` private void callMethod(String... input){ // and so forth... ``` How do I pass the collection of Strings to the callMethod method?
2021/09/29
[ "https://Stackoverflow.com/questions/69372101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17031679/" ]
Just convert the list to an array of Strings ([varargs turns into an array under the hood](https://docs.oracle.com/javase/specs/jls/se17/html/jls-8.html#jls-8.4.1): *"If the formal parameter is a variable arity parameter, then the declared type is an array type specified by §10.2."*): ``` callMethod(strings.toArray(new String[0])); ```
Convert the list of strings into arrays of strings. ``` ArrayList<String> strings = new ArrayList<>(); callMethod(strings.toArray(new String[strings.size()])); ```
69,372,101
I want to do something like this: ``` ArrayList<String> strings = new ArrayList<>(); //build a collection of Strings callMethod(strings); ``` The "callMethod" is legacy (in a legacy project), so I cannot change it. It's signature is this: ``` private void callMethod(String... input){ // and so forth... ``` How do I pass the collection of Strings to the callMethod method?
2021/09/29
[ "https://Stackoverflow.com/questions/69372101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17031679/" ]
Just convert the list to an array of Strings ([varargs turns into an array under the hood](https://docs.oracle.com/javase/specs/jls/se17/html/jls-8.html#jls-8.4.1): *"If the formal parameter is a variable arity parameter, then the declared type is an array type specified by §10.2."*): ``` callMethod(strings.toArray(new String[0])); ```
If you have a method with varargs (variable arguments), you have 2 options: 1. pass each item of the collection as a single argument or 2. pass the collection as an array Example method: ```java /** * <p> * Prints the {@link String}s passed * </p> * * @param item the bunch of character sequences to be printed */ public static void print(String... item) { System.out.println(String.join(" ", item)); } ``` You can use it like this: ```java public static void main(String[] args) throws IOException { // some example list of Strings List<String> words = new ArrayList<>(); words.add("You"); words.add("can"); words.add("pass"); words.add("items"); words.add("in"); words.add("an"); words.add("Array"); // first thing you can do is passing each item of the list to the method print(words.get(0), words.get(1), words.get(2), words.get(3), words.get(4), words.get(5), words.get(6)); // but better pass an array, String[] here String[] arrWords = words.stream().toArray(String[]::new); print(arrWords); } ``` which outputs ```none You can pass items in an Array You can pass items in an Array ```
69,372,101
I want to do something like this: ``` ArrayList<String> strings = new ArrayList<>(); //build a collection of Strings callMethod(strings); ``` The "callMethod" is legacy (in a legacy project), so I cannot change it. It's signature is this: ``` private void callMethod(String... input){ // and so forth... ``` How do I pass the collection of Strings to the callMethod method?
2021/09/29
[ "https://Stackoverflow.com/questions/69372101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17031679/" ]
Just convert the list to an array of Strings ([varargs turns into an array under the hood](https://docs.oracle.com/javase/specs/jls/se17/html/jls-8.html#jls-8.4.1): *"If the formal parameter is a variable arity parameter, then the declared type is an array type specified by §10.2."*): ``` callMethod(strings.toArray(new String[0])); ```
``` public void method() { ArrayList<String> strings = new ArrayList<>(); //1. calling method by passing the array callMethod(strings.toArray(new String[strings.size()])); //2. Using stream method to convert list into array callMethod(strings.stream().toArray(String[]::new)); } // method having array of String as parameter public static void callMethod(String... input){ // TODO Method stub } ```
55,744,147
Calendars have a owner and have a `ManyToMany` field 'assistants' i have a Calendar who has 2 assistants one of which is its owner. I think these 3 lines of code in the django shell can explain the weird behaviour quite well. ```py In [17]: Calendar.objects.filter(assistants=customer).exclude(owner=customer) Out[17]: <QuerySet []> In [20]: Calendar.objects.filter(owner=customer) Out[20]: <QuerySet [<Calendar: aliz cal>, <Calendar: yassi has a calendar>]> In [19]: Calendar.objects.filter(owner=customer) | Calendar.objects.filter(assistants=customer).exclude(owner=customer) Out[19]: <QuerySet [<Calendar: aliz cal>, <Calendar: aliz cal>, <Calendar: yassi has a calendar>]> ``` Of course expected the result of queryset join to be the actual union of them.
2019/04/18
[ "https://Stackoverflow.com/questions/55744147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2696242/" ]
Assuming this is for django 1.11+: `|` does not represent a union. It represents an OR-combination (which maintains **all** joins; hence aliz showing up twice) of two querysets . `qs1.filter(x=1) | qs2.exclude(x=1)` translates to: ``` SELECT STUFF FROM TABLES_AND_JOINS WHERE (x = 1 OR NOT (x = 1)) ``` While `qs1.filter(x=1).union(qs2.exclude(x=1))` translates to: ``` SELECT STUFF FROM TABLE1 WHERE x = 1 UNION SELECT STUFF FROM TABLE2 WHERE NOT x = 1 ``` Use `str(qs.query)` to see the SQL.
What you are doing is `OR`-ing the `WHERE` clauses of both queries, which is different from a union (and a bit tricky when joining is involved; here, the ORM switches from an inner join in queryset #1 to an outer join in queryset #3 to account for the second query that has no joins). See the relevant [docs](https://docs.djangoproject.com/en/2.1/ref/models/querysets/#or). Try [`union()`](https://docs.djangoproject.com/en/2.1/ref/models/querysets/#union), available from Django 1.11 onwards: ``` qs1 = Calendar.objects.filter(assistants=customer).exclude(owner=customer) qs2 = Calendar.objects.filter(owner=customer) qs3 = qs1.union(qs2) ```
14,042,251
I am trying to make buttons with different gradients programmatically. I use ShapeDrawable and it works like a charm. ``` RoundRectShape rs = new RoundRectShape(new float[] { 12f, 12f, 12f, 12f, 12f, 12f, 12f, 12f }, null, null); ShapeDrawable sd = new ShapeDrawable(rs); ShapeDrawable.ShaderFactory sf = new ShapeDrawable.ShaderFactory() { @Override public Shader resize(int width, int height) { LinearGradient lg = new LinearGradient(0, 0, 0, height, new int[] { Color.parseColor("#feccb1"), Color.parseColor("#f17432"), Color.parseColor("#e86320"), Color.parseColor("#f96e22") }, new float[] { 0, 0.50f, 0.50f, 1 }, Shader.TileMode.REPEAT); return lg; } }; sd.setShaderFactory(sf); myBtn.setBackgroundDrawable(sd); ``` However I would like to add a **shadow** to the button, **not the button text** programmatically. Any help would be appreciated.
2012/12/26
[ "https://Stackoverflow.com/questions/14042251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1005194/" ]
> > However I would like to add a shadow to the button, not the button > text programmatically. > > > I guess you want the shadow behind the current drawable you built. If yes then make a [`LayerDrawable`](http://developer.android.com/reference/android/graphics/drawable/LayerDrawable.html) along with another `Drawable`(placed first) that will act as the shadow: ``` RoundRectShape rss = new RoundRectShape(new float[] { 12f, 12f, 12f, 12f, 12f, 12f, 12f, 12f }, null, null); ShapeDrawable sds = new ShapeDrawable(rss); sds.setShaderFactory(new ShapeDrawable.ShaderFactory() { @Override public Shader resize(int width, int height) { LinearGradient lg = new LinearGradient(0, 0, 0, height, new int[] { Color.parseColor("#e5e5e5"), Color.parseColor("#e5e5e5"), Color.parseColor("#e5e5e5"), Color.parseColor("#e5e5e5") }, new float[] { 0, 0.50f, 0.50f, 1 }, Shader.TileMode.REPEAT); return lg; } }); LayerDrawable ld = new LayerDrawable(new Drawable[] { sds, sd }); ld.setLayerInset(0, 5, 5, 0, 0); // inset the shadow so it doesn't start right at the left/top ld.setLayerInset(1, 0, 0, 5, 5); // inset the top drawable so we can leave a bit of space for the shadow to use b.setBackgroundDrawable(ld); ```
A more clean way to do it is using `Paint.setShadowLayer` as in [Jack's answer](https://stackoverflow.com/a/26356439/2313889)
18,425,419
Hoping someone could let me know if this is possible as I have searched and couldn't come up with the desired effect I wanted. I basically want to have the border hover to be centred so when you mouse over the links the border-bottom is centred. I would like the border width to be a fixed size around 20px and centered. As you can see its really basic so far and the jsfiddle is here: <http://jsfiddle.net/pCQLN/3/> I want something like shown in the below image: --- ![enter image description here](https://i.stack.imgur.com/z1VGe.jpg) --- Thank you for any time you can spare! Here's my code; HTML ``` <div id="wrap"> <div id="nav"> <ul> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Projects</a></li> <li><a href="#">Blog</a></li> </ul> </div> </div> ``` CSS ``` #wrap { width:40em; height:3em; margin:0 auto; } #nav { float:right; width:75%; } #nav ul { display:inline; list-style: none; float: right; } #nav li { float: left; width:50px padding-right:1em; } #nav a { text-align:center; text-decoration:none; color: #888; font-size:1em; float: left; } #nav a:hover { color:#212121; display:block; width:20px; margin:0 auto; border-bottom:3px solid #000; } ```
2013/08/25
[ "https://Stackoverflow.com/questions/18425419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1722242/" ]
Use [`:after`](https://developer.mozilla.org/en-US/docs/Web/CSS/%3a%3aafter) pseudo selector in combination with `hover` pseudo selector. ``` #nav a:hover:after{ content: ""; color:#212121; display:block; width:20px; margin:0 auto; border-bottom:3px solid #000; } ``` [**Working Fiddle**](http://jsfiddle.net/venkateshwar/pCQLN/6/)
Add a span, center it and give it the bottom border inside your `a`. Show on hover. [jsfiddle](http://jsfiddle.net/pCQLN/7/) ``` <div id="wrap"> <div id="nav"> <ul> <li><a href="#">Home<span class="line"></span></a></li> <li><a href="#">About<span class="line"></span></a></li> <li><a href="#">Projects<span class="line"></span></a></li> <li><a href="#">Blog<span class="line"></span></a></li> </ul> </div> </div> ```
18,425,419
Hoping someone could let me know if this is possible as I have searched and couldn't come up with the desired effect I wanted. I basically want to have the border hover to be centred so when you mouse over the links the border-bottom is centred. I would like the border width to be a fixed size around 20px and centered. As you can see its really basic so far and the jsfiddle is here: <http://jsfiddle.net/pCQLN/3/> I want something like shown in the below image: --- ![enter image description here](https://i.stack.imgur.com/z1VGe.jpg) --- Thank you for any time you can spare! Here's my code; HTML ``` <div id="wrap"> <div id="nav"> <ul> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Projects</a></li> <li><a href="#">Blog</a></li> </ul> </div> </div> ``` CSS ``` #wrap { width:40em; height:3em; margin:0 auto; } #nav { float:right; width:75%; } #nav ul { display:inline; list-style: none; float: right; } #nav li { float: left; width:50px padding-right:1em; } #nav a { text-align:center; text-decoration:none; color: #888; font-size:1em; float: left; } #nav a:hover { color:#212121; display:block; width:20px; margin:0 auto; border-bottom:3px solid #000; } ```
2013/08/25
[ "https://Stackoverflow.com/questions/18425419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1722242/" ]
Use [`:after`](https://developer.mozilla.org/en-US/docs/Web/CSS/%3a%3aafter) pseudo selector in combination with `hover` pseudo selector. ``` #nav a:hover:after{ content: ""; color:#212121; display:block; width:20px; margin:0 auto; border-bottom:3px solid #000; } ``` [**Working Fiddle**](http://jsfiddle.net/venkateshwar/pCQLN/6/)
You can try something like this: ``` <li><a href="#">Home</a><span class="hovered"></span></li> .hovered { margin: 0; height: 3px; width: 20px; background-color:transparent; display: inline-block; } #nav a:hover + .hovered { background-color: black; } ``` <http://jsfiddle.net/pCQLN/9/>
18,425,419
Hoping someone could let me know if this is possible as I have searched and couldn't come up with the desired effect I wanted. I basically want to have the border hover to be centred so when you mouse over the links the border-bottom is centred. I would like the border width to be a fixed size around 20px and centered. As you can see its really basic so far and the jsfiddle is here: <http://jsfiddle.net/pCQLN/3/> I want something like shown in the below image: --- ![enter image description here](https://i.stack.imgur.com/z1VGe.jpg) --- Thank you for any time you can spare! Here's my code; HTML ``` <div id="wrap"> <div id="nav"> <ul> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Projects</a></li> <li><a href="#">Blog</a></li> </ul> </div> </div> ``` CSS ``` #wrap { width:40em; height:3em; margin:0 auto; } #nav { float:right; width:75%; } #nav ul { display:inline; list-style: none; float: right; } #nav li { float: left; width:50px padding-right:1em; } #nav a { text-align:center; text-decoration:none; color: #888; font-size:1em; float: left; } #nav a:hover { color:#212121; display:block; width:20px; margin:0 auto; border-bottom:3px solid #000; } ```
2013/08/25
[ "https://Stackoverflow.com/questions/18425419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1722242/" ]
Add a span, center it and give it the bottom border inside your `a`. Show on hover. [jsfiddle](http://jsfiddle.net/pCQLN/7/) ``` <div id="wrap"> <div id="nav"> <ul> <li><a href="#">Home<span class="line"></span></a></li> <li><a href="#">About<span class="line"></span></a></li> <li><a href="#">Projects<span class="line"></span></a></li> <li><a href="#">Blog<span class="line"></span></a></li> </ul> </div> </div> ```
You can try something like this: ``` <li><a href="#">Home</a><span class="hovered"></span></li> .hovered { margin: 0; height: 3px; width: 20px; background-color:transparent; display: inline-block; } #nav a:hover + .hovered { background-color: black; } ``` <http://jsfiddle.net/pCQLN/9/>
408,115
I'm looking for an elementary proof of the fact that $\ell(nP) = \dim L(nP) = n$, where $L(nP)$ is the linear (Riemann-Roch) space of certain rational functions associated to the divisor $nP$, where $n > 0$ is an integer and $P$ is a point on a curve of genus 1. This fact is used to prove that every elliptic curve is isomorphic to a curve given by a Weierstrass equation. See for instance Silverman, The Arithmetic of Elliptic Curves, p. 59, Proposition 3.1.(a). I know that it's a corollary to the Riemann-Roch theorem (it follows from the corollary that says if $\deg D > 2g - 2$ then $\ell(D) = \deg D + 1 - g$). The proof of the full Riemann-Roch theorem still looks a little intimidating to me, so I'm hoping someone can provide a more elementary proof of this special case, perhaps by making the relevant simplifications in the proof of the Riemann-Roch theorem. Thanks in advance.
2013/06/01
[ "https://math.stackexchange.com/questions/408115", "https://math.stackexchange.com", "https://math.stackexchange.com/users/23180/" ]
Let $X$ be an elliptic curve over $k$, and $P \in X$. We have to prove that for $D=nP$ we have $$ l(D)=\deg(D)=n $$ If $D$ satisfies the above equation, and $E$ is a divisor such that $E \geq D$, then we have $l(E)=\deg(E)$ (cf. [Fulton](http://www.math.lsa.umich.edu/~wfulton/CurveBook.pdf), Corollary 8.3.1). Hence it is enough to show that $l(P)=1$. Clearly $l(P) > 0$, since $k \subset L(P)$. On the other hand, $l(P) > 1$ would imply that there exists $x \in k(X)$ such that $x$ has a simple pole at $P$, and no other poles. But this would imply that the map $$ x: X \rightarrow \Bbb{P}^1 $$ is an isomorphism, which is a contradiction. Thus $l(P)=1$.
Here is an elementary solution in a very special case. It assumes that the curve is already embedded in the plane using a Weierstrass-like equation, so you can't use it to later prove that every elliptic curve can be given by a Weierstrass equation, but perhaps it will still be instructive. We assume the base field is of characteristic $0$ and algebraically closed. Suppose $E$ is the projective curve in $\mathbb{P}^2$ defined by the following equation in $\mathbb{A}^2$, $$y^2 = (x - \lambda\_1)(x - \lambda\_2)(x - \lambda\_3)$$ where $\lambda\_1, \lambda\_2, \lambda\_3$ are non-zero and distinct. It can be shown that $E$ is a smooth curve with a unique point at infinity, namely $P = (0 : 0 : 1)$. As Nils Matthes has indicated, to show that $\ell (n P) = n$ for all $n \ge 1$, it suffices to prove the case $n = 1$. Suppose, for a contradiction, that $\ell (P) > 1$. We know that for all divisors $D$, $\ell (D) \le \deg D + 1$, so that means $\ell (P) = 2$, and so there is some non-constant rational function $t$ such that $L (P)$ is spanned by $1$ and $t$. Moreover, $t$ has a simple pole at $P$ (and nowhere else), so $t^n$ has a pole of order $n$ at $P$ (and nowhere else). As such, $L (n P)$ is spanned by $1, t, \ldots, t^n$. However, we know that $y$ is in $L (2 P)$ and $x$ is in $L (3 P)$, so that means, for some constants, \begin{align} x & = a\_0 + a\_1 t + a\_2 t^2 \\ y & = b\_0 + b\_1 t + b\_2 t^2 + b\_3 t^3 \end{align} and by rescaling $t$ if necessary, we may assume that $a\_2 = b\_3 = 1$. (Note that $a\_2^3 = b\_3^2$.) We may also complete the square to assume that $a\_1 = 0$. But then substituting into the original equation, we get $$(b\_0 + b\_1 t + b\_2 t^2 + t^3)^2 = (t^2 + a\_0 - \lambda\_1) (t^2 + a\_0 - \lambda\_2) (t^2 + a\_0 - \lambda\_3)$$ which is impossible, since the RHS has six distinct zeros.
53,676,235
My software builds use `-Xlint -Werror` so I routinely run across compiler warnings that break my build. Every once in a while I run across a warning that I need to suppress, but it's always difficult to figure out which `Xlint` option suppresses the warning I am seeing. I'll give you a concrete example. I recently ran across: ``` [WARNING] module-info.java:[16,106] module not found: org.bitbucket.cowwoc.requirements.guava ``` I searched the JDK 11 source-code and discovered this warning message declared at `/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/compiler.properties` as: ``` # 0: symbol compiler.err.module.not.found=\ module not found: {0} ``` Now, it turns out that this is suppressed by `-Xlint:-module` but that's not obvious from the documentation. `-Xlint:-export` could made sense as well. I've also run across warnings in the past that couldn't be suppressed at all (these were subsequently fixed). Instead of resorting to trial and error, **is there a deterministic way to figure out which `Xlint` option corresponds to each warning message**? Is there some sort of mapping file somewhere in the JDK source codes? **UPDATE**: I am using Maven 3.6.0, maven-compiler-plugin 3.8.0, JDK 11.0.1
2018/12/07
[ "https://Stackoverflow.com/questions/53676235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14731/" ]
One way to do that, if somehow you're not able to access the [online documentation](https://docs.oracle.com/en/java/javase/11/tools/javac.html#GUID-AEEC9F07-CB49-4E96-8BC7-BCC2C7F725C9) could be using the command ``` javac --help-extra ``` This would list out the possible warnings that you could enable/disable. For example from ***`javac 12-ea`*** : [![enter image description here](https://i.stack.imgur.com/W44GG.png)](https://i.stack.imgur.com/W44GG.png)
Alan Bateman pointed me in the right direction. It seems that the maven-compiler-plugin suppressing vital information. Here is the output from javac 11.0.1: ``` C:\Users\Gili\Documents\requirements\java\src\main\java\module-info.java:16: warning: [module] module not found: org.bitbucket.cowwoc.requirements.guava exports org.bitbucket.cowwoc.requirements.java.internal.impl to org.bitbucket.cowwoc.requirements.guava; ``` Here is the corresponding output from maven-compiler-plugin: ``` [WARNING] /C:/Users/Gili/Documents/requirements/java/src/main/java/module-info.java:[16,106] module not found: org.bitbucket.cowwoc.requirements.guava ``` `javac` mentions `[module]` at the beginning of the warning, indicating that `-Xlint:-module` will suppress this warning. I filed a bug report here: <https://issues.apache.org/jira/browse/MCOMPILER-367>
31,929,963
On my html page I have a button, and a number being displayed. I want the number to increase by 1 every time the button is pressed. This is the code that I have so far, but for some it doesn't work. mypage.html ```html <form method='get' action='#'> <input type="submit" value="add" name="add"/> </form> <h1>{{ p }}</h1> ``` views.py ```python p = 1 def mypage(request): global p my_dictionary = { "p" : p, } if request.GET.get('add'): p = p+1 my_dictionary = { "p" : p, } return render(request, "mypage.html", my_dictionary) ```
2015/08/10
[ "https://Stackoverflow.com/questions/31929963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5131031/" ]
On every request a new instance of the python script is run which would result in your global variable not being retained. You should store the count in a database and recall the value on every request. There are options other than a database but the basic idea of needing some sort of persistent storage still exists. Alternatively, you can have the requester keep track of the count and provide the current count in the request. You would then add one to the value provided in the request. This would require some additional code on the front end to maintain the count, and even then, if the user closes the browser the count will be reset. As dm03514 pointed out, you can can also use sessions like so: ``` if 'p' in request.session: request.session['p'] = request.session['p'] + 1 else: request.session['p'] = 1 ```
The p value needs to be kept track of across requests. 2 possibilities are * resend the data every request * store the data in a session and just make increment /decrement requests Should the variable be shared between all users? Or just the current user?
31,929,963
On my html page I have a button, and a number being displayed. I want the number to increase by 1 every time the button is pressed. This is the code that I have so far, but for some it doesn't work. mypage.html ```html <form method='get' action='#'> <input type="submit" value="add" name="add"/> </form> <h1>{{ p }}</h1> ``` views.py ```python p = 1 def mypage(request): global p my_dictionary = { "p" : p, } if request.GET.get('add'): p = p+1 my_dictionary = { "p" : p, } return render(request, "mypage.html", my_dictionary) ```
2015/08/10
[ "https://Stackoverflow.com/questions/31929963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5131031/" ]
On every request a new instance of the python script is run which would result in your global variable not being retained. You should store the count in a database and recall the value on every request. There are options other than a database but the basic idea of needing some sort of persistent storage still exists. Alternatively, you can have the requester keep track of the count and provide the current count in the request. You would then add one to the value provided in the request. This would require some additional code on the front end to maintain the count, and even then, if the user closes the browser the count will be reset. As dm03514 pointed out, you can can also use sessions like so: ``` if 'p' in request.session: request.session['p'] = request.session['p'] + 1 else: request.session['p'] = 1 ```
It should work if there is a single instance of django running (although it is not the recommended approach like other's have suggested). It didn't appear to work is because you used `action='#'`, and the browser refused to resubmit the form when your URL already ends with `#`. Instead you can use the following template: ``` <form method='get' action='.'> <input type="submit" value="add" name="add"/> </form> <h1>{{ p }}</h1> ```
196,904
Without warning, a wizard casts *telepathy* targeting a friend who is on a different continent. > > You create a telepathic link between yourself and a willing creature with which you are familiar. > > > How is it decided whether the target is willing? Does the wizard get 6 seconds to quickly introduce herself? Does the target "feel" a "friend request/phone call" and envision the caster in their head and then decide whether to let them in/answer? I wondered if the spell assumes the target is willing until the target decides otherwise, but there is no option for the target to end the spell.
2022/03/18
[ "https://rpg.stackexchange.com/questions/196904", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/46827/" ]
### Short answer, you will need to establish an agreement ahead of time. As the check occurs before the connection is ever established. This is apparently not a spell used for cold calling. As explained by @Fie (emphasis theirs) > > according to the spell targetting rules in XGE (pp. 85–6), the validity of the target (i.e. whether the creature is willing) must be determined *before* the spell has any effect (including the target recognising you as the creature it ***is* communicating** with). > > > Meaning that though you are familiar with the target, they must be willing to receive your message before they receive it. A short conversation among friends can be had, "Hey, is it ok if I use telepathy to communicate with you in the future?" to establish that willingness in some regard ahead of time. If the target for some reason becomes unwilling, the spell will fail without contact ever being established and the target not realizing you attempted to reach them. Perhaps they are busy at the moment, but that doesn't stop them from later being willing once more. **The Willingness check will occur before connection is made on casting the spell.** Alternatively, there may be a discussion on the hypothetical, * "if A somehow knew that it was B calling, would they accept the call?" willingness being applied that way, as they are willing in this case. But it is unclear if the question instead is, * "are they willing to accept an unknown call before knowing who sent the request?" which might not be the same willingness. Could be stated more clearly in either case. Curious though, the duration *is 24 hours* without an off switch *other than* moving to another plane of existence. Once the spell succeeds, the willingness of the creature to continue the link is seemingly **no longer** considered.
The rules don't specify the exact mechanism, so the GM will need to adjudicate. If the target of the spell is a PC, the GM will need to give the player enough information to decide if the player is willing. If the target of the spell is an NPC, the GM will need to decide for the NPC. The GM may want to establish house rules for exactly how it works, but the need for those rules is going to vary tremendously from table to table. In many cases, the adjudication should be pretty easy. Let's assume the target is a PC: GM: You get a strange feeling. Your friend, Wendy the Wizard, is trying to establish a telepathic link with you. Are you willing? Player: I...how do I know it's Wendy? GM: You just know. Player: How do I know? GM: It's magic, but it's sort of like seeing someone's face or hearing their voice, you recognize them. At this point, the player decides whether to accept the connection or not, or maybe they ask more questions. A given table may need to have further discussion, or may not.
196,904
Without warning, a wizard casts *telepathy* targeting a friend who is on a different continent. > > You create a telepathic link between yourself and a willing creature with which you are familiar. > > > How is it decided whether the target is willing? Does the wizard get 6 seconds to quickly introduce herself? Does the target "feel" a "friend request/phone call" and envision the caster in their head and then decide whether to let them in/answer? I wondered if the spell assumes the target is willing until the target decides otherwise, but there is no option for the target to end the spell.
2022/03/18
[ "https://rpg.stackexchange.com/questions/196904", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/46827/" ]
On further review, later in the spell description it says (emphasis added): > > Until the spell ends, you and the target can instantaneously share words, images, sounds, and other sensory messages with one another through the link, **and the target recognizes you as the creature it is communicating with**. > > > I see two reasons for that text: 1. To handle the corner case of multiple telepathy effects (you know who is who among the many voices in your head); and 2. The word "willing" is in error earlier in the spell and this sentence is indicating that the target knows who is "calling them". Note that the sharing of thoughts is optional, so there is no risk for unwilling recipients except maybe distracting images? I agree that RAW, you need to arrange things ahead of time (as per above), but I'm thinking that RAI you make the connection and they know who you are and can choose whether to share their thoughts.
The rules don't specify the exact mechanism, so the GM will need to adjudicate. If the target of the spell is a PC, the GM will need to give the player enough information to decide if the player is willing. If the target of the spell is an NPC, the GM will need to decide for the NPC. The GM may want to establish house rules for exactly how it works, but the need for those rules is going to vary tremendously from table to table. In many cases, the adjudication should be pretty easy. Let's assume the target is a PC: GM: You get a strange feeling. Your friend, Wendy the Wizard, is trying to establish a telepathic link with you. Are you willing? Player: I...how do I know it's Wendy? GM: You just know. Player: How do I know? GM: It's magic, but it's sort of like seeing someone's face or hearing their voice, you recognize them. At this point, the player decides whether to accept the connection or not, or maybe they ask more questions. A given table may need to have further discussion, or may not.
66,273,005
I am trying to integrate my spring boot application with docusign for sending the documents and getting it signed from the users. I am not able to do it because I am not getting as how to get the JWT token to call the API's. I have downloaded the java code example from the docusign and configured accordingly. I am able to call the API's from the postman properly, But when I call any API from my application by rest template it gives me 302 redirect found. Is there any example project with java available for this ? Am I missing something.
2021/02/19
[ "https://Stackoverflow.com/questions/66273005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6057802/" ]
I have figured out the solution myself. It's the issue with the session management and security in the example code. If I call any API from rest template there is no session at the beginning and it requires a JWT. So I need to pass a session Id in the header which is active and holds the value of the current user.
The Code Example Launchers that we have for Java do operate on SpringBoot and has an example framework for creating JWT tokens, they should work for you out of the box. Usually when we see someone getting stuck at a 302 it's because the application isn't following provided redirects -- most commonly when the baseUrl being targeted is using http over https. Can you doublecheck your baseUrl and make sure that's the case? It's common to see 302s like this but not so much for them to be a roadblock.
1,679,371
I have an ID (number format) that has trailing decimals in the source data. I need to retain the rounded number (see example attached) and have the trailing decimals removed from the data. The decimals are causing upload issues/error into a system that I use. I have tried formatting to number and removing decimal places, =INT, =ROUND, etc and I can get the cell view to reflect what I want but when I click on the cell, the formula bar still appears to retain the trailing decimals. How do I remove these? Thanks in advance! [![Example](https://i.stack.imgur.com/n3kOe.jpg)](https://i.stack.imgur.com/n3kOe.jpg)
2021/10/01
[ "https://superuser.com/questions/1679371", "https://superuser.com", "https://superuser.com/users/-1/" ]
All of IP addresses 1 - 7 may well exist only between your laptop and the 4G modem. As the whole path is wired, there's no way to set up a MITM in between; unless there's another way to access your firewall. The 4G modem requires connection to a service provider, and it will only connect to the provider who provided the SIM Card, so a MITM in between the modem and the service provider is also extremely unlikely. Tunnels in this context have nothing to do with caching, they're just a way to route traffic in a specific way. To quote [Wikipedia](https://en.wikipedia.org/wiki/IP_tunnel): > > An IP tunnel is an Internet Protocol (IP) network communications channel between two networks. It is used to transport another network protocol by encapsulation of its packets. > > > Usually tunnels are used because it simplifies the routing one way or another. In this context something may be internally configured to use a tunnel, for example the Ethernet-over-USB interface that connects the modem to the firewall. Can't say much more than that without knowing more of the setup; the hardware and the configuration. Connection refused has nothing to do with port 80, only the fact that your client isn't authorized to connect to that tunnel.
Your carrier is free to use any rfc1918 (ie private soace) in their network for parts you dont need to be able to reach - indeed doing this can save real IP space. You have not pointed out where your world routable or CGN IP is defined, and doing this could be useful in you understanding how tnings fit together. Also be aware that the reported IP addresses in a traceroute are for guidance purposes only It is entirely possible there are things messing with the ICMP (or equivalent) packet TTLs causing duplicates masking real IP addresses - but you would need to communicate with your ISP if those are a concern. HTTPS is cachable - although the word cachable is vague. Relatedly large content providers often will deploy equipment to ISPs to distribute and cache content. Typically the content provider will provide equipment to do caching including appropriate certificates so https does not fail, and work with the ISP to ensure traffic is appropriately routed to the caching bix in the ISP network.
24,399,292
I have made a client-server application which can connect over the internet. I have hard coded in my client the server's IP which is fixed. My question is that I want a way that will not take a lot of processing and memory. I want my client to check if internet is available and then try to connect to the server if its up and running. If not then to wait and try again. Keeping in mind that the app is supposed to always run on your computer 24/7 and connect when possible just like skype does, in the sense that its always on and when you have the internet available and server reachable , it connects. My client's code that connects to the server: ``` private void connectToServer() throws Exception { showMessage("Attempting Connection... \n"); try{ connection = new Socket(InetAddress.getByName(serverIP), 6789); showMessage("Ok dude you are Connected to:" + connection.getInetAddress().getHostName());} catch(IOException e){ int x = 0; while (true){ try { showMessage("Sorry Your IP was not found, \nAutomatic detection:"); showMessage("Now trying again"); connection = new Socket(InetAddress.getByName(serverIP),6789); break; } catch (UnknownHostException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); showMessage("\nConnection not established, trying again\n"); } /*x++; if(x>10) break;*/ } //throw new Exception(); } } ``` This does work but takes a lot of processing and memory ! I know that by adding thread.sleep(5000), I am going to add them eventually etc... But this doesn't solve the memory problem. My program would be running for a long time and this doesn't stop the inevitable. Is there a better way? THANKS P.S : showMessage() is just my function that displays the output on my GUI The way I checked memory was using Window's Task Manager ! (the memory increases drastically)
2014/06/25
[ "https://Stackoverflow.com/questions/24399292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3677907/" ]
An array of T when used in most expressions will decay to a pointer of type "pointer to T" and have the value equal to the address of the first element of the array. If `Str` is declared as: ``` char Str[3][5]; ``` Then `Str` will decay to `char (*)[5]`, and have the value of `&Str[0]`. If passing to a function, you can declare the function as follows: ``` void foo (char (*str)[5], size_t n); ``` And within `foo()`, you would access `str` as you would access `Str` itself.
[Pointer address in a C multidimensional array](https://stackoverflow.com/questions/2003745/pointer-address-in-a-c-multidimensional-array) To expand on this answer to a similar question, when we type to get addresses of arrays. The name of the array is actually a pointer to the first variable in the array. You can't really pass a pointer of a particular part of an array, as what we interact with in coding is the pointer itself. `(array + 1) == array[1]` Let's say we have create an array pointer `int* arrayPointer;` and you want to get the second variable in the array. You could either assign `arrayPointer = array + 1` or `arrayPointer = &array[1]` So if you want to modify part of array[3][5] the easiest way is to pick that part of the array and assign a variable to it. For example if you want to modify the first "column" and first "row" you would type... `array[0][0] = variable` Hope this helps.
48,479,065
I have a code given below. when I run the code, all x1,x2 and x3 having same values.As per logic x1 should have random numbers, x2 also random numbers , x3 should have 0s and 1s. ``` import numpy as np def reluDerivative(x): yy=x; yy[yy<=0] = 0 yy[yy>0] = 1 return yy x1=np.random.uniform(-1, 1,10) x2=x1 x3=reluDerivative(x1) ```
2018/01/27
[ "https://Stackoverflow.com/questions/48479065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7425709/" ]
You should think of python variables as **labels**, hence when you do `x2=x1` you are just creating a new label for the same data in memory, this differs in behaviour for mutable and immutable objects, for example: ``` x1 = [] x2 = x1 x2.append(10) print(x2) print(x1) ``` will result on printing: ``` [10] [10] ``` Because both `x2` and `x1` are labeling the same list. This is the behaviour for mutable objects, for immutable objects: ``` x1 = 10 x2 = x1 x2 += 5 print(x2) print(x1) ``` will print: ``` 15 10 ``` Because in this case `x2` is re-assigned to label the new created `15` due to the `+` operation. The solution is just to copy the data from the original object (for your numpy object): ``` x2 = np.copy(x1) ```
You just give the same list `x1` another name: `x2` that bot point to the same data. modifying one is modifying the data that the other one points to as well. You need to (shallow) copy: ``` import numpy as np def reluDerivative(yy): return [0 if x <=0 else 1 for x in yy ] x1 = np.random.uniform(-1, 1,10) x2 = x1.copy() # copy of x1, no longer same data x1[0] = 2 # proves decoupling of x1 and x2 x3 = reluDerivative(x2) print(x1, x2, x3) ``` Output: ``` [2. 0.84077008 -0.30286357 -0.26964574 0.3979045 -0.8478326 -0.4056378 0.16776436 0.55790904 0.3550891 ] [-0.00736343 0.84077008 -0.30286357 -0.26964574 0.3979045 -0.8478326 -0.4056378 0.16776436 0.55790904 0.3550891 ] [0, 1, 0, 0, 1, 0, 0, 1, 1, 1] ```
65,838,713
I was looking to download kdiff for windows from <https://download.kde.org/stable/kdiff3/> and I noticed the latest package is kdiff3-1.8.5-windows-64-cl.exe while the next-latest is kdiff3-1.8.4-windows-64.exe Does the -cl signify anything like a library I need or stability or ??? There is 0 documentation that I can find on how to download and install anything later than 0.9.98. Couldn't find any clue on the project site <https://invent.kde.org/sdk/kdiff3> about the -cl and I couldnt figure out how to ask there ... Loading up a new computer and reluctant to add something that seems a little like it might have special requirements or caveats. thanks!
2021/01/22
[ "https://Stackoverflow.com/questions/65838713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2407039/" ]
It was built using the MSVC command line compiler (cl.exe) that comes with Visual Studio. See: <https://learn.microsoft.com/en-us/cpp/build/reference/compiler-options?view=msvc-160>
I can't say what the `-cl` stands for, but it has been a suffix before, for example for version 1.8.2. I'm currently running 1.8.5 (from that location, the one with the `-cl` suffix) and it works fine.
10,751,076
I'm new to django and for practice I'm trying to program my own version of the all familiar 'todo list' app. I have some page that displays all todo list items the user has entered, along with a button to edit each one. The edit button sends the user to another page with a form to enter in the changes to the item. It's possible for the user to change everything about the item. Obviously request.POST gives me all the information the user just put into the form, but I want this information to rewrite the info of the item they originally clicked on. So how do I write the view code to find out what that original item was? I guess I could format my form submit button to: > > `<button type="submit" name="save" value={{ item.pk }}>Save</button>` > > > and get the primary key that way but lets say I had passed two items to the edit page and I wanted to give the user the ability to combined them. Again, I *could* figure out what those items were by doing: > > `<button type="submit" name="save" value='{{ item1.pk }} {{ item2.pk }}'>Save</button>` > > > then > > `request['save'].split(' ')` > > > this seems kinda stupid though. Is there some other, less brute force, way? like a: > > request.tell\_me\_all\_items\_passed\_to\_the\_template > > > kind of thing?
2012/05/25
[ "https://Stackoverflow.com/questions/10751076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1322179/" ]
In case someone else has the same question **So instead of doing this:** *template* ``` <form method="post" action="/list/saving/"> <!--- form fields ---> <button type="submit" name="save" value='{{ item.pk }}'>Save</button> </form> ``` *url.py* ``` (r'^list/saving/$', save) ``` *views.py* ``` def save(request): .... item = Item.objects.get(pk=request.POST['save']) .... ``` **do this:** *template* ``` <form method="post" action="{% url todolist.views.save item.pk %}"> <!--- form fields ---> <button type="submit" name="save">Save</button> </form> ``` *url.py* ``` (r'^list/saving/(\d+)/$', save) ``` *views.py* ``` def save(request, pk): .... item = Item.objects.get(pk=pk) .... ``` [More info on url reversing](https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#url)
If you really need to, just use hidden inputs. But, this is unnecessary anyways. The user may be able to change "everything" about the item, but they can't change the `pk` (or at least they *shouldn't* be able to... don't give them the option to). The `pk` is what Django uses to identify an object, so this is already handled for you. Not sure what the issue here is.
356,472
What do the matching "L" shapes (near `.5` and `20`) mean in this forumla? ![fomula with unknown symbols](https://i.stack.imgur.com/MoxWg.png) The document where I found this formula can be found here: <http://www.cs.cmu.edu/~hcwong/Pdfs/icip02.ps>
2013/04/09
[ "https://math.stackexchange.com/questions/356472", "https://math.stackexchange.com", "https://math.stackexchange.com/users/13360/" ]
The bracketing symbol means Floor (see <http://en.wikipedia.org/wiki/Floor_and_ceiling_functions>) The definition of Floor is $\lfloor x \rfloor$ = Largest integer less than x. This is very similar to rounding down as $\lfloor 2.3 \rfloor = \lfloor 2.999 \rfloor = 2$. However, the subtlety is that for negative numbers it acts slightly differently, as $\lfloor -1.5 \rfloor = -2$ which might not be what you expect at first.
Floor function: Round down to the nearest integer.
4,346,191
hey :) ok im looking for a way to create a large number of panels in wxpython and append a hold to them in a list but am not sure how best to do this. for example for i in list: wx.Panel(self, -1, pos, size) #create the panel somehow store a hold to it e.g ============================== anotherlist.append(a) #where a is the hold to the panel when i say hold i mean say the variable name is x, so x = wx.Panel. i would call x the hold cos x can be used for any manipulation of the widget, e.g x.SetPosition etc.. i was thinking maybe using a class something(wx.Panel) that creates the panel and saves the id of the panel.. problem is having the id i have no idea how to access the widget. say the panels id is -206. how do i do something like widgetid(-206).SetBackgroundColour("RED")
2010/12/03
[ "https://Stackoverflow.com/questions/4346191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/527204/" ]
Some people solve these sorts of things by creating the ids at the beginning of the file: ``` panelOneId = wx.NewId() panelTwoId = wx.NewId() ``` And then doing something like myPanel = wx.FindWindowById(panelOneId). Of course, if all you're doing is setting panel attributes, it might just behoove you to create a helper method like this: ``` #---------------------------------------------------------------------- def createPanel(self, sizer, id, bg): """""" panel = wx.Panel(self, id=id) panel.SetBackgroundColour(bg) sizer.Add(panel) ``` You can also use wx.FindWindowByName, if you've given the panels unique name parameters.
A simple solution is to use a dictionary to map ids to panels ``` panels = {} for i in range(100): id = wx.NewId() panels[id] = wx.Panel(parent, id, ...) ``` You then have access to a list of ids (`.keys()`), a list of panels (`.values()`) and a mapping from id to panel.
49,152,669
I have an android app that gets my devices location and adds a marker. It also tracks the location and the marker moves. I want to add a marker on the map each time the location changes, so I can then draw a Polyline between them at a later date. I am not using firebase or a DBHelper. Just looking for a simple way to do it. This is the onLocationChanged function ``` @Override public void onLocationChanged(Location location) { LatLng myCoordinates = new LatLng(location.getLatitude(), location.getLongitude()); LocationMarker.setPosition(myCoordinates); mMap.moveCamera(CameraUpdateFactory.newLatLng(myCoordinates)); float zoomLevel = 12.0f; mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myCoordinates, zoomLevel)); ``` } This is my onCreate function ``` protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tracking); mOptions = new MarkerOptions().position(new LatLng(0, 0)).title("My Current Location") .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)); if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { checkLocationPermission(); } // Gets map fragment and allows map to display location SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(map); mapFragment.getMapAsync(this); } ``` Is it possible to store the lat and long into an array and use the array to plot the points? I've been trying to get my head around it but there isn't a definitive
2018/03/07
[ "https://Stackoverflow.com/questions/49152669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9385851/" ]
The config variables are created using the firebase cli. If you type `firebase --help` you will get an output which includes the following: ``` functions:config:clone [options] clone environment config from another project functions:config:get [path] fetch environment config stored at the given path functions:config:set [values...] set environment config with key=value syntax functions:config:unset [keys...] unset environment config at the specified path(s) ```
What are you trying to achieve exactly ? I think you missed a step, this part uses the cloud function from firebase. You can see here "Extending Cloud Firestore with Cloud Functions" <https://cloud.google.com/firestore/docs/extend-with-functions> Which will help you to extend firestore with cloud functions, and here you have a tutorial to write your first cloud function: <https://firebase.google.com/docs/functions/get-started> Once you have that, you will notice that you will create ``` const functions = require('firebase-functions'); ``` Which then allow you to do: ``` functions.config() ``` This is your "functions config variables". I'm guessing if you load Algolia dependency, you will have access to ``` functions.config().algolia.xxx; ```
49,152,669
I have an android app that gets my devices location and adds a marker. It also tracks the location and the marker moves. I want to add a marker on the map each time the location changes, so I can then draw a Polyline between them at a later date. I am not using firebase or a DBHelper. Just looking for a simple way to do it. This is the onLocationChanged function ``` @Override public void onLocationChanged(Location location) { LatLng myCoordinates = new LatLng(location.getLatitude(), location.getLongitude()); LocationMarker.setPosition(myCoordinates); mMap.moveCamera(CameraUpdateFactory.newLatLng(myCoordinates)); float zoomLevel = 12.0f; mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myCoordinates, zoomLevel)); ``` } This is my onCreate function ``` protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tracking); mOptions = new MarkerOptions().position(new LatLng(0, 0)).title("My Current Location") .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)); if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { checkLocationPermission(); } // Gets map fragment and allows map to display location SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(map); mapFragment.getMapAsync(this); } ``` Is it possible to store the lat and long into an array and use the array to plot the points? I've been trying to get my head around it but there isn't a definitive
2018/03/07
[ "https://Stackoverflow.com/questions/49152669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9385851/" ]
I get the feeling that the reasons the other answers may not be working for you is that you are looking for how to SET the config, as opposed to retrieving it. If you don't have it already, you'll need to install the Firebase CLI, as per the steps in <https://firebase.google.com/docs/cli/> . with it installed, you can set up your config like so: `firebase functions:config:set algolia.app_id="YOUR_APP_ID_HERE"` You can set multiple variables at once by just separating them with spaces like so: `firebase functions:config:set algolia.api_id="YOUR_API_ID_HERE" algolia.search_key="YOUR_SEARCH_KEY_HERE"` To check you have the right config in there, you can also run: `firebase functions:config:get` Which should print out, in JSON format, the current config you have set.
What are you trying to achieve exactly ? I think you missed a step, this part uses the cloud function from firebase. You can see here "Extending Cloud Firestore with Cloud Functions" <https://cloud.google.com/firestore/docs/extend-with-functions> Which will help you to extend firestore with cloud functions, and here you have a tutorial to write your first cloud function: <https://firebase.google.com/docs/functions/get-started> Once you have that, you will notice that you will create ``` const functions = require('firebase-functions'); ``` Which then allow you to do: ``` functions.config() ``` This is your "functions config variables". I'm guessing if you load Algolia dependency, you will have access to ``` functions.config().algolia.xxx; ```
49,152,669
I have an android app that gets my devices location and adds a marker. It also tracks the location and the marker moves. I want to add a marker on the map each time the location changes, so I can then draw a Polyline between them at a later date. I am not using firebase or a DBHelper. Just looking for a simple way to do it. This is the onLocationChanged function ``` @Override public void onLocationChanged(Location location) { LatLng myCoordinates = new LatLng(location.getLatitude(), location.getLongitude()); LocationMarker.setPosition(myCoordinates); mMap.moveCamera(CameraUpdateFactory.newLatLng(myCoordinates)); float zoomLevel = 12.0f; mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myCoordinates, zoomLevel)); ``` } This is my onCreate function ``` protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tracking); mOptions = new MarkerOptions().position(new LatLng(0, 0)).title("My Current Location") .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)); if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { checkLocationPermission(); } // Gets map fragment and allows map to display location SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(map); mapFragment.getMapAsync(this); } ``` Is it possible to store the lat and long into an array and use the array to plot the points? I've been trying to get my head around it but there isn't a definitive
2018/03/07
[ "https://Stackoverflow.com/questions/49152669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9385851/" ]
I get the feeling that the reasons the other answers may not be working for you is that you are looking for how to SET the config, as opposed to retrieving it. If you don't have it already, you'll need to install the Firebase CLI, as per the steps in <https://firebase.google.com/docs/cli/> . with it installed, you can set up your config like so: `firebase functions:config:set algolia.app_id="YOUR_APP_ID_HERE"` You can set multiple variables at once by just separating them with spaces like so: `firebase functions:config:set algolia.api_id="YOUR_API_ID_HERE" algolia.search_key="YOUR_SEARCH_KEY_HERE"` To check you have the right config in there, you can also run: `firebase functions:config:get` Which should print out, in JSON format, the current config you have set.
The config variables are created using the firebase cli. If you type `firebase --help` you will get an output which includes the following: ``` functions:config:clone [options] clone environment config from another project functions:config:get [path] fetch environment config stored at the given path functions:config:set [values...] set environment config with key=value syntax functions:config:unset [keys...] unset environment config at the specified path(s) ```
676,518
C#: In the keydown event of a textbox, how do you detect currently pressed modifiers + keys? I did the following, but I'm not too familiar with these operators so I'm not sure if and what I'm doing wrong. ``` private void txtShortcut_KeyDown(object sender, KeyEventArgs e) { if (e.Modifiers == (Keys.Alt || Keys.Control || Keys.Shift)) { lbLogger.Items.Add(e.Modifiers.ToString() + " + " + "show non-modifier key being pressed here"); } } ``` 1) How would I check if e contains any modifier keys?
2009/03/24
[ "https://Stackoverflow.com/questions/676518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
according to msdn [linkt](http://support.microsoft.com/kb/839201) ``` private void txtShortcut_KeyDown(object sender, KeyEventArgs e) { if (e.Alt || e.Control || e.Shift)) { lbLogger.Items.Add(e.ToString() + " + " + "show non-modifier key being pressed here"); } } ```
The [documentation](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.modifierkeys.aspx) says it is a bitwise combination, but you're doing a logical OR. Try: ``` if (e.Modifiers & (Keys.Alt | Keys.Control | Keys.Shift)) { lbLogger.Items.Add(e.Modifiers.ToString() + " + " + "show non-modifier key being pressed here"); } ``` And I think you can get the actual key with e.KeyCode.ToString().
3,003,349
The problem was this: radius is $2$, tangent to the $x$ axis, passes through $(1, -1)$. I don't know how to solve this, and my math teacher didnt teach this yet.
2018/11/18
[ "https://math.stackexchange.com/questions/3003349", "https://math.stackexchange.com", "https://math.stackexchange.com/users/617065/" ]
Given the conditions you gave, there is only two circle that works: their center is $\left(\begin{array}{cc} 1-\sqrt{3}\\ -2 \end{array}\right)$ and $\left(\begin{array}{cc} 1+\sqrt{3}\\ -2 \end{array}\right)$, their radius is $2$. So their respective equation are: $(x - 1+\sqrt{3})^2 + (y+2)^2 = 4$ and $(x-1-\sqrt{3})^2 + (y+2)^2 = 4$.
Since the circle is tangent to the x-axis and passes through $(1,-1)$ with radius $2$ we know the center is below the x-axis and $2$ units away from it. Thus the center is a point $ C(x,-2)$ which is $2$ unit apart from $(1,-1)$ That gives us $$(x-1)^2 + (-1)^2 =4$$ which implies $x=1\pm \sqrt 3 $ There are two circles with equations $$(x-1\pm \sqrt 3)^2 +(y+2)^2=4$$
56,854,614
[![enter image description here](https://i.stack.imgur.com/CGEth.png)](https://i.stack.imgur.com/CGEth.png)When I install redux-thunk it shows an error and you can see attached image for more info - npm ERR! Error: EPERM: operation not permitted, rename 'C:\Users\siddharth.vyas\Desktop\react-native\_Proj\AwesomeProject\node\_modules.staging\redux-thunk-069b38d0' -> 'C:\Users\siddharth.vyas\Desktop\react-native\_Proj\AwesomeProject\node\_modules\redux-thunk' And I have also try to install "redux-thunk" with the administrator but shows the same error. Pakage.json - "dependencies": { "axios": "^0.19.0", "react": "16.8.3", "react-native": "0.59.9", "react-native-loading-spinner-overlay": "^1.0.1", "react-redux": "^7.1.0", "redux": "^4.0.1", "redux-axios-middleware": "^4.0.0" }, "devDependencies": { "@babel/core": "7.4.5", "@babel/runtime": "7.4.5", "babel-jest": "24.8.0", "jest": "24.8.0", "metro-react-native-babel-preset": "0.54.1", "react-test-renderer": "16.8.3" },
2019/07/02
[ "https://Stackoverflow.com/questions/56854614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8039805/" ]
try removing node\_modules and do `npm install`. If it doesn't work, delete node\_modules, add "redux-thunk": "^2.3.0" to your dependencies, then run `npm install -i`
I have faced similar issues in windows. this looks more of a permission issue. Try running the cmd window in run as administrator mode. this should mostly give permission to npm to execute the script. if that does not work, then the option would be to delete the folder redux-thunk from node\_modules directory and try reinstalling the redux-thunk module again
67,719
I'm currently following a tutorial to rig a character. All goes well until I go to Pose Mode to see if my rig moves (I can do that before or after doing the automatic weight things, it changes nothing). [![Pose Mode](https://i.stack.imgur.com/3kqsV.png)](https://i.stack.imgur.com/3kqsV.png) What happens is most strange: I select a bone and press `G`. The usual box with the colour arrows appear, I try to grab and move one of them and it turns into a `><` like that. [![Cursor Change](https://i.stack.imgur.com/9h0im.png)](https://i.stack.imgur.com/9h0im.png) So far I've only seen that whilst scaling in edit mode and it does nothing, same with rotating. I verified I do not have any lock on location or rotation for the chosen bone or it's neighbours. I also dont have the `ctrl` + `.` or snap to center turned on, I checked all I could in the manual and here and found nothing. I've spent the afternoon on this and it's driving me nuts. I haven't found anywhere on the net anyone who talked about a dead scale `><` cursor dragging and replacing the wheel and grab and scale box. I am following the free rig the biker tutorial on Digital Tutors and so far so good, I checked everything. I'm nearing nervous breakdown.
2016/11/21
[ "https://blender.stackexchange.com/questions/67719", "https://blender.stackexchange.com", "https://blender.stackexchange.com/users/32816/" ]
Judging from your second screenshot, I'd suppose you've got `Manipulate Center Points` activated. While this is useful on multiple selected objects or bones, when bones are **not** connected, it leads to the behavior you describe in your Question. See the GIF below on how to deactivate this feature: [![Manipulate Center Points](https://i.stack.imgur.com/e5R3T.gif)](https://i.stack.imgur.com/e5R3T.gif) The purpose of this feature is to **Translate** objects by using **Rotate** or **Scale** functions. In your case, as the bone is already a child of another bone, Translation channels are automatically locked already. That's why nothing happens.
Try Alt , (Alt-comma) - worked for me. :) What this does is get you out of 'Manipulate Centre Point' mode: [![enter image description here](https://i.stack.imgur.com/HD086.png)](https://i.stack.imgur.com/HD086.png)
19,097,562
Which is a better approach to building a complex object (eager loading). A single call to a stored procedure that returns multiple result sets or multiple calls to stored procedures with one result set each? I'm building my DAL using T4/text templates in .NET so I'm leaning towards to latter. Thanks!
2013/09/30
[ "https://Stackoverflow.com/questions/19097562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/57106/" ]
For a pass to install, the following criteria have to be met: * The link must be https * The URL must return a valid `.pkpass` bundle * The `Content-Type` header must be `application/vnd.apple.pkpass` Unfortunately, these requirements are not yet documented, but they are mentioned in the WWDC session [What's new in Passbook](https://developer.apple.com/wwdc/videos/?id=302)
The URL contained in the QR code must return a valid PKPASS file and have the correct MIME type in the HTTP response. Does that help?
10,617,363
I have ``` SharedPreferences myPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); ``` and ``` myPreferences.getBoolean("checkbox", true) ``` So, how can my main activity know when user change preferences state? For example if user don't wont to get notifications any more. Thanks.
2012/05/16
[ "https://Stackoverflow.com/questions/10617363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1159613/" ]
You could either re-read all the preferences in `Activity.onResume()`, or as long as your main activity launches the preferences activity (e.g. from a menu), you could launch with `startActivityForResult(Intent, int)` and re-read all the preferences in `onActivityResult(int, int, Intent)`. I have also found it sufficient to re-check each relevant preference before starting the appropriate behavior (i.e. before issuing the `Notification` for your example).
You can create a static boolean that is changed whenever a preference is changed, or when your preference activity is started. The purpose of this boolean is to let your main activity know the preferences are dirty and need to be reloaded. They should be reloaded `onResume` if the `mDirty` flag is true. Another option is to just reload all the preferences `onResume`, regardless. This may not be as efficient, but if you don't have loads of preferences, it's fine. The most efficient way would be to set onPreferenceChanged listeners for all your prefs in your prefs activity, the prefs then notify the activity only when they actually change. This solves the case when your user enters your prefs activity, but doesn't actually change anything.
10,617,363
I have ``` SharedPreferences myPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); ``` and ``` myPreferences.getBoolean("checkbox", true) ``` So, how can my main activity know when user change preferences state? For example if user don't wont to get notifications any more. Thanks.
2012/05/16
[ "https://Stackoverflow.com/questions/10617363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1159613/" ]
You need to implement the onSharedPreferenceChangeListener interface. Then register to receive change updates in your onCreate/onStart: ``` myPreferences.registerOnSharedPreferenceChangeListener(); ``` In your listener you do something like this: ``` @Override public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { if (key.equals("MyKey")) { // Do something. } else if (key.equals("MyOtherKey")) { // Do something else. } } ``` Remember to remove the listener in onStop/onDestroy.
You can create a static boolean that is changed whenever a preference is changed, or when your preference activity is started. The purpose of this boolean is to let your main activity know the preferences are dirty and need to be reloaded. They should be reloaded `onResume` if the `mDirty` flag is true. Another option is to just reload all the preferences `onResume`, regardless. This may not be as efficient, but if you don't have loads of preferences, it's fine. The most efficient way would be to set onPreferenceChanged listeners for all your prefs in your prefs activity, the prefs then notify the activity only when they actually change. This solves the case when your user enters your prefs activity, but doesn't actually change anything.
41,063,941
I am writing a Rule Engine based on ANTLR 4 for C# (I am using the [Sam Harwell alternative](https://github.com/tunnelvisionlabs/antlr4cs)) but I can't get my grammar correctly parsing my inputs about two rules very similar. There are probably several others mistakes, but I am stuck with this one for the moment. Also, I am new to ANTLR (except my old days in school ^^), so do not hesitate to give me some tips/explanations :). My goal are to interprete binary and numeric assignments such as: * `Fact := Fact1 OR Fact2` Behind the scene I want it to match the `bin_assign` rule. * `Fact := 8 * 4` Behind the scene I want it to match the `num_assign` rule. But my parser always matchs `num_assign` and failed matching the operator (because it is expecting a NUM\_OP or a EOF). You will see that those two rules start the same way with the FACT token. But my intuition tells me it is not the cause of the issue (as I say, I'm new to ANTLR, it is just my intuition). I wrote those two rules to avoid `Fact := 1 + true` being a right statment. Here are my grammars: 1. Common lexer rules: ``` lexer grammar Common; /* * Lexer Rules */ FACT: [a-zA-Z](([a-zA-Z0-9] | '.' | '_')*[a-zA-Z0-9])?; ASSIGN: ':='; LITERAL: '\'' .*? '\'' | '"' .*? '"'; WS : [ \t\r\n]+ -> skip; ``` 2. Numeric grammar: ``` grammar NumericGrammar; import Common; /* * Parser Rules */ num_stat: num_stat NUM_OP num_stat # ArithmeticStat | '(' num_stat ')' # ArithmeticBrakedStat | DIGIT # DigitStat | FACT # ArithmeticFactStat ; num_assign: FACT NUM_ASSIGN num_stat # ArithmeticAssign ; /* * Lexer Rules */ DIGIT: INT | FLOAT; INT: ([1-9][0-9]*)?[0-9]; FLOAT: INT(','|'.')[0-9]+; NUM_OP: MULT | DIV | ADD | SUB; MULT: '*'; DIV: '/'; ADD: '+'; SUB: '-'; NUM_ASSIGN: MULT_ASSIGN | DIV_ASSIGN | ADD_ASSIGN | SUB_ASSIGN | ASSIGN; MULT_ASSIGN: '*='; DIV_ASSIGN: '\\='; ADD_ASSIGN: '+='; SUB_ASSIGN: '-='; ``` 3. Binary grammar : ``` grammar BinaryGrammar; import NumericGrammar; /* * Parser Rules */ bin_stat: bin_stat BIN_OP bin_stat # BinaryStat | '(' bin_stat ')' # BinaryBrakedStat | NOT bin_stat # NegateStat | num_stat COMPARE_OP num_stat # CompareStat | FACT EQUALITY_OP (LITERAL | DIGIT) # LiteralComparisonStat | num_stat IN SET # IntervalComparisonStat | BOOL # BoolStat | FACT # BinaryFactStat ; bin_assign: FACT ASSIGN bin_stat # BinAssign ; /* * Lexer Rules */ BOOL: TRUE | FALSE; TRUE: '1' | 'true' | 'True' | 'YES' | 'Yes' | 'yes'; FALSE: '0' | 'false' | 'False' | 'NO' | 'No' | 'no'; BIN_OP: AND | OR | EQUALITY_OP; COMPARE_OP: EQUALITY_OP | GT | GTE | LT | LTE; AND: 'AND' | 'And' | 'and' | '&' | '&&'; OR: 'OR' | 'Or' | 'or' | '|' | '||'; EQUALITY_OP: EQUALITY | UNEQUALITY; EQUALITY: '=' | '=='; UNEQUALITY: '<>' | '!=' | '=/=' | '=\\='; GT: '>'; GTE: '>='; LT: '<'; LTE: '<='; NOT: '!' | 'NOT' | 'not'; IN: 'IN' | 'in'; SET: ('[' | ']') (INT | FLOAT) ';' (INT | FLOAT) ('[' | ']'); ``` 4. Final grammar: ``` grammar Test; import BinaryGrammar; /* * Parser Rules */ r: (IF bin_stat THEN)? assign EOF; assign: bin_assign | num_assign; /* * Lexer Rules */ IF: 'if' | 'IF' | 'If'; THEN: 'then' | 'THEN' | 'Then'; ``` Here a screenshot of the execution if needed:[![bad matching](https://i.stack.imgur.com/dPdX7.png)](https://i.stack.imgur.com/dPdX7.png)
2016/12/09
[ "https://Stackoverflow.com/questions/41063941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2183236/" ]
Using inconsistent naming of tokens makes analysis of the rules harder for you (parser/lexer won't mind). So it is just suggestion for easier (manual) reading the rules -- when I read my grammar, when I see two rules with different tokens all in caps (terminal) I know for sure they are different at that point. In your case you have to check that token if it is really terminal and if not, how it can unfold.
The `FACT` lexer rule will not match `Fact1` ``` FACT: [a-zA-Z](([a-zA-Z0-9] | '.' | '_')*[a-zA-Z0-9])?; ``` The kleene star in the middle is nominally a greedy operator. So, all terminal numbers will be captured, leaving nothing to complete the rule. Just make it non-greedy: ``` FACT: [a-zA-Z](([a-zA-Z0-9] | '.' | '_')*?[a-zA-Z0-9])?; ```
7,244,836
I have tabbar application, in first tab I have a webView, so when user open the website and going to download some song mp3 format, it push another View which takes the title from the user. after giving the title I just change the tabbarSelectController to one title for song and the downloading begins and shown on the tabbar at selected Index 1. when i change the tab to selected Index 0 and select another song for downloading and again back to selectedIndex 1 first downloading stop and 2nd downloading resume. so i want to download multiple songs and don't have much idea how to do that in this scenario because user add songs dynamically I have seen ASINtworkQueue as well but don't get the idea of how that works
2011/08/30
[ "https://Stackoverflow.com/questions/7244836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/868703/" ]
You may start using: m2e ( maven to eclipse integration ) -> <http://www.eclipse.org/m2e/> Eclipse WTP ( web tools platform ) -> <http://www.eclipse.org/webtools/> WTP will allow you to run Tomcat from eclipse and m2e will take care of converting your Maven build into Eclipse project and integrating it with WTP.
If you are using `eclipse` then you need not to use `mvn -o compile war:exploded` every time. But yes, you need to use `mvn install` each time you make a change in your application. This is what you need to do: * Open `Server View` * Open expected tomcat server settings. A settings window for tomcat will be opened. * Select modules tab. * Choose `Add external web module`. An input form will be opened. * Browse to your application's `target` (generated by maven) folder and then select already exploded war directory and set it as `Document Base` * Enter `Path` as the base url for your application. This is just one time effort.
21,420,252
I have a live video stream from FFMpeg, and I am having a hard time viewing the stream using my own custom Java application. Before someone tells me to use VLC or something like that I do want to use my own application. The stream I am trying to read is a H.264 encoded Mpeg-ts stream streamed over UDP. I do know how to decode the H.264 frames, but I am simply wondering about how to receive the Mpeg-ts stream.
2014/01/29
[ "https://Stackoverflow.com/questions/21420252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1618141/" ]
Try this on: `d = collections.OrderedDict({ i:'*'*i for i in range(8) })` **EDIT** `pprint.pprint(list(d.items()))`
If you are specifically targeting CPython\* 3.6 or later, then you can [just use regular dictionaries](https://docs.python.org/3.6/whatsnew/3.6.html#whatsnew36-compactdict) instead of `OrderedDict`. You'll miss out on a few [methods exclusive to `OrderedDict`](https://docs.python.org/3.6/library/collections.html#collections.OrderedDict), and this is not (yet) guaranteed to be portable to other Python implementations,\*\* but it is probably the simplest way to accomplish what you are trying to do. \* CPython is the reference implementation of Python which may be downloaded from python.org. \*\* CPython [stole this idea from PyPy](https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html), so you can probably depend on it working there too.
21,420,252
I have a live video stream from FFMpeg, and I am having a hard time viewing the stream using my own custom Java application. Before someone tells me to use VLC or something like that I do want to use my own application. The stream I am trying to read is a H.264 encoded Mpeg-ts stream streamed over UDP. I do know how to decode the H.264 frames, but I am simply wondering about how to receive the Mpeg-ts stream.
2014/01/29
[ "https://Stackoverflow.com/questions/21420252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1618141/" ]
Try this on: `d = collections.OrderedDict({ i:'*'*i for i in range(8) })` **EDIT** `pprint.pprint(list(d.items()))`
I realize this is sort of necroposting, but I thought I'd post what I use. Its main virtue is that its aoutput can be read back into python, thus allowing, for instance, to shutlle between representations (which I use, for instance, on JSON files). Of course it breaks pprint encapsulation, by ripping some code off its inner \_format function. ``` #!/bin/env python from __future__ import print_function import pprint; from collections import OrderedDict import json import sys class MyPP (pprint.PrettyPrinter): def _format(self, object, stream, indent, allowance, context, level): if not isinstance(object, OrderedDict) : return pprint.PrettyPrinter._format(self, object, stream, indent, allowance, context, level) level = level + 1 objid = id(object) if objid in context: stream.write(_recursion(object)) self._recursive = True self._readable = False return write = stream.write _len=len rep = self._repr(object, context, level - 1) typ = type(object) sepLines = _len(rep) > (self._width - 1 - indent - allowance) if self._depth and level > self._depth: write(rep) return write('OrderedDict([\n%s'%(' '*(indent+1),)) if self._indent_per_level > 1: write((self._indent_per_level - 1) * ' ') length = _len(object) #import pdb; pdb.set_trace() if length: context[objid] = 1 indent = indent + self._indent_per_level items = object.items() key, ent = items[0] rep = self._repr(key, context, level) write('( ') write(rep) write(', ') self._format(ent, stream, indent + _len(rep) + 2, allowance + 1, context, level) write(' )') if length > 1: for key, ent in items[1:]: rep = self._repr(key, context, level) if sepLines: write(',\n%s( %s , ' % (' '*indent, rep)) else: write(', ( %s , ' % rep) self._format(ent, stream, indent + _len(rep) + 2, allowance + 1, context, level) write(' )') indent = indent - self._indent_per_level del context[objid] write('])') return pp = MyPP(indent=1) handle=open(sys.argv[1],"r") values=json.loads(handle.read(),object_pairs_hook=OrderedDict) pp.pprint(values) ```
21,420,252
I have a live video stream from FFMpeg, and I am having a hard time viewing the stream using my own custom Java application. Before someone tells me to use VLC or something like that I do want to use my own application. The stream I am trying to read is a H.264 encoded Mpeg-ts stream streamed over UDP. I do know how to decode the H.264 frames, but I am simply wondering about how to receive the Mpeg-ts stream.
2014/01/29
[ "https://Stackoverflow.com/questions/21420252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1618141/" ]
I found a relatively simple solution for this, but it includes the risk of making the output for your ordered dictionary appear exactly as if it were a regular `dict` object. The original solution for using a context manager to prevent `pprint` from sorting dictionary keys comes from [this answer](https://stackoverflow.com/a/25688431/3637954). ``` @contextlib.contextmanager def pprint_OrderedDict(): pp_orig = pprint._sorted od_orig = OrderedDict.__repr__ try: pprint._sorted = lambda x:x OrderedDict.__repr__ = dict.__repr__ yield finally: pprint._sorted = pp_orig OrderedDict.__repr__ = od_orig ``` (You could also just patch the `OrderedDict.__repr__` method with `dict.__repr__`, but please don't.) Example: ``` >>> foo = [('Roger', 'Owner'), ('Diane', 'Manager'), ('Bob', 'Manager'), ... ('Ian', 'Associate'), ('Bill', 'Associate'), ('Melinda', 'Associate')] >>> d = OrderedDict(foo) >>> pprint.pprint(d) OrderedDict([('Roger', 'Owner'), ('Diane', 'Manager'), ('Bob', 'Manager'), ('Ian', 'Associate'), ('Bill', 'Associate'), ('Melinda', 'Associate')]) >>> pprint.pprint(dict(d)) {'Bill': 'Associate', 'Bob': 'Manager', 'Diane': 'Manager', 'Ian': 'Associate', 'Melinda': 'Associate', 'Roger': 'Owner'} >>> with pprint_OrderedDict(): ... pprint.pprint(d) ... {'Roger': 'Owner', 'Diane': 'Manager', 'Bob': 'Manager', 'Ian': 'Associate', 'Bill': 'Associate', 'Melinda': 'Associate'} ```
If you are specifically targeting CPython\* 3.6 or later, then you can [just use regular dictionaries](https://docs.python.org/3.6/whatsnew/3.6.html#whatsnew36-compactdict) instead of `OrderedDict`. You'll miss out on a few [methods exclusive to `OrderedDict`](https://docs.python.org/3.6/library/collections.html#collections.OrderedDict), and this is not (yet) guaranteed to be portable to other Python implementations,\*\* but it is probably the simplest way to accomplish what you are trying to do. \* CPython is the reference implementation of Python which may be downloaded from python.org. \*\* CPython [stole this idea from PyPy](https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html), so you can probably depend on it working there too.
21,420,252
I have a live video stream from FFMpeg, and I am having a hard time viewing the stream using my own custom Java application. Before someone tells me to use VLC or something like that I do want to use my own application. The stream I am trying to read is a H.264 encoded Mpeg-ts stream streamed over UDP. I do know how to decode the H.264 frames, but I am simply wondering about how to receive the Mpeg-ts stream.
2014/01/29
[ "https://Stackoverflow.com/questions/21420252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1618141/" ]
I found a relatively simple solution for this, but it includes the risk of making the output for your ordered dictionary appear exactly as if it were a regular `dict` object. The original solution for using a context manager to prevent `pprint` from sorting dictionary keys comes from [this answer](https://stackoverflow.com/a/25688431/3637954). ``` @contextlib.contextmanager def pprint_OrderedDict(): pp_orig = pprint._sorted od_orig = OrderedDict.__repr__ try: pprint._sorted = lambda x:x OrderedDict.__repr__ = dict.__repr__ yield finally: pprint._sorted = pp_orig OrderedDict.__repr__ = od_orig ``` (You could also just patch the `OrderedDict.__repr__` method with `dict.__repr__`, but please don't.) Example: ``` >>> foo = [('Roger', 'Owner'), ('Diane', 'Manager'), ('Bob', 'Manager'), ... ('Ian', 'Associate'), ('Bill', 'Associate'), ('Melinda', 'Associate')] >>> d = OrderedDict(foo) >>> pprint.pprint(d) OrderedDict([('Roger', 'Owner'), ('Diane', 'Manager'), ('Bob', 'Manager'), ('Ian', 'Associate'), ('Bill', 'Associate'), ('Melinda', 'Associate')]) >>> pprint.pprint(dict(d)) {'Bill': 'Associate', 'Bob': 'Manager', 'Diane': 'Manager', 'Ian': 'Associate', 'Melinda': 'Associate', 'Roger': 'Owner'} >>> with pprint_OrderedDict(): ... pprint.pprint(d) ... {'Roger': 'Owner', 'Diane': 'Manager', 'Bob': 'Manager', 'Ian': 'Associate', 'Bill': 'Associate', 'Melinda': 'Associate'} ```
I realize this is sort of necroposting, but I thought I'd post what I use. Its main virtue is that its aoutput can be read back into python, thus allowing, for instance, to shutlle between representations (which I use, for instance, on JSON files). Of course it breaks pprint encapsulation, by ripping some code off its inner \_format function. ``` #!/bin/env python from __future__ import print_function import pprint; from collections import OrderedDict import json import sys class MyPP (pprint.PrettyPrinter): def _format(self, object, stream, indent, allowance, context, level): if not isinstance(object, OrderedDict) : return pprint.PrettyPrinter._format(self, object, stream, indent, allowance, context, level) level = level + 1 objid = id(object) if objid in context: stream.write(_recursion(object)) self._recursive = True self._readable = False return write = stream.write _len=len rep = self._repr(object, context, level - 1) typ = type(object) sepLines = _len(rep) > (self._width - 1 - indent - allowance) if self._depth and level > self._depth: write(rep) return write('OrderedDict([\n%s'%(' '*(indent+1),)) if self._indent_per_level > 1: write((self._indent_per_level - 1) * ' ') length = _len(object) #import pdb; pdb.set_trace() if length: context[objid] = 1 indent = indent + self._indent_per_level items = object.items() key, ent = items[0] rep = self._repr(key, context, level) write('( ') write(rep) write(', ') self._format(ent, stream, indent + _len(rep) + 2, allowance + 1, context, level) write(' )') if length > 1: for key, ent in items[1:]: rep = self._repr(key, context, level) if sepLines: write(',\n%s( %s , ' % (' '*indent, rep)) else: write(', ( %s , ' % rep) self._format(ent, stream, indent + _len(rep) + 2, allowance + 1, context, level) write(' )') indent = indent - self._indent_per_level del context[objid] write('])') return pp = MyPP(indent=1) handle=open(sys.argv[1],"r") values=json.loads(handle.read(),object_pairs_hook=OrderedDict) pp.pprint(values) ```
21,420,252
I have a live video stream from FFMpeg, and I am having a hard time viewing the stream using my own custom Java application. Before someone tells me to use VLC or something like that I do want to use my own application. The stream I am trying to read is a H.264 encoded Mpeg-ts stream streamed over UDP. I do know how to decode the H.264 frames, but I am simply wondering about how to receive the Mpeg-ts stream.
2014/01/29
[ "https://Stackoverflow.com/questions/21420252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1618141/" ]
If you are specifically targeting CPython\* 3.6 or later, then you can [just use regular dictionaries](https://docs.python.org/3.6/whatsnew/3.6.html#whatsnew36-compactdict) instead of `OrderedDict`. You'll miss out on a few [methods exclusive to `OrderedDict`](https://docs.python.org/3.6/library/collections.html#collections.OrderedDict), and this is not (yet) guaranteed to be portable to other Python implementations,\*\* but it is probably the simplest way to accomplish what you are trying to do. \* CPython is the reference implementation of Python which may be downloaded from python.org. \*\* CPython [stole this idea from PyPy](https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html), so you can probably depend on it working there too.
I realize this is sort of necroposting, but I thought I'd post what I use. Its main virtue is that its aoutput can be read back into python, thus allowing, for instance, to shutlle between representations (which I use, for instance, on JSON files). Of course it breaks pprint encapsulation, by ripping some code off its inner \_format function. ``` #!/bin/env python from __future__ import print_function import pprint; from collections import OrderedDict import json import sys class MyPP (pprint.PrettyPrinter): def _format(self, object, stream, indent, allowance, context, level): if not isinstance(object, OrderedDict) : return pprint.PrettyPrinter._format(self, object, stream, indent, allowance, context, level) level = level + 1 objid = id(object) if objid in context: stream.write(_recursion(object)) self._recursive = True self._readable = False return write = stream.write _len=len rep = self._repr(object, context, level - 1) typ = type(object) sepLines = _len(rep) > (self._width - 1 - indent - allowance) if self._depth and level > self._depth: write(rep) return write('OrderedDict([\n%s'%(' '*(indent+1),)) if self._indent_per_level > 1: write((self._indent_per_level - 1) * ' ') length = _len(object) #import pdb; pdb.set_trace() if length: context[objid] = 1 indent = indent + self._indent_per_level items = object.items() key, ent = items[0] rep = self._repr(key, context, level) write('( ') write(rep) write(', ') self._format(ent, stream, indent + _len(rep) + 2, allowance + 1, context, level) write(' )') if length > 1: for key, ent in items[1:]: rep = self._repr(key, context, level) if sepLines: write(',\n%s( %s , ' % (' '*indent, rep)) else: write(', ( %s , ' % rep) self._format(ent, stream, indent + _len(rep) + 2, allowance + 1, context, level) write(' )') indent = indent - self._indent_per_level del context[objid] write('])') return pp = MyPP(indent=1) handle=open(sys.argv[1],"r") values=json.loads(handle.read(),object_pairs_hook=OrderedDict) pp.pprint(values) ```