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 |
|---|---|---|---|---|---|
36,538,113 | I am writing an application that integrates with [Smooch](http://smooch.io) and [Carnival](http://carnival.io). Both these libraries receive GCM push messages using the standard approach of defining a GCM Intent Service to receive messages.
When I use only Smooch, everything works great. When I use only Carnival, everything works great. The problem comes in when I try to use both. What I have found is that the GCM receiver will simply start the first service listed in the manifest that defines intent `com.google.android.c2dm.intent.RECEIVE`.
In fact, I found that the order the libraries are listed in my `build.gradle` affects in which order their manifests are merged into the application manifest. So, if I put smooch first, it works (but Carnival doesn't receive anything). And if I put Carnival first, it works (but Smooch never receives anything).
How can I handle multiple GCM intent services when I don't control either one? In general, how should applications define and manage multiple GCM intent services? | 2016/04/11 | [
"https://Stackoverflow.com/questions/36538113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/95462/"
] | The reason you can't get push to work in both Carnival and Smooch is that both libraries are registering their own GcmListenerService, and in Android the first GcmListenerService defined in your manifest will receive all GCM messages.
I have a solution for you based primarily off the following SO article:
[Multiple GCM listeners using GcmListenerService](https://stackoverflow.com/questions/32050275/multiple-gcm-listeners-using-gcmlistenerservice/32058699#32058699)
>
> The best solution would be to just have one GcmListenerService implementation, and have this handle messages for both.
>
>
>
In order to specify your own GcmListenerService, follow the instructions from [Google's Cloud Messaging Documentation](https://developers.google.com/cloud-messaging/android/client#sample-register).
Smooch provides the tools necessary for you to disable their internal GCM registration when you have your own.
To do so, simply call `setGoogleCloudMessagingAutoRegistrationEnabled` while initializing Smooch:
```
Settings settings = new Settings("<your_app_token>");
settings.setGoogleCloudMessagingAutoRegistrationEnabled(false);
Smooch.init(this, settings);
```
And in your own `GcmRegistrationIntentService`, call `Smooch.setGoogleCloudMessagingToken(token);` with your token.
Once that is complete, you'll be able to pass the GCM message on to any GCM Receiver that you'd like.
```
@Override
public void onMessageReceived(String from, Bundle data) {
final String smoochNotification = data.getString("smoochNotification");
if (smoochNotification != null && smoochNotification.equals("true")) {
data.putString("from", from);
Intent intent = new Intent();
intent.putExtras(data);
intent.setAction("com.google.android.c2dm.intent.RECEIVE");
intent.setComponent(new ComponentName(getPackageName(), "io.smooch.core.GcmService"));
GcmReceiver.startWakefulService(getApplicationContext(), intent);
}
}
```
**EDIT**
As of Smooch version 3.2.0, you can now more easily trigger Smooch’s notification by calling [`GcmService.triggerSmoochGcm`](http://docs.smooch.io/api/android/io/smooch/core/GcmService.html#triggerSmoochGcm-android.os.Bundle-android.content.Context-) in your onMessageReceived.
```
@Override
public void onMessageReceived(String from, Bundle data) {
final String smoochNotification = data.getString("smoochNotification");
if (smoochNotification != null && smoochNotification.equals("true")) {
GcmService.triggerSmoochGcm(data, this);
}
}
``` | You are using both as gradle dependencies? You will have to download both libraries and use them as modules, they probably are using the same services, if you download them you can change the services name and solve any issue that can be corelating both.
My guess is that you will probably have to create the GCM broadcast receiver from with your app module (even if it calls the libs services). |
4,111,737 | Okay, so I'm not sure at all what is going on here. I just got my MAC, and I am trying to download and install setuptools, so I can download different python packages (using easy\_install). So, following the instructions here (http://pypi.python.org/pypi/setuptools):
1. I currently have version 2.6
2. I downloaded the following egg: setuptools-0.6c11-py2.6.egg (md5)
3. I placed the file on my desktop (File Name: setuptools-0.6c11-py2.6.egg.sh)
4. I navigate to the desktop on the directory, and use the following command line, as suggested by the above link:
sh setuptools-0.6c11-py2.6.egg
5. I get an error: No such file or directory, so then I use this other command
sh setuptools-0.6c11-py2.6.egg.sh
6. Then, I get the following error:
setuptools-0.6c11-py2.6.egg.sh is not the correct name for this egg file.
Please rename it back to setuptools-0.6c11-py2.6.egg and try again.
I am really not sure at all what to do here. Any help would be appreciated! Thanks! | 2010/11/06 | [
"https://Stackoverflow.com/questions/4111737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/487588/"
] | **edit Try this from a command line**
Here is an easier thing to do that might work better for you. Open a terminal (Applications->Utilities->Terminal) and run this as a shell script. You can also run the individual commands.
```
#!/bin/sh
cd ~
# Downloads python setuptools for 2.6
curl -o setuptools-0.6c11-py2.6.egg http://pypi.python.org/packages/2.6/s/setuptools/setuptools-0.6c11-py2.6.egg#md5=bfa92100bd772d5a213eedd356d64086
# installs it, will probably prompt you for password
sudo sh setuptools-0.6c11-py2.6.egg
# clean up and delete egg
rm setuptools-0.6c11-py2.6.egg
```
**Stuff below was original response**
I just did this on my own Mac machine, and installation went off without a problem. Did you open a terminal to do this?
I downloaded setuptools to my Downloads folder, and then opened a terminal, and did this:
```
> cd ~/Downloads
> sudo sh setuptools-0.6c11-py2.6.egg
Password:
Processing setuptools-0.6c11-py2.6.egg
Removing /Library/Python/2.6/site-packages/setuptools-0.6c11-py2.6.egg
Copying setuptools-0.6c11-py2.6.egg to /Library/Python/2.6/site-packages
setuptools 0.6c11 is already the active version in easy-install.pth
Installing easy_install script to /usr/local/bin
Installing easy_install-2.6 script to /usr/local/bin
Installed /Library/Python/2.6/site-packages/setuptools-0.6c11-py2.6.egg
Processing dependencies for setuptools==0.6c11
Finished processing dependencies for setuptools==0.6c11
``` | Try this
```
mv setuptools-0.6c11-py2.6.egg.sh setuptools-0.6c11-py2.6.egg
sh setuptools-0.6c11-py2.6.egg
``` |
8,672,218 | I'm keen to know exactly how the classes will be arranged in memory esp. with inheritance and virtual functions.
I know that this is not defined by the c++ language standard. However, is there any easy way to find out how your specific compiler will implement these say by writing some test code?
EDIT:- Using some of the answers below :-
```
#include <iostream>
using namespace std;
class A {
public:
int a;
virtual void func() {}
};
class B : public A {
public:
int b;
virtual void func() {}
};
class C {
public:
int c;
virtual void func() {}
};
class D : public A, public C {
public:
int d;
virtual void func() {}
};
class E : public C, public A {
public:
int e;
virtual void func() {}
};
class F : public A {
public:
int f;
virtual void func() {}
};
class G : public B, public F {
public:
int g;
virtual void func() {}
};
int main() {
A a; B b; C c; D d; E e; F f; G g;
cout<<"A: "<<(size_t)&a.a-(size_t)&a<<"\n";
cout<<"B: "<<(size_t)&b.a-(size_t)&b<<" "<<(size_t)&b.b-(size_t)&b<<"\n";
cout<<"C: "<<(size_t)&c.c-(size_t)&c<<"\n";
cout<<"D: "<<(size_t)&d.a-(size_t)&d<<" "<<(size_t)&d.c-(size_t)&d<<" "<<(size_t)&d.d- (size_t)&d<<"\n";
cout<<"E: "<<(size_t)&e.a-(size_t)&e<<" "<<(size_t)&e.c-(size_t)&e<<" "<<(size_t)&e.e- (size_t)&e<<"\n";
cout<<"F: "<<(size_t)&f.a-(size_t)&f<<" "<<(size_t)&f.f-(size_t)&f<<"\n";
cout<<"G: "<<(size_t)&g.B::a-(size_t)&g<<" "<<(size_t)&g.F::a-(size_t)&g<<" " <<(size_t)&g.b-(size_t)&g<<" "<<(size_t)&g.f-(size_t)&g<<" "<<(size_t)&g.g-(size_t)&g<<"\n";
}
```
And the output is :-
```
A: 8
B: 8 12
C: 8
D: 8 24 28
E: 24 8 28
F: 8 12
G: 8 24 12 28 32
```
So all classes have got a v-ptr at loc 0 of size 8.
D has another v-ptr at location 16. Similarly for E.
G also seems to have a v-ptr at 16 although from my (limited) understanding I would have guessed it to have more. | 2011/12/29 | [
"https://Stackoverflow.com/questions/8672218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1098524/"
] | Visual Studio atleast has a [hidden compiler option](http://channel9.msdn.com/Shows/Going+Deep/C9-Lectures-Stephan-T-Lavavej-Advanced-STL-3-of-n) `/d1reportSingleClassLayout` (starting at ~32:00).
Usage: `/d1reportSingleClassLayoutCLASSNAME` where there shall be no whitespace between the compiler switch and `CLASSNAME` (obviously replace this with the name of the class you'e interested in). | The best way is probably writing a few simple test cases and then compile and debug them in assembler (all optimization off): running one instruction at a time you'll see where everything fits.
At least that's the way I learned it.
And if you find any case particularly challenging, post in in SO! |
8,672,218 | I'm keen to know exactly how the classes will be arranged in memory esp. with inheritance and virtual functions.
I know that this is not defined by the c++ language standard. However, is there any easy way to find out how your specific compiler will implement these say by writing some test code?
EDIT:- Using some of the answers below :-
```
#include <iostream>
using namespace std;
class A {
public:
int a;
virtual void func() {}
};
class B : public A {
public:
int b;
virtual void func() {}
};
class C {
public:
int c;
virtual void func() {}
};
class D : public A, public C {
public:
int d;
virtual void func() {}
};
class E : public C, public A {
public:
int e;
virtual void func() {}
};
class F : public A {
public:
int f;
virtual void func() {}
};
class G : public B, public F {
public:
int g;
virtual void func() {}
};
int main() {
A a; B b; C c; D d; E e; F f; G g;
cout<<"A: "<<(size_t)&a.a-(size_t)&a<<"\n";
cout<<"B: "<<(size_t)&b.a-(size_t)&b<<" "<<(size_t)&b.b-(size_t)&b<<"\n";
cout<<"C: "<<(size_t)&c.c-(size_t)&c<<"\n";
cout<<"D: "<<(size_t)&d.a-(size_t)&d<<" "<<(size_t)&d.c-(size_t)&d<<" "<<(size_t)&d.d- (size_t)&d<<"\n";
cout<<"E: "<<(size_t)&e.a-(size_t)&e<<" "<<(size_t)&e.c-(size_t)&e<<" "<<(size_t)&e.e- (size_t)&e<<"\n";
cout<<"F: "<<(size_t)&f.a-(size_t)&f<<" "<<(size_t)&f.f-(size_t)&f<<"\n";
cout<<"G: "<<(size_t)&g.B::a-(size_t)&g<<" "<<(size_t)&g.F::a-(size_t)&g<<" " <<(size_t)&g.b-(size_t)&g<<" "<<(size_t)&g.f-(size_t)&g<<" "<<(size_t)&g.g-(size_t)&g<<"\n";
}
```
And the output is :-
```
A: 8
B: 8 12
C: 8
D: 8 24 28
E: 24 8 28
F: 8 12
G: 8 24 12 28 32
```
So all classes have got a v-ptr at loc 0 of size 8.
D has another v-ptr at location 16. Similarly for E.
G also seems to have a v-ptr at 16 although from my (limited) understanding I would have guessed it to have more. | 2011/12/29 | [
"https://Stackoverflow.com/questions/8672218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1098524/"
] | One way is to print out the offsets of all the members:
```
class Parent{
public:
int a;
int b;
virtual void foo(){
cout << "parent" << endl;
}
};
class Child : public Parent{
public:
int c;
int d;
virtual void foo(){
cout << "child" << endl;
}
};
int main(){
Parent p;
Child c;
p.foo();
c.foo();
cout << "Parent Offset a = " << (size_t)&p.a - (size_t)&p << endl;
cout << "Parent Offset b = " << (size_t)&p.b - (size_t)&p << endl;
cout << "Child Offset a = " << (size_t)&c.a - (size_t)&c << endl;
cout << "Child Offset b = " << (size_t)&c.b - (size_t)&c << endl;
cout << "Child Offset c = " << (size_t)&c.c - (size_t)&c << endl;
cout << "Child Offset d = " << (size_t)&c.d - (size_t)&c << endl;
system("pause");
}
```
**Output:**
```
parent
child
Parent Offset a = 8
Parent Offset b = 12
Child Offset a = 8
Child Offset b = 12
Child Offset c = 16
Child Offset d = 20
```
So you can see all the offsets here. You'll notice that there's nothing at offset 0, as that is presumably where the pointer to the [vtable](http://en.wikipedia.org/wiki/Virtual_method_table) goes.
Also notice that the inherited members have the same offsets in both Child and Parent. | Visual Studio atleast has a [hidden compiler option](http://channel9.msdn.com/Shows/Going+Deep/C9-Lectures-Stephan-T-Lavavej-Advanced-STL-3-of-n) `/d1reportSingleClassLayout` (starting at ~32:00).
Usage: `/d1reportSingleClassLayoutCLASSNAME` where there shall be no whitespace between the compiler switch and `CLASSNAME` (obviously replace this with the name of the class you'e interested in). |
8,672,218 | I'm keen to know exactly how the classes will be arranged in memory esp. with inheritance and virtual functions.
I know that this is not defined by the c++ language standard. However, is there any easy way to find out how your specific compiler will implement these say by writing some test code?
EDIT:- Using some of the answers below :-
```
#include <iostream>
using namespace std;
class A {
public:
int a;
virtual void func() {}
};
class B : public A {
public:
int b;
virtual void func() {}
};
class C {
public:
int c;
virtual void func() {}
};
class D : public A, public C {
public:
int d;
virtual void func() {}
};
class E : public C, public A {
public:
int e;
virtual void func() {}
};
class F : public A {
public:
int f;
virtual void func() {}
};
class G : public B, public F {
public:
int g;
virtual void func() {}
};
int main() {
A a; B b; C c; D d; E e; F f; G g;
cout<<"A: "<<(size_t)&a.a-(size_t)&a<<"\n";
cout<<"B: "<<(size_t)&b.a-(size_t)&b<<" "<<(size_t)&b.b-(size_t)&b<<"\n";
cout<<"C: "<<(size_t)&c.c-(size_t)&c<<"\n";
cout<<"D: "<<(size_t)&d.a-(size_t)&d<<" "<<(size_t)&d.c-(size_t)&d<<" "<<(size_t)&d.d- (size_t)&d<<"\n";
cout<<"E: "<<(size_t)&e.a-(size_t)&e<<" "<<(size_t)&e.c-(size_t)&e<<" "<<(size_t)&e.e- (size_t)&e<<"\n";
cout<<"F: "<<(size_t)&f.a-(size_t)&f<<" "<<(size_t)&f.f-(size_t)&f<<"\n";
cout<<"G: "<<(size_t)&g.B::a-(size_t)&g<<" "<<(size_t)&g.F::a-(size_t)&g<<" " <<(size_t)&g.b-(size_t)&g<<" "<<(size_t)&g.f-(size_t)&g<<" "<<(size_t)&g.g-(size_t)&g<<"\n";
}
```
And the output is :-
```
A: 8
B: 8 12
C: 8
D: 8 24 28
E: 24 8 28
F: 8 12
G: 8 24 12 28 32
```
So all classes have got a v-ptr at loc 0 of size 8.
D has another v-ptr at location 16. Similarly for E.
G also seems to have a v-ptr at 16 although from my (limited) understanding I would have guessed it to have more. | 2011/12/29 | [
"https://Stackoverflow.com/questions/8672218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1098524/"
] | Visual Studio atleast has a [hidden compiler option](http://channel9.msdn.com/Shows/Going+Deep/C9-Lectures-Stephan-T-Lavavej-Advanced-STL-3-of-n) `/d1reportSingleClassLayout` (starting at ~32:00).
Usage: `/d1reportSingleClassLayoutCLASSNAME` where there shall be no whitespace between the compiler switch and `CLASSNAME` (obviously replace this with the name of the class you'e interested in). | As long as you stick to single inheritance, the subobjects are typically layed out in the order they are declared. A pointer is prepended to they type information at the front which is e.g. used for dynamic dispatch. Once multiple inheritance is incolved things become more complex, especially when virtual inheritance is involved.
To find precise information at least for one ABI flavour you can look for the Itanium ABI. This documents all these details. It is used as the C++ ABI at least on some Linux platforms (i.e. there multiple compilers can produce object files linked into one executable).
To determine the layout just print the addresses of subobjects of a give object. That said, unless you happen to implement a compiler it typically doesn't matter. The only real use of the object layout I doubd is arranging members to minimize padding. |
8,672,218 | I'm keen to know exactly how the classes will be arranged in memory esp. with inheritance and virtual functions.
I know that this is not defined by the c++ language standard. However, is there any easy way to find out how your specific compiler will implement these say by writing some test code?
EDIT:- Using some of the answers below :-
```
#include <iostream>
using namespace std;
class A {
public:
int a;
virtual void func() {}
};
class B : public A {
public:
int b;
virtual void func() {}
};
class C {
public:
int c;
virtual void func() {}
};
class D : public A, public C {
public:
int d;
virtual void func() {}
};
class E : public C, public A {
public:
int e;
virtual void func() {}
};
class F : public A {
public:
int f;
virtual void func() {}
};
class G : public B, public F {
public:
int g;
virtual void func() {}
};
int main() {
A a; B b; C c; D d; E e; F f; G g;
cout<<"A: "<<(size_t)&a.a-(size_t)&a<<"\n";
cout<<"B: "<<(size_t)&b.a-(size_t)&b<<" "<<(size_t)&b.b-(size_t)&b<<"\n";
cout<<"C: "<<(size_t)&c.c-(size_t)&c<<"\n";
cout<<"D: "<<(size_t)&d.a-(size_t)&d<<" "<<(size_t)&d.c-(size_t)&d<<" "<<(size_t)&d.d- (size_t)&d<<"\n";
cout<<"E: "<<(size_t)&e.a-(size_t)&e<<" "<<(size_t)&e.c-(size_t)&e<<" "<<(size_t)&e.e- (size_t)&e<<"\n";
cout<<"F: "<<(size_t)&f.a-(size_t)&f<<" "<<(size_t)&f.f-(size_t)&f<<"\n";
cout<<"G: "<<(size_t)&g.B::a-(size_t)&g<<" "<<(size_t)&g.F::a-(size_t)&g<<" " <<(size_t)&g.b-(size_t)&g<<" "<<(size_t)&g.f-(size_t)&g<<" "<<(size_t)&g.g-(size_t)&g<<"\n";
}
```
And the output is :-
```
A: 8
B: 8 12
C: 8
D: 8 24 28
E: 24 8 28
F: 8 12
G: 8 24 12 28 32
```
So all classes have got a v-ptr at loc 0 of size 8.
D has another v-ptr at location 16. Similarly for E.
G also seems to have a v-ptr at 16 although from my (limited) understanding I would have guessed it to have more. | 2011/12/29 | [
"https://Stackoverflow.com/questions/8672218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1098524/"
] | Visual Studio atleast has a [hidden compiler option](http://channel9.msdn.com/Shows/Going+Deep/C9-Lectures-Stephan-T-Lavavej-Advanced-STL-3-of-n) `/d1reportSingleClassLayout` (starting at ~32:00).
Usage: `/d1reportSingleClassLayoutCLASSNAME` where there shall be no whitespace between the compiler switch and `CLASSNAME` (obviously replace this with the name of the class you'e interested in). | Create an object of class, cast pointer to it to your machine's word, use `sizeof` to find the size of the object, and examine the memory at the location. Something like this:
```
#include <iostream>
class A
{
public:
unsigned long long int mData;
A() :
mData( 1 )
{
}
virtual ~A()
{
}
};
class B : public A
{
public:
unsigned long long int mData1;
B() :
A(), mData1( 2 )
{
}
};
int main( void )
{
B lB;
unsigned long long int * pB = ( unsigned long long int * )( &lB );
for( int i = 0; i < sizeof(B) / 8; i++ )
{
std::cout << *( pB + i ) << std::endl;
}
return ( 0 );
}
Program output (MSVC++ x86-64):
5358814688 // vptr
1 // A::mData
2 // B::mData1
```
On a side note, Stanley B. Lippman has excellent book ["Inside the C++ Object Model"](http://www.amazon.ca/Inside-Object-Model-Stanley-Lippman/dp/0201834545). |
8,672,218 | I'm keen to know exactly how the classes will be arranged in memory esp. with inheritance and virtual functions.
I know that this is not defined by the c++ language standard. However, is there any easy way to find out how your specific compiler will implement these say by writing some test code?
EDIT:- Using some of the answers below :-
```
#include <iostream>
using namespace std;
class A {
public:
int a;
virtual void func() {}
};
class B : public A {
public:
int b;
virtual void func() {}
};
class C {
public:
int c;
virtual void func() {}
};
class D : public A, public C {
public:
int d;
virtual void func() {}
};
class E : public C, public A {
public:
int e;
virtual void func() {}
};
class F : public A {
public:
int f;
virtual void func() {}
};
class G : public B, public F {
public:
int g;
virtual void func() {}
};
int main() {
A a; B b; C c; D d; E e; F f; G g;
cout<<"A: "<<(size_t)&a.a-(size_t)&a<<"\n";
cout<<"B: "<<(size_t)&b.a-(size_t)&b<<" "<<(size_t)&b.b-(size_t)&b<<"\n";
cout<<"C: "<<(size_t)&c.c-(size_t)&c<<"\n";
cout<<"D: "<<(size_t)&d.a-(size_t)&d<<" "<<(size_t)&d.c-(size_t)&d<<" "<<(size_t)&d.d- (size_t)&d<<"\n";
cout<<"E: "<<(size_t)&e.a-(size_t)&e<<" "<<(size_t)&e.c-(size_t)&e<<" "<<(size_t)&e.e- (size_t)&e<<"\n";
cout<<"F: "<<(size_t)&f.a-(size_t)&f<<" "<<(size_t)&f.f-(size_t)&f<<"\n";
cout<<"G: "<<(size_t)&g.B::a-(size_t)&g<<" "<<(size_t)&g.F::a-(size_t)&g<<" " <<(size_t)&g.b-(size_t)&g<<" "<<(size_t)&g.f-(size_t)&g<<" "<<(size_t)&g.g-(size_t)&g<<"\n";
}
```
And the output is :-
```
A: 8
B: 8 12
C: 8
D: 8 24 28
E: 24 8 28
F: 8 12
G: 8 24 12 28 32
```
So all classes have got a v-ptr at loc 0 of size 8.
D has another v-ptr at location 16. Similarly for E.
G also seems to have a v-ptr at 16 although from my (limited) understanding I would have guessed it to have more. | 2011/12/29 | [
"https://Stackoverflow.com/questions/8672218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1098524/"
] | One way is to print out the offsets of all the members:
```
class Parent{
public:
int a;
int b;
virtual void foo(){
cout << "parent" << endl;
}
};
class Child : public Parent{
public:
int c;
int d;
virtual void foo(){
cout << "child" << endl;
}
};
int main(){
Parent p;
Child c;
p.foo();
c.foo();
cout << "Parent Offset a = " << (size_t)&p.a - (size_t)&p << endl;
cout << "Parent Offset b = " << (size_t)&p.b - (size_t)&p << endl;
cout << "Child Offset a = " << (size_t)&c.a - (size_t)&c << endl;
cout << "Child Offset b = " << (size_t)&c.b - (size_t)&c << endl;
cout << "Child Offset c = " << (size_t)&c.c - (size_t)&c << endl;
cout << "Child Offset d = " << (size_t)&c.d - (size_t)&c << endl;
system("pause");
}
```
**Output:**
```
parent
child
Parent Offset a = 8
Parent Offset b = 12
Child Offset a = 8
Child Offset b = 12
Child Offset c = 16
Child Offset d = 20
```
So you can see all the offsets here. You'll notice that there's nothing at offset 0, as that is presumably where the pointer to the [vtable](http://en.wikipedia.org/wiki/Virtual_method_table) goes.
Also notice that the inherited members have the same offsets in both Child and Parent. | The best way is probably writing a few simple test cases and then compile and debug them in assembler (all optimization off): running one instruction at a time you'll see where everything fits.
At least that's the way I learned it.
And if you find any case particularly challenging, post in in SO! |
8,672,218 | I'm keen to know exactly how the classes will be arranged in memory esp. with inheritance and virtual functions.
I know that this is not defined by the c++ language standard. However, is there any easy way to find out how your specific compiler will implement these say by writing some test code?
EDIT:- Using some of the answers below :-
```
#include <iostream>
using namespace std;
class A {
public:
int a;
virtual void func() {}
};
class B : public A {
public:
int b;
virtual void func() {}
};
class C {
public:
int c;
virtual void func() {}
};
class D : public A, public C {
public:
int d;
virtual void func() {}
};
class E : public C, public A {
public:
int e;
virtual void func() {}
};
class F : public A {
public:
int f;
virtual void func() {}
};
class G : public B, public F {
public:
int g;
virtual void func() {}
};
int main() {
A a; B b; C c; D d; E e; F f; G g;
cout<<"A: "<<(size_t)&a.a-(size_t)&a<<"\n";
cout<<"B: "<<(size_t)&b.a-(size_t)&b<<" "<<(size_t)&b.b-(size_t)&b<<"\n";
cout<<"C: "<<(size_t)&c.c-(size_t)&c<<"\n";
cout<<"D: "<<(size_t)&d.a-(size_t)&d<<" "<<(size_t)&d.c-(size_t)&d<<" "<<(size_t)&d.d- (size_t)&d<<"\n";
cout<<"E: "<<(size_t)&e.a-(size_t)&e<<" "<<(size_t)&e.c-(size_t)&e<<" "<<(size_t)&e.e- (size_t)&e<<"\n";
cout<<"F: "<<(size_t)&f.a-(size_t)&f<<" "<<(size_t)&f.f-(size_t)&f<<"\n";
cout<<"G: "<<(size_t)&g.B::a-(size_t)&g<<" "<<(size_t)&g.F::a-(size_t)&g<<" " <<(size_t)&g.b-(size_t)&g<<" "<<(size_t)&g.f-(size_t)&g<<" "<<(size_t)&g.g-(size_t)&g<<"\n";
}
```
And the output is :-
```
A: 8
B: 8 12
C: 8
D: 8 24 28
E: 24 8 28
F: 8 12
G: 8 24 12 28 32
```
So all classes have got a v-ptr at loc 0 of size 8.
D has another v-ptr at location 16. Similarly for E.
G also seems to have a v-ptr at 16 although from my (limited) understanding I would have guessed it to have more. | 2011/12/29 | [
"https://Stackoverflow.com/questions/8672218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1098524/"
] | Create an object of class, cast pointer to it to your machine's word, use `sizeof` to find the size of the object, and examine the memory at the location. Something like this:
```
#include <iostream>
class A
{
public:
unsigned long long int mData;
A() :
mData( 1 )
{
}
virtual ~A()
{
}
};
class B : public A
{
public:
unsigned long long int mData1;
B() :
A(), mData1( 2 )
{
}
};
int main( void )
{
B lB;
unsigned long long int * pB = ( unsigned long long int * )( &lB );
for( int i = 0; i < sizeof(B) / 8; i++ )
{
std::cout << *( pB + i ) << std::endl;
}
return ( 0 );
}
Program output (MSVC++ x86-64):
5358814688 // vptr
1 // A::mData
2 // B::mData1
```
On a side note, Stanley B. Lippman has excellent book ["Inside the C++ Object Model"](http://www.amazon.ca/Inside-Object-Model-Stanley-Lippman/dp/0201834545). | The best way is probably writing a few simple test cases and then compile and debug them in assembler (all optimization off): running one instruction at a time you'll see where everything fits.
At least that's the way I learned it.
And if you find any case particularly challenging, post in in SO! |
8,672,218 | I'm keen to know exactly how the classes will be arranged in memory esp. with inheritance and virtual functions.
I know that this is not defined by the c++ language standard. However, is there any easy way to find out how your specific compiler will implement these say by writing some test code?
EDIT:- Using some of the answers below :-
```
#include <iostream>
using namespace std;
class A {
public:
int a;
virtual void func() {}
};
class B : public A {
public:
int b;
virtual void func() {}
};
class C {
public:
int c;
virtual void func() {}
};
class D : public A, public C {
public:
int d;
virtual void func() {}
};
class E : public C, public A {
public:
int e;
virtual void func() {}
};
class F : public A {
public:
int f;
virtual void func() {}
};
class G : public B, public F {
public:
int g;
virtual void func() {}
};
int main() {
A a; B b; C c; D d; E e; F f; G g;
cout<<"A: "<<(size_t)&a.a-(size_t)&a<<"\n";
cout<<"B: "<<(size_t)&b.a-(size_t)&b<<" "<<(size_t)&b.b-(size_t)&b<<"\n";
cout<<"C: "<<(size_t)&c.c-(size_t)&c<<"\n";
cout<<"D: "<<(size_t)&d.a-(size_t)&d<<" "<<(size_t)&d.c-(size_t)&d<<" "<<(size_t)&d.d- (size_t)&d<<"\n";
cout<<"E: "<<(size_t)&e.a-(size_t)&e<<" "<<(size_t)&e.c-(size_t)&e<<" "<<(size_t)&e.e- (size_t)&e<<"\n";
cout<<"F: "<<(size_t)&f.a-(size_t)&f<<" "<<(size_t)&f.f-(size_t)&f<<"\n";
cout<<"G: "<<(size_t)&g.B::a-(size_t)&g<<" "<<(size_t)&g.F::a-(size_t)&g<<" " <<(size_t)&g.b-(size_t)&g<<" "<<(size_t)&g.f-(size_t)&g<<" "<<(size_t)&g.g-(size_t)&g<<"\n";
}
```
And the output is :-
```
A: 8
B: 8 12
C: 8
D: 8 24 28
E: 24 8 28
F: 8 12
G: 8 24 12 28 32
```
So all classes have got a v-ptr at loc 0 of size 8.
D has another v-ptr at location 16. Similarly for E.
G also seems to have a v-ptr at 16 although from my (limited) understanding I would have guessed it to have more. | 2011/12/29 | [
"https://Stackoverflow.com/questions/8672218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1098524/"
] | One way is to print out the offsets of all the members:
```
class Parent{
public:
int a;
int b;
virtual void foo(){
cout << "parent" << endl;
}
};
class Child : public Parent{
public:
int c;
int d;
virtual void foo(){
cout << "child" << endl;
}
};
int main(){
Parent p;
Child c;
p.foo();
c.foo();
cout << "Parent Offset a = " << (size_t)&p.a - (size_t)&p << endl;
cout << "Parent Offset b = " << (size_t)&p.b - (size_t)&p << endl;
cout << "Child Offset a = " << (size_t)&c.a - (size_t)&c << endl;
cout << "Child Offset b = " << (size_t)&c.b - (size_t)&c << endl;
cout << "Child Offset c = " << (size_t)&c.c - (size_t)&c << endl;
cout << "Child Offset d = " << (size_t)&c.d - (size_t)&c << endl;
system("pause");
}
```
**Output:**
```
parent
child
Parent Offset a = 8
Parent Offset b = 12
Child Offset a = 8
Child Offset b = 12
Child Offset c = 16
Child Offset d = 20
```
So you can see all the offsets here. You'll notice that there's nothing at offset 0, as that is presumably where the pointer to the [vtable](http://en.wikipedia.org/wiki/Virtual_method_table) goes.
Also notice that the inherited members have the same offsets in both Child and Parent. | As long as you stick to single inheritance, the subobjects are typically layed out in the order they are declared. A pointer is prepended to they type information at the front which is e.g. used for dynamic dispatch. Once multiple inheritance is incolved things become more complex, especially when virtual inheritance is involved.
To find precise information at least for one ABI flavour you can look for the Itanium ABI. This documents all these details. It is used as the C++ ABI at least on some Linux platforms (i.e. there multiple compilers can produce object files linked into one executable).
To determine the layout just print the addresses of subobjects of a give object. That said, unless you happen to implement a compiler it typically doesn't matter. The only real use of the object layout I doubd is arranging members to minimize padding. |
8,672,218 | I'm keen to know exactly how the classes will be arranged in memory esp. with inheritance and virtual functions.
I know that this is not defined by the c++ language standard. However, is there any easy way to find out how your specific compiler will implement these say by writing some test code?
EDIT:- Using some of the answers below :-
```
#include <iostream>
using namespace std;
class A {
public:
int a;
virtual void func() {}
};
class B : public A {
public:
int b;
virtual void func() {}
};
class C {
public:
int c;
virtual void func() {}
};
class D : public A, public C {
public:
int d;
virtual void func() {}
};
class E : public C, public A {
public:
int e;
virtual void func() {}
};
class F : public A {
public:
int f;
virtual void func() {}
};
class G : public B, public F {
public:
int g;
virtual void func() {}
};
int main() {
A a; B b; C c; D d; E e; F f; G g;
cout<<"A: "<<(size_t)&a.a-(size_t)&a<<"\n";
cout<<"B: "<<(size_t)&b.a-(size_t)&b<<" "<<(size_t)&b.b-(size_t)&b<<"\n";
cout<<"C: "<<(size_t)&c.c-(size_t)&c<<"\n";
cout<<"D: "<<(size_t)&d.a-(size_t)&d<<" "<<(size_t)&d.c-(size_t)&d<<" "<<(size_t)&d.d- (size_t)&d<<"\n";
cout<<"E: "<<(size_t)&e.a-(size_t)&e<<" "<<(size_t)&e.c-(size_t)&e<<" "<<(size_t)&e.e- (size_t)&e<<"\n";
cout<<"F: "<<(size_t)&f.a-(size_t)&f<<" "<<(size_t)&f.f-(size_t)&f<<"\n";
cout<<"G: "<<(size_t)&g.B::a-(size_t)&g<<" "<<(size_t)&g.F::a-(size_t)&g<<" " <<(size_t)&g.b-(size_t)&g<<" "<<(size_t)&g.f-(size_t)&g<<" "<<(size_t)&g.g-(size_t)&g<<"\n";
}
```
And the output is :-
```
A: 8
B: 8 12
C: 8
D: 8 24 28
E: 24 8 28
F: 8 12
G: 8 24 12 28 32
```
So all classes have got a v-ptr at loc 0 of size 8.
D has another v-ptr at location 16. Similarly for E.
G also seems to have a v-ptr at 16 although from my (limited) understanding I would have guessed it to have more. | 2011/12/29 | [
"https://Stackoverflow.com/questions/8672218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1098524/"
] | One way is to print out the offsets of all the members:
```
class Parent{
public:
int a;
int b;
virtual void foo(){
cout << "parent" << endl;
}
};
class Child : public Parent{
public:
int c;
int d;
virtual void foo(){
cout << "child" << endl;
}
};
int main(){
Parent p;
Child c;
p.foo();
c.foo();
cout << "Parent Offset a = " << (size_t)&p.a - (size_t)&p << endl;
cout << "Parent Offset b = " << (size_t)&p.b - (size_t)&p << endl;
cout << "Child Offset a = " << (size_t)&c.a - (size_t)&c << endl;
cout << "Child Offset b = " << (size_t)&c.b - (size_t)&c << endl;
cout << "Child Offset c = " << (size_t)&c.c - (size_t)&c << endl;
cout << "Child Offset d = " << (size_t)&c.d - (size_t)&c << endl;
system("pause");
}
```
**Output:**
```
parent
child
Parent Offset a = 8
Parent Offset b = 12
Child Offset a = 8
Child Offset b = 12
Child Offset c = 16
Child Offset d = 20
```
So you can see all the offsets here. You'll notice that there's nothing at offset 0, as that is presumably where the pointer to the [vtable](http://en.wikipedia.org/wiki/Virtual_method_table) goes.
Also notice that the inherited members have the same offsets in both Child and Parent. | Create an object of class, cast pointer to it to your machine's word, use `sizeof` to find the size of the object, and examine the memory at the location. Something like this:
```
#include <iostream>
class A
{
public:
unsigned long long int mData;
A() :
mData( 1 )
{
}
virtual ~A()
{
}
};
class B : public A
{
public:
unsigned long long int mData1;
B() :
A(), mData1( 2 )
{
}
};
int main( void )
{
B lB;
unsigned long long int * pB = ( unsigned long long int * )( &lB );
for( int i = 0; i < sizeof(B) / 8; i++ )
{
std::cout << *( pB + i ) << std::endl;
}
return ( 0 );
}
Program output (MSVC++ x86-64):
5358814688 // vptr
1 // A::mData
2 // B::mData1
```
On a side note, Stanley B. Lippman has excellent book ["Inside the C++ Object Model"](http://www.amazon.ca/Inside-Object-Model-Stanley-Lippman/dp/0201834545). |
8,672,218 | I'm keen to know exactly how the classes will be arranged in memory esp. with inheritance and virtual functions.
I know that this is not defined by the c++ language standard. However, is there any easy way to find out how your specific compiler will implement these say by writing some test code?
EDIT:- Using some of the answers below :-
```
#include <iostream>
using namespace std;
class A {
public:
int a;
virtual void func() {}
};
class B : public A {
public:
int b;
virtual void func() {}
};
class C {
public:
int c;
virtual void func() {}
};
class D : public A, public C {
public:
int d;
virtual void func() {}
};
class E : public C, public A {
public:
int e;
virtual void func() {}
};
class F : public A {
public:
int f;
virtual void func() {}
};
class G : public B, public F {
public:
int g;
virtual void func() {}
};
int main() {
A a; B b; C c; D d; E e; F f; G g;
cout<<"A: "<<(size_t)&a.a-(size_t)&a<<"\n";
cout<<"B: "<<(size_t)&b.a-(size_t)&b<<" "<<(size_t)&b.b-(size_t)&b<<"\n";
cout<<"C: "<<(size_t)&c.c-(size_t)&c<<"\n";
cout<<"D: "<<(size_t)&d.a-(size_t)&d<<" "<<(size_t)&d.c-(size_t)&d<<" "<<(size_t)&d.d- (size_t)&d<<"\n";
cout<<"E: "<<(size_t)&e.a-(size_t)&e<<" "<<(size_t)&e.c-(size_t)&e<<" "<<(size_t)&e.e- (size_t)&e<<"\n";
cout<<"F: "<<(size_t)&f.a-(size_t)&f<<" "<<(size_t)&f.f-(size_t)&f<<"\n";
cout<<"G: "<<(size_t)&g.B::a-(size_t)&g<<" "<<(size_t)&g.F::a-(size_t)&g<<" " <<(size_t)&g.b-(size_t)&g<<" "<<(size_t)&g.f-(size_t)&g<<" "<<(size_t)&g.g-(size_t)&g<<"\n";
}
```
And the output is :-
```
A: 8
B: 8 12
C: 8
D: 8 24 28
E: 24 8 28
F: 8 12
G: 8 24 12 28 32
```
So all classes have got a v-ptr at loc 0 of size 8.
D has another v-ptr at location 16. Similarly for E.
G also seems to have a v-ptr at 16 although from my (limited) understanding I would have guessed it to have more. | 2011/12/29 | [
"https://Stackoverflow.com/questions/8672218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1098524/"
] | Create an object of class, cast pointer to it to your machine's word, use `sizeof` to find the size of the object, and examine the memory at the location. Something like this:
```
#include <iostream>
class A
{
public:
unsigned long long int mData;
A() :
mData( 1 )
{
}
virtual ~A()
{
}
};
class B : public A
{
public:
unsigned long long int mData1;
B() :
A(), mData1( 2 )
{
}
};
int main( void )
{
B lB;
unsigned long long int * pB = ( unsigned long long int * )( &lB );
for( int i = 0; i < sizeof(B) / 8; i++ )
{
std::cout << *( pB + i ) << std::endl;
}
return ( 0 );
}
Program output (MSVC++ x86-64):
5358814688 // vptr
1 // A::mData
2 // B::mData1
```
On a side note, Stanley B. Lippman has excellent book ["Inside the C++ Object Model"](http://www.amazon.ca/Inside-Object-Model-Stanley-Lippman/dp/0201834545). | As long as you stick to single inheritance, the subobjects are typically layed out in the order they are declared. A pointer is prepended to they type information at the front which is e.g. used for dynamic dispatch. Once multiple inheritance is incolved things become more complex, especially when virtual inheritance is involved.
To find precise information at least for one ABI flavour you can look for the Itanium ABI. This documents all these details. It is used as the C++ ABI at least on some Linux platforms (i.e. there multiple compilers can produce object files linked into one executable).
To determine the layout just print the addresses of subobjects of a give object. That said, unless you happen to implement a compiler it typically doesn't matter. The only real use of the object layout I doubd is arranging members to minimize padding. |
58,701,483 | I am trying to use the Java AnyChart data visualization library (<https://github.com/AnyChart/AnyChart-Android>) in my Android app. However, when I try adding the required imports for the app:
```
import com.anychart.AnyChart;
import com.anychart.AnyChartView;
import com.anychart.DataEntry;
import com.anychart.Pie;
import com.anychart.ValueDataEntry;
```
I get the following errors:
```
Unresolved reference: DataEntry
Unresolved reference: Pie
Unresolved reference: ValueDataEntry
```
This seems strange, given that my gradle compiles without error and that the first two statements do not show an "Unresolved reference" error. I have tried **Invalidating Caches and Restart** but that has not worked. I have tried replacing `com.anychart` with `com.anychart.anychart`, but that has not worked either. | 2019/11/04 | [
"https://Stackoverflow.com/questions/58701483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7789984/"
] | You might have missed this part:
a) Add this to the root `build.gradle` at the end of repositories:
```
allprojects {
repositories {
...
maven { url "https://jitpack.io" }
}
}
```
b) Add the dependency to the project `build.gradle`:
```
dependencies {
implementation "com.github.AnyChart:AnyChart-Android:1.1.2"
}
```
It's simply [`com.anychart.AnyChart`](https://github.com/AnyChart/AnyChart-Android/blob/master/anychart/src/main/java/com/anychart/AnyChart.java). | Typo:
```
import com.anychart.AnyChart;
import com.anychart.AnyChartView;
import com.anychart.DataEntry;
import com.anychart.Pie;
import com.anychart.ValueDataEntry;
```
Solution:
```
import com.anychart.anychart.AnyChart; // Based off of the link
import com.anychart.anychart.AnyChartView; // Based off of the link
import com.anychart.anychart.DataEntry;
import com.anychart.anychart.Pie;
import com.anychart.anychart.ValueDataEntry;
```
Also, I found this by looking [here](https://www.anychart.com/de/technical-integrations/samples/android-charts). |
73,144,659 | Why can't I read the properties using `${ array[a].name }` with For of ?
I made an ex with an array of objects just to simplify the problem diagnosis
```js
const movie = [{
name: "Shrek",
year: 2001
},
{
name: "Shrek 2",
year: 2004
},
{
name: "Shrek Third",
year: 2007
},
{
name: "Shrek For Ever",
year: 2010
}
]
forIn = array => {
for (a in array) {
console.log(`Index ${a} in Array Object`)
console.log(`FOR IN array[a] -> ${array[a]}`, array[a])
console.log(`FOR IN array[a].nome -> ${array[a].nome}`)
console.log(`FOR IN array[a].year -> ${array[a].year}`)
console.log('')
}
}
forOf = array => {
for (a of array) {
console.log(`Index of Array -> Object`)
console.log(a)
console.log(array[a])
console.log('')
/* console.log(`FOR OF array[a].name -> ${array[a].name}`) ERROR LINE */
}
}
forIn(movie)
console.log('')
forOf(movie)
``` | 2022/07/27 | [
"https://Stackoverflow.com/questions/73144659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19635802/"
] | As mentioned in the comments, it is pretty easy to obtain in R with `pROC`. You need to convert `val` to a numeric vector first, then you can create the ROC curve, let's call it `cut_roc`:
```
cut_$val <- as.numeric(cut_$val)
library(pROC)
cut_roc <- roc(cut_$ref, cut_$val)
```
Then it's as simple as a call to `coords` with `x="best"` to get the best threshold(s) (youden is the default so the last argument is optional):
```
coords(cut_roc, x="best", best.method="youden")
# threshold specificity sensitivity
# 1 1.15 0.125 1.000
# 2 1.45 0.250 0.875
# 3 2.25 0.625 0.500
# 4 2.45 0.750 0.375
# 5 2.60 0.875 0.250
```
Note that in this specific ROC curve, multiple points of the curve maximize the Youden index. | Consider this a comment, not an answer; see the answer by @Calimo instead.
I thought it might be interesting to plot the ROC curve with the "best" thresholds. Unfortunately, as the figure shows, the binary classifier behind this ROC curve doesn't have much discriminative ability at any threshold.
Here is some R code. Run it after @Calimo's code which shows how to create the `cut_roc` object.
```r
par(pty = "s") # Make this ROC plot square
plot(cut_roc, print.thres = "best", print.thres.best.method = "youden")
```

```r
par(pty = "m") # Reset the `pty` parameter
```
Created on 2022-07-28 by the [reprex package](https://reprex.tidyverse.org) (v2.0.1) |
19,776,159 | For laboratory I need to run android 1.5 emulator. Yes.. Very old version. Does anyone have emulator image or idea how to stimulate it? | 2013/11/04 | [
"https://Stackoverflow.com/questions/19776159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1978482/"
] | In the Android SDK Manager, if you check the "Obsolete" box you'll see the 1.5 SDK is available, not sure if this will get you what you need or not, but it's a start.
 | Got it!
But not sure how, after API 3 instalation and computer reboot or after this file instalation <http://www.filecrop.com/70027503/index.html>
Safety will be first try install 1.5 SDK and reboot computer, othervise check this link by antivirus
 |
34,695,934 | I am trying to make a super basic program that involves a picture and sound popping up every time I click F4. I have the background of the program set to green, because I am going to be using it as a green screen for the picture. I don't have much experience with VB, but since I couldn't find a program to do this on the web, I decided to take a swing and try to make it myself. (Failed...) Anyways, this is what I got so far.
```
Public Class Form1
Private Sub Form1_KeyPress(KeyAscii As Integer)
If (Chr(KeyAscii) = "115") Then Form1.Picture = loadpicture("directory")
End Sub
End Class
```
Note: "Directory" is not what I have in loadpicture(). | 2016/01/09 | [
"https://Stackoverflow.com/questions/34695934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5365441/"
] | Try this:
```
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.KeyPreview = True 'This enable the key event on the form (me).
End Sub
Private Sub Form1_KeyUp(sender As Object, e As KeyEventArgs) Handles Me.KeyUp
If e.KeyCode = Keys.F4 Then Me.BackgroundImage = Image.FromFile("C:\image.jpg")
End Sub
``` | This is the final code that also includes an audio clip that plays when the key is pressed as well!
```
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.KeyPreview = True 'This enable the key event on the form (me).
End Sub
Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
If e.KeyCode = Keys.F4 Then Me.BackgroundImage = Image.FromFile("C:\image.jpg")
If e.KeyCode = Keys.F4 Then My.Computer.Audio.Play("C:\audio.wav", AudioPlayMode.Background)
End Sub
Private Sub Form1_KeyUp(sender As Object, e As KeyEventArgs) Handles Me.KeyUp
If e.KeyCode = Keys.F4 Then Me.BackgroundImage = Nothing
End Sub
End Class
``` |
21,180,197 | I have integrated the new google maps api v2 fragment in a view pager. When i move from the map tab(street view screen) to second tab(client detail), a black view shown instend of data into fragment. anyone know about solution.??
ScreenShot:

Code:
ListingStreetViewFragment.java
```
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View inflatedView = inflater.inflate(R.layout.map_view, container, false);
try {
MapsInitializer.initialize(getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
// TODO handle this situation
}
markers = new Hashtable<String, String>();
mMapView = (MapView) inflatedView.findViewById(R.id.map);
mMapView.onCreate(mBundle);
mMapView.onResume();
setUpMapIfNeeded(inflatedView);
return inflatedView;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBundle = savedInstanceState;
}
// mapping between map object with xml layout.
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((MapView) inflatedView.findViewById(R.id.map)).getMap();
if (mMap != null) {
mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter());
setUpMap();
}
}
}
//set location on map and show marker on random location
private void setUpMap() {
// random latitude and logitude
// Adding a marker
MarkerOptions marker = new MarkerOptions().position(
new LatLng(53.558, 9.927))
.title("Hello Maps ");
marker.snippet("dinet");
// changing marker color
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
mMap.addMarker(marker);
// Move the camera to last position with a zoom level
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(53.558,
9.927)).zoom(16).build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
@Override
public void onResume() {
if (null != mMapView)
mMapView.onResume();
super.onResume();
}
@Override
public void onPause() {
super.onPause();
if (null != mMapView)
mMapView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
if (null != mMapView)
mMapView.onDestroy();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (null != mMapView)
mMapView.onSaveInstanceState(outState);
}
@Override
public void onLowMemory() {
super.onLowMemory();
if (null != mMapView)
mMapView.onLowMemory();
}
```
ListingClientDetailFragment.java
```
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.client_detail, container, false);
initUi(rootView);
idval = ListingListFragment.cid;
System.out.println("SET: " + idval);
setValues();
return rootView;
}
protected void initUi(View v){
db = new Databasehelper(getActivity());
cDetail = new HashMap<String, String>();
tvName = (TextView)v.findViewById(R.id.tvName);
tvType = (TextView)v.findViewById(R.id.tvType);
tvStatus = (TextView)v.findViewById(R.id.tvStatus);
tvEmail = (TextView)v.findViewById(R.id.tvEmail);
tvPhone = (TextView)v.findViewById(R.id.tvPhone);
ivCall = (ImageView)v.findViewById(R.id.ivCall);
ivMsg = (ImageView)v.findViewById(R.id.ivMsg);
}
//get data from database and set into controls.
protected void setValues(){
cDetail = db.getClientDetail(idval);
tvName.setText(cDetail.get("name"));
tvType.setText(cDetail.get("type"));
tvStatus.setText(cDetail.get("status"));
tvEmail.setText(cDetail.get("email"));
tvPhone.setText(cDetail.get("phone"));
}
```
and there is no errors display in logcat. so, i cant trace it from there. | 2014/01/17 | [
"https://Stackoverflow.com/questions/21180197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1581185/"
] | As far as google is concerned I am pretty sure that the API is deprecated and is not working anymore. you can probably use Yahoo finance api, They have api for csv downloads and via yql.
Refer: <https://code.google.com/p/yahoo-finance-managed/wiki/YahooFinanceAPIs>
As far as realtime is conecrned, I suggest look at yahoo web services. Following is an example:
<http://finance.yahoo.com/webservice/v1/symbols/ITC.NS,ITC.BO/quote?format=json>
If you do not provide format, it will return a XML.
How would you make it realtime without refreshing or Ajax?
You can create a pubsub model and make your application subscribe to your application, you will have to create this layer since the yahoo api is pull based and not push based. So you will need to pull stock quotes from yahoo and push them to your application. You can probably use JMS for java or sockets, whichever suits you. | I have rebuild my linux script:
```
#!/bin/bash
l="http://finance.yahoo.com/q?s="
a=$l$1
all=$(w3m -dump "$a")
echo "$all" | grep -A 5 'Visitors'
```
No need a tempory file. |
21,180,197 | I have integrated the new google maps api v2 fragment in a view pager. When i move from the map tab(street view screen) to second tab(client detail), a black view shown instend of data into fragment. anyone know about solution.??
ScreenShot:

Code:
ListingStreetViewFragment.java
```
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View inflatedView = inflater.inflate(R.layout.map_view, container, false);
try {
MapsInitializer.initialize(getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
// TODO handle this situation
}
markers = new Hashtable<String, String>();
mMapView = (MapView) inflatedView.findViewById(R.id.map);
mMapView.onCreate(mBundle);
mMapView.onResume();
setUpMapIfNeeded(inflatedView);
return inflatedView;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBundle = savedInstanceState;
}
// mapping between map object with xml layout.
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((MapView) inflatedView.findViewById(R.id.map)).getMap();
if (mMap != null) {
mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter());
setUpMap();
}
}
}
//set location on map and show marker on random location
private void setUpMap() {
// random latitude and logitude
// Adding a marker
MarkerOptions marker = new MarkerOptions().position(
new LatLng(53.558, 9.927))
.title("Hello Maps ");
marker.snippet("dinet");
// changing marker color
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
mMap.addMarker(marker);
// Move the camera to last position with a zoom level
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(53.558,
9.927)).zoom(16).build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
@Override
public void onResume() {
if (null != mMapView)
mMapView.onResume();
super.onResume();
}
@Override
public void onPause() {
super.onPause();
if (null != mMapView)
mMapView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
if (null != mMapView)
mMapView.onDestroy();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (null != mMapView)
mMapView.onSaveInstanceState(outState);
}
@Override
public void onLowMemory() {
super.onLowMemory();
if (null != mMapView)
mMapView.onLowMemory();
}
```
ListingClientDetailFragment.java
```
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.client_detail, container, false);
initUi(rootView);
idval = ListingListFragment.cid;
System.out.println("SET: " + idval);
setValues();
return rootView;
}
protected void initUi(View v){
db = new Databasehelper(getActivity());
cDetail = new HashMap<String, String>();
tvName = (TextView)v.findViewById(R.id.tvName);
tvType = (TextView)v.findViewById(R.id.tvType);
tvStatus = (TextView)v.findViewById(R.id.tvStatus);
tvEmail = (TextView)v.findViewById(R.id.tvEmail);
tvPhone = (TextView)v.findViewById(R.id.tvPhone);
ivCall = (ImageView)v.findViewById(R.id.ivCall);
ivMsg = (ImageView)v.findViewById(R.id.ivMsg);
}
//get data from database and set into controls.
protected void setValues(){
cDetail = db.getClientDetail(idval);
tvName.setText(cDetail.get("name"));
tvType.setText(cDetail.get("type"));
tvStatus.setText(cDetail.get("status"));
tvEmail.setText(cDetail.get("email"));
tvPhone.setText(cDetail.get("phone"));
}
```
and there is no errors display in logcat. so, i cant trace it from there. | 2014/01/17 | [
"https://Stackoverflow.com/questions/21180197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1581185/"
] | ```
<?php
class U_Yahoo{
private function file_get_contents_curl($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
//return the history quote from the simbol, default begin date is 90 day ago, the default end is today
public function getHistoryQuote($symbol, $begin = 90, $end = 0){
if(!$begin && !$end)
$begin = $end = 0;
$begin = Date('Y-m-d', strtotime("-{$begin} days"));
$end = Date('Y-m-d', strtotime("-{$end} days"));
$url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.historicaldata%20where%20symbol%20%3D%20%22$symbol%22%20and%20startDate%20%3D%20%22$begin%22%20and%20endDate%20%3D%20%22$end%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";
$jason_obj = json_decode( $this->file_get_contents_curl($url) );
return $jason_obj->query->results->quote;
}
//return not just the quote but others informations too
public function getCurrentData($symbol){
$is_array = is_array($symbol);
$imp_symbol = ($is_array)? implode('%22%2C%22', $symbol) : $symbol;
$url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quote%20where%20symbol%20in%20(%22$imp_symbol%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";
$jason_obj = json_decode( $this->file_get_contents_curl($url) );
$result = $jason_obj->query->results->quote;
return (is_array($symbol) and (count($symbol) == 1))? [$result] : $result;
}
//return all quotes from the param $symbol passed, if symbol is array, it will return other array indexed by the symbols
public function getCurrentQuote($symbol){
if(is_array($symbol)){
$symbol = empty($symbol)? ['GOOG'] : $symbol;
$data = $this->getCurrentData($symbol);
$result = [];
for ($c = 0; $c < count($data); $c++) {
$result[$data[$c]->Symbol] = $data[$c]->LastTradePriceOnly;
}
return $result;
}else
return $this->getCurrentData($symbol)->LastTradePriceOnly;
}
}
```
How use:
```
$yahoo = new U_Yahoo();
var_dump( $yahoo->getCurrentQuote('GOOG') );
var_dump( $yahoo->getCurrentQuote(['GOOG', 'YHOO']) );
var_dump( $yahoo->getCurrentData(['GOOG', 'YHOO']) );
var_dump( $yahoo->getHistoryQuote('YHOO', 20, 0) );
``` | The pass with yahoo work not. I have create two scripts to get the quote:
Shell script (quote.sh):
```
#!/bin/bash
a=http://finance.yahoo.com/q?s=
u=$a$1
w3m -dump "$u" > sortie.txt
grep -A 5 'Visitors' sortie.txt
```
PHP script (temp.php):
```
<?php
$Q = $_REQUEST['q'];
$output = shell_exec("/bin/sh ./quote.sh $Q");
$all_lines=explode(chr(10), $output);
$data=$all_lines[2];
$p1=strpos($data,'(');
$p2=strpos($data,')');
$ps=substr($data,$p1+1,$p2-$p1-1);
$p=strpos($data,'+');
if($p<1){$p=strpos($data,'-');}
$v=substr($data,0,$p);
$change=substr($data,$p,$p1-$p);
echo $Q.':<br>';
echo "%= $ps<br>";
echo "value= $v<br>";
echo "change= $change<br>";
?>
```
Usage: http://localhost/temp.php?q=goog |
21,180,197 | I have integrated the new google maps api v2 fragment in a view pager. When i move from the map tab(street view screen) to second tab(client detail), a black view shown instend of data into fragment. anyone know about solution.??
ScreenShot:

Code:
ListingStreetViewFragment.java
```
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View inflatedView = inflater.inflate(R.layout.map_view, container, false);
try {
MapsInitializer.initialize(getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
// TODO handle this situation
}
markers = new Hashtable<String, String>();
mMapView = (MapView) inflatedView.findViewById(R.id.map);
mMapView.onCreate(mBundle);
mMapView.onResume();
setUpMapIfNeeded(inflatedView);
return inflatedView;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBundle = savedInstanceState;
}
// mapping between map object with xml layout.
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((MapView) inflatedView.findViewById(R.id.map)).getMap();
if (mMap != null) {
mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter());
setUpMap();
}
}
}
//set location on map and show marker on random location
private void setUpMap() {
// random latitude and logitude
// Adding a marker
MarkerOptions marker = new MarkerOptions().position(
new LatLng(53.558, 9.927))
.title("Hello Maps ");
marker.snippet("dinet");
// changing marker color
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
mMap.addMarker(marker);
// Move the camera to last position with a zoom level
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(53.558,
9.927)).zoom(16).build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
@Override
public void onResume() {
if (null != mMapView)
mMapView.onResume();
super.onResume();
}
@Override
public void onPause() {
super.onPause();
if (null != mMapView)
mMapView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
if (null != mMapView)
mMapView.onDestroy();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (null != mMapView)
mMapView.onSaveInstanceState(outState);
}
@Override
public void onLowMemory() {
super.onLowMemory();
if (null != mMapView)
mMapView.onLowMemory();
}
```
ListingClientDetailFragment.java
```
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.client_detail, container, false);
initUi(rootView);
idval = ListingListFragment.cid;
System.out.println("SET: " + idval);
setValues();
return rootView;
}
protected void initUi(View v){
db = new Databasehelper(getActivity());
cDetail = new HashMap<String, String>();
tvName = (TextView)v.findViewById(R.id.tvName);
tvType = (TextView)v.findViewById(R.id.tvType);
tvStatus = (TextView)v.findViewById(R.id.tvStatus);
tvEmail = (TextView)v.findViewById(R.id.tvEmail);
tvPhone = (TextView)v.findViewById(R.id.tvPhone);
ivCall = (ImageView)v.findViewById(R.id.ivCall);
ivMsg = (ImageView)v.findViewById(R.id.ivMsg);
}
//get data from database and set into controls.
protected void setValues(){
cDetail = db.getClientDetail(idval);
tvName.setText(cDetail.get("name"));
tvType.setText(cDetail.get("type"));
tvStatus.setText(cDetail.get("status"));
tvEmail.setText(cDetail.get("email"));
tvPhone.setText(cDetail.get("phone"));
}
```
and there is no errors display in logcat. so, i cant trace it from there. | 2014/01/17 | [
"https://Stackoverflow.com/questions/21180197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1581185/"
] | As far as google is concerned I am pretty sure that the API is deprecated and is not working anymore. you can probably use Yahoo finance api, They have api for csv downloads and via yql.
Refer: <https://code.google.com/p/yahoo-finance-managed/wiki/YahooFinanceAPIs>
As far as realtime is conecrned, I suggest look at yahoo web services. Following is an example:
<http://finance.yahoo.com/webservice/v1/symbols/ITC.NS,ITC.BO/quote?format=json>
If you do not provide format, it will return a XML.
How would you make it realtime without refreshing or Ajax?
You can create a pubsub model and make your application subscribe to your application, you will have to create this layer since the yahoo api is pull based and not push based. So you will need to pull stock quotes from yahoo and push them to your application. You can probably use JMS for java or sockets, whichever suits you. | The pass with yahoo work not. I have create two scripts to get the quote:
Shell script (quote.sh):
```
#!/bin/bash
a=http://finance.yahoo.com/q?s=
u=$a$1
w3m -dump "$u" > sortie.txt
grep -A 5 'Visitors' sortie.txt
```
PHP script (temp.php):
```
<?php
$Q = $_REQUEST['q'];
$output = shell_exec("/bin/sh ./quote.sh $Q");
$all_lines=explode(chr(10), $output);
$data=$all_lines[2];
$p1=strpos($data,'(');
$p2=strpos($data,')');
$ps=substr($data,$p1+1,$p2-$p1-1);
$p=strpos($data,'+');
if($p<1){$p=strpos($data,'-');}
$v=substr($data,0,$p);
$change=substr($data,$p,$p1-$p);
echo $Q.':<br>';
echo "%= $ps<br>";
echo "value= $v<br>";
echo "change= $change<br>";
?>
```
Usage: http://localhost/temp.php?q=goog |
21,180,197 | I have integrated the new google maps api v2 fragment in a view pager. When i move from the map tab(street view screen) to second tab(client detail), a black view shown instend of data into fragment. anyone know about solution.??
ScreenShot:

Code:
ListingStreetViewFragment.java
```
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View inflatedView = inflater.inflate(R.layout.map_view, container, false);
try {
MapsInitializer.initialize(getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
// TODO handle this situation
}
markers = new Hashtable<String, String>();
mMapView = (MapView) inflatedView.findViewById(R.id.map);
mMapView.onCreate(mBundle);
mMapView.onResume();
setUpMapIfNeeded(inflatedView);
return inflatedView;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBundle = savedInstanceState;
}
// mapping between map object with xml layout.
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((MapView) inflatedView.findViewById(R.id.map)).getMap();
if (mMap != null) {
mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter());
setUpMap();
}
}
}
//set location on map and show marker on random location
private void setUpMap() {
// random latitude and logitude
// Adding a marker
MarkerOptions marker = new MarkerOptions().position(
new LatLng(53.558, 9.927))
.title("Hello Maps ");
marker.snippet("dinet");
// changing marker color
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
mMap.addMarker(marker);
// Move the camera to last position with a zoom level
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(53.558,
9.927)).zoom(16).build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
@Override
public void onResume() {
if (null != mMapView)
mMapView.onResume();
super.onResume();
}
@Override
public void onPause() {
super.onPause();
if (null != mMapView)
mMapView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
if (null != mMapView)
mMapView.onDestroy();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (null != mMapView)
mMapView.onSaveInstanceState(outState);
}
@Override
public void onLowMemory() {
super.onLowMemory();
if (null != mMapView)
mMapView.onLowMemory();
}
```
ListingClientDetailFragment.java
```
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.client_detail, container, false);
initUi(rootView);
idval = ListingListFragment.cid;
System.out.println("SET: " + idval);
setValues();
return rootView;
}
protected void initUi(View v){
db = new Databasehelper(getActivity());
cDetail = new HashMap<String, String>();
tvName = (TextView)v.findViewById(R.id.tvName);
tvType = (TextView)v.findViewById(R.id.tvType);
tvStatus = (TextView)v.findViewById(R.id.tvStatus);
tvEmail = (TextView)v.findViewById(R.id.tvEmail);
tvPhone = (TextView)v.findViewById(R.id.tvPhone);
ivCall = (ImageView)v.findViewById(R.id.ivCall);
ivMsg = (ImageView)v.findViewById(R.id.ivMsg);
}
//get data from database and set into controls.
protected void setValues(){
cDetail = db.getClientDetail(idval);
tvName.setText(cDetail.get("name"));
tvType.setText(cDetail.get("type"));
tvStatus.setText(cDetail.get("status"));
tvEmail.setText(cDetail.get("email"));
tvPhone.setText(cDetail.get("phone"));
}
```
and there is no errors display in logcat. so, i cant trace it from there. | 2014/01/17 | [
"https://Stackoverflow.com/questions/21180197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1581185/"
] | check this web this may be what you want(Use it for realtime web application)
<http://express-io.org/>
<http://socket.io/>
Tutorials
<http://blog.nodeknockout.com/post/34243127010/knocking-out-socket-io> | I have rebuild my linux script:
```
#!/bin/bash
l="http://finance.yahoo.com/q?s="
a=$l$1
all=$(w3m -dump "$a")
echo "$all" | grep -A 5 'Visitors'
```
No need a tempory file. |
21,180,197 | I have integrated the new google maps api v2 fragment in a view pager. When i move from the map tab(street view screen) to second tab(client detail), a black view shown instend of data into fragment. anyone know about solution.??
ScreenShot:

Code:
ListingStreetViewFragment.java
```
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View inflatedView = inflater.inflate(R.layout.map_view, container, false);
try {
MapsInitializer.initialize(getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
// TODO handle this situation
}
markers = new Hashtable<String, String>();
mMapView = (MapView) inflatedView.findViewById(R.id.map);
mMapView.onCreate(mBundle);
mMapView.onResume();
setUpMapIfNeeded(inflatedView);
return inflatedView;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBundle = savedInstanceState;
}
// mapping between map object with xml layout.
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((MapView) inflatedView.findViewById(R.id.map)).getMap();
if (mMap != null) {
mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter());
setUpMap();
}
}
}
//set location on map and show marker on random location
private void setUpMap() {
// random latitude and logitude
// Adding a marker
MarkerOptions marker = new MarkerOptions().position(
new LatLng(53.558, 9.927))
.title("Hello Maps ");
marker.snippet("dinet");
// changing marker color
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
mMap.addMarker(marker);
// Move the camera to last position with a zoom level
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(53.558,
9.927)).zoom(16).build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
@Override
public void onResume() {
if (null != mMapView)
mMapView.onResume();
super.onResume();
}
@Override
public void onPause() {
super.onPause();
if (null != mMapView)
mMapView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
if (null != mMapView)
mMapView.onDestroy();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (null != mMapView)
mMapView.onSaveInstanceState(outState);
}
@Override
public void onLowMemory() {
super.onLowMemory();
if (null != mMapView)
mMapView.onLowMemory();
}
```
ListingClientDetailFragment.java
```
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.client_detail, container, false);
initUi(rootView);
idval = ListingListFragment.cid;
System.out.println("SET: " + idval);
setValues();
return rootView;
}
protected void initUi(View v){
db = new Databasehelper(getActivity());
cDetail = new HashMap<String, String>();
tvName = (TextView)v.findViewById(R.id.tvName);
tvType = (TextView)v.findViewById(R.id.tvType);
tvStatus = (TextView)v.findViewById(R.id.tvStatus);
tvEmail = (TextView)v.findViewById(R.id.tvEmail);
tvPhone = (TextView)v.findViewById(R.id.tvPhone);
ivCall = (ImageView)v.findViewById(R.id.ivCall);
ivMsg = (ImageView)v.findViewById(R.id.ivMsg);
}
//get data from database and set into controls.
protected void setValues(){
cDetail = db.getClientDetail(idval);
tvName.setText(cDetail.get("name"));
tvType.setText(cDetail.get("type"));
tvStatus.setText(cDetail.get("status"));
tvEmail.setText(cDetail.get("email"));
tvPhone.setText(cDetail.get("phone"));
}
```
and there is no errors display in logcat. so, i cant trace it from there. | 2014/01/17 | [
"https://Stackoverflow.com/questions/21180197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1581185/"
] | check this web this may be what you want(Use it for realtime web application)
<http://express-io.org/>
<http://socket.io/>
Tutorials
<http://blog.nodeknockout.com/post/34243127010/knocking-out-socket-io> | The pass with yahoo work not. I have create two scripts to get the quote:
Shell script (quote.sh):
```
#!/bin/bash
a=http://finance.yahoo.com/q?s=
u=$a$1
w3m -dump "$u" > sortie.txt
grep -A 5 'Visitors' sortie.txt
```
PHP script (temp.php):
```
<?php
$Q = $_REQUEST['q'];
$output = shell_exec("/bin/sh ./quote.sh $Q");
$all_lines=explode(chr(10), $output);
$data=$all_lines[2];
$p1=strpos($data,'(');
$p2=strpos($data,')');
$ps=substr($data,$p1+1,$p2-$p1-1);
$p=strpos($data,'+');
if($p<1){$p=strpos($data,'-');}
$v=substr($data,0,$p);
$change=substr($data,$p,$p1-$p);
echo $Q.':<br>';
echo "%= $ps<br>";
echo "value= $v<br>";
echo "change= $change<br>";
?>
```
Usage: http://localhost/temp.php?q=goog |
21,180,197 | I have integrated the new google maps api v2 fragment in a view pager. When i move from the map tab(street view screen) to second tab(client detail), a black view shown instend of data into fragment. anyone know about solution.??
ScreenShot:

Code:
ListingStreetViewFragment.java
```
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View inflatedView = inflater.inflate(R.layout.map_view, container, false);
try {
MapsInitializer.initialize(getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
// TODO handle this situation
}
markers = new Hashtable<String, String>();
mMapView = (MapView) inflatedView.findViewById(R.id.map);
mMapView.onCreate(mBundle);
mMapView.onResume();
setUpMapIfNeeded(inflatedView);
return inflatedView;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBundle = savedInstanceState;
}
// mapping between map object with xml layout.
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((MapView) inflatedView.findViewById(R.id.map)).getMap();
if (mMap != null) {
mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter());
setUpMap();
}
}
}
//set location on map and show marker on random location
private void setUpMap() {
// random latitude and logitude
// Adding a marker
MarkerOptions marker = new MarkerOptions().position(
new LatLng(53.558, 9.927))
.title("Hello Maps ");
marker.snippet("dinet");
// changing marker color
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
mMap.addMarker(marker);
// Move the camera to last position with a zoom level
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(53.558,
9.927)).zoom(16).build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
@Override
public void onResume() {
if (null != mMapView)
mMapView.onResume();
super.onResume();
}
@Override
public void onPause() {
super.onPause();
if (null != mMapView)
mMapView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
if (null != mMapView)
mMapView.onDestroy();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (null != mMapView)
mMapView.onSaveInstanceState(outState);
}
@Override
public void onLowMemory() {
super.onLowMemory();
if (null != mMapView)
mMapView.onLowMemory();
}
```
ListingClientDetailFragment.java
```
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.client_detail, container, false);
initUi(rootView);
idval = ListingListFragment.cid;
System.out.println("SET: " + idval);
setValues();
return rootView;
}
protected void initUi(View v){
db = new Databasehelper(getActivity());
cDetail = new HashMap<String, String>();
tvName = (TextView)v.findViewById(R.id.tvName);
tvType = (TextView)v.findViewById(R.id.tvType);
tvStatus = (TextView)v.findViewById(R.id.tvStatus);
tvEmail = (TextView)v.findViewById(R.id.tvEmail);
tvPhone = (TextView)v.findViewById(R.id.tvPhone);
ivCall = (ImageView)v.findViewById(R.id.ivCall);
ivMsg = (ImageView)v.findViewById(R.id.ivMsg);
}
//get data from database and set into controls.
protected void setValues(){
cDetail = db.getClientDetail(idval);
tvName.setText(cDetail.get("name"));
tvType.setText(cDetail.get("type"));
tvStatus.setText(cDetail.get("status"));
tvEmail.setText(cDetail.get("email"));
tvPhone.setText(cDetail.get("phone"));
}
```
and there is no errors display in logcat. so, i cant trace it from there. | 2014/01/17 | [
"https://Stackoverflow.com/questions/21180197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1581185/"
] | ```
<?php
class U_Yahoo{
private function file_get_contents_curl($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
//return the history quote from the simbol, default begin date is 90 day ago, the default end is today
public function getHistoryQuote($symbol, $begin = 90, $end = 0){
if(!$begin && !$end)
$begin = $end = 0;
$begin = Date('Y-m-d', strtotime("-{$begin} days"));
$end = Date('Y-m-d', strtotime("-{$end} days"));
$url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.historicaldata%20where%20symbol%20%3D%20%22$symbol%22%20and%20startDate%20%3D%20%22$begin%22%20and%20endDate%20%3D%20%22$end%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";
$jason_obj = json_decode( $this->file_get_contents_curl($url) );
return $jason_obj->query->results->quote;
}
//return not just the quote but others informations too
public function getCurrentData($symbol){
$is_array = is_array($symbol);
$imp_symbol = ($is_array)? implode('%22%2C%22', $symbol) : $symbol;
$url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quote%20where%20symbol%20in%20(%22$imp_symbol%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";
$jason_obj = json_decode( $this->file_get_contents_curl($url) );
$result = $jason_obj->query->results->quote;
return (is_array($symbol) and (count($symbol) == 1))? [$result] : $result;
}
//return all quotes from the param $symbol passed, if symbol is array, it will return other array indexed by the symbols
public function getCurrentQuote($symbol){
if(is_array($symbol)){
$symbol = empty($symbol)? ['GOOG'] : $symbol;
$data = $this->getCurrentData($symbol);
$result = [];
for ($c = 0; $c < count($data); $c++) {
$result[$data[$c]->Symbol] = $data[$c]->LastTradePriceOnly;
}
return $result;
}else
return $this->getCurrentData($symbol)->LastTradePriceOnly;
}
}
```
How use:
```
$yahoo = new U_Yahoo();
var_dump( $yahoo->getCurrentQuote('GOOG') );
var_dump( $yahoo->getCurrentQuote(['GOOG', 'YHOO']) );
var_dump( $yahoo->getCurrentData(['GOOG', 'YHOO']) );
var_dump( $yahoo->getHistoryQuote('YHOO', 20, 0) );
``` | As far as google is concerned I am pretty sure that the API is deprecated and is not working anymore. you can probably use Yahoo finance api, They have api for csv downloads and via yql.
Refer: <https://code.google.com/p/yahoo-finance-managed/wiki/YahooFinanceAPIs>
As far as realtime is conecrned, I suggest look at yahoo web services. Following is an example:
<http://finance.yahoo.com/webservice/v1/symbols/ITC.NS,ITC.BO/quote?format=json>
If you do not provide format, it will return a XML.
How would you make it realtime without refreshing or Ajax?
You can create a pubsub model and make your application subscribe to your application, you will have to create this layer since the yahoo api is pull based and not push based. So you will need to pull stock quotes from yahoo and push them to your application. You can probably use JMS for java or sockets, whichever suits you. |
21,180,197 | I have integrated the new google maps api v2 fragment in a view pager. When i move from the map tab(street view screen) to second tab(client detail), a black view shown instend of data into fragment. anyone know about solution.??
ScreenShot:

Code:
ListingStreetViewFragment.java
```
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View inflatedView = inflater.inflate(R.layout.map_view, container, false);
try {
MapsInitializer.initialize(getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
// TODO handle this situation
}
markers = new Hashtable<String, String>();
mMapView = (MapView) inflatedView.findViewById(R.id.map);
mMapView.onCreate(mBundle);
mMapView.onResume();
setUpMapIfNeeded(inflatedView);
return inflatedView;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBundle = savedInstanceState;
}
// mapping between map object with xml layout.
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((MapView) inflatedView.findViewById(R.id.map)).getMap();
if (mMap != null) {
mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter());
setUpMap();
}
}
}
//set location on map and show marker on random location
private void setUpMap() {
// random latitude and logitude
// Adding a marker
MarkerOptions marker = new MarkerOptions().position(
new LatLng(53.558, 9.927))
.title("Hello Maps ");
marker.snippet("dinet");
// changing marker color
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
mMap.addMarker(marker);
// Move the camera to last position with a zoom level
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(53.558,
9.927)).zoom(16).build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
@Override
public void onResume() {
if (null != mMapView)
mMapView.onResume();
super.onResume();
}
@Override
public void onPause() {
super.onPause();
if (null != mMapView)
mMapView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
if (null != mMapView)
mMapView.onDestroy();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (null != mMapView)
mMapView.onSaveInstanceState(outState);
}
@Override
public void onLowMemory() {
super.onLowMemory();
if (null != mMapView)
mMapView.onLowMemory();
}
```
ListingClientDetailFragment.java
```
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.client_detail, container, false);
initUi(rootView);
idval = ListingListFragment.cid;
System.out.println("SET: " + idval);
setValues();
return rootView;
}
protected void initUi(View v){
db = new Databasehelper(getActivity());
cDetail = new HashMap<String, String>();
tvName = (TextView)v.findViewById(R.id.tvName);
tvType = (TextView)v.findViewById(R.id.tvType);
tvStatus = (TextView)v.findViewById(R.id.tvStatus);
tvEmail = (TextView)v.findViewById(R.id.tvEmail);
tvPhone = (TextView)v.findViewById(R.id.tvPhone);
ivCall = (ImageView)v.findViewById(R.id.ivCall);
ivMsg = (ImageView)v.findViewById(R.id.ivMsg);
}
//get data from database and set into controls.
protected void setValues(){
cDetail = db.getClientDetail(idval);
tvName.setText(cDetail.get("name"));
tvType.setText(cDetail.get("type"));
tvStatus.setText(cDetail.get("status"));
tvEmail.setText(cDetail.get("email"));
tvPhone.setText(cDetail.get("phone"));
}
```
and there is no errors display in logcat. so, i cant trace it from there. | 2014/01/17 | [
"https://Stackoverflow.com/questions/21180197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1581185/"
] | ```
<?php
class U_Yahoo{
private function file_get_contents_curl($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
//return the history quote from the simbol, default begin date is 90 day ago, the default end is today
public function getHistoryQuote($symbol, $begin = 90, $end = 0){
if(!$begin && !$end)
$begin = $end = 0;
$begin = Date('Y-m-d', strtotime("-{$begin} days"));
$end = Date('Y-m-d', strtotime("-{$end} days"));
$url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.historicaldata%20where%20symbol%20%3D%20%22$symbol%22%20and%20startDate%20%3D%20%22$begin%22%20and%20endDate%20%3D%20%22$end%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";
$jason_obj = json_decode( $this->file_get_contents_curl($url) );
return $jason_obj->query->results->quote;
}
//return not just the quote but others informations too
public function getCurrentData($symbol){
$is_array = is_array($symbol);
$imp_symbol = ($is_array)? implode('%22%2C%22', $symbol) : $symbol;
$url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quote%20where%20symbol%20in%20(%22$imp_symbol%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";
$jason_obj = json_decode( $this->file_get_contents_curl($url) );
$result = $jason_obj->query->results->quote;
return (is_array($symbol) and (count($symbol) == 1))? [$result] : $result;
}
//return all quotes from the param $symbol passed, if symbol is array, it will return other array indexed by the symbols
public function getCurrentQuote($symbol){
if(is_array($symbol)){
$symbol = empty($symbol)? ['GOOG'] : $symbol;
$data = $this->getCurrentData($symbol);
$result = [];
for ($c = 0; $c < count($data); $c++) {
$result[$data[$c]->Symbol] = $data[$c]->LastTradePriceOnly;
}
return $result;
}else
return $this->getCurrentData($symbol)->LastTradePriceOnly;
}
}
```
How use:
```
$yahoo = new U_Yahoo();
var_dump( $yahoo->getCurrentQuote('GOOG') );
var_dump( $yahoo->getCurrentQuote(['GOOG', 'YHOO']) );
var_dump( $yahoo->getCurrentData(['GOOG', 'YHOO']) );
var_dump( $yahoo->getHistoryQuote('YHOO', 20, 0) );
``` | well, in your approach, the stock price fetching is triggered by the client (the user's browser). So there is no way to trigger it outside page refresh or AJAX.
However, your server could fetch those data, irrespective of users. Something like:
```
data source <----> your backend server fetching the data ---> your database <---- your frontend web server <---> users
```
Backend and frontend servers can be the same server but with different processes. |
21,180,197 | I have integrated the new google maps api v2 fragment in a view pager. When i move from the map tab(street view screen) to second tab(client detail), a black view shown instend of data into fragment. anyone know about solution.??
ScreenShot:

Code:
ListingStreetViewFragment.java
```
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View inflatedView = inflater.inflate(R.layout.map_view, container, false);
try {
MapsInitializer.initialize(getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
// TODO handle this situation
}
markers = new Hashtable<String, String>();
mMapView = (MapView) inflatedView.findViewById(R.id.map);
mMapView.onCreate(mBundle);
mMapView.onResume();
setUpMapIfNeeded(inflatedView);
return inflatedView;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBundle = savedInstanceState;
}
// mapping between map object with xml layout.
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((MapView) inflatedView.findViewById(R.id.map)).getMap();
if (mMap != null) {
mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter());
setUpMap();
}
}
}
//set location on map and show marker on random location
private void setUpMap() {
// random latitude and logitude
// Adding a marker
MarkerOptions marker = new MarkerOptions().position(
new LatLng(53.558, 9.927))
.title("Hello Maps ");
marker.snippet("dinet");
// changing marker color
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
mMap.addMarker(marker);
// Move the camera to last position with a zoom level
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(53.558,
9.927)).zoom(16).build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
@Override
public void onResume() {
if (null != mMapView)
mMapView.onResume();
super.onResume();
}
@Override
public void onPause() {
super.onPause();
if (null != mMapView)
mMapView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
if (null != mMapView)
mMapView.onDestroy();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (null != mMapView)
mMapView.onSaveInstanceState(outState);
}
@Override
public void onLowMemory() {
super.onLowMemory();
if (null != mMapView)
mMapView.onLowMemory();
}
```
ListingClientDetailFragment.java
```
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.client_detail, container, false);
initUi(rootView);
idval = ListingListFragment.cid;
System.out.println("SET: " + idval);
setValues();
return rootView;
}
protected void initUi(View v){
db = new Databasehelper(getActivity());
cDetail = new HashMap<String, String>();
tvName = (TextView)v.findViewById(R.id.tvName);
tvType = (TextView)v.findViewById(R.id.tvType);
tvStatus = (TextView)v.findViewById(R.id.tvStatus);
tvEmail = (TextView)v.findViewById(R.id.tvEmail);
tvPhone = (TextView)v.findViewById(R.id.tvPhone);
ivCall = (ImageView)v.findViewById(R.id.ivCall);
ivMsg = (ImageView)v.findViewById(R.id.ivMsg);
}
//get data from database and set into controls.
protected void setValues(){
cDetail = db.getClientDetail(idval);
tvName.setText(cDetail.get("name"));
tvType.setText(cDetail.get("type"));
tvStatus.setText(cDetail.get("status"));
tvEmail.setText(cDetail.get("email"));
tvPhone.setText(cDetail.get("phone"));
}
```
and there is no errors display in logcat. so, i cant trace it from there. | 2014/01/17 | [
"https://Stackoverflow.com/questions/21180197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1581185/"
] | well, in your approach, the stock price fetching is triggered by the client (the user's browser). So there is no way to trigger it outside page refresh or AJAX.
However, your server could fetch those data, irrespective of users. Something like:
```
data source <----> your backend server fetching the data ---> your database <---- your frontend web server <---> users
```
Backend and frontend servers can be the same server but with different processes. | I have rebuild my linux script:
```
#!/bin/bash
l="http://finance.yahoo.com/q?s="
a=$l$1
all=$(w3m -dump "$a")
echo "$all" | grep -A 5 'Visitors'
```
No need a tempory file. |
21,180,197 | I have integrated the new google maps api v2 fragment in a view pager. When i move from the map tab(street view screen) to second tab(client detail), a black view shown instend of data into fragment. anyone know about solution.??
ScreenShot:

Code:
ListingStreetViewFragment.java
```
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View inflatedView = inflater.inflate(R.layout.map_view, container, false);
try {
MapsInitializer.initialize(getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
// TODO handle this situation
}
markers = new Hashtable<String, String>();
mMapView = (MapView) inflatedView.findViewById(R.id.map);
mMapView.onCreate(mBundle);
mMapView.onResume();
setUpMapIfNeeded(inflatedView);
return inflatedView;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBundle = savedInstanceState;
}
// mapping between map object with xml layout.
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((MapView) inflatedView.findViewById(R.id.map)).getMap();
if (mMap != null) {
mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter());
setUpMap();
}
}
}
//set location on map and show marker on random location
private void setUpMap() {
// random latitude and logitude
// Adding a marker
MarkerOptions marker = new MarkerOptions().position(
new LatLng(53.558, 9.927))
.title("Hello Maps ");
marker.snippet("dinet");
// changing marker color
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
mMap.addMarker(marker);
// Move the camera to last position with a zoom level
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(53.558,
9.927)).zoom(16).build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
@Override
public void onResume() {
if (null != mMapView)
mMapView.onResume();
super.onResume();
}
@Override
public void onPause() {
super.onPause();
if (null != mMapView)
mMapView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
if (null != mMapView)
mMapView.onDestroy();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (null != mMapView)
mMapView.onSaveInstanceState(outState);
}
@Override
public void onLowMemory() {
super.onLowMemory();
if (null != mMapView)
mMapView.onLowMemory();
}
```
ListingClientDetailFragment.java
```
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.client_detail, container, false);
initUi(rootView);
idval = ListingListFragment.cid;
System.out.println("SET: " + idval);
setValues();
return rootView;
}
protected void initUi(View v){
db = new Databasehelper(getActivity());
cDetail = new HashMap<String, String>();
tvName = (TextView)v.findViewById(R.id.tvName);
tvType = (TextView)v.findViewById(R.id.tvType);
tvStatus = (TextView)v.findViewById(R.id.tvStatus);
tvEmail = (TextView)v.findViewById(R.id.tvEmail);
tvPhone = (TextView)v.findViewById(R.id.tvPhone);
ivCall = (ImageView)v.findViewById(R.id.ivCall);
ivMsg = (ImageView)v.findViewById(R.id.ivMsg);
}
//get data from database and set into controls.
protected void setValues(){
cDetail = db.getClientDetail(idval);
tvName.setText(cDetail.get("name"));
tvType.setText(cDetail.get("type"));
tvStatus.setText(cDetail.get("status"));
tvEmail.setText(cDetail.get("email"));
tvPhone.setText(cDetail.get("phone"));
}
```
and there is no errors display in logcat. so, i cant trace it from there. | 2014/01/17 | [
"https://Stackoverflow.com/questions/21180197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1581185/"
] | ```
<?php
class U_Yahoo{
private function file_get_contents_curl($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
//return the history quote from the simbol, default begin date is 90 day ago, the default end is today
public function getHistoryQuote($symbol, $begin = 90, $end = 0){
if(!$begin && !$end)
$begin = $end = 0;
$begin = Date('Y-m-d', strtotime("-{$begin} days"));
$end = Date('Y-m-d', strtotime("-{$end} days"));
$url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.historicaldata%20where%20symbol%20%3D%20%22$symbol%22%20and%20startDate%20%3D%20%22$begin%22%20and%20endDate%20%3D%20%22$end%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";
$jason_obj = json_decode( $this->file_get_contents_curl($url) );
return $jason_obj->query->results->quote;
}
//return not just the quote but others informations too
public function getCurrentData($symbol){
$is_array = is_array($symbol);
$imp_symbol = ($is_array)? implode('%22%2C%22', $symbol) : $symbol;
$url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quote%20where%20symbol%20in%20(%22$imp_symbol%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";
$jason_obj = json_decode( $this->file_get_contents_curl($url) );
$result = $jason_obj->query->results->quote;
return (is_array($symbol) and (count($symbol) == 1))? [$result] : $result;
}
//return all quotes from the param $symbol passed, if symbol is array, it will return other array indexed by the symbols
public function getCurrentQuote($symbol){
if(is_array($symbol)){
$symbol = empty($symbol)? ['GOOG'] : $symbol;
$data = $this->getCurrentData($symbol);
$result = [];
for ($c = 0; $c < count($data); $c++) {
$result[$data[$c]->Symbol] = $data[$c]->LastTradePriceOnly;
}
return $result;
}else
return $this->getCurrentData($symbol)->LastTradePriceOnly;
}
}
```
How use:
```
$yahoo = new U_Yahoo();
var_dump( $yahoo->getCurrentQuote('GOOG') );
var_dump( $yahoo->getCurrentQuote(['GOOG', 'YHOO']) );
var_dump( $yahoo->getCurrentData(['GOOG', 'YHOO']) );
var_dump( $yahoo->getHistoryQuote('YHOO', 20, 0) );
``` | I have rebuild my linux script:
```
#!/bin/bash
l="http://finance.yahoo.com/q?s="
a=$l$1
all=$(w3m -dump "$a")
echo "$all" | grep -A 5 'Visitors'
```
No need a tempory file. |
21,180,197 | I have integrated the new google maps api v2 fragment in a view pager. When i move from the map tab(street view screen) to second tab(client detail), a black view shown instend of data into fragment. anyone know about solution.??
ScreenShot:

Code:
ListingStreetViewFragment.java
```
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View inflatedView = inflater.inflate(R.layout.map_view, container, false);
try {
MapsInitializer.initialize(getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
// TODO handle this situation
}
markers = new Hashtable<String, String>();
mMapView = (MapView) inflatedView.findViewById(R.id.map);
mMapView.onCreate(mBundle);
mMapView.onResume();
setUpMapIfNeeded(inflatedView);
return inflatedView;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBundle = savedInstanceState;
}
// mapping between map object with xml layout.
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((MapView) inflatedView.findViewById(R.id.map)).getMap();
if (mMap != null) {
mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter());
setUpMap();
}
}
}
//set location on map and show marker on random location
private void setUpMap() {
// random latitude and logitude
// Adding a marker
MarkerOptions marker = new MarkerOptions().position(
new LatLng(53.558, 9.927))
.title("Hello Maps ");
marker.snippet("dinet");
// changing marker color
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
mMap.addMarker(marker);
// Move the camera to last position with a zoom level
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(53.558,
9.927)).zoom(16).build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
@Override
public void onResume() {
if (null != mMapView)
mMapView.onResume();
super.onResume();
}
@Override
public void onPause() {
super.onPause();
if (null != mMapView)
mMapView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
if (null != mMapView)
mMapView.onDestroy();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (null != mMapView)
mMapView.onSaveInstanceState(outState);
}
@Override
public void onLowMemory() {
super.onLowMemory();
if (null != mMapView)
mMapView.onLowMemory();
}
```
ListingClientDetailFragment.java
```
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.client_detail, container, false);
initUi(rootView);
idval = ListingListFragment.cid;
System.out.println("SET: " + idval);
setValues();
return rootView;
}
protected void initUi(View v){
db = new Databasehelper(getActivity());
cDetail = new HashMap<String, String>();
tvName = (TextView)v.findViewById(R.id.tvName);
tvType = (TextView)v.findViewById(R.id.tvType);
tvStatus = (TextView)v.findViewById(R.id.tvStatus);
tvEmail = (TextView)v.findViewById(R.id.tvEmail);
tvPhone = (TextView)v.findViewById(R.id.tvPhone);
ivCall = (ImageView)v.findViewById(R.id.ivCall);
ivMsg = (ImageView)v.findViewById(R.id.ivMsg);
}
//get data from database and set into controls.
protected void setValues(){
cDetail = db.getClientDetail(idval);
tvName.setText(cDetail.get("name"));
tvType.setText(cDetail.get("type"));
tvStatus.setText(cDetail.get("status"));
tvEmail.setText(cDetail.get("email"));
tvPhone.setText(cDetail.get("phone"));
}
```
and there is no errors display in logcat. so, i cant trace it from there. | 2014/01/17 | [
"https://Stackoverflow.com/questions/21180197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1581185/"
] | well, in your approach, the stock price fetching is triggered by the client (the user's browser). So there is no way to trigger it outside page refresh or AJAX.
However, your server could fetch those data, irrespective of users. Something like:
```
data source <----> your backend server fetching the data ---> your database <---- your frontend web server <---> users
```
Backend and frontend servers can be the same server but with different processes. | The pass with yahoo work not. I have create two scripts to get the quote:
Shell script (quote.sh):
```
#!/bin/bash
a=http://finance.yahoo.com/q?s=
u=$a$1
w3m -dump "$u" > sortie.txt
grep -A 5 'Visitors' sortie.txt
```
PHP script (temp.php):
```
<?php
$Q = $_REQUEST['q'];
$output = shell_exec("/bin/sh ./quote.sh $Q");
$all_lines=explode(chr(10), $output);
$data=$all_lines[2];
$p1=strpos($data,'(');
$p2=strpos($data,')');
$ps=substr($data,$p1+1,$p2-$p1-1);
$p=strpos($data,'+');
if($p<1){$p=strpos($data,'-');}
$v=substr($data,0,$p);
$change=substr($data,$p,$p1-$p);
echo $Q.':<br>';
echo "%= $ps<br>";
echo "value= $v<br>";
echo "change= $change<br>";
?>
```
Usage: http://localhost/temp.php?q=goog |
12,853 | I want to thank you beforehand for taking your time to read and (hopefully) answer this. My question is a bit ambiguous, so I'll give an example. Let's say I'm playing white, the enemy has castled king-side so his king is on g8, with his rook on f8, and his knight is on f6. Also, he's got his three castle pawns at their original positions. My dark-square bishop is fianchettoed and I can thus trade it for his f6 knight. If he can only take the bishop with the g7 pawn, opening up his king, when is it a good idea to trade (i. e. what other factors affect if it is a good idea or not)?
```
[FEN "5rk1/5ppp/5n2/8/8/8/1B3PPP/5RK1 w - - 0 1"]
``` | 2015/11/17 | [
"https://chess.stackexchange.com/questions/12853",
"https://chess.stackexchange.com",
"https://chess.stackexchange.com/users/8768/"
] | As always with such questions, the correct answer is "It depends on the position!".
For example if your opponent doesn't have an e-pawn, you will create isolated doubled pawns, which are generally quite weak. But in a 4 vs 3 rook endgame, with all pawns on the kingside this structure is actually better for black than f7-g7-h7 because it is harder for white to create a passed pawn.
Taking gxf6 will often weaken the black king, but only if you are actually able to attack him. If you have all your pieces on the queenside he might just play Kh8, Rg8 and start an attack on your king!
So, this is a weakening of his structure, but you have to be able to take advantage of it. Otherwise a bishop might just be more useful than a knight. | It's "usually" a good idea to capture a knight in this situation. If possible, you might consider using a rook on f1 to make this capture. The reason is that you have a second rook to control the open file, but only one dark-squared bishop to control the diagonal a1-h8,
It's always a good idea to capture the knight if you can see a way to a winning combination. (This will often be the case.) Then finish the combination and win.
Another poster pointed out that capturing might cause endgame problems for you. That is if the game lasts till the endgame. If you capture, it's your job to see that it doesn't. |
12,853 | I want to thank you beforehand for taking your time to read and (hopefully) answer this. My question is a bit ambiguous, so I'll give an example. Let's say I'm playing white, the enemy has castled king-side so his king is on g8, with his rook on f8, and his knight is on f6. Also, he's got his three castle pawns at their original positions. My dark-square bishop is fianchettoed and I can thus trade it for his f6 knight. If he can only take the bishop with the g7 pawn, opening up his king, when is it a good idea to trade (i. e. what other factors affect if it is a good idea or not)?
```
[FEN "5rk1/5ppp/5n2/8/8/8/1B3PPP/5RK1 w - - 0 1"]
``` | 2015/11/17 | [
"https://chess.stackexchange.com/questions/12853",
"https://chess.stackexchange.com",
"https://chess.stackexchange.com/users/8768/"
] | As always with such questions, the correct answer is "It depends on the position!".
For example if your opponent doesn't have an e-pawn, you will create isolated doubled pawns, which are generally quite weak. But in a 4 vs 3 rook endgame, with all pawns on the kingside this structure is actually better for black than f7-g7-h7 because it is harder for white to create a passed pawn.
Taking gxf6 will often weaken the black king, but only if you are actually able to attack him. If you have all your pieces on the queenside he might just play Kh8, Rg8 and start an attack on your king!
So, this is a weakening of his structure, but you have to be able to take advantage of it. Otherwise a bishop might just be more useful than a knight. | There are a lot of factors which gets counted in situations like this .
1. If you see that there can be a Kingside attack after you break the castle and you have a lot of initiative with the pieces forcing a strong attack on the King .
2. According to the diagram above it might be that you will be closing the centre soon with your pawns and your pawns will belong to the dark squares so you part with your dark square Bishop.
3. A situation in End game can arise where your & your enemy Pawns are all on one flank and you do not have any other pawns in other flank . You can trade your Bishop for a knight because Knight is generally worse if you need to control both flanks .
4. If it is a Middle game and your Knights are on good central squares like d5 or f5 , h6 somewhere then it is surely a good choice (Weak Squares around the King).
There can be other factors also but the above is the most common . |
14,797,261 | I am trying to use the Select2 plugin to have 4 dropdown lists that depend on each other. I have struggled to find the right way to update the data that loads the options in.
My goal is to load the new data via ajax, but once I have it in the client I am unable to add the new data to the select list.
The code I have tried is here:
```
$(#"a3").select2({
placeholder: "select an item",
allowClear: true}).on("change",
function (e) {
var results = $.get("url?id=2",
function (data, textStatus, jqXHR) {
$(this).select2({ data: { results: data, text: "Name" } });
});
}
);
```
There is another question here
[select2 changing items dynamically](https://stackoverflow.com/questions/13268083/select2-changing-items-dynamically?rq=1)
but the solution there worked with Select2 v3.2 but not Select2 v3.3 | 2013/02/10 | [
"https://Stackoverflow.com/questions/14797261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/201596/"
] | Igor has come back to me with a way to do this
```
var data=[...];
$().select2({data: function() {return {results:data};}});
/// later
data=[...something else];
// next query select2 will use 'something else' data
``` | The correct format is:
```
.select2("data", {...})
``` |
14,797,261 | I am trying to use the Select2 plugin to have 4 dropdown lists that depend on each other. I have struggled to find the right way to update the data that loads the options in.
My goal is to load the new data via ajax, but once I have it in the client I am unable to add the new data to the select list.
The code I have tried is here:
```
$(#"a3").select2({
placeholder: "select an item",
allowClear: true}).on("change",
function (e) {
var results = $.get("url?id=2",
function (data, textStatus, jqXHR) {
$(this).select2({ data: { results: data, text: "Name" } });
});
}
);
```
There is another question here
[select2 changing items dynamically](https://stackoverflow.com/questions/13268083/select2-changing-items-dynamically?rq=1)
but the solution there worked with Select2 v3.2 but not Select2 v3.3 | 2013/02/10 | [
"https://Stackoverflow.com/questions/14797261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/201596/"
] | The correct format is:
```
.select2("data", {...})
``` | Here's a way to do it without Ajax. You can view a working example on [codepen](https://codepen.io/lflier/pen/xxWXwpg).
```js
$(document).ready(function() {
$('#groups').select2({
placeholder: "Choose Group",
width: '300px',
});
$('#items').select2({
placeholder: "Choose Item",
width: '300px',
});
});
$('#groups').on('select2:select', function(event) {
let group = event.params.data.id;
$('#items').html('<option></option');
$('#item-options option').each(function() {
if ($(this).hasClass(group)) {
let option = $(this).clone();
$('#items').append(option[0]);
}
})
});
```
```css
body {
font-family: sans-serif;
width: 730px;
margin: 20px auto;
}
.select {
display: flex;
flex-direction: column;
justify-content: center;
width: 300px;
margin: 40px auto;
}
.select2-container {
margin: 10px;
}
.hidden {
display: none;
}
```
```html
<div class="select">
<select id="groups">
<option></option>
<option value="1">Group 1</option>
<option value="2">Group 2</option>
</select>
<select id="items">
</select>
</div>
<div id="item-options" class="hidden">
<option class="1" value="A">Group 1: Item A</option>
<option class="1" value="B">Group 1: Item B</option>
<option class="1" value="C">Group 1: Item C</option>
<option class="2" value="R">Group 2: Item R</option>
<option class="2" value="S">Group 2: Item S</option>
</div>
```
<https://codepen.io/lflier/pen/xxWXwpg> |
14,797,261 | I am trying to use the Select2 plugin to have 4 dropdown lists that depend on each other. I have struggled to find the right way to update the data that loads the options in.
My goal is to load the new data via ajax, but once I have it in the client I am unable to add the new data to the select list.
The code I have tried is here:
```
$(#"a3").select2({
placeholder: "select an item",
allowClear: true}).on("change",
function (e) {
var results = $.get("url?id=2",
function (data, textStatus, jqXHR) {
$(this).select2({ data: { results: data, text: "Name" } });
});
}
);
```
There is another question here
[select2 changing items dynamically](https://stackoverflow.com/questions/13268083/select2-changing-items-dynamically?rq=1)
but the solution there worked with Select2 v3.2 but not Select2 v3.3 | 2013/02/10 | [
"https://Stackoverflow.com/questions/14797261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/201596/"
] | Igor has come back to me with a way to do this
```
var data=[...];
$().select2({data: function() {return {results:data};}});
/// later
data=[...something else];
// next query select2 will use 'something else' data
``` | For Select2 v4.x, here is a small [js class](https://gist.github.com/ajaxray/187e7c9a00666a7ffff52a8a69b8bf31 "gist").
Using this, options of a select2 list box will be loaded/refreshed by ajax based on selection of another select2 list box. And the dependency can be chained.
For example -
```
new Select2Cascade($('#country'), $('#province'), 'path/to/geocode', {type:"province", parent_id: ''});
new Select2Cascade($('#province'), $('#district'), 'path/to/geocode', {type:"district", parent_id: ''});
```
Check the demo on [codepen](https://codepen.io/ajaxray/full/oBPbQe/). Also here is a post on [how to use](http://ajaxray.com/blog/select2-dependent-cascading-select-list-reload/) it. |
14,797,261 | I am trying to use the Select2 plugin to have 4 dropdown lists that depend on each other. I have struggled to find the right way to update the data that loads the options in.
My goal is to load the new data via ajax, but once I have it in the client I am unable to add the new data to the select list.
The code I have tried is here:
```
$(#"a3").select2({
placeholder: "select an item",
allowClear: true}).on("change",
function (e) {
var results = $.get("url?id=2",
function (data, textStatus, jqXHR) {
$(this).select2({ data: { results: data, text: "Name" } });
});
}
);
```
There is another question here
[select2 changing items dynamically](https://stackoverflow.com/questions/13268083/select2-changing-items-dynamically?rq=1)
but the solution there worked with Select2 v3.2 but not Select2 v3.3 | 2013/02/10 | [
"https://Stackoverflow.com/questions/14797261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/201596/"
] | Igor has come back to me with a way to do this
```
var data=[...];
$().select2({data: function() {return {results:data};}});
/// later
data=[...something else];
// next query select2 will use 'something else' data
``` | Here's a way to do it without Ajax. You can view a working example on [codepen](https://codepen.io/lflier/pen/xxWXwpg).
```js
$(document).ready(function() {
$('#groups').select2({
placeholder: "Choose Group",
width: '300px',
});
$('#items').select2({
placeholder: "Choose Item",
width: '300px',
});
});
$('#groups').on('select2:select', function(event) {
let group = event.params.data.id;
$('#items').html('<option></option');
$('#item-options option').each(function() {
if ($(this).hasClass(group)) {
let option = $(this).clone();
$('#items').append(option[0]);
}
})
});
```
```css
body {
font-family: sans-serif;
width: 730px;
margin: 20px auto;
}
.select {
display: flex;
flex-direction: column;
justify-content: center;
width: 300px;
margin: 40px auto;
}
.select2-container {
margin: 10px;
}
.hidden {
display: none;
}
```
```html
<div class="select">
<select id="groups">
<option></option>
<option value="1">Group 1</option>
<option value="2">Group 2</option>
</select>
<select id="items">
</select>
</div>
<div id="item-options" class="hidden">
<option class="1" value="A">Group 1: Item A</option>
<option class="1" value="B">Group 1: Item B</option>
<option class="1" value="C">Group 1: Item C</option>
<option class="2" value="R">Group 2: Item R</option>
<option class="2" value="S">Group 2: Item S</option>
</div>
```
<https://codepen.io/lflier/pen/xxWXwpg> |
14,797,261 | I am trying to use the Select2 plugin to have 4 dropdown lists that depend on each other. I have struggled to find the right way to update the data that loads the options in.
My goal is to load the new data via ajax, but once I have it in the client I am unable to add the new data to the select list.
The code I have tried is here:
```
$(#"a3").select2({
placeholder: "select an item",
allowClear: true}).on("change",
function (e) {
var results = $.get("url?id=2",
function (data, textStatus, jqXHR) {
$(this).select2({ data: { results: data, text: "Name" } });
});
}
);
```
There is another question here
[select2 changing items dynamically](https://stackoverflow.com/questions/13268083/select2-changing-items-dynamically?rq=1)
but the solution there worked with Select2 v3.2 but not Select2 v3.3 | 2013/02/10 | [
"https://Stackoverflow.com/questions/14797261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/201596/"
] | For Select2 v4.x, here is a small [js class](https://gist.github.com/ajaxray/187e7c9a00666a7ffff52a8a69b8bf31 "gist").
Using this, options of a select2 list box will be loaded/refreshed by ajax based on selection of another select2 list box. And the dependency can be chained.
For example -
```
new Select2Cascade($('#country'), $('#province'), 'path/to/geocode', {type:"province", parent_id: ''});
new Select2Cascade($('#province'), $('#district'), 'path/to/geocode', {type:"district", parent_id: ''});
```
Check the demo on [codepen](https://codepen.io/ajaxray/full/oBPbQe/). Also here is a post on [how to use](http://ajaxray.com/blog/select2-dependent-cascading-select-list-reload/) it. | Here's a way to do it without Ajax. You can view a working example on [codepen](https://codepen.io/lflier/pen/xxWXwpg).
```js
$(document).ready(function() {
$('#groups').select2({
placeholder: "Choose Group",
width: '300px',
});
$('#items').select2({
placeholder: "Choose Item",
width: '300px',
});
});
$('#groups').on('select2:select', function(event) {
let group = event.params.data.id;
$('#items').html('<option></option');
$('#item-options option').each(function() {
if ($(this).hasClass(group)) {
let option = $(this).clone();
$('#items').append(option[0]);
}
})
});
```
```css
body {
font-family: sans-serif;
width: 730px;
margin: 20px auto;
}
.select {
display: flex;
flex-direction: column;
justify-content: center;
width: 300px;
margin: 40px auto;
}
.select2-container {
margin: 10px;
}
.hidden {
display: none;
}
```
```html
<div class="select">
<select id="groups">
<option></option>
<option value="1">Group 1</option>
<option value="2">Group 2</option>
</select>
<select id="items">
</select>
</div>
<div id="item-options" class="hidden">
<option class="1" value="A">Group 1: Item A</option>
<option class="1" value="B">Group 1: Item B</option>
<option class="1" value="C">Group 1: Item C</option>
<option class="2" value="R">Group 2: Item R</option>
<option class="2" value="S">Group 2: Item S</option>
</div>
```
<https://codepen.io/lflier/pen/xxWXwpg> |
40,612,987 | I have a `UITableView` which looks like this image
.
When I swipe to delete the record, I can remove it perfectly okay from the array in which it is stored, but I am having difficulties in accessing it in Firebase to delete it there.
My Firebase database structure is as follows for the above screenshot:
```
-KWc7RTuOe5PefiMM2tL
bodyPart: "Arms"
exerciseName: "Test 1 "
userId: "8rHmyTxdocTEvk1ERiiavjMUYyD3"
-KWcEbpw_f6kxcePY5cO
bodyPart: "Chest"
exerciseName: "Test 2 "
userId: "8rHmyTxdocTEvk1ERiiavjMUYyD3"
-KWcEdUN49QaJIVf0kwO
bodyPart: "Legs"
exerciseName: "Test 3 "
userId: "8rHmyTxdocTEvk1ERiiavjMUYyD3"
-KWcFrMSaLKQRxghGHyT
bodyPart: "Arms"
exerciseName: "Test 4"
userId: "8rHmyTxdocTEvk1ERiiavjMUYyD3"
```
How can I access the autoId value which is set when it is created e.g "-KWc7RTuOe5PefiMM2tL" so I can remove that child node?
Or alternatively could I access the `exerciseName` value depending on the `UserId` that is logged in? | 2016/11/15 | [
"https://Stackoverflow.com/questions/40612987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6912551/"
] | To solve this issue I tried a number of different methods before finally reaching my intended result.
To delete the value, I created a reference to the child node 'userExercises', then ordered it by 'exerciseName' and then .queryEqual(toValue:) the exercise name value which I extracted form the UITableViewCell.
I then removed the snapshot value of this and the example code is below:
```
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
if let exerciseName = exercises[indexPath.row].exerciseName {
let ref = FIRDatabase.database().reference().child("userExercises")
ref.queryOrdered(byChild: "exerciseName").queryEqual(toValue: exerciseName).observe(.childAdded, with: { (snapshot) in
snapshot.ref.removeValue(completionBlock: { (error, reference) in
if error != nil {
print("There has been an error:\(error)")
}
})
})
}
exercises.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .left)
}
}
``` | It's a fairly straightforward process:
In general, a datasource for tableViews is an array. That array is built from dictionaries read from Firebase snapshots - or an array of objects built from the snapshots (recommended).
So here's an example that matches your Firebase structure (this was populated from a single node from a snapshot)
```
class Exercise {
key: "KWc7RTuOe5PefiMM2tL"
bodyPart: "Legs"
exerciseName: "Test 3 "
userId: "8rHmyTxdocTEvk1ERiiavjMUYyD3"
}
```
Then, when the user swipes row 3 for example, retrieve the Exercise object from the array, row3.
```
let theObject = ExerciseArray[3]
let parentNode = theObject.key
let ref = rootNode.child(parentNode)
ref.setValue(nil)
```
and you're done. |
40,612,987 | I have a `UITableView` which looks like this image
.
When I swipe to delete the record, I can remove it perfectly okay from the array in which it is stored, but I am having difficulties in accessing it in Firebase to delete it there.
My Firebase database structure is as follows for the above screenshot:
```
-KWc7RTuOe5PefiMM2tL
bodyPart: "Arms"
exerciseName: "Test 1 "
userId: "8rHmyTxdocTEvk1ERiiavjMUYyD3"
-KWcEbpw_f6kxcePY5cO
bodyPart: "Chest"
exerciseName: "Test 2 "
userId: "8rHmyTxdocTEvk1ERiiavjMUYyD3"
-KWcEdUN49QaJIVf0kwO
bodyPart: "Legs"
exerciseName: "Test 3 "
userId: "8rHmyTxdocTEvk1ERiiavjMUYyD3"
-KWcFrMSaLKQRxghGHyT
bodyPart: "Arms"
exerciseName: "Test 4"
userId: "8rHmyTxdocTEvk1ERiiavjMUYyD3"
```
How can I access the autoId value which is set when it is created e.g "-KWc7RTuOe5PefiMM2tL" so I can remove that child node?
Or alternatively could I access the `exerciseName` value depending on the `UserId` that is logged in? | 2016/11/15 | [
"https://Stackoverflow.com/questions/40612987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6912551/"
] | Following on from what MHDev has already answered:
```
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
if let exerciseName = exercises[indexPath.row].exerciseName {
let ref = FIRDatabase.database().reference().child("userExercises")
ref.queryOrdered(byChild: "exerciseName").queryEqual(toValue: exerciseName).observe(.childAdded, with: { (snapshot) in
snapshot.ref.removeValue(completionBlock: { (error, reference) in
if error != nil {
print("There has been an error:\(error)")
}
})
})
}
exercises.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .left)
}
}
``` | It's a fairly straightforward process:
In general, a datasource for tableViews is an array. That array is built from dictionaries read from Firebase snapshots - or an array of objects built from the snapshots (recommended).
So here's an example that matches your Firebase structure (this was populated from a single node from a snapshot)
```
class Exercise {
key: "KWc7RTuOe5PefiMM2tL"
bodyPart: "Legs"
exerciseName: "Test 3 "
userId: "8rHmyTxdocTEvk1ERiiavjMUYyD3"
}
```
Then, when the user swipes row 3 for example, retrieve the Exercise object from the array, row3.
```
let theObject = ExerciseArray[3]
let parentNode = theObject.key
let ref = rootNode.child(parentNode)
ref.setValue(nil)
```
and you're done. |
62,687,992 | I want to know how to remove space between first and second word. But it should not remove other spaces in the same column. (Using SQL)
It looks like this,
```
No. 378, Bearly Road, Colombo.
```
I want to remove only the space between "No." and "378". After remove it should be like this,
```
No.378, Bearly Road, Colombo.
``` | 2020/07/02 | [
"https://Stackoverflow.com/questions/62687992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7417632/"
] | NULL records are drawn using the "IS NULL" keyword for comparison. Here is an example how you can get null records
```
with data
as (select 'PLACEHOLDER' as market_concept,'PLACEHOLDER' as range_type
union all
select 'MarketConcept1' as market_concept,'Rangetype1' as range_type
union all
select null as market_concept, null as range_type
)
select *
from data
where ((market_concept <> 'PLACEHOLDER'
and range_type <>'PLACEHOLDER'
)
--This OR condition brings out the records which are null
OR(market_concept is null
and range_type is null
)
)
+----------------+------------+
| market_concept | range_type |
+----------------+------------+
| MarketConcept1 | Rangetype1 |
| null | null |
+----------------+------------+
``` | You can use ISNULL function to consider NULL value same as placeholder.
```sql
SELECT DISTINCT M.MATERIAL,
A.MARKET_CONCEPT,
A.RANGE_TYPE
FROM VW_MRP_ALLOCATION_COMBINED M
JOIN VW_ARTICLE_ATTRIBUTES_COMBINED A ON M.Material = A.Article AND M.SALES_ORGANIZATION = A.SALES_ORGANIZATION
WHERE M.stock_type = ''
AND ISNULL(A.market_concept,'PLACEHOLDER') <> 'PLACEHOLDER'
AND ISNULL(A.RANGE_TYPE,'PLACEHOLDER') <> 'PLACEHOLDER'
AND A.Article in ('BK0348',
'BQ2718',
'BQ2719',
'BS3674',
'CF3607',
'CF3608',
'CF3609',
'CF3610',
'CV5091',
'D94751',
'DH6911',
'DT5039')
AND M.Sales_Organization = 6040;
``` |
62,687,992 | I want to know how to remove space between first and second word. But it should not remove other spaces in the same column. (Using SQL)
It looks like this,
```
No. 378, Bearly Road, Colombo.
```
I want to remove only the space between "No." and "378". After remove it should be like this,
```
No.378, Bearly Road, Colombo.
``` | 2020/07/02 | [
"https://Stackoverflow.com/questions/62687992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7417632/"
] | I would suggest being explicit:
```
(A.market_concept <> 'PLACEHOLDER' OR A.market_concept IS NULL) AND
(A.RANGE_TYPE <> 'PLACEHOLDER' A.range_type IS NULL) AND
```
Note: This assumes that `'PLACEHOLDER'` is not `NULL`. If that is possible, I would suggest asking a new question, with clear sample data and desired results. | You can use ISNULL function to consider NULL value same as placeholder.
```sql
SELECT DISTINCT M.MATERIAL,
A.MARKET_CONCEPT,
A.RANGE_TYPE
FROM VW_MRP_ALLOCATION_COMBINED M
JOIN VW_ARTICLE_ATTRIBUTES_COMBINED A ON M.Material = A.Article AND M.SALES_ORGANIZATION = A.SALES_ORGANIZATION
WHERE M.stock_type = ''
AND ISNULL(A.market_concept,'PLACEHOLDER') <> 'PLACEHOLDER'
AND ISNULL(A.RANGE_TYPE,'PLACEHOLDER') <> 'PLACEHOLDER'
AND A.Article in ('BK0348',
'BQ2718',
'BQ2719',
'BS3674',
'CF3607',
'CF3608',
'CF3609',
'CF3610',
'CV5091',
'D94751',
'DH6911',
'DT5039')
AND M.Sales_Organization = 6040;
``` |
19,484,587 | I am running Ubuntu 12.04 and emacs 24.3. I have successfully downloaded sage, and sage\_mode. My problem is that when I try to run SAGE in emacs it doesn't load.
When I try to run SAGE with `M-x sage` it will then say: `Run sage (like this): /home/path/to/sage`. I hit enter then everything freezes inside of emacs with a message in the mini-buffer: `Sent python-eldoc-setup-code` Emacs stays frozen until I quit with `C-g` After that SAGE appears normally. If I run sage in the terminal everything starts up quickly and normally as I would expect.
Here is the output from my messages buffer:
```
Sent python-shell-completion-setup-code
Sent python-ffap-setup-code
Sent python-eldoc-setup-code
```
1. Why is it freezing like this and not starting normally?
I have seen a few bug reports that look similar, which are specifically problems with the python shell (SAGE runs on top of python).
Here is one [bug](https://groups.google.com/forum/#!topic/gnu.emacs.bug/JWvREtalP98) report.
**EDIT:** I am looking for specific instructions on how to fix the sage process that runs through emacs. Type `M-x emacs-version` I know that I have Emacs 24.3.1. Please let me know if you need any more information to help me fix my issue.
Thanks for all the help! | 2013/10/21 | [
"https://Stackoverflow.com/questions/19484587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1104823/"
] | I'm sorry you're experiencing this.
This sounds like a bug (in sage-mode) that I fixed a while ago in which it would get stuck waiting for the prompt. What version of `sage-mode` are you using? `C-h v sage-mode-version RET`. The latest released version is `0.10` and doesn't have such a bug to the best of my knowledge. If you are using an older version please upgrade. Otherwise I would really appreciate a bug report at <https://bitbucket.org/gvol/sage-mode/issues?status=new&status=open> so that I don't forget it.
Also, what version of Sage are you using, and do you have anything in your `~/.sage/init.sage`? | Check your config WRT to commands prefixes.
"python-" expects python.el
"py-" expects python-mode.el
`(load "python")` loads mode from python.el
It provides 'python
`(load "python-mode")` loads mode from python-mode.el
It provides 'python-mode
BTW the bug linked to doesn't exist in python-mode.el |
49,989,147 | In one of my Scala tests, using `ProcessBuilder`, I fire up 3 Apache Spark streaming applications in separate JVMs. (Two or more Spark streaming applications can not co-exist in the same JVM.) One Spark application processes data and ingests into Apache Kafka, which the other ones read. Moreover the test involves writing into a NoSQL database.
While using `ProcessBuilder`, the Spark application's class path is set using:
`val classPath = System.getProperty("java.class.path")`
Running the test in IntelliJ works as expected, but on a CI system, the test is invoked by SBT's test task. The `java.class.path` in the latter case, will be solely the `sbt.jar`, so the child JVM exits with `NoClassFoundException`, again, as expected. :-)
I'm looking for a way to "span" JVMs from SBT tests using the same class path that the tests are actually using. For example if the test is invoked in project `core`, the class path of project `core` should be supplied to the child JVM, where the Spark application starts. Unfortunately I have got no idea how to retrieve the correct class path in SBT tasks - which then could be supplied to child JVMs. | 2018/04/23 | [
"https://Stackoverflow.com/questions/49989147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/775988/"
] | [`Tests.Setup`](https://www.scala-sbt.org/0.13/docs/Testing.html#Setup+and+Cleanup) can be used to access the classpath within SBT:
```
testOptions in Test += Tests.Setup { classLoader =>
// give Spark classpath via classLoader
}
```
For example, on my machine `Tests.Setup(classLoader => println(classLoader))` gives
```
> test
ClasspathFilter(
parent = URLClassLoader with NativeCopyLoader with RawResources(
urls = List(/home/mario/sandbox/sbt/so-classpath/target/scala-2.12/test-classes, /home/mario/sandbox/sbt/so-classpath/target/scala-2.12/classes, /home/mario/.ivy2/cache/org.scala-lang/scala-library/jars/scala-library-2.12.4.jar, /home/mario/.ivy2/cache/org.scalatest/scalatest_2.12/bundles/scalatest_2.12-3.0.5.jar, /home/mario/.ivy2/cache/org.scalactic/scalactic_2.12/bundles/scalactic_2.12-3.0.5.jar, /home/mario/.ivy2/cache/org.scala-lang/scala-reflect/jars/scala-reflect-2.12.4.jar, /home/mario/.ivy2/cache/org.scala-lang.modules/scala-xml_2.12/bundles/scala-xml_2.12-1.0.6.jar),
parent = DualLoader(a = java.net.URLClassLoader@3fcb37f1, b = java.net.URLClassLoader@271053e1),
resourceMap = Set(app.class.path, boot.class.path),
nativeTemp = /tmp/sbt_741bc913/sbt_c770779a
)
root = sun.misc.Launcher$AppClassLoader@33909752
cp = Set(/home/mario/.ivy2/cache/jline/jline/jars/jline-2.14.5.jar, /home/mario/.ivy2/cache/org.scala-lang/scala-reflect/jars/scala-reflect-2.12.4.jar, /home/mario/.ivy2/cache/org.scala-lang/scala-compiler/jars/scala-compiler-2.12.4.jar, /home/mario/.ivy2/cache/org.scala-lang.modules/scala-xml_2.12/bundles/scala-xml_2.12-1.0.6.jar, /home/mario/sandbox/sbt/so-classpath/target/scala-2.12/classes, /home/mario/.ivy2/cache/org.scalatest/scalatest_2.12/bundles/scalatest_2.12-3.0.5.jar, /home/mario/.sbt/boot/scala-2.10.7/org.scala-sbt/sbt/0.13.17/test-interface-1.0.jar, /home/mario/.ivy2/cache/org.scalactic/scalactic_2.12/bundles/scalactic_2.12-3.0.5.jar, /home/mario/sandbox/sbt/so-classpath/target/scala-2.12/test-classes, /home/mario/.ivy2/cache/org.scala-lang/scala-library/jars/scala-library-2.12.4.jar)
)
```
where we see that
```
.../target/scala-2.12/test-classes
.../target/scala-2.12/classes
```
are present.
On the other hand, to retrieve the classpath from within the test itself:
```
val classLoader = this.getClass.getClassLoader
// give Spark classpath via classLoader
```
For example, on my machine, `println(classLoader)` given in the following test
```
class CubeCalculatorTest extends FunSuite {
test("CubeCalculator.cube") {
val classLoader = this.getClass.getClassLoader
println(classLoader)
assert(CubeCalculator.cube(3) === 27)
}
}
```
prints
```
URLClassLoader with NativeCopyLoader with RawResources(
urls = List(/home/mario/sandbox/sbt/so-classpath/target/scala-2.12/test-classes, /home/mario/sandbox/sbt/so-classpath/target/scala-2.12/classes, /home/mario/.ivy2/cache/org.scala-lang/scala-library/jars/scala-library-2.12.4.jar, /home/mario/.ivy2/cache/org.scalatest/scalatest_2.12/bundles/scalatest_2.12-3.0.5.jar, /home/mario/.ivy2/cache/org.scalactic/scalactic_2.12/bundles/scalactic_2.12-3.0.5.jar, /home/mario/.ivy2/cache/org.scala-lang/scala-reflect/jars/scala-reflect-2.12.4.jar, /home/mario/.ivy2/cache/org.scala-lang.modules/scala-xml_2.12/bundles/scala-xml_2.12-1.0.6.jar),
parent = DualLoader(a = java.net.URLClassLoader@6307eb76, b = java.net.URLClassLoader@271053e1),
resourceMap = Set(app.class.path, boot.class.path),
nativeTemp = /tmp/sbt_fa64d1a1/sbt_66bd50e2
)
```
where again we can see
```
.../target/scala-2.12/test-classes
.../target/scala-2.12/classes
```
are present.
To actually pass the classpath to [`ProcessBuilder`](https://www.scala-lang.org/api/current/scala/sys/process/ProcessBuilder.html) within a test:
```
import java.net.URLClassLoader
import sys.process._
class CubeCalculatorTest extends FunSuite {
test("CubeCalculator.cube") {
val classLoader = this.getClass.getClassLoader
val classpath = classLoader.asInstanceOf[URLClassLoader].getURLs.map(_.getFile).mkString(":")
s"java -classpath $classpath MyExternalApp".!
...
}
}
``` | You can get the full `classpath`, to be used in the `ProcessBuilder`'s JVM, from your `sbt` tests, with:
```scala
Thread
.currentThread
.getContextClassLoader
.getParent
.asInstanceOf[java.net.URLClassLoader]
.getURLs
.map(_.getFile)
.mkString(System.getProperty("path.separator"))
``` |
50,439,309 | Using Windows 10 with Spyder IDE running Python 3.5. I am seeing following in the `__init__.py` file complaining about `unable to detect undefined names`:
[](https://i.stack.imgur.com/xRQtR.png)
However, it seems `__init__.py` file is in the same folders as all other files.
[](https://i.stack.imgur.com/TefWn.png)
So why it is complaining? I tried to remove the leading dot in the front, but it still complains. Please give me some pointers. | 2018/05/20 | [
"https://Stackoverflow.com/questions/50439309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1277239/"
] | Your IDE is complaining, not Python. When you do `from simple import *`, you import *everything* exposed by `simple`. This is typically not recommended because it pollutes the global namespace and may implicitly overwrite an existing object.
You get a warning instead of an error because this behavior is not always bad. Having an `__init__.py` file that exposes objects from sub-modules is a very common pattern. As long as you understand the potential risks, just silence the warning:
```
from .input import * # NOQA
```
If your modules don't expose many objects, just import them by name:
```
from .input import A, B, C
```
This has the benefit of allowing Python code analysis tools to better understand your code and warn you of potential issues. | I had the same problem,
the asterisk.
I located the modules to call them as indicated by **Blender**
and it was solved
[](https://i.stack.imgur.com/Uo7IE.png)
change the asterisk by the names of the modules
[](https://i.stack.imgur.com/0pgrZ.png)
locate the names that have conflict
[](https://i.stack.imgur.com/gd6oQ.png)
and as you add them up, the error will be silenced
[](https://i.stack.imgur.com/DwtQB.png)
Thanks for your comments, they helped me with the problem I had |
3,496,564 | I've recently started developing flash and have been getting accustomed to the weirdness of flash builder. Fortunately, I've had exposure to eclipse for java development, so I'm at least familiar with things like the project, preference structure and shortcuts.
One issue that I've run into for both the standalone and plugin client though is that the shortcut for open type (ctrl+shift+t on windows) doesn't seem to work. However, the one for open resource (ctrl+shift+r on windows) works perfectly. I've added my source folder to the source path, so that shouldn't be the problem.
The key binding for this is the default one:
Command: Open Type, Binding: Ctrl+Shift+T, When: Flash Builder Global Scope, Category:Navigation, User: (none)
Has anyone else run into this issue? Any ideas for fixing this? I rely heavily on open type. | 2010/08/16 | [
"https://Stackoverflow.com/questions/3496564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115984/"
] | I experienced the same error. Here's my solution:
`Preference` -> `General` -> `Keys`. Then type without quotes: `Open Type` in field where itg states "type filter here". Then select in "When:" In Action Script Mode. And then press "OK".
Its work in MXML and ActionScript. | Customize Perspective -> “Command Groups Availability” -> Unchecked the “Flash Navigation“
This worked for me. Also check after this that the Preferences - keys - are set to defaults. |
37,573,763 | I'm trying to do a shell script that reads from a file from a string A to a B string. The string A I'm sure that is UNIQUE, but the B string is repeated more than one time.
I'm reading from a file that contains a lot of CREATE queries.
each query ends with (my String B)
>
> ); ------------------------
>
>
>
String A is composed this way:
```
CREATE MULTISET TABLE DBNAME.TABLENAME
```
so I read with sed from A to B
```
sed -n "/$FROMSTR/,/$TOSTR/p" $2 >> querytest.txt
```
I want to stop to the first occurrence of `$TOSTR` (String B) | 2016/06/01 | [
"https://Stackoverflow.com/questions/37573763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4225081/"
] | In place of:
```
sed -n "/$FROMSTR/,/$TOSTR/p"
```
use:
```
sed -n "/$FROMSTR/,\${p; /$TOSTR/q}"
```
This prints from the first occurrence of `$FROMSTR` to the last line `$` except that it quits when it sees the first occurrence of `$TOSTR`.
*Aside:* You should be sure that you trust the source of `FROMSTR` and `TOSTR`. If either variable contained sed-active characters, the result might not be what you want.
### Example 1
As a simple example:
```
$ FROMSTR=2; TOSTR=4; seq 10 | sed -n "/$FROMSTR/,\${p; /$TOSTR/q}"
2
3
4
```
### Example 2
As an exampled closer to your actual input, consider this test file:
```
$ cat file
1
CREATE MULTISET TABLE DBNAME.TABLENAME
2
3
); ------------------------
4
```
And run this command:
```
$ FROMSTR="CREATE MULTISET TABLE DBNAME.TABLENAME"
$ TOSTR="); ------------------------"
$ sed -n "/$FROMSTR/,\${p; /$TOSTR/q}" file
CREATE MULTISET TABLE DBNAME.TABLENAME
2
3
); ------------------------
```
### Example 3
Consider this test file:
```
$ cat file
1
CREATE MULTISET TABLE DBNAME.TABLENAME
2
); ------------------------
); ------------------------
3
CREATE MULTISET TABLE DBNAME.TABLENAME
4
); ------------------------
5
```
We define our variables:
```
$ FROMSTR="CREATE MULTISET TABLE DBNAME.TABLENAME"
$ TOSTR="); ------------------------"
```
And, run our code:
```
$ sed -n "/$FROMSTR/,\${p; /$TOSTR/q}" file
CREATE MULTISET TABLE DBNAME.TABLENAME
2
); ------------------------
``` | I solved my problem, seems that sed has some problem in managing escape characters (\r\n)
I changed my $TOSTR to ");"
and used a loop.
```
sed -n "/$FROMSTR/{p; :loop n; p; /$TOSTR/q; b loop}" $2 >> $3
```
then i echo the characters that i need after ");"
```
echo -e "\r\n--------------------------------------------------------------------------------" >> $3
```
[An useful one on stackoverflow that explain loop](https://stackoverflow.com/questions/20943025/how-can-i-get-sed-to-quit-after-the-first-matching-address-range) |
309,058 | I have temporary contacts in Skype that I want to remove when I no longer need them. So, if I just delete the user via `Remove from Contacts` option, will he be able to see me in his contacts after I delete him?
If this is true, then I guess option `Block User` (without checking `Report Abuse`) is the right way to completely remove both user from your contacts and yourself from his contacts.
I am asking this because I remember that MSN `delete user` option just deletes a user from your contact list while he still sees you in his. | 2011/07/11 | [
"https://superuser.com/questions/309058",
"https://superuser.com",
"https://superuser.com/users/74014/"
] | Removing the user will prevent them from continuing to see your status, but they will still be able to message you, or re-request authorization - they just will have no idea when you are online. In the vast majority of cases, this is the best option, and if your privacy preferences are set to only allow calls/messages from contacts, this will keep you from having to continue to deal with them - they may still see you in their list, but it won't do them any good.
Blocking them will prevent them from messaging you or requesting to add you to their contacts again. It should probably be reserved for serious issues, since it goes beyond removing them from contacts and it's a pain to unblock them if you ever need to contact them again. | From main menu go to Contacts choose 'Advanced',choose 'Backup contacts to file'.
Make sure the Backup has extension .vcf.Do not block,just remove contacts,you are reluctant to deal with for an hour or few.Hold you Skype open for as long as you want.
You are seen only by wanted people.For unwanted you look like you didn't turn on the application at all. Upon finishing the session go the same route, but this time you'll need to 'Restore contacts from file'. You'll have all the previous contacts activated again. People will not take offense. |
309,058 | I have temporary contacts in Skype that I want to remove when I no longer need them. So, if I just delete the user via `Remove from Contacts` option, will he be able to see me in his contacts after I delete him?
If this is true, then I guess option `Block User` (without checking `Report Abuse`) is the right way to completely remove both user from your contacts and yourself from his contacts.
I am asking this because I remember that MSN `delete user` option just deletes a user from your contact list while he still sees you in his. | 2011/07/11 | [
"https://superuser.com/questions/309058",
"https://superuser.com",
"https://superuser.com/users/74014/"
] | Removing the user will prevent them from continuing to see your status, but they will still be able to message you, or re-request authorization - they just will have no idea when you are online. In the vast majority of cases, this is the best option, and if your privacy preferences are set to only allow calls/messages from contacts, this will keep you from having to continue to deal with them - they may still see you in their list, but it won't do them any good.
Blocking them will prevent them from messaging you or requesting to add you to their contacts again. It should probably be reserved for serious issues, since it goes beyond removing them from contacts and it's a pain to unblock them if you ever need to contact them again. | 1. Log into your <https://people.live.com/> account
2. Chose the unnamed or odd contact that you can-not delete
3. Hover and choose “add to Skype”
4. Choose allow
5. On the skype page choose unblock if needed
6. Give the contact a name like “xyz”
7. Go through your entire list of unnamed contacts this way
8. When all of the skype contacts have synced with people, go back to skype
9. Choose to delete the newly named contact
10. Wait for these to sync again with people, may need to refresh “people contacts page”
11. Those annoying farts should now be gone!!!
This is a slow process, contacts need to sync between programs so be patient. Appears the unnamed contact is not able to be serviced without a name, once it is added back to Skype with a name, it can be deleted at will.
Tim J Kelly
DIGITIM llc
TJKelly@digitimllc.com |
309,058 | I have temporary contacts in Skype that I want to remove when I no longer need them. So, if I just delete the user via `Remove from Contacts` option, will he be able to see me in his contacts after I delete him?
If this is true, then I guess option `Block User` (without checking `Report Abuse`) is the right way to completely remove both user from your contacts and yourself from his contacts.
I am asking this because I remember that MSN `delete user` option just deletes a user from your contact list while he still sees you in his. | 2011/07/11 | [
"https://superuser.com/questions/309058",
"https://superuser.com",
"https://superuser.com/users/74014/"
] | From main menu go to Contacts choose 'Advanced',choose 'Backup contacts to file'.
Make sure the Backup has extension .vcf.Do not block,just remove contacts,you are reluctant to deal with for an hour or few.Hold you Skype open for as long as you want.
You are seen only by wanted people.For unwanted you look like you didn't turn on the application at all. Upon finishing the session go the same route, but this time you'll need to 'Restore contacts from file'. You'll have all the previous contacts activated again. People will not take offense. | 1. Log into your <https://people.live.com/> account
2. Chose the unnamed or odd contact that you can-not delete
3. Hover and choose “add to Skype”
4. Choose allow
5. On the skype page choose unblock if needed
6. Give the contact a name like “xyz”
7. Go through your entire list of unnamed contacts this way
8. When all of the skype contacts have synced with people, go back to skype
9. Choose to delete the newly named contact
10. Wait for these to sync again with people, may need to refresh “people contacts page”
11. Those annoying farts should now be gone!!!
This is a slow process, contacts need to sync between programs so be patient. Appears the unnamed contact is not able to be serviced without a name, once it is added back to Skype with a name, it can be deleted at will.
Tim J Kelly
DIGITIM llc
TJKelly@digitimllc.com |
621,244 | If a CMB photon traveled for 13.7 billion years (- 374,000 years) to reach me.
How far away was the source of that CMB photon when it first emitted it?
My attempt to solve this question was to use the following assumptions:
1. Temperature of CMB photon today is 2.725 K (will use value of 3 K here)
2. Temperature of CMB photon when it was first emitted is 3000 K
3. A factor of x1000 in temperature decrease results in a factor of x1000 in wavelength increase. (According to Wien's displacement law)
Does this mean that the source of the CMB photon that just reached me today, was actually 13.7 billion light years / 1000 = 13.7 million light years away from me when it first emitted the photon? | 2021/03/15 | [
"https://physics.stackexchange.com/questions/621244",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/84727/"
] | The comoving distance traveled by light in vacuum between cosmological times $t\_i$ and $t\_f$ is $\displaystyle \int\_{t\_i}^{t\_f} \frac{c\,dt}{a(t)}$. The metric distance at cosmological time $t$ is $a(t)$ times the comoving distance. The distance you're looking for is therefore $\displaystyle \int\_{t\_i}^{t\_f} \frac{a(t\_i)}{a(t)} c\,dt$.
This value depends on $a(t)$ over the whole time interval from $t\_i$ to $t\_f$, not just at the endpoints. The redshift factor is equal to $\displaystyle\frac{a(t\_f)}{a(t\_i)}$, but you can't just divide $cΔt$ by that factor to get the distance.
You can, however, divide the usually quoted comoving distance to the CMBR (around $46\text{ Gly}$ or $14\text{ Gpc}$) by the CMBR redshift (around $1100$) to get the correct distance (around $42\text{ Mly}$ or $13\text{ Mpc}$). This is because the $46\text{ Gly}$ distance is calculated using that first integral, without multiplying by $a(t\_i)$, and $a(t\_f)=a(t\_0)=1$ by convention. | The light was emitted 367.000 years after the big bang from the edge of the universe. So The distance to where you now are at that epoch was 367.000 lightyears. |
621,244 | If a CMB photon traveled for 13.7 billion years (- 374,000 years) to reach me.
How far away was the source of that CMB photon when it first emitted it?
My attempt to solve this question was to use the following assumptions:
1. Temperature of CMB photon today is 2.725 K (will use value of 3 K here)
2. Temperature of CMB photon when it was first emitted is 3000 K
3. A factor of x1000 in temperature decrease results in a factor of x1000 in wavelength increase. (According to Wien's displacement law)
Does this mean that the source of the CMB photon that just reached me today, was actually 13.7 billion light years / 1000 = 13.7 million light years away from me when it first emitted the photon? | 2021/03/15 | [
"https://physics.stackexchange.com/questions/621244",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/84727/"
] | The comoving distance traveled by light in vacuum between cosmological times $t\_i$ and $t\_f$ is $\displaystyle \int\_{t\_i}^{t\_f} \frac{c\,dt}{a(t)}$. The metric distance at cosmological time $t$ is $a(t)$ times the comoving distance. The distance you're looking for is therefore $\displaystyle \int\_{t\_i}^{t\_f} \frac{a(t\_i)}{a(t)} c\,dt$.
This value depends on $a(t)$ over the whole time interval from $t\_i$ to $t\_f$, not just at the endpoints. The redshift factor is equal to $\displaystyle\frac{a(t\_f)}{a(t\_i)}$, but you can't just divide $cΔt$ by that factor to get the distance.
You can, however, divide the usually quoted comoving distance to the CMBR (around $46\text{ Gly}$ or $14\text{ Gpc}$) by the CMBR redshift (around $1100$) to get the correct distance (around $42\text{ Mly}$ or $13\text{ Mpc}$). This is because the $46\text{ Gly}$ distance is calculated using that first integral, without multiplying by $a(t\_i)$, and $a(t\_f)=a(t\_0)=1$ by convention. | "13.7 million light years away from me when it first emitted the photon?"
Based on your assumptions, this is sort-of correct. There are two not-quite-correct details.
(1) The temperature you assune for the production of the CMBR is corrected in the comment by benrg.
(2) The "me" was not present in the univese when the observed CMBR was emitted. A better dscription is the location of the comoving point where you are now at the location it was when the CMRB was emitted. |
621,244 | If a CMB photon traveled for 13.7 billion years (- 374,000 years) to reach me.
How far away was the source of that CMB photon when it first emitted it?
My attempt to solve this question was to use the following assumptions:
1. Temperature of CMB photon today is 2.725 K (will use value of 3 K here)
2. Temperature of CMB photon when it was first emitted is 3000 K
3. A factor of x1000 in temperature decrease results in a factor of x1000 in wavelength increase. (According to Wien's displacement law)
Does this mean that the source of the CMB photon that just reached me today, was actually 13.7 billion light years / 1000 = 13.7 million light years away from me when it first emitted the photon? | 2021/03/15 | [
"https://physics.stackexchange.com/questions/621244",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/84727/"
] | "13.7 million light years away from me when it first emitted the photon?"
Based on your assumptions, this is sort-of correct. There are two not-quite-correct details.
(1) The temperature you assune for the production of the CMBR is corrected in the comment by benrg.
(2) The "me" was not present in the univese when the observed CMBR was emitted. A better dscription is the location of the comoving point where you are now at the location it was when the CMRB was emitted. | The light was emitted 367.000 years after the big bang from the edge of the universe. So The distance to where you now are at that epoch was 367.000 lightyears. |
33,230,901 | I'm maintaining a webshop and would like to use seo friendly urls.
I have everything set and it works which is nice.
But the webshop is about tires and i have a few tires using a / in the name like this:
```
1000/50R25
```
As it isn't possible (well i assume?) to use this name in the url what would be the best way to go to make a nice readable url which works correct.
My url looks now like this:
```
http://example.nl/TireRetreading/Rounding/Agricultural?product_id=1601
```
Note: I can't remove or replace it with another character. | 2015/10/20 | [
"https://Stackoverflow.com/questions/33230901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2724940/"
] | First a disclaimer: no one will ever have a definitive answer of what is or isn't SEO friendly. That said, here's some hint.
The direct approach is to url\_encode each part of the friendly URL. In your example, you can decide that an URL is defined as `http://example.nl/tires/<vendor>/<measure>` so you url encode each part and obtain url like `http://example.nl/tires/Afronden%20Landbouw/1000%2F50R25`. This are a bit more SEO friendly, but definetly not readable by users. This can penalize you when choosing between multiple results in SERP.
My suggestion is to replace each "page breaking" character with a dash (not underscores, since is a non-breaking character) and obtain a better url like
`http://example.nl/tires/Afronden-Landbouw/1000-50R25`.
Notice that I haven't placed the product ID in the URL; if you find a way of mapping URL to product without ID is much better, but if can't is not a big issue.
Then you need to think carefully about "categories". When defining sub-path, think at each level as an "explorable category", with nested product. This imply that valid URL could be:
* `http://example.nl/tires/` (search through all tires);
* `http://example.nl/tires/Afronden-Landbouw/` (list of tires made by Afronden-Landbouw)
* `http://example.nl/tires/Afronden-Landbouw/1000-50R25` (a single model)
* `http://example.nl/tires/Afronden-Landbouw/1000-50R25/1601` (a single model, with explicit product ID)
With this organization you use a meaningful sub-path, search engines like Google, will have a better "understanding" of your websites and can provide better result to the user. Also, some advanced users can play with your sub-path and get meaningful resources.
Last and NOT least, always always always set redirect from the old URL to the new one. You can start with 302 redirect for testing, and then set a definitive 301 redirect. If you don't use redirect you will loose ALL your reputation so far... which is not SEO at all.
Happy SEO | since not much details provided on how the seo friendly urls is done, so I'm assuming all the seo friendly url is like this:
```
http://domain.com/product/tires/michelin/size/205/40/17Z
```
and assuming you have product.php file mapped to read the request. you can simply have some code to read the REQUEST\_URI
```
$uri = explode('/', trim($_SERVER['REQUEST_URI'], '/'));
```
and you may get the value from the $uri
```
$page = $uri[0];
$product = $uri[1];
$manufacturer = $uri[2];
$option = $uri[3];
$tire_size = implode("/" array($uri[4], $uri[5], $uri[6]));
```
Hope you get the idea, maybe can share a bit more on how you achieve those friendly seo urls, so that other might have different ideas. |
9,677 | I recently started my three and a half year old at karate, because he had a great time at a bring a friend day.
I feel that I have an active child, but he seems to be no more active than other little boys his age. His class is for 3 to 5-year-olds. Today in class the instructor had to speak to him several times about playing. The second time he spoke to my child he gave him a choice of sitting out on the side or saying that he would not play again. My child agreed not to do it again. But, as some 3-year-olds do, he forgot pretty quickly. The third time he took his belt away. My child cried just a little bit and wiped his tears away. He looked at me in sadness to tell me his belt was taken away. It was hard to watch. I would have preferred for him to maybe sit out a few minutes instead of having his belt removed. The instructor said that he could earn it back next time, which will be next week.
We have had a different instructor teach the class before as a sub and there was a difference between their teaching styles. The substitute instructor did a great job of keeping the kids active throughout the entire class. Today's instructor had a lot more down time.
**What I'm really trying to determine here is if the expectations and consequences for behavior are developmentally appropriate for this age.**
And I'm also waiting for your advises about whether or not to continue karate classes versus trying other sports at this time in his life.
I know I could shop around for other centers or work with the other instructor. But I'm also considering other sports that may have more activity and less downtime. But if anyone out there can tell me what appropriate expectations and consequences might be for behavior for an almost 4-year-old in karate classes, I would really appreciate it. I would love to know some specifics about what you would expect during a 30-minute period in the way of self-control and activity. Thanks
A quick update: my husband took our son to class today and he earned his belt back. My husband did get a minute to touch base with the instructor to get his assessment on how our kiddo is doing, and he said he's doing as expected for his age. Thank you everyone for sharing your experience and insight. It helped me understand everything better. | 2020/02/14 | [
"https://martialarts.stackexchange.com/questions/9677",
"https://martialarts.stackexchange.com",
"https://martialarts.stackexchange.com/users/10643/"
] | I'll answer this question from the perspective of a dad and a former martial arts instructor.
Your kid is like a lot of other kids it sounds like. It's normal at this age (3 years old) for kids to not be able to concentrate and do what they're told for extended periods of time. A good teacher has to be able to get the kids interested in what he/she is doing. They need to make it fun. They can't spend too much time on any one thing, or else the kids will get bored. And they can't expect kids to pay attention perfectly. They have to go into it knowing that kids at this age are just trying to have fun, and if they can get one or two kids to be able to do what they're being shown every now and then, that's a success. Their expectations must be pretty low.
**That being said, it sounds to me like your kid's karate instructor did the right thing.** Actually, he was probably a little light if all he did was remove your kid's belt. The best thing he could have done would have been to take your child off the floor and have him sit it out on the side - with you, of course, not alone. My guess is he was being nice and reserving that for the future.
The other thing to note is that the instructor did this right away in the first class. If he avoided it until several classes had gone by, your child would have been confused, because this was inconsistent with all of the other times your child was not disciplined. And that would have made it harder for your child to learn. The fact that the instructor did this right away is a point in his favor.
Your child had a typical reaction, which was to be upset and cry. From this, he'll learn that if he disobeys the instructor again, the same thing will happen, or worse.
Kids at this age don't understand the boundaries and what they can and can not do. So they test. They goof off. You can tell them not to do stuff, but you can't reason with them at this age. That's not going to be very effective. Instead, it takes some kind of disciplinary **action** to get them to realize there are **consequences** to bad behavior. Actions are a lot more effective than words.
We do a disservice to children by not giving them proper boundaries. That goes for parents and for teachers. In most martial arts classes teaching children, you're going to see some really bad behavior going on with the kids. They're going to be goofing off, playing with other kids, talking while the instructor is talking, running around the class, etc.
What are the teachers doing? If you watch any of these kinds of classes, you'll commonly see the same thing. The teachers are ignoring the kids that aren't paying attention, and they only care about the kids that are giving them attention. They tell the misbehaving kids to not misbehave, but those kids just laugh and keep misbehaving. And the cycle continues.
This is generally how teachers cope with it. They know parents don't want their kids to be "disciplined". Parents want their kids to have a good time. They don't want it to be "too serious". But let me ask you, if your kid is one of the ones misbehaving, aren't you upset that the teacher isn't giving them any attention? Aren't you upset they're not improving? You should be.
And by "improving", I don't mean at karate. I think expecting a 3 year old to be improving at karate is misguided. Instead, improving in this context means being able to follow along in class with the rest of the students and to keep his attention on the teacher. That's going to pay off in all aspects of his life, especially academics later on.
So you need to be on-board with the teacher disciplining your child when it is necessary. Otherwise don't pretend it's anything but a babysitting class. Because, they're getting nothing out of it otherwise. They're not improving.
This idea extends into parenting as well. In fact, it starts and ends at home with the parents. Parents that do not tell their kids "No" a lot and frequently are doing a disservice to their kids. They need to set those boundaries, and the way to do that isn't by talking and hoping their kids will eventually get better. The way to do it is by taking their children out of the situation forcefully if they're not obeying right away. They need to make sure their kids know that if they don't obey without delay, there will be consequences.
Let me give you an example from my life as a dad. My 4 year old daughter and I drove to a nearby park to play. I parked the car and told her to put on her coat, because it was too cold outside to be without it. She refused. I told her that she had to, because it was too cold. She said no again. Rather than argue with her about it, as I did in the past without success, I said, "Okay then. No park today." And I quickly drove back home.
In the car, she said "okay", she would put her coat on. But it was too late. It wasn't about the coat, but about her refusing to do what she was told. So I kept driving home. And she cried some more. It hurt me, too, because I love her to death. But this is what a real parent has to do. Actions speak louder than words. Knowing there are consequences to bad behavior is really important for young children ages 2 and up. It establishes boundaries and guides them towards making better choices in life.
The other thing I do when my daughter misbehaves is I tell her what I saw her do from my perspective and how it made me feel, and how it made others feel. We have a conversation about it when some time has passed and she's not too upset anymore. Being able to see things from someone else's perspective is a huge part of their development. It helps them figure out what went wrong. Otherwise it can seem pretty arbitrary and trivial to them, which just makes them angry and resentful.
And keep loving your child. Changing your parenting style does not change how often you hug and kiss your kid and tell him how much you love him. Keep doing that. He's going to hate you and cry after you discipline him, but it will be short lived. And you should always tell him you love him, even as you're disciplining.
And by the way, I don't recommend spanking or hitting your child, either. That's not what I mean by disciplinary action. Spanking just breaks his trust of you and creates hatred and resentment. It drives him away from you. That's not what you want. You want open lines of communication. You want him to go to you and tell you things without fear. You want him to feel comfortable enough around you to express his feelings. Spanking will poison all of that.
Anyway, getting back to the incident with the karate instructor, once again I think what he did was the right thing to do. The fact that he did this immediately on day one helps, also. Without proper boundaries, your kid probably will not improve. And that goes for parenting and for regular academic classes as well.
Hope that helps. | I'd like to preface anything that I say with the caveat that we are not present in your school, and we don't know the policy of the head instructor/school owner when it comes to things like taking away belts and other disciplinary actions. I am also speaking as a high ranking black belt, and a father of two boys (5 1/2 and 4 years old) that are in classes as well (I don't teach them).
Class management for this age is hard, as they have a limited attention span, and like to move from activity to activity with little down time. However, this is also a great age to start teaching and managing expectations. Our classes have them starting out by sitting on their dots, from whenever they get in class until it starts. There is a monitoring instructor/helper assisting in managing this, with gentle reminders and encouragement.
Classes have some downtime, and there are points where they are expected to sit for a minute or two while another group/child demonstrates something. And, kids being kids, this doesn't always go smooth. The discipline escalates from gentle reminders, to having to sit to the side of the class, or (and we are lucky in that we have a lot of staff/assistants) an instructor sitting with them being an example. I can think of only a couple instances in the last couple of years where anyone has had a belt taken away. We also give out attitude slips for kids that are doing the things they should when they should.
I don't think it is unreasonable to ask a child in this age group to be able to pay attention or sit quietly through a 30 minute class (Heh, my kids would sit all day watching Wild Kratts if I let them). The trick is to make it enjoyable for them, even when they are sitting, and to manage it so that there is not much down/sitting time as can be arranged.
It does sound like the instructor needs a little more practice managing time, and/or doesn't quite know how to reinforce correct behavior. I (personally) don't like taking away a belt, especially from a new student, as much of their martial arts identity is tied up (no pun intended) in that belt. You take it away, you take away their identity essentially. However, if that is a consequence that is explained to them ahead of time, it's a little easier to manage.
What is very important, is how YOU handle this as well. I would not put any blame on the instructor. Yes, he may have been preemptive or arbitrary, but it was the behavior of your boy that prompted it. Be understanding, but also make it clear that it was HIS choices and HIS actions that caused the belt to be taken away, but it's also HIS actions that can earn it back. Kids that age are exploring and trying to exert their own control over things ("NO!", "I do it", "I wanna do that"), so letting him know that he can control this himself will be a big boost.
Be supportive, ride the inevitable rocky patches at the beginning, and if you have concerns, ask to speak privately with the head instructor or school owner. Explain your concerns and listen to what they have to say. This may be normal discipline progression at the school. |
191,572 | [33](https://github.com/TheOnlyMrCat/33) is a simple esolang I created. You may have seen me use it in a few questions. You're not going to be writing a full interpreter. The interpreter you will be writing is for a simplified version of 33.
This simplified 33 has two numeric registers: the accumulator and the counter. The accumulator holds all the post-arithmetic values, the counter is where numbers in the program come from. Both registers are initialized to 0.
```
0-9 | Appends the digit to the counter
a | Adds the counter to the accumulator
m | Subtracts the counter from the accumulator
x | Multiplies the accumulator by the counter
d | Divides the accumulator by the counter
r | Divides the accumulator by the counter, but stores the remainder in the accumulator
z | Sets the counter to 0
c | Swaps the accumulator and counter
-----
p | Outputs the current value of the accumulator as an ASCII character
o | Outputs the current value of the accumulator as a formatted decimal number
i | Outputs a newline character (0x0a)
-----
P | Stores the ASCII value of the next character read in the accumulator
O | Stores the next integer read into the accumulator
-----
n | Skips the next instruction if the accumulator is not 0
N | Skips the next instruction if the accumulator is 0
g | Skips the next instruction if the accumulator is less than or equal to 0
G | Skips the next instruction if the accumulator is greater than 0
h | Skips the next instruction if the accumulator is greater than or equal to 0
H | Skips the next instruction if the accumulator is less than 0
```
Test cases
----------
```
Program / Input -> Output
2o -> 0
25co -> 25
1a0aoi -> 11 (trailing newline)
Oo / 42 -> 42
Op / 42 -> *
1cNoo -> 11
no -> 0
Ogo / 2 -> 2
Ogoi / -4 -> (newline)
50a -> (no output)
On12co / 12 -> 2
```
Clarifications
--------------
* The input to your interpreter will be a valid simplified 33 program.
* The input may be given in any [acceptable format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods).
* The output may be given in any acceptable format.
* When dividing, truncate any decimal places.
* A trailing newline is acceptable, but it must be consistent; as in, if there's an `i` at the end of the program, it should have two trailing newlines.
* The accumulator and counter must be able to hold at least a signed byte (-128 to 127)
* You may assume that the `p` instruction will never be given when the accumulator has an invalid ASCII character in it.
* You may assume the `O` instruction will never be given unless there is a valid integer string (such as `3`, `-54`, `+23`) left in the input. | 2019/09/10 | [
"https://codegolf.stackexchange.com/questions/191572",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/77338/"
] | [JavaScript (Node.js)](https://nodejs.org), 264 bytes
=====================================================
```javascript
S=>I=>[...S].map(s=>K?K=0:1/s?C=+(C+s):eval("A*=C;[A,C]=[C,A];K=!A;;K=A;K=A>0;A%=C;K=A<=0;A=A/C|0;I=I.replace(/-?\\d+/,n=>(A=+n,''));K=A>=0;O+=A;K=A<0;A+=C;C=0;;[A]=B(I[0]),I=I.slice(1);O+=`\n`;O+=B([A]);A-=C".split`;`[B(s)[0]*73%378%22]),A=C=K=0,O='',B=Buffer)&&O
```
[Try it online!](https://tio.run/##bZJfb5swFMXf@RRepNR2@U9bdQq9RATtgUUqD3kkSFgUMiZqI0wqTds@e2YT2B4WJMwxPr9zr8Hf2QeT1dD2o83FW31p4HKAKIUodxznUDjvrCcSov12D97Gd@U2AZMkpqSb@oN1ZBXfQxLmsZUUkCdWXIR7@BSHaoz1HXlhvFYGJV9AaYjd5JcXppA6Q913rKqJa2@PxzfTtThEJAaTWxhTOsGKyMxr0IuCTRWUqHeqXAE7kuZeQS0dJbtWBflUu8sjL/VzR5SLhrENycqRfdeOZVjmOyKpwu6fH9YPz5/XQaASYkhAbc7KAGNrB7tz09QDvbvLLmMtx4rJGgEqjUCg@TKCp2qeGD7zmGgnmQnkosdgkv1f6VevQhj8H5ydtC@YZau0/YiMJ48t69wPKm3xA2SUhrE04YxD@07odS8EHzmmTiOGL6z6RrqWqyYj9NNAqBJcjiiX4jxUtYVa3p9HtQGMCzVq45JgR1h/i2XqqrzpZ@sgOVej4ZwoutrpxImsDlPuZmWhr4fs1ZHKx09t84NcC94gUKpbuEFMrd0AsvN4G2iWIgv6H4ttrA9WzUYSeHr5Nw0vfwA "JavaScript (Node.js) – Try It Online")
Saved ~20 bytes, thanks to Arnauld's magic integer modulus. | ### Lua 5.3, 342 bytes
Code is provided as a cmdline argument, input is provided via stdin.
```lua
H=string.char R=io.read A=0 C=0 i=1 s=...while i<=#s do
b=s:byte(i)d=H(b)i=i+(({H=A<0,G=A>0,N=A==0,g=A<=0,h=A>=0,n=A~=0})[d]and 2or
1)io.write(({i='\n',o=A|0,p=H(A%255)})[d]or'')A,C=d=='O'and R'n'or d=='P'and
R(1):byte()or d=='d'and A//C or d=='r'and A%C or({a=A+C,c=C,m=A-C,x=A*C})[d]or
A,b>=48 and b<58 and b-48+C*10or({c=A,z=0})[d]or C end
``` |
191,572 | [33](https://github.com/TheOnlyMrCat/33) is a simple esolang I created. You may have seen me use it in a few questions. You're not going to be writing a full interpreter. The interpreter you will be writing is for a simplified version of 33.
This simplified 33 has two numeric registers: the accumulator and the counter. The accumulator holds all the post-arithmetic values, the counter is where numbers in the program come from. Both registers are initialized to 0.
```
0-9 | Appends the digit to the counter
a | Adds the counter to the accumulator
m | Subtracts the counter from the accumulator
x | Multiplies the accumulator by the counter
d | Divides the accumulator by the counter
r | Divides the accumulator by the counter, but stores the remainder in the accumulator
z | Sets the counter to 0
c | Swaps the accumulator and counter
-----
p | Outputs the current value of the accumulator as an ASCII character
o | Outputs the current value of the accumulator as a formatted decimal number
i | Outputs a newline character (0x0a)
-----
P | Stores the ASCII value of the next character read in the accumulator
O | Stores the next integer read into the accumulator
-----
n | Skips the next instruction if the accumulator is not 0
N | Skips the next instruction if the accumulator is 0
g | Skips the next instruction if the accumulator is less than or equal to 0
G | Skips the next instruction if the accumulator is greater than 0
h | Skips the next instruction if the accumulator is greater than or equal to 0
H | Skips the next instruction if the accumulator is less than 0
```
Test cases
----------
```
Program / Input -> Output
2o -> 0
25co -> 25
1a0aoi -> 11 (trailing newline)
Oo / 42 -> 42
Op / 42 -> *
1cNoo -> 11
no -> 0
Ogo / 2 -> 2
Ogoi / -4 -> (newline)
50a -> (no output)
On12co / 12 -> 2
```
Clarifications
--------------
* The input to your interpreter will be a valid simplified 33 program.
* The input may be given in any [acceptable format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods).
* The output may be given in any acceptable format.
* When dividing, truncate any decimal places.
* A trailing newline is acceptable, but it must be consistent; as in, if there's an `i` at the end of the program, it should have two trailing newlines.
* The accumulator and counter must be able to hold at least a signed byte (-128 to 127)
* You may assume that the `p` instruction will never be given when the accumulator has an invalid ASCII character in it.
* You may assume the `O` instruction will never be given unless there is a valid integer string (such as `3`, `-54`, `+23`) left in the input. | 2019/09/10 | [
"https://codegolf.stackexchange.com/questions/191572",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/77338/"
] | [JavaScript (Node.js)](https://nodejs.org), 264 bytes
=====================================================
```javascript
S=>I=>[...S].map(s=>K?K=0:1/s?C=+(C+s):eval("A*=C;[A,C]=[C,A];K=!A;;K=A;K=A>0;A%=C;K=A<=0;A=A/C|0;I=I.replace(/-?\\d+/,n=>(A=+n,''));K=A>=0;O+=A;K=A<0;A+=C;C=0;;[A]=B(I[0]),I=I.slice(1);O+=`\n`;O+=B([A]);A-=C".split`;`[B(s)[0]*73%378%22]),A=C=K=0,O='',B=Buffer)&&O
```
[Try it online!](https://tio.run/##bZJfb5swFMXf@RRepNR2@U9bdQq9RATtgUUqD3kkSFgUMiZqI0wqTds@e2YT2B4WJMwxPr9zr8Hf2QeT1dD2o83FW31p4HKAKIUodxznUDjvrCcSov12D97Gd@U2AZMkpqSb@oN1ZBXfQxLmsZUUkCdWXIR7@BSHaoz1HXlhvFYGJV9AaYjd5JcXppA6Q913rKqJa2@PxzfTtThEJAaTWxhTOsGKyMxr0IuCTRWUqHeqXAE7kuZeQS0dJbtWBflUu8sjL/VzR5SLhrENycqRfdeOZVjmOyKpwu6fH9YPz5/XQaASYkhAbc7KAGNrB7tz09QDvbvLLmMtx4rJGgEqjUCg@TKCp2qeGD7zmGgnmQnkosdgkv1f6VevQhj8H5ydtC@YZau0/YiMJ48t69wPKm3xA2SUhrE04YxD@07odS8EHzmmTiOGL6z6RrqWqyYj9NNAqBJcjiiX4jxUtYVa3p9HtQGMCzVq45JgR1h/i2XqqrzpZ@sgOVej4ZwoutrpxImsDlPuZmWhr4fs1ZHKx09t84NcC94gUKpbuEFMrd0AsvN4G2iWIgv6H4ttrA9WzUYSeHr5Nw0vfwA "JavaScript (Node.js) – Try It Online")
Saved ~20 bytes, thanks to Arnauld's magic integer modulus. | [Julia 1.0](http://julialang.org/), 355 bytes
=============================================
```julia
p=print
function f(s,a=0,c=0,i=1)
for x=s
z=findfirst(==(x),"amxdrzcpoiPOnNgGhH0123456789")
y=z-9
i<1&&(i=1;continue)
z<6 ? a=(+,-,*,÷,%)[z](a,c) :
z<7 ? c=0 :
z<8 ? ((a,c)=(c,a)) :
z<9 ? p(Char(a)) :
y<1 ? p(a) :
y<2 ? p("\n") :
y<3 ? a=0+read(stdin,UInt8) :
y<4 ? a=parse(Int,readline()) :
y<10 ? (!=,==,<=,>,>=,<)[y-3](a,0)&&(i=0) :
c=10c+y-10
end
end
```
Program provided as an argument, eg `f("2o")`, input taken from `stdin`.
[Try it online!](https://tio.run/##RVDLTsMwELz7K0IkqjV1JDtNXzQLBw7ApeXCqXCwnEeNihMlqZTkx/gAPiw4jwrJq52dWY/X@3U5aynqrssxL7SpSHIxqtKZcRIomUTOlA2NgpIkK5waS9Jiok2U6KKsABFqylz5XUdFq/JMvx3MPn0@vXDhL4Llar3ZupQ02HpbokMxm4G12qnMVNpcYkracOU8OhJhzjx2x35/2C09tp8gmaLOvZXXVrYTDHhjMQwSgmKSjh1by@bwdJIFjFQTioGSY@EPhfth3LFeDA/yeRHLCMoq0oa9v5pqM6rBoOayKGOwLOu7ztrEcLXm/RA3yBBZiOyBPdhMj4236IfmdPgh73sVCq7mjSc4iU3UR5dCSR10wK6W7oZ1n401Jim4fuaOeakmJCSXmR7xYeIO@aSpfTZR5iql/2C6teRyoozwe9su8Ik9PvECIvw/ "Julia 1.0 – Try It Online") |
51,389,792 | I have a table that is a combination of 4 things.
```
place1 <- c("Florida", "California", "Georgia")
race1 <- c("NHW", "NHB", "Hisp")
race2 <- c("NHW", "NHB", "Hisp")
cancer <- c("Lung", "Liver", "Thyroid")
combos <- expand.grid(place1, race1, race2, cancer, stringsAsFactors = FALSE)
names(combos) <- c("place1", "race1", "race2", "cancer")
```
I would like to add another column that is called `place2`. It needs to hold the value from `place1`, "USA", and then "France". That is, I need to take each record and multiply it by 3.
Currently, the first two records are:

The dataframe I want to produce will look like this:
 | 2018/07/17 | [
"https://Stackoverflow.com/questions/51389792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9835261/"
] | using `tidyverse`:
```
library(tidyverse)
combos %>%
mutate(place2 = map(place1,list,"USA","France")) %>%
unnest
# place1 race1 race2 cancer place2
# 1 Florida NHW NHW Lung Florida
# 2 Florida NHW NHW Lung USA
# 3 Florida NHW NHW Lung France
# 4 California NHW NHW Lung California
# 5 California NHW NHW Lung USA
# 6 California NHW NHW Lung France
# 7 Georgia NHW NHW Lung Georgia
# 8 Georgia NHW NHW Lung USA
# 9 Georgia NHW NHW Lung France
# 10 Florida NHB NHW Lung Florida
# 11 Florida NHB NHW Lung USA
# ...
``` | A simple way could be by using combination of `cbind` and `rbind` as:
```
rbind(cbind(combos, place2 = combos$place1),
cbind(combos, place2 = "USA"),
cbind(combos, place2 = "France"))
# place1 race1 race2 cancer place2
# 1 Florida NHW NHW Lung Florida
# 2 California NHW NHW Lung California
# 3 Georgia NHW NHW Lung Georgia
# 4 Florida NHB NHW Lung Florida
#
# so on 239 more rows
``` |
51,389,792 | I have a table that is a combination of 4 things.
```
place1 <- c("Florida", "California", "Georgia")
race1 <- c("NHW", "NHB", "Hisp")
race2 <- c("NHW", "NHB", "Hisp")
cancer <- c("Lung", "Liver", "Thyroid")
combos <- expand.grid(place1, race1, race2, cancer, stringsAsFactors = FALSE)
names(combos) <- c("place1", "race1", "race2", "cancer")
```
I would like to add another column that is called `place2`. It needs to hold the value from `place1`, "USA", and then "France". That is, I need to take each record and multiply it by 3.
Currently, the first two records are:

The dataframe I want to produce will look like this:
 | 2018/07/17 | [
"https://Stackoverflow.com/questions/51389792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9835261/"
] | Just with base R:
```
# add columns
new_vals = c("USA", "France")
result = rbind(
merge(combos, data.frame(place2 = new_vals), all = TRUE),
transform(combos, place2 = place1)
)
# order result rows and columns
with(result, result[order(place1, race1, race2, cancer, place2), c("place1", "place2", "race1", "race2", "cancer")])
# place1 place2 race1 race2 cancer
# 134 California France Hisp Hisp Liver
# 53 California USA Hisp Hisp Liver
# 215 California California Hisp Hisp Liver
# 107 California France Hisp Hisp Lung
# 26 California USA Hisp Hisp Lung
# 188 California California Hisp Hisp Lung
# ...
``` | A simple way could be by using combination of `cbind` and `rbind` as:
```
rbind(cbind(combos, place2 = combos$place1),
cbind(combos, place2 = "USA"),
cbind(combos, place2 = "France"))
# place1 race1 race2 cancer place2
# 1 Florida NHW NHW Lung Florida
# 2 California NHW NHW Lung California
# 3 Georgia NHW NHW Lung Georgia
# 4 Florida NHB NHW Lung Florida
#
# so on 239 more rows
``` |
51,389,792 | I have a table that is a combination of 4 things.
```
place1 <- c("Florida", "California", "Georgia")
race1 <- c("NHW", "NHB", "Hisp")
race2 <- c("NHW", "NHB", "Hisp")
cancer <- c("Lung", "Liver", "Thyroid")
combos <- expand.grid(place1, race1, race2, cancer, stringsAsFactors = FALSE)
names(combos) <- c("place1", "race1", "race2", "cancer")
```
I would like to add another column that is called `place2`. It needs to hold the value from `place1`, "USA", and then "France". That is, I need to take each record and multiply it by 3.
Currently, the first two records are:

The dataframe I want to produce will look like this:
 | 2018/07/17 | [
"https://Stackoverflow.com/questions/51389792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9835261/"
] | using `tidyverse`:
```
library(tidyverse)
combos %>%
mutate(place2 = map(place1,list,"USA","France")) %>%
unnest
# place1 race1 race2 cancer place2
# 1 Florida NHW NHW Lung Florida
# 2 Florida NHW NHW Lung USA
# 3 Florida NHW NHW Lung France
# 4 California NHW NHW Lung California
# 5 California NHW NHW Lung USA
# 6 California NHW NHW Lung France
# 7 Georgia NHW NHW Lung Georgia
# 8 Georgia NHW NHW Lung USA
# 9 Georgia NHW NHW Lung France
# 10 Florida NHB NHW Lung Florida
# 11 Florida NHB NHW Lung USA
# ...
``` | Just with base R:
```
# add columns
new_vals = c("USA", "France")
result = rbind(
merge(combos, data.frame(place2 = new_vals), all = TRUE),
transform(combos, place2 = place1)
)
# order result rows and columns
with(result, result[order(place1, race1, race2, cancer, place2), c("place1", "place2", "race1", "race2", "cancer")])
# place1 place2 race1 race2 cancer
# 134 California France Hisp Hisp Liver
# 53 California USA Hisp Hisp Liver
# 215 California California Hisp Hisp Liver
# 107 California France Hisp Hisp Lung
# 26 California USA Hisp Hisp Lung
# 188 California California Hisp Hisp Lung
# ...
``` |
3,947,139 | $h\_n(x) = n^2 (e^{x/n} -1 - x/n)$
So I know that the pointwise limit is $x^2/x.$ I found it by using L'hopital's rule (is there a way to show it without using l'hopital's rule?).
I know to show that the convergence is not uniform I need to:
* Find $\epsilon >0$ st $\forall N \in \mathbb{N}, \exists \geq N, x \in \mathbb{R}$ such that $|h\_n(x)-x^2/n| = |n^2 (e^{x/n} -1 - x/n) - x^2/2| \geq \epsilon$.
Is the negation above correct?
From there I said let $\epsilon =1/10$ then $\forall N \in \mathbb{N},$ let $n=N$ and $x=0$ then $|n^2 (e^{x/n} -1 - x/n) - x^2/2| = |n^2 (1-1-0) - 1/2| = |-1/2| = |1/2| \geq 1/10.$
edit: that dosent work. | 2020/12/13 | [
"https://math.stackexchange.com/questions/3947139",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/747484/"
] | Let us notice (with the aid of Taylor series) that $h\_n(x) \to \frac{x^2}2$ for any fixed $x$. So, $h\_n(x)$ converges uniformly iff $\sup\_{x} |h\_n(x) - \frac{x^2}2| \to 0$, $n \to \infty$.
But if $x = n$ then $|h\_n(x) - \frac{x^2}2| = |n^2(e - 1 -1 ) - \frac{n^2}2|$ doesn't converge to $0$. Hence, $h\_n(x)$ doesn't converges uniformly. | Since$$n^2(e^{x/n}-1-x/n)=x^2/2+x^3/(6n)+o(x^3/n),$$the error term $\sim x^3/(6n)$ exceeds $\epsilon$ for $x\gtrsim\sqrt[3]{6n\epsilon}$. |
1,186,062 | I want to learn it but I have **no** idea where to start. Everything out there suggests reading the `libpurple` source but I don't think I understand enough `c` to really get a grasp of it. | 2009/07/27 | [
"https://Stackoverflow.com/questions/1186062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/143596/"
] | There isn't much about it yet... the [intro](http://brunoabinader.blogspot.com/2009/04/introducing-python-purple.html), the [howto](http://developer.pidgin.im/wiki/PythonHowTo), and the [sources](https://git.maemo.org/projects/python-purple/?p=python-purple;a=tree) (here browsing them online but of course you can git clone them) are about it. In particular, the tiny example client you can get from [here](https://git.maemo.org/projects/python-purple/?p=python-purple;a=blob_plain;f=nullclient.py;hb=HEAD) does have some miniscule example of use of purple's facilities (definitely not enough, but maybe it can get you started with the help of some 'dir', 'help' and the like...?) | Not sure how much help this will be but based on information from [here](http://developer.pidgin.im/wiki/PythonHowTo), it seems like you just install python-purple and import and call the functions as normal Python functions. |
1,186,062 | I want to learn it but I have **no** idea where to start. Everything out there suggests reading the `libpurple` source but I don't think I understand enough `c` to really get a grasp of it. | 2009/07/27 | [
"https://Stackoverflow.com/questions/1186062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/143596/"
] | Not sure how much help this will be but based on information from [here](http://developer.pidgin.im/wiki/PythonHowTo), it seems like you just install python-purple and import and call the functions as normal Python functions. | Can't help you with a concrete example as I decided to use something else. However, one of the first things I wanted to do after I cloned the repo was remove the ecore dependency. Here's a patch submitted to the mailing list to do just that: <https://garage.maemo.org/pipermail/python-purple-devel/2009-March/000000.html>
Incidentally, if you're looking for AIM take a look at twisted.words. For Yahoo, trying getting the source for curphoo or zinc (both are console YMSG clients). For GTalk/Jabber, I've had good experiences with xmpppy. |
1,186,062 | I want to learn it but I have **no** idea where to start. Everything out there suggests reading the `libpurple` source but I don't think I understand enough `c` to really get a grasp of it. | 2009/07/27 | [
"https://Stackoverflow.com/questions/1186062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/143596/"
] | There isn't much about it yet... the [intro](http://brunoabinader.blogspot.com/2009/04/introducing-python-purple.html), the [howto](http://developer.pidgin.im/wiki/PythonHowTo), and the [sources](https://git.maemo.org/projects/python-purple/?p=python-purple;a=tree) (here browsing them online but of course you can git clone them) are about it. In particular, the tiny example client you can get from [here](https://git.maemo.org/projects/python-purple/?p=python-purple;a=blob_plain;f=nullclient.py;hb=HEAD) does have some miniscule example of use of purple's facilities (definitely not enough, but maybe it can get you started with the help of some 'dir', 'help' and the like...?) | Can't help you with a concrete example as I decided to use something else. However, one of the first things I wanted to do after I cloned the repo was remove the ecore dependency. Here's a patch submitted to the mailing list to do just that: <https://garage.maemo.org/pipermail/python-purple-devel/2009-March/000000.html>
Incidentally, if you're looking for AIM take a look at twisted.words. For Yahoo, trying getting the source for curphoo or zinc (both are console YMSG clients). For GTalk/Jabber, I've had good experiences with xmpppy. |
15,925,938 | I want to know if there is a way to access the variables set by php using java-script, so that on one page the php variables are set. And then on the next page, i can use java-script to interrogate the PHP file in order to extract the variables, so that they can be displayed on another page?
Thanks in advance! | 2013/04/10 | [
"https://Stackoverflow.com/questions/15925938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2257003/"
] | Not sure if this works, works for my get and post variables
```
var mySessionVariable = "<?php echo $_SESSION['sessionVariable']; ?>";
``` | The only way, you would do it, is by setting cookies from PHP (or Javascript), and access these.. You can access cookies via PHP using `$_COOKIE['var']`, and via Js by, `document.cookie("var")` |
1,031,032 | Hi I had a **jquery** thickbox **modal popu**p on my application. (**iframe**)
Everything works great but I want to set the **focus** to a **specific input fiel**d.
The Iframe loads a normal aspx page so I thought I'd do a $(document).ready(..focus);
I put that script in the IFrame code
However this does not work. I believe that after the "ready" some other code is executed by the thickbox so that it loses focus again. (for instance.. I CAN set the value of the input field so the mechanism does work..
Can anybody help me set the focus ? Below is my calling code..
```
<a href="page.aspx?placeValuesBeforeTB_=savedValues&TB_iframe=true&height=550&width=700" title="Add" class="thickbox">Add</a>
``` | 2009/06/23 | [
"https://Stackoverflow.com/questions/1031032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44894/"
] | ThickBox displays the iframe's container by calling a method in the onload event of the iframe element. Since the iframe is hidden on the parent page until after the iframe's content is loaded you cannot set the focus simply using $(document).ready(..focus);. The easiest way I've found to get around this is to use setTimeout to delay the function call that sets the focus until after the iframe is displayed:
```
jQuery(document).ready(function() {
setTimeout(function(){
$('#YourElementID').focus();
},200);
});
```
Note: You might have to adjust the milliseconds value you pass to setTimeout. | From docs.jquery.com:
>
> Triggers the focus event of each matched element.
>
>
> This causes all of the functions that have been bound to the focus event to be executed.
> Note that this does not execute the focus method of the underlying elements.
>
>
>
That means, your code should more likely be:
$('#input\_field').get(0).focus ()
The difference is, that you use in my example the DOM element's own focus element, whereas in yours you use jQuery's.
**That still doesn't work**, but is perhaps a step in the right direction.
Cheers, |
30,137,791 | I am attempting to parse a regex formula in PowerShell and not having any luck. I've created the Regex and have tested it works on RegExr although when I attempt to execute a match query on it it returns no results.
The Regex is looking for any occurrence of a pattern such as below (including the TWO blank line spaces between the Price and the Address.:
```
$9,999,999
26 Fake Street, Fake Island, ABC 9999
```
my regex:`\$[\d]{1},[\d]{3},[\d]{3}\n\n\n\d{1}.*?, ([A-Z])\w+ [[\d]{4}`
My PowerShell code is as Below:
```
$Webcontent = Get-Content 'C:\Utilities\Content.txt' -Raw
[regex]::Match($WebContent,'\$[\d]{1},[\d]{3},[\d]{3}\n\n\n\d{1}.*?, ([A-Z])\w+ [[\d]{4}').Groups.Value | Out-File C:\utilities\NewContent.txt
```
Is it this query possible and also can it return ALL occurrences of this when it finds it? | 2015/05/09 | [
"https://Stackoverflow.com/questions/30137791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4635139/"
] | You can use the following regular expression:
```
(?m)s*\$\d{1},\d{3},\d{3}\s*(?:\r\n|\r|\n)+\d+.*?, ([A-Z][a-zA-Z]*)\s+\d{4}
```
See [demo](http://regexstorm.net/tester?p=(%3Fm)s*%5C%24%5Cd%7B1%7D%2C%5Cd%7B3%7D%2C%5Cd%7B3%7D%5Cs*(%3F%3A%5Cr%5Cn%7C%5Cr%7C%5Cn)%7B2%7D%5Cd%2B.*%3F%2C%20(%5BA-Z%5D%5Ba-zA-Z%5D*)%5Cs%2B%5Cd%7B4%7D&i=%249%2C999%2C999%0D%0A%0D%0A%0D%0A26%20Fake%20Street%2C%20Fake%20Island%2C%20ABC%209999)
All the matches are returned in the global `$matches` variable that is set by the `-match` operator. Please see more on this at [regular-expressions.info](http://www.regular-expressions.info/powershell.html). | To match newlines you need to match carriage return character as well as new line character in order `\r\n`. So you just need to change `\n\n\n` to `\r\n\r\n\r\n` |
362,229 | I was looking at the man page for the `rm` command on my MacBook and I noticed the the following:
>
> -W Attempt to undelete the named files. Currently, this option can only be used to recover
> files covered by whiteouts.
>
>
>
What does this mean? What is a "whiteout"? | 2017/04/30 | [
"https://unix.stackexchange.com/questions/362229",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/-1/"
] | A whiteout is a special marker file placed by some "see-through" higher-order filesystems (those which use one or more real locations as a basis for their presentation), particularly union filesystems, to indicate that a file that exists in one of the base locations has been deleted within the artificial filesystem even though it still exists elsewhere. Listing the union filesystem won't show the whited-out file.
Having a special kind of file representing these is in the BSD tradition that macOS derives from: [macOS uses `st_mode` bits 0160000 to mark them](https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man2/stat.2.html#//apple_ref/doc/man/2/stat). Using [`ls -F`, those files will be marked with a `%` sign](https://unix.stackexchange.com/a/146804), and [`ls -W` will show that they exist](https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man1/ls.1.html) (otherwise, they're generally omitted from listings). Many union systems also make normal files with a special name to represent whiteouts on systems that don't support those files.
I'm not sure that macOS exposes these itself in any way, but other systems from its BSD heritage do and it's possible that external filesystem drivers could use them. | A "whiteout" is a feature of some union filesystem.
If you have a file hierarchy that is overlain by a union mount, and a file exists in both layers of the resulting visible file hierarchy, a "whiteout" may be used to remove the file from the top layer while preserving it in the lower layer (like using Tipp-ex).
The `rm` utility is able to remove the whiteout and make the file appear again (since it was never deleted from the lower file system). |
69,295,963 | I am trying to color the bar plots of the negative values differently. Any pointer to accomplish this is much appreciated. Thanks.
```
import matplotlib.pyplot as plt
import numpy as np
city=['a','b','c','d']
pos = np.arange(len(city))
Effort =[4, 3, -1.5, -3.5]
plt.barh(pos,Effort,color='blue',edgecolor='black')
plt.yticks(pos, city)
plt.xlabel('DV', fontsize=16)
plt.ylabel('Groups', fontsize=16)
plt.title('ABCDEF',fontsize=20)
plt.show()
```
[ABCDEF matplotlib graph](https://i.stack.imgur.com/QkTju.png) | 2021/09/23 | [
"https://Stackoverflow.com/questions/69295963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13494561/"
] | This will colour the positive bars as green and the negative as red.
```py
import matplotlib.pyplot as plt
import numpy as np
city=['a','b','c','d']
pos = np.arange(len(city))
Effort =[4, 3, -1.5, -3.5]
colors = ['g' if e >= 0 else 'r' for e in Effort]
plt.barh(pos,Effort,color=colors,edgecolor='black')
plt.yticks(pos, city)
plt.xlabel('DV', fontsize=16)
plt.ylabel('Groups', fontsize=16)
plt.title('ABCDEF',fontsize=20)
plt.show()
```
[](https://i.stack.imgur.com/BBAwH.png)
If Effort was a numpy array we could use np.where to get the colours rather than a list comprehension.
```py
Effort = np.array([4, 3, -1.5, -3.5])
colors = np.where(Effort >= 0, 'g', 'r')
``` | Just color a second plot differently:
```py
city = ['a', 'b', 'c', 'd']
pos = np.arange(len(city))
Effort = np.array([4, 3, -1.5, -3.5])
plt.barh(pos[Effort >= 0], Effort[Effort >= 0], color='blue', edgecolor='black') # positive values in blue
plt.barh(pos[Effort < 0], Effort[Effort < 0], color='red', edgecolor='black') # negative values in red
plt.yticks(pos, city)
plt.xlabel('DV', fontsize=16)
plt.ylabel('Groups', fontsize=16)
plt.title('ABCDEF', fontsize=20)
plt.show()
```
This results in:
[](https://i.stack.imgur.com/9qJTV.png) |
6,778,734 | I am trying to use the jQuery-based Wijmo WijMenu control with jqGrid in order to create a dynamic grid toolbar.

Getting the menu to appear works fine. However, my menuitem1 has a submenu, and this submenu falls behind the jqGrid when I hover over 'menuitem1'.
I've tried setting the z-Index on the menu and the individual menu items, but with no luck. This behavior happens on IE9, Chrome, FF and Safari. It does work when I turn compatibility mode on with IE9, which makes me think it may have something to do with the z-index...but I'm not sure. I feel like I'm missing something obvious.
I created a [jsFiddle](http://jsfiddle.net/dhoerster/pKk3P/6/) to demonstrate my issue.
Can anyone help me get the submenu to fall in front of the jqGrid?
Thank you in advance for any help/advice. | 2011/07/21 | [
"https://Stackoverflow.com/questions/6778734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/237808/"
] | It's not a z-index issue. The .ui-jqgrid .ui-userdata has overflow:hidden on it. Try making it overflow: visible.
Although I'm not sure if it will cause problems on the grid when doing this. | Change your CSS from
```
.ui-jqgrid .ui-userdata {
border-left: 0px none;
border-right: 0px none;
height: 21px;
overflow: hidden;
}
.ui-jqgrid .ui-userdata {
border-left: 0px none;
border-right: 0px none;
height: 21px;
}
```
Removing the `overflow:hidden` It was hiding your menu. |
67,570,098 | I need a hidden delete button to appear and work when a input is focused using markup and CSS in Svelte.
I got it all working in browsers for OS X and Raspberry Pi OS (Chrome, Chromium, Safari and Firefox). [Click here to see it](https://2-dos.netlify.app/).
The problem is that the button appears but is not working in any of my iOS browsers (Safari or Firefox). Nothing is happening when the delete button is clicked.
I've tried following:
* [focus-within works on Android browser but not iOS](https://stackoverflow.com/questions/66477748/focus-within-works-on-android-browser-but-not-ios)
* [How to make a button appear only when input is focused](https://stackoverflow.com/questions/57930783/how-to-make-a-button-appear-only-when-input-is-focused)
Here is the markup...
```
<form>
{#if $todos}
{#each $todos as { data }, i}
<div id="todo">
<button on:click|preventDefault={remove(i + 1)}></button>
<input
bind:value={data.name}
on:change={update(i + 1)}
size={data.name.length}
maxlength="35"
/>
</div>
{/each}
{/if}
</form>
```
...and here is the styling...
```
<style>
form,
div {
display: flex;
flex-wrap: wrap;
}
input {
border-style: none;
font-size: 2vh;
}
input:focus {
border-style: solid;
}
button {
visibility: hidden;
font-size: 2vh;
}
#todo:focus-within button {
visibility: visible;
}
</style>
```
```css
form,
div {
display: flex;
}
form {
width: 100vw;
}
input {
border-style: none;
}
input:focus {
border-style: solid;
}
button {
visibility: hidden;
}
#todo1:focus-within button {
visibility: visible;
}
#todo2:focus-within button {
visibility: visible;
}
#todo3:focus-within button {
visibility: visible;
}
```
```html
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Svelte + Node.js API</title>
</head>
<body>
<h1>To Do</h1>
<form>
<div id="todo1">
<button onclick="alert('Input deleted')"></button>
<input value="Try it out">
</div>
<div id="todo2">
<button onclick="alert('Input deleted')"></button>
<input value="Fix the bug">
</div>
<div id="todo3">
<button onclick="alert('Input deleted')"></button>
<input value="Celebrate">
</div>
</form>
</body>
</html>
``` | 2021/05/17 | [
"https://Stackoverflow.com/questions/67570098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14248700/"
] | With a little bit of debugging, it turns out, that by attempting to click on a button, you actually click on a `<div>` element itself:
```js
function setLogs(element) {
element.addEventListener("focus", () => {
console.log("focus", element);
});
element.addEventListener("blur", () => {
console.log("blur", element);
});
for (const child of element.children)
setLogs(child);
}
setLogs(document.body);
```
```css
button {
visibility: hidden;
}
#todo:focus-within button {
visibility: visible;
}
```
```html
<div class="content">
<h1>To Do</h1>
<form onsubmit="return false">
<div id="todo">
<button onclick="console.log('Input deleted')"></button>
<input value="Try it out">
</div>
</form>
</div>
```
The reason for that is that focusing on one element after another one is a two-part event: first, you remove focus from the first element, then you set focus to the second one. By clicking on the area with the button, you remove the focus from the `<input>` element. Removed focus leads to `:focus-within` stop being applicable, and the button becomes hidden again. So, when the second part of the clicking event happens, there's no button there anymore, and the click is applied to the next element in the stack – the `<div>` element itself. | Here is a solution using "opacity" instead of "visibility" which seems to work also with iOS browsers.
```css
form,
div {
display: flex;
}
form {
width: 100vw;
}
input {
border-style: none;
}
input:focus {
border-style: solid;
}
button {
opacity: 0;
}
#todo1:focus-within button {
opacity: 1;
}
#todo2:focus-within button {
opacity: 1;
}
#todo3:focus-within button {
opacity: 1;
}
```
```html
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Svelte + Node.js API</title>
</head>
<body>
<h1>To Do</h1>
<form>
<div id="todo1">
<button onclick="alert('Input deleted')"></button>
<input value="Try it out">
</div>
<div id="todo2">
<button onclick="alert('Input deleted')"></button>
<input value="Fix the bug">
</div>
<div id="todo3">
<button onclick="alert('Input deleted')"></button>
<input value="Celebrate">
</div>
</form>
</body>
</html>
``` |
67,570,098 | I need a hidden delete button to appear and work when a input is focused using markup and CSS in Svelte.
I got it all working in browsers for OS X and Raspberry Pi OS (Chrome, Chromium, Safari and Firefox). [Click here to see it](https://2-dos.netlify.app/).
The problem is that the button appears but is not working in any of my iOS browsers (Safari or Firefox). Nothing is happening when the delete button is clicked.
I've tried following:
* [focus-within works on Android browser but not iOS](https://stackoverflow.com/questions/66477748/focus-within-works-on-android-browser-but-not-ios)
* [How to make a button appear only when input is focused](https://stackoverflow.com/questions/57930783/how-to-make-a-button-appear-only-when-input-is-focused)
Here is the markup...
```
<form>
{#if $todos}
{#each $todos as { data }, i}
<div id="todo">
<button on:click|preventDefault={remove(i + 1)}></button>
<input
bind:value={data.name}
on:change={update(i + 1)}
size={data.name.length}
maxlength="35"
/>
</div>
{/each}
{/if}
</form>
```
...and here is the styling...
```
<style>
form,
div {
display: flex;
flex-wrap: wrap;
}
input {
border-style: none;
font-size: 2vh;
}
input:focus {
border-style: solid;
}
button {
visibility: hidden;
font-size: 2vh;
}
#todo:focus-within button {
visibility: visible;
}
</style>
```
```css
form,
div {
display: flex;
}
form {
width: 100vw;
}
input {
border-style: none;
}
input:focus {
border-style: solid;
}
button {
visibility: hidden;
}
#todo1:focus-within button {
visibility: visible;
}
#todo2:focus-within button {
visibility: visible;
}
#todo3:focus-within button {
visibility: visible;
}
```
```html
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Svelte + Node.js API</title>
</head>
<body>
<h1>To Do</h1>
<form>
<div id="todo1">
<button onclick="alert('Input deleted')"></button>
<input value="Try it out">
</div>
<div id="todo2">
<button onclick="alert('Input deleted')"></button>
<input value="Fix the bug">
</div>
<div id="todo3">
<button onclick="alert('Input deleted')"></button>
<input value="Celebrate">
</div>
</form>
</body>
</html>
``` | 2021/05/17 | [
"https://Stackoverflow.com/questions/67570098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14248700/"
] | With a little bit of debugging, it turns out, that by attempting to click on a button, you actually click on a `<div>` element itself:
```js
function setLogs(element) {
element.addEventListener("focus", () => {
console.log("focus", element);
});
element.addEventListener("blur", () => {
console.log("blur", element);
});
for (const child of element.children)
setLogs(child);
}
setLogs(document.body);
```
```css
button {
visibility: hidden;
}
#todo:focus-within button {
visibility: visible;
}
```
```html
<div class="content">
<h1>To Do</h1>
<form onsubmit="return false">
<div id="todo">
<button onclick="console.log('Input deleted')"></button>
<input value="Try it out">
</div>
</form>
</div>
```
The reason for that is that focusing on one element after another one is a two-part event: first, you remove focus from the first element, then you set focus to the second one. By clicking on the area with the button, you remove the focus from the `<input>` element. Removed focus leads to `:focus-within` stop being applicable, and the button becomes hidden again. So, when the second part of the clicking event happens, there's no button there anymore, and the click is applied to the next element in the stack – the `<div>` element itself. | Listen to the `mousedown` event instead of `click` and you'll be able to handle the event before iOS changes focus.
It's more standard practice to trigger an event on `click` but in this case it seems to be the only workaround to iOS's behaviour. |
26,487,750 | In Android 4.x, it was enough to put an APK-file into /system/priv-app, and the package-manager recognized that new file and (un-)installed the corresponding application or service.
Since Android L, it seems to be not enough to just put the file into that directory - a reboot of the system is required to force Android to recognize that change.
Has anyone an idea how to circumvent this? Maybe with any `setprop ctl.restart xxx` or by killing a dedicated service?
EDIT:
Here are some logs from logcat:
### 1. Move APK from /system to /system/priv-app (=installation)
```
su
mount -o remount rw /system
cd /system/priv-app
mv ../AARSCService.apk . // move from /system to /system/priv-app
W/mv ( 3268): type=1400 audit(0.0:53): avc: denied { rename } for name="AARSCService.apk" dev="mmcblk0p22" ino=23041 scontext=u:r:init:s0 tcontext=u:object_r:system_file:s0 tclass=file
```
(but file HAS been moved as the current root-implementation for Nexus 7 Android Android L P2 disables SELinux for the root-commands!)
-> APK NOT loaded and not listed in app-list -> NOT as expected, APK is going to be automatically installed once put into priv-app folder on Android 4.4.
### 2. Reboot device, having APK inside /system/priv-app
```
reboot
I/PackageManager( 567): /system/priv-app/AARSCService.apk changed; collecting certs
```
-> APK IS loaded and listed in app-list -> as expected
### 3. Move APK from /system/priv-app to /system (=deinstallation)
```
su
mount -o remount rw /system
cd /system/priv-app
mv AARSCService.apk .. // move from /system/priv-app to /system
W/mv ( 3189): type=1400 audit(0.0:31): avc: denied { rename } for name="AARSCService.apk" dev="mmcblk0p22" ino=23041 scontext=u:r:init:s0 tcontext=u:object_r:system_file:s0 tclass=file
```
(but file HAS been moved as the current root-implementation for Nexus 7 Android Android L P2 disables SELinux for the root-commands!)
-> APK still loaded and listed inside app-list, service inside app can still be bound from another app -> NOT as expected, APK is going to be automatically uninstalled once removed from priv-app folder on Android 4.4.
### 4. Reboot device, having APK NOT inside /system/priv-app
```
reboot
W/PackageManager( 570): System package eu.airaudio.aarscservice no longer exists; wiping its data
```
-> APK is no more loaded and no more listed in app-list -> as expected
EDIT 2:
There's the same behaviour on unrooted Android L (21) emulator - sure, without the SELinux-warning.
But the APK is also just (un-)installed after reboot (=kill zygote). | 2014/10/21 | [
"https://Stackoverflow.com/questions/26487750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/164036/"
] | Based on your logcat messages, looks like the `PackageManagerService` is not even seeing the folder/file changes.
Here is one way to circumvent/trigger a rescan, simulate a a "boot completed" event with broadcast action:
```
adb shell am broadcast -a android.intent.action.BOOT_COMPLETED
```
This should trigger a rescan by the `PackageManagerService` | Here you go:
```
adb shell cmd package compile -f -r first-boot com.yourpackage.name
``` |
26,487,750 | In Android 4.x, it was enough to put an APK-file into /system/priv-app, and the package-manager recognized that new file and (un-)installed the corresponding application or service.
Since Android L, it seems to be not enough to just put the file into that directory - a reboot of the system is required to force Android to recognize that change.
Has anyone an idea how to circumvent this? Maybe with any `setprop ctl.restart xxx` or by killing a dedicated service?
EDIT:
Here are some logs from logcat:
### 1. Move APK from /system to /system/priv-app (=installation)
```
su
mount -o remount rw /system
cd /system/priv-app
mv ../AARSCService.apk . // move from /system to /system/priv-app
W/mv ( 3268): type=1400 audit(0.0:53): avc: denied { rename } for name="AARSCService.apk" dev="mmcblk0p22" ino=23041 scontext=u:r:init:s0 tcontext=u:object_r:system_file:s0 tclass=file
```
(but file HAS been moved as the current root-implementation for Nexus 7 Android Android L P2 disables SELinux for the root-commands!)
-> APK NOT loaded and not listed in app-list -> NOT as expected, APK is going to be automatically installed once put into priv-app folder on Android 4.4.
### 2. Reboot device, having APK inside /system/priv-app
```
reboot
I/PackageManager( 567): /system/priv-app/AARSCService.apk changed; collecting certs
```
-> APK IS loaded and listed in app-list -> as expected
### 3. Move APK from /system/priv-app to /system (=deinstallation)
```
su
mount -o remount rw /system
cd /system/priv-app
mv AARSCService.apk .. // move from /system/priv-app to /system
W/mv ( 3189): type=1400 audit(0.0:31): avc: denied { rename } for name="AARSCService.apk" dev="mmcblk0p22" ino=23041 scontext=u:r:init:s0 tcontext=u:object_r:system_file:s0 tclass=file
```
(but file HAS been moved as the current root-implementation for Nexus 7 Android Android L P2 disables SELinux for the root-commands!)
-> APK still loaded and listed inside app-list, service inside app can still be bound from another app -> NOT as expected, APK is going to be automatically uninstalled once removed from priv-app folder on Android 4.4.
### 4. Reboot device, having APK NOT inside /system/priv-app
```
reboot
W/PackageManager( 570): System package eu.airaudio.aarscservice no longer exists; wiping its data
```
-> APK is no more loaded and no more listed in app-list -> as expected
EDIT 2:
There's the same behaviour on unrooted Android L (21) emulator - sure, without the SELinux-warning.
But the APK is also just (un-)installed after reboot (=kill zygote). | 2014/10/21 | [
"https://Stackoverflow.com/questions/26487750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/164036/"
] | Comparing the source code of `PackageManagerService` between KitKat and Lollipop you can see significant changes, and some that are obviously related to this change.
[`PackageManagerService.java` on Lollipop](https://github.com/android/platform_frameworks_base/blob/96b46ebaeec6cc3919513599cce79b4134022cf4/services/core/java/com/android/server/pm/PackageManagerService.java)
[`PackageManagerService.java` on KitKat](https://github.com/android/platform_frameworks_base/blob/kitkat-mr2.2-release/services/java/com/android/server/pm/PackageManagerService.java)
The most significant change to the question topic is the removal of all references to `AppDirObserver` (a nested class of `PackageManagerService`) that was initialized to monitor all directories (the attached image shows a comparison of the relevant code where it was used. Right side shows KitKat code and left side shows Lollipop)

Still haven't found a solution for this but might help someone figure it out. | I had the exact same problem.
Turns out when I coped the package back to priv-app it was copied with different permission
Permissions of all packages in priv-app (and app) :
```
rwx-r-x-r-x
```
Permission of the package I copied back :
```
rwx--------
```
A simple `chmod -R a+rw <path/to/package>` solved the problem
EDIT:
Make sure your /system/ is not readonly by issuing
`mount -o remount,rw /system/` |
26,487,750 | In Android 4.x, it was enough to put an APK-file into /system/priv-app, and the package-manager recognized that new file and (un-)installed the corresponding application or service.
Since Android L, it seems to be not enough to just put the file into that directory - a reboot of the system is required to force Android to recognize that change.
Has anyone an idea how to circumvent this? Maybe with any `setprop ctl.restart xxx` or by killing a dedicated service?
EDIT:
Here are some logs from logcat:
### 1. Move APK from /system to /system/priv-app (=installation)
```
su
mount -o remount rw /system
cd /system/priv-app
mv ../AARSCService.apk . // move from /system to /system/priv-app
W/mv ( 3268): type=1400 audit(0.0:53): avc: denied { rename } for name="AARSCService.apk" dev="mmcblk0p22" ino=23041 scontext=u:r:init:s0 tcontext=u:object_r:system_file:s0 tclass=file
```
(but file HAS been moved as the current root-implementation for Nexus 7 Android Android L P2 disables SELinux for the root-commands!)
-> APK NOT loaded and not listed in app-list -> NOT as expected, APK is going to be automatically installed once put into priv-app folder on Android 4.4.
### 2. Reboot device, having APK inside /system/priv-app
```
reboot
I/PackageManager( 567): /system/priv-app/AARSCService.apk changed; collecting certs
```
-> APK IS loaded and listed in app-list -> as expected
### 3. Move APK from /system/priv-app to /system (=deinstallation)
```
su
mount -o remount rw /system
cd /system/priv-app
mv AARSCService.apk .. // move from /system/priv-app to /system
W/mv ( 3189): type=1400 audit(0.0:31): avc: denied { rename } for name="AARSCService.apk" dev="mmcblk0p22" ino=23041 scontext=u:r:init:s0 tcontext=u:object_r:system_file:s0 tclass=file
```
(but file HAS been moved as the current root-implementation for Nexus 7 Android Android L P2 disables SELinux for the root-commands!)
-> APK still loaded and listed inside app-list, service inside app can still be bound from another app -> NOT as expected, APK is going to be automatically uninstalled once removed from priv-app folder on Android 4.4.
### 4. Reboot device, having APK NOT inside /system/priv-app
```
reboot
W/PackageManager( 570): System package eu.airaudio.aarscservice no longer exists; wiping its data
```
-> APK is no more loaded and no more listed in app-list -> as expected
EDIT 2:
There's the same behaviour on unrooted Android L (21) emulator - sure, without the SELinux-warning.
But the APK is also just (un-)installed after reboot (=kill zygote). | 2014/10/21 | [
"https://Stackoverflow.com/questions/26487750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/164036/"
] | pms will scan `/system/app(priv-app)` at start. so just kill process `systemserver` :)
it work at my lollipop emulator. just take a little while to showing "upgrade android, opt app..." | I had the exact same problem.
Turns out when I coped the package back to priv-app it was copied with different permission
Permissions of all packages in priv-app (and app) :
```
rwx-r-x-r-x
```
Permission of the package I copied back :
```
rwx--------
```
A simple `chmod -R a+rw <path/to/package>` solved the problem
EDIT:
Make sure your /system/ is not readonly by issuing
`mount -o remount,rw /system/` |
26,487,750 | In Android 4.x, it was enough to put an APK-file into /system/priv-app, and the package-manager recognized that new file and (un-)installed the corresponding application or service.
Since Android L, it seems to be not enough to just put the file into that directory - a reboot of the system is required to force Android to recognize that change.
Has anyone an idea how to circumvent this? Maybe with any `setprop ctl.restart xxx` or by killing a dedicated service?
EDIT:
Here are some logs from logcat:
### 1. Move APK from /system to /system/priv-app (=installation)
```
su
mount -o remount rw /system
cd /system/priv-app
mv ../AARSCService.apk . // move from /system to /system/priv-app
W/mv ( 3268): type=1400 audit(0.0:53): avc: denied { rename } for name="AARSCService.apk" dev="mmcblk0p22" ino=23041 scontext=u:r:init:s0 tcontext=u:object_r:system_file:s0 tclass=file
```
(but file HAS been moved as the current root-implementation for Nexus 7 Android Android L P2 disables SELinux for the root-commands!)
-> APK NOT loaded and not listed in app-list -> NOT as expected, APK is going to be automatically installed once put into priv-app folder on Android 4.4.
### 2. Reboot device, having APK inside /system/priv-app
```
reboot
I/PackageManager( 567): /system/priv-app/AARSCService.apk changed; collecting certs
```
-> APK IS loaded and listed in app-list -> as expected
### 3. Move APK from /system/priv-app to /system (=deinstallation)
```
su
mount -o remount rw /system
cd /system/priv-app
mv AARSCService.apk .. // move from /system/priv-app to /system
W/mv ( 3189): type=1400 audit(0.0:31): avc: denied { rename } for name="AARSCService.apk" dev="mmcblk0p22" ino=23041 scontext=u:r:init:s0 tcontext=u:object_r:system_file:s0 tclass=file
```
(but file HAS been moved as the current root-implementation for Nexus 7 Android Android L P2 disables SELinux for the root-commands!)
-> APK still loaded and listed inside app-list, service inside app can still be bound from another app -> NOT as expected, APK is going to be automatically uninstalled once removed from priv-app folder on Android 4.4.
### 4. Reboot device, having APK NOT inside /system/priv-app
```
reboot
W/PackageManager( 570): System package eu.airaudio.aarscservice no longer exists; wiping its data
```
-> APK is no more loaded and no more listed in app-list -> as expected
EDIT 2:
There's the same behaviour on unrooted Android L (21) emulator - sure, without the SELinux-warning.
But the APK is also just (un-)installed after reboot (=kill zygote). | 2014/10/21 | [
"https://Stackoverflow.com/questions/26487750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/164036/"
] | pms will scan `/system/app(priv-app)` at start. so just kill process `systemserver` :)
it work at my lollipop emulator. just take a little while to showing "upgrade android, opt app..." | Here you go:
```
adb shell cmd package compile -f -r first-boot com.yourpackage.name
``` |
26,487,750 | In Android 4.x, it was enough to put an APK-file into /system/priv-app, and the package-manager recognized that new file and (un-)installed the corresponding application or service.
Since Android L, it seems to be not enough to just put the file into that directory - a reboot of the system is required to force Android to recognize that change.
Has anyone an idea how to circumvent this? Maybe with any `setprop ctl.restart xxx` or by killing a dedicated service?
EDIT:
Here are some logs from logcat:
### 1. Move APK from /system to /system/priv-app (=installation)
```
su
mount -o remount rw /system
cd /system/priv-app
mv ../AARSCService.apk . // move from /system to /system/priv-app
W/mv ( 3268): type=1400 audit(0.0:53): avc: denied { rename } for name="AARSCService.apk" dev="mmcblk0p22" ino=23041 scontext=u:r:init:s0 tcontext=u:object_r:system_file:s0 tclass=file
```
(but file HAS been moved as the current root-implementation for Nexus 7 Android Android L P2 disables SELinux for the root-commands!)
-> APK NOT loaded and not listed in app-list -> NOT as expected, APK is going to be automatically installed once put into priv-app folder on Android 4.4.
### 2. Reboot device, having APK inside /system/priv-app
```
reboot
I/PackageManager( 567): /system/priv-app/AARSCService.apk changed; collecting certs
```
-> APK IS loaded and listed in app-list -> as expected
### 3. Move APK from /system/priv-app to /system (=deinstallation)
```
su
mount -o remount rw /system
cd /system/priv-app
mv AARSCService.apk .. // move from /system/priv-app to /system
W/mv ( 3189): type=1400 audit(0.0:31): avc: denied { rename } for name="AARSCService.apk" dev="mmcblk0p22" ino=23041 scontext=u:r:init:s0 tcontext=u:object_r:system_file:s0 tclass=file
```
(but file HAS been moved as the current root-implementation for Nexus 7 Android Android L P2 disables SELinux for the root-commands!)
-> APK still loaded and listed inside app-list, service inside app can still be bound from another app -> NOT as expected, APK is going to be automatically uninstalled once removed from priv-app folder on Android 4.4.
### 4. Reboot device, having APK NOT inside /system/priv-app
```
reboot
W/PackageManager( 570): System package eu.airaudio.aarscservice no longer exists; wiping its data
```
-> APK is no more loaded and no more listed in app-list -> as expected
EDIT 2:
There's the same behaviour on unrooted Android L (21) emulator - sure, without the SELinux-warning.
But the APK is also just (un-)installed after reboot (=kill zygote). | 2014/10/21 | [
"https://Stackoverflow.com/questions/26487750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/164036/"
] | pms will scan `/system/app(priv-app)` at start. so just kill process `systemserver` :)
it work at my lollipop emulator. just take a little while to showing "upgrade android, opt app..." | 1. Push apk to /system/priv-app/
2. Run command: adb shell > su > am restart (using this command you don't loose adb connection)
3. Wait for system boots - install script can wait for clean output of command: "adb shell dumpsys phone"
Snippet:
```
def am_restart(self):
"""Restarts am waits for complete Android boot."""
self._log.info('Restarting application manager!')
ret, out, err = self.shell('am restart', require_root=True)
if ret != 0:
self.log_failure('am restart', ret, out, err)
return False
on_main_screen = False
while not on_main_screen:
sleep(2)
ret, out, err = self.shell('dumpsys phone')
if ret != 0:
self.log_failure('dumpsys phone', ret, out, err)
return False
if not (out or err):
on_main_screen = True
self._log.info('Application manager successfully restarted!')
return True
``` |
26,487,750 | In Android 4.x, it was enough to put an APK-file into /system/priv-app, and the package-manager recognized that new file and (un-)installed the corresponding application or service.
Since Android L, it seems to be not enough to just put the file into that directory - a reboot of the system is required to force Android to recognize that change.
Has anyone an idea how to circumvent this? Maybe with any `setprop ctl.restart xxx` or by killing a dedicated service?
EDIT:
Here are some logs from logcat:
### 1. Move APK from /system to /system/priv-app (=installation)
```
su
mount -o remount rw /system
cd /system/priv-app
mv ../AARSCService.apk . // move from /system to /system/priv-app
W/mv ( 3268): type=1400 audit(0.0:53): avc: denied { rename } for name="AARSCService.apk" dev="mmcblk0p22" ino=23041 scontext=u:r:init:s0 tcontext=u:object_r:system_file:s0 tclass=file
```
(but file HAS been moved as the current root-implementation for Nexus 7 Android Android L P2 disables SELinux for the root-commands!)
-> APK NOT loaded and not listed in app-list -> NOT as expected, APK is going to be automatically installed once put into priv-app folder on Android 4.4.
### 2. Reboot device, having APK inside /system/priv-app
```
reboot
I/PackageManager( 567): /system/priv-app/AARSCService.apk changed; collecting certs
```
-> APK IS loaded and listed in app-list -> as expected
### 3. Move APK from /system/priv-app to /system (=deinstallation)
```
su
mount -o remount rw /system
cd /system/priv-app
mv AARSCService.apk .. // move from /system/priv-app to /system
W/mv ( 3189): type=1400 audit(0.0:31): avc: denied { rename } for name="AARSCService.apk" dev="mmcblk0p22" ino=23041 scontext=u:r:init:s0 tcontext=u:object_r:system_file:s0 tclass=file
```
(but file HAS been moved as the current root-implementation for Nexus 7 Android Android L P2 disables SELinux for the root-commands!)
-> APK still loaded and listed inside app-list, service inside app can still be bound from another app -> NOT as expected, APK is going to be automatically uninstalled once removed from priv-app folder on Android 4.4.
### 4. Reboot device, having APK NOT inside /system/priv-app
```
reboot
W/PackageManager( 570): System package eu.airaudio.aarscservice no longer exists; wiping its data
```
-> APK is no more loaded and no more listed in app-list -> as expected
EDIT 2:
There's the same behaviour on unrooted Android L (21) emulator - sure, without the SELinux-warning.
But the APK is also just (un-)installed after reboot (=kill zygote). | 2014/10/21 | [
"https://Stackoverflow.com/questions/26487750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/164036/"
] | Comparing the source code of `PackageManagerService` between KitKat and Lollipop you can see significant changes, and some that are obviously related to this change.
[`PackageManagerService.java` on Lollipop](https://github.com/android/platform_frameworks_base/blob/96b46ebaeec6cc3919513599cce79b4134022cf4/services/core/java/com/android/server/pm/PackageManagerService.java)
[`PackageManagerService.java` on KitKat](https://github.com/android/platform_frameworks_base/blob/kitkat-mr2.2-release/services/java/com/android/server/pm/PackageManagerService.java)
The most significant change to the question topic is the removal of all references to `AppDirObserver` (a nested class of `PackageManagerService`) that was initialized to monitor all directories (the attached image shows a comparison of the relevant code where it was used. Right side shows KitKat code and left side shows Lollipop)

Still haven't found a solution for this but might help someone figure it out. | Here you go:
```
adb shell cmd package compile -f -r first-boot com.yourpackage.name
``` |
26,487,750 | In Android 4.x, it was enough to put an APK-file into /system/priv-app, and the package-manager recognized that new file and (un-)installed the corresponding application or service.
Since Android L, it seems to be not enough to just put the file into that directory - a reboot of the system is required to force Android to recognize that change.
Has anyone an idea how to circumvent this? Maybe with any `setprop ctl.restart xxx` or by killing a dedicated service?
EDIT:
Here are some logs from logcat:
### 1. Move APK from /system to /system/priv-app (=installation)
```
su
mount -o remount rw /system
cd /system/priv-app
mv ../AARSCService.apk . // move from /system to /system/priv-app
W/mv ( 3268): type=1400 audit(0.0:53): avc: denied { rename } for name="AARSCService.apk" dev="mmcblk0p22" ino=23041 scontext=u:r:init:s0 tcontext=u:object_r:system_file:s0 tclass=file
```
(but file HAS been moved as the current root-implementation for Nexus 7 Android Android L P2 disables SELinux for the root-commands!)
-> APK NOT loaded and not listed in app-list -> NOT as expected, APK is going to be automatically installed once put into priv-app folder on Android 4.4.
### 2. Reboot device, having APK inside /system/priv-app
```
reboot
I/PackageManager( 567): /system/priv-app/AARSCService.apk changed; collecting certs
```
-> APK IS loaded and listed in app-list -> as expected
### 3. Move APK from /system/priv-app to /system (=deinstallation)
```
su
mount -o remount rw /system
cd /system/priv-app
mv AARSCService.apk .. // move from /system/priv-app to /system
W/mv ( 3189): type=1400 audit(0.0:31): avc: denied { rename } for name="AARSCService.apk" dev="mmcblk0p22" ino=23041 scontext=u:r:init:s0 tcontext=u:object_r:system_file:s0 tclass=file
```
(but file HAS been moved as the current root-implementation for Nexus 7 Android Android L P2 disables SELinux for the root-commands!)
-> APK still loaded and listed inside app-list, service inside app can still be bound from another app -> NOT as expected, APK is going to be automatically uninstalled once removed from priv-app folder on Android 4.4.
### 4. Reboot device, having APK NOT inside /system/priv-app
```
reboot
W/PackageManager( 570): System package eu.airaudio.aarscservice no longer exists; wiping its data
```
-> APK is no more loaded and no more listed in app-list -> as expected
EDIT 2:
There's the same behaviour on unrooted Android L (21) emulator - sure, without the SELinux-warning.
But the APK is also just (un-)installed after reboot (=kill zygote). | 2014/10/21 | [
"https://Stackoverflow.com/questions/26487750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/164036/"
] | Comparing the source code of `PackageManagerService` between KitKat and Lollipop you can see significant changes, and some that are obviously related to this change.
[`PackageManagerService.java` on Lollipop](https://github.com/android/platform_frameworks_base/blob/96b46ebaeec6cc3919513599cce79b4134022cf4/services/core/java/com/android/server/pm/PackageManagerService.java)
[`PackageManagerService.java` on KitKat](https://github.com/android/platform_frameworks_base/blob/kitkat-mr2.2-release/services/java/com/android/server/pm/PackageManagerService.java)
The most significant change to the question topic is the removal of all references to `AppDirObserver` (a nested class of `PackageManagerService`) that was initialized to monitor all directories (the attached image shows a comparison of the relevant code where it was used. Right side shows KitKat code and left side shows Lollipop)

Still haven't found a solution for this but might help someone figure it out. | 1. Push apk to /system/priv-app/
2. Run command: adb shell > su > am restart (using this command you don't loose adb connection)
3. Wait for system boots - install script can wait for clean output of command: "adb shell dumpsys phone"
Snippet:
```
def am_restart(self):
"""Restarts am waits for complete Android boot."""
self._log.info('Restarting application manager!')
ret, out, err = self.shell('am restart', require_root=True)
if ret != 0:
self.log_failure('am restart', ret, out, err)
return False
on_main_screen = False
while not on_main_screen:
sleep(2)
ret, out, err = self.shell('dumpsys phone')
if ret != 0:
self.log_failure('dumpsys phone', ret, out, err)
return False
if not (out or err):
on_main_screen = True
self._log.info('Application manager successfully restarted!')
return True
``` |
26,487,750 | In Android 4.x, it was enough to put an APK-file into /system/priv-app, and the package-manager recognized that new file and (un-)installed the corresponding application or service.
Since Android L, it seems to be not enough to just put the file into that directory - a reboot of the system is required to force Android to recognize that change.
Has anyone an idea how to circumvent this? Maybe with any `setprop ctl.restart xxx` or by killing a dedicated service?
EDIT:
Here are some logs from logcat:
### 1. Move APK from /system to /system/priv-app (=installation)
```
su
mount -o remount rw /system
cd /system/priv-app
mv ../AARSCService.apk . // move from /system to /system/priv-app
W/mv ( 3268): type=1400 audit(0.0:53): avc: denied { rename } for name="AARSCService.apk" dev="mmcblk0p22" ino=23041 scontext=u:r:init:s0 tcontext=u:object_r:system_file:s0 tclass=file
```
(but file HAS been moved as the current root-implementation for Nexus 7 Android Android L P2 disables SELinux for the root-commands!)
-> APK NOT loaded and not listed in app-list -> NOT as expected, APK is going to be automatically installed once put into priv-app folder on Android 4.4.
### 2. Reboot device, having APK inside /system/priv-app
```
reboot
I/PackageManager( 567): /system/priv-app/AARSCService.apk changed; collecting certs
```
-> APK IS loaded and listed in app-list -> as expected
### 3. Move APK from /system/priv-app to /system (=deinstallation)
```
su
mount -o remount rw /system
cd /system/priv-app
mv AARSCService.apk .. // move from /system/priv-app to /system
W/mv ( 3189): type=1400 audit(0.0:31): avc: denied { rename } for name="AARSCService.apk" dev="mmcblk0p22" ino=23041 scontext=u:r:init:s0 tcontext=u:object_r:system_file:s0 tclass=file
```
(but file HAS been moved as the current root-implementation for Nexus 7 Android Android L P2 disables SELinux for the root-commands!)
-> APK still loaded and listed inside app-list, service inside app can still be bound from another app -> NOT as expected, APK is going to be automatically uninstalled once removed from priv-app folder on Android 4.4.
### 4. Reboot device, having APK NOT inside /system/priv-app
```
reboot
W/PackageManager( 570): System package eu.airaudio.aarscservice no longer exists; wiping its data
```
-> APK is no more loaded and no more listed in app-list -> as expected
EDIT 2:
There's the same behaviour on unrooted Android L (21) emulator - sure, without the SELinux-warning.
But the APK is also just (un-)installed after reboot (=kill zygote). | 2014/10/21 | [
"https://Stackoverflow.com/questions/26487750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/164036/"
] | Based on your logcat messages, looks like the `PackageManagerService` is not even seeing the folder/file changes.
Here is one way to circumvent/trigger a rescan, simulate a a "boot completed" event with broadcast action:
```
adb shell am broadcast -a android.intent.action.BOOT_COMPLETED
```
This should trigger a rescan by the `PackageManagerService` | 1. Push apk to /system/priv-app/
2. Run command: adb shell > su > am restart (using this command you don't loose adb connection)
3. Wait for system boots - install script can wait for clean output of command: "adb shell dumpsys phone"
Snippet:
```
def am_restart(self):
"""Restarts am waits for complete Android boot."""
self._log.info('Restarting application manager!')
ret, out, err = self.shell('am restart', require_root=True)
if ret != 0:
self.log_failure('am restart', ret, out, err)
return False
on_main_screen = False
while not on_main_screen:
sleep(2)
ret, out, err = self.shell('dumpsys phone')
if ret != 0:
self.log_failure('dumpsys phone', ret, out, err)
return False
if not (out or err):
on_main_screen = True
self._log.info('Application manager successfully restarted!')
return True
``` |
26,487,750 | In Android 4.x, it was enough to put an APK-file into /system/priv-app, and the package-manager recognized that new file and (un-)installed the corresponding application or service.
Since Android L, it seems to be not enough to just put the file into that directory - a reboot of the system is required to force Android to recognize that change.
Has anyone an idea how to circumvent this? Maybe with any `setprop ctl.restart xxx` or by killing a dedicated service?
EDIT:
Here are some logs from logcat:
### 1. Move APK from /system to /system/priv-app (=installation)
```
su
mount -o remount rw /system
cd /system/priv-app
mv ../AARSCService.apk . // move from /system to /system/priv-app
W/mv ( 3268): type=1400 audit(0.0:53): avc: denied { rename } for name="AARSCService.apk" dev="mmcblk0p22" ino=23041 scontext=u:r:init:s0 tcontext=u:object_r:system_file:s0 tclass=file
```
(but file HAS been moved as the current root-implementation for Nexus 7 Android Android L P2 disables SELinux for the root-commands!)
-> APK NOT loaded and not listed in app-list -> NOT as expected, APK is going to be automatically installed once put into priv-app folder on Android 4.4.
### 2. Reboot device, having APK inside /system/priv-app
```
reboot
I/PackageManager( 567): /system/priv-app/AARSCService.apk changed; collecting certs
```
-> APK IS loaded and listed in app-list -> as expected
### 3. Move APK from /system/priv-app to /system (=deinstallation)
```
su
mount -o remount rw /system
cd /system/priv-app
mv AARSCService.apk .. // move from /system/priv-app to /system
W/mv ( 3189): type=1400 audit(0.0:31): avc: denied { rename } for name="AARSCService.apk" dev="mmcblk0p22" ino=23041 scontext=u:r:init:s0 tcontext=u:object_r:system_file:s0 tclass=file
```
(but file HAS been moved as the current root-implementation for Nexus 7 Android Android L P2 disables SELinux for the root-commands!)
-> APK still loaded and listed inside app-list, service inside app can still be bound from another app -> NOT as expected, APK is going to be automatically uninstalled once removed from priv-app folder on Android 4.4.
### 4. Reboot device, having APK NOT inside /system/priv-app
```
reboot
W/PackageManager( 570): System package eu.airaudio.aarscservice no longer exists; wiping its data
```
-> APK is no more loaded and no more listed in app-list -> as expected
EDIT 2:
There's the same behaviour on unrooted Android L (21) emulator - sure, without the SELinux-warning.
But the APK is also just (un-)installed after reboot (=kill zygote). | 2014/10/21 | [
"https://Stackoverflow.com/questions/26487750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/164036/"
] | Based on your logcat messages, looks like the `PackageManagerService` is not even seeing the folder/file changes.
Here is one way to circumvent/trigger a rescan, simulate a a "boot completed" event with broadcast action:
```
adb shell am broadcast -a android.intent.action.BOOT_COMPLETED
```
This should trigger a rescan by the `PackageManagerService` | I had the exact same problem.
Turns out when I coped the package back to priv-app it was copied with different permission
Permissions of all packages in priv-app (and app) :
```
rwx-r-x-r-x
```
Permission of the package I copied back :
```
rwx--------
```
A simple `chmod -R a+rw <path/to/package>` solved the problem
EDIT:
Make sure your /system/ is not readonly by issuing
`mount -o remount,rw /system/` |
26,487,750 | In Android 4.x, it was enough to put an APK-file into /system/priv-app, and the package-manager recognized that new file and (un-)installed the corresponding application or service.
Since Android L, it seems to be not enough to just put the file into that directory - a reboot of the system is required to force Android to recognize that change.
Has anyone an idea how to circumvent this? Maybe with any `setprop ctl.restart xxx` or by killing a dedicated service?
EDIT:
Here are some logs from logcat:
### 1. Move APK from /system to /system/priv-app (=installation)
```
su
mount -o remount rw /system
cd /system/priv-app
mv ../AARSCService.apk . // move from /system to /system/priv-app
W/mv ( 3268): type=1400 audit(0.0:53): avc: denied { rename } for name="AARSCService.apk" dev="mmcblk0p22" ino=23041 scontext=u:r:init:s0 tcontext=u:object_r:system_file:s0 tclass=file
```
(but file HAS been moved as the current root-implementation for Nexus 7 Android Android L P2 disables SELinux for the root-commands!)
-> APK NOT loaded and not listed in app-list -> NOT as expected, APK is going to be automatically installed once put into priv-app folder on Android 4.4.
### 2. Reboot device, having APK inside /system/priv-app
```
reboot
I/PackageManager( 567): /system/priv-app/AARSCService.apk changed; collecting certs
```
-> APK IS loaded and listed in app-list -> as expected
### 3. Move APK from /system/priv-app to /system (=deinstallation)
```
su
mount -o remount rw /system
cd /system/priv-app
mv AARSCService.apk .. // move from /system/priv-app to /system
W/mv ( 3189): type=1400 audit(0.0:31): avc: denied { rename } for name="AARSCService.apk" dev="mmcblk0p22" ino=23041 scontext=u:r:init:s0 tcontext=u:object_r:system_file:s0 tclass=file
```
(but file HAS been moved as the current root-implementation for Nexus 7 Android Android L P2 disables SELinux for the root-commands!)
-> APK still loaded and listed inside app-list, service inside app can still be bound from another app -> NOT as expected, APK is going to be automatically uninstalled once removed from priv-app folder on Android 4.4.
### 4. Reboot device, having APK NOT inside /system/priv-app
```
reboot
W/PackageManager( 570): System package eu.airaudio.aarscservice no longer exists; wiping its data
```
-> APK is no more loaded and no more listed in app-list -> as expected
EDIT 2:
There's the same behaviour on unrooted Android L (21) emulator - sure, without the SELinux-warning.
But the APK is also just (un-)installed after reboot (=kill zygote). | 2014/10/21 | [
"https://Stackoverflow.com/questions/26487750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/164036/"
] | Based on your logcat messages, looks like the `PackageManagerService` is not even seeing the folder/file changes.
Here is one way to circumvent/trigger a rescan, simulate a a "boot completed" event with broadcast action:
```
adb shell am broadcast -a android.intent.action.BOOT_COMPLETED
```
This should trigger a rescan by the `PackageManagerService` | pms will scan `/system/app(priv-app)` at start. so just kill process `systemserver` :)
it work at my lollipop emulator. just take a little while to showing "upgrade android, opt app..." |
64,861,695 | Liquibase was install in the following location
C:\liquibase
when I run the following command on cmd,
```
liquibase
```
I get error
```
the system can not find specified path
```
I added liquibase to system variable
[](https://i.stack.imgur.com/LQn9h.png)
when I run the following command on cmd
```
java -version
```
The following output is displayed
```
java version "1.8.0_271"
Java(TM) SE Runtime Environment (build 1.8.0_271-b09)
Java HotSpot(TM) Client VM (build 25.271-b09, mixed mode, sharing)
```
I also tried navigating to C:\liquibase and ran
```
liquibase --help
```
and the output was
```
the system can not find specified path
```
Any suggestion on what should be adjusted to run liquibase? | 2020/11/16 | [
"https://Stackoverflow.com/questions/64861695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8765728/"
] | After deleting JAVA\_HOME variable that was set on user variables, the issue was fixed. See the following image that shows the user and system evironment variables, the user variable that was deleted is indicated surrounded by a red rectangle.
[](https://i.stack.imgur.com/GIhnM.png) | You need to add `C:\liquibase` to your `Path` variable in order for `liquibase.bat` file (which is located in `C:\liquibase`) to be accessible from any location. |
59,603,226 | I have this annoying issue with the Cupertino widgets. When I create a super simple app setup (scaffold, navbar, one text item) the text seems to start far outside of the viewport.
heres the example:
```dart
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _MyAppState();
}
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return CupertinoApp(
home: CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: Text('Me Title'),
),
child: Column(
children: <Widget>[
Text(
"No matter how short or long your journey to your accomplishment is, if you don't begin you can't get there. Beginning is difficult, but unavoidable!",
style: TextStyle(fontSize: 30),
),
],
),
),
);
}
}
```
which leads to [this result](https://i.stack.imgur.com/qXG0A.png).
The "native" Widgets (MaterialApp, Scaffold, AppBar) [lead to this](https://i.imgur.com/VpLpivZ.png) and work just fine:
```dart
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Me Title'),
),
body: Column(
children: <Widget>[
Text(
"No matter how short or long your journey to your accomplishment is, if you don't begin you can't get there. Beginning is difficult, but unavoidable!",
```
Can somebody help out here? This is a bit annoying and I imagine this will f\*\*\* up every layout I try to build on it.
Thanks in advance! | 2020/01/05 | [
"https://Stackoverflow.com/questions/59603226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/902327/"
] | The solution that worked for me is wrapping the central `Column` into a `SafeArea` widget ([screenshot](https://imgur.com/PlJJE7u)):
```dart
return CupertinoApp(
home: CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: Text('Me Title'),
),
// the SafeArea is new!
child: SafeArea(
// that's unchanged.
child: Column(
// ... etc.
``` | I have tried to change the alignment of the child using MainAxisAlignment:
```
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _MyAppState();
}
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return CupertinoApp(
home: CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: Text('Me Title'),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
"No matter how short or long your journey to your accomplishment is, if you don't begin you can't get there. Beginning is difficult, but unavoidable!",
style: TextStyle(fontSize: 30),
),
],
),
),
);
}
}
``` |
48,160,728 | I'm modifying some code to be compatible between `Python 2` and `Python 3`, but have observed a warning in unit test output.
```
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/case.py:601:
ResourceWarning: unclosed socket.socket fd=4,
family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=6,
laddr=('1.1.2.3', 65087), raddr=('5.8.13.21', 8080)
```
A little research determined this was also happening from popular libraries like [requests](https://github.com/requests/requests/issues/3912) and [boto3](https://github.com/boto/boto3/issues/454).
I could ignore the warning or [filter it](https://stackoverflow.com/questions/14938716/socket-resourcewarning-using-urllib-in-python-3) completely. If was my service, I could set the `connection: close` header in my response ([link](https://stackoverflow.com/questions/14938716/socket-resourcewarning-using-urllib-in-python-3)).
Here's an example that exhibits the warning in `Python 3.6.1`:
**app.py**
```
import requests
class Service(object):
def __init__(self):
self.session = requests.Session()
def get_info(self):
uri = 'http://api.stackexchange.com/2.2/info?site=stackoverflow'
response = self.session.get(uri)
if response.status_code == 200:
return response.json()
else:
response.raise_for_status()
def __del__(self):
self.session.close()
if __name__ == '__main__':
service = Service()
print(service.get_info())
```
**test.py**
```
import unittest
class TestService(unittest.TestCase):
def test_growing(self):
import app
service = app.Service()
res = service.get_info()
self.assertTrue(res['items'][0]['new_active_users'] > 1)
if __name__ == '__main__':
unittest.main()
```
Is there a better / correct way to manage the session so that it gets explicitly closed and not rely on `__del__()` to result in this sort of warning.
Thanks for any help. | 2018/01/09 | [
"https://Stackoverflow.com/questions/48160728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2233231/"
] | Having the teardown logic in `__del__` can make your program incorrect or harder to reason about, because there is no guarantee on when that method will get called, potentially leading to the warning you got. There are a couple of ways to address this:
1) Expose a method to close the session, and call it in the test `tearDown`
===========================================================================
`unittest`'s [`tearDown`](https://docs.python.org/3/library/unittest.html#unittest.TestCase.tearDown) method allows you to define some code that will be run after each test. Using this hook to close the session will work even if the test fails or has an exception, which is nice.
**app.py**
```
import requests
class Service(object):
def __init__(self):
self.session = requests.Session()
def get_info(self):
uri = 'http://api.stackexchange.com/2.2/info?site=stackoverflow'
response = self.session.get(uri)
if response.status_code == 200:
return response.json()
else:
response.raise_for_status()
def close(self):
self.session.close()
if __name__ == '__main__':
service = Service()
print(service.get_info())
service.close()
```
**test.py**
```
import unittest
import app
class TestService(unittest.TestCase):
def setUp(self):
self.service = app.Service()
super().setUp()
def tearDown(self):
self.service.close()
def test_growing(self):
res = self.service.get_info()
self.assertTrue(res['items'][0]['new_active_users'] > 1)
if __name__ == '__main__':
unittest.main()
```
2) Use a context manager
========================
A [context manager](https://docs.python.org/3/library/stdtypes.html#typecontextmanager) is also a very useful way to explicitly define the scope of something. In the previous example, you have to make sure `.close()` is called correctly at every call site, otherwise your resources will leak. With a context manager, this is handled automatically even if there is an exception within the scope of the context manager.
Building on top of solution 1), you can define extra magic methods (`__enter__` and `__exit__`) so that your class works with the `with` statement.
*Note: The nice thing here is that this code also supports the usage in solution 1), with explicit `.close()`, which can be useful if a context manager was inconvenient for some reason.*
**app.py**
```
import requests
class Service(object):
def __init__(self):
self.session = requests.Session()
def __enter__(self):
return self
def get_info(self):
uri = 'http://api.stackexchange.com/2.2/info?site=stackoverflow'
response = self.session.get(uri)
if response.status_code == 200:
return response.json()
else:
response.raise_for_status()
def close(self):
self.session.close()
def __exit__(self, exc_type, exc_value, traceback):
self.close()
if __name__ == '__main__':
with Service() as service:
print(service.get_info())
```
**test.py**
```
import unittest
import app
class TestService(unittest.TestCase):
def test_growing(self):
with app.Service() as service:
res = service.get_info()
self.assertTrue(res['items'][0]['new_active_users'] > 1)
if __name__ == '__main__':
unittest.main()
```
Depending on what you need, you can use either, or a combination of `setUp`/`tearDown` and context manager, and get rid of that warning, plus having more explicit resource management in your code! | This is the best solution if you are not much concern about warnings
Just import **warnings** and add this line where your driver is initiating -
```py
import warnings
warnings.filterwarnings(action="ignore", message="unclosed", category=ResourceWarning)
``` |
319,980 | I'm trying to provide a USB power source to a string of fairy lights that [look like these](https://www.target.com.au/p/twinkle-wire-string-lights-1-m/59361954).
They all appear to run in parallel, connected horizontally along two wires until the last led.
I tried isolating a single led to calculate the forward voltage drop, but my multimeter shows "1" with the diode test, and successfully lights up the LED. Any other range fails to light the LED, and also shows "1".
Am I going about this the right way? I'm still confused about the difference in being able to supply current, and drawing current. I know a USB can provide 100mA, but there's no specification for a battery except for mAh?
How can I figure out an appropriate resistor, or at least calculate the forward voltage drop?
*The waterfall analogy doesn't seem to be working for me...*
Can I just assume it's 3 volts because it's in parallel? | 2017/07/23 | [
"https://electronics.stackexchange.com/questions/319980",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/111539/"
] | * The LEDs in the linked picture are white and probably have a forward voltage drop of about 3 to 3.6 V.
* Without any specifications we'll assume they can handle 20 mA.
* On a 5 V supply we need to drop 1.5 to 2 V across the resistor.
* From Ohm's law we can calculate a suitable resistance: \$ R = \frac {V}{I} = \frac {1.75}{0.02} = 87 \; \Omega \$ (choosing mid-range on the voltage). 80 Ω will be good enough for now.
* Connect four of your 20 Ω resistors in series with each other and the LED. You would need to disconnect one led from the string for this.
* Connect up to your 5 V supply and measure the voltage drop across the LED. You could also measure the current through the line. (Be careful not to measure voltage on current range.)
* Go back to step 1 and recalculate with the new values.
The image below may help.
[](https://i.stack.imgur.com/qEPmL.png)
*Figure 1 shows that a green LED at 20 mA will have a forward voltage drop of about 2.2 V. If the supply voltage is 5 V then the resistor has to drop 5–2.2=2.8V. The required value is \$ R=\frac {V}{I}= \frac {2.80}{02}=140\;Ω\$. The nearest standard value of 150 Ω will do fine. Source: [LEDnique](http://lednique.com/gpio-tricks/interfacing-with-logic/).*
In your case you will use the 'W' curve for white LEDs. | I got some fairy lights just like the ones you mentioned, and without thinking about it I bought a 3v power supply and just hooked them up. They originally ran on a pair of 2032 batteries. They are slightly brighter on the power supply than on the batteries. There was no resistor in the package.
Another set of fairy lights I have has a timer, and it runs off 3 AAs. (6 actually but the supply is 4.5 volts). I soldered directly into the box because I wanted the timer function. I connected a 5v supply (5.1 measured) right to where the battery hookups were, and it works just fine. Something I noticed is that the output of the timer box is a DC square wave that drives the lamps at the supply voltage but with a duty cycle that looks like about 70%. So if you drive the box just hook it up (if it is 3 cells), or maybe 3 diodes to drop it to around 3v if you want to drive the string directly. |
319,980 | I'm trying to provide a USB power source to a string of fairy lights that [look like these](https://www.target.com.au/p/twinkle-wire-string-lights-1-m/59361954).
They all appear to run in parallel, connected horizontally along two wires until the last led.
I tried isolating a single led to calculate the forward voltage drop, but my multimeter shows "1" with the diode test, and successfully lights up the LED. Any other range fails to light the LED, and also shows "1".
Am I going about this the right way? I'm still confused about the difference in being able to supply current, and drawing current. I know a USB can provide 100mA, but there's no specification for a battery except for mAh?
How can I figure out an appropriate resistor, or at least calculate the forward voltage drop?
*The waterfall analogy doesn't seem to be working for me...*
Can I just assume it's 3 volts because it's in parallel? | 2017/07/23 | [
"https://electronics.stackexchange.com/questions/319980",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/111539/"
] | The way these fairy lights work is how you described, all in parallel. They typically have a single resistor at the battery box if 3 batteries, or maybe no resistor if 2 batteries. Smarter ones with a timer circuit will still be fairly similar. While transistors answer is correct for finding the forward voltage of a single led, at an assumed 20mA forward current, it doesn't answer most of your questions.
To find the voltage and current of the string, you take part of what transistor said, but apply it differently. Use a set of new, good batteries. You will need to measure their voltage while the leds are on. And you would need to take the case apart to access the resistor inside. Measure the voltage across the resistor. This will give you a fairly accurate forward voltage of the parallel led string (Source Voltage - Resistor Voltage = load voltage)
Now remove the batteries and measure the value of the resistor, or read the color code or smd resistor code if available. With this, you have both the voltage across The resistor and the resistance, so you can find the current through it. Voltage / Resistance = Current in amps. *Alternatively* you can simply measure the current through the circuit with the batteries. Any timer IC is unlikely to consume enough to make the current you measure inaccurate.
Now that you have the total current, you can divide by the number of leds, for a fairly close forward current. You can then use those numbers to replace the resistor and battery box with a usb source and resistor for the usb 5V voltage.
As to your question on supplying or drawing current, USB by standard is supposed to limit to 100 ma without enumeration, but it is rarely enforced by hardware. You can assume you can pull 500mA or more in 99% of supplies. Usb supplies like wall chargers are often 2.1 amp. Your load, especially a simple led + resistor circuit, will only pull what it needs.
Your assumption of 3V is a pretty good assumption in practice, as that's less than the Vf of your typical blue or white leds at the recommended nominal 20mA If. They would draw less current and last longer that way. Red leds you should assume lower.
All that said, the easiest thing to get these on a usb supply is to use 1 or 2 diodes like the 1n4001 with a 0.7V average forward voltage drop to drop the 5V usb supply voltage to about the same as the batteries that the fairy light uses. Connect to the battery leads with the right polarity and you are done. | I got some fairy lights just like the ones you mentioned, and without thinking about it I bought a 3v power supply and just hooked them up. They originally ran on a pair of 2032 batteries. They are slightly brighter on the power supply than on the batteries. There was no resistor in the package.
Another set of fairy lights I have has a timer, and it runs off 3 AAs. (6 actually but the supply is 4.5 volts). I soldered directly into the box because I wanted the timer function. I connected a 5v supply (5.1 measured) right to where the battery hookups were, and it works just fine. Something I noticed is that the output of the timer box is a DC square wave that drives the lamps at the supply voltage but with a duty cycle that looks like about 70%. So if you drive the box just hook it up (if it is 3 cells), or maybe 3 diodes to drop it to around 3v if you want to drive the string directly. |
32,397,347 | I need to return the sin and cos values of every element in a large array. At the moment I am doing:
```
a,b=np.sin(x),np.cos(x)
```
where x is some large array. I need to keep the sign information for each result, so:
```
a=np.sin(x)
b=(1-a**2)**0.5
```
is not an option. Is there any faster way to return both sin and cos at once? | 2015/09/04 | [
"https://Stackoverflow.com/questions/32397347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5300564/"
] | I compared the suggested solution with [perfplot](https://github.com/nschloe/perfplot) and found that nothing beats calling `sin` and `cos` explicitly.
[](https://i.stack.imgur.com/1u9jF.png)
Code to reproduce the plot:
```py
import perfplot
import numpy as np
def sin_cos(x):
return np.sin(x), np.cos(x)
def exp_ix(x):
eix = np.exp(1j * x)
return eix.imag, eix.real
def cos_from_sin(x):
sin = np.sin(x)
abs_cos = np.sqrt(1 - sin ** 2)
sgn_cos = np.sign(((x - np.pi / 2) % (2 * np.pi)) - np.pi)
cos = abs_cos * sgn_cos
return sin, cos
perfplot.save(
"out.png",
setup=lambda n: np.linspace(0.0, 2 * np.pi, n),
kernels=[sin_cos, exp_ix, cos_from_sin],
n_range=[2 ** k for k in range(20)],
xlabel="n",
)
``` | You can use complex numbers and the fact that *e i · φ = cos(φ) + i · sin(φ)*.
```
import numpy as np
from cmath import rect
nprect = np.vectorize(rect)
x = np.arange(2 * np.pi, step=0.01)
c = nprect(1, x)
a, b = c.imag, c.real
```
I'm using here the trick from <https://stackoverflow.com/a/27788291/674064> to make a version of [`cmath.rect()`](https://docs.python.org/2/library/cmath.html#cmath.rect) that'll accept and return NumPy arrays.
This doesn't gain any speedup on my machine, though:
```
c = nprect(1, x)
a, b = c.imag, c.real
```
takes about three times the time (160μs) that
```
a, b = np.sin(x), np.cos(x)
```
took in my measurement (50.4μs). |
32,397,347 | I need to return the sin and cos values of every element in a large array. At the moment I am doing:
```
a,b=np.sin(x),np.cos(x)
```
where x is some large array. I need to keep the sign information for each result, so:
```
a=np.sin(x)
b=(1-a**2)**0.5
```
is not an option. Is there any faster way to return both sin and cos at once? | 2015/09/04 | [
"https://Stackoverflow.com/questions/32397347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5300564/"
] | For completeness, another way to combine this down to a single `cos()` call is to prepare an angle array where the second half has a phase shift of pi/2.
Borrowing the profiling code from Nico Schlömer, we get:
```
import perfplot
import numpy as np
def sin_cos(x):
return np.sin(x), np.cos(x)
def exp_ix(x):
eix = np.exp(1j * x)
return eix.imag, eix.real
def cos_shift(x):
angles = x[np.newaxis, :] + np.array(((-np.pi/2,), (0,)))
return tuple(np.cos(angles))
perfplot.save(
"out.png",
setup=lambda n: np.linspace(0.0, 2 * np.pi, n),
kernels=[sin_cos, exp_ix, cos_shift],
n_range=[2 ** k for k in range(1, 16)],
xlabel="n",
)
```
[](https://i.stack.imgur.com/Kb047.png)
So it's slower than the separate `sin`/`cos` calls, but in some (narrow) contexts might be more convenient because - from the `cos()` onward - it only needs to deal with a single array. | ```
def cosfromsin(x,sinx):
cosx=absolute((1-sinx**2)**0.5)
signx=sign(((x-pi/2)%(2*pi))-pi)
return cosx*signx
a=sin(x)
b=cosfromsin(x,a)
```
I've just timed this and it is about 25% faster than using sin and cos. |
32,397,347 | I need to return the sin and cos values of every element in a large array. At the moment I am doing:
```
a,b=np.sin(x),np.cos(x)
```
where x is some large array. I need to keep the sign information for each result, so:
```
a=np.sin(x)
b=(1-a**2)**0.5
```
is not an option. Is there any faster way to return both sin and cos at once? | 2015/09/04 | [
"https://Stackoverflow.com/questions/32397347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5300564/"
] | You can use complex numbers and the fact that *e i · φ = cos(φ) + i · sin(φ)*.
```
import numpy as np
from cmath import rect
nprect = np.vectorize(rect)
x = np.arange(2 * np.pi, step=0.01)
c = nprect(1, x)
a, b = c.imag, c.real
```
I'm using here the trick from <https://stackoverflow.com/a/27788291/674064> to make a version of [`cmath.rect()`](https://docs.python.org/2/library/cmath.html#cmath.rect) that'll accept and return NumPy arrays.
This doesn't gain any speedup on my machine, though:
```
c = nprect(1, x)
a, b = c.imag, c.real
```
takes about three times the time (160μs) that
```
a, b = np.sin(x), np.cos(x)
```
took in my measurement (50.4μs). | You could take advantage by the fact that tan(x) contains both sin(x) and cos(x) function. So you could use the tan(x) and retrieve cos(x) ans sin(x) using the common transformation function. |
32,397,347 | I need to return the sin and cos values of every element in a large array. At the moment I am doing:
```
a,b=np.sin(x),np.cos(x)
```
where x is some large array. I need to keep the sign information for each result, so:
```
a=np.sin(x)
b=(1-a**2)**0.5
```
is not an option. Is there any faster way to return both sin and cos at once? | 2015/09/04 | [
"https://Stackoverflow.com/questions/32397347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5300564/"
] | You can use complex numbers and the fact that *e i · φ = cos(φ) + i · sin(φ)*.
```
import numpy as np
from cmath import rect
nprect = np.vectorize(rect)
x = np.arange(2 * np.pi, step=0.01)
c = nprect(1, x)
a, b = c.imag, c.real
```
I'm using here the trick from <https://stackoverflow.com/a/27788291/674064> to make a version of [`cmath.rect()`](https://docs.python.org/2/library/cmath.html#cmath.rect) that'll accept and return NumPy arrays.
This doesn't gain any speedup on my machine, though:
```
c = nprect(1, x)
a, b = c.imag, c.real
```
takes about three times the time (160μs) that
```
a, b = np.sin(x), np.cos(x)
```
took in my measurement (50.4μs). | A pure numpy version via complex numbers, *e iφ = cosφ + i sinφ*,
inspired by the answer from [das-g](https://stackoverflow.com/users/674064/das-g).
```
x = np.arange(2 * np.pi, step=0.01)
eix = np.exp(1j*x)
cosx, sinx = eix.real, eix.imag
```
This is faster than the `nprect`, but still slower than `sin` and `cos` calls:
```
In [6]: timeit c = nprect(1, x); cosx, sinx = cos(x), sin(x)
1000 loops, best of 3: 242 us per loop
In [7]: timeit eix = np.exp(1j*x); cosx, sinx = eix.real, eix.imag
10000 loops, best of 3: 49.1 us per loop
In [8]: timeit cosx, sinx = cos(x), sin(x)
10000 loops, best of 3: 32.7 us per loop
``` |
32,397,347 | I need to return the sin and cos values of every element in a large array. At the moment I am doing:
```
a,b=np.sin(x),np.cos(x)
```
where x is some large array. I need to keep the sign information for each result, so:
```
a=np.sin(x)
b=(1-a**2)**0.5
```
is not an option. Is there any faster way to return both sin and cos at once? | 2015/09/04 | [
"https://Stackoverflow.com/questions/32397347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5300564/"
] | You can use complex numbers and the fact that *e i · φ = cos(φ) + i · sin(φ)*.
```
import numpy as np
from cmath import rect
nprect = np.vectorize(rect)
x = np.arange(2 * np.pi, step=0.01)
c = nprect(1, x)
a, b = c.imag, c.real
```
I'm using here the trick from <https://stackoverflow.com/a/27788291/674064> to make a version of [`cmath.rect()`](https://docs.python.org/2/library/cmath.html#cmath.rect) that'll accept and return NumPy arrays.
This doesn't gain any speedup on my machine, though:
```
c = nprect(1, x)
a, b = c.imag, c.real
```
takes about three times the time (160μs) that
```
a, b = np.sin(x), np.cos(x)
```
took in my measurement (50.4μs). | ```
def cosfromsin(x,sinx):
cosx=absolute((1-sinx**2)**0.5)
signx=sign(((x-pi/2)%(2*pi))-pi)
return cosx*signx
a=sin(x)
b=cosfromsin(x,a)
```
I've just timed this and it is about 25% faster than using sin and cos. |
32,397,347 | I need to return the sin and cos values of every element in a large array. At the moment I am doing:
```
a,b=np.sin(x),np.cos(x)
```
where x is some large array. I need to keep the sign information for each result, so:
```
a=np.sin(x)
b=(1-a**2)**0.5
```
is not an option. Is there any faster way to return both sin and cos at once? | 2015/09/04 | [
"https://Stackoverflow.com/questions/32397347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5300564/"
] | You can use complex numbers and the fact that *e i · φ = cos(φ) + i · sin(φ)*.
```
import numpy as np
from cmath import rect
nprect = np.vectorize(rect)
x = np.arange(2 * np.pi, step=0.01)
c = nprect(1, x)
a, b = c.imag, c.real
```
I'm using here the trick from <https://stackoverflow.com/a/27788291/674064> to make a version of [`cmath.rect()`](https://docs.python.org/2/library/cmath.html#cmath.rect) that'll accept and return NumPy arrays.
This doesn't gain any speedup on my machine, though:
```
c = nprect(1, x)
a, b = c.imag, c.real
```
takes about three times the time (160μs) that
```
a, b = np.sin(x), np.cos(x)
```
took in my measurement (50.4μs). | For completeness, another way to combine this down to a single `cos()` call is to prepare an angle array where the second half has a phase shift of pi/2.
Borrowing the profiling code from Nico Schlömer, we get:
```
import perfplot
import numpy as np
def sin_cos(x):
return np.sin(x), np.cos(x)
def exp_ix(x):
eix = np.exp(1j * x)
return eix.imag, eix.real
def cos_shift(x):
angles = x[np.newaxis, :] + np.array(((-np.pi/2,), (0,)))
return tuple(np.cos(angles))
perfplot.save(
"out.png",
setup=lambda n: np.linspace(0.0, 2 * np.pi, n),
kernels=[sin_cos, exp_ix, cos_shift],
n_range=[2 ** k for k in range(1, 16)],
xlabel="n",
)
```
[](https://i.stack.imgur.com/Kb047.png)
So it's slower than the separate `sin`/`cos` calls, but in some (narrow) contexts might be more convenient because - from the `cos()` onward - it only needs to deal with a single array. |
32,397,347 | I need to return the sin and cos values of every element in a large array. At the moment I am doing:
```
a,b=np.sin(x),np.cos(x)
```
where x is some large array. I need to keep the sign information for each result, so:
```
a=np.sin(x)
b=(1-a**2)**0.5
```
is not an option. Is there any faster way to return both sin and cos at once? | 2015/09/04 | [
"https://Stackoverflow.com/questions/32397347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5300564/"
] | A pure numpy version via complex numbers, *e iφ = cosφ + i sinφ*,
inspired by the answer from [das-g](https://stackoverflow.com/users/674064/das-g).
```
x = np.arange(2 * np.pi, step=0.01)
eix = np.exp(1j*x)
cosx, sinx = eix.real, eix.imag
```
This is faster than the `nprect`, but still slower than `sin` and `cos` calls:
```
In [6]: timeit c = nprect(1, x); cosx, sinx = cos(x), sin(x)
1000 loops, best of 3: 242 us per loop
In [7]: timeit eix = np.exp(1j*x); cosx, sinx = eix.real, eix.imag
10000 loops, best of 3: 49.1 us per loop
In [8]: timeit cosx, sinx = cos(x), sin(x)
10000 loops, best of 3: 32.7 us per loop
``` | ```
def cosfromsin(x,sinx):
cosx=absolute((1-sinx**2)**0.5)
signx=sign(((x-pi/2)%(2*pi))-pi)
return cosx*signx
a=sin(x)
b=cosfromsin(x,a)
```
I've just timed this and it is about 25% faster than using sin and cos. |
32,397,347 | I need to return the sin and cos values of every element in a large array. At the moment I am doing:
```
a,b=np.sin(x),np.cos(x)
```
where x is some large array. I need to keep the sign information for each result, so:
```
a=np.sin(x)
b=(1-a**2)**0.5
```
is not an option. Is there any faster way to return both sin and cos at once? | 2015/09/04 | [
"https://Stackoverflow.com/questions/32397347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5300564/"
] | A pure numpy version via complex numbers, *e iφ = cosφ + i sinφ*,
inspired by the answer from [das-g](https://stackoverflow.com/users/674064/das-g).
```
x = np.arange(2 * np.pi, step=0.01)
eix = np.exp(1j*x)
cosx, sinx = eix.real, eix.imag
```
This is faster than the `nprect`, but still slower than `sin` and `cos` calls:
```
In [6]: timeit c = nprect(1, x); cosx, sinx = cos(x), sin(x)
1000 loops, best of 3: 242 us per loop
In [7]: timeit eix = np.exp(1j*x); cosx, sinx = eix.real, eix.imag
10000 loops, best of 3: 49.1 us per loop
In [8]: timeit cosx, sinx = cos(x), sin(x)
10000 loops, best of 3: 32.7 us per loop
``` | You could take advantage by the fact that tan(x) contains both sin(x) and cos(x) function. So you could use the tan(x) and retrieve cos(x) ans sin(x) using the common transformation function. |
32,397,347 | I need to return the sin and cos values of every element in a large array. At the moment I am doing:
```
a,b=np.sin(x),np.cos(x)
```
where x is some large array. I need to keep the sign information for each result, so:
```
a=np.sin(x)
b=(1-a**2)**0.5
```
is not an option. Is there any faster way to return both sin and cos at once? | 2015/09/04 | [
"https://Stackoverflow.com/questions/32397347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5300564/"
] | I compared the suggested solution with [perfplot](https://github.com/nschloe/perfplot) and found that nothing beats calling `sin` and `cos` explicitly.
[](https://i.stack.imgur.com/1u9jF.png)
Code to reproduce the plot:
```py
import perfplot
import numpy as np
def sin_cos(x):
return np.sin(x), np.cos(x)
def exp_ix(x):
eix = np.exp(1j * x)
return eix.imag, eix.real
def cos_from_sin(x):
sin = np.sin(x)
abs_cos = np.sqrt(1 - sin ** 2)
sgn_cos = np.sign(((x - np.pi / 2) % (2 * np.pi)) - np.pi)
cos = abs_cos * sgn_cos
return sin, cos
perfplot.save(
"out.png",
setup=lambda n: np.linspace(0.0, 2 * np.pi, n),
kernels=[sin_cos, exp_ix, cos_from_sin],
n_range=[2 ** k for k in range(20)],
xlabel="n",
)
``` | For completeness, another way to combine this down to a single `cos()` call is to prepare an angle array where the second half has a phase shift of pi/2.
Borrowing the profiling code from Nico Schlömer, we get:
```
import perfplot
import numpy as np
def sin_cos(x):
return np.sin(x), np.cos(x)
def exp_ix(x):
eix = np.exp(1j * x)
return eix.imag, eix.real
def cos_shift(x):
angles = x[np.newaxis, :] + np.array(((-np.pi/2,), (0,)))
return tuple(np.cos(angles))
perfplot.save(
"out.png",
setup=lambda n: np.linspace(0.0, 2 * np.pi, n),
kernels=[sin_cos, exp_ix, cos_shift],
n_range=[2 ** k for k in range(1, 16)],
xlabel="n",
)
```
[](https://i.stack.imgur.com/Kb047.png)
So it's slower than the separate `sin`/`cos` calls, but in some (narrow) contexts might be more convenient because - from the `cos()` onward - it only needs to deal with a single array. |
32,397,347 | I need to return the sin and cos values of every element in a large array. At the moment I am doing:
```
a,b=np.sin(x),np.cos(x)
```
where x is some large array. I need to keep the sign information for each result, so:
```
a=np.sin(x)
b=(1-a**2)**0.5
```
is not an option. Is there any faster way to return both sin and cos at once? | 2015/09/04 | [
"https://Stackoverflow.com/questions/32397347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5300564/"
] | I compared the suggested solution with [perfplot](https://github.com/nschloe/perfplot) and found that nothing beats calling `sin` and `cos` explicitly.
[](https://i.stack.imgur.com/1u9jF.png)
Code to reproduce the plot:
```py
import perfplot
import numpy as np
def sin_cos(x):
return np.sin(x), np.cos(x)
def exp_ix(x):
eix = np.exp(1j * x)
return eix.imag, eix.real
def cos_from_sin(x):
sin = np.sin(x)
abs_cos = np.sqrt(1 - sin ** 2)
sgn_cos = np.sign(((x - np.pi / 2) % (2 * np.pi)) - np.pi)
cos = abs_cos * sgn_cos
return sin, cos
perfplot.save(
"out.png",
setup=lambda n: np.linspace(0.0, 2 * np.pi, n),
kernels=[sin_cos, exp_ix, cos_from_sin],
n_range=[2 ** k for k in range(20)],
xlabel="n",
)
``` | You could take advantage by the fact that tan(x) contains both sin(x) and cos(x) function. So you could use the tan(x) and retrieve cos(x) ans sin(x) using the common transformation function. |
222,186 | The description for the AdvAgg bundler says:
>
> If not checked, the bundler will not split up aggregates.
>
>
>
I know that aggregation is merging files together and I take that splitting isn't the opposite of *aggregation*. What is it, then? | 2016/12/05 | [
"https://drupal.stackexchange.com/questions/222186",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/-1/"
] | The short answer is to take advantage of the browser cache. It can also be used to take advantage of the number of parallel connections that the browser can make.
Example:
Front page has a.css and b.css; node 1 has a.css, b.css and c.css. If using one aggregate then the user going from the front page to node 1 would have to download all of the CSS again. By splitting up the aggregate in a smart manner the user will only need to download c.css | Aggregated bundles can be aggregated in groups. For example, let's say there was some CSS you wanted included in the head tag and other CSS that should be included towards the bottom of your page. In this case there might be two aggregate groups.
In AdvAgg I believe the use-case you really want to look at is for JS more so than CSS. In JS you may have a "site-wide" group and a "theme" group and...
You can also have AdvAgg break up the groups by filesize or number of files being aggregated. There are some old browsers (read <= IE6) that have some issues with number of included CSS and number of CSS definitions in a single CSS file... these settings can be used to help with that.
Also, there are some HTTP2 improvements that make file aggregation less necessary for the typical use case (fewer TCP connection === better), but sometimes you would still want to aggregate in order to keep certain files together since they are functionally similar. |
41,284,153 | At the risk of sounding really dumb, here i go:
Can someone tell me how to verify if a string was entered through the scanner?
I've written some code down below but i'm stuck.
As you'll probably notice, I'm a complete novice.
```
import static java.lang.System.in;
import static java.lang.System.out;
import java.util.Scanner;
public class Test {
public static void main(String args[]) {
Scanner keyboard = new Scanner(in);
char reply;
do {
System.out.print("Nieuwe klant? (j/n)");
reply = keyboard.findWithinHorizon(".", 0).charAt(0);
} while (reply != 'j' && reply != 'n');
String giveFirstName;
String giveLastName;
String giveStreet;
String giveNumber;
String giveCity;
String giveLand;
String giveMail;
String giveGsm;
String enterLastName;
String enterFirstName;
if (reply == 'j') {
System.out.print("Voornaam Klant: ");
giveFirstName = keyboard.next();
System.out.print("Achternaam Klant: ");
giveLastName = keyboard.next();
System.out.print("Straatnaam: ");
giveStreet = keyboard.next();
System.out.print("nummer: ");
giveNumber = keyboard.next();
System.out.print("Stad: ");
giveCity = keyboard.next();
System.out.print("Land: ");
giveLand = keyboard.next();
System.out.print("E-mail adress: ");
giveMail = keyboard.next();
System.out.print("Gsm-nummer: ");
giveGsm = keyboard.next();
} else {
out.print("Voornaam bestaande klant:");
enterFirstName = keyboard.next();
System.out.print("Achternaam bestaande klant:");
enterLastName = keyboard.next();
}
}
}
``` | 2016/12/22 | [
"https://Stackoverflow.com/questions/41284153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7330532/"
] | Have you noticed you are try to run a command with `sudo`, that means the user **www-data** must to be included in the /etc/sudoers file.
I've tried your code, it works if i remove the 'sudo' and if i give permissions in the /www directory.
I think you need to configure the user in the sudoers file.
An example of my sudoers file:
```
#WWW-DATA
User_Alias WEBUSER = www-data
Cmnd_Alias CMDCOMMAND = /usr/sbin/asterisk, /sbin/iptables
WEBUSER ALL = NOPASSWD:CMDCOMMAND
#Allow members of group sudo to execute any command
%sudo ALL=(ALL:ALL) ALL
```
You need to replace the CMDCOMMAND, with the commands your webserver will run as root. In this case `mkdir`.
Remember you need to go to **/etc/** directory and use `visudo -f sudoers` to edit the sudoers file correctly.
`sudoers` [Here](https://linux.die.net/man/5/sudoers)
P.S: If you want to test if your webserver could run a command, you can:
```
su - www-data
```
After it will be a `sh` console.
You could run your command before adding in code. | You can create a directory with PHP without calling out to the shell. PHP has its own [mkdir](http://php.net/manual/en/function.mkdir.php) function.
Replace this line:
```
exec('sudo mkdir /www/test');
```
with this:
```
mkdir("/www/test1", 0700);
```
and do the same for the second mkdir command.
The first argument is the directory to create the second is the mode (permissions).
If you really want to create this directory in **/www** (see note about security below) you will need to edit the sudoers file for the www-data user as described in Ivan's answer or create the directory and change the owner. You can create the **/www** directory with the following:
```
sudo mkdir /www
```
and change the ownership with the following:
```
chown www-data:www-data /www
```
**Note:** Giving www-data sudo privileges creates a security hole. You should probably create the directories you need in the /var/www/html/ directory where permissions are not an issue and sudo is not required. If you do not want these directories accessible from the web, I would suggest creating them in /var/www and changing the owner. |
4,994,071 | I am making a use case diagram, and the problem is:
I type some text and it is always display in one line, making my use case elipse too big. Does anyone know how to make it go to the next line? I think this option is called wrap text in StarUML...
Thank you in advance!
Nanek | 2011/02/14 | [
"https://Stackoverflow.com/questions/4994071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/616446/"
] | 1. Right-click the use case.
2. Select "Show ShapeSheet".
3. Scroll down to the "Protection" section.
4. Change the value near "LockTextEdit" to `0`.
5. Close the ShapeSheet.
Now press `F2` and edit the name. Add line breaks with `Enter`.
It is tedious to unprotect each use case individually. If you are starting a new diagram, you may want to unprotect one use case and copy it instead of adding new use cases from the palette.
The downside of adding line breaks to the name of use case is that when you modify its properties, the name truncates to the first line break. Luckily, use cases do not have much useful properties other than name and documentation. | Try editing the TextBox properties in the object properties dialog. |
4,994,071 | I am making a use case diagram, and the problem is:
I type some text and it is always display in one line, making my use case elipse too big. Does anyone know how to make it go to the next line? I think this option is called wrap text in StarUML...
Thank you in advance!
Nanek | 2011/02/14 | [
"https://Stackoverflow.com/questions/4994071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/616446/"
] | I found that by putting extra spaces in between the words I could get Visio to wrap the text. I had to add enough spaces so that it would push a word beyond the margin of the use case's textbox. Sometimes this would cause a line break between two different words, so I had to add additional spaces elsewhere in the use case name.
This does cause the use cases to be displayed oddly in Visio's Model Explorer task window but this didn't bother me. | click into the text box and hit enter between the text you want on the next line. |
4,994,071 | I am making a use case diagram, and the problem is:
I type some text and it is always display in one line, making my use case elipse too big. Does anyone know how to make it go to the next line? I think this option is called wrap text in StarUML...
Thank you in advance!
Nanek | 2011/02/14 | [
"https://Stackoverflow.com/questions/4994071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/616446/"
] | **Real text wrap; no bloody carriage returns.**
Visio 2010.
SysML Stencil (source unknown) 'Activity' shape in 'Activity Diagram' shapes collection.
1. If you cannot see the 'Developer' tab on the ribbon:
File > Options > Customize Ribbon > [Select 'Developer' in 'Main Tabs' list]
2. Right-click shape of interest and select 'Show Shapesheet'
3. Find the width property of interest
Text Transform > TxtWidth
4. Change the formula in the TxtWidth property cell
5. from (something like) '=MAX(Char.Size,TEXTWIDTH(TheText))'
6. to '=MIN(Width-0.08,MAX(Char.Size,TEXTWIDTH(TheText)))'
7. Enjoy.
The magic here is the decrementer -0.08. Without it, I couldn't make the shape any smaller because the formula would not allow the text width to be smaller than the shape width, and the shape width appeared to automatically limit itself to, at minimum, the text width. Fun. You may find you *need* a larger decrementer or that you can get away with a finer one.
Save the shape to which you've made this change into the stencil if you can.
Here is the quick/dirty VBA I used to apply the formula change across all the 'Action' blocks:
```
Public Sub ApplyWrapTextPropertyToAllActionBlocks()
Const STR_ACTION_BLOCK_NAME As String = "Action with Wrap Text."
Const STR_DECREMENTER As String = "-0.08"
Dim objShape As Shape
Dim objActionBlock As Shape
For Each objShape In ActivePage.Shapes
If InStr(1, objShape.Name, STR_ACTION_BLOCK_NAME, vbBinaryCompare) <> 0 Then
Debug.Print "Found one: " & objShape.Name
Set objActionBlock = objShape
objActionBlock.CellsU("TxtWidth").Formula = "=MIN(Width" & STR_DECREMENTER & ",MAX(Char.Size,TEXTWIDTH(TheText)))"
End If
Next objShape
```
End Sub | click into the text box and hit enter between the text you want on the next line. |
4,994,071 | I am making a use case diagram, and the problem is:
I type some text and it is always display in one line, making my use case elipse too big. Does anyone know how to make it go to the next line? I think this option is called wrap text in StarUML...
Thank you in advance!
Nanek | 2011/02/14 | [
"https://Stackoverflow.com/questions/4994071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/616446/"
] | In Microsoft Visio 2007 first you need to select your shape, right click it and choose "Format", then "Protection..." and uncheck "Text" checkbox, click OK. This will allow to edit shape text.
When that is done you can select your use case shape, choose "Text Tool" from standard toolbar. Use case text will appear as text box. You can hit enter where necessary and then click "Pointer Tool" to complete operation. | I found that by putting extra spaces in between the words I could get Visio to wrap the text. I had to add enough spaces so that it would push a word beyond the margin of the use case's textbox. Sometimes this would cause a line break between two different words, so I had to add additional spaces elsewhere in the use case name.
This does cause the use cases to be displayed oddly in Visio's Model Explorer task window but this didn't bother me. |
4,994,071 | I am making a use case diagram, and the problem is:
I type some text and it is always display in one line, making my use case elipse too big. Does anyone know how to make it go to the next line? I think this option is called wrap text in StarUML...
Thank you in advance!
Nanek | 2011/02/14 | [
"https://Stackoverflow.com/questions/4994071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/616446/"
] | **Real text wrap; no bloody carriage returns.**
Visio 2010.
SysML Stencil (source unknown) 'Activity' shape in 'Activity Diagram' shapes collection.
1. If you cannot see the 'Developer' tab on the ribbon:
File > Options > Customize Ribbon > [Select 'Developer' in 'Main Tabs' list]
2. Right-click shape of interest and select 'Show Shapesheet'
3. Find the width property of interest
Text Transform > TxtWidth
4. Change the formula in the TxtWidth property cell
5. from (something like) '=MAX(Char.Size,TEXTWIDTH(TheText))'
6. to '=MIN(Width-0.08,MAX(Char.Size,TEXTWIDTH(TheText)))'
7. Enjoy.
The magic here is the decrementer -0.08. Without it, I couldn't make the shape any smaller because the formula would not allow the text width to be smaller than the shape width, and the shape width appeared to automatically limit itself to, at minimum, the text width. Fun. You may find you *need* a larger decrementer or that you can get away with a finer one.
Save the shape to which you've made this change into the stencil if you can.
Here is the quick/dirty VBA I used to apply the formula change across all the 'Action' blocks:
```
Public Sub ApplyWrapTextPropertyToAllActionBlocks()
Const STR_ACTION_BLOCK_NAME As String = "Action with Wrap Text."
Const STR_DECREMENTER As String = "-0.08"
Dim objShape As Shape
Dim objActionBlock As Shape
For Each objShape In ActivePage.Shapes
If InStr(1, objShape.Name, STR_ACTION_BLOCK_NAME, vbBinaryCompare) <> 0 Then
Debug.Print "Found one: " & objShape.Name
Set objActionBlock = objShape
objActionBlock.CellsU("TxtWidth").Formula = "=MIN(Width" & STR_DECREMENTER & ",MAX(Char.Size,TEXTWIDTH(TheText)))"
End If
Next objShape
```
End Sub | I found that by putting extra spaces in between the words I could get Visio to wrap the text. I had to add enough spaces so that it would push a word beyond the margin of the use case's textbox. Sometimes this would cause a line break between two different words, so I had to add additional spaces elsewhere in the use case name.
This does cause the use cases to be displayed oddly in Visio's Model Explorer task window but this didn't bother me. |
4,994,071 | I am making a use case diagram, and the problem is:
I type some text and it is always display in one line, making my use case elipse too big. Does anyone know how to make it go to the next line? I think this option is called wrap text in StarUML...
Thank you in advance!
Nanek | 2011/02/14 | [
"https://Stackoverflow.com/questions/4994071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/616446/"
] | When you wish to edit a shape, you need to unlock the protection attributes applied on the shape. None of the answers here have informed you how to show the "Shape Data".
1. You need to select File menu on the top. Select "Options" and select "Advanced"
2. Scroll down till the end and select "Run in Developer mode". Press Ok.
3. Select Home menu at the top to return to your diagram.
4. Right click on your Shape (let's say you're editing a Use case shape)
5. Select "Show ShapeSheet" option.
6. You will be able to see a window below the diagram window. In this window, scroll down until you can see the "Protection" preferences.
7. Select "LockTextEdit" variable and double click and change 1 to 0. Press enter to save your preference.
8. Now click on the shape and select "Text" from format menu.
9. Click on the text and you will be able to Edit it. Press Enter key in between the text where you need to insert line break. | I found that by putting extra spaces in between the words I could get Visio to wrap the text. I had to add enough spaces so that it would push a word beyond the margin of the use case's textbox. Sometimes this would cause a line break between two different words, so I had to add additional spaces elsewhere in the use case name.
This does cause the use cases to be displayed oddly in Visio's Model Explorer task window but this didn't bother me. |
4,994,071 | I am making a use case diagram, and the problem is:
I type some text and it is always display in one line, making my use case elipse too big. Does anyone know how to make it go to the next line? I think this option is called wrap text in StarUML...
Thank you in advance!
Nanek | 2011/02/14 | [
"https://Stackoverflow.com/questions/4994071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/616446/"
] | Procedure for applying Word Wrap:
1. Select from the diagram area an element for which to apply Word Wrap.
2. Right-click and select the [Format] -> [Word Wrap Name] menu.
Perform the steps above once again to removed Word Wrap. | Select the shape.
use this menu: [Home] -> [Tools] -> [Text]
now text editing is available on the shape.
Now by just hitting shift+enter on every place you want to end the line, you can wrap text manually.
Good Luck |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.