qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
26,219
It seems that about 2 weeks ago, Gmail began *always* opening a new tab (in Chrome at least) *every* time I switch Accounts. Previously it only opened new tabs when I logged into a new account, but if I closed down to 1 tab, and switched between accounts, I could stay in the same tab. Does anyone know of a setting in Gmail to keep the same tab when switching accounts? NOTE: I know about opening links in new windows and tabs, and this *not* what I am asking - this question is *specific* only to switching accounts in Gmail.
2012/04/27
[ "https://webapps.stackexchange.com/questions/26219", "https://webapps.stackexchange.com", "https://webapps.stackexchange.com/users/662/" ]
I don't know if this is what you need, but you can drag the "Add Account" Button to your address bar, works for me on Firefox.
I got it, I just solved the issue. You have to switch with the profile icon on the webpage itself instead of the button on the browser task bar (the icon next to the 3 dots icon).
36,781,384
In SQL Server I am joining 2 tables and need a way to get the maximum or greatest (version Number) value for each (Record ID) that exists in the table including it's row data selected. My query is returning the data as follows but returns ALL record id's and versions, I need this to return only the max version number value and all row data: ``` SELECT DISTINCT MAX(a.VERSION_NUM), MAX(a.RECORD_ID), b.PERSON, b.STATUS, CAST(a.SUMMARY_DATA AS NVARCHAR(4000)) FROM TABLE1 a, TABLE2 b WHERE a.RECORD_ID = b.RECORD_ID AND a.RECORD_ID not NULL AND a.SUMMARY_DATA is not NULL GROUP BY a.VERSION_NUM, a.RECORD_ID, b.PERSON, b.STATUS, CAST(a.SUMMARY_DATA AS NVARCHAR(4000)) ORDER BY MAX(a.VERSION_NUM), MAX(a.RECORD_ID) DESC ``` This query returns duplicate Record ID's with its version number and row data: ``` VersionNum Record ID Person Status Summary Data 5 000000000000418 John Open "specific Summary data ... 4 000000000000418 Jane Closed "specific Summary data ..." 3 000000000000418 Sam Closed: "specific Summary data ..." 4 000000000000229 Joe Pending "specific Summary data ..." 3 000000000000229 Betty Closed "specific Summary data ..." 2 000000000000229 David Closed "specific Summary data ..." 7 000000000000318 Karen Closed "specific Summary data ..." 6 000000000000318 Sam Pending "specific Summary data ..." 5 000000000000318 Betty Closed "specific Summary data ..." 4 000000000000318 David Closed "specific Summary data ..." ``` I instead need this to return only the max (version number value) with it's adjacent (ID) and remainder of all it's selected row data : i.e. ``` VersionNUM Record ID Person Status Summary Data 5 000000000000418 John Open "specific Summary data ..." 4 000000000000229 Joe Pending "specific Summary data ..." 7 000000000000318 Karen Closed "specific Summary data ..." ``` Any help is greatly appreciated! I applied and tried this but got an error - need help on the correct syntax to return these fields ``` SELECT * FROM (SELECT dt.VERSION, dt.Job_Doc_Set_Request_ID, dt.SUBMITTER,st.STATUS, dt.SUMMARY, ROW_NUMBER() OVER (PARTITION BY dt.Job_Doc_Set_Request_ID ORDER BY dt.VERSION DESC) rn FROM RICPM_JD_JobDocDetails dt, RICPM_JD_JobDocSet st) q WHERE rn = 1 AND dt.Job_DOC_Set_Request_ID NOT LIKE '%DELETED' AND st.STATUS = 2 AND dt.SUMMARY NOT LIKE 'Obsolete%' AND dt.Job_Doc_Set_Request_ID = st.REQUEST_ID ``` Error: > > java.sql.SQLException: The multi-part identifier "dt.Job\_DOC\_Set\_Request\_ID" could not be bound. > > at net.sourceforge.jtds.jdbc.SQLDiagnostic.addDiagnostic(SQLDiagnostic.java:372) > at net.sourceforge.jtds.jdbc.TdsCore.tdsErrorToken(TdsCore.java:2988) > > >
2016/04/21
[ "https://Stackoverflow.com/questions/36781384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5561275/" ]
Dockerfiles are for creating images. I see gosu as more useful as part of a container initialization when you can no longer change users between run commands in your Dockerfile. After the image is created, something like gosu allows you to drop root permissions at the end of your entrypoint inside of a container. You may initially need root access to do some initialization steps (fixing uid's, host mounted volume permissions, etc). Then once initialized, you run the final service without root privileges and as pid 1 to handle signals cleanly. --- Edit: Here's a simple example of using gosu in an image for docker and jenkins: <https://github.com/bmitch3020/jenkins-docker> The entrypoint.sh looks up the gid of the /var/lib/docker.sock file and updates the gid of the docker user inside the container to match. This allows the image to be ported to other docker hosts where the gid on the host may differ. Changing the group requires root access inside the container. Had I used `USER jenkins` in the dockerfile, I would be stuck with the gid of the docker group as defined in the image which wouldn't work if it doesn't match that of the docker host it's running on. But root access can be dropped when running the app which is where gosu comes in. At the end of the script, the exec call prevents the shell from forking gosu, and instead it replaces pid 1 with that process. Gosu in turn does the same, switching the uid and then exec'ing the jenkins process so that it takes over as pid 1. This allows signals to be handled correctly which would otherwise be ignored by a shell as pid 1.
I am using gosu and entrypoint.sh because I want the user in the container to have the same UID as the user that created the container. [Docker Volumes and Permissions.](https://denibertovic.com/posts/handling-permissions-with-docker-volumes/) The purpose of the container I am creating is for development. I need to build for linux but I still want all the connivence of local (OS X) editing, tools, etc. My keeping the UIDs the same inside and outside the container it keeps the file ownership a lot more sane and prevents some errors (container user cannot edit files in mounted volume, etc)
36,781,384
In SQL Server I am joining 2 tables and need a way to get the maximum or greatest (version Number) value for each (Record ID) that exists in the table including it's row data selected. My query is returning the data as follows but returns ALL record id's and versions, I need this to return only the max version number value and all row data: ``` SELECT DISTINCT MAX(a.VERSION_NUM), MAX(a.RECORD_ID), b.PERSON, b.STATUS, CAST(a.SUMMARY_DATA AS NVARCHAR(4000)) FROM TABLE1 a, TABLE2 b WHERE a.RECORD_ID = b.RECORD_ID AND a.RECORD_ID not NULL AND a.SUMMARY_DATA is not NULL GROUP BY a.VERSION_NUM, a.RECORD_ID, b.PERSON, b.STATUS, CAST(a.SUMMARY_DATA AS NVARCHAR(4000)) ORDER BY MAX(a.VERSION_NUM), MAX(a.RECORD_ID) DESC ``` This query returns duplicate Record ID's with its version number and row data: ``` VersionNum Record ID Person Status Summary Data 5 000000000000418 John Open "specific Summary data ... 4 000000000000418 Jane Closed "specific Summary data ..." 3 000000000000418 Sam Closed: "specific Summary data ..." 4 000000000000229 Joe Pending "specific Summary data ..." 3 000000000000229 Betty Closed "specific Summary data ..." 2 000000000000229 David Closed "specific Summary data ..." 7 000000000000318 Karen Closed "specific Summary data ..." 6 000000000000318 Sam Pending "specific Summary data ..." 5 000000000000318 Betty Closed "specific Summary data ..." 4 000000000000318 David Closed "specific Summary data ..." ``` I instead need this to return only the max (version number value) with it's adjacent (ID) and remainder of all it's selected row data : i.e. ``` VersionNUM Record ID Person Status Summary Data 5 000000000000418 John Open "specific Summary data ..." 4 000000000000229 Joe Pending "specific Summary data ..." 7 000000000000318 Karen Closed "specific Summary data ..." ``` Any help is greatly appreciated! I applied and tried this but got an error - need help on the correct syntax to return these fields ``` SELECT * FROM (SELECT dt.VERSION, dt.Job_Doc_Set_Request_ID, dt.SUBMITTER,st.STATUS, dt.SUMMARY, ROW_NUMBER() OVER (PARTITION BY dt.Job_Doc_Set_Request_ID ORDER BY dt.VERSION DESC) rn FROM RICPM_JD_JobDocDetails dt, RICPM_JD_JobDocSet st) q WHERE rn = 1 AND dt.Job_DOC_Set_Request_ID NOT LIKE '%DELETED' AND st.STATUS = 2 AND dt.SUMMARY NOT LIKE 'Obsolete%' AND dt.Job_Doc_Set_Request_ID = st.REQUEST_ID ``` Error: > > java.sql.SQLException: The multi-part identifier "dt.Job\_DOC\_Set\_Request\_ID" could not be bound. > > at net.sourceforge.jtds.jdbc.SQLDiagnostic.addDiagnostic(SQLDiagnostic.java:372) > at net.sourceforge.jtds.jdbc.TdsCore.tdsErrorToken(TdsCore.java:2988) > > >
2016/04/21
[ "https://Stackoverflow.com/questions/36781384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5561275/" ]
I am using gosu and entrypoint.sh because I want the user in the container to have the same UID as the user that created the container. [Docker Volumes and Permissions.](https://denibertovic.com/posts/handling-permissions-with-docker-volumes/) The purpose of the container I am creating is for development. I need to build for linux but I still want all the connivence of local (OS X) editing, tools, etc. My keeping the UIDs the same inside and outside the container it keeps the file ownership a lot more sane and prevents some errors (container user cannot edit files in mounted volume, etc)
Advantage of using `gosu` is also signal handling. You may `trap` for instance `SIGHUP` for reloading the process as you would normally achieve via `systemctl reload <process>` or such.
36,781,384
In SQL Server I am joining 2 tables and need a way to get the maximum or greatest (version Number) value for each (Record ID) that exists in the table including it's row data selected. My query is returning the data as follows but returns ALL record id's and versions, I need this to return only the max version number value and all row data: ``` SELECT DISTINCT MAX(a.VERSION_NUM), MAX(a.RECORD_ID), b.PERSON, b.STATUS, CAST(a.SUMMARY_DATA AS NVARCHAR(4000)) FROM TABLE1 a, TABLE2 b WHERE a.RECORD_ID = b.RECORD_ID AND a.RECORD_ID not NULL AND a.SUMMARY_DATA is not NULL GROUP BY a.VERSION_NUM, a.RECORD_ID, b.PERSON, b.STATUS, CAST(a.SUMMARY_DATA AS NVARCHAR(4000)) ORDER BY MAX(a.VERSION_NUM), MAX(a.RECORD_ID) DESC ``` This query returns duplicate Record ID's with its version number and row data: ``` VersionNum Record ID Person Status Summary Data 5 000000000000418 John Open "specific Summary data ... 4 000000000000418 Jane Closed "specific Summary data ..." 3 000000000000418 Sam Closed: "specific Summary data ..." 4 000000000000229 Joe Pending "specific Summary data ..." 3 000000000000229 Betty Closed "specific Summary data ..." 2 000000000000229 David Closed "specific Summary data ..." 7 000000000000318 Karen Closed "specific Summary data ..." 6 000000000000318 Sam Pending "specific Summary data ..." 5 000000000000318 Betty Closed "specific Summary data ..." 4 000000000000318 David Closed "specific Summary data ..." ``` I instead need this to return only the max (version number value) with it's adjacent (ID) and remainder of all it's selected row data : i.e. ``` VersionNUM Record ID Person Status Summary Data 5 000000000000418 John Open "specific Summary data ..." 4 000000000000229 Joe Pending "specific Summary data ..." 7 000000000000318 Karen Closed "specific Summary data ..." ``` Any help is greatly appreciated! I applied and tried this but got an error - need help on the correct syntax to return these fields ``` SELECT * FROM (SELECT dt.VERSION, dt.Job_Doc_Set_Request_ID, dt.SUBMITTER,st.STATUS, dt.SUMMARY, ROW_NUMBER() OVER (PARTITION BY dt.Job_Doc_Set_Request_ID ORDER BY dt.VERSION DESC) rn FROM RICPM_JD_JobDocDetails dt, RICPM_JD_JobDocSet st) q WHERE rn = 1 AND dt.Job_DOC_Set_Request_ID NOT LIKE '%DELETED' AND st.STATUS = 2 AND dt.SUMMARY NOT LIKE 'Obsolete%' AND dt.Job_Doc_Set_Request_ID = st.REQUEST_ID ``` Error: > > java.sql.SQLException: The multi-part identifier "dt.Job\_DOC\_Set\_Request\_ID" could not be bound. > > at net.sourceforge.jtds.jdbc.SQLDiagnostic.addDiagnostic(SQLDiagnostic.java:372) > at net.sourceforge.jtds.jdbc.TdsCore.tdsErrorToken(TdsCore.java:2988) > > >
2016/04/21
[ "https://Stackoverflow.com/questions/36781384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5561275/" ]
Dockerfiles are for creating images. I see gosu as more useful as part of a container initialization when you can no longer change users between run commands in your Dockerfile. After the image is created, something like gosu allows you to drop root permissions at the end of your entrypoint inside of a container. You may initially need root access to do some initialization steps (fixing uid's, host mounted volume permissions, etc). Then once initialized, you run the final service without root privileges and as pid 1 to handle signals cleanly. --- Edit: Here's a simple example of using gosu in an image for docker and jenkins: <https://github.com/bmitch3020/jenkins-docker> The entrypoint.sh looks up the gid of the /var/lib/docker.sock file and updates the gid of the docker user inside the container to match. This allows the image to be ported to other docker hosts where the gid on the host may differ. Changing the group requires root access inside the container. Had I used `USER jenkins` in the dockerfile, I would be stuck with the gid of the docker group as defined in the image which wouldn't work if it doesn't match that of the docker host it's running on. But root access can be dropped when running the app which is where gosu comes in. At the end of the script, the exec call prevents the shell from forking gosu, and instead it replaces pid 1 with that process. Gosu in turn does the same, switching the uid and then exec'ing the jenkins process so that it takes over as pid 1. This allows signals to be handled correctly which would otherwise be ignored by a shell as pid 1.
Advantage of using `gosu` is also signal handling. You may `trap` for instance `SIGHUP` for reloading the process as you would normally achieve via `systemctl reload <process>` or such.
45,210,969
I'm trying to understand an existing piece of code written implementing generics, so it sets up a generic dictionary and then adds items to the dictionary with the key being the type and the value a delegate ``` private readonly Dictionary<Type, Func<actionType, Task>> requestedActions; private void AddAction<T>(Func<T, Task> action) where T : actionType { this.requestedActions[typeof(T)] = (request) => action((T)request); } this.AddAction<AddItem>(this.HandleAdd); this.AddAction<UpdateItem>(this.HandleUpdate); this.AddAction<DeleteItem>(this.HandleDelete); private Task HandleAdd(AddItem message) { ..... } ``` then when an action is received it executes the relevant delegate ``` public bool ProcessData(ItemMessage request) { Func<ItemMessage, Task> requestAction; if (this.requestedActions.TryGetValue(requestType, out requestAction)) { requestAction(request).Await(); } } ``` why would this approach be prefered\better to something like a switch statement on the actionType, as if new types were added you would still have to add the new type to the dictionary and implement a new handler function. Im trying to understand what i gain from using generics in this instance ?? ``` switch (actionType) { case AddItem: HandleAdd(); break; case UpdateItem: HandleUpdate(); break; ... } ```
2017/07/20
[ "https://Stackoverflow.com/questions/45210969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4433801/" ]
The Generic example lets you dynamically add handlers (during runtime), while the switch statement is basically "baked" into the code. This is the primary example of why I can come up with. Also the Generic example looks fancy.
It's hard to tell which approach is better without knowing the use scenario but with the initial example you'll be able to pull in and serialize the data from the Database without having to hassle with adding switch statement every time you introduce a new action. Looks to be saving dev time through the use of Generics. Let's also examine what are the speed differences for using this example as opposed to your switch statement. Dictionary time retrieval is O(1) if you have the type ready at function call. This is the same time retrieval as the switch statement minus having to hassle with the switch.
45,210,969
I'm trying to understand an existing piece of code written implementing generics, so it sets up a generic dictionary and then adds items to the dictionary with the key being the type and the value a delegate ``` private readonly Dictionary<Type, Func<actionType, Task>> requestedActions; private void AddAction<T>(Func<T, Task> action) where T : actionType { this.requestedActions[typeof(T)] = (request) => action((T)request); } this.AddAction<AddItem>(this.HandleAdd); this.AddAction<UpdateItem>(this.HandleUpdate); this.AddAction<DeleteItem>(this.HandleDelete); private Task HandleAdd(AddItem message) { ..... } ``` then when an action is received it executes the relevant delegate ``` public bool ProcessData(ItemMessage request) { Func<ItemMessage, Task> requestAction; if (this.requestedActions.TryGetValue(requestType, out requestAction)) { requestAction(request).Await(); } } ``` why would this approach be prefered\better to something like a switch statement on the actionType, as if new types were added you would still have to add the new type to the dictionary and implement a new handler function. Im trying to understand what i gain from using generics in this instance ?? ``` switch (actionType) { case AddItem: HandleAdd(); break; case UpdateItem: HandleUpdate(); break; ... } ```
2017/07/20
[ "https://Stackoverflow.com/questions/45210969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4433801/" ]
The Generic example lets you dynamically add handlers (during runtime), while the switch statement is basically "baked" into the code. This is the primary example of why I can come up with. Also the Generic example looks fancy.
While you are using as example generic data structure (dictionary), this problem is related to polymorphism not generics. As you've been already told, switch is bad, because you must modify this piece of code if you want to add another case. Switch is usually code smell, indicating polymorphism should be used. Using switch in this case violates open/close principle ([SOLID](https://en.wikipedia.org/wiki/SOLID_(object-oriented_design))). In short, this principle says, code should be opened for change, but closed for modification. Example you provided follows this rule. If you want another action, you don't need to touch this code, just add another Task class. With switch you need to **MODIFY** existing code. I hope this helps!
4,624,341
I'm making an MVC2 app to manage billing schemes. These billing schemes can be of various types, e.g. daily, weekly, monthly, etc. and all types have their specific properties. My class structure looks like this: ``` public abstract class BillingScheme { /* basic billing scheme properties */ } public class BillingSchemeMonthly : BillingScheme { public string SpecificMonths; } //etc. for other scheme types ``` I retrieve a billing scheme through the base class using the billing scheme ID, and it gives me an object of the correct type. The property SpecificMonths maps to a database varchar field that contains a ;-separated string of month numbers. I want to split this to an array so I can create a list of checkboxes and I'd preferably do this with a facade property in a viewmodel. I could do it right inside the view but that seems to go against the MVC pattern. The problem is I can only create this viewmodel specifically for a BillingSchemeMonthly, and I can't cast a BillingSchemeMonthly to a BillingSchemeMonthlyViewModel. I'd rather not implement a clone method in the viewmodel since the entire billing scheme is quite large and the number of properties may grow. Thanks in advance for any help.
2011/01/07
[ "https://Stackoverflow.com/questions/4624341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/403465/" ]
You may take a look at [AutoMapper](http://automapper.codeplex.com/).
Ideally when converting from Models to ViewModels you'll have a seperate converter class. In our MVC projects we have two types of converter, `IConverter<TFrom,TTo>` defining a `Convert` method, and `ITwoWayConverter<TFrom,TTo>` defining `ConvertTo` and `ConvertFrom` methods. We then inject our converters into the necessary controller and use them to do all our conversions. This keeps everything nice and tidy and allows a clear seperation of concerns. When we impliment this, we'd create a new class specifically for the type of conversion we're looking to do: ``` public class MonthlySchemeBillingToMonthlySchemeBillingViewModelConverter : IConverter<MonthlySchemeBilling,MonthlySchemeBillingViewModel> { public MonthlySchemeBillingViewModel Convert(MonthlySchemeBilling) { // Impliment conversion } } ```
1,989,971
In problems where I have to find the limit of a given sequence example **$\lim\_{n→∞}1 \big(\frac{1}{1·2}+\frac{1}{2·3}+ . . .+\frac{1}{n·(n + 1)}\big)$** how can i find what that sequence equals to in order to solve the limit? or example find the limit of **$\lim\_{n→∞}1 \big(\frac{1}{(4·5)} + \frac{1}{(5·6)} + \frac{1}{(6·7)} +...+ \frac{1}{(n+3)(n+4)}\big) ?$**
2016/10/29
[ "https://math.stackexchange.com/questions/1989971", "https://math.stackexchange.com", "https://math.stackexchange.com/users/383809/" ]
Hint: Observe \begin{align} \frac{1}{n(n+1)} = \frac{1}{n}-\frac{1}{n+1} \end{align}
There is no general algorithm. But, the example you gave, it is a series of type $$\dfrac{1}{(a+d)(a+2d)}+\dfrac{1}{(a+2d)(a+3d)}...+\dfrac{1}{(a+(n-2)d)(a+(n-1)d)}$$ You can sum this series by making it a telescoping sum, and then compute the limit.
73,120
[Statistical closeness implies computational indistinguishability](https://crypto.stackexchange.com/q/73108/23115) was recently posed. It revolves around a numeric value $\Delta(n)$ of the statistical difference between a pair of distribution ensembles, as:- $$ \Delta(n) = 1/2 \sum\_{\alpha}|\mathbb{P}[X\_n = \alpha] - \mathbb{P}[Y\_n = \alpha]| $$ But statistical distances can also be measured via other techniques such as Pearson's chi-squared test, Kolmogorov-Smirnov & Anderson–Darling tests and Kullback–Leibler. There are many other exotic tests as well. My four examples are non parametric tests too that produce a numeric test statistic. And they are also used in many aspects of cryptography. Is the $\Delta(n)$ formula specific to cryptography, and if so, why?
2019/09/06
[ "https://crypto.stackexchange.com/questions/73120", "https://crypto.stackexchange.com", "https://crypto.stackexchange.com/users/23115/" ]
What we call "statistical distance" in cryptography is called [total variation distance](https://en.wikipedia.org/wiki/Total_variation_distance_of_probability_measures) by statisticians. So it certainly exists outside of cryptography. I can't speak to its applications within statistics. But it certainly is the most natural metric for cryptography because it has an equivalent formulation in terms of distinguishing two source distributions given a sample, which is how we state many security properties. Restricting the distinguisher to be polynomial-time leads to natural and useful generalizations.
In the cryptographic context, the $\Delta(X;Y)$ formula(i.e the statistical distance) seems to be the most 'natural' because of the way we define security in terms of a distinguishing advantage. i.e $$\Delta^D(X;Y) = |Pr^{DY}[D(Y) = 1] - Pr^{DX}[D(X) = 1]$$. As mentioned here [here](https://crypto.stackexchange.com/a/73118/58690), this definition implies that the statistical distance is an upper bound on the distinguishing advantage of **any** distinguisher(computationally bounded or not). In other words, as consequence of the definition, the statistical distance is 'The metric' for security. Now why is this definition of advantage the most natural? I have no idea... Talking about metrics, the distinguising advantage can be shown to also be a pseudo-metric. Which is not the case for all distance measure. At [Swiss Crypto Day](https://swisscryptoday.github.io/) Maurer gave an intringuing talk titled *'Adversaryless cryptography'*. The main insight was that by essentially using the statistical distance, one can make security claims without the need of explicitly speaking of an adversary, this would potentially simplify our security proofs and help gain more insight into the security claims that we make. I am curious to see where this goes ;). Looking at the specific case of Pearson's $\chi^2$, i don't know of many indistinguishability proofs based on that. The only one I could find was in the paper [Information-theoretic Indistinguishability via the Chi-squared Method](https://eprint.iacr.org/2017/537) by Dai and al. The insight of the paper was that the new method could be a potentially simpler framework to make security claims based on statistical distance, since the classical proof frameworks seem to be error-prone. But ironically, this [paper](https://www.researchgate.net/publication/322525006_A_note_on_the_chi-square_method_A_tool_for_proving_cryptographic_security) seems to show that the proof by Dai and al. had some mistakes furthermore they show ways to fix the proof. So it seems that an exiting advancement but we still have a long way to go...
7,568,479
I know that similar questions have been asked in the past but I can't seem to get this working at all even with the suggestions. I get the above abend on the "show()" command. ``` public void onCreate(Bundle savedInstanceState) { try{ super.onCreate(savedInstanceState); setContentView(R.layout.submitscoredummylayout); scoreloopInit(); AlertDialog whatToUploadDialog; whatToUploadDialog = new AlertDialog.Builder(YanivSubmitScoreActivity.this).create(); whatToUploadDialog.setContentView(R.layout.submitscoreprompt); whatToUploadDialog.setTitle(R.string.uploadedScoreTitle); whatToUploadDialog.setCancelable(false); ((CheckBox)whatToUploadDialog.findViewById(R.id.ckbScoreloop)).setChecked(settings.getUploadToSL()); ((CheckBox)whatToUploadDialog.findViewById(R.id.ckbFacebook)).setChecked(settings.getUploadToFB()); ((CheckBox) whatToUploadDialog.findViewById(R.id.ckbScoreloop)).setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton ckBox, boolean isChecked) { settings.setUploadToSL(isChecked,true); findViewById(R.id.btnYes).setEnabled(isChecked||settings.getUploadToFB()); } }); ((CheckBox) whatToUploadDialog.findViewById(R.id.ckbFacebook)).setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton ckBox, boolean isChecked) { settings.setUploadToFB(isChecked,true); findViewById(R.id.btnYes).setEnabled(isChecked||settings.getUploadToSL()); } }); whatToUploadDialog.findViewById(R.id.btnYes).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { submitScore(SUBMIT_UPLOAD_TO_SL); whatToUploadDialog.dismiss(); } }); whatToUploadDialog.findViewById(R.id.btnNo).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { whatToUploadDialog.dismiss(); finish(); } }); whatToUploadDialog.show(); } ``` Logcat: ``` W/System.err(14969): android.util.AndroidRuntimeException: requestFeature() must be called before adding content W/System.err(14969): at com.android.internal.policy.impl.PhoneWindow.requestFeature(PhoneWindow.java:184) W/System.err(14969): at com.android.internal.app.AlertController.installContent(AlertController.java:198) W/System.err(14969): at android.app.AlertDialog.onCreate(AlertDialog.java:251) W/System.err(14969): at android.app.Dialog.dispatchOnCreate(Dialog.java:307) W/System.err(14969): at android.app.Dialog.show(Dialog.java:225) W/System.err(14969): at ui.YanivSubmitScoreActivity.onCreate(YanivSubmitScoreActivity.java:105) W/System.err(14969): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) W/System.err(14969): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627) W/System.err(14969): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679) W/System.err(14969): at android.app.ActivityThread.access$2300(ActivityThread.java:125) W/System.err(14969): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033) W/System.err(14969): at android.os.Handler.dispatchMessage(Handler.java:99) W/System.err(14969): at android.os.Looper.loop(Looper.java:123) W/System.err(14969): at android.app.ActivityThread.main(ActivityThread.java:4627) W/System.err(14969): at java.lang.reflect.Method.invokeNative(Native Method) W/System.err(14969): at java.lang.reflect.Method.invoke(Method.java:521) W/System.err(14969): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:871) W/System.err(14969): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629) W/System.err(14969): at dalvik.system.NativeStart.main(Native Method) ```
2011/09/27
[ "https://Stackoverflow.com/questions/7568479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/648746/" ]
Substitude the following line: ``` whatToUploadDialog.setContentView(R.layout.submitscoreprompt); ``` with: ``` whatToUploadDialog.setView(R.layout.submitscoreprompt); ```
Try calling ``` .setTitle(R.string.uploadedScoreTitle); ``` before ``` .setContentView(R.layout.submitscoreprompt); ```
7,568,479
I know that similar questions have been asked in the past but I can't seem to get this working at all even with the suggestions. I get the above abend on the "show()" command. ``` public void onCreate(Bundle savedInstanceState) { try{ super.onCreate(savedInstanceState); setContentView(R.layout.submitscoredummylayout); scoreloopInit(); AlertDialog whatToUploadDialog; whatToUploadDialog = new AlertDialog.Builder(YanivSubmitScoreActivity.this).create(); whatToUploadDialog.setContentView(R.layout.submitscoreprompt); whatToUploadDialog.setTitle(R.string.uploadedScoreTitle); whatToUploadDialog.setCancelable(false); ((CheckBox)whatToUploadDialog.findViewById(R.id.ckbScoreloop)).setChecked(settings.getUploadToSL()); ((CheckBox)whatToUploadDialog.findViewById(R.id.ckbFacebook)).setChecked(settings.getUploadToFB()); ((CheckBox) whatToUploadDialog.findViewById(R.id.ckbScoreloop)).setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton ckBox, boolean isChecked) { settings.setUploadToSL(isChecked,true); findViewById(R.id.btnYes).setEnabled(isChecked||settings.getUploadToFB()); } }); ((CheckBox) whatToUploadDialog.findViewById(R.id.ckbFacebook)).setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton ckBox, boolean isChecked) { settings.setUploadToFB(isChecked,true); findViewById(R.id.btnYes).setEnabled(isChecked||settings.getUploadToSL()); } }); whatToUploadDialog.findViewById(R.id.btnYes).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { submitScore(SUBMIT_UPLOAD_TO_SL); whatToUploadDialog.dismiss(); } }); whatToUploadDialog.findViewById(R.id.btnNo).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { whatToUploadDialog.dismiss(); finish(); } }); whatToUploadDialog.show(); } ``` Logcat: ``` W/System.err(14969): android.util.AndroidRuntimeException: requestFeature() must be called before adding content W/System.err(14969): at com.android.internal.policy.impl.PhoneWindow.requestFeature(PhoneWindow.java:184) W/System.err(14969): at com.android.internal.app.AlertController.installContent(AlertController.java:198) W/System.err(14969): at android.app.AlertDialog.onCreate(AlertDialog.java:251) W/System.err(14969): at android.app.Dialog.dispatchOnCreate(Dialog.java:307) W/System.err(14969): at android.app.Dialog.show(Dialog.java:225) W/System.err(14969): at ui.YanivSubmitScoreActivity.onCreate(YanivSubmitScoreActivity.java:105) W/System.err(14969): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) W/System.err(14969): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627) W/System.err(14969): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679) W/System.err(14969): at android.app.ActivityThread.access$2300(ActivityThread.java:125) W/System.err(14969): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033) W/System.err(14969): at android.os.Handler.dispatchMessage(Handler.java:99) W/System.err(14969): at android.os.Looper.loop(Looper.java:123) W/System.err(14969): at android.app.ActivityThread.main(ActivityThread.java:4627) W/System.err(14969): at java.lang.reflect.Method.invokeNative(Native Method) W/System.err(14969): at java.lang.reflect.Method.invoke(Method.java:521) W/System.err(14969): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:871) W/System.err(14969): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629) W/System.err(14969): at dalvik.system.NativeStart.main(Native Method) ```
2011/09/27
[ "https://Stackoverflow.com/questions/7568479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/648746/" ]
I experienced the same problem. I found that the problem only occurs if I do both of the following things: * I don't use activity managed dialogs (`activity.showDialog()` -> `activity.onCreateDialog()`/`onPrepareDialog()`) * I do `dialog.findViewById()` (and this is indeed the line difference between success or the requestFeature exception!). ``` final Builder dialogBuilder = new AlertDialog.Builder(activity); b.setView(rootView); b.setIcon(android.R.drawable.ic_dialog_info); b.setTitle(R.string.message_of_the_day_title); b.setCancelable(false); dialog = b.createDialog(); dialog.findViewById(R.id.myid); // this is the problem ``` The `dialog.findViewById()` causes the problem because it calls ``` dialog.getWindow().getDecorView() ``` and the method javadoc of `getDecorView()` says: > > Note that calling this function for the first time "locks in" various > window characteristics as described in {@link #setContentView(View, > android.view.ViewGroup.LayoutParams)}. > > > Isn't that nice, `findViewById()` has a side effect which causes seemingly correct applications to crash. Why there's a difference between `Activity` managed dialogs and normal dialogs I do not know, but I guess `getDecorView()` does some magic for `Activity` managed dialogs. I did the above because I moved from using `Activity` managed dialogs to handling dialogs myself. The solution for me is to manipulate the rootView, using `rootView.findViewById()`, instead of manipulating the dialog.
Try calling ``` .setTitle(R.string.uploadedScoreTitle); ``` before ``` .setContentView(R.layout.submitscoreprompt); ```
7,568,479
I know that similar questions have been asked in the past but I can't seem to get this working at all even with the suggestions. I get the above abend on the "show()" command. ``` public void onCreate(Bundle savedInstanceState) { try{ super.onCreate(savedInstanceState); setContentView(R.layout.submitscoredummylayout); scoreloopInit(); AlertDialog whatToUploadDialog; whatToUploadDialog = new AlertDialog.Builder(YanivSubmitScoreActivity.this).create(); whatToUploadDialog.setContentView(R.layout.submitscoreprompt); whatToUploadDialog.setTitle(R.string.uploadedScoreTitle); whatToUploadDialog.setCancelable(false); ((CheckBox)whatToUploadDialog.findViewById(R.id.ckbScoreloop)).setChecked(settings.getUploadToSL()); ((CheckBox)whatToUploadDialog.findViewById(R.id.ckbFacebook)).setChecked(settings.getUploadToFB()); ((CheckBox) whatToUploadDialog.findViewById(R.id.ckbScoreloop)).setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton ckBox, boolean isChecked) { settings.setUploadToSL(isChecked,true); findViewById(R.id.btnYes).setEnabled(isChecked||settings.getUploadToFB()); } }); ((CheckBox) whatToUploadDialog.findViewById(R.id.ckbFacebook)).setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton ckBox, boolean isChecked) { settings.setUploadToFB(isChecked,true); findViewById(R.id.btnYes).setEnabled(isChecked||settings.getUploadToSL()); } }); whatToUploadDialog.findViewById(R.id.btnYes).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { submitScore(SUBMIT_UPLOAD_TO_SL); whatToUploadDialog.dismiss(); } }); whatToUploadDialog.findViewById(R.id.btnNo).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { whatToUploadDialog.dismiss(); finish(); } }); whatToUploadDialog.show(); } ``` Logcat: ``` W/System.err(14969): android.util.AndroidRuntimeException: requestFeature() must be called before adding content W/System.err(14969): at com.android.internal.policy.impl.PhoneWindow.requestFeature(PhoneWindow.java:184) W/System.err(14969): at com.android.internal.app.AlertController.installContent(AlertController.java:198) W/System.err(14969): at android.app.AlertDialog.onCreate(AlertDialog.java:251) W/System.err(14969): at android.app.Dialog.dispatchOnCreate(Dialog.java:307) W/System.err(14969): at android.app.Dialog.show(Dialog.java:225) W/System.err(14969): at ui.YanivSubmitScoreActivity.onCreate(YanivSubmitScoreActivity.java:105) W/System.err(14969): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) W/System.err(14969): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627) W/System.err(14969): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679) W/System.err(14969): at android.app.ActivityThread.access$2300(ActivityThread.java:125) W/System.err(14969): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033) W/System.err(14969): at android.os.Handler.dispatchMessage(Handler.java:99) W/System.err(14969): at android.os.Looper.loop(Looper.java:123) W/System.err(14969): at android.app.ActivityThread.main(ActivityThread.java:4627) W/System.err(14969): at java.lang.reflect.Method.invokeNative(Native Method) W/System.err(14969): at java.lang.reflect.Method.invoke(Method.java:521) W/System.err(14969): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:871) W/System.err(14969): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629) W/System.err(14969): at dalvik.system.NativeStart.main(Native Method) ```
2011/09/27
[ "https://Stackoverflow.com/questions/7568479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/648746/" ]
I experienced the same problem. I found that the problem only occurs if I do both of the following things: * I don't use activity managed dialogs (`activity.showDialog()` -> `activity.onCreateDialog()`/`onPrepareDialog()`) * I do `dialog.findViewById()` (and this is indeed the line difference between success or the requestFeature exception!). ``` final Builder dialogBuilder = new AlertDialog.Builder(activity); b.setView(rootView); b.setIcon(android.R.drawable.ic_dialog_info); b.setTitle(R.string.message_of_the_day_title); b.setCancelable(false); dialog = b.createDialog(); dialog.findViewById(R.id.myid); // this is the problem ``` The `dialog.findViewById()` causes the problem because it calls ``` dialog.getWindow().getDecorView() ``` and the method javadoc of `getDecorView()` says: > > Note that calling this function for the first time "locks in" various > window characteristics as described in {@link #setContentView(View, > android.view.ViewGroup.LayoutParams)}. > > > Isn't that nice, `findViewById()` has a side effect which causes seemingly correct applications to crash. Why there's a difference between `Activity` managed dialogs and normal dialogs I do not know, but I guess `getDecorView()` does some magic for `Activity` managed dialogs. I did the above because I moved from using `Activity` managed dialogs to handling dialogs myself. The solution for me is to manipulate the rootView, using `rootView.findViewById()`, instead of manipulating the dialog.
Substitude the following line: ``` whatToUploadDialog.setContentView(R.layout.submitscoreprompt); ``` with: ``` whatToUploadDialog.setView(R.layout.submitscoreprompt); ```
16,035,188
Assume that there is a table which is called Stack; ``` Id StackId ------------------- . . 1 10 2 12 3 10 4 10 5 11 11 5 . . . . ``` how to learn cross id like ? ``` Id = 5 StackId = 11 Id = 11 StackId = 5 ``` I could not write the sql sentences which shows me ``` 5,11 11,5 ``` I dont know the numbers because the table has 1.000.000+ rows, so I want to find rows which likes 5,11
2013/04/16
[ "https://Stackoverflow.com/questions/16035188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1514165/" ]
Use `JOIN` to the table itself with `s1.Id = s2.StackId AND s1.StackId = s2.Id` condition: ``` SELECT s1.Id, s1.StackId FROM Stack s1 JOIN Stack s2 ON s1.Id = s2.StackId AND s1.StackId = s2.Id ``` Because `INNER JOIN` is used (it's by default) rows with no corresponding `s2` values won't be returned.
Please try: ``` select a.* from YourTable a inner join YourTable b on a.Id=b.StackId ```
16,035,188
Assume that there is a table which is called Stack; ``` Id StackId ------------------- . . 1 10 2 12 3 10 4 10 5 11 11 5 . . . . ``` how to learn cross id like ? ``` Id = 5 StackId = 11 Id = 11 StackId = 5 ``` I could not write the sql sentences which shows me ``` 5,11 11,5 ``` I dont know the numbers because the table has 1.000.000+ rows, so I want to find rows which likes 5,11
2013/04/16
[ "https://Stackoverflow.com/questions/16035188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1514165/" ]
Use `JOIN` to the table itself with `s1.Id = s2.StackId AND s1.StackId = s2.Id` condition: ``` SELECT s1.Id, s1.StackId FROM Stack s1 JOIN Stack s2 ON s1.Id = s2.StackId AND s1.StackId = s2.Id ``` Because `INNER JOIN` is used (it's by default) rows with no corresponding `s2` values won't be returned.
Another solution: ``` select * from Stack s where exists (select 1 from Stack where Id = s.StackId and StackId = s.Id) ```
16,035,188
Assume that there is a table which is called Stack; ``` Id StackId ------------------- . . 1 10 2 12 3 10 4 10 5 11 11 5 . . . . ``` how to learn cross id like ? ``` Id = 5 StackId = 11 Id = 11 StackId = 5 ``` I could not write the sql sentences which shows me ``` 5,11 11,5 ``` I dont know the numbers because the table has 1.000.000+ rows, so I want to find rows which likes 5,11
2013/04/16
[ "https://Stackoverflow.com/questions/16035188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1514165/" ]
You can approach this with aggregation as well as a join. Here is one method: ``` select (case when id < StackId then id else StackId end) as FirstVal, (case when id < StackId then StackId else id end) as SecondVal from t group by (case when id < StackId then id else StackId end), (case when id < StackId then StackId else id end) having count(distinct id) = 2 ``` If you have a database with a `least()` and `greatest()` functions, and you know there are now duplicates in the table, you can rephrase this as: ``` select least(id, StackId) as FirstVal, greatest(id, StackId) as SecondVal from t group by least(id, StackId), greatest(id, StackId) having count(*) = 2 ```
Please try: ``` select a.* from YourTable a inner join YourTable b on a.Id=b.StackId ```
16,035,188
Assume that there is a table which is called Stack; ``` Id StackId ------------------- . . 1 10 2 12 3 10 4 10 5 11 11 5 . . . . ``` how to learn cross id like ? ``` Id = 5 StackId = 11 Id = 11 StackId = 5 ``` I could not write the sql sentences which shows me ``` 5,11 11,5 ``` I dont know the numbers because the table has 1.000.000+ rows, so I want to find rows which likes 5,11
2013/04/16
[ "https://Stackoverflow.com/questions/16035188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1514165/" ]
You can approach this with aggregation as well as a join. Here is one method: ``` select (case when id < StackId then id else StackId end) as FirstVal, (case when id < StackId then StackId else id end) as SecondVal from t group by (case when id < StackId then id else StackId end), (case when id < StackId then StackId else id end) having count(distinct id) = 2 ``` If you have a database with a `least()` and `greatest()` functions, and you know there are now duplicates in the table, you can rephrase this as: ``` select least(id, StackId) as FirstVal, greatest(id, StackId) as SecondVal from t group by least(id, StackId), greatest(id, StackId) having count(*) = 2 ```
Another solution: ``` select * from Stack s where exists (select 1 from Stack where Id = s.StackId and StackId = s.Id) ```
35,531,538
I need to have an absolute `div` that is a child of only `body` fill the entire document area (window + any scroll area) -- width: 100% only fills the viewable screen I prefer a CSS only solution but pure javascript is ok. I tried without success setting: ``` opaque.style.minHeight = Math.max(document.body.offsetHeight, document.body.scrollHeight); ``` I made a [jsFiddle](https://jsfiddle.net/mseifert/dsxvre7t/) of the code below. If you scroll down the output, you will see that the opaque div stops at whatever height the output window was when it was rendered. In case you are wondering... it is to make an opaque overlay of all content in the div behind it (think slideshow). My only other solution is to disable scrolling, but this is problematic. Thanks for any help. ``` <div class="page-container"></div> <div id="opaque"></div> body { width:100%; } .page-container { position: relative; max-width:978px; width: 100%; min-height:2500px; margin:0 auto -50px auto; border:solid #999; border-width:2px; background: lightblue; } #opaque { position: absolute; top: 0px; left: 0px; width: 100%; height: 100%; z-index: 100; background: grey; filter: alpha(opacity=70); opacity: 0.7; } ```
2016/02/21
[ "https://Stackoverflow.com/questions/35531538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1101341/" ]
Can use ``` #opaque { position: fixed; top: 0; left: 0; right:0; bottom:0; } ``` remove `width:100%` from body due to creates horizontal scrollbar Depending on use case it is often common to add class to body when using such an overlay that sets body overflow to hidden `**[DEMO](https://jsfiddle.net/dsxvre7t/1/)**`
You can put a `position: relative` on your body so that the body will be used as a reference point by the child element in terms of height (as opposed to the `document` object).
35,531,538
I need to have an absolute `div` that is a child of only `body` fill the entire document area (window + any scroll area) -- width: 100% only fills the viewable screen I prefer a CSS only solution but pure javascript is ok. I tried without success setting: ``` opaque.style.minHeight = Math.max(document.body.offsetHeight, document.body.scrollHeight); ``` I made a [jsFiddle](https://jsfiddle.net/mseifert/dsxvre7t/) of the code below. If you scroll down the output, you will see that the opaque div stops at whatever height the output window was when it was rendered. In case you are wondering... it is to make an opaque overlay of all content in the div behind it (think slideshow). My only other solution is to disable scrolling, but this is problematic. Thanks for any help. ``` <div class="page-container"></div> <div id="opaque"></div> body { width:100%; } .page-container { position: relative; max-width:978px; width: 100%; min-height:2500px; margin:0 auto -50px auto; border:solid #999; border-width:2px; background: lightblue; } #opaque { position: absolute; top: 0px; left: 0px; width: 100%; height: 100%; z-index: 100; background: grey; filter: alpha(opacity=70); opacity: 0.7; } ```
2016/02/21
[ "https://Stackoverflow.com/questions/35531538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1101341/" ]
You can put a `position: relative` on your body so that the body will be used as a reference point by the child element in terms of height (as opposed to the `document` object).
Using javascript to set one elements height equal to anothers ``` var o = document.getElementById('opaque'); var p = document.querySelector('.page-container'); o.style.height = window.getComputedStyle(p).getPropertyValue("height"); ``` [**FIDDLE**](https://jsfiddle.net/dsxvre7t/2/)
35,531,538
I need to have an absolute `div` that is a child of only `body` fill the entire document area (window + any scroll area) -- width: 100% only fills the viewable screen I prefer a CSS only solution but pure javascript is ok. I tried without success setting: ``` opaque.style.minHeight = Math.max(document.body.offsetHeight, document.body.scrollHeight); ``` I made a [jsFiddle](https://jsfiddle.net/mseifert/dsxvre7t/) of the code below. If you scroll down the output, you will see that the opaque div stops at whatever height the output window was when it was rendered. In case you are wondering... it is to make an opaque overlay of all content in the div behind it (think slideshow). My only other solution is to disable scrolling, but this is problematic. Thanks for any help. ``` <div class="page-container"></div> <div id="opaque"></div> body { width:100%; } .page-container { position: relative; max-width:978px; width: 100%; min-height:2500px; margin:0 auto -50px auto; border:solid #999; border-width:2px; background: lightblue; } #opaque { position: absolute; top: 0px; left: 0px; width: 100%; height: 100%; z-index: 100; background: grey; filter: alpha(opacity=70); opacity: 0.7; } ```
2016/02/21
[ "https://Stackoverflow.com/questions/35531538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1101341/" ]
Can use ``` #opaque { position: fixed; top: 0; left: 0; right:0; bottom:0; } ``` remove `width:100%` from body due to creates horizontal scrollbar Depending on use case it is often common to add class to body when using such an overlay that sets body overflow to hidden `**[DEMO](https://jsfiddle.net/dsxvre7t/1/)**`
Using javascript to set one elements height equal to anothers ``` var o = document.getElementById('opaque'); var p = document.querySelector('.page-container'); o.style.height = window.getComputedStyle(p).getPropertyValue("height"); ``` [**FIDDLE**](https://jsfiddle.net/dsxvre7t/2/)
52,727,570
Given the following code snippet from my nodejs server: ``` router.get('/page/:id', async function (req, res, next) { var id = req.params.id; if ( typeof req.params.id === "number"){id = parseInt(id);} res.render('page.ejs' , { vara:a , varb:b }); }); ``` I want to do exactly what I'm doing in the nodejs server but on from the service worker. I've generated & built it using workbox but I don't know how to cache all the urls like /page/1 or /page/2 or .... /page/4353 and so on without overcharging the service worker source code. The nodejs code from above it's working 100%. I tried to so something like: ``` .....{ "url": "/page/\*", "revision": "q8j4t1d072f2g6l5unc0q6c0r7vgs5w0" },.... ``` It doesn't work in the service worker pre-cache when I reloaded the website with this code added into the service worker it was installing and it took pretty much. Is that normal? Can't I do that without overcharging the entire installing process and browser cache memory? Thank you for help! EDIT: My service worker looks like : ``` importScripts("https://storage.googleapis.com/workbox-cdn/releases/3.6.2/workbox-sw.js"); if (workbox) { console.log('Workbox status : ONLINE'); } else { console.log('Workbox status : OFFLINE'); } workbox.skipWaiting(); workbox.clientsClaim(); self.__precacheManifest = [ { "url": "/", "revision": "7e50eec344ce4d01730894ef1d637d4d" }, 'head.ejs', 'navbar.ejs', 'map_script.ejs', 'scripts.ejs', 'details.json', 'page.ejs', 'home.ejs', 'map.ejs', 'about.ejs', { "url": "/page", "revision": "881d8ca1f2aacfc1617c09e3cf7364f0", "cleanUrls": "true" }, { "url": "/about", "revision": "11d729194a0669e3bbc938351eba5d00" }, { "url": "/map", "revision": "c3942a2a8ac5b713d63c53616676974a" }, { "url": "/getJson", "revision": "15c88be34ben24a683f7be97fd8abc4e" }, { "url": "/getJson1", "revision": "15c88be34bek24a6l3f7be97fd3aoc4e" }, { "url": "/getJson2", "revision": "15c82be34ben24a683f7be17fd3amc4e" }, { "url": "/getJson3", "revision": "15c62be94ben24a683f7be17gd3amc4r" }, { "url": "/getJson4", "revision": "15c62beh4ben24a6g3f7be97gd3amc4p" }, { "url": "/public/_processed_/2/7/csm.jpg", "revision": "15c62beh4bek44a6g3f7ben7gd3amc4p" }, { "url": "/public/_processed_/2/7/csm.jpg", "revision": "15c62beh4ben24a6g3f7be9ngd3a2c4p" } ].concat(self.__precacheManifest || []); workbox.precaching.suppressWarnings(); workbox.precaching.precacheAndRoute(self.__precacheManifest, {}); ```
2018/10/09
[ "https://Stackoverflow.com/questions/52727570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9581773/" ]
The `gethostbyname()` and `gethostbyaddr()` functions are deprecated on most platforms, and they don't implement support for IPv6. IPv4 has reached its limits, the world has been moving to IPv6 for awhile now. Use `getaddrinfo()` and `getnameinfo()` instead, respectively. To answer your questions: A. `getaddrinfo()` and `getnameinfo()` can be used for clients and servers alike, just as `gethostbyname()` and `gethostbyaddr()` can be. They are just host/address resolution functions, how the resolved values get used is up to the calling app to decide. B. client code using `getaddrinfo()` would look something like this: ``` int OpenConnection(const char *hostname, int port) { int sd, err; struct addrinfo hints = {}, *addrs; char port_str[16] = {}; hints.ai_family = AF_INET; // Since your original code was using sockaddr_in and // PF_INET, I'm using AF_INET here to match. Use // AF_UNSPEC instead if you want to allow getaddrinfo() // to find both IPv4 and IPv6 addresses for the hostname. // Just make sure the rest of your code is equally family- // agnostic when dealing with the IP addresses associated // with this connection. For instance, make sure any uses // of sockaddr_in are changed to sockaddr_storage, // and pay attention to its ss_family field, etc... hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; sprintf(port_str, "%d", port); err = getaddrinfo(hostname, port_str, &hints, &addrs); if (err != 0) { fprintf(stderr, "%s: %s\n", hostname, gai_strerror(err)); abort(); } for(struct addrinfo *addr = addrs; addr != NULL; addr = addr->ai_next) { sd = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol); if (sd == -1) { err = errno; break; // if using AF_UNSPEC above instead of AF_INET/6 specifically, // replace this 'break' with 'continue' instead, as the 'ai_family' // may be different on the next iteration... } if (connect(sd, addr->ai_addr, addr->ai_addrlen) == 0) break; err = errno; close(sd); sd = -1; } freeaddrinfo(addrs); if (sd == -1) { fprintf(stderr, "%s: %s\n", hostname, strerror(err)); abort(); } return sd; } ```
I've always used [gethostbyname()](https://linux.die.net/man/3/gethostbyname) since "forever". It's always worked, it continues to work, and it's "simpler". [getaddrinfo()](http://man7.org/linux/man-pages/man3/getaddrinfo.3.html) is the newer function: > > <http://man7.org/linux/man-pages/man3/getaddrinfo.3.html> > > > The getaddrinfo() function combines the > functionality provided by the gethostbyname(3) and getservbyname(3) > functions into a single interface, but unlike the latter functions, > getaddrinfo() is reentrant and allows programs to eliminate > IPv4-versus-IPv6 dependencies. > > > I understand that getaddrinfo() ismore robust, more efficient, and more secure: [You shouldn't be using gethostbyname() anyway](https://blog.erratasec.com/2015/01/you-shouldnt-be-using-gethostbyname.html#.W7z8LlFJmCg) ADDENDUM: In reply to your specific questions: A] `getaddrinfo()` is preferred over `gethostbyname()` to lookup the IP address of a hostname; either "client" or "server". B] Q: How would I modify the hints struct and the function parameters? A: The "hints" look OK, but I would probably modify the port to NULL. Here's a complete example: <https://www.kutukupret.com/2009/09/28/gethostbyname-vs-getaddrinfo/> ``` #include <stdio.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <arpa/inet.h> int main(int argc, char *argv[]) { struct addrinfo hints, *res, *p; int status; char ipstr[INET6_ADDRSTRLEN]; if (argc != 2) { fprintf(stderr, "Usage: %s hostname\n", argv[0]); return 1; } memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; // AF_INET or AF_INET6 to force version hints.ai_socktype = SOCK_STREAM; if ((status = getaddrinfo(argv[1], NULL, &hints, &res)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status)); return 2; } for(p = res;p != NULL; p = p->ai_next) { void *addr; if (p->ai_family == AF_INET) { return 1; } else { struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr; addr = &(ipv6->sin6_addr); /* convert the IP to a string and print it: */ inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr); printf("Hostname: %s\n", argv[1]); printf("IP Address: %s\n", ipstr); } } freeaddrinfo(res); // free the linked list return 0; } ```
17,085,277
Is there an easy way to lock all files in directory for svn. As I know we cannot lock all directory?
2013/06/13
[ "https://Stackoverflow.com/questions/17085277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1960347/" ]
You need a different syntax, as per [the documentation](http://api.jquery.com/on/): ``` $('body').on('click', 'button.btn_change_status', function(e) { alert(e.target.id); return false; }); ```
Use the following syntax for [**.on()**](http://api.jquery.com/on/) ``` $(document).on('click','btn_change_status', function(e) { //write your code here }); ```
17,085,277
Is there an easy way to lock all files in directory for svn. As I know we cannot lock all directory?
2013/06/13
[ "https://Stackoverflow.com/questions/17085277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1960347/" ]
Update your css with the following. I'm assuming you don't need mouse events on your icon. ``` .icon-eye-open { pointer-events:none; } ``` [MDN Information regarding pointer-events](https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events)
Use the following syntax for [**.on()**](http://api.jquery.com/on/) ``` $(document).on('click','btn_change_status', function(e) { //write your code here }); ```
46,642,184
I have a code where im looping through hosts list and appending connections to connections list, if there is a connection error, i want to skip that and continue with the next host in the hosts list. Heres what i have now: ``` def do_connect(self): """Connect to all hosts in the hosts list""" for host in self.hosts: try: client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(host['ip'], port=int(host['port']), username=host['user'], timeout=2) except: pass #client.connect(host['ip'], port=int(host['port']), username=host['user'], password=host['passwd']) finally: if paramiko.SSHException(): pass else: self.connections.append(client) ``` This does not work properly, if connection fails it just loops the same host again and again forever, till it establishes connection, how do i fix this?
2017/10/09
[ "https://Stackoverflow.com/questions/46642184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7943938/" ]
Your own answer is still wrong on quite a few points... ``` import logging logger = logging.getLogger(__name__) def do_connect(self): """Connect to all hosts in the hosts list""" for host in self.hosts: # this one has to go outside the try/except block # else `client` might not be defined. client = paramiko.SSHClient() try: client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(host['ip'], port=int(host['port']), username=host['user'], timeout=2) # you only want to catch specific exceptions here except paramiko.SSHException as e: # this will log the full error message and traceback logger.exception("failed to connect to %(ip)s:%(port)s (user %(user)s)", host) continue # here you want a `else` clause not a `finally` # (`finally` is _always_ executed) else: self.connections.append(client) ```
Ok, got it working, i needed to add the Continue, mentioned by Mark and also the previous if check inside finally was always returning true so that was fixed aswell. Here is the fixed code, that doesnt add failed connections and continues the loop normally after that: ``` def do_connect(self): """Connect to all hosts in the hosts list""" for host in self.hosts: try: client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(host['ip'], port=int(host['port']), username=host['user'], timeout=2) except: continue #client.connect(host['ip'], port=int(host['port']), username=host['user'], password=host['passwd']) finally: if client._agent is None: pass else: self.connections.append(client) ```
83,033
How do I season an antique cast iron cider press that I just bought? It is substantially bigger than any stove, oven, or grill that I own, at about 48" diameter. I'd consider other food-safe finishes too, but seasoning seems the obvious choice given that it is cast iron.
2017/07/17
[ "https://cooking.stackexchange.com/questions/83033", "https://cooking.stackexchange.com", "https://cooking.stackexchange.com/users/751/" ]
I would not heat up a large cast iron press - too much to go wrong there, little benefit. You are not frying on the thing. Clean any oil/rust that's on it, dry carefully, oil it with mineral oil or wax it with beeswax (or paraffin wax, but beeswax will probably stick better,) use it, clean it up well, dry very carefully, and re-oil/wax before storage.
I expect that the "[Open Fire](http://americanskilletcompany.com/use-care/re-seasoning/)" method (the second technique in the linked article) may be your best bet. Create a fire pit large enough to meet your needs. Make sure you allow for enough room around where you will place your device to allow the fire to properly breath. Place (or devise) a grate to support your cast iron and build a fire. (You might want get some Coal (real coal...not charcoal...reach out to a local blacksmith if you don't know where to get it.) and go through several repetitions of the process. Process : Seasoning: 1. Build a fire up until you have a bed of red embers & a low, non-sooty flame. ( 30 min. ) This kind of fire is nearly smokeless & hot as all get out. 2. Set the clean iron over the fire & heat ‘till it turns “white-blue” in color. This means it’s ripping hot, and you’re now ready for the first coat of oil ! 3. Hook the handle, pull the pan off the fire, & mist it evenly with the Flax Oil. 4. Not Too Much! You don’t want puddles, drips or thick coats. Just a very thin & even layer into every nook, cranny, handle & backside. The pan should be smoking fiercely when you do this. Stand down wind.[sic] *(added: stand UP Wind so the smoke is blowing away from you.)* 5. Put the smokin’ pan back onto the fire & let it smoke out until it stops. Watch for uneven heating & adjust the iron over the best heat spot on your fire. 6. You’ll know you are ready for the next layer of oil when you see the ash of the fire wisp off the face of the once sticky oiled surface. The color should be even, the first few coats have a brownish-red hue on them, & the pan will look dry again. 7. Repeat steps #2-#5 about 6 times ! You’ll see the pan turn to a rich “blue-black” by the last round of oil. (Approx. 1 hour of seasoning.) Enjoy the fire when you’re all done & marvel at your crafty work while letting your iron cool down naturally on a wire rack. Tips: Be very careful to not put the hot iron onto something wet or cold ! The dramatic difference of temperatures could cause a cast iron skillet to crack or warp from thermal shock!Your pan should be a deep black color and ready to use within one hour’s time of this open-fire process. If you find that the cookware is still a little sticky after it’s cool, you may need to oven bake it for 30-45 minutes, to finish it off and get it totally dry.If your pan develops of reddish color and you can’t seem to get it black, there’s three possible issues you’re facing: You probably don’t have enough heat on it You haven’t done the seasoning long enough You put the oil on too thick *(Copied from linked article, should the link die in the future)*
83,033
How do I season an antique cast iron cider press that I just bought? It is substantially bigger than any stove, oven, or grill that I own, at about 48" diameter. I'd consider other food-safe finishes too, but seasoning seems the obvious choice given that it is cast iron.
2017/07/17
[ "https://cooking.stackexchange.com/questions/83033", "https://cooking.stackexchange.com", "https://cooking.stackexchange.com/users/751/" ]
I expect that the "[Open Fire](http://americanskilletcompany.com/use-care/re-seasoning/)" method (the second technique in the linked article) may be your best bet. Create a fire pit large enough to meet your needs. Make sure you allow for enough room around where you will place your device to allow the fire to properly breath. Place (or devise) a grate to support your cast iron and build a fire. (You might want get some Coal (real coal...not charcoal...reach out to a local blacksmith if you don't know where to get it.) and go through several repetitions of the process. Process : Seasoning: 1. Build a fire up until you have a bed of red embers & a low, non-sooty flame. ( 30 min. ) This kind of fire is nearly smokeless & hot as all get out. 2. Set the clean iron over the fire & heat ‘till it turns “white-blue” in color. This means it’s ripping hot, and you’re now ready for the first coat of oil ! 3. Hook the handle, pull the pan off the fire, & mist it evenly with the Flax Oil. 4. Not Too Much! You don’t want puddles, drips or thick coats. Just a very thin & even layer into every nook, cranny, handle & backside. The pan should be smoking fiercely when you do this. Stand down wind.[sic] *(added: stand UP Wind so the smoke is blowing away from you.)* 5. Put the smokin’ pan back onto the fire & let it smoke out until it stops. Watch for uneven heating & adjust the iron over the best heat spot on your fire. 6. You’ll know you are ready for the next layer of oil when you see the ash of the fire wisp off the face of the once sticky oiled surface. The color should be even, the first few coats have a brownish-red hue on them, & the pan will look dry again. 7. Repeat steps #2-#5 about 6 times ! You’ll see the pan turn to a rich “blue-black” by the last round of oil. (Approx. 1 hour of seasoning.) Enjoy the fire when you’re all done & marvel at your crafty work while letting your iron cool down naturally on a wire rack. Tips: Be very careful to not put the hot iron onto something wet or cold ! The dramatic difference of temperatures could cause a cast iron skillet to crack or warp from thermal shock!Your pan should be a deep black color and ready to use within one hour’s time of this open-fire process. If you find that the cookware is still a little sticky after it’s cool, you may need to oven bake it for 30-45 minutes, to finish it off and get it totally dry.If your pan develops of reddish color and you can’t seem to get it black, there’s three possible issues you’re facing: You probably don’t have enough heat on it You haven’t done the seasoning long enough You put the oil on too thick *(Copied from linked article, should the link die in the future)*
Tropical method for seasoning a press. Pick a day when the temperatures are likely to stay above 90°F for a good part of the day. Clean well. Place in black plastic bag. close bag. Let set in direct sunlight for 4 hours during the hottest part of the day (in summer). Rub with bees wax. Set to cool in shade. Bees wax is anti bacterial. .
83,033
How do I season an antique cast iron cider press that I just bought? It is substantially bigger than any stove, oven, or grill that I own, at about 48" diameter. I'd consider other food-safe finishes too, but seasoning seems the obvious choice given that it is cast iron.
2017/07/17
[ "https://cooking.stackexchange.com/questions/83033", "https://cooking.stackexchange.com", "https://cooking.stackexchange.com/users/751/" ]
I would not heat up a large cast iron press - too much to go wrong there, little benefit. You are not frying on the thing. Clean any oil/rust that's on it, dry carefully, oil it with mineral oil or wax it with beeswax (or paraffin wax, but beeswax will probably stick better,) use it, clean it up well, dry very carefully, and re-oil/wax before storage.
Cos Callie's suggestion seems very good, but I thought I'd mention there is another way of finishing cast iron. You can make a tea-based seasoning, where tannins from tea react with the iron to form a stable, rustproof outer layer of [ferric tannate](https://cooking.stackexchange.com/questions/43950/why-dont-i-have-to-season-my-cast-iron-teapot?s=1%7C0.1438). Cast iron teapots are seasoned this way. I would suppose you thickly brew tea, and either soak the press, or douse the press several times with the brew to build up layers of seasoning (letting dry between coats). Once the tannins have a chance to react with the iron (possibly after warming or heating), the seasoning should be stable and any remaining tea residues washed off. The choice would depend on your resources, ie, if you have a container big enough to soak the press, or someplace to lay it in the sun when drying, or space for a suitably sized open fire.
83,033
How do I season an antique cast iron cider press that I just bought? It is substantially bigger than any stove, oven, or grill that I own, at about 48" diameter. I'd consider other food-safe finishes too, but seasoning seems the obvious choice given that it is cast iron.
2017/07/17
[ "https://cooking.stackexchange.com/questions/83033", "https://cooking.stackexchange.com", "https://cooking.stackexchange.com/users/751/" ]
I would not heat up a large cast iron press - too much to go wrong there, little benefit. You are not frying on the thing. Clean any oil/rust that's on it, dry carefully, oil it with mineral oil or wax it with beeswax (or paraffin wax, but beeswax will probably stick better,) use it, clean it up well, dry very carefully, and re-oil/wax before storage.
Tropical method for seasoning a press. Pick a day when the temperatures are likely to stay above 90°F for a good part of the day. Clean well. Place in black plastic bag. close bag. Let set in direct sunlight for 4 hours during the hottest part of the day (in summer). Rub with bees wax. Set to cool in shade. Bees wax is anti bacterial. .
83,033
How do I season an antique cast iron cider press that I just bought? It is substantially bigger than any stove, oven, or grill that I own, at about 48" diameter. I'd consider other food-safe finishes too, but seasoning seems the obvious choice given that it is cast iron.
2017/07/17
[ "https://cooking.stackexchange.com/questions/83033", "https://cooking.stackexchange.com", "https://cooking.stackexchange.com/users/751/" ]
Cos Callie's suggestion seems very good, but I thought I'd mention there is another way of finishing cast iron. You can make a tea-based seasoning, where tannins from tea react with the iron to form a stable, rustproof outer layer of [ferric tannate](https://cooking.stackexchange.com/questions/43950/why-dont-i-have-to-season-my-cast-iron-teapot?s=1%7C0.1438). Cast iron teapots are seasoned this way. I would suppose you thickly brew tea, and either soak the press, or douse the press several times with the brew to build up layers of seasoning (letting dry between coats). Once the tannins have a chance to react with the iron (possibly after warming or heating), the seasoning should be stable and any remaining tea residues washed off. The choice would depend on your resources, ie, if you have a container big enough to soak the press, or someplace to lay it in the sun when drying, or space for a suitably sized open fire.
Tropical method for seasoning a press. Pick a day when the temperatures are likely to stay above 90°F for a good part of the day. Clean well. Place in black plastic bag. close bag. Let set in direct sunlight for 4 hours during the hottest part of the day (in summer). Rub with bees wax. Set to cool in shade. Bees wax is anti bacterial. .
3,130,884
If you have a look at their website it shows statical data ``` $25 Billion in transactions 60,000+ merchants 2,000+ extensions 2+ Million downloads ``` **EDIT:** just wanted to know where does magento get its data from!?
2010/06/28
[ "https://Stackoverflow.com/questions/3130884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/103264/" ]
Often numbers like these are sort of accurate guesstimates done by canvassing users. You should take this up with them directly, I'm sure they'll be happy to help. Making wild claims like this without proof is also a good way to get sued for libel, btw.
Magento code is open source, meaning you can take a look at it any time. I worked with Magento for 3 months and I didn't notice any pingbacks and generally in open source projects developers avoid pingbacks. Especially in a eCommerce environment this could be a security breach and a potential source of information leakage. I assume Magento data are estimates and not real data provided by any monitoring tools in the code. Magento is using [OSL](http://opensource.org/licenses/osl-3.0.php) licence.
3,064,608
How to know that, the system you are building is a better as Desktop Application than an Web Application?
2010/06/17
[ "https://Stackoverflow.com/questions/3064608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/369672/" ]
My top 3: 1. I need to use/control the hardware directly (printer, graphic card...). 2. I don't care if my project is platform dependant. 3. Need complex user interface (OK Web 2.0 is better than ever, but it's still hell to make advanced specialized stuff to work in all Web browsers).
It depends on your target audience, desired features, and what delivery method makes the most sense. It might help to answer these questions: 1) Who will use this? 2) What will they do with it? (think about thinks like media operations, data storage,..) 3) How will they best be able to get this app? 4) What operating system(s) will it support?
3,064,608
How to know that, the system you are building is a better as Desktop Application than an Web Application?
2010/06/17
[ "https://Stackoverflow.com/questions/3064608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/369672/" ]
Interesting question. in practice the answer hinges primarily on the deployment requirements: * If you want very broad and "instant" deployment - then use HTML and HTTP. * if you or your organization have administrative control over the computers on which the app will be deployed, making it a "desktop app" is acceptable. Most apps lie between those extremes.
It depends on your target audience, desired features, and what delivery method makes the most sense. It might help to answer these questions: 1) Who will use this? 2) What will they do with it? (think about thinks like media operations, data storage,..) 3) How will they best be able to get this app? 4) What operating system(s) will it support?
41,941
How can I identify the make and model of a chain? I need to take a chain off and clean it. (It's a new-to-me used bike, and I'm giving everything the once over.) The chain doesn't have a master link, so I'm going to have to break it and add a master link. To do this, I need to figure out what kind of chain it is so I can get the right master link. (It might make sense to just get a new chain given relative prices, but I'd rather keep the chain I have because this is my knock-around bike and I don't want it to look new, I want it to look not worth stealing.) Looking at the chain, it says KMC, NARROW, with a stylized Z. The bike is a 3x7 department store bike. The rear cogs say Shimano MF-TZ21. Here's a picture. [![chain close-up](https://i.stack.imgur.com/BHY3s.jpg)](https://i.stack.imgur.com/BHY3s.jpg)
2016/08/18
[ "https://bicycles.stackexchange.com/questions/41941", "https://bicycles.stackexchange.com", "https://bicycles.stackexchange.com/users/28706/" ]
Any brand link that is rated for a 7 speed chain will fit. Sram refers to there's as a Power Link, KMC calls it a Missing Link other are quick connect. What is important is that it not the type with the "U" clip that it together. That type is only for non derailleur bikes.
It looks like a variant of the [KMC Z8](http://www.kmcchain.eu/chain-KMC_Z8_S-touring_city-8%2C7%2C6%2C5_speed), with a pin length of 7.1mm: [![enter image description here](https://i.stack.imgur.com/a2n5D.jpg)](https://i.stack.imgur.com/a2n5D.jpg) The KMC website suggests using a [MissingLink 7/8R 7.1mm](http://www.kmcchain.eu/connector-KMC_MissingLink_7_8R_7%2C1mm_reusable-touring_city-8%2C7%2C6%2C5_speed) (although others should work as well, as mikes points out).
36,787,793
I have 2 tables User\_places where I can see for each user their home location defined by 2 separate attributes: longitude and latitude. And I have second table Neighborhoods with attribute 'Area', that defines each neighborhood as polygon - jsonb format - "[{"latitude":XXXXX,"longitude":YYYYY},{"latitude":ZZZZZ,"longitude":AAAAA},{"latitude":BBBBBB,"longitude":CCCCC},{"latitude":DDDDD,"longitude":EEEEE}]". Does anybody know how to check whether particular user lives in given neighborhood in Postgresql?
2016/04/22
[ "https://Stackoverflow.com/questions/36787793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5735692/" ]
``` SELECT user_id, ST_Contains( ST_GeomFromText( (select replace(replace(replace(replace(replace(area::text,']','))'),'[','POLYGON(('),'}', ''),',"longitude":',' '),'{"latitude":','') from neighbourhoods limit 1), 4326) (ST_SetSRID(ST_MakePoint(latitude, longitude),4326)) ) as polygon_check from user_places ```
I will assume you have [Postgis](http://postgis.net/) installed on your copy of postgresql? As this has all the Geometry and geographical function extensions to postgresql. You could use [ST\_Contains](http://postgis.refractions.net/documentation/manual-1.4/ST_Contains.html) to check if a point is contained in a given polygon, this returns a boolean. ``` select ST_Contains(neigbourhood.polygon,User_place.geom) ``` If you don't have a geom point value in the User\_places table then this can be created using the [ST\_SetSRID](http://postgis.refractions.net/docs/ST_SetSRID.html) function and [ST\_MakePoint](http://postgis.refractions.net/docs/ST_MakePoint.html) function. For example - `SELECT ST_SetSRID(ST_MakePoint(LAT, LON),SRID);` where SRID is the reference for the projection you are using for example 4326 for WGS 84 ` I would recommend in postgresql make sure all of your Geographical tables have geoms in them, as it makes comparisons much easier. For reference a good place to get answers for geographic and geometry database based questions is <https://gis.stackexchange.com/>
41,987
I'm trying to find an application that can generate waveform and sine waves of whatever audio file I input. I require this application for my college project, it is a research on sound and mathematical patterns. It'd be great if you guys can help me out! I've been looking for some time but can't find any. I apologize if I posted it in the wrong place.
2017/09/01
[ "https://sound.stackexchange.com/questions/41987", "https://sound.stackexchange.com", "https://sound.stackexchange.com/users/22861/" ]
I am an engineering student my self and I use Audacity to generate Sine, Sawtooth, Square waves. It's easy as pie. 1. Download Audacity from [here](http://www.audacityteam.org/download/). 2. Open Audacity and click on Generate from the Toolbar on top. 3. Select the waveform you need, the frequency, the amplitude and duration you want it. 4. Play the track.
You can use Sony Sound Forge, there's a waveform generator inside of it. Best for you could be Audacity which is free see the [doc](http://manual.audacityteam.org/man/generate_menu.html). You could also use a synth in a DAW to generate sines even squares etc...
41,987
I'm trying to find an application that can generate waveform and sine waves of whatever audio file I input. I require this application for my college project, it is a research on sound and mathematical patterns. It'd be great if you guys can help me out! I've been looking for some time but can't find any. I apologize if I posted it in the wrong place.
2017/09/01
[ "https://sound.stackexchange.com/questions/41987", "https://sound.stackexchange.com", "https://sound.stackexchange.com/users/22861/" ]
I am an engineering student my self and I use Audacity to generate Sine, Sawtooth, Square waves. It's easy as pie. 1. Download Audacity from [here](http://www.audacityteam.org/download/). 2. Open Audacity and click on Generate from the Toolbar on top. 3. Select the waveform you need, the frequency, the amplitude and duration you want it. 4. Play the track.
Any DAW (digital audio workstation) or even most video editing software will display a waveform for the audio in a particular file. You can not, however, make a "sine wave of whatever audio file" because the file doesn't contain a sine wave. A sine wave is a very particular type of fixed frequency oscillation. You would set a signal generator to a particular frequency for sinusoidal waves and it would create a sine wave at that frequency. The waveform in an audio file for speech or music or anything like that is a much more complicated compound wave composed of many interacting frequencies. All sound "frequencies" are simply rates of pressure change. The "volume" or SPL (sound pressure level) of a sound is determined by the amount of air that is moved. A loud sound moves a lot of air, a quiet sound moves a little air. A high frequency sound moves air back and forth a lot of times per second, a low frequency sound moves the air back and forth fewer times per second. When you combine the two, it moves the air in and out slowly for the low frequency with the high frequency causing variations along that slow oscillation because of the pressure change from the higher frequency. It all eventually ends up picked up by our ear or a microphone which is able to make sense of the pressure changes hitting it. A waveform is simply the graphical representation of the amount of pressure (either high or low pressure relative to still air) that is being experienced at a given moment over time. It is the result of all the various frequencies that make up the sound you are hearing being combined.
41,987
I'm trying to find an application that can generate waveform and sine waves of whatever audio file I input. I require this application for my college project, it is a research on sound and mathematical patterns. It'd be great if you guys can help me out! I've been looking for some time but can't find any. I apologize if I posted it in the wrong place.
2017/09/01
[ "https://sound.stackexchange.com/questions/41987", "https://sound.stackexchange.com", "https://sound.stackexchange.com/users/22861/" ]
I am an engineering student my self and I use Audacity to generate Sine, Sawtooth, Square waves. It's easy as pie. 1. Download Audacity from [here](http://www.audacityteam.org/download/). 2. Open Audacity and click on Generate from the Toolbar on top. 3. Select the waveform you need, the frequency, the amplitude and duration you want it. 4. Play the track.
You may want to check out [SPEAR](http://www.klingbeil.com/spear/). From the website: * SPEAR is an application for audio analysis, editing and synthesis. The analysis procedure (which is based on the traditional McAulay-Quatieri technique) attempts to represent a sound with many individual sinusoidal tracks (partials), each corresponding to a single sinusoidal wave with time varying frequency and amplitude.
6,986,928
Simple problem here (I think). I have a form with a checkbox at the bottom where the user must agree to the terms and conditions. If the user doesn't check the box, I'd like an error message to be displayed in my validation summary along with the other form errors. I added this to my view model: ``` [Required] [Range(1, 1, ErrorMessage = "You must agree to the Terms and Conditions")] public bool AgreeTerms { get; set; } ``` But that didn't work. Is there an easy way to force a value to be true with data annotations?
2011/08/08
[ "https://Stackoverflow.com/questions/6986928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/295302/" ]
``` using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Threading.Tasks; using System.Web.Mvc; namespace Checked.Entitites { public class BooleanRequiredAttribute : ValidationAttribute, IClientValidatable { public override bool IsValid(object value) { return value != null && (bool)value == true; } public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { //return new ModelClientValidationRule[] { new ModelClientValidationRule() { ValidationType = "booleanrequired", ErrorMessage = this.ErrorMessage } }; yield return new ModelClientValidationRule() { ValidationType = "booleanrequired", ErrorMessage = this.ErrorMessageString }; } } } ```
You can write a custom validation attribute which has already been mentioned. You will need to write custom javascript to enable the unobtrusive validation functionality to pick it up if you are doing client side validation. e.g. if you are using jQuery: ``` // extend jquery unobtrusive validation (function ($) { // add the validator for the boolean attribute $.validator.addMethod( "booleanrequired", function (value, element, params) { // value: the value entered into the input // element: the element being validated // params: the parameters specified in the unobtrusive adapter // do your validation here an return true or false }); // you then need to hook the custom validation attribute into the MS unobtrusive validators $.validator.unobtrusive.adapters.add( "booleanrequired", // adapter name ["booleanrequired"], // the names for the properties on the object that will be passed to the validator method function(options) { // set the properties for the validator method options.rules["booleanRequired"] = options.params; // set the message to output if validation fails options.messages["booleanRequired] = options.message; }); } (jQuery)); ``` Another way (which is a bit of a hack and I don't like it) is to have a property on your model that is always set to true, then use the **CompareAttribute** to compare the value of your \**AgreeTerms \** attribute. Simple yes but I don't like it :)
6,986,928
Simple problem here (I think). I have a form with a checkbox at the bottom where the user must agree to the terms and conditions. If the user doesn't check the box, I'd like an error message to be displayed in my validation summary along with the other form errors. I added this to my view model: ``` [Required] [Range(1, 1, ErrorMessage = "You must agree to the Terms and Conditions")] public bool AgreeTerms { get; set; } ``` But that didn't work. Is there an easy way to force a value to be true with data annotations?
2011/08/08
[ "https://Stackoverflow.com/questions/6986928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/295302/" ]
``` using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Threading.Tasks; using System.Web.Mvc; namespace Checked.Entitites { public class BooleanRequiredAttribute : ValidationAttribute, IClientValidatable { public override bool IsValid(object value) { return value != null && (bool)value == true; } public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { //return new ModelClientValidationRule[] { new ModelClientValidationRule() { ValidationType = "booleanrequired", ErrorMessage = this.ErrorMessage } }; yield return new ModelClientValidationRule() { ValidationType = "booleanrequired", ErrorMessage = this.ErrorMessageString }; } } } ```
There's actually a way to make it work with DataAnnotations. The following way: ``` [Required] [Range(typeof(bool), "true", "true")] public bool AcceptTerms { get; set; } ```
6,986,928
Simple problem here (I think). I have a form with a checkbox at the bottom where the user must agree to the terms and conditions. If the user doesn't check the box, I'd like an error message to be displayed in my validation summary along with the other form errors. I added this to my view model: ``` [Required] [Range(1, 1, ErrorMessage = "You must agree to the Terms and Conditions")] public bool AgreeTerms { get; set; } ``` But that didn't work. Is there an easy way to force a value to be true with data annotations?
2011/08/08
[ "https://Stackoverflow.com/questions/6986928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/295302/" ]
``` using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Threading.Tasks; using System.Web.Mvc; namespace Checked.Entitites { public class BooleanRequiredAttribute : ValidationAttribute, IClientValidatable { public override bool IsValid(object value) { return value != null && (bool)value == true; } public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { //return new ModelClientValidationRule[] { new ModelClientValidationRule() { ValidationType = "booleanrequired", ErrorMessage = this.ErrorMessage } }; yield return new ModelClientValidationRule() { ValidationType = "booleanrequired", ErrorMessage = this.ErrorMessageString }; } } } ```
ASP.Net Core 3.1 I know this is a very old question but for asp.net core the `IClientValidatable` does not exist and i wanted a solution that works with `jQuery Unobtrusive Validation` as well as on server validation so with the help of this SO question [Link](https://stackoverflow.com/questions/36566836/asp-net-core-mvc-client-side-validation-for-custom-attribute) i made a small modification that works with boolean field like checkboxes. Attribute Code ============== ``` [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] public class MustBeTrueAttribute : ValidationAttribute, IClientModelValidator { public void AddValidation(ClientModelValidationContext context) { MergeAttribute(context.Attributes, "data-val", "true"); var errorMsg = FormatErrorMessage(context.ModelMetadata.GetDisplayName()); MergeAttribute(context.Attributes, "data-val-mustbetrue", errorMsg); } public override bool IsValid(object value) { return value != null && (bool)value == true; } private bool MergeAttribute( IDictionary<string, string> attributes, string key, string value) { if (attributes.ContainsKey(key)) { return false; } attributes.Add(key, value); return true; } } ``` Model ===== ``` [Display(Name = "Privacy policy")] [MustBeTrue(ErrorMessage = "Please accept our privacy policy!")] public bool PrivacyPolicy { get; set; } ``` Client Side Code ================ ``` $.validator.addMethod("mustbetrue", function (value, element, parameters) { return element.checked; }); $.validator.unobtrusive.adapters.add("mustbetrue", [], function (options) { options.rules.mustbetrue = {}; options.messages["mustbetrue"] = options.message; }); ```
6,986,928
Simple problem here (I think). I have a form with a checkbox at the bottom where the user must agree to the terms and conditions. If the user doesn't check the box, I'd like an error message to be displayed in my validation summary along with the other form errors. I added this to my view model: ``` [Required] [Range(1, 1, ErrorMessage = "You must agree to the Terms and Conditions")] public bool AgreeTerms { get; set; } ``` But that didn't work. Is there an easy way to force a value to be true with data annotations?
2011/08/08
[ "https://Stackoverflow.com/questions/6986928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/295302/" ]
You can write a custom validation attribute which has already been mentioned. You will need to write custom javascript to enable the unobtrusive validation functionality to pick it up if you are doing client side validation. e.g. if you are using jQuery: ``` // extend jquery unobtrusive validation (function ($) { // add the validator for the boolean attribute $.validator.addMethod( "booleanrequired", function (value, element, params) { // value: the value entered into the input // element: the element being validated // params: the parameters specified in the unobtrusive adapter // do your validation here an return true or false }); // you then need to hook the custom validation attribute into the MS unobtrusive validators $.validator.unobtrusive.adapters.add( "booleanrequired", // adapter name ["booleanrequired"], // the names for the properties on the object that will be passed to the validator method function(options) { // set the properties for the validator method options.rules["booleanRequired"] = options.params; // set the message to output if validation fails options.messages["booleanRequired] = options.message; }); } (jQuery)); ``` Another way (which is a bit of a hack and I don't like it) is to have a property on your model that is always set to true, then use the **CompareAttribute** to compare the value of your \**AgreeTerms \** attribute. Simple yes but I don't like it :)
ASP.Net Core 3.1 I know this is a very old question but for asp.net core the `IClientValidatable` does not exist and i wanted a solution that works with `jQuery Unobtrusive Validation` as well as on server validation so with the help of this SO question [Link](https://stackoverflow.com/questions/36566836/asp-net-core-mvc-client-side-validation-for-custom-attribute) i made a small modification that works with boolean field like checkboxes. Attribute Code ============== ``` [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] public class MustBeTrueAttribute : ValidationAttribute, IClientModelValidator { public void AddValidation(ClientModelValidationContext context) { MergeAttribute(context.Attributes, "data-val", "true"); var errorMsg = FormatErrorMessage(context.ModelMetadata.GetDisplayName()); MergeAttribute(context.Attributes, "data-val-mustbetrue", errorMsg); } public override bool IsValid(object value) { return value != null && (bool)value == true; } private bool MergeAttribute( IDictionary<string, string> attributes, string key, string value) { if (attributes.ContainsKey(key)) { return false; } attributes.Add(key, value); return true; } } ``` Model ===== ``` [Display(Name = "Privacy policy")] [MustBeTrue(ErrorMessage = "Please accept our privacy policy!")] public bool PrivacyPolicy { get; set; } ``` Client Side Code ================ ``` $.validator.addMethod("mustbetrue", function (value, element, parameters) { return element.checked; }); $.validator.unobtrusive.adapters.add("mustbetrue", [], function (options) { options.rules.mustbetrue = {}; options.messages["mustbetrue"] = options.message; }); ```
6,986,928
Simple problem here (I think). I have a form with a checkbox at the bottom where the user must agree to the terms and conditions. If the user doesn't check the box, I'd like an error message to be displayed in my validation summary along with the other form errors. I added this to my view model: ``` [Required] [Range(1, 1, ErrorMessage = "You must agree to the Terms and Conditions")] public bool AgreeTerms { get; set; } ``` But that didn't work. Is there an easy way to force a value to be true with data annotations?
2011/08/08
[ "https://Stackoverflow.com/questions/6986928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/295302/" ]
There's actually a way to make it work with DataAnnotations. The following way: ``` [Required] [Range(typeof(bool), "true", "true")] public bool AcceptTerms { get; set; } ```
ASP.Net Core 3.1 I know this is a very old question but for asp.net core the `IClientValidatable` does not exist and i wanted a solution that works with `jQuery Unobtrusive Validation` as well as on server validation so with the help of this SO question [Link](https://stackoverflow.com/questions/36566836/asp-net-core-mvc-client-side-validation-for-custom-attribute) i made a small modification that works with boolean field like checkboxes. Attribute Code ============== ``` [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] public class MustBeTrueAttribute : ValidationAttribute, IClientModelValidator { public void AddValidation(ClientModelValidationContext context) { MergeAttribute(context.Attributes, "data-val", "true"); var errorMsg = FormatErrorMessage(context.ModelMetadata.GetDisplayName()); MergeAttribute(context.Attributes, "data-val-mustbetrue", errorMsg); } public override bool IsValid(object value) { return value != null && (bool)value == true; } private bool MergeAttribute( IDictionary<string, string> attributes, string key, string value) { if (attributes.ContainsKey(key)) { return false; } attributes.Add(key, value); return true; } } ``` Model ===== ``` [Display(Name = "Privacy policy")] [MustBeTrue(ErrorMessage = "Please accept our privacy policy!")] public bool PrivacyPolicy { get; set; } ``` Client Side Code ================ ``` $.validator.addMethod("mustbetrue", function (value, element, parameters) { return element.checked; }); $.validator.unobtrusive.adapters.add("mustbetrue", [], function (options) { options.rules.mustbetrue = {}; options.messages["mustbetrue"] = options.message; }); ```
777
I have a very large `SparseArray` called `A`. What is the most efficient way to update say element `{i,j}` with value `x` to the value `f[x]` ? I worry about **memory usage and code speed** if I need to make a very large number of updates. I've seen [Leonid's comment here](https://mathematica.stackexchange.com/questions/276/efficient-way-to-combine-sparsearray-objects/287#287) about a similar problem. But there is a lot of info scattered over old SO site and I am looking for function and a syntax something like `f[A_, {i_,j_}, f_]` that will do the job. I think it is a very essential question for recursive by-element updates to `SparseArrays' and would love to see a complete solution here.
2012/01/26
[ "https://mathematica.stackexchange.com/questions/777", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/13/" ]
If you need a batch update, then the answer is in my comment you linked. If you need element-by-element, then there are two cases: * Most of values you update are non-zero (or, generally, not equal to default element). In this case, I believe the answer of @Mr. Wizard is optimal, and you should expect update of a single element to be constant time. * Most (or at least a sizable fraction) of these elements are initially zero (or, default element). Then, you are out of luck. I gave a brief answer to a similar request [in this thread](http://groups.google.com/group/comp.soft-sys.math.mathematica/browse_thread/thread/6e227d2882982860). Basically, SparseArray object keeps lists of non-zero elements and their positions in packed arrays. Therefore, a transition from zero to non-zero for an element requires insertion in the middle of them, which is `O(n)` operation, where `n` is the current number of non-zero elements. So, this is the same situation as building a list with `Append`, and it will lead to a quadratic complexity. This tidbit is not well-known, so I'd like to emphasize it again: ***element-by-element update for the SparseArray generally has complexity ~ `updates * nzero`, where `updates` is the number of updates, and `nzero` is the final non-zero elements***. If you can organize your elements into batches which can be updated at the same time, you win big. Then, I suggest that you use the function I described in the [cited answer](https://mathematica.stackexchange.com/questions/276/efficient-way-to-combine-sparsearray-objects/287#287). A main obstacle in a batch approach would be if you need the current state of your array to be used for something, say matrix multiplication, in between single element updates. If this is not the case, I think you should be able to use the batch update method.
I believe that `Part` works quite well. ``` sa = SparseArray[RandomInteger[{1, 10000}, {5000, 2}] -> 1]; new = RandomInteger[{1, 7000}, {5000, 3}]; (sa[[#, #2]] = #3) & @@@ new; // Timing ``` > > > ``` > {0.078, Null} > > ``` > > Notice that this is being done one element at a time with `@@@` and it is still very fast.
10,550,637
I want to require/include a content from database record, but require/include only accepts files. This thing is related to caching, so I dont want to write anything to file (collisions etc). How to dodge it?
2012/05/11
[ "https://Stackoverflow.com/questions/10550637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1043342/" ]
Are you fetching PHP code from a database? If so, you're probably doing it wrong. Ideally you should only store data inside a database, not code. If you're fetching a PHP structure from the database, consider using a `serialize()`'d version of it (or `json_encode()`'d). Maybe I have missed the exact purpose of what you're trying to accomplish, do let me know if I'm on the wrong path with my answer. Whatever you do, don't rely on `eval` unless you really really have to; and even then, don't :)
This is very dangerous, especially if the database content was contributed from a user, but anyway you could use this : ``` eval($your_database_content); ``` [Manual](http://us3.php.net/manual/en/function.eval.php)
10,550,637
I want to require/include a content from database record, but require/include only accepts files. This thing is related to caching, so I dont want to write anything to file (collisions etc). How to dodge it?
2012/05/11
[ "https://Stackoverflow.com/questions/10550637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1043342/" ]
Since others have covered `eval()` and the fact that this is a bad idea, I will touch on the topic of writing this "content" to a file. Use [`tempnam`](http://php.net/manual/en/function.tempnam.php). This will give you the name of a just-created unique filename with 0600 permissions. You can then open it, write your content, close, then require/include. See Example #1 on the [`tempnam`](http://php.net/manual/en/function.tempnam.php) man page. Make sure to check that the return value of `tempnam` is not false; make sure to `unlink` the file after you are done.
This is very dangerous, especially if the database content was contributed from a user, but anyway you could use this : ``` eval($your_database_content); ``` [Manual](http://us3.php.net/manual/en/function.eval.php)
10,550,637
I want to require/include a content from database record, but require/include only accepts files. This thing is related to caching, so I dont want to write anything to file (collisions etc). How to dodge it?
2012/05/11
[ "https://Stackoverflow.com/questions/10550637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1043342/" ]
Are you fetching PHP code from a database? If so, you're probably doing it wrong. Ideally you should only store data inside a database, not code. If you're fetching a PHP structure from the database, consider using a `serialize()`'d version of it (or `json_encode()`'d). Maybe I have missed the exact purpose of what you're trying to accomplish, do let me know if I'm on the wrong path with my answer. Whatever you do, don't rely on `eval` unless you really really have to; and even then, don't :)
If it is code, you need to use `eval()`, though there are many anti-patterns that involve `eval()` The manual says: > > Caution The eval() language construct is very dangerous because it > allows execution of arbitrary PHP code. Its use thus is discouraged. > If you have carefully verified that there is no other option than to > use this construct, pay special attention not to pass any user > provided data into it without properly validating it beforehand. > > >
10,550,637
I want to require/include a content from database record, but require/include only accepts files. This thing is related to caching, so I dont want to write anything to file (collisions etc). How to dodge it?
2012/05/11
[ "https://Stackoverflow.com/questions/10550637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1043342/" ]
Since others have covered `eval()` and the fact that this is a bad idea, I will touch on the topic of writing this "content" to a file. Use [`tempnam`](http://php.net/manual/en/function.tempnam.php). This will give you the name of a just-created unique filename with 0600 permissions. You can then open it, write your content, close, then require/include. See Example #1 on the [`tempnam`](http://php.net/manual/en/function.tempnam.php) man page. Make sure to check that the return value of `tempnam` is not false; make sure to `unlink` the file after you are done.
If it is code, you need to use `eval()`, though there are many anti-patterns that involve `eval()` The manual says: > > Caution The eval() language construct is very dangerous because it > allows execution of arbitrary PHP code. Its use thus is discouraged. > If you have carefully verified that there is no other option than to > use this construct, pay special attention not to pass any user > provided data into it without properly validating it beforehand. > > >
7,414,811
Inside my Shell Script , i have this line present ``` RUN_CMD="$JAVA_HOME/bin/java -cp $CLASSPATH com/mypack/BalanceRunner ``` Could anybody please tell me , what is meant by this command RUN\_CMD and where can i see this RUN\_CMD defined Thanks for reading
2011/09/14
[ "https://Stackoverflow.com/questions/7414811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/784597/" ]
That's defining an environment variable `RUN_CMD` (looks like a quote omitted at the end, though). It's shorthand for running that Java command (which defines where to find some classes and then specifies which class to run - `BalanceRunner`) The variable is in scope for the current process (a shell, or shell script, most likely). You can see what it's set to by doing: ``` echo $RUN_CMD ``` (note: specifics are shell-dependent but the above is true for Bourne shell derivatives certainly)
You set the value of an environment variable. As to the title of your question: ``` echo $ENV_VAR_NAME ``` will print the value of a defined environment variable to the console
7,414,811
Inside my Shell Script , i have this line present ``` RUN_CMD="$JAVA_HOME/bin/java -cp $CLASSPATH com/mypack/BalanceRunner ``` Could anybody please tell me , what is meant by this command RUN\_CMD and where can i see this RUN\_CMD defined Thanks for reading
2011/09/14
[ "https://Stackoverflow.com/questions/7414811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/784597/" ]
That's defining an environment variable `RUN_CMD` (looks like a quote omitted at the end, though). It's shorthand for running that Java command (which defines where to find some classes and then specifies which class to run - `BalanceRunner`) The variable is in scope for the current process (a shell, or shell script, most likely). You can see what it's set to by doing: ``` echo $RUN_CMD ``` (note: specifics are shell-dependent but the above is true for Bourne shell derivatives certainly)
The line you quote *is* the assignment. As Brian said, it's only in scope for the current process. When you run a script (say with `./<script>` or `bash <script>`), a *new* shell is created in which the script is executed. As such, once the script finishes and you're returned to the prompt, all the variables assigned in the script will be undefined. The exception to this is of course if you execute the script in the current shell, say by executing it with `. <script>` or `source <script>` (see your shell's manual for more details). You can experiment with this on the prompt: ``` $ FOO=bar $ if [ $FOO ]; then echo "FOO defined"; else echo "FOO undefined"; fi FOO defined $ echo $FOO bar $ unset FOO $if [ $FOO ]; then echo "FOO defined"; else echo "FOO undefined"; fi FOO undefined $ echo $FOO $ echo 'FOO=bar' > temp $ . temp $ echo $FOO bar $ unset FOO $ bash temp $ echo $FOO $ ``` As for the actual content and purpose of the variable in your script, I think Brian and others answer this excellently.
7,414,811
Inside my Shell Script , i have this line present ``` RUN_CMD="$JAVA_HOME/bin/java -cp $CLASSPATH com/mypack/BalanceRunner ``` Could anybody please tell me , what is meant by this command RUN\_CMD and where can i see this RUN\_CMD defined Thanks for reading
2011/09/14
[ "https://Stackoverflow.com/questions/7414811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/784597/" ]
The line you quote *is* the assignment. As Brian said, it's only in scope for the current process. When you run a script (say with `./<script>` or `bash <script>`), a *new* shell is created in which the script is executed. As such, once the script finishes and you're returned to the prompt, all the variables assigned in the script will be undefined. The exception to this is of course if you execute the script in the current shell, say by executing it with `. <script>` or `source <script>` (see your shell's manual for more details). You can experiment with this on the prompt: ``` $ FOO=bar $ if [ $FOO ]; then echo "FOO defined"; else echo "FOO undefined"; fi FOO defined $ echo $FOO bar $ unset FOO $if [ $FOO ]; then echo "FOO defined"; else echo "FOO undefined"; fi FOO undefined $ echo $FOO $ echo 'FOO=bar' > temp $ . temp $ echo $FOO bar $ unset FOO $ bash temp $ echo $FOO $ ``` As for the actual content and purpose of the variable in your script, I think Brian and others answer this excellently.
You set the value of an environment variable. As to the title of your question: ``` echo $ENV_VAR_NAME ``` will print the value of a defined environment variable to the console
35,356,956
I have a problem using the std::map, specifically when using find. I have the following code. ``` class MyClass { update(const QVariant&); QVariant m_itemInfo; std::map<QVariant, int> m_testMap; } void update(const QVariant& itemInfo) { if(m_itemInfo != itemInfo) { // The items are not equal m_itemInfo = itemInfo; } if(m_testMap.find(itemInfo) == m_testMap.end()) { // TestMap doesnt contain key itemInfo. m_testMap.insert(std::make_pair(itemInfo, 1)); } // More code } ``` The function `update` is called several times (with different itemInfo objects) in my code. Now when I start to debug it, I see that the first time `update` is called, both the first and the second if loop are entered. So far so good. However the second time `update` is called I do see that the first if loop is called, but the second is skipped! What am I missing here?
2016/02/12
[ "https://Stackoverflow.com/questions/35356956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1479628/" ]
I guess the problem that the first and second `QVariant`s that you pass to your Update method have different type (for example, `bool` and `uint`). `std::map::find` doesn't use !=operator to compare keys, it uses operator < (less) by default. If two compared `QVariant` values have different types operators != and < may work contradictory. `std::map::find` compares keys in the following way: > > Two keys are considered equivalent if the container's comparison object returns false reflexively (i.e., no matter the order in which the elements are passed as arguments). > > > i.e. `std::map::find` considers that v1 is equal to v2 ``` if(!(v1<v2) && !(v2>v1)) { //is TRUE !!! } ``` To solve your problem, you should define a *less* comparison for `std:map`. ``` class QVariantLessCompare { bool operator()(const QVariant& v1, QVariant& v2) const { // ==== You SHOULD IMPLEMENT appropriate comparison here!!! ==== // Implementation will depend on type of QVariant values you use //return v1 < v2; } }; ``` And use `QVariantCompare` in a such way: ``` std::map<QVariant, int, QVariantLessCompare> m_testMap; ```
A more paradigmatic solution is to use `QMap` which correctly implements the comparison of most `QVariant` types. It won't do `userTypes()` out of the box, but this still might suit your application. A cleaner version of the solution proposed by Володин Андрей, that builds, might look like: ``` struct QVariantLessCompare { bool operator()(const QVariant& v1,const QVariant& v2) const { return v1.toInt() < v2.toInt(); } }; ```
51,396,490
I’m using this character, double sharp `''` which unicode is 0x1d12a. If I use it in a string, I can’t get the correct string length: ``` str = "F" str.length // returns 3, even though there are 2 characters! ``` How do I get the function to return the correct answer, whether or not I’m using special unicode or not ?
2018/07/18
[ "https://Stackoverflow.com/questions/51396490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7329561/" ]
``` String.prototype.codes = function() { return [...this].length }; String.prototype.chars = function() { let GraphemeSplitter = require('grapheme-splitter'); return (new GraphemeSplitter()).countGraphemes(this); } console.log("F".codes()); // 2 console.log("‍❤️‍‍".codes()); // 8 console.log("❤️".codes()); // 2 console.log("F".chars()); // 2 console.log("‍❤️‍‍".chars()); // 1 console.log("❤️".chars()); // 1 ```
To sumarize my comments: That's just the lenght of that string. Some chars involve other chars as well, even if it looks like a single character. `"̉mủt̉ả̉̉̉t̉ẻd̉W̉ỏ̉r̉̉d̉̉".length == 24` From [this (great) blog post](https://blog.jonnew.com/posts/poo-dot-length-equals-two), they have a function that will return correct length: ```js function fancyCount(str){ const joiner = "\u{200D}"; const split = str.split(joiner); let count = 0; for(const s of split){ //removing the variation selectors const num = Array.from(s.split(/[\ufe00-\ufe0f]/).join("")).length; count += num; } //assuming the joiners are used appropriately return count / split.length; } console.log(fancyCount("F") == 2) // true ```
51,396,490
I’m using this character, double sharp `''` which unicode is 0x1d12a. If I use it in a string, I can’t get the correct string length: ``` str = "F" str.length // returns 3, even though there are 2 characters! ``` How do I get the function to return the correct answer, whether or not I’m using special unicode or not ?
2018/07/18
[ "https://Stackoverflow.com/questions/51396490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7329561/" ]
To sumarize my comments: That's just the lenght of that string. Some chars involve other chars as well, even if it looks like a single character. `"̉mủt̉ả̉̉̉t̉ẻd̉W̉ỏ̉r̉̉d̉̉".length == 24` From [this (great) blog post](https://blog.jonnew.com/posts/poo-dot-length-equals-two), they have a function that will return correct length: ```js function fancyCount(str){ const joiner = "\u{200D}"; const split = str.split(joiner); let count = 0; for(const s of split){ //removing the variation selectors const num = Array.from(s.split(/[\ufe00-\ufe0f]/).join("")).length; count += num; } //assuming the joiners are used appropriately return count / split.length; } console.log(fancyCount("F") == 2) // true ```
Javascript (and Java) strings use UTF-16 encoding. Unicode codepoint U+0046 (`F`) is encoded in UTF-16 using 1 codeunit: `0x0046` Unicode codepoint U+1D12A () is encoded in UTF-16 using 2 codeunits (known as a "surrogate pair"): `0xD834 0xDD2A` That is why you are getting a `length` of 3, not 2. The `length` counts the number of encoded codeunits, not the number of Unicode codepoints.
51,396,490
I’m using this character, double sharp `''` which unicode is 0x1d12a. If I use it in a string, I can’t get the correct string length: ``` str = "F" str.length // returns 3, even though there are 2 characters! ``` How do I get the function to return the correct answer, whether or not I’m using special unicode or not ?
2018/07/18
[ "https://Stackoverflow.com/questions/51396490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7329561/" ]
``` String.prototype.codes = function() { return [...this].length }; String.prototype.chars = function() { let GraphemeSplitter = require('grapheme-splitter'); return (new GraphemeSplitter()).countGraphemes(this); } console.log("F".codes()); // 2 console.log("‍❤️‍‍".codes()); // 8 console.log("❤️".codes()); // 2 console.log("F".chars()); // 2 console.log("‍❤️‍‍".chars()); // 1 console.log("❤️".chars()); // 1 ```
Javascript (and Java) strings use UTF-16 encoding. Unicode codepoint U+0046 (`F`) is encoded in UTF-16 using 1 codeunit: `0x0046` Unicode codepoint U+1D12A () is encoded in UTF-16 using 2 codeunits (known as a "surrogate pair"): `0xD834 0xDD2A` That is why you are getting a `length` of 3, not 2. The `length` counts the number of encoded codeunits, not the number of Unicode codepoints.
51,396,490
I’m using this character, double sharp `''` which unicode is 0x1d12a. If I use it in a string, I can’t get the correct string length: ``` str = "F" str.length // returns 3, even though there are 2 characters! ``` How do I get the function to return the correct answer, whether or not I’m using special unicode or not ?
2018/07/18
[ "https://Stackoverflow.com/questions/51396490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7329561/" ]
``` String.prototype.codes = function() { return [...this].length }; String.prototype.chars = function() { let GraphemeSplitter = require('grapheme-splitter'); return (new GraphemeSplitter()).countGraphemes(this); } console.log("F".codes()); // 2 console.log("‍❤️‍‍".codes()); // 8 console.log("❤️".codes()); // 2 console.log("F".chars()); // 2 console.log("‍❤️‍‍".chars()); // 1 console.log("❤️".chars()); // 1 ```
That's the function I wrote to get string length in codepoint length ``` function nbUnicodeLength(string){ var stringIndex = 0; var unicodeIndex = 0; var length = string.length; var second; var first; while (stringIndex < length) { first = string.charCodeAt(stringIndex); // returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index. if (first >= 0xD800 && first <= 0xDBFF && string.length > stringIndex + 1) { second = string.charCodeAt(stringIndex + 1); if (second >= 0xDC00 && second <= 0xDFFF) { stringIndex += 2; } else { stringIndex += 1; } } else { stringIndex += 1; } unicodeIndex += 1; } return unicodeIndex; } ```
51,396,490
I’m using this character, double sharp `''` which unicode is 0x1d12a. If I use it in a string, I can’t get the correct string length: ``` str = "F" str.length // returns 3, even though there are 2 characters! ``` How do I get the function to return the correct answer, whether or not I’m using special unicode or not ?
2018/07/18
[ "https://Stackoverflow.com/questions/51396490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7329561/" ]
That's the function I wrote to get string length in codepoint length ``` function nbUnicodeLength(string){ var stringIndex = 0; var unicodeIndex = 0; var length = string.length; var second; var first; while (stringIndex < length) { first = string.charCodeAt(stringIndex); // returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index. if (first >= 0xD800 && first <= 0xDBFF && string.length > stringIndex + 1) { second = string.charCodeAt(stringIndex + 1); if (second >= 0xDC00 && second <= 0xDFFF) { stringIndex += 2; } else { stringIndex += 1; } } else { stringIndex += 1; } unicodeIndex += 1; } return unicodeIndex; } ```
Javascript (and Java) strings use UTF-16 encoding. Unicode codepoint U+0046 (`F`) is encoded in UTF-16 using 1 codeunit: `0x0046` Unicode codepoint U+1D12A () is encoded in UTF-16 using 2 codeunits (known as a "surrogate pair"): `0xD834 0xDD2A` That is why you are getting a `length` of 3, not 2. The `length` counts the number of encoded codeunits, not the number of Unicode codepoints.
243,263
I need to make my dropdown menu apprear over the top of a flash movie, how is this done cross browser? It can be done, IBM do it: <http://www.ibm.com/us/> so do GE: <http://www.ge.com/> Setting the the WMODE to transparent doesn't work for Firefox Putting it into an Iframe doesnt work below IE7 Any one know the best way to achieve this?
2008/10/28
[ "https://Stackoverflow.com/questions/243263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Set the wmode to transparent and if necessary, use z-index as you would on any other element, that really should work for Firefox too.
Firefox for linux shows flash on top of everything. Regardles of wmode or z-index. EDIT: I just found out that the Linux issue described above can be "fixed". You need to add an iframe with a z-index between the swf and the layer you want to put on top of it. The iframe needs to have style="display:none" initially and you must use javascript to set display:block on it after the flash plugin has initialized. The Iframe will hide all swfs that are below it on linux.
243,263
I need to make my dropdown menu apprear over the top of a flash movie, how is this done cross browser? It can be done, IBM do it: <http://www.ibm.com/us/> so do GE: <http://www.ge.com/> Setting the the WMODE to transparent doesn't work for Firefox Putting it into an Iframe doesnt work below IE7 Any one know the best way to achieve this?
2008/10/28
[ "https://Stackoverflow.com/questions/243263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
here is an example with all three modes: opaque, transparent and no wmode at all <http://www.communitymx.com/content/source/E5141/wmodeopaque.htm> use transparent if you have something under the flash movie that you want visible, opaque if you don't want to show what's underneath and set a higher z-index for menu than the flash movie has
Firefox for linux shows flash on top of everything. Regardles of wmode or z-index. EDIT: I just found out that the Linux issue described above can be "fixed". You need to add an iframe with a z-index between the swf and the layer you want to put on top of it. The iframe needs to have style="display:none" initially and you must use javascript to set display:block on it after the flash plugin has initialized. The Iframe will hide all swfs that are below it on linux.
36,260,631
Actually I am getting an error: ``` Exception in thread "main" java.lang.NoClassDefFoundError:sun/io/CharToByteConverter ``` This is because in Java 8, the CharToByteConverter class has been removed as it was deprecated. Now I want to know of any alternative which would replace this package/class and provide its functionality without throwing the exception mentioned above. This class is used in the SQLJ's ``` Translator.jar ``` and inside it it is in ``` sqlj.util.io.OracleOutputStream.class ``` Edit: If I replace the CharToByteConverter class with the java.nio.charset class, still the SQLJ might not be able to detect it. Please correct me if I am wrong. And let me know if replacing the CharToByteConverter with java.nio.charset might fix the issue?
2016/03/28
[ "https://Stackoverflow.com/questions/36260631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3520291/" ]
This is an old issue, but WAS an issue for me until today as well. So maybe others may benefit from the information, that Oracle has a bug #21315718 for that, containing the solution: "Translator.jar and runtime12.jar were not compatible with JDK 8. The issue is reported in unpublished Bug 21315718 - sqlj translator does not work with jdk 8." After upgrading these two jars, SQLJ did not raise the above error for me.
The javadoc comment says it all: > > Deprecated! Replaced - by java.nio.charset > > > Look for a replacement class/method in the java.nio.charset package. Note that using classes in the JDK that are not part of the officially documented API is a bad idea in the first place
14,378,837
I have a problem with the UIImagePickerController component. Currently in my app the user can pick an image from the saved photos library with the picker, no problems there. However, it seems that if I crop and save a photo *in Photos.app* before picking the image, UIImagePickerController gives me the original uncropped version in the `UIImagePickerControllerOriginalImage` dictionary key. I understand that `UIImagePickerControllerEditedImage` works when the crop is done inside the picker, but when done in the Photos app this key returns nil. So my question is, how do I access the correct version of the image (without rolling my own picker with ALAssetLibrary)?
2013/01/17
[ "https://Stackoverflow.com/questions/14378837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/438807/" ]
The solution was simple; I was using `UIImagePickerControllerSourceTypeSavedPhotosAlbum` instead of `UIImagePickerControllerSourceTypePhotoLibrary`.
What is your ``` -(void)imagePickerController:(UIImagePickerController *)pickr didFinishPickingMediaWithInfo; ``` method like? Have you tried to do something like ``` -(void)imagePickerController:(UIImagePickerController *)pickr didFinishPickingMediaWithInfo:(NSDictionary *)info{ UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage]; [myImageView setImage:image]; [pickr dismissModalViewControllerAnimated:YES]; } ``` (in the example it's `UIImagePickerControllerEditedImage`, don't know if you set YES to your picker `allowEditing`)
19,516
I am using OBS to stream on facebook. I could connect to facebook with OBS and see preview at facebook (audio and video is streaming in preview mode at facebook). When I go live it stop working. What can be the issue? Thanks
2016/10/06
[ "https://avp.stackexchange.com/questions/19516", "https://avp.stackexchange.com", "https://avp.stackexchange.com/users/16846/" ]
If you're designing source artwork in Illustrator, take advantage of the fact you can bring your .ai files straight in AE. On the layer in AE that you put the AI vector, click the 'continuously rasterize' button and you'll get your crisp vector edges back. [![After Effects Timeline option](https://i.stack.imgur.com/2OpGf.png)](https://i.stack.imgur.com/2OpGf.png)
OK, so the asset is sharp when it's 956×956, but you then put it in your comp and scale it down to 50% meaning that it is now 478×478. It looks softer than it did at full resolution. Yes, *what did you expect to happen?* It has lost 75% of the pixels it originally had, it's going to look softer, end of story. Export from AI at the same pixel size that it's going to be in the comp and that's the resolution you have to work to. If it looks too soft, then change your design. Video is a raster format. If you put something in a comp it is going to be rasterised, and if you make it teeny tiny you may run out of pixels. That's what designing for the screen is all about. You've only got a grid as large as your final resolution to play with. Let's put it into perspective that will help you visualise it from a print designer's view. If you were designing for print with a dpi of 300, your 720p video frame would measure around 11cm × 6cm (4.3" × 2.5"). Not very big eh? For something this size you wouldn't put in elements with tiny details and expect those details to look super crisp on the final result. Same for video. Tiny details will get antialiased and look soft - when they're compressed you will lose even more detail. Your job as a designer is to design stuff that looks good at the final resolution. (And if you think that's a drag, try designing for standard definition interlaced content delivered on VHS tapes. You kids don't know how good you gots it).
6,112,883
I have a background image used as tooltip container's background. The image is shown below: ![enter image description here](https://i.stack.imgur.com/lqrxP.png) It is used like this: ``` .tooltip { display:none; background:url(images/black_arrow_big.png); height:163px; padding:40px 30px 10px 30px; width:310px; font-size:11px; color:#fff; } <div class="tooltip">Tolltip text goes here</div> ``` However all tooltips do not have the same amount of text, so I need a way to make the container bigger or smaller based on the amount of text. How should I do this? Does sliding door technique allow both horizontal and vertical resizing? How? Also, could I have the same diagonal gradient if I use a sliding door technique? If not, any alternatives?
2011/05/24
[ "https://Stackoverflow.com/questions/6112883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66580/" ]
**Update** this can be done using pure CSS. [Example](http://nicolasgallagher.com/pure-css-speech-bubbles/). Good question. Right now, it looks like your drop shadow is part of the PNG image, and that's not resizable, as you know. You can use CSS3 drop shadows, which will adapt to the size of the container. The problem with that is, you can only add those shadows to text, or boxes (not arrows!). I think your best option is to add a drop shadow to the box with CSS3, and have a PNG image of JUST the arrow, kind of like this: ![enter image description here](https://i.stack.imgur.com/jvabI.png) It may take a little adjustment to get it aligned perfectly, but it will allow the box to resize based on the content. ``` .tooltip { display:none; padding:40px 30px 10px 30px; font-size:11px; color:#fff; position: relative; background: #000; /* rounded corners */ -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; /* box shadow */ -webkit-box-shadow: 0px 0px 10px rgba(0,0,0,0.3); -moz-box-shadow: 0px 0px 10px rgba(0,0,0,0.3); box-shadow: 0px 0px 10px rgba(0,0,0,0.3); /* background gradient, see http://gradients.glrzad.com/ */ background-image: -webkit-gradient( linear, left bottom, left top, color-stop(0.08, rgb(0,0,0)), color-stop(0.57, rgb(48,48,48)) ); background-image: -moz-linear-gradient( center bottom, rgb(0,0,0) 8%, rgb(48,48,48) 57% ); } .tooltip_arrow { position: absolute; bottom: -37px; /* 37px is the height of the black_arrow.png */ left: 45%; /* roughly centered... you can decide how to best do this */ } <div class="tooltip"> Tolltip text goes here <img src="images/black_arrow.png" class="tooltip_arrow" /> </div> ``` I haven't tested this, but I hope it gives a good start.
Try CSS Arrows: <http://cssarrowplease.com/>
38,258,489
So I have a web app that login to Instagram. Works fine for months. No code changes, and suddenly I'm getting ``` {"code": 400, "error_type": "OAuthException", "error_message": "Matching code was not found or was already used."} ``` Logging out of instagram.com on my browser and using my web app to login with instagram oauth.... now it works. And it works repeatedly (logging in and out of my app with instagram oauth). Works fine. Until I access a www.instagram.com webpage on my browser. Then my oauth login fails again with the same error. And I can't login to my web app with instagram oauth again until I logout of instagram.com itself
2016/07/08
[ "https://Stackoverflow.com/questions/38258489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/136558/" ]
``` document.getElementsByTagName('header') ``` will store all the header which is in the page in array. ```js var test = document.getElementsByTagName("header"); alert(test[0].innerHTML); alert(test[1].innerHTML); ``` ```html <header>first test</header> <header>second test</header> ``` Reference link [here](http://www.w3schools.com/jsref/met_element_getelementsbytagname.asp)
If you don't want to assign id or class names and want to use tag name. Then it is also fine with or without html5. ``` var test = document.getElementsByTagName("header") ; ``` You are not able to get value as test is array here , notice method name is getElementsByTagName instead of getElementByTagName. So for getting value you need to traverse through this array and if you know it has only one header element then you can simply fetch using index. ``` var myValue = test[0].innerHtml; ```
42,908,846
I'm trying to write values to my VideoFlag list when the pixel intensity difference is higher than a predefined threshold. On output however my output 'flag.txt' file is empty, and I'm not sure why. Does anyone know in what way my code is wrong? Thanks! ``` import cv2 import tkinter as tk from tkinter.filedialog import askopenfilename import numpy as np import os import matplotlib.pyplot as plt MIList =[] VideoFlag=[] def frame_diff(prev_frame, cur_frame, next_frame): diff_frames1 = cv2.absdiff(next_frame, cur_frame) diff_frames2 = cv2.absdiff(cur_frame, prev_frame) return cv2.bitwise_and(diff_frames1, diff_frames2) def get_frame(cap): ret, frame = cap.read() if ret == True: scaling_factor = 1 frame = cv2.resize(frame, None, fx = scaling_factor, fy = scaling_factor, interpolation = cv2.INTER_AREA) return cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY) def moving_average(MIList, n=30) : ret = np.cumsum(MIList, dtype=float) ret[n:] = ret[n:] - ret[:-n] return ret[n - 1:] / n def main(): root = tk.Tk() root.withdraw() selectedvideo = askopenfilename() cap = cv2.VideoCapture(selectedvideo) length = cap.get(cv2.CAP_PROP_FRAME_COUNT) intlength = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) currentframenumber = cap.get(cv2.CAP_PROP_POS_FRAMES) intcurrentframenumber = int(cap.get(cv2.CAP_PROP_POS_FRAMES)) scaling_factor = 1 fourcc = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter((selectedvideo + 'motionindexed.avi'),fourcc, 60.0, (640,478), isColor=False) with open((selectedvideo + 'threshold' + '.txt'), 'r') as readthreshold: threshold = float(readthreshold.readline()) prev_frame = get_frame(cap) cur_frame = get_frame(cap) next_frame = get_frame(cap) while (cap.isOpened()): try: cv2.imshow("Object Movement", frame_diff(prev_frame, cur_frame, next_frame)) prev_frame = cur_frame cur_frame = next_frame next_frame = get_frame(cap) differencesquared = (next_frame-cur_frame)**2 interframedifference = np.sum(differencesquared) MIList.append(interframedifference) print(interframedifference) if interframedifference >= threshold: out.write(cur_frame) VideoFlag.append(str(intcurrentframenumber + '|' + 1)) print(VideoFlag) elif interframedifference < threshold: VideoFlag.append(str(intcurrentframenumber + '|' + 0)) print(VideoFlag) key = cv2.waitKey(1) if key == ord('q'): break except: break with open((selectedvideo + 'flag' + '.txt'), 'w') as f: for item in VideoFlag: f.write(str(item)) cap.release() cv2.destroyAllWindows() if __name__ == '__main__': # this is called if this code was not imported ... ie it was directly run # if this is called, that means there is no GUI already running, so we need to create a root root = tk.Tk() root.withdraw() main() ```
2017/03/20
[ "https://Stackoverflow.com/questions/42908846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6614782/" ]
Replacing ``` with open((selectedvideo + 'flag' + '.txt'), 'w') as f: for item in VideoFlag: f.write(str(item)) ``` with ``` # Note that you need to append('a') data to the file instead of writing('w') to it for each iteration. # The last line will be empty string and that is what contains finally. with open((selectedvideo + 'flag' + '.txt'), 'a') as f: for item in VideoFlag: f.write(str(item)) ``` shall resolve the problem.
I think I've solved my problem - so for whatever reason it wasn't running due to my types in my append method - I'd forgotten to convert one of my integers to a string I think, I've reworked it and I think that's solved my issue! Cheers for the input guys! ``` import cv2 import tkinter as tk from tkinter.filedialog import askopenfilename import numpy as np import os import matplotlib.pyplot as plt def frame_diff(prev_frame, cur_frame, next_frame): diff_frames1 = cv2.absdiff(next_frame, cur_frame) diff_frames2 = cv2.absdiff(cur_frame, prev_frame) return cv2.bitwise_and(diff_frames1, diff_frames2) def get_frame(cap): ret, frame = cap.read() if ret == True: scaling_factor = 1 frame = cv2.resize(frame, None, fx = scaling_factor, fy = scaling_factor, interpolation = cv2.INTER_AREA) return cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY) def main(): root = tk.Tk() root.withdraw() MIList = [] VideoFlag = [] selectedvideo = askopenfilename() cap = cv2.VideoCapture(selectedvideo) length = cap.get(cv2.CAP_PROP_FRAME_COUNT) intlength = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) currentframenumber = cap.get(cv2.CAP_PROP_POS_FRAMES) intcurrentframenumber = int(cap.get(cv2.CAP_PROP_POS_FRAMES)) scaling_factor = 1 fourcc = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter((selectedvideo + 'motionindexed.avi'),fourcc, 60.0, (640,478), isColor=False) with open((selectedvideo + 'threshold' + '.txt'), 'r') as readthreshold: threshold = float(readthreshold.readline()) prev_frame = get_frame(cap) cur_frame = get_frame(cap) next_frame = get_frame(cap) while (cap.isOpened()): try: cv2.imshow("Object Movement", frame_diff(prev_frame, cur_frame, next_frame)) prev_frame = cur_frame cur_frame = next_frame next_frame = get_frame(cap) differencesquared = (next_frame-cur_frame)**2 interframedifference = np.sum(differencesquared) MIList.append(interframedifference) print(interframedifference) if interframedifference >= threshold: out.write(cur_frame) VideoFlag.append((str(intcurrentframenumber) + ' ' + '|' + ' ' + '1' + '\n' )) elif interframedifference < threshold: VideoFlag.append((str(intcurrentframenumber) + ' ' + '|' + ' ' + '0' + ' \n')) key = cv2.waitKey(1) if key == ord('q'): break except: break with open((selectedvideo + 'flag' + '.txt'), 'w') as f: for item in VideoFlag: f.write((str(item) + '\n')) print(VideoFlag) cap.release() cv2.destroyAllWindows() if __name__ == '__main__': # this is called if this code was not imported ... ie it was directly run # if this is called, that means there is no GUI already running, so we need to create a root root = tk.Tk() root.withdraw() main() ```
55,471,965
I have this code in c language, it does check if a number written in a certain numeric base, decimal, octal, ..etc is correct, means that it is using characters which belongs to this certain base, for example, an octal number should only use characters [0, 1, 2, 3, 4, 5, 6, 7], it checks all the bases between 2 and 36. The problem is that when I try to substring "base" characters from the total characters it give me a warning saying that `ISO C90 forbids variable length array 'base_symbols'` ``` int checkNumBase(char *num, int base){ char all_symbols[36] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; char base_symbols[base]; int i; unsigned int k; for(i = 0; i<base; i++){ base_symbols[i] = all_symbols[i]; } for(k = 0; k<strlen(num); k++){ if(strchr(base_symbols, num[k]) == NULL){ return 0; } } return 1; } ```
2019/04/02
[ "https://Stackoverflow.com/questions/55471965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1583266/" ]
> > ISO C90 forbids variable length array 'base\_symbols' > > > There's nothing wrong with the code, you get error this because you are using an old, obsolete compiler. You need to get a modern one such as gcc. Please note that older versions of gcc did support newer versions of the language if you compiled correctly: `gcc -std=c11` or `gcc -std=c99`, but used "gnu90" as default, which is C90 + non-standard extensions. Newer versions 5.0 or later default to "gnu11". For example, `-ansi` means "give me 30 years old crap mode" aka C90. Unless you really need C90 for backwards-compatibility reasons, you should be using `gcc -std=c17 -pedantic-errors -Wall -Wextra`. [What is the difference between C, C99, ANSI C and GNU C?](https://stackoverflow.com/questions/17206568/what-is-the-difference-between-c-c99-ansi-c-and-gnu-c)
use `char *index;` then `index = strchr(all_symbols, toupper ( num[k]));` to see if the character is in the set if `index` is in the set it will have a larger address. subtract the smaller address from the larger address to get a positive result then `if ( index && index - all_symbols < base)` then num[k] is valid for that base. `toupper()` is in `ctype.h`
55,471,965
I have this code in c language, it does check if a number written in a certain numeric base, decimal, octal, ..etc is correct, means that it is using characters which belongs to this certain base, for example, an octal number should only use characters [0, 1, 2, 3, 4, 5, 6, 7], it checks all the bases between 2 and 36. The problem is that when I try to substring "base" characters from the total characters it give me a warning saying that `ISO C90 forbids variable length array 'base_symbols'` ``` int checkNumBase(char *num, int base){ char all_symbols[36] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; char base_symbols[base]; int i; unsigned int k; for(i = 0; i<base; i++){ base_symbols[i] = all_symbols[i]; } for(k = 0; k<strlen(num); k++){ if(strchr(base_symbols, num[k]) == NULL){ return 0; } } return 1; } ```
2019/04/02
[ "https://Stackoverflow.com/questions/55471965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1583266/" ]
One simple solution would be to truncate the string ``` char all_symbols[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // length corrected if(base > 36) return 0; all_symbols[base] = 0; //.. as before ```
use `char *index;` then `index = strchr(all_symbols, toupper ( num[k]));` to see if the character is in the set if `index` is in the set it will have a larger address. subtract the smaller address from the larger address to get a positive result then `if ( index && index - all_symbols < base)` then num[k] is valid for that base. `toupper()` is in `ctype.h`
55,471,965
I have this code in c language, it does check if a number written in a certain numeric base, decimal, octal, ..etc is correct, means that it is using characters which belongs to this certain base, for example, an octal number should only use characters [0, 1, 2, 3, 4, 5, 6, 7], it checks all the bases between 2 and 36. The problem is that when I try to substring "base" characters from the total characters it give me a warning saying that `ISO C90 forbids variable length array 'base_symbols'` ``` int checkNumBase(char *num, int base){ char all_symbols[36] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; char base_symbols[base]; int i; unsigned int k; for(i = 0; i<base; i++){ base_symbols[i] = all_symbols[i]; } for(k = 0; k<strlen(num); k++){ if(strchr(base_symbols, num[k]) == NULL){ return 0; } } return 1; } ```
2019/04/02
[ "https://Stackoverflow.com/questions/55471965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1583266/" ]
One simple solution would be to truncate the string ``` char all_symbols[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // length corrected if(base > 36) return 0; all_symbols[base] = 0; //.. as before ```
> > ISO C90 forbids variable length array 'base\_symbols' > > > There's nothing wrong with the code, you get error this because you are using an old, obsolete compiler. You need to get a modern one such as gcc. Please note that older versions of gcc did support newer versions of the language if you compiled correctly: `gcc -std=c11` or `gcc -std=c99`, but used "gnu90" as default, which is C90 + non-standard extensions. Newer versions 5.0 or later default to "gnu11". For example, `-ansi` means "give me 30 years old crap mode" aka C90. Unless you really need C90 for backwards-compatibility reasons, you should be using `gcc -std=c17 -pedantic-errors -Wall -Wextra`. [What is the difference between C, C99, ANSI C and GNU C?](https://stackoverflow.com/questions/17206568/what-is-the-difference-between-c-c99-ansi-c-and-gnu-c)
55,471,965
I have this code in c language, it does check if a number written in a certain numeric base, decimal, octal, ..etc is correct, means that it is using characters which belongs to this certain base, for example, an octal number should only use characters [0, 1, 2, 3, 4, 5, 6, 7], it checks all the bases between 2 and 36. The problem is that when I try to substring "base" characters from the total characters it give me a warning saying that `ISO C90 forbids variable length array 'base_symbols'` ``` int checkNumBase(char *num, int base){ char all_symbols[36] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; char base_symbols[base]; int i; unsigned int k; for(i = 0; i<base; i++){ base_symbols[i] = all_symbols[i]; } for(k = 0; k<strlen(num); k++){ if(strchr(base_symbols, num[k]) == NULL){ return 0; } } return 1; } ```
2019/04/02
[ "https://Stackoverflow.com/questions/55471965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1583266/" ]
> > ISO C90 forbids variable length array 'base\_symbols' > > > There's nothing wrong with the code, you get error this because you are using an old, obsolete compiler. You need to get a modern one such as gcc. Please note that older versions of gcc did support newer versions of the language if you compiled correctly: `gcc -std=c11` or `gcc -std=c99`, but used "gnu90" as default, which is C90 + non-standard extensions. Newer versions 5.0 or later default to "gnu11". For example, `-ansi` means "give me 30 years old crap mode" aka C90. Unless you really need C90 for backwards-compatibility reasons, you should be using `gcc -std=c17 -pedantic-errors -Wall -Wextra`. [What is the difference between C, C99, ANSI C and GNU C?](https://stackoverflow.com/questions/17206568/what-is-the-difference-between-c-c99-ansi-c-and-gnu-c)
The solution by @WeatherVane (i.e. <https://stackoverflow.com/a/55472654/4386427>) is a very good solution for the code posted by OP. The solution below shows an alternative approach that doesn't use string functions. ``` // Calculate the minimum base that allows use of char c int requiredBase(char c) { if (c >= '0' && c <= '9') return c - '0' + 1; // '0' requires base 1, '1' requires base 2, ... if (c >= 'A' && c <= 'Z') return c - 'A' + 11; // 'A' requires base 11, 'B'requires base 12, ... return INT_MAX; } int checkNumBase(char *num, int base){ while (*num) { if (requiredBase(*num) > base) return 0; ++num; } return 1; } ```
55,471,965
I have this code in c language, it does check if a number written in a certain numeric base, decimal, octal, ..etc is correct, means that it is using characters which belongs to this certain base, for example, an octal number should only use characters [0, 1, 2, 3, 4, 5, 6, 7], it checks all the bases between 2 and 36. The problem is that when I try to substring "base" characters from the total characters it give me a warning saying that `ISO C90 forbids variable length array 'base_symbols'` ``` int checkNumBase(char *num, int base){ char all_symbols[36] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; char base_symbols[base]; int i; unsigned int k; for(i = 0; i<base; i++){ base_symbols[i] = all_symbols[i]; } for(k = 0; k<strlen(num); k++){ if(strchr(base_symbols, num[k]) == NULL){ return 0; } } return 1; } ```
2019/04/02
[ "https://Stackoverflow.com/questions/55471965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1583266/" ]
One simple solution would be to truncate the string ``` char all_symbols[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // length corrected if(base > 36) return 0; all_symbols[base] = 0; //.. as before ```
The solution by @WeatherVane (i.e. <https://stackoverflow.com/a/55472654/4386427>) is a very good solution for the code posted by OP. The solution below shows an alternative approach that doesn't use string functions. ``` // Calculate the minimum base that allows use of char c int requiredBase(char c) { if (c >= '0' && c <= '9') return c - '0' + 1; // '0' requires base 1, '1' requires base 2, ... if (c >= 'A' && c <= 'Z') return c - 'A' + 11; // 'A' requires base 11, 'B'requires base 12, ... return INT_MAX; } int checkNumBase(char *num, int base){ while (*num) { if (requiredBase(*num) > base) return 0; ++num; } return 1; } ```
130,974
My whole life, I've heard that large accelerations cause damage to humans (e.g. g-forces in space movies). However, after reading about general relativity, it seems to me that a strong force which affected a body uniformly (such as a very massive object a good distance away) would cause no stresses whatsoever on the human body due to the lack of tidal forces. It seems to me that the usual stresses of acceleration (like those experienced in a spacecraft) are caused by the fact that the engines push the ship, which must then push the person, causing the part of the person touching the ship to be accelerated at a different rate than the rest of his body. Is this true? Or would a uniform acceleration on the body still cause stresses?
2014/08/14
[ "https://physics.stackexchange.com/questions/130974", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/16371/" ]
If you experience such a uniform force, e.g. when an astronaut on a space walk near the ISS (just earth's gravity), you don't experience any forces at all. That's freefall. Even with 10G, you'd experience a rapid freefall, but that is still harmless. It's the hitting the ground which kills you - that's not a uniform force.
You are correct. The concern over accelerations is with respect to a force applied on the surface of your body. Even with something like a uniform fluid to apply nearly even pressure across the body, your interior will always have density differences. Any density differences will create internal forces when the outside of the body is given a net force. A uniform gravitational field or any other magical method of creating a force on every part of the body in such a way as to generate uniform acceleration would not be dangerous. It is the fact that we have no way to control such fields that it's not mentioned.
130,974
My whole life, I've heard that large accelerations cause damage to humans (e.g. g-forces in space movies). However, after reading about general relativity, it seems to me that a strong force which affected a body uniformly (such as a very massive object a good distance away) would cause no stresses whatsoever on the human body due to the lack of tidal forces. It seems to me that the usual stresses of acceleration (like those experienced in a spacecraft) are caused by the fact that the engines push the ship, which must then push the person, causing the part of the person touching the ship to be accelerated at a different rate than the rest of his body. Is this true? Or would a uniform acceleration on the body still cause stresses?
2014/08/14
[ "https://physics.stackexchange.com/questions/130974", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/16371/" ]
If you experience such a uniform force, e.g. when an astronaut on a space walk near the ISS (just earth's gravity), you don't experience any forces at all. That's freefall. Even with 10G, you'd experience a rapid freefall, but that is still harmless. It's the hitting the ground which kills you - that's not a uniform force.
Basically, it appears that, according to the opinions expressed in the answers in this page, there is a difference between acceleration by a distant gravity field, and acceleration, say, against a wall as we crash with our car. Let me restate the opinions expressed here in this form: we lock a person inside a windowless spaceship, then subject the spaceship to acceleration by rockets, or free fall into a gravity field. Then according to the opinions here, it is possible to distinguish between the two circumstances by means of experiments carried out purely inside the spaceship. The statement above contradicts the principle of General Relativity, according to which (in layman's terms) it is impossible to distinguish between these two situations. Your conclusion is revealed as even more strident by the fact that the OP explicitly mentions a *uniform* field, so that we are deprived of the only phenomenon (the deviation of geodesics) which can truly distinguish between the two different circumstances. It also contradicts common experience: astronauts undergo a period of training in a centrifuge, where they are subject to collapses, loss of conscience, nausea, vomit. They are also trained in airplanes in free fall, which are better known by their nickname, `the house of vomit`. It is revealing, at least to me, that the effects of free-fall or of a centrifuge are indeed the same, except perhaps for the severity of the symptoms; but there is little to be surprised there, given that the centrifuge is not limited to the modest acceleration, $1\; g$, which can be achieved during free fall in the Earth's gravitational field.
130,974
My whole life, I've heard that large accelerations cause damage to humans (e.g. g-forces in space movies). However, after reading about general relativity, it seems to me that a strong force which affected a body uniformly (such as a very massive object a good distance away) would cause no stresses whatsoever on the human body due to the lack of tidal forces. It seems to me that the usual stresses of acceleration (like those experienced in a spacecraft) are caused by the fact that the engines push the ship, which must then push the person, causing the part of the person touching the ship to be accelerated at a different rate than the rest of his body. Is this true? Or would a uniform acceleration on the body still cause stresses?
2014/08/14
[ "https://physics.stackexchange.com/questions/130974", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/16371/" ]
In short, you're correct: it's not the fall (uniform acceleration) that kills you, but the sudden stop at the bottom (large contact acceleration). But just for fun I'll point out that it's not clear what "uniform acceleration" even means. To operationally define (i.e., measure) acceleration you need an accelerometer. An example is a rigid sphere with a smaller rigid ball suspended in the center of it with springs. When the sphere accelerates, the springs compress and expand, and you can read off the magnitude and direction of the acceleration from that. But this only works if the acceleration is via a contact force. If the outer sphere and inner ball are accelerated together by the external force, so that the ball remains at the center, then this device will register no acceleration. The same argument applies to any mechanical accelerometer. In Newtonian physics that's the end of the story, but in special relativity you can build a better accelerometer using light. Suspend the ball with rigid rods instead of springs, put a mirror finish on the inside of the sphere, emit an isotropic pulse of light from the ball, and time its return. If you are moving inertially it will all arrive back at the same time, but if you are accelerating it will not. This works as long as the acceleration is nongravitational, but fails for gravitational acceleration in general relativity, since that bends light too. [It can detect gravitational tidal forces, but not vector acceleration.] If you take a hardline view of what "uniform" means, you're forced into the conclusion that uniform acceleration not only doesn't damage you, it doesn't do *anything*, and ought to be treated as physically equivalent to no acceleration at all. This is one way of understanding the equivalence principle. In GR (unlike Newtonian physics) only gravitation can accelerate "uniformly" in this sense; anything else can be detected by the light-based accelerometer.
You will answer your question if you understand *inertia*: mass tend to oppose resistance to movement. *Example*: In a lift going upwards e.g., your feet are lifted while your head "wants" to remain at the same place (in a galilean reference frame). In the frame of the lift, everything happens as if a force ($m\_\text{head}\ddot x$, roughly) was exerted on your head, downwards. The heavier is your head, the greater is this force, which can, of course, damage your poor little body.
130,974
My whole life, I've heard that large accelerations cause damage to humans (e.g. g-forces in space movies). However, after reading about general relativity, it seems to me that a strong force which affected a body uniformly (such as a very massive object a good distance away) would cause no stresses whatsoever on the human body due to the lack of tidal forces. It seems to me that the usual stresses of acceleration (like those experienced in a spacecraft) are caused by the fact that the engines push the ship, which must then push the person, causing the part of the person touching the ship to be accelerated at a different rate than the rest of his body. Is this true? Or would a uniform acceleration on the body still cause stresses?
2014/08/14
[ "https://physics.stackexchange.com/questions/130974", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/16371/" ]
I have a feeling, that you may be asking whether gravity is a force or an acceleration? In the confines of Newtonian mechanics, it's much better to talk about gravity in terms of acceleration, because point-like, free falling test masses responding to a large, gravitating body do not experience any actual forces acting on them. It's only a slight of hand, where we transform F=m\*(a + a\_gravity) into F=m\*a + m\*a\_gravity = m\*a + F\_gravity, that gravity starts looking like a force. That's a useful trick for engineering applications, but it misses the actual physics. This, of course, is mended beautifully in general relativity. As for the question of how to accelerate a human body strongly in a rocket or in an electromagnetic mass driver, (where we do have a real accelerating force)... one can theoretically submerge the body in a liquid of equal average density and fill the lungs with an oxygenated liquid. I do not have any actual research on the limits of this, but I would guesstimate that one can probably survive sustained acceleration beyond 50g with such an approach without undue injury, if necessary. Why one would want to torture oneself in such a way is, of course, another very sensible question. I don't see any practical applications worth pursuing, maybe with exception of "landing" a one way mission on Jupiter (i.e. a pressure vessel that is tethered to a balloon and that could float for months or years in the atmosphere of the planet). Jupiter has a surface gravity of about 2.5g and an astronaut submerged in a tank could certainly survive more comfortably (and maybe longer), even with dry lungs.
You will answer your question if you understand *inertia*: mass tend to oppose resistance to movement. *Example*: In a lift going upwards e.g., your feet are lifted while your head "wants" to remain at the same place (in a galilean reference frame). In the frame of the lift, everything happens as if a force ($m\_\text{head}\ddot x$, roughly) was exerted on your head, downwards. The heavier is your head, the greater is this force, which can, of course, damage your poor little body.
130,974
My whole life, I've heard that large accelerations cause damage to humans (e.g. g-forces in space movies). However, after reading about general relativity, it seems to me that a strong force which affected a body uniformly (such as a very massive object a good distance away) would cause no stresses whatsoever on the human body due to the lack of tidal forces. It seems to me that the usual stresses of acceleration (like those experienced in a spacecraft) are caused by the fact that the engines push the ship, which must then push the person, causing the part of the person touching the ship to be accelerated at a different rate than the rest of his body. Is this true? Or would a uniform acceleration on the body still cause stresses?
2014/08/14
[ "https://physics.stackexchange.com/questions/130974", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/16371/" ]
I have a feeling, that you may be asking whether gravity is a force or an acceleration? In the confines of Newtonian mechanics, it's much better to talk about gravity in terms of acceleration, because point-like, free falling test masses responding to a large, gravitating body do not experience any actual forces acting on them. It's only a slight of hand, where we transform F=m\*(a + a\_gravity) into F=m\*a + m\*a\_gravity = m\*a + F\_gravity, that gravity starts looking like a force. That's a useful trick for engineering applications, but it misses the actual physics. This, of course, is mended beautifully in general relativity. As for the question of how to accelerate a human body strongly in a rocket or in an electromagnetic mass driver, (where we do have a real accelerating force)... one can theoretically submerge the body in a liquid of equal average density and fill the lungs with an oxygenated liquid. I do not have any actual research on the limits of this, but I would guesstimate that one can probably survive sustained acceleration beyond 50g with such an approach without undue injury, if necessary. Why one would want to torture oneself in such a way is, of course, another very sensible question. I don't see any practical applications worth pursuing, maybe with exception of "landing" a one way mission on Jupiter (i.e. a pressure vessel that is tethered to a balloon and that could float for months or years in the atmosphere of the planet). Jupiter has a surface gravity of about 2.5g and an astronaut submerged in a tank could certainly survive more comfortably (and maybe longer), even with dry lungs.
Basically, it appears that, according to the opinions expressed in the answers in this page, there is a difference between acceleration by a distant gravity field, and acceleration, say, against a wall as we crash with our car. Let me restate the opinions expressed here in this form: we lock a person inside a windowless spaceship, then subject the spaceship to acceleration by rockets, or free fall into a gravity field. Then according to the opinions here, it is possible to distinguish between the two circumstances by means of experiments carried out purely inside the spaceship. The statement above contradicts the principle of General Relativity, according to which (in layman's terms) it is impossible to distinguish between these two situations. Your conclusion is revealed as even more strident by the fact that the OP explicitly mentions a *uniform* field, so that we are deprived of the only phenomenon (the deviation of geodesics) which can truly distinguish between the two different circumstances. It also contradicts common experience: astronauts undergo a period of training in a centrifuge, where they are subject to collapses, loss of conscience, nausea, vomit. They are also trained in airplanes in free fall, which are better known by their nickname, `the house of vomit`. It is revealing, at least to me, that the effects of free-fall or of a centrifuge are indeed the same, except perhaps for the severity of the symptoms; but there is little to be surprised there, given that the centrifuge is not limited to the modest acceleration, $1\; g$, which can be achieved during free fall in the Earth's gravitational field.
130,974
My whole life, I've heard that large accelerations cause damage to humans (e.g. g-forces in space movies). However, after reading about general relativity, it seems to me that a strong force which affected a body uniformly (such as a very massive object a good distance away) would cause no stresses whatsoever on the human body due to the lack of tidal forces. It seems to me that the usual stresses of acceleration (like those experienced in a spacecraft) are caused by the fact that the engines push the ship, which must then push the person, causing the part of the person touching the ship to be accelerated at a different rate than the rest of his body. Is this true? Or would a uniform acceleration on the body still cause stresses?
2014/08/14
[ "https://physics.stackexchange.com/questions/130974", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/16371/" ]
You are correct. The concern over accelerations is with respect to a force applied on the surface of your body. Even with something like a uniform fluid to apply nearly even pressure across the body, your interior will always have density differences. Any density differences will create internal forces when the outside of the body is given a net force. A uniform gravitational field or any other magical method of creating a force on every part of the body in such a way as to generate uniform acceleration would not be dangerous. It is the fact that we have no way to control such fields that it's not mentioned.
You will answer your question if you understand *inertia*: mass tend to oppose resistance to movement. *Example*: In a lift going upwards e.g., your feet are lifted while your head "wants" to remain at the same place (in a galilean reference frame). In the frame of the lift, everything happens as if a force ($m\_\text{head}\ddot x$, roughly) was exerted on your head, downwards. The heavier is your head, the greater is this force, which can, of course, damage your poor little body.
130,974
My whole life, I've heard that large accelerations cause damage to humans (e.g. g-forces in space movies). However, after reading about general relativity, it seems to me that a strong force which affected a body uniformly (such as a very massive object a good distance away) would cause no stresses whatsoever on the human body due to the lack of tidal forces. It seems to me that the usual stresses of acceleration (like those experienced in a spacecraft) are caused by the fact that the engines push the ship, which must then push the person, causing the part of the person touching the ship to be accelerated at a different rate than the rest of his body. Is this true? Or would a uniform acceleration on the body still cause stresses?
2014/08/14
[ "https://physics.stackexchange.com/questions/130974", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/16371/" ]
In short, you're correct: it's not the fall (uniform acceleration) that kills you, but the sudden stop at the bottom (large contact acceleration). But just for fun I'll point out that it's not clear what "uniform acceleration" even means. To operationally define (i.e., measure) acceleration you need an accelerometer. An example is a rigid sphere with a smaller rigid ball suspended in the center of it with springs. When the sphere accelerates, the springs compress and expand, and you can read off the magnitude and direction of the acceleration from that. But this only works if the acceleration is via a contact force. If the outer sphere and inner ball are accelerated together by the external force, so that the ball remains at the center, then this device will register no acceleration. The same argument applies to any mechanical accelerometer. In Newtonian physics that's the end of the story, but in special relativity you can build a better accelerometer using light. Suspend the ball with rigid rods instead of springs, put a mirror finish on the inside of the sphere, emit an isotropic pulse of light from the ball, and time its return. If you are moving inertially it will all arrive back at the same time, but if you are accelerating it will not. This works as long as the acceleration is nongravitational, but fails for gravitational acceleration in general relativity, since that bends light too. [It can detect gravitational tidal forces, but not vector acceleration.] If you take a hardline view of what "uniform" means, you're forced into the conclusion that uniform acceleration not only doesn't damage you, it doesn't do *anything*, and ought to be treated as physically equivalent to no acceleration at all. This is one way of understanding the equivalence principle. In GR (unlike Newtonian physics) only gravitation can accelerate "uniformly" in this sense; anything else can be detected by the light-based accelerometer.
Basically, it appears that, according to the opinions expressed in the answers in this page, there is a difference between acceleration by a distant gravity field, and acceleration, say, against a wall as we crash with our car. Let me restate the opinions expressed here in this form: we lock a person inside a windowless spaceship, then subject the spaceship to acceleration by rockets, or free fall into a gravity field. Then according to the opinions here, it is possible to distinguish between the two circumstances by means of experiments carried out purely inside the spaceship. The statement above contradicts the principle of General Relativity, according to which (in layman's terms) it is impossible to distinguish between these two situations. Your conclusion is revealed as even more strident by the fact that the OP explicitly mentions a *uniform* field, so that we are deprived of the only phenomenon (the deviation of geodesics) which can truly distinguish between the two different circumstances. It also contradicts common experience: astronauts undergo a period of training in a centrifuge, where they are subject to collapses, loss of conscience, nausea, vomit. They are also trained in airplanes in free fall, which are better known by their nickname, `the house of vomit`. It is revealing, at least to me, that the effects of free-fall or of a centrifuge are indeed the same, except perhaps for the severity of the symptoms; but there is little to be surprised there, given that the centrifuge is not limited to the modest acceleration, $1\; g$, which can be achieved during free fall in the Earth's gravitational field.
130,974
My whole life, I've heard that large accelerations cause damage to humans (e.g. g-forces in space movies). However, after reading about general relativity, it seems to me that a strong force which affected a body uniformly (such as a very massive object a good distance away) would cause no stresses whatsoever on the human body due to the lack of tidal forces. It seems to me that the usual stresses of acceleration (like those experienced in a spacecraft) are caused by the fact that the engines push the ship, which must then push the person, causing the part of the person touching the ship to be accelerated at a different rate than the rest of his body. Is this true? Or would a uniform acceleration on the body still cause stresses?
2014/08/14
[ "https://physics.stackexchange.com/questions/130974", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/16371/" ]
If you experience such a uniform force, e.g. when an astronaut on a space walk near the ISS (just earth's gravity), you don't experience any forces at all. That's freefall. Even with 10G, you'd experience a rapid freefall, but that is still harmless. It's the hitting the ground which kills you - that's not a uniform force.
You will answer your question if you understand *inertia*: mass tend to oppose resistance to movement. *Example*: In a lift going upwards e.g., your feet are lifted while your head "wants" to remain at the same place (in a galilean reference frame). In the frame of the lift, everything happens as if a force ($m\_\text{head}\ddot x$, roughly) was exerted on your head, downwards. The heavier is your head, the greater is this force, which can, of course, damage your poor little body.
130,974
My whole life, I've heard that large accelerations cause damage to humans (e.g. g-forces in space movies). However, after reading about general relativity, it seems to me that a strong force which affected a body uniformly (such as a very massive object a good distance away) would cause no stresses whatsoever on the human body due to the lack of tidal forces. It seems to me that the usual stresses of acceleration (like those experienced in a spacecraft) are caused by the fact that the engines push the ship, which must then push the person, causing the part of the person touching the ship to be accelerated at a different rate than the rest of his body. Is this true? Or would a uniform acceleration on the body still cause stresses?
2014/08/14
[ "https://physics.stackexchange.com/questions/130974", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/16371/" ]
If you experience such a uniform force, e.g. when an astronaut on a space walk near the ISS (just earth's gravity), you don't experience any forces at all. That's freefall. Even with 10G, you'd experience a rapid freefall, but that is still harmless. It's the hitting the ground which kills you - that's not a uniform force.
In short, you're correct: it's not the fall (uniform acceleration) that kills you, but the sudden stop at the bottom (large contact acceleration). But just for fun I'll point out that it's not clear what "uniform acceleration" even means. To operationally define (i.e., measure) acceleration you need an accelerometer. An example is a rigid sphere with a smaller rigid ball suspended in the center of it with springs. When the sphere accelerates, the springs compress and expand, and you can read off the magnitude and direction of the acceleration from that. But this only works if the acceleration is via a contact force. If the outer sphere and inner ball are accelerated together by the external force, so that the ball remains at the center, then this device will register no acceleration. The same argument applies to any mechanical accelerometer. In Newtonian physics that's the end of the story, but in special relativity you can build a better accelerometer using light. Suspend the ball with rigid rods instead of springs, put a mirror finish on the inside of the sphere, emit an isotropic pulse of light from the ball, and time its return. If you are moving inertially it will all arrive back at the same time, but if you are accelerating it will not. This works as long as the acceleration is nongravitational, but fails for gravitational acceleration in general relativity, since that bends light too. [It can detect gravitational tidal forces, but not vector acceleration.] If you take a hardline view of what "uniform" means, you're forced into the conclusion that uniform acceleration not only doesn't damage you, it doesn't do *anything*, and ought to be treated as physically equivalent to no acceleration at all. This is one way of understanding the equivalence principle. In GR (unlike Newtonian physics) only gravitation can accelerate "uniformly" in this sense; anything else can be detected by the light-based accelerometer.
130,974
My whole life, I've heard that large accelerations cause damage to humans (e.g. g-forces in space movies). However, after reading about general relativity, it seems to me that a strong force which affected a body uniformly (such as a very massive object a good distance away) would cause no stresses whatsoever on the human body due to the lack of tidal forces. It seems to me that the usual stresses of acceleration (like those experienced in a spacecraft) are caused by the fact that the engines push the ship, which must then push the person, causing the part of the person touching the ship to be accelerated at a different rate than the rest of his body. Is this true? Or would a uniform acceleration on the body still cause stresses?
2014/08/14
[ "https://physics.stackexchange.com/questions/130974", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/16371/" ]
You are correct. The concern over accelerations is with respect to a force applied on the surface of your body. Even with something like a uniform fluid to apply nearly even pressure across the body, your interior will always have density differences. Any density differences will create internal forces when the outside of the body is given a net force. A uniform gravitational field or any other magical method of creating a force on every part of the body in such a way as to generate uniform acceleration would not be dangerous. It is the fact that we have no way to control such fields that it's not mentioned.
Basically, it appears that, according to the opinions expressed in the answers in this page, there is a difference between acceleration by a distant gravity field, and acceleration, say, against a wall as we crash with our car. Let me restate the opinions expressed here in this form: we lock a person inside a windowless spaceship, then subject the spaceship to acceleration by rockets, or free fall into a gravity field. Then according to the opinions here, it is possible to distinguish between the two circumstances by means of experiments carried out purely inside the spaceship. The statement above contradicts the principle of General Relativity, according to which (in layman's terms) it is impossible to distinguish between these two situations. Your conclusion is revealed as even more strident by the fact that the OP explicitly mentions a *uniform* field, so that we are deprived of the only phenomenon (the deviation of geodesics) which can truly distinguish between the two different circumstances. It also contradicts common experience: astronauts undergo a period of training in a centrifuge, where they are subject to collapses, loss of conscience, nausea, vomit. They are also trained in airplanes in free fall, which are better known by their nickname, `the house of vomit`. It is revealing, at least to me, that the effects of free-fall or of a centrifuge are indeed the same, except perhaps for the severity of the symptoms; but there is little to be surprised there, given that the centrifuge is not limited to the modest acceleration, $1\; g$, which can be achieved during free fall in the Earth's gravitational field.
69,514,919
I have this error in javascript code : (JavaScript error (Uncaught SyntaxError: Unexpected end of input)) I saw many questions same as this, but could not solve my error, so now ask help My code is so simple as follows; ``` const playBtn = document.querySelector('.play') const audio = new Audio('/sounds/1M.mp4') function playAudio(){ for (i = 0; i < 5; i++){ audio.play(); audio.loop = true; audio.playbackRate = 2; } playBtn.addEventListener('click', ()=> { playAudio() }) ``` Why this kind of error comes out from my code? Uncaught SyntaxError: Unexpected end of input) : audio.js 14 (line 14 is the empty line next the end of parenthesis '})' How the empty line gives an error ?
2021/10/10
[ "https://Stackoverflow.com/questions/69514919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13957027/" ]
Got Kibana working with plugins by using a custom container image dockerfile ``` FROM docker.elastic.co/kibana/kibana:7.11.2 RUN /usr/share/kibana/bin/kibana-plugin install https://github.com/fbaligand/kibana-enhanced-table/releases/download/v1.11.2/enhanced-table-1.11.2_7.11.2.zip RUN /usr/share/kibana/bin/kibana --optimize ``` yaml ``` apiVersion: kibana.k8s.elastic.co/v1 kind: Kibana metadata: name: quickstart spec: version: 7.11.2 image: my-conatiner-path/kibana-with-plugins:7.11.2 count: 1 elasticsearchRef: name: quickstart ```
Building you own image would sure work, though it could be avoided in that case. Your initContainer is pretty much what you were looking for. With one exception: you need to add some emptyDir volume. Mount it to both your initContainer and regular kibana container, sharing the plugins you would install during init. Although I'm not familiar with the Kibana CR, here's how I would do this with elasti.co official images: ``` spec: template: spec: containers: - name: kibana image: official-kibana:x.y.z securityContext: runAsUser: 1000 volumeMounts: - mountPath: /usr/share/kibana/plugins name: plugins initContainers: - command: - /bin/bash - -c - | set -xe if ! ./bin/kibana-plugin list | grep prometheus-exporter >/dev/null; then if ! ./bin/kibana-plugin install "https://github.com/pjhampton/kibana-prometheus-exporter/releases/download/7.12.1/kibanaPrometheusExporter-7.12.1.zip"; then echo WARNING: failed to install Kibana exporter plugin fi fi name: init image: official-kibana:x.y.z securityContext: runAsUser: 1000 volumeMounts: - mountPath: /usr/share/kibana/plugins name: plugins volumes: - emptyDir: {} name: plugins ```
19,055,539
``` $galleryData = []; foreach($input['gallery'] as $galleryImg) { } ``` I want to push in the galleryData array, a keyed array. How can I do this? I've tried: ``` $galleryData[] = ['name'=>$galleryImg['file']['name'], 'comment'=> $galleryImg['file']['comment'], 'youtube'=> $galleryImg['file']['youtube']]; ``` But no luck.
2013/09/27
[ "https://Stackoverflow.com/questions/19055539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1013512/" ]
``` $galleryData[] = array( 'name'=>$galleryImg['file']['name'], 'comment'=> $galleryImg['file']['comment'], 'youtube'=> $galleryImg['file']['youtube'] ); ``` should work
Try this: ``` $galleryData = array_map(function($a) {return $a['file'];},$input['gallery']); ``` If there are other keys, try this variant: ``` $allowedKeys = array("name","comment","youtube"); $galleryData = array_map(function($a) use ($allowedKeys) { return array_intersect_key($a['file'],array_flip($allowedKeys)); },$input['gallery']); ``` Taking into consideration your update, there's no longer such a shortcut. Try this: ``` $galleryData = array_map(function($a) { return array( "comment"=>$a['comment'], "name"=>$a['file']['name'], "youtube"=>$a['file']['youtube'] ); },$input['gallery']); ```
17,151,709
I have a package on my TeamCity NuGet feed, built by TeamCity, but a dependent TC project cannot see it during package restore. > > [14:05:02][Exec] E:\TeamCity-BuildAgent\work\62023563850993a7\Web.nuget\nuget.targets(88, 9): Unable to find version '1.0.17.0' of package 'MarkLogicManager40'. > > > [14:05:02][Exec] E:\TeamCity-BuildAgent\work\62023563850993a7\Web.nuget\nuget.targets(88, 9): error MSB3073: The command ""E:\TeamCity-BuildAgent\work\62023563850993a7\Web.nuget\nuget.exe" install "E:\TeamCity-BuildAgent\work\62023563850993a7\ProductMvc\packages.config" -source "" -RequireConsent -solutionDir "E:\TeamCity-BuildAgent\work\62023563850993a7\Web\ "" exited with code 1. > > > Note that the `source` parameter in the NuGet command line is empty. Could this be the cause?
2013/06/17
[ "https://Stackoverflow.com/questions/17151709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/107783/" ]
As of today, NuGet.targets has the following way to specify custom feed(s): ``` <ItemGroup Condition=" '$(PackageSources)' == '' "> <!-- Package sources used to restore packages. By default, registered sources under %APPDATA%\NuGet\NuGet.Config will be used --> <!-- The official NuGet package source (https://nuget.org/api/v2/) will be excluded if package sources are specified and it does not appear in the list --> <PackageSource Include="https://nuget.org/api/v2/" /> <PackageSource Include="\\MyShare" /> <PackageSource Include="http://MyServer/" /> </ItemGroup> ``` Another option is to put **NuGet.config** next to the solution file: ``` <?xml version="1.0" encoding="utf-8"?> <configuration> <packageSources> <add key="nuget.org" value="https://www.nuget.org/api/v2/" /> <add key="MyShare" value="\\MyShare" /> <add key="MyServer" value="http://MyServer" /> </packageSources> <activePackageSource> <add key="All" value="(Aggregate source)" /> </activePackageSource> </configuration> ```
Apparently NuGet custom feeds are set not via anything in the solution or project files, or nuget.config in the solution, but in the nuget.config in the developer's profile. Over on TeamCity, there's no check by the agent of this config file, or writing to it, to ensure it contains the feed for the TeamCity server itself. So package restore on TC using a custom TC feed won't 'just work'. You have to waste hundreds of pounds of client's money chasing your tail to discover all this and then set/copy your nuget.config from your profile into the profile of the user account running the build agent. Horrible.
54,315
Is there any relationship between salesforce Reports and Folder objects, to determine the content of the folder or find the residing folder of a particular report ?
2014/10/27
[ "https://salesforce.stackexchange.com/questions/54315", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/10578/" ]
The [Report object](http://www.salesforce.com/developer/docs/api/Content/sforce_api_objects_report.htm) does not have a **FolderId** field like **Dashboard**, **Document** and **EmailTemplate** objects. But as you can see from this their does exist a **child relationship** between **[Folder](http://www.salesforce.com/developer/docs/api/Content/sforce_api_objects_folder.htm)** and **Report**, which is in fact determined by the OwnerId of the Report. Thus once you know the folder Id you can query for reports that are contained within it. ``` SELECT Id, DeveloperName,Name,Type FROM Folder WHERE Name = 'My Test Folder' And Type = 'Report' ``` Then query by OwernId with the Folder Id returned e.g. ``` SELECT Description,DeveloperName FROM Report WHERE OwnerId = '00lG0000000TwG5IAK' ``` ![enter image description here](https://i.stack.imgur.com/AksyA.png)
Reports can be created in public folders or in personal folders. It all depends on whether you want to make them available for others to use. For more details on the subject, you might want to look at [Using the Reports Tab](https://developer.salesforce.com/docs/atlas.en-us.salesforce_reports_enhanced_reports_tab_tipsheet.meta/salesforce_reports_enhanced_reports_tab_tipsheet/).
54,315
Is there any relationship between salesforce Reports and Folder objects, to determine the content of the folder or find the residing folder of a particular report ?
2014/10/27
[ "https://salesforce.stackexchange.com/questions/54315", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/10578/" ]
The [Report object](http://www.salesforce.com/developer/docs/api/Content/sforce_api_objects_report.htm) does not have a **FolderId** field like **Dashboard**, **Document** and **EmailTemplate** objects. But as you can see from this their does exist a **child relationship** between **[Folder](http://www.salesforce.com/developer/docs/api/Content/sforce_api_objects_folder.htm)** and **Report**, which is in fact determined by the OwnerId of the Report. Thus once you know the folder Id you can query for reports that are contained within it. ``` SELECT Id, DeveloperName,Name,Type FROM Folder WHERE Name = 'My Test Folder' And Type = 'Report' ``` Then query by OwernId with the Folder Id returned e.g. ``` SELECT Description,DeveloperName FROM Report WHERE OwnerId = '00lG0000000TwG5IAK' ``` ![enter image description here](https://i.stack.imgur.com/AksyA.png)
you could create a custom report type on report object and by editing its layout, using folder lookup relationship pull any folder fields needed. Creating a report using this report type will show folder details along with report's.
54,315
Is there any relationship between salesforce Reports and Folder objects, to determine the content of the folder or find the residing folder of a particular report ?
2014/10/27
[ "https://salesforce.stackexchange.com/questions/54315", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/10578/" ]
The [Report object](http://www.salesforce.com/developer/docs/api/Content/sforce_api_objects_report.htm) does not have a **FolderId** field like **Dashboard**, **Document** and **EmailTemplate** objects. But as you can see from this their does exist a **child relationship** between **[Folder](http://www.salesforce.com/developer/docs/api/Content/sforce_api_objects_folder.htm)** and **Report**, which is in fact determined by the OwnerId of the Report. Thus once you know the folder Id you can query for reports that are contained within it. ``` SELECT Id, DeveloperName,Name,Type FROM Folder WHERE Name = 'My Test Folder' And Type = 'Report' ``` Then query by OwernId with the Folder Id returned e.g. ``` SELECT Description,DeveloperName FROM Report WHERE OwnerId = '00lG0000000TwG5IAK' ``` ![enter image description here](https://i.stack.imgur.com/AksyA.png)
If you don't need to access Reports or Folders in code then you can simply use the 'Reports' administrative Report Type, to view all public reports and any in your My Personal Reports folder, along with the folders that they're contained in. You'll need the 'View Setup and Configuration' permission in order to access this Report Type [see here](https://help.salesforce.com/HTViewSolution?id=000133762&language=en_US).
122,056
On the Am/G: Is this an Am with 2nd inversion and an alternative bass note G? On the C/G: Is this a C with an alternative bass note G? [![enter image description here](https://i.stack.imgur.com/UErN3.png)](https://i.stack.imgur.com/UErN3.png)
2022/03/26
[ "https://music.stackexchange.com/questions/122056", "https://music.stackexchange.com", "https://music.stackexchange.com/users/69074/" ]
Inversions are always named from which note is *lowest*. Since in the Am bar, the lowest note is G (signified by the slash G), it actually makes an Am7 chord, and, since the G is lowest, that inversion is called 3rd. With C/G, the lowest note is G, under a C major chord. That gives it the name 2nd inversion. It matters not in which order the higher notes are played or written, it's a always the lowest note which defines the inversion. Root lowest = *Root*, 3rd lowest = 1st inversion, 5th lowest = 2nd inversion, 7th lowest = 3rd inversion. Occasionally, the lowest note is not from a simple chord, so it's easier to use a slash. As in C/D. not really an inversion then, though.
C/G = CEG over G = G,C,E ...yes! (0 2nd inversion -> 5th = basstone Am/G= ACE above G = G,A,C,E. This is the 3rd inversion of Am7 Am7 root-position = A,C,E,G 1st inversion = C,E,G,A (basstone = 3rd) 2nd inversion = E,G,A,C (basstone = 5th) 3rd inversion = G,A,C,E (basstone = 7th)
122,056
On the Am/G: Is this an Am with 2nd inversion and an alternative bass note G? On the C/G: Is this a C with an alternative bass note G? [![enter image description here](https://i.stack.imgur.com/UErN3.png)](https://i.stack.imgur.com/UErN3.png)
2022/03/26
[ "https://music.stackexchange.com/questions/122056", "https://music.stackexchange.com", "https://music.stackexchange.com/users/69074/" ]
Am/G is an Am chord over the bass note G. It differs from a last-inversion Am7 chord in that the 7th, G, is specifically NOT included anywhere except as the lowest note. There's no such complication with C/G. G is part of a C major triad, so C/G is simply a second inversion C major chord.
C/G = CEG over G = G,C,E ...yes! (0 2nd inversion -> 5th = basstone Am/G= ACE above G = G,A,C,E. This is the 3rd inversion of Am7 Am7 root-position = A,C,E,G 1st inversion = C,E,G,A (basstone = 3rd) 2nd inversion = E,G,A,C (basstone = 5th) 3rd inversion = G,A,C,E (basstone = 7th)
27,584,004
I have a number n, let's say n = 5. I've calculated n! like this: 1\*2\*3\*4\*5 = 1\*2\*3\*20 = 1\*2\*60 = 1\*120 = 120; ``` int factorial(int y){ int z1 = 0; if (y != 0) goto L1; goto L7; L1: z1 = equals(y); z1 = z1 - 1; if (z1 != 0) goto L5; goto L7; L5: y = multiplication(y, z1); L2: z1 = z1 - 1; if (z1 != 0) goto L3; goto E; L3: y = multiplication(y, z1); z1 = z1 - 1; if (z1 != 0) goto L3; goto E; E: return y; L7: return 1; } ``` What is it's time complexity? Thank you.
2014/12/20
[ "https://Stackoverflow.com/questions/27584004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4016912/" ]
Linear. Your obfuscating use of labels and `goto` can be directly translated into: ``` int factorial(int y){ int z1 = 0; if (y == 0) return 1; z1 = equals(y); z1 = z1 - 1; if (z1 == 0) return 1; y = multiplication(y, z1); z1 = z1 - 1; if (z1 == 0) return y; do { y = multiplication(y, z1); z1 = z1 - 1; } while (z1 != 0) return y; } ``` That `while` loop will execute `y - 2` times, which is linear in the value of `y`. Thus the runtime of the function is linear. But I think this linear code is much simpler: ``` int factorial(int y) { // factorial(0) and factorial(1) are just 1 if (y < 2) return 1; // Now just calculate y * (y - 1) * (y - 2) * ... * 4 * 3 * 2 int f = y; while (--y > 1) { f *= y; } return f; } ```
``` int factorial(int n){ if(n==1 || n==0) return 1; return n*(factorial(n-1)); ``` } This implementation has T(n)=O(n). I think that also your implementation has the same complexity because the "do while" cycle is done n times.
64,265,606
I am passing multiple values in a list and I want to filter my queryset with this values. I know about Q object but I don't know how to add filters together. I thought of something like: ``` categories = ['1','3','4'] for category in categories: Q+= Q(id = category) ``` and after that I would filter my queryset `queryset.filter(Q)`
2020/10/08
[ "https://Stackoverflow.com/questions/64265606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13534726/" ]
Use the following `xpath` to find the element. ``` driver.find_element_by_xpath('//td[@class="datepickerSelected"]/a[./span[text()="8"]]').click() ```
To get today's date, you can use `datetime`. See [the docs](https://docs.python.org/3/library/datetime.html) for more info. Once you have it, you can insert the day into the locator and click the element. There are a couple problems with your locator vs the HTML that you posted. ``` //td[@class="datepickerSelected"]/a[text()="8"] ``` 1. This is looking for a TD that has a class "datepickerSelected" but it doesn't exist in the HTML you posted. I'm assuming that class only appears after you've selected a date but when you first enter the page, this won't be true so we can't use that class to locate the day we want. 2. The `text()` method finds text inside of the element specified, in this case an A tag. If you look at the HTML, the text is actually inside the SPAN child of the A tag. There are a couple ways to deal with this. You can change that part of the locator to be `/a/span[text()="8"]` or use `.` which "flattens" the text from all child elements, e.g. `/a[.="8"]`. Either way will work. Another problem you will have to deal with is if the day is late or early in the month, then it shows up twice in the HTML, e.g. 2 or 28. To get the right one, you need to specify the day in the SPAN under a TD with an empty class. The wrong ones have a TD with the class `datepickerNotInMonth`. Taking all this into account, here's the code I would use. ``` import datetime today = datetime.datetime.now().day driver.find_element_by_xpath(f'//td[@class=""]/a[.="{today}"]').click() ``` The locator finds a TD that contains an empty class that has a child A that contains (the flattened) text corresponding to today's day.
43,571,622
First attempts at getting firebase push notifications to work isn't going so well. I have followed the tutorial listed [here](https://www.codementor.io/flame3/send-push-notifications-to-android-with-firebase-du10860kb) to set it up, but whenever I try and send a notification, the app "closes unexpecedly", and the logical throws the following crash information: Logcat: ``` --------- beginning of crash 04-23 23:04:28.081 7395-7395/com.surfdogdesigns.pandsi E/AndroidRuntime: FATAL EXCEPTION: main Process: com.surfdogdesigns.pandsi, PID: 7395 java.lang.RuntimeException: Unable to instantiate service com.surfdogdesigns.pandsi.MainActivity$MyFirebaseMessagingService: java.lang.InstantiationException: class com.surfdogdesigns.pandsi.MainActivity$MyFirebaseMessagingService has no zero argument constructor at android.app.ActivityThread.handleCreateService(ActivityThread.java:2746) at android.app.ActivityThread.access$1800(ActivityThread.java:151) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1386) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5254) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) Caused by: java.lang.InstantiationException: class com.surfdogdesigns.pandsi.MainActivity$MyFirebaseMessagingService has no zero argument constructor at java.lang.Class.newInstance(Class.java:1597) at android.app.ActivityThread.handleCreateService(ActivityThread.java:2743) at android.app.ActivityThread.access$1800(ActivityThread.java:151)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1386)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:135)  at android.app.ActivityThread.main(ActivityThread.java:5254)  at java.lang.reflect.Method.invoke(Native Method)  at java.lang.reflect.Method.invoke(Method.java:372)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)  Caused by: java.lang.NoSuchMethodException: <init> [] at java.lang.Class.getConstructor(Class.java:531) at java.lang.Class.getDeclaredConstructor(Class.java:510) at java.lang.Class.newInstance(Class.java:1595) at android.app.ActivityThread.handleCreateService(ActivityThread.java:2743)  at android.app.ActivityThread.access$1800(ActivityThread.java:151)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1386)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:135)  at android.app.ActivityThread.main(ActivityThread.java:5254)  at java.lang.reflect.Method.invoke(Native Method)  at java.lang.reflect.Method.invoke(Method.java:372)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)  04-23 23:04:28.082 1543-1559/system_process W/ActivityManager: Force finishing activity 1 com.surfdogdesigns.pandsi/.MainActivity 04-23 23:04:28.093 1164-1164/? E/EGL_emulation: tid 1164: eglCreateSyncKHR(1299): error 0x3004 (EGL_BAD_ATTRIBUTE) 04-23 23:04:28.211 1543-1599/system_process I/OpenGLRenderer: Initialized EGL, version 1.4 04-23 23:04:28.225 1174-1724/? E/Drm: Failed to find drm plugin 04-23 23:04:28.226 2728-6161/com.google.android.gms.unstable W/DG.WV: Widevine DRM not supported on this device android.media.UnsupportedSchemeException: Failed to instantiate drm object. at android.media.MediaDrm.native_setup(Native Method) at android.media.MediaDrm.<init>(MediaDrm.java:180) at ono.a(:com.google.android.gms:122) at okh.run(:com.google.android.gms:1095) at lmq.run(:com.google.android.gms:450) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at lra.run(:com.google.android.gms:17) at java.lang.Thread.run(Thread.java:818) 04-23 23:04:28.661 1543-1564/system_process W/ActivityManager: Activity pause timeout for ActivityRecord{cb0d51e u0 com.surfdogdesigns.pandsi/.MainActivity t31 f} 04-23 23:04:29.521 1828-2091/com.google.android.googlequicksearchbox W/OpenGLRenderer: Incorrectly called buildLayer on View: aep, destroying layer... 04-23 23:04:29.633 3034-6156/com.google.android.gms.persistent W/GLSUser: [AppCertManager] IOException while requesting key: java.io.IOException: Invalid device key response. at ewg.a(:com.google.android.gms:274) at ewg.a(:com.google.android.gms:4238) at ewf.a(:com.google.android.gms:45) at evz.a(:com.google.android.gms:50) at evy.a(:com.google.android.gms:104) at com.google.android.gms.auth.account.be.legacy.AuthCronChimeraService.b(:com.google.android.gms:4049) at edi.call(:com.google.android.gms:2041) at java.util.concurrent.FutureTask.run(FutureTask.java:237) at lmq.run(:com.google.android.gms:450) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at lra.run(:com.google.android.gms:17) at java.lang.Thread.run(Thread.java:818) 04-23 23:04:29.693 1646-1646/com.android.systemui W/ResourceType: No package identifier when getting value for resource number 0x00000000 04-23 23:04:29.694 1646-1646/com.android.systemui W/PackageManager: Failure retrieving resources for com.surfdogdesigns.pandsi: Resource ID #0x0 04-23 23:04:33.229 2285-7929/com.google.android.gms W/PlatformStatsUtil: Could not retrieve Usage & Diagnostics setting. Giving up. 04-23 23:04:34.372 2285-2299/com.google.android.gms W/SQLiteConnectionPool: A SQLiteConnection object for database '/data/data/com.google.android.gms/databases/metrics.db' was leaked! Please fix your application to end transactions in progress properly and to close the database when it is no longer needed. 04-23 23:04:34.380 2285-2299/com.google.android.gms W/SQLiteConnectionPool: A SQLiteConnection object for database '/data/data/com.google.android.gms/databases/help_responses.db.18' was leaked! Please fix your application to end transactions in progress properly and to close the database when it is no longer needed. 04-23 23:04:34.388 2285-2299/com.google.android.gms W/SQLiteConnectionPool: A SQLiteConnection object for database '/data/data/com.google.android.gms/databases/auto_complete_suggestions.db' was leaked! Please fix your application to end transactions in progress properly and to close the database when it is no longer needed. 04-23 23:04:39.325 1543-1564/system_process W/ActivityManager: Activity destroy timeout for ActivityRecord{cb0d51e u0 com.surfdogdesigns.pandsi/.MainActivity t31 f} 04-23 23:04:42.527 8148-8148/? D/AndroidRuntime: >>>>>> START com.android.internal.os.RuntimeInit uid 0 <<<<<< 04-23 23:04:42.532 8148-8148/? D/AndroidRuntime: CheckJNI is ON 04-23 23:04:42.561 8148-8148/? E/memtrack: Couldn't load memtrack module (No such file or directory) 04-23 23:04:42.561 8148-8148/? E/android.os.Debug: failed to load memtrack module: -2 04-23 23:04:42.574 8148-8148/? D/AndroidRuntime: Calling main entry com.android.commands.am.Am 04-23 23:04:42.579 1543-1560/system_process I/ActivityManager: Force stopping com.surfdogdesigns.pandsi appid=10058 user=0: from pid 8148 04-23 23:04:42.579 1543-1560/system_process I/ActivityManager: Killing 7395:com.surfdogdesigns.pandsi/u0a58 (adj 0): stop com.surfdogdesigns.pandsi 04-23 23:04:42.580 1543-1560/system_process W/libprocessgroup: failed to open /acct/uid_10058/pid_7395/cgroup.procs: No such file or directory 04-23 23:04:42.588 1543-1560/system_process W/ActivityManager: Scheduling restart of crashed service com.surfdogdesigns.pandsi/.MainActivity$MyFirebaseMessagingService in 29020ms 04-23 23:04:42.588 1543-1560/system_process I/ActivityManager: Force stopping service ServiceRecord{2a3bed30 u0 com.surfdogdesigns.pandsi/.MainActivity$MyFirebaseMessagingService} 04-23 23:04:42.599 1543-1811/system_process I/ActivityManager: Killing 2654:com.android.settings/1000 (adj 15): empty #17 04-23 23:04:42.599 1543-1811/system_process W/libprocessgroup: failed to open /acct/uid_1000/pid_2654/cgroup.procs: No such file or directory 04-23 23:04:42.600 8148-8148/? D/AndroidRuntime: Shutting down VM 04-23 23:04:42.608 1543-1560/system_process W/InputMethodManagerService: Got RemoteException sending setActive(false) notification to pid 7395 uid 10058 04-23 23:04:42.625 2004-8160/com.google.android.googlequicksearchbox:search I/HotwordRecognitionRnr: Starting hotword detection. 04-23 23:04:42.627 2004-8159/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_starting gzi@cc534c0 04-23 23:04:42.636 1174-1542/? E/audio_hw_generic: Error opening input stream format 1, channel_mask 0010, sample_rate 16000 04-23 23:04:42.654 1174-8162/? I/AudioFlinger: AudioFlinger's thread 0xb5d99000 ready to run 04-23 23:04:42.663 2004-8159/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_started gzi@cc534c0 04-23 23:04:42.670 2004-2004/com.google.android.googlequicksearchbox:search I/HotwordWorker: onReady 04-23 23:04:42.750 2285-8164/com.google.android.gms W/IcingInternalCorpora: getNumBytesRead when not calculated. 04-23 23:04:42.812 2285-2425/com.google.android.gms I/Icing: Usage reports 0 indexed 0 rejected 0 imm upload true ``` Main Activity: ``` import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.FirebaseInstanceIdService; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; public class MainActivity extends AppCompatActivity { public MainActivity() { } public class MyFirebaseMessagingService extends FirebaseMessagingService { private static final String TAG = "FCM Service"; @Override public void onMessageReceived(RemoteMessage remoteMessage) { // //TODO: Handle FCM messages here. //If the application is in the foreground handle both data and notification messages here. //Also if you intend on generating your own notifications as a result of a received FCM //message, here is where that should be initiated. // Log.d(TAG, "From: " + remoteMessage.getFrom()); Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody()); } } public class FirebaseIDService extends FirebaseInstanceIdService { private static final String TAG = "FirebaseIDService"; @Override public void onTokenRefresh() { // Get updated InstanceID token. String refreshedToken = FirebaseInstanceId.getInstance().getToken(); Log.d(TAG, "Refreshed token: " + refreshedToken); // TODO: Implement this method to send any registration to your app's servers. sendRegistrationToServer(refreshedToken); } /** * Persist token to third-party servers. * * Modify this method to associate the user's FCM InstanceID token with any server-side account * maintained by your application. * * @param token The new token. */ private void sendRegistrationToServer(String token) { // Add custom implementation, as needed. } } ``` Manifest: ``` <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.surfdogdesigns.pandsi"> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme" > <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name=".MainActivity$MyFirebaseMessagingService"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT"/> </intent-filter> </service> <service android:name=".MainActivity$FirebaseIDService"> <intent-filter> <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/> </intent-filter> </service> </application> </manifest> ``` Can anybody see what is going wrong? And how to fix it?
2017/04/23
[ "https://Stackoverflow.com/questions/43571622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2901545/" ]
I haven't tested it, but I suspect that your services cannot be inner classes of `MainActivity`. It would be safer, and may be required, to declare them as non-nested classes, as is done in the sample project: [MyFirebaseInstanceIDService](https://github.com/firebase/quickstart-android/blob/master/messaging/app/src/main/java/com/google/firebase/quickstart/fcm/MyFirebaseInstanceIDService.java) [MyFirebaseMessagingService](https://github.com/firebase/quickstart-android/blob/master/messaging/app/src/main/java/com/google/firebase/quickstart/fcm/MyFirebaseMessagingService.java) It's also possible that the services can be nested classes of `MainActivity` if you declare them as **static** nested classes: ``` public static class MyFirebaseMessagingService... ```
You need to add the empty constructor in the class `MyFirebaseMessagingService` ``` public MyFirebaseMessagingService() { super("MyFirebaseMessagingService"); } ``` For explanation, you can see the details [here](https://developer.android.com/reference/android/app/IntentService.html#IntentService(java.lang.String))
43,571,622
First attempts at getting firebase push notifications to work isn't going so well. I have followed the tutorial listed [here](https://www.codementor.io/flame3/send-push-notifications-to-android-with-firebase-du10860kb) to set it up, but whenever I try and send a notification, the app "closes unexpecedly", and the logical throws the following crash information: Logcat: ``` --------- beginning of crash 04-23 23:04:28.081 7395-7395/com.surfdogdesigns.pandsi E/AndroidRuntime: FATAL EXCEPTION: main Process: com.surfdogdesigns.pandsi, PID: 7395 java.lang.RuntimeException: Unable to instantiate service com.surfdogdesigns.pandsi.MainActivity$MyFirebaseMessagingService: java.lang.InstantiationException: class com.surfdogdesigns.pandsi.MainActivity$MyFirebaseMessagingService has no zero argument constructor at android.app.ActivityThread.handleCreateService(ActivityThread.java:2746) at android.app.ActivityThread.access$1800(ActivityThread.java:151) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1386) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5254) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) Caused by: java.lang.InstantiationException: class com.surfdogdesigns.pandsi.MainActivity$MyFirebaseMessagingService has no zero argument constructor at java.lang.Class.newInstance(Class.java:1597) at android.app.ActivityThread.handleCreateService(ActivityThread.java:2743) at android.app.ActivityThread.access$1800(ActivityThread.java:151)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1386)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:135)  at android.app.ActivityThread.main(ActivityThread.java:5254)  at java.lang.reflect.Method.invoke(Native Method)  at java.lang.reflect.Method.invoke(Method.java:372)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)  Caused by: java.lang.NoSuchMethodException: <init> [] at java.lang.Class.getConstructor(Class.java:531) at java.lang.Class.getDeclaredConstructor(Class.java:510) at java.lang.Class.newInstance(Class.java:1595) at android.app.ActivityThread.handleCreateService(ActivityThread.java:2743)  at android.app.ActivityThread.access$1800(ActivityThread.java:151)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1386)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:135)  at android.app.ActivityThread.main(ActivityThread.java:5254)  at java.lang.reflect.Method.invoke(Native Method)  at java.lang.reflect.Method.invoke(Method.java:372)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)  04-23 23:04:28.082 1543-1559/system_process W/ActivityManager: Force finishing activity 1 com.surfdogdesigns.pandsi/.MainActivity 04-23 23:04:28.093 1164-1164/? E/EGL_emulation: tid 1164: eglCreateSyncKHR(1299): error 0x3004 (EGL_BAD_ATTRIBUTE) 04-23 23:04:28.211 1543-1599/system_process I/OpenGLRenderer: Initialized EGL, version 1.4 04-23 23:04:28.225 1174-1724/? E/Drm: Failed to find drm plugin 04-23 23:04:28.226 2728-6161/com.google.android.gms.unstable W/DG.WV: Widevine DRM not supported on this device android.media.UnsupportedSchemeException: Failed to instantiate drm object. at android.media.MediaDrm.native_setup(Native Method) at android.media.MediaDrm.<init>(MediaDrm.java:180) at ono.a(:com.google.android.gms:122) at okh.run(:com.google.android.gms:1095) at lmq.run(:com.google.android.gms:450) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at lra.run(:com.google.android.gms:17) at java.lang.Thread.run(Thread.java:818) 04-23 23:04:28.661 1543-1564/system_process W/ActivityManager: Activity pause timeout for ActivityRecord{cb0d51e u0 com.surfdogdesigns.pandsi/.MainActivity t31 f} 04-23 23:04:29.521 1828-2091/com.google.android.googlequicksearchbox W/OpenGLRenderer: Incorrectly called buildLayer on View: aep, destroying layer... 04-23 23:04:29.633 3034-6156/com.google.android.gms.persistent W/GLSUser: [AppCertManager] IOException while requesting key: java.io.IOException: Invalid device key response. at ewg.a(:com.google.android.gms:274) at ewg.a(:com.google.android.gms:4238) at ewf.a(:com.google.android.gms:45) at evz.a(:com.google.android.gms:50) at evy.a(:com.google.android.gms:104) at com.google.android.gms.auth.account.be.legacy.AuthCronChimeraService.b(:com.google.android.gms:4049) at edi.call(:com.google.android.gms:2041) at java.util.concurrent.FutureTask.run(FutureTask.java:237) at lmq.run(:com.google.android.gms:450) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at lra.run(:com.google.android.gms:17) at java.lang.Thread.run(Thread.java:818) 04-23 23:04:29.693 1646-1646/com.android.systemui W/ResourceType: No package identifier when getting value for resource number 0x00000000 04-23 23:04:29.694 1646-1646/com.android.systemui W/PackageManager: Failure retrieving resources for com.surfdogdesigns.pandsi: Resource ID #0x0 04-23 23:04:33.229 2285-7929/com.google.android.gms W/PlatformStatsUtil: Could not retrieve Usage & Diagnostics setting. Giving up. 04-23 23:04:34.372 2285-2299/com.google.android.gms W/SQLiteConnectionPool: A SQLiteConnection object for database '/data/data/com.google.android.gms/databases/metrics.db' was leaked! Please fix your application to end transactions in progress properly and to close the database when it is no longer needed. 04-23 23:04:34.380 2285-2299/com.google.android.gms W/SQLiteConnectionPool: A SQLiteConnection object for database '/data/data/com.google.android.gms/databases/help_responses.db.18' was leaked! Please fix your application to end transactions in progress properly and to close the database when it is no longer needed. 04-23 23:04:34.388 2285-2299/com.google.android.gms W/SQLiteConnectionPool: A SQLiteConnection object for database '/data/data/com.google.android.gms/databases/auto_complete_suggestions.db' was leaked! Please fix your application to end transactions in progress properly and to close the database when it is no longer needed. 04-23 23:04:39.325 1543-1564/system_process W/ActivityManager: Activity destroy timeout for ActivityRecord{cb0d51e u0 com.surfdogdesigns.pandsi/.MainActivity t31 f} 04-23 23:04:42.527 8148-8148/? D/AndroidRuntime: >>>>>> START com.android.internal.os.RuntimeInit uid 0 <<<<<< 04-23 23:04:42.532 8148-8148/? D/AndroidRuntime: CheckJNI is ON 04-23 23:04:42.561 8148-8148/? E/memtrack: Couldn't load memtrack module (No such file or directory) 04-23 23:04:42.561 8148-8148/? E/android.os.Debug: failed to load memtrack module: -2 04-23 23:04:42.574 8148-8148/? D/AndroidRuntime: Calling main entry com.android.commands.am.Am 04-23 23:04:42.579 1543-1560/system_process I/ActivityManager: Force stopping com.surfdogdesigns.pandsi appid=10058 user=0: from pid 8148 04-23 23:04:42.579 1543-1560/system_process I/ActivityManager: Killing 7395:com.surfdogdesigns.pandsi/u0a58 (adj 0): stop com.surfdogdesigns.pandsi 04-23 23:04:42.580 1543-1560/system_process W/libprocessgroup: failed to open /acct/uid_10058/pid_7395/cgroup.procs: No such file or directory 04-23 23:04:42.588 1543-1560/system_process W/ActivityManager: Scheduling restart of crashed service com.surfdogdesigns.pandsi/.MainActivity$MyFirebaseMessagingService in 29020ms 04-23 23:04:42.588 1543-1560/system_process I/ActivityManager: Force stopping service ServiceRecord{2a3bed30 u0 com.surfdogdesigns.pandsi/.MainActivity$MyFirebaseMessagingService} 04-23 23:04:42.599 1543-1811/system_process I/ActivityManager: Killing 2654:com.android.settings/1000 (adj 15): empty #17 04-23 23:04:42.599 1543-1811/system_process W/libprocessgroup: failed to open /acct/uid_1000/pid_2654/cgroup.procs: No such file or directory 04-23 23:04:42.600 8148-8148/? D/AndroidRuntime: Shutting down VM 04-23 23:04:42.608 1543-1560/system_process W/InputMethodManagerService: Got RemoteException sending setActive(false) notification to pid 7395 uid 10058 04-23 23:04:42.625 2004-8160/com.google.android.googlequicksearchbox:search I/HotwordRecognitionRnr: Starting hotword detection. 04-23 23:04:42.627 2004-8159/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_starting gzi@cc534c0 04-23 23:04:42.636 1174-1542/? E/audio_hw_generic: Error opening input stream format 1, channel_mask 0010, sample_rate 16000 04-23 23:04:42.654 1174-8162/? I/AudioFlinger: AudioFlinger's thread 0xb5d99000 ready to run 04-23 23:04:42.663 2004-8159/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_started gzi@cc534c0 04-23 23:04:42.670 2004-2004/com.google.android.googlequicksearchbox:search I/HotwordWorker: onReady 04-23 23:04:42.750 2285-8164/com.google.android.gms W/IcingInternalCorpora: getNumBytesRead when not calculated. 04-23 23:04:42.812 2285-2425/com.google.android.gms I/Icing: Usage reports 0 indexed 0 rejected 0 imm upload true ``` Main Activity: ``` import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.FirebaseInstanceIdService; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; public class MainActivity extends AppCompatActivity { public MainActivity() { } public class MyFirebaseMessagingService extends FirebaseMessagingService { private static final String TAG = "FCM Service"; @Override public void onMessageReceived(RemoteMessage remoteMessage) { // //TODO: Handle FCM messages here. //If the application is in the foreground handle both data and notification messages here. //Also if you intend on generating your own notifications as a result of a received FCM //message, here is where that should be initiated. // Log.d(TAG, "From: " + remoteMessage.getFrom()); Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody()); } } public class FirebaseIDService extends FirebaseInstanceIdService { private static final String TAG = "FirebaseIDService"; @Override public void onTokenRefresh() { // Get updated InstanceID token. String refreshedToken = FirebaseInstanceId.getInstance().getToken(); Log.d(TAG, "Refreshed token: " + refreshedToken); // TODO: Implement this method to send any registration to your app's servers. sendRegistrationToServer(refreshedToken); } /** * Persist token to third-party servers. * * Modify this method to associate the user's FCM InstanceID token with any server-side account * maintained by your application. * * @param token The new token. */ private void sendRegistrationToServer(String token) { // Add custom implementation, as needed. } } ``` Manifest: ``` <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.surfdogdesigns.pandsi"> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme" > <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name=".MainActivity$MyFirebaseMessagingService"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT"/> </intent-filter> </service> <service android:name=".MainActivity$FirebaseIDService"> <intent-filter> <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/> </intent-filter> </service> </application> </manifest> ``` Can anybody see what is going wrong? And how to fix it?
2017/04/23
[ "https://Stackoverflow.com/questions/43571622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2901545/" ]
You need to add the empty constructor in the class `MyFirebaseMessagingService` ``` public MyFirebaseMessagingService() { super("MyFirebaseMessagingService"); } ``` For explanation, you can see the details [here](https://developer.android.com/reference/android/app/IntentService.html#IntentService(java.lang.String))
check if you have different version with dependency implementation ``` implementation 'com.google.android.gms:play-services-gcm:+' implementation 'com.google.firebase:firebase-core:+' implementation 'com.google.firebase:firebase-messaging:+' ```
43,571,622
First attempts at getting firebase push notifications to work isn't going so well. I have followed the tutorial listed [here](https://www.codementor.io/flame3/send-push-notifications-to-android-with-firebase-du10860kb) to set it up, but whenever I try and send a notification, the app "closes unexpecedly", and the logical throws the following crash information: Logcat: ``` --------- beginning of crash 04-23 23:04:28.081 7395-7395/com.surfdogdesigns.pandsi E/AndroidRuntime: FATAL EXCEPTION: main Process: com.surfdogdesigns.pandsi, PID: 7395 java.lang.RuntimeException: Unable to instantiate service com.surfdogdesigns.pandsi.MainActivity$MyFirebaseMessagingService: java.lang.InstantiationException: class com.surfdogdesigns.pandsi.MainActivity$MyFirebaseMessagingService has no zero argument constructor at android.app.ActivityThread.handleCreateService(ActivityThread.java:2746) at android.app.ActivityThread.access$1800(ActivityThread.java:151) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1386) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5254) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) Caused by: java.lang.InstantiationException: class com.surfdogdesigns.pandsi.MainActivity$MyFirebaseMessagingService has no zero argument constructor at java.lang.Class.newInstance(Class.java:1597) at android.app.ActivityThread.handleCreateService(ActivityThread.java:2743) at android.app.ActivityThread.access$1800(ActivityThread.java:151)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1386)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:135)  at android.app.ActivityThread.main(ActivityThread.java:5254)  at java.lang.reflect.Method.invoke(Native Method)  at java.lang.reflect.Method.invoke(Method.java:372)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)  Caused by: java.lang.NoSuchMethodException: <init> [] at java.lang.Class.getConstructor(Class.java:531) at java.lang.Class.getDeclaredConstructor(Class.java:510) at java.lang.Class.newInstance(Class.java:1595) at android.app.ActivityThread.handleCreateService(ActivityThread.java:2743)  at android.app.ActivityThread.access$1800(ActivityThread.java:151)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1386)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:135)  at android.app.ActivityThread.main(ActivityThread.java:5254)  at java.lang.reflect.Method.invoke(Native Method)  at java.lang.reflect.Method.invoke(Method.java:372)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)  04-23 23:04:28.082 1543-1559/system_process W/ActivityManager: Force finishing activity 1 com.surfdogdesigns.pandsi/.MainActivity 04-23 23:04:28.093 1164-1164/? E/EGL_emulation: tid 1164: eglCreateSyncKHR(1299): error 0x3004 (EGL_BAD_ATTRIBUTE) 04-23 23:04:28.211 1543-1599/system_process I/OpenGLRenderer: Initialized EGL, version 1.4 04-23 23:04:28.225 1174-1724/? E/Drm: Failed to find drm plugin 04-23 23:04:28.226 2728-6161/com.google.android.gms.unstable W/DG.WV: Widevine DRM not supported on this device android.media.UnsupportedSchemeException: Failed to instantiate drm object. at android.media.MediaDrm.native_setup(Native Method) at android.media.MediaDrm.<init>(MediaDrm.java:180) at ono.a(:com.google.android.gms:122) at okh.run(:com.google.android.gms:1095) at lmq.run(:com.google.android.gms:450) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at lra.run(:com.google.android.gms:17) at java.lang.Thread.run(Thread.java:818) 04-23 23:04:28.661 1543-1564/system_process W/ActivityManager: Activity pause timeout for ActivityRecord{cb0d51e u0 com.surfdogdesigns.pandsi/.MainActivity t31 f} 04-23 23:04:29.521 1828-2091/com.google.android.googlequicksearchbox W/OpenGLRenderer: Incorrectly called buildLayer on View: aep, destroying layer... 04-23 23:04:29.633 3034-6156/com.google.android.gms.persistent W/GLSUser: [AppCertManager] IOException while requesting key: java.io.IOException: Invalid device key response. at ewg.a(:com.google.android.gms:274) at ewg.a(:com.google.android.gms:4238) at ewf.a(:com.google.android.gms:45) at evz.a(:com.google.android.gms:50) at evy.a(:com.google.android.gms:104) at com.google.android.gms.auth.account.be.legacy.AuthCronChimeraService.b(:com.google.android.gms:4049) at edi.call(:com.google.android.gms:2041) at java.util.concurrent.FutureTask.run(FutureTask.java:237) at lmq.run(:com.google.android.gms:450) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at lra.run(:com.google.android.gms:17) at java.lang.Thread.run(Thread.java:818) 04-23 23:04:29.693 1646-1646/com.android.systemui W/ResourceType: No package identifier when getting value for resource number 0x00000000 04-23 23:04:29.694 1646-1646/com.android.systemui W/PackageManager: Failure retrieving resources for com.surfdogdesigns.pandsi: Resource ID #0x0 04-23 23:04:33.229 2285-7929/com.google.android.gms W/PlatformStatsUtil: Could not retrieve Usage & Diagnostics setting. Giving up. 04-23 23:04:34.372 2285-2299/com.google.android.gms W/SQLiteConnectionPool: A SQLiteConnection object for database '/data/data/com.google.android.gms/databases/metrics.db' was leaked! Please fix your application to end transactions in progress properly and to close the database when it is no longer needed. 04-23 23:04:34.380 2285-2299/com.google.android.gms W/SQLiteConnectionPool: A SQLiteConnection object for database '/data/data/com.google.android.gms/databases/help_responses.db.18' was leaked! Please fix your application to end transactions in progress properly and to close the database when it is no longer needed. 04-23 23:04:34.388 2285-2299/com.google.android.gms W/SQLiteConnectionPool: A SQLiteConnection object for database '/data/data/com.google.android.gms/databases/auto_complete_suggestions.db' was leaked! Please fix your application to end transactions in progress properly and to close the database when it is no longer needed. 04-23 23:04:39.325 1543-1564/system_process W/ActivityManager: Activity destroy timeout for ActivityRecord{cb0d51e u0 com.surfdogdesigns.pandsi/.MainActivity t31 f} 04-23 23:04:42.527 8148-8148/? D/AndroidRuntime: >>>>>> START com.android.internal.os.RuntimeInit uid 0 <<<<<< 04-23 23:04:42.532 8148-8148/? D/AndroidRuntime: CheckJNI is ON 04-23 23:04:42.561 8148-8148/? E/memtrack: Couldn't load memtrack module (No such file or directory) 04-23 23:04:42.561 8148-8148/? E/android.os.Debug: failed to load memtrack module: -2 04-23 23:04:42.574 8148-8148/? D/AndroidRuntime: Calling main entry com.android.commands.am.Am 04-23 23:04:42.579 1543-1560/system_process I/ActivityManager: Force stopping com.surfdogdesigns.pandsi appid=10058 user=0: from pid 8148 04-23 23:04:42.579 1543-1560/system_process I/ActivityManager: Killing 7395:com.surfdogdesigns.pandsi/u0a58 (adj 0): stop com.surfdogdesigns.pandsi 04-23 23:04:42.580 1543-1560/system_process W/libprocessgroup: failed to open /acct/uid_10058/pid_7395/cgroup.procs: No such file or directory 04-23 23:04:42.588 1543-1560/system_process W/ActivityManager: Scheduling restart of crashed service com.surfdogdesigns.pandsi/.MainActivity$MyFirebaseMessagingService in 29020ms 04-23 23:04:42.588 1543-1560/system_process I/ActivityManager: Force stopping service ServiceRecord{2a3bed30 u0 com.surfdogdesigns.pandsi/.MainActivity$MyFirebaseMessagingService} 04-23 23:04:42.599 1543-1811/system_process I/ActivityManager: Killing 2654:com.android.settings/1000 (adj 15): empty #17 04-23 23:04:42.599 1543-1811/system_process W/libprocessgroup: failed to open /acct/uid_1000/pid_2654/cgroup.procs: No such file or directory 04-23 23:04:42.600 8148-8148/? D/AndroidRuntime: Shutting down VM 04-23 23:04:42.608 1543-1560/system_process W/InputMethodManagerService: Got RemoteException sending setActive(false) notification to pid 7395 uid 10058 04-23 23:04:42.625 2004-8160/com.google.android.googlequicksearchbox:search I/HotwordRecognitionRnr: Starting hotword detection. 04-23 23:04:42.627 2004-8159/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_starting gzi@cc534c0 04-23 23:04:42.636 1174-1542/? E/audio_hw_generic: Error opening input stream format 1, channel_mask 0010, sample_rate 16000 04-23 23:04:42.654 1174-8162/? I/AudioFlinger: AudioFlinger's thread 0xb5d99000 ready to run 04-23 23:04:42.663 2004-8159/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_started gzi@cc534c0 04-23 23:04:42.670 2004-2004/com.google.android.googlequicksearchbox:search I/HotwordWorker: onReady 04-23 23:04:42.750 2285-8164/com.google.android.gms W/IcingInternalCorpora: getNumBytesRead when not calculated. 04-23 23:04:42.812 2285-2425/com.google.android.gms I/Icing: Usage reports 0 indexed 0 rejected 0 imm upload true ``` Main Activity: ``` import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.FirebaseInstanceIdService; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; public class MainActivity extends AppCompatActivity { public MainActivity() { } public class MyFirebaseMessagingService extends FirebaseMessagingService { private static final String TAG = "FCM Service"; @Override public void onMessageReceived(RemoteMessage remoteMessage) { // //TODO: Handle FCM messages here. //If the application is in the foreground handle both data and notification messages here. //Also if you intend on generating your own notifications as a result of a received FCM //message, here is where that should be initiated. // Log.d(TAG, "From: " + remoteMessage.getFrom()); Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody()); } } public class FirebaseIDService extends FirebaseInstanceIdService { private static final String TAG = "FirebaseIDService"; @Override public void onTokenRefresh() { // Get updated InstanceID token. String refreshedToken = FirebaseInstanceId.getInstance().getToken(); Log.d(TAG, "Refreshed token: " + refreshedToken); // TODO: Implement this method to send any registration to your app's servers. sendRegistrationToServer(refreshedToken); } /** * Persist token to third-party servers. * * Modify this method to associate the user's FCM InstanceID token with any server-side account * maintained by your application. * * @param token The new token. */ private void sendRegistrationToServer(String token) { // Add custom implementation, as needed. } } ``` Manifest: ``` <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.surfdogdesigns.pandsi"> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme" > <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name=".MainActivity$MyFirebaseMessagingService"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT"/> </intent-filter> </service> <service android:name=".MainActivity$FirebaseIDService"> <intent-filter> <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/> </intent-filter> </service> </application> </manifest> ``` Can anybody see what is going wrong? And how to fix it?
2017/04/23
[ "https://Stackoverflow.com/questions/43571622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2901545/" ]
I haven't tested it, but I suspect that your services cannot be inner classes of `MainActivity`. It would be safer, and may be required, to declare them as non-nested classes, as is done in the sample project: [MyFirebaseInstanceIDService](https://github.com/firebase/quickstart-android/blob/master/messaging/app/src/main/java/com/google/firebase/quickstart/fcm/MyFirebaseInstanceIDService.java) [MyFirebaseMessagingService](https://github.com/firebase/quickstart-android/blob/master/messaging/app/src/main/java/com/google/firebase/quickstart/fcm/MyFirebaseMessagingService.java) It's also possible that the services can be nested classes of `MainActivity` if you declare them as **static** nested classes: ``` public static class MyFirebaseMessagingService... ```
check if you have different version with dependency implementation ``` implementation 'com.google.android.gms:play-services-gcm:+' implementation 'com.google.firebase:firebase-core:+' implementation 'com.google.firebase:firebase-messaging:+' ```
2,947,019
I am having weird scrolling issues in my pretty simple GridView. Each item in the Grid is simply an ImageView and a TextView. The activity itself is simply an application selector. It looks like a rough version of the basic App Tray in Android. The issue is that after spending some times scrolling through my view, it will inevitably allow me to continue scrolling past the top row of icons, to a blank screen, and the scroll bar will disappear, leaving me stuck. It doesn't happen every time I go to the top of the view, only sometimes, and usually only after some excessive scrolling. If I happen to notice the problem and catch it before the top row disappears off the bottom of the screen, I can usually scroll back through the view and spot some icons missing. There are empty spaces in the grid, and I can only assume that those icons have been moved to some bizarre position, which is allowing the view to scroll past the top. This is my first Android app beyond a basic Hello World, so it's likely that I've just screwed up something in my layout files. I also realize that this is probably a pretty confusing description, so I'm hoping someone has experienced this and my search abilities simply were unable to find it. I can post my layout files or other code if someone thinks that's useful. Oh, and the program is built against 1.5, but is running on 2.2 (whatever state of 2.2 that was that snuck out last week) on my phone. I don't have enough apps to test this on an emulator, but could probably set something up if someone felt it necessary. Thanks in advance for any help on the issue.
2010/06/01
[ "https://Stackoverflow.com/questions/2947019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/355016/" ]
i have solved it: in the link [GridView cannot show image](https://stackoverflow.com/questions/5944250/gridview-cannot-show-image/5958097#5958097) you can try
It seems that if you scroll off the bottom of the GridView and back again very fast a couple of times, you eventually will notice that the elements of the view get shifted one place to the "left" from where they originally were. When this happens, you then can scroll all the way off the top of the GridView. When you do reach the top of the list, item 0 is not displayed, having item 1 in its place and nothing but blackness above that row. Clicking on any item in this situation resets the list and everything is back to normal. This must be a bug. It's highly reproducible, and I don't think anything I'm doing is causing the mix up. At this point, adding to the list adapter has stopped. Right now I'm working with Android 2.3.3.
2,947,019
I am having weird scrolling issues in my pretty simple GridView. Each item in the Grid is simply an ImageView and a TextView. The activity itself is simply an application selector. It looks like a rough version of the basic App Tray in Android. The issue is that after spending some times scrolling through my view, it will inevitably allow me to continue scrolling past the top row of icons, to a blank screen, and the scroll bar will disappear, leaving me stuck. It doesn't happen every time I go to the top of the view, only sometimes, and usually only after some excessive scrolling. If I happen to notice the problem and catch it before the top row disappears off the bottom of the screen, I can usually scroll back through the view and spot some icons missing. There are empty spaces in the grid, and I can only assume that those icons have been moved to some bizarre position, which is allowing the view to scroll past the top. This is my first Android app beyond a basic Hello World, so it's likely that I've just screwed up something in my layout files. I also realize that this is probably a pretty confusing description, so I'm hoping someone has experienced this and my search abilities simply were unable to find it. I can post my layout files or other code if someone thinks that's useful. Oh, and the program is built against 1.5, but is running on 2.2 (whatever state of 2.2 that was that snuck out last week) on my phone. I don't have enough apps to test this on an emulator, but could probably set something up if someone felt it necessary. Thanks in advance for any help on the issue.
2010/06/01
[ "https://Stackoverflow.com/questions/2947019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/355016/" ]
I had same problem, but I post to `GridView` only `ImageView`'s so pengwang's answer didn't help me. I found explanation for this bug <https://code.google.com/p/android/issues/detail?id=16218> > > The problem is that GridView does not currently handle items with differing heights. > > > My solution is to use exactly specified `layout_height` same for all `GridView`'s items.
It seems that if you scroll off the bottom of the GridView and back again very fast a couple of times, you eventually will notice that the elements of the view get shifted one place to the "left" from where they originally were. When this happens, you then can scroll all the way off the top of the GridView. When you do reach the top of the list, item 0 is not displayed, having item 1 in its place and nothing but blackness above that row. Clicking on any item in this situation resets the list and everything is back to normal. This must be a bug. It's highly reproducible, and I don't think anything I'm doing is causing the mix up. At this point, adding to the list adapter has stopped. Right now I'm working with Android 2.3.3.
2,947,019
I am having weird scrolling issues in my pretty simple GridView. Each item in the Grid is simply an ImageView and a TextView. The activity itself is simply an application selector. It looks like a rough version of the basic App Tray in Android. The issue is that after spending some times scrolling through my view, it will inevitably allow me to continue scrolling past the top row of icons, to a blank screen, and the scroll bar will disappear, leaving me stuck. It doesn't happen every time I go to the top of the view, only sometimes, and usually only after some excessive scrolling. If I happen to notice the problem and catch it before the top row disappears off the bottom of the screen, I can usually scroll back through the view and spot some icons missing. There are empty spaces in the grid, and I can only assume that those icons have been moved to some bizarre position, which is allowing the view to scroll past the top. This is my first Android app beyond a basic Hello World, so it's likely that I've just screwed up something in my layout files. I also realize that this is probably a pretty confusing description, so I'm hoping someone has experienced this and my search abilities simply were unable to find it. I can post my layout files or other code if someone thinks that's useful. Oh, and the program is built against 1.5, but is running on 2.2 (whatever state of 2.2 that was that snuck out last week) on my phone. I don't have enough apps to test this on an emulator, but could probably set something up if someone felt it necessary. Thanks in advance for any help on the issue.
2010/06/01
[ "https://Stackoverflow.com/questions/2947019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/355016/" ]
It seems that if you scroll off the bottom of the GridView and back again very fast a couple of times, you eventually will notice that the elements of the view get shifted one place to the "left" from where they originally were. When this happens, you then can scroll all the way off the top of the GridView. When you do reach the top of the list, item 0 is not displayed, having item 1 in its place and nothing but blackness above that row. Clicking on any item in this situation resets the list and everything is back to normal. This must be a bug. It's highly reproducible, and I don't think anything I'm doing is causing the mix up. At this point, adding to the list adapter has stopped. Right now I'm working with Android 2.3.3.
I just ran into this exact same issue myself -- I have a grid of images that have different heights. After reading the Android developer's doc on GridView, GridView.LayoutParams and GridLayout, I did two things that fix my issue: 1. find the tallest image in each row, and store the height in a map of row -> rowHeight. Each image that I download has width and height info, so this is easy for me to do by overriding my adapter's addAll(items) method. 2. in getView(), I create a GridView.LayoutParams(MATCH\_PARENT, getRowHeight(position)), which sets each grid item to the max row height for its specific row. 3. wrap my ImageView inside a LinearLayout. I have tried other layout but LinearLayout is the one that works. Set android:scaleType="fitCenter" and android:adjustViewBounds="true" for the image view. After above 3 steps I finally got the grid to look right, they have different heights, and there's no scrolling issues.
2,947,019
I am having weird scrolling issues in my pretty simple GridView. Each item in the Grid is simply an ImageView and a TextView. The activity itself is simply an application selector. It looks like a rough version of the basic App Tray in Android. The issue is that after spending some times scrolling through my view, it will inevitably allow me to continue scrolling past the top row of icons, to a blank screen, and the scroll bar will disappear, leaving me stuck. It doesn't happen every time I go to the top of the view, only sometimes, and usually only after some excessive scrolling. If I happen to notice the problem and catch it before the top row disappears off the bottom of the screen, I can usually scroll back through the view and spot some icons missing. There are empty spaces in the grid, and I can only assume that those icons have been moved to some bizarre position, which is allowing the view to scroll past the top. This is my first Android app beyond a basic Hello World, so it's likely that I've just screwed up something in my layout files. I also realize that this is probably a pretty confusing description, so I'm hoping someone has experienced this and my search abilities simply were unable to find it. I can post my layout files or other code if someone thinks that's useful. Oh, and the program is built against 1.5, but is running on 2.2 (whatever state of 2.2 that was that snuck out last week) on my phone. I don't have enough apps to test this on an emulator, but could probably set something up if someone felt it necessary. Thanks in advance for any help on the issue.
2010/06/01
[ "https://Stackoverflow.com/questions/2947019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/355016/" ]
It seems that if you scroll off the bottom of the GridView and back again very fast a couple of times, you eventually will notice that the elements of the view get shifted one place to the "left" from where they originally were. When this happens, you then can scroll all the way off the top of the GridView. When you do reach the top of the list, item 0 is not displayed, having item 1 in its place and nothing but blackness above that row. Clicking on any item in this situation resets the list and everything is back to normal. This must be a bug. It's highly reproducible, and I don't think anything I'm doing is causing the mix up. At this point, adding to the list adapter has stopped. Right now I'm working with Android 2.3.3.
I had a similar, but probably less common problem, where just scrolling a little bit would scroll the gridview to the end and I was not able to scroll up at all. This only occurred when the gridview was smaller, for example when the keyboard was visible. The problem was that I used: ``` android:paddingBottom="400dp" android:clipToPadding="false" ``` Making padding bottom much smaller fixed my issue. I hope this helps at least someone!
2,947,019
I am having weird scrolling issues in my pretty simple GridView. Each item in the Grid is simply an ImageView and a TextView. The activity itself is simply an application selector. It looks like a rough version of the basic App Tray in Android. The issue is that after spending some times scrolling through my view, it will inevitably allow me to continue scrolling past the top row of icons, to a blank screen, and the scroll bar will disappear, leaving me stuck. It doesn't happen every time I go to the top of the view, only sometimes, and usually only after some excessive scrolling. If I happen to notice the problem and catch it before the top row disappears off the bottom of the screen, I can usually scroll back through the view and spot some icons missing. There are empty spaces in the grid, and I can only assume that those icons have been moved to some bizarre position, which is allowing the view to scroll past the top. This is my first Android app beyond a basic Hello World, so it's likely that I've just screwed up something in my layout files. I also realize that this is probably a pretty confusing description, so I'm hoping someone has experienced this and my search abilities simply were unable to find it. I can post my layout files or other code if someone thinks that's useful. Oh, and the program is built against 1.5, but is running on 2.2 (whatever state of 2.2 that was that snuck out last week) on my phone. I don't have enough apps to test this on an emulator, but could probably set something up if someone felt it necessary. Thanks in advance for any help on the issue.
2010/06/01
[ "https://Stackoverflow.com/questions/2947019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/355016/" ]
i have solved it: in the link [GridView cannot show image](https://stackoverflow.com/questions/5944250/gridview-cannot-show-image/5958097#5958097) you can try
I had same problem, but I post to `GridView` only `ImageView`'s so pengwang's answer didn't help me. I found explanation for this bug <https://code.google.com/p/android/issues/detail?id=16218> > > The problem is that GridView does not currently handle items with differing heights. > > > My solution is to use exactly specified `layout_height` same for all `GridView`'s items.
2,947,019
I am having weird scrolling issues in my pretty simple GridView. Each item in the Grid is simply an ImageView and a TextView. The activity itself is simply an application selector. It looks like a rough version of the basic App Tray in Android. The issue is that after spending some times scrolling through my view, it will inevitably allow me to continue scrolling past the top row of icons, to a blank screen, and the scroll bar will disappear, leaving me stuck. It doesn't happen every time I go to the top of the view, only sometimes, and usually only after some excessive scrolling. If I happen to notice the problem and catch it before the top row disappears off the bottom of the screen, I can usually scroll back through the view and spot some icons missing. There are empty spaces in the grid, and I can only assume that those icons have been moved to some bizarre position, which is allowing the view to scroll past the top. This is my first Android app beyond a basic Hello World, so it's likely that I've just screwed up something in my layout files. I also realize that this is probably a pretty confusing description, so I'm hoping someone has experienced this and my search abilities simply were unable to find it. I can post my layout files or other code if someone thinks that's useful. Oh, and the program is built against 1.5, but is running on 2.2 (whatever state of 2.2 that was that snuck out last week) on my phone. I don't have enough apps to test this on an emulator, but could probably set something up if someone felt it necessary. Thanks in advance for any help on the issue.
2010/06/01
[ "https://Stackoverflow.com/questions/2947019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/355016/" ]
i have solved it: in the link [GridView cannot show image](https://stackoverflow.com/questions/5944250/gridview-cannot-show-image/5958097#5958097) you can try
I just ran into this exact same issue myself -- I have a grid of images that have different heights. After reading the Android developer's doc on GridView, GridView.LayoutParams and GridLayout, I did two things that fix my issue: 1. find the tallest image in each row, and store the height in a map of row -> rowHeight. Each image that I download has width and height info, so this is easy for me to do by overriding my adapter's addAll(items) method. 2. in getView(), I create a GridView.LayoutParams(MATCH\_PARENT, getRowHeight(position)), which sets each grid item to the max row height for its specific row. 3. wrap my ImageView inside a LinearLayout. I have tried other layout but LinearLayout is the one that works. Set android:scaleType="fitCenter" and android:adjustViewBounds="true" for the image view. After above 3 steps I finally got the grid to look right, they have different heights, and there's no scrolling issues.
2,947,019
I am having weird scrolling issues in my pretty simple GridView. Each item in the Grid is simply an ImageView and a TextView. The activity itself is simply an application selector. It looks like a rough version of the basic App Tray in Android. The issue is that after spending some times scrolling through my view, it will inevitably allow me to continue scrolling past the top row of icons, to a blank screen, and the scroll bar will disappear, leaving me stuck. It doesn't happen every time I go to the top of the view, only sometimes, and usually only after some excessive scrolling. If I happen to notice the problem and catch it before the top row disappears off the bottom of the screen, I can usually scroll back through the view and spot some icons missing. There are empty spaces in the grid, and I can only assume that those icons have been moved to some bizarre position, which is allowing the view to scroll past the top. This is my first Android app beyond a basic Hello World, so it's likely that I've just screwed up something in my layout files. I also realize that this is probably a pretty confusing description, so I'm hoping someone has experienced this and my search abilities simply were unable to find it. I can post my layout files or other code if someone thinks that's useful. Oh, and the program is built against 1.5, but is running on 2.2 (whatever state of 2.2 that was that snuck out last week) on my phone. I don't have enough apps to test this on an emulator, but could probably set something up if someone felt it necessary. Thanks in advance for any help on the issue.
2010/06/01
[ "https://Stackoverflow.com/questions/2947019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/355016/" ]
i have solved it: in the link [GridView cannot show image](https://stackoverflow.com/questions/5944250/gridview-cannot-show-image/5958097#5958097) you can try
I had a similar, but probably less common problem, where just scrolling a little bit would scroll the gridview to the end and I was not able to scroll up at all. This only occurred when the gridview was smaller, for example when the keyboard was visible. The problem was that I used: ``` android:paddingBottom="400dp" android:clipToPadding="false" ``` Making padding bottom much smaller fixed my issue. I hope this helps at least someone!
2,947,019
I am having weird scrolling issues in my pretty simple GridView. Each item in the Grid is simply an ImageView and a TextView. The activity itself is simply an application selector. It looks like a rough version of the basic App Tray in Android. The issue is that after spending some times scrolling through my view, it will inevitably allow me to continue scrolling past the top row of icons, to a blank screen, and the scroll bar will disappear, leaving me stuck. It doesn't happen every time I go to the top of the view, only sometimes, and usually only after some excessive scrolling. If I happen to notice the problem and catch it before the top row disappears off the bottom of the screen, I can usually scroll back through the view and spot some icons missing. There are empty spaces in the grid, and I can only assume that those icons have been moved to some bizarre position, which is allowing the view to scroll past the top. This is my first Android app beyond a basic Hello World, so it's likely that I've just screwed up something in my layout files. I also realize that this is probably a pretty confusing description, so I'm hoping someone has experienced this and my search abilities simply were unable to find it. I can post my layout files or other code if someone thinks that's useful. Oh, and the program is built against 1.5, but is running on 2.2 (whatever state of 2.2 that was that snuck out last week) on my phone. I don't have enough apps to test this on an emulator, but could probably set something up if someone felt it necessary. Thanks in advance for any help on the issue.
2010/06/01
[ "https://Stackoverflow.com/questions/2947019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/355016/" ]
I had same problem, but I post to `GridView` only `ImageView`'s so pengwang's answer didn't help me. I found explanation for this bug <https://code.google.com/p/android/issues/detail?id=16218> > > The problem is that GridView does not currently handle items with differing heights. > > > My solution is to use exactly specified `layout_height` same for all `GridView`'s items.
I just ran into this exact same issue myself -- I have a grid of images that have different heights. After reading the Android developer's doc on GridView, GridView.LayoutParams and GridLayout, I did two things that fix my issue: 1. find the tallest image in each row, and store the height in a map of row -> rowHeight. Each image that I download has width and height info, so this is easy for me to do by overriding my adapter's addAll(items) method. 2. in getView(), I create a GridView.LayoutParams(MATCH\_PARENT, getRowHeight(position)), which sets each grid item to the max row height for its specific row. 3. wrap my ImageView inside a LinearLayout. I have tried other layout but LinearLayout is the one that works. Set android:scaleType="fitCenter" and android:adjustViewBounds="true" for the image view. After above 3 steps I finally got the grid to look right, they have different heights, and there's no scrolling issues.
2,947,019
I am having weird scrolling issues in my pretty simple GridView. Each item in the Grid is simply an ImageView and a TextView. The activity itself is simply an application selector. It looks like a rough version of the basic App Tray in Android. The issue is that after spending some times scrolling through my view, it will inevitably allow me to continue scrolling past the top row of icons, to a blank screen, and the scroll bar will disappear, leaving me stuck. It doesn't happen every time I go to the top of the view, only sometimes, and usually only after some excessive scrolling. If I happen to notice the problem and catch it before the top row disappears off the bottom of the screen, I can usually scroll back through the view and spot some icons missing. There are empty spaces in the grid, and I can only assume that those icons have been moved to some bizarre position, which is allowing the view to scroll past the top. This is my first Android app beyond a basic Hello World, so it's likely that I've just screwed up something in my layout files. I also realize that this is probably a pretty confusing description, so I'm hoping someone has experienced this and my search abilities simply were unable to find it. I can post my layout files or other code if someone thinks that's useful. Oh, and the program is built against 1.5, but is running on 2.2 (whatever state of 2.2 that was that snuck out last week) on my phone. I don't have enough apps to test this on an emulator, but could probably set something up if someone felt it necessary. Thanks in advance for any help on the issue.
2010/06/01
[ "https://Stackoverflow.com/questions/2947019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/355016/" ]
I had same problem, but I post to `GridView` only `ImageView`'s so pengwang's answer didn't help me. I found explanation for this bug <https://code.google.com/p/android/issues/detail?id=16218> > > The problem is that GridView does not currently handle items with differing heights. > > > My solution is to use exactly specified `layout_height` same for all `GridView`'s items.
I had a similar, but probably less common problem, where just scrolling a little bit would scroll the gridview to the end and I was not able to scroll up at all. This only occurred when the gridview was smaller, for example when the keyboard was visible. The problem was that I used: ``` android:paddingBottom="400dp" android:clipToPadding="false" ``` Making padding bottom much smaller fixed my issue. I hope this helps at least someone!