date
stringlengths
10
10
nb_tokens
int64
60
629k
text_size
int64
234
1.02M
content
stringlengths
234
1.02M
2018/03/21
776
2,565
<issue_start>username_0: I would like to query all models of a hasMany relationship that also have a pivoted relationship with a specified other model. Example: ``` Customer: belongsToMany -> Entry EntryGroup: hasMany -> Entry Entry: belongsToMany -> Customer belongsTo -> EntryGroup ``` The belongsToMany relationship between Customer and Entry is stored in a pivot table. I now want to collect the relationship to all Entries that belong to a specified Customer on an EntryGroup. Without this filtering restriction, I would have a function like ``` class EntryGroup extends Model { ... public function entries() { return $this->hasMany(Entry::class); } } ``` Thanks in advance for any suggestions you might have.<issue_comment>username_1: Apparently jedi-vim doesn't use the canonical -mappings, but separate configuration variables. Nonetheless ``` let g:jedi#goto_assignments_command = ",g" let g:jedi#goto_command = ",d" ``` in your `~/.vimrc` (i.e. before jedi-vim is sourced) should do the trick, and this is what I would recommend. ### Alternative The key is influenced by the `mapleader` variable. From [`:help`](https://vimhelp.appspot.com/map.txt.html#<Leader>) : > > Note that the value of "mapleader" is used at the moment the mapping is > defined. Changing "mapleader" after that has no effect for already defined > mappings. > > > So, you could also solve it this way: ``` let mapleader = ',' runtime! plugin/jedi.vim unlet mapleader ``` Plugin managers or installing as a *pack plugin* further complicate this, and it changes the ordering of plugin initialization. I do not recommend this. Upvotes: 3 [selected_answer]<issue_comment>username_2: Follow @[Ingo](https://stackoverflow.com/users/813602/ingo-karkat) answer. I remaped most used functions in [jedi-vim docu](https://github.com/davidhalter/jedi-vim/blob/master/doc/jedi-vim.txt): ``` :let g:jedi#goto_command = ",jd" :let g:jedi#goto_assignments_command = ",jg" :let g:jedi#usages_command = ",jn" :let g:jedi#rename_command = ",jr" " will auto-create next visual-map: ,jr *@:call jedi#rename_visual() " rename\_command() fails in normal-mode, but success in visual-mode ! :let g:jedi#goto\_stubs\_command = ",js" :let g:jedi#documentation\_command = ",jK" " s \*@'c'.jedi#complete\_string(0) :let g:jedi#completions\_command = "" " jedi-vim Plug called AFTER remaping its commands only Plug 'davidhalter/jedi-vim', {'for': 'python'} ``` PD: this should be a comment of Mr. Karkat answer, but still not 50 points. Upvotes: 0
2018/03/21
1,831
6,151
<issue_start>username_0: I tried to display Values on `TextView` but if I want to populate my `TextViews` on `PostExecute` I get a `NullPointerException`. I already checked if the `LIST>` is empty with `Log` but it is populated. My code: ``` public class DBResult extends MainActivity { //Erstellen eines JSON Parser Objekts JSONParser jParser = new JSONParser(); ArrayList> LIST = new ArrayList<>(); // url to get all products list private static String url\_dataget = "DATAGET\_PHP"; // JSON Node private static final String TAG\_SUCCESS = "success"; private static final String TAG\_PRODUCTS = "products"; private static final String TAG\_NAME = "name"; private static final String TAG\_INN = "inn"; private static final String TAG\_AnalgetikaGroup= "analgetikagroup"; private static final String TAG\_WHOLevel = "wholevel"; private static final String TAG\_DailyDose = "dailydose"; private static final String TAG\_contraindication = "contraindication"; private static final String TAG\_SideEffect = "sideeffect"; private static final String TAG\_GastricProtection = "gastricprotection"; // products JSONArray JSONArray products = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Background Thread new LoadMed().execute(); } class LoadMed extends AsyncTask{ protected String doInBackground(String...args){ // Building Parameters List params = new ArrayList(); // getting JSON string from URL JSONObject json = jParser.makeHttpRequest(url\_dataget, "GET", params); // Check your log cat for JSON reponse Log.d("Medic: ", json.toString()); try { // Checking for SUCCESS TAG int success = json.getInt(TAG\_SUCCESS); if (success == 1) { // products found // Getting Array of Products products = json.getJSONArray(TAG\_PRODUCTS); // looping through All Products for (int i = 0; i < products.length(); i++) { JSONObject c = products.getJSONObject(i); // Storing each json item in variable String name = c.getString(TAG\_NAME); String INN = c.getString(TAG\_INN); String AnalgetikaGroup = c.getString(TAG\_AnalgetikaGroup); String WHOLevel = c.getString(TAG\_WHOLevel); String DailyDose = c.getString(TAG\_DailyDose); String contraindication = c.getString(TAG\_contraindication); String SideEffect = c.getString(TAG\_SideEffect); String GastricProtection = c.getString(TAG\_GastricProtection); HashMap map = new HashMap<>(); map.put(TAG\_NAME,name); map.put(TAG\_INN,INN); map.put(TAG\_AnalgetikaGroup,AnalgetikaGroup); map.put(TAG\_WHOLevel,WHOLevel); map.put(TAG\_DailyDose,DailyDose); map.put(TAG\_contraindication,contraindication); map.put(TAG\_SideEffect,SideEffect); map.put(TAG\_GastricProtection,GastricProtection); Log.d("LIL",map.toString()); LIST.add(map); } } }catch (JSONException e) { e.printStackTrace(); } return null; } protected void onPostExecute(String file\_url) { runOnUiThread(new Runnable() { public void run() { Log.d("sad", LIST.toString()); TextView mednamefield = findViewById(R.id.medname); TextView sideeffectfield = findViewById(R.id.sideeffect); TextView medWHOfield = findViewById(R.id.wholevel); TextView medGastricProtectionfield = findViewById(R.id.gastricprotecio); TextView medINNfield = findViewById(R.id.INN); TextView medDailyDosefield = findViewById(R.id.dailydose); TextView medanalgeticafield = findViewById(R.id.analgeticagroup); TextView contraindicationfield = findViewById(R.id.contraindication); mednamefield.setText(LIST.get(0).get(TAG\_NAME)); sideeffectfield.setText(LIST.get(1).get(TAG\_SideEffect)); medWHOfield.setText((LIST.get(2).get(TAG\_WHOLevel))); medGastricProtectionfield.setText("Magenschutz empfohlen: " + LIST.get(3).get(TAG\_GastricProtection)); contraindicationfield.setText(LIST.get(4).get(TAG\_contraindication)); medINNfield.setText("INN: " + LIST.get(5).get(TAG\_INN)); medDailyDosefield.setText(LIST.get(6).get(TAG\_DailyDose)); medanalgeticafield.setText(LIST.get(7).get(TAG\_AnalgetikaGroup)); } }); } } ``` LOGCAT ERROR: ``` FATAL EXCEPTION: main Process: com.example.simon.test123, PID: 4019 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference at com.example.simon.test123.DBResult$LoadMed$1.run(DBResult.java:128) at android.app.Activity.runOnUiThread(Activity.java:5866) at com.example.simon.test123.DBResult$LoadMed.onPostExecute(DBResult.java:113) at com.example.simon.test123.DBResult$LoadMed.onPostExecute(DBResult.java:55) at android.os.AsyncTask.finish(AsyncTask.java:667) at android.os.AsyncTask.-wrap1(AsyncTask.java) at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:684) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6119) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) ``` NOTE: ***I already read the article "What is a NullPointerException" and a few other articles about this topic on stackoverflow but I still can't find the right solution.***<issue_comment>username_1: You need to add : `setContentView(R.layout.your_xml);` inside `onCreate` UPDATE: for the seceond issue you have, you actually putting the instance `map` on `LIST` not the values of the map, you need to do somthing like this instead : ``` List list = new ArrayList(map.values()); ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: you can not add in activity in setContentView Method.. ``` setContentView(R.layout.layout_issue);//your layout. ``` Upvotes: 0 <issue_comment>username_3: You missed `setContentView();` in `onCreate()` ``` setContentView(R.layout.your_xml); ``` onCreate: ``` @Override public void onCreate (Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.your_xml); //Background Thread new LoadMed().execute(); } ``` Upvotes: 1
2018/03/21
1,093
3,417
<issue_start>username_0: I am having a problem getting my head around how to group data based upon when a zero appears in a column to start a new group. Whilst there are numerous solutions I've not managed to get any of them to fit. One of the problems is currently my largest set has 178 zeros and so repeat iterations from joins or unions seems to be out of the question. Here is a small sample of the data. All we need for this is the Low\_Link. Each time the Low\_Link is zero a new incremented rank value is to be added. I have included a rank column in the data to show what it should be. Any help appreciated! ``` +----------+----------+-----------+------+ | Order_ID | Low_Link | High_Link | Rank | +----------+----------+-----------+------+ | 1 | 0 | 2 | 1 | | 2 | 1 | 3 | 1 | | 3 | 2 | 4 | 1 | | 4 | 0 | 5 | 2 | | 5 | 4 | 6 | 2 | | 6 | 5 | 7 | 2 | | 7 | 6 | 8 | 2 | | 8 | 0 | 9 | 3 | | 9 | 8 | 10 | 3 | | 10 | 9 | 11 | 3 | | 11 | 10 | 12 | 3 | | 12 | 11 | 13 | 3 | | 13 | 12 | 14 | 3 | | 14 | 0 | 15 | 4 | | 15 | 14 | 16 | 4 | | 16 | 15 | 17 | 4 | | 17 | 0 | 18 | 5 | | 18 | 0 | 19 | 6 | | 19 | 0 | 20 | 7 | | 20 | 19 | 21 | 7 | | 21 | 0 | 22 | 8 | | 22 | 0 | 99 | 9 | | 23 | 0 | 99 | 10 | | 24 | 0 | 99 | 11 | | 25 | 0 | 99 | 12 | +----------+----------+-----------+------+ ```<issue_comment>username_1: In SQL Server 2008, you can assign the rank by counting the number of 0s that occur *before* each value: ``` select t.*, (select count(*) from t t2 where t2.order_id <= t.order_id and t2.low_link = 0 ) as rank from t; ``` This will not be particularly efficient. In SQL Server 2012+ you can use the `order by` in window functions which would significantly speed up this query. ``` select t.*, sum(case when low_link = 0 then 1 else 0 end) over (order by order_id) as rnk from t; ``` Upvotes: 2 <issue_comment>username_2: One more option with `cross apply`. ``` select t.*,tt.rnk from tbl t cross apply (select sum(case when t1.low_link=0 then 1 else 0 end) as rnk from tbl t1 where t1.id<=t.id ) tt ``` Upvotes: 0 <issue_comment>username_3: Using `Window` function, easily achieve this: ``` DECLARE @Tab TABLE(id INT, low_Rank INT) INSERT INTO @Tab VALUES (1,0) INSERT INTO @Tab VALUES (2,1) INSERT INTO @Tab VALUES (3,2) INSERT INTO @Tab VALUES (4,0) INSERT INTO @Tab VALUES (5,1) INSERT INTO @Tab VALUES (6,2) INSERT INTO @Tab VALUES (7,3) INSERT INTO @Tab VALUES (8,0) INSERT INTO @Tab VALUES (9,1) SELECT * ,SUM(CASE WHEN low_Rank=0 THEN 1 ELSE 0 END) OVER(ORDER BY id) [Rank] FROM @Tab ``` **Output:** ``` id low_Rank Rank 1 0 1 2 1 1 3 2 1 4 0 2 5 1 2 6 2 2 7 3 2 8 0 3 9 1 3 ``` Upvotes: 0
2018/03/21
837
3,198
<issue_start>username_0: I have a problem with showing progress on ProgressBar. I have function that calls my server with Volley, when return result I have implemented a Callback that return data to my activity. Something like: ``` public static void saveData(Data data, final VolleyCallbackJsonObject callback){ ... callback.onSuccessResponse(new JSONObject()); ... } ``` Supposing that the function is called on cycle like: ``` for(int i = 1; i<=5; i++){ final int copyIndex = i; MyClass.saveData(new Data(i), new VolleyCallbackJsonObject() { @Override public void onSuccessResponse(JSONObject result) { callFunctionForShowAndUpdateProgress(copyIndex); } }) } } ``` I would like show a ProgressBar that show a bar with a progress from 1/5 to 5/5 so I have my Function in my activityClass: ``` public Class Test extends Activity{ private ProgressBar pb; public void callFunctionForShowAndUpdateProgress(int index){ if(index == 1){ pb = (ProgressBar) findViewById(R.id.pbLoading); pb.setMax(5); pb.setIndeterminate(false); pb.setVisibility(View.VISIBLE); } if(pb != null){ pb.setProgress(index); } if(index == 5){ pb.postDelayed(new Runnable() { @Override public void run() { pb.setVisibility(View.GONE); } }, 3000); } } } ``` My problem is that progress bar not set progress, but it show only at the end so with 5/5 and not show the progress step (1/5, 2/5, 3/5, 4/5) and then it will hide after 3 seconds how specified on postDelayed. So How can I show all the step? what is wrong?<issue_comment>username_1: Try to postDelay the method 'callFunctionForShowAndUpdateProgress' in the method 'onSuccessResponse' instead the postDelay you are already making because the delay you are making happens only when i = 5, so technically the progress goes through 2, 3, and 4 but you don't see it. try this inside 'onSuccessResponse': ``` Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { callFunctionForShowAndUpdateProgress(copyIndex); } }, 3000); ``` By the way, When the method 'callFunctionForShowAndUpdateProgress' is called in the 'onSuccessResponse' the index initially will be 1 and that is fine, the compiler then will go to second if statement ``` if(pb != null){ pb.setProgress(index); } ``` and will execute it because the condition is correct there, it will not cause a problem but leaving it like this is not a good practice, to solve this prevent the compiler from getting into this if statement by adding else. I hope that helps Upvotes: 1 <issue_comment>username_2: Change your cycle calling function as like below and then check, ``` int copyIndex = 1; callFunctionForShowAndUpdateProgress(copyIndex); for(int i = 1; i<=5; i++) { MyClass.saveData(new Data(i), new VolleyCallbackJsonObject() { @Override public void onSuccessResponse(JSONObject result) { copyIndex++; callFunctionForShowAndUpdateProgress(copyIndex); } }) } ``` Upvotes: 0
2018/03/21
432
1,728
<issue_start>username_0: Can anyone guide me on if we can scan an error alert in TOSCA which appears on the screen only for few seconds. Is there any way to do it after the element has disappeared.<issue_comment>username_1: Try to postDelay the method 'callFunctionForShowAndUpdateProgress' in the method 'onSuccessResponse' instead the postDelay you are already making because the delay you are making happens only when i = 5, so technically the progress goes through 2, 3, and 4 but you don't see it. try this inside 'onSuccessResponse': ``` Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { callFunctionForShowAndUpdateProgress(copyIndex); } }, 3000); ``` By the way, When the method 'callFunctionForShowAndUpdateProgress' is called in the 'onSuccessResponse' the index initially will be 1 and that is fine, the compiler then will go to second if statement ``` if(pb != null){ pb.setProgress(index); } ``` and will execute it because the condition is correct there, it will not cause a problem but leaving it like this is not a good practice, to solve this prevent the compiler from getting into this if statement by adding else. I hope that helps Upvotes: 1 <issue_comment>username_2: Change your cycle calling function as like below and then check, ``` int copyIndex = 1; callFunctionForShowAndUpdateProgress(copyIndex); for(int i = 1; i<=5; i++) { MyClass.saveData(new Data(i), new VolleyCallbackJsonObject() { @Override public void onSuccessResponse(JSONObject result) { copyIndex++; callFunctionForShowAndUpdateProgress(copyIndex); } }) } ``` Upvotes: 0
2018/03/21
742
2,464
<issue_start>username_0: I got HTML classes like With javascript I am trying to unhide all elements one by one to create animation. As you can see, my js code doesn't work and after few hours of trying a decided to ask because I am lost. EDIT: I forgot to append my project -> <https://codepen.io/r8w9/pen/ZxePML><issue_comment>username_1: This is what I would do: 1. add the onload function as an anonymous function, because it doesn't need a name 2. put the elements in a real array to have access to `.shift()` 3. set an interval to perform the unhiding on a timed basis 4. inside the timed function: remove and get the first element from the array using `.shift()` 5. set the elements display to `initial`(it's default, because it could be other than `block`) 6. if the array is empty remove the interval ```js window.onload = function() { var paths = document.querySelectorAll(".paths"); var hidden = []; for (var i = 0; i < paths.length; i++) hidden.push(paths[i]); var interval = setInterval(() => { hidden.shift().style.display = "initial"; if (hidden.length == 0) clearInterval(interval); }, 200); } ``` ```css .paths { display: none; } ``` ```html AAAA ``` (I used , so something is visibly happening) **EDIT** For older browsers (without arrow functions support): ```js var hidden = []; var interval; window.onload = function() { var paths = document.querySelectorAll(".paths"); for (var i = 0; i < paths.length; i++) hidden.push(paths[i]); interval = setInterval(function() { hidden.shift().style.display = "initial"; if (hidden.length == 0) clearInterval(interval); }, 200); } ``` ```css .paths { display: none; } ``` ```html AAAA ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: ```js window.onload=show(); function show(){ var a = document.querySelectorAll(".paths"); for(var i=0; i ``` ```css .paths {display:none;} Because class still exist in element that's why it's not show content. Best approach is to remove class to show ``` ```html a b c ``` Upvotes: 1 <issue_comment>username_3: Hope this will also helps you. ```js var elements = document.getElementsByClassName("paths"); console.log(elements) for (var i = 0, len = elements.length; i < len; i++) { (function(i){ window.setTimeout(function(){ elements[i].style.display="block"; }, i * 300); }(i)); } ``` ```css .paths { display:none; } ``` ```html ``` Upvotes: 1
2018/03/21
821
2,551
<issue_start>username_0: I have a atom: ``` (def data (atom[ {:orderid 0 :productid 0 :description "A" :amount 2} {:orderid 1 :productid 1 :description "A" :amount 2}])) ``` and my swap function: ``` (defn edit-order [params] (filter #(and (= (:orderid %) (:orderid params))) @data (swap! data (fn [old new] (merge old new)) params)) ``` The result I got is: ``` (println (edit-order {:orderid 0 :description "edited" :amount 3})) ;=> [{:orderid 0, :productid 0, :description A, :amount 2} {:orderid 1, :productid 1, :description A, :amount 2} {:orderid 0, :description edited, :amount 3}] ``` What I trying to do is update the new value to old value not just add it as a new one. How should I do that? ``` ;=> [{:orderid 0, :productid 0, :description edited, :amount 3} {:orderid 1, :productid 1, :description A, :amount 2}] ``` Thanks for helping!<issue_comment>username_1: The way to go about this is: ``` (def data (atom [{:orderid 0 :productid 0 :description "A" :amount 2} {:orderid 1 :productid 1 :description "A" :amount 2}])) (defn edit-order [params] (swap! data (fn [old-orders] (mapv (fn [order] (if (= (:orderid order) (:orderid params)) (merge order params) order)) old-orders)))) (comment (edit-order {:orderid 0 :description "edited" :amount 3}) #_ [{:orderid 0, :productid 0, :description "edited", :amount 3} {:orderid 1, :productid 1, :description "A", :amount 2}] ) ``` Notice that you cannot mutate just one map inside a vector. You are creating an entirely new vector based on the old one, because the entire data structure inside the atom is (should be) immutable. Upvotes: 2 [selected_answer]<issue_comment>username_2: Another option, if you're doing a lot of nested structure manipulation, is to use <https://github.com/nathanmarz/specter>, in this case the "transform" operation. ``` (ns specterplay.core (:require [com.rpl.specter :refer :all])) (def data (atom[ {:orderid 0 :productid 0 :description "A" :amount 2} {:orderid 1 :productid 1 :description "A" :amount 2}])) (defn edit-order! [params data] (swap! data (fn [a] (transform [ALL #(= (:orderid params) (:orderid %))] #(merge % params) a)))) (edit-order! {:description "edited" :amount 3} data) @data ;; [{:orderid 0, :productid 0, :description "edited", :amount 3} {:orderid 1, :productid 1, :description "A", :amount 2}] ``` Upvotes: 0
2018/03/21
465
1,833
<issue_start>username_0: I have 3 nodes in kubernetes cluster. I create a `daemonset` and deployed it in all the 3 devices. This `daemonset` created 3 pods and they were successfully running. But for some reasons, one of the pod failed. I need to know how can we restart this pod without affecting other pods in the daemon set, also without creating any other daemon set deployment? Thanks<issue_comment>username_1: `kubectl delete pod` it will delete this one pod and Deployment/StatefulSet/ReplicaSet/DaemonSet will reschedule a new one in its place Upvotes: 8 [selected_answer]<issue_comment>username_2: Just for others reading this... A better solution (IMHO) is to implement a [liveness probe](https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-probes/) that will force the pod to restart the container if it fails the probe test. This is a great feature K8s offers out of the box. This is auto healing. Also look into the pod [lifecycle docs](https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/). Upvotes: 4 <issue_comment>username_3: `kubectl -n delete pods --field-selector=status.phase=Failed` I think the above command is quite useful when you want to restart 1 or more failed pods :D And we don't need to care about name of the failed pod. Upvotes: 1 <issue_comment>username_4: There are other possibilities to acheive what you want: * Just use `rollout` command `kubectl rollout restart deployment mydeploy` * You can set some environment variable which will force your deployment pods to restart: `kubectl set env deployment mydeploy DEPLOY_DATE="$(date)"` * You can scale your deployment to zero, and then back to some positive value ``` kubectl scale deployment mydeploy --replicas=0 kubectl scale deployment mydeploy --replicas=1 ``` Upvotes: 6
2018/03/21
528
1,899
<issue_start>username_0: What is checklist for android GO? I want to update my android app for android GO operating System. how to check my App is compatible Android GO?<issue_comment>username_1: Please find the requirements to be Android go ready below 1. Runs on device with **512MB RAM** 2. APK installed size **≤ 40MB** 3. **Target SDK 26 (Oreo)** 4. App **starts ≤ 5s** (connected to WiFi) 5. **RAM ≤ 50MB PSS** What is **PSS**? The "proportional set size" (PSS) of a process is the count of pages it has in memory, where each page is divided by the number of processes sharing it. So if a process has 1000 pages all to itself, and 1000 shared with one other process, its PSS will be 1500. Checkout more details at official android developer site here [Optimize for devices running Android (Go edition)](https://developer.android.com/develop/quality-guidelines/building-for-billions-device-capacity.html#androidgo) Upvotes: 3 [selected_answer]<issue_comment>username_2: Checklist items for Android (Go edition): 1. targetSdkVersion ≥ API 26 2. The app should run smoothly on devices with ≤ 1GB RAM. 3. App size ≤ 40MB 4. App startup time ≤ 5 seconds 5. The Proportional Set Size (PSS) of the app's RAM usage ≤ 50MB, For games, the PSS of the game's RAM usage ≤ 150 You can use the Multiple APK feature on the Play Console to distribute a specific APK for Android (Go edition) devices but you should only do so without compromising the experience (e.g. you should avoid removing features). The APK targeting Android (Go edition) devices needs to declare , target at least API Level 26, and have a higher version code than the non-Go edition APK. Checkout more details at official android developer site here [Optimize for devices running Android (Go edition)](https://developer.android.com/develop/quality-guidelines/building-for-billions-device-capacity.html#androidgo) Upvotes: 1
2018/03/21
633
2,354
<issue_start>username_0: I'm developing an application which acts as an **Http-Proxy** for serving files from an external resource. It actually downloads the file from the external resource, checks for **viruses** and if the file is not infected, returns the file to the client. My problem is, **in case of the file is infected**, what HTTP Status code my service should return? I suppose that any type of 4xx error codes is not appropriate for that situation because this class of code is intended for Client errors. Is a 502 (Bad Gateway) error more appropriate? Is there any kind of Standard that covers this situation?<issue_comment>username_1: Please find the requirements to be Android go ready below 1. Runs on device with **512MB RAM** 2. APK installed size **≤ 40MB** 3. **Target SDK 26 (Oreo)** 4. App **starts ≤ 5s** (connected to WiFi) 5. **RAM ≤ 50MB PSS** What is **PSS**? The "proportional set size" (PSS) of a process is the count of pages it has in memory, where each page is divided by the number of processes sharing it. So if a process has 1000 pages all to itself, and 1000 shared with one other process, its PSS will be 1500. Checkout more details at official android developer site here [Optimize for devices running Android (Go edition)](https://developer.android.com/develop/quality-guidelines/building-for-billions-device-capacity.html#androidgo) Upvotes: 3 [selected_answer]<issue_comment>username_2: Checklist items for Android (Go edition): 1. targetSdkVersion ≥ API 26 2. The app should run smoothly on devices with ≤ 1GB RAM. 3. App size ≤ 40MB 4. App startup time ≤ 5 seconds 5. The Proportional Set Size (PSS) of the app's RAM usage ≤ 50MB, For games, the PSS of the game's RAM usage ≤ 150 You can use the Multiple APK feature on the Play Console to distribute a specific APK for Android (Go edition) devices but you should only do so without compromising the experience (e.g. you should avoid removing features). The APK targeting Android (Go edition) devices needs to declare , target at least API Level 26, and have a higher version code than the non-Go edition APK. Checkout more details at official android developer site here [Optimize for devices running Android (Go edition)](https://developer.android.com/develop/quality-guidelines/building-for-billions-device-capacity.html#androidgo) Upvotes: 1
2018/03/21
874
2,805
<issue_start>username_0: I needed it for a socket buffer that I'm making (reading and writing...), this is more a trick than anything else so I would like to know if there is a better way of doing it with the current c++ features/standards? I'm sure of it. ``` enum e_Types { Type_64 , Type_32 , Type_16 , Type_8 , Type_ALL }; template constexpr auto \_GetVarType() { if constexpr( Type == Type\_8 ) return ( unsigned char\* ) 0; if constexpr( Type == Type\_16 ) return ( unsigned short\* ) 0; if constexpr( Type == Type\_32 ) return ( unsigned long\* ) 0; if constexpr( Type == Type\_64 ) return ( unsigned long long\* ) 0; } #define GetVarType(type) decltype( \_GetVarType() ) ``` Example: ``` GetVarType( Type_64 ) p64 = malloc(0x1000); ``` Thanks for replies.<issue_comment>username_1: You can use good old explicit template class specialization: ``` template struct type\_of; template <> struct type\_of { using type = unsigned long long; }; template <> struct type\_of { using type = unsigned long; }; template <> struct type\_of { using type = unsigned short; }; template <> struct type\_of { using type = unsigned char; }; template using type\_of\_t = typename type\_of::type; ``` Usage: ``` type_of_t\* p64 = malloc(0x1000); ``` --- If you want to go down the `constexpr`-based route, you can do something like: ``` template struct type\_wrapper { using type = T; }; template inline constexpr type\_wrapper t{}; template inline constexpr auto type\_of = t; template <> inline constexpr auto type\_of = t; template <> inline constexpr auto type\_of = t; template <> inline constexpr auto type\_of = t; template <> inline constexpr auto type\_of = t; ``` Usage: ``` typename decltype(type_of)::type\* p64 = malloc(0x1000); ``` But I don't find this superior to the more traditional approach. Upvotes: 3 [selected_answer]<issue_comment>username_2: Based on @liliscent and @VittorioRomeo replies/comments, I ended up to do this: ``` template struct Type\_Wrapper { using Type = T; }; template inline constexpr Type\_Wrapper \_Type{}; template inline constexpr auto \_GetVarType() { if constexpr( Type == Type\_8 ) return \_Type; else if constexpr( Type == Type\_16 ) return \_Type; else if constexpr( Type == Type\_32 ) return \_Type; else if constexpr( Type == Type\_64 ) return \_Type; else if constexpr( Type == Type\_Pointer ) return \_Type; else if constexpr( Type == Type\_Size ) return \_Type; else if constexpr( Type == Type\_Array ) return \_Type; else return \_Type; }; template using GetVarType\_t = typename decltype( \_GetVarType<\_Type>() ); ``` ... ``` GetVarType_t< Type_64 >::Type Ok = 0; ``` It's good now, I wanted to get rid off those 0 cuz it didn't look good. Thanks again! Upvotes: 0
2018/03/21
712
2,401
<issue_start>username_0: This is my first question on here and I'm not very experienced with vba. I have an Excel worksheet called Log with formulas in cells AK2:AQ500 that are capturing information. When the document is saved, I would like to convert any non-blank cells in that range to values, whilst leaving the formulas in the cells that appear blank. Can anybody give me some help? Thanks.<issue_comment>username_1: You can use good old explicit template class specialization: ``` template struct type\_of; template <> struct type\_of { using type = unsigned long long; }; template <> struct type\_of { using type = unsigned long; }; template <> struct type\_of { using type = unsigned short; }; template <> struct type\_of { using type = unsigned char; }; template using type\_of\_t = typename type\_of::type; ``` Usage: ``` type_of_t\* p64 = malloc(0x1000); ``` --- If you want to go down the `constexpr`-based route, you can do something like: ``` template struct type\_wrapper { using type = T; }; template inline constexpr type\_wrapper t{}; template inline constexpr auto type\_of = t; template <> inline constexpr auto type\_of = t; template <> inline constexpr auto type\_of = t; template <> inline constexpr auto type\_of = t; template <> inline constexpr auto type\_of = t; ``` Usage: ``` typename decltype(type_of)::type\* p64 = malloc(0x1000); ``` But I don't find this superior to the more traditional approach. Upvotes: 3 [selected_answer]<issue_comment>username_2: Based on @liliscent and @VittorioRomeo replies/comments, I ended up to do this: ``` template struct Type\_Wrapper { using Type = T; }; template inline constexpr Type\_Wrapper \_Type{}; template inline constexpr auto \_GetVarType() { if constexpr( Type == Type\_8 ) return \_Type; else if constexpr( Type == Type\_16 ) return \_Type; else if constexpr( Type == Type\_32 ) return \_Type; else if constexpr( Type == Type\_64 ) return \_Type; else if constexpr( Type == Type\_Pointer ) return \_Type; else if constexpr( Type == Type\_Size ) return \_Type; else if constexpr( Type == Type\_Array ) return \_Type; else return \_Type; }; template using GetVarType\_t = typename decltype( \_GetVarType<\_Type>() ); ``` ... ``` GetVarType_t< Type_64 >::Type Ok = 0; ``` It's good now, I wanted to get rid off those 0 cuz it didn't look good. Thanks again! Upvotes: 0
2018/03/21
559
1,550
<issue_start>username_0: I have the following structure/code: ```css .navbar__brand, .navcontainer { float:left; } .navbar__brand img { vertical-align:middle;} .navbar__menu { display:inline-block; } .navbar__menu li { display:inline-block; list-style: none; } ``` ```html [![](../img/logo.png)](#) * [Item 1](#) * [Item 2](#) ``` I want the image in navbar\_\_brand to be vertical align in the middle; At this moment is align at the top of the div. I need to support old IE browser so please no flex.<issue_comment>username_1: (Edit) Thanks @TemaniAfif for pointing out that you need to support old IE browsers. This answer won't work in old browsers. As usual, what is a pain to achieve with classic CSS (floats, inline-block, clearfix, etc.) is a breeze with [Flex](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) : ```css .navbar { display: flex; align-items: center; border: blue dashed 2px; } ul.navbar__menu { display: flex; } .navbar__menu li { list-style: none; padding: 10px; } ``` ```html [![](../img/logo.png)](#) * [Item 1](#) * [Item 2](#) ``` Upvotes: 0 <issue_comment>username_2: The easiest way to achive this is simulating a table ```css .asTable{ display:table; } .asTR{ display:table-row; } .asTD{ display:table-cell; vertical-align:middle; border:1px solid; } .asTD ul{ list-style:none; } .asTD ul li { display:inline-block; } ``` ```html [![](../img/logo.png)](#) * [Item 1](#) * [Item 2](#) ``` Upvotes: 2 [selected_answer]
2018/03/21
565
1,731
<issue_start>username_0: How I can make a `select` tag display the value from mysql table but still have the other options below. ``` Yes No ``` I want to see the selected value from the mysql table first instead of the first option.<issue_comment>username_1: I think you're looking for this: ``` php echo $row['pslAtOffice']; ? Yes No ``` Thanks @username_2 for reminding me of "selected" **EDIT**: You mentioned that the whole block is inside an echo, so I guess it should look like this: ``` echo ' ' . $row['pslAtOffice'] . ' Yes No '; ``` Upvotes: 1 <issue_comment>username_2: You need to add the selected tag to the option, not a value to the select. In your case, this might work well: ``` php if($row['pslAtOffice'] != 'Yes' && $row['pslAtOffice'] != 'No') { ? php echo $row['pslAtOffice'] ? php } ? >Yes >No ``` You could also do a shorthand if you prefer: ``` php echo ($row['pslAtOffice'] == 'Yes') ? 'selected' : '' ? ``` EDIT: You have to use shorthand statements if your whole code was wrapped in an echo. Check out this solution: ``` php $row['pslAtOffice'] = 'Something'; echo '<select id="slct" name="psl" class="select"' . (($row['pslAtOffice'] != 'Yes' && $row['pslAtOffice'] != 'No') ? '' . $row['pslAtOffice'] . '' : '') . 'YesNo'; $row['pslAtOffice'] = 'No'; echo '' . (($row['pslAtOffice'] != 'Yes' && $row['pslAtOffice'] != 'No') ? '' . $row['pslAtOffice'] . '' : '') . 'YesNo'; ``` Upvotes: 1 [selected_answer]<issue_comment>username_3: You need to add database variable (i.e `$row['pslAtOffice'`]) into the first option, not into the select attribute iteself. Please check below code for more detail. ``` php echo $row['pslAtOffice']; ? Yes No ``` Upvotes: 0
2018/03/21
569
1,762
<issue_start>username_0: I am trying to store an image in a json object and display it on a html page with the rest of the data in the object. The image is stored locally in a folder called images. I have some code, but it doesnt seem to work... Can anyone please advise?<issue_comment>username_1: I think you're looking for this: ``` php echo $row['pslAtOffice']; ? Yes No ``` Thanks @username_2 for reminding me of "selected" **EDIT**: You mentioned that the whole block is inside an echo, so I guess it should look like this: ``` echo ' ' . $row['pslAtOffice'] . ' Yes No '; ``` Upvotes: 1 <issue_comment>username_2: You need to add the selected tag to the option, not a value to the select. In your case, this might work well: ``` php if($row['pslAtOffice'] != 'Yes' && $row['pslAtOffice'] != 'No') { ? php echo $row['pslAtOffice'] ? php } ? >Yes >No ``` You could also do a shorthand if you prefer: ``` php echo ($row['pslAtOffice'] == 'Yes') ? 'selected' : '' ? ``` EDIT: You have to use shorthand statements if your whole code was wrapped in an echo. Check out this solution: ``` php $row['pslAtOffice'] = 'Something'; echo '<select id="slct" name="psl" class="select"' . (($row['pslAtOffice'] != 'Yes' && $row['pslAtOffice'] != 'No') ? '' . $row['pslAtOffice'] . '' : '') . 'YesNo'; $row['pslAtOffice'] = 'No'; echo '' . (($row['pslAtOffice'] != 'Yes' && $row['pslAtOffice'] != 'No') ? '' . $row['pslAtOffice'] . '' : '') . 'YesNo'; ``` Upvotes: 1 [selected_answer]<issue_comment>username_3: You need to add database variable (i.e `$row['pslAtOffice'`]) into the first option, not into the select attribute iteself. Please check below code for more detail. ``` php echo $row['pslAtOffice']; ? Yes No ``` Upvotes: 0
2018/03/21
584
1,864
<issue_start>username_0: I have an XML file that was written from a powershell "Export-Clixml" call and it appears quite strange to me. Here's a very simple sample: ``` PS C:\> Get-Date | Export-Clixml sample.xml PS C:\> cat .\sample.xml 2018-03-21T08:05:39.5085956-04:00 Microsoft.PowerShell.Commands.DisplayHintType System.Enum System.ValueType System.Object DateTime 2 ``` How are you supposed to parse these "Objs" and "MS" and "TN" and the rest of it? I need something that can reliably read this in python. Does anyone have a way to do this? ConvertTo-Xml has an output like this ``` xml version="1.0"? someKey value otherKey otherValue ``` So there's no way to tell which "key" goes with which "value" other than the position.<issue_comment>username_1: PowerShell's Extended Type System supports auxiliary properties and type information, and the XML serialization scheme thus needs some way of representing this metadata. In your case, everything under `MS` contains properties native to the **M**onad**S**hell (the original moniker for PowerShell). `TN` is likely short for **T**ype**N**ames. The full [schema you're looking for is available here](https://msdn.microsoft.com/en-us/library/mt766752.aspx) if you want to write a parser/deserializer in python Upvotes: 3 [selected_answer]<issue_comment>username_2: Can you regenerate the file? If so use `ConvertTo-Xml` rather than `Export-CliXml` ``` $Xml = Get-Date | ConvertTo-Xml $Xml.Save("C:\Temp\File.xml") ``` File content: ``` xml version="1.0" encoding="utf-8"? 21/03/2018 15:25:33 ``` Convert hash table to object before export/save ``` $HashTable = @{ Prop1 = "Value1" Prop2 = "Value2" Prop3 = "Value2" } $Object = New-Object -TypeName PsCustomObject -Property $HashTable $Xml = $Object | ConvertTo-Xml $Xml.Save("C:\Temp\File.xml") ``` Upvotes: 0
2018/03/21
1,743
6,100
<issue_start>username_0: The example is as follows: I have a `Box` that needs to be filled with some `Thing`s. I'm interested only in weight of each thing. Also, beside weight, I need to correctly identify the thing that I'm measuring. Each thing type has different Id type. In this case I have toys and fruits, which have `ToyId` and `FruitId` respectively. In the end, I need to be able to print thing identifier and thing weight. Question: Is it somehow possible to access specific methods on `ThingId`s without using instanceof operator (as in example)? ``` class Color{} interface ThingId {} class FruitId implements ThingId { String name; //"apple", "orange", ... FruitId(String name){ this.name = name; } String getName(){ return this.name; } } class ToyId implements ThingId { String shape; //"square", "circle", ... Color color; //"red", "blue"... ToyId(String shape, Color color){ this.shape = shape; this.color = color; } String getShape(){ return this.shape; } Color getColor(){ return this.color; } } class Thing{ ThingId thingId; Integer weight; public Thing(ThingId thingId, Integer weight){ this.thingId = thingId; this.weight = weight; } ThingId getThingId(){ return this.thingId; } Integer getWeight(){ return this.weight; } } class Box { Set things = new HashSet<>(); void addThing(Thing thing){ this.things.add(thing); } Collection getThings(){ return this.things; } } class Program { public static void main(String[] args) { FruitId appleId = new FruitId("apple"); Thing apple = new Thing(appleId, 1); ToyId cubeId = new ToyId("square", new Color()); Thing cube = new Thing(cubeId, 22); Box box = new Box(); box.addThing(apple); box.addThing(cube); for(Thing t : box.getThings()){ System.out.print("Thing Id is: "); if(t.getThingId() instanceof FruitId) { //any other possibility than using instance of? process((FruitId)t.getThingId()); } if(t.getThingId() instanceof ToyId){ //any other possibility than using instance of? process((ToyId)t.getThingId()); } System.out.println("Weight is : " + t.getWeight()); } } static void process(FruitId fruitId){ System.out.println(fruitId.getName()); } static void process(ToyId toyId){ System.out.println(toyId.getShape() + toyId.getColor()); } } ``` **UPDATE** OK, I think Visitor pattern could be useful here: ``` class Color{} interface ThingId { void visitThingId(ThingIdVisitor visitor); } class FruitId implements ThingId { String name; //"apple", "orange", ... FruitId(String name){ this.name = name; } String getName(){ return this.name; } @Override public void visitThingId(ThingIdVisitor visitor) { visitor.process(this); } } class ToyId implements ThingId { String shape; //"square", "circle", ... Color color; //"red", "blue"... ToyId(String shape, Color color){ this.shape = shape; this.color = color; } String getShape(){ return this.shape; } Color getColor(){ return this.color; } @Override public void visitThingId(ThingIdVisitor visitor) { visitor.process(this); } } class Thing{ ThingId thingId; Integer weight; public Thing(ThingId thingId, Integer weight){ this.thingId = thingId; this.weight = weight; } ThingId getThingId(){ return this.thingId; } Integer getWeight(){ return this.weight; } } class Box { Set things = new HashSet<>(); void addThing(Thing thing){ this.things.add(thing); } Collection getThings(){ return this.things; } } class ThingIdVisitor{ void process(FruitId fruitId){ System.out.println(fruitId.getName()); } void process(ToyId toyId){ System.out.println(toyId.getShape() + toyId.getColor()); } } class Program { public static void main(String[] args) { FruitId appleId = new FruitId("apple"); Thing apple = new Thing(appleId, 1); ToyId cubeId = new ToyId("square", new Color()); Thing cube = new Thing(cubeId, 22); Box box = new Box(); box.addThing(apple); box.addThing(cube); for(Thing t : box.getThings()){ System.out.print("Thing Id is: "); t.getThingId().visitThingId(new ThingIdVisitor()); System.out.println("Weight is : " + t.getWeight()); } } } ```<issue_comment>username_1: your interface `ThingId` must provide the respective methods that you want to have. If you simple want to print out information, then you can use like a simple ``` public String getInformation(); ``` Then the implementations can return the information that is relevant for them and you can simply work with `ThingId` in your application code. BTW: As you are storing your `Thing`s in a `HashSet` make sure to implement `equals` and `hashCode` in all `Thing` implementations Also I dont really see, why you need a `Thing` and a `ThingId`, as `ThingId` seems a bit more than a simple id and actually a thing. So for me it seems that `ThingId` is redundant and all can be achieved by the having different `Thing`s Upvotes: 1 <issue_comment>username_2: I don't really get what you're trying to achieve. First of all, I don't get the use of the interface `ThingId`. Second, I think you're a bit confused about interfaces and inheritance. If I were you, I'd look up [polymorphism](https://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html). Anyway, I propose you remove the `ThingId` interface and let the `FruitId` and `ToyId` classes extend the `Thing` class. As your collection only exists of `Thing`s, and as your `Fruit` and `Toy` classes all extend this `Thing` class and thus implement the `getWeight()` method, you should not use `instanceof` anymore. But please, read up on [polymorphism](https://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html). Upvotes: 2 <issue_comment>username_3: Since you are calling the same method `process` on both the instance types, why not add that method to `ThingId` interface itself. By doing so, you could just call: ``` t.getThingId().process(); ``` Instead of finding the instance type and calling respective methods. Upvotes: 1
2018/03/21
1,488
5,705
<issue_start>username_0: I have a Vue.js project, when I check the console I found this issue below: > > Refused to apply style from 'http://localhost:8080/dist/cropper.min.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. > > > --- `[![enter image description here](https://i.stack.imgur.com/AI0Az.jpg)](https://i.stack.imgur.com/AI0Az.jpg)` I searchedSO, found a [Angular related post](https://stackoverflow.com/questions/48733509/bootstrap-is-not-working-in-angularjs-4-project), but it does not help me, the two are based on different frontend frameworks.<issue_comment>username_1: You provided insufficient information. But i had the same problem, so i have a solution. Say you @import css files in a component's style block. So my problem was in path that i specified. And the error message `Refused to apply style` appeared because of wrong path. I thought that my src path alias `~` is resolved in a style block, but it wasn't. All i had to do is to specify `/src/assets/css...` instead of `~/assets/css...` Upvotes: 3 <issue_comment>username_2: The usual reason for this error message is that when the browser tries to load that resource, the server returns an HTML page instead, for example if your router catches unknown paths and displays a default page without a 404 error. Of course that means the path does not return the expected CSS file / image / icon / whatever. To make sure you are in that case, copy the path and try to access it directly in a new browser window or tab. You will see what your server sends. The solution is to find the correct path and router configuration so that you get your plain CSS file / image / etc. when accessing that path. The exact path and router configuration depends on how you have setup your project and the framework you are using. Upvotes: 7 [selected_answer]<issue_comment>username_3: yo have to change the place of your file css into the directory assets assets/style.css and then put these path in your file index.html src/index.html in addition you have to modify to file angular.json in styles ```js "styles": [ "src/assets/style.css", "./node_modules/materialize-css/dist/css/materialize.min.css", ], ``` Upvotes: 2 <issue_comment>username_4: I got exact same problem " Refused to apply style from '<http://localhost:8080/css/formatting.css>' because its MIME type ('application/json') is not a supported stylesheet MIME type ..." I browse through the window explorer and corrected the file paths (folders) as i intended to. There was also spelling error in the addressing like the path was as above (formatting.css or double 't') but the file actually was formating.css (single 't') and the problem solved. Some solutions are not expensive at all. Thanks. Upvotes: 2 <issue_comment>username_5: It might also occur when you set incorrect BUILD directory in package.json. for example ``` // Somewhere in index.js // Client Build directory for the Server app.use(express.static(path.resolve(__dirname, '../this-client/**build**'))); ``` then package.json: ``` "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test --env=jsdom", "eject": "react-scripts eject", "install:clean": "rm -rf node_modules/ && rm -rf package-lock.json && npm install && npm start", "build-package-css": "cp src/assets/css/my-this-react.css **build**/my-this-react.css", "build-package": "npm run build-package-css && babel src --out-dir **build**" }, ``` The directories I marked as Bold should be the same. If there is a difference then it won't run. Upvotes: 1 <issue_comment>username_6: I was dealing with the same problem with my React project, and the solution I found was to add a "publicPath" to the output in webpack.config.js. ``` output: { path: path.resolve(__dirname, "dist"), filename: "bundle.js", publicPath: "/", }, ``` Upvotes: 1 <issue_comment>username_7: I encountered the same error when running my app in production. With `npm run serve` everything worked but the result of `npm run build` resulted in that same error. It turns out that I was using vue router in history mode and my nginx server wasn't properly configured. I changed vue router to hash mode and stopped getting that error message. Try using hash mode and see if the message goes away. If it does then you need to tweak your web server settings. Upvotes: 1 <issue_comment>username_8: I ran into this issue.. I was integrating some scss files into my project and just presumed that I should use the `rel="stylesheet"` once I removed the attribute no more style sheet issues... Working .scss file ``` ``` Upvotes: 0 <issue_comment>username_9: in my case , I just changed the link tag from to and it worked . just add ~ Upvotes: 0 <issue_comment>username_10: For my case (not for vue.js) adding the "base" tag solved the error: ``` ... ... ``` Upvotes: 0 <issue_comment>username_11: I know this is a bit too late but for anyone coming from Laravel inertia-react space, I faced the same issue. The whole application was blank with the same error of **"Refused to apply style..."**. For me, it was my first time building and deploying a Laravel inertia-react project to shared hosting. What you need to do is move the **build** folder in the public directory to your server root. Then, move the **manifest.json** file in the build folder back to the **public/build** folder. The application throws an error if the manifest.json file is not found in that directory. Clear your browser and application caches and you're good to go. Upvotes: 0
2018/03/21
831
3,058
<issue_start>username_0: I'm trying to create tables in my database (postgresql 9.6) and when I launch my python script to do so, it returns me an error of the following type: "Section postgresql not found in the $FILEDIR/database.ini file" It seems like the parser cannot read the section, but I don't understand why. This is my config method: ``` def config(filename='$FILEDIR/database.ini', section='postgresql'): parser = ConfigParser() parser.read(filename) db = {} if parser.has_section(section): params = parser.items(section) for param in params: db[param[0]] = param[1] else: raise Exception('Section {0} not found in the {1} file'.format(section, filename)) return db ``` Database.ini: ``` [postgresql] host=localhost database=mydatabase user=myuser password=<PASSWORD> ``` I've tried the answers in [this following thread](https://stackoverflow.com/questions/44030707/referencing-ini-file-fails-in-cron) but it does not help me at all. Anyone knows the cause? I'm using python 2.7 and I've executed "pip install config" and "pip install configparser" for dependencies.<issue_comment>username_1: I had the same issue aswell, it was cured by placing the whole file path into the kwarg in config: `def config(filename='/Users/gramb0t/Desktop/python-postgre/data/database.ini', section='postgresql'):` Upvotes: 3 <issue_comment>username_2: ``` #just remove the $FILEDIR. it worked for me. from configparser import ConfigParser def config(filename="database.ini", section="postgresql"): # create a parser parser = ConfigParser() # read config file parser.read(filename) # get section, default to postgresql db = {} if parser.has_section(section): params = parser.items(section) for param in params: db[param[0]] = param[1] else: raise Exception( "Section {0} not found in the {1} file".format(section, filename) ) return db ``` Upvotes: 2 <issue_comment>username_3: the problem in path for solve this you can use os to get dir to database.ini as following example ``` import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) params = config(filename=BASE_DIR+'\memory\database.ini', section='postgresql_pc__server') ``` Upvotes: 2 <issue_comment>username_4: The thing is, you made a mistake. You don’t need to add or invent anything, just do this: ``` def config(filename=r'/database.ini', section='postgresql'): parser = ConfigParser() parser.read(filename) # получить раздел, по умолчанию postgresql db = {} if parser.has_section(section): print(section) params = parser.items(section) for param in params: db[param[0]] = param[1] else: raise Exception("Раздел {0} не найдено в {1} файл".format(section, filename)) return db ``` but if you are in the main directory then (r, '/') you most likely need to remove and leave everything as in the documentation Upvotes: -1
2018/03/21
815
2,685
<issue_start>username_0: JAVA I want to parse every element of JSON file (using gson will be the best) to Array. I searched for two days and I still can't figure out how to do it correctly. My JSON file looks like this: ``` { "spawn1": { "x": 336.4962312645427, "y": 81.0, "z": -259.029426052796 }, "spawn2": { "x": 341.11558917719424, "y": 80.0, "z": -246.07415114625 } } ``` There will be more and more elements with different names. What I need is to take all the elements like x, y, z and create an object using it and place it to the array. Class for this object looks like this: ``` public class Chest { private double x, y, z; public Chest(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } } ```<issue_comment>username_1: I had the same issue aswell, it was cured by placing the whole file path into the kwarg in config: `def config(filename='/Users/gramb0t/Desktop/python-postgre/data/database.ini', section='postgresql'):` Upvotes: 3 <issue_comment>username_2: ``` #just remove the $FILEDIR. it worked for me. from configparser import ConfigParser def config(filename="database.ini", section="postgresql"): # create a parser parser = ConfigParser() # read config file parser.read(filename) # get section, default to postgresql db = {} if parser.has_section(section): params = parser.items(section) for param in params: db[param[0]] = param[1] else: raise Exception( "Section {0} not found in the {1} file".format(section, filename) ) return db ``` Upvotes: 2 <issue_comment>username_3: the problem in path for solve this you can use os to get dir to database.ini as following example ``` import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) params = config(filename=BASE_DIR+'\memory\database.ini', section='postgresql_pc__server') ``` Upvotes: 2 <issue_comment>username_4: The thing is, you made a mistake. You don’t need to add or invent anything, just do this: ``` def config(filename=r'/database.ini', section='postgresql'): parser = ConfigParser() parser.read(filename) # получить раздел, по умолчанию postgresql db = {} if parser.has_section(section): print(section) params = parser.items(section) for param in params: db[param[0]] = param[1] else: raise Exception("Раздел {0} не найдено в {1} файл".format(section, filename)) return db ``` but if you are in the main directory then (r, '/') you most likely need to remove and leave everything as in the documentation Upvotes: -1
2018/03/21
555
1,743
<issue_start>username_0: Say I have two sizable arrays, `a` and `b`. I want to have `b=a+b`, but I don't really need `a` afterwards, and would much rather have the memory saved, in order to avoid swapping. I have thought about simply using: ``` b.unshift( *a.slice!(0..-1) ) ``` But the above has the downside of still keeping a copy of `a` until the procedure is finished. The other option would be: ``` while ! a.empty?() do b.unshift( a.pop() ) end ``` While not elegant, and maybe even slower (this is iterations, I don't know how fast the `*` operator works, maybe it is on lower level), this keeps the intermediate memory footprint to a minimum. Is there something more elegant?<issue_comment>username_1: > > Is there something more elegant? > > > Using both `unshift` and `pop`: ``` a = [1,2,3] b = [4,5,6] b.unshift(*a.pop(a.size)) p a, b # [] # [1, 2, 3, 4, 5, 6] ``` Or if you don't want to use `*`: ``` a = [1,2,3] b = [4,5,6] b.unshift(a.pop(a.size)).flatten! p a, b # [] # [1, 2, 3, 4, 5, 6] ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: There's no guarantee the memory allocated to `a` will be released just because you've removed all of the elements. Most dynamic array systems allocate as the array is increased in size, that's a hard necessity, but are more relaxed when it comes to decreasing size. The best approach is to do `b += a`, let `a` fall out of scope, and then let the garbage collector sort it out. Unless you can produce a concrete benchmark that shows that your convoluted approach works better, which it probably doesn't as a splat operation is going to create additional garbage that needs to be collected, you should do the simplest thing that works. Upvotes: 2
2018/03/21
614
2,285
<issue_start>username_0: I want to make the following work, but I don't know how to mock forEach behavior properly. (The code is taken from a related question [Testing Java enhanced for behavior with Mockito](https://stackoverflow.com/questions/6379308/testing-java-enhanced-for-behavior-with-mockito) ) ``` @Test public void aa() { Collection fruits; Iterator fruitIterator; fruitIterator = mock(Iterator.class); when(fruitIterator.hasNext()).thenReturn(true, true, true, false); when(fruitIterator.next()).thenReturn("Apple") .thenReturn("Banana").thenReturn("Pear"); fruits = mock(Collection.class); when(fruits.iterator()).thenReturn(fruitIterator); doCallRealMethod().when(fruits).forEach(any(Consumer.class)); // this doesn't work (it doesn't print anything) fruits.forEach(f -> { mockObject.someMethod(f); }); // this works fine /\* int iterations = 0; for (String fruit : fruits) { mockObject.someMethod(f); } \*/ // I want to verify something like this verify(mockObject, times(3)).someMethod(anyString()); } ``` Any help will be very appreciated.<issue_comment>username_1: The method `forEach` of the `Collection` interface is a "defender" method; it does not use `Iterator` but call the `Consumer` passed to the method. If you are using Mockito version 2+ (\*), you can ask the default method `forEach` of the `Collection` interface to be called: ``` Mockito.doCallRealMethod().when(fruits).forEach(Mockito.any(Consumer.class)); ``` Note that the "defender" method is actually going to request an `Iterator` to traverse the collection, hence will use the `Iterator` you mocked in your test. It wouldn't work if no `Iterator` was provided by the mocked collection, as with `when(fruits.iterator()).thenReturn(fruitIterator)` (\*): Mockito has added the possibility to support Java 8 default ("defender") method since version 2 - you can check the tracking issue [here](https://github.com/mockito/mockito/issues/186). Upvotes: 3 <issue_comment>username_2: ``` Iterator mockIterator = mock(Iterator.class); doCallRealMethod().when(fruits).forEach(any(Consumer.class)); when(fruits.iterator()).thenReturn(mockIterator); when(mockIterator.hasNext()).thenReturn(true, false); when(mockIterator.next()).thenReturn(mockObject); ``` Upvotes: 4
2018/03/21
604
2,011
<issue_start>username_0: How to achieve method overloading UDFs in Spark2 using Spark Session. ```scala scala> spark.udf.register("func",(a:String)=>a.length) scala> spark.udf.register("func",(a:Int)=>a*1000) ``` Following is my Hive table named 'orc' and its description ```scala scala> spark.sql("desc orc").collect.foreach(println) [id,int,null] [name,string,null] [time_stamp,timestamp,null] ``` There are two records in my table ```scala scala> spark.sql("select * from orc").collect.foreach(println) [1,<NAME>,null] [2,<NAME>,2016-01-01 00:00:00.0] ``` When I query using spark session, the second function takes effect, preventing method overloading ```scala scala> spark.sql("select func(id),func(name) from orc").collect.foreach(println) [1000,null] [2000,null] ```<issue_comment>username_1: The method `forEach` of the `Collection` interface is a "defender" method; it does not use `Iterator` but call the `Consumer` passed to the method. If you are using Mockito version 2+ (\*), you can ask the default method `forEach` of the `Collection` interface to be called: ``` Mockito.doCallRealMethod().when(fruits).forEach(Mockito.any(Consumer.class)); ``` Note that the "defender" method is actually going to request an `Iterator` to traverse the collection, hence will use the `Iterator` you mocked in your test. It wouldn't work if no `Iterator` was provided by the mocked collection, as with `when(fruits.iterator()).thenReturn(fruitIterator)` (\*): Mockito has added the possibility to support Java 8 default ("defender") method since version 2 - you can check the tracking issue [here](https://github.com/mockito/mockito/issues/186). Upvotes: 3 <issue_comment>username_2: ``` Iterator mockIterator = mock(Iterator.class); doCallRealMethod().when(fruits).forEach(any(Consumer.class)); when(fruits.iterator()).thenReturn(mockIterator); when(mockIterator.hasNext()).thenReturn(true, false); when(mockIterator.next()).thenReturn(mockObject); ``` Upvotes: 4
2018/03/21
778
2,199
<issue_start>username_0: On java 8 giving JVM a command line options ``` -XX:+PrintGCDateStamps and -XX:+PrintGCDetails ``` results in the JVM printing exactly on line per each GC operation, like this: ``` 2018-03-21T01:35:39.624-0700: [GC (Allocation Failure) [PSYoungGen: 328192K->23443K(382464K)] 328192K->23459K(1256448K), 0.0268406 secs] [Times: user=0.04 sys=0.01, real=0.03 secs] ``` or ``` 2018-03-21T01:35:58.404-0700: [Full GC (Metadata GC Threshold) [PSYoungGen: 1952K->0K(348672K)] [ParOldGen: 457235K->256822K(873984K)] 459187K->256822K(1222656K), [Metaspace: 122374K->122350K(1163264K)], 0.9086909 secs] [Times: user=3.25 sys=0.01, real=0.91 secs] ``` How can I make Java 9 do something similar? One row per GC operation and preferably listing both elapsed time and the amount of memory free after the operation. The closest I've been able to get is to enable GC logging at level 'info', like this: -Xlog:gc=info. However, it still prints half a dozen rows for every round of GC.<issue_comment>username_1: The method `forEach` of the `Collection` interface is a "defender" method; it does not use `Iterator` but call the `Consumer` passed to the method. If you are using Mockito version 2+ (\*), you can ask the default method `forEach` of the `Collection` interface to be called: ``` Mockito.doCallRealMethod().when(fruits).forEach(Mockito.any(Consumer.class)); ``` Note that the "defender" method is actually going to request an `Iterator` to traverse the collection, hence will use the `Iterator` you mocked in your test. It wouldn't work if no `Iterator` was provided by the mocked collection, as with `when(fruits.iterator()).thenReturn(fruitIterator)` (\*): Mockito has added the possibility to support Java 8 default ("defender") method since version 2 - you can check the tracking issue [here](https://github.com/mockito/mockito/issues/186). Upvotes: 3 <issue_comment>username_2: ``` Iterator mockIterator = mock(Iterator.class); doCallRealMethod().when(fruits).forEach(any(Consumer.class)); when(fruits.iterator()).thenReturn(mockIterator); when(mockIterator.hasNext()).thenReturn(true, false); when(mockIterator.next()).thenReturn(mockObject); ``` Upvotes: 4
2018/03/21
682
2,303
<issue_start>username_0: When I do: ``` console.log(JSON) ``` it will display in JSON syntax in the console: ``` [ { test1: 'data', test2: 'data', test3: 'data' } ] ``` When I do: ``` console.log(`JSON Data\n\n${JSON}`) ``` it will display `[object Object]` so I do: ``` console.log(`JSON Data\n\n${JSON.stringify(JSON)}`) ``` which displays it in String syntax: ``` [{"test1":"data","test2":"data","test3":"data"}] ``` I want to do a console.log of the JSON data followed by some text in a template literal whilst keeping the JSON syntax, like so: ``` [ { test1: 'data', test2: 'data', test3: 'data' } ] JSON Data Displayed Above ```<issue_comment>username_1: When you use a template literal, the result is a string. If you want to add texts labels before/after the logged data, or other values, separate them by comma: ```js var data = { a: 1, b: [1, 2] }; console.log('Before:', data, '\n\nJSON Data Displayed Above'); console.log(data, '\n\nAfter'); console.log('Before\n', data, '\n\nAfter'); ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Alternatively you could change the way objects are converted to a string: ``` Object.prototype.toString = function(){ return JSON.stringify(this); }; ``` Now this will work as expected: ``` console.log(`JSON Data\n\n${JSON}`) ``` Upvotes: 0 <issue_comment>username_3: `console` implementation is browser-specific. In modern browsers, objects can be outputted in human-readable form. Modern implementations support multiple `console` arguments (as another answer suggests): ``` console.log(`JSON Data`, json); ``` This may not work as expected in legacy browsers; multiple `console.log` arguments were originally intended for [string substitutions](https://developer.mozilla.org/en-US/docs/Web/API/console#Outputting_text_to_the_console), and there may be problems if first argument accidentally contains substitution syntax, e.g. `%s`. A compatible, cross-platform way to achieve string-only, human-readable output is to configure object stringification: ``` console.log(`JSON Data\n\n${JSON.stringify(json, null, 2)}`) ``` The benefit of this approach is that the output stays the same everywhere, whether it's legacy browser or `console.log` call that was intercepted by a logger. Upvotes: 0
2018/03/21
1,637
5,358
<issue_start>username_0: I'm using angular 4 and ionic 3. Now when i run "ionic cordova run android" It gives me the following error: ``` "more than one library with package name 'com.google.android.gms.license'" ``` My project.property file: ``` target=android-26 android.library.reference.1=CordovaLib cordova.system.library.1=com.android.support:support-v4:27.1.0 cordova.system.library.2=com.android.support:support-v4:27.1.0 cordova.system.library.3=com.android.support:support-v4:27.1.0 cordova.system.library.4=com.android.support:appcompat-v7:25.+ cordova.gradle.include.1=cordova-plugin-firebase/starter-build.gradle cordova.system.library.5=com.google.gms:google-services:+ cordova.system.library.6=com.google.android.gms:play-services-tagmanager:+ cordova.system.library.7=com.google.firebase:firebase-core:+ cordova.system.library.8=com.google.firebase:firebase-messaging:+ cordova.system.library.9=com.google.firebase:firebase-crash:+ cordova.system.library.10=com.google.firebase:firebase-config:+ ``` My dependencies in build.gradle file : ``` dependencies { compile fileTree(dir: 'libs', include: '*.jar') // SUB-PROJECT DEPENDENCIES START debugCompile(project(path: "CordovaLib", configuration: "debug")) releaseCompile(project(path: "CordovaLib", configuration: "release")) compile "com.android.support:support-v4:27.1.0" compile "com.android.support:appcompat-v7:25.+" compile "com.google.gms:google-services:+" compile "com.google.android.gms:play-services-tagmanager:+" compile "com.google.firebase:firebase-core:+" compile "com.google.firebase:firebase-messaging:+" compile "com.google.firebase:firebase-crash:+" compile "com.google.firebase:firebase-config:+" // SUB-PROJECT DEPENDENCIES END } ``` Thanks in advance :)<issue_comment>username_1: I think your issue comes here: > > compile "com.google.gms:google-services:+" > > > compile "com.google.android.gms:play-services-tagmanager:+" > > > Rather than importing gms services like this, you should only import specific libraries. Upvotes: 0 <issue_comment>username_2: You are using together those both library. ``` compile "com.google.gms:google-services:+" compile "com.google.android.gms:play-services-tagmanager:+" ``` this `"com.google.gms:google-services:+"` library has all play service libraries. Remove this dependency `"com.google.android.gms:play-services-tagmanager:+"` and it will work. But still This is not a good way to add `com.google.gms:google-services:+`, because un-necessary you are adding all google's dependency. Instead of this dependecy you can use specific dependency, for example if you are using map, then use only map play service. Here is the list of all play service dependency <https://developers.google.com/android/guides/setup> . I suggest you add only required dependency instead of play service universal dependency. Upvotes: 0 <issue_comment>username_3: Change your project.property file to: ``` target=android-26 android.library.reference.1=CordovaLib cordova.system.library.1=com.android.support:support-v4:27.1.0 cordova.system.library.2=com.android.support:support-v4:25.+ cordova.system.library.3=com.android.support:appcompat-v7:25.+ cordova.system.library.6=com.google.firebase:firebase-core:11.8.0 cordova.system.library.7=com.google.firebase:firebase-messaging:11.8.0 cordova.system.library.8=com.google.firebase:firebase-crash:11.8.0 cordova.system.library.9=com.google.firebase:firebase-config:11.8.0 cordova.system.library.9=com.google.firebase:firebase-auth:11.8.0 cordova.system.library.9=me.leolin:ShortcutBadger:1.1.4@aar ``` Upvotes: 1 [selected_answer]<issue_comment>username_4: Please update your build.gradle file ``` dependencies { classpath 'com.android.tools.build:gradle:2.3.0' } ``` changes your version to `2.3.0` its worked for me... Thanks Upvotes: 3 <issue_comment>username_5: * If you've already changed version at /android/build.gradle but not work yet. Maybe you need check some library package at node\_modules. * Eg: react-native-onesignal also compile some play-services with highest version (they use +) so it can make this issue. * You can put a script at root directory and add {"scripts": {"postinstall": "node changeVersionGoogleService.js"}} in package .json so it can run to auto change your version when you npm install. * This is the script: <https://gist.github.com/duytq94/47ef945131b61de538447d449813b3d4> * My script at now auto change 'react-native-onesignal', 'react-native-admob', 'react-native-maps', 'react-native-google-sign-in' Upvotes: 0 <issue_comment>username_6: None of the solutions discussed here worked for me so I went on to * renamed the `/platform/android` folder and Remove android platform * add android platform `ionic cordova platform add android` * faced another issue with facebook due to this which has a solution [here](https://github.com/jeduan/cordova-plugin-facebook4/issues/599) where you need to add your app id and name in `platforms/android/app/src/main/res/values/strings.xml` file compiled worked fine after that. The problem occurred for me when **upgrading to cordova 7**. Upvotes: 0 <issue_comment>username_7: just Add : ``` googlePlayServicesVersion=11.8.0 ``` to your gradle.properties have fun ... Upvotes: 0
2018/03/21
1,092
3,621
<issue_start>username_0: I'm using the pvclust package in R to perform bootstrapped hierarchical clustering. The output is then plotted as a hclust object with a few extra features (different default title, p-values at nodes). [I've attached a link to one of the plots here.](https://i.stack.imgur.com/FNdGv.png) This plot is exactly what I want, except that I need the leaf labels to be displayed horizontally instead of vertically. As far as I can tell there isn't an option for rotating the leaf labels in plot.hclust. I can plot the hclust object as a dendrogram (i.e. `plot(as.dendrogram(example$hclust), leaflab="textlike")` instead of `plot(example)`) but the leaf labels are then printed in boxes that I can't seem to remove, and the heights of the nodes in the hclust object are lost. [I've attached a link to the dendrogram plot here.](https://i.stack.imgur.com/ayoNB.png) What would be the best way to make a plot that is as similar as possible to the standard `plot.pvclust()` output, but with horizontal leaf labels?<issue_comment>username_1: One way to get the text the way you want is to have `plot.dendrogram` print nothing and just add the labels yourself. Since you don't provide your data, I illustrate with some built-in data. By default, the plot was not leaving enough room for the labels, so I set the `ylim` to allow the extra needed room. ``` set.seed(1234) HC = hclust(dist(iris[sample(150,6),1:4])) plot(as.dendrogram(HC), leaflab="none", ylim=c(-0.2, max(HC$height))) text(x=seq_along(HC$labels), y=-0.2, labels=HC$labels) ``` [![Dendrogram with horizontal labels](https://i.stack.imgur.com/n4pxK.png)](https://i.stack.imgur.com/n4pxK.png) Upvotes: 1 <issue_comment>username_2: I've written a function that plots the standard pvclust plot with empty strings as leaf labels, then plots the leaf labels separately. ``` plot.pvclust2 <- function(clust, x_adj_val, y_adj_val, ...){ # Assign the labels in the hclust object to x_labels, # then replace x$hclust$labels with empty strings. # The pvclust object will be plotted as usual, but without # any leaf labels. clust_labels <- clust$hclust$labels clust$hclust$labels <- rep("", length(clust_labels)) clust_merge <- clust$hclust$merge #For shorter commands # Create empty vector for the y_heights and populate with height vals y_heights <- numeric(length = length(clust_labels)) for(i in 1:nrow(clust_merge)){ # For i-th merge singletons <- clust_merge[i,] < 0 #negative entries in merge indicate #agglomerations of singletons, and #positive entries indicate agglomerations #of non-singletons. y_index <- - clust_merge[i, singletons] y_heights[y_index] <- clust$hclust$height[i] - y_adj_val } # Horizontal text can be cutoff by the margins, so the x_adjust moves values # on the left of a cluster to the right, and values on the right of a cluster # are moved to the left x_adjust <- numeric(length = length(clust_labels)) # Values in column 1 of clust_merge are on the left of a cluster, column 2 # holds the right-hand values x_adjust[-clust_merge[clust_merge[ ,1] < 0, 1]] <- 1 * x_adj_val x_adjust[-clust_merge[clust_merge[ ,2] < 0, 2]] <- -1 * x_adj_val # Plot the pvclust object with empty labels, then plot horizontal labels plot(clust, ...) text(x = seq(1, length(clust_labels)) + x_adjust[clust$hclust$order], y = y_heights[clust$hclust$order], labels = clust_labels[clust$hclust$order]) } ``` Upvotes: 1 [selected_answer]
2018/03/21
656
2,632
<issue_start>username_0: Here I have an abstract class Person and multiple subclasses: ``` public abstract class Person { public String name; public Person(String name) { this.name = name; } } public class ComputerScientist extends Person { public String job; public ComputerScientist(String name, String job) { super(name); this.job = job; } } public class SoftwareEngineer extends Person { public String job; public SoftwareEngineer(String name, String job) { super(name); this.job = null; } } ``` This is what I run: ``` public static void main(String[] args) { List people = new ArrayList(); person.add(new ComputerScientist("ben", "job")); person.add(new SoftwareEngineer("larry", "job")); Random r = new Random(); Person person = people.get(r.nextInt(people.size() - 1); } ``` Person becomes the same as the Person in the list, how do I get it as a person clone. Cloning and new Instance do not work. I can probably do it using a copy method (requres me to rewrite a great deal of code) but is there any (perhaps more efficient) way to do it without?<issue_comment>username_1: Make your class cloneable with implements with Cloneable interface. and at object user .clone() method to clone of person class object Upvotes: 0 <issue_comment>username_2: I'm not a fan of `clone()` - see also [Clone() vs Copy constructor- which is recommended in java](https://stackoverflow.com/questions/2427883/clone-vs-copy-constructor-which-is-recommended-in-java) So, instead use a copy constructor or copy method, that accepts a person and then transfers the relevant information Upvotes: 1 <issue_comment>username_3: You can create a method to create a new Object of the Person(as per the sub class) and another method to copy the states in the new object. Refer below approach for the basic implementation of the same. ``` public abstract class Person{ ...//your states and methods protected void copy(Person copiedPerson){ copiedPerson.name = this.name; } public abstract Person getCopyPerson(); } public class SoftwareEngineer extends Person{ ....//your states and methods @override protected void copy( Person copiedPerson ){ super(copiedPerson); copiedPerson.job = this.job; } @override public Person getCopyPerson(){ Person copyPerson = new SoftwareEngineer(); copy(copyPerson); return copyPerson; } } ``` Now whenever you fetch the object of Person, simply call `getCopyPerson()` on it to get a copy object. Upvotes: 2 [selected_answer]
2018/03/21
1,211
3,575
<issue_start>username_0: How to avoid multiple nested for-loops when one nested for-loop has range up to the current iteration of the outer for-loop? For example, consider the following code: This program returns a triplet from a list arr such that `arr[i] - arr[j] = arr[j] - arr[k] = d` and `i.` ``` d =3 arr = [1, 2, 4, 5, 7, 8, 10] list1 = [] for biggest in range(0, len(arr)): for bigger in range(0, biggest): for big in range(0, bigger): if abs(arr[big] - arr[bigger]) == d and abs(arr[bigger] - arr[biggest]) == d: list1.append([arr[big], arr[bigger], arr[biggest]]) print(list1)) ``` Are there any other alternatives to using multiple nested loops?<issue_comment>username_1: You can use [the combinations function from itertools](https://docs.python.org/3/library/itertools.html#itertools.combinations). Your code would then become: ``` from itertools import combinations d = 3 arr = [1, 2, 4, 5, 7, 8, 10] list1 = [] for big, bigger, biggest in combinations(arr, 3): if abs(big - bigger) == d and abs(bigger - biggest) == d: list1.append([big, bigger, biggest]) print(list1) ``` Which gives the same printout as your code (after you remove the extraneous right parenthesis on your last line): ``` [[1, 4, 7], [2, 5, 8], [4, 7, 10]] ``` Note that I changed the meanings of your variables `big`, `bigger`, `biggest` to be the array values rather than their indices. Working with values and avoiding indices is more pythonic and easier to understand. You could also just do it in a list comprehension, for a slightly different look, avoiding the temporary list, and probable speed increase. ``` from itertools import combinations d = 3 arr = [1, 2, 4, 5, 7, 8, 10] print([[big, bigger, biggest] for big, bigger, biggest in combinations(arr, 3) if abs(big - bigger) == d and abs(bigger - biggest) == d ]) ``` Upvotes: 2 <issue_comment>username_2: You can replace the three loops with: ``` from itertools import combinations for big, bigger, biggest in combinations(range(0, len(arr)), 3): ``` You can replace all the code with: ``` print([t for t in combinations(arr, 3) if t[2] - t[1] == t[1] - t[0] == d]) ``` Upvotes: 4 [selected_answer]<issue_comment>username_3: While previous answers are pythonic, if you care about the implementation of the search algorithm, you can reduce the complexity of your algorithm from `O(N^3)` to `O(N^2logN)` by implementing a binary search algorithm to find `k` in the space between `j+1` and the length of `lst` which satisfies `d - abs(lst[j] - lst[k]) == 0`. ``` d = 3 lst = [1, 2, 4, 5, 7, 8, 10] def bsearch(lst, left, right, j): while left < right: k = (left + right) // 2 diff = d - abs(lst[j] - lst[k]) if diff == 0: return k if diff > 0: left = k + 1 else: right = k return None l, result = len(lst), [] for i in range(l): for j in range(i + 1, l): diff = d - abs(lst[i] - lst[j]) if diff != 0: continue k = bsearch(lst, j + 1, l, j) if not k: continue result.append((lst[i], lst[j], lst[k])) print(result) [(1, 4, 7), (2, 5, 8), (4, 7, 10)] ``` Upvotes: 0 <issue_comment>username_4: Found a better way I guess! avoiding the nested loops. ``` arr = [1,2,3,4,5,6,7,8,9] d = 3 list1 = arr list2 = [] for each in (0,len(list1)): if list1[each] + d in arr and list1[each] + 2*d in arr: list2.append([list1[each], list1[each]+d, list1[each]+2*d]) print(list2) ``` Upvotes: 1
2018/03/21
1,425
2,615
<issue_start>username_0: Hi so i got this array: ``` var locations = [ ['<NAME>', -33.890542, 151.274856, 4], ['Coogee Beach', -33.923036, 151.259052, 5], ['Cronulla Beach', -34.028249, 151.157507, 3], ['Manly Beach', -33.80010128657071, 151.28747820854187, 2], ['Maroubra Beach', -33.950198, 151.259302, 1] ]; ``` and i want to append to it just like it is example: ``` var locations = [ ['<NAME>ach', -33.890542, 151.274856, 4], ['Coogee Beach', -33.923036, 151.259052, 5], ['Cronulla Beach', -34.028249, 151.157507, 3], ['Manly Beach', -33.80010128657071, 151.28747820854187, 2], ['Maroubra Beach', -33.950198, 151.259302, 1], ['New item', -22.950198, 141.259302, 6] ]; ``` I have no idea how to do it, search 'Add items to array in array ' didn't quite seem to work out.<issue_comment>username_1: ``` var locations = [ ['Bondi Beach', -33.890542, 151.274856, 4], ['Coogee Beach', -33.923036, 151.259052, 5], ['Cronulla Beach', -34.028249, 151.157507, 3], ['Manly Beach', -33.80010128657071, 151.28747820854187, 2], ['Maroubra Beach', -33.950198, 151.259302, 1] ]; var newLocation = ['New item', -22.950198, 141.259302, 6]; locations.push(newLocation); ``` Upvotes: 1 <issue_comment>username_2: locations.push( ['New item', -22.950198, 141.259302, 6]); ist the right answer. Upvotes: 1 <issue_comment>username_3: you can use push() method if you want to add on the last ! or you can add in the first by using .unshift method ! look here for more informations <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array> Upvotes: 0 <issue_comment>username_4: Try to use this: ``` var locations = [ {'Bondi Beach', -33.890542, 151.274856, 4}, {'Coogee Beach', -33.923036, 151.259052, 5}, {'Cronulla Beach', -34.028249, 151.157507, 3}, {'Manly Beach', -33.80010128657071, 151.28747820854187, 2}, {'Maroubra Beach', -33.950198, 151.259302, 1} ``` ]; Now you can apply a push ``` locations.push({'New item', -22.950198, 141.259302, 6}); ``` Let me know if it work. Upvotes: 0 <issue_comment>username_5: or you can use [spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) ```js var locations = [ ['Bondi Beach', -33.890542, 151.274856, 4], ['Coogee Beach', -33.923036, 151.259052, 5], ['Cronulla Beach', -34.028249, 151.157507, 3], ['Manly Beach', -33.80010128657071, 151.28747820854187, 2], ['Maroubra Beach', -33.950198, 151.259302, 1] ]; locations = [...locations,['New item', -22.950198, 141.259302, 6]]; console.log(locations); ``` Upvotes: 0
2018/03/21
610
2,116
<issue_start>username_0: I have a containing a tags and further divs: ``` some content ``` Im trying to select the data attribute on the anchor tag with jquery so that i can display the the tags in which have the same ID (if that makes sense?). So far i've been able to identify the data id with `$(".group.popOutDisplay a")[0].attributes[1].value;` but this only gives the ID of the first element, due to the `[0]` index. **tldr: How can I get the data-ID of the tag that has just been clicked?**<issue_comment>username_1: Here we go: ``` $('.popOutDisplay a').click(function(e) { e.preventDefault(); console.log($(this).data('id')); }); ``` Here the **[documentation](https://api.jquery.com/data/)** of `.data()` attribute. Demo: <https://jsfiddle.net/ru4pjz3c/2/> Upvotes: 3 [selected_answer]<issue_comment>username_2: ``` $(".group a").click(function(){ var data=$(this).attr("data-id"); alert(data) }); ``` To retrieve the value's attribute as a string without any attempt to convert it, use the attr() method. Upvotes: 0 <issue_comment>username_3: You can use ".click()" for this. check snippet below.. ```js $('.popOutDisplay a').click(function(e){ e.preventDefault(); var elID = $(this).data('id'); console.log(elID); }) ``` ```html some content ``` Upvotes: 2 <issue_comment>username_4: bind click event listener on the `a` element container div `. the reason is because click events on the `a` elements will bubble up to div container.` something like ``` $('.group.popOutDisplay').bind('click', function(e) { var target = e.target; if (target.tagName.toLowerCase() === 'a') { e.preventDefault(); //prevent the default action of navigating to the url var id = target.dataset.id; //you now have the id; $('#' + id).css('display', 'block'); //display the div } }); ``` Upvotes: -1 <issue_comment>username_5: ``` $(document).on("click", "[data-id]", function (event){ event.preventDefault(); var id = $(this).attr("data-id"); // Apply your logic here // $("#" + id) }); ``` Upvotes: 0
2018/03/21
447
1,458
<issue_start>username_0: Following is a part of my whole xml of constraint Layout. ``` ``` What I am trying to do is get the text view on exact centre on the right side of image view. In linear layout we achieve it mostly by gravity. Here I am using `marginTop` to achieve the same . So can I do the same by using any property . Is there a property something like `rightOfCentreOf` ? Thanks<issue_comment>username_1: pls add one line in your textview ``` app:layout_constraintBottom_toBottomOf="@+id/img_apn_not_set" ``` also remove **android:layout\_marginTop="5dp"** hope it help you Upvotes: 4 [selected_answer]<issue_comment>username_2: Try this ``` xml version="1.0" encoding="utf-8"? ``` **RESULT** [![enter image description here](https://i.stack.imgur.com/bpLrE.png)](https://i.stack.imgur.com/bpLrE.png) Upvotes: 2 <issue_comment>username_3: ``` xml version="1.0" encoding="utf-8"? ``` Upvotes: 2 <issue_comment>username_4: You can use **app:layout\_constraintWidth\_default="wrap"** and give all 4 side constraint it will be at center Example: ``` xml version="1.0" encoding="utf-8"? ``` It will look like this [![enter image description here](https://i.stack.imgur.com/innkV.png)](https://i.stack.imgur.com/innkV.png) Upvotes: 1 <issue_comment>username_5: Try this, If you want to move the text to the right or left use Horizontal bias, If you want to move your text to the top or bottom use vertical bias. ``` ``` Upvotes: 2
2018/03/21
543
1,759
<issue_start>username_0: I'm trying to copy a MAT image loaded in from a file to a specific address location. I have the following code ``` int main() { cv::Mat inImg = cv::imread("M6_traffic.jpg"); //Data point copy unsigned char * pData = (unsigned char *)inImg.data; unsigned char * Dest = (unsigned char *)0x0f000000;; int width = inImg.rows; int height = inImg.cols; //data copy using memcpy function memcpy(Dest, pData, sizeof(unsigned char)*width*height*3); } ``` But when I run this it always crashes, any idea why? and is there a better why to do this? My end goal is to able to copy a image data to specific address in a Linux based system<issue_comment>username_1: pls add one line in your textview ``` app:layout_constraintBottom_toBottomOf="@+id/img_apn_not_set" ``` also remove **android:layout\_marginTop="5dp"** hope it help you Upvotes: 4 [selected_answer]<issue_comment>username_2: Try this ``` xml version="1.0" encoding="utf-8"? ``` **RESULT** [![enter image description here](https://i.stack.imgur.com/bpLrE.png)](https://i.stack.imgur.com/bpLrE.png) Upvotes: 2 <issue_comment>username_3: ``` xml version="1.0" encoding="utf-8"? ``` Upvotes: 2 <issue_comment>username_4: You can use **app:layout\_constraintWidth\_default="wrap"** and give all 4 side constraint it will be at center Example: ``` xml version="1.0" encoding="utf-8"? ``` It will look like this [![enter image description here](https://i.stack.imgur.com/innkV.png)](https://i.stack.imgur.com/innkV.png) Upvotes: 1 <issue_comment>username_5: Try this, If you want to move the text to the right or left use Horizontal bias, If you want to move your text to the top or bottom use vertical bias. ``` ``` Upvotes: 2
2018/03/21
979
3,327
<issue_start>username_0: I'm having some trouble with jQuery overwriting the elements of a particular parent class. For instance, I have two classes that have the same name but I am looking only to use the first instance for a particular purpose and then the others for something else, but the data inside keeps being overwritten by the next function I am using. I think I know why it is doing it, I'm just unsure of how to fix it so it doesn't. Here is my jQuery code: ``` function buildFriendStatus() { $.getJSON('/members/feed/get-friend-status', function(data) { var notFirstElement = $('.w3-container.w3-card-2.w3-white.w3-round.w3-margin:not(first)') $.each(data, function(i, item) { var element = notFirstElement.eq(i); element.find('h4').html(data[i].username); element.find('p').html(data[i].status); element.find('img').attr('src', data[i].images); }); }).fail(function(response) { console.log(response.fail); }); } function buildSelfStatus() { $.getJSON('/members/feed/list-own-status', function(data) { $.each(data, function(i, item) { $('.w3-container.w3-card-2.w3-white.w3-round.w3-margin:first').find('h4').html(data[i].username); $('.w3-container.w3-card-2.w3-white.w3-round.w3-margin:first').find('p').html(data[i].status); $('.w3-container.w3-card-2.w3-white.w3-round.w3-margin:first').find('img').attr('src', data[i].images); }); }).fail(function(response) { console.log(response.fail); }); } setInterval(function() { buildFriendStatus(); }, 1000); ``` and then the html/calling of the functions ``` buildSelfStatus(); buildFriendStatus(); #### ![<?php echo $this->identity() . ]()" class="w3-margin-bottom w3-round w3-border"> #### ![<?php echo ]()" class="w3-margin-bottom w3-round w3-border"> Like Comment ``` Here is a screenshot of the issue. [![enter image description here](https://i.stack.imgur.com/zqKCk.png)](https://i.stack.imgur.com/zqKCk.png) Updated screenshot (shows the first image but not the other result(s) now) [![enter image description here](https://i.stack.imgur.com/30Kd7.png)](https://i.stack.imgur.com/30Kd7.png) Any help would be appreciated Thanks! Oh, on another note, is there a way to use jQuery to put data inside the class but have the class be shown more than once without overwriting the data previously added but only have one element with the class name? Sort of like the screenshot attached but just not overwriting each class the same time. Just curious as I couldn't find anything regarding this. I guess I mean build the div element and it's child elements dynamically based on the results retrieved via `$.getJSON`.<issue_comment>username_1: ```js $(".getfirst").click(function(){ alert($(".testdiv").first().text()); }); ``` ```html 33 44 55 66 get me!! ``` Why dont you use .first() of jQuery? For example lets say you have 4 divs with same class but you want to get the text of the first div element with the specific class name: ``` 33 44 55 66 get me!! $(".getfirst").click(function(){ alert($(".testdiv").first().text()); }); ``` Upvotes: 0 <issue_comment>username_2: just added another class to the first element. Upvotes: -1
2018/03/21
875
2,817
<issue_start>username_0: I have a BAT file that parses out the header of a CSV file and replaces spaces with underscores, then merges a series of CSV files [here](https://stackoverflow.com/a/49395485/6779756). The problem is, my header file is very long and is being truncated at 1024 characters. Does anyone have a suggestion? I’m hoping to not have to go to PowerShell or anything beyond basic batch programming if possible. The only issue is with the headers. ``` @ECHO OFF set Outputfolder=c:\Test REM Get the header string out of one of the files for %%I in (%outputFolder%\*_stats.csv) do set /p HeaderString=< %%I REM replace the spaces in that header string with underscores SET HeaderString=%HeaderString: =_% REM write that header as the first line of the output file echo.%HeaderString%>%outputFolder%\all_stats_merged.csv REM append the non-header lines from all the files >>%outputFolder%\all_stats_merged.csv ( for %%I in (%outputFolder%\*_stats.csv) do more +1 "%%I" ) ```<issue_comment>username_1: Despite your preference to steer away from `PowerShell`, *(if possible)*, give the following `.ps1` a go and see if it helps change your preference: ```ps1 $First = $True GCI 'C:\test\*_stats.csv' | % {$Csv = $_ $Lines = $Lines = GC $Csv $Write = Switch($First) {$True {$Line = $Lines | Select -First 1 $Line.Replace(' ','_') $First = $False} $False {$Lines | Select -Skip 1}} AC 'C:\test\all_stats_merged.csv' $Write} ``` For completeness, here's an untested batch file attempt using `FindStr` which should be okay up to 8191 characters \*\*: ```bat @Echo Off Set "OutputFolder=C:\Test" Set "HeaderString=" For /F "Tokens=3* Delims=:" %%A In ( 'FindStr /N "^" "%OutputFolder%\*_stats.csv" 2^>Nul') Do (If "%%A"=="1" ( If Not Defined HeaderString (Set "HeaderString=%%B" Call Echo %%HeaderString: =_%%)) Else Echo %%B )>>"%OutputFolder%\all_stats_merged.csv" ``` The above `.cmd` file was designed with `%OutputFolder%` containing a drive specification; if its final value is without a drive letter, you'll need to change `Tokens=3*` to `Tokens=2*`. \*\* *The 8191 characters will however include the full file path of each file, each lines line number and two colon separator characters.* Upvotes: 0 <issue_comment>username_2: Your problem is you are using SET /P to read the header line, which is limited to 1021 characters (not 1024). See <https://www.dostips.com/forum/viewtopic.php?f=3&t=2160> as well as <https://www.dostips.com/forum/viewtopic.php?f=3&t=2160#p12339> for more info. This can easily be solved if you switch to FOR /F which can read ~8k ``` for %%A in (%outputFolder%\*_stats.csv) do for /f "usebackq delims=" %%B in ("%%A") do ( set "HeaderString=%%B" goto :break ) :break ``` Upvotes: 2
2018/03/21
307
1,061
<issue_start>username_0: I tried a lot of combinations, but somehow I don't get it. The id for the text I want to show is generated. **I need to write a variable here instead of a concrete id**. So not: ``` getString(R.string.id_1) ``` But something like: ``` var myId = ... getString(R.string."$myId") ``` Do you know what I mean? What ever I tried I got an error that only an Int. How would you solve this in Kotlin?<issue_comment>username_1: Try below code, it will work for you: ``` fun AppCompatActivity.getString(name: String): String { return resources.getString(resources.getIdentifier(name, "string", packageName)) } Usage: val resource = getString($resourceName); ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: if you want to access string resource dynamically than you have to create pattern something like below string.xml ``` Hello Hello1 Hello2 Hello3 ``` java code ``` getString(R.string.abc+) ``` this is just an idea, i haven't tried it. Let me know whether it works or fail. Happy Coding :) Upvotes: -1
2018/03/21
278
1,183
<issue_start>username_0: I'm using Chrome 65 on Mac. I have set up a workspace in Chrome under the 'Sources > Filesystem' tab. I'm able to edit files and Chrome will save these changes to the actual file on my disk. But I would like to use the live editing capabilities of the 'Elements' tab to alter HTML & CSS and let Chrome save these changes. I have found many answers, but none work with the current version of Chrome.<issue_comment>username_1: You may not be able to save the file locally as you can with you CSS changes (from the "Sources" tab), but you can copy and paste elements using Chrome 65 and above (maybe older versions too). Copying the element also copies all of its children and their children. So, if you copy the element, you will get the entire page - everything between and . Right click on the element, go to Copy > Copy element. Then paste the clipboard content into your favorite editor or IDE and save. Not as convenient as saving from the Sources tab, but it does allow you to get/save all the changes you've made in the Elements tab. Upvotes: 2 <issue_comment>username_2: Simply saving the website (File > Save Page As...) works for me. Upvotes: 0
2018/03/21
1,316
4,493
<issue_start>username_0: I am working with an API right now and I am using `details[5].Value` to target information in the following format: ``` details: "value":[ { "ID": "6", "Name": "Links", "Value": "URL" }, { "ID": "7", "Name": "Other", "Value": "URL" } etc ] ``` The problem is that the location inside of the JSON response is likely to change in the future, making my code obsolete and as the url has the potential to change as well, I cannot target that. I want a way to target the value of url, mostly, because of this, by the value of the `"Name"` property. However, if I use something like ``` _.where(details, { Name: "Links" }).Value ``` It comes back as undefined. I am not sure if there would be another way to get to the information?<issue_comment>username_1: Take a look at this mini function. Let me know if there is something wrong Update ------ This is the ES5 Version ``` function f(key, value, array){ return array.value.filter(function(sub_array){ return sub_array[key] == value; }); } ``` This is the ES6 Golfed Version ``` f=(k,v,a)=>a.value.filter(_=>_[k]==v) ``` ```js //This is your JSON var details = { value: [ { "ID": "6", "Name": "Links", "Value": "URL" }, { "ID": "7", "Name": "Other", "Value": "URL" } ] } // Short code f=(k,v,a)=>a.value.filter(_=>_[k]==v) // f is the function name // Recives k = array key, v = value, a = array // filter by the given key and value // return the result as an array console.log(f('Name', 'Links', details)) ``` Upvotes: 0 <issue_comment>username_2: An alternative is using the Javascript built-in function **[`find`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find)** to get a specific object within an array. * This alternative allows you to pass either an object or a string. * If the `byThis` parameter is an object, the whole set of `key-values` must match with the `key-values` of every object within the target array. * Otherwise, if `byThis` is a string every object will be treated as string to make the necessary comparison. ```js let details = { "value": [{ "ID": "6", "Name": "Links", "Value": "URL" }, { "ID": "7", "Name": "Other", "Value": "URL" }]}; let findBy = (array, byThis) => { return array.find(o => { if (typeof byThis === 'object') return Object.keys(byThis).every(k => o[k] === byThis[k]); else if (typeof byThis === 'string') return o.toString() === byThis; }); } let found = findBy(details.value, {Name: "Links"}); console.log(found); ``` ```css .as-console-wrapper { max-height: 100% !important; top: 0; } ``` Upvotes: 0 <issue_comment>username_3: There are a couple points of confusion here. [`_.where`](http://underscorejs.org/#where) returns an array: > > Looks through each value in the **list**, returning an array of all the values that contain all of the key-value pairs listed in **properties**. > > > so your `_.where(details, obj).Value` will (almost) always give you `undefined` because an array is unlikely to have a `Value` property. [`_.findWhere`](http://underscorejs.org/#findWhere) on the other hand does return a single value: > > Looks through the **list** and returns the first value that matches all of the key-value pairs listed in **properties**. > > > Secondly, your `details` appears to look like: ``` let details = { value: [ { ID: '6', Name: 'Links', Value: 'URL' }, { ID: '7', Name: 'Other', Value: 'URL' }, ... ] } ``` so you don't want to search `details`, you want to search `details.value`. Putting them together: ``` _(details.value).findWhere({ Name: 'Links' }).Value ``` or ``` _.findWhere(details.value, { Name: 'Links' }).Value ``` You could use [`Array.prototype.find`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) (or [`Array.prototype.filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) if you're looking for all matches) and write your own callback but you already have Underscore available so why bother? Furthermore, Backbone collections have `findWhere` and `where` methods and there are advantages to matching Backbone's overall terminology. Upvotes: 3 [selected_answer]
2018/03/21
539
2,087
<issue_start>username_0: I have 60 servers, VMs to be particular. And I have a local admin username and password. Instead of logging on to 60 servers using these local admin creds, it would be better if there is a script to check if I could log on to these servers as a local admin using the local admin creds. To be precise, I want to check.if I can use this local admin creds to successfully log on to all 60 VMs. I have googled but no luck. I know stackoverflow is not a place to directly ask for a piece of code, but in this case I am forced to. Even if you dont have a direct answer please direct me somewhere. ``` gc serverlist.txt | % { $admin_share = '\\' + $_ + '\admin$' if (Test-Path $admin_share) { Write-Host "Access test passed on $($_)" } else { Write-Host "Access test failed on $($_)" } } ```<issue_comment>username_1: If you have ICMP enabled, you could use Test-Connection cmdlet with the Credential switch. You can see more details in example 3 here: <https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/test-connection?view=powershell-6> Upvotes: 0 <issue_comment>username_2: This is a variation of your attempt. It assumes the same username and password for all computers. ``` #Get list of cserver names from file $Servers = Get-Content -Path serverlist.txt #Prompt user foe credentials $Cred = Get-Credential foreach ($Svr in $Servers) { #path to share (\\ServerName\Admin$) $Path = '\\' + $Svr + '\Admin$' Try { #Map admin share as PS Drive (NOT visable in the GUI) #ErrorAction stop will jump to catch block if the connection is unsuccessfull New-PSDrive -Name TEST -PSProvider FileSystem -Root $Path -Credential $Cred -ErrorAction Stop #Success Message Write-Output "Connection Successful $Svr" #Remove drive before next loop Remove-PSDrive -Name TEST } Catch { #Error message if connection fails Write-Warning -Message "Connect failed $Svr" } } ``` Upvotes: 2 [selected_answer]
2018/03/21
1,355
2,323
<issue_start>username_0: I have a dataset as follows: ``` ts Out[227]: Sales Month Jan 1808 Feb 1251 Mar 3023 Apr 4857 May 2506 Jun 2453 Jul 1180 Aug 4239 Sep 1759 Oct 2539 Nov 3923 Dec 2999 ``` After taking a moving average of window=2, the output is: ``` shifted = ts.shift(0) window = shifted.rolling(window=2) means = window.mean() print(means) Sales Month Jan NaN Feb 1529.5 Mar 2137.0 Apr 3940.0 May 3681.5 Jun 2479.5 Jul 1816.5 Aug 2709.5 Sep 2999.0 Oct 2149.0 Nov 3231.0 Dec 3460.5 ``` I want NaN to be replaced by its original value. Can it be done?<issue_comment>username_1: Try this: ``` In [92]: ts.rolling(window=2, min_periods=1).mean() Out[92]: Sales Jan 1808.0 Feb 1529.5 Mar 2137.0 Apr 3940.0 May 3681.5 Jun 2479.5 Jul 1816.5 Aug 2709.5 Sep 2999.0 Oct 2149.0 Nov 3231.0 Dec 3461.0 ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: Use: ``` df = df['Sales'].rolling(window=2).mean().fillna(df['Sales']) print (df) Jan 1808.0 Feb 1529.5 Mar 2137.0 Apr 3940.0 May 3681.5 Jun 2479.5 Jul 1816.5 Aug 2709.5 Sep 2999.0 Oct 2149.0 Nov 3231.0 Dec 3461.0 Name: Sales, dtype: float64 ``` There are differences in both solutions if rolling by `n>2`: ``` df['Sales1'] = df['Sales'] * 2 df1 = df.rolling(window=3).mean().combine_first(df) print (df1) Sales Sales1 Jan 1808.000000 3616.000000 Feb 1251.000000 2502.000000 <-diff Mar 2027.333333 4054.666667 Apr 3043.666667 6087.333333 May 3462.000000 6924.000000 Jun 3272.000000 6544.000000 Jul 2046.333333 4092.666667 Aug 2624.000000 5248.000000 Sep 2392.666667 4785.333333 Oct 2845.666667 5691.333333 Nov 2740.333333 5480.666667 Dec 3153.666667 6307.333333 df2 = df.rolling(window=3, min_periods=1).mean() print (df2) Sales Sales1 Jan 1808.000000 3616.000000 Feb 1529.500000 3059.000000 <-diff Mar 2027.333333 4054.666667 Apr 3043.666667 6087.333333 May 3462.000000 6924.000000 Jun 3272.000000 6544.000000 Jul 2046.333333 4092.666667 Aug 2624.000000 5248.000000 Sep 2392.666667 4785.333333 Oct 2845.666667 5691.333333 Nov 2740.333333 5480.666667 Dec 3153.666667 6307.333333 ``` Upvotes: 2
2018/03/21
1,004
3,953
<issue_start>username_0: i have kind of wired requirement for converting JSON to xml. we have an API that returns the JSON response as below. ``` { "status":"Error", "errorMessages":{ "1001":"Schema validation Error" } } ``` We want to convert this JSON to XML as below using c# ``` ERROR 1001 Schema validation Error ``` The API team is very resistant to change the way there are generating the JSON. So i have to find a way to convert this json to XML. I am getting the below error when i try to convert ``` XmlDocument doc = JsonConvert.DeserializeXmlNode(json); ``` "JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifying a DeserializeRootElementName. Path errorMessages thanks for the help in advance. :)<issue_comment>username_1: Use the JsonConvert class which contains helper methods for this precise purpose: ``` // To convert an XML node contained in string xml into a JSON string XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); string jsonText = JsonConvert.SerializeXmlNode(doc); // To convert JSON text contained in string json into an XML node XmlDocument doc = JsonConvert.DeserializeXmlNode(json); ``` The Completed Documentation : [Here](https://www.newtonsoft.com/json/help/html/ConvertingJSONandXML.htm) Upvotes: 0 <issue_comment>username_2: if you are using asp.net web api. Its already can return xml response just add an accept header like `Accept: application/xml` Upvotes: 1 <issue_comment>username_3: From the documentation at <https://www.newtonsoft.com/json/help/html/ConvertingJSONandXML.htm> ``` string json = @"{ '?xml': { '@version': '1.0', '@standalone': 'no' }, 'root': { 'person': [ { '@id': '1', 'name': 'Alan', 'url': 'http://www.google.com' }, { '@id': '2', 'name': 'Louis', 'url': 'http://www.yahoo.com' } ] } }"; XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json); ``` Upvotes: 1 <issue_comment>username_4: At first, I would hardly recommend that your API team provides a valid JSON object. Otherwise you will have to write a converter that does the job. The converter could look like this: ``` using System.Collections.Generic; namespace Json { using System.IO; using System.Xml.Serialization; using Newtonsoft.Json.Linq; class Program { static void Main(string[] args) { var converter = new Converter(); converter.Convert(); } } class Converter { public void Convert() { // your JSON string goes here var jsonString = @"{""status"":""Error"",""errorMessages"":{ ""1001"":""Schema validation Error"", ""1953"":""Another error""}}"; // deconstruct the JSON var jObject = JObject.Parse(jsonString); var root = new Root { Status = jObject["status"].ToString(), ErrorMessages = new List() }; foreach (var errorMessageJsonObject in jObject["errorMessages"]) { var jProperty = (JProperty)errorMessageJsonObject; var errorCode = System.Convert.ToInt16(jProperty.Name); var errorDescription = jProperty.Value.ToString(); var errorMessage = new ErrorMessage() { ErrorCode = errorCode, ErrorDescription = errorDescription}; root.ErrorMessages.Add(errorMessage); } // serialize as XML var xmlSerializer = new XmlSerializer(typeof(Root)); string xml; using (StringWriter textWriter = new StringWriter()) { xmlSerializer.Serialize(textWriter, root); xml = textWriter.ToString(); } } } public class Root { public string Status; public List ErrorMessages; } public class ErrorMessage { public int ErrorCode; public string ErrorDescription; } } ``` With this, you will read the JSON, deconstruct it into a proper object and serialize it as XML. Upvotes: 3 [selected_answer]
2018/03/21
2,036
7,855
<issue_start>username_0: I am trying to validate my form and I have no validation errors, yet my form is not getting submitted. I have used FormGroup controls. I believe it would be very trivial issue but some how I am not able to understand where did I go wrong. This is my HTML ``` Full Name: Please enter a valid full name Birth Date: Gender: Female Male Email Id: Please enter a valid email Mobile: Please enter a valid phone number Address: Please enter a valid address. Only # , . - and numbers accepted Pincode: Please enter a valid 6 digit pincode City/Town: Please enter a valid city/town State: {{state}} Update ``` This is my TS file ``` import { Component } from '@angular/core'; import { NavController, NavParams ,Platform,AlertController,ToastController, LoadingController} from 'ionic-angular'; import { NativeStorage } from '@ionic-native/native-storage'; import {FormBuilder, FormGroup, Validators, AbstractControl} from '@angular/forms'; import { CustomValidtorsProvider } from '../../providers/custom-validators/custom-validators'; import { ProfileProvider } from '../../providers/profile/profile'; import { StatelistProvider } from '../../providers/statelist/statelist'; @Component({ selector: 'personal-details', templateUrl: 'personal-details.html', }) export class PersonalDetailsPage { statesList : any; formPersonal : FormGroup; username : AbstractControl; phone : AbstractControl; dob : AbstractControl; pincode : AbstractControl; address : AbstractControl; state : AbstractControl; city: AbstractControl; gender : AbstractControl; email : AbstractControl; myDate : AbstractControl; userEmail : string; userPhone : number; userDob : string; userAddress : string; userPincode : number; userGender : string; userState : string; userCity : string; userImg : any; userName : string; userId : string; headers: any; params : any; selectOptions:any; loader : any; timer : any; dateFormat : string; userPinCode : any; constructor(public navCtrl: NavController, public ProfileDetails :ProfileProvider, public navParams: NavParams, private nativeStorage : NativeStorage, private fb : FormBuilder, private platform : Platform, public alertCtrl: AlertController,private toastCtrl : ToastController, private loadingScreen : LoadingController) { platform.ready().then(()=> { } }) } GetDetails() { } InitForm() { this.formPersonal = this.fb.group({ 'username':[this.userName, Validators.compose([Validators.required,CustomValidtorsProvider.TextOnlyValidator])], 'password':['',Validators.compose([Validators.required])], 'phone':[ this.userPhone, Validators.compose([Validators.required])], //'dob':['', Validators.compose([Validators.required])], 'pincode':[ this.userPincode, Validators.compose([Validators.required])], 'address':[this.userAddress, Validators.compose([Validators.required,CustomValidtorsProvider.AddressFieldValidator])], 'state':[this.userState], 'city':[ this.userCity, Validators.compose([Validators.required,CustomValidtorsProvider.TextOnlyValidator])], 'gender':[this.userGender], 'email':[this.userEmail, Validators.compose([Validators.required,CustomValidtorsProvider.EmailValidator])], 'dob':['',""], }); this.username = this.formPersonal.controls['username']; this.phone = this.formPersonal.controls['phone']; //this.dob = this.formPersonal.controls['dob']; this.pincode = this.formPersonal.controls['pincode']; this.address = this.formPersonal.controls['address']; this.state = this.formPersonal.controls['state']; this.city = this.formPersonal.controls['city']; this.gender = this.formPersonal.controls['gender']; this.email = this.formPersonal.controls['email']; this.dob = this.formPersonal.controls['dob']; this.formPersonal.controls.gender.setValue(this.userGender); this.formPersonal.controls.state.setValue(this.userState); } } Loader(){ } UpdateNativeStorage(){ } DateFormat(date:string){ } showAlert(){ } ionViewDidLoad() { } onSubmit(value: string) : void{ console.log(2); if(this.formPersonal.valid){ this.showAlert() } } } ``` I have removed all other non-relevant code, the button click works fine, I can see console.log() printed, but my this.showAlert() method doesn't fire up. I am not getting why the form is invalid when all my fields dont get any error. Here is a snap shot of it without errors. [![enter image description here](https://i.stack.imgur.com/rhDjQ.png)](https://i.stack.imgur.com/rhDjQ.png) If at all I get any validation errors, the fields are highlighted in red. Do let me know what did I miss here.<issue_comment>username_1: Use the JsonConvert class which contains helper methods for this precise purpose: ``` // To convert an XML node contained in string xml into a JSON string XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); string jsonText = JsonConvert.SerializeXmlNode(doc); // To convert JSON text contained in string json into an XML node XmlDocument doc = JsonConvert.DeserializeXmlNode(json); ``` The Completed Documentation : [Here](https://www.newtonsoft.com/json/help/html/ConvertingJSONandXML.htm) Upvotes: 0 <issue_comment>username_2: if you are using asp.net web api. Its already can return xml response just add an accept header like `Accept: application/xml` Upvotes: 1 <issue_comment>username_3: From the documentation at <https://www.newtonsoft.com/json/help/html/ConvertingJSONandXML.htm> ``` string json = @"{ '?xml': { '@version': '1.0', '@standalone': 'no' }, 'root': { 'person': [ { '@id': '1', 'name': 'Alan', 'url': 'http://www.google.com' }, { '@id': '2', 'name': 'Louis', 'url': 'http://www.yahoo.com' } ] } }"; XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json); ``` Upvotes: 1 <issue_comment>username_4: At first, I would hardly recommend that your API team provides a valid JSON object. Otherwise you will have to write a converter that does the job. The converter could look like this: ``` using System.Collections.Generic; namespace Json { using System.IO; using System.Xml.Serialization; using Newtonsoft.Json.Linq; class Program { static void Main(string[] args) { var converter = new Converter(); converter.Convert(); } } class Converter { public void Convert() { // your JSON string goes here var jsonString = @"{""status"":""Error"",""errorMessages"":{ ""1001"":""Schema validation Error"", ""1953"":""Another error""}}"; // deconstruct the JSON var jObject = JObject.Parse(jsonString); var root = new Root { Status = jObject["status"].ToString(), ErrorMessages = new List() }; foreach (var errorMessageJsonObject in jObject["errorMessages"]) { var jProperty = (JProperty)errorMessageJsonObject; var errorCode = System.Convert.ToInt16(jProperty.Name); var errorDescription = jProperty.Value.ToString(); var errorMessage = new ErrorMessage() { ErrorCode = errorCode, ErrorDescription = errorDescription}; root.ErrorMessages.Add(errorMessage); } // serialize as XML var xmlSerializer = new XmlSerializer(typeof(Root)); string xml; using (StringWriter textWriter = new StringWriter()) { xmlSerializer.Serialize(textWriter, root); xml = textWriter.ToString(); } } } public class Root { public string Status; public List ErrorMessages; } public class ErrorMessage { public int ErrorCode; public string ErrorDescription; } } ``` With this, you will read the JSON, deconstruct it into a proper object and serialize it as XML. Upvotes: 3 [selected_answer]
2018/03/21
1,079
3,592
<issue_start>username_0: I am using a json array in AngularJS `ng-repeat`. I observed that it orders the input that overrides what I have in my html. Is there any way to prevent this ordering to happen? Here is my code (See it in [Plunkr](https://plnkr.co/edit/af1TsBBA3CtSZq8eAx5R?p=preview)): ``` **project ABC is wonderful** **How is this EFG?** **This is my IJK project** {{data}} ``` And the ata: ``` $scope.data = [{ "Project": "IJK", "Show": "true" }, { "Project": "DEF", "Show": "false" }, { "Project": "ABC", "Show": "true" } ]; ``` I found a [solution](https://stackoverflow.com/questions/19287716/skip-ng-repeat-json-ordering-in-angular-js), but this is using an outside function but I am looking for some better way if possible. Please suggest.<issue_comment>username_1: Make an `ng-repeat` over `data` and use its content for generating dynamically the `intput`s instead of showing/hiding the three of them in every iteration. This would show the values in the same order of the JSON, like this: ``` **Project {{x.Project}} is Present** ``` Notice here how the model is created dynamically too, in the object `x.Show`. This object will have now an index for every project and in that index the property will be `true`|`false` depending on the value of the project checkbox. See a working [**Plunker**](https://plnkr.co/edit/af1TsBBA3CtSZq8eAx5R?p=preview) Upvotes: 2 <issue_comment>username_2: Your question is not at all clear... The way you approach it would not at all scale if more projects arrive, so try to describe your end goal rather than where you are at now... If Your only ever interested in knowing something about those 3 particular projects regardless of how many the server returns, convert it to a map and then then just lookup: ``` $scope.map = $scope.data.reduce(function(map, next) { map[next.Project] = next; return map; }, {}); **project ABC is wonderful** **How is this EFG?** **This is my IJK project** ``` If the list is dynamic (you may get any number of projects to show)... Sort it!... ``` **Bla {{x.Project}} bla** ``` Or in code if you need more control: ``` var sorted = $scope.data.slice(0); sorted.sort(function(left, right) { var l = left.Project.toUpperCase(); // ignore upper and lowercase var r = right.Project.toUpperCase(); // ignore upper and lowercase if (l < r) { return -1; } if (l > r) { return 1; } // names must be equal return 0; }); $scope.sorted = sorted; **Bla {{x.Project}} bla** ``` Finally, if you wish to change the text on a pr. project bases in this case, either need another lookup: ``` $scope.text = { ABC: "project ABC is wonderful", DEF: "How is this EFG?", IJK: "This is my IJK project", } **{{text[x.Project]}}** ``` OR to enrich the model: ``` $scope.enriched = sorted.map(function(item){ item.text = textmap[item.Project]; return item; }) **{{x.text}}** ``` But I can't tell which of the solutions you are looking for? <https://plnkr.co/edit/ZTKe9QMWnEiSiCXUb9Gz?p=preview> I should also note that I converted the "Show" property into booleans rather than text, as it appears you wan't the checkbox to bind to it I assumed you wanted that... If the input json comes with text you can use ng-true-value/ng-false-value, see the docs: <https://docs.angularjs.org/api/ng/input/input%5Bcheckbox%5D> or map the values. The samples are easier to explain with just booleans so ill keep em that way. Upvotes: 2 [selected_answer]
2018/03/21
1,188
4,160
<issue_start>username_0: I am having an issue resetting the errorText to it's original state. Every time the form is submitted with an error(s) it adds all of the errors to the end even if they are from a previous submit. **1st click on blank form** // I expect this result every time. "Errors: Email is invalid. Password is invalid." **2nd click on blank form** "Errors: Email is invalid. Password is invalid. Email is invalid. Password is invalid." **Code Snippet** ``` class LoginForm extends Component { constructor(props) { super(props) this.state = { details: { email: '', password: '', }, hasError: false, errorText: 'Errors: \n', } } render() { let { hasError, errorText } = this.state const { LogUserIn } = this.props const onTapLogin = e => { // broken? if (hasError) { this.setState({ hasError: false, errorText: 'Errors: \n', }) } if (!check.emailValid(e.email)){ this.setState({ hasError: true, errorText: errorText += "\n - Email address is invalid. " }) } if (!check.passwordValid(e.password)){ this.setState({ hasError: true, errorText: errorText += "\n- Password is invalid. " }) } if (!hasError){ LogUserIn(e) } } return ( SIGN IN {errorText} ... // the form. ```<issue_comment>username_1: Make an `ng-repeat` over `data` and use its content for generating dynamically the `intput`s instead of showing/hiding the three of them in every iteration. This would show the values in the same order of the JSON, like this: ``` **Project {{x.Project}} is Present** ``` Notice here how the model is created dynamically too, in the object `x.Show`. This object will have now an index for every project and in that index the property will be `true`|`false` depending on the value of the project checkbox. See a working [**Plunker**](https://plnkr.co/edit/af1TsBBA3CtSZq8eAx5R?p=preview) Upvotes: 2 <issue_comment>username_2: Your question is not at all clear... The way you approach it would not at all scale if more projects arrive, so try to describe your end goal rather than where you are at now... If Your only ever interested in knowing something about those 3 particular projects regardless of how many the server returns, convert it to a map and then then just lookup: ``` $scope.map = $scope.data.reduce(function(map, next) { map[next.Project] = next; return map; }, {}); **project ABC is wonderful** **How is this EFG?** **This is my IJK project** ``` If the list is dynamic (you may get any number of projects to show)... Sort it!... ``` **Bla {{x.Project}} bla** ``` Or in code if you need more control: ``` var sorted = $scope.data.slice(0); sorted.sort(function(left, right) { var l = left.Project.toUpperCase(); // ignore upper and lowercase var r = right.Project.toUpperCase(); // ignore upper and lowercase if (l < r) { return -1; } if (l > r) { return 1; } // names must be equal return 0; }); $scope.sorted = sorted; **Bla {{x.Project}} bla** ``` Finally, if you wish to change the text on a pr. project bases in this case, either need another lookup: ``` $scope.text = { ABC: "project ABC is wonderful", DEF: "How is this EFG?", IJK: "This is my IJK project", } **{{text[x.Project]}}** ``` OR to enrich the model: ``` $scope.enriched = sorted.map(function(item){ item.text = textmap[item.Project]; return item; }) **{{x.text}}** ``` But I can't tell which of the solutions you are looking for? <https://plnkr.co/edit/ZTKe9QMWnEiSiCXUb9Gz?p=preview> I should also note that I converted the "Show" property into booleans rather than text, as it appears you wan't the checkbox to bind to it I assumed you wanted that... If the input json comes with text you can use ng-true-value/ng-false-value, see the docs: <https://docs.angularjs.org/api/ng/input/input%5Bcheckbox%5D> or map the values. The samples are easier to explain with just booleans so ill keep em that way. Upvotes: 2 [selected_answer]
2018/03/21
587
1,611
<issue_start>username_0: I have a Dataframe with one column where each cell in the column is a JSON object. ``` players 0 {"name": "tony", "age": 57} 1 {"name": "peter", age": 46} ``` I want to convert this to a data frame as: ``` name age tony 57 peter 46 ``` Any ideas how I do this? Note: the original JSON object looks like this... ``` { "players": [{ "age": 57, "name":"tony" }, { "age": 46, "name":"peter" }] } ```<issue_comment>username_1: This can do it: ``` df = df['players'].apply(pd.Series) ``` However, it's slow: ``` In [20]: timeit df.players.apply(pd.Series) 1000 loops, best of 3: 824 us per loop ``` @username_2 suggestion is faster: ``` In [24]: timeit pd.DataFrame(df.players.values.tolist()) 1000 loops, best of 3: 387 us per loop ``` Upvotes: 1 <issue_comment>username_2: Use `DataFrame` constructor if `type`s of values are `dict`s: ``` #print (type(df.loc[0, 'players'])) # #import ast #df['players'] = df['players'].apply(ast.literal\_eval) print (type(df.loc[0, 'players'])) df = pd.DataFrame(df['players'].values.tolist()) print (df) age name 0 57 tony 1 46 peter ``` But better is use [`json_normalize`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.json.json_normalize.html) from `json`s object as suggested @jpp: ``` json = { "players": [{ "age": 57, "name":"tony" }, { "age": 46, "name":"peter" }] } df = json_normalize(json, 'players') print (df) age name 0 57 tony 1 46 peter ``` Upvotes: 2
2018/03/21
708
2,273
<issue_start>username_0: I wrote a method in unity but I think it is wrong. I want to do if some sorted letters matching to any word, then it will say true. I mean 10 columns and 20 rows char array. the method will check the letters up to down or left to right(like scrabble game). e.g. there is a word in char array "H","U","N","D". this letters will match and matched letters will destroy in game and it will be null in char array. I wrote this code at below but does not work. where do i wrong? ``` [System.Serializable] public class ColumnLetters { public string[] lettersRows = new string[20]; } public ColumnLetters[] lettersColumns = new ColumnLetters[10]; public void CheckWord() { foreach (string item in answers) { for (int i = 0; i < lettersColumns.Length; i++) { for (int j = 0; j < lettersColumns[i].lettersRows.Length; j++) { if (item == lettersColumns[i].lettersRows[j]) { Debug.Log("True"); } else { Debug.Log("false"); } } } } } ```<issue_comment>username_1: This can do it: ``` df = df['players'].apply(pd.Series) ``` However, it's slow: ``` In [20]: timeit df.players.apply(pd.Series) 1000 loops, best of 3: 824 us per loop ``` @username_2 suggestion is faster: ``` In [24]: timeit pd.DataFrame(df.players.values.tolist()) 1000 loops, best of 3: 387 us per loop ``` Upvotes: 1 <issue_comment>username_2: Use `DataFrame` constructor if `type`s of values are `dict`s: ``` #print (type(df.loc[0, 'players'])) # #import ast #df['players'] = df['players'].apply(ast.literal\_eval) print (type(df.loc[0, 'players'])) df = pd.DataFrame(df['players'].values.tolist()) print (df) age name 0 57 tony 1 46 peter ``` But better is use [`json_normalize`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.json.json_normalize.html) from `json`s object as suggested @jpp: ``` json = { "players": [{ "age": 57, "name":"tony" }, { "age": 46, "name":"peter" }] } df = json_normalize(json, 'players') print (df) age name 0 57 tony 1 46 peter ``` Upvotes: 2
2018/03/21
653
1,850
<issue_start>username_0: I have a class which contains references, like: ``` class A { A(B &b) : b(b) {} // constructor B &b } ``` Sometimes b must be read-only, sometimes it is writeable. When I make a `const A a(b);` object, it's obvious that I want to protect the data inside it as `const`. But - by accident - it's easy to make a non-const copy of the object which will make the data inside it vulnerable. ``` const A a(b); // b object protected here A a_non_const(a); a_non_const.b.non_const_function(...); // b not protected now ``` I think that I should somehow prevent copies of the object when it is `const` like this: ``` const A a(b); const A a2(a); // OK! A a_non_const(a); // Compiler error ``` Is this possible at all?<issue_comment>username_1: This can do it: ``` df = df['players'].apply(pd.Series) ``` However, it's slow: ``` In [20]: timeit df.players.apply(pd.Series) 1000 loops, best of 3: 824 us per loop ``` @username_2 suggestion is faster: ``` In [24]: timeit pd.DataFrame(df.players.values.tolist()) 1000 loops, best of 3: 387 us per loop ``` Upvotes: 1 <issue_comment>username_2: Use `DataFrame` constructor if `type`s of values are `dict`s: ``` #print (type(df.loc[0, 'players'])) # #import ast #df['players'] = df['players'].apply(ast.literal\_eval) print (type(df.loc[0, 'players'])) df = pd.DataFrame(df['players'].values.tolist()) print (df) age name 0 57 tony 1 46 peter ``` But better is use [`json_normalize`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.json.json_normalize.html) from `json`s object as suggested @jpp: ``` json = { "players": [{ "age": 57, "name":"tony" }, { "age": 46, "name":"peter" }] } df = json_normalize(json, 'players') print (df) age name 0 57 tony 1 46 peter ``` Upvotes: 2
2018/03/21
807
1,791
<issue_start>username_0: I have two data.tables A: ``` contract.name contract.start contract.end price Q1-2019 2019-01-01 2019-04-01 10 Q2-2019 2019-04-01 2019-07-01 12 Q3-2019 2019-07-01 2019-10-01 11 Q4-2019 2019-10-01 2020-01-01 13 ``` and B: ``` contract delivery.begin delivery.end bid ask Q2-2018 2018-04-01 2018-06-30 9.8 10.5 Q3-2018 2018-07-01 2018-09-30 11.5 12.1 Q4-2018 2018-10-01 2018-12-31 10.5 11.3 Q1-2019 2019-01-01 2019-03-31 12.8 13.5 ``` I want a vector with the bid values from B ordered by the contract.name values from A like so: `bid = c(12.8, 0, 0, 0)`<issue_comment>username_1: This can do it: ``` df = df['players'].apply(pd.Series) ``` However, it's slow: ``` In [20]: timeit df.players.apply(pd.Series) 1000 loops, best of 3: 824 us per loop ``` @username_2 suggestion is faster: ``` In [24]: timeit pd.DataFrame(df.players.values.tolist()) 1000 loops, best of 3: 387 us per loop ``` Upvotes: 1 <issue_comment>username_2: Use `DataFrame` constructor if `type`s of values are `dict`s: ``` #print (type(df.loc[0, 'players'])) # #import ast #df['players'] = df['players'].apply(ast.literal\_eval) print (type(df.loc[0, 'players'])) df = pd.DataFrame(df['players'].values.tolist()) print (df) age name 0 57 tony 1 46 peter ``` But better is use [`json_normalize`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.json.json_normalize.html) from `json`s object as suggested @jpp: ``` json = { "players": [{ "age": 57, "name":"tony" }, { "age": 46, "name":"peter" }] } df = json_normalize(json, 'players') print (df) age name 0 57 tony 1 46 peter ``` Upvotes: 2
2018/03/21
1,252
3,995
<issue_start>username_0: I am writing some code to calculate the total of each row in the array. ``` public static int sum(int[][] array) { int total = 0; for (int i = 0; i < array.length; i++) { for (int k = 0; k < array[i].length; k++) { total = total + array[i][k]; } } return total; } ``` The code above is to work out the total sum for all the numbers in the two dimensional array however I am trying to work out to the total for each individual row for the array. ``` public static int[] rowSums(int[][] array) { } ``` I am very unsure on what to do for the code to work out the 2D array for each row.<issue_comment>username_1: If you are using Java 8 you can do it in the following way: ``` int[] ar = Arrays.stream(new int[][]{{1,2},{3,5}}) // source .mapToInt(arr -> IntStream.of(arr).sum()) // sum inner array .toArray(); // back to int[] System.out.println(Arrays.toString(ar)); // print the array ``` Without stream: ``` int[][] arr = {{1,2},{3,5}}; // create a array that stores the total of each inner array int[] total = new int[arr.length]; // first loop for outer array for (int i = 0; i < arr.length; i++) { // loop for inner array for (int k = 0; k < arr[i].length; k++) { // since default value of total[i] is 0, we can directly use += total[i] += arr[i][k]; } } // print the array System.out.println(Arrays.toString(total)); ``` Upvotes: 2 <issue_comment>username_2: Did you mean something like this : ``` public static int[] sum(int[][] array) { //create an array of size array.length int[] result = new int[array.length]; int total; //Loop over the first dimension for (int i = 0; i < array.length; i++) { total = 0;//Make sure to re-initialize the total in each iteration //For each row calculate the sum and store it in total for (int k = 0; k < array[i].length; k++) { total += array[i][k]; } //When you finish put the result of each row in result[i] result[i] = total; } return result; } ``` Example ``` System.out.println( Arrays.toString(sum(new int[][]{{1, 1, 1}, {2, 2}, {3, 3}})) ); ``` Outputs ``` [3, 4, 6] ``` Upvotes: 3 <issue_comment>username_3: Try this with slight modification with your code ``` public static int[] sum(int[][] array) { List rowTotal = new ArrayList<>(); int total = 0; for (int i = 0; i < array.length; i++) { for (int k = 0; k < array[i].length; k++) { total = total + array[i][k]; } rowTotal.add(total); total = 0; } return rowTotal.stream().mapToInt(i->i).toArray(); } ``` Upvotes: 1 <issue_comment>username_4: ``` public static List sum(int[][] array) { List total = new ArrayList<>(); for (int i = 0; i < array.length; i++) { int sum = 0; for (int k = 0; k < array[i].length; k++) { sum = sum + array[i][k]; } total.add(sum); } return total; } ``` In case if you need to use int[] after getting result, ``` List total = sum(ar); Integer[] result = total.toArray(new Integer[0]); ``` Use result object for further use. Upvotes: 1 <issue_comment>username_5: Based on @YFC\_L answer, but using the enhanced loop: ``` public static int[] sum2(int[][] array) { //create an array of size based of how many rows the array has int[] result = new int[array.length]; int rowIndex = 0; //Loop over each row for (int[] row : array) { int total = 0; //Calculate the sum of the row for (int n : row) { total += n; } //Store the sum in the result result[rowIndex++] = total; } return result; } ``` Also, this method can be tested in the exatelly same way: ``` public static void main(String[] args) { System.out.println( Arrays.toString(sum2(new int[][]{{1, 1, 1}, {2, 2}, {3, 3}})) ); } ``` and, of course the output is the same: ``` [3, 4, 6] ``` Upvotes: 2
2018/03/21
1,193
3,797
<issue_start>username_0: I see a lot of npm modules that require a build/compilation step have a `dist/` folder in their repo. Do the authors run the build step before committing manually or is this automated on commit, if so how? Example repos: <https://github.com/se-panfilov/vue-notifications> <https://github.com/ratiw/vuetable-2> <https://github.com/hilongjw/vue-progressbar> Is it common to run the build step manually before a commit? How is this enforced?<issue_comment>username_1: If you are using Java 8 you can do it in the following way: ``` int[] ar = Arrays.stream(new int[][]{{1,2},{3,5}}) // source .mapToInt(arr -> IntStream.of(arr).sum()) // sum inner array .toArray(); // back to int[] System.out.println(Arrays.toString(ar)); // print the array ``` Without stream: ``` int[][] arr = {{1,2},{3,5}}; // create a array that stores the total of each inner array int[] total = new int[arr.length]; // first loop for outer array for (int i = 0; i < arr.length; i++) { // loop for inner array for (int k = 0; k < arr[i].length; k++) { // since default value of total[i] is 0, we can directly use += total[i] += arr[i][k]; } } // print the array System.out.println(Arrays.toString(total)); ``` Upvotes: 2 <issue_comment>username_2: Did you mean something like this : ``` public static int[] sum(int[][] array) { //create an array of size array.length int[] result = new int[array.length]; int total; //Loop over the first dimension for (int i = 0; i < array.length; i++) { total = 0;//Make sure to re-initialize the total in each iteration //For each row calculate the sum and store it in total for (int k = 0; k < array[i].length; k++) { total += array[i][k]; } //When you finish put the result of each row in result[i] result[i] = total; } return result; } ``` Example ``` System.out.println( Arrays.toString(sum(new int[][]{{1, 1, 1}, {2, 2}, {3, 3}})) ); ``` Outputs ``` [3, 4, 6] ``` Upvotes: 3 <issue_comment>username_3: Try this with slight modification with your code ``` public static int[] sum(int[][] array) { List rowTotal = new ArrayList<>(); int total = 0; for (int i = 0; i < array.length; i++) { for (int k = 0; k < array[i].length; k++) { total = total + array[i][k]; } rowTotal.add(total); total = 0; } return rowTotal.stream().mapToInt(i->i).toArray(); } ``` Upvotes: 1 <issue_comment>username_4: ``` public static List sum(int[][] array) { List total = new ArrayList<>(); for (int i = 0; i < array.length; i++) { int sum = 0; for (int k = 0; k < array[i].length; k++) { sum = sum + array[i][k]; } total.add(sum); } return total; } ``` In case if you need to use int[] after getting result, ``` List total = sum(ar); Integer[] result = total.toArray(new Integer[0]); ``` Use result object for further use. Upvotes: 1 <issue_comment>username_5: Based on @YFC\_L answer, but using the enhanced loop: ``` public static int[] sum2(int[][] array) { //create an array of size based of how many rows the array has int[] result = new int[array.length]; int rowIndex = 0; //Loop over each row for (int[] row : array) { int total = 0; //Calculate the sum of the row for (int n : row) { total += n; } //Store the sum in the result result[rowIndex++] = total; } return result; } ``` Also, this method can be tested in the exatelly same way: ``` public static void main(String[] args) { System.out.println( Arrays.toString(sum2(new int[][]{{1, 1, 1}, {2, 2}, {3, 3}})) ); } ``` and, of course the output is the same: ``` [3, 4, 6] ``` Upvotes: 2
2018/03/21
1,161
3,773
<issue_start>username_0: I am using my own customrenderer for Webviews it has always worked but since I upgraded Xamarin Forms nuget package to version 2.5 it crashes because it seems like the member method OnElementChanged is called with null Native control and null thisActivity. any idea how to fix it? this is the error I get: ``` Unhandled Exception: System.ArgumentNullException: Value cannot be null. Parameter name: thisActivity ```<issue_comment>username_1: If you are using Java 8 you can do it in the following way: ``` int[] ar = Arrays.stream(new int[][]{{1,2},{3,5}}) // source .mapToInt(arr -> IntStream.of(arr).sum()) // sum inner array .toArray(); // back to int[] System.out.println(Arrays.toString(ar)); // print the array ``` Without stream: ``` int[][] arr = {{1,2},{3,5}}; // create a array that stores the total of each inner array int[] total = new int[arr.length]; // first loop for outer array for (int i = 0; i < arr.length; i++) { // loop for inner array for (int k = 0; k < arr[i].length; k++) { // since default value of total[i] is 0, we can directly use += total[i] += arr[i][k]; } } // print the array System.out.println(Arrays.toString(total)); ``` Upvotes: 2 <issue_comment>username_2: Did you mean something like this : ``` public static int[] sum(int[][] array) { //create an array of size array.length int[] result = new int[array.length]; int total; //Loop over the first dimension for (int i = 0; i < array.length; i++) { total = 0;//Make sure to re-initialize the total in each iteration //For each row calculate the sum and store it in total for (int k = 0; k < array[i].length; k++) { total += array[i][k]; } //When you finish put the result of each row in result[i] result[i] = total; } return result; } ``` Example ``` System.out.println( Arrays.toString(sum(new int[][]{{1, 1, 1}, {2, 2}, {3, 3}})) ); ``` Outputs ``` [3, 4, 6] ``` Upvotes: 3 <issue_comment>username_3: Try this with slight modification with your code ``` public static int[] sum(int[][] array) { List rowTotal = new ArrayList<>(); int total = 0; for (int i = 0; i < array.length; i++) { for (int k = 0; k < array[i].length; k++) { total = total + array[i][k]; } rowTotal.add(total); total = 0; } return rowTotal.stream().mapToInt(i->i).toArray(); } ``` Upvotes: 1 <issue_comment>username_4: ``` public static List sum(int[][] array) { List total = new ArrayList<>(); for (int i = 0; i < array.length; i++) { int sum = 0; for (int k = 0; k < array[i].length; k++) { sum = sum + array[i][k]; } total.add(sum); } return total; } ``` In case if you need to use int[] after getting result, ``` List total = sum(ar); Integer[] result = total.toArray(new Integer[0]); ``` Use result object for further use. Upvotes: 1 <issue_comment>username_5: Based on @YFC\_L answer, but using the enhanced loop: ``` public static int[] sum2(int[][] array) { //create an array of size based of how many rows the array has int[] result = new int[array.length]; int rowIndex = 0; //Loop over each row for (int[] row : array) { int total = 0; //Calculate the sum of the row for (int n : row) { total += n; } //Store the sum in the result result[rowIndex++] = total; } return result; } ``` Also, this method can be tested in the exatelly same way: ``` public static void main(String[] args) { System.out.println( Arrays.toString(sum2(new int[][]{{1, 1, 1}, {2, 2}, {3, 3}})) ); } ``` and, of course the output is the same: ``` [3, 4, 6] ``` Upvotes: 2
2018/03/21
877
3,422
<issue_start>username_0: I'm building an Android media player application that I intend to use to play media (videos, pictures, etc.) on a TV while connected via an HDMI cable. I want to have the media player app pause when the TV's power status is OFF and want it to play when the TV is turned ON. How do I detect the TV's power status within my Android application when my Android device is connected to the TV via HDMI? Both the TV and the Android device have support for HDMI-CEC. The device in question is an ODROID C2. I've seen this functionality on the KODI Android application which has a feature to pause the video when the HDMI-CEC status is OFF, I'm looking to implement this within my app as well. Any help is appreciated. Thanks in advance! EDIT: Progress below I tried reading the status of the HDMI connection from within this file `/sys/devices/virtual/switch/hdmi/state`. However, this file holds `int` `1` no matter whether the power status of the connected screen / TV is ON or OFF. 2nd Progress update I'm still working on this. Will not give up, and once I'm done I will surely post the answer here.<issue_comment>username_1: In Some TV's, You need to monitor that (**sys/class/amhdmitx/amhdmitx0/hpd\_state**) folder for changes by 500 ms Interval. because it'll change from 1 to 0 and again from 0 to 1 within 1 seconds. Upvotes: 1 <issue_comment>username_2: You can listen for changes in HDMI status (0 for unplugged and 1 for plugged) by registering for **ACTION\_HDMI\_AUDIO\_PLUG**. It reports with status 0 when tv is switched off, switches to any other display medium or HDMI is removed. To read into its technicality, you can check out how hot plug detection works in HDMI. Overall, your app can at all times monitor whether the display can currently play your content or not. I have myself implemented this in a solution (on X96 mini android box & amazon fire-stick) where I needed to ensure that the content was actually being played because it included paid content. Also, I have attached the sample code file. **Note**: This solution will only work when android device is HDMI source not sink! Here's the documentation link too- <https://developer.android.com/reference/android/media/AudioManager#ACTION_HDMI_AUDIO_PLUG> ``` private BroadcastReceiver eventReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // pause video String action = intent.getAction(); switch (action) { case ACTION_HDMI_AUDIO_PLUG : // EXTRA_AUDIO_PLUG_STATE: 0 - UNPLUG, 1 - PLUG Toast.makeText(getApplicationContext(),"HDMI PLUGGED OR UNPLUGGED",Toast.LENGTH_LONG).show(); Log.d("MainActivity", "ACTION_HDMI_AUDIO_PLUG " + intent.getIntExtra(EXTRA_AUDIO_PLUG_STATE, -1)); ((TextView)(findViewById(R.id.textView))).setText(((TextView)(findViewById(R.id.textView))).getText().toString().concat("At "+System.nanoTime()+": "+intent.getIntExtra(EXTRA_AUDIO_PLUG_STATE, -1) +"\n")); break; } } }; @Override protected void onPause() { super.onPause(); unregisterReceiver(eventReceiver); } @Override protected void onResume() { super.onResume(); IntentFilter filter = new IntentFilter(); filter.addAction(ACTION_HDMI_AUDIO_PLUG); registerReceiver(eventReceiver, filter); } ``` Upvotes: 2
2018/03/21
2,857
9,212
<issue_start>username_0: So I am trying to remove all parentheses and the content of them on this wikipedia page. I try using `.replace(/(.*)/g, '')`. The result of that is an empty string. So I tried not using the `g` part. I then lost a big part of the start of the text. I also tried replacing the parentheses with a word, for example Red, the result of that was: > > RedRed RedRed RedRed RedRed RedRed RedRed > > > I was wondering if any of you knew what is happening here and if you have a solution. Here is the text: > > Norway ( ( listen); Norwegian: Norge (Bokmål) or Noreg (Nynorsk); Northern >Sami: Norga), officially the Kingdom of Norway, is a sovereign state and >unitary monarchy whose territory comprises the western portion of the > Scandinavian Peninsula plus the remote island of Jan Mayen and the > archipelago of Svalbard. The Antarctic Peter I Island and the sub-Antarctic > Bouvet Island are dependent territories and thus not considered part of the > Kingdom. Norway also lays claim to a section of Antarctica known as Queen > Maud Land. Until 1814, the kingdom included the Faroe Islands, Greenland, and > Iceland. It also included Bohuslän until 1658, Jämtland and Härjedalen until > 1645, Shetland and Orkney until 1468, and the Hebrides and Isle of Man until > 1266. Norway has a total area of 385,252 square kilometres (148,747 sq mi) > and a population of 5,258,317 (as of January 2017). The country shares a long > eastern border with Sweden (1,619 km or 1,006 mi long). Norway is bordered by > Finland and Russia to the north-east, and the Skagerrak strait to the south, > with Denmark on the other side. Norway has an extensive coastline, facing the > North Atlantic Ocean and the Barents Sea. King Harald V of the Dano-German > House of Glücksburg is the current King of Norway. <NAME> became Prime > Minister in 2013, and was reelected in September, 2017. <NAME> replaced > <NAME> who was the Prime Minister between 2000-2001 and 2005-2013. > A constitutional monarchy, Norway divides state power between the Parliament, > the Cabinet and the Supreme Court, as determined by the 1814 Constitution. > The kingdom was established as a merger of a large number of petty kingdoms. > By the traditional count from the year 872, the kingdom has existed > continuously for 1,145 years, and the list of Norwegian monarchs includes > over sixty kings and earls. Norway has both administrative and political > subdivisions on two levels: counties and municipalities. The Sámi people have > a certain amount of self-determination and influence over traditional > territories through the Sámi Parliament and the Finnmark Act. Norway > maintains close ties with both the European Union and the United States. > Norway is a founding member of the United Nations, NATO, the European Free > Trade Association, the Council of Europe, the Antarctic Treaty, and the > Nordic Council; a member of the European Economic Area, the WTO, and the > OECD; and a part of the Schengen Area. Norway maintains Nordic welfare model > with universal health care and a comprehensive social security system, and > Norwegian Society's values are rooted in egalitarian ideals. Defined as a The > XXI century socialism, , the Norwegian state owns key industrial sectors such > as oil (Statoil) or hydropower (Statkraft), having extensive reserves of > petroleum, natural gas, minerals, lumber, seafood and fresh water. The > petroleum industry accounts for around a quarter of the country's gross > domestic product (GDP). > > ><issue_comment>username_1: This one removes all " (.....)" from the String. ``` /([^\(\)]*?)(\s*\([^\(\)]*?\))([^\(\)]*?)/$1$3/g ``` * **([^()]\*?)**: Text without the signs '(' and ')' as the first Group ($1) * **(\s\*([^()]\*?))**: Text that can start with a Space (or something like that) (\s), then a '(' than Text without '(' and ')' and then a ')' as the second group ($2) * **([^()]\*?)**: Text without the signs '(' and ')' as the thirdGroup ($3) * **[^()]**: All Signs except '(' and ')' * **[^()]\*?**: Zero or more signs except '(' and ')' Upvotes: 0 <issue_comment>username_2: You have to remove the parenthesis from the inside to the outside, by matching parenthesis pairs which don't contain any other parenthesis and then repeat the process until there are no pairs anymore: ```js function deParenthesise(text) { var replaced = text; var before = replaced; do { before = replaced; replaced = replaced.replace(/\([^()]*\)/g, ''); } while (replaced != before); return replaced; } var text = "Norway ( ( listen); Norwegian: Norge (Bokmål) or Noreg (Nynorsk); Northern >Sami: Norga), officially the Kingdom of Norway, is a sovereign state and >unitary monarchy whose territory comprises the western portion of the Scandinavian Peninsula plus the remote island of <NAME> and the archipelago of Svalbard. The Antarctic Peter I Island and the sub-Antarctic Bouvet Island are dependent territories and thus not considered part of the Kingdom. Norway also lays claim to a section of Antarctica known as Queen Maud Land. Until 1814, the kingdom included the Faroe Islands, Greenland, and > Iceland. It also included Bohuslän until 1658, Jämtland and Härjedalen until > 1645, Shetland and Orkney until 1468, and the Hebrides and Isle of Man until > 1266. Norway has a total area of 385,252 square kilometres (148,747 sq mi) and a population of 5,258,317 (as of January 2017). The country shares a long > eastern border with Sweden (1,619 km or 1,006 mi long). Norway is bordered by > Finland and Russia to the north-east, and the Skagerrak strait to the south, > with Denmark on the other side. Norway has an extensive coastline, facing the > North Atlantic Ocean and the Barents Sea. King Harald V of the Dano-German House of Glücksburg is the current King of Norway. <NAME> became Prime > Minister in 2013, and was reelected in September, 2017. <NAME> replaced > <NAME> who was the Prime Minister between 2000-2001 and 2005-2013. > A constitutional monarchy, Norway divides state power between the Parliament, > the Cabinet and the Supreme Court, as determined by the 1814 Constitution. The kingdom was established as a merger of a large number of petty kingdoms. > By the traditional count from the year 872, the kingdom has existed continuously for 1,145 years, and the list of Norwegian monarchs includes over sixty kings and earls. Norway has both administrative and political subdivisions on two levels: counties and municipalities. The Sámi people have > a certain amount of self-determination and influence over traditional territories through the Sámi Parliament and the Finnmark Act. Norway maintains close ties with both the European Union and the United States. Norway is a founding member of the United Nations, NATO, the European Free Trade Association, the Council of Europe, the Antarctic Treaty, and the Nordic Council; a member of the European Economic Area, the WTO, and the OECD; and a part of the Schengen Area. Norway maintains Nordic welfare model with universal health care and a comprehensive social security system, and Norwegian Society's values are rooted in egalitarian ideals. Defined as a The > XXI century socialism, , the Norwegian state owns key industrial sectors such > as oil (Statoil) or hydropower (Statkraft), having extensive reserves of petroleum, natural gas, minerals, lumber, seafood and fresh water. The petroleum industry accounts for around a quarter of the country's gross domestic product (GDP)."; console.log(deParenthesise(text)); ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: Using regex, might be tricky for this, as you can have multiple levels of brackets,.. Like you do at the start. A simple pure Javascript solution though isn't too hard to do.. ```js const txt = `Norway ( ( listen); Norwegian: Norge (Bokmål) or Noreg (Nynorsk); Northern >Sami: Norga), officially the Kingdom of Norway, is a sovereign state and >unitary monarchy whose territory comprises the western portion of the Scandinavian Peninsula plus the remote island of Jan Mayen and the archipelago of Svalbard. The Antarctic Peter I Island and the sub-Antarctic Bouvet Island are dependent territories and thus not considered part of the Kingdom. Norway also lays claim to a section of Antarctica known as Queen Maud Land. Until 1814, the kingdom included the Faroe Islands, Greenland, and > Iceland. It also included Bohuslän until 1658, Jämtland and Härjedalen until > 1645, Shetland and Orkney until 1468, and the Hebrides and Isle of Man until > 1266. Norway has a total area of 385,252 square kilometres (148,747 sq mi) and a population of 5,258,317 (as of January 2017).`; function removeBrackets(txt) { const letters = Array.from(txt); const output = []; let bcount = 0; let pos = 0; while (pos < letters.length) { const letter = letters[pos]; if (letter === "(") bcount +=1; if (!bcount) output.push(letter); if (letter === ")") bcount -=1; pos += 1; } return output.join(""); } console.log(removeBrackets(txt)); ``` Upvotes: 1
2018/03/21
2,350
8,668
<issue_start>username_0: All the examples I've seen of the new Context API in React are in a single file, e.g. <https://github.com/wesbos/React-Context>. When I try to get it working across multiple files, I'm clearly missing something. I'm hoping to make a `GlobalConfiguration` component (the `MyProvider` below) create and manage the values in the context, ready for any child component (`MyConsumer` below) read from it. App.js ------ ``` render() { return ( ); } ``` provider.js ----------- ``` import React, { Component } from 'react'; const MyContext = React.createContext('test'); export default class MyProvider extends Component { render() { return ( {this.props.children} ); } } ``` consumer.js ----------- ``` import React, { Component } from 'react'; const MyContext = React.createContext('test'); export default class MyConsumer extends Component { render() { return ( {(context) => ( {context.state.somevalue} )} ); } } ``` Unfortunately that fails with this in the console: `consumer.js:12 Uncaught TypeError: Cannot read property 'somevalue' of undefined` Have I completely missed the point? Is there documentation or an example of how this works across multiple files?<issue_comment>username_1: Reading the source code of React-Context, they do ``` ``` and ``` {(context) => {context.state.age} } ``` So if you do ``` {this.props.children} ``` You should get `somevalue` like that ``` {(context) => {context.somevalue}} ``` EDIT What if you create a file called `myContext.js` with: ``` const MyContext = React.createContext('test'); export default MyContext; ``` and then import it like : `import MyContext form '/myContext';` Upvotes: 4 <issue_comment>username_2: As of right now, the two context you created in the files are not the same even thought the name is the same. You need to export the context that you created in one of the files, and use that through out. so something like this, in your provider.js file: ``` import React, { Component } from 'react'; const MyContext = React.createContext(); export const MyContext; export default class MyProvider extends Component { render() { return ( {this.props.children} ); } } ``` then in your consumer.js file ``` import MyContext from 'provider.js'; import React, { Component } from 'react'; export default class MyConsumer extends Component { render() { return ( {(context) => ( {context.somevalue} )} ); } } ``` Upvotes: 3 <issue_comment>username_3: [TLDR; Demo on CodeSandbox](https://codesandbox.io/s/xo679ykm1o) My current method of solving the same problem is to use the [Unstated library](https://github.com/jamiebuilds/unstated), which as a convenient wrapper around the React Context API. "Unstated" also provides dependency injection allow the creating of discrete instances of a container; which is handy for code reuse and testing. How to Wrap a React/Unstated-Context as a Service ================================================= The following skeleton API Service holds state properties such as `loggedIn`, as well as two service methods: `login()` and `logout()`. These props and methods are now available throughout the app with a single import in each file that needs the context. For example: ### Api.js ```jsx import React from "react"; // Import helpers from Unstated import { Provider, Subscribe, Container } from "unstated"; // APIContainer holds shared/global state and methods class APIContainer extends Container { constructor() { super(); // Shared props this.state = { loggedIn: false }; } // Shared login method async login() { console.log("Logging in"); this.setState({ loggedIn: true }); } // Shared logout method async logout() { console.log("Logging out"); this.setState({ loggedIn: false }); } } // Instantiate the API Container const instance = new APIContainer(); // Wrap the Provider const ApiProvider = props => { return {props.children}; }; // Wrap the Subscriber const ApiSubscribe = props => { return {props.children}; }; // Export wrapped Provider and Subscriber export default { Provider: ApiProvider, Subscribe: ApiSubscribe } ``` App.js ------ Now the `Api.js` module can be used as global provide in `App.js`: ```jsx import React from "React"; import { render } from "react-dom"; import Routes from "./Routes"; import Api from "./Api"; class App extends React.Component { render() { return ( ); } } render(, document.getElementById("root")); ``` Pages/Home.js: -------------- Finally, `Api.js` can subscribe to the state of the API from deep within the React tree. ```jsx import React from "react"; import Api from "../Api"; const Home = () => { return ( {api => ( Home ===== ``` api.state.loggedIn = {api.state.loggedIn ? " true" : " false"} ``` api.login()}>Login api.logout()}>Logout )} ); }; export default Home; ``` Try the CodeSandbox demo here: <https://codesandbox.io/s/wqpr1o6w15> Hope that helps! PS: Someone bash me on the head quick if I'm doing this the wrong way. I'd love to learn different/better approaches. - Thanks! Upvotes: 1 <issue_comment>username_4: I think the problem that you are running into is that you are creating two different contexts, and trying to use them as one. It is the `Context` created by `React.createContext` that links `Provider` and `Consumer`. Make a single file (I'll call it `configContext.js`) ### `configContext.js` ```jsx import React, { Component, createContext } from "react"; // Provider and Consumer are connected through their "parent" context const { Provider, Consumer } = createContext(); // Provider will be exported wrapped in ConfigProvider component. class ConfigProvider extends Component { state = { userLoggedIn: false, // Mock login profile: { // Mock user data username: "Morgan", image: "https://morganfillman.space/200/200", bio: "I'm Mogran—so... yeah." }, toggleLogin: () => { const setTo = !this.state.userLoggedIn; this.setState({ userLoggedIn: setTo }); } }; render() { return ( {this.props.children} ); } } export { ConfigProvider }; // I make this default since it will probably be exported most often. export default Consumer; ``` ### `index.js` ```jsx ... // We only import the ConfigProvider, not the Context, Provider, or Consumer. import { ConfigProvider } from "./configContext"; import Header from "./Header"; import Profile from "./Profile"; import "./styles.css"; function App() { return ( ... ); } ... ``` ### `Header.js` ```jsx import React from 'react' import LoginBtn from './LoginBtn' ... // a couple of styles const Header = props => { return ( ... // Opening tag, etc. // LoginBtn has access to Context data, see file. ... // etc. export default Header ``` `LoginBtn.js` ------------- ```jsx import React from "react"; import Consumer from "./configContext"; const LoginBtn = props => { return ( {ctx => { return ( ctx.toggleLogin()}> {ctx.userLoggedIn ? "Logout" : "Login"} ); }} ); }; export default LoginBtn; ``` ### `Profile.js` ```jsx import React, { Fragment } from "react"; import Consumer from "./configContext"; // Always from that same file. const UserProfile = props => {...}; // Dumb component const Welcome = props => {...}; // Dumb component const Profile = props => { return ( ... {ctx.userLoggedIn ? ( ) : ()} ... ... ``` Upvotes: 7 [selected_answer]<issue_comment>username_5: I'm gonna throw my solution into the pot - it was inspired by @username_1 and simply just renames the exports into something that makes sense in my head. ``` import React, { Component } from 'react' import Blockchain from './cloudComputing/Blockchain' const { Provider, Consumer: ContextConsumer } = React.createContext() class ContextProvider extends Component { constructor(props) { super(props) this.state = { blockchain: new Blockchain(), } } render() { return ( {this.props.children} ) } } module.exports = { ContextConsumer, ContextProvider } ``` Now it's easy to implement a `ContextConsumer` into any component ``` ... import { ContextConsumer } from '../Context' ... export default class MyComponent extends PureComponent { ... render() { return ( {context => { return ( {map(context.blockchain.chain, block => ( ))} ) }} ) } ``` **I'm SO done with redux!** Upvotes: 2
2018/03/21
1,034
3,417
<issue_start>username_0: I am wondering whether it is possible to get the angular multi-providers from (ideally) all ancestors. Lets say that I have a `INJECTION_TOKEN` `X` and I have a component structure like this: ``` ``` `comp-a` providers: `providers: {provide: X, useValue: "A", multi: true}` `comp-b` providers: `providers: {provide: X, useValue: "B", multi: true}` Is there a way how to get `["A", "B"]` in `comp-c` when I use Dependency injection like: ``` constructor(@Inject(X) obtainedArray:TypeOfX[]) { console.log(obtainedArray.length); //Expected to be 2 } ``` I have tried to use this provider in `comp-b` but it is throwing a cyclic DI expection: ``` providers:[ {provide: X, useExisting: X, multi: true} {provide: X, useValue: "B", multi: true} ] ```<issue_comment>username_1: No, you can't do what you are trying to do with dependency injection, as far as I know. When you provide something in a component, it automatically hides previous providers with the same token. This is the way it is intended to work. To achieve what you need, the only solution I can think of is to pass the providers as `inputs`. I mean, `comp-a` declares a provider. `comp-b` also does it, but accepts an `input` containing a provider or array of providers. Then `comp-b` can add its own provider to the array and pass it as an input to `comp-c`. I do not understand why exactly you want this, though ... Upvotes: 0 <issue_comment>username_2: As the following article states: * [What you always wanted to know about Angular Dependency Injection tree](https://blog.angularindepth.com/angular-dependency-injection-and-tree-shakeable-tokens-4588a8f70d5d) Angular stores providers on element by using **prototypical inheritance**. So, never mind whether you use `multi` or not you will get the following object that contains all providers on current element: [![enter image description here](https://i.stack.imgur.com/5eXjn.png)](https://i.stack.imgur.com/5eXjn.png) As you can see all providers are here, but since angular just [uses square brackets](https://github.com/angular/angular/blob/ce63dc6f954bcacd86f7ee0c401c1824f519b794/packages/core/src/view/provider.ts#L378-L387) to get provider from element you will get only nearest provider. To workaround this you can use addition token that uses factory to collect all parent providers: ```typescript import { Component, VERSION, InjectionToken, Inject, SkipSelf, Optional } from '@angular/core'; @Component({ selector: 'my-app', template: ` ` }) export class AppComponent { } const X = new InjectionToken('X'); const XArray = new InjectionToken('XArray'); const XArrayProvider = { provide: XArray, useFactory: XFactory, deps: [X, [new SkipSelf(), new Optional(), XArray]] }; export function XFactory(x: any, arr: any[]) { return arr ? [x, ...arr] : [x]; } @Component({ selector: 'comp-a', template: ``, providers: [ { provide: X, useValue: "A" }, XArrayProvider ] }) export class CompA { } @Component({ selector: 'comp-b', template: ``, providers: [ { provide: X, useValue: "B" }, XArrayProvider ] }) export class CompB { } @Component({ selector: 'comp-c', template: `{{ tokens }}` }) export class CompC { constructor( @Inject(XArray) public tokens: any[]) { } } ``` **[Ng-run Example](https://ng-run.com/edit/IpRjmtlg7posK49fa1rc?layout=1)** Upvotes: 5 [selected_answer]
2018/03/21
492
1,709
<issue_start>username_0: I was trying to get the config for one of the kafka clusters we have. After doing a config change through puppet, I want to know if kafka has reloaded the config, or if we need to restart the service for that. I have tried with `./kafka-configs.sh --describe --zookeeper my-zookeeper:2181 --entity-type brokers` but I only have empty output. I have also tried to find for the config browsing inside the zookeepers but i have found nothing. Is there any way to retrieve which config is being used?<issue_comment>username_1: as suggested @LijuJohn i found the config in the server.log file. Thanks a lot!! Upvotes: 3 [selected_answer]<issue_comment>username_2: Have you tried with parameter `--entity-name 0` where 0 is the id of the broker? This is required at least for my cluster. Upvotes: 0 <issue_comment>username_3: Since Kafka 2.5.0 (see issue [here](https://issues.apache.org/jira/browse/KAFKA-9040)), you can now specify the `--all` flag to list all configs (not just the dynamic ones) when using `./kafka-configs.sh` Upvotes: 1 <issue_comment>username_4: Here's full working command to list all configs for the broker with id=1: ``` ./bin/kafka-configs.sh --bootstrap-server :9092 --entity-type brokers --entity-name 1 --all --describe ``` Upvotes: 4 <issue_comment>username_5: On CentOS7, kafka version:3.3.2 Should be able to find all the configurations via: ```bash bin/kafka-configs.sh --describe --bootstrap-server :9092 --entity-type brokers --entity-name --all #example: bin/kafka-configs.sh --describe --bootstrap-server localhost:9092 --entity-type brokers --entity-name 0 --all ``` Note: Both and could be found in `config/server.properties` Upvotes: 0
2018/03/21
1,195
3,377
<issue_start>username_0: I wrote a serial program to generate 2 random matrices, multiply them and display the result. I wrote functions for each of the tasks, i.e. generating random matrix, multiplying the matrices and displaying the results. I cannot figure out why both the generated matrices are the same. ``` #include #include #include int \*\*matrix\_generator(int row,int col); int \*\*multiply\_matrices(int \*\*matrix\_A,int \*\*matrix\_B,int rowsA, int colsA,int rowsB,int colsB); void display\_result(int \*\*matrix,int cols,int rows); void display\_matrix(int \*\*matrixA,int cols,int rows); void main() { int \*\*matrix\_A,\*\*matrix\_B,\*\*matrix\_result,i,j,k,tid,rowsA,colsA,rowsB,colsB; printf("Enter the dimensions of Matrix A:\n"); scanf("%d%d",&rowsA,&colsA); printf("Enter the dimensions of Matrix B:\n"); scanf("%d%d",&rowsB,&colsB); if(colsA==rowsB) { matrix\_A = matrix\_generator(rowsA,colsA); matrix\_B = matrix\_generator(rowsB,colsB); matrix\_result = multiply\_matrices(matrix\_A,matrix\_B,rowsA,colsA,rowsB,colsB); printf("Matrix A:\n"); display\_matrix(matrix\_A,rowsA,colsA); printf("\n\n"); printf("Matrix B:\n"); display\_matrix(matrix\_B,rowsB,colsB); printf("\n\n"); display\_matrix(matrix\_result,rowsB,colsA); } else { printf("Check the dimensions of the matrices!\n"); exit(-1); } } int \*\*matrix\_generator(int row, int col) { int i, j, \*\*intMatrix; intMatrix = (int \*\*)malloc(sizeof(int \*) \* row); srand(time(0)); for (i = 0; i < row; i++) { intMatrix[i] = (int \*)malloc(sizeof(int \*) \* col); for (j = 0;j ``` OUTPUT: ``` Enter the dimensions of Matrix A: 4 4 Enter the dimensions of Matrix B: 4 4 Matrix A: 8 7 8 4 9 8 3 9 1 2 0 4 6 0 2 3 Matrix B: 8 7 8 4 9 8 3 9 1 2 0 4 6 0 2 3 159 128 93 139 201 133 114 147 50 23 22 34 68 46 54 41 ``` Can someone please help me understand where I'm going wrong? I have a pretty good idea that it's the matrix\_generator() function but cannot seem to figure out what's wrong. Also, It's only multiplying square matrices, if the dimensions are different, like 4X5 and 5X4, I get a segmentation fault.<issue_comment>username_1: As pointed out in the comments: You need to seed the rand() function only once. Do srand(time(0)); at the start of your main() function and remove it from elsewhere. Non-square matrices: There is a bug/typo in `multiply_matrices` The line ``` for (k = 0; k < colsA; k++) ``` should be ``` for (k = 0; k < rowsA; k++) ``` Upvotes: 1 <issue_comment>username_2: There are a few issues in your code: 1) You allocate memory incorrectly: in *multiply\_matrices* should be ``` resMatrix[i] = (int *)malloc(sizeof(int) * colsB); ``` and in *matrix\_generator* ``` intMatrix[i] = (int *)malloc(sizeof(int) * col); ``` 2) In *main* if you want to print *matrix\_result* call ``` display_matrix(matrix_result,rowsA,colsB); ``` Dimensions of [rowsA,colsA] x [rowsB,colsB] is **rowsA x colsB** 3) `malloc` returns pointer to **uninitialized memory**, so you should set `resMatrix` elements to zero before summing Content of 2-nd for loop in *multiply\_matrices* should be ``` resMatrix[i][j] = 0; for (k = 0; k < rowsB; k++) // CHANGED to rowsB resMatrix[i][j] = resMatrix[i][j] + matrix_A[i][k] * matrix_B[k][j]; ``` Upvotes: 3 [selected_answer]
2018/03/21
9,913
16,613
<issue_start>username_0: I have a query to get Stock-items with it's Balance and Its receiving Transactions cods with its quantity Ordered By date, And i Want to create a column which has only the proportion Balance of every RS Code according to First in First Out Principle. As An Example in the attached sample [![enter image description here](https://i.stack.imgur.com/RxRJr.png)](https://i.stack.imgur.com/RxRJr.png) we have StockItemId = (2222,2262,2263). and the expected result will be AS: [![enter image description here](https://i.stack.imgur.com/850ZF.png)](https://i.stack.imgur.com/850ZF.png) As in Pic the Balance of every row in RS\_Portion is depending on the Quantity of the Code and the sum of RS\_Portion of every item should equal the GlobalBalance of the same item. Here's my Code: ``` WITH M AS ( SELECT WHS.StockItemId,SUM(WHS.OnHandBalance) AS GlobalBalance FROM Warehouse.WarehouseStocks WHS GROUP BY WHS.StockItemId HAVING SUM(WHS.OnHandBalance) > 0 ) SELECT M.StockItemId,M.GlobalBalance,WHWorkOrderHeader.Code,WHWorkOrderDetails.Quantity,WHWorkOrderHeader.Date FROM M LEFT OUTER JOIN Warehouse.WHWorkOrderDetails ON WHWorkOrderDetails.StockItemId = M.StockItemId LEFT OUTER JOIN Warehouse.WHWorkOrderHeader ON WHWorkOrderHeader.ID = WHWorkOrderDetails.WHWorkOrderHeaderId WHERE WHWorkOrderHeader.Type = 'RS' AND M.StockItemId IN (2222,2262,2263) ORDER BY M.StockItemId ASC, WHWorkOrderHeader.Date DESC StockItemId,GlobalBalance,Code,Quantity,Date 2222,158.0000,RS-1-1543,1,2017-12-13 07:25:29.727 2222,158.0000,RS-1-1471,77,2017-08-22 14:53:11.880 2222,158.0000,RS-1-1470,77,2017-08-22 14:53:09.920 2222,158.0000,RS-1-1409,5,2017-02-16 13:41:00.740 2222,158.0000,RS-1-1409,5,2017-02-16 13:41:00.740 2222,158.0000,RS-1-1231,150,2015-09-29 15:41:45.000 2222,158.0000,RS-1-1226,100,2015-09-21 09:50:37.000 2262,23.0000,RS-14-371,20,2016-10-16 09:11:57.670 2262,23.0000,RS-14-334,30,2016-08-04 16:16:48.803 2262,23.0000,RS-14-303,18,2016-03-08 13:17:17.023 2262,23.0000,RS-14-301,70,2016-03-01 13:45:49.767 2262,23.0000,RS-14-298,30,2016-02-18 10:10:03.973 2262,23.0000,RS-14-286,2,2016-02-08 10:18:14.203 2262,23.0000,RS-14-285,30,2016-02-07 07:14:01.000 2262,23.0000,RS-14-280,3,2016-02-02 15:11:12.220 2262,23.0000,RS-14-276,1,2016-01-18 12:13:37.860 2262,23.0000,RS-14-274,2,2016-01-14 14:33:53.863 2262,23.0000,RS-14-273,1,2016-01-14 13:25:20.457 2262,23.0000,RS-14-271,1,2016-01-12 16:43:30.397 2262,23.0000,RS-14-270,4,2016-01-12 15:54:43.380 2262,23.0000,RS-14-268,1,2016-01-11 16:43:36.843 2262,23.0000,RS-14-267,1,2016-01-10 13:19:42.617 2262,23.0000,RS-14-266,1,2016-01-06 15:58:00.513 2262,23.0000,RS-14-261,1,2016-01-03 15:20:07.410 2262,23.0000,RS-14-259,6,2015-12-30 13:58:46.217 2262,23.0000,RS-14-258,1,2015-12-30 10:59:23.120 2262,23.0000,RS-14-250,3,2015-12-17 16:32:29.937 2262,23.0000,RS-14-245,1,2015-12-10 14:19:14.910 2262,23.0000,RS-14-240,1,2015-12-06 13:13:45.847 2262,23.0000,RS-14-236,1,2015-11-30 15:36:41.233 2262,23.0000,RS-14-233,4,2015-11-26 12:44:22.067 2262,23.0000,RS-14-228,1,2015-11-23 11:38:35.553 2262,23.0000,RS-14-226,1,2015-11-23 10:11:49.393 2262,23.0000,RS-14-223,2,2015-11-10 13:04:17.540 2263,25.0000,RS-14-301,60,2016-03-01 13:45:49.767 2263,25.0000,RS-14-298,20,2016-02-18 10:10:03.973 2263,25.0000,RS-14-295,1,2016-02-11 17:04:54.423 2263,25.0000,RS-14-294,1,2016-02-10 16:06:13.090 2263,25.0000,RS-14-293,2,2016-02-10 15:58:40.353 2263,25.0000,RS-14-276,1,2016-01-18 12:13:37.860 2263,25.0000,RS-14-274,2,2016-01-14 14:33:53.863 2263,25.0000,RS-14-271,1,2016-01-12 16:43:30.397 2263,25.0000,RS-14-268,1,2016-01-11 16:43:36.843 2263,25.0000,RS-14-267,1,2016-01-10 13:19:42.617 2263,25.0000,RS-14-266,1,2016-01-06 15:58:00.513 2263,25.0000,RS-14-259,6,2015-12-30 13:58:46.217 2263,25.0000,RS-14-258,1,2015-12-30 10:59:23.120 2263,25.0000,RS-14-250,3,2015-12-17 16:32:29.937 2263,25.0000,RS-14-240,1,2015-12-06 13:13:45.847 2263,25.0000,RS-14-236,1,2015-11-30 15:36:41.233 2263,25.0000,RS-14-223,2,2015-11-10 13:04:17.540 ```<issue_comment>username_1: Assuming you are using **SQL Server 2012 and up** you can do it using `FIRST_VALUE` and `SUM() OVER (PARTITION BY)` I don't quite understand why you're ignoring the codes `RS-1-1231` and `RS-1-1226`, they were prior to the code `RS-1-1409` ***UPDATE!!*** **[Demo](http://rextester.com/SAGR6482)** ``` DECLARE @Table TABLE (StockItemId int , GlobalBalance money,Code nvarchar(50), Quantity INT , [Date] DATETIME) INSERT INTO @Table VALUES ('2222', '158', 'RS-1-1543', '1', '2017-12-13 07:25:29.727') ,('2222', '158', 'RS-1-1471', '77', '2017-08-22 14:53:11.880') ,('2222', '158', 'RS-1-1470', '77', '2017-08-22 14:53:09.920') ,('2222', '158', 'RS-1-1409', '5', '2017-02-16 13:41:00.740') ,('2222', '158', 'RS-1-1409', '5', '2017-02-16 13:41:00.740') ,('2222', '158', 'RS-1-1231', '150', '2015-09-29 15:41:45.000') ,('2222', '158', 'RS-1-1226', '100', '2015-09-21 09:50:37.000') ,('2262', '23', 'RS-14-371', '20', '2016-10-16 09:11:57.670') ,('2262', '23', 'RS-14-334', '30', '2016-08-04 16:16:48.803') ,('2262', '23', 'RS-14-303', '18', '2016-03-08 13:17:17.023') ,('2262', '23', 'RS-14-301', '70', '2016-03-01 13:45:49.767') ,('2262', '23', 'RS-14-298', '30', '2016-02-18 10:10:03.973') ,('2262', '23', 'RS-14-286', '2', '2016-02-08 10:18:14.203') ,('2262', '23', 'RS-14-285', '30', '2016-02-07 07:14:01.000') ,('2262', '23', 'RS-14-280', '3', '2016-02-02 15:11:12.220') ,('2262', '23', 'RS-14-276', '1', '2016-01-18 12:13:37.860') ,('2262', '23', 'RS-14-274', '2', '2016-01-14 14:33:53.863') ,('2262', '23', 'RS-14-273', '1', '2016-01-14 13:25:20.457') ,('2262', '23', 'RS-14-271', '1', '2016-01-12 16:43:30.397') ,('2262', '23', 'RS-14-270', '4', '2016-01-12 15:54:43.380') ,('2262', '23', 'RS-14-268', '1', '2016-01-11 16:43:36.843') ,('2262', '23', 'RS-14-267', '1', '2016-01-10 13:19:42.617') ,('2262', '23', 'RS-14-266', '1', '2016-01-06 15:58:00.513') ,('2262', '23', 'RS-14-261', '1', '2016-01-03 15:20:07.410') ,('2262', '23', 'RS-14-259', '6', '2015-12-30 13:58:46.217') ,('2262', '23', 'RS-14-258', '1', '2015-12-30 10:59:23.120') ,('2262', '23', 'RS-14-250', '3', '2015-12-17 16:32:29.937') ,('2262', '23', 'RS-14-245', '1', '2015-12-10 14:19:14.910') ,('2262', '23', 'RS-14-240', '1', '2015-12-06 13:13:45.847') ,('2262', '23', 'RS-14-236', '1', '2015-11-30 15:36:41.233') ,('2262', '23', 'RS-14-233', '4', '2015-11-26 12:44:22.067') ,('2262', '23', 'RS-14-228', '1', '2015-11-23 11:38:35.553') ,('2262', '23', 'RS-14-226', '1', '2015-11-23 10:11:49.393') ,('2262', '23', 'RS-14-223', '2', '2015-11-10 13:04:17.540') ,('2263', '25', 'RS-14-301', '60', '2016-03-01 13:45:49.767') ,('2263', '25', 'RS-14-298', '20', '2016-02-18 10:10:03.973') ,('2263', '25', 'RS-14-295', '1', '2016-02-11 17:04:54.423') ,('2263', '25', 'RS-14-294', '1', '2016-02-10 16:06:13.090') ,('2263', '25', 'RS-14-293', '2', '2016-02-10 15:58:40.353') ,('2263', '25', 'RS-14-276', '1', '2016-01-18 12:13:37.860') ,('2263', '25', 'RS-14-274', '2', '2016-01-14 14:33:53.863') ,('2263', '25', 'RS-14-271', '1', '2016-01-12 16:43:30.397') ,('2263', '25', 'RS-14-268', '1', '2016-01-11 16:43:36.843') ,('2263', '25', 'RS-14-267', '1', '2016-01-10 13:19:42.617') ,('2263', '25', 'RS-14-266', '1', '2016-01-06 15:58:00.513') ,('2263', '25', 'RS-14-259', '6', '2015-12-30 13:58:46.217') ,('2263', '25', 'RS-14-258', '1', '2015-12-30 10:59:23.120') ,('2263', '25', 'RS-14-250', '3', '2015-12-17 16:32:29.937') ,('2263', '25', 'RS-14-240', '1', '2015-12-06 13:13:45.847') ,('2263', '25', 'RS-14-236', '1', '2015-11-30 15:36:41.233') ,('2263', '25', 'RS-14-223', '2', '2015-11-10 13:04:17.540') ;WITH Main as ( SELECT * , FIRST_VALUE (Quantity) OVER (PARTITION BY StockItemId ORDER BY [Date]) FirstQuantity, SUM(Quantity) OVER (PARTITION BY StockItemId) SumAllPerItem, GlobalBalance - SUM(Quantity) OVER (PARTITION BY StockItemId ORDER BY [Date] DESC ) DiffFromMOstRecent FROM @Table ) ,Results as ( SELECT StockItemId , GlobalBalance , Code , Quantity , [Date], DiffFromMOstRecent , ISNULL(LAG(DiffFromMOstRecent) OVER (PARTITION BY StockItemId ORDER BY [Date] DESC), DiffFromMOstRecent) PrevRunningSum ,CASE WHEN Quantity = FirstQuantity THEN GlobalBalance - SumAllPerItem + Quantity ELSE Quantity END RS_Portion FROM Main ) ,Final as ( SELECT StockItemId , GlobalBalance , Code , Quantity , [Date] ,CASE WHEN MAX(PrevRunningSum) OVER(PARTITION BY StockItemId) < 0 then Quantity + MAX(PrevRunningSum) OVER(PARTITION BY StockItemId) WHEN DiffFromMOstRecent < 0 THEN PrevRunningSum ELSE RS_Portion END RS_Portion FROM Results ) SELECT * FROM Final WHERE RS_Portion >= 0 ORDER BY StockItemId , [Date] Desc ``` Upvotes: 1 <issue_comment>username_2: Since you didn't provide any DDL, I generated sample data, but it's clearly equivalent to yours. I hope you will be able to modify it accordingly to your needs. Try this: ``` declare @x table (stockItemId int, globalBalance int, quantity int, [date] date) insert into @x values (1,158, 1,'2018-03-31'), (1,158, 77,'2018-03-30'), (1,158, 77,'2018-03-29'), (1,158, 5,'2018-03-28'), (1,158, 5,'2018-03-27'), (1,158, 150,'2018-03-26'), (1,158, 100,'2018-03-25'), (2,23, 20,'2018-03-31'), (2,23, 77,'2018-03-30'), (2,23, 77,'2018-03-29'), (2,23, 5,'2018-03-28'), (2,23, 5,'2018-03-27'), (2,23, 150,'2018-03-26'), (2,23, 100,'2018-03-25') select stockItemId, globalBalance, quantity, case when cumsum < 0 then quantity + cumSum else quantity end [RS_Portion] from ( select stockItemId, globalBalance, quantity, globalBalance - SUM(quantity) over (partition by stockitemid order by [date] desc rows between unbounded preceding and current row) [cumSum] from @x ) a --where [RS_Portion] > 0 - below is equivalent where (case when cumsum < 0 then quantity + cumSum else quantity end) > 0 ``` To understand this query you might need reading about window functions and cumulative sum in SQL using window functions. Upvotes: 1 <issue_comment>username_3: This will give you the output you have provided: ``` WITH DataSource AS ( SELECT * ,[GlobalBalance] - SUM([Quantity]) OVER (PARTITION BY [StockItemId], [GlobalBalance] ORDER BY [Date] DESC) AS [Dif] ,ROW_NUMBER() OVER (PARTITION BY [StockItemId], [GlobalBalance] ORDER BY [Date] DESC) [RecordID] FROM @DataSource ), DataSourceWithPrevDiff AS ( SELECT * ,LAG([Dif], 1, NULL) OVER (PARTITION BY [StockItemId], [GlobalBalance] ORDER BY [Date] DESC) AS [PrevDif] FROM DataSource ) SELECT [StockItemId] ,[GlobalBalance] ,[Date] ,[Code] ,[Quantity] ,CASE WHEN [Dif] > 0 THEN [Quantity] WHEN [RecordID] = 1 THEN [Quantity] + [Dif] WHEN [PrevDif] > 0 THEN [PrevDif] END AS [RS_Portion] FROM DataSourceWithPrevDiff WHERE [Dif] > 0 OR [PrevDif] > 0 OR [RecordID] = 1 ORDER BY [StockItemId] ,[Date] DESC; ``` [![enter image description here](https://i.stack.imgur.com/N4mjs.png)](https://i.stack.imgur.com/N4mjs.png) Of course you can split the query on parts. The idea is calculated the sum till the current row for each stoc item - balance pair. Also, we need to get the first item for each pair, too. Then in the final query we are showing the first item, the items where the sum till now is positive, or where the previous sum was positive. Here is the full working example: ``` DECLARE @DataSource TABLE ( [StockItemId] INT ,[GlobalBalance] INT ,[Code] VARCHAR(32) ,[Quantity] INT ,[Date] DATETIME2 ); INSERT INTO @DataSource ([StockItemId], [GlobalBalance], [Code], [Quantity], [Date]) VALUES ('2222', '158', 'RS-1-1543', '1', '2017-12-13 07:25:29.727') ,('2222', '158', 'RS-1-1471', '77', '2017-08-22 14:53:11.880') ,('2222', '158', 'RS-1-1470', '77', '2017-08-22 14:53:09.920') ,('2222', '158', 'RS-1-1409', '5', '2017-02-16 13:41:00.740') ,('2222', '158', 'RS-1-1409', '5', '2017-02-16 13:41:00.740') ,('2222', '158', 'RS-1-1231', '150', '2015-09-29 15:41:45.000') ,('2222', '158', 'RS-1-1226', '100', '2015-09-21 09:50:37.000') ,('2262', '23', 'RS-14-371', '20', '2016-10-16 09:11:57.670') ,('2262', '23', 'RS-14-334', '30', '2016-08-04 16:16:48.803') ,('2262', '23', 'RS-14-303', '18', '2016-03-08 13:17:17.023') ,('2262', '23', 'RS-14-301', '70', '2016-03-01 13:45:49.767') ,('2262', '23', 'RS-14-298', '30', '2016-02-18 10:10:03.973') ,('2262', '23', 'RS-14-286', '2', '2016-02-08 10:18:14.203') ,('2262', '23', 'RS-14-285', '30', '2016-02-07 07:14:01.000') ,('2262', '23', 'RS-14-280', '3', '2016-02-02 15:11:12.220') ,('2262', '23', 'RS-14-276', '1', '2016-01-18 12:13:37.860') ,('2262', '23', 'RS-14-274', '2', '2016-01-14 14:33:53.863') ,('2262', '23', 'RS-14-273', '1', '2016-01-14 13:25:20.457') ,('2262', '23', 'RS-14-271', '1', '2016-01-12 16:43:30.397') ,('2262', '23', 'RS-14-270', '4', '2016-01-12 15:54:43.380') ,('2262', '23', 'RS-14-268', '1', '2016-01-11 16:43:36.843') ,('2262', '23', 'RS-14-267', '1', '2016-01-10 13:19:42.617') ,('2262', '23', 'RS-14-266', '1', '2016-01-06 15:58:00.513') ,('2262', '23', 'RS-14-261', '1', '2016-01-03 15:20:07.410') ,('2262', '23', 'RS-14-259', '6', '2015-12-30 13:58:46.217') ,('2262', '23', 'RS-14-258', '1', '2015-12-30 10:59:23.120') ,('2262', '23', 'RS-14-250', '3', '2015-12-17 16:32:29.937') ,('2262', '23', 'RS-14-245', '1', '2015-12-10 14:19:14.910') ,('2262', '23', 'RS-14-240', '1', '2015-12-06 13:13:45.847') ,('2262', '23', 'RS-14-236', '1', '2015-11-30 15:36:41.233') ,('2262', '23', 'RS-14-233', '4', '2015-11-26 12:44:22.067') ,('2262', '23', 'RS-14-228', '1', '2015-11-23 11:38:35.553') ,('2262', '23', 'RS-14-226', '1', '2015-11-23 10:11:49.393') ,('2262', '23', 'RS-14-223', '2', '2015-11-10 13:04:17.540') ,('2263', '25', 'RS-14-301', '60', '2016-03-01 13:45:49.767') ,('2263', '25', 'RS-14-298', '20', '2016-02-18 10:10:03.973') ,('2263', '25', 'RS-14-295', '1', '2016-02-11 17:04:54.423') ,('2263', '25', 'RS-14-294', '1', '2016-02-10 16:06:13.090') ,('2263', '25', 'RS-14-293', '2', '2016-02-10 15:58:40.353') ,('2263', '25', 'RS-14-276', '1', '2016-01-18 12:13:37.860') ,('2263', '25', 'RS-14-274', '2', '2016-01-14 14:33:53.863') ,('2263', '25', 'RS-14-271', '1', '2016-01-12 16:43:30.397') ,('2263', '25', 'RS-14-268', '1', '2016-01-11 16:43:36.843') ,('2263', '25', 'RS-14-267', '1', '2016-01-10 13:19:42.617') ,('2263', '25', 'RS-14-266', '1', '2016-01-06 15:58:00.513') ,('2263', '25', 'RS-14-259', '6', '2015-12-30 13:58:46.217') ,('2263', '25', 'RS-14-258', '1', '2015-12-30 10:59:23.120') ,('2263', '25', 'RS-14-250', '3', '2015-12-17 16:32:29.937') ,('2263', '25', 'RS-14-240', '1', '2015-12-06 13:13:45.847') ,('2263', '25', 'RS-14-236', '1', '2015-11-30 15:36:41.233') ,('2263', '25', 'RS-14-223', '2', '2015-11-10 13:04:17.540'); SELECT * ,SUM([Quantity]) OVER (PARTITION BY [StockItemId], [GlobalBalance] ORDER BY [Date] DESC) ,[GlobalBalance] - SUM([Quantity]) OVER (PARTITION BY [StockItemId], [GlobalBalance] ORDER BY [Date] DESC) FROM @DataSource ORDER BY [StockItemId] ,[Date] DESC; WITH DataSource AS ( SELECT * ,[GlobalBalance] - SUM([Quantity]) OVER (PARTITION BY [StockItemId], [GlobalBalance] ORDER BY [Date] DESC) AS [Dif] ,ROW_NUMBER() OVER (PARTITION BY [StockItemId], [GlobalBalance] ORDER BY [Date] DESC) [RecordID] FROM @DataSource ), DataSourceWithPrevDiff AS ( SELECT * ,LAG([Dif], 1, NULL) OVER (PARTITION BY [StockItemId], [GlobalBalance] ORDER BY [Date] DESC) AS [PrevDif] FROM DataSource ) SELECT [StockItemId] ,[GlobalBalance] ,[Date] ,[Code] ,[Quantity] ,CASE WHEN [Dif] > 0 THEN [Quantity] WHEN [RecordID] = 1 THEN [Quantity] + [Dif] WHEN [PrevDif] > 0 THEN [PrevDif] END AS [RS_Portion] FROM DataSourceWithPrevDiff WHERE [Dif] > 0 OR [PrevDif] > 0 OR [RecordID] = 1 ORDER BY [StockItemId] ,[Date] DESC; ``` Upvotes: 3 [selected_answer]
2018/03/21
1,067
4,214
<issue_start>username_0: I have the follow trouble, in my base controller i do dependency injection. And i have a class child with implementation of base controller and i need pass the constructor. So my doubt is, my way to implementation of dependency injection is correctly? If no, what is the best way to do this? I use unity to implementate D.I, and my ide is VS2017 web api 2. Follow this code i using: Base controller or parent controller: ``` public class BaseController : ApiController { public string[] includes = null; private readonly IFiltroServico servico; public BaseController(IFiltroServico _servico) { servico = _servico; } } ``` Base controller to generics types implements Base Controller: ``` public abstract class BaseController : BaseController where E : class where R : class where F : class { private readonly IFiltroServico servico; public AreaFormacaoController(IFiltroServico \_servico): base(\_servico) { servico = \_servico; } } ``` Child controller: ``` public abstract class BaseController : BaseController where R : class { private readonly IFiltroServico servico; public AreaFormacaoController(IFiltroServico \_servico): base(\_servico) { servico = \_servico; } //services of controller; } ```<issue_comment>username_1: You don't need to define the private field `servico` over and over again as it is already preset in the base controller. Just define it as `protected readonly` in the base class and use it in the childs. Other than that your code is fine. It is perfectly reasonable that a child has the same dependency parameters in the constructor as it inherits behavior of the base class that is most likely relying on the dependency. Another option would be to use [property injection](https://msdn.microsoft.com/en-us/library/ff649447.aspx) in the base class but you need to add a unity specific attribute to the property. I don't like that as you *bind* your code directly to Unity. Upvotes: 3 [selected_answer]<issue_comment>username_2: Have you seen <https://simpleinjector.org/index.html> check out git from <https://github.com/simpleinjector/SimpleInjector> It is one of the best Inversion of Control library (IOC). Only thing you need to do is register all your services and types. ``` using SimpleInjector; static class Program { static readonly Container container; static Program() { // 1. Create a new Simple Injector container container = new Container(); // 2. Configure the container (register) container.Register(); container.Register(Lifestyle.Singleton); container.Register(); // 3. Verify your configuration container.Verify(); } static void Main(string[] args)) { // 4. Use the container var handler = container.GetInstance(); var orderId = Guid.Parse(args[0]); var command = new CancelOrder { OrderId = orderId }; handler.Handle(command); } } ``` Once you register all your types and services you can inject those services where ever you want ``` public class CancelOrderHandler { private readonly IOrderRepository repository; private readonly ILogger logger; private readonly IEventPublisher publisher; // Use constructor injection for the dependencies public CancelOrderHandler( IOrderRepository repository, ILogger logger, IEventPublisher publisher) { this.repository = repository; this.logger = logger; this.publisher = publisher; } public void Handle(CancelOrder command) { this.logger.Log("Cancelling order " + command.OrderId); var order = this.repository.GetById(command.OrderId); order.Status = OrderStatus.Cancelled; this.repository.Save(order); this.publisher.Publish(new OrderCancelled(command.OrderId)); } } public class SqlOrderRepository : IOrderRepository { private readonly ILogger logger; // Use constructor injection for the dependencies public SqlOrderRepository(ILogger logger) { this.logger = logger; } public Order GetById(Guid id) { this.logger.Log("Getting Order " + order.Id); // Retrieve from db. } public void Save(Order order) { this.logger.Log("Saving order " + order.Id); // Save to db. } } ``` Let me know if you have any queries, Thanks. Upvotes: 1
2018/03/21
821
3,193
<issue_start>username_0: I have a div as follows: ``` | some content here | content 2 here | ``` css: ``` .section{ //style here } .info{ //another style here } ``` In this case, i don't want to apply the *section* style in the in *info*. How to do that?<issue_comment>username_1: You don't need to define the private field `servico` over and over again as it is already preset in the base controller. Just define it as `protected readonly` in the base class and use it in the childs. Other than that your code is fine. It is perfectly reasonable that a child has the same dependency parameters in the constructor as it inherits behavior of the base class that is most likely relying on the dependency. Another option would be to use [property injection](https://msdn.microsoft.com/en-us/library/ff649447.aspx) in the base class but you need to add a unity specific attribute to the property. I don't like that as you *bind* your code directly to Unity. Upvotes: 3 [selected_answer]<issue_comment>username_2: Have you seen <https://simpleinjector.org/index.html> check out git from <https://github.com/simpleinjector/SimpleInjector> It is one of the best Inversion of Control library (IOC). Only thing you need to do is register all your services and types. ``` using SimpleInjector; static class Program { static readonly Container container; static Program() { // 1. Create a new Simple Injector container container = new Container(); // 2. Configure the container (register) container.Register(); container.Register(Lifestyle.Singleton); container.Register(); // 3. Verify your configuration container.Verify(); } static void Main(string[] args)) { // 4. Use the container var handler = container.GetInstance(); var orderId = Guid.Parse(args[0]); var command = new CancelOrder { OrderId = orderId }; handler.Handle(command); } } ``` Once you register all your types and services you can inject those services where ever you want ``` public class CancelOrderHandler { private readonly IOrderRepository repository; private readonly ILogger logger; private readonly IEventPublisher publisher; // Use constructor injection for the dependencies public CancelOrderHandler( IOrderRepository repository, ILogger logger, IEventPublisher publisher) { this.repository = repository; this.logger = logger; this.publisher = publisher; } public void Handle(CancelOrder command) { this.logger.Log("Cancelling order " + command.OrderId); var order = this.repository.GetById(command.OrderId); order.Status = OrderStatus.Cancelled; this.repository.Save(order); this.publisher.Publish(new OrderCancelled(command.OrderId)); } } public class SqlOrderRepository : IOrderRepository { private readonly ILogger logger; // Use constructor injection for the dependencies public SqlOrderRepository(ILogger logger) { this.logger = logger; } public Order GetById(Guid id) { this.logger.Log("Getting Order " + order.Id); // Retrieve from db. } public void Save(Order order) { this.logger.Log("Saving order " + order.Id); // Save to db. } } ``` Let me know if you have any queries, Thanks. Upvotes: 1
2018/03/21
1,039
4,122
<issue_start>username_0: ``` # stack_depth is initialised to 0 def find_in_tree(node, find_condition, stack_depth): assert (stack_depth < max_stack_depth), 'Deeper than max depth' stack_depth += 1 result = [] if find_condition(node): result += [node] for child_node in node.children: result.extend(find_in_tree(child_node, find_condition, stack_depth)) return result ``` I need help understanding this piece of code. The question i want to answer is **The Python function above searches the contents of a balanced binary tree. If an upper limit of 1,000,000 nodes is assumed what should the max\_stack\_depth constant be set to?** From what I understand, this is a trick question. If you think about it, stack\_depth is incremented every time the find\_in\_tree() function is called in the recursion. And we are trying to find a particular node in the tree. And in our case we are accessing every single node every time even if we find the correct node. Because there is no return condition when stops the algorithm when the correct node is found. Hence, max\_stack\_depth should 1,000,000? Can someone please try to explain me their thought process.<issue_comment>username_1: You don't need to define the private field `servico` over and over again as it is already preset in the base controller. Just define it as `protected readonly` in the base class and use it in the childs. Other than that your code is fine. It is perfectly reasonable that a child has the same dependency parameters in the constructor as it inherits behavior of the base class that is most likely relying on the dependency. Another option would be to use [property injection](https://msdn.microsoft.com/en-us/library/ff649447.aspx) in the base class but you need to add a unity specific attribute to the property. I don't like that as you *bind* your code directly to Unity. Upvotes: 3 [selected_answer]<issue_comment>username_2: Have you seen <https://simpleinjector.org/index.html> check out git from <https://github.com/simpleinjector/SimpleInjector> It is one of the best Inversion of Control library (IOC). Only thing you need to do is register all your services and types. ``` using SimpleInjector; static class Program { static readonly Container container; static Program() { // 1. Create a new Simple Injector container container = new Container(); // 2. Configure the container (register) container.Register(); container.Register(Lifestyle.Singleton); container.Register(); // 3. Verify your configuration container.Verify(); } static void Main(string[] args)) { // 4. Use the container var handler = container.GetInstance(); var orderId = Guid.Parse(args[0]); var command = new CancelOrder { OrderId = orderId }; handler.Handle(command); } } ``` Once you register all your types and services you can inject those services where ever you want ``` public class CancelOrderHandler { private readonly IOrderRepository repository; private readonly ILogger logger; private readonly IEventPublisher publisher; // Use constructor injection for the dependencies public CancelOrderHandler( IOrderRepository repository, ILogger logger, IEventPublisher publisher) { this.repository = repository; this.logger = logger; this.publisher = publisher; } public void Handle(CancelOrder command) { this.logger.Log("Cancelling order " + command.OrderId); var order = this.repository.GetById(command.OrderId); order.Status = OrderStatus.Cancelled; this.repository.Save(order); this.publisher.Publish(new OrderCancelled(command.OrderId)); } } public class SqlOrderRepository : IOrderRepository { private readonly ILogger logger; // Use constructor injection for the dependencies public SqlOrderRepository(ILogger logger) { this.logger = logger; } public Order GetById(Guid id) { this.logger.Log("Getting Order " + order.Id); // Retrieve from db. } public void Save(Order order) { this.logger.Log("Saving order " + order.Id); // Save to db. } } ``` Let me know if you have any queries, Thanks. Upvotes: 1
2018/03/21
1,227
4,602
<issue_start>username_0: Context ======= I have a question about my App context path configuration. I have an Angular App that I include in a WAR (using plugin com.github.eirslett.frontend-maven-plugin) so that I can deploy it to the Jboss server of my company. In local mode, no problem, I can access my app at <http://localhost:4200/home> where /home is the route associated with my home page. I start my application using the Angular CLI console with the command **npm run start**. Below is an extract of my package.json. In production mode I use the command **run buildprod**. ``` "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", "buildprod": "ng build --base-href=/my-app/ --prod", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e" } ``` The problem =========== In production mode, I can access without http:// where CONTEXT is the name of my war, i.e my-app.war. So no problem when accessing <http://HOST_NAME:4200/my-app>. Then I think Angular immediately change the displayed URL to http://:4200/my-app/home. * But, If I refresh the URL on <http://HOST_NAME:4200/my-app/home> (or just If I try to manually enter that URL in the address bar) I get a 404 error. The full error message is: > > The requested URL /release-mgr/home was not found on this server. > > > Additionally, a 403 Forbidden error was encountered while trying to > use an ErrorDocument to handle the request. > > > Questions ========= * Do you have any idea if the problem is due to any JBoss or Angular configuration? * Any ideas of how to not have this error and display the target page instead? Thanks a lot for your help! :)<issue_comment>username_1: You don't need to define the private field `servico` over and over again as it is already preset in the base controller. Just define it as `protected readonly` in the base class and use it in the childs. Other than that your code is fine. It is perfectly reasonable that a child has the same dependency parameters in the constructor as it inherits behavior of the base class that is most likely relying on the dependency. Another option would be to use [property injection](https://msdn.microsoft.com/en-us/library/ff649447.aspx) in the base class but you need to add a unity specific attribute to the property. I don't like that as you *bind* your code directly to Unity. Upvotes: 3 [selected_answer]<issue_comment>username_2: Have you seen <https://simpleinjector.org/index.html> check out git from <https://github.com/simpleinjector/SimpleInjector> It is one of the best Inversion of Control library (IOC). Only thing you need to do is register all your services and types. ``` using SimpleInjector; static class Program { static readonly Container container; static Program() { // 1. Create a new Simple Injector container container = new Container(); // 2. Configure the container (register) container.Register(); container.Register(Lifestyle.Singleton); container.Register(); // 3. Verify your configuration container.Verify(); } static void Main(string[] args)) { // 4. Use the container var handler = container.GetInstance(); var orderId = Guid.Parse(args[0]); var command = new CancelOrder { OrderId = orderId }; handler.Handle(command); } } ``` Once you register all your types and services you can inject those services where ever you want ``` public class CancelOrderHandler { private readonly IOrderRepository repository; private readonly ILogger logger; private readonly IEventPublisher publisher; // Use constructor injection for the dependencies public CancelOrderHandler( IOrderRepository repository, ILogger logger, IEventPublisher publisher) { this.repository = repository; this.logger = logger; this.publisher = publisher; } public void Handle(CancelOrder command) { this.logger.Log("Cancelling order " + command.OrderId); var order = this.repository.GetById(command.OrderId); order.Status = OrderStatus.Cancelled; this.repository.Save(order); this.publisher.Publish(new OrderCancelled(command.OrderId)); } } public class SqlOrderRepository : IOrderRepository { private readonly ILogger logger; // Use constructor injection for the dependencies public SqlOrderRepository(ILogger logger) { this.logger = logger; } public Order GetById(Guid id) { this.logger.Log("Getting Order " + order.Id); // Retrieve from db. } public void Save(Order order) { this.logger.Log("Saving order " + order.Id); // Save to db. } } ``` Let me know if you have any queries, Thanks. Upvotes: 1
2018/03/21
1,071
2,465
<issue_start>username_0: I have a df column "days" of 1000 row of records. If the days less than 7.0 days (0-7) group as "1-6 days" If the days more than 7.1 but less than 14.0 days (7.1 - 14.0) group as "7-14 days" If the days more or equal to 15 days group as "> 14 days" How can i create a new column "Days\_Group" to represent the days grouping? ``` e.g of days values: 1 3.0 2 4.6 3 14.9 4 7.1 5 15.1 6 109 ```<issue_comment>username_1: Use [`pd.cut`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html#pandas-cut) ``` df.assign(Day_Group=pd.cut(df['Days'], [0,7,14,np.inf], labels=['1-6 days','7-14 days','> 14 days'])) ``` Output: ``` Days Day_Group 1 3.0 1-6 days 2 4.6 1-6 days 3 14.9 > 14 days 4 7.1 7-14 days 5 15.1 > 14 days 6 109.0 > 14 days ``` Upvotes: 1 <issue_comment>username_2: I think need [`cut`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html): ``` import numpy as np df['Days_Group'] = pd.cut(df['days'], bins=[0,7,14,np.inf], labels=['1-6 days','7-14 days','> 14 days'], include_lowest=True) print (df) days Days_Group 1 3.0 1-6 days 2 4.6 1-6 days 3 14.9 > 14 days 4 7.1 7-14 days 5 15.1 > 14 days 6 109.0 > 14 days ``` --- ``` df['Days_Group'] = pd.cut(df['days'], bins=[0,7,14, pd.np.inf], labels=['1-6 days','7-14 days','> 14 days'], include_lowest=True) print (df) days Days_Group 1 3.0 1-6 days 2 4.6 1-6 days 3 14.9 > 14 days 4 7.1 7-14 days 5 15.1 > 14 days 6 109.0 > 14 days ``` EDIT: If timedeltas in `days`: ``` print (df) days 1 3 days 00:00:00 2 4 days 14:24:00 3 14 days 21:36:00 4 7 days 02:24:00 5 15 days 02:24:00 6 109 days 00:00:00 df['days'] = df['days'].dt.total_seconds() / 24 / 3600 print (df) days 1 3.0 2 4.6 3 14.9 4 7.1 5 15.1 6 109.0 ``` Upvotes: 2 [selected_answer]<issue_comment>username_3: ### `np.searchsorted` ``` labels = np.array(['1-6 days', '7-14 days', '>14 days']) bins = np.array([7, 14]) df.assign(Day_Group=labels[bins.searchsorted(df.days)]) days Day_Group 1 3.0 1-6 days 2 4.6 1-6 days 3 14.9 >14 days 4 7.1 7-14 days 5 15.1 >14 days 6 109.0 >14 days ``` Upvotes: 2
2018/03/21
349
928
<issue_start>username_0: I have string in the bellow format: > > let str = "url(#123456)"; > > > My string have only number contain in it. It can be any where. I want to extract the number `123456` from the above string. I am using es6.<issue_comment>username_1: `str.replace(/[^0-9]/g, '')` ```js let str = "url(#123456)"; console.log(str.replace(/[^0-9]/g, '')) ``` Upvotes: 1 <issue_comment>username_2: another way to do it ``` let str = "url(#123456)"; console.log(str.match(/\d+/)[0]) ``` Upvotes: 0 <issue_comment>username_3: I did it in a way too complicated way, but it does not involve regex so it's probably better to understand: ```js let str = "url(#123456)"; str = str.split("#"); str = str[1].split(")"); str = str[0]; console.log(str); ``` Upvotes: 0 <issue_comment>username_4: Using only Array methods: ```js console.log("url(#123456)".split('#').pop().slice(0, this.length -1)) ``` Upvotes: 0
2018/03/21
242
845
<issue_start>username_0: How to flush all of the cached contents of Docker container memcached from command line without restarting memcached?<issue_comment>username_1: `docker exec -it $MEMCACHE_CONTAINER_ID bash -c "echo flush_all > /dev/tcp/localhost/11211"` Upvotes: 4 [selected_answer]<issue_comment>username_2: Assuming that you have the memcahed port `11211` exposed. You can flush the cache via either `telnet` or `nc` and sending `flush_all` ``` echo flush_all | nc localhost 11211 OK ``` You can replace localhost, with the machine hostname if you are not executing the command on the same machine where the container is running. Upvotes: 3 <issue_comment>username_3: Try to use the following (also works on alpine docker image): ``` docker exec -it $DOCKER_CONTAINER_ID sh -c "echo flush_all | nc localhost 11211" ``` Upvotes: 2
2018/03/21
1,008
3,469
<issue_start>username_0: Overview ======== I would like to use switch statement by matching array type. I have the following classes. Class: ====== ``` class A {} class B : A {} ``` Switch on single value works: ============================= ``` let a : A = B() switch a { case let b as B: print("b = \(b)") default: print("unknown type") } ``` Switch on array (Compilation Error): ==================================== ``` let aArray : [A] = [B(), B()] switch aArray { case let bArray as [B] : print("bArray = \(bArray)") default: print("unknown type") } ``` Error: ====== ``` Downcast pattern value of type '[B]' cannot be used ``` **Note:** Tested on **Swift 4** Question: ========= * How can I achieve this ?<issue_comment>username_1: In Swift 4.1, you get a better error message (thanks to [#11441](https://github.com/apple/swift/pull/11441)): > > Collection downcast in cast pattern is not implemented; use an explicit downcast to '[B]' instead > > > In short, you're hitting a bit of the compiler that isn't fully implemented yet, the progress of which is tracked by the bug [SR-5671](https://bugs.swift.org/browse/SR-5671). You can however workaround this limitation by coercing to `Any` before performing the cast: ``` class A {} class B : A {} let aArray : [A] = [B(), B()] switch aArray /* or you could say 'as Any' here depending on the other cases */ { case let (bArray as [B]) as Any: print("bArray = \(bArray)") default: print("unknown type") } // bArray = [B, B] ``` Why does this work? Well first, a bit of background. Arrays, dictionaries and sets are treated specially by Swift's casting mechanism – despite being generic types (which are invariant by default), Swift allows you to cast between collections of different element types (see [this Q&A](https://stackoverflow.com/q/37188580/2976878) for more info). The functions that implement these conversions reside in the standard library (for example, `Array`'s [implementation is here](https://github.com/apple/swift/blob/1e894cd80bbb4a4c52919ad13bfffc994669052b/stdlib/public/core/ArrayCast.swift#L72)). At compile time, Swift will try to identify collection downcasts (e.g `[A]` to `[B]` in your example) so it can directly call the aforementioned conversion functions, and avoid having to do a *full* dynamic cast through the Swift runtime. However the problem is that this specialised logic isn't implemented for collection downcasting *patterns* (such as in your example), so the compiler emits an error. By first coercing to `Any`, we force Swift to perform a fully dynamic cast, which dispatches through the runtime, which will eventually wind up calling the aforementioned conversion functions. Although why the compiler can't temporarily treat such casts as fully dynamic casts until the necessary specialised logic is in place, I'm not too sure. Upvotes: 4 <issue_comment>username_2: For anyone that has the same question, it's has been fixed in Swift 5.8. Switch on array (original code) compiles fine. As mentioned in [Hacking with swift](https://www.hackingwithswift.com/swift/5.8/collection-downcasts), you can now do this: ``` class Pet { } class Dog: Pet { func bark() { print("Woof!") } } func bark(using pets: [Pet]) { switch pets { case let pets as [Dog]: for pet in pets { pet.bark() } default: print("No barking today.") } } ``` Upvotes: 3 [selected_answer]
2018/03/21
2,977
7,020
<issue_start>username_0: I have a file, called `ETHBTC.json`: ``` [{ "open": "0.06252000", "high": "0.06264700", "low": "0.06239800", "close": "0.06254100", "volume": "681.69300000", "timestamp": 1521575400000 }, { "open": "0.06253500", "high": "0.06270000", "low": "0.06242800", "close": "0.06261900", "volume": "371.99900000", "timestamp": 1521575700000 }, { "open": "0.06261500", "high": "0.06280000", "low": "0.06257500", "close": "0.06266200", "volume": "519.11000000", "timestamp": 1521576000000 }, ... ] ``` I am trying to save the `low` value to a variable in Node.js so I can add all the low values together, etc: ``` for(item in words) { var lowTotal = 0; lowTotal += words.low; } ``` But I have no luck. I'm also having trouble with the `console.log` just to log the `low` variable.<issue_comment>username_1: Just iterate over the object and sum the total ```js var data = [{ "open": "0.06252000", "high": "0.06264700", "low": "0.06239800", "close": "0.06254100", "volume": "681.69300000", "timestamp": 1521575400000 }, { "open": "0.06253500", "high": "0.06270000", "low": "0.06242800", "close": "0.06261900", "volume": "371.99900000", "timestamp": 1521575700000 }, { "open": "0.06261500", "high": "0.06280000", "low": "0.06257500", "close": "0.06266200", "volume": "519.11000000", "timestamp": 1521576000000 }] var lowTotal = 0; data.map(a=>lowTotal+=+a.low) console.log(lowTotal) ``` Upvotes: 0 <issue_comment>username_2: You can [reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) to give an initial value & increment per item in the array ``` const json = JSON.parse('...'); const lowTotal = json.reduce((val, item) => val += parseFloat(item.low), 0); ``` **Example** ```js const data = `[{ "open": "0.06252000", "high": "0.06264700", "low": "0.06239800", "close": "0.06254100", "volume": "681.69300000", "timestamp": 1521575400000 }, { "open": "0.06253500", "high": "0.06270000", "low": "0.06242800", "close": "0.06261900", "volume": "371.99900000", "timestamp": 1521575700000 }, { "open": "0.06261500", "high": "0.06280000", "low": "0.06257500", "close": "0.06266200", "volume": "519.11000000", "timestamp": 1521576000000 }]`; const json = JSON.parse(data); const lowTotal = json.reduce((val, item) => val += parseFloat(item.low), 0); console.log(`Total low=${lowTotal}`); ``` Upvotes: 0 <issue_comment>username_3: I am not sure if you are having trouble reading json file but there are bugs in your code `var lowTotal = 0;` should be outside for loop. Parse String JSON object to float Read `item` not `words` ``` var lowTotal = 0; for(item in words){ lowTotal += parseFloat(item.low); } ``` Upvotes: 0 <issue_comment>username_4: You have several issues in your code: 1. You have `var lowTotal = 0;` inside `for` which is incorrect 2. Better to use a `for` loop so that you get each item of array rather than index of array as in `for(item in words)` 3. `low` is a `string` type value so convert it to `float` type and add it to get the sum. ```js var words = [{ "open": "0.06252000", "high": "0.06264700", "low": "0.06239800", "close": "0.06254100", "volume": "681.69300000", "timestamp": 1521575400000 }, { "open": "0.06253500", "high": "0.06270000", "low": "0.06242800", "close": "0.06261900", "volume": "371.99900000", "timestamp": 1521575700000 }, { "open": "0.06261500", "high": "0.06280000", "low": "0.06257500", "close": "0.06266200", "volume": "519.11000000", "timestamp": 1521576000000 }]; var lowTotal = 0; words.forEach(function(word){ lowTotal += parseFloat(word.low); }); console.log(lowTotal) ``` Upvotes: 1 [selected_answer]<issue_comment>username_5: You can do this with a one-liner using [reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) ``` let sum = words.reduce((a,c)=>a+parseFloat(c.low), 0); ``` Upvotes: 0 <issue_comment>username_6: You should fix your code a bit: ``` let lowTotal = 0; for(item in words){ lowTotal += item.low; } ``` Or you can do it in a bit different way: ``` let lowTotal = 0; words.forEach(word => lowTotal += word.low); ``` Or the most elegant way: ``` let lowTotal = words.reduce((a, b) => { if(isNaN(a)) { a = a.low; } return a + b.low; } ``` Upvotes: 0 <issue_comment>username_7: [For..in](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) is used to iterate over properties of an object. there are many ways to loop throw an array of object, the easiest is to use [for](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for). one last thing the `lowTotal` variable should be declared outside the loop: ```js var words= [{ "open": "0.06252000", "high": "0.06264700", "low": "0.06239800", "close": "0.06254100", "volume": "681.69300000", "timestamp": 1521575400000 }, { "open": "0.06253500", "high": "0.06270000", "low": "0.06242800", "close": "0.06261900", "volume": "371.99900000", "timestamp": 1521575700000 }, { "open": "0.06261500", "high": "0.06280000", "low": "0.06257500", "close": "0.06266200", "volume": "519.11000000", "timestamp": 1521576000000 }]; var lowTotal = 0; for(var i=0; i ``` Upvotes: 0 <issue_comment>username_8: First you need to parse the JSON file: ``` let fs = require('fs'); let content = fs.readFileSync('PathToFile').toString(); ``` Then you need to parse it: ``` let jsonData = JSON.parse(content); ``` Then iterate over the elements. I recommend the for...of loop ``` let total = 0; for(let element of jsonData){ total += element.low } ``` You can also use `Array.prototype.map` or `Array.prototype.reduce` but first stick to the basics. Also please be sure to work on the right types: your numbers in the JSON are saved as strings. You will have to convert them also: ``` let total = 0; for(let element of jsonData){ total += parseFloat(element.low); } ``` Upvotes: 1 <issue_comment>username_9: As some other suggested. But brackets around your tickerdata to create an array. Another suggestion. ``` var tickers = require('./JSONFILE.json') for (const value of Object.values(tickers)) { console.log(value.low) } ``` since you probably don't want to sum all low values. Upvotes: 0 <issue_comment>username_10: please use Object.values like below. Convert JSON to object though using 'JSON.Parse' method ``` let sum = 0; Object.values(YOURJSONOBJECT).forEach(element => { sum += parseFloat(element["low"]); }); console.log(sum); ``` and result would be "0.18740099999999998", which is the sum of 'low' property Upvotes: 1
2018/03/21
2,613
6,305
<issue_start>username_0: I have date column like this ``` DEC07 SEP2007 SEP2008 JUN10 JUN09 ``` how can I can convert this into MM/YYYY assuming DEC07 is 12/2007?<issue_comment>username_1: Just iterate over the object and sum the total ```js var data = [{ "open": "0.06252000", "high": "0.06264700", "low": "0.06239800", "close": "0.06254100", "volume": "681.69300000", "timestamp": 1521575400000 }, { "open": "0.06253500", "high": "0.06270000", "low": "0.06242800", "close": "0.06261900", "volume": "371.99900000", "timestamp": 1521575700000 }, { "open": "0.06261500", "high": "0.06280000", "low": "0.06257500", "close": "0.06266200", "volume": "519.11000000", "timestamp": 1521576000000 }] var lowTotal = 0; data.map(a=>lowTotal+=+a.low) console.log(lowTotal) ``` Upvotes: 0 <issue_comment>username_2: You can [reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) to give an initial value & increment per item in the array ``` const json = JSON.parse('...'); const lowTotal = json.reduce((val, item) => val += parseFloat(item.low), 0); ``` **Example** ```js const data = `[{ "open": "0.06252000", "high": "0.06264700", "low": "0.06239800", "close": "0.06254100", "volume": "681.69300000", "timestamp": 1521575400000 }, { "open": "0.06253500", "high": "0.06270000", "low": "0.06242800", "close": "0.06261900", "volume": "371.99900000", "timestamp": 1521575700000 }, { "open": "0.06261500", "high": "0.06280000", "low": "0.06257500", "close": "0.06266200", "volume": "519.11000000", "timestamp": 1521576000000 }]`; const json = JSON.parse(data); const lowTotal = json.reduce((val, item) => val += parseFloat(item.low), 0); console.log(`Total low=${lowTotal}`); ``` Upvotes: 0 <issue_comment>username_3: I am not sure if you are having trouble reading json file but there are bugs in your code `var lowTotal = 0;` should be outside for loop. Parse String JSON object to float Read `item` not `words` ``` var lowTotal = 0; for(item in words){ lowTotal += parseFloat(item.low); } ``` Upvotes: 0 <issue_comment>username_4: You have several issues in your code: 1. You have `var lowTotal = 0;` inside `for` which is incorrect 2. Better to use a `for` loop so that you get each item of array rather than index of array as in `for(item in words)` 3. `low` is a `string` type value so convert it to `float` type and add it to get the sum. ```js var words = [{ "open": "0.06252000", "high": "0.06264700", "low": "0.06239800", "close": "0.06254100", "volume": "681.69300000", "timestamp": 1521575400000 }, { "open": "0.06253500", "high": "0.06270000", "low": "0.06242800", "close": "0.06261900", "volume": "371.99900000", "timestamp": 1521575700000 }, { "open": "0.06261500", "high": "0.06280000", "low": "0.06257500", "close": "0.06266200", "volume": "519.11000000", "timestamp": 1521576000000 }]; var lowTotal = 0; words.forEach(function(word){ lowTotal += parseFloat(word.low); }); console.log(lowTotal) ``` Upvotes: 1 [selected_answer]<issue_comment>username_5: You can do this with a one-liner using [reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) ``` let sum = words.reduce((a,c)=>a+parseFloat(c.low), 0); ``` Upvotes: 0 <issue_comment>username_6: You should fix your code a bit: ``` let lowTotal = 0; for(item in words){ lowTotal += item.low; } ``` Or you can do it in a bit different way: ``` let lowTotal = 0; words.forEach(word => lowTotal += word.low); ``` Or the most elegant way: ``` let lowTotal = words.reduce((a, b) => { if(isNaN(a)) { a = a.low; } return a + b.low; } ``` Upvotes: 0 <issue_comment>username_7: [For..in](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) is used to iterate over properties of an object. there are many ways to loop throw an array of object, the easiest is to use [for](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for). one last thing the `lowTotal` variable should be declared outside the loop: ```js var words= [{ "open": "0.06252000", "high": "0.06264700", "low": "0.06239800", "close": "0.06254100", "volume": "681.69300000", "timestamp": 1521575400000 }, { "open": "0.06253500", "high": "0.06270000", "low": "0.06242800", "close": "0.06261900", "volume": "371.99900000", "timestamp": 1521575700000 }, { "open": "0.06261500", "high": "0.06280000", "low": "0.06257500", "close": "0.06266200", "volume": "519.11000000", "timestamp": 1521576000000 }]; var lowTotal = 0; for(var i=0; i ``` Upvotes: 0 <issue_comment>username_8: First you need to parse the JSON file: ``` let fs = require('fs'); let content = fs.readFileSync('PathToFile').toString(); ``` Then you need to parse it: ``` let jsonData = JSON.parse(content); ``` Then iterate over the elements. I recommend the for...of loop ``` let total = 0; for(let element of jsonData){ total += element.low } ``` You can also use `Array.prototype.map` or `Array.prototype.reduce` but first stick to the basics. Also please be sure to work on the right types: your numbers in the JSON are saved as strings. You will have to convert them also: ``` let total = 0; for(let element of jsonData){ total += parseFloat(element.low); } ``` Upvotes: 1 <issue_comment>username_9: As some other suggested. But brackets around your tickerdata to create an array. Another suggestion. ``` var tickers = require('./JSONFILE.json') for (const value of Object.values(tickers)) { console.log(value.low) } ``` since you probably don't want to sum all low values. Upvotes: 0 <issue_comment>username_10: please use Object.values like below. Convert JSON to object though using 'JSON.Parse' method ``` let sum = 0; Object.values(YOURJSONOBJECT).forEach(element => { sum += parseFloat(element["low"]); }); console.log(sum); ``` and result would be "0.18740099999999998", which is the sum of 'low' property Upvotes: 1
2018/03/21
1,582
4,527
<issue_start>username_0: Here I am having 3 table using I have to take the count > > trip\_details > > > ``` id allocationId tripId 1 7637 aIz2o 2 7626 osseC 3 7536 01LEC 4 7536 78w2w 5 7640 S60zF 6 7548 ruaoR 7 7548 Qse6s ``` > > escort\_allocation > > > ``` id allocationId escortId 3 7637 1 4 7626 1 5 7627 1 6 7536 1 7 7640 1 7 7548 1 ``` > > cab\_allocation > > > ``` allocationId allocationType 7637 Daily Trip 7626 Daily Trip 7627 Daily Trip 7536 Adhoc Trip 7640 Adhoc Trip 7548 Daily Trip ``` Using above table I have to get the count, I tried but it is not happening my expected results. **I tried sql query** ``` SELECT a.`tripId` FROM `trip_details` a INNER JOIN escort_allocation b ON a.`allocationId` = b.`allocationId` GROUP BY a.`allocationId` LIMIT 0 , 30 ``` **I am getting like this** ``` tripId 01LEC ruaoR osseC aIz2o S60zF ``` `total 6 tripId i got` ,so now I want to take the count so I am using this query ``` SELECT COUNT(*) FROM `trip_details` a INNER JOIN escort_allocation b ON a.`allocationId` = b.`allocationId` GROUP BY a.`allocationId` LIMIT 0 , 30 ``` but this query is not working.**I am getting results like below** ``` 2 2 1 1 1 ``` > > MY MYSQL TABLES AND VALUES LOOK LIKE THIS > > > ``` CREATE TABLE `trip_details` ( `id` int(11) NOT NULL AUTO_INCREMENT, `allocationId` int(11) NOT NULL, `tripId` varchar(100) NOT NULL, PRIMARY KEY (`id`), KEY `tripId` (`tripId`), KEY `allocationId` (`allocationId`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1 ; INSERT INTO trip_details (id, allocationId, tripId) VALUES (1, 7637, '00SwM'), (2, 7626, '00SwM'), (3, 7536, '00SwM'), (4, 7536, '01hEU'), (5, 7640, '01hEU'), (6, 7548, 'IRZMS'), (7, 7548, 'IRZMS'); CREATE TABLE `escort_allocation` ( `id` int(11) NOT NULL AUTO_INCREMENT, `allocationId` int(11) NOT NULL, `escortId` varchar(100) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1 ; INSERT INTO escort_allocation (id, allocationId, escortId) VALUES (1, 7637, 'ssda'), (2, 7626, 'adad'), (3, 7627, 'sfsaf'), (4, 7536, 'ssaf'), (5, 7640, 'asf'), (6, 7548, 'a3r'); CREATE TABLE `cab_allocation` ( `allocationId` int(11) NOT NULL AUTO_INCREMENT, `allocationType` enum('Daily Trip','Adhoc Trip') NOT NULL, PRIMARY KEY (`allocationId`) ) ENGINE=InnoDB AUTO_INCREMENT=7695 DEFAULT CHARSET=latin1; INSERT INTO cab_allocation (allocationId, allocationType) VALUES (7637, 'Daily Trip'), (7626, 'Daily Trip'), (7627, 'Daily Trip'), (7536, 'Adhoc Trip'), (7640, 'Adhoc Trip'), (7548, 'Daily Trip'); ```<issue_comment>username_1: With this, you should get the tripid and the amount: ``` SELECT COUNT(a.tripId) as total, a.tripId as tripId FROM trip_details a INNER JOIN escort_allocation b ON a.allocationId = b.allocationId GROUP BY a.allocationId LIMIT 0 , 30 ``` Upvotes: 1 <issue_comment>username_2: You can try this ``` SELECT COUNT(DISTINCT (a.`tripId`)) FROM `trip_details` a INNER JOIN escort_allocation b ON a.`allocationId`=b.`allocationId` LIMIT 0 , 30 ``` because of `GROUP BY` there is separate count for all **allocationId**. Upvotes: 1 <issue_comment>username_3: You may use: ``` SELECT COUNT(DISTINCT a.allocationId) FROM trip_details a INNER JOIN escort_allocation b ON a.allocationId = b.allocationId ``` Previously you used `COUNT(*)` and also used `GROUP BY` so the counts of rows you were getting are from individual groups. **Update-2:** ``` SELECT ( SELECT COUNT(*) FROM trip_details ) AS Total_Trip_Count, COUNT(T.tripId) as Escort_Count, ( SELECT COUNT(*) FROM ( SELECT a.allocationId FROM escort_allocation a INNER JOIN cab_allocation c ON a.allocationId = c.allocationId WHERE c.allocationType = 'Adhoc Trip' GROUP BY a.allocationId ) AS Ad ) AS Adhoc_Trip_Count FROM ( SELECT a.tripId FROM trip_details a INNER JOIN escort_allocation b ON a.allocationId = b.allocationId GROUP BY a.allocationId ) AS T ``` Upvotes: 1 [selected_answer]
2018/03/21
798
2,715
<issue_start>username_0: I am trying to open a file based on a name that is only partially complete in VBA. Here is an example: I want to pull a file with the name: "MMM B2 06222018" The file will always be located in "C:\Myfile\" However, these two files are saved in "C:\Myfile\": "MMM B2 06222018 Updated" - Updated at 10:00 "MMM B2 06222018" - Updated at 9:00 What I want is for the macro to pull the most recently updated file that has the name "MMM B2 06222018" within the file name, but that name may or maynot be the complete name of the file. In this case, the "MMM B2 06222018 Updated" is the file I want pulled because it includes all of the "MMM B2 06222018" name, AND it is the most recently saved file. ``` FileDateTime(file_path) 'I was thinking of using this to compare the file save times. 'But I can only use this if I have a file name. ``` What is a good way of analyzing the partial file name? Thanks!<issue_comment>username_1: ``` Function GET_LATEST_FILE(strFolder As String, strWildCardStart As String) As String Dim d As Date, fld as Object, f As Object d = DateSerial(1900, 1, 1) With CreateObject("scripting.filesystemobject") Set fld = .getfolder(strFolder) For Each f In fld.Files If f.Name Like strWildCardStart & "*" Then If f.datelastmodified > d Then d = f.datelastmodified GET_LATEST_FILE = f.Name End If End If Next f End With End Function ``` Use this like so `GET_LATEST_FILE("C:\Workspace\Dummy Data","Sample")` Upvotes: 3 [selected_answer]<issue_comment>username_2: A less powerful way to do this, without FileSystemObject, is to use `Dir`: ```vb Function GetLatestFile(ByVal FolderName As String, ByVal FileName As String) As String GetLatestFile = "" 'Default to blank 'Declare variables Dim sTestFile As String, dTestFile As Date, dLatest As Date If Right(FolderName, 1) <> "\" Then FolderName = FolderName & "\" 'Add final slash if missing If Len(FileName) = Len(Replace(FileName, "*", "")) Then FileName = FileName & "*" 'Add wildcard if missing dLatest = DateSerial(1900, 0, 0) 'Default to 0 sTestFile = Dir(FolderName & sTestFile) 'First file that matches the filename, if any While Len(sTestFile) > 1 'Loop through all files until we run out dTestFile = FileDateTime(FolderName & sTestFile) 'Get Created/Modifed Date If dTestFile > dLatest Then 'If new file is newer GetLatestFile = sTestFile dLatest = dTestFile 'Store date End If sTestFile = Dir() 'Calling Dir without any arguments gets the next file to match the last filename given Wend End Function ``` Upvotes: 0
2018/03/21
2,018
6,586
<issue_start>username_0: I've got some strange issue. I have following setup: one docker-host running traefik as LB serving multiple sites. sites are most php/apache. HTTPS is managed by traefik. Each site is started using a docker-compose YAML containing the following: ``` version: '2.3' services: redis: image: redis:alpine container_name: ${PROJECT}-redis networks: - internal php: image: registry.gitlab.com/OUR_NAMESPACE/docker/php:${PHP_IMAGE_TAG} environment: - APACHE_DOCUMENT_ROOT=${APACHE_DOCUMENT_ROOT} container_name: ${PROJECT}-php-fpm volumes: - ${PROJECT_PATH}:/var/www/html:cached - .docker/php/php-ini-overrides.ini:/usr/local/etc/php/conf.d/99-overrides.ini ports: - 80 networks: - proxy - internal labels: - traefik.enable=true - traefik.port=80 - traefik.frontend.headers.SSLRedirect=false - traefik.frontend.rule=Host:${PROJECT} - "traefik.docker.network=proxy" networks: proxy: external: name: proxy internal: ``` (as PHP we use 5.6.33-apache-jessie or 7.1.12-apache f.e.) Additionally to above, some sites get following labels: ``` traefik.docker.network=proxy traefik.enable=true traefik.frontend.headers.SSLRedirect=true traefik.frontend.rule=Host:example.com, www.example.com traefik.port=80 traefik.protocol=http ``` what we get is that some requests end in 502 Bad Gateway traefik debug output shows: ``` time="2018-03-21T12:20:21Z" level=debug msg="vulcand/oxy/forward/http: Round trip: http://172.18.0.8:80, code: 502, Length: 11, duration: 2.516057159s" ``` can someone help with that? it's completely random when it happens our traefik.toml: ``` debug = true checkNewVersion = true logLevel = "DEBUG" defaultEntryPoints = ["https", "http"] [accessLog] [web] address = ":8080" [web.auth.digest] users = ["admin:traefik:some-encoded-pass"] [entryPoints] [entryPoints.http] address = ":80" # [entryPoints.http.redirect] # had to disable this because HTTPS must be enable manually (not my decission) # entryPoint = "https" [entryPoints.https] address = ":443" [entryPoints.https.tls] [retry] [docker] endpoint = "unix:///var/run/docker.sock" domain = "example.com" watch = true exposedbydefault = false [acme] email = "<EMAIL>" storage = "acme.json" entryPoint = "https" onHostRule = true [acme.httpChallenge] entryPoint = "http" ``` Could the issue be related to using the same docker-compose.yml?<issue_comment>username_1: For anyone getting the same issue: After recreating the network (proxy) and restarting every site/container it seems to work now. I still don't know where the issue was from. Upvotes: 5 [selected_answer]<issue_comment>username_2: In your example you don't have traefik enabled: ``` traefik.enable=false ``` Make sure to enable it first and then test your containers. Upvotes: 2 <issue_comment>username_3: If you see `Bad Gateway` with Traefik chances are you have a Docker networking issue. First have a look at [this issue](https://github.com/containous/traefik/issues/1254) and consider [this solution](https://github.com/containous/traefik/issues/1254#issuecomment-299114960). Then take a look at [`providers.docker.network`](https://docs.traefik.io/providers/docker/#network) (Traefik 2.0) or, in your case, the [`docker.network`](https://docs.traefik.io/v1.7/configuration/backends/docker/#docker-provider) setting (Traefik 1.7). You could add a default `network` here: ``` [docker] endpoint = "unix:///var/run/docker.sock" domain = "example.com" watch = true exposedbydefault = false network = "proxy" ``` Or define/override it for a given service using the `traefik.docker.network` label. Upvotes: 3 <issue_comment>username_4: Got the same problem and none of the above mentioned answers solved it for me. In my case a wrong loadbalancer was added. Removing the label or changing it to the correct port made the trick. ``` - "traefik.http.services.XXX.loadbalancer.server.port=XXX" ``` Upvotes: 3 <issue_comment>username_5: Another cause can be exposing a container at a port that Traefik already uses. Upvotes: 1 <issue_comment>username_6: The error "bad gateway" is returned when the web server in the container doesn't allow traffic from traefik e.g. because of wrong interface binding like localhost instead of 0.0.0.0. Take Ruby on Rails for example. Its web server puma is configured by default like this (see config/puma.rb): ``` port ENV.fetch("PORT") { 3000 } ``` But in order to allow access from traefik puma must bind to 0.0.0.0 like so: ``` bind "tcp://0.0.0.0:#{ ENV.fetch("PORT") { 3000 } }" ``` This solved the problem for me. Upvotes: 2 <issue_comment>username_7: Another reason can be that you might be accidentally mapping to the vm's port instead of the container port. I made a change to my port mapping on the docker-compose file and forgot to update the labeled port so it was trying to map to a port on the machine that was not having any process attached to it **Wrong way:** ``` ports: - "8080:8081" labels: - "traefik.http.services.front-web.loadbalancer.server.port=8080" ``` **Right way** ``` ports: - "8080:8081" labels: - "traefik.http.services.front-web.loadbalancer.server.port=8081" ``` Also in general don't do this, instead of exposing ports try docker networks they are much better and cleaner. I made my configuration documentation like a year ago and this was more of a beginner mistake on my side but might help someone :) Upvotes: 4 <issue_comment>username_8: I forgot to expose the port in my `Dockerfile` thats why traefik did not find a port to route to. So expose the port BEFORE you start the application like node: ```yaml #other stuff before... EXPOSE 3000 CMD ["node", "dist/main" ] ``` Or if you have multiple ports open you have to specify which port traefik should route the domain to with: `- "traefik.http.services.myservice.loadbalancer.server.port=3000"` Or see [docs](https://doc.traefik.io/traefik/routing/providers/docker/#port) Upvotes: 1 <issue_comment>username_9: I faced very close issue to this exception my problem was not related to network settings or config, after time we figured out that the exposed port from the backend container is not like the port we mapping to to access form outside the service port was 5000 and we mapped 9000:9000 the solution was to fix the port issue first 9000:5000. Upvotes: 0 <issue_comment>username_10: Expose port 80 for traefik ``` services: php: expose: - "80" ``` Upvotes: 0
2018/03/21
202
612
<issue_start>username_0: please advice on how to check if a string ends with any integer at all in javascript. Not a specific integer. e.g `aahdhs7; //Returns true` `assa4; //also returns true` Thank you<issue_comment>username_1: Regex to detect if last value is an integer: ``` ^.*(\d)$ ``` Example here - <https://regexr.com/3mk0q> Upvotes: -1 [selected_answer]<issue_comment>username_2: try `Number.isNumber()` ```js my_str = "Hi Hello 3"; my_str1 = "Hi Hello"; console.log(Number.isInteger(parseInt(my_str.substr(-1)))); console.log(Number.isInteger(parseInt(my_str1.substr(-1)))); ``` Upvotes: 0
2018/03/21
344
1,325
<issue_start>username_0: I have a problem when building a default project created by NetBeans when Maven-Java Web application is created. When I add Spring MVC dependency under Properties->Framework category and build a project I get this error: ``` Failure to find org.springframework:spring-framework-bom:jar:4.0.1.RELEASE in http://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced -> [Help 1] ```<issue_comment>username_1: Did you add this dependency? ``` org.springframework spring-framework-bom 4.0.1.RELEASE pom ``` and throws you that error? Could be a missed library. Upvotes: 0 <issue_comment>username_2: You have a placeholder in your local repo, try to delete this placeholder delete the folder ``` ~/.m2/repository/org/springframework/spring-framework-bom/4.0.1.RELEASE ``` Then rebuild with ``` mvn clean install -U ``` This assume your maven instillation is correct. Upvotes: 1 <issue_comment>username_3: Before adding it manually (or any other solution), make sure u really need the spring bom in your dependencies... The bom should go under dependencyManagement section in your parent pom xml. BTW the bom is only available as "POM" , not as "jar" scope. Upvotes: 0
2018/03/21
947
3,529
<issue_start>username_0: I received this crash report in Google Play Console which I myself never experience. ``` java.lang.IllegalArgumentException: at android.widget.ListPopupWindow.setHeight (ListPopupWindow.java:541) at android.widget.AutoCompleteTextView.setDropDownHeight (AutoCompleteTextView.java:414) at .MyEditText.showDropDown (MyEditText.java:44) at android.widget.AutoCompleteTextView.updateDropDownForFilter (AutoCompleteTextView.java:1086) at android.widget.AutoCompleteTextView.onFilterComplete (AutoCompleteTextView.java:1068) at android.widget.Filter$ResultsHandler.handleMessage (Filter.java:285) at android.os.Handler.dispatchMessage (Handler.java:105) at android.os.Looper.loop (Looper.java:172) at android.app.ActivityThread.main (ActivityThread.java:6637) at java.lang.reflect.Method.invoke (Method.java) at com.android.internal.os.Zygote$MethodAndArgsCaller.run (Zygote.java:240) at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:767) ``` I am using this `showDropDown` method to leave the space of 50 dp from the bottom of screen so that the drop down will not cover my Admob ads on the bottom. ``` public void showDropDown() { Rect displayFrame = new Rect(); getWindowVisibleDisplayFrame(displayFrame); int[] locationOnScreen = new int[2]; getLocationOnScreen(locationOnScreen); int bottom = locationOnScreen[1] + getHeight(); int availableHeightBelow = displayFrame.bottom - bottom; Resources r = getResources(); int bannerHeight = Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, r.getDisplayMetrics())); int downHeight = availableHeightBelow - bannerHeight; setDropDownHeight(downHeight); super.showDropDown(); } ``` From Google Play Console, this crash only affects Mi A1 and Mate 10 Pro running Android 8.0. I do not experience this crash on emulator running Android 8.0. This is the desired effect: [![enter image description here](https://i.stack.imgur.com/jJmAf.png)](https://i.stack.imgur.com/jJmAf.png)<issue_comment>username_1: It looks like the IllegalArgumentException is thrown [here](https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/widget/ListPopupWindow.java#541). If you track earlier versions of Android ([N](https://android.googlesource.com/platform/frameworks/base/+/nougat-release/core/java/android/widget/ListPopupWindow.java#541) and earlier) that defensive code does not exist. Based on your computations, the height could be negative. I think you'd need a different way to achieve the desired result. How does your layout look like? Upvotes: 3 <issue_comment>username_2: For the time being, I added code to check whether `downHeight > 0` to prevent this crash. ``` public void showDropDown() { Rect displayFrame = new Rect(); getWindowVisibleDisplayFrame(displayFrame); int[] locationOnScreen = new int[2]; getLocationOnScreen(locationOnScreen); int bottom = locationOnScreen[1] + getHeight(); int availableHeightBelow = displayFrame.bottom - bottom; Resources r = getResources(); int bannerHeight = Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, r.getDisplayMetrics())); int downHeight = availableHeightBelow - bannerHeight; if (downHeight > 0) { setDropDownHeight(downHeight); } else { setDropDownHeight(300); } super.showDropDown(); } ``` Upvotes: 3 [selected_answer]
2018/03/21
458
1,573
<issue_start>username_0: I'm new to Plone 5 and I'm actually following the plone training. However, I'm not used to the way that all is build. I would like to do simple things but I don't know where to start. For example: * How can I move the search bar from the header to the navbar menu? * How can I add an image to the header next to the logo? * Is there any tutorial that can help me?<issue_comment>username_1: Most of your questions can probably be answered with techniques from the official tutorials and documentation. See: * <https://docs.plone.org/index.html> * <https://docs.plone.org/adapt-and-extend/index.html> * <https://docs.plone.org/develop/index.html> Upvotes: 1 <issue_comment>username_2: You can install the add-on Products.ContentWellPortlets and replace the top-viewlets with portlets, by adding a `portlets.xml` in one of your add-on's profiles. This example adds a logo and an image next to it: ``` xml version ="1.0"? Logo True <a href="/Plone"> <img src="logo.png" /> </a> Some image next to Logo True <img src="defaultUser.png" title="Dummy-user-avatar" /> ``` And polish it with some styling. For the search-box I'd may assign a search-portlet above the content (using ContentWellPortlets), give it a minus-margin-top and for the globnav a margin-right, but as there's many ways to Rome, I'd might replace the globnav with a navigation-portlet, too. Here's an add-on for illustration-purposes (see its `viewlets.xml` on how to hide the top-viewlets): <https://github.com/ida/adi/tree/master/adi.samplestructure> Upvotes: 0
2018/03/21
932
3,758
<issue_start>username_0: I try to migrate my app from spring boot 1.5 to 2.0 The problem is that I cannot find EmbeddedServletContainerCustomizer. Any ideas how to make it through? ``` @Bean public EmbeddedServletContainerCustomizer customizer() { return container -> container.addErrorPages(new ErrorPage(HttpStatus.UNAUTHORIZED, "/unauthenticated")); } ``` **Update:** I found it as ServletWebServerFactoryCustomizer in org.springframework.boot.autoconfigure.web.servlet package. ``` @Bean public ServletWebServerFactoryCustomizer customizer() { return container -> container.addErrorPages(new ErrorPage(HttpStatus.UNAUTHORIZED, "/unauthenticated")); } ``` But there is an error: Cannot resolve method > > 'addErrorPages(org.springframework.boot.web.server.ErrorPage)' > > > I also had to change import of new Error Page from `org.springframework.boot.web.servlet` to `org.springframework.boot.web.server`<issue_comment>username_1: I think you need `ConfigurableServletWebServerFactory`, instead of `ServletWebServerFactoryCustomizer`. You can find the code snippet below: ``` import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory; import org.springframework.boot.web.server.ErrorPage; import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpStatus; @Configuration public class ServerConfig { @Bean public ConfigurableServletWebServerFactory webServerFactory() { UndertowServletWebServerFactory factory = new UndertowServletWebServerFactory(); factory.addErrorPages(new ErrorPage(HttpStatus.UNAUTHORIZED, "/unauthenticated")); return factory; } } ``` The above code is for Undertow. For tomcat, you need to replace `UndertowServletWebServerFactory` with `TomcatServletWebServerFactory`. You will need to add the following dependency to your project (in case of Maven): ``` io.undertow undertow-servlet 2.0.26.Final ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: You can find the code snippet below: ``` @Bean public ErrorPageRegistrar errorPageRegistrar(){ return new MyErrorPageRegistrar(); } // ... private static class MyErrorPageRegistrar implements ErrorPageRegistrar { @Override public void registerErrorPages(ErrorPageRegistry registry) { registry.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/400")); } } ``` Upvotes: 0 <issue_comment>username_3: You don't need the container customizer to register your error pages. Simple bean definition implemented as a lambda does the trick: ``` @Bean public ErrorPageRegistrar errorPageRegistrar() { return registry -> { registry.addErrorPages( new ErrorPage(HttpStatus.UNAUTHORIZED, "/unauthenticated"), ); }; } ``` Upvotes: 3 <issue_comment>username_4: From Spring Boot 2 on the *WebServerFactoryCustomizer* has replaced the *EmbeddedServletContainerCustomizer*: ``` @Bean public WebServerFactoryCustomizer webServerFactoryCustomizer() { return (factory) -> factory.addErrorPages(new ErrorPage(HttpStatus.UNAUTHORIZED, "/401.html")); } ``` **Alternatively** you might add a view controller like ``` @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/unauthorized").setViewName("forward:/401.html"); } ``` and then your WebServerFactory should point to /unauthorized instead: ``` @Bean public WebServerFactoryCustomizer webServerFactoryCustomizer() { return (factory) -> factory.addErrorPages(new ErrorPage(HttpStatus.UNAUTHORIZED, "/unauthorized")); } ``` Upvotes: 2
2018/03/21
567
2,252
<issue_start>username_0: I have a button that when clicked calls a function that sorts the products by case amount. I am updating the products array so I assumed this would trigger a re-render of the products being mapped in the code below but it is not. Does anyone know how to get this to trigger the products.map to be re-rendered again thus displaying the new sorted products? ``` render() { const {products} = this.props; const cartIcon = (); sortCartItems = () => { products.sort((a, b) => a.cases > b.cases); } return ( {cartIcon} Sort {products.map((product, index) => this.collapseAllOtherProducts} /> )} ); } ```<issue_comment>username_1: A component should not mutate it's own props. [If your data changes during the lifetime of a component you need to use `state`.](https://reactjs.org/tutorial/tutorial.html#an-interactive-component) Your inline arrow function `sortCartItems` tries to mutate the `products` that come from props. Your need to store the products in the components state instead and call `setState` to change them which will trigger a re-render. ``` class MyComponent extends React.Component { constructor(props) { super(props); this.state = { products: props.products, } } sortCartItems = () => { this.setState(prevState => ({products: prevState.products.sort((a, b) => a.cases > b.cases);})) } render() {...} } ``` Note that you need to use a callback in `setState` whenever you are updating the state based on the previous state. The callback receives the old state as a parameter and returns the new state. Upvotes: 2 <issue_comment>username_2: I used a combination of messerbill's and username_1's answers to come up with the following which is now working. And I added a products property to state which receives its data from props.products ``` render() { const cartIcon = (); sortCartItems = () => { this.setState({ products: this.state.products.sort((a, b) => a.cases > b.cases) }); } return ( {cartIcon} Sort {this.state.products.map((product, index) => this.collapseAllOtherProducts} /> )} ); } ``` Upvotes: 0
2018/03/21
443
1,470
<issue_start>username_0: I have a function that takes as many "data vector" inputs as desired, and performs operations on all of them together. So following works: ``` myFunction( df[,1], df[,2], df[,3], ..up to the number of columns.. ) ``` I would like to split a data frame (or matrix) into different column vectors and supply all of them as different inputs (basically example above without having to write the each column one by one) I have already tried to following: ``` myFunction( split( df, col(df) ) ) ``` and this doesn't work because the function I am trying to use does not accept list of inputs, it expects each of them to be a different argument. Is there a way to do this?<issue_comment>username_1: The question seems to be ambiguous a little. That said, the following covers the things mentioned in the question to a great extent. ``` set.seed(1) df <- as.data.frame(matrix(c(rep(rnorm(10),5)), ncol=5, byrow=TRUE)) df sum(df[,1], df[,2], df[,3], df[,4], df[,5]) # 6.610139 sum(unlist(lapply(as.matrix(1:ncol(df)), function(i) {df[,i] }))) # 6.610139 ``` Upvotes: 0 <issue_comment>username_2: Working example of what is suggested in the comments: ``` argumentList <- split(df, col(df)) # create a list of arguments names(argumentList)[1] <- "x" # name at least one of the inputs for the default value x argumentList["na.rm"] <- TRUE # add any other arguments needed do.call( myFunction, argumentList ) ``` Upvotes: 2 [selected_answer]
2018/03/21
534
1,782
<issue_start>username_0: I have a computed property witch looks inside a `items: {}` array, this array have 26 objects inside. The property only "read" the first 23 objects, the 24 and the next ones looks out of the filter range. Before this conclusion i think the problem is because the **24** object have an special character but i revert the array order and the special character was filter correctly. ``` items: [ {...}, 23: { alias: "Correcto", id: 11 }, 24: { alias: "Tamaño", id: 12 } 25: { alias: "silla", id: 13 ] }; ``` This is the code of my filter as a `computed:` porperty ``` computed: { filteredItems() { if (this.items) { return this.items.filter((item) => { if (!this.search) return ''; return item.alias.toLowerCase().match(this.search.toLowerCase().trim()); }); } } }, ``` How can i make the filter works with big arrays?<issue_comment>username_1: The question seems to be ambiguous a little. That said, the following covers the things mentioned in the question to a great extent. ``` set.seed(1) df <- as.data.frame(matrix(c(rep(rnorm(10),5)), ncol=5, byrow=TRUE)) df sum(df[,1], df[,2], df[,3], df[,4], df[,5]) # 6.610139 sum(unlist(lapply(as.matrix(1:ncol(df)), function(i) {df[,i] }))) # 6.610139 ``` Upvotes: 0 <issue_comment>username_2: Working example of what is suggested in the comments: ``` argumentList <- split(df, col(df)) # create a list of arguments names(argumentList)[1] <- "x" # name at least one of the inputs for the default value x argumentList["na.rm"] <- TRUE # add any other arguments needed do.call( myFunction, argumentList ) ``` Upvotes: 2 [selected_answer]
2018/03/21
437
1,524
<issue_start>username_0: I'm reading through test classes that use Assertj to verify results. Occasionally, I've spotted an assertThat without assertions. ``` assertThat(object.getField()); ``` Is it possible to identify these classes somewhere in the development cycle? My first guess would be to use a custom Sonar rule. Although I don't see how I should define that this method should be followed by an assertion (a method returning void?).<issue_comment>username_1: As said in [the AssertJ FAQ](http://joel-costigliola.github.io/assertj/assertj-core.html#faq-incorrect-api-usage): > > Static code analysis tools like SpotBugs/FindBugs/ErrorProne can now detect such problems thanks to the [`CheckReturnValue`](https://github.com/joel-costigliola/assertj-core/pull/695) annotation introduced in 2.5+ / 3.5+ and improved in 2.7+ / 3.7+. > > > And indeed, SpotBugs finds this issue easily as I just tested with AssertJ 3.9.0, Java 8 and SpotBugs 3.1.1: [![SpotBugs: ](https://i.stack.imgur.com/CHl6Q.png)assertThat() ignored"">](https://i.stack.imgur.com/CHl6Q.png) Therefore, if you do not see this warning in your static analysis tool, perhaps you have disabled the check for using return values from methods annotated with `@CheckReturnValue`. Upvotes: 2 <issue_comment>username_2: SonarJava is having the rule S2970 "Assertions should be complete" that can detect `assertThat` without assertions for AssertJ, Fest and Truth. See: <https://rules.sonarsource.com/java/RSPEC-2970> Upvotes: 3 [selected_answer]
2018/03/21
540
1,962
<issue_start>username_0: I have an application using SpringBoot2 with mongodb and I am trying to test json serialization of some DTOS by making tests like: ``` @JsonTest @RunWith(SpringRunner.class) public class SomeDTOTest { @Autowired JacksonTester < SomeDTO > json; @Test public void someTest() {} } ``` However underneath spring is trying to create repository bean and giving me informations: ``` *************************** APPLICATION FAILED TO START *************************** Description: A component required a bean named 'mongoTemplate' that could not be found. Action: Consider defining a bean named 'mongoTemplate' in your configuration. ``` I have more integration test that is using the repository and are annotated with @SpringBootTests and they are working fine... Is there a way of restricting spring to only creating JacksonTester bean?<issue_comment>username_1: As said in [the AssertJ FAQ](http://joel-costigliola.github.io/assertj/assertj-core.html#faq-incorrect-api-usage): > > Static code analysis tools like SpotBugs/FindBugs/ErrorProne can now detect such problems thanks to the [`CheckReturnValue`](https://github.com/joel-costigliola/assertj-core/pull/695) annotation introduced in 2.5+ / 3.5+ and improved in 2.7+ / 3.7+. > > > And indeed, SpotBugs finds this issue easily as I just tested with AssertJ 3.9.0, Java 8 and SpotBugs 3.1.1: [![SpotBugs: ](https://i.stack.imgur.com/CHl6Q.png)assertThat() ignored"">](https://i.stack.imgur.com/CHl6Q.png) Therefore, if you do not see this warning in your static analysis tool, perhaps you have disabled the check for using return values from methods annotated with `@CheckReturnValue`. Upvotes: 2 <issue_comment>username_2: SonarJava is having the rule S2970 "Assertions should be complete" that can detect `assertThat` without assertions for AssertJ, Fest and Truth. See: <https://rules.sonarsource.com/java/RSPEC-2970> Upvotes: 3 [selected_answer]
2018/03/21
1,204
3,376
<issue_start>username_0: I have JSON object that I want to convert to C# object. To create class in C# I use <http://json2csharp.com/> page. But the converter doesn't do well. My JSON object: ``` { "data": { "krs_podmioty.data_sprawdzenia": "2016-12-22T05:36:21", "krs_podmioty.regon": "0", "krs_podmioty.adres_lokal": "", "krs_podmioty.adres_miejscowosc": "Warszawa", "krs_podmioty.liczba_czlonkow_komitetu_zal": 0, } } ``` I receive Object looking like below: ``` public class Data { public DateTime __invalid_name__krs_podmioty.data_sprawdzenia { get; set; } public string __invalid_name__krs_podmioty.regon { get; set; } public string __invalid_name__krs_podmioty.adres_lokal { get; set; } public string __invalid_name__krs_podmioty.adres_miejscowosc { get; set; } public int __invalid_name__krs_podmioty.liczba_czlonkow_komitetu_zal { get; set; } } ``` I don't know why data have `krs_podmioty.object`. I try to cut *\_\_invalid\_name\_\_krs\_podmioty* but then `JsonConvert.DeserializeObject` from package `JSON.Net` didn't work. Any one know what is wrong? What should I do to fix it?<issue_comment>username_1: Please see if this works for you. It's important to have a root object which then *contains* the `data`. Also, using the [`JsonPropertyAttribute`](https://www.newtonsoft.com/json/help/html/SerializationAttributes.htm#JsonPropertyAttribute) helps in cases where the property names differ from the actual JSON property names. ``` public class Rootobject { public Data data { get; set; } } public class Data { [JsonProperty(PropertyName = "krs_podmioty.data_sprawdzenia")] public DateTime krs_podmiotydata_sprawdzenia { get; set; } [JsonProperty(PropertyName = "krs_podmioty.regon")] public string krs_podmiotyregon { get; set; } [JsonProperty(PropertyName = "krs_podmioty.adres_lokal")] public string krs_podmiotyadres_lokal { get; set; } [JsonProperty(PropertyName = "krs_podmioty.adres_miejscowosc")] public string krs_podmiotyadres_miejscowosc { get; set; } [JsonProperty(PropertyName = "krs_podmioty.liczba_czlonkow_komitetu_zal")] public int krs_podmiotyliczba_czlonkow_komitetu_zal { get; set; } } ``` --- If it does *not*, please show where you get the JSON from and show the structure of the objects you serialize to JSON. Upvotes: 3 [selected_answer]<issue_comment>username_2: I have tried this code. This works for me: ``` public class Data { [JsonProperty(PropertyName = "krs_podmioty.data_sprawdzenia")] public DateTime data_sprawdzenia { get; set; } [JsonProperty(PropertyName = "krs_podmioty.regon")] public string regon { get; set; } [JsonProperty(PropertyName = "krs_podmioty.adres_lokal")] public string adres_lokal { get; set; } [JsonProperty(PropertyName = "krs_podmioty.adres_miejscowosc")] public string adres_miejscowosc { get; set; } [JsonProperty(PropertyName = "krs_podmioty.liczba_czlonkow_komitetu_zal")] public int liczba_czlonkow_komitetu_zal { get; set; } } var json = "{ \"data\": { \"krs_podmioty.data_sprawdzenia\": \"2016 -12-22T05:36:21\", \"krs_podmioty.regon\": \"0\", \"krs_podmioty.adres_lokal\": \"\", \"krs_podmioty.adres_miejscowosc\": \"Warszawa\", \"krs_podmioty.liczba_czlonkow_komitetu_zal\": 0,} }"; var t = JsonConvert.DeserializeObject(json); ``` Upvotes: 2
2018/03/21
1,236
4,366
<issue_start>username_0: When I type `M-;`, this invokes `comment-dwim` which, on a line containing text and with no active region, I believe ultimately invokes `comment-indent` to add an in-line or end-of-line comment. In this custom major-mode, `comment-start` is set to `"# "` (and `comment-style` is `'plain`) but this should only apply at the very start of a line. How do I get an in-line comment to start with `";; "`? Example of current behaviour: ``` # Whole line comment SOME CODE HERE # in-line comment ``` Example of required behaviour: ``` # Whole line comment SOME CODE HERE ;; in-line comment ``` Additionally, `comment-region` works perfectly when region starts at the beginning of a line and `comment-start` is always left-aligned for this. However, halfway through a line, it will begin the comment with `comment-start` (`#`).<issue_comment>username_1: You may need to make custom syntax table as described at [Emacs Wiki](https://www.emacswiki.org/emacs/EmacsSyntaxTable) and [ErgoEmacs](http://ergoemacs.org/emacs/elisp_syntax_table.html): For example, for my cql-mode I use following to distinguish between `/* .. */` for block comments, and `--` or `//` for single-line/end-of line comments. ``` (defvar cql-mode-syntax-table (let ((st (make-syntax-table))) (modify-syntax-entry ?/ ". 124b" st) (modify-syntax-entry ?* ". 23" st) ;; double-dash starts comments (modify-syntax-entry ?- ". 12b" st) ;; newline and formfeed end comments (modify-syntax-entry ?\n "> b" st) (modify-syntax-entry ?\f "> b" st) st) "Syntax table for CQL mode") ``` and in declaration of derived mode I specify: ``` (set-syntax-table cql-mode-syntax-table) ``` And meaning is described in documentation for function `modify-syntax-entry`: for `/` - `1` means that character can start comment, `2` means that it could be also 2nd character in sequence, `4` - that it finishes comment, `b` is that it could be comment type `b`. for `*` it says that it could be second or second to last character of comment type `a` (default type). Similarly, for `-` it declares that it could be first & second characters in comment type `b`. In your case it could look following way (not tested): ``` (defvar some-mode-syntax-table (let ((st (make-syntax-table))) (modify-syntax-entry ?# ". 1b" st) ;; double-; starts comments (modify-syntax-entry ?; ". 12b" st) ;; newline and formfeed end comments (modify-syntax-entry ?\n "> b" st) (modify-syntax-entry ?\f "> b" st) st) "Syntax table for some mode") ``` Upvotes: 1 <issue_comment>username_2: I've managed to write a solution to this: I noted that `comment-indent-function` is a variable which holds (from emacs `describe-variable`): > > Function to compute desired indentation for a comment. > This function is called with no args with point at the beginning of > the comment's starting delimiter and should return either the desired > column indentation or nil. > If nil is returned, indentation is delegated to `indent-according-to-mode'. > > > This allows creation of a custom function which can replace `comment-start` and return `nil` to allow default indentation, noting that when this function is called, `point` will be "at the beginning of the comment's starting delimiter" (i.e. at the beginning of `comment-start`). The following is now included in my custom major mode `comment-indent` (through `comment-dwim`) now behaves as required: ``` ;; (defun my-major-mode () (interactive) (kill-all-local-variables) ... (make-local-variable 'comment-start) (make-local-variable 'comment-indent-function) (make-local-variable 'comment-indent-start) ... (setq major-mode 'my-major-mode ... comment-start "# " comment-indent-function 'my-comment-indent comment-indent-start ";; " ) ... ) (defun my-comment-indent () "Replace indented '#' with ';;'" (interactive) (if (not (looking-back ".\\{1\\}")) ;; if comment is left aligned 0 ;; leave it left aligned (return 0) (progn ;; else: don't return until we're ready (looking-at comment-start) ;; find "#" (replace-match comment-indent-start)) ;; replace with ";;" nil))) ;; return `nil' for default indentation ``` Upvotes: 0
2018/03/21
997
3,246
<issue_start>username_0: I've successfully created a PWA for my site, but after I've added it to my home screen and I open up the app, the icon on the splash screen remains extremely small. My manifest has both a 192x192 and 512x512 icon, but as I've read from here (<https://developers.google.com/web/updates/2015/10/splashscreen>), it picks the closes to 128dp to display. Since a the A2HS banner requires a 192x192 in the manifest, does that mean that the splash screen icon will always be super small? Is there no way to make the icon larger for the splash screen?<issue_comment>username_1: Customs screens are automatically shown if you've met this following requirements: [Recommendations](https://developers.google.com/web/tools/lighthouse/audits/custom-splash-screen#recommendations) Chrome for Android automatically shows your custom splash screen so long as you meet the following requirements in your web app manifest: * The `name` property is set to the name of your PWA. * The `background_color` property is set to a valid CSS color value. * The `icons` array specifies an icon that is at least **512px by 512px**. * The icon exists and is a **PNG**. So do that and check if your 512 png image is used this time. Upvotes: 0 <issue_comment>username_2: **TL;DR:** remove your 192x192 icon and your splash screen should default to the 512x512 icon. Check out this [issue about auditing icon size](https://github.com/GoogleChrome/lighthouse/issues/291) on the Google Chrome Lighthouse issues which provides the following: > > ...There are 2 layouts for splash screens. You get the "small icon layout" if the icon you provide is <= 80dp. You get the "large icon layout" if it's over >80 dp. Ideal size for splash screen is 128dp. (There is also a way that a non-provided icon is used, though it's unclear what that is.) > > > It seems that if there is an icon at 192x192 in the `manifest.json` that an icon at 512x512 will not be used. Check the comments in the link above for some discussion on this - it remains an open issue. I had the same problem with my PWA and tested removing the 192x192 image leaving the 512x512 and the splash screen icon was larger. I think I will try having a 1024x1024 and removing the 512x512 next build. **EDIT:** I tried the 1024x1024 and confirmed there are only 2 layouts depending on the dp. The 1024x1024 didn't display and the splash screen defaulted to a smaller one I had at 384x384. Upvotes: 3 <issue_comment>username_3: When we create react app by default 512x512 192x192 this property not have in manifast.json icon size, so that Web app icon get change on splash screen of Mobile/Desktop/Tablet etc. In **manifest.json** need to configure following way, if you are developing react project then you can find manifest.json file in `public/manifest.json` directory. ``` { "short_name": "thefarmerson", "name": "This is official page of <NAME> Indian Computer Science Engineer", "icons": [ { "src": "favicon.ico", "sizes": " 512x512 192x192 64x64 32x32 24x24 16x16", "type": "image/x-icon" } ], "start_url": "./index.html", "display": "standalone", "theme_color": "#000000", "background_color": "#ffffff" } ``` Upvotes: 2
2018/03/21
714
2,848
<issue_start>username_0: I have a SOAP message as as string which looks like: ``` String testMsg = "Some Header stuffSome Body Stuff"; ``` Then it goes to XPath but can't find a node (came as null) to set text value ``` Document doc = convertStringToDocument(testMsg); XPath xpath = XPathFactory.newInstance().newXPath(); String expression = "//soap:Envelope/soap:Body"; Node node = (Node) xpath.evaluate(expression, doc, XPathConstants.NODE); // Set the node content node.setTextContent("Body was removed"); ``` I try to convert it to XML document using method below ``` private static Document convertStringToDocument(String xmlStr) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); try { DocumentBuilder builder = factory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(xmlStr)); Document doc = builder.parse(is); return doc; } catch (Exception e) { e.printStackTrace(); } return null; } ``` Any thoughts?<issue_comment>username_1: You definitely should redirect your question to IDE debugger. For me such code snippet works properly. For example, I can output text inside `Header` tags like so ``` System.out.println( doc.getElementsByTagNameNS("http://www.w3.org/2003/05/soap-envelope", "Header") .item(0).getTextContent()); ``` It outputs expected `Some Header stuff`. In your case I think you'd printed `Document` instance itself and saw result like `[#document: null]` which confused you. But the truth is that the object exist. **UPDATE** You forget to let `XPath` be aware of your namespace. This will do that you want. ``` XPath xpath = XPathFactory.newInstance().newXPath(); xpath.setNamespaceContext(new NamespaceContext() { @Override public Iterator getPrefixes(String namespaceURI) { // TODO Auto-generated method stub return null; } @Override public String getPrefix(String namespaceURI) { // TODO Auto-generated method stub return null; } @Override public String getNamespaceURI(String prefix) { if ("soap".equals(prefix)) { return "http://www.w3.org/2003/05/soap-envelope"; } return null; } }); String expression = "/soap:Envelope/soap:Body"; Node node = (Node) xpath.compile(expression).evaluate(doc, XPathConstants.NODE); node.setTextContent("Body was removed"); ``` Hope it helps! Upvotes: 2 [selected_answer]<issue_comment>username_2: Other solution is to set ``` factory.setNamespaceAware(false); ``` and then update XPath code to ``` String expression = "/Envelope/Body"; Node node = (Node) xpath.compile(expression).evaluate(doc, XPathConstants.NODE); ``` Hope it will help somebody else. Upvotes: 0
2018/03/21
516
1,959
<issue_start>username_0: I need that when the user returns to the home the color of the navigation bar becomes transparent so that the background of the view is appreciated in full screen I found an example page with the desired effect: <https://angular.io/> I need to do this but in react [here my project code](https://i.stack.imgur.com/rN55X.png)<issue_comment>username_1: You can set the header class / style based on the route params from `react-router`. Then if you're in the homepage route set the color and maybe make it not fixed (if you want it to behave like in angular.io) Upvotes: 0 <issue_comment>username_2: There are two ways: 1. In Header.js render method you can check `window.location.pathname` if it matches `/` which is root and usually homepage. If that is correct, append some class to header element and style it accordingly. 2. In Header.js you can `import { withRouter } from "react-router-dom";` after which you can use HOC (Higher Order Component) withRouter in the bottom where you export the component `export default withRouter(Header);` After this you can use `componentWillReceiveProps` lifecycle method (read more [here](http://busypeoples.github.io/post/react-component-lifecycle/)), and check if `nextProps.location.pathname` matches `/` and set state accordingly, which then you can use to append class. **Note** Recent activity on this answer prompted me to update this as most of this is obsolete. Recommended use now is to use `useLocation` hook instead of withRouter HOC or window.location.pathname, but the latter will still work just fine. Upvotes: 3 [selected_answer]<issue_comment>username_3: I garet, thanks. this is my code index.js ``` . . import {... HashRouter,withRouter**} from 'react-router-dom'; . . const HeaderWithRouter = withRouter(Header);//<- needed this ReactDOM.render( // to use here to have access to this.props.location in the header . . . ``` header.js ``` ``` Upvotes: 0
2018/03/21
1,526
5,506
<issue_start>username_0: I'm trying to configure an installer to conditionally install certain components only when certain versions of a 3rd party application are installed. It should be noted there is a 1:1 correspondence between the 3rd party software version and ours.. are there are dozens of such releases of the 3rd party software (plus up to three additional releases each month), so we do not want to be performing hand editing. Our programs are automatically built against all releases of the 3rd party software, but which files get installed needs to occur conditionally. <\EDIT> I'm only deploying this as a single .MSI, so no Bootstrapper etc. From my readings and googlings, I believe that I need to have an UPGRADE section, to identify what PRODUCTCODE the application will currently have (multiple versions.. so there are multiple PRODUCTCODEs possible). This PRODUCTCODE can then be used to read the DisplayVersion out of the registry. So I have: ``` ``` for the UPGRADE section, and then.. ``` ``` For the REGISTRYSEARCH. It seems that the PRODUCTCODE lookup is working, however the Registrysearch isn't.. (I'm expecting a PROPERTY CHANGE entry after the AppSearch) ``` FindRelatedProducts: Found application: {2ACE38B2-F142-4EFE-9AC7-B25514E4930E} MSI (c) (F0:90) [23:17:39:598]: PROPERTY CHANGE: Adding CLEARSCADADETECTED property. Its value is '{2ACE38B2-F142-4EFE-9AC7-B25514E4930E}'. Action ended 23:17:39: FindRelatedProducts. Return value 1. ... AppSearch: Property: CLEARSCADA_VER, Signature: ClearSCADAVersionSearch MSI (c) (F0:90) [23:17:39:629]: Note: 1: 2262 2: Signature 3: -2147287038 Action ended 23:17:39: AppSearch. Return value 1. ``` I've tried hardcoding the registry lookup (i.e. replacing the [CLEARSCADADETECTED] by static text of {2ACE38B2-F142-4EFE-9AC7-B25514E4930E}), without any change. [![Regedit showing registry key exists](https://i.stack.imgur.com/CpotJ.png)](https://i.stack.imgur.com/CpotJ.png) Any other suggestions for what to check would be greatly appreciated. Ok, confusingly, if I reference the Version DWORD value (instead of the DisplayVersion String value) then it does read it correctly as #105781730. Is it possible that the RegistrySearch wouldn't work for String values? Yay... it's working. And I guess it's been working for a while now also. When I put the Value='6.78.6626.1', I should have realised that if the version that I was testing it on was already '6.78.6626.1' then it wouldn't have indicated a PROPERTY CHANGE. Bevan<issue_comment>username_1: It's not clear that you need the registry search because you can have more than one UpgradeVersion element, each with the version you want. So multiple ProductCode values are not something you need to worry about in the search. This documentation here: <https://www.firegiant.com/wix/tutorial/upgrades-and-modularization/checking-for-oldies/> shows examples of multiple UpgradeVersion element. Having said that, the easiest thing would be to have one UpgradeVersion that refers to the exact range of versions that you care about, and this will set your property if anything in that range is found. You just need to set the minimum and maximum to the values. Your registry search screen shot seems to show what is probably the native registry on a 64-bit system. Your search does not explicitly set Win64 and might be searching the 32-bit registry. Upvotes: 0 <issue_comment>username_2: I didn't test with the actual major upgrade detection, but maybe try to remove the `Hidden` attribute which would seem to remove the set property operation from the log. I initially also removed the `Value` attribute, but put it back and now set it equal to 0: ``` ``` I ran a quick test and this works for me. And you are correctly searching the 64-bit section of the registry (provided this is indeed the section you want to search) with the settings in your WiX file. Perhaps you have updated your question since username_1 answered? --- I also verified that the **registry search** is **not case sensitive**. I couldn't remember if it was or not. To inspect **searches and property values**, you can use a script custom action for debugging (then there is no compilation and hassle). * A VBScript will do fine for debugging, but shouldn't be used for production code. * I can dump in the required WiX custom action elements for a VBScript custom action that shows property values for you, but I don't want to make this answer any more verbose than it already is if you don't want it. --- Are you sure there will be only one version of the 3rd party application installed at a time? Maybe a check with the vendor and some assurances of how they will do their deployment going forward could save you a sudden problem later on? *Dependencies on the behavior of other packages can be a time bomb - it is **very tight coupling out of your control**. Not to sound too dramatic, it is probably fine. Just mentioning it. And checking this is a manager task if you ask me.* It is sort of **neat what you are doing**, but sadly I often experience that logic gets more complicated over time and I eventually have to resort to a custom action to deal with all kinds of edge cases. Let's hope you don't have to go down that road, since you are doing the right thing [trying to avoid custom actions](https://stackoverflow.com/questions/46179778/why-is-it-a-good-idea-to-limit-the-use-of-custom-actions-in-my-wix-msi-setups/46179779#46179779). Upvotes: 2 [selected_answer]
2018/03/21
832
3,365
<issue_start>username_0: How should I choose between `new ScheduledThreadPoolExecutor(1).scheduleWithFixedDelay` or `Handler.postDelayed()`? Are they same? What are the differences between them? ``` Future scheduledFuture = scheduledExecutor.scheduleWithFixedDelay(runnable, 0, delay, TimeUnit.MILLISECONDS); ``` --- ``` new Handler().postDelayed(runnable, delay); ```<issue_comment>username_1: It's not clear that you need the registry search because you can have more than one UpgradeVersion element, each with the version you want. So multiple ProductCode values are not something you need to worry about in the search. This documentation here: <https://www.firegiant.com/wix/tutorial/upgrades-and-modularization/checking-for-oldies/> shows examples of multiple UpgradeVersion element. Having said that, the easiest thing would be to have one UpgradeVersion that refers to the exact range of versions that you care about, and this will set your property if anything in that range is found. You just need to set the minimum and maximum to the values. Your registry search screen shot seems to show what is probably the native registry on a 64-bit system. Your search does not explicitly set Win64 and might be searching the 32-bit registry. Upvotes: 0 <issue_comment>username_2: I didn't test with the actual major upgrade detection, but maybe try to remove the `Hidden` attribute which would seem to remove the set property operation from the log. I initially also removed the `Value` attribute, but put it back and now set it equal to 0: ``` ``` I ran a quick test and this works for me. And you are correctly searching the 64-bit section of the registry (provided this is indeed the section you want to search) with the settings in your WiX file. Perhaps you have updated your question since username_1 answered? --- I also verified that the **registry search** is **not case sensitive**. I couldn't remember if it was or not. To inspect **searches and property values**, you can use a script custom action for debugging (then there is no compilation and hassle). * A VBScript will do fine for debugging, but shouldn't be used for production code. * I can dump in the required WiX custom action elements for a VBScript custom action that shows property values for you, but I don't want to make this answer any more verbose than it already is if you don't want it. --- Are you sure there will be only one version of the 3rd party application installed at a time? Maybe a check with the vendor and some assurances of how they will do their deployment going forward could save you a sudden problem later on? *Dependencies on the behavior of other packages can be a time bomb - it is **very tight coupling out of your control**. Not to sound too dramatic, it is probably fine. Just mentioning it. And checking this is a manager task if you ask me.* It is sort of **neat what you are doing**, but sadly I often experience that logic gets more complicated over time and I eventually have to resort to a custom action to deal with all kinds of edge cases. Let's hope you don't have to go down that road, since you are doing the right thing [trying to avoid custom actions](https://stackoverflow.com/questions/46179778/why-is-it-a-good-idea-to-limit-the-use-of-custom-actions-in-my-wix-msi-setups/46179779#46179779). Upvotes: 2 [selected_answer]
2018/03/21
880
3,418
<issue_start>username_0: what i need ``` select column1,column2,column3 from table where condition ``` output should be > > select column1 from table where condition > > > i try to use explode ``` print_r (explode(",",$str)); ``` Output i need Array ``` [0] => SELECT column1 [1] => from [2] => table ``` and so on . but it will split into array and sql is dyanmic . * any suggestion is most welcome.<issue_comment>username_1: It's not clear that you need the registry search because you can have more than one UpgradeVersion element, each with the version you want. So multiple ProductCode values are not something you need to worry about in the search. This documentation here: <https://www.firegiant.com/wix/tutorial/upgrades-and-modularization/checking-for-oldies/> shows examples of multiple UpgradeVersion element. Having said that, the easiest thing would be to have one UpgradeVersion that refers to the exact range of versions that you care about, and this will set your property if anything in that range is found. You just need to set the minimum and maximum to the values. Your registry search screen shot seems to show what is probably the native registry on a 64-bit system. Your search does not explicitly set Win64 and might be searching the 32-bit registry. Upvotes: 0 <issue_comment>username_2: I didn't test with the actual major upgrade detection, but maybe try to remove the `Hidden` attribute which would seem to remove the set property operation from the log. I initially also removed the `Value` attribute, but put it back and now set it equal to 0: ``` ``` I ran a quick test and this works for me. And you are correctly searching the 64-bit section of the registry (provided this is indeed the section you want to search) with the settings in your WiX file. Perhaps you have updated your question since username_1 answered? --- I also verified that the **registry search** is **not case sensitive**. I couldn't remember if it was or not. To inspect **searches and property values**, you can use a script custom action for debugging (then there is no compilation and hassle). * A VBScript will do fine for debugging, but shouldn't be used for production code. * I can dump in the required WiX custom action elements for a VBScript custom action that shows property values for you, but I don't want to make this answer any more verbose than it already is if you don't want it. --- Are you sure there will be only one version of the 3rd party application installed at a time? Maybe a check with the vendor and some assurances of how they will do their deployment going forward could save you a sudden problem later on? *Dependencies on the behavior of other packages can be a time bomb - it is **very tight coupling out of your control**. Not to sound too dramatic, it is probably fine. Just mentioning it. And checking this is a manager task if you ask me.* It is sort of **neat what you are doing**, but sadly I often experience that logic gets more complicated over time and I eventually have to resort to a custom action to deal with all kinds of edge cases. Let's hope you don't have to go down that road, since you are doing the right thing [trying to avoid custom actions](https://stackoverflow.com/questions/46179778/why-is-it-a-good-idea-to-limit-the-use-of-custom-actions-in-my-wix-msi-setups/46179779#46179779). Upvotes: 2 [selected_answer]
2018/03/21
963
3,777
<issue_start>username_0: In my php script i have the following query: ``` SELECT inv as INVOICE, shpdate as SHIPDATE FROM table1 WHERE to_date(char(shpdate), 'YYYYMMDD') >= '2018-01-01' ``` which returns records successfully. This is taking a packed value and returning it to match the YYYY-MM-DD format. I'm trying to add an interval and insert to mysql like so: ``` INSERT INTO table (column1) values(DATE_ADD(DATE_FORMAT(CONVERT(:SHIPDATE, CHAR(20)), '%Y-%m-%d'),INTERVAL 127 DAY) as expire_date) ``` But when I run this it says it is not a valid function. I know the query is successful, but the insert is failing, most likely because I'm not using the DATE-ADD correctly for some reason. Any help on how to change this insert syntax is much appreciated.<issue_comment>username_1: It's not clear that you need the registry search because you can have more than one UpgradeVersion element, each with the version you want. So multiple ProductCode values are not something you need to worry about in the search. This documentation here: <https://www.firegiant.com/wix/tutorial/upgrades-and-modularization/checking-for-oldies/> shows examples of multiple UpgradeVersion element. Having said that, the easiest thing would be to have one UpgradeVersion that refers to the exact range of versions that you care about, and this will set your property if anything in that range is found. You just need to set the minimum and maximum to the values. Your registry search screen shot seems to show what is probably the native registry on a 64-bit system. Your search does not explicitly set Win64 and might be searching the 32-bit registry. Upvotes: 0 <issue_comment>username_2: I didn't test with the actual major upgrade detection, but maybe try to remove the `Hidden` attribute which would seem to remove the set property operation from the log. I initially also removed the `Value` attribute, but put it back and now set it equal to 0: ``` ``` I ran a quick test and this works for me. And you are correctly searching the 64-bit section of the registry (provided this is indeed the section you want to search) with the settings in your WiX file. Perhaps you have updated your question since username_1 answered? --- I also verified that the **registry search** is **not case sensitive**. I couldn't remember if it was or not. To inspect **searches and property values**, you can use a script custom action for debugging (then there is no compilation and hassle). * A VBScript will do fine for debugging, but shouldn't be used for production code. * I can dump in the required WiX custom action elements for a VBScript custom action that shows property values for you, but I don't want to make this answer any more verbose than it already is if you don't want it. --- Are you sure there will be only one version of the 3rd party application installed at a time? Maybe a check with the vendor and some assurances of how they will do their deployment going forward could save you a sudden problem later on? *Dependencies on the behavior of other packages can be a time bomb - it is **very tight coupling out of your control**. Not to sound too dramatic, it is probably fine. Just mentioning it. And checking this is a manager task if you ask me.* It is sort of **neat what you are doing**, but sadly I often experience that logic gets more complicated over time and I eventually have to resort to a custom action to deal with all kinds of edge cases. Let's hope you don't have to go down that road, since you are doing the right thing [trying to avoid custom actions](https://stackoverflow.com/questions/46179778/why-is-it-a-good-idea-to-limit-the-use-of-custom-actions-in-my-wix-msi-setups/46179779#46179779). Upvotes: 2 [selected_answer]
2018/03/21
780
2,804
<issue_start>username_0: I am using the Azure IoT Device Client SDK for .NET Core (1.17.0-preview-001 but also tried 1.7.0-stable). When calling `deviceClient.GetTwinAsync()`all fields are `NULL`except for the `Properties`(Desired as well as Reported are there): [![enter image description here](https://i.stack.imgur.com/AsQm4.png)](https://i.stack.imgur.com/AsQm4.png) At least things like DeviceId I would expect to be there. Also when I add any Tags in the DeviceTwin, those does not get down to the device. Is this a bug or am I missing something?<issue_comment>username_1: You can use **Microsoft.Azure.Devices** to get device twin.It is a service client SDK for Azure IoT Hub. ``` dynamic registryManager = RegistryManager.CreateFromConnectionString("{connectionString}"); var deviceTwin = await registryManager.GetTwinAsync("{device name}"); ``` In this [article](https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-sdks),maybe you will get more understanding about Azure IoT SDKs. > > * **Device SDKs** enable you to build apps that run on your IoT devices. These apps send telemetry to your IoT hub, and optionally receive messages from your IoT hub. > * **Service SDKs** enable you to manage your IoT hub, and optionally send messages to your IoT devices. > > > Upvotes: -1 <issue_comment>username_2: The device twin composed with **tags**, **properties**(desired, reported) and **metadata**. And we can only query the **properties** from **device app** like figure below as the document [stated](https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-device-twins): [![enter image description here](https://i.stack.imgur.com/z4y1V.png)](https://i.stack.imgur.com/z4y1V.png) You can also refer the [Azure IoT hub endpoints](https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-endpoints) for the specific operation support by Azure IoT hub like figure below: [![enter image description here](https://i.stack.imgur.com/jHJTy.png)](https://i.stack.imgur.com/jHJTy.png) ***Device twin management***. Each IoT hub exposes a set of **service-facing HTTPS REST endpoint** to query and update device twins (update tags and properties). This behavior is also easy to verified by tracking the raw data using Fiddler. For example, here is a query to get device twin from Azure IoT Hub using the MQTT protocol via MQTTBOX: [![enter image description here](https://i.stack.imgur.com/SwuvP.png)](https://i.stack.imgur.com/SwuvP.png) And based on my understanding, the device app rarely need that info. You may consider manage the device twin from service-endpoint instead of client app. If you do have that kind of special scenario, you can submit the feedback from [Azure IoT - UserVoice](https://i.stack.imgur.com/qejF0.png) . Upvotes: 2 [selected_answer]
2018/03/21
873
3,116
<issue_start>username_0: I read about char\*, that it should be used and instead of it I should use just char[]. Does it concern also function types? I paste below this what I read and my code below. > > will place "Hello world" in the read-only parts of the memory, and making s a pointer to that makes any writing operation on this memory illegal > [What is the difference between char s[] and char \*s?](https://stackoverflow.com/questions/1704407/what-is-the-difference-between-char-s-and-char-s) > > > ``` char* GetModulePath() { char ownPth[MAX_PATH]; HMODULE hModule = GetModuleHandle(NULL); if (hModule != NULL) { GetModuleFileName(hModule, ownPth, (sizeof(ownPth))); } return ownPth; } ``` So is it ok? Maybe instead of char\* I should do it using const chars\* ? EDIT: added link of this article which I've read.<issue_comment>username_1: You can use **Microsoft.Azure.Devices** to get device twin.It is a service client SDK for Azure IoT Hub. ``` dynamic registryManager = RegistryManager.CreateFromConnectionString("{connectionString}"); var deviceTwin = await registryManager.GetTwinAsync("{device name}"); ``` In this [article](https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-sdks),maybe you will get more understanding about Azure IoT SDKs. > > * **Device SDKs** enable you to build apps that run on your IoT devices. These apps send telemetry to your IoT hub, and optionally receive messages from your IoT hub. > * **Service SDKs** enable you to manage your IoT hub, and optionally send messages to your IoT devices. > > > Upvotes: -1 <issue_comment>username_2: The device twin composed with **tags**, **properties**(desired, reported) and **metadata**. And we can only query the **properties** from **device app** like figure below as the document [stated](https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-device-twins): [![enter image description here](https://i.stack.imgur.com/z4y1V.png)](https://i.stack.imgur.com/z4y1V.png) You can also refer the [Azure IoT hub endpoints](https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-endpoints) for the specific operation support by Azure IoT hub like figure below: [![enter image description here](https://i.stack.imgur.com/jHJTy.png)](https://i.stack.imgur.com/jHJTy.png) ***Device twin management***. Each IoT hub exposes a set of **service-facing HTTPS REST endpoint** to query and update device twins (update tags and properties). This behavior is also easy to verified by tracking the raw data using Fiddler. For example, here is a query to get device twin from Azure IoT Hub using the MQTT protocol via MQTTBOX: [![enter image description here](https://i.stack.imgur.com/SwuvP.png)](https://i.stack.imgur.com/SwuvP.png) And based on my understanding, the device app rarely need that info. You may consider manage the device twin from service-endpoint instead of client app. If you do have that kind of special scenario, you can submit the feedback from [Azure IoT - UserVoice](https://i.stack.imgur.com/qejF0.png) . Upvotes: 2 [selected_answer]
2018/03/21
644
1,971
<issue_start>username_0: I have a some data stored in $cache[], there are some number in it. How do I remove duplicate values in a printed output? : ``` #mysql connect mysql_connect($host,$user,$pass) or die(mysql_error()); mysql_select_db($name) or die(mysql_error()); function get_numerics ($str) { preg_match_all('/\d+/', $str, $matches); return $matches[0]; } function validatecard($number) { //preg_match_all('/^[6-9][0-9]{9}$/', $number, $found); preg_match_all('/^[0-9]{4}$/',$number, $found); //print_r($found); return $found[0]; } $query = mysql_query("SELECT * FROM client WHERE status = 1 ORDER BY id") or die(mysql_error()); while ($raw = mysql_fetch_array($query)) { $name = $raw["postdata"]; $id = $raw["id"]; $cache = []; for($i=0;$i<=count(get_numerics($name));$i++){ $ccv = get_numerics($name); $num = $ccv[$i]; if (is_numeric($num)) { $cc = validatecard($num); if (!in_array($cc, $cache)){ $cache[] = $cc; } } } print_r($cache); } ? ``` i have use some function like :array unique and convert it to json or serialize... and not work.<issue_comment>username_1: Use the `array_unique($array)` function. It removes duplicate values of an array. Please check this for more information : > > <http://php.net/manual/en/function.array-unique.php> > > > Upvotes: 2 <issue_comment>username_2: If $cache is multidimensionnal then array\_unique will not work. You may want to use : ``` $input = array_map("unserialize", array_unique(array_map("serialize", $input))); ``` See : [How to remove duplicate values from a multi-dimensional array in PHP](https://stackoverflow.com/questions/307674/how-to-remove-duplicate-values-from-a-multi-dimensional-array-in-php) Upvotes: 1 <issue_comment>username_3: Or let the database handle the removing the duplication with DISTINCT ``` SELECT DISTINCT id , postdata FROM client WHERE status = 1 ORDER BY id ASC ``` Upvotes: 0
2018/03/21
825
2,942
<issue_start>username_0: I am trying to use Golang as a REST API. I have managed to get handlers to work and queries as well. But not got a query inside a handler to work. When the query resides within the main() it works: ``` func handleRequests() { http.HandleFunc("/getuser", Getuser) } ---> this handler gets respons on localhost:8080/getuser func Getuser(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Getuser") } func main() { handleRequests() //Connect to db rows, err := db.Queryx(`SELECT "USER_ID","USER_NAME" FROM user`) for rows.Next() { results := make(map[string]interface{}) err = rows.MapScan(results) fmt.Printf("%#v\n", results) } log.Fatal(http.ListenAndServe(":8080", nil)) } ``` But when I move the query to the handler it gives an error that the db is not defined. ``` func handleRequests() { http.HandleFunc("/getuser", Getuser) } ---> this gives the error that the db is not defined func Getuser(w http.ResponseWriter, r *http.Request) { rows, err := db.Queryx(`SELECT "USER_ID","USER_NAME" FROM user`) for rows.Next() { results := make(map[string]interface{}) err = rows.MapScan(results) fmt.Printf("%#v\n", results) } } func main() { handleRequests() //Connect to db log.Fatal(http.ListenAndServe(":8080", nil)) } ``` **EDIT** Full code inside the handler (added db var as suggested), but gives various errors on "err". ``` var db *sqlx.DB <---solved the db problem func Getsign(w http.ResponseWriter, r *http.Request) { rows, err := db.Queryx(`SELECT "USER_ID","USER_NAME" FROM user`) for rows.Next() { results := make(map[string]interface{}) err = rows.MapScan(results) fmt.Printf("%#v\n", results) } defer rows.Close() if err := rows.Err(); err != nil { log.Fatal(err) } } ``` Any tip what I am doing wrong?<issue_comment>username_1: Define your db variable outside of main, e.g.: ``` var db *sql.DB func handler(w http.ResponseWriter, r *http.Request) { rows, err := db.Query(...) // use it } func main() { db, _ = sql.Open(...) } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: For what I can see with the code you posted (next time I suggest to post the full code) you are declaring the db variable on the main function but you are referring it in a function who have no visibility of that variable. In order to fix the problem you have various way. the easiest way is to declare a global variable like `var db typename` and on the main function don't use the `:=` assign but only `=`. In this mode you can set the global variable (in the other case you are create a local variable named db in the main function). Note in a concurrency environment this could be a problem, consider to study your driver library to see if have some guarantee about concurrency or best practice. Upvotes: 0
2018/03/21
742
2,852
<issue_start>username_0: Hello my code looks okay but I don't know why its visible without scrolling the page. ``` jQuery(document).ready(function($){ //Check to see if the window is top if not then display button $(window).scroll(function(){ if ($(this).scrollTop() > 100) { $('.TopButton').fadeIn(); } else { $('.TopButton').fadeOut(); } }); //Click event to scroll to top $('.TopButton').click(function(){ $('html, body').animate({scrollTop : 0},360); return false; }); }); ``` So, I have used `if ($(this).scrollTop() > 100` but when I open the page its showing the button without scrolling the page.When I scroll the page and go back to top its working and hiding the button. Do you have any idea what Im doing wrong?<issue_comment>username_1: Try this code ``` jQuery(document).ready(function($){ // hide the topbutton on page load/ready. $('.TopButton').hide(); //Check to see if the window is top if not then display button $(window).scroll(function(){ if ($(this).scrollTop() > 100) { $('.TopButton').show().fadeIn(); } else { $('.TopButton').fadeOut().hide(); } }); //Click event to scroll to top $('.TopButton').click(function(){ $('html, body').animate({scrollTop : 0},360); return false; }); }); ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: You have to check the scrollTop on ready, now you are doing it only on scroll. ``` jQuery(document).ready(function($){ //Check to see if the window is top if not then display button toggleButton() $(window).scroll(toggleButton); //Click event to scroll to top $('.TopButton').click(function(){ $('html, body').animate({scrollTop : 0},360); return false; }); }); function toggleButton() { if ($(window).scrollTop() > 100) { $('.TopButton').fadeIn(); } else { $('.TopButton').fadeOut(); } } ``` Upvotes: 0 <issue_comment>username_3: The scroll event occurs when the user scrolls in the specified element. So, check for the position of the scrollbar on document load. ``` jQuery(document).ready(function($){ //check if window scroll is < 100 if($(window).scrollTop() < 100){ $('.TopButton').fadeOut().hide(); } //Check to see if the window is top if not then display button $(window).scroll(function(){ if ($(this).scrollTop() > 100) { $('.TopButton').show().fadeIn(); } else { $('.TopButton').fadeOut().hide(); } }); //Click event to scroll to top $('.TopButton').click(function(){ $('html, body').animate({scrollTop : 0},360); return false; }); }); ``` Or you may even hide the button by default, as Mr.ZZ mentioned in the comment. Upvotes: 1
2018/03/21
486
1,672
<issue_start>username_0: ``` import React, { Component } from 'react'; import axios from 'axios'; import './App.css'; class App extends Component { state = {user:[]} componentDidMount(){ axios.get('http://a99d12de.ngrok.io/api/Docs') .then(res => { const user = res.data; this.setState({user}); }) .catch((error) =>{ alert(error); }) } render() { return ( names ====== {this.state.user.map(person => * {person.data.fname} )} ) } } export default App; ``` Please correct my mistakes.. I am just trying to rectify some data from server/url.I dont know why the map function is not defined.<issue_comment>username_1: ``` render(){ let array = this.state.user || [] return( names ====== {array.map((item,index) => ( * {item.fname} ))} ``` Upvotes: 0 <issue_comment>username_2: Probably your response data is `JSON String`, you must use `JSON.parse(user)` ``` (res => { const user = JSON.parse(res.data); this.setState({user}); }) ``` Upvotes: 0 <issue_comment>username_3: Axios is wrapping the response in an object that has a `data` property. So I guess you have to do something like this: ``` axios.get('http://a99d12de.ngrok.io/api/Docs') .then(res => { // axios wrapped the data in a response object with a data property const data = res.data; // Your API also wrapped the data in a response object with a data property :) const user = data.data; this.setState({user}); }) .catch((error) =>{ alert(error); }) } ``` See the axios docs [here](https://github.com/axios/axios). Upvotes: 2 [selected_answer]
2018/03/21
1,362
4,040
<issue_start>username_0: I have a table with detail rows. We want to make transactions for aggregated values from this table. There might be situations, where one row is positive and the another one negative. The aggregate is 0. I want to remove those rows. Here is my example: ``` DECLARE @tmp TABLE ( orderid INT , account INT , vatid INT , amount DECIMAL(10,2) , vat DECIMAL(10,2) ) --test values INSERT @tmp VALUES ( 10001, 30500, 47, 175.50, 9.20 ) , ( 10001, 30501, 47, 2010.60, 18.30 ) , ( 10001, 30501, 47, 147.65, 8.05 ) , ( 10001, 30502, 47, 321.15, 18.40 ) , ( 10001, 30502, 47, 13.50, 0.95 ) , ( 10001, 30510, 40, 15.00, 0.0 ) , ( 10001, 30510, 40, -15.00, 0.0 ) --all rows SELECT * FROM @tmp --aggregate --aggregate for account 30510 is 0 SELECT tmp.orderid , tmp.account , tmp.vatid , SUM(tmp.amount) [totalamount] , SUM(tmp.vat) [totalvat] FROM @tmp tmp GROUP BY tmp.orderid , tmp.account , tmp.vatid --delete rows with aggregated values 0 DELETE tmp FROM @tmp tmp JOIN ( SELECT ag.orderid , ag.account , ag.vatid FROM ( SELECT tmp.orderid , tmp.account , tmp.vatid , SUM(tmp.amount) [totalamount] , SUM(tmp.vat) [totalvat] FROM @tmp tmp GROUP BY tmp.orderid , tmp.account , tmp.vatid ) ag WHERE ISNULL(ag.totalamount,0) = 0 AND ISNULL(ag.totalvat,0) = 0 ) tmp2 ON tmp2.orderid = tmp.orderid AND tmp2.account = tmp.account AND tmp2.vatid = tmp.vatid --check rows SELECT * FROM @tmp ``` My code works and deletes rows with aggregated values of 0. But it doesn't look very elegant. Is there a better way to achieve the same result? Greetings Reto<issue_comment>username_1: **Try this** > > Used `HAVING` at the earlier stage instead of `WHERE` at later stage. So query will filter out unwanted records right at grouping level and will still produce same results. > > > ``` --delete rows with aggregated values 0 DELETE tmp FROM @tmp tmp JOIN ( SELECT ag.orderid , ag.account , ag.vatid FROM ( SELECT tmp.orderid , tmp.account , tmp.vatid -- Removed unwanted aggregates from select clause here FROM @tmp tmp GROUP BY tmp.orderid , tmp.account , tmp.vatid HAVING SUM(tmp.amount) = 0 -- This line is updated AND SUM(tmp.vat) = 0 -- This line is updated ) ag -- Removed WHERE clause from here and added HAVING above ) tmp2 ON tmp2.orderid = tmp.orderid AND tmp2.account = tmp.account AND tmp2.vatid = tmp.vatid ``` Upvotes: 1 <issue_comment>username_2: I would use a common table expression to get only the rows that needs to be deleted, and then delete from the table using an inner join to the cte on the group by columns: ``` ;WITH CTE AS ( SELECT tmp.orderid , tmp.account , tmp.vatid FROM @tmp tmp GROUP BY tmp.orderid , tmp.account , tmp.vatid HAVING SUM(tmp.amount) = 0 AND SUM(tmp.vat) = 0 ) DELETE t FROM @Tmp as t JOIN CTE ON t.orderid = cte.orderid AND t.account = cte.account AND t.vatid = cte.vatid ``` [You can see a live demo on rextester.](http://rextester.com/ZVG65589) Upvotes: 1 <issue_comment>username_3: Using [window function](https://learn.microsoft.com/en-us/sql/t-sql/queries/select-over-clause-transact-sql) ``` delete tt from ( select sum(t.vat) over (partition by t.orderid, t.account, t.vatid) as sumVat , sum(t.amount) over (partition by t.orderid, t.account, t.vatid) as sumAmt from @tmp t ) tt where isnull(tt.sumAmt, 0) = 0 and isnull(tt.sumVat, 0) = 0 ``` Upvotes: 3 [selected_answer]
2018/03/21
752
2,281
<issue_start>username_0: I have written the following code, when you click on the button the whole style will be changed. ```js $(".Button1").click(function() { $(this).toggleClass('Button1Changed'); }); ``` ```css .Button1 { background-color:#000000; color:#ffffff; } .Button1Changed { background-color:#ff0000; color:#ffffff; } ``` ```html Button 1 - Click ``` But now I need to add some new buttons, like the code below. I want that when I click the "Button 2", the styles of the "Button 1" again changes to the first class! Or when I click on the "Button 3", the style of the button 2 changes again & ... How can I do it ?! ```js $(".Button1").click(function() { $(this).toggleClass('Button1Changed'); }); ``` ```css .Button1 { background-color:#000000; color:#ffffff; } .Button1Changed { background-color:#ff0000; color:#ffffff; } ``` ```html Button 1 - Click Button 2 - Click Button 3 - Click Button 4 - Click ```<issue_comment>username_1: You can exclude current element i.e.`this` using [`.not()`](http://api.jquery.com/not/) method and [`.removeClass()`](http://api.jquery.com/removeClass/) from other elements. ``` $(".Button1").not(this).removeClass('Button1Changed'); ``` ```js $(".Button1").click(function() { $(".Button1").not(this).removeClass('Button1Changed'); $(this).toggleClass('Button1Changed'); }); ``` ```css .Button1 { background-color: #000000; color: #ffffff; } .Button1Changed { background-color: #ff0000; color: #ffffff; } ``` ```html Button 1 - Click Button 2 - Click Button 3 - Click Button 4 - Click ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: Another approach can be based on [.add()](https://api.jquery.com/add/): toggle the classes of the current element and the last changed button: ``` $('.Button1.Button1Changed').add(this).toggleClass('Button1Changed'); ``` ```js $(".Button1").on('click', function(e) { $('.Button1.Button1Changed').add(this).toggleClass('Button1Changed'); }); ``` ```css .Button1 { background-color: #000000; color: #ffffff; } .Button1Changed { background-color: #ff0000; color: #ffffff; } ``` ```html Button 1 - Click Button 2 - Click Button 3 - Click Button 4 - Click ``` Upvotes: 0
2018/03/21
604
1,926
<issue_start>username_0: i am trying to call a function on right click on the select box which has disabled attribute. but i am unable to call a function.if i remove disabled attribute, then the right click is working. ```js function hello() { alert('clicked'); window.event.returnValue = false; } ``` ```css #testSelect { width: 100px; height: 20px; } ``` ```html 1 2 3 4 ``` How can i do this?<issue_comment>username_1: Wrap it in a tag and call it by using .click() function from jquery. [Click function](https://api.jquery.com/click/) Upvotes: -1 <issue_comment>username_2: You won't be able to trigger any mouse event on a `disabled` select. **BUT** I added a dirty trick that uses a div to simulate the effect : Put a `div` after your select, position it on top of your select and give it a `display: none`. Add the CSS rule `.yourSelect:disabled + .yourDiv{display: block;}` to put the new div on top of your select. You will then be able to catch mouse events on that div. **Demo:** ```js $(document).on('contextmenu','.dirty-hack', e => { alert('clicked'); return false; }); ``` ```css body { margin: 0; } #testSelect { width: 100px; height: 20px; } div.dirty-hack { position: absolute; top: 0; display: none; width: 100px; height: 20px; } #testSelect:disabled+.dirty-hack { display: block; } ``` ```html 1 2 3 4 ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: You can just disable interaction with this select if disabled and create a dummy element which will catch the click: ```js let element = document.getElementById('dummy'); element.addEventListener('contextmenu', (e)=>{ alert('clicked'); e.preventDefault(); e.stopPropagation(); }); ``` ```css #testSelect { width: 100px; height: 20px; } #testSelect:disabled { pointer-events: none; } ``` ```html 1 2 3 4 ``` Upvotes: 0
2018/03/21
660
3,081
<issue_start>username_0: I have created the following alert dialog with a simple view comprising of a `TextView`, `EditText` and `Button`: ``` alert { customView { verticalLayout { textView { text = getString(R.string.enter_quantity) textSize = 18f textColor = Color.BLACK }.lparams { topMargin = dip(17) horizontalMargin = dip(17) bottomMargin = dip(10) } val quantity = editText { inputType = InputType.TYPE_CLASS_NUMBER background = ContextCompat.getDrawable(this@ProductsList, R.drawable.textbox_bg) }.lparams(width = matchParent, height = wrapContent) { bottomMargin = dip(10) horizontalMargin = dip(17) } button(getString(R.string.confirm)) { background = ContextCompat.getDrawable(this@ProductsList, R.color.colorPrimary) textColor = Color.WHITE }.lparams(width = matchParent, height = matchParent) { topMargin = dip(10) }.setOnClickListener { if (quantity.text.isNullOrBlank()) snackbar(parentLayout!!, getString(R.string.enter_valid_quantity)) else addToCart(product, quantity.text.toString().toInt()) } } } }.show() ``` I want to dismiss it whenever the button is clicked and the `if-else` clause has been executed. I tried using `this@alert` but it doesn't provide the dialog methods.<issue_comment>username_1: This is problematic because your `button` function call which registers the listener executes when the dialog doesn't even exist yet. Here's one way to do it, using a local [`lateinit`](https://kotlinlang.org/docs/reference/properties.html#late-initialized-properties-and-variables) variable to make the `dialog` available inside the listener: ``` lateinit var dialog: DialogInterface dialog = alert { customView { button("Click") { dialog.dismiss() } } }.show() ``` You could also assign the result of the builder to a class property, etc. Note that `lateinit` for local variables is available [since Kotlin 1.2](https://kotlinlang.org/docs/reference/whatsnew12.html#lateinit-top-level-properties-and-local-variables). Upvotes: 4 [selected_answer]<issue_comment>username_2: You can do simply, `it.dismiss()` inside yes or no button callback, like this here `it` is `DialogInterface`: ``` alert(getString(R.string.logout_message),getString(R.string.logout_title)){ yesButton { // some code here it.dismiss() } noButton { it.dismiss() } }.show() ``` Upvotes: 0