date
stringlengths
10
10
nb_tokens
int64
60
629k
text_size
int64
234
1.02M
content
stringlengths
234
1.02M
2018/03/15
654
2,154
<issue_start>username_0: I have multiple tables named like so MOM2016, MOM2017, MOM2018. When i run query in phpmyadmin ``` SHOW TABLES LIKE 'MOM%' ``` it returns 3 items as expected. BUT!!!! When i run in php, my code seem to give me only 1 item in the array (first one only MOM2016). ``` $sql = "SHOW TABLES LIKE 'MOM%'"; $result = $conn->query($sql); $dbArray = $result->fetch_assoc(); echo "DEBUG:".count($dbArray); ``` This give: > > DEBUG:1 > > > My php code is wrong? Pls help.<issue_comment>username_1: I think all you need to do is give link text in uppercase but this link is dynamic as the banner auto-slides to the next one. You should come up with another locator to click on exactly the locator you want to click. Otherwise you might get `ElementNotVisibleException` if the banner is changed. ``` banner_tell=driver.find_element_by_link_text('TELL ME MORE') ``` Upvotes: 1 <issue_comment>username_2: try with xpath ``` banner_tell= driver.find_element_by_xpath("//*[contains(text(),'TELL ME MORE')]") ``` Upvotes: 0 <issue_comment>username_3: Seems you were almost near however the `function()` should have been : ``` find_element_by_link_text() ``` To click on the button with text as **TELL ME MORE** you have to induce [WebDriverWait](https://seleniumhq.github.io/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.wait.html#module-selenium.webdriver.support.wait) with [expected\_conditions](https://seleniumhq.github.io/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.expected_conditions.html#module-selenium.webdriver.support.expected_conditions) clause [`element_to_be_clickable`](https://seleniumhq.github.io/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.expected_conditions.html#selenium.webdriver.support.expected_conditions.element_to_be_clickable) as follows : ``` from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.LINK_TEXT, "TELL ME MORE"))).click() ``` Upvotes: 0
2018/03/15
508
1,709
<issue_start>username_0: Question is quite simple, how do I print a deque, but from behind. Example: I have a deque with elements {5,4,3,2,1}. I want to print that deque, but starting from the last element, so I should have someting like 1 2 3 4 5 on my screen. Usual `for(int i(deque.size()); i > 0; i--)` loop obviously won't work. Little intro to the program. It finds numbers whose sum is even or odd, and sorts them into two different deques that are to be printed on screen. This is the code that works for 'usual' printing. But my task says to print them backwards. Oh, and the elements are added to the deque using push\_front function. And no, I'm not allowed to use push\_back to 'fix' it. ``` void PrintDek(Dek v4) { for (int i(0); i < v4.size(); i++) { std::cout << v4[i]; if (i != v4.size() - 1) std::cout << ","; } } ``` If some of you feel the need for the whole program's code, I'll edit my post.<issue_comment>username_1: You can use [reverse iterators](http://en.cppreference.com/w/cpp/iterator/reverse_iterator). See <http://en.cppreference.com/w/cpp/container/deque/rbegin>. ``` for(auto iter = deque.rbegin(); iter != deque.rend(); ++iter) { // do stuff } ``` Upvotes: 2 <issue_comment>username_2: So after seeing my code after a good few hours of sleep (this question was posted after 2AM according to my timezone), I've come to realize what my mistake was. By using `deque.size()` and moving all the way up to the value that the `size()` function returns, I was actually going out of range, accessing forbidden parts of memory. Simple `deque.size()-1` now works. So the loop would look like this `for(int i(deque.size()-1); i >= 0; i--)`. Upvotes: 3 [selected_answer]
2018/03/15
1,516
6,067
<issue_start>username_0: I'm wondering if is it possible to make the "property name" dynamic in the filter expressions Consider scenario ``` List GetPerson(int countryID, int stateID, int cityID, int zip) { //List of person can be filtered based on below line of code List filteredPersons= persons.FindAll(rule => rule.CountryID == countryID).ToList(); //is it possible to specify ".Country" dynamically. something like List filteredPersons= persons.FindAll(rule => rule."propertyName"== countryID).ToList(); } ```<issue_comment>username_1: Search for **System.Linq.Dynamic** in NuGet. That's the easiest way to start with Dynamic Linq. Upvotes: 0 <issue_comment>username_2: Considering your example one method you could employ is using the `.Where()` extension instead of `FindAll()` this could then allow you to build your expression manually. A quick example would be as below. ``` static List GetPerson(int countryID, int stateID, int cityID, int zip) { //create a new expression for the type of person this. var paramExpr = Expression.Parameter(typeof(Person)); //next we create a property expression based on the property named "CountryID" (this is case sensitive) var property = Expression.Property(paramExpr, "CountryID"); //next we create a constant express based on the country id passed in. var constant = Expression.Constant(countryID); //next we create an "Equals" express where property equals containt. ie. ".CountryId" = 1 var idEqualsExpr = Expression.Equal(property, constant); //next we convert the expression into a lamba expression var lExpr = Expression.Lambda>(idEqualsExpr, paramExpr); //finally we query our dataset return persons.AsQueryable().Where(lExpr).ToList(); } ``` So this looks like alot of code but what we have basically done is manually constructed the expression tree with the end result looking similar to (and functioning as) `return persons.AsQueryable().Where(p => p.CountryId = countryId);` Now we can take this forward lets say you wanted to query for multiple properties using an and\or based on the method call. Ie you could change all your "filter" paramters to be Nullable and check if a value is passed in we filter for it such as. ``` static List GetPerson(int? countryID = null, int? stateID = null, int? cityID = null, int? zip = null) { //create a new expression for the type of person this. var paramExpr = Expression.Parameter(typeof(Person)); //var equalExpression = Expression.Empty(); BinaryExpression equalExpression = null; if (countryID.HasValue) { var e = BuildExpression(paramExpr, "CountryId", countryID.Value); if (equalExpression == null) equalExpression = e; else equalExpression = Expression.And(equalExpression, e); } if (stateID.HasValue) { var e = BuildExpression(paramExpr, "StateID", stateID.Value); if (equalExpression == null) equalExpression = e; else equalExpression = Expression.And(equalExpression, e); } if (equalExpression == null) { return new List(); } //next we convert the expression into a lamba expression var lExpr = Expression.Lambda>(equalExpression, paramExpr); //finally we query our dataset return persons.AsQueryable().Where(lExpr).ToList(); } static BinaryExpression BuildExpression(Expression expression, string propertyName, object value) { //next we create a property expression based on the property named "CountryID" (this is case sensitive) var property = Expression.Property(expression, propertyName); //next we create a constant express based on the country id passed in. var constant = Expression.Constant(value); //next we create an "Equals" express where property equals containt. ie. ".CountryId" = 1 return Expression.Equal(property, constant); } ``` Now this is a bit more code but as you can see we are now accepting `null` values for all our parameters and building our query for additional properties. Now you could take this further (as assuming a more generic method is required) of passing in a `Dictionary` of the properties \ values to query. This can be done as an extension method on an `IEnumerable` as listed below. ``` public static class LinqExtensions { public static IEnumerable CustomParameterQuery(this IEnumerable entities, Dictionary queryVars) { if (entities.Count() == 0 || queryVars.Count == 0) { return entities; } //create a new expression for the type of person this. var paramExpr = Expression.Parameter(typeof(T)); BinaryExpression equalExpression = null; foreach (var kvp in queryVars) { var e = BuildExpression(paramExpr, kvp.Key, kvp.Value); if (equalExpression == null) equalExpression = e; else equalExpression = Expression.And(equalExpression, e); } if (equalExpression == null) { return new T[0]; } //next we convert the expression into a lamba expression var lExpr = Expression.Lambda>(equalExpression, paramExpr); //finally we query our dataset return entities.AsQueryable().Where(lExpr); } static BinaryExpression BuildExpression(Expression expression, string propertyName, object value) { //next we create a property expression based on the property name var property = Expression.Property(expression, propertyName); //next we create a constant express based on the country id passed in. var constant = Expression.Constant(value); //next we create an "Equals" express where property equals containt. ie. ".CountryId" = 1 return Expression.Equal(property, constant); } } ``` Now this could be easily called as: ``` var dict = new Dictionary { { "CountryID", 1 }, { "StateID", 2 } }; var e = persons.CustomParameterQuery(dict); ``` Now obiously this is not a perfect example, but should get you moving in the right direction. Now you "could" also support "OR" statements etc by using `Expression.Or` instead of `Expression.And` when combining expressions. **I Must add this is very error prone as it requires the Property names to be exact to the entity, you could use reflection on `T` and determine if the PropertyName exists and If it is in the correct casing.** Upvotes: 3 [selected_answer]
2018/03/15
1,715
6,904
<issue_start>username_0: I'm having issues with a triple nested IF statement. I have a form which has a question with two radio buttons, this question is not always visible. I want to capture the selection made, but as default the radio buttons aren't selected and are still visible in the source code but use CSS display:none to hide. Therefore I need to specify that the data for the selection is only sent (console log for testing) IF a selection is made. The logic should be, if div is visible, check if Q3\_1 selected, if true, send Yes, if false, check if Q3\_0 selected, if true, send False, if not selected don't send. I think it'd be better to have the logic as below, but I couldn't get this to work either. If div visible and Q3\_1 selected send Yes else If div visible and Q3\_0 selected send No Many thanks in advance. ``` $(function () { // Handler for .ready() called. if ($("[id^=divWantMedical]").is(":visible")) { if (document.querySelector("[id$='PreexistingConditions.Question3_1']").checked == true){ console.log("Send Yes"); } else { if ((document.querySelector("[id$='PreexistingConditions.Question3_0']").checked == true){ console.log("Send No"); } else { console.log("Don't send anything"); } } } }); ```<issue_comment>username_1: Search for **System.Linq.Dynamic** in NuGet. That's the easiest way to start with Dynamic Linq. Upvotes: 0 <issue_comment>username_2: Considering your example one method you could employ is using the `.Where()` extension instead of `FindAll()` this could then allow you to build your expression manually. A quick example would be as below. ``` static List GetPerson(int countryID, int stateID, int cityID, int zip) { //create a new expression for the type of person this. var paramExpr = Expression.Parameter(typeof(Person)); //next we create a property expression based on the property named "CountryID" (this is case sensitive) var property = Expression.Property(paramExpr, "CountryID"); //next we create a constant express based on the country id passed in. var constant = Expression.Constant(countryID); //next we create an "Equals" express where property equals containt. ie. ".CountryId" = 1 var idEqualsExpr = Expression.Equal(property, constant); //next we convert the expression into a lamba expression var lExpr = Expression.Lambda>(idEqualsExpr, paramExpr); //finally we query our dataset return persons.AsQueryable().Where(lExpr).ToList(); } ``` So this looks like alot of code but what we have basically done is manually constructed the expression tree with the end result looking similar to (and functioning as) `return persons.AsQueryable().Where(p => p.CountryId = countryId);` Now we can take this forward lets say you wanted to query for multiple properties using an and\or based on the method call. Ie you could change all your "filter" paramters to be Nullable and check if a value is passed in we filter for it such as. ``` static List GetPerson(int? countryID = null, int? stateID = null, int? cityID = null, int? zip = null) { //create a new expression for the type of person this. var paramExpr = Expression.Parameter(typeof(Person)); //var equalExpression = Expression.Empty(); BinaryExpression equalExpression = null; if (countryID.HasValue) { var e = BuildExpression(paramExpr, "CountryId", countryID.Value); if (equalExpression == null) equalExpression = e; else equalExpression = Expression.And(equalExpression, e); } if (stateID.HasValue) { var e = BuildExpression(paramExpr, "StateID", stateID.Value); if (equalExpression == null) equalExpression = e; else equalExpression = Expression.And(equalExpression, e); } if (equalExpression == null) { return new List(); } //next we convert the expression into a lamba expression var lExpr = Expression.Lambda>(equalExpression, paramExpr); //finally we query our dataset return persons.AsQueryable().Where(lExpr).ToList(); } static BinaryExpression BuildExpression(Expression expression, string propertyName, object value) { //next we create a property expression based on the property named "CountryID" (this is case sensitive) var property = Expression.Property(expression, propertyName); //next we create a constant express based on the country id passed in. var constant = Expression.Constant(value); //next we create an "Equals" express where property equals containt. ie. ".CountryId" = 1 return Expression.Equal(property, constant); } ``` Now this is a bit more code but as you can see we are now accepting `null` values for all our parameters and building our query for additional properties. Now you could take this further (as assuming a more generic method is required) of passing in a `Dictionary` of the properties \ values to query. This can be done as an extension method on an `IEnumerable` as listed below. ``` public static class LinqExtensions { public static IEnumerable CustomParameterQuery(this IEnumerable entities, Dictionary queryVars) { if (entities.Count() == 0 || queryVars.Count == 0) { return entities; } //create a new expression for the type of person this. var paramExpr = Expression.Parameter(typeof(T)); BinaryExpression equalExpression = null; foreach (var kvp in queryVars) { var e = BuildExpression(paramExpr, kvp.Key, kvp.Value); if (equalExpression == null) equalExpression = e; else equalExpression = Expression.And(equalExpression, e); } if (equalExpression == null) { return new T[0]; } //next we convert the expression into a lamba expression var lExpr = Expression.Lambda>(equalExpression, paramExpr); //finally we query our dataset return entities.AsQueryable().Where(lExpr); } static BinaryExpression BuildExpression(Expression expression, string propertyName, object value) { //next we create a property expression based on the property name var property = Expression.Property(expression, propertyName); //next we create a constant express based on the country id passed in. var constant = Expression.Constant(value); //next we create an "Equals" express where property equals containt. ie. ".CountryId" = 1 return Expression.Equal(property, constant); } } ``` Now this could be easily called as: ``` var dict = new Dictionary { { "CountryID", 1 }, { "StateID", 2 } }; var e = persons.CustomParameterQuery(dict); ``` Now obiously this is not a perfect example, but should get you moving in the right direction. Now you "could" also support "OR" statements etc by using `Expression.Or` instead of `Expression.And` when combining expressions. **I Must add this is very error prone as it requires the Property names to be exact to the entity, you could use reflection on `T` and determine if the PropertyName exists and If it is in the correct casing.** Upvotes: 3 [selected_answer]
2018/03/15
1,242
4,052
<issue_start>username_0: I'm trying to implement basic ajax. I've been following [this tutorial](https://pippinsplugins.com/using-ajax-your-plugin-wordpress-admin/). My JS fires when I click the button but I get a `400` from the ajax url: `POST http://localhost:8080/wp-admin/admin-ajax.php 400 (Bad Request)` As far as I can tell, I haven't strayed far from the tutorial code. Her is my JS: ``` jQuery(document).ready(function($){ $('#baa_form').submit(function(){ var data = { action: 'baa_response' } $.post(ajaxurl, data, function(response){ alert('Hello'); }); return false; }); }); ``` PHP: ``` php function baa_add_menu() { global $baa_settings_page; $baa_settings_page = add_menu_page( 'Basic Admin Ajax', 'Basic Admin Ajax', 'edit_pages', 'basic-admin-ajax', 'baa_render_settings_page', false, 62.1 ); } function baa_load_scripts( $hook ) { global $baa_settings_page; if ( $hook !== $baa_settings_page ) { return; } $path = plugin_dir_url( __FILE__ ) . 'js/basic-admin-ajax.js'; wp_enqueue_script( 'basic-admin-ajax', $path, array( 'jquery' ) ); } add_action( 'admin_menu', 'baa_add_menu' ); add_action( 'admin_enqueue_scripts', 'baa_load_scripts' ); function baa_render_settings_page() { ? php } function baa_response() { die( 'I got died' ); } </code ``` I've had a look inside `admin-ajax.php` and the only reason for returning a `400` that I can see is if I've failed to set an action. `data['action']` is certainly set, unless I'm crazy. Am I doing anything that's obviously wrong? What could be causing the `400` response? **update** To clarify, the JS fires but the request to `admin-ajax.php` receives a `400`. You can see where the tutorial make has implemented similar JS [here](https://www.youtube.com/watch?time_continue=1799&v=7pO-FYVZv94). (I haven't added a nonce yet but the video maker had already demonstrated it working without implementing a nonce.) **edit** I've updated the PHP to show the plugin's entire PHP file. **update 2** I've stripped the JS back to the essentials and followed the top example from [Wordpress](https://codex.wordpress.org/AJAX_in_Plugins). The response is still `400`. Which leads me to believe that it might be something I've overlooked in the php. At the moment, I don't understand why or what it might be. ``` jQuery(document).ready(function($) { var data = { 'action': 'baa_response' }; $.post(ajaxurl, data, function(response) { alert('Got this from the server: ' + response); }); }); ```<issue_comment>username_1: Please try like this, Add this to your **functions.php**, ``` $path = plugin_dir_url( __FILE__ ) . 'js/basic-admin-ajax.js'; wp_enqueue_script( 'basic-admin-ajax', $path, array('jquery'), '1.0', true ); wp_localize_script( 'basic-admin-ajax', 'action_linklist', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) )); function baa_response() { echo "something....."; die(); } ``` in your **JS** file, ``` jQuery(document).ready(function($){ $('#baa_form').submit(function(){ jQuery.ajax({ url: action_linklist.ajax_url, type: 'post', data:{'action': 'baa_response'}, success: function (response) { alert(response); } }); return false; }); }); ``` Hope this will helps you, For more information, please visit. [Using AJAX with wordpress](https://premium.wpmudev.org/blog/using-ajax-with-wordpress/) [AJAX in Plugins](https://codex.wordpress.org/AJAX_in_Plugins) Upvotes: 1 <issue_comment>username_2: You missed `action`, which will fired on your Ajax request. WordPress can't guess which function related to your Ajax call, and that's why just blocking it( `400 Bad Request` ). In the php file add this line: ``` add_action('wp_ajax_baa_response', 'baa_response'); ``` You may also want to look at the [Ajax in Wordpress](https://codex.wordpress.org/AJAX_in_Plugins) documentation. Upvotes: 3 [selected_answer]
2018/03/15
2,152
5,423
<issue_start>username_0: I'm new to Python and I'm working on a project for a Data Science class I'm taking. I have a big csv file (around 190 million lines, approx. 7GB of data) and I need, first, to do some data preparation. Full disclaimer: data here is from this [Kaggle competition](https://www.kaggle.com/c/talkingdata-adtracking-fraud-detection/overview). A picture from Jupyter Notebook with headers follows. Although it reads `full_data.head()`, I'm using a 100,000-lines sample just to test code. [![enter image description here](https://i.stack.imgur.com/1kyHm.png)](https://i.stack.imgur.com/1kyHm.png) The most important column is `click_time`. The format is: `dd hh:mm:ss`. I want to split this in 4 different columns: day, hour, minute and second. I've reached a solution that works fine with this little file but it takes too long to run on 10% of real data, let alone on top 100% of real data (hasn't even been able to try that since just reading the full csv is a big problem right now). Here it is: ``` # First I need to split the values click = full_data['click_time'] del full_data['click_time'] click = click.str.replace(' ', ':') click = click.str.split(':') # Then I transform everything into integers. The last piece of code # returns an array of lists, one for each line, and each list has 4 # elements. I couldn't figure out another way of making this conversion click = click.apply(lambda x: list(map(int, x))) # Now I transform everything into unidimensional arrays day = np.zeros(len(click), dtype = 'uint8') hour = np.zeros(len(click), dtype = 'uint8') minute = np.zeros(len(click), dtype = 'uint8') second = np.zeros(len(click), dtype = 'uint8') for i in range(0, len(click)): day[i] = click[i][0] hour[i] = click[i][1] minute[i] = click[i][2] second[i] = click[i][3] del click # Transforming everything to a Pandas series day = pd.Series(day, index = full_data.index, dtype = 'uint8') hour = pd.Series(hour, index = full_data.index, dtype = 'uint8') minute = pd.Series(minute, index = full_data.index, dtype = 'uint8') second = pd.Series(second, index = full_data.index, dtype = 'uint8') # Adding to data frame full_data['day'] = day del day full_data['hour'] = hour del hour full_data['minute'] = minute del minute full_data['second'] = second del second ``` The result is ok, it's what I want, but there has to be a faster way doing this: [![enter image description here](https://i.stack.imgur.com/TlhWn.png)](https://i.stack.imgur.com/TlhWn.png) Any ideas on how to improve this implementation? If one is interested in the dataset, this is from the test\_sample.csv: <https://www.kaggle.com/c/talkingdata-adtracking-fraud-detection/data> Thanks a lot in advance!! --- **EDIT 1**: Following @COLDSPEED request, I provide the results of `full_data.head.to_dict()`: ``` {'app': {0: 12, 1: 25, 2: 12, 3: 13, 4: 12}, 'channel': {0: 497, 1: 259, 2: 212, 3: 477, 4: 178}, 'click_time': {0: '07 09:30:38', 1: '07 13:40:27', 2: '07 18:05:24', 3: '07 04:58:08', 4: '09 09:00:09'}, 'device': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1}, 'ip': {0: 87540, 1: 105560, 2: 101424, 3: 94584, 4: 68413}, 'is_attributed': {0: 0, 1: 0, 2: 0, 3: 0, 4: 0}, 'os': {0: 13, 1: 17, 2: 19, 3: 13, 4: 1}} ```<issue_comment>username_1: One solution is to first split by whitespace, then convert to `datetime` objects, then extract components directly. ``` import pandas as pd df = pd.DataFrame({'click_time': ['07 09:30:38', '07 13:40:27', '07 18:05:24', '07 04:58:08', '09 09:00:09', '09 01:22:13', '09 01:17:58', '07 10:01:53', '08 09:35:17', '08 12:35:26']}) df[['day', 'time']] = df['click_time'].str.split().apply(pd.Series) df['datetime'] = pd.to_datetime(df['time']) df['day'] = df['day'].astype(int) df['hour'] = df['datetime'].dt.hour df['minute'] = df['datetime'].dt.minute df['second'] = df['datetime'].dt.second df = df.drop(['time', 'datetime'], 1) ``` **Result** ``` click_time day hour minute second 0 07 09:30:38 7 9 30 38 1 07 13:40:27 7 13 40 27 2 07 18:05:24 7 18 5 24 3 07 04:58:08 7 4 58 8 4 09 09:00:09 9 9 0 9 5 09 01:22:13 9 1 22 13 6 09 01:17:58 9 1 17 58 7 07 10:01:53 7 10 1 53 8 08 09:35:17 8 9 35 17 9 08 12:35:26 8 12 35 26 ``` Upvotes: 2 <issue_comment>username_2: Convert to `timedelta` and extract components: ``` v = df.click_time.str.split() df['days'] = v.str[0].astype(int) df[['hours', 'minutes', 'seconds']] = ( pd.to_timedelta(v.str[-1]).dt.components.iloc[:, 1:4] ) ``` ``` df app channel click_time device ip is_attributed os days hours \ 0 12 497 07 09:30:38 1 87540 0 13 7 9 1 25 259 07 13:40:27 1 105560 0 17 7 13 2 12 212 07 18:05:24 1 101424 0 19 7 18 3 13 477 07 04:58:08 1 94584 0 13 7 4 4 12 178 09 09:00:09 1 68413 0 1 9 9 minutes seconds 0 30 38 1 40 27 2 5 24 3 58 8 4 0 9 ``` Upvotes: 3 [selected_answer]
2018/03/15
708
2,685
<issue_start>username_0: The simple animation example show in the Windows UWP docs under the section of Visual Layer and sub-section of Time animation is not working... [![UWP docs animation code Image](https://i.stack.imgur.com/PsXIC.png)](https://i.stack.imgur.com/PsXIC.png) Above is the code example shown in the docs. [![XAML rectangle code](https://i.stack.imgur.com/FNsDg.png)](https://i.stack.imgur.com/FNsDg.png) Above is the code of XAML rectangle that I am animating.[![C# code for animation](https://i.stack.imgur.com/KwDoS.png)](https://i.stack.imgur.com/KwDoS.png) Above is the code I have written, similar to the code in first image.[![Error in debug mode](https://i.stack.imgur.com/BeNJP.png)](https://i.stack.imgur.com/BeNJP.png) Now this is the error I am getting every time I run the app in debug mode. The property was not found. But that is what is written in docs, then how could it be. One more thing I have tried setting the property to renderTransform as well but that doesn't work either. What am I doing wrong?<issue_comment>username_1: I believe that the [example](https://learn.microsoft.com/en-us/windows/uwp/composition/time-animations#example) is wrong. The Visual object have no properties like as "Translation". To move it from left to right, ``` visual.StartAnimation("Offset.X", animation); ``` or ``` visual.StartAnimation(nameof(visual.Offset) + "." + nameof(visual.Offset.X), animation); ``` I have very simple example code of animate the object with UI.Composition on GitHub. The comments are all Japanese, but it may help you, I hope so. [CompositionGridView](https://github.com/pnp0a03/CompositionGridView) Upvotes: 1 <issue_comment>username_2: Adding another answer because the one here isn't entirely correct - whilst the example *IS* wrong, there is in fact a `Translation` property on Composition Visuals that come from XAML objects - that is also most likely preferable to using offset if your animating a visual of a XAML object. Firstly, you need to enable the translation property on the element like so: `ElementCompositionPreview.SetIsTranslationEnabled(uiElement, true)` Secondly, you then need to change the animation property to actually target the correct property: `visual.StartAnimation("Translation.X", animation);` *This only works if you're targeting the creators update or above.* Using `Translation` over `Offset` entirely avoids issues where XAML layout updates break the animation - as XAML position updates will overwrite a Visual's Offset and stop any current animation, whereas Translation animations will continue to run unabated of what the XAML layout engine does. Upvotes: 3 [selected_answer]
2018/03/15
1,559
4,988
<issue_start>username_0: When I try to decode JSON I get the error: > > (Error: typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [sweetyanime.Video.(CodingKeys in \_D1045E05CDE474AEBA8BDCAF57455DC3).video, sweetyanime.iD.(CodingKeys in \_D1045E05CDE474AEBA8BDCAF57455DC3).ID, sweetyanime.other.(CodingKeys in \_D1045E05CDE474AEBA8BDCAF57455DC3).CountOfVideos], debugDescription: "Expected to decode String but found a dictionary instead.", underlyingError: nil) > > > 1) JSON: ``` { "video":{ "ID":{ "Name":"NameOfAnime", "Describe":"SomeDescribe", "Image":"https://firebasestorage.googleapis.com/v0/b/sweety-anime-e6bb4.appspot.com/o/main.png?alt=media&token=<PASSWORD>", "CountOfVideos":{ "1Series":"https://firebasestorage.googleapis.com/v0/b/sweety-anime-e6bb4.appspot.com/o/message_movies%252F12323439-9729-4941-BA07-2BAE970967C7.movalt=media&token=<PASSWORD>" } } } } ``` 2) Swift code: ``` let jsonUrl = "file:///Users/tima/WebstormProjects/untitled/db.json" guard let url = URL(string: jsonUrl) else { return } URLSession.shared.dataTask(with: url) { (data, reponse, error) in guard let data = data else {return} do { let video = try JSONDecoder().decode(Video.self, from: data) print(video.video.ID.Name) } catch let jsonErr { print("Error: ", jsonErr) } }.resume() ``` 3) Video.swift ``` struct Video: Decodable { private enum CodingKeys : String, CodingKey { case video = "video" } let video: iD } struct iD: Decodable { private enum CodingKeys : String, CodingKey { case ID = "ID" } let ID: other } struct other: Decodable { private enum CodingKeys : String, CodingKey { case Name = "Name" case Describe = "Describe" case Image = "Image" case CountOfVideos = "CountOfVideos" } let Name: String let Describe: String let Image: String let CountOfVideos: String } ```<issue_comment>username_1: Let's put some line breaks in your error message to make it understandable: ``` (Error: typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [ sweetyanime.Video.(CodingKeys in _D1045E05CDE474AEBA8BDCAF57455DC3).video, sweetyanime.iD.(CodingKeys in _D<KEY>).ID, sweetyanime.other.(CodingKeys in _D1045E05CDE474AEBA8BDCAF57455DC3).CountOfVideos], debugDescription: "Expected to decode String but found a dictionary instead.", underlyingError: nil) ``` So it was trying to decode the value for “CountOfVideos”. It expected a String but it found a dictionary. You need to either define a `struct` corresponding to the “CountOfVideos” dictionary (it appears to contain one key, “1Series”, with a string value), or you need to remove the `CountOfVideos` property from your `other` struct so you don't try to decode it at all. Upvotes: 3 [selected_answer]<issue_comment>username_2: My I think you should implement the init(from decoder) initializer that is part of Decodable. It gives a lot more flexibility on how to handle nested JSON than you get from the automatic implementation. One possible implementation would be something like: ``` struct Video: Decodable { let name: String let describe: String let image: String let countOfVideos: String private enum VideoKey: String, CodingKey { case video = "video" } private enum IDKey: String, CodingKey { case id = "ID" } private enum CodingKeys: String, CodingKey { case name = "Name" case describe = "Describe" case image = "Image" case countOfVideos = "CountOfVideos" } private enum VideoCountKey: String, CodingKey { case videoCount = "1Series" } init(from decoder: Decoder) throws { let videoContainer = try decoder.container(keyedBy: VideoKey.self) let idContainer = try videoContainer.nestedContainer(keyedBy: IDKey.self, forKey: .video) let valuesContainer = try idContainer.nestedContainer(keyedBy: CodingKeys.self, forKey: .id) self.name = try valuesContainer.decode(String.self, forKey: .name) self.describe = try valuesContainer.decode(String.self, forKey: .describe) self.image = try valuesContainer.decode(String.self, forKey: .image) let videoCountContainer = try valuesContainer.nestedContainer(keyedBy: VideoCountKey.self, forKey: .countOfVideos) self.countOfVideos = try videoCountContainer.decode(String.self, forKey: .videoCount) } ``` This works with your example data in a Playground. I really don't know if you wanted the key or the value for your videoCount. (Neither looks like a count of videos to me. Generally, you just need to define a CodingKey enum for every level of your nested JSON and you can decode individual values as you see fit. (Note, since I've only seen one example of your data, this may break on some stuff in whatever API you're working with, so modify/take the ideas and rewrite it as needed) Upvotes: -1
2018/03/15
3,500
9,579
<issue_start>username_0: I have a simple GUI made with `PyQt5` with two `QWidgets` and two pushbuttons. Each pushbutton generates a bar chart. This part works perfectly but when the size of the window changes, the left bar chart overwrites the one on the right side (i.e. I have the same bar chart twice). How can I prevent this overwritting? Backend code: ``` from PyQt5.QtCore import * from PyQt5.QtWidgets import * from PyQt5.QtGui import * import matplotlib.pyplot as plt from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from network_view import Ui_MainWindow import sys class Run_script(QMainWindow, Ui_MainWindow): def __init__(self,parent=None): super(Run_script,self).__init__(parent) self.setupUi(self) self.pushButton1.clicked.connect(self.view_graph1) self.pushButton2.clicked.connect(self.view_graph2) self.figure = plt.figure() self.graph1 = FigureCanvas(self.figure) self.gridLayout.addWidget(self.graph1, 1, 0, 1, 1) self.graph2 = FigureCanvas(self.figure) self.gridLayout.addWidget(self.graph2, 1, 1, 1, 1) def view_graph1(self): self.figure.clf() self.axes = self.figure.add_subplot(111) x1 = [1, 2, 3, 4, 5] y1 = [10, 20, 30, 40, 50] x2 = [1.5, 2.5, 3.5, 4.5, 5.5] y2 = [15, 25, 35, 45, 55] self.axes.bar(x1,y1,width=0.40) self.axes.bar(x2,y2,width=0.40) self.graph1.draw() def view_graph2(self): self.figure.clf() self.axes = self.figure.add_subplot(111) x1 = [1, 2, 3, 4, 5] y1 = [10, 20, 30, 40, 50] x2 = [1.25, 2.25, 3.25, 4.25, 5.25] y2 = [15, 25, 35, 45, 55] x3 = [1.5, 2.5, 3.5, 4.5, 5.5] y3 = [1, 2, 3, 4, 5] self.axes.bar(x1,y1,width=0.40) self.axes.bar(x2,y2,width=0.40) self.axes.bar(x3,y3,width=0.40) self.graph2.draw() if __name__ == '__main__': app = QApplication(sys.argv) prog = Run_script() prog.show() sys.exit(app.exec_()) ``` Frontend code: ``` from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(800, 600) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.gridLayout = QtWidgets.QGridLayout(self.centralwidget) self.gridLayout.setObjectName("gridLayout") self.pushButton1 = QtWidgets.QPushButton(self.centralwidget) self.pushButton1.setObjectName("pushButton1") self.gridLayout.addWidget(self.pushButton1, 0, 0, 1, 1) self.pushButton2 = QtWidgets.QPushButton(self.centralwidget) self.pushButton2.setObjectName("pushButton2") self.gridLayout.addWidget(self.pushButton2, 0, 1, 1, 1) self.widget1 = QtWidgets.QWidget(self.centralwidget) self.widget1.setObjectName("widget1") self.gridLayout.addWidget(self.widget1, 1, 0, 1, 1) self.widget2 = QtWidgets.QWidget(self.centralwidget) self.widget2.setObjectName("widget2") self.gridLayout.addWidget(self.widget2, 1, 1, 1, 1) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21)) self.menubar.setObjectName("menubar") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self.pushButton1.setText(_translate("MainWindow", "PushButton")) self.pushButton2.setText(_translate("MainWindow", "PushButton")) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_()) ``` Thank you<issue_comment>username_1: The problem is caused because you are using the same `plt.figure()`, so when you use `clf()` clean the drawing and add a new plot, that's why you think it is overwritten. > > Why do not you see that effect immediately after pressing the button? > > > Because it has not been notified to the view that you have to apply the changes, but as soon as you change the size it is repainted with the updated data, the same thing you could see when using `update()`. A possible solution is each each `FigureCanvas` have a `plt.figure()`: ``` class Run_script(QMainWindow, Ui_MainWindow): def __init__(self,parent=None): super(Run_script,self).__init__(parent) self.setupUi(self) self.pushButton1.clicked.connect(self.view_graph1) self.pushButton2.clicked.connect(self.view_graph2) self.figure1 = plt.figure() self.graph1 = FigureCanvas(self.figure1) self.gridLayout.addWidget(self.graph1, 1, 0, 1, 1) self.figure2 = plt.figure() self.graph2 = FigureCanvas(self.figure2) self.gridLayout.addWidget(self.graph2, 1, 1, 1, 1) def view_graph1(self): self.figure1.clf() axes = self.figure1.add_subplot(111) x1 = [1, 2, 3, 4, 5] y1 = [10, 20, 30, 40, 50] x2 = [1.5, 2.5, 3.5, 4.5, 5.5] y2 = [15, 25, 35, 45, 55] axes.bar(x1,y1,width=0.40) axes.bar(x2,y2,width=0.40) self.graph1.draw() def view_graph2(self): self.figure2.clf() axes = self.figure2.add_subplot(111) x1 = [1, 2, 3, 4, 5] y1 = [10, 20, 30, 40, 50] x2 = [1.25, 2.25, 3.25, 4.25, 5.25] y2 = [15, 25, 35, 45, 55] x3 = [1.5, 2.5, 3.5, 4.5, 5.5] y3 = [1, 2, 3, 4, 5] axes.bar(x1,y1,width=0.40) axes.bar(x2,y2,width=0.40) axes.bar(x3,y3,width=0.40) self.graph2.draw() ``` A better implementation is to create your own canvas: ``` class MyCanvas(FigureCanvas): def __init__(self, *args, **kwargs): self.figure = plt.figure() FigureCanvas.__init__(self, self.figure) class Run_script(QMainWindow, Ui_MainWindow): def __init__(self,parent=None): super(Run_script,self).__init__(parent) self.setupUi(self) self.pushButton1.clicked.connect(self.view_graph1) self.pushButton2.clicked.connect(self.view_graph2) self.graph1 = MyCanvas() self.gridLayout.addWidget(self.graph1, 1, 0, 1, 1) self.graph2 = MyCanvas() self.gridLayout.addWidget(self.graph2, 1, 1, 1, 1) def view_graph1(self): self.graph1.figure.clf() axes = self.graph1.figure.add_subplot(111) x1 = [1, 2, 3, 4, 5] y1 = [10, 20, 30, 40, 50] x2 = [1.5, 2.5, 3.5, 4.5, 5.5] y2 = [15, 25, 35, 45, 55] axes.bar(x1,y1,width=0.40) axes.bar(x2,y2,width=0.40) self.graph1.draw() def view_graph2(self): self.graph2.figure.clf() axes = self.graph2.figure.add_subplot(111) x1 = [1, 2, 3, 4, 5] y1 = [10, 20, 30, 40, 50] x2 = [1.25, 2.25, 3.25, 4.25, 5.25] y2 = [15, 25, 35, 45, 55] x3 = [1.5, 2.5, 3.5, 4.5, 5.5] y3 = [1, 2, 3, 4, 5] axes.bar(x1,y1,width=0.40) axes.bar(x2,y2,width=0.40) axes.bar(x3,y3,width=0.40) self.graph2.draw() ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: As commented already you have only one figure in the programm. Hence both plots *are* the same. You would need to have two different figures. Additionally, do not use pyplot in GUIs because this allows you to easily run into problems like this. ``` from PyQt5.QtCore import * from PyQt5.QtWidgets import * from PyQt5.QtGui import * from matplotlib.figure import Figure from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas class Run_script(QMainWindow, Ui_MainWindow): def __init__(self,parent=None): super(Run_script,self).__init__(parent) self.setupUi(self) self.pushButton1.clicked.connect(self.view_graph1) self.pushButton2.clicked.connect(self.view_graph2) self.figure1 = Figure() self.graph1 = FigureCanvas(self.figure1) self.gridLayout.addWidget(self.graph1, 1, 0, 1, 1) self.figure2 = Figure() self.graph2 = FigureCanvas(self.figure2) self.gridLayout.addWidget(self.graph2, 1, 1, 1, 1) def view_graph1(self): self.figure1.clf() self.axes = self.figure1.add_subplot(111) x1 = [1, 2, 3, 4, 5] y1 = [10, 20, 30, 40, 50] x2 = [1.5, 2.5, 3.5, 4.5, 5.5] y2 = [15, 25, 35, 45, 55] self.axes.bar(x1,y1,width=0.40) self.axes.bar(x2,y2,width=0.40) self.graph1.draw() def view_graph2(self): self.figure2.clf() self.axes = self.figure2.add_subplot(111) x1 = [1, 2, 3, 4, 5] y1 = [10, 20, 30, 40, 50] x2 = [1.25, 2.25, 3.25, 4.25, 5.25] y2 = [15, 25, 35, 45, 55] x3 = [1.5, 2.5, 3.5, 4.5, 5.5] y3 = [1, 2, 3, 4, 5] self.axes.bar(x1,y1,width=0.40) self.axes.bar(x2,y2,width=0.40) self.axes.bar(x3,y3,width=0.40) self.graph2.draw() ``` Upvotes: 1
2018/03/15
969
3,578
<issue_start>username_0: I have 3 different tables I need to pull data from. What needs to happen is we pull posts from the posts table where the user who made the post is set as a public user, or if set as private, users they grant access to can view their posts. Here are the tables: ``` user: id, username, name, password, email, private posts: id, title, user, date, state privateallowed: id, privateuser, alloweduser ``` and here is my code where I try to get the records: ``` $username = $_COOKIE['username']; $sqlposts = "select p.id, u.id, u.private, a.privateuser, a.alloweduser from user u inner join posts p on u.id = p.user inner join privateallowed a on a.privateuser = u.id and a.alloweduser = " . $username . " where u.private='public' or (a.privateuser=p.user and a.alloweduser=" . $username . ")"; $resultpost = mysqli_query($dbcon, $sqlposts); $numrows = mysqli_num_rows($resultpost); ``` Unfortunately, no records are being returned. Any help or ideas are appreciated.<issue_comment>username_1: For what it's worth (@pgngp commented about needing single quotes around `'" . $username . "'`): ``` $username = $_COOKIE['username']; $sqlposts = "SELECT p.id, u.id, u.private, a.privateuser, a.alloweduser FROM user u INNER JOIN posts p ON u.id = p.user INNER JOIN privateallowed a ON a.privateuser = u.id AND a.alloweduser = '" . $username . "' WHERE u.private='public'; $resultpost = mysqli_query($dbcon, $sqlposts); $numrows = mysqli_num_rows($resultpost)"; ``` --- Also note, I've removed the following from your `WHERE` condition because it is redundant due to previous `INNER JOIN`'s. We can only infer this because you've used `INNER JOIN`, had you used `LEFT JOIN` you would need to leave the condition in as-is. ``` . . .or (a.privateuser=p.user and a.alloweduser=" . $username . ")" ``` Explanation: * `INNER JOIN posts p ON u.id = p.user` + So we have determined that `u.id = p.user` * `INNER JOIN privateallowed a ON a.privateuser = u.id` + So we infer that `a.privateuser = p.user` * `AND a.alloweduser = '" . $username . "'` + This covers the remaining condition in your `WHERE` Upvotes: 1 <issue_comment>username_2: I did find an answer, though I'm sure it isn't a perfect one. What I did was I broke the statements into separate select statements, and then embed one in the where clause, as follows: ``` $sqlposts = "SELECT p.id, u.id, u.private FROM user u INNER JOIN posts p ON u.id = p.user WHERE u.private='public' or p.user in ( select a.privateuser from privateallowed a inner join posts p on p.user = a.privateuser where a.alloweduser=" . $username . " )"; ``` Me and another person who is pretty good with sql looked at this for a couple of hours, and we just couldn't get the select to return the correct results. We tried the following, but it returned each public user 3 times for some reason: ``` SELECT p.id, u.id, u.private FROM user u INNER JOIN posts p ON u.id = p.user INNER JOIN privateallowed a on a.alloweduser=24 WHERE u.private='public' or p.user = a.privateuser ``` I appreciate everyone's help on this. If anyone has any other ideas, I appreciate them. I'm working on a web site that I am hoping will grow, and I want to make sure the page loads as fast as possible. Upvotes: 1 [selected_answer]
2018/03/15
426
1,322
<issue_start>username_0: I am looking for a solution to find an unused number in the table. The most of the solutions I came across so far is creating a temporary table with all the numbers and used left join to find the unused number. In my case, I have no opportunity to create a temporary table. The number range with leading zeros: `0001-1999`. These numbers are dialing pad numbers and it has to be 4 digits in length. listings table: ``` +----+--------+------------+ | id | title | pad_number | +----+--------+------------+ | 1 | Foo | 0001 | | 2 | bar | 0005 | | 3 | Baz | 1999 | | 10 | FooBar | 0002 | +----+--------+------------+ ``` Expected result: ``` 0003 ``` Is there any way to retrieve the number?<issue_comment>username_1: Use `not exists`. ``` select lpad(cast(cast(pad_number as unsigned)+1 as char(4)),4,'0') from tbl t where not exists (select 1 from tbl t1 where cast(t.pad_number as unsigned)=cast(t1.pad_number as unsigned)-1) and cast(pad_number as unsigned) >=0 and cast(pad_number as unsigned) < 1999 order by 1 limit 1 ``` Upvotes: 1 <issue_comment>username_2: I would do this as: ``` select lpad(min(pad_number) + 1, 4, '0') from t where not exists (select 1 from t t2 where t2.pad_number = t.pad_number + 1); ``` Upvotes: 2
2018/03/15
739
2,472
<issue_start>username_0: How would I go about checking if the Windows operating system is 32 or 64 bit during runtime? I would like to compile the application once for 32-bit, but have it be used for both versions, so using macros is out of the question. From what I can tell, I'm supposed to use [QSysInfo](http://doc.qt.io/qt-5/qsysinfo.html) in order to determine this, but everything in the documentation looks foreign; I have no clue what I'm supposed to check or which value I should be checking for. If someone could clarify and give an example on how to do this, or provide a more effective alternative, it would be greatly appreciated!<issue_comment>username_1: You can use [`IsWow64Process()`](https://msdn.microsoft.com/en-us/library/ms684139.aspx). It checks if the application is running on a 64-bit Windows. [For Example](https://vcpptips.wordpress.com/tag/computer-is-running-a-32-bit-or-64-bit-os/): ``` BOOL Is64BitOS() { BOOL bIs64BitOS = FALSE; // We check if the OS is 64 Bit typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL); LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress( GetModuleHandle("kernel32"),"IsWow64Process"); if (NULL != fnIsWow64Process) { if (!fnIsWow64Process(GetCurrentProcess(),&bIs64BitOS)) { //error } } return bIs64BitOS; } ``` Upvotes: 1 <issue_comment>username_2: This used to work for C#, your mileage may vary... ``` [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] static extern bool IsWow64Process(IntPtr hProcess, out bool wow64Process); public static bool Is64BitOperatingSystem() { // 64-bit programs run only on Win64 if (IntPtr.Size == 8) { return true; } else { // 32-bit programs run on both 32-bit and 64-bit Windows // Detect whether the current process is a 32-bit process running on a 64-bit system. bool flag; return ((doesWin32MethodExist("kernel32.dll", "IsWow64Process") && IsWow64Process(GetCurrentProcess(), out flag)) && flag); } } private static bool doesWin32MethodExist(string moduleName, string methodName) { IntPtr moduleHandle = GetModuleHandle(moduleName); if (moduleHandle == IntPtr.Zero) { return false; } return (GetProcAddress(moduleHandle, methodName) != IntPtr.Zero); } ``` Upvotes: -1
2018/03/15
660
2,140
<issue_start>username_0: I have all menu on one canvas. How can I check which scene I am using now? I try this code, but it always shows that index of the scene is 0. ``` Scene currentScene = SceneManager.GetActiveScene (); string sceneName = currentScene.name; int buildIndex = currentScene.buildIndex; ```<issue_comment>username_1: You can use [`IsWow64Process()`](https://msdn.microsoft.com/en-us/library/ms684139.aspx). It checks if the application is running on a 64-bit Windows. [For Example](https://vcpptips.wordpress.com/tag/computer-is-running-a-32-bit-or-64-bit-os/): ``` BOOL Is64BitOS() { BOOL bIs64BitOS = FALSE; // We check if the OS is 64 Bit typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL); LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress( GetModuleHandle("kernel32"),"IsWow64Process"); if (NULL != fnIsWow64Process) { if (!fnIsWow64Process(GetCurrentProcess(),&bIs64BitOS)) { //error } } return bIs64BitOS; } ``` Upvotes: 1 <issue_comment>username_2: This used to work for C#, your mileage may vary... ``` [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] static extern bool IsWow64Process(IntPtr hProcess, out bool wow64Process); public static bool Is64BitOperatingSystem() { // 64-bit programs run only on Win64 if (IntPtr.Size == 8) { return true; } else { // 32-bit programs run on both 32-bit and 64-bit Windows // Detect whether the current process is a 32-bit process running on a 64-bit system. bool flag; return ((doesWin32MethodExist("kernel32.dll", "IsWow64Process") && IsWow64Process(GetCurrentProcess(), out flag)) && flag); } } private static bool doesWin32MethodExist(string moduleName, string methodName) { IntPtr moduleHandle = GetModuleHandle(moduleName); if (moduleHandle == IntPtr.Zero) { return false; } return (GetProcAddress(moduleHandle, methodName) != IntPtr.Zero); } ``` Upvotes: -1
2018/03/15
350
846
<issue_start>username_0: I want to count the number of numbers (not digits) in a string that are separated by spaces. ``` tst1 = "69 21 -" tst2 = "69 24 7" ## ATTEMPT: grep('([0-9])', tst1, perl = TRUE) ## EXPECT 2 grep('([0-9])', tst2, perl = TRUE) ## EXPECT 3 ```<issue_comment>username_1: You could use the `str_count` function from the `stringr` package ``` library(stringr) str_count(tst1, '\\d+') 2 str_count(tst2, '\\d+') 3 ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: using `gsub`, extract only digits and count them using `sum()` Data: ``` tst1 <- list( "69 21 -" , "69 24 7", "sdfsdf 24 453 35 sdff 45", "sfsdff" ) ``` Code: ``` y <- lapply(tst1, function(x) { temp <- unlist( strsplit( gsub("[^[:digit:]]", " ", x), split = " ") ) sum( temp != "" ) } ) ``` Output: ``` y # [1] 2 3 4 0 ``` Upvotes: 1
2018/03/15
977
3,540
<issue_start>username_0: I am using the sharp library to create dynamic JPEG license plate images. Basically, I have a PNG that is a vanity license plate with no numbers. Then I create an svg in code like so ``` const svg = new Buffer( ` <![CDATA[ @font-face { font-family: LicensePlate; src: url('LicensePlate.ttf'); } svg { width: 100%; height: 100%; } ]]> ${platenumber.toUpperCase()} ` ); ``` Passing in the desired width, height, and license plate number. Then I use the sharp library to overlay my SVG in the middle of the license plate. This all works just fine. However, I have imported a custom license plate font (LicensePlate.ttf). In order to debug my in-code SVG image I made an actual svg image file that I open in the browser to make sure that it all looks correct, which it does. The problem is that when the final JPEG file is created it does not contain my custom font. Instead it falls back on Verdana. My question is, is there any way I can maintain the SVG font while creating the image with sharp? Thanks! ### Full Code ``` function createImage(platenumber) { //Trying to create some sort of responsiveness let fontsize = 80; let letterspace = 10; let width = 300; let height = 90; let x = 0; let y = -45; const inputlength = platenumber.length; //Minumum Length if (inputlength == 2) { x = -200; } if (inputlength == 3) { x = -150; } if (inputlength == 4) { x = -130; } if (inputlength == 5) { x = -105; } if (inputlength == 6) { x = -65; } try { console.log('stream is duplex, ', pipe instanceof stream.Duplex); //Read the svg code into a buffer with a passed in plate number const svg = new Buffer( ` <![CDATA[ @font-face { font-family: LicensePlate; src: url('LicensePlate.ttf'); } svg { width: 100%; height: 100%; } ]]> ${platenumber.toUpperCase()} ` ); const plateid = rand.generate(10); //Create a write stream to a randomly generated file name const write = new fs.createWriteStream(`plates/${plateid}.jpg`); //Create the sharp pipeline const pipeline = pipe .overlayWith(svg, { gravity: sharp.gravity.center })//we center the svg image over the top of whatever image gets passed into the pipeline .jpeg();//we convert to JPG because it is a compressed file format and will save space (we could also do webp if we really want to be slick about it) //Create the read stream from the license plate template const read = new fs.createReadStream('plate-2.png') .pipe(pipeline)//pipe out sharp pipeline .pipe(write);//add the write stream so that our sharp pipeline knows where to put the image return plateid; } catch (e) { console.log(e); return null; } } ``` ### SVG Image ``` <![CDATA[ @font-face { font-family: LicensePlate; src: url('LicensePlate.ttf'); } ]]> Pl@T3# ``` ### Exact Font Here is a link to the exact font I used <http://www.fontspace.com/dave-hansen/license-plate><issue_comment>username_1: I dealt with this problem by installing the font in my OS, when the file is being converted, the libraries can only access OS fonts. Upvotes: 2 <issue_comment>username_2: install font on OS, if you using Windows, don't forget install font(s) with All Users for IIS and NodeJS have permission to access the font(s) Upvotes: 0
2018/03/15
375
1,444
<issue_start>username_0: I got a lot of entities, 160 to be specific. I need to override `toString` method in all of them. My question is: Is there some shortcut on Intellij or some external tool where I can auto generate `toString` method in all of those entities?<issue_comment>username_1: In Intellij i supposed it can be done like this : 1. Open the desired class for editing and do one of the following: * On the main menu, choose Code | Generate. * Right-click the editor and choose Generate on the context menu * Press Alt+Insert. 2. From the pop-up list that shows up, select toString() option. Generate toString() wizard displays the list of fields in the class. In eclipse it could be done aswell : 1. Right click the editor 2. Select Source 3. Then Select generate toString(). 4. Then select all the fields you want. Upvotes: 3 <issue_comment>username_2: A little bit late, but the easiest way is to add [Project Lombok](https://projectlombok.org) to your project and then annotate all the entities with [@ToString](https://projectlombok.org/features/ToString) annotation. Simple example: ``` import lombok.ToString; @ToString public class Account { private String id; private String name; // standard getters and setters or you can use @Getter and @Setter form lombok too } ``` Here is the result when you call the toString method: ``` Account(id=12345, name=<NAME>) ``` Upvotes: 1 [selected_answer]
2018/03/15
733
2,797
<issue_start>username_0: After updating MassTransit packages to the latest version (4.1.0.1426-develop) I experience problems with registering more then 26 queues. For example, code below crushes with error > > [20:51:06 ERR] RabbitMQ Connect Failed: Broker unreachable: > guest@localhost:5672/test > > > ``` static void Main(string[] args) { var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json", true, true); var configuration = builder.Build(); Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.Console() .ReadFrom.Configuration(configuration) .CreateLogger(); Log.Information("Starting Receiver..."); var services = new ServiceCollection(); services.AddSingleton(context => Bus.Factory.CreateUsingRabbitMq(x => { IRabbitMqHost host = x.Host(new Uri("rabbitmq://guest:guest@localhost:5672/test"), h => { }); for (var i = 0; i < 27; i++) { x.ReceiveEndpoint(host, $"receiver_queue{i}", e => { e.Consumer(); }); } x.UseSerilog(); })); var container = services.BuildServiceProvider(); var busControl = container.GetRequiredService(); busControl.Start(); Log.Information("Receiver started..."); } ``` So, it can't register 27 queues. However it works if I decrease the number to 26 :) If I downgrade MT NuGet packages to the latest stable 4.0.1 version it perfectly works and I can register up to 50 queues. Also, another observation - with 4.1.0.1426-develop versions it takes much longer to start this very tiny app. However when I test it with latest stable 4.0.1 and try to create 50 queues it starts almost immediately. Any ideas where this limitation came from and how to avoid it?<issue_comment>username_1: Thank you for opening the issue, that helps track it. Also, it seems to be fixed now. There was an issue with how the netcoreapp2.0 program stack (and possibly the TaskScheduler) causing it to delay for a long period of time the Connect method in RabbitMQ.Client. I'm thinking this is a TPL/thread issue where the connection wasn't being scheduled for a good 15+ seconds, after which it completed immediately. Moving it into a Task.Factory.StartNew() (deep inside the MT code) appears to have fixed the issue to where it doesn't fail, and it executes immediately. Upvotes: 2 [selected_answer]<issue_comment>username_2: I know this has been marked as resolved but I ran into a similar issue. > > fail: MassTransit[0] partners.moneytransfer | RabbitMQ Connect Failed: > serviceUser@rabbitmq:5672/ > > > The only way I was able to resolve is, is by adding the user to the rabbitmq database with its username and password as specified in the Bus configuration. Upvotes: 0
2018/03/15
1,147
3,206
<issue_start>username_0: My ultimate goal is to get an array of Ints extracted from a String inputted in a textfield. For this I created a function whose parameter is a String. I use a for-loop to get all the characters from the textfield into an array. Then I loop through the array and append only the numbers (if they're <= 24) to a new array. When I print the array with just numbers, I get the first element of array1 repeating. Why is this happening? ``` var array1 = [String]() var array2 = [Int]() func getDigits (userInput: String) { for element in userInput { array1.append(String(element)) } var mx = 0 var fx = 1 func findNumbers() { for number in 1...24 { if array1[mx] == "\(fx)" { array2.append(Int(String(array1[mx]))!) } else { fx += 1 findNumbers() } } } findNumbers() print (array2) } getDigits(userInput: "4-5") ``` Output: [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]<issue_comment>username_1: try this ``` func getDigits (userInput: String) { let splitsCharacters = ",;:- " let seperators = CharacterSet(charactersIn: splitsCharacters) let updateInput = userInput.components(separatedBy: seperators) print(array1) func findNumbers() { for item in updateInput { if let number = Int(item) { if number <= 24{ array2.append(number) } } } } findNumbers() print (array2) } getDigits(userInput: "4-5 hello, 34;12,23") ``` **Output** : [4, 5,12,23] Upvotes: 1 <issue_comment>username_2: I am not sure what you are trying to do but you can try something like **Swift 4** ``` func getDigits (userInput: String) { var resultArray = [Int]() for char in userInput { if let number = Int("\(char)"), number < 24 { resultArray.append(number) } } print(resultArray) } ``` testing ``` getDigits(userInput: "4-5") //prints => [4, 5] ``` You need just 1 array to hold the numbers Note: in swift for the string is array type so you can loop on it directly, but for earlier versions you can use: ``` for char in userInput.characters { } ``` to get the array of string characters Upvotes: 0 <issue_comment>username_3: This will support multi-digit numbers in your input string, and also filter out-of-range values. ``` import Foundation func parseNumbers (userInput: String, splitBy: String, min: Int, max: Int) -> Array { let separators = CharacterSet(charactersIn: splitBy) let numericStrings = userInput.components(separatedBy: separators) var numArray = [Int]() for item in numericStrings { if let number = Int(item) { if (number >= min) && (number <= max) { numArray.append(number) } } } return numArray } print(parseNumbers(userInput: "5:hello,34-7 12;103,abc", splitBy: " -:,;", min:1, max:24)) ``` output: [5, 7, 12] Upvotes: 2 [selected_answer]
2018/03/15
710
2,300
<issue_start>username_0: How to use opencv to perfectly extract the digits text from the below image? The color of the text are dynamic. [![enter image description here](https://i.stack.imgur.com/IinvD.png)](https://i.stack.imgur.com/IinvD.png) [![enter image description here](https://i.stack.imgur.com/IHnpf.png)](https://i.stack.imgur.com/IHnpf.png)<issue_comment>username_1: try this ``` func getDigits (userInput: String) { let splitsCharacters = ",;:- " let seperators = CharacterSet(charactersIn: splitsCharacters) let updateInput = userInput.components(separatedBy: seperators) print(array1) func findNumbers() { for item in updateInput { if let number = Int(item) { if number <= 24{ array2.append(number) } } } } findNumbers() print (array2) } getDigits(userInput: "4-5 hello, 34;12,23") ``` **Output** : [4, 5,12,23] Upvotes: 1 <issue_comment>username_2: I am not sure what you are trying to do but you can try something like **Swift 4** ``` func getDigits (userInput: String) { var resultArray = [Int]() for char in userInput { if let number = Int("\(char)"), number < 24 { resultArray.append(number) } } print(resultArray) } ``` testing ``` getDigits(userInput: "4-5") //prints => [4, 5] ``` You need just 1 array to hold the numbers Note: in swift for the string is array type so you can loop on it directly, but for earlier versions you can use: ``` for char in userInput.characters { } ``` to get the array of string characters Upvotes: 0 <issue_comment>username_3: This will support multi-digit numbers in your input string, and also filter out-of-range values. ``` import Foundation func parseNumbers (userInput: String, splitBy: String, min: Int, max: Int) -> Array { let separators = CharacterSet(charactersIn: splitBy) let numericStrings = userInput.components(separatedBy: separators) var numArray = [Int]() for item in numericStrings { if let number = Int(item) { if (number >= min) && (number <= max) { numArray.append(number) } } } return numArray } print(parseNumbers(userInput: "5:hello,34-7 12;103,abc", splitBy: " -:,;", min:1, max:24)) ``` output: [5, 7, 12] Upvotes: 2 [selected_answer]
2018/03/15
532
2,121
<issue_start>username_0: ``` compile 'com.squareup.picasso:picasso:2.5.2' ``` This the dependency of picasso that i downloaded, After downloading it i use it in the project ``` Picasso.with(context) .load(R.drawable.user) .centerCrop() .resize(avatarSize, avatarSize) .transform(new RoundedTransformation()) .into(holder.ivUserAvatar); ``` Though i get a red code on RoundedTransformation showing cannot resolve Symbol 'RoundedTransformation' Am not used to using Picasso so i need some help<issue_comment>username_1: Your problem is you don't have this class . You can use this class and try again. ``` class RoundedTransformation implements Transformation { @Override public Bitmap transform(Bitmap source) { int size = Math.min(source.getWidth(), source.getHeight()); int x = (source.getWidth() - size) / 2; int y = (source.getHeight() - size) / 2; Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size); if (squaredBitmap != source) { source.recycle(); } Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig()); Canvas canvas = new Canvas(bitmap); Paint paint = new Paint(); BitmapShader shader = new BitmapShader(squaredBitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP); paint.setShader(shader); paint.setAntiAlias(true); float r = size / 2f; canvas.drawCircle(r, r, r, paint); squaredBitmap.recycle(); return bitmap; } @Override public String key() { return "circle"; } } ``` Upvotes: 1 <issue_comment>username_2: Transformations are not part the library yet . So you need to add them as per your need . There are already a bunch of optimized transformations available which you can use directly. 1. [wasabeef/picasso-transformations](https://github.com/wasabeef/picasso-transformations) 2. [TannerPerrien/picasso-transformations](https://github.com/TannerPerrien/picasso-transformations) Upvotes: 0
2018/03/15
264
893
<issue_start>username_0: the code below replaces numbers with the token NUMB: `raw_corpus.loc[:,'constructed_recipe']=raw_corpus['constructed_recipe'].str.replace('\d+','NUMB')` It works fine if the numbers have a space before and a space after, but creates a problem if the numbers are included in another string. How do I modify the code so that it only replaces numbers with NUMB if the numbers are surrounded by a space on both sides? e.g. do not modify this string: "from url 500px", but do modify this string: "dishwasher 10 pods" to "dishwasher NUMB pods". I'm not sure how to modify '\d+' to make this happen. Any ideas?<issue_comment>username_1: just fix your regex for space: ``` \s\d+\s ``` or for any word boundary: ``` \b\d+\b ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: I also tried `' \d+ '` and that works! probably not "pythonic" though... Upvotes: 0
2018/03/15
1,362
4,231
<issue_start>username_0: How would you store an ordered list of N items in Google Firestore? For example, a todo list. I had a couple of ideas but neither seem that smart. You could put a 'position' key on the item but that would require updating all of the items' position value when one changes. You could store them in a sorted array and do some splicing to resort before persisting. I'd be keen to hear what is the recommend approach.<issue_comment>username_1: Firestore doesn't "store sorted lists" as one of its features. What it *will* do is build an index of documents in a collection using the values of document fields that you define. You can then sort documents based on that index. What you do with those document fields is completely up to you. If you need to re-write the values to suit your intended ordering, then do that. Upvotes: 1 <issue_comment>username_2: You could store two lists in Firestore. One with your actual data (unordered) and the other with a map of id to order. Here's a Dart example: ```dart main() { List myList = [ {'id': 'red', 'test': 'some data'}, {'id': 'green', 'other': 'some other data'}, {'id': 'blue'}, ]; List myOrderList = ['green', 'red', 'blue']; List orderByOtherList(List theList, String commonField, List orderList) { List listOut = []; orderList.forEach((o) => listOut.add(theList.firstWhere((m) => m[commonField] == o))); return listOut; } print(myList); print(orderByOtherList(myList, 'id', myOrderList)); } ``` Here's the example on DartPad: <https://dartpad.dartlang.org/dc77acd6e4cfce608796a51cda3ee9ad> Then combine the streams with combineLatest2 from rxdart to order the actual list in your app whenever either list changes. This example uses Dart, but you should be able to create something similar in other languages. Upvotes: 2 <issue_comment>username_3: You can use Realtime DB with **id:data** branch and **id:idPrevious** branch. You are basically making a linked list, which will allow you to make 2 writes on add, and 1 on delete. Reordering / moving will require to rewrite 3 things. Here is an example: ***Original*** **id:data** 1:A, 2:B, 3:C, 4:D, 5:E **id:idPrevious** 1:0, 2:1, 3:2, 4:3, 5:4 ***Modified*** ABC**D**E->A**D**BCE **id:data** 1:A, 2:B, 3:C, 4:D, 5:E - stays the same **id:idPrevious** 1:0, **2:4**, 3:2, **4:1**, **5:3** - 3 changes max Further detail: **5:3** happened when D was deleted from the order. **4:1** happened when D was assigned a place after an item. **2:4** happened when D was sharing an idPrevious with another data chunk, so feeling sorry for kicking it out, it offers its id as idPrevious for the kicked item. Upvotes: 0 <issue_comment>username_4: The approach I use works without updating all the documents, but only the one you are ordering using a position property (This is the way Trello lists work I believe) Suppose you have a list with 5 elements: ``` - A (position: 1) - B (position: 2) - C (position: 3) - D (position: 4) - E (position: 5) ``` Let's say you drag C between A and B, (this is the easiest calculation) you would get: ``` - A (position: 1) - C (old position: 3, new?) <---- you need to calculate this new position - B (position: 2) - D (position: 4) - E (position: 5) ``` At this point, you just need to know the previous element position and the next element position: ``` (A + B) / 2 = 1.5 ``` 1.5 is the new position for "C" ``` - A (position: 1) - C (position: 1.5) <--- update only this doc in your db - B (position: 2) - D (position: 4) - E (position: 5) ``` Let's move C again, to the latest position. You don't have a next element, in this case you do `last + 0.5`: ``` - A (position: 1) - B (position: 2) - D (position: 4) - E (position: 5) - C (new position: 5.5) ``` Last, if you don't have a previous element... first you check if you have a next element, in that case you do: `next / 2` otherwise, set it to `0.5`. Let's move C to the top: ``` - C (new position: A / 2 = 0.5) - A (position: 1) - B (position: 2) - D (position: 4) - E (position: 5) ``` Eventually, you would divide float numbers, but it's not a problem because they are nearly infinite. (depending on the language you use). Upvotes: 3
2018/03/15
963
3,451
<issue_start>username_0: I'm a Java programmer forced to do some C++. What a nightmare! I'm trying to send a POST request to a web service like this: ``` #include #include #include static TCHAR hdrs[] = \_T("Content-Type: application/x-www-form-urlencoded"); static TCHAR frmdata[] = \_T("id=01&message=test\_message"); static LPCSTR accept[2] = { "\*/\*", NULL }; static LPCWSTR tag = L"MyAgent"; static LPCWSTR requestType = L"POST"; // for clarity, error-checking has been removed HINTERNET hSession = InternetOpen(tag, INTERNET\_OPEN\_TYPE\_PRECONFIG, NULL, NULL, 0); HINTERNET hConnect = InternetConnect(hSession, \_T("desktop-60nl2pl:9998"), INTERNET\_DEFAULT\_HTTP\_PORT, NULL, NULL, INTERNET\_SERVICE\_HTTP, 0, 1); HINTERNET hRequest = HttpOpenRequest(hConnect, requestType, \_T("/GUser/login"), NULL, NULL, (LPCWSTR\*)accept, 0, 1); HttpSendRequest(hRequest, hdrs, strlen((char\*)hdrs), frmdata, strlen((char\*)frmdata)); ``` That code is based on this posting: <https://social.msdn.microsoft.com/Forums/sqlserver/en-US/dc74e7bf-3ac9-41a0-b1c7-ece14a76a906/send-post-request-to-simple-php-page-using-wininet?forum=vcgeneral> It compiles but doesn't link. Getting a bunch of these "unresolved external symbol \_imp\_InternetOpenW referenced in function "class std::vector Sorry if this is a newby question but I'm not able to understand all the gobbldygook I read about linker errors. Can someone explain in simple terms?<issue_comment>username_1: TL;DR you're missing a library in your linker options. Going from `.cpp` to `.exe` is a two step operation. Step one is compilation that converts `.cpp` to `.obj`. Step two is linking that converts `.obj` to `.exe`. The reason to do this in two steps becomes very apparent when your program becomes big enough to require two or more `.cpp` files. You compile each `.cpp` on its own, and then link the two `.obj`s together. That cuts your iteration time dramatically, especially when you have 100 or so `.cpp` files and have only changed one of them. During the link phase, the linker also includes various libraries. Most of the really common ones are included automatically so everything just "works right"™ a reasonable percentage of the time. However less commonly used ones, e.g. networking libraries are not included by default and need to be explicitly named in the linker options. Luckily, Microsoft make it pretty easy to track them down. Take one of the undefined function names, "undecorate" it to get the original back, e.g. `InternetOpen` and then google for `InternetOpen msdn`. The first link will take you here: <https://msdn.microsoft.com/en-us/library/windows/desktop/aa385096(v=vs.85).aspx> and if you scroll right to the bottom, there's a `Requirements` section. Listed in there is the library you want: `wininet.lib` so all you have to do is explicitly name it in the `Additinal Dependencies` field of the `Input` page of the `Linker` options under `Project Properties`, and you should be good to go. You are using Visual Studio for this, right? Upvotes: 2 [selected_answer]<issue_comment>username_2: You are referencing functions such as InternetOpen, but they are not defined in your code. The live in Win32 libraries that must be linked against your code. In this case, all the InternetXXXX functions live in the WinInet.lib static library and WinInet.dll dynamic link library. You must link against WinINet.lib for your program to compile. Upvotes: 2
2018/03/15
3,078
8,074
<issue_start>username_0: Hi I am relatively new in R / `ggplot2` and I would like to ask for some advice on how to create a plot that looks like this: [![enter image description here](https://i.stack.imgur.com/h7ln7.jpg)](https://i.stack.imgur.com/h7ln7.jpg) Explanation: A diverging bar plot showing biological functions with genes that have increased expression (yellow) pointing towards the right, as well as genes with reduced expression (purple) pointing towards the left. The length of the bars represent the number of differentially expressed genes, and color intensity vary according to their p-values. Note that the x-axis must be 'positive' in both directions. (In published literature on gene expression experimental studies, bars that point towards the left represent genes that have reduced expression, and right to show genes that have increased expression. The purpose of the graph is not to show the "magnitude" of change (which would give rise to positive and negative values). Instead, we are trying to plot the NUMBER of genes that have changes of expression, therefore cannot be negative) I have tried `ggplot2` but fails completely to reproduce the graph that is shown. Here is the data which I am trying to plot: [Click here for link](https://uploadfiles.io/newbd) ``` > dput(sample) structure(list(Name = structure(c(15L, 19L, 5L, 11L, 8L, 6L, 16L, 13L, 17L, 1L, 3L, 2L, 14L, 18L, 7L, 12L, 10L, 9L, 4L, 20L ), .Label = c("Actin synthesis", "Adaptive immunity", "Antigen presentation", "Autophagy", "Cell cycle", "Cell division", "Cell polarity", "DNA repair", "Eye development", "Lipid metabolism", "Phosphorylation", "Protein metabolism", "Protein translation", "Proteolysis", "Replication", "Signaling", "Sumoylation", "Trafficking", "Transcription", "Translational initiation" ), class = "factor"), Trend_in_AE = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L ), .Label = c("Down", "Up"), class = "factor"), Count = c(171L, 201L, 38L, 63L, 63L, 47L, 22L, 33L, 20L, 16L, 16L, 7L, 10L, 4L, 13L, 15L, 5L, 7L, 9L, 7L), PValue = c(1.38e-08, 1.22e-06, 1.79e-06, 2.89e-06, 0.000122, 0.000123, 0.00036, 0.000682, 0.001030253, 0.001623939, 7.76e-05, 0.000149, 0.000734, 0.001307039, 0.00292414, 0.003347556, 0.00360096, 0.004006781, 0.007330264, 0.010083734 )), .Names = c("Name", "Trend_in_AE", "Count", "PValue"), class = "data.frame", row.names = c(NA, -20L)) ``` Thank you very much for your help and suggestions, this is really help with my learning. My own humble attempt was this: ``` table <- read.delim("file.txt", header = T, sep = "\t") library(ggplot2) ggplot(aes(x=Number, y=Names)) + geom_bar(stat="identity",position="identity") + xlab("number of genes") + ylab("Name")) ``` Result was error message regarding the aes<issue_comment>username_1: Although not exactly what you are looking for, but the following should get you started. @Genoa, as the expression goes, "there are no free lunches". So in this spirit, like @dww has rightly pointed out, show "some effort"! ``` # create dummy data df <- data.frame(x = letters,y = runif(26)) # compute normalized occurence for letter df$normalize_occurence <- round((df$y - mean(df$y))/sd(df$y), 2) # categorise the occurence df$category<- ifelse(df$normalize_occurence >0, "high","low") # check summary statistic summary(df) x y normalize_occurence a : 1 Min. :0.00394 Min. :-1.8000000 b : 1 1st Qu.:0.31010 1st Qu.:-0.6900000 c : 1 Median :0.47881 Median :-0.0800000 d : 1 Mean :0.50126 Mean : 0.0007692 e : 1 3rd Qu.:0.70286 3rd Qu.: 0.7325000 f : 1 Max. :0.93091 Max. : 1.5600000 (Other):20 category Length:26 Class :character Mode :character ggplot(df,aes(x = x,y = normalize_occurence)) + geom_bar(aes(fill = category),stat = "identity") + labs(title= "Diverging Bars")+ coord_flip() ``` [![Diverging bars](https://i.stack.imgur.com/4z3pN.png)](https://i.stack.imgur.com/4z3pN.png) Upvotes: 2 <issue_comment>username_2: @ddw and @Ashish are right - there's a lot in this question. It's also not clear how ggplot "failed" in reproducing the figure, and that would help understand what you're struggling with. The key to ggplot is that pretty much everything that you want to include in the plotting should be included in the data. Adding a few variables to your table to help with putting bars in the right direction will get you a long way toward what you want. Make the variables that are actually negative ("down" values) negative, and they'll plot that way: ``` r_sample$Count2 <- ifelse(r_sample$Trend_in_AE=="Down",r_sample$Count*-1,r_sample$Count) r_sample$PValue2 <- ifelse(r_sample$Trend_in_AE=="Down",r_sample$PValue*-1,r_sample$PValue) ``` Then reorder your "Name" so that it plots according to the new PValue2 variable: ``` r_sample$Name <- factor(r_sample$Name, r_sample$Name[order(r_sample$PValue2)], ordered=T) ``` Lastly, you'll want to left-justify some labels and right-justify others, so make that a variable now: ``` r_sample$just <- ifelse(r_sample$Trend_in_AE=="Down",0,1) ``` Then some fairly minimal plot code gets you quite close to what you want: ``` ggplot(r_sample, aes(x=Name, y=Count2, fill=PValue2)) + geom_bar(stat="identity") + scale_y_continuous("Number of Differently Regulated Genes", position="top", limits=c(-100,225), labels=c(100,0,100,200)) + scale_x_discrete("", labels=NULL) + scale_fill_gradient2(low="blue", mid="light grey", high="yellow", midpoint=0) + coord_flip() + theme_minimal() + geom_text(aes(x=Name, y=0, label=Name), hjust=r_sample$just) ``` You can explore the [theme commands on the ggplot2 help page](http://ggplot2.tidyverse.org/reference/theme.html) to figure out the rest of the formatting. [![enter image description here](https://i.stack.imgur.com/Lp1Nd.png)](https://i.stack.imgur.com/Lp1Nd.png) Upvotes: 1 <issue_comment>username_3: Just try this, ``` library(tidyverse) library(patchwork) set.seed(1) data <- data.frame( x = paste("Gene", 1:30), y = rnorm(30, 0, 50) ) p1 <- data |> mutate(mnls.grp = ifelse(y < 0, 1, 2)) |> # Just to separate y > 0 vs y < 0 ggplot(aes(y, fct_reorder(x, mnls.grp), fill = y)) + # Try ?fct_reorder() geom_col() + geom_text(aes(x = ifelse(y < 0, 3, -3), label = x), hjust = ifelse(data$y < 0, 0, 1), size = 2.5) + geom_segment(x = -100, xend = 100, y = Inf, yend = Inf, lineend = "square") + scale_fill_gradient2(expression(italic("P") * "-values"), low = "purple4", mid = "lightgrey", high = "yellow") + scale_x_continuous(position = "top") + labs(x = "Number of Differently Regulated Genes", y = NULL) + coord_cartesian(xlim = c(-100, 100)) + theme_minimal(base_size = 9) + theme( panel.grid = element_blank(), axis.text.y = element_blank(), axis.ticks.x = element_line(), axis.ticks.length.x = unit(0.5, "line") ) # p1 p2 <- data |> ggplot(aes(y, fct_reorder(x, y), fill = y)) + geom_col() + geom_text(aes(x = ifelse(y < 0, 3, -3), label = x), hjust = ifelse(data$y < 0, 0, 1), size = 2.5) + geom_segment(x = -100, xend = 100, y = Inf, yend = Inf, lineend = "square") + scale_fill_gradient2(expression(italic("P") * "-values"), low = "purple4", mid = "lightgrey", high = "yellow") + scale_x_continuous(position = "top") + labs(x = "Number of Differently Regulated Genes", y = NULL) + coord_cartesian(xlim = c(-100, 100)) + theme_minimal(base_size = 9) + theme( panel.grid = element_blank(), axis.text.y = element_blank(), axis.ticks.x = element_line(), axis.ticks.length.x = unit(0.5, "line") ) # p2 p3 <- p1 + p2 + plot_annotation(tag_levels = "a") & theme(plot.tag = element_text(face = "bold")) # p3 ggsave(plot = p3, "diverging_bar_plot.png", width = 6, height = 4, dpi = 600) ``` [![diverging_bar_plot](https://i.stack.imgur.com/7agOo.png)](https://i.stack.imgur.com/7agOo.png) Upvotes: 1
2018/03/15
800
3,414
<issue_start>username_0: hi guys messing with the youtube api for android. ive got it all set up and working. im using my firebase database to send all relavent info to my app in the form of a list. all works great the list shows, the video plays from the list. and goes in to full screen ok.. but if i want to click another video in my list after nothing happens. so i assume i have to stop and clear my YouTubePlayerView but i dont know how to do this this is how i get my strings from firebase ``` Dl_Strings dlStrings = dataSnapshot.getValue(Dl_Strings.class); Downloadscount.add(" " + String.valueOf(dlStrings.downloads)); AppNameList.add(dlStrings.name); urlList.add(dlStrings.url); ``` this is where i grab the url and add it to my youtube player ``` mlv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView adapterView, View view, int i, long l) { urlmain = urlList.get(i).toString(); tag = TAGGER.get(i).toString(); App_DownLoadCounter(); YouTubePlayerView myoutubeplayerView = (YouTubePlayerView) ((Activity)mContext).findViewById(R.id.youtube); YouTubePlayer.OnInitializedListener mOninitial; mOninitial = new YouTubePlayer.OnInitializedListener() { @Override public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) { youTubePlayer.loadVideo(urlmain); } @Override public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) { } }; ```<issue_comment>username_1: I think a part of code is missing from your snippet, but here's why this isn't working: The YouTube player needs to be initialized only once. `loadVideo` is not called because `onInitializationSuccess` is called only the 1st time you initialize the player. You could simply keep a reference of `YouTubePlayer youTubePlayer` the first time you initialize it and re use that when you need it. ``` YouTubePlayer youTubePlayer; public void onCreate() { super.onCreate(); // initialize player here and save // ... @Override public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) { this.youTubePlayer = youTubePlayer; } } // in your listener mlv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView adapterView, View view, int i, long l) { String videoID = urlList.get(i).toString(); this.youTubePlayer.loadVideo(videoID); } } ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: According to Android Player API, you can do this using [release()](https://developers.google.com/youtube/android/player/reference/com/google/android/youtube/player/YouTubePlayer) method: **public abstract void release ()** > > Stop any loading or video playback and release any system resources > used by this YouTubePlayer. > > > Note that after calling this method any further interaction with this > YouTubePlayer is forbidden. A new instance must be created to > re-enable playback. > > > Upvotes: 2
2018/03/15
1,021
3,638
<issue_start>username_0: I'm trying to build a Rails API with the following JSON structure: ``` { team: "team_name", players: players: [ { name: "player_one", contracts: [ { start_date: '7/1/2017', seasons: [ { year: 2017, salary: 1000000 } ] } ] }, { name: "player_two" } ] } ``` My models are set up as follows: ``` class Team < ApplicationRecord has_many :players end class Player < ApplicationRecord belongs_to :team has_many :contracts end class Contract < ApplicationRecord belongs_to :player has_many :seasons end class Season < ApplicationRecord belongs_to :contract end ``` I'm currently using the following code, but I'd like to clean this up using ActiveModel Serializers (Or other clean solutions) ``` def show @team = Team.find(params[:id]) render json: @team.as_json( except: [:id, :created_at, :updated_at], include: { players: { except: [:created_at, :updated_at, :team_id], include: { contracts: { except: [:id, :created_at, :updated_at, :player_id], include: { seasons: { except: [:id, :contract_id, :created_at, :updated_at] } } } } } } ) end ``` Additionally, the array items are showing in descending order by ID, I'm hoping to reverse that. I'm also hoping to order the players by the first contract, first season, salary.<issue_comment>username_1: I think your approach is right. Looks clean as it could be. You can use also `named_scopes` on your Model. See [docs](http://api.rubyonrails.org/classes/ActiveRecord/Scoping/Named/ClassMethods.html) here. Upvotes: -1 <issue_comment>username_2: **Active Model Serializers** is a nice gem to fit into your needs. Assuming you would use [`0-10-stable`](https://github.com/rails-api/active_model_serializers/tree/0-10-stable) branch (latest: 0.10.7), you can go in this way: ### Serializers ([Doc](https://github.com/rails-api/active_model_serializers/blob/0-10-stable/docs/general/serializers.md)) ``` # app/serializers/team_serializer.rb or app/serializers/api/v1/team_serializer.rb (if your controllers are in app/controllers/api/v1/ subdirectory) class TeamSerializer < ActiveModel::Serializer attributes :name # list all desired attributes here has_many :players end # app/serializers/player_serializer.rb class PlayerSerializer < ActiveModel::Serializer attributes :name # list all desired attributes here has_many :contracts end # app/serializers/contract_serializer.rb class ContractSerializer < ActiveModel::Serializer attributes :start_date # list all desired attributes here has_many :seasons end # app/serializers/season_serializer.rb class SeasonSerializer < ActiveModel::Serializer attributes :year, :salary # list all desired attributes here end ``` ### TeamController ``` def show @team = Team .preload(players: [contracts: :seasons]) .find(params[:id]) render json: @team, include: ['players.contracts.seasons'], adapter: :attributes end ``` Note 1: Using `preload` (or `includes`) will help you [eager-load multiple associations](http://guides.rubyonrails.org/active_record_querying.html#eager-loading-multiple-associations), hence saving you from **N + 1 problem**. Note 2: You may wish to read the details of the `include` option in `render` method from [Doc](https://github.com/rails-api/active_model_serializers/blob/0-10-stable/docs/general/adapters.md#include-option) Upvotes: 1
2018/03/15
3,338
11,675
<issue_start>username_0: I am writing a script that does a Copy-S3Object from S3 using Powershell, however, I need to check the bucket before for a .ready file. The bucket has a folder /test/\*.ready. I know how to check my local for a file, but can't figure out how to check the S3: ``` Initialize-AWSDefaultConfiguration -AccessKey $AKey -SecretKey $SKey -Region $region Set-Location $source $files = Get-ChildItem 'test/*.ready' | Select-Object -Property Name try { if(Test-S3Bucket -BucketName $bucket) { foreach($file in $files) { if(!(Get-S3Object -BucketName $bucket -Key $file.Name)) { ## verify if exist Copy-S3Object -BucketName $bucket -Key $s3File -Region $region -AccessKey $Akey -SecretKey $SKey -LocalFolder $localpath } } } Else { Write-Host "The bucket $bucket does not exist." } } catch { Write-Host "Error uploading file $file" } ```<issue_comment>username_1: You can use "[Head Object](https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectHEAD.html)" API to see if the S3 file/Object is created. Here is PowerShell equivalent for HeadObject. [Get-S3ObjectMetadata](https://docs.aws.amazon.com/powershell/latest/reference/Index.html) > > The HEAD operation retrieves metadata from an object without returning > the object itself. This operation is useful if you're only interested > in an object's metadata. To use HEAD, you must have READ access to the > object. > > > **Example** ``` try {$metadata = Get-S3ObjectMetadata -BucketName bucket-name -Key someFile.txt; "Found"} catch { "Not Found" } ``` Upvotes: 3 <issue_comment>username_2: You can check like this as well (remove the forward slash after ready in the below snippet if you want to test file): ``` if(Get-S3Object -BucketName abhibucketsss | where{$_.Key -like "test/*.ready/"}){ "Folder found" } else{ "Folder Not found" } ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: **\*Update:** I have fully developed a script/module you can read about it [here](https://www.linkedin.com/pulse/one-way-sync-aws-s3-bucket-using-powershell-loveparteek-tiwana) and download the code [here](https://github.com/ltiwana/Sync-Files-To-AWS-S3-Bucket). ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- I was in the same situation, so I started working on a PowerShell script that syncs data and not overwrites it. Write-s3Object CMDlet will overwrite by default, and I checked there is no option to specify not to overwrite existing files. This is how I check if the Local folder exists on S3: ``` if ((Get-S3Object -BucketName $BucketName -KeyPrefix $Destination -MaxKey 2).count -lt "2") { ``` This is how I check if the file exists and if the S3 file is the same size as the local file. ``` $fFile = Get-ChildItem -Force -File -Path "LocalFileName" $S3file = Get-S3Object -BucketName "S3BucketName" -Key "S3FilePath" $s3obj = ($S3file.key -split "/")[-1] if ($fFile.name -eq $s3obj -and $S3file.size -ge $fFile.Length) { WriteWarning "File exists: $s3obj" } ``` Here is the full script. ``` Function Sync-ToS3Bucket { [CmdletBinding()] param ( [Parameter(Mandatory=$True,Position=1)] [string]$BucketName, [Parameter(Mandatory=$True,Position=2)] [string]$LocalFolderPath, [string]$S3DestinationFolder, [string]$S3ProfileName, [string]$AccessKey, [string]$SecretKey, [switch]$ShowProgress ) Function WriteInfo ($msg) { Write-Host "[$(get-date)]:: $msg" } Function WriteAction ($msg) { Write-Host "[$(get-date)]:: $msg" -ForegroundColor Cyan } Function WriteWarning ($msg) { Write-Host "[$(get-date)]:: $msg" -ForegroundColor Yellow } Function WriteError ($msg) { Write-Host "[$(get-date)]:: $msg" -ForegroundColor Red } Function WriteLabel ($msg) { "`n`n`n" Write-Host ("*" * ("[$(get-date)]:: $msg").Length) $msg Write-Host( "*" * ("[$(get-date)]:: $msg").Length) } function Calculate-TransferSpeed ($size, $eTime) { writeInfo "Total Data: $size bytes, Total Time: $eTime seconds" if ($size -ge "1000000") { WriteInfo ("Upload speed : " + [math]::round($($size / 1MB)/$eTime, 2) + " MB/Sec") } Elseif ($size -ge "1000" -and $size -lt "1000000" ) { WriteInfo ("Upload speed : " + [math]::round($($size / 1kb)/$eTime,2)+ " KB/Sec") } Else { if ($size -ne $null -and $size) { WriteInfo ("Upload speed : " + [math]::round($ssize/$eTime,2) + " Bytes/Sec") } else { WriteInfo ("Upload speed : 0 Bytes/Sec") } } } function Get-ItemSize ($size, $msg) { if ($size -ge "1000000000") { WriteInfo "Upload $msg Size : $([math]::round($($size /1gb),2)) GB" } Elseif ($size -ge "1000000" -and $size -lt "1000000000" ) { WriteInfo "Upload $msg Size : $([math]::round($($size / 1MB),2)) MB" } Elseif ($size -ge "1000" -and $size -lt "1000000" ) { WriteInfo "Upload $msg Size : $([math]::round($($size / 1kb),2)) KB" } Else { if ($size -ne $null -and $size) { WriteInfo "Upload $msg Size : $([string]$size) Bytes" } else { WriteInfo "Upload $msg Size : 0 Bytes" } } } clear "`n`n`n`n`n`n`n`n`n`n" $OstartTime = get-date if ($LocalFolderPath.Substring($LocalFolderPath.Length -1) -eq '\') { #$LocalFolderPath = $LocalFolderPath + '\' $LocalFolderPath = $Localfolderpath.Substring(0,$Localfolderpath.Length -1) } if ($S3DestinationFolder.Substring($S3DestinationFolder.Length -1) -eq '\') { #$LocalFolderPath = $LocalFolderPath + '\' $S3DestinationFolder = $S3DestinationFolder.Substring(0,$S3DestinationFolder.Length -1) } set-location $LocalFolderPath $LocalFolderPath = $PWD.Path Start-Transcript "AWS-S3Upload.log" -Append "`n`n`n`n`n`n`n`n`n`n" WriteLabel "Script start time: $OstartTime" WriteAction "Getting sub directories" $Folders = Get-ChildItem -Path $LocalFolderPath -Directory -Recurse -Force | select FullName WriteAction "Getting list of all files" $allFiles = Get-ChildItem -Path $LocalFolderPath -File -Recurse -Force | select FullName WriteAction "Getting folder count" $FoldersCount = $Folders.count WriteAction "Getting file count" $allFilesCount = $allFiles.count $i = 0 foreach ($Folder in $Folders.fullname) { $UploadFolder = $Folder.Substring($LocalFolderPath.length) $Source = $Folder $Destination = $S3DestinationFolder + $UploadFolder if ($ShowProgress) { $i++ $Percent = [math]::Round($($($i/$FoldersCount*100))) Write-Progress -Activity "Processing folder: $i out of $FoldersCount" -Status "Overall Upload Progress: $Percent`% || Current Upload Folder Name: $UploadFolder" -PercentComplete $Percent } "`n`n" "_" * $("[$(get-date)]:: Local Folder Name : $UploadFolder".Length) WriteInfo "Local Folder Name : $UploadFolder" WriteInfo "S3 Folder path : $Destination" WriteAction "Getting folder size" $Files = Get-ChildItem -Force -File -Path $Source | Measure-Object -sum Length Get-ItemSize $Files.sum "Folder" if ((Get-S3Object -BucketName $BucketName -KeyPrefix $Destination -MaxKey 2).count -lt "2") { WriteAction "Folder does not exist" WriteAction "Uploading all files" WriteInfo ("Upload File Count : " + $files.count) $startTime = get-date WriteInfo "Upload Start Time : $startTime" Write-S3Object -BucketName $BucketName -KeyPrefix $Destination -Folder $Source -Verbose -ConcurrentServiceRequest 100 $stopTime = get-date WriteInfo "Upload Finished Time : $stopTime" $elapsedTime = $stopTime - $StartTime WriteInfo ("Time Elapsed : " + $elapsedTime.days + " Days, " + $elapsedTime.hours + " Hours, " + $elapsedTime.minutes + " Minutes, " + $elapsedTime.seconds+ " Seconds") Calculate-TransferSpeed $files.Sum $elapsedTime.TotalSeconds #sleep 10 } else { WriteAction "Getting list of local files in local folder to transfer" $fFiles = Get-ChildItem -Force -File -Path $Source WriteAction "Counting files" $fFilescount = $ffiles.count WriteInfo "Upload File Count : $fFilescount" $j=0 foreach ($fFile in $fFiles) { if ($ShowProgress) { $j++ $fPercent = [math]::Round($($($j/$fFilescount*100))) Write-Progress -Activity "Processing File: $j out of $fFilescount" -Id 1 -Status "Current Progress: $fPercent`% || Processing File: $ffile" -PercentComplete $fPercent } #WriteAction "Getting S3 bucket objects" $S3file = Get-S3Object -BucketName $BucketName -Key "$Destination\$ffile" $s3obj = $S3file.key -replace "/","\" if ("$S3DestinationFolder$UploadFolder\$ffile" -eq $s3obj -and $S3file.size -ge $ffile.Length) { WriteWarning "File exists: $s3obj" } else { WriteAction "Uploading file : $ffile" Get-ItemSize $fFile.Length "File" $startTime = get-date WriteInfo "Upload Start Time : $startTime" Write-S3Object -BucketName $BucketName -File $fFile.fullname -Key "$Destination\$fFile" -ConcurrentServiceRequest 100 -Verbose $stopTime = get-date WriteInfo "Upload Finished Time : $stopTime" $elapsedTime = $stopTime - $StartTime WriteInfo ("Time Elapsed : " + $elapsedTime.days + " Days, " + $elapsedTime.hours + " Hours, " + $elapsedTime.minutes + " Minutes, " + $elapsedTime.seconds+ " Seconds") Calculate-TransferSpeed $fFile.Length $elapsedTime.TotalSeconds break } } } } $OstopTime = get-date "Script Finished Time : $OstopTime" $elapsedTime = $OstopTime - $OStartTime "Time Elapsed : " + $elapsedTime.days + " Days, " + $elapsedTime.hours + " Hours, " + $elapsedTime.minutes + " Minutes, " + $elapsedTime.seconds+ " Seconds" stop-transcript } ``` Run the script in your AWS Powershell instance and it will create a cmdlet or function. You can use it like this: **Sync-ToS3Bucket -BucketName** *YouS3BucketName* **-LocalFolderPath** *"C:\AmazonDrive\"* **-S3DestinationFolder** *YourDestinationS3folderName* -**ShowProgress:$true** * make sure to use relative path * Make sure you have initiated your defaultAWSconfiguration by running `Initialize-AWSDefaultConfiguration` * By default, the script will not show progress which is better for performance, but you can turn it on by using switch `-showProgress:$true` * The script will create a folder structure as well * You can use it to sync a local folder to S3. If the folder doesn't exist on S3, then the script will upload the whole folder. If the folder exists, then the script will go through each file on a local folder and make sure it exists on S3. I am still working on improving the script and will publish it on my GitHub profile. Let me know if you have any feedback. Some screenshot: [![enter image description here](https://i.stack.imgur.com/BKCHx.png)](https://i.stack.imgur.com/BKCHx.png) [![enter image description here](https://i.stack.imgur.com/W6Yws.png)](https://i.stack.imgur.com/W6Yws.png) Upvotes: 3
2018/03/15
1,235
3,467
<issue_start>username_0: I have a table containing: ``` table = [[1,'THEINCREDIBLES'],[2,'IRONMAN']] ``` and I want to convert the words in each list in table into its numeric representation (ASCII). I've tried: ``` movie = 'THEINCREDIBLES' h = 0 for c in movie: h = h + ord(c) print(h) ``` and it works but if I were to use a list of lists as table above, I'm getting an error saying `ord expected string of length 1` ``` table = [[1,'THEINCREDIBLES'],[2,'IRONMAN']] h = 0 for c in table: h = h + ord(c) print(h) ``` edit for @Sphinx I've done: ``` table = [[1,'THEINCREDIBLES'],[2,'IRONMAN']] h = 0 ordlist = [] for row in table: for c in row[1]: h = h + ord(c) ordlist.append(row[0]) oralist.append(h) h = 0 print(ordlist) ``` and my output is now: ``` [1,1029,2,532] ``` which is almost close to what I've wanted which is: ``` [[1,1029],[2,532]] ``` how do i enclose each ordinal representation into individual list within a list as above? Do i introduce a new list for this purpose?<issue_comment>username_1: You have lists within your your `table` list. This can be unravelled via a list compression. Below are some examples relating to your data. ``` movie = 'THEINCREDIBLES' h1 = list(map(ord, movie)) # [84, 72, 69, 73, 78, 67, 82, 69, 68, 73, 66, 76, 69, 83] table = [['THEINCREDIBLES'],['IRONMAN']] h2 = [list(map(ord, m[0])) for m in table] # [[84, 72, 69, 73, 78, 67, 82, 69, 68, 73, 66, 76, 69, 83], # [73, 82, 79, 78, 77, 65, 78]] ``` Upvotes: 0 <issue_comment>username_2: Ord() only works on characters. Python represents characters as a string of length one instead of an object in memory with only enough space for a single character. In other words, it doesn't make a distinction between strings and characters. You've got to convert the strings one character at a time. [edit] The answer posted the same time as mine suggesting to use ord() in a map function is a good solution. The core concept, though, is that you're passing one character at a time to ord(). Upvotes: 0 <issue_comment>username_3: for first loop (`for item in table`), item will be one list, not one character as your expected. So you need to loop again for item[0] to get each character then ord. Below is the straightforward way: ``` table = [['THEINCREDIBLES'],['IRONMAN']] result = [] for row in table: h = 0 for c in row[0]: h = h + ord(c) result.append(h) print(result) ``` Also you can use map and recude to sum ord of each character in your table. The codes like below: ``` from functools import reduce table = [['THEINCREDIBLES'],['IRONMAN']] print(list(map(lambda item: reduce(lambda pre, cur : pre + ord(cur), item[0], 0), table))) ``` Both above codes Output: ``` [1029, 532] [Finished in 0.186s] ``` Upvotes: 1 <issue_comment>username_4: ``` tables = [['THEINCREDIBLES'],['IRONMAN']] for table in tables: t= ''.join(table) h = 0 for c in t: h = h + ord(c) print(h) ``` Upvotes: 1 <issue_comment>username_5: The `bytes` type may do just what you want, it transforms a string into an immutable sequence of ascii values. ``` title = 'THEINCREDIBLES' sum(bytes(title.encode())) # 1029 ``` Now what you need is to apply this only to the nested strings in your `table`. ``` table = [[1, 'THEINCREDIBLES'], [2, 'IRONMAN']] new_table = [[id, sum(bytes(title.encode()))] for id, title in table] # new_table: [[1, 1029], [2, 532]] ``` Upvotes: 1
2018/03/15
507
1,754
<issue_start>username_0: I can upload my images while i'm working on local but when I moved my site to host it doesn't upload images while get names of them in database, my `filesystems.php` ``` 'default' => env('FILESYSTEM_DRIVER', 'local'), disks' => [ 'local' => [ 'driver' => 'local', 'root' => public_path('images/'), ], .... ``` sample of my upload codes: ``` if ($request->hasFile('imageOne')) { $imageOne = $request->file('imageOne'); $filename = 'productone' . '-' . time() . '.' . $imageOne->getClientOriginalExtension(); $location = public_path('images/'); $request->file('imageOne')->move($location, $filename); $product->imageOne = $filename; } ``` Issue: > > In host i get uploaded `image name in database`, but no image in my > `public/images` folder. > > > any idea? UPDATE ====== I found interesting folder in my host, as I moved all my `public` folder files to server `public_html` now it created another folder in my root called `public` and inside that has `images` folder including all images i uploaded so far! **Questions:** 1. Why laravel created new `public/images` folder in my root instead of using my `public_html`? 2. How to fix it?<issue_comment>username_1: SOLVED ====== I added this code to my `public_html/index.php` file and it's working now. ``` // set the public path to this directory $app->bind('path.public', function() { return __DIR__; }); ``` Hope it helps. Upvotes: 4 [selected_answer]<issue_comment>username_2: I change the public path inside my save image controller to look like this: ``` if (request()->imagefile->move(public_path('../../public_html/destination'), $imageName)) echo "Yap"; else echo "Nop"; ``` Upvotes: -1
2018/03/15
1,574
6,797
<issue_start>username_0: I am trying to call an API asynchronously using Spring's Async and using the ThreadPoolTaskExecutor in my Thread Config which goes: ``` @Configuration @EnableAsync public class ThreadConfig extends AsyncConfigurerSupport { @Value("${core.pool.size}") private int corePoolSize; @Value("${max.pool.size}") private int maxPoolSize; @Value("${queue.capacity}") private int queueCapacity; @Override @Bean public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(corePoolSize); executor.setMaxPoolSize(maxPoolSize); executor.setQueueCapacity(queueCapacity); executor.setThreadNamePrefix("default_task_executor_thread"); executor.initialize(); return executor; } ``` The settings here are: ``` corePoolSize = 5; maxPoolSize = 10; QueueCapacity = 10; ``` I'm calling the Async service as follows: ``` for (String path : testList) { Future pro = services.invokeAPI(path); } ``` The testList has about 50 records. When I run this, the compiler processes 10 threads and calls the invokeAPI method 10 times after which it gives: ``` org.springframework.core.task.TaskRejectedException: Executor[java.util.concurrent.ThreadPoolExecutor@3234ad78[Running, pool size = 10, active threads = 10, queued tasks = 10, completed tasks = 0]] did not accept task: org.springframework.aop.interceptor.AsyncExecutionInterceptor$1@5c17b70 ``` I was assuming that it will wait for the current tasks to complete and re-assign the threads instead of throwing me the exception and terminating the program. What should I do to have all my 50 records call the invokeAPI method? Edit: the number of records in testList can change. Any suggestions please?<issue_comment>username_1: This is happening because of the size you are using for the pool. Since the size of the queue is 10 and the max threads you can have is 10, therefore after 20 tasks (10 running and 10 in queue) the executor starts rejecting the tasks. There are various ways to solve this problem. 1. Use unbounded queue. i.e. Don't specify the size of the queue and hence it will be able to hold all the tasks. Once the threads are free, the tasks will be submitted. 2. Provide a `RejectedExecutionHandler` which does something with the tasks. i.e. Runs them on the caller thread or discard them or something else (Depending on the use case). There are some of them already provided by Java like `CallerRunsPolicy`, `AbortPolicy`, `DiscardPolicy` and `DiscardOldestPolicy`. You can specify them like using `executor#setRejectedExecutionHandler`. 3. Provide your own Blocking Thread Pool Executor which blocks till the there is more room for tasks (Uses Semaphore). Here is an example of Blocking Executor ``` public class BlockingExecutor extends ThreadPoolExecutor { private final Semaphore semaphore; public BlockingExecutor(final int corePoolSize, final int poolSize, final int queueSize) { super(corePoolSize, poolSize, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>()); semaphore = new Semaphore(poolSize + queueSize); } @Override public void execute(final Runnable task) { boolean acquired = false; do { try { semaphore.acquire(); acquired = true; } catch (final InterruptedException e) { //do something here } } while (!acquired); try { super.execute(task); } catch (final RejectedExecutionException e) { semaphore.release(); throw e; } } protected void afterExecute(final Runnable r, final Throwable t) { super.afterExecute(r, t); semaphore.release(); } } ``` Upvotes: 4 <issue_comment>username_2: One way to approach this is by implementing a RejectedExecutionHandler policy with something like the below ``` import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadPoolExecutor; public class BlockCallerExecutionPolicy implements RejectedExecutionHandler { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { try { // based on the BlockingQueue documentation below should block until able to place on the queue... executor.getQueue().put(r); } catch (InterruptedException e) { throw new RejectedExecutionException("Unexpected InterruptedException while waiting to add Runnable to ThreadPoolExecutor queue...", e); } } } ``` What this does is cause the calling thread (likely the main thread) to wait until there's room on the blocking queue. Upvotes: 2 <issue_comment>username_3: Hy @<NAME>, According to @username_2's response: ``` import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadPoolExecutor; public class RejectedExecutionHandlerImpl implements RejectedExecutionHandler { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { try { executor.getQueue().put(r); } catch (InterruptedException e) { throw new RejectedExecutionException("There was an unexpected InterruptedException whilst waiting to add a Runnable in the executor's blocking queue", e); } } } ``` in order to have multi threading without TaskRejectedException, you have to implement a TaskRejectedHnadler, see below: ``` @Configuration @EnableAsync public class ThreadConfig extends AsyncConfigurerSupport { @Value("${core.pool.size}") private int corePoolSize; @Value("${max.pool.size}") private int maxPoolSize; @Value("${queue.capacity}") private int queueCapacity; @Override @Bean public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(corePoolSize); executor.setMaxPoolSize(maxPoolSize); executor.setQueueCapacity(queueCapacity); executor.setThreadNamePrefix("default_task_executor_thread"); // add a rejected execution handler executor.setRejectedExecutionHandler(new RejectedExecutionHandlerImpl()); executor.initialize(); return executor; } } ``` Another way is to use reactive **FLUX** with **synchronously method instead Async**: ``` Flux.just(dtos.toArray()) // in my case an ArrayList .parallel(corePoolSize) // 8 in my case .runOn(Schedulers.parallel()) .subscribe(dto -> computeService.compute((CastYourObject) dto)); ``` and you're done. Best. Upvotes: 3
2018/03/15
977
3,096
<issue_start>username_0: I'm having some trouble counting the number of occurrences of a key, while also keeping several values. Usually I will just do: ``` val a = file1.map(x => (x, 1)).reduceByKey(_ + _) ``` which gives the number of occurrences for each key. However, I also want to keep the values for each occurrence of a key, at the same time as counting the number of occurrences of the key. Something like this: ``` val a = file1.map(x => (x(1), (x(2), 1)).reduceByKey{case (x,y) => (x._1, y._1, x._2+y._2)} ``` For example: if the key `x(1)` is a country and `x(2)` is a city, I want to keep all the cities in a country, as well as knowing how many cities there are in a country.<issue_comment>username_1: It's complicated and redundant to keep the count of the cities together with its list. You can just collect all the cities, and add the size at the end: It is of course easier if you use the dataframe interface (assuming a dataframe `(key:Int, city:String)`) ``` import org.apache.spark.sql.{ functions => f} import spark.implicits._ df.groupBy($"key"). agg(f.collect_set($"city").as("cities")). withColumn("ncities", f.size($"cities")) ``` but you can do something similar with raw rdd (I am assuming in input tuples of `(id,city)` ) ``` rdd.map{ x => (x(0),Set(x(1)))}. reduceByKey{ case(x,y) => x ++ y }. map { case(x,y:Set[_]) => (x,y, y.size)} ``` Upvotes: 1 <issue_comment>username_2: In this case, I would recommend using a dataframe instead of a RDD, and use the `groupBy` and `agg` methods. You can easily convert an RDD to a dataframe using the `toDF` function, just make sure you import implicits first. Example assuming the RDD has two columns: ``` val spark = SparkSession.builder.getOrCreate() import spark.implicits._ val df = rdd.toDF("country", "city") ``` Then use the `groupBy` and aggregate the values you want. ``` df.groupBy("country").agg(collect_set($"city").as("cities"), count($"city").as("count")) ``` Upvotes: 0 <issue_comment>username_3: I would suggest you to go with `dataframes` as well as `dataframes` are *optimized and easy to use* than `rdds`. But if you want to learn about `reduceByKey` functionality (i.e. *keeping other information as you said city information*) then you can do something like below Lets say you have a `rdd` as ``` val rdd = sc.parallelize(Seq( ("country1", "city1"), ("country1", "city2"), ("country1", "city3"), ("country1", "city3"), ("country2", "city1"), ("country2", "city2") )) ``` Your tried `reducyByKey` would need some modification as ``` rdd.map(x => (x._1, (Set(x._2), 1))) //I have used Set to get distinct cities (you can use list or arrays or any other collection .reduceByKey((x,y)=> (x._1 ++ y._1, x._2 + y._2)) //cities are also summed and counts are also summed ``` which should give you ``` (country2,(Set(city1, city2),2)) (country1,(Set(city1, city2, city3),4)) ``` I hope the answer is helpful **If you want to learn reduceByKey in detail you can check my [detailed answer](https://stackoverflow.com/a/49166009/5880706)** Upvotes: 0
2018/03/15
709
2,464
<issue_start>username_0: I'm wondering if it is possible to add a custom rule or modify an existing rule - as mentioned in <https://docs.sonarqube.org/display/DEV/Adding+Coding+Rules> - to our SonarCloud instance. We've setup SonarCloud on a couple of private projects and I want to - for instance - modify rule 'php:S1068 - Unused private fields should be removed". In the framework that we're using, a private field with the name of "$db" shouldn't be marked as 'unused', because that framework uses that variable through reflection. Is it possible to add/modify such rules in SonarCloud?<issue_comment>username_1: From SonarCloud Team > > For custom rules, this is unfortunately not possible on SonarCloud - yet. (and I don't know when this is available - this is not in our short-term list) > > > Upvotes: 3 <issue_comment>username_2: AFAIK, you can partly modify (some) rules and you can disable them. I don't know how to add a new rule for a public project and we don't have any private one. To disable/modify the rule: 1. On your organization page, click on 'Quality Profiles' 2. Select the language you want to alter, and using the 'gear' setting button, copy existing (default) profile and set the new one as default. 3. You can now look for the rule you want to deactivate / modify in the 'Rules' tab Bellow is a screen from the current version. In our project, we have deactivates several Python rules: [![enter image description here](https://i.stack.imgur.com/1eOdg.png)](https://i.stack.imgur.com/1eOdg.png) Upvotes: 3 <issue_comment>username_3: Yes, you actually can do that (partialy)! Go to **"Quality Profiles"** of your organization, scroll down to the required-one, click **'triple dot'** button at the right of profile and select in drop-down menu **"Extend"**. [![Step №1](https://i.stack.imgur.com/i8gtp.png)](https://i.stack.imgur.com/i8gtp.png) Now you can change rules in your extended profile by opening it, selecting the rule you want to change and setting new walue of parameters you want (if possible). [![Step №2](https://i.stack.imgur.com/Kqj7P.png)](https://i.stack.imgur.com/Kqj7P.png) Now, it is possible to apply this profile as new default by selecting **"Set as Default"** from **'triple dot'** menu of that profile: [![Step №3](https://i.stack.imgur.com/n05Jb.png)](https://i.stack.imgur.com/n05Jb.png) --- P.S.: *The only trick here is you can only change parameters which are allowed to change* Upvotes: 0
2018/03/15
857
2,432
<issue_start>username_0: Given a ndarray of size `(n, 3)` with `n` around 1000, how to multiply together all elements for each row, fast? The (inelegant) second solution below runs in about 0.3 millisecond, can it be improved? ``` # dummy data n = 999 a = np.random.uniform(low=0, high=10, size=n).reshape(n/3,3) # two solutions def prod1(array): return [np.prod(row) for row in array] def prod2(array): return [row[0]*row[1]*row[2] for row in array] # benchmark start = time.time() prod1(a) print time.time() - start # 0.0015 start = time.time() prod2(a) print time.time() - start # 0.0003 ```<issue_comment>username_1: `np.prod` accepts an axis argument: ``` np.prod(a, axis=1) ``` With `axis=1`, the column-wise product is computed for each row. *Sanity check* ``` assert np.array_equal(np.prod(a, axis=1), prod1(a)) ``` *Performance* ``` 17.6 µs ± 146 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) ``` (1000x speedup) Upvotes: 3 <issue_comment>username_2: **Improving performance further** At first a general rule of thumb. You are working with numerical arrays, so use arrays and not lists. Lists may look somewhat like a general array, but beeing completely different in the backend and absolutely not suteable for most numerical calculations. If you write a simple code using Numpy-Arrays you can gain performance by simply jitting it as shown beyond. If you use lists you can more or less rewrite your code. ``` import numpy as np import numba as nb @nb.njit(fastmath=True) def prod(array): assert array.shape[1]==3 #Enable SIMD-Vectorization (adding some performance) res=np.empty(array.shape[0],dtype=array.dtype) for i in range(array.shape[0]): res[i]=array[i,0]*array[i,1]*array[i,2] return res ``` Using `np.prod(a, axis=1)` isn't a bad idea, but the performance isn't really good. For an array with only 1000x3 the function call overhead is quite significant. This can be completely avoided, when using the jitted prod function in another jitted function. **Benchmarks** ``` # The first call to the jitted function takes about 200ms compilation overhead. #If you use @nb.njit(fastmath=True,cache=True) you can cache the compilation result for every successive call. n=999 prod1 = 795 µs prod2 = 187 µs np.prod = 7.42 µs prod 0.85 µs n=9990 prod1 = 7863 µs prod2 = 1810 µs np.prod = 50.5 µs prod 2.96 µs ``` Upvotes: 3 [selected_answer]
2018/03/15
2,576
8,315
<issue_start>username_0: I have an Intel NUC (I5) and Raspberry-Pi Model-B . I tried to create a kubernetes cluster by making the Intel-NUC as master node and Raspberry-Pi as worker node.When I try the above set up, I see that the worker node crashing all the time . Here's the output . This happens only with the above set up. If I try creating a cluster with two Raspberry-Pis (One master and one worker node), it works fine. What am I doing wrong? ``` sudo kubectl get pods --all-namespaces NAMESPACE NAME READY STATUS RESTARTS AGE kube-system etcd-ubuntu 1/1 Running 0 13h kube-system kube-apiserver-ubuntu 1/1 Running 0 13h kube-system kube-controller-manager-ubuntu 1/1 Running 0 13h kube-system kube-dns-6f4fd4bdf-fqmmt 3/3 Running 0 13h kube-system kube-proxy-46ddk 0/1 CrashLoopBackOff 5 3m kube-system kube-proxy-j48fc 1/1 Running 0 13h kube-system kube-scheduler-ubuntu 1/1 Running 0 13h kube-system kubernetes-dashboard-5bd6f767c7-nh6hz 1/1 Running 0 13h kube-system weave-net-2bnzq 2/2 Running 0 13h kube-system weave-net-7hr54 1/2 CrashLoopBackOff 3 3m ``` I examined the logs for kube-proxy and found the following entry `Logs from kube-proxy standard_init_linux.go:178: exec user process caused "exec format error"` This seem to stem from the issue that the image picked up is arm arch as oppose x86 arch. Here's the yaml file ``` { "kind": "Pod", "apiVersion": "v1", "metadata": { "name": "kube-proxy-5xc9c", "generateName": "kube-proxy-", "namespace": "kube-system", "selfLink": "/api/v1/namespaces/kube-system/pods/kube-proxy-5xc9c", "uid": "a227b43b-27ef-11e8-8cf2-b827eb03776e", "resourceVersion": "22798", "creationTimestamp": "2018-03-15T01:24:40Z", "labels": { "controller-revision-hash": "3203044440", "k8s-app": "kube-proxy", "pod-template-generation": "1" }, "ownerReferences": [ { "apiVersion": "extensions/v1beta1", "kind": "DaemonSet", "name": "kube-proxy", "uid": "361aca09-27c9-11e8-a102-b827eb03776e", "controller": true, "blockOwnerDeletion": true } ] }, "spec": { "volumes": [ { "name": "kube-proxy", "configMap": { "name": "kube-proxy", "defaultMode": 420 } }, { "name": "xtables-lock", "hostPath": { "path": "/run/xtables.lock", "type": "FileOrCreate" } }, { "name": "lib-modules", "hostPath": { "path": "/lib/modules", "type": "" } }, { "name": "kube-proxy-token-kzt5h", "secret": { "secretName": "kube-proxy-token-kzt5h", "defaultMode": 420 } } ], "containers": [ { "name": "kube-proxy", "image": "gcr.io/google_containers/kube-proxy-arm:v1.9.4", "command": [ "/usr/local/bin/kube-proxy", "--config=/var/lib/kube-proxy/config.conf" ], "resources": {}, "volumeMounts": [ { "name": "kube-proxy", "mountPath": "/var/lib/kube-proxy" }, { "name": "xtables-lock", "mountPath": "/run/xtables.lock" }, { "name": "lib-modules", "readOnly": true, "mountPath": "/lib/modules" }, { "name": "kube-proxy-token-kzt5h", "readOnly": true, "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount" } ], "terminationMessagePath": "/dev/termination-log", "terminationMessagePolicy": "File", "imagePullPolicy": "IfNotPresent", "securityContext": { "privileged": true } } ], "restartPolicy": "Always", "terminationGracePeriodSeconds": 30, "dnsPolicy": "ClusterFirst", "serviceAccountName": "kube-proxy", "serviceAccount": "kube-proxy", "nodeName": "udubuntu", "hostNetwork": true, "securityContext": {}, "schedulerName": "default-scheduler", "tolerations": [ { "key": "node-role.kubernetes.io/master", "effect": "NoSchedule" }, { "key": "node.cloudprovider.kubernetes.io/uninitialized", "value": "true", "effect": "NoSchedule" }, { "key": "node.kubernetes.io/not-ready", "operator": "Exists", "effect": "NoExecute" }, { "key": "node.kubernetes.io/unreachable", "operator": "Exists", "effect": "NoExecute" }, { "key": "node.kubernetes.io/disk-pressure", "operator": "Exists", "effect": "NoSchedule" }, { "key": "node.kubernetes.io/memory-pressure", "operator": "Exists", "effect": "NoSchedule" } ] }, "status": { "phase": "Running", "conditions": [ { "type": "Initialized", "status": "True", "lastProbeTime": null, "lastTransitionTime": "2018-03-15T01:24:45Z" }, { "type": "Ready", "status": "False", "lastProbeTime": null, "lastTransitionTime": "2018-03-15T01:35:41Z", "reason": "ContainersNotReady", "message": "containers with unready status: [kube-proxy]" }, { "type": "PodScheduled", "status": "True", "lastProbeTime": null, "lastTransitionTime": "2018-03-15T01:24:46Z" } ], "hostIP": "192.168.178.24", "podIP": "192.168.178.24", "startTime": "2018-03-15T01:24:45Z", "containerStatuses": [ { "name": "kube-proxy", "state": { "waiting": { "reason": "CrashLoopBackOff", "message": "Back-off 5m0s restarting failed container=kube-proxy pod=kube-proxy-5xc9c_kube-system(a227b43b-27ef-11e8-8cf2-b827eb03776e)" } }, "lastState": { "terminated": { "exitCode": 1, "reason": "Error", "startedAt": "2018-03-15T01:40:51Z", "finishedAt": "2018-03-15T01:40:51Z", "containerID": "docker://866dd8e7175bd71557b9dcfc84716a0f3abd634d5d78c94441f971b8bf24cd0d" } }, "ready": false, "restartCount": 8, "image": "gcr.io/google_containers/kube-proxy-arm:v1.9.4", "imageID": "docker-pullable://gcr.io/google_containers/kube-proxy-arm@sha256:c6fa0de67fb6dbbb0009b2e6562860d1f6da96574d23617726e862f35f9344e7", "containerID": "docker://866dd8e7175bd71557b9dcfc84716a0f3abd634d5d78c94441f971b8bf24cd0d" } ], "qosClass": "BestEffort" } } ```<issue_comment>username_1: it is perfectly possible to do that, but you need to ensure that you launch pods for given cpu architecture on appropriate machines. Use nodeSelector or Node. Otherwise, you get what you experience - amd64 binaries failing to run on arm, or vice versa. Hint: use `beta.kubernetes.io/arch` label to distinct between cpu architectures. Upvotes: 1 <issue_comment>username_2: Yes, it's possible and i've just done that for one of my customers. Basically there is an issue that the KubeProxy DaemonSet deployed automatically on the master is compiled to x64 - because you wanted that the master will be x64 and the nodes will be ARM. When you add ARM nodes to the cluster, the DaemonSet tries to deploy the x64 image on them, and fails. You'll need to edit the default DaemonSet after installation to select only x64 nodes, and deploy another DaemonSet for ARM nodes. This gist will walk you through: [Multiplatform (amd64 and arm) Kubernetes cluster setup](https://gist.github.com/squidpickles/dda268d9a444c600418da5e1641239af) Hope this helps, Ofir. Upvotes: 4 [selected_answer]
2018/03/15
598
2,154
<issue_start>username_0: I'm using a function to create multiple buttons for my game. ``` func createButton() { let button = UIButton() button.setTitle("", for: .normal) button.frame = CGRect(x:15, y: 50, width: 200, height:100) button.backgroundColor = UIColor.red self.view.addSubview(button) button.addTarget(self, action: Selector(("buttonPressed:")), for: .touchUpInside) } ``` I call this function once for testing in viewDidLoad function, but I don't know what code I should put into my buttonPressed() function for the color of my button to change? I tried doing ``` self.backgroundColor = UIColor.blue ``` but that didn't work. I also tried using UIButton and button instead of self, but both of those didn't work either. What should I do?<issue_comment>username_1: Just make the button an instance property. ``` let changingButton = UIButton() func createButton() { changingButton.backgroundColor = UIColor.red changingButton.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside) } @objc func buttonPressed() { changingButton.backgroundColor = UIColor.blue } ``` Upvotes: 0 <issue_comment>username_2: Your code isn't clean Swift 4 code. Here's how to do this: * Create your button like you are, but change `Selector` to `#selector`: ``` func createButton() { let button = UIButton() button.setTitle("", for: .normal) button.frame = CGRect(x:15, y: 50, width: 200, height:100) button.backgroundColor = UIColor.red self.view.addSubview(button) button.addTarget(self, action: #selector((buttonPressed)), for: .touchUpInside) } ``` * Use the `sender` that is automatically added: ``` @objc func buttonPressed(sender: UIButton) { sender.backgroundColor = UIColor.blue } ``` Additionally may I offer a few suggestions? * Check the background color *before* changing it. No sense in needlessly changing a button that is already blue. * Since you aren't setting the title to your button, set the `tag` property (you can even add this as a parameter to `createButton`). This way you can know *which* button was tapped. Upvotes: 3 [selected_answer]
2018/03/15
2,186
7,880
<issue_start>username_0: During my project, I am confronted with C program. 1. As shown below, `htmp` is a struct pointer. We first allocate a memory for it. But why should we allocate a memory for its element `word` again? 2. If it's essential to allocate memory for each element of a struct, why not allocate memory for its other elements, `id` and `next`? ``` #define HASHREC bitewisehash typedef struct hashrec { char *word; long long id; struct hashrec *next; } HASHREC; /* Move-to-front hashing and hash function from <NAME>, http://www.seg.rmit.edu.au/code/zwh-ipl/ */ /* Simple bitwise hash function */ unsigned int bitwisehash(char *word, int tsize, unsigned int seed) { char c; unsigned int h; h = seed; for (; (c =* word) != '\0'; word++) h ^= ((h << 5) + c + (h >> 2)); return((unsigned int)((h&0x7fffffff) % tsize)); } /* Insert string in hash table, check for duplicates which should be absent */ void hashinsert(HASHREC **ht, char *w, long long id) { HASHREC *htmp, *hprv; unsigned int hval = HASHFN(w, TSIZE, SEED); for (hprv = NULL, htmp = ht[hval]; htmp != NULL && scmp(htmp->word, w) != 0; hprv = htmp, htmp = htmp->next); if (htmp == NULL) { htmp = (HASHREC *) malloc(sizeof(HASHREC)); # allocate memory for htmp htmp->word = (char *) malloc(strlen(w) + 1); # why allocate memory again ? strcpy(htmp->word, w); # htmp->id = id; # why not allocate memory for htmp->id ? htmp->next = NULL; # why nor allocate memory for htmp->next? if (hprv == NULL) ht[hval] = htmp; else hprv->next = htmp; } else fprintf(stderr, "Error, duplicate entry located: %s.\n",htmp->word); return; } ```<issue_comment>username_1: When you allocate the memory for the struct, only enough memory to hold a pointer is allocated for the member `word`, that pointer also has to point to valid memory which you can then allocate. Without making it point to valid memory, it's value is *indeterminate* and trying to dereference such pointer with an *indeterminate* value is undefined behavior. Upvotes: 1 <issue_comment>username_2: You need to separate in your mind two things (1) in what memory is the thing I want to store stored?; and (2) what variable (pointer) holds the address to where it is stored so I can find it again. You first declare two pointers to `struct hashrec`: ``` HASHREC *htmp, *hprv; ``` A pointer is nothing but a variable that holds the address to something else as its value. When you first declare the two pointers, they are *uninitialized* and hold no address. You then, in a rather awkward manner, initialize both pointers within a `for` loop declaration, e.g. `hprv = NULL, htmp = ht[hval]` and later `hprv = htmp, htmp = htmp->next` so presumably both pointers now hold an address and point somewhere. Following the loop (with an empty body), you test `if (htmp == NULL)`, meaning that `htmp` does not point to an address (which can be the case if you have found the hash-index of interest empty). Then in order to provide storage for one `HASHREC` (e.g. a `struct hashrec`) you need to allocate storage so you have a block of memory in which to store the thing you want to store. So you allocate a block to hold one struct. (See: [**Do I cast the result of malloc?**](http://stackoverflow.com/q/605845/995714)) Now, look at what you have allocated memory for: ``` typedef struct hashrec { char *word; long long id; struct hashrec *next; } HASHREC; ``` You have allocated storage for a struct that contains (1) a `char *word;` (a pointer to char - 8-bytes (4-bytes on x86)); (2) a `long long id;` (8-bytes on both) and (3) a pointer to hold the address of the next `HASHREC` in the sequence. There is no question that `id` can hold a `long long` value, but what about `word` and `next`? They are both pointers. What do pointers hold? The address to where the thing they point to can be found. Where can `word` be found? The thing you want is currently pointed to by `w`, but there is no guarantee that `w` will continue to hold the word you want, so you are going to make a copy and store it as part of the `HASHREC`. So you see: ``` htmp->word = malloc(strlen(w) + 1); /* useless cast removed */ ``` Now what does `malloc` return? It returns the address to the beginning of a new block of memory, `strlen(w) + 1` bytes long. Since a pointer holds the value of something else as its value, `htmp->word` now stores the address to the beginning of the new block of memory as its value. So `htmp->word` *"points"* to the new block of memory and you can use `htmp->word` as a reference to refer to that block of memory. What happens next is important: ``` strcpy(htmp->word, w); # htmp->id = id; # why not allocate memory for htmp->id ? htmp->next = NULL; # why nor allocate memory for htmp->next? ``` `strcpy(htmp->word, w);` copies `w` into that new block of memory. `htmp->id = id;` assigns the value of `id` to `htmp->id` and **no allocation is required** because when you allocate: ``` htmp = malloc(sizeof(HASHREC)); /* useless cast removed */ ``` You allocate storage for a (1) `char *` pointer, (2) a `long long id;` and (3) a `struct hashrec*` pointer -- you have *already allocated* for a `long long` so `htmp->id` can store the value of `id` in the memory for the `long long`. ``` htmp->next = NULL; # why nor allocate memory for htmp->next? ``` What is it that you are attempting to store that would require new allocation for `htmp->next`? (hint: nothing currently) It will point to the next `struct hashrec`. Currently it is initialize to `NULL` so that the next time you iterate to the end of all the `struct hashrec next` pointers, you know you are at the end when you reach `NULL`. Another way to think of it is that the previous `struct hashrec next` can now point to this node you just allocated. Again no additional allocation is required, the previous node `->next` pointer simply points to the next node in sequence, not requiring any specific new memory to be allocated. It is just used as a reference to refer (or point to) the next node in the chain. There is a lot of information here, but when you go through the thought process of determining (1) in what memory is the thing I want to store stored?; and (2) what variable (pointer) holds the address to where it is stored so I can find it again... -- things start to fall into place. Hope this helps. Upvotes: 3 [selected_answer]<issue_comment>username_3: `malloc(size)` will allocate memory of given size and returns starting address of the allocated memory. Addresses are stored in pointer variables. In `char *word`, variable `word` is of pointer type and it can only hold a pointer of type char i.e., address of a character data in memory. so, when you allocate memory to the struct type variable `htmp`, it will allocate memory as follows, **2** bytes for `*word`, **4** bytes for `id` and **2** bytes for `*next` Now, lets assume that you want to store following into your struct: ``` { word = Elephant id = 1245 } ``` Now you can save id directly into `id` member by doing this `htmp->id = 1245`. But you also want to save a word "**Elephant**" in your struct, how to achieve this? `htmp->word = 'Elephant'` will cause **error** because word is a pointer. So, now you allocate memory to store actual string literal **Elephant** and store the starting address in `htmp->word`. Instead of using `char *word` in your struct, you could have used `char word[size]` where no need to allocate memory separately for member `word`. The reason behind not doing so, is that you want to select some random size for word, which can waste memory if you are storing less characters and which even fall shot if word is too big. Upvotes: 1
2018/03/15
431
1,485
<issue_start>username_0: We are starting to use the MySQL json datatype. Is there any recommended best practices when storing default values as `NULL` or `{}` for the JSON datatype? What are the PROs and CONs for each?<issue_comment>username_1: This would depend upon your business use-case. * `null` is usually meant to indicate that the value is unknown/doesn't exists. * `{}` on the other hand means that the value is known/does exist and the known value is an empty JSON object `{}` Upvotes: 2 <issue_comment>username_2: PhpMyAdmin uses the text `null` by default, if you add a new JSON column to existing rows. Note this is different from *`NULL`*. *`NULL`* means unknown/doesn't exist in the database, `null` means unknown/doesn't exist after converted to JSON. `{}` is an empty JSON object. Upvotes: 1 <issue_comment>username_3: Keep in mind that MySQL did not allow non-null default values for JSON columns prior to version 8.0.13 (released on 22/10/2018), according to the [documentation](https://dev.mysql.com/doc/refman/8.0/en/json.html): > > Prior to MySQL 8.0.13, a JSON column cannot have a non-NULL default value. > > > If you try it on a previous version you get an error: `BLOB, TEXT, GEOMETRY or JSON column 'column_name' can't have a default value` So if backwards compatibility is a requirement, this is a con for `{}`. Upvotes: 2 <issue_comment>username_4: [42000][1101] BLOB, TEXT, GEOMETRY or JSON column 'xxxx' can't have a default value. Upvotes: 0
2018/03/15
486
1,744
<issue_start>username_0: I'm banging my head against a wall here. Just started learning SQL, I have three tables like this: Table CD (num, producer, band\_name, cd\_name) Table BandSingers (band\_name, singer\_id) Table Singer (id, name) I'm trying to figure out how to get the name of the singer that shows up on the most Cds by going through the band, and I'm not sure how to go about it but here's what I've got: ``` select id, name from Singer, BandSingers where Singer.id = (select singer_id from BandSingers where band_name = (select band_name from CD where max(count(band_name)))); ``` think I'm way off but help is appreciated, thanks!<issue_comment>username_1: figured it out, I manipulated the syntax to a 'group by' and 'having', and it worked out. Upvotes: -1 <issue_comment>username_2: Try this dude ``` SELECT DISTINCT S.NAME FROM SINGER s JOIN BANDSINGERS bs ON s.singer_id = bs.singer_id JOIN CD c ON c.BAND_NAME = bs.band_name WHERE c.band_name = (SELECT band_name FROM (SELECT band_name,COUNT(band_name) cnt FROM CD GROUP BY band_name HAVING COUNT (band_name)=(SELECT MAX(mycount) FROM ( SELECT band_name, COUNT(band_name) mycount FROM CD GROUP BY band_name)))) ``` Upvotes: 0 <issue_comment>username_3: please try this instead ``` Select Top 1 c.id, c.[name], Count(a.band_name) From CD a left join BandSingers b on b.band_name = a.band_name left join Singer c on c.id = b.singer_id Group by c.id, c.[name] Order by 3 desc ``` Upvotes: 0
2018/03/15
812
2,888
<issue_start>username_0: I'm testing some prototype application. We have json data with nested fields. I'm trying to pull some field using following json and code: ``` Feed: {name: "test",[Record: {id: 1 AllColumns: {ColA: "1",ColB: "2"}}...]} Dataset completeRecord = sparkSession.read().json(inputPath); final Dataset feed = completeRecord.select(completeRecord.col("Feed.Record.AllColumns")); ``` I have around 2000 files with such records. I have tested some files individually and they are working fine. But for some file I am getting below error on second line: > > org.apache.spark.sql.AnalysisException: Can't extract value from > Feed#8.Record: need struct type but got string; > > > I'm not sure what is going on here. But I would like to either handle this error gracefully and log which file has that record. Also, is there any way to ignore this and continue with rest of the files?<issue_comment>username_1: The exception says that one of the json files differs in its structure and that the path `Feed.Record.AllColumns` does not exist in this specific file. Based on this method ```java private boolean pathExists(Dataset df, String path) { try { df.apply(path); return true; } catch(Exception ex){ return false; } } ``` you can decide if you execute the `select` or log an error message: ```java if(pathExists(completeRecord, "Feed.Record.AllColumns") { final Dataset feed = completeRecord.select(completeRecord.col("Feed.Record.AllColumns")); //continue with processing } else { //log error message } ``` Upvotes: 2 <issue_comment>username_2: Answering my own question based on what I have learned. There are couple of ways to solve it. Spark provides options to ignore corrupt files and corrupt records. To ignore corrupt files one can set following flag to true: > > spark.sql.files.ignoreCorruptFiles=true > > > For more fine grained control and to ignore bad records instead of ignoring the complete file. You can use one of three modes that Spark api provides. > > According to [DataFrameReader](https://spark.apache.org/docs/2.0.2/api/java/org/apache/spark/sql/DataFrameReader.html#json(java.lang.String...)) api > > > > > > > mode (default **PERMISSIVE**): allows a mode for dealing with corrupt > > records during parsing. > > **PERMISSIVE** : sets other fields to null when it > > meets a corrupted record, and puts the malformed string into a new > > field configured by columnNameOfCorruptRecord. When a schema is set by > > user, it sets null for extra fields. > > > > **DROPMALFORMED** : ignores the whole > > corrupted records. > > > > **FAILFAST** : throws an exception when it meets > > corrupted records. > > > > > > > > > PERMISSIVE mode worked really well for me but when I provided my own schema Spark filled missing attributes with null instead of marking it corrupt record. Upvotes: 3
2018/03/15
514
1,902
<issue_start>username_0: I've got a list of Person objects like this: ``` list.add(new Person("John", 20)); //person is just name and age list.add(new Person("Maria", 21)); list.add(new Person("John", 40)); list.add(new Person("Carl", 10)); ``` The resulting list must have no persons with the same name, regardless of age, so only 3 elements would survive. How can this be accomplished using Java 8 lambda expressions?<issue_comment>username_1: You can try the following: ``` Set unique = new HashSet<>(); list.removeIf(e -> !unique.add(e.getName())); ``` Note, that the Person class needs to have a getter to return the name of the person. Upvotes: 2 <issue_comment>username_2: Overwrite the `hashCode()` and `equals()`. Then you can use this: ``` List collect = list.stream().distinct().collect(Collectors.toList()); ``` Upvotes: 0 <issue_comment>username_3: Turn the list into a map in which they key is Person::getName and the value is the object itself, and if they are equal choose the first one, then get the map values which is a Collection, and lastly convert to a List ``` list = list.stream().collect(Collectors.toMap(Person:getName, Function.Identity(), (a, b) -> a)).values().stream().collect(Collections.toList()); ``` Upvotes: 0 <issue_comment>username_4: This could easily be done using `Comparator`. As this is really flexible to use and also allows multiple comparison criteria as per your need. See code below:- ``` Set expectedOutput = new TreeSet<>((person1, person2) -> person1.getName().equals(person2.getName()) ? 0 : 1 ); list.listIterator().forEachRemaining(expectedOutput::add); ``` I personally will avoid overriding equals for a fluctuating criteria. For example, If i say that my objects are equal if names are equal in one scenario and in other scenario I say my objects are equal if ages are equal. Then it's better to use `comparator`. Upvotes: 0
2018/03/15
681
2,007
<issue_start>username_0: I have this kind of strings in a table: * AM-65-800 * AM-75/86-650 * D-27-600 What I'm trying to do is to get only the middle part, for example: * 65 * 75/86 * 27 Basically the substring after and before the '-' Char I tried this (from an example in here): ``` SELECT SUBSTRING(Product.Name, LEN(LEFT(Product.[Name], CHARINDEX ('-', Product.[Name]))) + 1, LEN(Product.[Name]) - LEN(LEFT(Product.[Name], CHARINDEX ('-', Product.[Name]))) - LEN(RIGHT(Product.[Name], LEN(Producto.[Name]) - CHARINDEX ('-', Product.[Name]))) - 1) FROM Product ``` But it gives me this error: ``` [42000] [Microsoft][SQL Server Native Client 10.0][SQL Server]Invalid length parameter passed to the LEFT or SUBSTRING function. (537) ``` Being honest, I don't know how to solve the error because I don't understand the solution from the example. what can I do? Thanks.<issue_comment>username_1: One option is ParseName() **Example** ``` Declare @S varchar(max)='AM-65-800' Select parsename(replace(@S,'-','.'),2) ``` **Returns** ``` 65 ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Use `SUBSTRING` with start and lengths calculated based on position of the '-': ``` SELECT SUBSTRING('ABC-65-DEF', CHARINDEX('-', 'ABC-65-DEF') + 1, CHARINDEX('-', 'ABC-65-DEF', CHARINDEX('-', 'ABC-65-DEF') + 1) - CHARINDEX('-', 'ABC-65-DEF') - 1) ``` Basically, it finds the first instance of the '-' (`CHARINDEX('-', 'ABC-65-DEF')`) and then the second instance of '-' (`CHARINDEX('-', 'ABC-65-DEF', CHARINDEX('-', 'ABC-65-DEF') + 1)`) and grabs the substring inbetween. Upvotes: 1 <issue_comment>username_3: This will work to find the middle part on older SQL Servers up to and including 2008. ``` DECLARE @SomeText VARCHAR(100) = 'AM-75/86-650' SELECT LEFT(RIGHT(@SomeText, LEN(@SomeText) - CHARINDEX('-', @SomeText)), CHARINDEX('-', RIGHT(@SomeText, LEN(@SomeText) - CHARINDEX('-', @SomeText)))-1) ``` Returns: '75/86' Upvotes: 0
2018/03/15
614
1,701
<issue_start>username_0: I have two anchor tags within a single div. I want to apply the padding style only if the div has one anchor tag. For example the set 2, shouldn't show padding ```css .email a { padding-top:10px; display: block; } // for set 1 //I need to remove padding for a tag when div having two a tag like set 2 ``` ```html Set 1: [Hello](#) Set 2: [Hello](#) [Hello](#) ```<issue_comment>username_1: Use the [`only-child`](https://developer.mozilla.org/en-US/docs/Web/CSS/:only-child) selector: ```css .email a { display: block; } .email a:only-child { padding-top: 10px; } ``` ```html Set 1: [Hello](#) Set 2: [Hello](#) [Hello](#) ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Using css's `:only-child` selector can accomplish this! For example, ``` .email a:only-child{ padding-top:10px; display: block; } ``` Upvotes: 1 <issue_comment>username_3: ```css .email a { padding-top:10px; display: block; } .email:not(:first-child) a{ padding-top: 0; } //I need to remove padding for a tag when div having two a tag like set 2 ``` ```html Set 1: [Hello](#) Set 2: [Hello](#) [Hello](#) ``` Upvotes: 0 <issue_comment>username_4: Try this: ``` .email > a:not(:only-child):first-child { padding-top:0px} ``` Obviously, you can adjust the CSS there to adjust your original style for the .email a class You can see a working Fiddle here: <https://jsfiddle.net/37js9wae/3/> ```css .email a { padding-top:30px; display: block; } .email > a:not(:only-child):first-child { padding-top:0px} ``` ```html Set 1: [Hello](#) Set 2: [Hello](#) [Hello](#) ``` Upvotes: 0
2018/03/15
1,095
3,359
<issue_start>username_0: I have a UIButton that I am placing on a different UIView than the one it is declared in but I want the Target Selector to be in the UIView I declared the button in. The init\_button function is getting called because the button is being placed on the view. Here is what I have: ``` import Foundation import UIKit class Menu1 : Element { var color_base = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1) var mock : UIView = UIView() var button : UIButton = UIButton() var view_width: CGFloat = 0, view_height: CGFloat = 0, menu_vertical_buffer : CGFloat = 0, menu_width : CGFloat = 0, button_vertical_buffer : CGFloat = 0, button_width : CGFloat = 0 required init(mock: UIView) { super.init(mock: mock) self.mock = mock init_dims() init_button() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func init_dims(){ view_width = mock.frame.width view_height = mock.frame.height menu_vertical_buffer = CGFloat(floor(Double(view_height/17.5))) menu_width = CGFloat(floor(Double(view_width/2.67))) button_vertical_buffer = CGFloat(floor(Double(menu_vertical_buffer/3.6))) button_width = menu_width - CGFloat(floor(Double(menu_width/7))) } func init_button(){ button = UIButton(frame: CGRect(x: mock.frame.width - menu_width, y: mock.frame.height - (menu_vertical_buffer + (2 * button_vertical_buffer)), width: button_width, height: menu_vertical_buffer)) button.backgroundColor = color_base button.layer.cornerRadius = button.frame.height/2 button.addTarget(self, action: #selector(changeMenuState), for: .touchUpInside) mock.addSubview(button) } dynamic func changeMenuState(){ print("Menu state changed") } } ``` `changeMenuState` is the function I am adding as the target selector but the button is in the view `mock` not in the view that these functions are in.<issue_comment>username_1: Use the [`only-child`](https://developer.mozilla.org/en-US/docs/Web/CSS/:only-child) selector: ```css .email a { display: block; } .email a:only-child { padding-top: 10px; } ``` ```html Set 1: [Hello](#) Set 2: [Hello](#) [Hello](#) ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Using css's `:only-child` selector can accomplish this! For example, ``` .email a:only-child{ padding-top:10px; display: block; } ``` Upvotes: 1 <issue_comment>username_3: ```css .email a { padding-top:10px; display: block; } .email:not(:first-child) a{ padding-top: 0; } //I need to remove padding for a tag when div having two a tag like set 2 ``` ```html Set 1: [Hello](#) Set 2: [Hello](#) [Hello](#) ``` Upvotes: 0 <issue_comment>username_4: Try this: ``` .email > a:not(:only-child):first-child { padding-top:0px} ``` Obviously, you can adjust the CSS there to adjust your original style for the .email a class You can see a working Fiddle here: <https://jsfiddle.net/37js9wae/3/> ```css .email a { padding-top:30px; display: block; } .email > a:not(:only-child):first-child { padding-top:0px} ``` ```html Set 1: [Hello](#) Set 2: [Hello](#) [Hello](#) ``` Upvotes: 0
2018/03/15
1,629
5,825
<issue_start>username_0: I'm trying to use the Python library *Pygmo2* (<https://esa.github.io/pagmo2/index.html>) to parallelize an optimization problem. To my understanding, parallelization can be achieved with an *archipelago* of *islands* (in this case, *mp\_island*). As a minimal working example, one of the tutorials from the official site can serve: <https://esa.github.io/pagmo2/docs/python/tutorials/using_archipelago.html> I extracted the code: ``` class toy_problem: def __init__(self, dim): self.dim = dim def fitness(self, x): return [sum(x), 1 - sum(x*x), - sum(x)] def gradient(self, x): return pg.estimate_gradient(lambda x: self.fitness(x), x) def get_nec(self): return 1 def get_nic(self): return 1 def get_bounds(self): return ([-1] * self.dim, [1] * self.dim) def get_name(self): return "A toy problem" def get_extra_info(self): return "\tDimensions: " + str(self.dim) import pygmo as pg a_cstrs_sa = pg.algorithm(pg.cstrs_self_adaptive(iters=1000)) p_toy = pg.problem(toy_problem(50)) p_toy.c_tol = [1e-4, 1e-4] archi = pg.archipelago(n=32,algo=a_cstrs_sa, prob=p_toy, pop_size=70) print(archi) archi.evolve() print(archi) ``` Looking at the documentation of the old version of the library (<http://esa.github.io/pygmo/documentation/migration.html>), migration between islands seems to be an essential feature of the island parallelization model. Also, to my understanding, optimization algorithms like evolutionary algorithms could not work without it. However, in the documentation of *Pygmo2*, I can nowhere find how to perform migration. Is it happening automatically in an archipelago? Does it depend on the selected algorithm? Is it not yet implemented in *Pygmo2*? Is the documentation on this yet missing or did I just not find it? Can somebody enlighten me?<issue_comment>username_1: IMHO, the **`PyGMO2/pagmo`** documentation is confirming the **[migration](https://esa.github.io/pagmo2/docs/python/tutorials/using_archipelago.html?highlight=migration)** feature to be present. > > The **`archipelago`** class is the main parallelization engine of `pygmo`. It essentially is a container of **`island`** **able to** initiate **evolution** (optimization tasks) in each **`island`** asynchronously **while keeping track** of the results and **of the information exchange (*migration*)** between the tasks ... > > > With an exception of `thread_island`-s ( where some automated inference may take place and enforce 'em for thread-safe UDI-s ), all other **`island`** types - **`{ mp_island | ipyparallel_island }`**-s do create a GIL-independent form of a parallelism, yet the computing is performed via an async-operated **`.evolve()`** method In original `PyGMO`, the **`archipelago`** class was auto `.__init__()`-ed with attribute `topology = unconnected()`, unless specified explicitly, as documented in **`PyGMO`**, having a tuple of call-interfaces for `archipelago.__init__()` method ( showing just the matching one ): ``` __init__( algo, prob, n\_isl, n\_ind [, topology = unconnected(), distribution\_type = point\_to\_point, migration\_direction = destination ] ) ``` But, adding that, one may redefine the default, so as to meet one's PyGMO evolutionary process preferences: ``` topo = topology.erdos_renyi( nodes = 100, p = 0.03 ) # Erdos-Renyi ( random ) topology ``` [![enter image description here](https://i.stack.imgur.com/i7V81.png)](https://i.stack.imgur.com/i7V81.png) or set a Clustered Barabási-Albert, with ageing vertices graph topology: ``` topo = topology.clustered_ba( m0 = 3, m = 3, p = 0.5, a = 1000, nodes = 0 ) # clustered Barabasi-Albert, # # with Ageing vertices topology ``` [![enter image description here](https://i.stack.imgur.com/CsJzf.png)](https://i.stack.imgur.com/CsJzf.png) or: ``` topo = topology.watts_strogatz( nodes = 100, p = 0.1 ) # Watts-Strogatz ( circle # + links ) topology ``` [![enter image description here](https://i.stack.imgur.com/DbHNm.png)](https://i.stack.imgur.com/DbHNm.png) and finally, set it by assignment into the class-instance attribute: ``` archi = pg.archipelago( n = 32, algo = a_cstrs_sa, prob = p_toy, pop_size = 70 ) # constructs an archipelago archi.topology = topo # sets the topology to the # # above selected, pre-defined ``` Upvotes: 0 <issue_comment>username_2: The migration framework has not been fully ported from pagmo1 to pagmo2 yet. There is a long-standing PR open here: <https://github.com/esa/pagmo2/pull/102> We will complete the implementation of the migration framework in the next few months, hopefully by the beginning of the summer. Upvotes: 1 [selected_answer]<issue_comment>username_3: pagmo2 is now implementing migration since v2.11, the PR has benn completed and merged into master. Almost all capabilities present in pagmo1.x are restored. We will still add more topologies in the future, but they can already be implemented manually. Refer to docs here: <https://esa.github.io/pagmo2/docs/cpp/cpp_docs.html> Tutorial and example are missing and will be added in the near future (help is welcome) Upvotes: 1
2018/03/15
1,275
4,858
<issue_start>username_0: I am writing a program to calculate a gpa. the only thing that doesn't work is when I try to write code to prevent the gpa from going over 4 or under 0. here is my whole class. I think the problem may be somewhere in my gpa full property. in my program class where I call the functions I have code to ask for studentID, firstName, lastName, and gpa. When I run the program and enter in a gpa of 5 it still returns the number 5 with a letter grade of A. I need it to return a number 4 with a letter grade of A. Any help would be greatly appreciated. ``` using System; using System.Collections.Generic; using System.Text; namespace UnitTest1 { public class Student { public int StudentID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public double Gpa { get; set; } private string letterGrade; public string LetterGrade { get { if (GPA >= 0 && GPA <= 0.99) { return "F"; } else if (GPA >= 1 && GPA <= 1.29) { return "D"; } else if (GPA >= 1.3 && GPA <= 1.69) { return "D+"; } else if (GPA >= 1.7 && GPA <= 1.99) { return "C-"; } else if (GPA >= 2 && GPA <= 2.29) { return "C"; } else if (GPA >= 2.3 && GPA <= 2.69) { return "C+"; } else if (GPA >= 2.7 && GPA <= 2.99) { return "B-"; } else if (GPA >= 3 && GPA <= 3.29) { return "B"; } else if (GPA >= 3.3 && GPA <= 3.69) { return "B+"; } else if (GPA >= 3.7 && GPA <= 3.99) { return "A-"; } else if (GPA == 4) { return "A"; } return LetterGrade; } //All of this code sets the gpa number to a letter grade } private double gPA; public double GPA { get { if (Gpa <= 0) { return 0; } else if (Gpa >= 4) { return 4; } else { return Gpa; } } set { if (Gpa <= 0) { Gpa = 0; } else if (Gpa >= 4) { Gpa = 4; } Gpa = value; // <<=== remove me please } } public Student(int studentID, string firstName, string lastName, double gpa) { StudentID = studentID; FirstName = firstName; LastName = lastName; Gpa = gpa; } public void PrintTranscript() { Console.WriteLine(""); Console.WriteLine("{0, -20} {1, 26}", "University of Coding", $"Student ID: {StudentID}"); Console.WriteLine("{0, -20} {1, 23}", "123 Sea Sharp Street", "Date: 02/15/2018"); //The coordinates in these two lines sets the text in a certain spot in the output screen Console.WriteLine("Cedarville, OH 45314"); Console.WriteLine($"Student: {FirstName} {LastName}"); Console.WriteLine(""); Console.WriteLine($"Current GPA {Gpa}"); Console.WriteLine(""); Console.WriteLine($"Letter Grade: {LetterGrade}"); //This code outputs what the user input } } } ```<issue_comment>username_1: I don't think you need a setter at all here and you are outputting the wrong property. ``` public double GPA { get { if (Gpa <= 0) { return 0; } else if (Gpa >= 4) { return 4; } else { return Gpa; } } } ``` Output line ----------- ``` Console.WriteLine($"Current GPA {GPA}"); ``` Upvotes: 0 <issue_comment>username_2: You can get rid of the `Gpa` property (you already have a backing field and are using custom get and set methods), and your getter and setter can be simplified: ``` private decimal gPA; public decimal GPA { get { return gPA; } set { if (value <= 0) // use value, not gPA here { gPA = 0; } else if (value >= 4) { gPA = 4; } else { gPA = value; } } } ``` I would also switch to `decimal` if you want to use exact equality comparisons, and use `<` instead of `<=` in cases where it's what you intend (e.g. `< 4` is more appropriate than `<= 3.99`) Upvotes: 2 [selected_answer]
2018/03/15
1,251
4,811
<issue_start>username_0: I have just added SQLite to my asp.net webApi project, and am having trouble working out how get the path to the App\_Data folder to pass to `DbContextOptionsBuilderUseSqlite` I have the following in the `web.config` I have a link to an external a config file with the conenction string... ``` ``` and in there I have... ``` ``` And in my `DbContext.OnConfiguring` I Have.... ``` protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { string path = WebConfigurationManager.ConnectionStrings["MyDatastore"].ConnectionString; optionsBuilder.UseSqlite(path); } } ``` The path is correctly retrieved (I can see I get the path as configured on `connectionStrings.config` so `./App_Data/test.sqlite` is passed to `optionsBuilder.UseSqlite(path)`. However, I get the following error... ``` SQLite Error 14: 'unable to open database file'. ``` If I use just `connectionString="DataSource=test.sqlite" />` then it seems to magically find the file in the App\_Data folder, when I ran on my dev machine in debug, but I had problems on another machine (release build). I assume it is the path, though all I get back is 'unable to open database file'. I also tried.. ``` connectionString="DataSource=|DataDirectory|test.sqlite" /> ``` This gives me a `Illegal characters in path` error. The following does work (full path) ``` connectionString="d:\0\test.sqlite" /> ``` But I want to be able to use relative paths, eg maybe even `.\datastore\test.sqlite`. Does any one have any ideas on this? Thanks in advance<issue_comment>username_1: You'll have to fix up the relative paths at runtime: ``` var builder = new SqliteConnectionStringBuilder(connectionString); builder.DataSource = Path.GetFullPath( Path.Combine( AppDomain.CurrentDomain.GetData("DataDirectory") as string ?? AppDomain.CurrentDomain.BaseDirectory, builder.DataSource); connectionString = builder.ToString(); ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: Works perfectly for me. ``` protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { var dataSource = Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "siteDB.db"); optionsBuilder .UseSqlite($"Data Source={dataSource};"); } ``` Upvotes: 2 <issue_comment>username_3: *Note: This solution was tested for .Net Core 5, and one can presume it will work on 2.x, 3.x, 5* If you want to use a diferent project than the one provided when you started, you have to specify the correct path ("Data Source = ..\\MyApplication.DAL\\sqliteDatabase.db") in the appsettings.json. In this presented case, you don't even need to write the method OnConfiguring(DbContextOptionsBuilder optionsBuilder) in the ApplicationDbContext.cs. You have a full setup bellow (Startup & appsettings.json). My project structure: ``` -> MyApplication (solution) -> MyApplication.UI (initial project of the solution) -> MyApplication.BL (project) -> MyApplication.DAL (project) ``` Inside Startup.cs ```cs public void ConfigureServices(IServiceCollection services) { //... other services services.AddDbContext (x => x.UseSqlite(Configuration.GetConnectionString("SqliteConnection"))); //.... other services and logic } ``` In appsettings.json : ```js "ConnectionStrings": { "SqliteConnection": "Data Source = ..\\MyApplication.DAL\\sqliteDatabase.db" } ``` Upvotes: 2 <issue_comment>username_4: If you are a .Net Core backend developer who use sqlite, make sure to use below code example. Otherwise **SQLite Error 14: 'unable to open database file'** error will come. Startup.cs ``` var baseDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); string dbPathSystemLog = Path.Combine(baseDirectory, "CAMSCoreSystemLog.db"); ``` SystemLogDBContext.cs ``` public class SystemLogDBContext : DbContext { public SystemLogDBContext(DbContextOptions options) : base(options) { Database.EnsureCreated(); } } ``` This line will create the Db if not exist ``` Database.EnsureCreated(); ``` I was struggling two days. This will help someone. Upvotes: 0 <issue_comment>username_5: Works for me on linux, .net core 5. ```cs var builder = new SqliteConnectionStringBuilder("Data Source=MyDatabase.db"); builder.DataSource = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, builder.DataSource); services.AddDbContext(o => o.UseSqlite(builder.ToString()); ``` Assumes database is in the bin directory, e.g. `MyProject/bin/Debug/MyDatabase.db` or `MyProject/bin/Release/MyDatabase.db`. Upvotes: 1
2018/03/15
595
1,825
<issue_start>username_0: I want to find the max number among the first and second elements of each array inside the array of arrays separately: ```js function largestOfElements(mainArray) { return mainArray.map(function(subArray) { return subArray.reduce(function(previousLargestNumber, currentLargestNumber) { return (currentLargestNumber > previousLargestNumber) ? currentLargestNumber : previousLargestNumber; }, 0); }); } console.log(largestOfElements([ [], [13, 47], [38, 35], [24, 34] ])); ``` ```css .as-console-wrapper { max-height: 100% !important; top: 0; } ``` the current way returns an array of the largest numbers in each array. How can I return the largest of the first elements and the largest of the second elements? the expected result will be: `[38, 47]`<issue_comment>username_1: You can use the function `reduce`. * The initial value for the function reduce are the min values to start getting the highest values. * Check for the length of the current array. * Use destructuring assignment to get the first and second value [first, second]. * Check the current value against first and second respectively to get the highest. ```js var array = [ [], [13, 47], [38, 35], [24, 34] ]; var result = Object.values(array.reduce((a, c) => { if (c.length) { var [first, second] = c; if (first > a.f) a.f = first; if (second > a.s) a.s = second; } return a; }, {f: Number.MIN_VALUE, s: Number.MIN_VALUE})); console.log(result); ``` ```css .as-console-wrapper { max-height: 100% !important; top: 0; } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: ```js var array = [ [], [13, 47], [38, 35], [24, 34] ]; console.log([0,1].map(i => Math.max(...array.map(v => v[i]).filter(v => v)))); ``` Upvotes: 0
2018/03/15
1,891
4,375
<issue_start>username_0: Using python/numpy, I can create the 3D array (note the matrix exponential function) I want like so ``` import numpy as np from scipy.linalg import expm a = np.arange(3) B = np.ones((2,2)) C = np.zeros((2,2,3)) for i in range(3): C[:,:,i] = expm(a[i]*B) ``` which yields for C, the 3D array ``` [[[ 1. 4.19452805 27.79907502] [ 0. 3.19452805 26.79907502]] [[ 0. 3.19452805 26.79907502] [ 1. 4.19452805 27.79907502]]] ``` But I'd like to eliminate the loop. Is there any way I can get rid of the `for` loop? Perhaps by NumPy broadcasting? I had thought of `np.kron` but can't seem to figure out a good way to reshape so that I can apply the `expm` function, which requires a square array as an argument.<issue_comment>username_1: I'm not sure if this is exactly what you'd like but it gives the same result without a for loop. ``` a = np.arange(3) B = np.ones((2,2)) C = np.array([expm(a[i]*B) for i in range(3)]).T ``` Granted there's still a "for" in the list comprehension, not sure if that fits your purposes. Upvotes: 0 <issue_comment>username_2: If you want to get the result without calling `expm` multiple times in a for loop, you can construct the input like this: ``` import numpy as np from scipy.linalg import expm n = 4 t = np.zeros([n*2, n*2]) for i in range(n): t[2*i:2*i+2, 2*i:2*i+2] = i C0 = expm(t) ``` This results in a format ``` >>> t array([[0., 0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0., 0.], [0., 0., 1., 1., 0., 0., 0., 0.], [0., 0., 1., 1., 0., 0., 0., 0.], [0., 0., 0., 0., 2., 2., 0., 0.], [0., 0., 0., 0., 2., 2., 0., 0.], [0., 0., 0., 0., 0., 0., 3., 3.], [0., 0., 0., 0., 0., 0., 3., 3.]]) >>> C0 array([[ 1. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ], [ 0. , 1. , 0. , 0. , 0. , 0. , 0. , 0. ], [ 0. , 0. , 4.19452805, 3.19452805, 0. , 0. , 0. , 0. ], [ 0. , 0. , 3.19452805, 4.19452805, 0. , 0. , 0. , 0. ], [ 0. , 0. , 0. , 0. , 27.79907502, 26.79907502, 0. , 0. ], [ 0. , 0. , 0. , 0. , 26.79907502, 27.79907502, 0. , 0. ], [ 0. , 0. , 0. , 0. , 0. , 0. , 202.21439675, 201.21439675], [ 0. , 0. , 0. , 0. , 0. , 0. , 201.21439675, 202.21439675]]) ``` If you insist on having the results in your example structure of `C`, I believe that you'll have to use some kind of loop (list comprehension, `range`, or otherwise) to achieve this, as I don't think that is a standard output structure for this kind of function. ``` i1 = range(0, 2*n, 2) i2 = range(1, 2*n+1, 2) i = (tuple(i1 + i2 + i1 + i2), tuple(i1 + i1 + i2 + i2)) C = C0[i].reshape(2,2,n) >>> C array([[[ 1. , 4.19452805, 27.79907502, 202.21439675], [ 0. , 3.19452805, 26.79907502, 201.21439675]], [[ 0. , 3.19452805, 26.79907502, 201.21439675], [ 1. , 4.19452805, 27.79907502, 202.21439675]]]) ``` For larger inputs, `expm` handles sparse square arrays so you shouldn't have any issues with memory. Upvotes: 0 <issue_comment>username_3: Using [Sylvester's Formula](https://en.wikipedia.org/wiki/Sylvester%27s_formula) and a slightly different shape, you can do this vectorized: ``` C = a[:, None, None] * B C.shape (3, 2, 2) E, V = np.linalg.eig(C) V.swapaxes(-1,-2) @ np.exp(E)[..., None] * V array([[[ 1. , 0. ], [ 0. , 1. ]], [[ 4.19452805, -4.19452805], [ -3.19452805, -3.19452805]], [[ 27.79907502, -27.79907502], [-26.79907502, -26.79907502]]]) ``` This method can take any number of square matrces as inputs in a `(*, N, N)` array, but while it eliminates the `for` loop overhead it exchanges it for an `np.linalg.eig` call, which may be slow if `N` is large. Upvotes: 1
2018/03/15
1,664
3,922
<issue_start>username_0: How to iterate over all property values for a node in Cypher? I can iterate over keys by doing: ``` "WHERE any (key in keys(n) where key ='xxx')" ``` Is there a similar way to do this for property value? I need to test each key value to see whether the key value equals a variable. If matching, I issue a query.<issue_comment>username_1: I'm not sure if this is exactly what you'd like but it gives the same result without a for loop. ``` a = np.arange(3) B = np.ones((2,2)) C = np.array([expm(a[i]*B) for i in range(3)]).T ``` Granted there's still a "for" in the list comprehension, not sure if that fits your purposes. Upvotes: 0 <issue_comment>username_2: If you want to get the result without calling `expm` multiple times in a for loop, you can construct the input like this: ``` import numpy as np from scipy.linalg import expm n = 4 t = np.zeros([n*2, n*2]) for i in range(n): t[2*i:2*i+2, 2*i:2*i+2] = i C0 = expm(t) ``` This results in a format ``` >>> t array([[0., 0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0., 0.], [0., 0., 1., 1., 0., 0., 0., 0.], [0., 0., 1., 1., 0., 0., 0., 0.], [0., 0., 0., 0., 2., 2., 0., 0.], [0., 0., 0., 0., 2., 2., 0., 0.], [0., 0., 0., 0., 0., 0., 3., 3.], [0., 0., 0., 0., 0., 0., 3., 3.]]) >>> C0 array([[ 1. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ], [ 0. , 1. , 0. , 0. , 0. , 0. , 0. , 0. ], [ 0. , 0. , 4.19452805, 3.19452805, 0. , 0. , 0. , 0. ], [ 0. , 0. , 3.19452805, 4.19452805, 0. , 0. , 0. , 0. ], [ 0. , 0. , 0. , 0. , 27.79907502, 26.79907502, 0. , 0. ], [ 0. , 0. , 0. , 0. , 26.79907502, 27.79907502, 0. , 0. ], [ 0. , 0. , 0. , 0. , 0. , 0. , 202.21439675, 201.21439675], [ 0. , 0. , 0. , 0. , 0. , 0. , 201.21439675, 202.21439675]]) ``` If you insist on having the results in your example structure of `C`, I believe that you'll have to use some kind of loop (list comprehension, `range`, or otherwise) to achieve this, as I don't think that is a standard output structure for this kind of function. ``` i1 = range(0, 2*n, 2) i2 = range(1, 2*n+1, 2) i = (tuple(i1 + i2 + i1 + i2), tuple(i1 + i1 + i2 + i2)) C = C0[i].reshape(2,2,n) >>> C array([[[ 1. , 4.19452805, 27.79907502, 202.21439675], [ 0. , 3.19452805, 26.79907502, 201.21439675]], [[ 0. , 3.19452805, 26.79907502, 201.21439675], [ 1. , 4.19452805, 27.79907502, 202.21439675]]]) ``` For larger inputs, `expm` handles sparse square arrays so you shouldn't have any issues with memory. Upvotes: 0 <issue_comment>username_3: Using [Sylvester's Formula](https://en.wikipedia.org/wiki/Sylvester%27s_formula) and a slightly different shape, you can do this vectorized: ``` C = a[:, None, None] * B C.shape (3, 2, 2) E, V = np.linalg.eig(C) V.swapaxes(-1,-2) @ np.exp(E)[..., None] * V array([[[ 1. , 0. ], [ 0. , 1. ]], [[ 4.19452805, -4.19452805], [ -3.19452805, -3.19452805]], [[ 27.79907502, -27.79907502], [-26.79907502, -26.79907502]]]) ``` This method can take any number of square matrces as inputs in a `(*, N, N)` array, but while it eliminates the `for` loop overhead it exchanges it for an `np.linalg.eig` call, which may be slow if `N` is large. Upvotes: 1
2018/03/15
400
1,679
<issue_start>username_0: I have a main-page.componenent.ts like so... ``` ``` and then inside my app-page component I have another nested component like so.. ``` ``` so basically my app looks like this ``` // where the function is // where the button is ``` now I have a button in my nested-component and I want that to trigger a function on the top parent component.. now I know if I was passing an event to the most direct parent I could use an event emitter but Im not sure if that will work in this case.. so my question is how can I 'bubble' up an event so it hits the most parent container and triggers and event? any help would be appreciated<issue_comment>username_1: You have two options. The first option, you can have each component have an output that broadcasts the event up. This can get unweildly pretty quickly, especially if it is deeply nested. The second option, you can use a shared service to send and receive messages. Essentially your component that has the button would call a method on your service that broadcasts out the event and your parent component would use the service to subscribe to these events that are broadcast out and act appropriately. Upvotes: 2 <issue_comment>username_2: There are lots of cases and little bit hard to understand what your case is. In my view, There would be 2 opstions. 1. grandparent <=> parent <=> children : event emitter (<https://angular.io/guide/component-interaction#!#bidirectional-service>) 2. using service : define service and call children components to set data or make events, and grandparent subscribe the value changes or event subscribe. I hope this would be helpful :) Upvotes: 1
2018/03/15
732
2,533
<issue_start>username_0: I'm trying to load images dynamically within a single file component, but I'm getting an error that the module cannot be found. I think I'm trying to do the same thing as [this SO post](https://stackoverflow.com/questions/40491506/vue-js-dynamic-images-not-working), but I'm not sure what I'm doing wrong. I used the [webpack template](https://github.com/vuejs-templates/webpack) to set up my project. Here's the relevant markup in my template: ``` ![]() {{ job.title }} ``` And the function I'm trying to get the image from: ``` methods: { getIconPath (iconName) { const icons = require.context('../assets/', false, /\.png$/) return iconName ? icons(`./${iconName}.png`) : '' } } ``` I have the images in the `/src/assets/` directory. The error I'm getting in the browser console is: `[Vue warn]: Error in render: "Error: Cannot find module './some-icon.png'."` I'm not sure if this is a webpack config issue, or a problem with the getIconPath function. Anything help is appreciated, thanks!<issue_comment>username_1: Considering your JavaScript code is at `/src/components/JobList.vue` and your images are at `/src/assets/`, use as follows: ```js methods: { getIconPath (iconName) { return iconName ? require(`../assets/${iconName}`) : '' } } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: It looks like to me that the static assets such as images should be going to /static when webpack builds in dev or prod. Looking in the config file: [vuejs-templates/webpack/blob/develop/template/config/index.js](https://github.com/vuejs-templates/webpack/blob/develop/template/config/index.js), you have the following configuration (provided you haven't changed anything): ``` // Paths assetsSubDirectory: 'static', assetsPublicPath: '/', ``` So the src should probably be something like: ``` ![](/static/whatEverMyIconIs.png) ``` EDIT: Looking further into the configs, in [vuejs-templates/webpack/blob/develop/template/build/webpack.base.conf.js](https://github.com/vuejs-templates/webpack/blob/develop/template/build/webpack.base.conf.js), there's a url-loader plugin which should place images into /static/img: ``` { test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, loader: 'url-loader', options: { limit: 10000, name: utils.assetsPath('img/[name].[hash:7].[ext]') } }, ``` Which could make your src url (depending on how the icons are being loaded): ``` ![](/static/img/whatEverMyIconIs.png) ``` Upvotes: 0
2018/03/15
577
1,986
<issue_start>username_0: I have a dataset in google sheets where the "name" field looks like this: ``` Stephen & <NAME> ``` I am trying to figure out the Regular expression to find the space between "<NAME>" so I can split it into Name and Last Name. That way Stephen & Sally remain in the name field and Fitzpatrick becomes the last name. But the extent of the question is simply to find that space, not split it. I believe it is a fairly new compiler, so \s, \b, \w are supported.<issue_comment>username_1: Considering your JavaScript code is at `/src/components/JobList.vue` and your images are at `/src/assets/`, use as follows: ```js methods: { getIconPath (iconName) { return iconName ? require(`../assets/${iconName}`) : '' } } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: It looks like to me that the static assets such as images should be going to /static when webpack builds in dev or prod. Looking in the config file: [vuejs-templates/webpack/blob/develop/template/config/index.js](https://github.com/vuejs-templates/webpack/blob/develop/template/config/index.js), you have the following configuration (provided you haven't changed anything): ``` // Paths assetsSubDirectory: 'static', assetsPublicPath: '/', ``` So the src should probably be something like: ``` ![](/static/whatEverMyIconIs.png) ``` EDIT: Looking further into the configs, in [vuejs-templates/webpack/blob/develop/template/build/webpack.base.conf.js](https://github.com/vuejs-templates/webpack/blob/develop/template/build/webpack.base.conf.js), there's a url-loader plugin which should place images into /static/img: ``` { test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, loader: 'url-loader', options: { limit: 10000, name: utils.assetsPath('img/[name].[hash:7].[ext]') } }, ``` Which could make your src url (depending on how the icons are being loaded): ``` ![](/static/img/whatEverMyIconIs.png) ``` Upvotes: 0
2018/03/15
560
1,946
<issue_start>username_0: I think i have a grasp of the generator functions, don't know if i would really use them but i found something that <NAME> said that is particularly interesting. In this video ( <https://www.youtube.com/watch?v=DxnYQRuLX7Q> ) at 26:00 he says that generators can be replicated using a factory type pattern and normal functions. I am unable to formulate 'how' that might be possible. Any program proving that would be cool to look at.<issue_comment>username_1: Considering your JavaScript code is at `/src/components/JobList.vue` and your images are at `/src/assets/`, use as follows: ```js methods: { getIconPath (iconName) { return iconName ? require(`../assets/${iconName}`) : '' } } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: It looks like to me that the static assets such as images should be going to /static when webpack builds in dev or prod. Looking in the config file: [vuejs-templates/webpack/blob/develop/template/config/index.js](https://github.com/vuejs-templates/webpack/blob/develop/template/config/index.js), you have the following configuration (provided you haven't changed anything): ``` // Paths assetsSubDirectory: 'static', assetsPublicPath: '/', ``` So the src should probably be something like: ``` ![](/static/whatEverMyIconIs.png) ``` EDIT: Looking further into the configs, in [vuejs-templates/webpack/blob/develop/template/build/webpack.base.conf.js](https://github.com/vuejs-templates/webpack/blob/develop/template/build/webpack.base.conf.js), there's a url-loader plugin which should place images into /static/img: ``` { test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, loader: 'url-loader', options: { limit: 10000, name: utils.assetsPath('img/[name].[hash:7].[ext]') } }, ``` Which could make your src url (depending on how the icons are being loaded): ``` ![](/static/img/whatEverMyIconIs.png) ``` Upvotes: 0
2018/03/15
566
1,947
<issue_start>username_0: I have a dataframe with column 'code' which I have sorted based on frequency. In order to see what each code means, there is also a column 'note'. For each counting/grouping of the 'code' column, I display the first note that is attached to the first 'code' ``` df.groupby('code')['note'].agg(['count', 'first']).sort_values('count', ascending=False) ``` Now my question is, how do I display only those rows that have frequency of e.g. >= 30?<issue_comment>username_1: Considering your JavaScript code is at `/src/components/JobList.vue` and your images are at `/src/assets/`, use as follows: ```js methods: { getIconPath (iconName) { return iconName ? require(`../assets/${iconName}`) : '' } } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: It looks like to me that the static assets such as images should be going to /static when webpack builds in dev or prod. Looking in the config file: [vuejs-templates/webpack/blob/develop/template/config/index.js](https://github.com/vuejs-templates/webpack/blob/develop/template/config/index.js), you have the following configuration (provided you haven't changed anything): ``` // Paths assetsSubDirectory: 'static', assetsPublicPath: '/', ``` So the src should probably be something like: ``` ![](/static/whatEverMyIconIs.png) ``` EDIT: Looking further into the configs, in [vuejs-templates/webpack/blob/develop/template/build/webpack.base.conf.js](https://github.com/vuejs-templates/webpack/blob/develop/template/build/webpack.base.conf.js), there's a url-loader plugin which should place images into /static/img: ``` { test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, loader: 'url-loader', options: { limit: 10000, name: utils.assetsPath('img/[name].[hash:7].[ext]') } }, ``` Which could make your src url (depending on how the icons are being loaded): ``` ![](/static/img/whatEverMyIconIs.png) ``` Upvotes: 0
2018/03/15
647
2,031
<issue_start>username_0: How to pass a value to other page with URL Rewriting. I have 2 pages. 1 is index.php and 2 is videoplayer.php. inside index.php. there's ``` ![](film-ghost-shell-2017.jpg) [Ghost In The Shell (2017)](http://127.0.0.1/Ghost-In-The-Shell-2017/) ``` How can i pass the value anchor when i clicked Ghost-In-The-Shell-2017 to videoplayer.php without changing the name in url like still <http://127.0.0.1/ghost-in-the-shell-2017/>? videoplayerphp. i still don;t know how to pass anchor value to videoplayer but form it possible.<issue_comment>username_1: Considering your JavaScript code is at `/src/components/JobList.vue` and your images are at `/src/assets/`, use as follows: ```js methods: { getIconPath (iconName) { return iconName ? require(`../assets/${iconName}`) : '' } } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: It looks like to me that the static assets such as images should be going to /static when webpack builds in dev or prod. Looking in the config file: [vuejs-templates/webpack/blob/develop/template/config/index.js](https://github.com/vuejs-templates/webpack/blob/develop/template/config/index.js), you have the following configuration (provided you haven't changed anything): ``` // Paths assetsSubDirectory: 'static', assetsPublicPath: '/', ``` So the src should probably be something like: ``` ![](/static/whatEverMyIconIs.png) ``` EDIT: Looking further into the configs, in [vuejs-templates/webpack/blob/develop/template/build/webpack.base.conf.js](https://github.com/vuejs-templates/webpack/blob/develop/template/build/webpack.base.conf.js), there's a url-loader plugin which should place images into /static/img: ``` { test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, loader: 'url-loader', options: { limit: 10000, name: utils.assetsPath('img/[name].[hash:7].[ext]') } }, ``` Which could make your src url (depending on how the icons are being loaded): ``` ![](/static/img/whatEverMyIconIs.png) ``` Upvotes: 0
2018/03/15
500
1,550
<issue_start>username_0: I defined a two-dimensional array as follows: ``` predict_result = np.zeros((69,1000)) ``` In the loop, I was trying to inject a predicted one-dimensional array into it. ``` for ij in range(0,1000): # # some code to generate Ypredict predict_result[:,ij]=Ypredict ``` `Ypredict` is always the shape of `(69,1)`. However, running the program gives the following error > > predict\_result[:,ij]=Ypredict ValueError: could not broadcast input > array from shape (69,1) into shape (69) > > > How can I correct this error?<issue_comment>username_1: You don't need for-loop: ``` predict_result[:] = Ypredict ``` Or you can create the result by `repeat`: ``` np.repeat(Ypredict, 1000, axis=1) ``` Upvotes: -1 <issue_comment>username_2: Either change the (69,1) array to (69,), or make the receiving slot (69,1) `ravel` is one on several ways of flattening the 2d array: ``` predict_result[:,ij]=Ypredict.ravel() ``` Index with a list rather than a scalar works the other way: ``` predict_result[:,[ij]]=Ypredict ``` You could also use broadcasting to put the smaller array into the larger without a loop - as noted in the other answer: ``` (69,1000) <= (69,1) works ``` The 2 basic rules of broadcasting: * a size 1 dimension can be added at the start to match the number of dimensions * all size 1 dimensions can be changed to match to same dimension of the other array(s). (69,) cannot be changed to match (69,1). But (69,1) can be changed to match (69,1000). Upvotes: 2 [selected_answer]
2018/03/15
559
1,787
<issue_start>username_0: So I think\* RVM may be keeping my Ruby version back artificially. I am getting all sorts of errors in Rails. So I checked the Ruby version I was using. Said it was back a few versions.. so I tried updating to 2.5.0. System said 2.5.0 was already installed? So I checked ruby -v, and got 2.3.3 Here is exactly what my system is telling me: ``` Johns-MacBook-Pro:PLAYGROUND johnseabolt$ brew install ruby Warning: ruby 2.5.0_2 is already installed Johns-MacBook-Pro:PLAYGROUND johnseabolt$ ruby -v ruby 2.3.3p222 (2016-11-21 revision 56859) [universal.x86_64-darwin17] Johns-MacBook-Pro:PLAYGROUND johnseabolt$ ``` I thought it was an RVM issue maybe? But when I tried to use 2.5.0, I got this: ``` Johns-MacBook-Pro:PLAYGROUND johnseabolt$ rvm use 2.5.0_2 Required ruby-2.5.0_2 is not installed. To install do: 'rvm install "ruby-2.5.0"' ``` Any ideas what is going on? It's a bit of a pain.<issue_comment>username_1: This is the relevant line of output: ``` To install do: 'rvm install "ruby-2.5.0"' ``` what happens when you run that line of code? It should fix all your problems... :) Upvotes: 3 [selected_answer]<issue_comment>username_2: I'm not sure what you're saying your problem is exactly, but you can and will have multiple versions of Ruby installed in various places on a modern system. Different applications will require different versions. In terms of being held back, Ruby doesn't autoupdate like browsers, it's up to you to install the ones you want. It looks like you have at least one Ruby installed with RVM, and you may have installed with Brew too (which I didn't you know you could do, but I would recommend not to do) `which ruby` will tell you which Ruby is loaded in a new shell. It should be in an RVM bin. Upvotes: 0
2018/03/15
1,019
3,432
<issue_start>username_0: This code is supposed to print out a "barcode" from a given zip code. The problem is that it is only printing out **none** after it is done. No visible errors to me. Could you take a look? ``` def printDigit(d , x): if x <= 5: if d[x] == 0: return "||:::" + printDigit(d , x + 1) elif d[x] == 1: return ":::||" + printDigit(d , x + 1) elif d[x] == 2: return "::|:|" + printDigit(d , x + 1) elif d[x] == 3: return "::||:" + printDigit(d , x + 1) elif d[x] == 4: return ":|::|" + printDigit(d , x + 1) elif d[x] == 5: return ":|:|:" + printDigit(d , x + 1) elif d[x] == 6: return ":||:|" + printDigit(d , x + 1) elif d[x] == 7: return "|:::|" + printDigit(d , x + 1) elif d[x] == 8: return "|::|:" + printDigit(d , x + 1) elif d[x] == 9: return "|:|::" + printDigit(d , x + 1) else: return zipCode = str(input("Input a zip code: ")) print(printDigit(zipCode , 0)) ```<issue_comment>username_1: Here is one way you can do this. Instead of using recursion for this problem you can just iterate through the characters of the input. If there are less than 5 characters you can immediately `return None` since the zip code input is wrong. Then we will iterate through each character and add the barcode to a list. At the end we check if the length of the list is 25, this would mean that we indeed had 5 numbers, if there are any letters or special characters they will get ignored. ``` def printDigit(d): if len(str(d)) == 5 and str(d).isdigit(): temp = [] for i in str(d): if i == '0': temp.extend("||:::") elif i == '1': temp.extend(":::||") elif i == '2': temp.extend("::|:|") elif i == '3': temp.extend("::||:") elif i == '4': temp.extend(":|::|") elif i == '5': temp.extend(":|:|:") elif i == '6': temp.extend(":||:|") elif i == '7': temp.extend("|:::|") elif i == '8': temp.extend("|::|:") elif i == '9': temp.extend("|:|::") return ''.join(temp) else: return None zipCode = str(input("Input a zip code: ")) print(printDigit(zipCode)) ``` --- To avoid rewriting code segments. We can also use a dictionary to hold the translation of each digit to its barcode value. Then we can use list comprehensions as ``` def printDigit(d): dic = {'0': "||:::", '1': "||:::", '2': "::|:|", '3': "::||:", '4': ":|::|", '5': ":|:|:", '6': ":||:|", '7': "|:::|", '8': "|::|:", '9': "|:|::"} if len(str(d)) == 5 and str(d).isdigit(): return ''.join([dic[i] for i in str(d)]) else: return None zipCode = str(input("Input a zip code: ")) print(printDigit(zipCode)) ``` Upvotes: 1 <issue_comment>username_2: You're accepting the entered zipCode as a String object. So while comparing it's elements you can either put the digits within single quotes or convert the zipCode to an integer. I'd also suggest checking if the current character in the string is a digit using the isdigit() method. Also when the value of x crosses 5 then your printDigit method returns NoneType which cannot be combined with a string object. Therefore return "" ``` def printDigit(d , x): if x ``` Upvotes: 0
2018/03/15
1,312
4,525
<issue_start>username_0: I have made a program in c# that reads and removes duplicate. It works fine with 0-5000 values but when I tried it with 100,000 values it takes too long or NOT-RESPONDING. Any suggestions on how to fix it? Below is my algorithm. ``` try { DataTable dtExcel = new DataTable(); dtExcel = ReadExcel(filePath, fileExt); //read excel file dataGridView1.DataSource = dtExcel; mydatagrid.Rows.Clear(); for (int i = 1; i < dataGridView1.Rows.Count; i++) { string exists = "no"; //MessageBox.Show(dataGridView1.Rows[i].Cells[0].Value.ToString()); if (mydatagrid.Rows.Count == 1) { mydatagrid.Rows.Add(dataGridView1.Rows[i].Cells[0].Value.ToString(), dataGridView1.Rows[i].Cells[1].Value.ToString(), dataGridView1.Rows[i].Cells[2].Value.ToString(), dataGridView1.Rows[i].Cells[3].Value.ToString()); } else { int b = 1; while (b < (mydatagrid.Rows.Count - 1)) { //MessageBox.Show(mydatagrid.Rows[b].Cells[0].Value.ToString()); if (dataGridView1.Rows[i].Cells[0].Value.ToString() == mydatagrid.Rows[b].Cells[0].Value.ToString()) { exists = "yes"; } else { } b++; } if (exists == "no") { mydatagrid.Rows.Add(dataGridView1.Rows[i].Cells[0].Value.ToString(), dataGridView1.Rows[i].Cells[1].Value.ToString(), dataGridView1.Rows[i].Cells[2].Value.ToString(), dataGridView1.Rows[i].Cells[3].Value.ToString()); } } } ```<issue_comment>username_1: Bools are faster than strings (`exists`), and also the *correct* type to use. You should stop looping when you have the information you need (`break`). If you can find a way to move your special condition for a count of 1 OUTSIDE the loop (and I think you can), you should do so. ``` try { DataTable dtExcel = new DataTable(); dtExcel = ReadExcel(filePath, fileExt); //read excel file dataGridView1.DataSource = dtExcel; mydatagrid.Rows.Clear(); for (int i = 1; i < dataGridView1.Rows.Count; i++) { bool exists = false; if (mydatagrid.Rows.Count == 1) { mydatagrid.Rows.Add(dataGridView1.Rows[i].Cells[0].Value.ToString(), dataGridView1.Rows[i].Cells[1].Value.ToString(), dataGridView1.Rows[i].Cells[2].Value.ToString(), dataGridView1.Rows[i].Cells[3].Value.ToString()); } else { for (int b = 1; b < (mydatagrid.Rows.Count - 1); b++) { //MessageBox.Show(mydatagrid.Rows[b].Cells[0].Value.ToString()); if (dataGridView1.Rows[i].Cells[0].Value.ToString() == mydatagrid.Rows[b].Cells[0].Value.ToString()) { exists = true; break; } } if (!exists) { mydatagrid.Rows.Add(dataGridView1.Rows[i].Cells[0].Value.ToString(), dataGridView1.Rows[i].Cells[1].Value.ToString(), dataGridView1.Rows[i].Cells[2].Value.ToString(), dataGridView1.Rows[i].Cells[3].Value.ToString()); } } } } ``` Also you can probably rewrite the whole thing like this and it'll be much faster (the key being a hash set that keeps track of which items you've already added and more or less instantly tells you if a given string is or isn't already added): ``` try { DataTable dtExcel = new DataTable(); dtExcel = ReadExcel(filePath, fileExt); //read excel file HashSet addedItems = new HashSet(); dataGridView1.DataSource = dtExcel; mydatagrid.Rows.Clear(); for (int i = 1; i < dataGridView1.Rows.Count; i++) { if (!addedItems.Contains(dataGridView1.Rows[i].Cells[0].Value.ToString())) { mydatagrid.Rows.Add(dataGridView1.Rows[i].Cells[0].Value.ToString(), dataGridView1.Rows[i].Cells[1].Value.ToString(), dataGridView1.Rows[i].Cells[2].Value.ToString(), dataGridView1.Rows[i].Cells[3].Value.ToString()); addedItems.Add(dataGridView1.Rows[i].Cells[0].Value.ToString()); } } } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: 1. Change exists from string to bool 2. Create task for work each task have number of loop less than 5000 (by you work find) see Task.wait <https://msdn.microsoft.com/en-us/library/dd235635(v=vs.110).aspx> 3. Use mydatagrid.Rows.Add after filter twice data complete , first store it on List and use linq find data (where) instead while . see <https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.where?view=netframework-4.7.1> I think it can help you a little .... Upvotes: 2
2018/03/15
1,209
3,773
<issue_start>username_0: I am trying to check if 2 consecutive values in a string are characters (minus 5 operators I pre-determined). I tried doing this: ``` test = "abcdefghijklmnop" bad = "abfj" for i in test: if i in bad and i+1 in bad: print("it works") ``` with no luck. Is there anyway to get the next index of a string inside of a loop? Thanks!<issue_comment>username_1: `i` isn't the *index*, it's the actual *character*. That's why you can just write `i in bad` instead of `test[i] in bad`. If you want the index as well as the character, use `enumerate`, like this: ``` for idx, ch in enumerate(test): if ch in bad and test[idx+1] in bad: ``` Or just use the index for both: ``` for idx in range(len(test)): if test[idx] in bad and test[idx+1] in bad: ``` Also, notice that whichever way you do this, you're going to have a bug when you reach the last character—you're going to try to check the next character, but there *is* no next character. --- If you want to think a bit more abstractly, the `pairwise` function in [th recipes in the `itertools` docs](http://docs.python.org/library/itertools.html#recipes) (or you can `pip install` either `toolz` or `more-itertools`; I think they both have it) will let you loop over adjacent pairs of *anything*. So: ``` for current_char, next_char in pairwise(test): if current_char in bad and next_char in bad: ``` Or maybe this is a bit easier to understand, if less flexible: ``` for current_char, next_char in zip(test, test[1:]): if current_char in bad and next_char in bad: ``` --- Here's another trick that lets you avoid having to do two separate tests, if you understand the idea of set intersection: ``` bad = set(bad) for idx in range(len(test)): if bad.intersection(test[idx:idx+2]): ``` You still need to deal with the "last one" problem—you'll get an incorrect test instead of an exception, but it's still wrong. You can also combine this with `pairwise`. Upvotes: 2 [selected_answer]<issue_comment>username_2: You can use a generator expression with `zip` for this. The benefit of using a generator expression versus list comprehension is you do not have to iterate the entire string. ``` test = "abcdefghijklmnop" bad = "abfj" bad_set = set(bad) res = ((i in bad_set) and (j in bad_set) for i, j in zip(test, test[1:])) for k in res: if k: print(k) break # True ``` Upvotes: 1 <issue_comment>username_3: the i in that loop is a string,therefor you can't use it as an index change this part of the code to this: ``` for i in range(0,len(test)): while(i+1 ``` Upvotes: -1 <issue_comment>username_4: If you are only trying to check whether two consecutive characters of `test` match in `bad`(not interested in which two) you can do ``` >>> any("".join([i,j]) in bad for i,j in zip(test,test[1:])) >>> True ``` If you want which two characters match and which of them don't: ``` >>> [("".join([i,j]) in bad,"".join([i,j])) for i,j in zip(test,test[1:])] >>> [(True, 'ab'), (False, 'bc'), (False, 'cd'), (False, 'de'), (False, 'ef'), (False, 'fg'), (False, 'gh'), (False, 'hi'), (False, 'ij'), (False, 'jk'), (False, 'kl'), (False, 'lm'), (False, 'mn'), (False, 'no'), (False, 'op')] ``` Upvotes: 2 <issue_comment>username_5: with range method in one line: ``` test = "abcdefghijklmnop" bad = "abfj" print([("true",test[i:i+2]) for i in range(0,len(test),1) if test[i:i+2] in bad]) ``` With recursive approach: ``` test = "abcdefghijklmnop" bad = "abfj" def recursive_approach(test1): print(test1) if not test1: return 0 else: if test1[:2] in bad: print('True', test1[:2]) return recursive_approach(test1[1:]) print(recursive_approach(test)) ``` Upvotes: 0
2018/03/15
421
1,255
<issue_start>username_0: I have a table who have creation date like: ``` SELECT [CreationDate] FROM Store.Order ``` So each register have one datetime like: ``` 2018-03-14 00:00:00.000 2017-04-14 00:00:00.000 2017-06-14 00:00:00.000 ``` I want to know how to `COUNT` only register of Date equals to current month and year, for example in this case,if I only have one register in month 03 I just get 1 on count, how can I achieve it? Regards<issue_comment>username_1: Here is one option: ``` SELECT COUNT(*) FROM Store.Order WHERE CONVERT(varchar(7), [CreationDate], 126) = CONVERT(varchar(7), GETDATE(), 126); ``` [Demo ----](http://rextester.com/NLHQPE86189) We can convert both the creation date in your table and the current date into `yyyy-mm` strings, and then check if they be equal. Upvotes: 3 [selected_answer]<issue_comment>username_2: The most efficient way is to do: ``` where creationdate >= dateadd(day, 1 - day(getdate(), cast(getdate() as date)) and creationdate < dateadd(month, 1, dateadd(day, 1 - day(getdate(), cast(getdate() as date))) ``` Although this looks more complex than other solutions, all the complexity is on `getdate()` -- meaning that the optimizer can use indexes on `creationdate`. Upvotes: 0
2018/03/15
1,008
4,253
<issue_start>username_0: I have a cloud function that is triggered by a Firestore database write. It does an async operation (fetch data from some 3rd party API's) that may take a long time, might not. When it's finished, it writes the result to a 'search result' field. There's a possible race condition where the result from a newer trigger gets overwritten by an older operation that finishes this later. How should I solve this problem in the context of Firebase cloud functions and Firestore?<issue_comment>username_1: In general there are two approaches here: 1. Ensure your operations are idempotent 2. Ensure your operations detect conflicting updates and retry ### Ensure your operations are idempotent This is often the most scaleable and architecturally simple. When you perform the same idempotent operation on the same input, it has the same result. This means that it doesn't matter if the operation is performed multiple times, as the result will be the same. A good example of this is in the [Firestore documentation on arrays and sets](https://firebase.google.com/docs/firestore/solutions/arrays). Imagine that you're tagging blog posts with categories. A naïve model for this would be: ``` { title: "My great post", categories: [ "technology", "opinion", "cats" ] } ``` But now imagine that two users are tagging the same post as being about cats at almost the same time. You might end up with ``` { title: "My great post", categories: [ "technology", "opinion", "cats", "cats" ] } ``` Which is clearly not what you wanted. But since the data structure allows it, this may happen. The ideal solution here is to use a data structure that makes this impossible: a data structure where adding `cat` is an idempotent operation. In mathematical terms this would be a set, and in Firestore you'd model that as: ``` { title: "My great post", categories: { "technology": true, "opinion": true, "cats": true } } ``` Now in this structure, it doesn't matter how often you set `cats` to `true`, the result will always be the same. ### Ensure your operations detect conflicting updates and retry Sometimes it isn't possible (or feasible) to make your operations idempotent. In that case, you can also consider using a compare-and-set strategy. For example, say that the 3rd party API changes the data in some way, and that you want to only write the result back to the database if the original data in the database is unmodified. In that case you'll want to take these steps in your function: 1. read the original data 2. call the 3rd party API with the data 3. wait for the result 4. start a transaction 5. load the original data again 6. if the data has been modified go back to #2 7. if the data was not modified write the result from the 3rd party API This type of compare-and-set operation is actually how Firebase's Realtime Database implements transactions, with the "3rd party API" being your applications transaction handler. As you can probably see this second approach is more complex than the approach with idempotent operations. So when possible, I'd always recommend that approach. Upvotes: 5 [selected_answer]<issue_comment>username_2: Firebase cloud function provides transact() function and that could be used just to save some data onto database atomically. Upvotes: -1 <issue_comment>username_3: Although not a direct answer to the OP's question regarding waiting for a 3rd party response, for those who came here from a Google search for a generalized Firestore race condition solution, Firestore supports both transactions and batched writes: > > Cloud Firestore supports atomic operations for reading and writing data. In a set of atomic operations, either all of the operations succeed, or none of them are applied. There are two types of atomic operations in Cloud Firestore: > > > * Transactions: a transaction is a set of read and write operations on one or more documents. > * Batched Writes: a batched write is a set of write operations on one or more documents. > > > For more details, see: <https://firebase.google.com/docs/firestore/manage-data/transactions> Upvotes: 1
2018/03/15
2,658
9,167
<issue_start>username_0: I used Gmail API with curl.( [Users.messages: send](https://developers.google.com/gmail/api/v1/reference/users/messages/send)) But I recieve Error 400 recipient address required. **Command** ``` curl -X POST -H "Authorization: Bearer *****" -H "Content-Type:message/rfc822" -d "{'raw':'Encoded Value'}" "https://www.googleapis.com/upload/gmail/v1/users/me/messages/send" ``` **Response** ``` { "error": { "errors": [ { "domain": "global", "reason": "invalidArgument", "message": "Recipient address required" } ], "code": 400, "message": "Recipient address required" } } ``` The encoded value was created by the following python script. ``` import base64 from email.mime.text import MIMEText from email.utils import formatdate MAIL_FROM = "<EMAIL>" MAIL_TO = "<EMAIL>" def create_message(): message = MIMEText("Gmail body: Hello world!") message["from"] = MAIL_FROM message["to"] = MAIL_TO message["subject"] = "gmail api test" message["Date"] = formatdate(localtime=True) byte_msg = message.as_string().encode(encoding="UTF-8") byte_msg_b64encoded = base64.urlsafe_b64encode(byte_msg) str_msg_b64encoded = byte_msg_b64encoded.decode(encoding="UTF-8") return {"raw": str_msg_b64encoded} print(create_message()) ```<issue_comment>username_1: When the messages are sent by the media upload requests using `https://www.googleapis.com/upload/gmail/v1/users/me/messages/send`, the request body is required to be created as follows. I modified your python script for creating the request body. Please confirm it. Modified python script : ------------------------ ``` import base64 from email.mime.text import MIMEText from email.utils import formatdate MAIL_FROM = "<EMAIL>" MAIL_TO = "<EMAIL>" def encode(v): byte_msg = v.encode(encoding="UTF-8") byte_msg_b64encoded = base64.b64encode(byte_msg) return byte_msg_b64encoded.decode(encoding="UTF-8") def create_message(): message = "To: " + MAIL_TO + "\n" message += "From: " + MAIL_FROM + "\n" message += "Subject: =?utf-8?B?" + encode("gmail api test") + "?=\n" message += "Date: " + formatdate(localtime=True) + "\n" message += "Content-Type: multipart/alternative; boundary=boundaryboundary\n\n" message += "--boundaryboundary\n" message += "Content-Type: text/plain; charset=UTF-8\n" message += "Content-Transfer-Encoding: base64\n\n" message += encode("Hello world!") + "\n\n" message += "--boundaryboundary" return message print(create_message()) ``` ### Result : ``` To: <EMAIL> From: <EMAIL> Subject: =?utf-8?B?Z21haWwgYXBpIHRlc3Q=?= Date: Thu, 15 Mar 2018 01:23:45 +0100 Content-Type: multipart/alternative; boundary=boundaryboundary --boundaryboundary Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: base64 SGVsbG8gd29ybGQh --boundaryboundary ``` Please save above request body to a file as a text file. As a sample, the filename is `sample.txt`. ### Important point : Here, please be careful the place of "EOF" of the file. Please don't break after the last `--boundaryboundary`. If it breaks after the last `--boundaryboundary`, the body is not received. The image is as follows. [![enter image description here](https://i.stack.imgur.com/cDPkn.png)](https://i.stack.imgur.com/cDPkn.png) Curl command : -------------- ``` curl -s -X POST \ -H "Authorization: Bearer *****" \ -H "Content-Type: message/rfc822" \ --data-binary "@sample.txt" \ "https://www.googleapis.com/upload/gmail/v1/users/me/messages/send" ``` It posts `sample.txt` as the binary data. ### Result : ``` { "id": "#####", "threadId": "#####", "labelIds": [ "UNREAD", "SENT", "INBOX" ] } ``` Note : ------ * This is a very simple sample, so please modify this to your environment. * This answer supposes that your access token can be used for this situation. If the error related to the access token occurs, please check the scopes. If I misunderstand your question, I'm sorry. Upvotes: 3 [selected_answer]<issue_comment>username_2: I would like to give my thanks to the other answers which were helpful. My use case required me to use the user's access token obtained from Gmail and respond back to a given message thread. In this, I had to modify the above answer given by **username_1** to the following. ``` import base64 import mimetypes import os import traceback from email.mime.audio import MIMEAudio from email.mime.base import MIMEBase from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import httplib2 from apiclient import discovery from oauth2client.client import AccessTokenCredentials def send_message(access_token: str, sender: str, to: str, subject: str, html_message: str, thread_id: str, user_id: str = 'me', attachment_file=None): try: # Referenced from: https://oauth2client.readthedocs.io/en/latest/source/oauth2client.client.html credentials = AccessTokenCredentials(access_token, 'PostmanRuntime/7.29.2') http = credentials.authorize(httplib2.Http()) service = discovery.build('gmail', 'v1', http=http) if attachment_file: message_body = __create_message_with_attachment__(sender, to, subject, html_message, thread_id, attachment_file) else: message_body = __create_message_body__(sender, to, subject, html_message, thread_id) response = (service.users().messages().send(userId=user_id, body=message_body).execute()) print(response) return response['id'] except Exception as e: traceback.print_exc() def __create_message_body__(from_email: str, to_email: str, subject: str, message_body: str, thread_id: str): msg = MIMEMultipart('alternative') msg['Subject'] = subject msg['From'] = from_email msg['To'] = to_email msg.attach(MIMEText(message_body, 'plain')) msg.attach(MIMEText(message_body, 'html')) return { 'raw': base64.urlsafe_b64encode(msg.as_string().encode()).decode(), 'threadId': thread_id } def __create_message_with_attachment__(sender: str, to: str, subject: str, message_body, thread_id: str, attachment_file: str): """Create a message for an email. Args: sender: Email address of the sender. to: Email address of the receiver. subject: The subject of the email message. message_body: Html message to be sent thread_id: thread id to respond to attachment_file: The path to the file to be attached. Returns: An object containing a base64url encoded email object. """ message = MIMEMultipart('mixed') message['to'] = to message['from'] = sender message['subject'] = subject message_alternative = MIMEMultipart('alternative') message_related = MIMEMultipart('related') message_related.attach(MIMEText(message_body, 'html')) message_alternative.attach(MIMEText(message_body, 'plain')) message_alternative.attach(message_related) message.attach(message_alternative) print("create_message_with_attachment: file: %s" % attachment_file) content_type, encoding = mimetypes.guess_type(attachment_file) if content_type is None or encoding is not None: content_type = 'application/octet-stream' main_type, sub_type = content_type.split('/', 1) if main_type == 'text': fp = open(attachment_file, 'rb') msg = MIMEText(fp.read(), _subtype=sub_type) fp.close() elif main_type == 'image': fp = open(attachment_file, 'rb') msg = MIMEImage(fp.read(), _subtype=sub_type) fp.close() elif main_type == 'audio': fp = open(attachment_file, 'rb') msg = MIMEAudio(fp.read(), _subtype=sub_type) fp.close() else: fp = open(attachment_file, 'rb') msg = MIMEBase(main_type, sub_type) msg.set_payload(fp.read()) fp.close() filename = os.path.basename(attachment_file) msg.add_header('Content-Disposition', 'attachment', filename=filename) message.attach(msg) return { 'raw': base64.urlsafe_b64encode(message.as_string().encode()).decode(), 'threadId': thread_id } def main(): to = "<EMAIL>" sender = "<EMAIL>" subject = "subject" message = "Hi same message here" access_token = "ya29.a0AVA9y1uc1Ec-................" thread_id = '181b9292e6a.....' send_message(access_token=access_token, sender=sender, to=to, subject=subject, html_message=message, thread_id=thread_id) if __name__ == '__main__': main() ``` Please keep note of how I construct the required credential using the user's access token; ``` credentials = AccessTokenCredentials(access_token, 'user agent here') ``` This is obtained from <https://oauth2client.readthedocs.io/en/latest/source/oauth2client.client.html> Upvotes: 0
2018/03/15
2,114
6,991
<issue_start>username_0: Question: Write a program named SortWords that includes a method that accepts any number of words and sorts them in alphabetical order. Demonstrate that the program works correctly when the method is called with one, two, five, or ten words. What I have thus far: ``` private void button1_Click(object sender, EventArgs e) { String[] outWords = new string[20]; outWords[0] = textbox1.Text; outWords[1] = textBox2.Text; outWords[2] = textBox3.Text; outWords[3] = textBox4.Text; outWords[4] = textBox5.Text; outWords[5] = textBox6.Text; outWords[6] = textBox7.Text; outWords[7] = textBox8.Text; outWords[8] = textBox9.Text; outWords[9] = textBox10.Text; sortAndPrint(outWords[11]); } private void sortAndPrint(params string[] newWords) { Array.Sort(newWords); label1.Text = newWords[0]; label2.Text = newWords[1]; label3.Text = newWords[2]; label4.Text = newWords[3]; label5.Text = newWords[4]; label6.Text = newWords[5]; label7.Text = newWords[6]; label8.Text = newWords[7]; label9.Text = newWords[8]; label10.Text = newWords[9]; } ``` My issues here is that I either don't get anything in my label boxes or I get errors thrown from can't convert a string into `string[]` or `System.IndexOutOfRangeException`. I'm sure im doing something completely wrong here.<issue_comment>username_1: Try this : ``` private void button1_Click(object sender, EventArgs e) { string[] outWords = new string[10]; outWords[0] = textbox1.Text; outWords[1] = textBox2.Text; outWords[2] = textBox3.Text; outWords[3] = textBox4.Text; outWords[4] = textBox5.Text; outWords[5] = textBox6.Text; outWords[6] = textBox7.Text; outWords[7] = textBox8.Text; outWords[8] = textBox9.Text; outWords[9] = textBox10.Text; sortAndPrint(outWords); } private void sortAndPrint(string[] newWords) { Array.Sort(newWords); label1.Text = newWords[0]; label2.Text = newWords[1]; label3.Text = newWords[2]; label4.Text = newWords[3]; label5.Text = newWords[4]; label6.Text = newWords[5]; label7.Text = newWords[6]; label8.Text = newWords[7]; label9.Text = newWords[8]; label10.Text = newWords[9]; } ``` **Summary** Pass whole array `sortAndPrint(outWords);` not single element. Take array length only what you need. `string[] outWords = new string[10];` Please check [this question](https://stackoverflow.com/questions/7580277/why-use-the-params-keyword) for the use of `params`. You need to pass values when you user `param` but if you need to pass variable, you have to remove `params`. **Example of params** ``` private void button1_Click(object sender, EventArgs e) { sortAndPrint("one","two","three","four","five"); } private void sortAndPrint(params string[] newWords) { Array.Sort(newWords); label1.Text = newWords[0]; label2.Text = newWords[1]; label3.Text = newWords[2]; label4.Text = newWords[3]; label5.Text = newWords[4]; } ``` Upvotes: 1 <issue_comment>username_2: ``` sortAndPrint(outWords[11]); ``` will pass a *single* string (as an array) to `sortAndPrint`, so when you call ``` label2.Text = newWords[1]; ``` you get an out of bounds exception. Try just ``` sortAndPrint(outWords); ``` to pass the *entire* array. Also note that empty slots in the array wil get sorted *before* other strings, so you need to come up with a way to get rid of the blank/null string. Or, if the intent is to demonstrate how to use `params`, you could do something like: ``` sortAndPrint(textbox1.Text, textbox2.Text, textbox3.Text, textbox4.Text, textbox5.Text); ``` But you need to check the bounds of the array in `sortAndPrint`, rather than just assuming the array has a size of at least 10. Upvotes: 0 <issue_comment>username_3: If you read the instructions carefully, you have this requirement: > > ...includes a method that accepts any number of words... > > > You accomplish this by using the `params` keyword along with a `string[]`. > > ...and sorts them in alphabetical order. > > > This part you doing with `Array.Sort(newWords);` > > Demonstrate that the program works correctly when the method is called with one, two, five, or ten words > > > This part you're not doing - you're assuming in your code that the input array will have 10 items, when instead you should check to see how many items it has before outputting the results. Since the array size cannot be determined by the method, then it cannot make any assumption that there will be enough labels on the form to populate with the results. Given this, we could use a `MessageBox` to show the results instead, and we can use `String.Join` to join all the items in the array with an `Environment.NewLine` character in order to show the sorted words in different lines: ``` private void SortAndPrint(params string[] newWords) { Array.Sort(newWords); MessageBox.Show(string.Join(Environment.NewLine, newWords)); } ``` Now, we can demonstrate the use of this function by passing in different numbers of arguments to it. First, just so we're on the same page, I have this code in the `Form_Load` method that adds 10 textboxes to the form, all with the tag "input": ``` private void Form1_Load(object sender, EventArgs e) { var stdHeight = 20; var stdWidth = 100; var stdPad = 10; var count = 10; for (int i = 0; i < count; i++) { var textBox = new TextBox { Name = "textBox" + (i + 1), Left = stdPad, Width = stdWidth, Height = stdHeight, Top = (stdHeight + stdPad) * i + stdPad, Tag = "input" }; Controls.Add(textBox); } } ``` Now, in our button click event, we can search for all controls on the form who have the `Tag == "input"` and whose `.Text` property is not empty, and we can pass these `Text` values to our method both as a single array **OR** as individual items: ``` private void button1_Click(object sender, EventArgs e) { // Select all textbox Text fields that have some value var words = Controls.Cast() .Where(t => t.Tag == "input" && !string.IsNullOrWhiteSpace(t.Text)) .Select(t => t.Text) .ToArray(); // Pass all the words in a single array to our method SortAndPrint(words); // We can also demonstrate this by passing individual words // Pass one word if we can if (words.Length > 0) { SortAndPrint(words[0]); } // Pass two words if we can if (words.Length > 1) { SortAndPrint(words[0], words[1]); } // Pass five words if we can if (words.Length > 4) { SortAndPrint(words[0], words[1], words[2], words[3], words[4]); } // Pass ten words if we can if (words.Length > 9) { SortAndPrint(words[0], words[1], words[2], words[3], words[4], words[5], words[6], words[7], words[8], words[9]); } } ``` Upvotes: 0
2018/03/15
1,926
6,468
<issue_start>username_0: I am deleting a model in a many to one relation. Youll notice in the delete method I am exposing the parent model. This is for permissions which I will write later. The code is not deleting the objects. As in method runs and my javascript removes the object. But If I reload the page, I get the objects back. what could be happening? ``` def delete(self, request, *args, **kwargs): venuepk = kwargs.get('venuepk', None) venue = get_object_or_404(Venue, pk=venuepk) venuerooms = venue.room_set.all() roompk = kwargs.get('roompk') roomobject = None for room in venuerooms: if room.pk == roompk: roomobject = Room.objects.get(pk=roompk) roomobject.delete() return Response({}) return Response(status.HTTP_404_NOT_FOUND) ```<issue_comment>username_1: Try this : ``` private void button1_Click(object sender, EventArgs e) { string[] outWords = new string[10]; outWords[0] = textbox1.Text; outWords[1] = textBox2.Text; outWords[2] = textBox3.Text; outWords[3] = textBox4.Text; outWords[4] = textBox5.Text; outWords[5] = textBox6.Text; outWords[6] = textBox7.Text; outWords[7] = textBox8.Text; outWords[8] = textBox9.Text; outWords[9] = textBox10.Text; sortAndPrint(outWords); } private void sortAndPrint(string[] newWords) { Array.Sort(newWords); label1.Text = newWords[0]; label2.Text = newWords[1]; label3.Text = newWords[2]; label4.Text = newWords[3]; label5.Text = newWords[4]; label6.Text = newWords[5]; label7.Text = newWords[6]; label8.Text = newWords[7]; label9.Text = newWords[8]; label10.Text = newWords[9]; } ``` **Summary** Pass whole array `sortAndPrint(outWords);` not single element. Take array length only what you need. `string[] outWords = new string[10];` Please check [this question](https://stackoverflow.com/questions/7580277/why-use-the-params-keyword) for the use of `params`. You need to pass values when you user `param` but if you need to pass variable, you have to remove `params`. **Example of params** ``` private void button1_Click(object sender, EventArgs e) { sortAndPrint("one","two","three","four","five"); } private void sortAndPrint(params string[] newWords) { Array.Sort(newWords); label1.Text = newWords[0]; label2.Text = newWords[1]; label3.Text = newWords[2]; label4.Text = newWords[3]; label5.Text = newWords[4]; } ``` Upvotes: 1 <issue_comment>username_2: ``` sortAndPrint(outWords[11]); ``` will pass a *single* string (as an array) to `sortAndPrint`, so when you call ``` label2.Text = newWords[1]; ``` you get an out of bounds exception. Try just ``` sortAndPrint(outWords); ``` to pass the *entire* array. Also note that empty slots in the array wil get sorted *before* other strings, so you need to come up with a way to get rid of the blank/null string. Or, if the intent is to demonstrate how to use `params`, you could do something like: ``` sortAndPrint(textbox1.Text, textbox2.Text, textbox3.Text, textbox4.Text, textbox5.Text); ``` But you need to check the bounds of the array in `sortAndPrint`, rather than just assuming the array has a size of at least 10. Upvotes: 0 <issue_comment>username_3: If you read the instructions carefully, you have this requirement: > > ...includes a method that accepts any number of words... > > > You accomplish this by using the `params` keyword along with a `string[]`. > > ...and sorts them in alphabetical order. > > > This part you doing with `Array.Sort(newWords);` > > Demonstrate that the program works correctly when the method is called with one, two, five, or ten words > > > This part you're not doing - you're assuming in your code that the input array will have 10 items, when instead you should check to see how many items it has before outputting the results. Since the array size cannot be determined by the method, then it cannot make any assumption that there will be enough labels on the form to populate with the results. Given this, we could use a `MessageBox` to show the results instead, and we can use `String.Join` to join all the items in the array with an `Environment.NewLine` character in order to show the sorted words in different lines: ``` private void SortAndPrint(params string[] newWords) { Array.Sort(newWords); MessageBox.Show(string.Join(Environment.NewLine, newWords)); } ``` Now, we can demonstrate the use of this function by passing in different numbers of arguments to it. First, just so we're on the same page, I have this code in the `Form_Load` method that adds 10 textboxes to the form, all with the tag "input": ``` private void Form1_Load(object sender, EventArgs e) { var stdHeight = 20; var stdWidth = 100; var stdPad = 10; var count = 10; for (int i = 0; i < count; i++) { var textBox = new TextBox { Name = "textBox" + (i + 1), Left = stdPad, Width = stdWidth, Height = stdHeight, Top = (stdHeight + stdPad) * i + stdPad, Tag = "input" }; Controls.Add(textBox); } } ``` Now, in our button click event, we can search for all controls on the form who have the `Tag == "input"` and whose `.Text` property is not empty, and we can pass these `Text` values to our method both as a single array **OR** as individual items: ``` private void button1_Click(object sender, EventArgs e) { // Select all textbox Text fields that have some value var words = Controls.Cast() .Where(t => t.Tag == "input" && !string.IsNullOrWhiteSpace(t.Text)) .Select(t => t.Text) .ToArray(); // Pass all the words in a single array to our method SortAndPrint(words); // We can also demonstrate this by passing individual words // Pass one word if we can if (words.Length > 0) { SortAndPrint(words[0]); } // Pass two words if we can if (words.Length > 1) { SortAndPrint(words[0], words[1]); } // Pass five words if we can if (words.Length > 4) { SortAndPrint(words[0], words[1], words[2], words[3], words[4]); } // Pass ten words if we can if (words.Length > 9) { SortAndPrint(words[0], words[1], words[2], words[3], words[4], words[5], words[6], words[7], words[8], words[9]); } } ``` Upvotes: 0
2018/03/15
814
3,167
<issue_start>username_0: Say I have a simple Windows 10 UWP app ```xml > ``` The large number of ListView items causes it to overflow and scroll, as expected: [![enter image description here](https://i.stack.imgur.com/Hcru8.png)](https://i.stack.imgur.com/Hcru8.png) However, if I need to add another control as a sibling of the ListView, like so (replacing the Grid with a StackPanel for simplicity) ```xml ... ``` then the scrollbar disappears and the ListView isn't scrollable anymore. The content just gets clipped / cut off past the bottom of the window. What's going on here and how can I make it scroll again?<issue_comment>username_1: The key to this is the [ScrollViewer control](https://learn.microsoft.com/en-gb/windows/uwp/design/controls-and-patterns/scroll-controls). The reason ListViews and GridViews can scroll in the first place is because they have a ScrollViewer built in. When you place a ListView inside a parent layout panel (e.g. a StackPanel or a Grid row), if the ListView height is greater than the viewport, the parent panel becomes the full height of the ListView. But StackPanel doesn't implement ScrollViewer so it can't scroll, and you end up with a StackPanel extending off the bottom edge of the viewport. The fix is simple: put the parent layout panel in question inside a ScrollViewer ```xml ... ``` --- [ScrollViewer API reference - MSDN](https://learn.microsoft.com/en-us/uwp/api/windows.ui.xaml.controls.scrollviewer) Upvotes: 3 [selected_answer]<issue_comment>username_2: Going to add more context to username_1's answer: It depends on the layout logic of the panel you're using! To note beforehand: `ListView` internally has it's own `ScrollViewer` by default. When laying out it's children, a `Grid` will typically tell its children they should fit inside the bounds the grid. In the case of the `ListView`, it's happy to do this, and it's own internal `ScrollViewer` handles it's children scrolling. `StackPanel` on the other hand tells its children they have virtually infinite space to layout in in it's stacking direction - so your `ListView` has no idea it has to constrain itself to the height of your `StackPanel` because the `StackPanel` does not tell it do so and so the ListView never needs to use it's own `ScrollViewer` as it thinks it has infinite space. Now, put a `StackPanel` in a `ScrollViewer` by itself doesn't help - if you put that `ScrollViewer` inside a `StackPanel` you have the same problem as the `ListView` does - it thinks it has infinite space and so never needs to scroll it's content. But, put the `ScrollViewer` in a `Grid` and the grid will give the ScrollViewer a defined size to layout in, and so anything inside the `ScrollViewer` will now scroll if it get's too big. Put a `ListView` inside this `StackPanel` inside this `ScrollViewer`? The `ListView` still thinks it has infinite space and so never needs to use its own scroller, BUT it's also disables and virtualization and performance enhancements the `ListView` would normally have, as they rely on it's interal `ScrollViewer` actually being put a too use. (username_1's XAML answer will work.) Upvotes: 1
2018/03/15
1,686
5,281
<issue_start>username_0: I have to plot several curves with very high xtick density, say 1000 date strings. To prevent these tick labels overlapping each other I manually set them to be 60 dates apart. Code below: ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt ts_index = pd.period_range(start="20060429", periods=1000).strftime("%Y%m%d") fig = plt.figure(1) ax = plt.subplot(1, 1, 1) tick_spacing = 60 for i in range(5): plt.plot(ts_index, 1 + i * 0.01 * np.arange(0, 1000), label="group %d"%i) plt.legend(loc='best') plt.title(r'net value curves') xticks = ax.get_xticks() xlabels = ax.get_xticklabels() ax.set_xticks(xticks[::tick_spacing]) ax.set_xticklabels(xlabels[::tick_spacing]) plt.xticks(rotation="vertical") plt.xlabel(r'date') plt.ylabel('net value') plt.grid(True) plt.show() fig.savefig(r".\net_value_curves.png", ) fig.clf() ``` I'm running this piece of code in PyCharm Community Edition 2017.2.2 with a Python 3.6 kernel. Now comes the funny thing: whenever I ran the code in the normal "run" mode (i.e. just hit the execution button and let the code run "freely" till interruption or termination), then the figure I got would always miss xticklabels: [![enter image description here](https://i.stack.imgur.com/O9SvP.png)](https://i.stack.imgur.com/O9SvP.png) However, if I ran the code in "debug" mode and ran it step by step then I would get an expected figure with complete xticklabels: [![enter image description here](https://i.stack.imgur.com/zNVy5.png)](https://i.stack.imgur.com/zNVy5.png) This is really weird. Anyway, I just hope to find a way that can ensure me getting the desired output (the second figure) in the normal "run" mode. How can I modify my current code to achieve this? Thanks in advance!<issue_comment>username_1: You can set the visibility of the xticks-labels to `False` ``` for label in plt.gca().xaxis.get_ticklabels()[::N]: label.set_visible(False) ``` This will set every Nth label invisible. Upvotes: 0 <issue_comment>username_2: In general, the [`Axis`](https://matplotlib.org/api/axis_api.html#axis-objects) object computes and places ticks using a [`Locator`](https://matplotlib.org/api/ticker_api.html#ticker) object. `Locator`s and `Formatter`s are meant to be easily replaceable, with appropriate [methods](https://matplotlib.org/api/axis_api.html#formatters-and-locators) of `Axis`. The default `Locator` does not seem to be doing the trick for you so you can replace it with anything you want using [`axes.xaxis.set_major_locator`](https://matplotlib.org/api/_as_gen/matplotlib.axis.Axis.set_major_locator.html#matplotlib.axis.Axis.set_major_locator). This problem is not complicated enough to write your own, so I would suggest that [`MaxNLocator`](https://matplotlib.org/api/ticker_api.html#matplotlib.ticker.MaxNLocator) fits your needs fairly well. Your example seems to work well with `nbins=16` (which is what you have in the picture, since there are 17 ticks. You need to add an import: ``` from matplotlib.ticker import MaxNLocator ``` You need to replace the block ``` xticks = ax.get_xticks() xlabels = ax.get_xticklabels() ax.set_xticks(xticks[::tick_spacing]) ax.set_xticklabels(xlabels[::tick_spacing]) ``` with ``` ax.xaxis.set_major_locator(MaxNLocator(nbins=16)) ``` or just ``` ax.xaxis.set_major_locator(MaxNLocator(16)) ``` You may want to play around with the other arguments (all of which have to be keywords, except `nbins`). Pay especial attention to `integer`. Note that for the `Locator` and `Formatter` APIs we work with an `Axis` object, not `Axes`. `Axes` is the whole plot, while `Axis` is the thing with the spines on it. `Axes` usually contains two `Axis` objects and all the other stuff in your plot. Upvotes: 1 <issue_comment>username_3: Your x axis data are strings. Hence you will get one tick per data point. This is probably not what you want. Instead use the dates to plot. Because you are using pandas, this is easily converted, ``` dates = pd.to_datetime(ts_index, format="%Y%m%d") ``` You may then get rid of your manual xtick locating and formatting, because matplotlib will automatically choose some nice tick locations for you. ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt ts_index = pd.period_range(start="20060429", periods=1000).strftime("%Y%m%d") dates = pd.to_datetime(ts_index, format="%Y%m%d") fig, ax = plt.subplots() for i in range(5): plt.plot(dates, 1 + i * 0.01 * np.arange(0, 1000), label="group %d"%i) plt.legend(loc='best') plt.title(r'net value curves') plt.xticks(rotation="vertical") plt.xlabel(r'date') plt.ylabel('net value') plt.grid(True) plt.show() ``` [![enter image description here](https://i.stack.imgur.com/Le4HX.png)](https://i.stack.imgur.com/Le4HX.png) However in case you do want to have some manual control over the locations and formats you may use `matplotlib.dates` locators and formatters. ``` # tick every 3 months plt.gca().xaxis.set_major_locator(mdates.MonthLocator((1,4,7,10))) # format as "%Y%m%d" plt.gca().xaxis.set_major_formatter(mdates.DateFormatter("%Y%m%d")) ``` [![enter image description here](https://i.stack.imgur.com/psB1w.png)](https://i.stack.imgur.com/psB1w.png) Upvotes: 2 [selected_answer]
2018/03/15
1,410
4,537
<issue_start>username_0: I have some javascript code that fires a click event when the user scrolls up or down past a specific element (`.closemenu`). I'm using this to automatically open and close a header menu when the user scrolls the page. The problem I have is that this is firing too many times and causing lagging and glitching on scroll, I've found [this post](https://stackoverflow.com/questions/10966710/choppy-laggy-scroll-event-on-chrome-and-ie) which shows the usage of throttling for scroll events but I can't get it to work with my current javascript which is: ``` jQuery(window).scroll(function() { var hT = jQuery('.closemenu').offset().top, hH = jQuery('.closemenu').outerHeight(), wH = jQuery(window).height(), wS = jQuery(this).scrollTop(); console.log((hT-wH) , wS); if (wS > (hT+hH-wH) && (hT > wS) && (wS+wH > hT+hH)){ jQuery('.menu-bar').trigger('click'); } }); ``` I've tried a few variations but I can't work out what the issue is, does anyone know how can I throttle this event by 30ms or so?<issue_comment>username_1: You can set the visibility of the xticks-labels to `False` ``` for label in plt.gca().xaxis.get_ticklabels()[::N]: label.set_visible(False) ``` This will set every Nth label invisible. Upvotes: 0 <issue_comment>username_2: In general, the [`Axis`](https://matplotlib.org/api/axis_api.html#axis-objects) object computes and places ticks using a [`Locator`](https://matplotlib.org/api/ticker_api.html#ticker) object. `Locator`s and `Formatter`s are meant to be easily replaceable, with appropriate [methods](https://matplotlib.org/api/axis_api.html#formatters-and-locators) of `Axis`. The default `Locator` does not seem to be doing the trick for you so you can replace it with anything you want using [`axes.xaxis.set_major_locator`](https://matplotlib.org/api/_as_gen/matplotlib.axis.Axis.set_major_locator.html#matplotlib.axis.Axis.set_major_locator). This problem is not complicated enough to write your own, so I would suggest that [`MaxNLocator`](https://matplotlib.org/api/ticker_api.html#matplotlib.ticker.MaxNLocator) fits your needs fairly well. Your example seems to work well with `nbins=16` (which is what you have in the picture, since there are 17 ticks. You need to add an import: ``` from matplotlib.ticker import MaxNLocator ``` You need to replace the block ``` xticks = ax.get_xticks() xlabels = ax.get_xticklabels() ax.set_xticks(xticks[::tick_spacing]) ax.set_xticklabels(xlabels[::tick_spacing]) ``` with ``` ax.xaxis.set_major_locator(MaxNLocator(nbins=16)) ``` or just ``` ax.xaxis.set_major_locator(MaxNLocator(16)) ``` You may want to play around with the other arguments (all of which have to be keywords, except `nbins`). Pay especial attention to `integer`. Note that for the `Locator` and `Formatter` APIs we work with an `Axis` object, not `Axes`. `Axes` is the whole plot, while `Axis` is the thing with the spines on it. `Axes` usually contains two `Axis` objects and all the other stuff in your plot. Upvotes: 1 <issue_comment>username_3: Your x axis data are strings. Hence you will get one tick per data point. This is probably not what you want. Instead use the dates to plot. Because you are using pandas, this is easily converted, ``` dates = pd.to_datetime(ts_index, format="%Y%m%d") ``` You may then get rid of your manual xtick locating and formatting, because matplotlib will automatically choose some nice tick locations for you. ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt ts_index = pd.period_range(start="20060429", periods=1000).strftime("%Y%m%d") dates = pd.to_datetime(ts_index, format="%Y%m%d") fig, ax = plt.subplots() for i in range(5): plt.plot(dates, 1 + i * 0.01 * np.arange(0, 1000), label="group %d"%i) plt.legend(loc='best') plt.title(r'net value curves') plt.xticks(rotation="vertical") plt.xlabel(r'date') plt.ylabel('net value') plt.grid(True) plt.show() ``` [![enter image description here](https://i.stack.imgur.com/Le4HX.png)](https://i.stack.imgur.com/Le4HX.png) However in case you do want to have some manual control over the locations and formats you may use `matplotlib.dates` locators and formatters. ``` # tick every 3 months plt.gca().xaxis.set_major_locator(mdates.MonthLocator((1,4,7,10))) # format as "%Y%m%d" plt.gca().xaxis.set_major_formatter(mdates.DateFormatter("%Y%m%d")) ``` [![enter image description here](https://i.stack.imgur.com/psB1w.png)](https://i.stack.imgur.com/psB1w.png) Upvotes: 2 [selected_answer]
2018/03/15
447
1,377
<issue_start>username_0: How can you check if two DOM nodes are siblings without jquery? ``` ``` `a` and `c` are siblings but `a` and `d` are not. `a` and `a` are not siblings.<issue_comment>username_1: Just check their `.parentElement` property. ``` let isSibling = el1 !== el2 && el1.parentElement === el2.parentElement; ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: Why not check `parentNode` (or `parentElement`) property? ``` function areSiblings(a, b) { return a!=b && a.parentNode == b.parentNode; } ``` Upvotes: 2 <issue_comment>username_3: Just use [`.parentElement` or `.parentNode`](https://stackoverflow.com/questions/8685739/difference-between-dom-parentnode-and-parentelement) to determine if they share the same parent. ```js var a = document.querySelector('a'); var b = document.querySelector('b'); var c = document.querySelector('c'); var d = document.querySelector('d'); function areSiblings(x, y) { return x !== y && x.parentElement === y.parentElement; } function areSiblings2(x, y) { return x !== y && x.parentNode === y.parentNode; } console.log(areSiblings(a, b)); // true console.log(areSiblings(a, c)); // true console.log(areSiblings(a, d)); // false console.log(areSiblings2(a, b)); // true console.log(areSiblings2(a, c)); // true console.log(areSiblings2(a, d)); // false ``` ```html ``` Upvotes: 1
2018/03/15
1,246
4,424
<issue_start>username_0: I'm currently working on a random grid generation base for game map and I'm kinda stuck at how do I call an instantiated object based on their in game coordinates (not Vector3). This is my hex generation script: ``` public HexCell cellPrefab; HexCell[] cells; void CreateCell (int x, int z, int i) { Vector3 position; position.x = (x + z * 0.5f - z / 2) * (HexMetrics.innerRadius * 2f); position.y = 0f; position.z = z * (HexMetrics.outerRadius * 1.5f); HexCell cell = cells[i] = Instantiate(cellPrefab); cell.coordinates = HexCoordinates.FromOffsetCoordinates(x, z); } ``` I can call the object fine using index of objects' array but I can't wrap my head around the idea of calling it based on its given coordinates. This is how I give them coordinates based on each hex position; ``` public class HexCell : MonoBehaviour { public HexCoordinates coordinates; } public struct HexCoordinates { [SerializeField] private int x, z; public int X { get { return x; } } public int Y { get { return -X - Z; } } public int Z { get { return z; } } public HexCoordinates (int x, int z) { this.x = x; this.z = z; } public static HexCoordinates FromOffsetCoordinates (int x, int z) { return new HexCoordinates(x - z / 2, z); } } ``` So how do I call/select desired hex based on HexCell coordinates?<issue_comment>username_1: > > So how do I call/select desired hex based on HexCell coordinates? > > > This is easy to do since you used `int` instead of `float` to represent the coordinate. Just loop over the `cells` array. In each loop, access the `coordinates` variable from the `HexCell` component then compare x, `y` and z values. If they match, return the current `HexCell` in the loop. If not, simply return `null`. You can also do this with `linq` but avoid it. Your cell array: ``` HexCell[] cells; ``` Get `HexCell` from coordinate: ``` HexCell getHexCellFromCoordinate(int x, int y, int z) { //Loop thorugh each HexCell for (int i = 0; i < cells.Length; i++) { HexCoordinates hc = cells[i].coordinates; //Check if coordinate matches then return it if ((hc.X == x) && (hc.Y == y) && (hc.Z == z)) { return cells[i]; } } //No match. Return null return null; } ``` Since the coordinate is in `int` instead of `float`, you can also use [`Vector3Int`](https://docs.unity3d.com/ScriptReference/Vector3Int.html)*(Requires Unity 2017.2 and above)* to represent them instead of x, y and z. Note that this is different from [`Vector3`](https://docs.unity3d.com/ScriptReference/Vector3.html). ``` HexCell getHexCellFromCoordinate(Vector3Int coord) { //Loop thorugh each HexCell for (int i = 0; i < cells.Length; i++) { HexCoordinates hc = cells[i].coordinates; //Check if coordinate matches then return it if ((hc.X == coord.x) && (hc.Y == coord.y) && (hc.Z == coord.z)) { return cells[i]; } } //No match. Return null return null; } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Alternatively, you could use some built-in functions to make it more readable. ``` HexCell getHexCellFromCoordinate(int x, int y, int z) { return cells.FirstOrDefault( cell => cell.x == x && cell.y == y && cell.z == z ); } HexCell getHexCellFromCoordinate(Vector3Int coord) { return cells.FirstOrDefault(cell => cell.x == coord.x && cell.y == coord.y && cell.z == coord.z ); } ``` It's worth noting, since I'm not sure where you'll be needing to find the cells, that `FirstOrDefault` makes heap allocations and therefore invoking it too often on too large of a list (as in tens of thousands of times per frame, and/or against tens of thousands of objects) it could result in undesired garbage collections, which *may* cause a stutter in your application, and that stutter *may* be noticeable if combined with other code that uses heap allocations willy-nilly. So as a general rule, start with something simple. If your application starts to slow down or take up too much memory, go back and optimize starting with the hottest (least performant) code. You can use a profiler to help you find those spots. But please, don't riddle your code with for loops just to save some extra cpu cycles. Upvotes: 0
2018/03/15
935
3,502
<issue_start>username_0: So I have a button in Android. When this button is pressed it runs an ASYNC task and then displays results of this task on the screen. However the code to display the results is running before the async task completes. is there a solution to this? ``` size = 0; new initTask().doInBackground(); //get results setUpSeekBar();//display FillCards();//display ```<issue_comment>username_1: > > So how do I call/select desired hex based on HexCell coordinates? > > > This is easy to do since you used `int` instead of `float` to represent the coordinate. Just loop over the `cells` array. In each loop, access the `coordinates` variable from the `HexCell` component then compare x, `y` and z values. If they match, return the current `HexCell` in the loop. If not, simply return `null`. You can also do this with `linq` but avoid it. Your cell array: ``` HexCell[] cells; ``` Get `HexCell` from coordinate: ``` HexCell getHexCellFromCoordinate(int x, int y, int z) { //Loop thorugh each HexCell for (int i = 0; i < cells.Length; i++) { HexCoordinates hc = cells[i].coordinates; //Check if coordinate matches then return it if ((hc.X == x) && (hc.Y == y) && (hc.Z == z)) { return cells[i]; } } //No match. Return null return null; } ``` Since the coordinate is in `int` instead of `float`, you can also use [`Vector3Int`](https://docs.unity3d.com/ScriptReference/Vector3Int.html)*(Requires Unity 2017.2 and above)* to represent them instead of x, y and z. Note that this is different from [`Vector3`](https://docs.unity3d.com/ScriptReference/Vector3.html). ``` HexCell getHexCellFromCoordinate(Vector3Int coord) { //Loop thorugh each HexCell for (int i = 0; i < cells.Length; i++) { HexCoordinates hc = cells[i].coordinates; //Check if coordinate matches then return it if ((hc.X == coord.x) && (hc.Y == coord.y) && (hc.Z == coord.z)) { return cells[i]; } } //No match. Return null return null; } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Alternatively, you could use some built-in functions to make it more readable. ``` HexCell getHexCellFromCoordinate(int x, int y, int z) { return cells.FirstOrDefault( cell => cell.x == x && cell.y == y && cell.z == z ); } HexCell getHexCellFromCoordinate(Vector3Int coord) { return cells.FirstOrDefault(cell => cell.x == coord.x && cell.y == coord.y && cell.z == coord.z ); } ``` It's worth noting, since I'm not sure where you'll be needing to find the cells, that `FirstOrDefault` makes heap allocations and therefore invoking it too often on too large of a list (as in tens of thousands of times per frame, and/or against tens of thousands of objects) it could result in undesired garbage collections, which *may* cause a stutter in your application, and that stutter *may* be noticeable if combined with other code that uses heap allocations willy-nilly. So as a general rule, start with something simple. If your application starts to slow down or take up too much memory, go back and optimize starting with the hottest (least performant) code. You can use a profiler to help you find those spots. But please, don't riddle your code with for loops just to save some extra cpu cycles. Upvotes: 0
2018/03/15
805
2,701
<issue_start>username_0: I'm using [the Clap crate](https://crates.io/crates/clap) for parsing command line parameters. I've defined a subcommand `ls` that should list files. Clap also defines a `help` subcommand that displays information about the application and its usage. If no command is provided, nothing gets displayed at all, but I want the app to display help in that case. I've tried this code, which looks pretty straightforward, but it doesn't work: ``` extern crate clap; use clap::{App, SubCommand}; fn main() { let mut app = App::new("myapp") .version("0.0.1") .about("My first CLI APP") .subcommand(SubCommand::with_name("ls").about("List anything")); let matches = app.get_matches(); if let Some(cmd) = matches.subcommand_name() { match cmd { "ls" => println!("List something here"), _ => eprintln!("unknown command"), } } else { app.print_long_help(); } } ``` I get an error that `app` is used after move: ```none error[E0382]: use of moved value: `app` --> src/main.rs:18:9 | 10 | let matches = app.get_matches(); | --- value moved here ... 18 | app.print_long_help(); | ^^^ value used here after move | = note: move occurs because `app` has type `clap::App<'_, '_>`, which does not implement the `Copy` trait ``` Reading through the documentation of Clap, I've found that the `clap::ArgMatches` that's returned in `get_matches()` has a method [`usage`](https://docs.rs/clap/2.31.1/clap/struct.ArgMatches.html#method.usage) that returns the string for usage part, but, unfortunately, only this part and nothing else.<issue_comment>username_1: Use [`clap::AppSettings::ArgRequiredElseHelp`](https://docs.rs/clap/2.31.1/clap/enum.AppSettings.html#variant.ArgRequiredElseHelp): ``` App::new("myprog") .setting(AppSettings::ArgRequiredElseHelp) ``` See also: * [Method call on clap::App moving ownership more than once](https://stackoverflow.com/q/40951538/155423) Upvotes: 6 [selected_answer]<issue_comment>username_2: You can also use [`Command::arg_required_else_help`](https://docs.rs/clap/latest/clap/struct.App.html#method.arg_required_else_help) as a `bool` on the command itself. ``` Command::new("rule").arg_required_else_help(true) ``` Upvotes: 2 <issue_comment>username_3: If you are using the **derive instead of the builder API** you can set the flag mentioned by shepmaster as follows: ``` #[command(arg_required_else_help = true)] pub struct Cli { #[clap(short)] pub init: bool, ``` See also: <https://docs.rs/clap/latest/clap/_derive/_tutorial/index.html#configuring-the-parser> Upvotes: 2
2018/03/15
1,024
2,951
<issue_start>username_0: I am trying to create a navigation menu with 6 items, 3 on the left, 3 on the right with the logo (the logo to be both vertically and horizontally centered) The problem I am having is the logo looks centered, but not vertically. Also the navigation items are too far apart from the logo and the my navigation items on the right are not in the correct order. What I am trying to accomplish is to make it look like the screenshots attached. [![enter image description here](https://i.stack.imgur.com/TQVbb.png)](https://i.stack.imgur.com/TQVbb.png) [![enter image description here](https://i.stack.imgur.com/JErG4.png)](https://i.stack.imgur.com/JErG4.png) <https://jsfiddle.net/fa970mnm/2/> ```css .site-footer ul { list-style: none; } .site-footer ul li a { color: #e1c66b; } #logo { height: 125px; } .nav { text-align: center; } .nav li { display: inline; margin-right: 1em; } @media(min-width:786px) { .nav li:nth-child(1), .nav li:nth-child(2), li:nth-child(3) { float: left; } .nav li:nth-child(4), .nav li:nth-child(5), li:nth-child(6) { float: right; } } ``` ```html ![](http://www.jamaicacannabisestates.com/wp-content/uploads/2018/03/logo.png) ```<issue_comment>username_1: You would probably be best suited using a [flexbox](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) in this situation. You can simply use the following rules for your container . ``` #banner { display: flex; justify-content: center; align-items: center; } ``` And you can mess with the `margin-right` rule for the `.element` class I added to change the amount of spacing, or maybe take a look at `justify-content: space-between` from the link above. Here's the [JSFiddle](https://jsfiddle.net/vjw742pn). Upvotes: 2 [selected_answer]<issue_comment>username_2: Why do not you just put the logo between LI? Just move the logo and improve CSS: ``` .nav li { display: inline-block; vertical-align: middle; margin-right: 1em; } ``` Display as 'Inline-block', because 'vertical-align middle' doesnt work with 'inline'. <https://jsfiddle.net/fa970mnm/14/> Upvotes: 1 <issue_comment>username_3: First move your `logo` to `.nav` as a child. Then change `.nav li` `inline` to `display: inline-block;`. Like this ``` .nav li { display: inline-block; margin-right: 1em; } ``` ***Here is the working Snippet*** ```css .site-footer ul { list-style: none; } .site-footer ul li a { color: #e1c66b; } #logo { height: 125px; } .nav { text-align: center; vertical-align: middle; } .nav li { display: inline-block; margin-right: 1em; vertical-align: middle; } ``` ```html * [Home](/) * [Shop](/shop/) * [Our Story](/our-story/) * ![](http://www.jamaicacannabisestates.com/wp-content/uploads/2018/03/logo.png) * [Products](/products/) * [Contact Us](/contact-us/) * [Foundation](/foundation/) ``` Upvotes: 0
2018/03/15
737
2,196
<issue_start>username_0: I have a PySpark dataframe with about a billion rows. I want to average over every 2000 values, like average of rows with indeces 0-1999, average of rows with indeces 2000-3999, and so on. How do I do this? Alternatively, I could also average 10 values for every 2000, like average of rows with indeces 0-9, average of rows with indeces 2000-2009, and so on. The purpose of this is to downsample the data. I don't currently have an index row, so if I need this, how do I do it?<issue_comment>username_1: You would probably be best suited using a [flexbox](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) in this situation. You can simply use the following rules for your container . ``` #banner { display: flex; justify-content: center; align-items: center; } ``` And you can mess with the `margin-right` rule for the `.element` class I added to change the amount of spacing, or maybe take a look at `justify-content: space-between` from the link above. Here's the [JSFiddle](https://jsfiddle.net/vjw742pn). Upvotes: 2 [selected_answer]<issue_comment>username_2: Why do not you just put the logo between LI? Just move the logo and improve CSS: ``` .nav li { display: inline-block; vertical-align: middle; margin-right: 1em; } ``` Display as 'Inline-block', because 'vertical-align middle' doesnt work with 'inline'. <https://jsfiddle.net/fa970mnm/14/> Upvotes: 1 <issue_comment>username_3: First move your `logo` to `.nav` as a child. Then change `.nav li` `inline` to `display: inline-block;`. Like this ``` .nav li { display: inline-block; margin-right: 1em; } ``` ***Here is the working Snippet*** ```css .site-footer ul { list-style: none; } .site-footer ul li a { color: #e1c66b; } #logo { height: 125px; } .nav { text-align: center; vertical-align: middle; } .nav li { display: inline-block; margin-right: 1em; vertical-align: middle; } ``` ```html * [Home](/) * [Shop](/shop/) * [Our Story](/our-story/) * ![](http://www.jamaicacannabisestates.com/wp-content/uploads/2018/03/logo.png) * [Products](/products/) * [Contact Us](/contact-us/) * [Foundation](/foundation/) ``` Upvotes: 0
2018/03/15
328
1,137
<issue_start>username_0: I am using the following steps to duplicate all branches to the new-repository. ``` git clone --bare https://github.com/exampleuser/old-repository.git # Make a bare clone of the repository cd old-repository.git git push --mirror https://github.com/exampleuser/new-repository.git # Mirror-push to the new repository ``` Now, I have added two new branches in `old-repository.git` and want to move only those 2 branches to `new-repository.git` What git commands are required to perform it?<issue_comment>username_1: You can add new\_repo as a remote for old repo: this is more convenient for pushing: ``` cd old_repo git remote add new /path/to/new/repo git push new newBranch1 git push new newBranch2 ``` Upvotes: 5 [selected_answer]<issue_comment>username_2: Clone old branch ``` git clone --single-branch --branch branch_name github_repo_url ``` Tell git where your repo is: ``` git remote add mine your_repo_url ``` Then, push the branch to your repo with: ``` git push -u mine ``` Upvotes: 3 <issue_comment>username_3: cd old\_repo git remote add new git push new branchName Upvotes: 0
2018/03/15
1,226
4,450
<issue_start>username_0: I saw this good article to introduce [async/await](https://developers.google.com/web/fundamentals/primers/async-functions) from Google. However, I couldn't understand why these code run in parallel ``` async function parallel() { const wait1 = wait(500); const wait2 = wait(500); await wait1; await wait2; return "done!"; } ``` And this run in series ``` async function series() { await wait(500); await wait(500); return "done!"; } ``` Why is the key difference between these two methods ? In my opinion, both of them are await promise and should work the same result. Here is my test code. Can run in browser console which support async/await. ``` function wait(){ return new Promise((res)=>{setTimeout(()=>{res()}, 2000)}) } async function parallel() { const wait1 = wait(); const wait2 = wait(); await wait1; await wait2; return "done!"; } async function series() { await wait(); await wait(); return "done!"; } parallel().then(res => console.log("parallel!")) series().then(res => console.log("series!")) ``` ====== Thanks for the answers. But I still have some question. Why exact the async/await means? In my knowledge, constructing Promise instance would execute directly. Here is my test code ``` function wait(){ return new Promise((res)=>{setTimeout(()=>{console.log("wait!");res();}, 2000)}) } wait() //Promise {} //wait! let w = wait() //undefined //wait! let w = await wait() //wait! //undefined async function test(){await wait()} // undefined test() //Promise {} //wait! ``` So why `const wait1 = wait(); inside parallel function` execute directly? By the way, should I open another question to ask these question?<issue_comment>username_1: In `parallel()`, you call both methods *and then* `await` their results while in `series()` you `await` the result of the first `wait()` call before calling the second `wait()`. > > Why exact the async/await means? In my knowledge, constructing Promise instance would execute directly. > > > The `Promise` instance is returned immediately, i.e. synchronously. But the value of the `Promise` is evaluated asynchronously by calling the first parameter given to its constructor, a function usually called `resolve`. This is what you are `await`ing for. Upvotes: 2 <issue_comment>username_2: `await` doesn't cause the `Promise` or its `setTimeout()` to start, which seems to be what you're expecting. The call to `wait()` alone starts them immediately, whether there's an active `await` on the promise or not. `await` only helps you know when the already on-going operation, tracked through the promise, has completed. So, the difference is just due to when `wait()` is being called and starting each timeout: * `parallel()` calls `wait()` back-to-back as quickly as the engine can get from one to the next, before either are `await`ed, so the 2 timeouts begin/end at nearly the same time. * `series()` forces the 2nd `wait()` to not be called until after the 1st has completed, by having an `await` act in between them. --- Regarding your edit, `async` and `await` are syntactic sugar. Using them, the engine will modify your function at runtime, inserting additional code needed to interact with the promises. A (possible, but not precise) equivalent of `series()` without `await` and `async` might be: ``` function series() { return Promise.resolve() .then(function () { return wait(500) }) .then(function () { return wait(500) }) .then(function () { return "done!"; }); } ``` And for `parallel()`: ``` function parallel() { const wait1 = wait(500); const wait2 = wait(500); return Promise.resolve() .then(wait1) .then(wait2) .then(function () { return "done!"; }); } ``` Upvotes: 4 [selected_answer]<issue_comment>username_3: The difference is that in `parallel`, both of the promises are scheduled right after each other. In `series`, you wait for the first `wait` to **resolve** and *then* schedule the second `wait` to be called. If we expand the methods we'd get something similar to: ``` function parallel() { const wait1 = wait(); const wait2 = wait(); // Both wait1 and wait2 timeouts are scheduled return wait1 .then(() => wait2) .then(() => "done"); } function series() { // The second wait happens _after_ the first has been *resolved* return wait() .then(() => wait()) .then(() => "done"); } ``` Upvotes: 2
2018/03/15
1,040
3,781
<issue_start>username_0: So basically I am trying to write a program which accepts an array of integers and then outputs the Max Min and **smallest** Mode and how many times it occurs. I have been able to find both max and min and mode, but instead of the smallest mode my code outputs the one that occurs first. And i am not sure how to handle an input with more than one mode. Below i’ll post my code: #include using namespace std; ``` int main() { int p,max,min,mode; cout << "Enter the number of postive integers:"<< endl; cin >> p; int pos[p]; cout << "Now enter postive integers!" <> pos[i]; } max =pos[0]; min =pos[0]; for( int i=0; i max) max=pos[i]; if(pos[i]< min) min=pos[i]; } cout << "Max=" << max << endl; cout << "Min=" << min << mode= pos[0]; int count[20]; int t=0; for(int c=0;c ``` there may be simpler and better ways to code this but since i’m a beginner and have only learned loops/conditionals/arrays/variable declaration etc I can only use them in the program, any help will be appreciated.<issue_comment>username_1: In `parallel()`, you call both methods *and then* `await` their results while in `series()` you `await` the result of the first `wait()` call before calling the second `wait()`. > > Why exact the async/await means? In my knowledge, constructing Promise instance would execute directly. > > > The `Promise` instance is returned immediately, i.e. synchronously. But the value of the `Promise` is evaluated asynchronously by calling the first parameter given to its constructor, a function usually called `resolve`. This is what you are `await`ing for. Upvotes: 2 <issue_comment>username_2: `await` doesn't cause the `Promise` or its `setTimeout()` to start, which seems to be what you're expecting. The call to `wait()` alone starts them immediately, whether there's an active `await` on the promise or not. `await` only helps you know when the already on-going operation, tracked through the promise, has completed. So, the difference is just due to when `wait()` is being called and starting each timeout: * `parallel()` calls `wait()` back-to-back as quickly as the engine can get from one to the next, before either are `await`ed, so the 2 timeouts begin/end at nearly the same time. * `series()` forces the 2nd `wait()` to not be called until after the 1st has completed, by having an `await` act in between them. --- Regarding your edit, `async` and `await` are syntactic sugar. Using them, the engine will modify your function at runtime, inserting additional code needed to interact with the promises. A (possible, but not precise) equivalent of `series()` without `await` and `async` might be: ``` function series() { return Promise.resolve() .then(function () { return wait(500) }) .then(function () { return wait(500) }) .then(function () { return "done!"; }); } ``` And for `parallel()`: ``` function parallel() { const wait1 = wait(500); const wait2 = wait(500); return Promise.resolve() .then(wait1) .then(wait2) .then(function () { return "done!"; }); } ``` Upvotes: 4 [selected_answer]<issue_comment>username_3: The difference is that in `parallel`, both of the promises are scheduled right after each other. In `series`, you wait for the first `wait` to **resolve** and *then* schedule the second `wait` to be called. If we expand the methods we'd get something similar to: ``` function parallel() { const wait1 = wait(); const wait2 = wait(); // Both wait1 and wait2 timeouts are scheduled return wait1 .then(() => wait2) .then(() => "done"); } function series() { // The second wait happens _after_ the first has been *resolved* return wait() .then(() => wait()) .then(() => "done"); } ``` Upvotes: 2
2018/03/15
630
2,486
<issue_start>username_0: I noticed that in Visual Studio Code there is a menu item called *"Start Without Debugging"* under the *"Debug"* menu. When I have a PHP file open, I expected this to run the PHP file through the PHP executable and give me the output. Instead, when I click on *"Start Without Debugging"*, the User Settings page shows up. Why does the User Settings page show up? It's not clear why this page is presented to me. Does it want me to configure something? How do I get it to just run the PHP file that I have open through the PHP executable. Is this even possible? I noticed in the Default Settings there is a property called `"php.validate.executablePath"` that is set to `null`. I tried overriding this setting in my User Settings by pointing it to the path of my PHP executable like this: ``` { "php.validate.executablePath": "/usr/bin/php" } ``` But that didn't solve anything. The User Settings page still shows up when I click *"Start Without Debugging"*.<issue_comment>username_1: After doing more research, I found the solution to my problem. Based on [this section in the vscode docs](https://code.visualstudio.com/docs/editor/debugging#_global-launch-configuration) and [this comment](https://github.com/Microsoft/vscode/issues/18401#issuecomment-272400316) that mentions creating a global launch configuration, all you have to do is add a `launch` object to your User Settings JSON. In my case, I added this to my User Settings: ``` "launch": { "version": "0.2.0", "configurations": [ { "type": "php", "request": "launch", "name": "Launch Program", "program": "${file}", "runtimeExecutable": "/usr/bin/php" } ] } ``` Your value for `runtimeExecutable` may be different depending on the path to your PHP executable. Upvotes: 4 [selected_answer]<issue_comment>username_2: I ran in to the same issue except I was trying to run a C++ file (doing all this in Windows 11). I followed the [instructions here](https://code.visualstudio.com/docs/cpp/config-msvc), which said that I needed to run VSCode from within a "developer terminal" (which is able to run cl, the command for the MSVC C++ compiler). At first, I did so and it still did not work (I'm absolutely sure of this). But then I tried again and it worked; I was able to run and debug a hello.cpp. Not exactly sure what happened, maybe it needed time to "warm up" or something (which would be awful if true). Upvotes: 1
2018/03/15
406
1,470
<issue_start>username_0: Typescript get failed to find exported component,May be exported module not appropriatly imported into other component. It show an error message while call **AddToArray** method: > > Cannot read property 'push' of undefined > > > **PageOne.ts** ``` var const array = new Array(5); export array; class PageOne { constructor(public navCtrl: NavController, public navParams: NavParams) { } GoToPage(){ this.navCtrl.push('PageTwo'); } } ``` **PageTwo.ts** ``` import { players } from '../pageone/pageone.ts' export class PlayersPage { constructor(public navCtrl: NavController, public navParams: NavParams) { } AddToArray(){ array.push("TEST") } } ```<issue_comment>username_1: In fact, I do not understand why you use the array and export it. I guess if you just want to make some data type to save and share the data among components. I would say to use service since each component calls the service to set or get the data from the service. This doc would be helpful <https://angular.io/tutorial/toh-pt4#why-services> Upvotes: 3 [selected_answer]<issue_comment>username_2: You're getting the error because you must declare and initialize the array before using it. ``` class PageOne { let navCtrl: string[] =[]; constructor(public navCtrl: NavController, public navParams: NavParams) { } GoToPage(){ this.navCtrl.push('PageTwo'); } } ``` Upvotes: 0
2018/03/15
532
1,660
<issue_start>username_0: When I run Capistrano task with dry run it tells me that rbenv Ruby version can't be found. I assume with dry run it should use local environment. But when I run the commands locally I can easily find below mentioned directory and Ruby is installed. ``` > ./bin/bundle exec cap --dry-run development t DEBUG [8171d925] Running [ ! -d ~/.rbenv/versions/2.4.3 ] as user@dev DEBUG [8171d925] Command: [ ! -d ~/.rbenv/versions/2.4.3 ] ERROR rbenv: 2.4.3 is not installed or not found in ~/.rbenv/versions/2.4.3 > ls ~/.rbenv/versions/2.4.3 bin include lib share > rbenv global 2.4.3 > ruby -v ruby 2.4.3p205 (2017-12-14 revision 61247) [x86_64-darwin16] > bundle info capistrano * capistrano (3.4.0) ``` My Capfile contains below lines. ```rb require 'capistrano/rbenv' set :rbenv_type, :user set :rbenv_ruby, '2.4.3' ``` I'm using Mac OS and installed rbenv with homebrew.<issue_comment>username_1: In fact, I do not understand why you use the array and export it. I guess if you just want to make some data type to save and share the data among components. I would say to use service since each component calls the service to set or get the data from the service. This doc would be helpful <https://angular.io/tutorial/toh-pt4#why-services> Upvotes: 3 [selected_answer]<issue_comment>username_2: You're getting the error because you must declare and initialize the array before using it. ``` class PageOne { let navCtrl: string[] =[]; constructor(public navCtrl: NavController, public navParams: NavParams) { } GoToPage(){ this.navCtrl.push('PageTwo'); } } ``` Upvotes: 0
2018/03/15
274
1,003
<issue_start>username_0: I want to ask the logic to implement the timer clock like the following format: "**00:01 -> 00:02 -> 00:03 -> 00:04 ... -> 00:59 -> 01:00**". It increases every second after that auto update the `TextView`. Any suggestions?<issue_comment>username_1: In fact, I do not understand why you use the array and export it. I guess if you just want to make some data type to save and share the data among components. I would say to use service since each component calls the service to set or get the data from the service. This doc would be helpful <https://angular.io/tutorial/toh-pt4#why-services> Upvotes: 3 [selected_answer]<issue_comment>username_2: You're getting the error because you must declare and initialize the array before using it. ``` class PageOne { let navCtrl: string[] =[]; constructor(public navCtrl: NavController, public navParams: NavParams) { } GoToPage(){ this.navCtrl.push('PageTwo'); } } ``` Upvotes: 0
2018/03/15
696
2,459
<issue_start>username_0: I have a customer wanting kit components to be highlighted or specially formatted on a Picking Ticket with an advanced PDF. I can format the parent with no problem, but the customer wants the components to display in a different background colour. (custom column field indicating a Kit item, then using <#if> on the form to change to Bold... But i can't find a field or criteria to tell the template if the item in question is a KIT COMPONENT?? Anyone know how I can achieve this? Cheers Steve<issue_comment>username_1: Just for those who may be interested, I found a way to differentiate between kit parent and kit component on a Picking Ticket Advanced PDF Template. Firstly, create a transaction column field. Check Box; Stored Value; Sale Item/IF;HIDDEN;Default is CHECKED. During sales order entry, this field will be "checked" by default. However, as the kit components do not appear on the sales order entry, they will not inherit the default value and thus will remain NULL. In the advanced PDF template, I did the following: ``` <#assign committed="${item.quantitycommitted}"/><#if committed="0"><#assign committed=''/> <#if item.custcol_notcomponent='T'> <#if item.custcolitemtype="Kit/Package">| <#else>| ${item.item} | ${item.binnumber} | ${item.description} | ${item.quantity} | ${committed} | | | <#else> |     ${item.item} | ${item.binnumber} | ${item.description} | ${item.quantity} | ${committed} | | | ``` The result, is a picking ticket with BOLD kit parents, greyed and indented kit components, and just regular black text for standard inventory items. Something like this for the transaction lines: [![image sample](https://i.stack.imgur.com/tHUTm.png)](https://i.stack.imgur.com/tHUTm.png) Hope this helps someone out sometime :) Upvotes: 3 [selected_answer]<issue_comment>username_2: I tried your solution but it won't indent. Looks like it doesn't go to the <#else> part. ```html <#if item.custcol_f5_not_component = 'T'> <#if item.custcol_item_type="Kit/Package">|<#else>| ${item.custcol\_f5\_item} | ${item.description} | ${item.custcol\_skl\_bin\_location} | ${item.quantity} | ${item.units} | **${item.quantitycommitted}** | ${item.quantitybackordered} | <#else> | ${item.custcol\_f5\_item} | ${item.description} | ${item.custcol\_skl\_bin\_location} | ${item.quantity} | ${item.units} | **${item.quantitycommitted}** | ${item.quantitybackordered} | ``` Upvotes: 0
2018/03/15
902
3,356
<issue_start>username_0: I'm building Asp.Net Core 2.x web api integrated with Swagger. To access the swagger, I had to append /swagger to the url, eg. <https://mywebapi.azurewebsites.net/swagger/> How can I redirect <https://mywebapi.azurewebsites.net/> to <https://mywebapi.azurewebsites.net/swagger/> ?<issue_comment>username_1: Install **Microsoft.AspNetCore.Rewrite** from Nuget In Startup.cs ``` public void Configure(IApplicationBuilder app, IHostingEnvironment env) ``` before ``` app.UseMvc(); ``` add ``` var option = new RewriteOptions(); option.AddRedirect("^$", "swagger"); app.UseRewriter(option); ``` Upvotes: 6 [selected_answer]<issue_comment>username_2: Create a default controller like this: ```cs using Microsoft.AspNetCore.Mvc; namespace Api { [ApiExplorerSettings(IgnoreApi = true)] public class DefaultController : Controller { [Route("/")] [Route("/docs")] [Route("/swagger")] public IActionResult Index() { return new RedirectResult("~/swagger"); } } } ``` Any url "/", "/docs" or "/swagger" is redirect to "/swagger". Upvotes: 4 <issue_comment>username_3: 1. Open the **launchSettings.json** file. 2. Under the **"profiles"** node depending on your setup you should have one or more profiles. In may case I had **"IIS Express"** and another with named with my project name (*e.g WebApplication1* ), now changing the **launchUrl** entry to **"launchUrl": "swagger"** solved my problem. 3. If this does not work and you have other profiles do the same and test. Upvotes: 2 <issue_comment>username_4: In Startup.cs ``` public void Configure(IApplicationBuilder app, IHostingEnvironment env) ``` You should have section where you set Swagger UI options. Add and set the RoutePrefix option to an empty string. ``` app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My service"); c.RoutePrefix = string.Empty; // Set Swagger UI at apps root }); ``` Upvotes: 5 <issue_comment>username_5: On Startup.cs, after: ``` app.UseSwaggerUI(options => { options.SwaggerEndpoint("/swagger/v1/swagger.json", "API V1"); ``` add : ``` options.RoutePrefix = string.Empty; ``` this will make your root url the main api url. Upvotes: 3 <issue_comment>username_6: I have modified the launchSettings.json with "launchUrl": "swagger" instead of "launchUrl": "api/values" work for me, if that doesnt work for you remove the c.RoutePrefix = string.Empty; from your app.UseSwaggerUI configuration. Upvotes: 1 <issue_comment>username_7: One straitforward approach is to redirect directly via `IApplicationBuilder.Use()`: ``` app.Use(async (context, next) => { if (!context.Request.Path.Value.Contains("/swagger", StringComparison.OrdinalIgnoreCase)) { context.Response.Redirect("swagger"); return; } await next(); }); ``` Upvotes: 0 <issue_comment>username_8: If you want to keep the path /swagger/index.html and you want to redirect to it from the / (root), in aspnetcore 6 you can use the following: ``` app.UseEndpoints(endpoints => { ... endpoints.Map("/", context => Task.Run((() => context.Response.Redirect("/swagger/index.html")))); ... }); ``` Upvotes: 2
2018/03/15
329
1,169
<issue_start>username_0: How to disable right clicking mathjax in shiny? For example, see <https://shiny.rstudio.com/gallery/mathjax.html> Ideally, I would like users not to be abe to interact with the mathjax text at all.<issue_comment>username_1: You can turn off the MathJax contextual menu by adding ``` MathJax.Hub.Config({ showMathMenu: false }); ``` to your page just *before* the script that loads MathJax.js itself. I would encourage you not to do this, however. There are important functions in the menu, including the controls for those using assistive technology like screen readers. Those users may need access to those controls to set things appropriately for their assistive needs. If you disable the menu, you may prevent them from being able to use your pages. Upvotes: 3 <issue_comment>username_2: In case of *MathJax 3* [use the following syntax](http://docs.mathjax.org/en/latest/upgrading/v2.html#v2-contextual-menu-changes): ``` MathJax = { options: { renderActions: { addMenu: [] } } }; ``` Upvotes: 2 <issue_comment>username_3: a little CSS rule ``` mjx-container.MathJax { pointer-events: none; } ``` Upvotes: 0
2018/03/15
691
2,294
<issue_start>username_0: I have my own local HTML file open in my browser. When I click a certain button, the class to the button changes to "selected." What I want to do is have Python take the current updated HTML of the file in the browser and overwrite it as the original HTML file. The goal here is to save the changes that were updated from the browser as the new HTML file, so the next time I open this file, the changes don't need to be made again. Typically I would: 1. send an HTTP request to a url 2. turn the response into a BeautifulSoup object 3. then save it as a string as `myfile.html` ``` url = 'http://google.com' r = requests.get(url) soup = str(BeautifulSoup(r.content,'lxml')) file.write(soup) ``` But I cannot send an HTTP request because it's a file currently open in my browser, not a web page on a server to be requested. So I'm not sure how to receive the structured HTML into Python for further processing.<issue_comment>username_1: You can use the built in library [http.server](https://docs.python.org/3/library/http.server.html) to serve pages. In one console, change to your working directory: ``` J:\>echo hello > hello.html J:\>python -m http.server 8000 Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ... ``` And in another: ``` >>> import requests >>> resp = requests.get("http://127.0.0.1:8000/hello.html") >>> resp.text 'hello \r\n' >>> resp.status_code 200 ``` You'll see log entries in the server window, e.g. ``` 127.0.0.1 - - [15/Mar/2018 13:45:40] "GET /hello.html HTTP/1.1" 200 - ``` Upvotes: -1 <issue_comment>username_2: You can try using the `selenium` package. You will need to have the webdriver.exe for the browser of your choice in the same folder you are running this from (code below uses Chrome Web Driver). This example, for brevity, requires you to run it as a live script from the console. ``` from selenium import webdriver browser = webdriver.Chrome() ``` This will start the webdriver. It will look just like an ordinary browser. ``` browser.get('YOUR URL HERE') ``` Make some changes to the site, and when you are done: ``` html = browser.page_source ``` This will return the modified html as a string into `html` that you can use to overwrite your original html file. Upvotes: 1 [selected_answer]
2018/03/15
969
2,156
<issue_start>username_0: this my collection data collection ``` { "_id" : "001-000001", "employeeId" : "001-001", "paidAmount" : 30, "paidDate" : ISODate("2017-08-23T14:36:14.410+07:00") }, { "_id" : "001-000004", "employeeId" : "001-001", "paidAmount" : 10, "paidDate" : ISODate("2017-08-23T06:45:29.497+07:00"), }, { "_id" : "001-000005", "employeeId" : "001-001", "paidAmount" : 15, "paidDate" : ISODate("2017-08-01T06:45:29.497+07:00"), }, { "_id" : "001-000002", "employeeId" : "001-002", "paidAmount" : 15, "paidDate" : ISODate("2017-08-01T12:49:08.724+07:00") }, { "_id" : "001-000003", "employeeId" : "001-002", "paidAmount" : 15, "paidDate" : ISODate("2017-08-01T06:45:29.497+07:00"), }, ``` I want to get result like this Please help me ``` { "_id" : "001-004", "paidAmount" : 45, "employeeId" : "001-001", "item" : [ [ { "paidDate" : ISODate("2017-08-23T14:36:14.410+07:00") "paidAmount" : 30 }, { "paidDate" : ISODate("2017-08-01T06:45:29.497+07:00"), "paidAmount" : 15 }, ] ] }, { "_id" : "001-004", "paidAmount" : 30, "employeeId" : "001-002", "item" : [ [ { "paidDate" : ISODate("2017-08-01T12:49:08.724+07:00") "paidAmount" : 30 } ] ] }, ```<issue_comment>username_1: You can try below aggregation. ``` db.collection.aggregate([ {"$group":{ "_id":{"employeeId":"$employeeId","paidDate":"$paidDate"}, "paidAmount":{"$sum":"$paidAmount"} }}, {"$group":{ "_id":{"employeeId":"$_id.employeeId"}, "paidAmount":{"$sum":"$paidAmount"}, "item":{"$push":{"paidDate":"$_id.paidDate","paidAmount":"$paidAmount"}} }}, {"$project":{ "_id":0, "paidAmount":1, "employeeId":"$_id", "item":1 }} ]) ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: May be if you want to publish composite collection you might want to look at [meteor-publish-composite](https://github.com/englue/meteor-publish-composite) plugin. which allows you to publish composite collection. but it only works on server. Upvotes: 0
2018/03/15
1,907
5,572
<issue_start>username_0: I'm having an issue customizing the CSS of some button widgets that came with a WordPress theme I'm running. I grabbed a quick screen capture video of what's happening because it's hard to describe. Video Link: <https://drive.google.com/open?id=1mYvOtAjz-0QnJYV3_nGYXnFoRpsRdVo_> The CSS I have applied on the buttons: ``` .lc_button { height: 100px !important; width: 200px !important; font-size: 18px !important; border: 1px solid #dd3333 !important; text-align: center; background-color: white; border-radius: 5%; } .lc_button:hover { background-color: white; border: 4px solid #dd3333 !important; color: #151515 !important; } .lc_button a:hover { color: #151515 !important; } ``` Any idea what I have to do to get the inside to stay visible no matter where the cusror is at inside the button? Thanks<issue_comment>username_1: The .css you've provided seems fully functional, and customizable. (aka, not broken, works fine). The whole .css and the .html might shed some light on things without any "major alterations". ```css .lc_button { height: 100px !important; width: 200px !important; font-size: 18px !important; border: 1px solid #dd3333 !important; text-align: center; background-color: white; border-radius: 5%; } .lc_button:hover { background-color: white; border: 4px solid #0000ff !important; color: #00ff00 !important; } .lc_button a:hover { color: #151515 !important; } ``` ```html Test ``` Upvotes: 1 <issue_comment>username_2: I've shared the code snippet..I think this will help you to solve the problem... ```css *, *:after, *:before { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } body{ font-family: 'PT Sans', sans-serif; display: table; width: 100%; background: #f54785; } .container{ display: table-cell; vertical-align: middle; text-align: center; height: 100vh; } button{ display: inline-block; position: relative; background: none; border: none; color: #fff; font-size: 18px; cursor: pointer; margin: 20px 30px; background: rgba(0,0,0,0.09); } span{ display: block; padding: 25px 80px; } button::before, button::after{ content:""; width: 0; height: 2px; position: absolute; transition: all 0.2s linear; background: #fff; } span::before, span::after{ content:""; width:2px; height:0; position: absolute; transition: all 0.2s linear; background: #fff; } button:hover::before, button:hover::after{ width: 100%; } button:hover span::before, button:hover span::after{ height: 100%; } .btn-1::after{ left:0; bottom: 0; transition-duration: 0.4s; } .btn-1 span::after{ right:0; top: 0; transition-duration: 0.4s; } .btn-1::before{ right: 0; top: 0; transition-duration: 0.4s; } .btn-1 span::before{ left: 0; bottom: 0; transition-duration: 0.4s; } ``` ```html Hover Me ``` Upvotes: 0 <issue_comment>username_3: I've tried to solve your problem. I am successful. You can use this code of mine. **HTML** ``` [Watch video](#) ``` **CSS** ``` .lc_button a { display: block; width: 200px; height: 100px; line-height: 100px; font-size: 18px; font-weight: 700; color: #000000; border-radius: 5%; box-sizing: border-box; transition: 0.3s; background-color: white; text-decoration: none; text-transform: uppercase; text-align: center; position: relative; } .lc_button a:before { display: block; position: absolute; border-radius: 5%; left: 0; top: 0; content: ""; width: 200px; height: 100px; box-sizing: border-box; border: 1px solid red; transition: 0.3s; } .lc_button a:hover:before { border: 4px solid red; } .lc_button a:hover { color: #151515 !important; background-color: #ffffff; } ``` ```css .lc_button a { display: block; width: 200px; height: 100px; line-height: 100px; font-size: 18px; font-weight: 700; color: #000000; border-radius: 5%; box-sizing: border-box; transition: 0.3s; background-color: white; text-decoration: none; text-transform: uppercase; text-align: center; position: relative; } .lc_button a:before { display: block; position: absolute; border-radius: 5%; left: 0; top: 0; content: ""; width: 200px; height: 100px; box-sizing: border-box; border: 1px solid red; transition: 0.3s; } .lc_button a:hover:before { border: 4px solid red; } .lc_button a:hover { color: #151515 !important; background-color: #ffffff; } ``` ```html [Watch video](#) ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: This will help you to solve the problem... ```css button { height: 100px !important; width: 200px !important; font-size: 18px !important; border: 1px solid #dd3333 !important; text-align: center; background-color: white; border-radius: 5%; } button:hover { background-color: white; border: 4px solid #dd3333 !important; color: #151515 !important; } button a:hover { color: #151515 !important; } ``` ```html Hover Me ``` Upvotes: 0
2018/03/15
2,074
5,959
<issue_start>username_0: I have this code: ``` #include #include using namespace std; void copyString(char \*input, int offset, int length, bool invert, char \*output, int output\_offset) { char \*cp = new char[length+1]; for (int i = 0; i < length + 1; i++) { cp[i] = input[offset + i]; } if (invert) { for (int i = 0; i < length/2; i++) { swap(cp[i], cp[length - i - 1]); } } int count = 0; while (output[count]) count++; int cutlength = count - output\_offset; char \*temp = new char[count + 1]; for (int i = 0; i < count + 1; i++) temp[i] = output[i]; for (int i = 0; i < cutlength; i++) { temp[output\_offset + i] = cp[i]; } output = temp; } void main() { char \*st = "Hello world"; cout << "st= " << st << endl; char \*st2 = "My name is C++"; cout << "st2= " << st2 << endl; copyString(st, 6, 5, true, st2, 11); cout << "st2 output= " << st2 << endl; system("Pause"); } ``` The idea is that the function will copy a length of an input string and replace a part of an output with that copied string. All i want to do is make the **st2 value change after copyString function**, but i can't seem to change it through **temp** var. But if i try to change the **st2** value in the function, i got the Access Violation Error. Any idea how to fix this?<issue_comment>username_1: The .css you've provided seems fully functional, and customizable. (aka, not broken, works fine). The whole .css and the .html might shed some light on things without any "major alterations". ```css .lc_button { height: 100px !important; width: 200px !important; font-size: 18px !important; border: 1px solid #dd3333 !important; text-align: center; background-color: white; border-radius: 5%; } .lc_button:hover { background-color: white; border: 4px solid #0000ff !important; color: #00ff00 !important; } .lc_button a:hover { color: #151515 !important; } ``` ```html Test ``` Upvotes: 1 <issue_comment>username_2: I've shared the code snippet..I think this will help you to solve the problem... ```css *, *:after, *:before { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } body{ font-family: 'PT Sans', sans-serif; display: table; width: 100%; background: #f54785; } .container{ display: table-cell; vertical-align: middle; text-align: center; height: 100vh; } button{ display: inline-block; position: relative; background: none; border: none; color: #fff; font-size: 18px; cursor: pointer; margin: 20px 30px; background: rgba(0,0,0,0.09); } span{ display: block; padding: 25px 80px; } button::before, button::after{ content:""; width: 0; height: 2px; position: absolute; transition: all 0.2s linear; background: #fff; } span::before, span::after{ content:""; width:2px; height:0; position: absolute; transition: all 0.2s linear; background: #fff; } button:hover::before, button:hover::after{ width: 100%; } button:hover span::before, button:hover span::after{ height: 100%; } .btn-1::after{ left:0; bottom: 0; transition-duration: 0.4s; } .btn-1 span::after{ right:0; top: 0; transition-duration: 0.4s; } .btn-1::before{ right: 0; top: 0; transition-duration: 0.4s; } .btn-1 span::before{ left: 0; bottom: 0; transition-duration: 0.4s; } ``` ```html Hover Me ``` Upvotes: 0 <issue_comment>username_3: I've tried to solve your problem. I am successful. You can use this code of mine. **HTML** ``` [Watch video](#) ``` **CSS** ``` .lc_button a { display: block; width: 200px; height: 100px; line-height: 100px; font-size: 18px; font-weight: 700; color: #000000; border-radius: 5%; box-sizing: border-box; transition: 0.3s; background-color: white; text-decoration: none; text-transform: uppercase; text-align: center; position: relative; } .lc_button a:before { display: block; position: absolute; border-radius: 5%; left: 0; top: 0; content: ""; width: 200px; height: 100px; box-sizing: border-box; border: 1px solid red; transition: 0.3s; } .lc_button a:hover:before { border: 4px solid red; } .lc_button a:hover { color: #151515 !important; background-color: #ffffff; } ``` ```css .lc_button a { display: block; width: 200px; height: 100px; line-height: 100px; font-size: 18px; font-weight: 700; color: #000000; border-radius: 5%; box-sizing: border-box; transition: 0.3s; background-color: white; text-decoration: none; text-transform: uppercase; text-align: center; position: relative; } .lc_button a:before { display: block; position: absolute; border-radius: 5%; left: 0; top: 0; content: ""; width: 200px; height: 100px; box-sizing: border-box; border: 1px solid red; transition: 0.3s; } .lc_button a:hover:before { border: 4px solid red; } .lc_button a:hover { color: #151515 !important; background-color: #ffffff; } ``` ```html [Watch video](#) ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: This will help you to solve the problem... ```css button { height: 100px !important; width: 200px !important; font-size: 18px !important; border: 1px solid #dd3333 !important; text-align: center; background-color: white; border-radius: 5%; } button:hover { background-color: white; border: 4px solid #dd3333 !important; color: #151515 !important; } button a:hover { color: #151515 !important; } ``` ```html Hover Me ``` Upvotes: 0
2018/03/15
491
1,889
<issue_start>username_0: We are designing a system for conducting a survey in which it askes user a about 72 questions (Multiple Choice questions) And when the user submits this will be posted to php page which will save the answer in a MySQL table. Its works fine and perfectly well when we doing the test with a small number of user But I observed the when a large amount of users are submitting not all data reaches the server only a part of some users answer (around 65 answer) only reaches the server.But i get data from my all users but some answers aren't compete. Am using MySql engine : MyISAM What would be the problem or how can i solve this. is it the problem with some php configuration or mysql (large number of insert statement) What is the best way to handle larger amount data from a form submission php Thanks in Advance<issue_comment>username_1: You should use the ajax function for post the data.. Go through bellow link,it might help you <https://www.w3schools.com/jquery/ajax_ajax.asp> Upvotes: 0 <issue_comment>username_2: There is a limit on `POST` request size in PHP. You can adjust [`post_max_size`](http://php.net/ini.core.php#ini.post-max-size) in your `php.ini`. As for database, I don't know how you are saving them in the database, but there are character/storage limitation on the database as well. Whenever I'm dealing with large `POST` data like sending numerous field values through forms, using ajax does wonders! Try using jQuery [`$.post()`](https://api.jquery.com/jquery.post/), which is the shorthand for [`$.ajax()`](https://api.jquery.com/jQuery.ajax/). It's quite easy to use, even if you're not that familiar with jQuery :) Upvotes: 3 [selected_answer]<issue_comment>username_3: You need to Increase max\_input\_vars from php.ini OR you can set the following code in your .htaccess file. ``` php_value max_input_vars 3000 ``` Upvotes: 2
2018/03/15
1,016
3,215
<issue_start>username_0: I made 2D arrray which prints some random elements. Now i need a method which calculates the sum of that elements but just elements below the main diagonal. Here is my code... ``` class Init { public static void main(String[] args) { int n = 0; int m = 0; int aray[][]; Random random = new Random(); Scanner tastatura = new Scanner(System.in); int[][] array = new int[n][m]; n = tastatura.nextInt(); m = tastatura.nextInt(); array = new int[n][m]; for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { array[i][j] = random.nextInt(20); } } for (int[] a : array) { System.out.println(Arrays.toString(a)); } } } ``` I did it like this... Now i can sum, but when i try to multyply same numbers i am geting 0 Why is that? ``` Scanner scanner = new Scanner(System.in); System.out.print("Unesite duzinu kolona i redova : "); int rows = scanner.nextInt(); int columns = rows; int[][] matrix = new int[rows][rows]; Random random = new Random(); System.out.println("Nasumicni/random brojevi su :"); for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { matrix[i][j] = random.nextInt(20); } } for (int[] a : matrix) { System.out.println(Arrays.toString(a)); } //here is the logic which sum those elements int sum = 0; for (int i = 1; i < rows; i++) { for (int j = i - 1; j >= 0; j--) { sum = sum + matrix[i][j]; } } System.out.println("\nMatrix is : "); for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } System.out.println("Proizvod elemenata ispod glavne dijagonale je: " + sum); ```<issue_comment>username_1: The **main diagonal** of a matrix consists of those elements that lie on the diagonal that runs from top left to bottom right. But since you want those elements "below" the main diagonal, here is an algorithm I came up with for that. ``` int sum = 0; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (i == j && (i + 1 < n)) { int temp = i + 1; while (temp < n) { sum += arr[temp][j]; temp++; } } ``` Also, you declare `int[][] array` multiple times. You need to declare it only once, after you get the values for n and m. Upvotes: 1 <issue_comment>username_2: What about this? ``` int s = 0; for(int i = 1; i < m; ++i) for(int j = 0; j < i; ++j) s += a[i][j]; ``` This **selectively** loops through the elements below the main diagonal and sums them up, without **looping through the entire matrix** and making it lengthier. Upvotes: 2 <issue_comment>username_3: for(i=0;i         for(j=0;j         {                 if(j>i)                     d1+=a[i][j];. // Above the diagon                 else                     if(i>j)                         d2+=a[i][j];. // Below the diagonal         } Upvotes: 0
2018/03/15
515
2,017
<issue_start>username_0: I'm reading an article which says all Exceptions cause Ruby to crash. <http://blog.honeybadger.io/a-beginner-s-guide-to-exceptions-in-ruby/> I've got some DB schema constraints: ``` create_table :options_sets do |t| t.boolean :shared, :null => false end ``` So when I create a new options\_set that violates the constraint, causing the exception, I don't know how to check whether the server has restarted, but it doesn't look like it to me. ``` OptionsSet.create() ``` Error Msg: ``` ActiveRecord::StatementInvalid (PG::NotNullViolation: ERROR: null value in column "shared" violates not-null constraint ``` I've also read many times that "exceptions should not be expected" and that you shouldn't rely exclusively on model validation for various reasons (like race conditions). So it seems to me that this is an exception that must be expected sometimes. So, should I be rescuing this exception or should it be handled in another way?<issue_comment>username_1: Rails handles all otherwise unhandled exceptions and turns them into HTML error pages. Ruby does not "crash" or restart just because you failed to rescue an exception in your Rails application. > > So, should I be rescuing this exception or should it be handled in another way? > > > You should be using validations in your model to prevent you from reaching database-level exceptions. Upvotes: 1 <issue_comment>username_2: The exception that you see here is one that is caused by a faulty programming statement. If you have a bare ``` OptionsSet.create() ``` in your code, this statement **is** the error and it should be fixed. No need to rescue / handle anything. If, however this exception could be caused by **user input** or other program state, e.g. ``` OptionsSet.create(shared: some_expression_which_may_evaluate_to_nil) ``` then you **should** handle the exception to allow your application to return a meaningful error message to the user, allowing him/her to correct the input. Upvotes: 0
2018/03/15
872
3,472
<issue_start>username_0: I have a situation to do sliding count over large scale of messages using `State` and `TimeService`. The sliding size is one and the window size is larger than 10 hours. The problem I meet is the checkpointing takes a lot of time. In order to improve the performance we use the incremental checkpoints. But it is still slow when the system do the checkpoint. We figure out that the most of the time is used to serialize the timers which are used to clean data. We have a timer for each key and there are about 300M timers at all. Any suggestion to solve this problem would be appreciated. Or we can do the count in another way? ———————————————————————————————————————————— I'd like to add some details to the situation. The sliding size is one event and the window size is more than 10 hours(There are about 300 events per second), we need to react on each event. So in this situation we did not use the windows provided by Flink. we use the `keyed state` to store the previous information instead. The `timers` is used in `ProcessFunction` to trigger the cleaning job of the old data. At last the number of the dinstinct keys is very large.<issue_comment>username_1: What about if instead of using timers you add an extra field to every element of your stream to store the current processing time or the arrival time? So once you want to clean old data from your stream, you just have to use a filter operator and check if the data it's old engouh to be deleted. Upvotes: 0 <issue_comment>username_2: Rather than registering a clearing timer on each event, how about you register a timer only once per some period e.g. once per 1 minute? You could register it only the first time a key is seen, plus refresh it in `onTimer`. Sth like: ``` new ProcessFunction() { ... @Override public void processElement( SongEvent songEvent, Context context, Collector collector) throws Exception { Boolean isTimerRegistered = state.value(); if (isTimerRegistered != null && !isTimerRegistered) { context.timerService().registerProcessingTimeTimer(time); state.update(true); } // Standard processing } @Override public void onTimer(long timestamp, OnTimerContext ctx, Collector out) throws Exception { pruneElements(timestamp); if (!elements.isEmpty()) { ctx.timerService().registerProcessingTimeTimer(time); } else { state.clear(); } } } ``` Something similar is implemented for Flink SQL `Over` clause. You can have a look [here](https://github.com/apache/flink/blob/master/flink-libraries/flink-table/src/main/scala/org/apache/flink/table/runtime/aggregate/RowTimeUnboundedOver.scala) Upvotes: 0 <issue_comment>username_3: I think this should work: Dramatically reduce the number of keys Flink is working with from 300M down to 100K (for example), by effectively doing something like keyBy(key mod 100000). Your ProcessFunction can then use a MapState (where the keys are the original keys) to store whatever it needs. MapStates have iterators, which you can use to periodically crawl each of these maps to expire old items. Stick to the principle of having only one timer per key (per uberkey, if you will), so that you only have 100K timers. UPDATE: Flink 1.6 included [FLINK-9485](https://issues.apache.org/jira/browse/FLINK-9485), which allows timers to be checkpointed asynchronously, and to be stored in RocksDB. This makes it much more practical for Flink applications to have large numbers of timers. Upvotes: 2
2018/03/15
1,252
3,499
<issue_start>username_0: I have 3 divs. One of them is functioning as a wrapper for the other two. Let's call them div1 and div2. Div1 has a fixed width. The width of the wrapper is variable but never less then the width of div1. Now, how do I make div2 always have the width (width of wrapper - width of div1)? Here is what I got: ``` .wrapper { width: 420px; /*Variable but not less then width of div1*/ height: 500px; border: 2px solid #0000FF; } .div1 { width: 200px; height: 200px; /*Fixed*/ border: 2px solid #FF0000; display: inline-block; } .div2 { position: absolute; width: 100%; /*Should be width of wrapper - width of div1*/ height: 200px; border: 2px solid #00FF00; display: inline-block; } ``` <https://jsfiddle.net/kjhnhtny/10/><issue_comment>username_1: If I have not mistaken your question, you can use a pure css approach. ``` .wrapper { width: 420px; /*Variable but not less then width of div1*/ height: 500px; border: 2px solid #0000FF; box-sizing: border-box; } .div1 { width: 200px; height: 200px; /*Fixed*/ border: 2px solid #FF0000; float: left; box-sizing: border-box; } .div2 { width: 100%; /*Should be width of wrapper - width of div1*/ height: 200px; border: 2px solid #00FF00; box-sizing: border-box; } ``` Upvotes: 2 <issue_comment>username_2: You're looking for two things: * To set `float: left` on `.div2` * The CSS **[`calc()`](https://developer.mozilla.org/en-US/docs/Web/CSS/calc)** function, which can handle subtraction. Specifically, you're looking for `width: calc(100% - (200px + (2px * 2) + (2px * 2)))`, which is `100%` of the`.wrapper`, minus the `width` of `.div1`, along with both sides of both element's `border` width. This can be seen in the following: ```css .wrapper { width: 420px; /*Variable but not less then width of div1*/ height: 500px; border: 2px solid #0000FF; } .div1 { width: 200px; height: 200px; /*Fixed*/ border: 2px solid #FF0000; display: inline-block; } .div2 { float: left; width: calc(100% - (200px + (2px * 2) + (2px * 2))); /*Should be width of wrapper - width of div1*/ height: 200px; border: 2px solid #00FF00; display: inline-block; } ``` ```html ``` Note that you **could** make use of **[CSS variables](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables)** so that you only need to modify one property's value (with all elements being automatically adjusted), by setting a variable in `:root` and referencing it with **[`var()`](https://developer.mozilla.org/en-US/docs/Web/CSS/var)**. Having said that, CSS variables would probably be a bit overkill, but I'll show you how can use them in case you opt for this approach. Try adjusting the `--border-width` in the following, and you'll see that all elements update and resize appropriately :) ```css :root { --width: 200px; --border-width: 2px; } .wrapper { width: 420px; /*Variable but not less then width of div1*/ height: 500px; border: var(--border-width) solid #0000FF; } .div1 { width: var(--width); height: 200px; /*Fixed*/ border: var(--border-width) solid #FF0000; display: inline-block; } .div2 { float: left; width: calc(100% - (var(--width) + (var(--border-width) * 2) + (var(--border-width) * 2))); /*Should be width of wrapper - width of div1*/ height: 200px; border: var(--border-width) solid #00FF00; display: inline-block; } ``` ```html ``` Upvotes: 2 [selected_answer]
2018/03/15
499
1,980
<issue_start>username_0: I want to store a non-critical non-confidential piece of information in the user's session in a Ruby on Rails app. The user model is set up with Devise. How do I do this? Various guides give conflicting and incomplete information about it. `session[:foo]`? `user_session[:foo]`? Do I need to set something up to be able to use whichever it is - e.g. get a gem, config something, or insert any lines before setting the session variable? To provide context - the user may be creating multiple new items back-to-back, so it would be nice if the `new` form remembered and pre-selected the category based on what they selected previously. If there's a better way to do this, I'm open to suggestions. I'm new to all this. Thank you!!<issue_comment>username_1: > > Are session variables in 'session' or 'user\_session' in Rails? > > > The simple answer is the session variables is named `session`. A session usually consists of a hash of values and a session id, usually a 32-character string, to identify the hash. Every cookie sent to the client's browser includes the session id. And the other way round: the browser will send it to the server on every request from the client. In Rails you can save and retrieve values using the session method: ``` session[:cat_id] = cat_id Category.find(session[:cat_id]) ``` You can read this [`Rails Guide`](http://guides.rubyonrails.org/v5.0.1/security.html#sessions) about session. [`ActionDispatch::Session::CookieStore`](http://api.rubyonrails.org/classes/ActionDispatch/Session/CookieStore.html) Upvotes: 2 <issue_comment>username_2: The default Rails session object is accessible via the `session` helper method. It gives you an access to some chunks of data and is bound to a cookie value stored in your browser. The `user_session` helper is provided by the Devise gem. It gives you additional security by restricting access to specific session data while user is authenticated on a server. Upvotes: 1
2018/03/15
2,087
8,597
<issue_start>username_0: I was reading the documentation on the Auth0 site regarding [Refresh Tokens and SPA](https://auth0.com/docs/api-auth/which-oauth-flow-to-use#is-the-client-a-native-app-or-a-spa-), and they state that [SPA's should not use Refresh Tokens](https://auth0.com/docs/tokens/refresh-token/current) as they cannot be securely stored in a browser, and instead use Silent Authentication instead to retrieve new Access Tokens. > > A Single Page Application (normally implementing Implicit Grant) should not under any circumstances get a Refresh Token. The reason for that is the sensitivity of this piece of information. You can think of it as user credentials, since a Refresh Token allows a user to remain authenticated essentially forever. Therefore you cannot have this information in a browser, it must be stored securely. > > > I'm confused. From my understanding, the only way to retrieve a new access token would be to submit a new request to the Auth server, along with some form of an Auth0 session cookie to authenticate the user that is logged in. Upon receiving the session cookie the Auth0 server would then be able to issue a new Access Token. But how is that any different than having a Refresh Token in the browser or in the local storage? What makes the Session Cookie any more secure than a Refresh Token? Why is using a Refresh Token in an SPA a bad thing?<issue_comment>username_1: **Good question** - So there is no really secure way to store any tokens on a Browser (or any other confidential info) - see [links such as this](https://www.rdegges.com/2018/please-stop-using-local-storage/). Hence Single Page Apps (SPA) should not store a refresh token - a refresh token is particularly problematic, because it is long lived (long expiration or no expiration), and if stolen then an attacker can continue to refresh access tokens after each individually expires. It would be better to just retrieve your access token when you need it (for instance to call an API) and either store only in memory (still vulnerable to XSS / CSRF) but better - or use and forget. Then make another checkSession call next time you need an access token. To your question - the checkSession **request** does not require sending a Token. It is literally as the name suggests - a "check session" against the Authorization Server to see if a Session exists. If it does, then the Authorization Server **response** will include a fresh access token. See [here for an example usage with SPA](https://github.com/auth0-samples/auth0-single-page-app-login-with-sso-and-api/blob/master/public/javascript/index.js#L40) Please feel free to leave me comments beneath this answer if anything requires more clarification etc. Upvotes: 3 <issue_comment>username_2: The refresh tokens are not used in SPAs, because in order to use it - and to get a new access token from the `/token`, the SPA needs to have a client secret, which cannot be stored securely in a browser. But since the [OAuth 2.0 for Native Apps RFC](https://www.rfc-editor.org/rfc/rfc8252#section-8.5) recommends not requiring a client secret for the `/token` endpoint (for public clients), the refresh tokens could be used even in SPAs. To get a refresh token, you need to use the [Auth code grant](https://www.rfc-editor.org/rfc/rfc6749#section-4.1), which passes the code in a redirect URL, which goes to the server hosting the SPA (which can be an extra point of attack). The Implicit grant delivers tokens just to a browser (hash part of the redirect URL doesn't get to the server). The difference between using a refresh token and an SSO session cookie - the cookie is probably more secure, since it can be marked as [HttpOnly](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies), making it inaccessible for attacks using JavaScript code. **Update** With [PKCE](https://www.rfc-editor.org/rfc/rfc7636) extension, the Authorization code flow (with a refresh token) became a recommended flow even for browser based applications. For details see the latest version of the [OAuth 2.0 for Browser-Based Apps RFC](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-browser-based-apps-04). Upvotes: 4 <issue_comment>username_3: There are a lot of misunderstandings about both cookies and refresh tokens and OAuth2. First, it is not true that only confidential clients can use a refresh token. The OAuth2 protocol says that confidential clients must authenticate, but does not require confidential clients. Ergo, client authentication is optional on the refresh operation. See [RFC 6749, Section 6, Refreshing An Access Token](https://www.rfc-editor.org/rfc/rfc6749#section-6). Second, you have to understand what the alternatives are: 1. Forcing the user to enter his or her username and password every 5 minutes (whenever the access token expires) 2. Long lived access tokens 3. Authentication via HTTP Cookies Everybody in the world, who doesn't use refresh tokens, uses option #3. Authentication via cookies is functionally and security-wise 100% equivalent to storing a refresh token. Of course, with both tokens and cookies, there are options for where they are kept: a. HTTP only, b. secure (require TLS/SSL) and c. session (in memory) vs. persistent (local, domain storage) The "HTTP only" option applies only to cookies and, thus, may represent the only advantage of using cookies over tokens. I.e. tokens are handled via Javascript, so there's no option to keep them away from scripts. That said, the tokens are available only to Javascript from the domain of the page that stored it (or as allowed by CORS policy). So this issue can be overblown. Of course, care must be taken to ***always*** use TLS/SSL to transmit either authentication cookies or tokens. Honestly, since we know most breaches occur from within the private corporate network, end-to-end TLS is a basic requirement anymore. Finally, whether cookies or tokens are ever *persisted*, i.e. stored somewhere that survives closing the browser or even rebooting the device, depends on the trade-off you're making between usability and security - *for **your** application*. For applications that require a higher level of security, just keep everything in memory (i.e. session cookies, tokens in a Javascript variable). But for apps that don't require as much security and really want a session life on order of days or weeks, then you need to store them. Either way, that storage is accessible only to pages and scripts from the original domain and, thus, cookies and tokens are functionally equivalent. Upvotes: 5 <issue_comment>username_4: This is not true anymore (April 2021), [Auth0 site](https://auth0.com/docs/tokens/refresh-tokens#for-single-page-apps) now states a different thing: > > **Auth0 recommends using refresh token rotation which provides a secure method for using refresh tokens in SPAs** while providing end-users with seamless access to resources without the disruption in UX caused by browser privacy technology like ITP. > > > > > Auth0’s former guidance was to use the Authorization Code Flow with Proof Key for Code Exchange (PKCE) in conjunction with Silent Authentication in SPAs. This is a more secure solution than the Implicit Flow but not as secure as the Authorization Code Flow with Proof Key for Code Exchange (PKCE) with refresh token rotation. > > > Please note the importance of enabling rotation in refresh token. Upvotes: 4 <issue_comment>username_5: We could store the refresh token in a cookie with the httpOnly, secure and signed flags set to true. NodeJs Example on setting the refresh token in a cookie ``` const refreshToken = signToken(userId) const cookieName = "foo-bar-blah" res.cookie(cookieName , refreshToken , { httpOnly: true, signed: true, secure: true }) ``` All we have to do is send the cookie containing the refresh token with a request from the client side without needing to access it at all. Client-side requests with a library like axios ``` await axios.get('refresh-endpoint', { withCredentials: true }) ``` withCredentials set to true sends browser cookies with the request. Anytime the client hits the refresh-endpoint route on the server, the cookie is decrypted with the secret stored on the server and the refresh token is retrieved. This setup makes it difficult for the refresh token to be accessed by client-side JavaScript. Even if that was possible there's still a problem of retrieving the refresh token from the cookie without the cookie secret on the server. I think this is fairly secure. Upvotes: 0
2018/03/15
2,021
7,916
<issue_start>username_0: ``` Traceback (most recent call last): File "Final_3.py", line 42, in np.savetxt("table.csv", output\_arr, fmt='%s' , delimiter=",") File "/usr/local/lib/python2.7/dist-packages/numpy/lib/npyio.py", line 1381, in savetxt fh.write(v) File "/usr/local/lib/python2.7/dist-packages/numpy/lib/npyio.py", line 1291, in write\_normal self.fh.write(asunicode(v)) File "/usr/local/lib/python2.7/dist-packages/numpy/compat/py3k.py", line 70, in asunicode return str(s).decode('ascii') UnicodeDecodeError: 'ascii' codec can't decode byte 0xce in position 22: ordinal not in range(128) ``` I have also tried reload(sys) sys.setdefaultencoding('utf8') in my code, but it still didn't help.<issue_comment>username_1: **Good question** - So there is no really secure way to store any tokens on a Browser (or any other confidential info) - see [links such as this](https://www.rdegges.com/2018/please-stop-using-local-storage/). Hence Single Page Apps (SPA) should not store a refresh token - a refresh token is particularly problematic, because it is long lived (long expiration or no expiration), and if stolen then an attacker can continue to refresh access tokens after each individually expires. It would be better to just retrieve your access token when you need it (for instance to call an API) and either store only in memory (still vulnerable to XSS / CSRF) but better - or use and forget. Then make another checkSession call next time you need an access token. To your question - the checkSession **request** does not require sending a Token. It is literally as the name suggests - a "check session" against the Authorization Server to see if a Session exists. If it does, then the Authorization Server **response** will include a fresh access token. See [here for an example usage with SPA](https://github.com/auth0-samples/auth0-single-page-app-login-with-sso-and-api/blob/master/public/javascript/index.js#L40) Please feel free to leave me comments beneath this answer if anything requires more clarification etc. Upvotes: 3 <issue_comment>username_2: The refresh tokens are not used in SPAs, because in order to use it - and to get a new access token from the `/token`, the SPA needs to have a client secret, which cannot be stored securely in a browser. But since the [OAuth 2.0 for Native Apps RFC](https://www.rfc-editor.org/rfc/rfc8252#section-8.5) recommends not requiring a client secret for the `/token` endpoint (for public clients), the refresh tokens could be used even in SPAs. To get a refresh token, you need to use the [Auth code grant](https://www.rfc-editor.org/rfc/rfc6749#section-4.1), which passes the code in a redirect URL, which goes to the server hosting the SPA (which can be an extra point of attack). The Implicit grant delivers tokens just to a browser (hash part of the redirect URL doesn't get to the server). The difference between using a refresh token and an SSO session cookie - the cookie is probably more secure, since it can be marked as [HttpOnly](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies), making it inaccessible for attacks using JavaScript code. **Update** With [PKCE](https://www.rfc-editor.org/rfc/rfc7636) extension, the Authorization code flow (with a refresh token) became a recommended flow even for browser based applications. For details see the latest version of the [OAuth 2.0 for Browser-Based Apps RFC](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-browser-based-apps-04). Upvotes: 4 <issue_comment>username_3: There are a lot of misunderstandings about both cookies and refresh tokens and OAuth2. First, it is not true that only confidential clients can use a refresh token. The OAuth2 protocol says that confidential clients must authenticate, but does not require confidential clients. Ergo, client authentication is optional on the refresh operation. See [RFC 6749, Section 6, Refreshing An Access Token](https://www.rfc-editor.org/rfc/rfc6749#section-6). Second, you have to understand what the alternatives are: 1. Forcing the user to enter his or her username and password every 5 minutes (whenever the access token expires) 2. Long lived access tokens 3. Authentication via HTTP Cookies Everybody in the world, who doesn't use refresh tokens, uses option #3. Authentication via cookies is functionally and security-wise 100% equivalent to storing a refresh token. Of course, with both tokens and cookies, there are options for where they are kept: a. HTTP only, b. secure (require TLS/SSL) and c. session (in memory) vs. persistent (local, domain storage) The "HTTP only" option applies only to cookies and, thus, may represent the only advantage of using cookies over tokens. I.e. tokens are handled via Javascript, so there's no option to keep them away from scripts. That said, the tokens are available only to Javascript from the domain of the page that stored it (or as allowed by CORS policy). So this issue can be overblown. Of course, care must be taken to ***always*** use TLS/SSL to transmit either authentication cookies or tokens. Honestly, since we know most breaches occur from within the private corporate network, end-to-end TLS is a basic requirement anymore. Finally, whether cookies or tokens are ever *persisted*, i.e. stored somewhere that survives closing the browser or even rebooting the device, depends on the trade-off you're making between usability and security - *for **your** application*. For applications that require a higher level of security, just keep everything in memory (i.e. session cookies, tokens in a Javascript variable). But for apps that don't require as much security and really want a session life on order of days or weeks, then you need to store them. Either way, that storage is accessible only to pages and scripts from the original domain and, thus, cookies and tokens are functionally equivalent. Upvotes: 5 <issue_comment>username_4: This is not true anymore (April 2021), [Auth0 site](https://auth0.com/docs/tokens/refresh-tokens#for-single-page-apps) now states a different thing: > > **Auth0 recommends using refresh token rotation which provides a secure method for using refresh tokens in SPAs** while providing end-users with seamless access to resources without the disruption in UX caused by browser privacy technology like ITP. > > > > > Auth0’s former guidance was to use the Authorization Code Flow with Proof Key for Code Exchange (PKCE) in conjunction with Silent Authentication in SPAs. This is a more secure solution than the Implicit Flow but not as secure as the Authorization Code Flow with Proof Key for Code Exchange (PKCE) with refresh token rotation. > > > Please note the importance of enabling rotation in refresh token. Upvotes: 4 <issue_comment>username_5: We could store the refresh token in a cookie with the httpOnly, secure and signed flags set to true. NodeJs Example on setting the refresh token in a cookie ``` const refreshToken = signToken(userId) const cookieName = "foo-bar-blah" res.cookie(cookieName , refreshToken , { httpOnly: true, signed: true, secure: true }) ``` All we have to do is send the cookie containing the refresh token with a request from the client side without needing to access it at all. Client-side requests with a library like axios ``` await axios.get('refresh-endpoint', { withCredentials: true }) ``` withCredentials set to true sends browser cookies with the request. Anytime the client hits the refresh-endpoint route on the server, the cookie is decrypted with the secret stored on the server and the refresh token is retrieved. This setup makes it difficult for the refresh token to be accessed by client-side JavaScript. Even if that was possible there's still a problem of retrieving the refresh token from the cookie without the cookie secret on the server. I think this is fairly secure. Upvotes: 0
2018/03/15
721
2,844
<issue_start>username_0: I want create a View the same Image. [![enter image description here](https://i.stack.imgur.com/FB0Qy.png)](https://i.stack.imgur.com/FB0Qy.png) Touch value on View: [![enter image description here](https://i.stack.imgur.com/Es28f.png)](https://i.stack.imgur.com/Es28f.png) I using the solution create TextView and touch on TextView: This is layout xml: i create 6 TextViews to display value when Touch on Screen. ``` ``` and i create event Touch on TextViews, to change value of Textview: ``` dialog.txtPreSelect1.setOnTouchListener {v: View, event: MotionEvent -> // Perform tasks here when (event.action) { MotionEvent.ACTION_DOWN ->{ yValue=event.y } MotionEvent.ACTION_MOVE ->{ val curentY=event.y if(curentY>yValue) { if(curentY>yValue) { yValue=curentY var iStartValue=dialog.txtPreSelect1.text.toString().toInt() - iStep1 dialog.txtPreSelect1.text = iStartValue.toString() iStartValue=iStartValue +iStep1 dialog.txtSelect1.text = iStartValue.toString() iStartValue=iStartValue +iStep1 dialog.txtNextSelect1.text = iStartValue.toString() } } else if(curentY ``` How can create event move text the same image 2? Or Exist other View can process my work? Thank all.<issue_comment>username_1: If I understand correctly your problem is in creating two views with lists, so you can touch and scroll them separately. You can try to dive into this library that is quite similar what you are trying to reach: [SingleDateAndTimePicker](https://github.com/florent37/SingleDateAndTimePicker) Upvotes: 1 <issue_comment>username_2: My best guess is you want to use native component. You can use [ListView](https://developer.android.com/reference/android/widget/ListView.html) but that would require much code than [Number Picker](https://developer.android.com/reference/android/widget/NumberPicker.html). Number Picker is specifically designed to handle such situations. Here in SO a [Nice example](https://stackoverflow.com/questions/17944061/how-to-use-number-picker-with-dialog) can show you how to use it in dialog. Basically you need a [LinearLayout](https://developer.android.com/reference/android/widget/LinearLayout.html) with Horizontal Orientation and place two `Number Picker` inside it. You can set `MinValue` and `MaxValue` with the help of java/kotlin like this: ``` numberPicker.setMaxValue(50); numberPicker.setMinValue(1); ``` let me know if you have any query. Upvotes: 1 [selected_answer]
2018/03/15
484
1,736
<issue_start>username_0: Does anyone know how to load current date data dynamically into a date in PHP ? In example: the year, to automatically update. I'm trying the following without success. ``` $nowDate = date('d/m/Y'); $cYear = date('Y'); $dateBegin = DateTime::createFromFormat('d/m/Y', '01/01/'.$cYear); $dateEnd = DateTime::createFromFormat('d/m/Y', '31/12/'.$cYear); if ($nowDate >= $dateBegin && $nowDate <= $dateEnd) { echo "is between"; } else { echo 'OUT!'; } ```<issue_comment>username_1: If I understand correctly your problem is in creating two views with lists, so you can touch and scroll them separately. You can try to dive into this library that is quite similar what you are trying to reach: [SingleDateAndTimePicker](https://github.com/florent37/SingleDateAndTimePicker) Upvotes: 1 <issue_comment>username_2: My best guess is you want to use native component. You can use [ListView](https://developer.android.com/reference/android/widget/ListView.html) but that would require much code than [Number Picker](https://developer.android.com/reference/android/widget/NumberPicker.html). Number Picker is specifically designed to handle such situations. Here in SO a [Nice example](https://stackoverflow.com/questions/17944061/how-to-use-number-picker-with-dialog) can show you how to use it in dialog. Basically you need a [LinearLayout](https://developer.android.com/reference/android/widget/LinearLayout.html) with Horizontal Orientation and place two `Number Picker` inside it. You can set `MinValue` and `MaxValue` with the help of java/kotlin like this: ``` numberPicker.setMaxValue(50); numberPicker.setMinValue(1); ``` let me know if you have any query. Upvotes: 1 [selected_answer]
2018/03/15
1,181
4,231
<issue_start>username_0: I am trying to create a REST server using hyper. For robust error handling, I would prefer to have the service return a future with a custom error type that wraps hyper, Diesel, and other errors. Unfortunately, `hyper::Response` seems to hard-code a stream with error type `hyper::error::Error`, which conflicts with the error type I've defined for my service. I see a couple possible solutions: 1. Make my service return my custom error type by modifying `hyper::Response`, which seems hard. 2. Wrap non-hyper errors in a `hyper::error::Error`. This seems hacky. 3. Something else. It seems like I'm missing the "right" way to do this. The following code shows what I think I want to do: ``` extern crate diesel; extern crate futures; extern crate hyper; use futures::future::{ok, Future}; use hyper::StatusCode; use hyper::server::{Request, Response, Service}; fn main() { let address = "127.0.0.1:8080".parse().unwrap(); let server = hyper::server::Http::new() .bind(&address, move || Ok(ApiService {})) .unwrap(); server.run().unwrap(); } pub struct ApiService; impl Service for ApiService { type Request = Request; type Response = Response; type Error = Error; type Future = Box>; fn call(&self, request: Request) -> Self::Future { Box::new(ok(Response::new().with\_status(StatusCode::Ok))) } } #[derive(Debug)] pub enum Error { Request(hyper::Error), DatabaseResult(diesel::result::Error), DatabaseConnection(diesel::ConnectionError), Other(String), } // omitted impl of Display, std::error::Error for brevity ``` This code results in a compiler error which I believe is because the `bind` function requires that the response type have a body that is a stream with error type `hyper::error::Error`: ```none error[E0271]: type mismatch resolving `::Error == hyper::Error` --> src/main.rs:14:10 | 14 | .bind(&address, move || Ok(ApiService {})) | ^^^^ expected enum `Error`, found enum `hyper::Error` | = note: expected type `Error` found type `hyper::Error` ```<issue_comment>username_1: You can implement the [`std::convert::From`](https://doc.rust-lang.org/std/convert/trait.From.html) trait for your `Error` type. E.g. for the `hyper::Error` case: ``` impl From for Error { fn from(error: hyper::Error) -> Self { Error::Request(error) } } ``` Upvotes: -1 <issue_comment>username_2: Because the ultimate goal of the server is to return a response to the user, I found an acceptable solution to be to create a `finalize` function that converts errors encountered while processing a request into correctly formed responses and treats those errors as non-errors from hyper's perspective. I will need to flesh this idea out some (e.g. By passing along hyper errors as errors), but I believe the basic idea is sound. The following code modifies the code in the question to do this: ``` extern crate diesel; extern crate futures; extern crate hyper; #[macro_use] extern crate serde_derive; use futures::future::{ok, Future}; use hyper::StatusCode; use hyper::server::{Request, Response, Service}; fn main() { let address = "127.0.0.1:8080".parse().unwrap(); let server = hyper::server::Http::new() .bind(&address, move || Ok(ApiService {})) .unwrap(); server.run().unwrap(); } fn finalize(result: Result) -> FutureResult { match result { Ok(response) => ok(response), Err(error) => { let response\_body = json!({"status": 500, "description": error.description()}).to\_string(); ok(Response::new() .with\_status(StatusCode::InternalServerError) .with\_header(ContentLength(response\_body.len() as u64)) .with\_body(response\_body)) } } } pub struct ApiService; impl Service for ApiService { type Request = Request; type Response = Response; type Error = hyper::Error; type Future = Box>; fn call(&self, request: Request) -> Self::Future { let response = Ok(Response::new().with\_status(StatusCode::Ok)); Box::new(finalize(response)) } } #[derive(Debug)] pub enum Error { Request(hyper::Error), DatabaseResult(diesel::result::Error), DatabaseConnection(diesel::ConnectionError), Other(String), } // omitted impl of Display, std::error::Error for brevity ``` Upvotes: 3
2018/03/15
669
2,367
<issue_start>username_0: I have this java **method** which returns an **ArrayList**, but I want to return an **Array of Strings**. The method reads the file words.txt (contains all words with a word on each line), and I want to store those words into an Array of Strings. Heres the code I already have: ``` public static ArrayList readFile(){ File myFile=new File("./src/folder/words.txt"); Scanner s1=null; //Creates ArrayList to store each String aux ArrayList myWords = new ArrayList(); try { s1 = new Scanner(myFile); }catch (FileNotFoundException e) { System.out.println("File not found"); e.printStackTrace(); } while(s1.hasNext()){ String aux=s1.next(); System.out.println(aux); } s1.close(); return myWords; } ``` Can I change this code to return a String []?<issue_comment>username_1: You can call [`List.toArray(String[])`](https://docs.oracle.com/javase/8/docs/api/java/util/List.html#toArray-T:A-) to convert the `List` to a `String[]`. I would also prefer a `try-with-resources` over explicitly closing the `Scanner` and a `List` *interface*. Something like, ``` public static String[] readFile() { // <-- You could pass File myFile here File myFile = new File("./src/folder/words.txt"); // Creates ArrayList to store each String aux List myWords = new ArrayList<>(); try (Scanner s1 = new Scanner(myFile)) { while (s1.hasNext()) { String aux = s1.next(); System.out.println(aux); } } catch (FileNotFoundException e) { System.out.println("File not found"); e.printStackTrace(); } return myWords.toArray(new String[0]); } ``` Upvotes: 2 <issue_comment>username_2: Add this at last: ``` String [] arr = myWords.toArray(new String[myWords.size()]); return arr; ``` Or simply, ``` return myWords.toArray(new String[myWords.size()]); ``` Upvotes: 1 <issue_comment>username_3: try using a built in function of collections class . ``` ArrayList stringList = new ArrayList(); stringList.add("x"); stringList.add("y"); stringList.add("z"); stringList.add("a"); /\*ArrayList to Array Conversion \*/ /\*You can use the toArray method of the collections class and pass the new String array object in the constructor while making a new String array\*/ String stringArray[]=stringList.toArray(new String[stringList.size()]); for(String k: stringArray) { System.out.println(k); } ``` Upvotes: 2