qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
7,179,174
As most C programmers know, you can't directly compare two structures. Consider: ``` void isequal(MY_STRUCT a, MY_STRUCT b) { if (a == b) { puts("equal"); } else { puts("not equal"); } } ``` The `a==b` comparison will AFAIK throw a compile error on any sensible C compiler, because the C standard doesn't allow for built-in structure comparison. Workarounds using memcmp are of course a bad idea due to alignment, packing, bitfields etc., so we end up writing element by element comparison functions. On the other hand it DOES allow for structure assignment e.g. `a = b` is entirely legal. Clearly the compiler can cope with that fairly trivially, so why not comparison? The only idea I had was that structure assignment is probably fairly close to memcpy(), as the gaps due to alignment etc. don't matter. On the other hand, a comparison might be more complicated. Or is this something I'm missing? Obviously, I'm aware that doing a simple element by element comparison isn't necessarily enough, e.g. if the structure contains a pointer to a string, but there are circumstances where it would be useful.
2011/08/24
[ "https://Stackoverflow.com/questions/7179174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/152962/" ]
As others have mentioned, here's an extract from [C: A Reference Manual](https://rads.stackoverflow.com/amzn/click/com/013089592X) by Harbison and Steele: > > Structures and unions cannot be compared for equality, even though assignment for these types is allowed. The gaps in structures and unions caused by alignment restrictions could contain arbitrary values, and compensating for this would impose an unacceptable overhead on the equality comparison or on all operations that modified structure and union types. > > >
Comparison is unsupported for the same reason `memcmp` fails. Due to padding fields the comparison would fail in unpredictable ways which would be unacceptable for most programmers. Assignment changes the invisible padding fields, but these are invisible anyway, so nothing unexpected there. Obviously, you may ask: so why doesn't it just zero-fill all the padding fields ? Sure that would work but it would also make all programs pay for something they might not need. ### EDIT [Oli Charlesworth](https://stackoverflow.com/users/129570/oli-charlesworth) notes in the comments that you may be asking: "why doesn't the compiler generate code for member-by-member comparison". If that is the case, I must confess: **I don't know** :-). The compiler would have all the needed information if it would only allow comparing complete types.
7,179,174
As most C programmers know, you can't directly compare two structures. Consider: ``` void isequal(MY_STRUCT a, MY_STRUCT b) { if (a == b) { puts("equal"); } else { puts("not equal"); } } ``` The `a==b` comparison will AFAIK throw a compile error on any sensible C compiler, because the C standard doesn't allow for built-in structure comparison. Workarounds using memcmp are of course a bad idea due to alignment, packing, bitfields etc., so we end up writing element by element comparison functions. On the other hand it DOES allow for structure assignment e.g. `a = b` is entirely legal. Clearly the compiler can cope with that fairly trivially, so why not comparison? The only idea I had was that structure assignment is probably fairly close to memcpy(), as the gaps due to alignment etc. don't matter. On the other hand, a comparison might be more complicated. Or is this something I'm missing? Obviously, I'm aware that doing a simple element by element comparison isn't necessarily enough, e.g. if the structure contains a pointer to a string, but there are circumstances where it would be useful.
2011/08/24
[ "https://Stackoverflow.com/questions/7179174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/152962/" ]
Comparison is unsupported for the same reason `memcmp` fails. Due to padding fields the comparison would fail in unpredictable ways which would be unacceptable for most programmers. Assignment changes the invisible padding fields, but these are invisible anyway, so nothing unexpected there. Obviously, you may ask: so why doesn't it just zero-fill all the padding fields ? Sure that would work but it would also make all programs pay for something they might not need. ### EDIT [Oli Charlesworth](https://stackoverflow.com/users/129570/oli-charlesworth) notes in the comments that you may be asking: "why doesn't the compiler generate code for member-by-member comparison". If that is the case, I must confess: **I don't know** :-). The compiler would have all the needed information if it would only allow comparing complete types.
To add to the existing good answers: ``` struct foo { union { uint32_t i; float f; } u; } a, b; a.u.f = -0.0; b.u.f = 0.0; if (a==b) // what to do?! ``` The problem arises inherently from unions not being able to store/track which member is current.
7,179,174
As most C programmers know, you can't directly compare two structures. Consider: ``` void isequal(MY_STRUCT a, MY_STRUCT b) { if (a == b) { puts("equal"); } else { puts("not equal"); } } ``` The `a==b` comparison will AFAIK throw a compile error on any sensible C compiler, because the C standard doesn't allow for built-in structure comparison. Workarounds using memcmp are of course a bad idea due to alignment, packing, bitfields etc., so we end up writing element by element comparison functions. On the other hand it DOES allow for structure assignment e.g. `a = b` is entirely legal. Clearly the compiler can cope with that fairly trivially, so why not comparison? The only idea I had was that structure assignment is probably fairly close to memcpy(), as the gaps due to alignment etc. don't matter. On the other hand, a comparison might be more complicated. Or is this something I'm missing? Obviously, I'm aware that doing a simple element by element comparison isn't necessarily enough, e.g. if the structure contains a pointer to a string, but there are circumstances where it would be useful.
2011/08/24
[ "https://Stackoverflow.com/questions/7179174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/152962/" ]
As others have mentioned, here's an extract from [C: A Reference Manual](https://rads.stackoverflow.com/amzn/click/com/013089592X) by Harbison and Steele: > > Structures and unions cannot be compared for equality, even though assignment for these types is allowed. The gaps in structures and unions caused by alignment restrictions could contain arbitrary values, and compensating for this would impose an unacceptable overhead on the equality comparison or on all operations that modified structure and union types. > > >
Auto-generate comparison operator is bad idea. Imagine how comparison would work for this structure: ``` struct s1 { int len; char str[100]; }; ``` This is pascal like string with maximum length 100 Another case ``` struct s2 { char a[100]; } ``` How can the compiler know how to compare a field? If this is a NUL-terminated string, the compiler must use strcmp or strncmp. If this is char array compiler must use memcmp.
7,179,174
As most C programmers know, you can't directly compare two structures. Consider: ``` void isequal(MY_STRUCT a, MY_STRUCT b) { if (a == b) { puts("equal"); } else { puts("not equal"); } } ``` The `a==b` comparison will AFAIK throw a compile error on any sensible C compiler, because the C standard doesn't allow for built-in structure comparison. Workarounds using memcmp are of course a bad idea due to alignment, packing, bitfields etc., so we end up writing element by element comparison functions. On the other hand it DOES allow for structure assignment e.g. `a = b` is entirely legal. Clearly the compiler can cope with that fairly trivially, so why not comparison? The only idea I had was that structure assignment is probably fairly close to memcpy(), as the gaps due to alignment etc. don't matter. On the other hand, a comparison might be more complicated. Or is this something I'm missing? Obviously, I'm aware that doing a simple element by element comparison isn't necessarily enough, e.g. if the structure contains a pointer to a string, but there are circumstances where it would be useful.
2011/08/24
[ "https://Stackoverflow.com/questions/7179174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/152962/" ]
Auto-generate comparison operator is bad idea. Imagine how comparison would work for this structure: ``` struct s1 { int len; char str[100]; }; ``` This is pascal like string with maximum length 100 Another case ``` struct s2 { char a[100]; } ``` How can the compiler know how to compare a field? If this is a NUL-terminated string, the compiler must use strcmp or strncmp. If this is char array compiler must use memcmp.
To add to the existing good answers: ``` struct foo { union { uint32_t i; float f; } u; } a, b; a.u.f = -0.0; b.u.f = 0.0; if (a==b) // what to do?! ``` The problem arises inherently from unions not being able to store/track which member is current.
7,179,174
As most C programmers know, you can't directly compare two structures. Consider: ``` void isequal(MY_STRUCT a, MY_STRUCT b) { if (a == b) { puts("equal"); } else { puts("not equal"); } } ``` The `a==b` comparison will AFAIK throw a compile error on any sensible C compiler, because the C standard doesn't allow for built-in structure comparison. Workarounds using memcmp are of course a bad idea due to alignment, packing, bitfields etc., so we end up writing element by element comparison functions. On the other hand it DOES allow for structure assignment e.g. `a = b` is entirely legal. Clearly the compiler can cope with that fairly trivially, so why not comparison? The only idea I had was that structure assignment is probably fairly close to memcpy(), as the gaps due to alignment etc. don't matter. On the other hand, a comparison might be more complicated. Or is this something I'm missing? Obviously, I'm aware that doing a simple element by element comparison isn't necessarily enough, e.g. if the structure contains a pointer to a string, but there are circumstances where it would be useful.
2011/08/24
[ "https://Stackoverflow.com/questions/7179174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/152962/" ]
As others have mentioned, here's an extract from [C: A Reference Manual](https://rads.stackoverflow.com/amzn/click/com/013089592X) by Harbison and Steele: > > Structures and unions cannot be compared for equality, even though assignment for these types is allowed. The gaps in structures and unions caused by alignment restrictions could contain arbitrary values, and compensating for this would impose an unacceptable overhead on the equality comparison or on all operations that modified structure and union types. > > >
I found this in the C rationale ([C99 rationale V5.10](http://www.open-std.org/jtc1/sc22/wg14/www/C99RationaleV5.10.pdf)), 6.5.9: > > The C89 Committee considered, on more than one occasion, permitting comparison of structures > for equality. Such proposals foundered on the problem of holes in structures. A byte-wise > comparison of two structures would require that the holes assuredly be set to zero so that all > holes would compare equal, a difficult task for automatic or dynamically allocated variables. > > > The possibility of union-type elements in a structure raises insuperable problems with this > approach. Without the assurance that all holes were set to zero, the implementation would have > to be prepared to break a structure comparison into an arbitrary number of member comparisons; > a seemingly simple expression could thus expand into a substantial stretch of code, which is > contrary to the spirit of C > > > In plain English: Since structs/unions may contain padding bytes, and the committee had not enforced these to hold certain values, they wouldn't implement this feature. Because if all padding bytes must be set to zero, it would require additional run-time overhead.
7,179,174
As most C programmers know, you can't directly compare two structures. Consider: ``` void isequal(MY_STRUCT a, MY_STRUCT b) { if (a == b) { puts("equal"); } else { puts("not equal"); } } ``` The `a==b` comparison will AFAIK throw a compile error on any sensible C compiler, because the C standard doesn't allow for built-in structure comparison. Workarounds using memcmp are of course a bad idea due to alignment, packing, bitfields etc., so we end up writing element by element comparison functions. On the other hand it DOES allow for structure assignment e.g. `a = b` is entirely legal. Clearly the compiler can cope with that fairly trivially, so why not comparison? The only idea I had was that structure assignment is probably fairly close to memcpy(), as the gaps due to alignment etc. don't matter. On the other hand, a comparison might be more complicated. Or is this something I'm missing? Obviously, I'm aware that doing a simple element by element comparison isn't necessarily enough, e.g. if the structure contains a pointer to a string, but there are circumstances where it would be useful.
2011/08/24
[ "https://Stackoverflow.com/questions/7179174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/152962/" ]
As others have mentioned, here's an extract from [C: A Reference Manual](https://rads.stackoverflow.com/amzn/click/com/013089592X) by Harbison and Steele: > > Structures and unions cannot be compared for equality, even though assignment for these types is allowed. The gaps in structures and unions caused by alignment restrictions could contain arbitrary values, and compensating for this would impose an unacceptable overhead on the equality comparison or on all operations that modified structure and union types. > > >
To add to the existing good answers: ``` struct foo { union { uint32_t i; float f; } u; } a, b; a.u.f = -0.0; b.u.f = 0.0; if (a==b) // what to do?! ``` The problem arises inherently from unions not being able to store/track which member is current.
7,179,174
As most C programmers know, you can't directly compare two structures. Consider: ``` void isequal(MY_STRUCT a, MY_STRUCT b) { if (a == b) { puts("equal"); } else { puts("not equal"); } } ``` The `a==b` comparison will AFAIK throw a compile error on any sensible C compiler, because the C standard doesn't allow for built-in structure comparison. Workarounds using memcmp are of course a bad idea due to alignment, packing, bitfields etc., so we end up writing element by element comparison functions. On the other hand it DOES allow for structure assignment e.g. `a = b` is entirely legal. Clearly the compiler can cope with that fairly trivially, so why not comparison? The only idea I had was that structure assignment is probably fairly close to memcpy(), as the gaps due to alignment etc. don't matter. On the other hand, a comparison might be more complicated. Or is this something I'm missing? Obviously, I'm aware that doing a simple element by element comparison isn't necessarily enough, e.g. if the structure contains a pointer to a string, but there are circumstances where it would be useful.
2011/08/24
[ "https://Stackoverflow.com/questions/7179174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/152962/" ]
I found this in the C rationale ([C99 rationale V5.10](http://www.open-std.org/jtc1/sc22/wg14/www/C99RationaleV5.10.pdf)), 6.5.9: > > The C89 Committee considered, on more than one occasion, permitting comparison of structures > for equality. Such proposals foundered on the problem of holes in structures. A byte-wise > comparison of two structures would require that the holes assuredly be set to zero so that all > holes would compare equal, a difficult task for automatic or dynamically allocated variables. > > > The possibility of union-type elements in a structure raises insuperable problems with this > approach. Without the assurance that all holes were set to zero, the implementation would have > to be prepared to break a structure comparison into an arbitrary number of member comparisons; > a seemingly simple expression could thus expand into a substantial stretch of code, which is > contrary to the spirit of C > > > In plain English: Since structs/unions may contain padding bytes, and the committee had not enforced these to hold certain values, they wouldn't implement this feature. Because if all padding bytes must be set to zero, it would require additional run-time overhead.
To add to the existing good answers: ``` struct foo { union { uint32_t i; float f; } u; } a, b; a.u.f = -0.0; b.u.f = 0.0; if (a==b) // what to do?! ``` The problem arises inherently from unions not being able to store/track which member is current.
36,647,703
I would like to convert scalar tensor (`tf.constant([4])` for example) to python scalar (4) inside a computational graph so without use `tf.eval()`.
2016/04/15
[ "https://Stackoverflow.com/questions/36647703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4851438/" ]
Constant values are hardwired into the graph, so you can see it by inspecting graph definition. IE ``` tf.reset_default_graph() tf.constant(42) print tf.get_default_graph().as_graph_def() ``` This gives you ``` node { name: "Const" op: "Const" attr { key: "dtype" value { type: DT_INT32 } } attr { key: "value" value { tensor { dtype: DT_INT32 tensor_shape { } int_val: 42 } } } } versions { producer: 9 } ``` This means you can get the constant value out as ``` tf.get_default_graph().as_graph_def().node[0].attr["value"].tensor.int_val[0] ```
You can also use the Session.run() method. ``` In [1]: import tensorflow as tf In [2]: sess = tf.InteractiveSession() In [3]: x = tf.constant(4) In [4]: sess.run(x) Out[4]: 4 ```
5,144,775
I have the latest version of code in my website(Quite a few PHP files are modified). but the code that i have in my local host is bit older. Are there any file-comparison applications to find the latest modified code?
2011/02/28
[ "https://Stackoverflow.com/questions/5144775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/521710/" ]
Yes, It is [WinMerge](http://winmerge.org/)
You want `diff` to compare files, but more to the point, you should be using a version control system so you don't have these sorts of problems.
5,144,775
I have the latest version of code in my website(Quite a few PHP files are modified). but the code that i have in my local host is bit older. Are there any file-comparison applications to find the latest modified code?
2011/02/28
[ "https://Stackoverflow.com/questions/5144775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/521710/" ]
Yes, It is [WinMerge](http://winmerge.org/)
[ExamDiff](http://www.prestosoft.com/edp_examdiff.asp)... One .exe file that would solve your problem.
5,144,775
I have the latest version of code in my website(Quite a few PHP files are modified). but the code that i have in my local host is bit older. Are there any file-comparison applications to find the latest modified code?
2011/02/28
[ "https://Stackoverflow.com/questions/5144775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/521710/" ]
You want `diff` to compare files, but more to the point, you should be using a version control system so you don't have these sorts of problems.
[ExamDiff](http://www.prestosoft.com/edp_examdiff.asp)... One .exe file that would solve your problem.
50,557,650
I'm trying to achieve a layout that shows a view pager when the device is shown on portrait and show two panes when device is on landscape. So I made two different layout files, one with only a ViewPager, the other with a LinearLayout and the other with two FrameLayouts, I don't think it is necessary to show them here. There is also a boolean value `hasTwoPanes` for the two configurations. ``` @Inject FragmentOne fragmentOne; @Inject FragmentTwo fragmentTwo; @Override protected void onCreate(Bundle state) { super.onCreate(state); setContentView(R.layout.activity_main); FragmentManager fm = getSupportFragmentManager(); boolean hasTwoPanes = getResources().getBoolean(R.bool.hasTwoPanes); TabLayout tabLayout = findViewById(R.id.tab_layout); ViewPager viewPager = findViewById(R.id.view_pager); if (hasTwoPanes) { tabLayout.setVisibility(View.GONE); } else { tabLayout.setVisibility(View.VISIBLE); tabLayout.setupWithViewPager(viewPager); viewPager.setAdapter(new MyPagerAdapter(fm)); } FragmentOne frag1 = (FragmentOne) fm.findFragmentByTag(getFragmentName(0)); if (frag1 != null) fragmentOne = frag1; FragmentTwo frag2 = (FragmentTwo) fm.findFragmentByTag(getFragmentName(1)); if (frag2 != null) fragmentTwo = frag2; if (hasTwoPanes) { if (frag1 != null) { fm.beginTransaction().remove(fragmentOne).commit(); fm.beginTransaction().remove(fragmentTwo).commit(); fm.executePendingTransactions(); } fm.beginTransaction().add(R.id.frame_frag1, fragmentOne, getFragmentName(0)).commit(); fm.beginTransaction().add(R.id.frame_frag2, fragmentTwo, getFragmentName(1)).commit(); } } private class MyPagerAdapter extends FragmentPagerAdapter { MyPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { if (position == 0) { return fragmentOne; } else { return fragmentTwo; } } @Override public int getCount() { return 2; } } private static String getFragmentName(int pos) { return "android:switcher:" + R.id.view_pager + ":" + pos; } ``` Two fragments are injected with Dagger. If no fragments were already present, these injected fragments are added to the view pager or the layout depending on the orientation. Because the view pager adapter gives a name to its fragments, I need to know that name (hence `getFragmentName(int pos)` method) to get back that fragment after rotation. The result is state is correctly restored when rotating from portrait to landscape, but when rotating from landscape the portrait, the view pager is completely empty. When I rotate back to landscape, the fragments reappear. The tab layout is also buggy, there is no swipe animation, I can just continuously slide from one tab to the other, stopping anywhere. To clarify things, this is happening in an Activity, there is no parent fragment. Even though the fragments are not shown, the fragment's `onViewCreated` is called. The view pager seems to correctly restore the fragment references in `instantiateItem`. Also, when debugging, fragments have the `added` to true and `hidden` to false. This make it seem like a view pager rendering issue. * How do I make the view pager show my fragments? * Is there a better way to achieve the behavior I want?
2018/05/28
[ "https://Stackoverflow.com/questions/50557650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5288316/" ]
The solution I found is very simple, override `getPageWidth` in my pager adapter like this: ``` @Override public float getPageWidth(int position) { boolean hasTwoPanes = getResources().getBoolean(R.bool.hasTwoPanes); return hasTwoPanes ? 0.5f : 1.0f; } ``` `R.bool.hasTwoPanes` being a boolean resources available in default configuration and `values-land`. My layout is the same for both configuration, and the tab layout is simply hidden on landscape. The fragment restoration is done automatically by the view pager.
Try this Portrait Xml: ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <android.support.design.widget.TabLayout android:id="@+id/tab" android:layout_width="match_parent" android:layout_height="wrap_content" /> <android.support.v4.view.ViewPager android:id="@+id/pager" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> ``` Landscape Xml: ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <FrameLayout android:id="@+id/fragmentA" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" /> <FrameLayout android:id="@+id/fragmentB" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" /> </LinearLayout> ``` Activity Java: ``` package com.dev4solutions.myapplication; import android.graphics.Point; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import com.dev4solutions.myapplication.fragment.FragmentA; import com.dev4solutions.myapplication.fragment.FragmentB; public class FragmentActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Point point = new Point(); getWindowManager().getDefaultDisplay().getSize(point); setContentView(R.layout.activity_frag); if (point.y > point.x) { TabLayout tabLayout = findViewById(R.id.tab); ViewPager viewPager = findViewById(R.id.pager); tabLayout.setupWithViewPager(viewPager); viewPager.setAdapter(new PagerAdapter(getSupportFragmentManager())); } else { getSupportFragmentManager() .beginTransaction() .add(R.id.fragmentA, new FragmentA()) .commit(); getSupportFragmentManager() .beginTransaction() .add(R.id.fragmentB, new FragmentB()) .commit(); } } } ```
50,557,650
I'm trying to achieve a layout that shows a view pager when the device is shown on portrait and show two panes when device is on landscape. So I made two different layout files, one with only a ViewPager, the other with a LinearLayout and the other with two FrameLayouts, I don't think it is necessary to show them here. There is also a boolean value `hasTwoPanes` for the two configurations. ``` @Inject FragmentOne fragmentOne; @Inject FragmentTwo fragmentTwo; @Override protected void onCreate(Bundle state) { super.onCreate(state); setContentView(R.layout.activity_main); FragmentManager fm = getSupportFragmentManager(); boolean hasTwoPanes = getResources().getBoolean(R.bool.hasTwoPanes); TabLayout tabLayout = findViewById(R.id.tab_layout); ViewPager viewPager = findViewById(R.id.view_pager); if (hasTwoPanes) { tabLayout.setVisibility(View.GONE); } else { tabLayout.setVisibility(View.VISIBLE); tabLayout.setupWithViewPager(viewPager); viewPager.setAdapter(new MyPagerAdapter(fm)); } FragmentOne frag1 = (FragmentOne) fm.findFragmentByTag(getFragmentName(0)); if (frag1 != null) fragmentOne = frag1; FragmentTwo frag2 = (FragmentTwo) fm.findFragmentByTag(getFragmentName(1)); if (frag2 != null) fragmentTwo = frag2; if (hasTwoPanes) { if (frag1 != null) { fm.beginTransaction().remove(fragmentOne).commit(); fm.beginTransaction().remove(fragmentTwo).commit(); fm.executePendingTransactions(); } fm.beginTransaction().add(R.id.frame_frag1, fragmentOne, getFragmentName(0)).commit(); fm.beginTransaction().add(R.id.frame_frag2, fragmentTwo, getFragmentName(1)).commit(); } } private class MyPagerAdapter extends FragmentPagerAdapter { MyPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { if (position == 0) { return fragmentOne; } else { return fragmentTwo; } } @Override public int getCount() { return 2; } } private static String getFragmentName(int pos) { return "android:switcher:" + R.id.view_pager + ":" + pos; } ``` Two fragments are injected with Dagger. If no fragments were already present, these injected fragments are added to the view pager or the layout depending on the orientation. Because the view pager adapter gives a name to its fragments, I need to know that name (hence `getFragmentName(int pos)` method) to get back that fragment after rotation. The result is state is correctly restored when rotating from portrait to landscape, but when rotating from landscape the portrait, the view pager is completely empty. When I rotate back to landscape, the fragments reappear. The tab layout is also buggy, there is no swipe animation, I can just continuously slide from one tab to the other, stopping anywhere. To clarify things, this is happening in an Activity, there is no parent fragment. Even though the fragments are not shown, the fragment's `onViewCreated` is called. The view pager seems to correctly restore the fragment references in `instantiateItem`. Also, when debugging, fragments have the `added` to true and `hidden` to false. This make it seem like a view pager rendering issue. * How do I make the view pager show my fragments? * Is there a better way to achieve the behavior I want?
2018/05/28
[ "https://Stackoverflow.com/questions/50557650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5288316/" ]
The solution I found is very simple, override `getPageWidth` in my pager adapter like this: ``` @Override public float getPageWidth(int position) { boolean hasTwoPanes = getResources().getBoolean(R.bool.hasTwoPanes); return hasTwoPanes ? 0.5f : 1.0f; } ``` `R.bool.hasTwoPanes` being a boolean resources available in default configuration and `values-land`. My layout is the same for both configuration, and the tab layout is simply hidden on landscape. The fragment restoration is done automatically by the view pager.
Have you tried using PagerAdapter instead of FragmentPagerAdapter? You will get better control over creation and handling of fragments. Otherwise you dont know what is the FragmentPagerAdapter doing (hes doing it for you, but probably wrong). You cam move much of that logic into that class making the activity cleaner, and probably also fix the problems you have. EDIT: Since we are talking orientation changes here, you should probably incorporate `onConfigurationChanged` callback to handle that logic better.
20,746,711
I am able to convert a bytestream to its JSON representation. This is a JSONArray. I would like it to be converted to `bb_test` objects in a Vector instead. How do I do that? I used this example of json <http://codeoncloud.blogspot.com/2013/05/blackberry-java-json-tutorial.html> I am getting data from server like this: ``` [ { "settingName": "New", "onclick": "CreateNewDoc()" }, { "settingName": "Open", "settingValue": "OpenDoc()" }, { "settingName": "Close", "settingValue": "CloseDoc()" } ] ``` So I create a class like that ``` package mypackage; public class bb_test { String settingName; /** * */ String settingValue; public String getSettingName() { return settingName; } public void setSettingName(String settingName) { this.settingName = settingName; } public String getSettingValue() { return settingValue; } public void setSettingValue(String settingValue) { this.settingValue = settingValue; } } ```
2013/12/23
[ "https://Stackoverflow.com/questions/20746711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648752/" ]
You should be able to attach a handler to the Bootstrap tab show event.. ``` $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) { initialize(); }); ``` Working demo: <http://bootply.com/102241> -----------------------------------------
``` $('#myTab a[href="#location"]').one('shown.bs.tab', function (e) { initialize(); }); ``` Use **.one()** instead of **.on()**. This will prevent from reloading map again and again ;)
20,746,711
I am able to convert a bytestream to its JSON representation. This is a JSONArray. I would like it to be converted to `bb_test` objects in a Vector instead. How do I do that? I used this example of json <http://codeoncloud.blogspot.com/2013/05/blackberry-java-json-tutorial.html> I am getting data from server like this: ``` [ { "settingName": "New", "onclick": "CreateNewDoc()" }, { "settingName": "Open", "settingValue": "OpenDoc()" }, { "settingName": "Close", "settingValue": "CloseDoc()" } ] ``` So I create a class like that ``` package mypackage; public class bb_test { String settingName; /** * */ String settingValue; public String getSettingName() { return settingName; } public void setSettingName(String settingName) { this.settingName = settingName; } public String getSettingValue() { return settingValue; } public void setSettingValue(String settingValue) { this.settingValue = settingValue; } } ```
2013/12/23
[ "https://Stackoverflow.com/questions/20746711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648752/" ]
You should be able to attach a handler to the Bootstrap tab show event.. ``` $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) { initialize(); }); ``` Working demo: <http://bootply.com/102241> -----------------------------------------
``` $('#myTab a[href="#location"]').on('shown.bs.tab', function (e) { initialize(); }); ```
20,746,711
I am able to convert a bytestream to its JSON representation. This is a JSONArray. I would like it to be converted to `bb_test` objects in a Vector instead. How do I do that? I used this example of json <http://codeoncloud.blogspot.com/2013/05/blackberry-java-json-tutorial.html> I am getting data from server like this: ``` [ { "settingName": "New", "onclick": "CreateNewDoc()" }, { "settingName": "Open", "settingValue": "OpenDoc()" }, { "settingName": "Close", "settingValue": "CloseDoc()" } ] ``` So I create a class like that ``` package mypackage; public class bb_test { String settingName; /** * */ String settingValue; public String getSettingName() { return settingName; } public void setSettingName(String settingName) { this.settingName = settingName; } public String getSettingValue() { return settingValue; } public void setSettingValue(String settingValue) { this.settingValue = settingValue; } } ```
2013/12/23
[ "https://Stackoverflow.com/questions/20746711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648752/" ]
``` $('#myTab a[href="#location"]').on('shown.bs.tab', function (e) { initialize(); }); ```
This might be helpful, no JavaScript tricks needed. ``` .tab-content.tab-pane, .tab-pane { /* display: none; */ display: block; visibility: hidden; position: absolute; } .tab-content.active, .tab-content .tab-pane.active, .tab-pane.active { /* display: block; */ visibility: visible; position: static; } ``` <https://stackoverflow.com/a/32551984/3072600>
20,746,711
I am able to convert a bytestream to its JSON representation. This is a JSONArray. I would like it to be converted to `bb_test` objects in a Vector instead. How do I do that? I used this example of json <http://codeoncloud.blogspot.com/2013/05/blackberry-java-json-tutorial.html> I am getting data from server like this: ``` [ { "settingName": "New", "onclick": "CreateNewDoc()" }, { "settingName": "Open", "settingValue": "OpenDoc()" }, { "settingName": "Close", "settingValue": "CloseDoc()" } ] ``` So I create a class like that ``` package mypackage; public class bb_test { String settingName; /** * */ String settingValue; public String getSettingName() { return settingName; } public void setSettingName(String settingName) { this.settingName = settingName; } public String getSettingValue() { return settingValue; } public void setSettingValue(String settingValue) { this.settingValue = settingValue; } } ```
2013/12/23
[ "https://Stackoverflow.com/questions/20746711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648752/" ]
You should be able to attach a handler to the Bootstrap tab show event.. ``` $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) { initialize(); }); ``` Working demo: <http://bootply.com/102241> -----------------------------------------
I tried to make it to center on each tab click.. but seems need to initialize everytime ... @MrUpsidown any other way we can center the actual location without initializing everytime? **Possible solution ..** <https://stackoverflow.com/a/25347742/3752338>
20,746,711
I am able to convert a bytestream to its JSON representation. This is a JSONArray. I would like it to be converted to `bb_test` objects in a Vector instead. How do I do that? I used this example of json <http://codeoncloud.blogspot.com/2013/05/blackberry-java-json-tutorial.html> I am getting data from server like this: ``` [ { "settingName": "New", "onclick": "CreateNewDoc()" }, { "settingName": "Open", "settingValue": "OpenDoc()" }, { "settingName": "Close", "settingValue": "CloseDoc()" } ] ``` So I create a class like that ``` package mypackage; public class bb_test { String settingName; /** * */ String settingValue; public String getSettingName() { return settingName; } public void setSettingName(String settingName) { this.settingName = settingName; } public String getSettingValue() { return settingValue; } public void setSettingValue(String settingValue) { this.settingValue = settingValue; } } ```
2013/12/23
[ "https://Stackoverflow.com/questions/20746711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648752/" ]
<http://bootply.com/102479> Add an id to your map tab link so it's easier to identify. Trigger a map resize event when the corresponding tab content is shown. This way the map is only initialized once, which is not the case with the previous answer. Note that you need to define the map variable outside of the initialize function.
Bootstrap tabs (and carousels and modals) are initially set to display none, until they become active, so the parent element of your map has height / width of 0. I had the same problem with Bootstrap3 as you. finally I ended up with the simple CSS solution. ``` .tab-content.tab-pane, .tab-pane { /* display: none; */ display: block; visibility: hidden; position: absolute; } .tab-content.active, .tab-content .tab-pane.active, .tab-pane.active { /* display: block; */ visibility: visible; position: static; } ```
20,746,711
I am able to convert a bytestream to its JSON representation. This is a JSONArray. I would like it to be converted to `bb_test` objects in a Vector instead. How do I do that? I used this example of json <http://codeoncloud.blogspot.com/2013/05/blackberry-java-json-tutorial.html> I am getting data from server like this: ``` [ { "settingName": "New", "onclick": "CreateNewDoc()" }, { "settingName": "Open", "settingValue": "OpenDoc()" }, { "settingName": "Close", "settingValue": "CloseDoc()" } ] ``` So I create a class like that ``` package mypackage; public class bb_test { String settingName; /** * */ String settingValue; public String getSettingName() { return settingName; } public void setSettingName(String settingName) { this.settingName = settingName; } public String getSettingValue() { return settingValue; } public void setSettingValue(String settingValue) { this.settingValue = settingValue; } } ```
2013/12/23
[ "https://Stackoverflow.com/questions/20746711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648752/" ]
<http://bootply.com/102479> Add an id to your map tab link so it's easier to identify. Trigger a map resize event when the corresponding tab content is shown. This way the map is only initialized once, which is not the case with the previous answer. Note that you need to define the map variable outside of the initialize function.
``` $('#myTab a[href="#location"]').one('shown.bs.tab', function (e) { initialize(); }); ``` Use **.one()** instead of **.on()**. This will prevent from reloading map again and again ;)
20,746,711
I am able to convert a bytestream to its JSON representation. This is a JSONArray. I would like it to be converted to `bb_test` objects in a Vector instead. How do I do that? I used this example of json <http://codeoncloud.blogspot.com/2013/05/blackberry-java-json-tutorial.html> I am getting data from server like this: ``` [ { "settingName": "New", "onclick": "CreateNewDoc()" }, { "settingName": "Open", "settingValue": "OpenDoc()" }, { "settingName": "Close", "settingValue": "CloseDoc()" } ] ``` So I create a class like that ``` package mypackage; public class bb_test { String settingName; /** * */ String settingValue; public String getSettingName() { return settingName; } public void setSettingName(String settingName) { this.settingName = settingName; } public String getSettingValue() { return settingValue; } public void setSettingValue(String settingValue) { this.settingValue = settingValue; } } ```
2013/12/23
[ "https://Stackoverflow.com/questions/20746711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648752/" ]
``` $('#myTab a[href="#location"]').on('shown.bs.tab', function (e) { initialize(); }); ```
I tried to make it to center on each tab click.. but seems need to initialize everytime ... @MrUpsidown any other way we can center the actual location without initializing everytime? **Possible solution ..** <https://stackoverflow.com/a/25347742/3752338>
20,746,711
I am able to convert a bytestream to its JSON representation. This is a JSONArray. I would like it to be converted to `bb_test` objects in a Vector instead. How do I do that? I used this example of json <http://codeoncloud.blogspot.com/2013/05/blackberry-java-json-tutorial.html> I am getting data from server like this: ``` [ { "settingName": "New", "onclick": "CreateNewDoc()" }, { "settingName": "Open", "settingValue": "OpenDoc()" }, { "settingName": "Close", "settingValue": "CloseDoc()" } ] ``` So I create a class like that ``` package mypackage; public class bb_test { String settingName; /** * */ String settingValue; public String getSettingName() { return settingName; } public void setSettingName(String settingName) { this.settingName = settingName; } public String getSettingValue() { return settingValue; } public void setSettingValue(String settingValue) { this.settingValue = settingValue; } } ```
2013/12/23
[ "https://Stackoverflow.com/questions/20746711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648752/" ]
<http://bootply.com/102479> Add an id to your map tab link so it's easier to identify. Trigger a map resize event when the corresponding tab content is shown. This way the map is only initialized once, which is not the case with the previous answer. Note that you need to define the map variable outside of the initialize function.
This might be helpful, no JavaScript tricks needed. ``` .tab-content.tab-pane, .tab-pane { /* display: none; */ display: block; visibility: hidden; position: absolute; } .tab-content.active, .tab-content .tab-pane.active, .tab-pane.active { /* display: block; */ visibility: visible; position: static; } ``` <https://stackoverflow.com/a/32551984/3072600>
20,746,711
I am able to convert a bytestream to its JSON representation. This is a JSONArray. I would like it to be converted to `bb_test` objects in a Vector instead. How do I do that? I used this example of json <http://codeoncloud.blogspot.com/2013/05/blackberry-java-json-tutorial.html> I am getting data from server like this: ``` [ { "settingName": "New", "onclick": "CreateNewDoc()" }, { "settingName": "Open", "settingValue": "OpenDoc()" }, { "settingName": "Close", "settingValue": "CloseDoc()" } ] ``` So I create a class like that ``` package mypackage; public class bb_test { String settingName; /** * */ String settingValue; public String getSettingName() { return settingName; } public void setSettingName(String settingName) { this.settingName = settingName; } public String getSettingValue() { return settingValue; } public void setSettingValue(String settingValue) { this.settingValue = settingValue; } } ```
2013/12/23
[ "https://Stackoverflow.com/questions/20746711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648752/" ]
``` $('#myTab a[href="#location"]').on('shown.bs.tab', function (e) { initialize(); }); ```
Bootstrap tabs (and carousels and modals) are initially set to display none, until they become active, so the parent element of your map has height / width of 0. I had the same problem with Bootstrap3 as you. finally I ended up with the simple CSS solution. ``` .tab-content.tab-pane, .tab-pane { /* display: none; */ display: block; visibility: hidden; position: absolute; } .tab-content.active, .tab-content .tab-pane.active, .tab-pane.active { /* display: block; */ visibility: visible; position: static; } ```
20,746,711
I am able to convert a bytestream to its JSON representation. This is a JSONArray. I would like it to be converted to `bb_test` objects in a Vector instead. How do I do that? I used this example of json <http://codeoncloud.blogspot.com/2013/05/blackberry-java-json-tutorial.html> I am getting data from server like this: ``` [ { "settingName": "New", "onclick": "CreateNewDoc()" }, { "settingName": "Open", "settingValue": "OpenDoc()" }, { "settingName": "Close", "settingValue": "CloseDoc()" } ] ``` So I create a class like that ``` package mypackage; public class bb_test { String settingName; /** * */ String settingValue; public String getSettingName() { return settingName; } public void setSettingName(String settingName) { this.settingName = settingName; } public String getSettingValue() { return settingValue; } public void setSettingValue(String settingValue) { this.settingValue = settingValue; } } ```
2013/12/23
[ "https://Stackoverflow.com/questions/20746711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648752/" ]
<http://bootply.com/102479> Add an id to your map tab link so it's easier to identify. Trigger a map resize event when the corresponding tab content is shown. This way the map is only initialized once, which is not the case with the previous answer. Note that you need to define the map variable outside of the initialize function.
I tried to make it to center on each tab click.. but seems need to initialize everytime ... @MrUpsidown any other way we can center the actual location without initializing everytime? **Possible solution ..** <https://stackoverflow.com/a/25347742/3752338>
37,623,346
I have stumbled upon this pure python implementation for calculating percentiles [here](https://stackoverflow.com/a/2753343/6421279) and [here](http://code.activestate.com/recipes/51): ``` import math import functools def percentile(N, percent, key=lambda x:x): """ Find the percentile of a list of values. @parameter N - is a list of values. Note N MUST BE already sorted. @parameter percent - a float value from 0.0 to 1.0. @parameter key - optional key function to compute value from each element of N. @return - the percentile of the values """ if not N: return None k = (len(N)-1) * percent f = math.floor(k) c = math.ceil(k) if f == c: return key(N[int(k)]) d0 = key(N[int(f)]) * (c-k) d1 = key(N[int(c)]) * (k-f) return d0+d1 ``` I get the basic principle behind this function and i see that it works correctly: ``` >>> percentile(range(10),0.25) 2.25 ``` What I don't get is what the lambda function `key=lambda x:x` is there for. As far as i unterstand it, this lambda function simply returns the value that is passed to it. Basically, the whole function seems to yield the same result if i omit this lambda function altogether: ``` import math def percentile2(N, percent): """ Find the percentile of a list of values. @parameter N - is a list of values. Note N MUST BE already sorted. @parameter percent - a float value from 0.0 to 1.0. @parameter key - REMOVED @return - the percentile of the values """ if not N: return None k = (len(N)-1) * percent f = math.floor(k) c = math.ceil(k) if f == c: return N[int(k)] d0 = N[int(f)] * (c-k) d1 = N[int(c)] * (k-f) return d0+d1 ``` If I test this: ``` >>> percentile2(range(10),0.25) 2.25 ``` So what is the use of that lambda function, here?
2016/06/03
[ "https://Stackoverflow.com/questions/37623346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4685799/" ]
The answer is right there in the docstring (the string that starts on the line after the `def` statement): ``` @parameter key - optional key function to compute value from each element of N. ``` This allows you to use a list of something other than numbers. For example, your lambda could be `lambda x:x.getRelevantValue()` and your list would be one containing objects that have a `getRelevantValue` method.
It's a tie-breaker in case `f` ever equals `c`. You haven't come across such a case, so your code never blows up (since `key` now doesn't exist).
37,623,346
I have stumbled upon this pure python implementation for calculating percentiles [here](https://stackoverflow.com/a/2753343/6421279) and [here](http://code.activestate.com/recipes/51): ``` import math import functools def percentile(N, percent, key=lambda x:x): """ Find the percentile of a list of values. @parameter N - is a list of values. Note N MUST BE already sorted. @parameter percent - a float value from 0.0 to 1.0. @parameter key - optional key function to compute value from each element of N. @return - the percentile of the values """ if not N: return None k = (len(N)-1) * percent f = math.floor(k) c = math.ceil(k) if f == c: return key(N[int(k)]) d0 = key(N[int(f)]) * (c-k) d1 = key(N[int(c)]) * (k-f) return d0+d1 ``` I get the basic principle behind this function and i see that it works correctly: ``` >>> percentile(range(10),0.25) 2.25 ``` What I don't get is what the lambda function `key=lambda x:x` is there for. As far as i unterstand it, this lambda function simply returns the value that is passed to it. Basically, the whole function seems to yield the same result if i omit this lambda function altogether: ``` import math def percentile2(N, percent): """ Find the percentile of a list of values. @parameter N - is a list of values. Note N MUST BE already sorted. @parameter percent - a float value from 0.0 to 1.0. @parameter key - REMOVED @return - the percentile of the values """ if not N: return None k = (len(N)-1) * percent f = math.floor(k) c = math.ceil(k) if f == c: return N[int(k)] d0 = N[int(f)] * (c-k) d1 = N[int(c)] * (k-f) return d0+d1 ``` If I test this: ``` >>> percentile2(range(10),0.25) 2.25 ``` So what is the use of that lambda function, here?
2016/06/03
[ "https://Stackoverflow.com/questions/37623346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4685799/" ]
It's right there in the documentation of the function: ``` @parameter key - optional key function to compute value from each element of N. ``` Basically, the `percentile` function allows the user to *optionally* pass a key function which will be applied to the elements of N. Since it is optional, it has been given the default value `lambda x:x`, which does nothing, so the function works even if the user omits the `key` parameter.
It's a tie-breaker in case `f` ever equals `c`. You haven't come across such a case, so your code never blows up (since `key` now doesn't exist).
37,623,346
I have stumbled upon this pure python implementation for calculating percentiles [here](https://stackoverflow.com/a/2753343/6421279) and [here](http://code.activestate.com/recipes/51): ``` import math import functools def percentile(N, percent, key=lambda x:x): """ Find the percentile of a list of values. @parameter N - is a list of values. Note N MUST BE already sorted. @parameter percent - a float value from 0.0 to 1.0. @parameter key - optional key function to compute value from each element of N. @return - the percentile of the values """ if not N: return None k = (len(N)-1) * percent f = math.floor(k) c = math.ceil(k) if f == c: return key(N[int(k)]) d0 = key(N[int(f)]) * (c-k) d1 = key(N[int(c)]) * (k-f) return d0+d1 ``` I get the basic principle behind this function and i see that it works correctly: ``` >>> percentile(range(10),0.25) 2.25 ``` What I don't get is what the lambda function `key=lambda x:x` is there for. As far as i unterstand it, this lambda function simply returns the value that is passed to it. Basically, the whole function seems to yield the same result if i omit this lambda function altogether: ``` import math def percentile2(N, percent): """ Find the percentile of a list of values. @parameter N - is a list of values. Note N MUST BE already sorted. @parameter percent - a float value from 0.0 to 1.0. @parameter key - REMOVED @return - the percentile of the values """ if not N: return None k = (len(N)-1) * percent f = math.floor(k) c = math.ceil(k) if f == c: return N[int(k)] d0 = N[int(f)] * (c-k) d1 = N[int(c)] * (k-f) return d0+d1 ``` If I test this: ``` >>> percentile2(range(10),0.25) 2.25 ``` So what is the use of that lambda function, here?
2016/06/03
[ "https://Stackoverflow.com/questions/37623346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4685799/" ]
The answer is right there in the docstring (the string that starts on the line after the `def` statement): ``` @parameter key - optional key function to compute value from each element of N. ``` This allows you to use a list of something other than numbers. For example, your lambda could be `lambda x:x.getRelevantValue()` and your list would be one containing objects that have a `getRelevantValue` method.
It's right there in the documentation of the function: ``` @parameter key - optional key function to compute value from each element of N. ``` Basically, the `percentile` function allows the user to *optionally* pass a key function which will be applied to the elements of N. Since it is optional, it has been given the default value `lambda x:x`, which does nothing, so the function works even if the user omits the `key` parameter.
35,697,513
I'm trying to create an dictionary with names and points from a textfile called "score.txt". The contents of the file is stuctured like this: ``` Anders Johansson 1 Karin Johansson 1 Anders Johansson 2 Eva Johansson 0 ``` + 2000 names and points in total My method of getting the scores, calculating and finding the high-score looks like this ``` f = open('score.txt').read().split() d = {} for x in range(0, len(f), 3): name, value = ' '.join([f[x], f[x+1]]), int(f[x+2]) if(name in d): d[name] += value else: d[name] = value print(max(d, key=d.get),d[max(d, key=d.get)]) ``` I'm pretty new to python so i'm looking for ways to improve my code.
2016/02/29
[ "https://Stackoverflow.com/questions/35697513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5996975/" ]
It already looks non too crazy, but I have a few suggestions: * Naming [Python convention](https://www.python.org/dev/peps/pep-0008/) is descriptive names (scores instead of d). * [File opening](http://www.pythonforbeginners.com/files/with-statement-in-python) is best done with the `with` stanza. * You can iterate over lines so you don't need the `range`. * Use a [`defaultdict`](https://docs.python.org/2/library/collections.html#collections.defaultdict) so you don't need to test for existence in the dict. That would yield: ``` from collections import defaultdict scores = defaultdict(int) with open('score.txt') as infile: for line in infile: fields = line.split() name, score = ' '.join([fields[0], fields[1]]), int(fields[2]) scores[name] += score print(max(scores, key=scores.get), scores[max(scores, key=scores.get)]) ```
Small changes to your code. This will improve the performance a little . **Code:** ``` from collections import defaultdict datas ="""Anders Johansson 1 Karin Johansson 1 Anders Johansson 2 Eva Johansson 0""".split() dic = defaultdict(int) for i in range(0, len(f), 3): name, value = ' '.join([datas[i], datas[i+1]]), int(datas[i+2]) dic[name] += value max_key =max(dic, key=d.get) print(max_key, dic[max_key]) ``` **Output:** ``` ('Anders Johansson', 3) ``` **Notes:** * Since you are falling the same method with same parameter twice `max(d, key=d.get)` I have stored that in a variable and re-used it. * Since the value of the dictionary is only int type I have used defaultdict
35,697,513
I'm trying to create an dictionary with names and points from a textfile called "score.txt". The contents of the file is stuctured like this: ``` Anders Johansson 1 Karin Johansson 1 Anders Johansson 2 Eva Johansson 0 ``` + 2000 names and points in total My method of getting the scores, calculating and finding the high-score looks like this ``` f = open('score.txt').read().split() d = {} for x in range(0, len(f), 3): name, value = ' '.join([f[x], f[x+1]]), int(f[x+2]) if(name in d): d[name] += value else: d[name] = value print(max(d, key=d.get),d[max(d, key=d.get)]) ``` I'm pretty new to python so i'm looking for ways to improve my code.
2016/02/29
[ "https://Stackoverflow.com/questions/35697513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5996975/" ]
It already looks non too crazy, but I have a few suggestions: * Naming [Python convention](https://www.python.org/dev/peps/pep-0008/) is descriptive names (scores instead of d). * [File opening](http://www.pythonforbeginners.com/files/with-statement-in-python) is best done with the `with` stanza. * You can iterate over lines so you don't need the `range`. * Use a [`defaultdict`](https://docs.python.org/2/library/collections.html#collections.defaultdict) so you don't need to test for existence in the dict. That would yield: ``` from collections import defaultdict scores = defaultdict(int) with open('score.txt') as infile: for line in infile: fields = line.split() name, score = ' '.join([fields[0], fields[1]]), int(fields[2]) scores[name] += score print(max(scores, key=scores.get), scores[max(scores, key=scores.get)]) ```
The only semantic problem your code could present is that if you need to deal with [composite names](https://en.wikipedia.org/wiki/Spanish_naming_customs), e.g., *Pablo Ruiz Picasso*. In this case the program will break. Also, if your file is large, for improving the performance would be better to compute the high score while reading the file. My concerns are handled in the following code: ``` from collections import defaultdict highScore = 0 highScoreName = "" scores = defaultdict(int) with open('score.txt') as f: for line in f: fields = line.split() name, score = ' '.join(fields[:-1]), int(fields[-1]) #Handle composite names scores[name] += score if scores[name] > highScore: #Compute high score highScore, highScoreName = scores[name], name print highScoreName, highScore ```
65,812,597
I'm doing a command where you need to confirm something with emojis. I have a `wait_for("reaction_add")` with a check as a lambda function. The following code I have is: ``` try: reaction, user = await self.client.wait_for("reaction_add", check=lambda react, usr: str(reaction.emoji) == "✅" and usr.id == ctx.author.id, timeout=60) print(reaction.emoji) except asyncio.TimeoutError: await confirm_msg.edit(content="This message has timed out!", embed=None) ``` But it doesn't print out the reaction emoji. Without the check the code works fine, so it has to do with the check. How could I fix it? Thanks!
2021/01/20
[ "https://Stackoverflow.com/questions/65812597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13793359/" ]
```py try: reaction, user = await self.client.wait_for("reaction_add", check=lambda reaction, user: str(reaction.emoji) == "✅" and user.id == ctx.author.id, timeout=60) print(reaction.emoji) except asyncio.TimeoutError: await confirm_msg.edit(content="This message has timed out!", embed=None) ```
You can try this, without the lambda function: ``` @client.event async def on_raw_reaction_add(payload): reaction = str(payload.emoji) if reaction == "✅" and usr.id == ctx.author.id: print('do something') else: print('something else') ```
65,812,597
I'm doing a command where you need to confirm something with emojis. I have a `wait_for("reaction_add")` with a check as a lambda function. The following code I have is: ``` try: reaction, user = await self.client.wait_for("reaction_add", check=lambda react, usr: str(reaction.emoji) == "✅" and usr.id == ctx.author.id, timeout=60) print(reaction.emoji) except asyncio.TimeoutError: await confirm_msg.edit(content="This message has timed out!", embed=None) ``` But it doesn't print out the reaction emoji. Without the check the code works fine, so it has to do with the check. How could I fix it? Thanks!
2021/01/20
[ "https://Stackoverflow.com/questions/65812597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13793359/" ]
A **lambda** function is esentially the same as a normal function. Your lambda: ``` lambda react, usr: str(reaction.emoji) == "✅" and usr.id == ctx.author.id ``` Would be equal to defining the following function: ``` # Here we are within the wait_for(reaction_add) def f(react, usr): return str(reaction.emoji) == "✅" and user.id == ctx.author.id # Rest of the code ``` The problem is that the `reaction_add` does not have `react` or `usr` defined. The way to solve your code would be something like this: ``` reaction, user = await self.client.wait_for("reaction_add", check=lambda reaction, user: str(reaction.emoji) == "✅" and user.id == ctx.author.id, timeout=60) ```
You can try this, without the lambda function: ``` @client.event async def on_raw_reaction_add(payload): reaction = str(payload.emoji) if reaction == "✅" and usr.id == ctx.author.id: print('do something') else: print('something else') ```
48,308,839
I was using LIquibase 3.2 and am trying to upgrade to 3.3 and I'm using MySql 5.5. However, upgrading is failing for the following types of change sets ... ``` <changeSet author="me" id="my_changeset"> <addColumn tableName="my_table"> <column name="STUFF_VISIBLE" type="BOOLEAN" defaultValueNumeric="0"> <constraints nullable="false"/> </column> </addColumn> </changeSet> ``` It fails with the error ``` Error: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Invalid default value for 'STUFF_VISIBLE' ``` IS there any way to fix things without having to readjust all the checksums? There are a number of occurrences of these types of statements in my Liquibase change sets.
2018/01/17
[ "https://Stackoverflow.com/questions/48308839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1235929/" ]
Don't use `preg_split()`, use `preg_match_all().` ``` preg_match_all('/\*\*(.*?)\*\*/', $termsNOMaString, $match, PREG_PATTERN_ORDER); ``` `$match[0]` will contain the full matches, `$match[1]` contains just the capture group, which is the matches without the surrounding `**`. BTW, in your code, note that there's no difference between `[^**]` and just `[^*]`. `[]` matches single characters, not sequences, so putting `**` in there doesn't mean that it should skip over `**` but not `*`.
You can use `preg_split` like this with a simple regex that matches `**` surrounded by whitespaces: ``` $str = '** All quoted material is subject to prior sale ** ** All quotes are valid for 30 days ** ** No manufacturer\'s warranty provided unless otherwise specified **'; print_r(preg_split('/\s*\*\*\s*/', $str, -1, PREG_SPLIT_NO_EMPTY)); ``` [Code Demo](https://ideone.com/s6eaEg) Here use of flag `PREG_SPLIT_NO_EMPTY` will remove all empty results from output array. **Output:** ``` Array ( [0] => All quoted material is subject to prior sale [1] => All quotes are valid for 30 days [2] => No manufacturer's warranty provided unless otherwise specified ) ```
14,718,414
I have downloaded Python 2.7.3, PyInstaller (compatible with 2.7) and pywin32 (compatible with 2.7) and restarted my machine, but when I enter the prompt: pyinstaller.py [opts] nameofscript.py The prompt then tells me: Error: PyInstaller for Python 2.6+ on windows needs pywin32. Please install from <http://sourceforge.net/projects/pywin32/> Why is it that PyInstaller can't "see" that I have already downloaded pywin32?
2013/02/05
[ "https://Stackoverflow.com/questions/14718414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2044837/" ]
Got it! Found this useful tutorial: <http://bojan-komazec.blogspot.ca/2011/08/how-to-create-windows-executable-from.html> The 3rd paragraph tells you the how to get around the problem. The link he points to is tricky though. You need to go here to get the pywin32 installer. <http://sourceforge.net/projects/pywin32/files/pywin32/Build%20218/>
You should install pywin32 to the Python path first and then verify if it has succeeded by running this Python command: ``` import win32com ``` if there is no error, pywin32 is installed.
14,718,414
I have downloaded Python 2.7.3, PyInstaller (compatible with 2.7) and pywin32 (compatible with 2.7) and restarted my machine, but when I enter the prompt: pyinstaller.py [opts] nameofscript.py The prompt then tells me: Error: PyInstaller for Python 2.6+ on windows needs pywin32. Please install from <http://sourceforge.net/projects/pywin32/> Why is it that PyInstaller can't "see" that I have already downloaded pywin32?
2013/02/05
[ "https://Stackoverflow.com/questions/14718414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2044837/" ]
If you are using Python 2.7, the compat.py in the C:/Python27/Lib/site-packages/PyInstaller file need to be changed to: ``` if is_win: try: #from win32ctypes.pywin32 import pywintypes # noqa: F401 #from win32ctypes.pywin32 import win32api import pywintypes import win32api except ImportError: # This environment variable is set by seutp.py # - It's not an error for pywin32 to not be installed at that point if not os.environ.get('PYINSTALLER_NO_PYWIN32_FAILURE'): raise SystemExit('PyInstaller cannot check for assembly dependencies.\n' 'Please install PyWin32 or pywin32-ctypes.\n\n' 'pip install pypiwin32\n') ``` in order to work.
Got it! Found this useful tutorial: <http://bojan-komazec.blogspot.ca/2011/08/how-to-create-windows-executable-from.html> The 3rd paragraph tells you the how to get around the problem. The link he points to is tricky though. You need to go here to get the pywin32 installer. <http://sourceforge.net/projects/pywin32/files/pywin32/Build%20218/>
14,718,414
I have downloaded Python 2.7.3, PyInstaller (compatible with 2.7) and pywin32 (compatible with 2.7) and restarted my machine, but when I enter the prompt: pyinstaller.py [opts] nameofscript.py The prompt then tells me: Error: PyInstaller for Python 2.6+ on windows needs pywin32. Please install from <http://sourceforge.net/projects/pywin32/> Why is it that PyInstaller can't "see" that I have already downloaded pywin32?
2013/02/05
[ "https://Stackoverflow.com/questions/14718414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2044837/" ]
If you are using Python 2.7, the compat.py in the C:/Python27/Lib/site-packages/PyInstaller file need to be changed to: ``` if is_win: try: #from win32ctypes.pywin32 import pywintypes # noqa: F401 #from win32ctypes.pywin32 import win32api import pywintypes import win32api except ImportError: # This environment variable is set by seutp.py # - It's not an error for pywin32 to not be installed at that point if not os.environ.get('PYINSTALLER_NO_PYWIN32_FAILURE'): raise SystemExit('PyInstaller cannot check for assembly dependencies.\n' 'Please install PyWin32 or pywin32-ctypes.\n\n' 'pip install pypiwin32\n') ``` in order to work.
You should install pywin32 to the Python path first and then verify if it has succeeded by running this Python command: ``` import win32com ``` if there is no error, pywin32 is installed.
8,782,665
What is the most practical way of exchanging data between web sites (format, medium, protocol ...) ? For example say an open-source online game has been designed such that each site where it's installed acts as a separate world. How would you go about transferring the profile of a character between two sites?
2012/01/09
[ "https://Stackoverflow.com/questions/8782665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225899/" ]
this is a generic question so it probably belongs somewhere else, regardless what you normally do is to provide an API for external non-human clients to communicate, the details of it are completely up to you but the current popular choice is to make a [RESTful API](https://en.wikipedia.org/wiki/Representational_State_Transfer) and use [JSON](https://en.wikipedia.org/wiki/JSON) as the serialization format.
open-API maybe the bast way. Because your website client is more and more. And send each website a code.check the code in your online game and the request times every day.
8,782,665
What is the most practical way of exchanging data between web sites (format, medium, protocol ...) ? For example say an open-source online game has been designed such that each site where it's installed acts as a separate world. How would you go about transferring the profile of a character between two sites?
2012/01/09
[ "https://Stackoverflow.com/questions/8782665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225899/" ]
this is a generic question so it probably belongs somewhere else, regardless what you normally do is to provide an API for external non-human clients to communicate, the details of it are completely up to you but the current popular choice is to make a [RESTful API](https://en.wikipedia.org/wiki/Representational_State_Transfer) and use [JSON](https://en.wikipedia.org/wiki/JSON) as the serialization format.
I think you can use web service to exchange data between web sites.In web world web service soap is global format which is understand by all web framwork like php,asp,dotnet and other web framworks
8,782,665
What is the most practical way of exchanging data between web sites (format, medium, protocol ...) ? For example say an open-source online game has been designed such that each site where it's installed acts as a separate world. How would you go about transferring the profile of a character between two sites?
2012/01/09
[ "https://Stackoverflow.com/questions/8782665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225899/" ]
I think you can use web service to exchange data between web sites.In web world web service soap is global format which is understand by all web framwork like php,asp,dotnet and other web framworks
open-API maybe the bast way. Because your website client is more and more. And send each website a code.check the code in your online game and the request times every day.
28,254,857
I'm trying to make an alphabetically sorted array of objects from a class that contains also another int variable, but I can't make work qsort function properly. Here's my code: ``` #include <iostream> #include <stdlib.h> #include <string.h> int cmp (char **str1 , char **str2 ) { return strcmp(*str1,*str2); } class myclass { int id; char text[50]; public: void add(char a[], int i) { strcpy(text,a); id=i; } void show(void) { std::cout<<text<<std::endl; } }; int main (void) { myclass * myobject[4]; myobject[0] = new myclass; myobject[1] = new myclass; myobject[2] = new myclass; myobject[3] = new myclass; myobject[0]->add("zoom",1); myobject[1]->add("zoo",2); myobject[2]->add("animal",3); myobject[3]->add("bull",4); qsort (myobject,4,sizeof(char *), (int (*)(const void *, const void *)) cmp); for (int i=0; i < 4; i++) myobject[i]->show(); return 0; } ```
2015/01/31
[ "https://Stackoverflow.com/questions/28254857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4515210/" ]
First, your comparison function needs to be able to access the private member *text* of *myclass*. You could either make *text* public or add ``` friend int cmp (const void *, const void*); ``` in the class definition. Second, your comparison function is wrong. It takes pointers to the members of the array to be sorted. You should write it like this: ``` int cmp (const void *ptr1 , const void *ptr2) { myclass *m1 = *(myclass**)ptr1; myclass *m2 = *(myclass**)ptr2; return strcmp(m1->text, m2->text); } ```
Your comparison function is wrong. It receives a pointer to each array element, which is a pointer to `myclass`, not the `text`.You also shouldn't cast the function pointer when calling `qsort`, you should cast the arguments in the comparison function. ``` int cmp (void *a, void *b) { myclass **c1 = (myclass **)a; myclass **c2 = (myclass **)b; return strcmp((*c1)->text, (*c2)->text); } ```
28,254,857
I'm trying to make an alphabetically sorted array of objects from a class that contains also another int variable, but I can't make work qsort function properly. Here's my code: ``` #include <iostream> #include <stdlib.h> #include <string.h> int cmp (char **str1 , char **str2 ) { return strcmp(*str1,*str2); } class myclass { int id; char text[50]; public: void add(char a[], int i) { strcpy(text,a); id=i; } void show(void) { std::cout<<text<<std::endl; } }; int main (void) { myclass * myobject[4]; myobject[0] = new myclass; myobject[1] = new myclass; myobject[2] = new myclass; myobject[3] = new myclass; myobject[0]->add("zoom",1); myobject[1]->add("zoo",2); myobject[2]->add("animal",3); myobject[3]->add("bull",4); qsort (myobject,4,sizeof(char *), (int (*)(const void *, const void *)) cmp); for (int i=0; i < 4; i++) myobject[i]->show(); return 0; } ```
2015/01/31
[ "https://Stackoverflow.com/questions/28254857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4515210/" ]
Right now, your code looks like a warped version of C code, with just enough C++ "sprinkled" in to keep it from working with a C compiler. At least IMO, this gives pretty much the worst of both worlds--it removes most of the best features of C, and the best features of C++. If you're going to write C++, write C++, not warped C. To create and sort a collection of objects in C++, you should probably write the code more like this: ``` #include <iostream> #include <string> #include <vector> #include <algorithm> class myclass { int id; std::string text; public: myclass(std::string const &a, int i) : id(i), text(a) {} bool operator<(myclass const &other) { return text < other.text; } friend std::ostream &operator << (std::ostream &os, myclass const &m) { return std::cout << m.text << "\n"; } }; int main() { std::vector<myclass> myobjects{ { "zoom", 1 }, { "zoo", 2 }, { "animal", 3 }, { "bull", 4 } }; std::sort(myobjects.begin(), myobjects.end()); for (auto const &o : myobjects) std::cout << o; } ``` At least in my opinion, this is quite a bit simpler and easier to understand. It doesn't leak memory. If (for example) we added another item to the collection of items, we wouldn't have to rewrite other code to accommodate that. Probably more importantly than any of the above, at least for me this leads to faster, easier, more bug-free development. Just for example, the code above was bug-free (worked correctly) the first time it compiled. Other than fixing a couple of obvious typos (e.g., I'd mis-typed `operator` as `opertor`) it compiled and ran exactly as I originally typed it in. As a slight bonus, it probably runs faster than the C-like version. With only 4 items, the difference in speed won't be noticeable, but if you had (for example) thousands of items, `std::sort` would almost certainly be substantially faster than `qsort` (two to three times as fast is fairly common).
Your comparison function is wrong. It receives a pointer to each array element, which is a pointer to `myclass`, not the `text`.You also shouldn't cast the function pointer when calling `qsort`, you should cast the arguments in the comparison function. ``` int cmp (void *a, void *b) { myclass **c1 = (myclass **)a; myclass **c2 = (myclass **)b; return strcmp((*c1)->text, (*c2)->text); } ```
28,254,857
I'm trying to make an alphabetically sorted array of objects from a class that contains also another int variable, but I can't make work qsort function properly. Here's my code: ``` #include <iostream> #include <stdlib.h> #include <string.h> int cmp (char **str1 , char **str2 ) { return strcmp(*str1,*str2); } class myclass { int id; char text[50]; public: void add(char a[], int i) { strcpy(text,a); id=i; } void show(void) { std::cout<<text<<std::endl; } }; int main (void) { myclass * myobject[4]; myobject[0] = new myclass; myobject[1] = new myclass; myobject[2] = new myclass; myobject[3] = new myclass; myobject[0]->add("zoom",1); myobject[1]->add("zoo",2); myobject[2]->add("animal",3); myobject[3]->add("bull",4); qsort (myobject,4,sizeof(char *), (int (*)(const void *, const void *)) cmp); for (int i=0; i < 4; i++) myobject[i]->show(); return 0; } ```
2015/01/31
[ "https://Stackoverflow.com/questions/28254857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4515210/" ]
First, your comparison function needs to be able to access the private member *text* of *myclass*. You could either make *text* public or add ``` friend int cmp (const void *, const void*); ``` in the class definition. Second, your comparison function is wrong. It takes pointers to the members of the array to be sorted. You should write it like this: ``` int cmp (const void *ptr1 , const void *ptr2) { myclass *m1 = *(myclass**)ptr1; myclass *m2 = *(myclass**)ptr2; return strcmp(m1->text, m2->text); } ```
Right now, your code looks like a warped version of C code, with just enough C++ "sprinkled" in to keep it from working with a C compiler. At least IMO, this gives pretty much the worst of both worlds--it removes most of the best features of C, and the best features of C++. If you're going to write C++, write C++, not warped C. To create and sort a collection of objects in C++, you should probably write the code more like this: ``` #include <iostream> #include <string> #include <vector> #include <algorithm> class myclass { int id; std::string text; public: myclass(std::string const &a, int i) : id(i), text(a) {} bool operator<(myclass const &other) { return text < other.text; } friend std::ostream &operator << (std::ostream &os, myclass const &m) { return std::cout << m.text << "\n"; } }; int main() { std::vector<myclass> myobjects{ { "zoom", 1 }, { "zoo", 2 }, { "animal", 3 }, { "bull", 4 } }; std::sort(myobjects.begin(), myobjects.end()); for (auto const &o : myobjects) std::cout << o; } ``` At least in my opinion, this is quite a bit simpler and easier to understand. It doesn't leak memory. If (for example) we added another item to the collection of items, we wouldn't have to rewrite other code to accommodate that. Probably more importantly than any of the above, at least for me this leads to faster, easier, more bug-free development. Just for example, the code above was bug-free (worked correctly) the first time it compiled. Other than fixing a couple of obvious typos (e.g., I'd mis-typed `operator` as `opertor`) it compiled and ran exactly as I originally typed it in. As a slight bonus, it probably runs faster than the C-like version. With only 4 items, the difference in speed won't be noticeable, but if you had (for example) thousands of items, `std::sort` would almost certainly be substantially faster than `qsort` (two to three times as fast is fairly common).
2,373,861
> > **Possible Duplicate:** > > [Which sector of software industry uses C++?](https://stackoverflow.com/questions/537595/which-sector-of-software-industry-uses-c) > > > C++ was for many years the holy grail of mission critical high performance development. However, it seems that for the past 10 years like much of the development world has moved to Java and C#. My quesiton is this, is C++ effectively relegated to embedded systems, OS, Browser and other special purpose development? Should I let this skillset go the way of the VB 6 and other skillsets that are no longer showing the same level of demand and value in the market? I love C++ and would love to update my knowledge in it, but I wouldn't even know where to begin to try to apply it to common business problems today. Regards.
2010/03/03
[ "https://Stackoverflow.com/questions/2373861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135952/" ]
First of all, I doubt anybody can give a definitive answer -- there's just no way to tell exactly how much any particular language is really used. Nearly anything you can measure is a secondary measurement, such as how many people are advertising jobs using that language. The problem is that this tends to show relatively new languages as dominating to a much greater degree than is real. That said, my belief is as follows. At one time, C++ was the hot new language on the block, and there was a bubble when it dominated the market. That bubble deflated quite a while ago. Since then, use of C++ has been growing on an absolute basis, but the market has been growing (quite a bit) faster so its shrinking on a relative basis. There are a couple of reasons this doesn't show up in most secondary measures such as job advertisements though. A couple of the obvious ones include: 1. Many teams producing C++ have now had years to "settle in", so the turnover rate is relatively low. 2. It's now well established where it's used, so positions tend to be filled by internal promotions. There's another effect I almost hesitate to mention, but it's true no matter how little a lot of people like it: there are both programmers and managers who are more excited about "new" than effective. This leads to a large group of wannabes who are constantly on the move to the latest and greatest "technology" (whether that happens to be a language, framework, platform, or whatever). They get a job, loaf (or worse, actually write some code), then move on to their next victim...er...employer. They cause a lot of "churn", and inflate the number of job advertisements, but produce little or nothing of any real value. That group moved from C++ to Java a long time ago, and have long since moved from Java to C# to Ruby on Rails to Hadoop to whatever the managers are excited about this week. Lest I sound excessively negative, I should add that along the way, a few of them really find something they're good at, and (mostly) tend to stay with that. Unfortunately, for every one who does, there are at least five more new graduates to join the throng...
More often than not, we get lost in the hype cycle. First there was Java, then came PHP, and currently is Python. But the fact of the matter is development of general purpose desktop application still requires use of libraries like Carbon/Cocoa for mac, GTK/QT for Linux, MFC for Windows. All of which are C/C++ based. So are most applications written for these platforms. So calling C++ as being relegated to embedded is not right, although yeah its being extensively used now, unlike earlier when it was just assembly or C at the max. In my opinion, if you want a high performance application with great looking GUI, it still has to be done in C/C++.
2,373,861
> > **Possible Duplicate:** > > [Which sector of software industry uses C++?](https://stackoverflow.com/questions/537595/which-sector-of-software-industry-uses-c) > > > C++ was for many years the holy grail of mission critical high performance development. However, it seems that for the past 10 years like much of the development world has moved to Java and C#. My quesiton is this, is C++ effectively relegated to embedded systems, OS, Browser and other special purpose development? Should I let this skillset go the way of the VB 6 and other skillsets that are no longer showing the same level of demand and value in the market? I love C++ and would love to update my knowledge in it, but I wouldn't even know where to begin to try to apply it to common business problems today. Regards.
2010/03/03
[ "https://Stackoverflow.com/questions/2373861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135952/" ]
If I take a look at the applications I have installed on the laptop I am writing this message on, I see a lot of C/C++ and few (if any) managed apps. Examples? Google Chrome, Firefox, iTunes, uTorrent, Spotify, Picasa, Google Earth, OpenOffice, Notepad++, IrfanView... this list goes on and on. I write desktop applications for a living, which are installed on thousands of PCs worldwide, and C++ is still my language of choice. The lack of dependencies (WTL is your friend) is a massive plus IMHO (and that of my customers I should add!.) YMMV though - as a seasoned developer I think I am productive enough in C++, but I can't speak for everybody.
Different languages are prevalent in different domains. It is interesting that you think it might be rendered unimportant by being *relegated* to embedded systems when in fact that is where most software development occurs; at least in terms of number of projects/products. There are many ways of measuring, and a number of them are presented here: <http://langpop.com/>. The evidence suggests that C++ remains important.
2,373,861
> > **Possible Duplicate:** > > [Which sector of software industry uses C++?](https://stackoverflow.com/questions/537595/which-sector-of-software-industry-uses-c) > > > C++ was for many years the holy grail of mission critical high performance development. However, it seems that for the past 10 years like much of the development world has moved to Java and C#. My quesiton is this, is C++ effectively relegated to embedded systems, OS, Browser and other special purpose development? Should I let this skillset go the way of the VB 6 and other skillsets that are no longer showing the same level of demand and value in the market? I love C++ and would love to update my knowledge in it, but I wouldn't even know where to begin to try to apply it to common business problems today. Regards.
2010/03/03
[ "https://Stackoverflow.com/questions/2373861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135952/" ]
C++ is still used everywhere you want the best performance. Its major advantage is that you can use literally for everything. In addition to what other people have said you can also use it to power websites, for instance [OkCupid](http://okcupid.com/faq) uses it almost exclusively. As the recent Hip Hop of Facebook shows, in the end, if you can afford it (ie. you have a large and competent team) you can always gains something using it. Then it also a matter of scale, other than industry.
C++ is still very popular. For instance, combined with Qt it is often used.
2,373,861
> > **Possible Duplicate:** > > [Which sector of software industry uses C++?](https://stackoverflow.com/questions/537595/which-sector-of-software-industry-uses-c) > > > C++ was for many years the holy grail of mission critical high performance development. However, it seems that for the past 10 years like much of the development world has moved to Java and C#. My quesiton is this, is C++ effectively relegated to embedded systems, OS, Browser and other special purpose development? Should I let this skillset go the way of the VB 6 and other skillsets that are no longer showing the same level of demand and value in the market? I love C++ and would love to update my knowledge in it, but I wouldn't even know where to begin to try to apply it to common business problems today. Regards.
2010/03/03
[ "https://Stackoverflow.com/questions/2373861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135952/" ]
C++ is still valuable for many high performance apps. There are other technologies, and depends on the situation different languages are better suited for your needs. But if you want strong performance, good control of what your code is doing, and flexible networking and programming stack, C++ is still a good choice. A better suggestion is: let the problems come to you and find the language that best suites the situation, rather than take a language and go look for problems. Still: if you know C++ well, you can learn/program in anything.
C++ is still used everywhere you want the best performance. Its major advantage is that you can use literally for everything. In addition to what other people have said you can also use it to power websites, for instance [OkCupid](http://okcupid.com/faq) uses it almost exclusively. As the recent Hip Hop of Facebook shows, in the end, if you can afford it (ie. you have a large and competent team) you can always gains something using it. Then it also a matter of scale, other than industry.
2,373,861
> > **Possible Duplicate:** > > [Which sector of software industry uses C++?](https://stackoverflow.com/questions/537595/which-sector-of-software-industry-uses-c) > > > C++ was for many years the holy grail of mission critical high performance development. However, it seems that for the past 10 years like much of the development world has moved to Java and C#. My quesiton is this, is C++ effectively relegated to embedded systems, OS, Browser and other special purpose development? Should I let this skillset go the way of the VB 6 and other skillsets that are no longer showing the same level of demand and value in the market? I love C++ and would love to update my knowledge in it, but I wouldn't even know where to begin to try to apply it to common business problems today. Regards.
2010/03/03
[ "https://Stackoverflow.com/questions/2373861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135952/" ]
Different languages are prevalent in different domains. It is interesting that you think it might be rendered unimportant by being *relegated* to embedded systems when in fact that is where most software development occurs; at least in terms of number of projects/products. There are many ways of measuring, and a number of them are presented here: <http://langpop.com/>. The evidence suggests that C++ remains important.
C++ is still very popular. For instance, combined with Qt it is often used.
2,373,861
> > **Possible Duplicate:** > > [Which sector of software industry uses C++?](https://stackoverflow.com/questions/537595/which-sector-of-software-industry-uses-c) > > > C++ was for many years the holy grail of mission critical high performance development. However, it seems that for the past 10 years like much of the development world has moved to Java and C#. My quesiton is this, is C++ effectively relegated to embedded systems, OS, Browser and other special purpose development? Should I let this skillset go the way of the VB 6 and other skillsets that are no longer showing the same level of demand and value in the market? I love C++ and would love to update my knowledge in it, but I wouldn't even know where to begin to try to apply it to common business problems today. Regards.
2010/03/03
[ "https://Stackoverflow.com/questions/2373861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135952/" ]
"C++ effectively relegated to embedded systems, OS, Browser" "other special purpose development" You mean 99% of the code people run on a daily basis?
It hasn't gone away if you need to do something really, really fast. If "fast enough" is OK, then C# and Java are fine, but if you have a calculation that takes hours or days, or you need something to happen on the microsecond timescale (i.e. high frequency trading) C++ is still the language to use.
2,373,861
> > **Possible Duplicate:** > > [Which sector of software industry uses C++?](https://stackoverflow.com/questions/537595/which-sector-of-software-industry-uses-c) > > > C++ was for many years the holy grail of mission critical high performance development. However, it seems that for the past 10 years like much of the development world has moved to Java and C#. My quesiton is this, is C++ effectively relegated to embedded systems, OS, Browser and other special purpose development? Should I let this skillset go the way of the VB 6 and other skillsets that are no longer showing the same level of demand and value in the market? I love C++ and would love to update my knowledge in it, but I wouldn't even know where to begin to try to apply it to common business problems today. Regards.
2010/03/03
[ "https://Stackoverflow.com/questions/2373861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135952/" ]
C++ is still heavily used in many mission critical financial applications. For example, most of Bloomberg's platforms are based on C++ with very little front end in other languages. Many investment banks and hedge funds use algorithmic trading systems written completely in C++ (e.g., Tower Research Capital, Knight Capital, etc.). If you've been out of C++ for a while, you may need to get used to a whole bunch of now-standard libraries. When I was doing most of my C++, STL was fairly new and you either adopted the Microsoft libs or did not. If I went back to C++ now, I'll have to learn all the new libraries to be effective. I think most of the movement to other languages is related to web development and web-centric development. The main exception to that would be Google, which still primarily use C++ and Python.
C++ is still very popular. For instance, combined with Qt it is often used.
2,373,861
> > **Possible Duplicate:** > > [Which sector of software industry uses C++?](https://stackoverflow.com/questions/537595/which-sector-of-software-industry-uses-c) > > > C++ was for many years the holy grail of mission critical high performance development. However, it seems that for the past 10 years like much of the development world has moved to Java and C#. My quesiton is this, is C++ effectively relegated to embedded systems, OS, Browser and other special purpose development? Should I let this skillset go the way of the VB 6 and other skillsets that are no longer showing the same level of demand and value in the market? I love C++ and would love to update my knowledge in it, but I wouldn't even know where to begin to try to apply it to common business problems today. Regards.
2010/03/03
[ "https://Stackoverflow.com/questions/2373861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135952/" ]
First of all, I doubt anybody can give a definitive answer -- there's just no way to tell exactly how much any particular language is really used. Nearly anything you can measure is a secondary measurement, such as how many people are advertising jobs using that language. The problem is that this tends to show relatively new languages as dominating to a much greater degree than is real. That said, my belief is as follows. At one time, C++ was the hot new language on the block, and there was a bubble when it dominated the market. That bubble deflated quite a while ago. Since then, use of C++ has been growing on an absolute basis, but the market has been growing (quite a bit) faster so its shrinking on a relative basis. There are a couple of reasons this doesn't show up in most secondary measures such as job advertisements though. A couple of the obvious ones include: 1. Many teams producing C++ have now had years to "settle in", so the turnover rate is relatively low. 2. It's now well established where it's used, so positions tend to be filled by internal promotions. There's another effect I almost hesitate to mention, but it's true no matter how little a lot of people like it: there are both programmers and managers who are more excited about "new" than effective. This leads to a large group of wannabes who are constantly on the move to the latest and greatest "technology" (whether that happens to be a language, framework, platform, or whatever). They get a job, loaf (or worse, actually write some code), then move on to their next victim...er...employer. They cause a lot of "churn", and inflate the number of job advertisements, but produce little or nothing of any real value. That group moved from C++ to Java a long time ago, and have long since moved from Java to C# to Ruby on Rails to Hadoop to whatever the managers are excited about this week. Lest I sound excessively negative, I should add that along the way, a few of them really find something they're good at, and (mostly) tend to stay with that. Unfortunately, for every one who does, there are at least five more new graduates to join the throng...
I'm not sure whether the gaming industry falls under "general purpose development", but if you want to develop anything that you intend to get working on more than a single console, C++ is what's for lunch. While many gaming and 3D libraries have extensions for other languages, they -all- have extensions for C/C++.
2,373,861
> > **Possible Duplicate:** > > [Which sector of software industry uses C++?](https://stackoverflow.com/questions/537595/which-sector-of-software-industry-uses-c) > > > C++ was for many years the holy grail of mission critical high performance development. However, it seems that for the past 10 years like much of the development world has moved to Java and C#. My quesiton is this, is C++ effectively relegated to embedded systems, OS, Browser and other special purpose development? Should I let this skillset go the way of the VB 6 and other skillsets that are no longer showing the same level of demand and value in the market? I love C++ and would love to update my knowledge in it, but I wouldn't even know where to begin to try to apply it to common business problems today. Regards.
2010/03/03
[ "https://Stackoverflow.com/questions/2373861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135952/" ]
First of all, I doubt anybody can give a definitive answer -- there's just no way to tell exactly how much any particular language is really used. Nearly anything you can measure is a secondary measurement, such as how many people are advertising jobs using that language. The problem is that this tends to show relatively new languages as dominating to a much greater degree than is real. That said, my belief is as follows. At one time, C++ was the hot new language on the block, and there was a bubble when it dominated the market. That bubble deflated quite a while ago. Since then, use of C++ has been growing on an absolute basis, but the market has been growing (quite a bit) faster so its shrinking on a relative basis. There are a couple of reasons this doesn't show up in most secondary measures such as job advertisements though. A couple of the obvious ones include: 1. Many teams producing C++ have now had years to "settle in", so the turnover rate is relatively low. 2. It's now well established where it's used, so positions tend to be filled by internal promotions. There's another effect I almost hesitate to mention, but it's true no matter how little a lot of people like it: there are both programmers and managers who are more excited about "new" than effective. This leads to a large group of wannabes who are constantly on the move to the latest and greatest "technology" (whether that happens to be a language, framework, platform, or whatever). They get a job, loaf (or worse, actually write some code), then move on to their next victim...er...employer. They cause a lot of "churn", and inflate the number of job advertisements, but produce little or nothing of any real value. That group moved from C++ to Java a long time ago, and have long since moved from Java to C# to Ruby on Rails to Hadoop to whatever the managers are excited about this week. Lest I sound excessively negative, I should add that along the way, a few of them really find something they're good at, and (mostly) tend to stay with that. Unfortunately, for every one who does, there are at least five more new graduates to join the throng...
If I take a look at the applications I have installed on the laptop I am writing this message on, I see a lot of C/C++ and few (if any) managed apps. Examples? Google Chrome, Firefox, iTunes, uTorrent, Spotify, Picasa, Google Earth, OpenOffice, Notepad++, IrfanView... this list goes on and on. I write desktop applications for a living, which are installed on thousands of PCs worldwide, and C++ is still my language of choice. The lack of dependencies (WTL is your friend) is a massive plus IMHO (and that of my customers I should add!.) YMMV though - as a seasoned developer I think I am productive enough in C++, but I can't speak for everybody.
2,373,861
> > **Possible Duplicate:** > > [Which sector of software industry uses C++?](https://stackoverflow.com/questions/537595/which-sector-of-software-industry-uses-c) > > > C++ was for many years the holy grail of mission critical high performance development. However, it seems that for the past 10 years like much of the development world has moved to Java and C#. My quesiton is this, is C++ effectively relegated to embedded systems, OS, Browser and other special purpose development? Should I let this skillset go the way of the VB 6 and other skillsets that are no longer showing the same level of demand and value in the market? I love C++ and would love to update my knowledge in it, but I wouldn't even know where to begin to try to apply it to common business problems today. Regards.
2010/03/03
[ "https://Stackoverflow.com/questions/2373861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135952/" ]
"C++ effectively relegated to embedded systems, OS, Browser" "other special purpose development" You mean 99% of the code people run on a daily basis?
C++ is usually used for systems work, generally defined as software where the UI is not central, not application work -- where the UI *is* central. So, for general business use it's probably not very interesting and those problems are better solved with a higher level language. However, there will always be low level systems work to be done, and C or C++ is the practical answer for those problems right now.
53,283,195
I am trying to upload a file and well as take an input from the user in json format using Swagger UI. I have written the below code for the same. ``` upload_parser = api.parser() upload_parser.add_argument('file', location='files', type=FileStorage, required=True) type = api.model("tax", { "tax_form": fields.String()}) @api.route('/extraction') @api.expect(upload_parser) class extraction(Resource): @api.expect(type) def post(self): tax_form= api.payload # json input string print(tax_form['tax_form']) args = upload_parser.parse_args() # upload a file uploaded_file = args['file'] output = func_extract(uploaded_file,tax_form['tax_form']) return output, 201 ``` When i run the above individually for eg, if i only upload a file or only take an input from user, the code works but if i do them together. tax\_from returns **None** value, it does not take what I am inputting as json value via Swagger UI.
2018/11/13
[ "https://Stackoverflow.com/questions/53283195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8635591/" ]
I got the issue solved. Used reqparse for inputting the argument. See the code snippet as below ``` upload_parser = api.parser() upload_parser.add_argument('file', location='files', type=FileStorage, required=True) parser = reqparse.RequestParser() parser.add_argument('tax_form', required = True) @api.route('/extraction') @api.expect(upload_parser) class extraction(Resource): @api.expect(parser) def post(self): """ extract the content """ args1 = parser.parse_args() tax_form = args1['tax_form'] print(tax_form) args = upload_parser.parse_args() uploaded_file = args['file'] output = func_extract(uploaded_file,tax_form) return output, 201 ```
I recommend using list of models and parsers in api.expect with validate=True(if required). This will remove the dependency of defining the expected query parameter (in your case) in the class level as you may have GET/PUT/DELETE API on the same route which may not even need this parameter. Have modified your code to understand better: ``` upload_parser = api.parser() upload_parser.add_argument('file', location='files', type=FileStorage, required=True) tax_type = api.model("tax", {"tax_form": fields.String()}) @api.route('/extraction') class extraction(Resource): @api.expect(tax_type, upload_parser, validate=True) def post(self): tax_form= api.payload # json input string args = upload_parser.parse_args() # upload a file uploaded_file = args['file'] output = func_extract(uploaded_file,tax_form['tax_form']) return output, 201 # This METHOD is now independent of your POST data expectations def get(self): output = {} # Some JSON return output, 200 ``` Also, please avoid using python reserved keywords like 'type' as variables. Hope this helps ..!!
682,256
Streamlining the boot sequence for Windows 10 / Ubuntu 14 dual boot. Ok. Ubuntu installed quite easily on my Windows 10 laptop despite the secure boot stuff. Evidently Microsoft signs Ubuntu loaders so that it is acceptable for their secure boot system. Whatever. It works. Now I have a different problem. Firstly, I have to hit F12 at boot to see the Microsoft boot loader. Otherwise it just loads into Windows. That is not a big deal really. But it would be nice to just show the loader automatically. Not sure if anything can be done about that. But what COULD be done is switching the order of the OS's displayed in the Microsoft loader. It loads Windows by default, so if it is not displayed (by hitting F12) it just loads windows. But if I select Ubuntu, it THEN loads the Grub2 loader, which has the selection on it for Ubuntu or Windows (with Ubuntu as the default). Seems to me that if I just set the Microsoft loader to load Ubuntu by default, I would not have to hit F12 or even SEE that loader as it would just show Grub2. For clarity, here is my boot sequences: Not pressing anything extra: **press power. loads Windows 10. (never shows grub2 or the windows loader)** Dual boot by Pressing F12: **press power. Displays Microsoft boot loader, showing Windows 10 as default and Ubuntu. Select Ubuntu Displays the Grub2 boot loader, showing Ubuntu as default. Select nothing, loads Ubuntu** What I propose is making Ubuntu the default in the WINDOWS boot loader, so that my new sequence would be: **Press power: (Windows loader as default selects Ubuntu, and then loads Grub 2 by default without pressing anything) Grub2 displays, I select Windows or it just loads into Ubuntu by default.** When I installed Ubuntu I just let it do things automatically. I installed it to a USB, which booted fine, ran it from USB to test it, all devices on the laptop worked, so I installed it from inside Ubuntu. I selected the automatic setup for dual boot and did not make partitions myself (other than selecting the size for Ubuntu by moving that divider bar). Hope that is enough info. The Windows 10 version is the upgrade from Windows 8. I tried installing other versions of Linux that don't have the Microsoft approved-to-load signature and they failed every time to even get to a desktop from USB live. But of course, Ubuntu is "signed" by Microsoft to have the boot key necessary to work. The version of Ubuntu is the latest version as of this post, downloaded today. Version 14.04.3 directly from the Ubuntu website.
2015/10/06
[ "https://askubuntu.com/questions/682256", "https://askubuntu.com", "https://askubuntu.com/users/279269/" ]
You may find solace in this [link from Microsoft Answers](http://answers.microsoft.com/en-us/windows/forum/windows_7-update/time-to-display-list-of-operating-systems/094d778f-90db-4b90-a28f-11f477c5e779). *I take no credit for this answer*: I suggest you to boot the computer to WinRE from the elevated command prompt, and try running this command and check for the issue. 1. Use the Windows 10 DVD to start the computer in Windows Recovery (WinRE). 2. In WinRE, open a command prompt. To do this, follow these steps: * On the Install Windows screen, select the appropriate Language to install, Time and currency format, and Keyboard or input method options, and then click Next. * Click Repair your computer. * Click the 10 installation that you want to repair, and then click Next. * Click Command Prompt. * At the command prompt, type the following commands, and then press ENTER: `cd /d Partition:\Windows\System32` `bcdedit /timeout 5` You may also change the timeout value to anything below 30. Now you may restart your computer and check if you are able to boot to the desktop. **Refer:** [Change the default operating system for startup (multiboot)](http://windows.microsoft.com/en-US/windows7/Change-the-default-operating-system-for-startup-multiboot)
Well, I fixed the issue rather easily. Booting, pressed F2 to get into Bios. This used to be impossible in win 8 but for some reason in win 10 this is easy. Under the BOOT tab, I simply selected "UbuntuWDC WD10JPVX-22JC310" and move it to position 3, above "Windows Boot Manager" Now the boot sequence bypasses the Windows Boot Manager completely and goes straight to the Grub2. Selecting Windows from Grub2 does start a rather long boot for Windows, but I don't care as I hardly ever use Windows 10. Selecting Ubuntu loads Ubuntu pretty quick. Regarding the solution above, I did shorten the boot delay of the Windows loader but did not have to use dos instructions to do so. I just went into the advanced system startup settings and found it in the boot/recovery section. That was easy. [![image](https://i.stack.imgur.com/deVd7.jpg)](https://i.stack.imgur.com/deVd7.jpg)
60,594,144
Requirement: My pdf has 5 pages, I need to start the split on the second page and end at the last page, in a single pdf. Currently, I have made it so that it splits one pdf per page. Current code: ``` public static boolean SepararFC(String sequence, String pathfrom, String pathto) { try (PDDocument document = PDDocument.load(new File(pathfrom))) { Splitter splitter = new Splitter(); List<PDDocument> Pages = splitter.split(document); for (int i = 0; i < Pages.size(); i++) { PDDocument doc = Pages.get(i); doc.save(new File(pathfrom, sequence + "_" + i + ".pdf")); } } catch (IOException e){ System.err.println(e); } return true; ```
2020/03/09
[ "https://Stackoverflow.com/questions/60594144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5728714/" ]
Since you don't want page 1, you can just remove it and save a new file ``` try (PDDocument document = PDDocument.load(new File(pathfrom))) { //Listing the number of existing pages int noOfPages= document.getNumberOfPages(); System.out.print(noOfPages); //Removing the pages document.removePage(0); System.out.println("page removed"); //Saving the document document.save(new File(pathfrom, sequence + "new"+ ".pdf")); //Closing the document document.close();} catch (IOException e){ System.err.println(e); } ```
Assuming your code is correct: ``` public static boolean SepararFC(String sequence, String pathfrom, String pathto) { int start = 1; int end = 4; try (PDDocument document = PDDocument.load(new File(pathfrom))) { Splitter splitter = new Splitter(); List<PDDocument> Pages = splitter.split(document); for (int i = 0; i < Pages.size(); i++) { PDDocument doc = Pages.get(i); if(i > start && i <= end){ doc.save(new File(pathfrom, sequence + "_" + i + ".pdf")); } } } catch (IOException e){ System.err.println(e); } return true; ```
294,261
I have class with a member function that takes a default argument. ``` struct Class { void member(int n = 0) {} }; ``` By means of std::tr1::mem\_fn I can invoke it: ``` Class object; std::tr1::mem_fn(&Class::member)(object,10); ``` That said, if I want to invoke the *callable* member on the object with the default argument, what's the correct syntax? ``` std::tr1::mem_fn(&Class::member)(object); // This does not work ``` g++ complains with the following error: ``` test.cc:17: error: no match for call to ‘(std::tr1::_Mem_fn<void (Class::*)(int)>) (Class&)’ /usr/include/c++/4.3/tr1_impl/functional:551: note: candidates are: _Res std::tr1::_Mem_fn<_Res (_Class::*)(_ArgTypes ...)>::operator()(_Class&, _ArgTypes ...) const [with _Res = void, _Class = Class, _ArgTypes = int] /usr/include/c++/4.3/tr1_impl/functional:556: note: _Res std::tr1::_Mem_fn<_Res (_Class::*)(_ArgTypes ...)>::operator()(_Class*, _ArgTypes ...) const [with _Res = void, _Class = Class, _ArgTypes = int] ``` Still, the I have the same problem when Class::member is overloaded by members that takes different arguments...
2008/11/16
[ "https://Stackoverflow.com/questions/294261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19630/" ]
Default functions are bound at call time, but can't be bound into any sort of wrapper implicitly, because of the way they are implemented. When you pass `&Class::member`, `mem_fn` only sees a `void (Class::*)(int)`, and can't see the default argument. Using `tr1::bind`, you can bind the default argument explictly: `std::tr1::bind(&Class::member, 0)` or you can use it as you would `mem_fn`, but you can't do both in one object. You would have to write your own wrapper class for that. As for overloads, you will have to explicitly specify the template arguments for `mem_fn` so the right function pointer is picked as in `mem_fn<void(int)>(&Class::member)`.
The reason is that any default arguments do not change the function type of a function. `mem_fn` has no way to know the function only requires 1 argument, or that the functions' second argument is optional, since all the knowledge it gets is given to it by the type of `&Class::member` (which stays `void(Class::*)(int)`) . It therefor requires an integer as the second argument. If you want to pass the address of a member function overloaded, you have to cast to the right member function pointer type: `static_cast<void(Class::*)()>(&Class::member)` instead of just `&Class::member`, so the compiler has a context to figure out which address is to be taken. **Edit**: coppro has a nicer solution how to provide context: `std::tr1::mem_fn<void()>(&Class::member)`
45,140,226
How would I handle the following kind of scenario using Cucumber Java with Selenium: ``` Scenario: Raise Invoice by User according to Raise Invoice Type. When I select the Raise Invoice Type as "RaiseInvoiceType" IF RaiseInvoiceType == 'ABC' Method ABC() else if RaiseInvoiceType == 'XYZ' Method XYZ() ``` "RaiseInvoiceType" is a variable and is dependent on the radio button or drop-down. How to implement cucumber feature files and step definition class methods with the condition?
2017/07/17
[ "https://Stackoverflow.com/questions/45140226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8287292/" ]
**Background** Cucumber feature files are all about bridging the conversational gap between the business and the development team, and thus, code and conditional statements should never appear inside them. **The Solution** The solution to your problem is how you write the step definition. Using Cucumber's Ruby implementation as an example: ```rb When('I select the Raise Invoice Type as "$invoice_type"') do | invoice_type | if invoice_type == 'ABC' method_abc else if invoice_type == 'XYZ' method_xyz else raise 'Unknown invoice type' end end end ``` This brings the code and conditional statements out of the feature file, which is in essence meant to be living documentation of the *behaviours* of the application/system **Further Improvements** But I would go so far as to change the wording of the step too: ``` Scenario Outline: Raise Invoice by User according to Raise Invoice Type. When I raise the invoice type "<invoice_type>" Then some expected behaviour Examples: | invoice_type | | ABC | | XYZ | ``` This brings the step away from implementation (that could be dropdown, radio or text boxes for example), and more towards behaviours of the system in place - the feature that this scenario is highlighting is that you should be able to raise an invoice, not that you should have a list of options to choose from in a select box.
The important thing here is the difference between the two invoice types. Each type is important to your business so I would create a step for each type e.g. `When I raise an ABC invoice` and `When I raise an XYZ invoice` When implementing the step definitions I might then think about using the same helper method to reduce the code e.g. ``` When I raise an ABC invoice' do raise_invoice type: 'abc' end When I raise an XYZ invoice' do raise_invoice type: 'xyz' end ``` and then have a helper method deal with HOW you raise the invoice. ``` def raise_invoice(type: ) click_radio('invoice', type) end ``` This gives you very simple step definitions, no conditionals or other complications in your step defs and a simple method to deal with the interaction in the browser. *note all code above is pseudo-code/ruby*
32,565,304
I want to hide the scroll bar by using Jquery. Can anyone help me with it? ``` $ ::-webkit-scrollbar { display: none; } ``` This works for Chrome but I want my scroll to hide for all browsers, how can I do that?
2015/09/14
[ "https://Stackoverflow.com/questions/32565304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5176401/" ]
Instead you can hide the scrolling from the body itself. Try this ``` <style type="text/css"> body { overflow:hidden; } </style> ```
Try this JS Code ``` $("body").css("overflow", "hidden"); ``` Css Code ``` body {width:100%; height:100%; overflow:hidden, margin:0} ```
32,565,304
I want to hide the scroll bar by using Jquery. Can anyone help me with it? ``` $ ::-webkit-scrollbar { display: none; } ``` This works for Chrome but I want my scroll to hide for all browsers, how can I do that?
2015/09/14
[ "https://Stackoverflow.com/questions/32565304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5176401/" ]
The reason your code only works in Chrome is that you are using `-webkit-scrollbar`. Chrome is built upon the (modified) webkit rendering engine, so this tag will only affect Chrome (and Safari, incidentally). Typically, the `-webkit-scrollbar` property is used to style scrollbars. To hide them, instead use the `overflow` property. Here is a CSS solution: ``` body { overflow: hidden; } ``` If you would like to do the same in jQuery, as asked, try adding the overflow property dynamically, like so: ``` $("body").css("overflow", "hidden"); ``` Note that you do not have to apply this property to your entire body. Any valid selector will do! If you are trying to hide the scrollbar, but still allow scrolling, you will have to get a little tricky with how you go about it. Try adding an inner container with `overflow: auto` and some right padding. This will allow the scrollbar to be pushed out of the containing div, effectively hiding it. Check out this fiddle to see it in action: <http://jsfiddle.net/zjfdvmLx/> The downside to this approach is that it is not entirely cross-browser friendly. Each browser decides how wide the scrollbar should be, and it could change at any time. If the `15px` used in the fiddle is not enough for your browser, increase the value. See [this](https://stackoverflow.com/questions/16670931/hide-scroll-bar-but-still-being-able-to-scroll) answer for more information.
Instead you can hide the scrolling from the body itself. Try this ``` <style type="text/css"> body { overflow:hidden; } </style> ```
32,565,304
I want to hide the scroll bar by using Jquery. Can anyone help me with it? ``` $ ::-webkit-scrollbar { display: none; } ``` This works for Chrome but I want my scroll to hide for all browsers, how can I do that?
2015/09/14
[ "https://Stackoverflow.com/questions/32565304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5176401/" ]
Instead you can hide the scrolling from the body itself. Try this ``` <style type="text/css"> body { overflow:hidden; } </style> ```
``` <style> /* width */ ::-webkit-scrollbar { width: 10px; } /* Track */ ::-webkit-scrollbar-track { box-shadow: inset 0 0 0px transparent; border-radius: 0px; } /* Handle */ ::-webkit-scrollbar-thumb { background: transparent; border-radius: 0px; } /* Handle on hover */ ::-webkit-scrollbar-thumb:hover { background: transparent; } </style> ```
32,565,304
I want to hide the scroll bar by using Jquery. Can anyone help me with it? ``` $ ::-webkit-scrollbar { display: none; } ``` This works for Chrome but I want my scroll to hide for all browsers, how can I do that?
2015/09/14
[ "https://Stackoverflow.com/questions/32565304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5176401/" ]
The reason your code only works in Chrome is that you are using `-webkit-scrollbar`. Chrome is built upon the (modified) webkit rendering engine, so this tag will only affect Chrome (and Safari, incidentally). Typically, the `-webkit-scrollbar` property is used to style scrollbars. To hide them, instead use the `overflow` property. Here is a CSS solution: ``` body { overflow: hidden; } ``` If you would like to do the same in jQuery, as asked, try adding the overflow property dynamically, like so: ``` $("body").css("overflow", "hidden"); ``` Note that you do not have to apply this property to your entire body. Any valid selector will do! If you are trying to hide the scrollbar, but still allow scrolling, you will have to get a little tricky with how you go about it. Try adding an inner container with `overflow: auto` and some right padding. This will allow the scrollbar to be pushed out of the containing div, effectively hiding it. Check out this fiddle to see it in action: <http://jsfiddle.net/zjfdvmLx/> The downside to this approach is that it is not entirely cross-browser friendly. Each browser decides how wide the scrollbar should be, and it could change at any time. If the `15px` used in the fiddle is not enough for your browser, increase the value. See [this](https://stackoverflow.com/questions/16670931/hide-scroll-bar-but-still-being-able-to-scroll) answer for more information.
Yo can try the code below: ``` $("body").css("overflow", "hidden"); ```
32,565,304
I want to hide the scroll bar by using Jquery. Can anyone help me with it? ``` $ ::-webkit-scrollbar { display: none; } ``` This works for Chrome but I want my scroll to hide for all browsers, how can I do that?
2015/09/14
[ "https://Stackoverflow.com/questions/32565304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5176401/" ]
The reason your code only works in Chrome is that you are using `-webkit-scrollbar`. Chrome is built upon the (modified) webkit rendering engine, so this tag will only affect Chrome (and Safari, incidentally). Typically, the `-webkit-scrollbar` property is used to style scrollbars. To hide them, instead use the `overflow` property. Here is a CSS solution: ``` body { overflow: hidden; } ``` If you would like to do the same in jQuery, as asked, try adding the overflow property dynamically, like so: ``` $("body").css("overflow", "hidden"); ``` Note that you do not have to apply this property to your entire body. Any valid selector will do! If you are trying to hide the scrollbar, but still allow scrolling, you will have to get a little tricky with how you go about it. Try adding an inner container with `overflow: auto` and some right padding. This will allow the scrollbar to be pushed out of the containing div, effectively hiding it. Check out this fiddle to see it in action: <http://jsfiddle.net/zjfdvmLx/> The downside to this approach is that it is not entirely cross-browser friendly. Each browser decides how wide the scrollbar should be, and it could change at any time. If the `15px` used in the fiddle is not enough for your browser, increase the value. See [this](https://stackoverflow.com/questions/16670931/hide-scroll-bar-but-still-being-able-to-scroll) answer for more information.
Try this code: ``` $('body').css({ 'overflow': 'hidden' }); ```
32,565,304
I want to hide the scroll bar by using Jquery. Can anyone help me with it? ``` $ ::-webkit-scrollbar { display: none; } ``` This works for Chrome but I want my scroll to hide for all browsers, how can I do that?
2015/09/14
[ "https://Stackoverflow.com/questions/32565304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5176401/" ]
Try this JS Code ``` $("body").css("overflow", "hidden"); ``` Css Code ``` body {width:100%; height:100%; overflow:hidden, margin:0} ```
Try this code: ``` $('body').css({ 'overflow': 'hidden' }); ```
32,565,304
I want to hide the scroll bar by using Jquery. Can anyone help me with it? ``` $ ::-webkit-scrollbar { display: none; } ``` This works for Chrome but I want my scroll to hide for all browsers, how can I do that?
2015/09/14
[ "https://Stackoverflow.com/questions/32565304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5176401/" ]
The reason your code only works in Chrome is that you are using `-webkit-scrollbar`. Chrome is built upon the (modified) webkit rendering engine, so this tag will only affect Chrome (and Safari, incidentally). Typically, the `-webkit-scrollbar` property is used to style scrollbars. To hide them, instead use the `overflow` property. Here is a CSS solution: ``` body { overflow: hidden; } ``` If you would like to do the same in jQuery, as asked, try adding the overflow property dynamically, like so: ``` $("body").css("overflow", "hidden"); ``` Note that you do not have to apply this property to your entire body. Any valid selector will do! If you are trying to hide the scrollbar, but still allow scrolling, you will have to get a little tricky with how you go about it. Try adding an inner container with `overflow: auto` and some right padding. This will allow the scrollbar to be pushed out of the containing div, effectively hiding it. Check out this fiddle to see it in action: <http://jsfiddle.net/zjfdvmLx/> The downside to this approach is that it is not entirely cross-browser friendly. Each browser decides how wide the scrollbar should be, and it could change at any time. If the `15px` used in the fiddle is not enough for your browser, increase the value. See [this](https://stackoverflow.com/questions/16670931/hide-scroll-bar-but-still-being-able-to-scroll) answer for more information.
Try this JS Code ``` $("body").css("overflow", "hidden"); ``` Css Code ``` body {width:100%; height:100%; overflow:hidden, margin:0} ```
32,565,304
I want to hide the scroll bar by using Jquery. Can anyone help me with it? ``` $ ::-webkit-scrollbar { display: none; } ``` This works for Chrome but I want my scroll to hide for all browsers, how can I do that?
2015/09/14
[ "https://Stackoverflow.com/questions/32565304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5176401/" ]
``` <style> /* width */ ::-webkit-scrollbar { width: 10px; } /* Track */ ::-webkit-scrollbar-track { box-shadow: inset 0 0 0px transparent; border-radius: 0px; } /* Handle */ ::-webkit-scrollbar-thumb { background: transparent; border-radius: 0px; } /* Handle on hover */ ::-webkit-scrollbar-thumb:hover { background: transparent; } </style> ```
Try this code: ``` $('body').css({ 'overflow': 'hidden' }); ```
32,565,304
I want to hide the scroll bar by using Jquery. Can anyone help me with it? ``` $ ::-webkit-scrollbar { display: none; } ``` This works for Chrome but I want my scroll to hide for all browsers, how can I do that?
2015/09/14
[ "https://Stackoverflow.com/questions/32565304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5176401/" ]
Instead you can hide the scrolling from the body itself. Try this ``` <style type="text/css"> body { overflow:hidden; } </style> ```
Try this code: ``` $('body').css({ 'overflow': 'hidden' }); ```
32,565,304
I want to hide the scroll bar by using Jquery. Can anyone help me with it? ``` $ ::-webkit-scrollbar { display: none; } ``` This works for Chrome but I want my scroll to hide for all browsers, how can I do that?
2015/09/14
[ "https://Stackoverflow.com/questions/32565304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5176401/" ]
The reason your code only works in Chrome is that you are using `-webkit-scrollbar`. Chrome is built upon the (modified) webkit rendering engine, so this tag will only affect Chrome (and Safari, incidentally). Typically, the `-webkit-scrollbar` property is used to style scrollbars. To hide them, instead use the `overflow` property. Here is a CSS solution: ``` body { overflow: hidden; } ``` If you would like to do the same in jQuery, as asked, try adding the overflow property dynamically, like so: ``` $("body").css("overflow", "hidden"); ``` Note that you do not have to apply this property to your entire body. Any valid selector will do! If you are trying to hide the scrollbar, but still allow scrolling, you will have to get a little tricky with how you go about it. Try adding an inner container with `overflow: auto` and some right padding. This will allow the scrollbar to be pushed out of the containing div, effectively hiding it. Check out this fiddle to see it in action: <http://jsfiddle.net/zjfdvmLx/> The downside to this approach is that it is not entirely cross-browser friendly. Each browser decides how wide the scrollbar should be, and it could change at any time. If the `15px` used in the fiddle is not enough for your browser, increase the value. See [this](https://stackoverflow.com/questions/16670931/hide-scroll-bar-but-still-being-able-to-scroll) answer for more information.
``` <style> /* width */ ::-webkit-scrollbar { width: 10px; } /* Track */ ::-webkit-scrollbar-track { box-shadow: inset 0 0 0px transparent; border-radius: 0px; } /* Handle */ ::-webkit-scrollbar-thumb { background: transparent; border-radius: 0px; } /* Handle on hover */ ::-webkit-scrollbar-thumb:hover { background: transparent; } </style> ```
2,578,858
I have to find the limit : (let $k\in \mathbb{R}$) > > $$\lim\_{n\to \infty}n^k \left(\Big(1+\frac{1}{n+1}\Big)^{n+1}-\Big(1+\frac{1}{n}\Big)^n \right)=?$$ > > > My Try : $$\lim\_{n\to \infty}\frac{n^k}{\Big(1+\frac{1}{n}\Big)^n} \left(\frac{\Big(1+\frac{1}{n+1}\Big)^{n+1}}{\Big(1+\frac{1}{n}\Big)^n}-1\right)$$ we know that : $$\frac{\Big(1+\frac{1}{n+1}\Big)^{n+1}}{\Big(1+\frac{1}{n}\Big)^n}>1$$ now what do i do ?
2017/12/24
[ "https://math.stackexchange.com/questions/2578858", "https://math.stackexchange.com", "https://math.stackexchange.com/users/505955/" ]
$$\left(1+\frac{1}{n}\right)^n = \exp\left[n\log\left(1+\frac{1}{n}\right)\right]=e-\frac{e}{2n}+O\left(\frac{1}{n^2}\right) $$ hence $$ \left(1+\frac{1}{n+1}\right)^{n+1}-\left(1+\frac{1}{n}\right)^n = \frac{e}{2n^2}+O\left(\frac{1}{n^3}\right) $$ and for a fixed $k\in\mathbb{R}$ $$ \lim\_{n\to +\infty}n^k\left[\left(1+\frac{1}{n+1}\right)^{n+1}-\left(1+\frac{1}{n}\right)^n\right]$$ is non-trivial only if $k=2$. Otherwise, it is either $0$ or $+\infty$.
$$\lim\_{n\to \infty}n^k \left((1+\frac{1}{n+1})^{n+1}-(1+\frac{1}{n})^n \right)= \lim\_{n\to \infty}n^k \left(\frac{e}{2n^2}+O((\frac{1}{n^3})) \right)$$ for n<2 limit is 0, for n=2 limit is e/2, for n>2 limit is infinity
2,578,858
I have to find the limit : (let $k\in \mathbb{R}$) > > $$\lim\_{n\to \infty}n^k \left(\Big(1+\frac{1}{n+1}\Big)^{n+1}-\Big(1+\frac{1}{n}\Big)^n \right)=?$$ > > > My Try : $$\lim\_{n\to \infty}\frac{n^k}{\Big(1+\frac{1}{n}\Big)^n} \left(\frac{\Big(1+\frac{1}{n+1}\Big)^{n+1}}{\Big(1+\frac{1}{n}\Big)^n}-1\right)$$ we know that : $$\frac{\Big(1+\frac{1}{n+1}\Big)^{n+1}}{\Big(1+\frac{1}{n}\Big)^n}>1$$ now what do i do ?
2017/12/24
[ "https://math.stackexchange.com/questions/2578858", "https://math.stackexchange.com", "https://math.stackexchange.com/users/505955/" ]
$$\left(1+\frac{1}{n}\right)^n = \exp\left[n\log\left(1+\frac{1}{n}\right)\right]=e-\frac{e}{2n}+O\left(\frac{1}{n^2}\right) $$ hence $$ \left(1+\frac{1}{n+1}\right)^{n+1}-\left(1+\frac{1}{n}\right)^n = \frac{e}{2n^2}+O\left(\frac{1}{n^3}\right) $$ and for a fixed $k\in\mathbb{R}$ $$ \lim\_{n\to +\infty}n^k\left[\left(1+\frac{1}{n+1}\right)^{n+1}-\left(1+\frac{1}{n}\right)^n\right]$$ is non-trivial only if $k=2$. Otherwise, it is either $0$ or $+\infty$.
Using only the Binomial Theorem and Bernoulli's Inequality: $$ \begin{align} \hspace{-1cm}\left(1+\frac1{n+1}\right)^{n+1}\!\!-\left(1+\frac1n\right)^n &=\left(\frac{n+2}{n+1}\right)^{n+1}-\left(\frac{n+1}n\right)^n\tag{1a}\\ &=\color{#C00}{\left(\frac{n+1}n-\frac1{(n+1)n}\right)^{n+1}}-\color{#090}{\left(\frac{n+1}n\right)^n}\tag{1b}\\ &=\color{#C00}{\left(\frac{n+1}n\right)^{n+1}-(n+1)\left(\frac{n+1}n\right)^n\frac1{(n+1)n}}\\ &\color{#C00}{{}+\frac{(n+1)n}2\left(\frac{n+1}n\right)^{n-1}\left(\frac1{(n+1)n}\right)^2+O\!\left(\frac1{n^3}\right)}\\ &-\color{#090}{\left(\frac{n+1}n\right)^n}\tag{1c}\\ &=\frac{(n+1)n}2\left(\frac{n+1}n\right)^{n-1}\left(\frac1{(n+1)n}\right)^2+O\!\left(\frac1{n^3}\right)\tag{1d}\\ &=\frac1{2(n+1)n}\left(\frac{n+1}n\right)^{n-1}+O\!\left(\frac1{n^3}\right)\tag{1e}\\[3pt] &=\frac{e}{2n^2}+O\!\left(\frac1{n^3}\right)\tag{1f} \end{align} $$ Explanation: $\text{(1a)}$: combine terms $\text{(1b)}$: add and subtract $\frac1{(n+1)n}$ $\text{(1c)}$: expand the first three terms of the Binomial expansion $\text{(1d)}$: the sum of the first two terms of the Binomial expansion $\phantom{\text{(1d):}}$ equals $\left(\frac{n+1}n\right)^n$ $\text{(1e)}$: simplify $\text{(1f)}$: $\frac1{(n+1)n}=\frac1{n^2}+O\!\left(\frac1{n^3}\right)$ and $\left(\frac{n+1}n\right)^{n-1}=e+O\!\left(\frac1n\right)$ $\phantom{\text{(1f):}}$ the latter equation uses [this answer](https://math.stackexchange.com/a/306245) to show that $\phantom{\text{(1f):}}$ $\left(1+\frac1n\right)^n\le e\le\left(1+\frac1n\right)^{n+1}$ with Bernoulli's Inequality
58,252,839
Why the below is not a valid Lambda Expression? ``` (Integer i) -> return "Alan" + i; ``` I expect it to be valid, But it is actually Invalid , Please Explain
2019/10/05
[ "https://Stackoverflow.com/questions/58252839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3431510/" ]
It would be a valid lambda expression if you got the syntax right. ``` Function<Integer, String> f1 = (Integer i) -> { return "Alan" + i; }; Function<Integer, String> f2 = (Integer i) -> "Alan" + i; Function<Integer, String> f3 = (i) -> "Alan" + i; Function<Integer, String> f4 = i -> "Alan" + i; ``` A lambda body is either an expression (1) or a block (2) ([JLS-15.27.2](https://docs.oracle.com/javase/specs/jls/se13/html/jls-15.html#jls-15.27.2)). (1) `return``expression` `return` is never a part of an expression, it's a statement that controls execution flow ([JLS-14.17](https://docs.oracle.com/javase/specs/jls/se13/html/jls-14.html#jls-14.17)). (2) To make it a block, braces are needed. `{ return expression; }`
A bit more context is needed, about how you're using it. But for starters, try removing the `return`: ``` (Integer i) -> "Alan" + i ``` Also, the `Integer` declaration might be redundant - but we really need to see what you're trying to accomplish, and the expected type of the lambda. Are you sure that the lambda is supposed to return a `String`?
63,159,456
> > This is my function > > > ``` const clicker = (input) => { setoutput((prev) => { return [...prev, input]; }); }; ``` > > I passed above function as a prop > > > ``` <Createcard click={clicker} /> ``` > > this is my component where i m using that function > > > ``` const Createcard = (props) => { const [input, setInput] = useState({ titel: "", content: "", }); const setInputs = (event) => { const { name, value } = event.target; setInput((prevData) => { return { ...prevData, [name]: value, }; }); }; // here I am passing my state value in function const clik = () => { props.click(input); }; return ( <div> <Card className={classes.root}> <TextField id="standard-basic" name="titel" value={input.titel} label="Titel" onChange={setInputs} placeholder="set" type="text" /> <TextField id="standard-basic1" name="content" value={input.content} label="Content" onChange={setInputs} /> // here i want to make my textfield empty after button click <Button className={classes.wid} onClick={clik}> <AddCircleOutlineIcon /> </Button> </Card> </div> ); }; ```
2020/07/29
[ "https://Stackoverflow.com/questions/63159456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13985314/" ]
How about something like: **XSLT 1.0** ``` <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> <xsl:template match="/Records"> <xsl:copy> <xsl:for-each select="Record"> <xsl:variable name="common" select="FILE | PERSONID | LNAME"/> <xsl:for-each select="*[position() > 3]"> <Record> <xsl:copy-of select="$common"/> <ATTRIBUTE> <xsl:value-of select="name()"/> </ATTRIBUTE> <VALUE> <xsl:value-of select="."/> </VALUE> </Record> </xsl:for-each> </xsl:for-each> </xsl:copy> </xsl:template> </xsl:stylesheet> ``` --- Note that this assumes every Record has at least one additional attribute. And that the input is a well-formed XML, unlike the one in your question - for example, it has a root element named `Records`.
This is another XSLT-1.0 solution: ``` <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="xml" /> <xsl:strip-space elements="*" /> <!-- Identity template --> <xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="node()|@*" /> </xsl:copy> </xsl:template> <xsl:template match="Record | Record/* | text()"> <xsl:apply-templates /> </xsl:template> <xsl:template match="Record/*[position()>3]"> <Record> <xsl:copy-of select="../*[3 >= position()]" /> <ATTRIBUTE><xsl:value-of select="local-name()" /></ATTRIBUTE> <VALUE><xsl:value-of select="." /></VALUE> </Record> </xsl:template> </xsl:stylesheet> ```
16,136,904
If I create a function that loops through executing a bunch of dynamic queries, the process time seems to get exponentially larger. For the sake of an example, im going to use the following code. Keep in mind, I HAVE to use an execute statement in my code. ``` FOR i IN 0..10 LOOP EXECUTE 'SELECT AVG(val) FROM some_table where x < '||i INTO count_var; IF count_var < 1 THEN INSERT INTO some_other_table (vals) VALUES (count_var); END IF; END LOOP; ``` If my for statement loops 10x, it takes 125ms to finish. If my for statement loops 100x, it takes 4,250ms to finish. Is there a setting I could use so that looping through it 100x would finish in 1,250ms? EDIT: More info ``` PostgreSQL 9.2.4 on x86_64-unknown-linux-gnu, compiled by gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3, 64-bit ``` Each of the execute queries is doing index-only scans. Here is the plan. ``` Aggregate (cost=85843.94..85843.94 rows=1 width=8) (actual time=1241.941..1241.944 rows=1 loops=1) -> Index Only Scan using some_table_index on some_table (cost=0.00..85393.77 rows=300114 width=8) (actual time=0.046..1081.718 rows=31293 loops=1) Index Cond: ((x > 1) AND (y < 1)) Heap Fetches: 0 Total runtime: 1242.012 ms ``` EDIT2: I rewrote the function in plperl. When I used "spi\_exec\_query()" on the 100x execute query, it ran in 4,250ms. When I used "spi\_query()" on the 100x execute query, it ran in 1,250ms - eliminating the exponential increase.
2013/04/21
[ "https://Stackoverflow.com/questions/16136904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1385338/" ]
### Why the slowdown? Calculating an average for row that qualify for `x < 100` is obviously *much more* expensive than calculating the same for `x < 1`. How much, we do not know, there is *nothing* in your question. Without knowing the data distribution in your table, we can only guess. There could be 5 rows for `x = 5`, and 5M rows for `x = 77`. Test: ``` FOR i IN 90..100 LOOP ... ``` vs. ``` FOR i IN 0..10 LOOP ... ``` And consider the numbers from ``` SELECT x, count(*) FROM some_table WHERE x < 100 GROUP BY 1; ``` Also, comparing two data points is hardly grounds for claiming "exponential growth". In a comment you speculate that Postgres might be starting to write to disk, which might just explain it. ### Plain SQL alternative Either way, there is nothing in your question to support your claim: > > I HAVE to use an execute statement > > > *Do you really?* This plain SQL statement does exactly the same as your PL/pgSQL fragment, but might be quite a bit faster: ``` INSERT INTO some_other_table (vals) SELECT avg_val_by_x FROM ( SELECT avg(val) OVER (ORDER BY x) AS avg_val_by_x FROM some_table WHERE x < 10 ) sub WHERE avg_val_by_x < 1; ```
First I want to echo Craig's request for real information. In my experience, loops become exponentially slower based on very nitty gritty details. I don't know if this will answer the question but I will give an example I ran across in my own work. If nothing else it will give a good example of something to look for when troubleshooting this issue. In an earlier incarnation of the bulk payment functions in LedgerSMB, we'd loop through the invoices (which would come in as a 2d array). We would then insert two rows for each invoice, and then update a third. For 10 invoices this would be fast. For 100 there would be a noticeable slowdown, and for 1000 (yes, this could happen, 1000 invoices paid at once to a vendor), the system would take a long time (as in hours). The problem had to do with caching. The system would effectively begin missing caches and these would increase in frequency until every write was effectively, a new bit of random disk I/O. Consequently the system would slow down as the loop got big. Our solution was to write all rows to a temporary table and then run two insert queries based on the contents of the temporary table and finally one update based on the same. This cut the time from hours down to something like a minute or two. If your case is at all like what you are saying, PostgreSQL will more effectively cache the first rows than the last rows. Moreover you are going to end up with the following: where i is 1, the answer is a1, where i is 2, the answer is (a1 + a2)/2, where i is 3, it is (a1 + a2 + a3)/3, and so forth. So you have both caching issues and computation issues. A third possibility, raised in your plperl edit is that you may be getting a plan for a few rows re-used for a plan with many more rows, to the point where the plan no longer makes sense. Note index only scans are not necessarily cheaper if a large part of the table is to be accessed since you lose the OS readahead caching. Without seeing real code though it is impossible to see what the real problem is. The above are shots in the dark or things to check.
411,700
**Background:** At 3.20.2 I am unable to manually adjust the raster histogram minimum and maximum X-values, as shown in the screen shot below. There are fill-in boxes (within the red graphic box) which lead me to believe that a manual adjustment is possible. However, changing those values does not change the histogram image. Changing the options in the Prefs/Actions dropdown has no effect, either. In summary, I want to control the *numeric spread* of the X-axis by manually setting the lower and upper values. In the screenshot below, I would like to leave the lower value unchanged, while increasing the maximum value to +0.20. **EDIT: Why do I need to do this?** I have 12 rasters (covering the same spatial extent), each depicting NDVI at a separate time. Because NDVI changes with the growing season, the resulting 12 histograms have differing min-X and max-X values. I need to sequentially display the histograms, and it would really help the viewer interpret those histograms if they all displayed *the same* min-X and max-X range. I have determined the absolute min value and max value for all 12 rasters, which I would use for all the histograms. **Question:** How to manually set the max/min X-values for QGIS raster histograms? [![enter image description here](https://i.stack.imgur.com/XtHnz.jpg)](https://i.stack.imgur.com/XtHnz.jpg) **Solution:** Babel's answer was correct. For posterity, here are the steps that worked for me at 3.20.3: **Original histogram:** I want to change the default min/max values within the red box. [![enter image description here](https://i.stack.imgur.com/pDl90.png)](https://i.stack.imgur.com/pDl90.png) **Process:** Click the *Prefs/Actions* button and make sure the *Zoom to Min/Max* and *Update Style to Min/Max* options are checked on. Click the *Reset* button (1), which clears the min/max boxes (2). [![enter image description here](https://i.stack.imgur.com/xurhP.png)](https://i.stack.imgur.com/xurhP.png) Type in the new Min/Max values. **Important:** Don't press the *Enter* button after typing the new values. I used the Tab button after entering each value. Voila! The histogram is updated with the new Min/Max values. [![enter image description here](https://i.stack.imgur.com/oUEhD.png)](https://i.stack.imgur.com/oUEhD.png)
2021/09/14
[ "https://gis.stackexchange.com/questions/411700", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/12840/" ]
Click `Prefs/Actions`, then activate `Zoom to min/max`: [![enter image description here](https://i.stack.imgur.com/AESIi.png)](https://i.stack.imgur.com/AESIi.png)
By default, bands are stretched to Min/Max. You can adjust this from the symbology tab. [![Band Rendering Options in QGIS](https://i.stack.imgur.com/UnC5Q.png)](https://i.stack.imgur.com/UnC5Q.png) If you leave the render type in Singleband Gray, you can simply input your desired Min/Max values and update the settings to User Defined. You also have the option to do a singleband pseudocolor, where you are also able to define the number of classes, the breakpoints (including stretching), and the color ramps.
161,546
``` Argument 1 passed to Magento\Framework\App\Action\Action::__construct() must be an instance of Magento\Framework\App\Action\Context, instance of Magento\Framework\ObjectManager\ObjectManager given ``` Banging my head over this. I have cleared both `var/di` and `var/generation`, flushed cache and then recompiled. Same thing happens. Same thing with this super basic controller ``` <?php namespace MyNamespace\MyModule\Controller\Loginas; class Index extends \Magento\Framework\App\Action\Action { public function execute() { return "TEST"; } } ``` router ``` <?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd"> <router id="standard"> <route id="mymodule" frontName="mymodule"> <module name="MyNamespace_MyModule"/> </route> </router> </config> ```
2017/02/23
[ "https://magento.stackexchange.com/questions/161546", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/47792/" ]
make you need to change your code to this: ``` <?php namespace MyNamespace\MyModule\Controller\Loginas; class Index extends \Magento\Framework\App\Action\Action { public function __construct( \Magento\Framework\App\Action\Context $context) { return parent::__construct($context); } public function execute() { return "TEST"; } } ``` After changing the code, remove the contents of var/generation/MyNamespace and then try to run again.
Seems like \_\_construct() method is missing in your controller. ``` public function __construct( \Magento\Framework\App\Action\Context $context, ) { parent::__construct($context); } ``` Also, your controller file should be inside appropriate folder like "Index" or "Adminhtml"
161,546
``` Argument 1 passed to Magento\Framework\App\Action\Action::__construct() must be an instance of Magento\Framework\App\Action\Context, instance of Magento\Framework\ObjectManager\ObjectManager given ``` Banging my head over this. I have cleared both `var/di` and `var/generation`, flushed cache and then recompiled. Same thing happens. Same thing with this super basic controller ``` <?php namespace MyNamespace\MyModule\Controller\Loginas; class Index extends \Magento\Framework\App\Action\Action { public function execute() { return "TEST"; } } ``` router ``` <?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd"> <router id="standard"> <route id="mymodule" frontName="mymodule"> <module name="MyNamespace_MyModule"/> </route> </router> </config> ```
2017/02/23
[ "https://magento.stackexchange.com/questions/161546", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/47792/" ]
Seems like \_\_construct() method is missing in your controller. ``` public function __construct( \Magento\Framework\App\Action\Context $context, ) { parent::__construct($context); } ``` Also, your controller file should be inside appropriate folder like "Index" or "Adminhtml"
Try this, I have injected object manager check the code, run `di:compile` comment after adding this code. ``` namespace MyModule\Service\Controller\Module; class Version extends \MyModule\Service\Controller\Module { protected $resultJsonFactory; protected $objectManager; protected $helper = null; protected $config = null; /** * @param \Magento\Framework\App\Action\Context $context * @param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory * @param \MyModule\Service\Helper\Data $helper */ public function __construct( \Magento\Framework\App\Action\Context $context, \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory, \MyModule\Service\Helper\Data $helper,\Magento\Framework\ObjectManagerInterface $objectmanager ) { $this->resultJsonFactory = $resultJsonFactory; $this->helper = $helper; $this->objectManager = $objectmanager; parent::__construct($context); parent::initParams(); } /** * @return \Magento\Framework\Controller\Result\Json */ public function execute() { $result = $this->resultJsonFactory->create(); $data = new \stdClass(); $data->magentoVersion = (string) $this->objectManager->get('\Magento\Framework\App\ProductMetadata')->getVersion(); $data->phpVersion = (string) phpversion(); $data->moduleEnabled = $this->helper->getConfig()['enabled']; $data->apiVersion = "2.0"; return $result->setData($data); } } ```
161,546
``` Argument 1 passed to Magento\Framework\App\Action\Action::__construct() must be an instance of Magento\Framework\App\Action\Context, instance of Magento\Framework\ObjectManager\ObjectManager given ``` Banging my head over this. I have cleared both `var/di` and `var/generation`, flushed cache and then recompiled. Same thing happens. Same thing with this super basic controller ``` <?php namespace MyNamespace\MyModule\Controller\Loginas; class Index extends \Magento\Framework\App\Action\Action { public function execute() { return "TEST"; } } ``` router ``` <?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd"> <router id="standard"> <route id="mymodule" frontName="mymodule"> <module name="MyNamespace_MyModule"/> </route> </router> </config> ```
2017/02/23
[ "https://magento.stackexchange.com/questions/161546", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/47792/" ]
make you need to change your code to this: ``` <?php namespace MyNamespace\MyModule\Controller\Loginas; class Index extends \Magento\Framework\App\Action\Action { public function __construct( \Magento\Framework\App\Action\Context $context) { return parent::__construct($context); } public function execute() { return "TEST"; } } ``` After changing the code, remove the contents of var/generation/MyNamespace and then try to run again.
Try this, I have injected object manager check the code, run `di:compile` comment after adding this code. ``` namespace MyModule\Service\Controller\Module; class Version extends \MyModule\Service\Controller\Module { protected $resultJsonFactory; protected $objectManager; protected $helper = null; protected $config = null; /** * @param \Magento\Framework\App\Action\Context $context * @param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory * @param \MyModule\Service\Helper\Data $helper */ public function __construct( \Magento\Framework\App\Action\Context $context, \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory, \MyModule\Service\Helper\Data $helper,\Magento\Framework\ObjectManagerInterface $objectmanager ) { $this->resultJsonFactory = $resultJsonFactory; $this->helper = $helper; $this->objectManager = $objectmanager; parent::__construct($context); parent::initParams(); } /** * @return \Magento\Framework\Controller\Result\Json */ public function execute() { $result = $this->resultJsonFactory->create(); $data = new \stdClass(); $data->magentoVersion = (string) $this->objectManager->get('\Magento\Framework\App\ProductMetadata')->getVersion(); $data->phpVersion = (string) phpversion(); $data->moduleEnabled = $this->helper->getConfig()['enabled']; $data->apiVersion = "2.0"; return $result->setData($data); } } ```
60,850,234
Although I have created a Firebase in-app messaging click listener, it tries to open the android system when the button is clicked. The url like that : <https://site_url/product_id> I want to open this url after a logic operation. ``` class MainActivity : AppCompatActivity() : FirebaseInAppMessagingClickListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) .... FirebaseInAppMessaging.getInstance().addClickListener(this) FirebaseInAppMessaging.getInstance().triggerEvent("main_activity_ready") } override fun messageClicked(message: InAppMessage, action: Action) { val url =( action.actionUrl ?: "") Log.d(TAG, "in-app messaging url : $url") linkParsePresenter.startLinkParse(url, PreviousPage.InAppMessaging) // This is my logic function. } } ``` [![enter image description here](https://i.stack.imgur.com/Yfg4K.png)](https://i.stack.imgur.com/Yfg4K.png) messageClicked function invoked. There is no problem. But the system also trying to open this url. How can I override or disable it?
2020/03/25
[ "https://Stackoverflow.com/questions/60850234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3103437/" ]
I'm struggling with this as well. Unfortunately it looks like there's no way around it at the moment. Firebase will call your custom `FirebaseInAppMessagingClickListener`, but then it'll try to navigate to the provided action URL regardless. This is an extract from [`FirebaseInAppMessagingDisplay`](https://github.com/firebase/firebase-android-sdk/blob/master/firebase-inappmessaging-display/src/main/java/com/google/firebase/inappmessaging/display/FirebaseInAppMessagingDisplay.java) : ```java actionListener = new OnClickListener() { public void onClick(View v) { if (FirebaseInAppMessagingDisplay.this.callbacks != null) { FirebaseInAppMessagingDisplay.this.callbacks.messageClicked(action); } CustomTabsIntent i = (new Builder()).setShowTitle(true).build(); i.launchUrl(activity, Uri.parse(action.getActionUrl())); FirebaseInAppMessagingDisplay.this.notifyFiamClick(); FirebaseInAppMessagingDisplay.this.removeDisplayedFiam(activity); FirebaseInAppMessagingDisplay.this.inAppMessage = null; FirebaseInAppMessagingDisplay.this.callbacks = null; } }; ``` As you can see Firebase will run through all the custom callbacks but then attempt navigation regardless with `launchUrl(activity, Uri.parse(action.getActionUrl()))`. The only option I can think of is to properly support deep-links in your app as recommended in [Customize your Firebase In-App Messaging messages](https://firebase.google.com/docs/in-app-messaging/customize-messages?platform=android#implement_a_deep_link_handler).
I solved it by adding a transparent activity which handles the deeplink. 1. Create empty activity; ``` class FirebaseEmptyActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) finish() } } ``` 2. Declare it in manifest: ``` <activity android:name=".FirebaseEmptyActivity" android:theme="@style/Theme.Transparent"> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:host="example.com" android:pathPrefix="/path-to-access" android:scheme="customscheme" /> </intent-filter> </activity> ``` So the above deeplink will work for: `customScheme://example.com/path-to-access` Declare a transparent theme: ``` <style name="Theme.Transparent" parent="AppTheme.NoActionbar"> <item name="android:windowIsTranslucent">true</item> <item name="android:windowBackground">@android:color/transparent</item> <item name="android:windowContentOverlay">@null</item> <item name="android:windowNoTitle">true</item> <item name="android:windowIsFloating">false</item> <item name="android:backgroundDimEnabled">false</item> </style> ``` Now in your activity listen for the button click: ``` FirebaseInAppMessaging.getInstance().removeAllListeners() FirebaseInAppMessaging.getInstance().addClickListener { inAppMessage, action -> if (action.actionUrl?.contains("your custom scheme url...") == true) { // The button was clicked for that action... } } ```
60,850,234
Although I have created a Firebase in-app messaging click listener, it tries to open the android system when the button is clicked. The url like that : <https://site_url/product_id> I want to open this url after a logic operation. ``` class MainActivity : AppCompatActivity() : FirebaseInAppMessagingClickListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) .... FirebaseInAppMessaging.getInstance().addClickListener(this) FirebaseInAppMessaging.getInstance().triggerEvent("main_activity_ready") } override fun messageClicked(message: InAppMessage, action: Action) { val url =( action.actionUrl ?: "") Log.d(TAG, "in-app messaging url : $url") linkParsePresenter.startLinkParse(url, PreviousPage.InAppMessaging) // This is my logic function. } } ``` [![enter image description here](https://i.stack.imgur.com/Yfg4K.png)](https://i.stack.imgur.com/Yfg4K.png) messageClicked function invoked. There is no problem. But the system also trying to open this url. How can I override or disable it?
2020/03/25
[ "https://Stackoverflow.com/questions/60850234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3103437/" ]
I'm struggling with this as well. Unfortunately it looks like there's no way around it at the moment. Firebase will call your custom `FirebaseInAppMessagingClickListener`, but then it'll try to navigate to the provided action URL regardless. This is an extract from [`FirebaseInAppMessagingDisplay`](https://github.com/firebase/firebase-android-sdk/blob/master/firebase-inappmessaging-display/src/main/java/com/google/firebase/inappmessaging/display/FirebaseInAppMessagingDisplay.java) : ```java actionListener = new OnClickListener() { public void onClick(View v) { if (FirebaseInAppMessagingDisplay.this.callbacks != null) { FirebaseInAppMessagingDisplay.this.callbacks.messageClicked(action); } CustomTabsIntent i = (new Builder()).setShowTitle(true).build(); i.launchUrl(activity, Uri.parse(action.getActionUrl())); FirebaseInAppMessagingDisplay.this.notifyFiamClick(); FirebaseInAppMessagingDisplay.this.removeDisplayedFiam(activity); FirebaseInAppMessagingDisplay.this.inAppMessage = null; FirebaseInAppMessagingDisplay.this.callbacks = null; } }; ``` As you can see Firebase will run through all the custom callbacks but then attempt navigation regardless with `launchUrl(activity, Uri.parse(action.getActionUrl()))`. The only option I can think of is to properly support deep-links in your app as recommended in [Customize your Firebase In-App Messaging messages](https://firebase.google.com/docs/in-app-messaging/customize-messages?platform=android#implement_a_deep_link_handler).
Firebase In-App Messaging (FIAM) is in Beta and doesn't support actions other than dynamic links as of now. And dynamic links are still links, so it will always try to navigate to the web first. Jumps outside the app then back (which makes it look like a virus) I think a better alternative is to use Firebase Cloud Messaging instead. The implementation looks more complex, but I highly recommend watching this guy explaining everything in detail: <https://www.youtube.com/watch?v=p7aIZ3aEi2w> Benefits of Firebase Cloud Messaging over Firebase In-App Messaging: * Push notifications - if the goal with FIAM was to communicate with users, this gets it done * Custom data - A key/value payload can be sent to the app, so you can customize the click action handler, better than FIAM, where it always opens the dynamic link * Silent messages - if you really want to replicate FIAM without the notifications part, you can send silent messages and handle the payload with custom dialogs in the app (silent messages can only be sent from the server, not through the Firebase Console yet) * FCM can be A/B tested as the FIAM Hope that helps and hope that Firebase makes FIAM more user-friendly in the future (like with a custom callback to handle the button's click)
2,381,377
I got the following definition: > > Let $f:X\to Y$ and $B\subseteq Y,A\subseteq X$ > > > The image of $A,F(A)$ is defined as $f(A)=\{f(a):a \in A\}$ > > > The Pre-image of $B, f^{-1}(B)$ is defined as $f^{-1}(B)=\{x\in X:f(x)\in B\}$ > > > In the pre-image is there a reason that we look at $x\in X$ and not $a\in A$?
2017/08/03
[ "https://math.stackexchange.com/questions/2381377", "https://math.stackexchange.com", "https://math.stackexchange.com/users/103441/" ]
$A$ is irrelevant to the definition; we are defining the pre-image for *arbitrary* subsets of $Y$.
$f[A]$ answers the question: "what points in $Y$ do we reach with $f$ from $A$"? $f^{-1}[B]$ answers the question "what points from $X$ map inside $B$"? The $A$ is just meant as arbitrary subset of $X$. The $B$ is just meant as an arbitrary subset of $Y$. They are not related. Exercise in the definitions: $$f[f^{-1}[B]] \subseteq B$$ with equality for all $B$ iff $f$ is surjective (onto) and $$A \subseteq f^{-1}[f[A]]$$ with equality for all $A$ iff $f$ is injective (one-to-one).
2,381,377
I got the following definition: > > Let $f:X\to Y$ and $B\subseteq Y,A\subseteq X$ > > > The image of $A,F(A)$ is defined as $f(A)=\{f(a):a \in A\}$ > > > The Pre-image of $B, f^{-1}(B)$ is defined as $f^{-1}(B)=\{x\in X:f(x)\in B\}$ > > > In the pre-image is there a reason that we look at $x\in X$ and not $a\in A$?
2017/08/03
[ "https://math.stackexchange.com/questions/2381377", "https://math.stackexchange.com", "https://math.stackexchange.com/users/103441/" ]
$f^{-1}(B) \not\subset A $ in general . $A \text { and } B$ are just arbitrary sets, and there's no reason to assume the preimage of $B$ is contained in $A$.
$f[A]$ answers the question: "what points in $Y$ do we reach with $f$ from $A$"? $f^{-1}[B]$ answers the question "what points from $X$ map inside $B$"? The $A$ is just meant as arbitrary subset of $X$. The $B$ is just meant as an arbitrary subset of $Y$. They are not related. Exercise in the definitions: $$f[f^{-1}[B]] \subseteq B$$ with equality for all $B$ iff $f$ is surjective (onto) and $$A \subseteq f^{-1}[f[A]]$$ with equality for all $A$ iff $f$ is injective (one-to-one).
51,597,820
I am using VBA to clear certain cells in an excel file, but when it clears them the value remains. When I click on the cell value disappears but I need it to do it once the cell is cleared in the code. Edit: As requested, more code. The cells still do not empty until I have clicked them even with setting the value to empty as suggested. ``` Private Sub Update(Target As Range, EventTarget As Range) On Error GoTo ErrorHandling Application.EnableEvents = False Dim CurrDevice As String Dim CurrPort As String Dim ConcatInfo As String CurrDevice = Range("B" & Target.Row).Value CurrPort = Range("C" & Target.Row).Value ConcatInfo = CurrDevice + CurrPort Dim TargetRange As Range Set TargetRange = Range("R2:R" & EventTarget.Row - 1).Find(ConcatInfo, LookIn:=xlValues) If Not TargetRange Is Nothing And Not TargetRange.Row = EventTarget.Row Then 'Range("F" & TargetRange.Row, "P" & TargetRange.Row).ClearContents Range("F" & TargetRange.Row, "P" & TargetRange.Row).Value = Empty End If End If Set TargetRange = Nothing Set TargetRange = Range("R" & (EventTarget.Row + 1), Range("R" & (EventTarget.Row + 1)).End(xlDown)).Find(ConcatInfo, LookIn:=xlValues) If Not TargetRange Is Nothing And Not TargetRange.Row = EventTarget.Row Then 'Range("F" & TargetRange.Row, "P" & TargetRange.Row).ClearContents Range("F" & TargetRange.Row, "P" & TargetRange.Row).Value = Empty End If Exit Sub ``` ErrorHandling: Application.EnableEvents = True End Sub
2018/07/30
[ "https://Stackoverflow.com/questions/51597820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10145155/" ]
why not try like this with [forEach()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) ```js var residents = [{ name: "Pyrus", room: "32" }, { name: "Ash Ketchum", room: "22" }]; function people(residents) { residents.forEach((element) => { for (var key in element) { if (element.hasOwnProperty(key)) { console.log(key + ':' + element[key]); } } }); }; people(residents); ```
You can avoid some of the `for` loops and make the code a little easier to read using `forEach` and `Object.entries`: ```js var residents = [{name: "Pyrus", room: "32"},{name: "Ash Ketchum", room: "22"}]; residents.forEach(res => { Object.entries(res).forEach(([key, value]) => { console.log(key + ": " + value ); //subing console.log so it prints here //document.write(key + ": " + value + "<br>"); }) }) ```
51,597,820
I am using VBA to clear certain cells in an excel file, but when it clears them the value remains. When I click on the cell value disappears but I need it to do it once the cell is cleared in the code. Edit: As requested, more code. The cells still do not empty until I have clicked them even with setting the value to empty as suggested. ``` Private Sub Update(Target As Range, EventTarget As Range) On Error GoTo ErrorHandling Application.EnableEvents = False Dim CurrDevice As String Dim CurrPort As String Dim ConcatInfo As String CurrDevice = Range("B" & Target.Row).Value CurrPort = Range("C" & Target.Row).Value ConcatInfo = CurrDevice + CurrPort Dim TargetRange As Range Set TargetRange = Range("R2:R" & EventTarget.Row - 1).Find(ConcatInfo, LookIn:=xlValues) If Not TargetRange Is Nothing And Not TargetRange.Row = EventTarget.Row Then 'Range("F" & TargetRange.Row, "P" & TargetRange.Row).ClearContents Range("F" & TargetRange.Row, "P" & TargetRange.Row).Value = Empty End If End If Set TargetRange = Nothing Set TargetRange = Range("R" & (EventTarget.Row + 1), Range("R" & (EventTarget.Row + 1)).End(xlDown)).Find(ConcatInfo, LookIn:=xlValues) If Not TargetRange Is Nothing And Not TargetRange.Row = EventTarget.Row Then 'Range("F" & TargetRange.Row, "P" & TargetRange.Row).ClearContents Range("F" & TargetRange.Row, "P" & TargetRange.Row).Value = Empty End If Exit Sub ``` ErrorHandling: Application.EnableEvents = True End Sub
2018/07/30
[ "https://Stackoverflow.com/questions/51597820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10145155/" ]
You have chained two loops together so your function needs to access the parents index then the property that you wish to reference. ``` function people() { for (let i = 0; i < residents.length; i++) { for (let j in residents[i]) { document.write(j + ": " + residents[i][j] + "<br>"); } } }; ```
This is the simplest way I think(Use [`foreach()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)): ```js var residents = [{name: "Pyrus", room: "32"},{name: "Ash Ketchum", room: "22"}]; function people() { residents.forEach(function(resident) { document.write(resident.name + ": " + resident.room + "<br>"); }); } people(); ```
51,597,820
I am using VBA to clear certain cells in an excel file, but when it clears them the value remains. When I click on the cell value disappears but I need it to do it once the cell is cleared in the code. Edit: As requested, more code. The cells still do not empty until I have clicked them even with setting the value to empty as suggested. ``` Private Sub Update(Target As Range, EventTarget As Range) On Error GoTo ErrorHandling Application.EnableEvents = False Dim CurrDevice As String Dim CurrPort As String Dim ConcatInfo As String CurrDevice = Range("B" & Target.Row).Value CurrPort = Range("C" & Target.Row).Value ConcatInfo = CurrDevice + CurrPort Dim TargetRange As Range Set TargetRange = Range("R2:R" & EventTarget.Row - 1).Find(ConcatInfo, LookIn:=xlValues) If Not TargetRange Is Nothing And Not TargetRange.Row = EventTarget.Row Then 'Range("F" & TargetRange.Row, "P" & TargetRange.Row).ClearContents Range("F" & TargetRange.Row, "P" & TargetRange.Row).Value = Empty End If End If Set TargetRange = Nothing Set TargetRange = Range("R" & (EventTarget.Row + 1), Range("R" & (EventTarget.Row + 1)).End(xlDown)).Find(ConcatInfo, LookIn:=xlValues) If Not TargetRange Is Nothing And Not TargetRange.Row = EventTarget.Row Then 'Range("F" & TargetRange.Row, "P" & TargetRange.Row).ClearContents Range("F" & TargetRange.Row, "P" & TargetRange.Row).Value = Empty End If Exit Sub ``` ErrorHandling: Application.EnableEvents = True End Sub
2018/07/30
[ "https://Stackoverflow.com/questions/51597820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10145155/" ]
You have chained two loops together so your function needs to access the parents index then the property that you wish to reference. ``` function people() { for (let i = 0; i < residents.length; i++) { for (let j in residents[i]) { document.write(j + ": " + residents[i][j] + "<br>"); } } }; ```
Using a regular for-loop it would go like the below code. Also, I strongly recommend you to check if all the properties (`j`) are own properties (with [`hasOwnProperty`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty)), otherwise this will look up in the prototype chain. This can be a problem if the objects are added to the array dynamically, otherwise you can bypass this check. ```js var residents = [{name:"Pyrus",room:"32"},{name: "Ash Ketchum",room:"22"}]; function people() { for (let i = 0; i < residents.length; i++) { for (let j in residents[i]) { if (residents[i].hasOwnProperty(j)) { // <-- check if it is an own property! document.write(j + ": " + residents[i][j] + "<br>"); //first access the object in residents[i], for example {name: "Pyrus",room: "32"}, then to its properties-values with residents[i][j] } } } }; people(); ```
51,597,820
I am using VBA to clear certain cells in an excel file, but when it clears them the value remains. When I click on the cell value disappears but I need it to do it once the cell is cleared in the code. Edit: As requested, more code. The cells still do not empty until I have clicked them even with setting the value to empty as suggested. ``` Private Sub Update(Target As Range, EventTarget As Range) On Error GoTo ErrorHandling Application.EnableEvents = False Dim CurrDevice As String Dim CurrPort As String Dim ConcatInfo As String CurrDevice = Range("B" & Target.Row).Value CurrPort = Range("C" & Target.Row).Value ConcatInfo = CurrDevice + CurrPort Dim TargetRange As Range Set TargetRange = Range("R2:R" & EventTarget.Row - 1).Find(ConcatInfo, LookIn:=xlValues) If Not TargetRange Is Nothing And Not TargetRange.Row = EventTarget.Row Then 'Range("F" & TargetRange.Row, "P" & TargetRange.Row).ClearContents Range("F" & TargetRange.Row, "P" & TargetRange.Row).Value = Empty End If End If Set TargetRange = Nothing Set TargetRange = Range("R" & (EventTarget.Row + 1), Range("R" & (EventTarget.Row + 1)).End(xlDown)).Find(ConcatInfo, LookIn:=xlValues) If Not TargetRange Is Nothing And Not TargetRange.Row = EventTarget.Row Then 'Range("F" & TargetRange.Row, "P" & TargetRange.Row).ClearContents Range("F" & TargetRange.Row, "P" & TargetRange.Row).Value = Empty End If Exit Sub ``` ErrorHandling: Application.EnableEvents = True End Sub
2018/07/30
[ "https://Stackoverflow.com/questions/51597820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10145155/" ]
This is the simplest way I think(Use [`foreach()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)): ```js var residents = [{name: "Pyrus", room: "32"},{name: "Ash Ketchum", room: "22"}]; function people() { residents.forEach(function(resident) { document.write(resident.name + ": " + resident.room + "<br>"); }); } people(); ```
You can avoid some of the `for` loops and make the code a little easier to read using `forEach` and `Object.entries`: ```js var residents = [{name: "Pyrus", room: "32"},{name: "Ash Ketchum", room: "22"}]; residents.forEach(res => { Object.entries(res).forEach(([key, value]) => { console.log(key + ": " + value ); //subing console.log so it prints here //document.write(key + ": " + value + "<br>"); }) }) ```
51,597,820
I am using VBA to clear certain cells in an excel file, but when it clears them the value remains. When I click on the cell value disappears but I need it to do it once the cell is cleared in the code. Edit: As requested, more code. The cells still do not empty until I have clicked them even with setting the value to empty as suggested. ``` Private Sub Update(Target As Range, EventTarget As Range) On Error GoTo ErrorHandling Application.EnableEvents = False Dim CurrDevice As String Dim CurrPort As String Dim ConcatInfo As String CurrDevice = Range("B" & Target.Row).Value CurrPort = Range("C" & Target.Row).Value ConcatInfo = CurrDevice + CurrPort Dim TargetRange As Range Set TargetRange = Range("R2:R" & EventTarget.Row - 1).Find(ConcatInfo, LookIn:=xlValues) If Not TargetRange Is Nothing And Not TargetRange.Row = EventTarget.Row Then 'Range("F" & TargetRange.Row, "P" & TargetRange.Row).ClearContents Range("F" & TargetRange.Row, "P" & TargetRange.Row).Value = Empty End If End If Set TargetRange = Nothing Set TargetRange = Range("R" & (EventTarget.Row + 1), Range("R" & (EventTarget.Row + 1)).End(xlDown)).Find(ConcatInfo, LookIn:=xlValues) If Not TargetRange Is Nothing And Not TargetRange.Row = EventTarget.Row Then 'Range("F" & TargetRange.Row, "P" & TargetRange.Row).ClearContents Range("F" & TargetRange.Row, "P" & TargetRange.Row).Value = Empty End If Exit Sub ``` ErrorHandling: Application.EnableEvents = True End Sub
2018/07/30
[ "https://Stackoverflow.com/questions/51597820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10145155/" ]
This is the simplest way I think(Use [`foreach()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)): ```js var residents = [{name: "Pyrus", room: "32"},{name: "Ash Ketchum", room: "22"}]; function people() { residents.forEach(function(resident) { document.write(resident.name + ": " + resident.room + "<br>"); }); } people(); ```
You need to access `residents[i][j]` since you are iterating residents in the first place. so your code becomes : `document.write(j + ": " + residents[i][j] + "<br>");` See this [working js fiddle](https://jsfiddle.net/Lo1m07us/) You could also write it like this : ``` function people(){ residents.forEach(r => { for(let j in r){ document.write(j + ": " + r[j] + "<br>"); } }) } ``` Hope this helps.
51,597,820
I am using VBA to clear certain cells in an excel file, but when it clears them the value remains. When I click on the cell value disappears but I need it to do it once the cell is cleared in the code. Edit: As requested, more code. The cells still do not empty until I have clicked them even with setting the value to empty as suggested. ``` Private Sub Update(Target As Range, EventTarget As Range) On Error GoTo ErrorHandling Application.EnableEvents = False Dim CurrDevice As String Dim CurrPort As String Dim ConcatInfo As String CurrDevice = Range("B" & Target.Row).Value CurrPort = Range("C" & Target.Row).Value ConcatInfo = CurrDevice + CurrPort Dim TargetRange As Range Set TargetRange = Range("R2:R" & EventTarget.Row - 1).Find(ConcatInfo, LookIn:=xlValues) If Not TargetRange Is Nothing And Not TargetRange.Row = EventTarget.Row Then 'Range("F" & TargetRange.Row, "P" & TargetRange.Row).ClearContents Range("F" & TargetRange.Row, "P" & TargetRange.Row).Value = Empty End If End If Set TargetRange = Nothing Set TargetRange = Range("R" & (EventTarget.Row + 1), Range("R" & (EventTarget.Row + 1)).End(xlDown)).Find(ConcatInfo, LookIn:=xlValues) If Not TargetRange Is Nothing And Not TargetRange.Row = EventTarget.Row Then 'Range("F" & TargetRange.Row, "P" & TargetRange.Row).ClearContents Range("F" & TargetRange.Row, "P" & TargetRange.Row).Value = Empty End If Exit Sub ``` ErrorHandling: Application.EnableEvents = True End Sub
2018/07/30
[ "https://Stackoverflow.com/questions/51597820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10145155/" ]
why not try like this with [forEach()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) ```js var residents = [{ name: "Pyrus", room: "32" }, { name: "Ash Ketchum", room: "22" }]; function people(residents) { residents.forEach((element) => { for (var key in element) { if (element.hasOwnProperty(key)) { console.log(key + ':' + element[key]); } } }); }; people(residents); ```
You need to access `residents[i][j]` since you are iterating residents in the first place. so your code becomes : `document.write(j + ": " + residents[i][j] + "<br>");` See this [working js fiddle](https://jsfiddle.net/Lo1m07us/) You could also write it like this : ``` function people(){ residents.forEach(r => { for(let j in r){ document.write(j + ": " + r[j] + "<br>"); } }) } ``` Hope this helps.
51,597,820
I am using VBA to clear certain cells in an excel file, but when it clears them the value remains. When I click on the cell value disappears but I need it to do it once the cell is cleared in the code. Edit: As requested, more code. The cells still do not empty until I have clicked them even with setting the value to empty as suggested. ``` Private Sub Update(Target As Range, EventTarget As Range) On Error GoTo ErrorHandling Application.EnableEvents = False Dim CurrDevice As String Dim CurrPort As String Dim ConcatInfo As String CurrDevice = Range("B" & Target.Row).Value CurrPort = Range("C" & Target.Row).Value ConcatInfo = CurrDevice + CurrPort Dim TargetRange As Range Set TargetRange = Range("R2:R" & EventTarget.Row - 1).Find(ConcatInfo, LookIn:=xlValues) If Not TargetRange Is Nothing And Not TargetRange.Row = EventTarget.Row Then 'Range("F" & TargetRange.Row, "P" & TargetRange.Row).ClearContents Range("F" & TargetRange.Row, "P" & TargetRange.Row).Value = Empty End If End If Set TargetRange = Nothing Set TargetRange = Range("R" & (EventTarget.Row + 1), Range("R" & (EventTarget.Row + 1)).End(xlDown)).Find(ConcatInfo, LookIn:=xlValues) If Not TargetRange Is Nothing And Not TargetRange.Row = EventTarget.Row Then 'Range("F" & TargetRange.Row, "P" & TargetRange.Row).ClearContents Range("F" & TargetRange.Row, "P" & TargetRange.Row).Value = Empty End If Exit Sub ``` ErrorHandling: Application.EnableEvents = True End Sub
2018/07/30
[ "https://Stackoverflow.com/questions/51597820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10145155/" ]
You have chained two loops together so your function needs to access the parents index then the property that you wish to reference. ``` function people() { for (let i = 0; i < residents.length; i++) { for (let j in residents[i]) { document.write(j + ": " + residents[i][j] + "<br>"); } } }; ```
You need to access `residents[i][j]` since you are iterating residents in the first place. so your code becomes : `document.write(j + ": " + residents[i][j] + "<br>");` See this [working js fiddle](https://jsfiddle.net/Lo1m07us/) You could also write it like this : ``` function people(){ residents.forEach(r => { for(let j in r){ document.write(j + ": " + r[j] + "<br>"); } }) } ``` Hope this helps.
51,597,820
I am using VBA to clear certain cells in an excel file, but when it clears them the value remains. When I click on the cell value disappears but I need it to do it once the cell is cleared in the code. Edit: As requested, more code. The cells still do not empty until I have clicked them even with setting the value to empty as suggested. ``` Private Sub Update(Target As Range, EventTarget As Range) On Error GoTo ErrorHandling Application.EnableEvents = False Dim CurrDevice As String Dim CurrPort As String Dim ConcatInfo As String CurrDevice = Range("B" & Target.Row).Value CurrPort = Range("C" & Target.Row).Value ConcatInfo = CurrDevice + CurrPort Dim TargetRange As Range Set TargetRange = Range("R2:R" & EventTarget.Row - 1).Find(ConcatInfo, LookIn:=xlValues) If Not TargetRange Is Nothing And Not TargetRange.Row = EventTarget.Row Then 'Range("F" & TargetRange.Row, "P" & TargetRange.Row).ClearContents Range("F" & TargetRange.Row, "P" & TargetRange.Row).Value = Empty End If End If Set TargetRange = Nothing Set TargetRange = Range("R" & (EventTarget.Row + 1), Range("R" & (EventTarget.Row + 1)).End(xlDown)).Find(ConcatInfo, LookIn:=xlValues) If Not TargetRange Is Nothing And Not TargetRange.Row = EventTarget.Row Then 'Range("F" & TargetRange.Row, "P" & TargetRange.Row).ClearContents Range("F" & TargetRange.Row, "P" & TargetRange.Row).Value = Empty End If Exit Sub ``` ErrorHandling: Application.EnableEvents = True End Sub
2018/07/30
[ "https://Stackoverflow.com/questions/51597820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10145155/" ]
why not try like this with [forEach()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) ```js var residents = [{ name: "Pyrus", room: "32" }, { name: "Ash Ketchum", room: "22" }]; function people(residents) { residents.forEach((element) => { for (var key in element) { if (element.hasOwnProperty(key)) { console.log(key + ':' + element[key]); } } }); }; people(residents); ```
Using a regular for-loop it would go like the below code. Also, I strongly recommend you to check if all the properties (`j`) are own properties (with [`hasOwnProperty`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty)), otherwise this will look up in the prototype chain. This can be a problem if the objects are added to the array dynamically, otherwise you can bypass this check. ```js var residents = [{name:"Pyrus",room:"32"},{name: "Ash Ketchum",room:"22"}]; function people() { for (let i = 0; i < residents.length; i++) { for (let j in residents[i]) { if (residents[i].hasOwnProperty(j)) { // <-- check if it is an own property! document.write(j + ": " + residents[i][j] + "<br>"); //first access the object in residents[i], for example {name: "Pyrus",room: "32"}, then to its properties-values with residents[i][j] } } } }; people(); ```
51,597,820
I am using VBA to clear certain cells in an excel file, but when it clears them the value remains. When I click on the cell value disappears but I need it to do it once the cell is cleared in the code. Edit: As requested, more code. The cells still do not empty until I have clicked them even with setting the value to empty as suggested. ``` Private Sub Update(Target As Range, EventTarget As Range) On Error GoTo ErrorHandling Application.EnableEvents = False Dim CurrDevice As String Dim CurrPort As String Dim ConcatInfo As String CurrDevice = Range("B" & Target.Row).Value CurrPort = Range("C" & Target.Row).Value ConcatInfo = CurrDevice + CurrPort Dim TargetRange As Range Set TargetRange = Range("R2:R" & EventTarget.Row - 1).Find(ConcatInfo, LookIn:=xlValues) If Not TargetRange Is Nothing And Not TargetRange.Row = EventTarget.Row Then 'Range("F" & TargetRange.Row, "P" & TargetRange.Row).ClearContents Range("F" & TargetRange.Row, "P" & TargetRange.Row).Value = Empty End If End If Set TargetRange = Nothing Set TargetRange = Range("R" & (EventTarget.Row + 1), Range("R" & (EventTarget.Row + 1)).End(xlDown)).Find(ConcatInfo, LookIn:=xlValues) If Not TargetRange Is Nothing And Not TargetRange.Row = EventTarget.Row Then 'Range("F" & TargetRange.Row, "P" & TargetRange.Row).ClearContents Range("F" & TargetRange.Row, "P" & TargetRange.Row).Value = Empty End If Exit Sub ``` ErrorHandling: Application.EnableEvents = True End Sub
2018/07/30
[ "https://Stackoverflow.com/questions/51597820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10145155/" ]
You have chained two loops together so your function needs to access the parents index then the property that you wish to reference. ``` function people() { for (let i = 0; i < residents.length; i++) { for (let j in residents[i]) { document.write(j + ": " + residents[i][j] + "<br>"); } } }; ```
You can avoid some of the `for` loops and make the code a little easier to read using `forEach` and `Object.entries`: ```js var residents = [{name: "Pyrus", room: "32"},{name: "Ash Ketchum", room: "22"}]; residents.forEach(res => { Object.entries(res).forEach(([key, value]) => { console.log(key + ": " + value ); //subing console.log so it prints here //document.write(key + ": " + value + "<br>"); }) }) ```
51,597,820
I am using VBA to clear certain cells in an excel file, but when it clears them the value remains. When I click on the cell value disappears but I need it to do it once the cell is cleared in the code. Edit: As requested, more code. The cells still do not empty until I have clicked them even with setting the value to empty as suggested. ``` Private Sub Update(Target As Range, EventTarget As Range) On Error GoTo ErrorHandling Application.EnableEvents = False Dim CurrDevice As String Dim CurrPort As String Dim ConcatInfo As String CurrDevice = Range("B" & Target.Row).Value CurrPort = Range("C" & Target.Row).Value ConcatInfo = CurrDevice + CurrPort Dim TargetRange As Range Set TargetRange = Range("R2:R" & EventTarget.Row - 1).Find(ConcatInfo, LookIn:=xlValues) If Not TargetRange Is Nothing And Not TargetRange.Row = EventTarget.Row Then 'Range("F" & TargetRange.Row, "P" & TargetRange.Row).ClearContents Range("F" & TargetRange.Row, "P" & TargetRange.Row).Value = Empty End If End If Set TargetRange = Nothing Set TargetRange = Range("R" & (EventTarget.Row + 1), Range("R" & (EventTarget.Row + 1)).End(xlDown)).Find(ConcatInfo, LookIn:=xlValues) If Not TargetRange Is Nothing And Not TargetRange.Row = EventTarget.Row Then 'Range("F" & TargetRange.Row, "P" & TargetRange.Row).ClearContents Range("F" & TargetRange.Row, "P" & TargetRange.Row).Value = Empty End If Exit Sub ``` ErrorHandling: Application.EnableEvents = True End Sub
2018/07/30
[ "https://Stackoverflow.com/questions/51597820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10145155/" ]
This is the simplest way I think(Use [`foreach()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)): ```js var residents = [{name: "Pyrus", room: "32"},{name: "Ash Ketchum", room: "22"}]; function people() { residents.forEach(function(resident) { document.write(resident.name + ": " + resident.room + "<br>"); }); } people(); ```
why not try like this with [forEach()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) ```js var residents = [{ name: "Pyrus", room: "32" }, { name: "Ash Ketchum", room: "22" }]; function people(residents) { residents.forEach((element) => { for (var key in element) { if (element.hasOwnProperty(key)) { console.log(key + ':' + element[key]); } } }); }; people(residents); ```
46,012,272
I am currently building an electron app. I have a PDF on my local file system which I need to silently print out (on the default printer). I came across the node-printer library, but it doesn't seem to work for me. Is there an easy solution to achieve this?
2017/09/02
[ "https://Stackoverflow.com/questions/46012272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5609492/" ]
Well first of all it is near impossible to understand what you mean with "silent" print. Because once you send a print order to your system printer it will be out of your hand to be silent at all. On Windows for example once the order was given, at least the systemtray icon will indicate that something is going on. That said, there are very good described features for printing with electron even "silent" is one of them: You need to get [all system printers](https://electron.atom.io/docs/api/web-contents/#contentsgetprinters) if you do not want to use the default printer: ``` contents.getPrinters() ``` Which will return a `PrinterInfo[]` Object. Here is an example how the object will look like from the [electron PrtinerInfo Docs](https://electron.atom.io/docs/api/structures/printer-info/): ``` { name: 'Zebra_LP2844', description: 'Zebra LP2844', status: 3, isDefault: false, options: { copies: '1', 'device-uri': 'usb://Zebra/LP2844?location=14200000', finishings: '3', 'job-cancel-after': '10800', 'job-hold-until': 'no-hold', 'job-priority': '50', 'job-sheets': 'none,none', 'marker-change-time': '0', 'number-up': '1', 'printer-commands': 'none', 'printer-info': 'Zebra LP2844', 'printer-is-accepting-jobs': 'true', 'printer-is-shared': 'true', 'printer-location': '', 'printer-make-and-model': 'Zebra EPL2 Label Printer', 'printer-state': '3', 'printer-state-change-time': '1484872644', 'printer-state-reasons': 'offline-report', 'printer-type': '36932', 'printer-uri-supported': 'ipp://localhost/printers/Zebra_LP2844', system_driverinfo: 'Z' } } ``` To print your file you can do it with ``` contents.print([options]) ``` The options are descriped in the [docs for contents.print()](https://electron.atom.io/docs/api/web-contents/#contentsprintoptions): * options Object (optional): * silent Boolean (optional) - Don’t ask user for print settings. Default is false. * printBackground Boolean (optional) - Also prints the background color and image of the web page. Default is false. * deviceName String (optional) - Set the printer device name to use. Default is ''. Prints window’s web page. When `silent` is set to true, Electron will pick the system’s default printer if `deviceName` is empty and the default settings for printing. Calling `window.print()` in web page is equivalent to calling `webContents.print({silent: false, printBackground: false, deviceName: ''})`. Use `page-break-before: always;` CSS style to force to print to a new page. So all you need is to load the PDF into a hidden window and then fire the print method implemented in electron with the flag set to silent. ``` // In the main process. const {app, BrowserWindow} = require('electron'); let win = null; app.on('ready', () => { // Create window win = new BrowserWindow({width: 800, height: 600, show: false }); // Could be redundant, try if you need this. win.once('ready-to-show', () => win.hide()) // load PDF. win.loadURL(`file://directory/to/pdf/document.pdf`); // if pdf is loaded start printing. win.webContents.on('did-finish-load', () => { win.webContents.print({silent: true}); // close window after print order. win = null; }); }); ``` However let me give you a little warning: Once you start printing it can and will get frustrating because there are drivers out there which will interpret data in a slightly different way. Meaning that margins could be ignored and much more. Since you already have a PDF this problem will most likely not happen. But keep this in mind if you ever want to use [this method for example](https://electron.atom.io/docs/api/web-contents/#contentsprinttopdfoptions-callback) `contents.printToPDF(options, callback)`. That beeing said there are plently of options to avoid getting frustrated like using a predefined stylesheet like descriped in this question: [Print: How to stick footer on every page to the bottom?](https://stackoverflow.com/questions/42505164/print-how-to-stick-footer-on-every-page-to-the-bottom) If you want to search for features in electron and you do not know where they could be hidden, all you have to do is to go to "all" docs and use your search function: <https://electron.atom.io/docs/all/> regards, Megajin
To my knowledge there is currently no way to do this directly using Electron because while using `contents.print([])` does allow for 'silently' printing HTML files, it isn't able to print PDF views. This is currently an open feature request: <https://github.com/electron/electron/issues/9029> **Edit**: I managed to work around this by converting the PDF to a PNG and then using Electron's print functionality (which is able to print PNGs) to print the image based view. One of the major downsides to this is that all of the PDF to PNG/JPEG conversion libraries for NodeJS have a number of dependencies, meaning I had to implement them in an Express server and then have my Electron app send all PDFs to the server for conversion. It's not a great option, but it does work.
46,012,272
I am currently building an electron app. I have a PDF on my local file system which I need to silently print out (on the default printer). I came across the node-printer library, but it doesn't seem to work for me. Is there an easy solution to achieve this?
2017/09/02
[ "https://Stackoverflow.com/questions/46012272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5609492/" ]
I recently published NPM package to print PDF files from Node.js and Electron. You can send a PDF file to the default printer or to a specific one. Works fine on Windows and Unix-like operating systems: <https://github.com/artiebits/pdf-to-printer>. It's easy to install, just (if using **yarn**): ``` yarn add pdf-to-printer ``` or (if using **npm**): ``` npm install --save pdf-to-printer ``` Then, to silently print the file to the default printer you do: ``` import { print } from "pdf-to-printer"; print("assets/pdf-sample.pdf") .then(console.log) .catch(console.error); ```
To my knowledge there is currently no way to do this directly using Electron because while using `contents.print([])` does allow for 'silently' printing HTML files, it isn't able to print PDF views. This is currently an open feature request: <https://github.com/electron/electron/issues/9029> **Edit**: I managed to work around this by converting the PDF to a PNG and then using Electron's print functionality (which is able to print PNGs) to print the image based view. One of the major downsides to this is that all of the PDF to PNG/JPEG conversion libraries for NodeJS have a number of dependencies, meaning I had to implement them in an Express server and then have my Electron app send all PDFs to the server for conversion. It's not a great option, but it does work.
1,377,132
[This Question](https://superuser.com/q/1088165/212610) asks about getting the [fingerprint of a SSH key](https://en.wikipedia.org/wiki/Public_key_fingerprint) while generating the new key with `ssh-keygen`. But how does one get determine the fingerprint of an *existing* public key in a `.pub` file? ➥ How to get: * **SHA256 hash of an existing key**? Something like this: `SHA256:3VvabBNtRF0XEpYRFnIrhHX6tKZq/vzU+heb3dCYp+0 [email protected]` * **MD5 (is it MD5?) of an existing key**? Something like this: `b6:bf:18:b8:72:83:b7:fb:7d:08:98:72:1f:9f:05:27` * **Randomart for an existing key**? Something like this: ```none +--[ RSA 2048]----+ | o=. | | o o++E | | + . Ooo. | | + O B.. | | = *S. | | o | | | | | | | +-----------------+ ```
2018/11/20
[ "https://superuser.com/questions/1377132", "https://superuser.com", "https://superuser.com/users/212610/" ]
Install **openssh** and **openssl** packages which contain the commands. ``` # get the SHA256 and ascii art ssh-keygen -l -v -f /path/to/publickey # get the MD5 for private key openssl pkey -in /path/to/privatekey -pubout -outform DER | openssl md5 -c # get the MD5 for public key openssl pkey -in /path/to/publickey -pubin -pubout -outform DER | openssl md5 -c ```
The above works if you have access to the remote host. If not, to get the default sha256 hashes and Art from the remote host 'pi' (for example) you can do this: ``` $ ssh-keyscan pi | ssh-keygen -lvf - # pi:22 SSH-2.0-OpenSSH_7.4p1 Raspbian-10+deb9u4 # pi:22 SSH-2.0-OpenSSH_7.4p1 Raspbian-10+deb9u4 # pi:22 SSH-2.0-OpenSSH_7.4p1 Raspbian-10+deb9u4 2048 SHA256:P/Da4p1YbLDgnbGIkVE9SykONlVynPkwwap54RMW6+A pi (RSA) +---[RSA 2048]----+ | .+=+= | | +.oo% | | ..+ * * | | .oB . . | | .oB.oS | | E+=+ @ | | ..o.= B | | .B o | | .+.+ | +----[SHA256]-----+ 256 SHA256:eMaAlpPMA2/24ajrpHuiL7mCFCJycZNfuNfyB3cyx+U pi (ECDSA) +---[ECDSA 256]---+ | . . . | | .=++. . .| | o&ooo . . o | |+..+ *o=o o + + E| |+.. . +.So o = | | . . o . . | |o.o . | |*o.. | |BO+ | +----[SHA256]-----+ 256 SHA256:cpQtotFCbt4TXxa1474whR1Wkk3gOczhumE23s9pbxc pi (ED25519) +--[ED25519 256]--+ | . ..==o | | o . o *.*. | | = + + + % | | o = = + * + | | o + S B + | | + + B E | | = o .| | o +..o| | ..+oo| +----[SHA256]-----+ $ _ ``` If instead you'd like the md5 hash: ``` $ ssh-keyscan pi | ssh-keygen -E md5 -lf - # pi:22 SSH-2.0-OpenSSH_7.4p1 Raspbian-10+deb9u4 # pi:22 SSH-2.0-OpenSSH_7.4p1 Raspbian-10+deb9u4 # pi:22 SSH-2.0-OpenSSH_7.4p1 Raspbian-10+deb9u4 256 MD5:b3:74:1f:a7:e8:96:ee:e0:5d:7e:31:4d:5c:7c:5c:d2 pi (ECDSA) 2048 MD5:cb:1f:5b:85:fb:6f:c9:89:06:68:ce:96:88:f6:11:ed pi (RSA) 256 MD5:d7:93:a1:8e:53:06:4d:fe:41:5c:fa:4b:70:84:c3:88 pi (ED25519) $ _ ``` If you are on the actual host and want to get them, then you just sudo the part after the pipe like this: ``` $ sudo ssh-keygen -E sha256 -lf /etc/ssh/ssh_host_ecdsa_key 256 SHA256:eMaAlpPMA2/24ajrpHuiL7mCFCJycZNfuNfyB3cyx+U root@raspberrypi (ECDSA) $ _ ``` And sha256 is the default, so you'd use 'md5' to get that. Hope that helps. Patrick
1,377,132
[This Question](https://superuser.com/q/1088165/212610) asks about getting the [fingerprint of a SSH key](https://en.wikipedia.org/wiki/Public_key_fingerprint) while generating the new key with `ssh-keygen`. But how does one get determine the fingerprint of an *existing* public key in a `.pub` file? ➥ How to get: * **SHA256 hash of an existing key**? Something like this: `SHA256:3VvabBNtRF0XEpYRFnIrhHX6tKZq/vzU+heb3dCYp+0 [email protected]` * **MD5 (is it MD5?) of an existing key**? Something like this: `b6:bf:18:b8:72:83:b7:fb:7d:08:98:72:1f:9f:05:27` * **Randomart for an existing key**? Something like this: ```none +--[ RSA 2048]----+ | o=. | | o o++E | | + . Ooo. | | + O B.. | | = *S. | | o | | | | | | | +-----------------+ ```
2018/11/20
[ "https://superuser.com/questions/1377132", "https://superuser.com", "https://superuser.com/users/212610/" ]
In recent versions of ssh-keygen, one gets an RSA public key fingerprint on Unix-based systems with something like: `$ ssh-keygen -l -E md5 -f ~/.ssh/id_rsa.pub` where the path refers to a public key file.
Install **openssh** and **openssl** packages which contain the commands. ``` # get the SHA256 and ascii art ssh-keygen -l -v -f /path/to/publickey # get the MD5 for private key openssl pkey -in /path/to/privatekey -pubout -outform DER | openssl md5 -c # get the MD5 for public key openssl pkey -in /path/to/publickey -pubin -pubout -outform DER | openssl md5 -c ```
1,377,132
[This Question](https://superuser.com/q/1088165/212610) asks about getting the [fingerprint of a SSH key](https://en.wikipedia.org/wiki/Public_key_fingerprint) while generating the new key with `ssh-keygen`. But how does one get determine the fingerprint of an *existing* public key in a `.pub` file? ➥ How to get: * **SHA256 hash of an existing key**? Something like this: `SHA256:3VvabBNtRF0XEpYRFnIrhHX6tKZq/vzU+heb3dCYp+0 [email protected]` * **MD5 (is it MD5?) of an existing key**? Something like this: `b6:bf:18:b8:72:83:b7:fb:7d:08:98:72:1f:9f:05:27` * **Randomart for an existing key**? Something like this: ```none +--[ RSA 2048]----+ | o=. | | o o++E | | + . Ooo. | | + O B.. | | = *S. | | o | | | | | | | +-----------------+ ```
2018/11/20
[ "https://superuser.com/questions/1377132", "https://superuser.com", "https://superuser.com/users/212610/" ]
Install **openssh** and **openssl** packages which contain the commands. ``` # get the SHA256 and ascii art ssh-keygen -l -v -f /path/to/publickey # get the MD5 for private key openssl pkey -in /path/to/privatekey -pubout -outform DER | openssl md5 -c # get the MD5 for public key openssl pkey -in /path/to/publickey -pubin -pubout -outform DER | openssl md5 -c ```
If you need just the fingerprint without anything else for something like adding your key to digital ocean via doctl and a new server you can do this. ``` FINGERPRINT="$(ssh-keygen -l -E md5 -f ~/.ssh/${DROPLET_NAME}.pub | awk '{print $2}'| sed 's|MD5:||')" ``` ``` DROPLET_TAG="machineid-${tagname}" DROPLET_NAME="${tagname/_/-}" ssh-keygen -t ed25519 -f ~/.ssh/${DROPLET_NAME} -P "" -C "${DROPLET_NAME}" export SSH_PUB="$(cat ~/.ssh/${DROPLET_NAME}.pub)" export SSH_PRIVATE="$(cat ~/.ssh/${DROPLET_NAME})" FINGERPRINT="$(ssh-keygen -l -E md5 -f ~/.ssh/${DROPLET_NAME}.pub | awk '{print $2}'| sed 's|MD5:||')" doctl compute ssh-key create ${DROPLET_NAME} --public-key "$(cat ~/.ssh/${DROPLET_NAME}.pub)" ```
1,377,132
[This Question](https://superuser.com/q/1088165/212610) asks about getting the [fingerprint of a SSH key](https://en.wikipedia.org/wiki/Public_key_fingerprint) while generating the new key with `ssh-keygen`. But how does one get determine the fingerprint of an *existing* public key in a `.pub` file? ➥ How to get: * **SHA256 hash of an existing key**? Something like this: `SHA256:3VvabBNtRF0XEpYRFnIrhHX6tKZq/vzU+heb3dCYp+0 [email protected]` * **MD5 (is it MD5?) of an existing key**? Something like this: `b6:bf:18:b8:72:83:b7:fb:7d:08:98:72:1f:9f:05:27` * **Randomart for an existing key**? Something like this: ```none +--[ RSA 2048]----+ | o=. | | o o++E | | + . Ooo. | | + O B.. | | = *S. | | o | | | | | | | +-----------------+ ```
2018/11/20
[ "https://superuser.com/questions/1377132", "https://superuser.com", "https://superuser.com/users/212610/" ]
In recent versions of ssh-keygen, one gets an RSA public key fingerprint on Unix-based systems with something like: `$ ssh-keygen -l -E md5 -f ~/.ssh/id_rsa.pub` where the path refers to a public key file.
The above works if you have access to the remote host. If not, to get the default sha256 hashes and Art from the remote host 'pi' (for example) you can do this: ``` $ ssh-keyscan pi | ssh-keygen -lvf - # pi:22 SSH-2.0-OpenSSH_7.4p1 Raspbian-10+deb9u4 # pi:22 SSH-2.0-OpenSSH_7.4p1 Raspbian-10+deb9u4 # pi:22 SSH-2.0-OpenSSH_7.4p1 Raspbian-10+deb9u4 2048 SHA256:P/Da4p1YbLDgnbGIkVE9SykONlVynPkwwap54RMW6+A pi (RSA) +---[RSA 2048]----+ | .+=+= | | +.oo% | | ..+ * * | | .oB . . | | .oB.oS | | E+=+ @ | | ..o.= B | | .B o | | .+.+ | +----[SHA256]-----+ 256 SHA256:eMaAlpPMA2/24ajrpHuiL7mCFCJycZNfuNfyB3cyx+U pi (ECDSA) +---[ECDSA 256]---+ | . . . | | .=++. . .| | o&ooo . . o | |+..+ *o=o o + + E| |+.. . +.So o = | | . . o . . | |o.o . | |*o.. | |BO+ | +----[SHA256]-----+ 256 SHA256:cpQtotFCbt4TXxa1474whR1Wkk3gOczhumE23s9pbxc pi (ED25519) +--[ED25519 256]--+ | . ..==o | | o . o *.*. | | = + + + % | | o = = + * + | | o + S B + | | + + B E | | = o .| | o +..o| | ..+oo| +----[SHA256]-----+ $ _ ``` If instead you'd like the md5 hash: ``` $ ssh-keyscan pi | ssh-keygen -E md5 -lf - # pi:22 SSH-2.0-OpenSSH_7.4p1 Raspbian-10+deb9u4 # pi:22 SSH-2.0-OpenSSH_7.4p1 Raspbian-10+deb9u4 # pi:22 SSH-2.0-OpenSSH_7.4p1 Raspbian-10+deb9u4 256 MD5:b3:74:1f:a7:e8:96:ee:e0:5d:7e:31:4d:5c:7c:5c:d2 pi (ECDSA) 2048 MD5:cb:1f:5b:85:fb:6f:c9:89:06:68:ce:96:88:f6:11:ed pi (RSA) 256 MD5:d7:93:a1:8e:53:06:4d:fe:41:5c:fa:4b:70:84:c3:88 pi (ED25519) $ _ ``` If you are on the actual host and want to get them, then you just sudo the part after the pipe like this: ``` $ sudo ssh-keygen -E sha256 -lf /etc/ssh/ssh_host_ecdsa_key 256 SHA256:eMaAlpPMA2/24ajrpHuiL7mCFCJycZNfuNfyB3cyx+U root@raspberrypi (ECDSA) $ _ ``` And sha256 is the default, so you'd use 'md5' to get that. Hope that helps. Patrick
1,377,132
[This Question](https://superuser.com/q/1088165/212610) asks about getting the [fingerprint of a SSH key](https://en.wikipedia.org/wiki/Public_key_fingerprint) while generating the new key with `ssh-keygen`. But how does one get determine the fingerprint of an *existing* public key in a `.pub` file? ➥ How to get: * **SHA256 hash of an existing key**? Something like this: `SHA256:3VvabBNtRF0XEpYRFnIrhHX6tKZq/vzU+heb3dCYp+0 [email protected]` * **MD5 (is it MD5?) of an existing key**? Something like this: `b6:bf:18:b8:72:83:b7:fb:7d:08:98:72:1f:9f:05:27` * **Randomart for an existing key**? Something like this: ```none +--[ RSA 2048]----+ | o=. | | o o++E | | + . Ooo. | | + O B.. | | = *S. | | o | | | | | | | +-----------------+ ```
2018/11/20
[ "https://superuser.com/questions/1377132", "https://superuser.com", "https://superuser.com/users/212610/" ]
The above works if you have access to the remote host. If not, to get the default sha256 hashes and Art from the remote host 'pi' (for example) you can do this: ``` $ ssh-keyscan pi | ssh-keygen -lvf - # pi:22 SSH-2.0-OpenSSH_7.4p1 Raspbian-10+deb9u4 # pi:22 SSH-2.0-OpenSSH_7.4p1 Raspbian-10+deb9u4 # pi:22 SSH-2.0-OpenSSH_7.4p1 Raspbian-10+deb9u4 2048 SHA256:P/Da4p1YbLDgnbGIkVE9SykONlVynPkwwap54RMW6+A pi (RSA) +---[RSA 2048]----+ | .+=+= | | +.oo% | | ..+ * * | | .oB . . | | .oB.oS | | E+=+ @ | | ..o.= B | | .B o | | .+.+ | +----[SHA256]-----+ 256 SHA256:eMaAlpPMA2/24ajrpHuiL7mCFCJycZNfuNfyB3cyx+U pi (ECDSA) +---[ECDSA 256]---+ | . . . | | .=++. . .| | o&ooo . . o | |+..+ *o=o o + + E| |+.. . +.So o = | | . . o . . | |o.o . | |*o.. | |BO+ | +----[SHA256]-----+ 256 SHA256:cpQtotFCbt4TXxa1474whR1Wkk3gOczhumE23s9pbxc pi (ED25519) +--[ED25519 256]--+ | . ..==o | | o . o *.*. | | = + + + % | | o = = + * + | | o + S B + | | + + B E | | = o .| | o +..o| | ..+oo| +----[SHA256]-----+ $ _ ``` If instead you'd like the md5 hash: ``` $ ssh-keyscan pi | ssh-keygen -E md5 -lf - # pi:22 SSH-2.0-OpenSSH_7.4p1 Raspbian-10+deb9u4 # pi:22 SSH-2.0-OpenSSH_7.4p1 Raspbian-10+deb9u4 # pi:22 SSH-2.0-OpenSSH_7.4p1 Raspbian-10+deb9u4 256 MD5:b3:74:1f:a7:e8:96:ee:e0:5d:7e:31:4d:5c:7c:5c:d2 pi (ECDSA) 2048 MD5:cb:1f:5b:85:fb:6f:c9:89:06:68:ce:96:88:f6:11:ed pi (RSA) 256 MD5:d7:93:a1:8e:53:06:4d:fe:41:5c:fa:4b:70:84:c3:88 pi (ED25519) $ _ ``` If you are on the actual host and want to get them, then you just sudo the part after the pipe like this: ``` $ sudo ssh-keygen -E sha256 -lf /etc/ssh/ssh_host_ecdsa_key 256 SHA256:eMaAlpPMA2/24ajrpHuiL7mCFCJycZNfuNfyB3cyx+U root@raspberrypi (ECDSA) $ _ ``` And sha256 is the default, so you'd use 'md5' to get that. Hope that helps. Patrick
If you need just the fingerprint without anything else for something like adding your key to digital ocean via doctl and a new server you can do this. ``` FINGERPRINT="$(ssh-keygen -l -E md5 -f ~/.ssh/${DROPLET_NAME}.pub | awk '{print $2}'| sed 's|MD5:||')" ``` ``` DROPLET_TAG="machineid-${tagname}" DROPLET_NAME="${tagname/_/-}" ssh-keygen -t ed25519 -f ~/.ssh/${DROPLET_NAME} -P "" -C "${DROPLET_NAME}" export SSH_PUB="$(cat ~/.ssh/${DROPLET_NAME}.pub)" export SSH_PRIVATE="$(cat ~/.ssh/${DROPLET_NAME})" FINGERPRINT="$(ssh-keygen -l -E md5 -f ~/.ssh/${DROPLET_NAME}.pub | awk '{print $2}'| sed 's|MD5:||')" doctl compute ssh-key create ${DROPLET_NAME} --public-key "$(cat ~/.ssh/${DROPLET_NAME}.pub)" ```
1,377,132
[This Question](https://superuser.com/q/1088165/212610) asks about getting the [fingerprint of a SSH key](https://en.wikipedia.org/wiki/Public_key_fingerprint) while generating the new key with `ssh-keygen`. But how does one get determine the fingerprint of an *existing* public key in a `.pub` file? ➥ How to get: * **SHA256 hash of an existing key**? Something like this: `SHA256:3VvabBNtRF0XEpYRFnIrhHX6tKZq/vzU+heb3dCYp+0 [email protected]` * **MD5 (is it MD5?) of an existing key**? Something like this: `b6:bf:18:b8:72:83:b7:fb:7d:08:98:72:1f:9f:05:27` * **Randomart for an existing key**? Something like this: ```none +--[ RSA 2048]----+ | o=. | | o o++E | | + . Ooo. | | + O B.. | | = *S. | | o | | | | | | | +-----------------+ ```
2018/11/20
[ "https://superuser.com/questions/1377132", "https://superuser.com", "https://superuser.com/users/212610/" ]
In recent versions of ssh-keygen, one gets an RSA public key fingerprint on Unix-based systems with something like: `$ ssh-keygen -l -E md5 -f ~/.ssh/id_rsa.pub` where the path refers to a public key file.
If you need just the fingerprint without anything else for something like adding your key to digital ocean via doctl and a new server you can do this. ``` FINGERPRINT="$(ssh-keygen -l -E md5 -f ~/.ssh/${DROPLET_NAME}.pub | awk '{print $2}'| sed 's|MD5:||')" ``` ``` DROPLET_TAG="machineid-${tagname}" DROPLET_NAME="${tagname/_/-}" ssh-keygen -t ed25519 -f ~/.ssh/${DROPLET_NAME} -P "" -C "${DROPLET_NAME}" export SSH_PUB="$(cat ~/.ssh/${DROPLET_NAME}.pub)" export SSH_PRIVATE="$(cat ~/.ssh/${DROPLET_NAME})" FINGERPRINT="$(ssh-keygen -l -E md5 -f ~/.ssh/${DROPLET_NAME}.pub | awk '{print $2}'| sed 's|MD5:||')" doctl compute ssh-key create ${DROPLET_NAME} --public-key "$(cat ~/.ssh/${DROPLET_NAME}.pub)" ```
3,124
Quando se diz algo como "itens filtrados", o que foi retido (o que interessa, o objetivo) é o que teria passado através do filtro ou o que seria bloqueado (não passou)? Isso também acontece com outras palavas parecidas, como "peneirado" e "coado". Procurei nos dicionários, mas não deixam claro se é o que fica ou o que passa, parece ser apenas algo que "sofreu" uma filtragem, mas sem especificar. Porém não tenho certeza.
2016/04/24
[ "https://portuguese.stackexchange.com/questions/3124", "https://portuguese.stackexchange.com", "https://portuguese.stackexchange.com/users/47/" ]
*Filtrar* tem estes dois significados (entre outros, [Aulete](http://www.aulete.com.br/filtrar)): > > **1.** Fazer passar ou passar por um filtro [td. : *Filtrar a água*] [int. : *A água ainda não filtrou.*] > > **2.** Impedir que passe inteira ou parcialmente [td. : *Filtrar raios solares*] > > > Portanto se qualquer foi filtrada, podemos tanto: 1. estar a falar de uma massa que passa por um filtro, referindo a massa antes de esta passar pelo filtro (*esta água **vai ser filtrada***), ou depois de passar (*esta água **foi filtrada***), 2. como podemos estar a falar de uma massa que foi bloqueada pelo filtro (*as impurezas da água **foram filtradas***). Exemplo do [corpus TODOS da Linguateca](http://www.linguateca.pt/acesso/corpus.php?corpus=TODOS): *São micro-organismos **filtrados** na [es]tação de tratamento, mas que libertam produtos «aromáticos voláteis» que dão «o cheiro e sabor à água».* Falar de *itens filtrados* parece-me de facto ambíguo, porque aí só o contexto poderá esclarecer se devemos entender *itens* como: 1) os itens vistos como um todo (a coleção), 2) os itens que passaram o filtro e 3) os itens que não passaram o filtro. Por este mesmo motivo, não gosto de que, em programação, funções de filtragem de coleções de ordem superior sejam chamadas de *filter* (o que significa devolver o valor de verdade na função passada?). *Mathematica* chama-lhe [`Select`](https://reference.wolfram.com/language/ref/Select.html), o que na minha opinião é menos ambíguo.
Penso que em língua portuguesa corrente não existem palavras específicas derivadas de filtro (ou de peneira ou coar) para referir todos os diversos elementos participantes no processo,tanto quanto sei. Quando de diz filtrado penso que geralmente diz respeito a algo que participou no processo sem especificar que tipo de interveniente. * Filtragem: processo de filtrar * Filtrante/Filtro: aquele que filtra, ou retém * Filtrado: Retenção, o que ficou retido no filtro, o que foi retirado. * Filtrado: Elemento a ser submetido a filtragem * Filtrado: Elemento que foi submetido a filtragem * Filtrado: Elementos resultantes da filtragem, o que passou no filtro Pode igualmente referir se ao objectivo, o que se pretende obter, ou aos indesejáveis, o que se pretende descartar.
1,615,998
What object/method would I call to get current time in milliseconds (or great precision) to help measure how long a method took to execute? NSDate's timeIntervalSinceDate will return NSInterval which is measured in seconds. I am looking for something finer grained, something similar to Java's System.currentTimeMillis. Is there an equivalent version in objective-c/CocoaTouch?
2009/10/23
[ "https://Stackoverflow.com/questions/1615998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/119382/" ]
`timeIntervalSinceReferenceDate` is perfectly fine. However, unless it's a long-running method, this won't bear much fruit. Execution times can vary wildly when you're talking about a few millisecond executions. If your thread/process gets preempted mid-way through, you'll have non-deterministic spikes. Essentially, your sample size is too small. Either use a profiler or run 100,000 iterations to get total time and divide by 100,000 to get average run-time.
If you're trying to tune your code's performance, you would do better to use Instruments or Shark to get an overall picture of where your app is spending its time.
1,615,998
What object/method would I call to get current time in milliseconds (or great precision) to help measure how long a method took to execute? NSDate's timeIntervalSinceDate will return NSInterval which is measured in seconds. I am looking for something finer grained, something similar to Java's System.currentTimeMillis. Is there an equivalent version in objective-c/CocoaTouch?
2009/10/23
[ "https://Stackoverflow.com/questions/1615998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/119382/" ]
*Do not use `NSDate` for this.* You're loosing a lot of precision to call methods and instantiate objects, maybe even releasing something internal. You just don't have enough control. Use either `time.h` or as [Stephen Canon](https://stackoverflow.com/questions/1615998/rudimentary-ways-to-measure-execution-time-of-a-method/1616376#1616376) suggested `mach/mach_time.h`. They are both much more accurate. The best way to do this is to fire up Instruments or Shark, attach them to your process (works even if it's already running) and let them measure the time a method takes. After you're familiar with it this takes even less time than any put-in-mach-time-functions-and-recompile-the-whole-application solution. You even get a lot of information extra. I wouldn't settle for anything less.
I will repost my answer from another post here. Note that my admittedly simple solution to this complex problem uses NSDate and NSTimeInterval as its foundation: --- I know this is an old one but even I found myself wandering past it again, so I thought I'd submit my own option here. Best bet is to check out my blog post on this: [Timing things in Objective-C: A stopwatch](http://metal-sole.com/2012/01/24/timing-things-in-objective-c-a-stopwatch/) Basically, I wrote a class that does stop watching in a very basic way but is encapsulated so that you only need to do the following: ``` [MMStopwatchARC start:@"My Timer"]; // your work here ... [MMStopwatchARC stop:@"My Timer"]; ``` And you end up with: ``` MyApp[4090:15203] -> Stopwatch: [My Timer] runtime: [0.029] ``` in the log... Again, check out my post for a little more or download it here: [MMStopwatch.zip](http://metal-sole.com/wp-content/uploads/2012/01/MMStopwatch.zip)
1,615,998
What object/method would I call to get current time in milliseconds (or great precision) to help measure how long a method took to execute? NSDate's timeIntervalSinceDate will return NSInterval which is measured in seconds. I am looking for something finer grained, something similar to Java's System.currentTimeMillis. Is there an equivalent version in objective-c/CocoaTouch?
2009/10/23
[ "https://Stackoverflow.com/questions/1615998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/119382/" ]
Actually, `+[NSDate timeIntervalSinceReferenceDate]` returns an `NSTimeInterval`, which is a typedef for a double. The docs say > > NSTimeInterval is always specified in seconds; it yields sub-millisecond precision over a range of 10,000 years. > > > So it's safe to use for millisecond-precision timing. I do so all the time.
`timeIntervalSinceReferenceDate` is perfectly fine. However, unless it's a long-running method, this won't bear much fruit. Execution times can vary wildly when you're talking about a few millisecond executions. If your thread/process gets preempted mid-way through, you'll have non-deterministic spikes. Essentially, your sample size is too small. Either use a profiler or run 100,000 iterations to get total time and divide by 100,000 to get average run-time.