qid int64 10 74.7M | question stringlengths 15 26.2k | date stringlengths 10 10 | metadata list | response_j stringlengths 27 28.1k | response_k stringlengths 23 26.8k |
|---|---|---|---|---|---|
45,292,230 | I know that Python can be a server-side language but is there a way to make python act like a client side language (like javascript) i just want to try it out if its possible thank you | 2017/07/25 | [
"https://Stackoverflow.com/questions/45292230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8068744/"
] | Try <http://www.skulpt.org/> it is an entirely in the browser implementation of Python. | >
> Pyodide gives you a full, standard Python interpreter that runs
> entirely in the browser, with full access to the browser’s Web APIs.
>
>
>
article
<https://hacks.mozilla.org/2019/04/pyodide-bringing-the-scientific-python-stack-to-the-browser/>
download
<https://github.com/iodide-project/pyodide> |
20,840,807 | So far i have the code below:
```
$('.pagination').each(function(){
var paginationWidth = $(this).width();
var pixelOffset = '-' + paginationWidth + 'px';
console.log(paginationWidth.css('margin-left', pixelOffset ));
});
```
Console log shows "Object 57 has no method 'css'", the number being the width. Why is this the case on an each element? If its not an array why can't .css() be called upon each of said elements? | 2013/12/30 | [
"https://Stackoverflow.com/questions/20840807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1341935/"
] | Try this,
```
$('.pagination').each(function(){
var page=$(this);
var paginationWidth = page.width();
var pixelOffset = '-' + paginationWidth + 'px';
console.log(page.css('margin-left', pixelOffset ));
});
```
`$(this).width()` is not returns an object.It returns an integer number which representing it's width. | jQuery works like
$(selector).function/event(.....
but paginationWidth is not a selector. selectors are objects to be selected.
Better to use
```
$('any-selector-to apply-margin-left').css('margin-left', pixelOffset );
``` |
24,937,871 | I want to change the for-loop to block scheme
I have this for loop that does this:
let say n = 8
and node = 4
>
> n: [1][2][3][4][5][6][7][8]
>
>
> id: 0 1 2 3 0 1 2 3
>
>
>
```
id = 0;
while (id < node){
for (i = id + 1; i <= n; i = i + node)
{
//do stuff here
id = i;
}enter code here
id+1;
}//end while
```
and i want it to do this:
n = 8
node= 4
>
> n: [1][2][3][4][5][6][7][8]
>
>
> id: 0 0 1 1 2 2 3 3
>
>
>
n = 16
node = 4
>
> n: [1][2][3][4][5][6][7][8] ... [13][14][15][16]
>
>
> id: 0 0 0 0 1 1 1 1 ... 3 3 3 3
>
>
>
n = 8
node= 2
>
> n: [1][2][3][4][5][6][7][8]
>
>
> id: 0 0 0 0 1 1 1 1
>
>
>
where each id is assign to the top n show in examples
I have this but it only works for the specific scenario n= 8 & node = 4
```
...
b = id + 1
for (i = n-(n-(id+b)); i <= (n-(n-(id+b))+1); i+= 1)
...
``` | 2014/07/24 | [
"https://Stackoverflow.com/questions/24937871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2891901/"
] | Just swap the order of `field` declaration before `Default`.
So your lines:
```
public static SomeSingleton Default = new SomeSingleton();
private static int field = 0;
```
should be:
```
private static int field = 0;
public static SomeSingleton Default = new SomeSingleton();
```
The reason is due to field initialization order. First `Default` is initialized in your code, which assigns `field` value of `1`. Later that field is assigned `0` in initialization. Hence you see the latest value of `0` and not `1`.
See: [10.4.5.1 Static field initialization](http://msdn.microsoft.com/en-us/library/aa645758(v=vs.71).aspx)
>
> The static field variable initializers of a class correspond to a
> sequence of assignments that are executed in the **textual order** in
> which they appear in the class declaration.
>
>
> | This is because the ordering of the `static` variables. If you switch the two statements, the output becomes `1`:
```
private static int field = 0;
public static SomeSingleton Default = new SomeSingleton();
```
This is expected behavior as documented in [MSDN: Static field initialization](http://msdn.microsoft.com/en-us/library/aa645758(v=vs.71).aspx).
See [this .NET Fiddle](https://dotnetfiddle.net/CL9pLF). |
2,557 | I'm creating an SSL cert for my IIS server and need to know when I should choose the `Microsoft RSA SChannel Cryptographic Provider` or the `Microsoft DH SChannel Cryptographic Provider`.
**Question 1** Why would someone still need (what I assume is) a legacy certificate of 'DH'?
Given that the default is RSA/1024, I'm assuming that is the most secure choice, and the other one is for legacy reasons.
**Question 2** Is there any guide to determine what bit level is appropriate for x device?
I'd be interested in either lab results, a math formula, or your personal experience. I know the different bit levels influence the time needed to secure an SSL session and that is important for low powered devices.
**Question 3** How would bit-strength affect these scenarios?
My particular case involves these communication patterns:
1. A website that has powerful clients connecting and disconnecting the session frequently
2. A WCF website that sustains long durations of high IO data transfers
3. A client facing website geared for iPhones, and Desktops | 2011/03/16 | [
"https://security.stackexchange.com/questions/2557",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/396/"
] | This page has some interesting benchmarks that show the effect of key size on performance: <https://securitypitfalls.wordpress.com/2014/10/06/rsa-and-ecdsa-performance/> | 1. Because many clients don't support better technology.
2. Yes there is. By now RSA/2048 is considered default secure bit-length. There are conversion tables for bit-rate security for different PKC algorithms, but those are not really sepcific cause every new research in the field changes those. There are approximate coefficients.
3. The bit-length affects time of key generation exponentially, Key generation and SSL establishment is only done at the beginning of every secure connection and data is not encrypted with that, So IO transfers don't affect it. Frequent connections might put extra load on server, thats why loaded sites don't offer SSL for default. Check which bit-length/algorithms iPhone supports. Desktops have no problem. |
17,133 | Is USB or WIFI faster when syncing an iPhone 4 with iOS 5 to iTunes?
This SuperUser answer suggests that Wireless N might be faster than USB 2:
<https://superuser.com/questions/288705/speed-comparison-usb-vs-wireless-n-vs-cat-6>
Note: iPhone 4 is 802.11b/g/n Wi-Fi (802.11n 2.4GHz only) | 2011/07/08 | [
"https://apple.stackexchange.com/questions/17133",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/1262/"
] | USB 2.0 is faster, but Wi-Fi is better.
In practice, Wi-Fi will be superior to USB for syncing and backup since you don't have to worry about plugging it in. It can start as soon as you enter the network, throttle itself based on CPU/iOS activity. You can even start on WiFi and connect your iOS 5 device to USB and syncing will continue at faster speeds if WiFi proves to be slow for a particular sync session.
My experience is the devices can do their thing and sync in the background without me waiting for them and I'm almost always the slowest peg in the process. :-)
However, USB 2.0 speed is faster than 802.11n both in theory and in practice. See this chart from a [very nice Apple Insider article](http://www.appleinsider.com/articles/08/03/28/exploring_time_capsule_theoretical_speed_vs_practical_throughput.html) on relative speeds relating to Time Capsule performance. The one area where USB (or any other wired connection whether it's USB 2.0, 3.0, FireWire or Thunderbolt) is better than Wi-Fi is [latency](http://www.apogeedigital.com/knowledgebase/symphony-io/symphony-io-understanding-latency/). If your sync session is largely lots of little checks and no appreciable time is spent waiting for large files to transfer, then the wired connection could be much faster if your sessions are shorter than 15 to 30 seconds in length. Here's another nice article explaining how even a slow USB 2.0 connection can be fast enough for some demanding data transfers: <http://www.apogeedigital.com/knowledgebase/quartet/why-doesnt-quartet-use-usb-3-0/>
[
AppleInsider: Exploring Time Capsule: theoretical speed vs practical throughput](http://www.appleinsider.com/articles/08/03/28/exploring_time_capsule_theoretical_speed_vs_practical_throughput.html) | In my experience, USB sync is much faster than WiFi sync over my 802.11n AirPort, which can become an issue when I've recorded video. I was hoping that WiFi syncing meant my phone would auto-sync whenever I arrive home, but in reality it does not start syncing until you plug it in to charge within WiFi range. The upside is: I now sync whenever I plug my phone into any power brick in the house. |
9,252 | In order to encourage and motivate students to work harder and study more, it seems the teacher can use various competitions in class or after class. But on the other hand, competitions could cause jealousy and other destructive emotions among students and therefore affect the performance of some students adversely. Due to my doubts and my lack of experience, I haven't used competitions in my classes as a means of motivating students yet. But I would like to know if there is an experienced and useful method to do that. So my questions are:
**Have you ever used competitions in your classes? What are the pros and cons of students compete in the class for higher grades? Which points should I consider before encouraging students to compete with each other?** | 2013/04/09 | [
"https://academia.stackexchange.com/questions/9252",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/-1/"
] | I often have competitions in class. I try to use them primarily for motivation, not assessment.
Let me give an example: I was teaching an image processing class and we had some images of x-rays of "old master" canvas paintings. The goal was to create an algorithm that could count the density of the thread weave patterns. The quality of the answers could be assessed by comparing the algorithmic answers to manual counts, and I had about 200 locations where I knew the answer. I gave them 100 to train the algorithms. After about two weeks, there were 25 different algorithms submitted (most people worked in pairs) and then I ran the submitted codes on the 100 "unknown" locations.
I called it the "2010 Thread Counting Olympics" and made a big deal about giving out "medals". I created several different ways of measuring the quality of the algorithms: closest in least squares error, number of answers within +/-1 mm per thread, number within +/-2 mm per thread, closest in absolute value of error, closest on the canvases by Van Gogh and closest on the canvases by Vermeer. Then there were bronze, silver, gold, and titanium medals in each category. As I presented the results to the class, I described the various approaches and pitfalls of each of the algorithms, and often asked for clarifications and comments by the authors of the algorithms. By the end of the competition, well over half of the students had won "prizes"... plus they had the recognition of their peers.
The amount of effort that the students put into this project and into the class were amazing, and I think the "competition" aspect was a prime motivating factor. | One key thing to consider is whether you are encouraging your students to do better for themselves or if you are encouraging them to harm other students to look *relatively* better. Clearly, you must decide how to structure the class to achieve what you want.
I've seen many teachers take the stance: I will give 10% A's, 50% B's, 20% C's, 10% D's, and 10% F's. Their rationale is that this is the way the real world works: There are only a certain number of management positions and if they want it, they must work harder and step on others to get it. However, I've found this is not great for the classroom and it is not the way the real world works either. It is clearly possible to grow a company so that there are *more* management positions available (indeed, growth is the goal).
Personally, I have come to the point where each student should be judged on his/her own merits so I never run the kinds of competitions discussed above. That said, I have been known to offer prizes in class which are clearly limited. Prizes might include money (I don't generally offer a lot but students do seem excited about even small things, perhaps because they simply like something to represent them winning) but could easily be something else. What I offer comes out of my own pocket (though I don't tell the students this...and I'm not sure they would care either way). |
635,093 | I have been attempting to connect my Ubuntu 12.04 Virtual Machine to the internet. I have been searching and found some information but have not been successful so far. I have also tried Linux Mint and no network connectivity there either.
My Adapter Settings:

Ubuntu Network Setup in HyperV

HyperV Virtual Switch Manager

I'm not sure if this is the issue, but it seems likely. However, anytime I attempt to make the External Switch a Hyper-V Extensible Virtual Switch I get the message shown below and I am unable to set that property.

Any help is appreciated.
If more information is needed please let me know. I tried to be as thorough as possible | 2013/08/22 | [
"https://superuser.com/questions/635093",
"https://superuser.com",
"https://superuser.com/users/247490/"
] | Well, I figured it out. I had to create an Internal Virtual Switch and then go to the External Virtual switch and share its connection with the Internal Virtual Switch.
 | A solution without having to start/restart the guest OS.
1] Delete all the virtual switches and star over.
2] Create an External switch with external network selected either Ethernet or WiFi. (wait for a minute)
3] Now create an Internal switch. (again wait for a minute)
4] Go to Control Panel\Network and Internet\Network Connections and right-click on the External switch, go to Sharing tab and enable the sharing for the Internal switch. (Now, if you don't see a list of network adapters that includes the Internal switch, you may have to start over or wait for a while to let all the changes take effect.)
5] Select the Internal switch for your Linux type guest OS and enable the network in the OS. (You don't need to restart the guest OS at any of the steps) Hopefully your guest OS will connect to the internet as well as internal network.
I've tested & verified this exact process for RedHat7, CentOS7 and Kali Linux. |
10,975,752 | One common thing I see developers doing in WinForms is forms/controls subscribing to their own events so you get
```
this.Load += new System.EventHandler(this.WelcomeQuickViewWF_Load);
this.Activated += new System.EventHandler(this.WelcomeQuickViewWF_Activated);
```
rather than
```
protected override void OnActivated(EventArgs e)
{
}
```
Now I know the second way is more Object Oriented, the first way is event driven and I tend to refactor towards overriding - is there any reason NOT to do this? What I don't want to be doing is making changes that are not really needed and purely an aesthetic choice. | 2012/06/11 | [
"https://Stackoverflow.com/questions/10975752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1006869/"
] | Usually you would use AsyncTask for such a thing on Android..
***Intro:*** By default all code you write not using threads,services,etc.. will execute in `UI thread`.. That means that if you do some expensive work there, user interface will be blocked (not responsive). Good practise is to move such a expensive task to separate thread, otherwise you app will show `ANR` dialog and be closed.
***How:*** One of the best approach for your case is use of [AsyncTask](http://developer.android.com/reference/android/os/AsyncTask.html).. Basically in `onPreExecute()` you show progress dialog or "long task in progress" animation. In `doInBackground(Params... params)` you put code of expensive operation. In case u need to update progress bar you do it from `onProgressUpdate(Progress... values)`. When expensive task finishes it will provide results to `onPostExecute(Result result)` method. From this one you can update UI again and close previously displayed progress dialog.
Hope it helped. Cheers.. ;) | Use `Asyntask`, put that code in `doInBackground` , start `processbar` in `onPreExecute()` , dimiss in `onPostExecute()` |
39,367,423 | I am trying to understand OnInit functionality in angular2 and read the documentation:
>
> Description
>
>
> Implement this interface to execute custom initialization logic after
> your directive's data-bound properties have been initialized.
>
>
> ngOnInit is called right after the directive's data-bound properties
> have been checked for the first time, and before any of its children
> have been checked. It is invoked only once when the directive is
> instantiated.
>
>
>
I do not understand `directive's data-bound properties` what does it mean? | 2016/09/07 | [
"https://Stackoverflow.com/questions/39367423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1743843/"
] | When you have a component
```ts
@Component({
selector: 'my-component'
})
class MyComponent {
@Input() name:string;
ngOnChanges(changes) {
}
ngOnInit() {
}
}
```
you can use it like
```ts
<my-component [name]="somePropInParent"></my-component>
```
This make `name` a data-bound property.
When the value of `somePropInParent` was changed, Angulars change detection updates `name` and calls `ngOnChanges()`
After `ngOnChanges()` was called the first time, `ngOnInit()` is called once, to indicate that initial bindings (`[name]="somePropInParent"`) were resolved and applied.
For more details see <https://angular.io/docs/ts/latest/cookbook/component-communication.html> | data-bound properties are just properties of the class |
29,021,629 | I am trying to do a code in an asynctask that takes a picture from the camera and send it to a server over UDP 100 times. However, the PictureCallback isn't called. Can someone please help me?
this is what i tried:
```
public class MainAsyncTask extends AsyncTask<Void, String, Void> {
protected static final String TAG = null;
public MainActivity mainAct;
public MainAsyncTask(MainActivity mainActivity)
{
super();
this.mainAct = mainActivity;
}
@Override
protected Void doInBackground(Void... params) {
DatagramSocket clientSocket = null;
InetAddress IPAddress = null;
try {
clientSocket = new DatagramSocket();
IPAddress = InetAddress.getByName("192.168.1.15");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte [] data;
DatagramPacket sendPacket;
try {
for (int i=0; i < 100; i++)
{
publishProgress("");
File file = new File(Environment.getExternalStorageDirectory()+ File.separator +"img.jpg");
while (!file.exists() || file.length() == 0);
Bitmap screen = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+ File.separator +"img.jpg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
screen.compress(Bitmap.CompressFormat.JPEG, 15, bytes);
data = bytes.toByteArray();
sendPacket = new DatagramPacket(data, data.length, IPAddress, 3107);
clientSocket.send(sendPacket);
file.delete();
}
clientSocket.close();
} catch (Exception e) {
// TODO Auto-generated catch block
publishProgress(e.getMessage());
}
return null;
}
public static void takeSnapShots(MainActivity mainAct)
{
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera)
{
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(Environment.getExternalStorageDirectory()+File.separator+"img"+".jpg");
outStream.write(data);
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally
{
camera.stopPreview();
camera.release();
camera = null;
}
Log.d(TAG, "onPictureTaken - jpeg");
}
};
SurfaceView surface = new SurfaceView(mainAct.getApplicationContext());
Camera camera = Camera.open();
try {
camera.setPreviewDisplay(surface.getHolder());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
camera.startPreview();
camera.takePicture(null,null,jpegCallback);
}
protected void onProgressUpdate(String... progress) {
takeSnapShots(mainAct);
}
@Override
protected void onPostExecute(Void result)
{
}
```
} | 2015/03/12 | [
"https://Stackoverflow.com/questions/29021629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4651619/"
] | I don't think that `AsyncTask` is the most convenient tool to do the job.
You need a `SurfaceView` that is not simply created out of nowhere, but connected to the screen. You should initialize your **camera** only once, and you cannot call `camera.takePicture()` in a loop. You can call `takePicture()` from `onPictureTaken()` callback, but you should also remember that you cannot work with sockets from the UI thread. Luckily, you can follow the Google recommendations.
>
> [the recommended way to access the camera is to open Camera on a separate thread](http://developer.android.com/training/camera/cameradirect.html).
>
>
>
and
>
> [Callbacks will be invoked on the event thread `open(int)` was called from](http://developer.android.com/reference/android/hardware/Camera.html).
>
>
>
If you open camera in a new HandlerThread, as shown [here](https://stackoverflow.com/a/19154438/192373), the picture callbacks will arrive on that beckground thread, which may be used also for networking.
Also, I recommend you to send directly the JPEG buffer that you receive from the camera. I believe that overhead of saving image to file, reading the file to bitmap, and compressing the latter to another JPEG may be way too much. To control the image size, [choose appropriate picture size](http://developer.android.com/reference/android/hardware/Camera.Parameters.html#setPictureSize(int,%20int)). Note that the size should be selected from the [list of sizes supported by the specific camera](http://developer.android.com/reference/android/hardware/Camera.Parameters.html#getSupportedPictureSizes()).
```
public class CameraView extends SurfaceView
implements SurfaceHolder.Callback, Camera.PictureCallback {
private static final String TAG = "CameraView";
private Camera camera;
private HandlerThread cameraThread;
private Handler handler;
private boolean bCameraInitialized = false;
private int picturesToTake = 0;
public CameraView(Context context, AttributeSet attr) {
super(context, attr);
// install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
getHolder().addCallback(this);
}
@Override public void surfaceCreated(SurfaceHolder holder) {
cameraThread = new HandlerThread("CameraHandlerThread");
cameraThread.start();
handler = new Handler(cameraThread.getLooper());
hanlder.post(new Runnable() {
@Override public void run() {
openRearCamera();
bCameraInitialized = false;
}
});
}
@Override public void surfaceDestroyed(SurfaceHolder holder) {
if (camera != null) {
Log.d(TAG, "Camera release");
camera.release();
camera = null;
bCameraInitialized = false;
}
}
// finalize the camera init now that we know preview size
@Override public void surfaceChanged(SurfaceHolder holder, int format, final int w, final int h) {
Log.w(TAG, "surfaceChanged(" + w + ", " + h + ")");
if (!bCameraInitialized) {
cameraSetup(w, h);
bCameraInitialized = true;
}
}
private void openRearCamera() {
if (camera != null) {
Log.e(TAG, "openRearCamera(): camera is not null");
return;
}
try {
camera = Camera.open(0);
Log.d(TAG, "Camera ready " + String.valueOf(camera));
}
catch (Throwable e) {
Log.e(TAG, "openRearCamera(): Camera.open() failed", e);
}
}
private void cameraSetup(int w, int h) {
if (camera == null) {
Log.e(TAG, "cameraSetup(): camera is null");
return;
}
Log.d(TAG, "Camera setup");
try {
Camera.Parameters params = camera.getParameters();
// still picture settings - be close to preview size
Camera.Size pictureSize = params.getSupportedPictureSizes()[0];
params.setPictureSize(pictureSize.width, optimalPictureSize.height);
camera.setParameters(params);
camera.setPreviewDisplay(getHolder());
camera.startPreview();
}
catch (Throwable e) {
Log.e(TAG, "Failed to finalize camera setup", e);
}
}
private void sendJpeg(byte[] data) {
DatagramSocket clientSocket = null;
InetAddress IPAddress = null;
try {
clientSocket = new DatagramSocket();
IPAddress = InetAddress.getByName("192.168.1.15");
}
catch (Exception e) {
Log.e(TAG, "failed to initialize client socket", e);
}
DatagramPacket sendPacket;
sendPacket = new DatagramPacket(data, data.length, IPAddress, 3107);
clientSocket.send(sendPacket);
Log.d(TAG, "sent image");
}
@Override public void onPictureTaken(byte[] data, Camera camera) {
sendJpeg(data);
camera.startPreview();
takePictures(picturesToTake-1);
}
public void takePictures(int n) {
if (n > 0) {
picturesToTake = n;
Log.d(TAG, "take " + n + " images");
camera.takePicture(null, null, this);
}
else {
Log.d(TAG, "all images captured");
}
}
}
```
The class above is a compilation from several projects, with error checking reduced to minimum for brevity. It may require some fixes to compile. You simply add a `<CameraView />` to your activity layout, and call its `takePictures` when the user clicks a button or something. | Do you call to your AsyncTask like this? Just to create the AsyncTask is not enouge.
```
new MainAsyncTask(ActivityContext).execute();
``` |
61,394,350 | I am supposed to create 49 threads in a certain process( there are multiple processes here in my problem, so let's call the process P3). I have created those threads but the issue presents itself here: at any time, at most 5 threads are allowed to run in P3 without counting the main process. Thread 13 from P3 is allowed to end only if there are a total of 5 threads that are running(Thread 13 is among those 5 threads). My question is: how do I make sure that at some point of the program's execution there will be 5 threads running and among them there will be Thread 13 so it can end it's execution. I am using C as a programming language and Linux system calls. Moreover, I am not allowed to use "sleep()" and "usleep()".
This is a function in which I count the number of threads.
` void\* thread\_function2(void\* arg)
{
```
TH_STRUCT* st=(TH_STRUCT*)arg;
sem_wait(&sem);
sem_wait(&sem2);
nrThreads++;
sem_post(&sem2);
printf("Number of threads running: %d\n",nrThreads);
sem_wait(&sem3);
nrThreads--;
sem_post(&sem3);
sem_post(&sem);
return 0;
```
} `
This part is from the main thread in which I create my threads:
`sem_init(&sem,0,5);
sem_init(&sem2,0,1);
sem_init(&sem3,0,1);
sem_init(&sem4,0,1);`
```
for(int i=1;i<=49;i++)
{
params1[i].procNum=3;
params1[i].threadNum=i;
pthread_create(&tids1[i],NULL,thread_function2,¶ms1[i]);
}
```
`
Beginning a thread is done with the fuction info(args) which prints the word BEGIn and the thread number.
Ending a thread is done with a function info(args) which prints the word END and the thread number.
This is an example of an output and what the threads do when they begin and when they end:
```
[ ] BEGIN P5 T0 pid=30059 ppid=30009 tid=-99981504
[ ] END P5 T0 pid=30059 ppid=30009 tid=-99981504
[ ] BEGIN P6 T0 pid=30060 ppid=30009 tid=-99981504
[ ] END P6 T0 pid=30060 ppid=30009 tid=-99981504
[ ] BEGIN P7 T0 pid=30061 ppid=30009 tid=-99981504
[ ] END P7 T0 pid=30061 ppid=30009 tid=-99981504
[ ] BEGIN P8 T0 pid=30062 ppid=30009 tid=-99981504
[ ] END P8 T0 pid=30062 ppid=30009 tid=-99981504
[ ] END P3 T0 pid=30009 ppid=30006 tid=-99981504
[ ] BEGIN P9 T0 pid=30063 ppid=30006 tid=-99981504
[ ] BEGIN P9 T4 pid=30063 ppid=30006 tid=-125163776
[ ] BEGIN P9 T1 pid=30063 ppid=30006 tid=-125163776
[ ] END P9 T1 pid=30063 ppid=30006 tid=-125163776
[ ] BEGIN P9 T2 pid=30063 ppid=30006 tid=-108378368
[ ] END P9 T4 pid=30063 ppid=30006 tid=-125163776
[ ] END P9 T2 pid=30063 ppid=30006 tid=-108378368
[ ] BEGIN P9 T3 pid=30063 ppid=30006 tid=-116771072
[ ] END P9 T3 pid=30063 ppid=30006 tid=-116771072
[ ] END P9 T0 pid=30063 ppid=30006 tid=-99981504
[ ] END P1 T0 pid=30006 ppid=3467 tid=-99981504
``` | 2020/04/23 | [
"https://Stackoverflow.com/questions/61394350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12586342/"
] | You need to call the parent class initializer to the child class initializer, like :
```
class Apple:
def __init__(self):
self.year_established = 1976
def background(self):
return ('it is established in {}'.format(self.year_established))
class Macbook(Apple):
def __init__(self):
super().__init__()
self.price = 10000
def productdetails(self):
return (str(self.price) + self.background())
macbookpro = Macbook()
print(macbookpro.productdetails())
``` | Use `Base-Class (or iterface) / Inherit-Class` insted of `Child / Parent`, that whuld describe a "ownership" of classes like in this example
```
class Apple:
def __init__(self, parent=None):
self.parent = parent
class Macbook(Apple):
def __init__(self, **kwargs):
super(Macbook, self).__init__(**kwargs)
macbookpro = Macbook()
macbookpro_child = Macbook(parent=macbookpro)
```
The reason why a `super()` method deeded is becouse in python when a class inherits a base and a method already exists in the base class the method whuld not be changed, in other languages is diferent becouse overrides de base clase insted of ignoring the duplicate.
To fix this the super calls the original method and this can be done at any point in the `__init__()`, note that any method that you raplace from de base class have a super.
(Passing self is required to give context of in which class is the super executed)
Loocking at the old super method it can be a little more intuitive
```
class Macbook(Apple):
def __init__(self):
Apple.__init__(self)
```
This is your code with a super
```
class Apple:
def __init__(self):
self.year_established = 1976
def background(self):
return 'it is established in {}'.format(self.year_established)
class Macbook(Apple):
def __init__(self):
super(Macbook, self).__init__()
self.price = 10000
def product_details(self):
return str(self.price) + self.background()
macbookpro = Macbook()
print(macbookpro.product_details())
``` |
57,081,653 | I am trying to copy a column of data from one dataframe to another, using the index as a reference. When copying the column, I want to fill any entry that does not appear in both dataframes with a NaN.
For example, I have these two dummy dfs:
```
df1 =
col_1 col_2 col_3 col_4
index
A 1 4 7 10
B 2 5 8 11
C 3 6 9 12
```
```
df2 =
col_5 col_6
index
A 13 15
C 14 16
```
And I would like to copy col\_5 to `df1` based on the shared index so `df1` looks like:
```
df1 =
col_1 col_2 col_3 col_4 col_5
index
A 1 4 7 10 15
B 2 5 8 11 NaN
C 3 6 9 12 16
```
Since they're different lengths I can't simply do `df1['col_5'] = df2['col_5']`, and I didn't have any success with a `df1.merge(df2, how='left')`, and then I'd have to drop any unwanted columns anyway.
Any help appreciated. Thanks! | 2019/07/17 | [
"https://Stackoverflow.com/questions/57081653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4343815/"
] | Wanted to add to this as this is the only result for the Google search "tft.apply\_buckets" :)
The example for me did not work in the latest version of TFT. The following code did work for me.
Note that the buckets are specified as a rank 2 tensor, but with only one element in the inner dimension.
(I'm using the wrong words but hopefully my example below will clarify)
```
import tensorflow as tf
import tensorflow_transform as tft
import numpy as np
tf.enable_eager_execution()
xt = tf.cast(tf.convert_to_tensor(np.array([-1,9,19, 29, 39])),tf.float32)
bds = [[0],[10],[20],[30],[40]]
boundaries = tf.cast(tf.convert_to_tensor(bds),tf.float32)
buckets = tft.apply_buckets(xt, boundaries)
```
thanks for your help as this answer got me most of the way there!
The rest I found from the TFT source code:
<https://github.com/tensorflow/transform/blob/deb198d59f09624984622f7249944cdd8c3b733f/tensorflow_transform/mappers.py#L1697-L1698> | I love this answer, just wanted to add some simplification as enabling eager execution, casting, and numpy aren't really needed. Note that casting below for the float case is done by making one of the scalars a float, tensorflow standardizes on the highest fidelity data type.
The code below shows how this mapping works. The number of buckets created is the length of bucket boundaries vector + 1, or (in my opinion), more intuitively, the minimum number of commas + 2. Plus two because negative infinity to the smallest value, and the largest value to infinity. If something is on the bucket boundary, it goes to the bucket representing bigger numbers. What happens when the bucket boundaries aren't sorted is left as an exercise for the reader :)
```
import tensorflow as tf
import tensorflow_transform as tft
xt = tf.constant([-1., 9, 19, 29, 39, float('nan'), float('-inf'), float('inf')])
bucket_boundaries = tf.constant([[0], [10], [20], [30], [40]])
bucketed_floats = tft.apply_buckets(xt, bucket_boundaries)
for scalar, index in zip(xt, range(len(xt))):
print(f"{scalar} was mapped to bucket {bucketed_floats[index]}.")
```
>
> -1.0 was mapped to bucket 0.
>
> 9.0 was mapped to bucket 1.
>
> 19.0 was mapped to bucket 2.
>
> 29.0 was mapped to bucket 3.
>
> 39.0 was mapped to bucket 4.
>
> nan was mapped to bucket 5.
>
> -inf was mapped to bucket 0.
>
> inf was mapped to bucket 5.
>
>
>
>
```
xt_int = tf.constant([-1, 9, 19, 29, 39, 41])
bucketed_ints = tft.apply_buckets(xt_int, bucket_boundaries)
for scalar, index in zip(xt_int, range(len(xt_int))):
print(f"{scalar} was mapped to bucket {bucketed_ints[index]}.")
```
>
> -1 was mapped to bucket 0.
>
> 9 was mapped to bucket 1.
>
> 19 was mapped to bucket 2.
>
> 29 was mapped to bucket 3.
>
> 39 was mapped to bucket 4.
>
> 41 was mapped to bucket 5.
>
>
>
>
Note that there's also a function called `tft.bucketize` which appears to require a full pass over the data. I'm not a 100% clear on the nuance between `tft.apply_buckets` and `tft.bucketize`. |
5,696,675 | >
> **Possible Duplicate:**
>
> [How should I store GUID in MySQL tables?](https://stackoverflow.com/questions/412341/how-should-i-store-guid-in-mysql-tables)
>
>
>
Hello,
To represent a GUID in MySQL, should I just use varchar? Also, since it is something that will be used to recognize a user, should it be encrypted? Or does that lost the point of having the GUID? :)
Thanks! | 2011/04/17 | [
"https://Stackoverflow.com/questions/5696675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/478573/"
] | Yes, a varchar would be a good choice. Maybe even char, because the length is fixed, tough I don't know if you'd gain anything.
And I can't see why you would want to encrypt it. | I guess you're coming from a SQL Server background. In MySQL you generally use an INTEGER(10) field with AUTO\_INCREMENT as primary key. There's not really any reason to *encrypt* that value in any way. |
1,097,969 | Can web technologies be used for a desktop application written in a traditional language like C++? I'd guess that they can, though I've not been able to find any evidence of this. I understand Adobe Air can make desktop apps using Flash, but it uses web languages like php etc. What I'd like to do is to be able to build my GUI elements - edit boxes, sliders, menus and so on, using html/CSS - instead of native widgets - in an application that is otherwise built in the conventional way - using Visual Studio for example.
Does anyone know if this has been done, if there's any software that makes it easier, or if there are any objections to this approach? | 2009/07/08 | [
"https://Stackoverflow.com/questions/1097969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/134919/"
] | An application I've been involved in , TomTom HOME 2 is built as a big C++ plugin in the Mozilla XulRunner framework. This framework is shared with Mozilla FireFox so there is a lot of commonality. TomTom HOME is a free (as in beer) download and the model part is in readable Javascript, so you can have a look to see how it works.
Its predecessor, TomTom HOME 1.x was built like Antony Carthy describes, wrapping the MSHTML(IE) ActiveX control, or Safari on Mac. (Disclaimer: TomTom has filed a number of patent applications to communicate with the embedded browser; the ActiveX interfaces to the JS engine are rather limited)
It's fairly easy if you have a proper MVC design, and it makes it also easy to keep the Model/View seperation clean during the implementation. You can't put in a "quick hack" in the model to expose some internal detail of the model. The View code is Javascript and it can access the C++ model only via defined interfaces. | As a sideline, I have built an effictive application using an IE form control, basically embedding a web browser into my app, which served my purposes at the time.
Edit:
<http://msdn.microsoft.com/en-ca/library/aa770041(VS.85).aspx>
<https://stackoverflow.com/questions/tagged/mshtml> |
62,621,858 | I'm new to dependency injection in .net core.
So far i was using interface and was easily able to inject dependencies via DI framework.
Now, I have one external library which holds mongo DB connection and provides necessary database operation calls.
The class accepts two parameters i.e connection string and database name.
As MOQ can inject dependency without interface so i tried to add below code
```
services.AddSingleton<MongoManager>();
```
As `MongoManager` Class accepts connection string so this would not work.
After this tried below code.
```
services.AddSingleton(new MongoManager(userName, database));
```
Above code works as expected however it creates object at the time of app start.
In other cases .net framework gives instance of a class when its first time requested, however here its getting created without being asked by app anywhere.
Also would this object be disposed when app terminates?
Is there any way to register classes and tell the framework to pass certain arguments like connection string, database Name etc. to the class when the instance requested first time. | 2020/06/28 | [
"https://Stackoverflow.com/questions/62621858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4592855/"
] | Give this a try
```
setMenuOpen(prevMenuOpenState => !prevMenuOpenState);
```
or
```
<div
onClick={() => setMenuOpen(!menuOpen)}
>
``` | The Answer is just refactoring the code into class Component without using hooks useState. Using state and setState to update. The Problem will solve.
But If I use useState hooks the problem remains the same Whatever I do with the code. |
260,824 | When I am in battle, before I attack, it keeps saying I am feeling funky. What does that mean? Does it have any effect on my character? | 2016/03/30 | [
"https://gaming.stackexchange.com/questions/260824",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/-1/"
] | This is a status condition called **Mushroomized** that comes from mushroom type enemies. It's very similar to "confusion" in most other games where it can cause the infected player to unwantedly attack allies.
You should be able to remove the effect by visiting the hospital. IIRC there is a man in the lobby that you can talk to who will remove the effect.
[Here's a quick run down of mushroomized and its effects.](http://earthbound.wikia.com/wiki/Mushroom) | There is a second effect to confusion, your character will eventually run in directions that are not the direction you are pointing. Sometimes, the control is flipped-down is up, left is right. Other times, it is 1/4 turned-up is right, right is down, down is left, left is up. Better to get rid of it as soon as possible! |
55,899,896 | ```
def myFunction(cond_list, input_list):
res = []
data = list(set(input_list)) # filter duplicate elements
for i in cond_list:
for j in data:
if i in j:
res.append(i)
return res
cond = ['cat', 'rabbit']
input_list = ['', 'cat 88.96%', '.', 'I have a dog', '', 'rabbit 12.44%', '', 'I like tiger']
result = myFunction(cond_list=cond, input_list=input_list)
print(result) # the input list have: ['cat', 'rabbit']
```
I have a function. Is there any better way to modify my function according to the conditions? | 2019/04/29 | [
"https://Stackoverflow.com/questions/55899896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9061561/"
] | You can use [itertools.product](https://docs.python.org/3/library/itertools.html#itertools.product) to generate the pairs for comparison:
```
>>> product = itertools.product(cond, input_list)
>>> [p for (p, q) in product if p in q]
['cat', 'rabbit']
``` | ```
cond = ['cat', 'rabbit'] # filter duplicate elements
input_list = ['', 'cat 88.96%', '.', 'dog 40.12%', '', 'rabbit 12.44%', '', 'tiger
85.44%']
matching = list(set([s for s in input_list if any(xs in s for xs in cond)]))
for i in matching:
print(i)
``` |
159,199 | I'm trying to find where my prints screens are going in South Park Stick of Truth.
So far I've searched in My Pictures, My Documents and the location of the game, but I've had no luck so far. :(
I'm using Windows 7. | 2014/03/08 | [
"https://gaming.stackexchange.com/questions/159199",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/30762/"
] | Assuming you have actually taken any screenshots (that is, by default, using the `F12` key), your screenshots should be stored in `{steam root}\userdata\{user id}\760\remote\213670\screenshots`
`{steam root}` is, by default, `C:\Program Data (x86)`.
`{user id}` is most likely the only directory on that level anyway.
---
That said, after a play session during which you took a screenshot, Steam will (by default) prompt you with a Screenshot Manager window, which should give you access to cloud upload and, more importantly, a button to open the actual directory.
You can also change these settings via *Steam → Settings → In-Game*, which offers more tailored preferences:
 | The easiest way to view your screenshots is to go to `view --> screenshots` in Steam, then select the game.
Once there, you can click *"show on disk"* if you need access to the actual image file. |
73,007,498 | I'm working on PHP to output the email content. I want to check the width size through on the style of the html tag that if the width size which is greater than 400, I want to change it to 306px.
Example:
```
style="width: 406px;
```
If the width value is greater than 300, I want to change it to:
```
style="width: 306px;
```
Have is the html content on my php page:
```
<div class="a3V ui-widget-content ui-resizable ui-resizable-resizing" style="width: 406px; height: 128px;"><div class="ui-resizable-handle ui-resizable-nw a3T" id="nw" style="left: -5px; top: -5px; cursor: nw-resize;"></div><div class="ui-resizable-handle ui-resizable-sw a3T" id="sw" style="left: -5px; bottom: -5px; cursor: sw-resize;"></div><div class="ui-resizable-handle ui-resizable-ne a3T" id="ne" style="right: -5px; top: -5px; cursor: ne-resize;"></div><div class="ui-resizable-handle ui-resizable-se a3T" id="se" style="right: -5px; bottom: -5px; cursor: se-resize;"></div><div class="ui-resizable-handle ui-resizable-n a3b" id="n" style="top: 0px; left: 0px; right: 0px; height: 1px; cursor: n-resize;"></div><div class="ui-resizable-handle ui-resizable-s a3b" id="s" style="bottom: 0px; left: 0px; right: 0px; height: 1px; cursor: s-resize;"></div><div class="ui-resizable-handle ui-resizable-w a3b" id="w" style="top: 0px; left: 0px; bottom: 0px; width: 1px; cursor: w-resize;"></div><div class="ui-resizable-handle ui-resizable-e a3b" id="e" style="top: 0px; right: 0px; bottom: 0px; width: 1px; cursor: e-resize;"></div><img src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" alt="Google" style="width: 406px;height: 128px;"></div>
```
Here is the code:
```
$mailbox= $link->prepare("SELECT * FROM Drafts WHERE id = ?");
$mailbox->execute([$id]);
if ($mailbox->rowCount() > 0) {
$row = $mailbox->fetch(PDO::FETCH_ASSOC);
$draft_id = $row['email_id'];
$draft_attached_files = $row['attached_files'];
$draft_message = $row['message'];
if (!empty($draft_message)) {
$draft_message = base64_decode($draft_message);
}
echo '<body>
<div id="mobile-app-container" data-reactroot="" style="height: 100%; overflow-y: auto;">
<div id="app" data-test-id="mobile-app" class="a6" tabindex="-1">
<div class="eM" role="message" style="display: block; overflow-y: auto;">
<div id="eMB" style="overflow-y: auto;">
<div class="mSG">';
echo $draft_message;
if (!empty($draft_attachments)) {
echo $draft_attachments;
}
echo '</div>
</div>
</div>
</div>
</div>';
echo "</html><body>";
```
I have got no idea how to check if the value is greater than 300, the only things I can think of would be like this:
```
if (strpos($draft_message, 'width:400px;') !== false) {
$draft_message = str_replace('width:400px;', 'width: 335px;', $draft_message);
}
```
I would have to write hundred of lines for each different value which is not the right way to do.
Can you please show me an example how I can check on the tag for the width size that if the width size is greater than 400, then I want to replace it with 306??
Thank you. | 2022/07/16 | [
"https://Stackoverflow.com/questions/73007498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12632670/"
] | Perhaps add this somewhere:
```
<style>
div {
max-width: 306px !important;
}
</style>
``` | u can try and use max width set to 306px for that part |
196,600 | I'm testing for resilience against injection attacks on an SQL Server database.
All table names in the db are lower case, and the collation is case-sensitive, *Latin1\_General\_CS\_AS*.
The string I can send in is forced to uppercase, and can be a maximum of 26 characters in length. So I can't send in a DROP TABLE because the table name would be in uppercase and thus the statement would fail due to the collation.
So - what's the maximum damage I could do in 26 characters?
EDIT
I know all about parameterised queries and so forth - let's imagine that the person who developed the front end that builds the query to send in didn't use params in this case.
I'm also not trying to do anything nefarious, this is a system built by somebody else in the same organisation. | 2018/01/30 | [
"https://dba.stackexchange.com/questions/196600",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/3752/"
] | Easy:
```
GRANT EXECUTE TO LowlyDBA
```
Or, I guess in this case it'd be
```
grant execute to lowlydba
```
Take your pick of variations on this.
In all likelihood you may be able to test this now against your current system, but any number of small changes in the database over time could invalidate your testing. The character string could change, someone could create a lower case stored procedure that has destructive potential - anything. You can never say with 100% confidence that there isn't a destructive 26 character attack someone could construct.
I suggest you find a way to make the developer follow **basic** industry standard best security practices, if only for your own sake as someone who I presume is at least partially responsible should security breaches happen.
Edit:
And for maliciousness/fun, you could try enabling **every** trace flag. This would be interesting to observe. Feels like a blog post Brent Ozar would make...
```
DBCC TRACEON(xxxx, -1)
``` | You could create a table that you then fill up until the end of time or disk space runs out whichever comes first.
```
declare @S char(26);
set @S = 'create table t(c char(99))';
exec (@S);
set @S = 'insert t values('''')'
exec (@S);
set @S = 'insert t select c from t'
exec (@S);
exec (@S);
exec (@S);
exec (@S);
-- etc
``` |
412,610 | I'm trying to find a word or short phrase that generally describes *people* that have dietary requirements, food restrictions, sensitivities, and even preferences. The phrase might apply to different kinds of restrictions, might include taste likes / dislikes, etc.
Instead of saying something like "we help people with dietary restrictions, allergies, and sensitivities" (which is verbose), is there a way to say "we help \_\_\_\_\_\_\_\_\_\_\_\_\_\_" (where the blank is "people with dietary restrictions, allergies, and sensitivities")
Is there a word or short phrase that would make sense here? | 2017/10/03 | [
"https://english.stackexchange.com/questions/412610",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/260272/"
] | There is **no good word** for these.
There are obviously conditions (diabetes, celiac disease, acid reflux, etc.) that limit what people can eat, but most people do not want to define themselves by their conditions, any more than they want to define themselves by gender, age, or other things that are *attributes* of a human being.
Some people can get quite militant about their food choices. However, there too I'd suggest that their choices be treated as attributes, since this effectively denies them the opportunity for moral posturing.
There may be some *medical* term. However, in ordinary social usage, you're probably better off with a familiar phrase, e.g. a *person with diet restrictions*.
The concept of [ableism](https://en.wikipedia.org/wiki/Ableism) sometimes seems overblown, but it's not much fun being at a restaurant with nothing on the menu you can eat. There some ideas in the article you could maybe build on. | I shall probably regret this when I see how many points I lose . . .
When there is no suitable word for something, it is time to expand the English language and develop a new word.
I propose the word 'digestic'.
I cannot see any connotations to the word and nobody should be offended by it or embarrassed to say, 'I am digestic'.
There is a word 'dietetic' which is a general term meaning 'concerned with diet and nutrition'. So one could say, 'I have dietetic needs'. |
743,108 | I have a CISCO ASA 5506-X with 4 configured interfaces and a set of access-lists etc. It is configured via CLI and is running in routed mode, not transparent. Everything is running well, but now I have a problem I could not yet solve:
One of the interfaces contains a subnet (192.168.2.\*) with devices that send out a UDP broadcast to discover another kind of devices. Those other devices are in another subnet in another interface (192.168.3.\*). The udp broadcast is global (255.255.255.255) on a certain port.
I want the global UDP broadcast sent out in 192.168.2.\* to also be sent to 192.168.3.\* - and to allow the way back as well, of course.
On other Cisco devices, I already found out that one can do that with `ip helper-address` and `ip forward-protocol` commands - but the ASA models do not support those, as far as I can see.
So, how do I get the global UDP broadcast across the interfaces? | 2015/12/15 | [
"https://serverfault.com/questions/743108",
"https://serverfault.com",
"https://serverfault.com/users/11877/"
] | I think the issues here is that you misunderstand what 255.255.255.255 means. Its not a "global Broadcast". The definition from the RFC (<https://www.rfc-editor.org/rfc/rfc919>):
>
> "The address 255.255.255.255 denotes a broadcast on a local hardware
> network, which must not be forwarded. This address may be used, for
> example, by hosts that do not know their network number and are
> asking some server for it.
> Thus, a host on net 36, for example, may:
>
>
> * broadcast to all of its immediate neighbors by using 255.255.255.255
> * broadcast to all of net 36 by using 36.255.255.255
>
>
>
In your case a host 192.168.3.0/24 sending a broadcast to 255.255.255.255 is saying is please send this to all hosts in 192.168.3.0/24. This is the same as sending a packet to 192.168.3.255.
If a host in .3 wants to send a broadcast to .2 it needs to send a packet to 192.168.2.255. Having broadcasts from .3 rebroadcasted into .2 is essentially saying you want to make them the same subnet whilst keeping them as different subnets. (the common other name for a subnet is a "broadcast domain")
What the `ip helper` and `ip forward-protocol` and the ASAs `dhcprelay` commands do is to capture the **broadcast** packet and forward it as a **unicast** packet to a specific host. normally a remote DHCP server but there are other uses. This is explicitly stated in first paragraph of the Checkpoint doc linked in the previous answer. It could be thought of as a kind of NAT. ie the destination address (255.255.255.255) is changed to a specified unicast IP, 192.168.3.10. and then routed as a normal unicast packet. This works great for DHCP and allows the DHCP server to be in a remote network and still receive and respond to DHCP requests but unfortunately even if the ASA supported the `ip helper` and `ip forward-protocol` commands it still couldn't solve your problem. What your asking violates the RFC and the definition of what a subnet is.
The easiest solution here is to merge the 2 subnets into 192.168.2.0/23 then bridge the 2 interfaces and use the ASA in transparent mode to filter traffic between the 2 sets of hosts.
If you can't do that that then you need to work out a more scalable way for your devices to find each other. Either sending broadcasts to their subnets respective broadcast addresses (192.168.3.255 and 192.168.2.255) or using some other Discovery method. 255.255.255.255 isn't a scalable or flexible solution. | There is no feature for this in the current version (probably for security reasons). Cisco implemented "dhcprelay" instead and didn't provide a means for more general broadcast forwarding.
I'd suggest adding another device outside the ASA FW that could perform the same role (A Cisco router or a Linux machine perhaps). You will need to allow "directed broadcast" through the ASA.
You might also consider using a different firewall platform which does support broadcast relay, for example a Checkpoint Firewall.
Look [here](https://sc1.checkpoint.com/documents/R76/CP_R76_Gaia_Advanced_Routing_AdminGuide/81083.htm) to see how its configured |
18,271,282 | I saw a few questions in stackoverflow, but they all refer to old answers (from 2004) and using hibernate xml mappings.
I am writing an API in Java, which will return products which are stored in the database based on an algorithm.
The API would also get a locale and decide to return the name in the locale language.
Product table:
```
product_id
name
price
```
How should I support internalization?
Should I add `name_en` `name_fr` etc columns?
Or should I create different tables?
How should I return the name in the required locale in Hibernate?
I am using annotations for O/R mapping | 2013/08/16 | [
"https://Stackoverflow.com/questions/18271282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/264419/"
] | Try [bringSubviewToFront](http://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/UIView/UIView.html#//apple_ref/occ/instm/UIView/bringSubviewToFront%3a)
```
[youtView bringSubviewToFront:youtBtn];
``` | Use :
```
[self.view bringSubviewToFront:button];
```
Use your parent view on which buttons are added instead of self.view.
And make sure the order of above code for buttons.
Above code for latest button will come above of all buttons(view). |
17,369 | Is the quest "You Only Die Once a Night" even possible without Celerity? I'm running back and forth between the two gates, and no matter how fast I blast these Zombies heads off, I'm just wasting too much time going back and forth, and they're making it out of the cemetery around the 2 minute mark every time?
I'm playing as a Tremere, so Celerity is off the table as an option. Running Community Patch 7.3 if that's relevant. | 2011/02/28 | [
"https://gaming.stackexchange.com/questions/17369",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/3129/"
] | I just beat it as a Tremere, and it was incredibly difficult. For most of it, I used a pistol, walking up close to each zombie allowing me to pop them in the head, which is a 1-hit kill no matter your firearms skill. At about 1:30 left, things started to get crazy and I ended up having to run back and forth between gates casting Boil blood twice (One cast will not kill all of the zombies). Obviously, I had to chug a few blood packs while I made my way to the other gate to repeat this process. | It's possible. I beat it with Malkavian. What I did was use Auspex and only target the light blue color zombies - those are the only zombie that will attack the gate. and once more than 3 zombie at the gate I drop Mass Hysteria and it stun them long enough for me to run to and back both gates to stun lock them. And clear the timer. |
30,435,134 | I am integrating Map Annotation in my app. I am Adding Annotations on Map as below. All annotations are added successfully on MAP.
```
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
if (annotation is MKUserLocation) {
return nil
}
let reuseId = "CustomAnnotation"
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
annotationView.image = UIImage(named:"MapTemp")
annotationView.canShowCallout = false
return annotationView
}
```
I am showing a customView on click of map annotation. When a annotation is clicked its delegate is called in which custom view is added over map as done in below code-
```
func mapView(mapView: MKMapView!, didSelectAnnotationView view: MKAnnotationView!)
{
if (self.viewCustom != nil)
{
self.viewCustom.removeFromSuperview()
}
let nib:Array = NSBundle.mainBundle().loadNibNamed("View123", owner: self, options: nil)
self.viewCustom = nib[0] as? UIView
println(self.viewCustom.viewWithTag(100))
if let buttonFB = self.viewCustom.viewWithTag(100) as? UIButton {
buttonFB.addTarget(self, action:"clickFacebook:", forControlEvents: UIControlEvents.TouchUpInside)
}
self.addBounceAnimationToView(viewCustom)
var hitPoint : CGPoint = view.convertPoint(CGPointZero, toView: viewCustom)
self.viewCustom!.frame = CGRectMake(-100,-200, 250, 200)
view.addSubview(self.viewCustom!)
self.view.bringSubviewToFront(self.viewCustom)
}
```
Inside the custom view I have a button `buttonFB` specified with a tag value and event `clickFacebook`.
```
@IBAction func clickFacebook(sender: AnyObject)
{
//Face
}
```
but on click event of this button does not triggers and only Mapview's delegate `didDeselectAnnotationView` is always called (below method is called).
```
func mapView(mapView: MKMapView!, didDeselectAnnotationView view: MKAnnotationView!)
{
//
}
```
I want the event of the button to trigger. How can I do that.

darkgray Image is Annotation of MapView and yellow part is button according to image.
Please help me. | 2015/05/25 | [
"https://Stackoverflow.com/questions/30435134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2530594/"
] | After spending hours to try to figure out the problem, I updated R (v 3.2.0) and everything works fine now.
It is not clear if the problem was due to some packages conflict, for sure it wasn't an `RStudio` problem (as I had initially thought). | To add a little to this: It seems to be a bug with the `echo` parameter which defaults to `TRUE`. Setting it to false with `knitr` and `pdfLaTeX` as a renderer worked for me. In case you're in a situation where you can't update because of dependencies and/or rights issues, this input might be a helpful adhoc fix, since the error message is pretty useless. |
15,261,876 | I am normally pretty good with this, but I am having trouble with the `NSDate` object. I need a `NSDate` object set for tomorrow at 8am (relatively). How would I do this and what is the simplest method? | 2013/03/07 | [
"https://Stackoverflow.com/questions/15261876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1740273/"
] | Here's how [WWDC 2011 session 117 - Performing Calendar Calculations](https://developer.apple.com/videos/wwdc/2011/?id=117) taught me:
```
NSDate* now = [NSDate date] ;
NSDateComponents* tomorrowComponents = [NSDateComponents new] ;
tomorrowComponents.day = 1 ;
NSCalendar* calendar = [NSCalendar currentCalendar] ;
NSDate* tomorrow = [calendar dateByAddingComponents:tomorrowComponents toDate:now options:0] ;
NSDateComponents* tomorrowAt8AMComponents = [calendar components:(NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:tomorrow] ;
tomorrowAt8AMComponents.hour = 8 ;
NSDate* tomorrowAt8AM = [calendar dateFromComponents:tomorrowAt8AMComponents] ;
```
Too bad iOS doesn't have `[NSDate dateWithNaturalLanguageString:@"tomorrow at 8:00 am"]`. Thanks, [rmaddy](https://stackoverflow.com/users/1226963/rmaddy), for pointing that out. | **Swift 3+**
```
private func tomorrowMorning() -> Date? {
let now = Date()
var tomorrowComponents = DateComponents()
tomorrowComponents.day = 1
let calendar = Calendar.current
if let tomorrow = calendar.date(byAdding: tomorrowComponents, to: now) {
let components: Set<Calendar.Component> = [.era, .year, .month, .day]
var tomorrowValidTime = calendar.dateComponents(components, from: tomorrow)
tomorrowValidTime.hour = 7
if let tomorrowMorning = calendar.date(from: tomorrowValidTime) {
return tomorrowMorning
}
}
return nil
}
``` |
97,996 | How can an ultra-deep hole or canyon form naturally on an earth like world?
By ultra-deep I’m thinking something like the Marianas Trench but on land and not filled with water.
If it’s not possible why not and what would be a more realistic depth be?
If it is possible how much deeper might it realistically become?
By earth like I mean a world the same as ours, but with any alternative configuration of oceans, continents, tectonic plates and mountains that might be required. The surface configuration can be as you wish but must be plausible geologically even if it might be a very rare occurrence. | 2017/11/15 | [
"https://worldbuilding.stackexchange.com/questions/97996",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/42450/"
] | The fundamental problem is that as the trench becomes deeper and deeper, the walls will tend to crumble because of the hydrostatic pressure pushing sideways. Underwater trenches can be deeper than trenches on land because the pressure of column of water in the trench serves to counter in part the pressure of the column of rock in wall.
Another difficult problem is how to keep the trench free of sediment.
That being said, the deepest canyon in the world is the [Yarlung Tsangpo Grand Canyon](https://en.wikipedia.org/wiki/Yarlung_Tsangpo_Grand_Canyon) in Tibet, with an average depth of about 2.3 km and a maximum depth of over 6 km.
As to the mechanism, this kinds of canyons are formed when a mountain range is risen quickly, for example because the Indian plate crashed into the Asian plate raising the Himalayas; the pre-existing rivers continue to erode their bed keeping it more or less at the elevation it had before the birth of the mountain range. | I would suggest you consider tectonic plates splitting apart. The plates would perhaps have first pushed against each other, and now they are moving away from each other. Of course, the area would be very seismically active. |
102,674 | As a nonnative speaker, I have been curious about the difference between "what car" and "what kind of car". To me, these two seem exactly similar.
For example, when I go to the car dealership, a salesman asks, "what car would you like to buy?" or "what kind of car would you like to buy?"
What is the difference between these two questions? | 2016/09/04 | [
"https://ell.stackexchange.com/questions/102674",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/27282/"
] | Yes, there is a difference.
*What kind of car* involves questions such as the following: Do you want to buy a Kia, an Acura, a BMW, or a Ford? Do you want to by coupe, a sedan, or an SUV? Do you want the car to have a manual or automatic transmission? Do you want two-wheel or four-wheel drive? Etc.
*What car* in your context may mean that you've taken a look at some cars, and the salesman asks you which car, out of all the cars you've seen, you want to buy. Or the salesman simply asks you from the start what car you'd like to buy. He may be assuming that you already know exactly what you want. I think it would make more sense for the salesman to ask, "How can I help you? What kind of car are you looking for?" :-) | The first question asks what particular car (*any* make or model) would you like to buy, and the second question asks what kind of car (a *specific* make or model) would you like to buy.
This is summary of your sentences.
What car would you like to buy? = You would like to buy what car.
You | would like | to buy what car
Subject | verb phrase | noun infinitive phrase and direct object of the verb phrase
*what* is the direct object in the infinitive phrase, and *car* is the objective complement referring back to *what*.
***What***. prn.
: which thing or things
<http://www.merriam-webster.com/dictionary/what>
---
What kind of car would you like to buy? = You would like to buy what kind of car.
You | would like | to buy what kind of car
Same as the first sentence, except now the direct object in the infinitive is *kind*, which is modified by the adjective *what* and prepositional phrase *of car.*
**Kind**. *n*.
*: a particular type or variety of person or thing*
<http://www.merriam-webster.com/dictionary/kind> |
20,613,056 | I'm writing a program with AmMaps where I want a user to click on a map of a country, and to be able to select and save locations.
I'm stuck on getting data back after the user clicks on the map. I used the "clickMapObject" event on another page, but in this case they aren't clicking anything.
```
<script>
var map;
$(document).ready(function () {
map = new AmCharts.AmMap();
map.pathToImages = "ammap/images/";
var dataProvider = {
mapVar: AmCharts.maps.irelandHigh,
getAreasFromMap: false,
};
map.dataProvider = dataProvider;
map.areasSettings = {
autoZoom: false,
color: "#CDCDCD",
colorSolid: "#5EB7DE",
selectedColor: "",
outlineColor: "#666666",
rollOverColor: "#88CAE7",
rollOverOutlineColor: "#FFFFFF",
selectable: false,
};
map.addListener("click", click);
map.write("mapdiv");
function click() {
//Can i get long and lat here?
};
});
</script>
``` | 2013/12/16 | [
"https://Stackoverflow.com/questions/20613056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1098100/"
] | If you really really really want to do it:
```
static_cast<_T*>(this)->f2();
```
As people have mentioned, this is the [curiously recuring template pattern](https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern)! | A base class should have no notion of its children. Attempt to call a child method from base class is a sure sign of bad architecture. Virtual functions will not help you here by the way.
If you **have to** call a child's function from the base class you can do so just like you would do from any other function in your code. Still you will need an instance of the base class to call it on or alternatively you will have to `static_cast` the `this` pointer to a pointer of the child class type. This is a very bad idea! |
185,870 | In fiction, beings that can change shape can do so extremely rapidly and are immediately able to function in their new shape. While there is some precedent for the latter in nature (butterflies can *fly* more or less on emergence from their cocoon, and most ungulates can run within hours of birth), these critters are "hard-wired" for such feats.
On the other end, humans take months to years to learn to walk in childhood, or when recovering from major injury or very long periods of inactivity. (The scene from Kill Bill where manages to go from virtual immobility after months of being in a coma to driving a truck in the span of perhaps an hour is, at least in my experience, considered extremely unrealistic.)
Let's say we have a creature which has the ability to alter its form significantly. Body proportions and distribution of mass are considerably altered, perhaps even mass is significantly altered, such that the creature's balance and coordination is significantly different. How long, realistically, would it take the creature to learn to move again?
Rules:
* Although a lot has changed, the creature's nervous system remains its own (unlike in [this question](/questions/92664)); senses are mostly unaffected and nerves still control the same muscles. The creature is *clumsy* but not totally incapable of movement; it still has good control of *what* muscles move, they just tend to move too much or too little, and/or it needs to move in a way it isn't used to moving.
* The transformation takes about a month, but the creature is mostly sessile during this time. It has some very limited opportunity to move its limbs, but little or no opportunity to move around. (At least it doesn't need to re-learn how to *breathe*... that would end badly!) The transformation isn't necessarily permanent, but it's going to be keeping the new form for a while (months, at least; given it essentially "loses a month" every time it changes, it's not going to be doing this all the time!).
* The creature can't simply rewire itself to know how to move immediately. It doesn't have that ability, and didn't have that ability as an infant; it had to learn to walk the first time much like a human does. However, after the transformation, it does have the neurological malleability of a very young child.
* The creature was bipedal and wants to be bipedal again. The new form is reasonably suitable (about as much as, say, a two-year-old human) for bipedal locomotion.
* For the most part, the creature is moving around about as much as an average human toddler (it *is* a toddler after all, at least in the literal sense!) that will naturally help it improve, but isn't specifically focused on doing so. However, it is also engaging in 1-2 hours of daily targeted exercises designed to improve balance and coordination.
Now, it probably goes without saying that this will be a long process and "success" is fuzzy. So for the sake of being able to give a reasonable answer, let's say that I am specifically interested in how long until the creature can walk (bipedally!) with only occasional falls. Let's also say I'm specifically interested in *the first time* it tries to master a(ny) new form; as [Willk](/users/31698) [rightly observes](/a/185879/43697), the situation might improve dramatically with practice.
(Note: I've tried looking for information on *humans* learning to walk, but while it's trivial to find information on when we *start* walking, it's much harder to find information on milestones once they start. The only source I managed to find was [a youtube video](https://www.youtube.com/watch?v=x7u_dgRmVcI) that gives six months from first steps to running. Is this reasonably accurate? Is this even a reasonable model for the situation of my creature? Would it be plausible for my creature to get to the "usually doesn't fall over" stage quicker; say, in a month? Running can take longer; I just want walking without falling over.) | 2020/09/19 | [
"https://worldbuilding.stackexchange.com/questions/185870",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/43697/"
] | ### 3 weeks.
I had the misfortune of recently having a condition known as "Bells Palsy". Its when nerves on half of your face seize up and you loose control of many of your facial muscles. I looked like a stroke victim.
I had a week with a totally paralysed half face (couldn't even shut my left eye to sleep), about 3 days of mad twitching as the nerves started to recover. And then about 3 weeks where the muscles worked individually and would respond if I focused on them, but I couldn't use them right anymore.
3 weeks of slurred speech, biting my lips when eating, spilling liquid while drinking, winking at inappropriate times, lopsided smiling, kissing partner feeling wrong, cutting myself while shaving cause I couldn't keep the skin taught, and crying from one eye cause I'd stared at a computer for hours and forgotten to blink that one.
After 3 weeks of being not in control of my functional face, I got it back. It was gradual and I didn't really notice I was improving at the time, I could only see the improvement in hindsight (oh yeah I haven't droolled toothpaste for a few days now. Nice!)
Your shapeshifter will go through a similar process. They have the nerve connections, they can make any individual muscle work by focusing on it, and they know the process and sequence they need to do to accomplish a task. I estimate itll take them about 3 weeks of messing up before they can pass for normal again. | I'm going to post this as an answer rather than a post-mortem, as it's going to be on the lengthy side. Thank you everyone that answered! I consider all of the answers *useful*, and most were helpful. (Willk's is the exception because it operates on an incorrect assumption, which was totally my fault. As I already noted, however, it's still a correct and useful answer, just not applicable to my very specific situation.)
I've *accepted* [this answer](/185883/43697) because it explores a real life scenario with I think is most closely parallel to my fictional situation, and thus clearly meets the "most helpful" criteria for acceptance. Again, it isn't my intent to take away from any of the existing answers, but only to give a more detailed summary of where I ended up in case it's useful to anyone.
---
I try to ask questions in a way that is more general, in order to attract answers that are more general, and thus more likely to be useful outside of the extremely specific situation that actually pertains to a particular story. (This is why I still value Willk's answer.) That said, for the very specific case that actually pertains to my story, and that apply to this answer, I can additionally state that:
* This is the first time the creature has changed forms. This means it doesn't have the benefit of any prior practice.
* The transformation involves alteration of total mass and of mass distribution, but *not* a radical change in style of locomotion. We're talking about something like the difference between an infant and an adult, or a chihuahua and a mastiff, not the difference between a horse and a human (or, even worse, a cat and a sparrow).
* The transformation process is able to subvert muscular atrophy from disuse; it isn't having to build muscle mass *on top* of rewiring its reflexes.
As far as "learning to walk" and my target level of locomotion, we have on the one hand humans, which would need 2-3 years from birth, while ruminants on the other hand can, if we ignore bipedalism, manage in *hours*. Bipedal locomotion is harder, but also our creature has done it before, so we can probably consider that a wash. We can probably also cut down on the human time because the critter isn't also having to deal with a lack of muscular and skeletal strength. (For the same reason, while we shouldn't ignore Otkin's answer, we can probably similarly cut down on the 3-6 month time a bit; a human in the sort of situation Otkin cites is also dealing with atrophy.) Thus, Ash and Trioxidane are probably on the right track.
Accordingly, **3-5 weeks** for "mostly competent" functionality seems plausible. However, it also seems reasonable that it will take years before the creature is completely competent in the new form to the extent that there are no remaining observable effects from the change. |
261,655 | I have a list of tuples like this:
```
[
('a', 1),
('a', 2),
('a', 3),
('b', 1),
('b', 2),
('c', 1),
]
```
I want to iterate through this keying by the first item, so, for example, I could print something like this:
```
a 1 2 3
b 1 2
c 1
```
How would I go about doing this without keeping an item to track whether the first item is the same as I loop around the tuples? This feels rather messy (plus I have to sort the list to start with)... | 2008/11/04 | [
"https://Stackoverflow.com/questions/261655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18909/"
] | Slightly simpler...
```py
from collections import defaultdict
fq = defaultdict(list)
for n, v in myList:
fq[n].append(v)
print(fq) # defaultdict(<type 'list'>, {'a': [1, 2, 3], 'c': [1], 'b': [1, 2]})
``` | A solution using groupby
```
from itertools import groupby
l = [('a',1), ('a', 2),('a', 3),('b', 1),('b', 2),('c', 1),]
[(label, [v for l,v in value]) for (label, value) in groupby(l, lambda x:x[0])]
```
Output:
```
[('a', [1, 2, 3]), ('b', [1, 2]), ('c', [1])]
```
`groupby(l, lambda x:x[0])` gives you an iterator that contains
```
['a', [('a', 1), ...], c, [('c', 1)], ...]
``` |
89,405 | I am flying from the US in May and I have a golfing size umbrella as a souvenir which I want to bring back but I already have 2 luggages and can't bring the umbrella as a carry on for safety reasons. Will they allow it be checked it in? | 2017/03/07 | [
"https://travel.stackexchange.com/questions/89405",
"https://travel.stackexchange.com",
"https://travel.stackexchange.com/users/58317/"
] | Ok, so I have done some research and so far cheapest way is to get a Revolut card.
On 504 USD from EUR, the exchange loss was 2.19 EUR compared to the rate at Google (Google rate is 475.85, Revolut 478.04) which is way better than I would get at any local bank in UK.
The bank of choice is [Union Commercial bank](https://www.google.co.uk/maps/place/Union+Commercial+Bank/@10.6223518,103.5255065,18.75z/data=!4m5!3m4!1s0x0:0x641f92e6467838a1!8m2!3d10.6234334!4d103.5253092). They allow you to take out 500$ and charge 4$ on top which is the cheapest that I could find so far, also this is the only bank that worked with Revolut MasterCard and Maestro Card.
Also watch your step at their ATM they have a nasty step there...
**Update:** Union Commercial ATM started breaking down almost daily. An alternative is to use [Canadia Bank ATM](https://www.google.com.kh/maps/place/Canadia+Bank/@10.6235577,103.5227157,17z/data=!3m1!4b1!4m5!3m4!1s0x3107e1c6b896bd69:0x5e4459e7db770e36!8m2!3d10.6235577!4d103.5249044) (which is across the street) which charges 5$ and you can take out 500$ -- tested with MasterCard and Maestro. | Last time I was in Cambodia, which was a few years ago, Vattanak Bank was free, for European cards only. As the article says Canadia used be free but that was some years ago. According to the article you linked though, Maybank is still free, so I'd give them a go.
I have never paid an ATM fee in Cambodia, I was always able to find a bank that worked with no fees. They change all the time though. |
44,826,568 | Users owns licenses, and a plan is a combination of licenses.
Sometimes a user owns an individual license, which is not part of a plan.
I want to count the number of users per plan. In the exemple below, it should return :
```
PlanName | Number of Users
P1 | 1
P2 | 2
```
Tables :
```
Users Licenses Plans
----------------- --------------------- ----------------
Username | UserID LicenseName|LicenseID PlanName|PlanID
user1 | 1 L1 | 1 P1 | 1
user2 | 2 L2 | 2 P2 | 2
user3 | 3 L3 | 3
user4 | 4 L4 | 4
L5 | 5
UsersAndLicenses PlansAndLicenses
---------------- ----------------
UserID | LicenseID PlanID | LicenseID
1 | 1 P1 | 1
1 | 2 P1 | 2
1 | 3 P1 | 3
2 | 4 P2 | 4
2 | 5 P2 | 5
3 | 1
4 | 4
4 | 5
```
I started with a select to get the list of users and plans (I will apply a count on this select) and I get an issue : user3 who has only L1 (he hasn't a plan) is listed in P1 (L1 is part of P1). My select statement is :
```
SELECT Plans.PlanName, Users.UserName FROM Users
INNER JOIN (((Licenses INNER JOIN LicensesPlans ON Licenses.LicenseID = LicensesPlans.LicenseID)
INNER JOIN Plans ON LicensesPlans.PlanID = Plans.PlanID)
INNER JOIN UsersLicenses ON Licenses.LicenseID = UsersLicenses.LicenseID) ON Users.UserID = UsersLicenses.UserID
GROUP BY Plans.PlanName, Users.UserName;
```
What is wrong with my select ? | 2017/06/29 | [
"https://Stackoverflow.com/questions/44826568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8231785/"
] | I think you're printing the whole response, when really you want to drill down and get elements inside it. Try this:
```
print(info[0]["faceAttributes"]["glasses"])
```
I'm not sure how the API works so I don't know what your specified params are actually doing, but this should work on this end.
EDIT: Thank you to @Nuageux for noting that this is indeed an array, and you will have to specify that the first object is the one you want. | This looks more like a dictionary than a list. Dictionaries are defined using the { key: value } syntax, and can be referenced by the value for their key. In your code, you have `faceAttributes` as a key that for value contains another dictionary with a key `glasses` leading to the last value that you want.
Your info object is a list with one element: a dictionary. So in order to get at the values in that dictionary, you'll need to tell the list where the dictionary is (at the head of the list, so info[0]).
So your reference syntax will be:
```
#If you want to store it in a variable, like glass_var
glass_var = info[0]["faceAttributes"]["glasses"]
#Or if you want to print it directly
print(info[0]["faceAttributes"]["glasses"])
```
What's going on here? info[0] is the dictionary containing several keys, including `faceAttributes`,`faceId` and `faceRectangle`. `faceRectangle` and `faceAttributes` are both dictionaries in themselves with more keys, which you can reference to get their values.
Your printed tree there is showing all the keys and values of your dictionary, so you can reference any part of your dictionary using the right keys:
```
print(info["faceId"]) #prints "0f0a985e-8998-4c01-93b6-8ef4bb565cf6"
print(info["faceRectangle"]["left"]) #prints 177
print(info["faceRectangle"]["width"]) #prints 162
```
If you have multiple entries in your info list, then you'll have multiple dictionaries, and you can get all the outputs as so:
```
for entry in info: #Note: "entry" is just a variable name,
# this can be any name you want. Every
# iteration of entry is one of the
# dictionaries in info.
print(entry["faceAttributes"]["glasses"])
```
Edit: I didn't see that info was a list of a dictionary, adapted for that fact. |
413,915 | I have a df which looks like that:
| ID | Happy |
| --- | --- |
| 0 | Very |
| 1 | Little |
I'm trying to convert it into an attribute table:
```
headers = [col for col in df.columns]
fieldlist = QgsFields()
fieldlist.append(QgsField(headers[0],QVariant.Int))
for name in headers[1:]:
fieldlist.append(QgsField(name, QVariant.String))
for i in df.index.to_list():
featur = QgsFeature()
newrow = df[headers].iloc[i].tolist()
featur.setAttributes(newrow)
sink.addFeature(featur,QgsFeatureSink.FastInsert)
```
Although I get this error:
>
> Feature could not be written to
> Output\_layer\_9a58cfa4\_ee1e\_4b97\_a6e8\_dfc0410a280a: Could not store
> attribute "ID": Could not convert value "" to target type
>
>
>
Why do I get this even though I state that the first column (`QgsField`) has numbers and the others have Strings? | 2021/10/14 | [
"https://gis.stackexchange.com/questions/413915",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/187914/"
] | My suggested process is to run a Minimum Bounding Geometry, rectangle by width across the buildings to get a polygon with four corners. Connect the four corners in a cross (using a script). Finally clip the cross with the building footprint to ensure the crossed lines are only within the building footprint.
The script should look something like this:
```
import os
import arcpy
"""Draw diagonal lines across rectangle."""
in_features = 'PathToYourPolygons'
out_feature_class = 'PathToCrossPolylines'
desc = arcpy.Describe(in_features)
path, name = os.path.split(out_feature_class)
# Create output feature class
arcpy.management.CreateFeatureclass(
path, name, geometry_type="POLYLINE",
spatial_reference=desc.spatialReference)
# Add a field to transfer FID from input
arcpy.management.AddField(out_feature_class, "ORIG_FID", "LONG")
search_fields = ["SHAPE@", "OID@"]
insert_fields = ["SHAPE@", "ORIG_FID"]
with arcpy.da.SearchCursor(in_features, search_fields) as search_cur:
with arcpy.da.InsertCursor(out_feature_class, insert_fields) as insert_cur:
for row in search_cur:
geometry = row[0].getPart(0)
for i in range(2):
point1 = geometry[i]
point2 = geometry[i+2]
polyline = arcpy.Polyline(arcpy.Array([point1, point2]))
insert_cur.insertRow([polyline, row[1]])
``` | Variation of Mark answer, but without scripting. So, convert minimum bounding rectangles to vertices and select them by attribute:
```
mod( "OBJECTID",5)=1 OR mod( "OBJECTID",5)=3
```
It will select 2 opposite corners of individual rectangles, because each is made of 5 points. Use points to line tool with ORIG\_FID being line identifier, to create first diagonal. You'll need few more steps, because original polygons can have irregular shape:
* clip diagonals
* sort them in descending order by length
* delete identical for ORIG\_FID.
[](https://i.stack.imgur.com/9HcjR.png)
Proceed with second diagonal and merge results if necessary. |
219,184 | I am using a desktop with a wired connection. I can use Skype, surf the web. I can login to Steam on the browser.
I can't connect to League of Legends (logging in gives me a "Can't connect to maestro server" error). I can't connect to Steam (which gives me a "Can't connect to servers. Check your connection." error). I have flushed my DNS, checked proxy settings, checked internet settings (IPv4 DNS config), renewed IP, even checked hosts file.
On the other hand I can somehow play Hearthstone. On a laptop with a wireless connection I can login to League and Steam.
Any ideas? | 2015/05/12 | [
"https://gaming.stackexchange.com/questions/219184",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/112594/"
] | According to the League of Legends Forums ([here](http://forums.na.leagueoflegends.com/board/showthread.php?t=2648025)) you can try this:
Some sort of Maestro Error
--------------------------
1. Restart your computer
2. Temporarily Disable/Make exceptions in your Anti-virus/Anti-spyware software
3. Temporarily Disable/Make exceptions in your Firewall
4. Disable process protection software.
5. Make sure you're running software in Administrative Mode/With admin privileges
6. In Windows Vista/Windows 7, double check your Account Controls
7. Reset your Internet Explorer Settings and make sure you have not disabled scripting options
One person solved it by going to
>
> C:\Riot Games\League of Legends\RADS\projects\lol\_air\_client\releases\0.0.0.237\deploy
>
>
>
and setting LolClient.exe to run as admin.
One person updated Windows by running Windows Update and the problem was solved.
It's quite a common error and many people have odd ways of solving it. But since LoL and Steam don't connect I assume it's strictly connection or permissions.
**EDIT**:
[Here's](https://www.youtube.com/watch?v=8FoXZ0kl2RM) a video that explains how to fix the problem. (He explains the Maestro Error at 2 min 24 sec. It has to do with Anti-Virus ;) )
I've had this happen to me and it was the Anti-Virus I was running (Kaspersky btw). I tried white-listing it on the firewall, Virus list EVERYTHING and it still didn't work. The only way I managed it to work was to play with the Anti-Virus turned off. (But this was my personal case).
**END EDIT**
If you can solve it for LoL you will most likely solve it for Steam.
I wish you good luck! and I hope that I gave you some good things to try and fix the problem since we never know for sure what the solution is. | That thing happend to me before and there is MANY reasons why you can't connect to maestro server but you have to check 1 thing right now it might be sound but most people even programmers Don't check it first.
(Register The one and the only)
No matter how many times you will delete a file or reinstall it
as long the Register files are passed in the windows folder.
IT'S GAME OVER already if you have no idea how to check it.
The way to do it's kinda hard AND if you do 1 mistake and you happend to delete wrong files that happend your windows to use them
(you might wana re-install windows for GOOD because your pc wont be the same it used to be)
kind of advice? DON'T TOUCH REGISTER FILES if you dont know where to look
and i'll be honest even i have no IDEA where is the file you have to locate because of Riot.
Every time they update the game new stuff they put in register and i belive that 1 old files from register might stuck with others.
What you have to do?
1) Because riot might NOT help you instally and they will ask you many things and even if you do them they will ask you to repeat them again and again.
2) instead trying to find any clue about where to find the files... instead go and download CCleaner and run a clean up register all files gona be removed *EXPECT windows files* that are NOT connected with the file location. Don't worry you can keep a back up so nothing bad will happend
!!! BUT first run it before you uninstall the game to see IF by chance it will work and if that won't work Then unistall it !!!
3) If nothing work Grab a hammer, scream "IT'S HAMMER TIME" and start hammering your pc Hard. after that try to start your pc, if your pc is still working... Repeat 3rd stage again XD (sorry mate could not resist) |
214,611 | To me, as a macroscopic observer of light, it appears that light moves in straight lines. If I shine a light at object A and object B moves between me and object A, the light hits, i.e. gets blocked by object B and no longer hits object A.
However, since light is a transverse wave, doesn't that mean it is oscillating back and forth in space in a dimension perpendicular to its direction of travel? If so, then perhaps it only appears to move in straight lines because of low amplitude or high frequency?
Thus, say there was a radio wave with a wavelength of 1 meter. Could this radio wave then dodge around object B and still hit object A, assuming object B is smaller than 1 meter, say a basketball? | 2015/10/26 | [
"https://physics.stackexchange.com/questions/214611",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/96629/"
] | >
> Thus, say there was a radio wave with a wavelength of 1 meter. Could this radio wave then dodge around object B and still hit object A, assuming object B is smaller than 1 meter, say a basketball?
>
>
>
Waves of large wave lengths can indeed 'wash around' an object that is sufficiently smaller than the wave lengths, a phenomenon called *diffraction*.
[Have a look at the animation embedded in this link](http://www.acoustics.salford.ac.uk/feschools/waves/diffract.php#object) and play around with object size to see the effect. For *large wavelength to object size ratios* the waves down stream from the object are practically undisturbed. It's as if the wave 'doesn't see' the object.
We exploit the inverse effect in electron microscopy to see very small objects, much smaller than the wavelengths of visible light. Electron waves allow to achieve much smaller wavelengths and allows to see much smaller objects.
The importance of [Long Wave radio waves for similar reasons is explained in this link](http://www.acoustics.salford.ac.uk/feschools/waves/diffract2.php#radiotv).
Whether the waves are of transversal or longitudinal character is irrelevant here: sound waves (longitudinal) show diffraction too. | [Aragos or Poisson spot](https://en.wikipedia.org/wiki/Arago_spot)
During the 19th century scientists were still undecided if light is a wave
phenomenon or consisting of particles. Poisson thought he refuted the wave
theory by predicting correctly that a bright point should appear in the middle
of a shadow if the light and the object are prepared in a specific way.
Arago actually tried this and saw the "impossible" spot:
[](https://i.stack.imgur.com/gT3iD.jpg) |
9,066,640 | Hi I have a like box on my website scoreoid.net which already has 97 likes I'm using the Open Graph API however my Facebook is not showing the same amount of likes. I'm not sure why is it possible to have both the site and the Facebook company page match makes no sense that there different. | 2012/01/30 | [
"https://Stackoverflow.com/questions/9066640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1178416/"
] | The first `if` statement looks good - you're checking to see if the longitude of the point lies within the longitude of the polygon segment.
The second `if` should be interpolating the intercept of the segment with the exact longitude of the point, and determining if that intercept is above or below the point. I don't think that is what it is doing, due to a simple typo.
```
if (polygon[i][1]+(lon-polygon[i][0])/(polygon[j][0]-polygon[i][0])*(polygon[j][1]-polygon[i][1])<lat){
^
```
You should also include a separate case when `polygon[i][0]==polygon[j][0]` so that you don't get a divide-by-zero error. | You can use my clone of the libkml variant which I have mirrored in github here: <https://github.com/gumdal/libkml-pointinpolygon>
With help of the author of this open source, a module is designed which will indicate whether the given point is inside the KML polygon or not. Make sure that you check the branch "libkml-git" and not the "master" branch of the git sources. The class you would be interested in is "pointinpolygon.cc". It is C++ source code which you can include inside your project and build it along with your project.
**Edit** - The solution for point in polygon problem is independent of what map it is overlayed on. |
10,344,316 | i have already read the spring social document but the part of configuration is Java based, but my project's configuration is xml based. so please tell me how config spring social in spring xml config file. thank you and sorry for my poor english | 2012/04/27 | [
"https://Stackoverflow.com/questions/10344316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1360170/"
] | You need call the containableBehaivor on your model
```
<?php
class Item extends AppModel {
public $actsAs = array('Containable');
}
```
in your controller you can make the query
```
$items = $this->Item->find('all', array(
'contain'=>array(
'ItemDetail',
'Category'=>array(
'conditions'=>array('Category.item_category_id'=>1)
),
'Favorite'=>array(
'conditions'=>array('Favorite.member_id'=>8)
)
)
);
$this->set('test', $items);
```
try using [Joins](http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html)
```
$items = $this->Item->find('all', array(
'joins' => array(
array(
'table' => 'categories',
'alias' => 'Category',
'type' => 'inner',
'conditions'=> array('Category.item_category_id' => 1)
),
array(
'table' => 'favorites',
'alias' => 'Favorite',
'type' => 'inner',
'conditions'=> array('Favorite.member_id' => 8, 'Item.id = Favorite.item_id')
)
),
'contain'=>array('ItemDetail','Category','Favorite')
);
$this->set('test', $items);
``` | You could also try something like this:
```
$this->Item->hasMany['Favorite']['conditions']['member_id'] = 8;
```
Which has the same effect as rebinding the model with the condition.
Just a possible issue. The above will add the condition for the rest of the request, if you want to rollback to the previous behavior, you need to unset the condition:
```
unset($this->Item->hasMany['Favorite']['conditions']['member_id']);
```
Remember to set the $this->Item->recursive property to the desired value ([recursive attribute](http://book.cakephp.org/2.0/en/models/model-attributes.html#recursive)). The default it's 1, which it's the minimum you need for this to work. |
273,450 | Has anybody implemented a feature where if the user has not touched the screen for a certain time period, you take a certain action? I'm trying to figure out the best way to do that.
There's this somewhat-related method in UIApplication:
```
[UIApplication sharedApplication].idleTimerDisabled;
```
It'd be nice if you instead had something like this:
```
NSTimeInterval timeElapsed = [UIApplication sharedApplication].idleTimeElapsed;
```
Then I could set up a timer and periodically check this value, and take some action when it exceeds a threshold.
Hopefully that explains what I'm looking for. Has anyone tackled this issue already, or have any thoughts on how you would do it? Thanks. | 2008/11/07 | [
"https://Stackoverflow.com/questions/273450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/544/"
] | Here's the answer I had been looking for:
Have your application delegate subclass UIApplication. In the implementation file, override the sendEvent: method like so:
```
- (void)sendEvent:(UIEvent *)event {
[super sendEvent:event];
// Only want to reset the timer on a Began touch or an Ended touch, to reduce the number of timer resets.
NSSet *allTouches = [event allTouches];
if ([allTouches count] > 0) {
// allTouches count only ever seems to be 1, so anyObject works here.
UITouchPhase phase = ((UITouch *)[allTouches anyObject]).phase;
if (phase == UITouchPhaseBegan || phase == UITouchPhaseEnded)
[self resetIdleTimer];
}
}
- (void)resetIdleTimer {
if (idleTimer) {
[idleTimer invalidate];
[idleTimer release];
}
idleTimer = [[NSTimer scheduledTimerWithTimeInterval:maxIdleTime target:self selector:@selector(idleTimerExceeded) userInfo:nil repeats:NO] retain];
}
- (void)idleTimerExceeded {
NSLog(@"idle time exceeded");
}
```
where maxIdleTime and idleTimer are instance variables.
In order for this to work, you also need to modify your main.m to tell UIApplicationMain to use your delegate class (in this example, AppDelegate) as the principal class:
```
int retVal = UIApplicationMain(argc, argv, @"AppDelegate", @"AppDelegate");
``` | Actually the subclassing idea works great. Just don't make your delegate the `UIApplication` subclass. Create another file that inherits from `UIApplication` (e.g. myApp). In IB set the class of the `fileOwner` object to `myApp` and in myApp.m implement the `sendEvent` method as above. In main.m do:
```
int retVal = UIApplicationMain(argc,argv,@"myApp.m",@"myApp.m")
```
et voilà! |
1,644,656 | Suppose $x$ and $y$ are some integers satisfying $$x^2-16=y^3.$$ I'm trying to show that $x+4$ and $x-4$ are both perfect cubes.
I know that the greatest common divisor of $x+4$ and $x-4$ must divide $8$, but I don't know where to go from there. Would anyone be able to help? | 2016/02/07 | [
"https://math.stackexchange.com/questions/1644656",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/304680/"
] | If prime $p$ divides $x^2-16=(x+4)(x-4),$
$p^3$ must divide $(x+4)(x-4)$
But if $p$ divides both, $p$ must divide $x+4-(x-4)=8$
So, if $p>2,p^3$ must divide exactly one of $x+4,x-4$
For $p=2,$
if the highest power of $2$ that divides $x+4$ is $a$ and $x+4=c2^a$ where $c$ is odd
If $a>3, x-4=8(c2^{a-3}-1),$ then $3$ must divide $a$
If $a<3, x-4=2^a(c-2^{3-a}),$ then $3$ must divide $2a$
If $a=3, x-4=2^a(c-1),$ then $c-1,c$ must be perfect cube which is possible iff $c=0,1$
Hence we are done. | We rewrite the equation as $(x-4)(x+4)=y^3$. We know that $\gcd(x-4,x+4) \mid 8$, so for every prime $p>2$ the factors $p$ are either in $x-4$ or $x+4$.
If $y$ is even, at least one of $x-4$ and $x+4$ is divisble by 4, and hence they are both divisible by 4. But then $4 \mid y$, so one of them is divisible by 8 and hence they are both divisible by 8. Then one has a factor 8 and the other has all other factors two.
If $y$ is odd, we don't have any factors 2. |
2,186,525 | This is what I have:
```
glob(os.path.join('src','*.c'))
```
but I want to search the subfolders of src. Something like this would work:
```
glob(os.path.join('src','*.c'))
glob(os.path.join('src','*','*.c'))
glob(os.path.join('src','*','*','*.c'))
glob(os.path.join('src','*','*','*','*.c'))
```
But this is obviously limited and clunky. | 2010/02/02 | [
"https://Stackoverflow.com/questions/2186525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/169175/"
] | Here is my solution using list comprehension to search for **multiple** file extensions **recursively** in a directory and all subdirectories:
```
import os, glob
def _globrec(path, *exts):
""" Glob recursively a directory and all subdirectories for multiple file extensions
Note: Glob is case-insensitive, i. e. for '\*.jpg' you will get files ending
with .jpg and .JPG
Parameters
----------
path : str
A directory name
exts : tuple
File extensions to glob for
Returns
-------
files : list
list of files matching extensions in exts in path and subfolders
"""
dirs = [a[0] for a in os.walk(path)]
f_filter = [d+e for d in dirs for e in exts]
return [f for files in [glob.iglob(files) for files in f_filter] for f in files]
my_pictures = _globrec(r'C:\Temp', '\*.jpg','\*.bmp','\*.png','\*.gif')
for f in my_pictures:
print f
``` | I modified the top answer in this posting.. and recently created this script which will loop through all files in a given directory (searchdir) and the sub-directories under it... and prints filename, rootdir, modified/creation date, and size.
Hope this helps someone... and they can walk the directory and get fileinfo.
```
import time
import fnmatch
import os
def fileinfo(file):
filename = os.path.basename(file)
rootdir = os.path.dirname(file)
lastmod = time.ctime(os.path.getmtime(file))
creation = time.ctime(os.path.getctime(file))
filesize = os.path.getsize(file)
print "%s**\t%s\t%s\t%s\t%s" % (rootdir, filename, lastmod, creation, filesize)
searchdir = r'D:\Your\Directory\Root'
matches = []
for root, dirnames, filenames in os.walk(searchdir):
## for filename in fnmatch.filter(filenames, '*.c'):
for filename in filenames:
## matches.append(os.path.join(root, filename))
##print matches
fileinfo(os.path.join(root, filename))
``` |
38,846,414 | I was trying to write a small perl script to understand `Getopt::Long`.
Below is the script:
```
#!/usr/bin/perl
use strict;
use Getopt::Long;
my $op_type = "";
my @q_users;
GetOptions (
'query' => $op_type = "query",
'create' => $op_type = "create",
'modify' => $op_type = "modify",
'delete' => $op_type = "delete",
'user=s' => \@q_users
) or usage ("Invalid options.");
print "operation : $op_type\n";
```
When i ran this script as shown below:
```
$ ./all_opt.pl --query
operation : delete
```
I am assuming that am missing some kind of break statment in my program. I was expecting `operation : query` as the result.
Please let me know what i am missing here. | 2016/08/09 | [
"https://Stackoverflow.com/questions/38846414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1984289/"
] | You were very close, but I think you slightly misread the [Getopt::Long documentation](https://metacpan.org/pod/Getopt::Long). Any code that you want to run when an option is found needs to be in a subroutine.
```
#!/usr/bin/perl
use strict;
use Getopt::Long;
my $op_type = "";
my @q_users;
GetOptions (
'query' => sub { $op_type = 'query' },
'create' => sub { $op_type = 'create' },
'modify' => sub { $op_type = 'modify' },
'delete' => sub { $op_type = 'delete' },
'user=s' => \@q_users
) or usage ("Invalid options.");
print "operation : $op_type\n";
```
Note that I've just added `sub { ... }` around your existing `$op_type = '...'` code. | **Explanation of what your code does**
You are misunderstanding the syntax. Let's add some parenthesis to clarify how Perl sees this code.
```
GetOptions(
'query' => ( $op_type = "query" ),
'create' => ( $op_type = "create" ),
'modify' => ( $op_type = "modify" ),
'delete' => ( $op_type = "delete" ),
'user=s' => \@q_users
) or usage ("Invalid options.");
```
It will first run the assignment operations inside the parens. Each of those return the value that is assigned to `$op_type`.
```
$ perl -e 'print $foo = "bar"'
bar
```
Since all of them assign something to the same variable, the code is identical to this code.
```
GetOptions(
'query' => "query",
'create' => "create",
'modify' => "modify",
'delete' => "delete",
'user=s' => \@q_users
) or usage ("Invalid options.");
$op_type = "delete";
```
`GetOptions` wants you to pass references to variables so it can assign values to the variables for you. But you are doing that only for `user` with `\@q_users`. The rest of them is just strings.
In the end, you are printing the value of `$op_type`, which always has the value of the last assignment. As we saw above, that's *delete*. It cannot be anything else, because `GetOptions` never gets a reference to `$op_type`, so it cannot assign. |
765,090 | I believe that the best way to save your application state is to a traditional relational database which most of the time its table structure is pretty much represent the data model of our system + meta data.
However other guys in my team think that today it's best to simply serialize the entire object graph to a binary or XML file.
No need to say (but I'll still say it) that World War 3 is going between us and I would like to hear your opinion about this issue.
Personally I hate serialization because:
1. The data saved is adhered only to your development platform (C# in my case). No other platforms like Java or C++ can use this data.
2. Entire object graph (including all the inheritance chain) is saved and not only the data we need.
3. Changing the data model might cause severe backward compatibility issues when trying to load old states.
4. Sharing parts of the data between applications is problematic.
I would like to hear your opinion about that. | 2009/04/19 | [
"https://Stackoverflow.com/questions/765090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55373/"
] | For transfer and offline storage, serialization is fine; but for active use, some kind of database is far preferable.
Typically (as you say), without a database, you need to deserialize the entire stream to perform any query, which makes it hard to scale. Add the inherent issues with threading etc, and you're asking for pain.
Some of your other pain points about serialization aren't all true - as long as you pick wisely. Obviously, `BinaryFormatter` is a bad choice for [portability and versioning](http://marcgravell.blogspot.com/2009/03/obfuscation-serialization-and.html), but "[protocol buffers](http://code.google.com/p/protobuf/)" (Google's serialization format) has versions for Java, C++, [C#](http://code.google.com/p/protobuf-net/), and a [lot of others](http://code.google.com/p/protobuf/wiki/OtherLanguages), and is designed to be version tolerant. | Yes propably true. The downside is that you must retrieve the whole object which is like retrieving all rows from a table. And if it's big it will be a downside. But if it ain't so big and with my hobbyprojects they are not, so maybe they should be a perfect match? |
96 | I have deleted a validation rule in my dev environment. Is there any way to comunicate this through a change set to our QA environment or will this have to be done manualy? | 2012/08/01 | [
"https://salesforce.stackexchange.com/questions/96",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/43/"
] | Using the ANT-based [Force.com Migration Tool](http://www.salesforce.com/us/developer/docs/daas/index.htm) you can build deployments that can add, change or delete objects as well as test changes. The download comes with a sample build.xml file and has an entry for removing code. You will have to build an XML file describing what needs to happen, though this can be generated by the Force.com IDE if you use it. | I prefer change sets over Ant, but as Mike Chale pointed out, you lose the ability to handle any form of deletes and even renaming of picklist values. I keep track of these in Evernote and reproduce them in Production during deployment. |
19,339,022 | I have a lot of constant variables in my application. In this application I import a module. As part of testing I would like to call from a function in said imported module that prints out the variable's name and their values.
OK so this is not my code but this shows the concept of what I would like to do:
```
-main.py-
import mymodule
DEBUG = True
BATCH = False
ShowVars(['DEBUG','BATCH'])
-mymodule.py-
def ShowVars(varlist):
for name in varlist:
print('{} -> {}').format(name,eval(name))
```
I get at error at the eval(name) that 'DEBUG is not defined' of course but I am trying to get this concept working.
One way I found is to change main.py as:
```
-main.py-
import mymodule
DEBUG = True
BATCH = False
mymodule.DEBUG=DEBUG
mymodule.BATCH=BATCH
ShowVars(['DEBUG','BATCH'])
```
Then things work but I'm not sure I like it... Any ideas or anecdotes would be appreciated. | 2013/10/12 | [
"https://Stackoverflow.com/questions/19339022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34475/"
] | Using [`inspect` module](http://docs.python.org/2/library/inspect.html):
```
import inspect
def ShowVars(varlist):
frame = inspect.currentframe().f_back
g = frame.f_globals
l = frame.f_locals
for name in varlist:
print('{} -> {}'.format(name, l.get(name, g.get(name))))
```
---
**ALTERNATIVE**
main.py:
```
import mymodule
DEBUG = True
BATCH = False
mymodule.ShowVars(DEBUG, BATCH)
```
mymodule.py:
```
import inspect
def ShowVars(*values):
line = inspect.stack()[1][4][0]
names = line.rsplit('(', 1)[-1].split(')', 1)[0] # Extract argument names.
names = map(str.strip, names.split(','))
for name, value in zip(names, values):
print('{} -> {}'.format(name, value))
``` | ```
members = dir(module)
for item in members:
if not eval('hasattr(module.%s, "__call__")' % item):
print item, eval("module.%s" % item)
```
Should give you a first pass but you might wish to filter out things that start with \_ and other items. |
69,192,163 | How can I get the value of a cookie in oracle from a request that was originated with ajax from a non-apex page (inside an apex server)?
I wanted to start by creating a function that returns the value of the login cookie and use that function to return the value to the browser to see that it can be done.
So I created a resource template and handler with the following source: `select test() from dual`.
The `test` function is declared as:
```
create or replace function test return varchar2
is
c owa_cookie.cookie;
begin
c := owa_cookie.get('LOGIN_USERNAME_COOKIE');
return c.vals(1);
end;
```
When I run `select test() from dual` from an sql commands window I get the value of the cookie, but when I send a request to the handler with ajax I get the following error:
```
An error occurred when evaluating the SQL statement associated with this resource. SQL Error Code 6502, Error Message: ORA-06502: PL/SQL: numeric or value error
ORA-06512: at "SYS.OWA_UTIL", line 354
ORA-06512: at "SYS.OWA_COOKIE", line 59
ORA-06512: at "SYS.OWA_COOKIE", line 179
ORA-06512: at "<no need to see this>.TEST", line 5
```
I've been using the following call (checking the result through the network dev tools)
`$.ajax({url: "<handler url here>"})`
Update:
The reason I'm using a rest service is because the page that originates the request is not an apex application but it is on the same domain (so it has the same cookies). | 2021/09/15 | [
"https://Stackoverflow.com/questions/69192163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3133418/"
] | This is what I think is happening: The cookie is sent as part of the http request header of your apex application call. The rest call is *another* http request, unrelated to your apex http request and I don’t believe the header of that request includes the cookie. So in the database session that is created as part of your rest request the cookie will not exist. You could probably set the header of the rest request yourself to fix this.
--UPDATE--
To check which cookies can be read, create a rest handler of source type pl/sql with the following source:
```
DECLARE
l_names owa_cookie.vc_arr;
l_vals owa_cookie.vc_arr;
l_num_vals INTEGER;
BEGIN
owa_cookie.get_all(
names => l_names,
vals => l_vals,
num_vals => l_num_vals);
APEX_JSON.open_array('cookies');
FOR r IN 1 .. l_names.COUNT LOOP
APEX_JSON.open_object; -- {
APEX_JSON.write('name', l_names(r));
APEX_JSON.write('value', l_vals(r));
APEX_JSON.close_object; -- } cookie
END LOOP;
APEX_JSON.close_array; -- ] cookies
END;
```
The apex username cookie is not in that list of cookies. I suggest you create your own custom cookie in an after-login process in apex.
I verified that a cookie set with the following code in an apex process is picked up by the rest handler (based on blog <https://www.apex-at-work.com/2012/05/apex-simple-cookie-example.html>)
```
begin
owa_util.mime_header('text/html', FALSE);
owa_cookie.send(
name => 'CUSTOM_USER_COOKIE',
value => :APP_USER,
expires => sysdate + 30 );
apex_util.redirect_url (
p_url => 'f?p=&APP_ID.:1:' || :SESSION,
p_reset_htp_buffer => false );
end;
``` | To get a cookie from an AJAX request within APEX, you can use the `OWA_COOKIE` package, but you do not need to define any templates or handlers. It can all be done from within the page (or calling an external procedure from within the page). Below are the steps I used to get the JSESSIONID cookie.
I have built an [example application on apex.oracle.com](https://apex.oracle.com/pls/apex/adptest/r/ej-testing/ajax-test) that you can check out.
### Page Setup
The page is very simple with just one text box and one button. The button's action is set to **Redirect to URL** and this is the target:
```
javascript: apex.server.process("AJAX_TEST", { }, { success: function (pData) { console.log(pData); apex.item("P10_JSESSIONID").setValue(pData); }, dataType: "text", error: function (jqXHR, textStatus, errorThrown) { } }).always(function () { });
```
The javascript is calling the AJAX Callback (which is shown below) and storing the output in the P10\_JSESSIONID page item as well as logging it to the browser console.
[](https://i.stack.imgur.com/ZhgjN.png)
### AJAX Callback Setup
The code in the AJAX Callback is very similar to the code you shared. I am getting the cookie then printing it out with HTP.P. This is all that is needed to return the value of the cookie to the page to be used for whatever you'd like. You can also make the code in the AJAX callback call a standalone procedure compiled into the database if you so choose.
[](https://i.stack.imgur.com/EzmkK.png)
Update
------
I updated my example application so that there will be a dropdown showing all of the cookies, then you can select from the list and click the button to send an AJAX request to get the value of that cookie. |
14,361,022 | Say I have the following function:
```
sqrt_x = function(x) {
sqrtx = x^0.5
return(list("sqrtx" = sqrt))
}
attr(sqrt_x, "comment") <- "This is a comment to be placed on two different lines"
```
if I type
```
comment(sqrt_x)
```
I get
```
[1] "This is a comment to be placed on two different lines"
```
what I want, however, is that the comment is returned on two different lines (it could also be more lines and different comment elements. Any ideas appreciated. | 2013/01/16 | [
"https://Stackoverflow.com/questions/14361022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1889612/"
] | You can use `\n` to insert a newline. The `cat` method shows this in the way you want:
```
attr(sqrt_x, "comment") <- "This is a comment to be placed on two\ndifferent lines"
cat(comment(sqrt_x))
This is a comment to be placed on two
different lines
``` | This is a bit of a hack, and maybe not what you want, but if you provide a multi-element `character` vector, and the lines are long enough that R's default formatting decides they should be on multiple lines, you may get what you want:
```
comment(sqrt_x) <- c("This is a comment ",
"to be placed on two different lines")
comment(sqrt_x)
## [1] "This is a comment "
## [2] "to be placed on two different lines"
```
You could use `format` to pad automatically:
```
comment(sqrt_x) <- format(c("This is a comment",
"to be placed on two different lines"),
width=50)
```
(as shown elsewhere you could also use `strwrap()` to break up a single long string
into parts)
If you're absolutely desperate to have this and you don't like the extra spaces, you could mask the built-in `comment` function with something like @RichieCotton's multiline version:
```
comment <- function(x,width = getOption("width") - 1L) {
cat(strwrap(base::comment(x), width = width), sep = "\n")
}
```
but this is probably a bad idea. |
2,314,500 | We're using git with a central repo (using Gitosis). I've created a post-receive hook to generate an email to the dev mailing list whenever changes are pushed to the central repo, and to generate documentation from the documentation folder in the git repo.
Therefore, in ~git/ I've got a directory, we'll call it 'a' that contains a clone of the git repo. The post-receive hook looks like:
```
#!/bin/bash
cd ~git/repositories/a.git
. ~git/post-receive-email &> /dev/null
( cd ~git/a && git pull &> ~git/pull_log.log && php ~git/a/scripts/generate_markdown_documentation.php &> ~git/doc_log.log )
```
The email script is working, but the documentation generation is not. The content of pull\_log.log is:
```
fatal: Not a git repository: '.'
```
Which makes me think that it's not changing to the correct directory in line 5 of the above script. Am I wrong? How can I get this to work?
**Edit:** I've updated the post-receive hook as suggested in the responses. The script is now:
```
#!/bin/bash
function die {
echo "$*" >&2; exit 1
}
function checkgit {
[ -d "$1/.git" ] || die "$1 could not possibly be a git repo; $1/.git is not a dir"
}
cd ~git/repositories/a.git
. ~git/post-receive-email &> /dev/null
( set -x
checkgit ~git/a
cd ~git/a
checkgit .
pwd
git pull
php ~git/a/scripts/generate_markdown_documentation.php )
```
And I get the following output from git push:
```
+ checkgit /var/git/a
+ '[' -d /var/git/a/.git ']'
+ cd /var/git/a
+ checkgit .
+ '[' -d ./.git ']'
+ pwd
/var/git/a
+ git pull
fatal: Not a git repository: '.'
+ php /var/git/a/scripts/generate_markdown_documentation.php
```
Any more help?
Oh, and if I run the script myself, it works (I run it by saying hooks/post-receive)
Discovered the problem, thanks to [serverfault](https://serverfault.com/questions/107608/git-post-receive-hook-with-git-pull-failed-to-find-a-valid-git-directory) -- basically, environment variables `GIT_DIR` and `GIT_WORK_TREE` are set when the hook runs, and these affect git pull adversely. Unsetting the variables fixes the problem. | 2010/02/22 | [
"https://Stackoverflow.com/questions/2314500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2933/"
] | You need more diagnostics, e.g.,
```
function die {
echo "$*" >&2; exit 1
}
function checkgit {
[ -d "$1/.git" ] || die "$1 could not possibly be a git repo; $1/.git is not a dir"
}
```
At this point, in the subshell right after the parenthesis, you can try stuff like
```
set -x # show exactly what's executed (writes to stderr)
checkgit ~git/a
cd ~git/a && checkgit . && git pull ...
```
You might also consider redirecting the whole stderr of the subshell, e.g.,
```
( ... ) 2>/tmp/mydiagnosis$$.log
```
(This is a temporary measure and is OK only if there's no confidential info in the logs.)
---
OK Silas, your additional info rules out a lot of awkward possibilities. I'm nearing the end of my `git` fu, but here are some more things to try:
1. Go into `~git/a` and see if you can make it `git pull` by hand. This should fail.
2. Got into `~git/a` and run `git status`. This should also fail. If it doesn't, then `git` is giving you a very bad error message.
If both steps fail, `~git/a` is not the clone you thought it was. Rename it, make a new clone, and see if you can get the problem to persist.
If the first step succeeds by hand, then something strange is going on and I'm baffled.
If the first step fails but the second succeeds, you may have a problem with branches:
* Perhaps repo `~git/a` is set to the wrong branch, and your repo needs a branch it doesn't have. Try `git branch -a` and see if you see something unexpected.
* Perhaps you have the branch, but it's not properly associated with a remote repository. At this point you have to dive into `~git/a/.git/config`, and I don't really know how to explain what you should expect to find there. At that point you will need a *real* git expert; I just play one on TV. | `unset GIT_DIR` is a solution which works for the fatal error you are seeing.
This applies to all scripts in hooks (post-update is another common one), which uses the git command inside it. git command uses the GIT\_DIR from env instead of pwd.
See <https://stackoverflow.com/a/4100577> for further explanation. |
16,473,798 | The EDIT of all edits: after literally months working on it, the issue seems to be when some/all of the elements inside the current element are floated/absolutely positioned. This seems to interfere with the sliding.
If you have this same problem, I wish you luck in resolving your issue.
Original Post:
Pretty simple really. I have several divs with several elements, and only one of these divs are shown at a time (the rest are hidden).
When the user clicks "Next", the current div should hide by sliding to the left, and the next div should be shown by sliding in from the right (the actual logic is not an issue).
When I tried doing this with .slideUp() and .slideDown() it worked beautifully. However, when trying:
```
$(oldBox).hide("slide", { direction: "right" }, 1000);
```
it doesn't work. I have JQuery UI linked to already, so that's not the issue.
Any help would be much appreciated.
EDIT: Link to JSFiddle: <http://jsfiddle.net/NFyRW/>
EDIT2: It words in JSFiddle; however, I've been unable to get it to work on my actual site. The JS is in a separate file, and is loaded in the header of each page (same header for every single page). | 2013/05/10 | [
"https://Stackoverflow.com/questions/16473798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1851509/"
] | If your slides are positioned absolutely, animate them using the left property. If they're relative, then switch out the left for margin-left.
Considering your HTML looks similar to this:
```
<div id="mainContainer">
<div class="slide"></div>
<div class="slide"></div>
</div>
#mainContainer {}
.slide {position:absolute;top:0;left:0;}
```
Something like this should
* fade out the current slide
* push out the current slide to the left
* fade in the new slide
* pull in the new slide from the right
.
```
var $oldBox=$('#oldBox');
$oldBox.animate({
'left':-$oldBox.outerWidth(true),
'opacity':0
},{duration:500,queue:false,
specialEasing:{'left':'linear','opacity':'linear'}});
$newBox.animate({
'left':0,
'opacity':1
},{duration:500,queue:false,
specialEasing:{'left':'linear','opacity':'linear'}});
``` | Include the jquery as well as jquery ui js and css files
there is no need for custom js files.
then the codes below can be used :
**$(this).effect( "slide", "right" ); or
$(this).effect('slide', { direction: 'down'}, 500);** |
2,727,526 | I have to compute $\lim\_{n\rightarrow\infty}\frac{n^n}{(n!)^2}$.
I tried say that this limit exists and it's l, so we have $\lim\_{n\rightarrow\infty}\frac{n^n}{(n!)^2} = L$ then I rewrited it as:
$\lim\_{n\rightarrow\infty}(\frac{\sqrt n}{\sqrt[n]{n!}})^{2n}$ then I used natural log over the whole expresion but didn't got into a nice place.
I don't know about Pi function or gamma function so therefore can't really use L'Hospital's rule. | 2018/04/08 | [
"https://math.stackexchange.com/questions/2727526",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/547191/"
] | By ratio test
$$\frac{(n+1)^{n+1}}{((n+1)!)^2}\frac{(n!)^2}{n^n}=\frac1{n+1}\left(1+\frac1n\right)^n\to 0$$
then
$$\lim\_{n\rightarrow\infty}\frac{n^n}{(n!)^2}=0$$ | By the root test, the limit is
$n/(n!)^{2/n}$.
By looking at the last 2/3 of 1 to n,
$n! > (n/3)^{2n/3}$
so $(n!)^{2/n} > (n/3)^{4/3}$
so the ratio is less than
$3^{4/3}/n^{1/3}$
which goes to zero.
This method csn be used to shiw that
$n^n/(n!)^a \to 0$
for any $a > 1$. |
12,613,620 | I am a beginner in jQuery and I was wondering how to validate the form before submission specifically for check boxes.
I am creating a simple check list form where my user would tick a check box if he finished that step. What I am planning to do is that, the script would prevent the form submission if there is an "unticked" checkbox and highlight it with a color.
Here's my code :
```html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<style>
.error {
background-color: #F00;
}
.valid {
background-color: #0F0;
}
</style>
<script type="application/javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"> </script>
<script type="application/javascript">
$('#button').on('click', function() {
var $checkboxes = $('.container [type=checkbox]');
$checkboxes.filter(':checked').parent().removeClass('error').addClass('valid');
$checkboxes.not(':checked').parent().removeClass('valid').addClass('error');
});
</script>
</head>
<body>
<div class="container">
<input class="tick" id="option1" type="checkbox">
</div>
<div class="container">
<input class="tick" id="option1" type="checkbox">
</div>
<input id="button" type="button" value="check">
</body>
</html>
```
So what I am trying to do here is when the user clicks the button, the script will highlight all the unchecked check box with red and highlight all checked with green.
However, my script is not functioning. What is wrong with my script? Any suggestions on a more efficient way to do this? | 2012/09/27 | [
"https://Stackoverflow.com/questions/12613620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1699078/"
] | You have multiple elements with identical `id` attributes. `id`s are unique and should refer to one element. If you plan on grouping multiple elements together, use a `class` attribute instead.
Also, don't bind events using `onclick`. Just use the jQuery `.on('click'` handler.
**HTML**:
```
<div class="container">
<input class="tick" id="option1" type="checkbox" />
</div>
<div class="container">
<input class="tick" id="option2" type="checkbox" />
</div>
<input id="button" type="button" value="check" />
```
**JavaScript**:
```
$('#button').on('click', function() {
var $checkboxes = $('.container [type=checkbox]');
$checkboxes.filter(':checked').parent().removeClass('error').addClass('valid');
$checkboxes.not(':checked').parent().removeClass('valid').addClass('error');
});
```
**Demo: <http://jsfiddle.net/Blender/fzZFz/3/>** | A couple of things:
1.) you have multiple elements with the same ID (container). That is not valid html and jquery will only return the first element it finds when searching by ID.
2.) You are binding an event to the change only after the user clicks the check button. I think you could just bind to the .tick change event and have it validate as the user is checking items.
3.) Your logic was backwards for validation. You were adding the error condition when everything was valid.
The final js is this:
```
$(".tick").change(function(){
if ($('.tick:checked').length == $('.tick').length) {
$('.container').removeClass("error");
$('.container').addClass('valid');
} else {
$('.container').removeClass("valid");
$('.container').addClass('error');
}
});
```
With a small tweak to the html to remove the duplicate IDs:
```
<div class="container"><input class="tick" id="option1" type="checkbox"></div>
<div class="container"><input class="tick" id="option1" type="checkbox"></div>
```
See this fiddle:
<http://jsfiddle.net/johnkoer/225Ty/5/> |
52 | Since this is one of the [7 Essential Meta Questions of Every Beta](http://blog.stackoverflow.com/2010/07/the-7-essential-meta-questions-of-every-beta/)...
**What should go in our FAQ?**
Most of the FAQ is boilerplate, but we need to determine the on-topic and off-topic subjects that go into that particular section of the official FAQ. Those should be derived from the original site definition and the current set of questions.
**Example template:**
Following the example set out in the linked page, the section being discussed here might look like this:
>
> {Site Name} is for professional and amateur video game developers, designers, artists; and anyone else who is involved in the games development industry.
>
>
> If your question is about:
>
>
> * {On-topic subject}
> * {On-topic subject}
> * ...
>
>
> and it is **not about:**
>
>
> * {Off-topic subject}
> * {Off-topic subject}
> * {Off-topic subject}
>
>
> … then you're in the right place to ask your question!
>
>
>
**Answer format:**
Please post **one subject** and specify whether or not it is an on-topic or off-topic. Note that your answer should **not** be in the form of a specific example question; it should refer to an **entire subject group**. Example of such a response:
>
> **{On-topic}**
>
>
> **Tools used by Game Developers**
>
>
> (Optional comments)
>
>
>
Please **vote up** answers if you **agree** with the proposed on-topic/off-topic status. **Vote down** answers where you **disagree.** | 2010/07/17 | [
"https://gamedev.meta.stackexchange.com/questions/52",
"https://gamedev.meta.stackexchange.com",
"https://gamedev.meta.stackexchange.com/users/321/"
] | **{Off-topic}**
Hints, tips, strategies or cheat codes for games
------------------------------------------------ | **{On-topic}**
**Programming questions *unique* to video game development, or where a professional game developer would give a *substantially different* answer than other programmers (general programming questions should be asked on [StackOverflow](http://stackoverflow.com))**
([Taken from the bullet list in my answer here](https://gamedev.meta.stackexchange.com/questions/3/programming-questions-here-or-belongs-on-stackoverflow/14#14))
(The language here could probably be tightened up a bit... and the statement about general programming questions could probably be moved to its own "Off-topic" post... feel free to edit) |
47,925 | Consider the following puzzle type proposed by [JonMark Perry](https://puzzling.stackexchange.com/a/47842/5373).
>
> Start with a square grid of arrows, each one pointing in one of the four cardinal directions. For example:
>
>
> [](https://i.stack.imgur.com/QvVF1.png)
>
>
> You start at the top left. You travel 1 step in the direction of the arrow you are on. Continue until you reach the bottom right.
>
>
> Only there's a 'twist' - when you leave an arrow, it rotates 90°
> clockwise.
>
>
>
*edited from JMP's original "1 or 2 steps" for simplicity of the problem*
Let's try to analyse this puzzle!
**Is it always solvable, regardless of the initial setup of arrows in the grid? If not, are there conditions for when it is solvable? Does the answer vary according to the size of the grid?**
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
**Disclaimer**: I don't know the answer to this question, and nor, it seems, does JMP himself. | 2017/01/12 | [
"https://puzzling.stackexchange.com/questions/47925",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/5373/"
] | No it's not always solvable... consider
>
> all arrows pointing upwards. Then you keep going upwards until you 'fall off' i.e run out of room. As for solvability, I have no idea for simple conditions. For grid size, case bash small grids maybe?
>
>
>
I'll post here as I investigate. | For a grid of any size there are trivial examples where one reaches the bottom right corner, and trivial examples where one doesn't.
>
> If the top left arrow points up you're off the grid immediately.
>
>
>
>
> If all the arrows of the rightmost column point down and the top row of all columns bar the rightmost point right, you'll clearly reach the bottom right corner.
>
>
>
Supposing we're dealing with a randomly filled grid, or all possible fillings of a grid (same thing), then
You'd be more likely to complete the journey if
>
> the start and end points were not boundary points.
>
>
>
Beyond a certain size, the bigger the grid, the more likely you are to leave the grid before hitting the bottom right corner. (Your target is getting probabilistically smaller as your exit point). |
40,904,446 | I've been trying to validate a password text in a Modal window. When I enter the the incorrect password the alert keeps on displaying "Login is incorrect" message. Seems the while loop I am using, keeps continuing. How do I make the alert message display only once. But the Modal window should keep displaying
```js
var modal = document.getElementById('loginModal');
// Get the button that opens the modal
var btn = document.getElementById("loginBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
function promptPassword( )
{
while (document.getElementById("pwdText").value != 'P@ssw0rd'){
alert("Login is incorrect");
document.getElementById('pwdText').value = "";
}
alert("Password is correct, you are allowed to enter the site");
}
```
```css
.modal {
display: none; /* Modal not shown by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the modal box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 25%;
height: 25%;
}
/*Display of text box labels*/
label{
display: inline-block;
float: left;
clear: left;
width: 250px;
text-align: left;
}
label {
display: inline-block;
float: left;
}
/*Display of text and password boxes*/
input[type=text] {
width:250px;
}
input[type=password] {
width:250px;
}
/* Close Button */
.close {
float: right;
margin: -15px -15px 0 0;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
text-decoration: none;
cursor: pointer;
}
```
```html
<!-- Login button to pen Modal box -->
<button id="loginBtn">Login</button>
<!-- The Modal box-->
<div id="loginModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<form>
<br/>
<label>User Name</label><input id="userName" type="text"><br />
<br/>
<label>Password</label><input id="pwdText" type="password"><br />
<br/>
<button onclick="promptPassword()">Submit</button>
</form>
</div>
```
I need to do this without using Jquery | 2016/12/01 | [
"https://Stackoverflow.com/questions/40904446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5588792/"
] | First you need to replace
```
<button onclick="promptPassword()">Submit</button>
```
to
```
<button onclick="return promptPassword()">Submit</button>
```
Then you need to use only this
```
function promptPassword( )
{
var pwd = document.getElementById("pwdText").value;
if(pwd != 'P@ssw0rd'){
alert("Login is incorrect");
document.getElementById('pwdText').value = "";
return false;
}
else{
alert("Password is correct, you are allowed to enter the site");
// Enter Site Code Here
}
}
``` | You're using a while loop, which will keep repeating until the condition is no longer met.
What you need is an if statement.
```
function promptPassword( ) {
if(document.getElementById("pwdText").value != 'P@ssw0rd'){
alert("Login is incorrect");
document.getElementById('pwdText').value = "";
}
}
``` |
13,535,742 | ```
$insert = "INSERT INTO event_tracker_table (event_name, event_location, location_number, event_creator_username, event_creator_email)
VALUES (
'".$_POST['event_name']."',
'".$_POST['event_location']."',
'".$_POST['location_number']."',
'".phpCAS::getAttribute('uid')."',
'".phpCAS::getAttribute('mail')."'
)";
$mysqli->query($insert);
```
How do I get this AUTO INCREMENT that was generated by MySQL? I've tried this but it doesn't work:
```
$statement = $mysqli->query($insert);
echo $statement->insert_id;
``` | 2012/11/23 | [
"https://Stackoverflow.com/questions/13535742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1509580/"
] | Insert id is a property of the MYSQLI object and not the MYSQLI result object:
```
$statement = $mysqli->query($insert);
echo $mysqli->insert_id; // correct
echo $statement->insert_id; //not correct
```
<http://php.net/manual/en/mysqli.insert-id.php> | You can get the auto\_increment value with
```
$id = mysqli_insert_id($mysqli);
```
See [mysqli\_insert\_id](http://php.net/manual/de/mysqli.insert-id.php) for more info. |
1,438,464 | I am trying develop a SharePoint WebPart with "Visual Studio 2008 Extensions, Version 1.3".
When I try deploy or quick deploy or package or anything about deployment for my WebPart I am getting this message:
**The HTTP request is unauthorized with client authentication scheme 'Negotiate'. The authentication header received from the server was 'Negotiate,NTLM'.**
Is there someone who has a solution for this problem? Thanks! | 2009/09/17 | [
"https://Stackoverflow.com/questions/1438464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/60107/"
] | You may not use a sequence in a WHERE clause - it does look natural in your context, but Oracle does not allow the reference in a comparison expression.
[Edit]
This would be a PL/SQL implementation:
```
declare
v_custID number;
cursor custCur is
select customerid, name from customer
where customerid = v_custID;
begin
select customer_seq.nextval into v_custID from dual;
insert into customer (customerid, name) values (v_custID, 'AAA');
commit;
for custRow in custCur loop
dbms_output.put_line(custRow.customerID||' '|| custRow.name);
end loop;
end;
``` | You have not created any
```
sequence
```
First create any sequence its cycle and cache. This is some basic example
```
Create Sequence seqtest1
Start With 0 -- This Is Hirarchy Starts With 0
Increment by 1 --Increments by 1
Minvalue 0 --With Minimum value 0
Maxvalue 5 --Maximum Value 5. So The Cycle Of Creation Is Between 0-5
Nocycle -- No Cycle Means After 0-5 the Insertion Stopes
Nocache --The cache Option Specifies How Many Sequence Values Will Be Stored In Memory For Faster Access
```
You cannot do Where Clause on Sequence in SQL beacuse you cannot filter a sequence . Use procedures like @APC said |
2,193,231 | I am working in the Python Interactive Shell (ActiveState ActivePython 2.6.4 under Windows XP). I created a function that does what I want. However, I've cleared the screen so I can't go back and look at the function definition. It is also a multiline function so the up arrow to redisplay lines is of minimal value. Is there anyway to return the actual code of the function? There are "**code**" and "func\_code" attributes displayed by dir(), but I don't know if they contain what I need. | 2010/02/03 | [
"https://Stackoverflow.com/questions/2193231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/245029/"
] | No, not really. You could write yourfunc.func\_code.co\_code (the actually compiled bytecode) to a file and then try using decompyle or unpyc to decompile them, but both projects are old and unmaintained, and have never supported decompiling very well.
It's infinitely easier to simply write your function to a file to start with. | Unless there is a way of doing it on the activestate shell, no, there is no way to retrieve the exact code you've typed on the shell. At least on Linux, using the Python Shell provided by CPython there is no special way to achieve this. Maybe using iPython.
The func\_code attribute is an object representing the function bytecode, the only thing you can get from this object is bytecode itself, not the "original" code. |
4,569,730 | I have the following code for converting the integer(a score) into the character and then appending it with the player's name (player1). It gets displayed after that. It is a part of a bigger project :
```
#include <iostream>
#include <string.h>
using namespace std;
char* convertIntTochar(int number)
{
char t[3];
t[0] = 0;
t[1] = 0;
t[2] = '\0';
int i = 0;
for(; number != 0; i++)
{
t[i] = ((number%10) + 48);
number/=10;
}
if(i == 2)
{
char temp = t[0];
t[0] = t[1];
t[1] = temp;
}
else
t[i] = '\0';
char *ans = t;
return ans;
}
int main()
{
char str11[] = "Player1: ";
char *str1 = str11;
char *str2 = convertIntTochar(11);
strcat(str1 , str2);
while(*str1)
{
cout<<*(str1++);
}
return 0;
}
```
It compiles correctly but when I run it , it shows the following error :
```
*** stack smashing detected ***: ./a.out terminated
======= Backtrace: =========
/lib/tls/i686/cmov/libc.so.6(__fortify_fail+0x50)[0x9b3390]
/lib/tls/i686/cmov/libc.so.6(+0xe233a)[0x9b333a]
./a.out[0x80487ff]
/lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe6)[0x8e7bd6]
./a.out[0x8048621]
======= Memory map: ========
00110000-00134000 r-xp 00000000 08:06 2887608 /lib/tls/i686/cmov/libm-2.11.1.so
00134000-00135000 r--p 00023000 08:06 2887608 /lib/tls/i686/cmov/libm-2.11.1.so
00135000-00136000 rw-p 00024000 08:06 2887608 /lib/tls/i686/cmov/libm-2.11.1.so
004b9000-004d4000 r-xp 00000000 08:06 2887597 /lib/ld-2.11.1.so
004d4000-004d5000 r--p 0001a000 08:06 2887597 /lib/ld-2.11.1.so
004d5000-004d6000 rw-p 0001b000 08:06 2887597 /lib/ld-2.11.1.so
0077d000-00866000 r-xp 00000000 08:06 2756275 /usr/lib/libstdc++.so.6.0.13
00866000-00867000 ---p 000e9000 08:06 2756275 /usr/lib/libstdc++.so.6.0.13
00867000-0086b000 r--p 000e9000 08:06 2756275 /usr/lib/libstdc++.so.6.0.13
0086b000-0086c000 rw-p 000ed000 08:06 2756275 /usr/lib/libstdc++.so.6.0.13
0086c000-00873000 rw-p 00000000 00:00 0
008d1000-00a24000 r-xp 00000000 08:06 2887604 /lib/tls/i686/cmov/libc-2.11.1.so
00a24000-00a25000 ---p 00153000 08:06 2887604 /lib/tls/i686/cmov/libc-2.11.1.so
00a25000-00a27000 r--p 00153000 08:06 2887604 /lib/tls/i686/cmov/libc-2.11.1.so
00a27000-00a28000 rw-p 00155000 08:06 2887604 /lib/tls/i686/cmov/libc-2.11.1.so
00a28000-00a2b000 rw-p 00000000 00:00 0
00a3b000-00a58000 r-xp 00000000 08:06 2883667 /lib/libgcc_s.so.1
00a58000-00a59000 r--p 0001c000 08:06 2883667 /lib/libgcc_s.so.1
00a59000-00a5a000 rw-p 0001d000 08:06 2883667 /lib/libgcc_s.so.1
00b74000-00b75000 r-xp 00000000 00:00 0 [vdso]
08048000-08049000 r-xp 00000000 08:06 4719693 /home/dhruv/Desktop/a.out
08049000-0804a000 r--p 00000000 08:06 4719693 /home/dhruv/Desktop/a.out
0804a000-0804b000 rw-p 00001000 08:06 4719693 /home/dhruv/Desktop/a.out
08b67000-08b88000 rw-p 00000000 00:00 0 [heap]
b77f7000-b77f9000 rw-p 00000000 00:00 0
b780d000-b7810000 rw-p 00000000 00:00 0
bfd2a000-bfd3f000 rw-p 00000000 00:00 0 [stack]
Player1: "�ӿ�XMAborted
```
What is the reason for this? How can it be rectified. I have already put the null termination character in the convertIntTochar function. | 2010/12/31 | [
"https://Stackoverflow.com/questions/4569730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/262588/"
] | ```
char str11[] = "Player1: ";
```
This is the problem. There is not enough room for string concatenation. Try this:
```
char str11[100] = "Player1: ";
```
Better yet, use `std::string` instead of C-like `char*`. Smallest possible changes that fix string problems are these (because there exist `using namespace std` then `std::` part in `std::string` can be left out, but I just prefer to leave it in):
```
#include <iostream>
#include <string> // instead of <string.h>
using namespace std;
std::string convertIntTochar(int number)
{
...
}
int main()
{
std::string str1 = "Player1: ";
std::string str2 = convertIntTochar(11);
str1 += str2;
cout << str1;
// Or even more effective, just one line of code:
cout << "Player1: " << convertIntTochar(11);
return 0;
}
``` | To convert int to `char *` see if you can use `itoa` with your compiler.
If it is not supported you can find its implemenation to do what you want.
That is if you have to do it using C-strings |
193,059 | Since the dawn of time, mermaids have been able to make pearls through magic. (Mermen create seashells, and these are what the mermaids wear.) These pearls form in the center of their seashell top, right over their heart, over and over throughout their lifetime, and hold a bit of the mermaid's essence (they literally put their heart and soul, part of themselves, into their pearls. Don't worry though, what they lose they eventually regain since the heart and soul are immortal.)
Since each pearl contains a piece of their self, mermaids give them to their loved ones as a sign of their bond; for spouses, this strengthens their marital bond, while for their children, it brings out their potential and allows them to feel their mother's love for them within their own hearts. This is even more touching when one considers that a pearl gives one power over its creator; if you have a mermaid's pearl, you have power over them.
However, now that Atlantis has removed its Barrier of Secrecy there's a problem: *everyone* wants their pearls.
Human men seem to sense the significance of the pearls and desire one (or more, there are hoarders) for their own, and if that wasn't bad enough, they have an uncanny knack for finding them.
Additionally, witches have realized that they can claim a mermaid's pearl, adding her magic to their own *and* getting a new slave as well.
They (and other mages as well) also want to claim the pearls as ingredients for their potions or spells, for twisted experiments, and who knows what else.
Sea lamia (yes, there are sea lamia, just as there are sea snakes) desire the pearls for use in subjugating the mermaids, which they are incredibly jealous of (humans like mermaids better, so they feel wronged and want revenge).
Even crazy *dragons* want these pearls! (see ("https://worldbuilding.stackexchange.com/questions/193057/how-dragons-can-hoard-people") if you're curious as to why)
So now the question is: **How to defend the mermaid's pearls?**
Consider:
1. While the deep-sea location of Atlantis is a significant barrier, there are spells that negate even that advantage. (Magical submarines are tricky to make, but they *are* a thing.)
2. A simple "force field" can be broken or bypassed, so that's not a solution. Something more restrictive, like the Age Line from *Harry Potter and the Goblet of Fire* would be preferred.
3. Since no defense is invincible, and no defenders can repel would-be pearl thieves forever, a secretive location is best.
4. Secrecy, as mentioned above, are your friend, as are complexity and redundancy. You're designing a magical security system here, and stakes are high if it fails.
5. While magic exists, powerful magic is rare and powerful enchantments are even rarer. Setting up something like the Ark of the Covenant, that'll disintegrate anyone who's dumb enough to open it up, is not possible. Neither is impenetrable defenses or an impossible maze. Everything magical *has* to have weaknesses; the more "unfailable" you make it, the less likely it'll work. Simple but effective is the key here. | 2020/12/31 | [
"https://worldbuilding.stackexchange.com/questions/193059",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/80953/"
] | They just need to found a new religion, based on the worship of dragons. The dragons will reward the true faithful and punish the blasphemous ones.
* The method must result in uncontested ownership-the humans must not question that they belong to their dragon. Indoctrination is likely. **Check**
Religion and indoctrination walk together since forever. It's not something the humans aren't used to.
* The resulting relationship should be akin to the king-subject or master-servant relationship. **Check**
Every religion has its own set of rules and prohibition to be followed. Again, nothing brand new for the human minds.
* The dragons don't want to share ownership of their humans. **Check**
Do you know any religion which is happy to share their supporter base? | **Newsflash $-$ They Already Did.**
Dragons are the dominant species on the planet. The leaders of the major nations are dragons. This is a closely guarded secret, known only to the higher council mages who are paid a handsome sum for their cooperation, and for hunting down rogue anti-establishment mages.
Dragons live for thousands of years and are powerful spell casters. It is no trouble for them to appear human. Of course every few decades one must change their appearance and name to give the illusion of mortal human rulers dying and being replaced.
This is the reason the major nations have existed for thousands of years. It's because Dragons live long enough to either (a) plan that long or (b) erase their nations's history so it seems like the nation is really old when in fact they established it only 3 generations ago.
Another benefit is the Dragon Kings can arrange phony *wars* (see the famous England vs. France conflict) between neighboring kingdoms to keep the peasantry on their toes (you need me to protect you) while in fact the start and end dates are agreed long in advance. |
10,714,958 | I've implemented the Channel API w/ persistence. When I make a channel and connect the socket (this is on the real app, not the local dev\_appserver), Firebug goes nuts with log messages. I want to turn these off so I can see my OWN logs but cant find any documentation on how to disable the Channel API console logging.
one thing I'm probably doing differently than most is that I'm connecting cross-domain... which the Channel API supports (note the first message in the stream... if you can view that pic)

Does anyone know?
---
UPDATE
------
I finally realized that my code was creating two channels and trying to open/connect them both at the same time... and *that* was why I was getting a flood of messages. I didn't mean to do this (I know the rules: <https://developers.google.com/appengine/docs/python/channel/overview#Caveats> )... it was a bug... and once I fixed it, the messages went back to manageable level.
yay | 2012/05/23 | [
"https://Stackoverflow.com/questions/10714958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/130221/"
] | you can use `str_replace('admin','',$var_name);` if you have variable of this html. | Try using position relative with a negative left position, I don't know if you can apply those styles with no problem in your Drupal site, but at least it works in the fiddle.
<http://jsfiddle.net/cadence96/M5pfV/1/>
First give a relative position to the container moving it away of the view applying a css style of left: -9999px
then select the children elements, give them position relative, and style them with left: 9999px, this way you'll get your necessary elements back in the view.
PD: I tried to use the same process with negative text indent, but I don't know why it didn't work. |
45,941,090 | The docs are not clear on this as they mention fov and viewport suggesting a portion of the entire spherical image.
Does the Google Street View API support retrieving the **entire** 360 degree equi-rectangular (lat/lon) image? | 2017/08/29 | [
"https://Stackoverflow.com/questions/45941090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116169/"
] | Division in Python 2.x is integer division by default.
```
>>> (15. / 8) * 0.00167322032899 ** 2
5.2493742550226314e-06
>>> from __future__ import division
>>> (15 / 8) * 0.00167322032899 ** 2
5.2493742550226314e-06
``` | Doing `15 / 8` in Python (python2) does integer division. So you get `1`, whereas Excel evaluates that to `1.875`
I assume you want a fraction, so in python use `15.0 / 8` (or `15 / 8.0` or `15.0 / 8.0`) to force a fraction instead of integer division |
22,309,362 | I have this code:
```
Ext.define('innerWindow', {
extend: 'Ext.window.Window',
title: 'title',
height: 200,
width: 500,
modal: true
});
tb = Ext.getCmp('head-toolbar');
tb.add({
text: 'Export',
menu: Ext.create('Ext.menu.Menu', {
items: [
{
text: 'Export',
handler: function () {
var win = new innerWindow();
win.show();
}
}
]
})
});
```
It creates a dropdown that has a value called 'export'. I have managed to make it so that, when I click the 'Export', I get a window. For now this window is empty. What I have been looking for, and unable to find, is how to create a window that has some text inside, and some options (dropdown box), and labels etc.
More precisly, I want a window like the one I attached. I'm sure I can find examples on how to create this, but I just don't know what to search for. Searching on "Extjs window" and similar words, didnt bring me the help I'm looking for, nor looking at Senshas homepage (which normally has lots of brilliant examples).
Can someone help me out?
Thanks
 | 2014/03/10 | [
"https://Stackoverflow.com/questions/22309362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1960836/"
] | In your code change
```
var win = new innerWindow();
```
to
```
var win = Ext.create('innerWindow');
```
Then just define your window with the form inside:
```
Ext.define('innerWindow', {
extend: 'Ext.window.Window',
title: 'title',
height: 200,
width: 500,
modal: true,
items: [{
xtype: 'form',
items: [{
xtype: 'textfield',
fieldLabel: 'Age',
name: 'age'
},{
xtype: 'textfield',
fieldLabel: 'Height',
name: 'height'
}],
fbar: [{
text: 'Submit',
formBind: true,
itemId: 'submit'
}]
}]
});
```
The documentation is here: [form](http://docs.sencha.com/extjs/4.2.2/#!/api/Ext.form.Panel), [textfield](http://docs.sencha.com/extjs/4.2.2/#!/api/Ext.form.field.Text), [combobox](http://docs.sencha.com/extjs/4.2.2/#!/api/Ext.form.field.ComboBox). Start reading [the guides](http://docs.sencha.com/extjs/4.2.2/#!/guide). You must read the docs to understand. ExtJs doc is well written. | **Set Extjs Script**
```
<script type='text/javascript' src='http://cdn.sencha.io/ext-4.2.0-gpl/ext-all.js'></script>
```
**Set Extjs CSS**
```
<link href="http://cdn.sencha.com/ext/gpl/4.2.0/resources/css/ext-all.css" rel="stylesheet"/>
```
**Set Code**
```
<script type='text/javascript'>
Ext.onReady(function() {
Ext.create('Ext.window.Window', {
title: 'Windows',
closable: true,
closeAction: 'hide',
width: 350,
minWidth: 250,
height: 125,
animCollapse:false,
border: false,
modal: true,
layout: {
type: 'border',
padding: 5
},
items: [{
xtype: 'form',
items: [{
xtype : 'combo',
fieldLabel : 'Age',
width : 320,
store : [ '18', '19', '20' ]
},{
xtype : 'combo',
fieldLabel : 'Height',
width : 320,
store : [ '1', '2', '3' ]
},],
fbar: [{
text: 'Submit',
formBind: true,
itemId: 'submit'
}]
}]
}).show();
});
</script>
```
**Similar you want** <http://jsfiddle.net/ba3wnwpo/> |
3,523,985 | Does there exist a differentiable function with the following properties:
$f(0) = 1$
$0 < f(x) < 1$ for $ 0 < x < 1$
$f(x) = 0$ for $x \geq 1$
$f'(0) = 0$
and lastly, $f'(p) = f(p)$ for at least one value of $p$ between $0$ and $1$. | 2020/01/27 | [
"https://math.stackexchange.com/questions/3523985",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/353055/"
] | The function equal to $(x-1)^2(2x+1)$ for $x\leq 1$ and zero elsewhere satisfies all conditions except the last one ($p=1$ satisfies the condition, but no $p$ between $0$ and $1$).
However, you can modify this function by adding a continuously differentiable [bump function](https://en.wikipedia.org/wiki/Bump_function) $h(x)$ which is supported on a small neighborhood of any point in $(0,1)$ - for instance, $x=\tfrac12$ - in such a way that the derivative condition is satisfied in a neighborhood of $x$. This is possible because all the other conditions other than the last one are local to the endpoints.
To be a little more concrete, let the bump function $h(x)$ satisfy the following conditions:
1. $h(\tfrac12)=0$
2. $h'(\tfrac12)=\tfrac12$
3. $h(x)=0$ if $x\not\in (\tfrac14,\tfrac34)$
4. $|h(x)|<\tfrac{5}{32}$ for all $x$
Then $f(x)+h(x)$ satisfies the conditions with $p=\tfrac12$. (Note that $f(\tfrac12)=\tfrac12$ and the $\tfrac{5}{32}$ comes by considering the values of $f(\tfrac14)$ and $f(\tfrac34)$ (to ensure that $f(x)+h(x)$ remains in $(0,1)$. | Define $f(x) = \begin{cases} {1 \over 2} (54 x^3 -27 x^2 +2), & x \in [0, {1 \over 3}) \\
{1 \over 2} + {1 \over 8} (1-\cos (24 \pi (x-{1 \over 3}))),& x\in [{1 \over 3}, {2 \over 3})\\
{27 \over 2} (x-1)^2(2x-1), & x \in [{2 \over 3},1] \\
0, & x>1\end{cases}$.
Check that $f(0)=1$, $f'(0) = 0$, $f(x) = 0$ for $x \ge 1$, $f(x) \in (0,1)$ for all $x \in (0,1)$.
Since $[-8,8] \subset f'([{1 \over 3}, {2 \over 3}])$, it is clear that there is some $x \in (0,1)$ such that $f(x) = f'(x)$.
Note the function is much easier to construct than to figure out where the above definition came from. I started with the polynomial $x(x-{1 \over 3})$ and integrated, scaled & shifted. This defined the function on $[0, {1 \over 3}]$. Then I used this to define the 'complementary' function on $[{2 \over 3}, 1]$. Then I filled in the middle with a shifted & scaled $\cos$ to that the derivative would be all over the place. |
1,337,253 | How to show that for a cone with given volume and least curved surface area the altitude is equal to $\sqrt2$ times the radius of the base, using concept of maxima and minima? | 2015/06/24 | [
"https://math.stackexchange.com/questions/1337253",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/249868/"
] | Volume of a right circular cone, $$\mathbf{V = \frac{1}{3}\pi r^2h}$$ where **r** is the radius and **h** the altitude of the cone. Its curved surface area, $$\mathbf{CSA = \pi r\sqrt{r^2 + h^2}}$$ Now to make calculations easier we take our functions as $$\mathbf{(CSA)^2 = \pi^2 r^4 + \pi^2 r^2h^2}$$ and substitute $$\mathbf{r = \sqrt{\frac{3V}{\pi h}}}$$ (since volume is constant), giving us $$\mathbf{(CSA)^2 = \frac{9v^2}{h^2} + \pi 3Vh}$$ For minima : $$\mathbf{\frac{d}{dh}(CSA)^2 = 0}$$ and $$\mathbf{\frac{d^2}{dh^2}(CSA)^2 > 0}$$ To find relation between **r** and **h**, $$\mathbf{\frac{d}{dh}(CSA)^2 = -\frac{18V^2}{h^3} + \pi 3V = 0}$$
$$\mathbf{\Rightarrow h = \left(\frac{6V}{\pi}\right)^{1/3}}$$
$$\mathbf{\Rightarrow r = \left(\frac{3V}{\sqrt2 \pi}\right)^{1/3}}$$
$$\mathbf{\Rightarrow h = \sqrt{2} \times r}$$ To confirm it is indeed minima, $$\mathbf{\frac{d^2}{dh^2}(CSA)^2 = \frac{54V^2}{h^4} > 0}$$ | Given with a hope to induce interest for learning the more powerful Lagrange multiplier when there are two variables.
$$ A = r \sqrt {r^2+h^2},\, V = r^2h\,$$
the method requires taking a Lagrangian like $(A- \lambda V),$
$$ \dfrac{A\_r}{A\_h}= \dfrac{V\_r}{V\_h} $$
where these are partial derivatives of $ A,V $ w.r.t. subscripts $(r,h)$ given
$$\dfrac{ \sqrt {r^2+h^2} +r^2/\sqrt {r^2+h^2}}{rh/\sqrt {r^2+h^2}}= \dfrac{2 r h}{r^2} $$
which when simplified results in:
$$ \dfrac{h}{r} =\sqrt {2}. $$ |
55,100,098 | I want to create a line chart in `ggplot2` with 350 beer breweries. I want to count per year how many active breweries there are. I only have the start and end date of brewery activity. `tidyverse` answers prefered.
`begin_datum_jaar` is year the brewery started. `eind_datum_jaar` is in which year the brewery has ended.
example data frame:
```
library(tidyverse)
# A tibble: 4 x 3
brouwerijnaam begin_datum_jaar eind_datum_jaar
<chr> <int> <int>
1 Brand 1340 2019
2 Heineken 1592 2019
3 Grolsche 1615 2019
4 Bavaria 1719 2010
```
dput:
```
df <- structure(list(brouwerijnaam = c("Brand", "Heineken", "Grolsche",
"Bavaria"), begin_datum_jaar = c(1340L, 1592L, 1615L, 1719L),
eind_datum_jaar = c(2019L, 2019L, 2019L, 2010L)), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -4L))
```
Desired output where `etc.` is a placeholder.
```
# A tibble: 13 x 2
year n
<chr> <dbl>
1 1340 1
2 1341 1
3 1342 1
4 1343 1
5 etc. 1
6 1592 2
7 1593 2
8 etc. 2
9 1625 3
10 1626 3
11 1627 3
12 1628 3
13 etc. 3
``` | 2019/03/11 | [
"https://Stackoverflow.com/questions/55100098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5816847/"
] | Could try:
```
library(tidyverse)
df %>%
rowwise %>%
do(data.frame(brouwerij = .$brouwerijnaam,
Year = seq(.$begin_datum_jaar, .$eind_datum_jaar, by = 1))) %>%
count(Year, name = "Active breweries") %>%
ggplot(aes(x = Year, y = `Active breweries`)) +
geom_line() +
theme_minimal()
```
Or try `expand` for the first part:
```
df %>%
group_by(brouwerijnaam) %>%
expand(Year = begin_datum_jaar:eind_datum_jaar) %>%
ungroup() %>%
count(Year, name = "Active breweries")
```
However, note that the `rowwise`, `do` or `expand` parts are resource intensive and may take long time. If that happens, I'd rather use `data.table` for expanding the data frame, and then continue, like below:
```
library(data.table)
library(tidyverse)
df <- setDT(df)[, .(Year = seq(begin_datum_jaar, eind_datum_jaar, by = 1)), by = brouwerijnaam]
df %>%
count(Year, name = "Active breweries") %>%
ggplot(aes(x = Year, y = `Active breweries`)) +
geom_line() +
theme_minimal()
```
The above gives you the plot directly. If you'd like to save it to a data frame first (and then do the `ggplot2` thing), this is the main part (I use the `data.table` for expanding as it's much faster in my experience):
```
library(data.table)
library(tidyverse)
df <- setDT(df)[
, .(Year = seq(begin_datum_jaar, eind_datum_jaar, by = 1)),
by = brouwerijnaam] %>%
count(Year, name = "Active breweries")
```
Output:
```
# A tibble: 680 x 2
Year `Active breweries`
<dbl> <int>
1 1340 1
2 1341 1
3 1342 1
4 1343 1
5 1344 1
6 1345 1
7 1346 1
8 1347 1
9 1348 1
10 1349 1
# ... with 670 more rows
``` | ```
df1 <- data.frame(year=1000:2020) # Enter range for years of choice
df1 %>%
rowwise()%>%
mutate(cnt=nrow(df %>%
filter(begin_datum_jaar<year & eind_datum_jaar>year)
)
)
``` |
1,358,539 | I have a situation where I have an Oracle procedure that is being called from at least 3 or 4 different places. I need to be able to be able to call custom-code depending on some data. The custom-code is customer-specific - so, customer A might want to do A-B-C where customer B might want to do 6-7-8 and customer C doesn't need to do anything extra. When customers D...Z come along, I don't want to have to modify my existing procedure.
I'd like to be able to enter the customer-specific procedure into a table. In this existing procedure, check that database table if a custom-code procedure exists and if so, execute it. Each of the customer-code procedures would have the same parameters.
For instance:
1. My application (3+ places) calls this "delete" procedure
2. In this delete procedure, look up the name of a child-procedure to call (if one exists at all)
3. If one exists, execute that delete procedure (passing the parameters in)
I know I can do this with building a string that contains the call to the stored procedure. But, I'd like to know if Oracle 10g has anything built in for doing this kind of thing? | 2009/08/31 | [
"https://Stackoverflow.com/questions/1358539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/166123/"
] | The final solution that we went with was to store the name of a procedure in a database table. We then build the SQL call and use an EXECUTE statement. | Your solution seems reasonable given the requirements, so I voted it up.
Another option would be to loop through the results from your table look-up and put calls to the procedures inside a big case statement. It would be more code, but it would have the advantage of making the dependency chain visible so you could more easily catch missing permissions and invalid procedures. |
131,021 | What's the meaning of 90-plus? More than 90? If so, please tell me more ways to say "more than 90". Thank you! | 2013/10/11 | [
"https://english.stackexchange.com/questions/131021",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/53794/"
] | *#-plus* is used typically when quantifying something with a rough estimate. Typically, when using the phrase, the implication is that there are *at least* that many. Using your example, if someone told you there were *90-plus* grapefruits, you could likely count on there being at least 90, plus a little more.
Other examples of this might include sports, such as American football, where a player may have run for *100-plus* yards. It is not an accurate way of presenting statistics at all, rather more conversational.
Other ways of saying "more than 90" (besides the obvious) include *over 90* and *greater than 90*. | Yes, it means more than (greater than) 90.
Example usages:
>
> * There are 90 plus dogs in that basket.
> * It'll cost 90 plus dollars to buy that dog.
> * The dog is 90 plus years old.
>
>
> |
23,692,846 | I want to click on a 3D plane with my mouse. When I do this, I want it to return a `Vector3` of where I clicked. When I use:
```
Vector3 point = Camera.main.ScreenToWorldPoint(Input.mousePosition);
```
then, it gives me the `Vector3` of the center of the plane. Not what I want. I want it to be at the position I click.
I am trying to create a `Ray` (`Camera.ScreenPointToRay`) and work with `Physics.Raycast`, but that just returns a `bool`, and not where it actually hits.
I have spent the last 3 hours reading everyone else's questions...what am I missing here? | 2014/05/16 | [
"https://Stackoverflow.com/questions/23692846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1889720/"
] | I would guess SQL is converting it to an integer.
Code like this `select cast('00000' as varchar)` returns as you wish (00000, 00035) but `select cast('00000' as int)` returns your results (0, 35 etc) | My understanding is that you are using MSSQL server. If, yes then the default datatype for any variable or nullable column is INT |
401,117 | I just accidentally pressed Ctrl+Shift+W again and lost some work. I like using CTRL+W for individual windows, but I never want to close everything. Is there a way to disable this on Chrome? | 2012/03/15 | [
"https://superuser.com/questions/401117",
"https://superuser.com",
"https://superuser.com/users/119475/"
] | Complete version of this script. Works on new AHK versions.
* Works with any input language (assigned to key code, not key as letter)
* Only one running instance (SingleInstance force)
* Doesn't recording history of pressed keys (KeyHistory 0)
* Prevents from Ctrl+Shift+W and Ctrl+Shift+Q in Chrome
```
#NoEnv ; Recommended for performance and compatibility with future AutoHotkey releases.
#SingleInstance force;
#KeyHistory 0 ;
SendMode Input ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir% ; Ensures a consistent starting directory.
SetTitleMatchMode, Regex
#IfWinActive, ahk_class Chrome_WidgetWin_1
^+SC011::
;do nothing
return
^+SC010::
;do nothing
return
#IfWinActive
``` | Here is the autohotkey code to disable ctrl+w and ctrl+q for the tab named test1 and test2 (test1 is the title that appears on your tab. You can use also use autohotkey spy to figure out more stuff)
```
SetTitleMatchMode, Regex
#If WinActive("test1 ahk_class Chrome_WidgetWin_1") || WinActive("test2 ahk_class Chrome_WidgetWin_1")
^w::
^q::
return ; do nothing
#IfWinActive
```
credit to [Raj](https://superuser.com/a/782979/235752) and [this guy](https://autohotkey.com/boards/viewtopic.php?f=5&t=39492&p=180605#p180605) |
34,493,305 | I just started to learn Swift and xcode and the first problem that I'm facing is how and where should I place the json file ? And how to use those files? Should I place the .json files within Assets folder ? Since I find it difficult, I would love to hear some tips or examples from you ! | 2015/12/28 | [
"https://Stackoverflow.com/questions/34493305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3264924/"
] | Please review the below image to check where to place the file.
I suggest you to create a group and add the file in that.[](https://i.stack.imgur.com/Jy7nb.png)
After that, review the below could for using that file.
Edit: This is the updated code for Swift 5 if that helps anyone.
```
let path = Bundle.main.path(forResource: "filename", ofType: "json")
let jsonData = try? NSData(contentsOfFile: path!, options: NSData.ReadingOptions.mappedIfSafe)
``` | As per your requirement, you want to read json from that json file.
I am using SWIFTY JSON Library for that.
Find below the link for that
<https://github.com/SwiftyJSON/SwiftyJSON>
Add this library to your project.
After adding it, now review the below code:-
```
let json = JSON(data: jsonData!)
for (index, subjson): (String, JSON) in json{
let value = subjson["key"].stringValue
}
``` |
1,301,581 | The behaviour of `git commit -a` seems to be to include changes to submodules, if they have new commits inside them. This isn't what I normally want, and I sometimes find myself accidentally pushing a commit with submodule changes that I didn't intend to include.
Is there a way to set `git commit -a` to ignore submodules? I had a look in `git help config` and didn't see anything.
A (less good) alternative might be to get `git status` to make it clearer at a glance whether `git commit -a` would include a submodule. Currently it shows either
```
modified: submodule (modified content)
```
or
```
modified: submodule (new commits)
```
and those are annoyingly similar. It looks like the `submodule.<name>.ignore` config option can do something like what I want. But ideally I'd still like to see changes to submodules, just not in the same place as all my other changes unless `git commit -a` will add them. | 2018/03/08 | [
"https://superuser.com/questions/1301581",
"https://superuser.com",
"https://superuser.com/users/414722/"
] | You can set the submodule.ignore in git config or in the .gitmodules file.
NOTE: GIT is kind of stupid with this. If you set ignore = all, to get sane behavior with git commit -a, it will ALSO ignore the submodule in git show/diff when you EXPLICITLY add them. The only way to work-around the latter is using the command line option --ignore-submodule=none.
NOTE2: The diff.ignoreSubmodules config is supposed to be able to set the default command line option --ignore-submodule, but has been broken for years, and does nothing as .gitmodules wins the contest, so only explicit command line options will get you sane behavior. | If you don't have a ton of submodules, what I found the most convenient is to first commit all, then run
>
> git reset HEAD^1 submodule\_path
>
>
>
You can always get a reminder of this command syntax if you run git commit --amend without any change. It will show up near the top of the commented instructions. |
21,964,936 | I'm a newbie to design pattern. And I'm trying to learn some design patterns.
I read blogs online and most of them directly show me that: this is the simple factory and this is how we use it.
I understand inheritance and interfaces, and I'm using Java, of course, I don't have a lot of experience in design systems.
My question is that: what if we don't use the factory design pattern? I mean, can someone give a case that I'll get myself into a mess if I don't use factory design pattern? | 2014/02/23 | [
"https://Stackoverflow.com/questions/21964936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3342557/"
] | Because it's the most reasonable & useful thing that could happen when you only have 8 bits of space.
Discarding the *lowermost* bit would be a bad idea because now you can no longer increment the integer to get the next integer mod 28, etc... it would become useless as soon as it overflowed.
Discarding any other bit in the middle would be bizarre, and any other kind of awkward transformation would effectively border on insanity. | C is a low level language, which maps closely to actual hardware. Underneath the type `char`, there is an assumption that the CPU has an 8-bit register, consisting of fixed amount of transistors and wires.
As the computer can't grow the number of physical resources, the type `char` is chosen to represent integers *modulo* 256.
On a computer architecture, where the primitive resource is an 9-bit unit, char holds 9 bits.
High level languages, which are often interpreted, OTOH can and do often "grow" the variable width. |
11,143,892 | I have a question about string in TCL:
```
HANDLE_NAME "/group1/team1/RON"
proc HANDLE_NAME {playerName} {
#do something here
}
```
we pass the string "/group1/team1/RON" to the proc, but somewhere inside of the HANDLE\_NAME, we only need the last part which is "RON", how to operate the input string and get the last part of the input(only RON) and set it to a variable?
can anyone help? | 2012/06/21 | [
"https://Stackoverflow.com/questions/11143892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | ```
proc HANDLE_NAME {playerName} {
set lastPart [lindex [split $playerName "/"] end]
# ...
}
``` | Using string last to find the last forward slash. Then use string range to get the text after that.
<http://tcl.tk/man/tcl8.5/TclCmd/string.htm>
```
set mystring "/group1/team1/RON"
set slash_pos [string last "/" $mystring]
set ron_start_pos [incr slash_pos]
set ron [string range $mystring $ron_start_pos end]
``` |
1,558,243 | I need to store the datetime in CST timezone regardless of any timezone given.
The Clients who access the application are from from various time zones, like IST, CST, EST,...
I need to store all the datetime entered by the client in CST timezone to my database. And while retrieving, i need to convert back to there local timezone.
How to achieve it? | 2009/10/13 | [
"https://Stackoverflow.com/questions/1558243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/111435/"
] | It is generally accepted to store all datetime values in your DB in the GMT/UTC format.
For those who want to render the UTC value to a particular time zone for different users of the application, like wilpeck mentioned, it's suggested that you determine the end users locale and:
* when persisting, store the locale with the UTC date value
* when reading, render the UTC value to local time with the associated locale value
**EDIT:**
For example:
You might have a table with a field **StartDateTime** so to support multiple time zones you might have an additional field **StartDateTimeOffset**. If the client is in the Indian Standard Time (IST) zone you might have a datetime value of 2009/10/13 14:45 which is 2009/10/13 09:15 in UTC. So you would store the UTC value (2009/10/13 09:15) in the field **StartDateTime** and store the offset +05:30 in the **StartDateTimeOffset** field. Now when you read this value back from the DB you can use the offset to convert the UTC datetime value (2009/10/13 09:15) back to the local time of 2009/10/13 14:45. | **Try like this.**
```
DateTime clientDateTime = DateTime.Now;
DateTime centralDateTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(clientDateTime, "Central Standard Time");
```
**Time Zone Id**
```
DateTime currentTime = DateTime.Now;
Console.WriteLine("Current Times:");
Console.WriteLine();
Console.WriteLine("Los Angeles: {0}",
TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "Pacific Standard Time"));
Console.WriteLine("Chicago: {0}",
TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "Central Standard Time"));
Console.WriteLine("New York: {0}",
TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "Eastern Standard Time"));
Console.WriteLine("London: {0}",
TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "GMT Standard Time"));
Console.WriteLine("Moscow: {0}",
TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "Russian Standard Time"));
Console.WriteLine("New Delhi: {0}",
TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "India Standard Time"));
Console.WriteLine("Beijing: {0}",
TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "China Standard Time"));
Console.WriteLine("Tokyo: {0}",
TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "Tokyo Standard Time"));
```
<https://learn.microsoft.com/en-us/dotnet/api/system.timezoneinfo.converttimebysystemtimezoneid?view=netcore-3.1>
<https://www.c-sharpcorner.com/blogs/how-to-convert-a-datetime-object-into-specific-timezone-in-c-sharp> |
22,773,929 | I received a memory error while working on a project with Table View.
I replicated the storyboard on a new project and received the same error.
---
**Here's the storyboard layout:**
[01 - The Storyboard](http://i93.photobucket.com/albums/l47/carlodurso/Capturadepantalla2014-03-31alas173248_zps6ff44ae4.png)
**If the "Back" button is pressed while the Delete button is shown then I get a memory error as below:**
[02 - Running app and Memory error](http://i93.photobucket.com/albums/l47/carlodurso/Captura-de-pantalla2_zps240d75ec.png)
---
The code used for deletion is:
```
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
// Remove the row from data model
[tableData removeObjectAtIndex:indexPath.row];
// Request table view to reload
[tableView reloadData];
}
```
I'm posting this question in order to learn more about Xcode and Objective-C.
1. Has anyone experienced something similar?
2. What process should I follow to debug this error?
3. Is there a Apple procedure to report this kind of errors? | 2014/03/31 | [
"https://Stackoverflow.com/questions/22773929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1672895/"
] | >
> I'm following the spec here and I'm not sure whether it allows onFulfilled to be called with multiple arguments.
>
>
>
Nope, just the first parameter will be treated as resolution value in the promise constructor. You can resolve with a composite value like an object or array.
>
> I don't care about how any specific promises implementation does it, I wish to follow the w3c spec for promises closely.
>
>
>
That's where I believe you're wrong. The specification is *designed to be minimal* and is built for interoperating between promise libraries. The idea is to have a subset which DOM futures for example can reliably use and libraries can consume. Promise implementations do what you ask with `.spread` for a while now. For example:
```
Promise.try(function(){
return ["Hello","World","!"];
}).spread(function(a,b,c){
console.log(a,b+c); // "Hello World!";
});
```
With [Bluebird](https://github.com/petkaantonov/bluebird). One solution if you want this functionality is to polyfill it.
```
if (!Promise.prototype.spread) {
Promise.prototype.spread = function (fn) {
return this.then(function (args) {
return Promise.all(args); // wait for all
}).then(function(args){
//this is always undefined in A+ complaint, but just in case
return fn.apply(this, args);
});
};
}
```
This lets you do:
```
Promise.resolve(null).then(function(){
return ["Hello","World","!"];
}).spread(function(a,b,c){
console.log(a,b+c);
});
```
With native promises at ease [fiddle](http://jsfiddle.net/FswX6/). Or use spread which is now (2018) commonplace in browsers:
```
Promise.resolve(["Hello","World","!"]).then(([a,b,c]) => {
console.log(a,b+c);
});
```
Or with await:
```
let [a, b, c] = await Promise.resolve(['hello', 'world', '!']);
``` | The fulfillment value of a promise parallels the return value of a function and the rejection reason of a promise parallels the thrown exception of a function. Functions cannot return multiple values so promises must not have more than 1 fulfillment value. |
184,017 | A program that will count up the number of words in a text, as well as counting how many times a certain character shows up in the text. Only ignore spaces.
This gave me a lot of trouble as I grappled with list comprehension syntax errors.
```
class TextAnalyzer:
def __init__(self, txtFile):
self.txtContent = open(txtFile)
self.txtStream = self.txtContent.read()
def __repr__(self):
return self.txtStream
def countChars(self):
characters = {}
for char in self.txtStream:
if char != ' ' and char != '\n':
if char.lower() not in characters:
characters[char.lower()] = 1
else:
characters[char.lower()] += 1
return [x for x in characters.items()]
def countWords(self):
totalWords = 0
for b, a in enumerate(self.txtStream):
if a != ' ' and a != '\n' and b != len(self.txtStream)-1 and (self.txtStream[b+1] == ' ' or self.txtStream[b+1] == '\n'):
totalWords += 1
return totalWords+1
analyze = TextAnalyzer('Darwin.txt')
totalChars = 0;
print(analyze)
for x, y in sorted(analyze.countChars()):
totalChars += y
print('{0}: {1}'.format(x, y))
print('Total Characters: ', totalChars)
print('Total Words: ', analyze.countWords())
``` | 2018/01/01 | [
"https://codereview.stackexchange.com/questions/184017",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/85459/"
] | ### Incorrect counting
For a text file that ends with a space or newline character,
the `countWords` function counts 1 more word than there really are.
Before giving away the fix, I would point out a few things about this implementation:
>
>
> ```
> totalWords = 0
> for b, a in enumerate(self.txtStream):
> if a != ' ' and a != '\n' and b != len(self.txtStream)-1 and (self.txtStream[b+1] == ' ' or self.txtStream[b+1] == '\n'):
> totalWords += 1
> return totalWords+1
>
> ```
>
>
The names `b` and `a` make this a bit hard to read.
The value of `a` is a character,
the value of `b` is the position (or index) of the character.
Better names would have been `c` and `i` (or `pos` or `index`),
and the code would be a bit easier to read.
Processing the text character by character like this is a bit complicated,
and it will get even more complicated if you add the special treatment to fix the processing at the end of the content.
A simpler way would be to split the input, and use the length of the resulting list, for example:
```
return len(self.txtStream.split())
```
However, this is not exactly the same original code, and it has a drawback too.
It's not the same, because the `split()` function of strings splits the input by any whitespace,
including TAB,
while your code splits strictly on SPACE and NEWLINE.
If you really want to use the same logic and not split on TAB,
then you would have to use the `split` function from the `re` package:
```
import re
# ...
return len(re.split('[ \n]', self.txtStream))
```
This preserves the behavior of your original code,
and fixes the off-by-1 error,
because just like the `split` function of strings,
it ignores whitespace at the end of the content.
The splitting technique has an important drawback though:
it consumes more memory,
because it creates a list of words from the content,
effectively doubling the memory use.
Your solution is harder to implement correctly and to read,
but it's more memory-efficient.
### Always close resources
There are several issues here:
>
>
> ```
> def __init__(self, txtFile):
> self.txtContent = open(txtFile)
> self.txtStream = self.txtContent.read()
>
> def __repr__(self):
> return self.txtStream
>
> ```
>
>
The biggest issue is that a filehandle is not properly closed.
When you open something, remember to close it!
Since it's so easy to forget closing filehandles,
Python has a syntax to do this automatically for you:
```
with open(txtFile) as fh:
self.content = fh.read()
```
### Class attributes vs local variables
In the `with` example in the previous section,
I renamed `self.txtContent` to `fh`,
for two reasons:
* It's a more appropriate name: `txtContent` implies some text content, which is not true and misleading. Likewise, I renamed `txtStream` to `content`, because that's what it really is. A "stream" is usually something that doesn't occupy much memory, doesn't contain the full content, but a data structure from which you can *stream* the content gradually without consuming much memory.
* Even more importantly, `self.txtContent` is not used anywhere outside the `__init__` function,
so there's no need to make it an attribute of the class, it can be a local variable.
### Avoid repeated operations
In this code, `char.lower()` is performed 3 times:
>
>
> ```
> if char.lower() not in characters:
> characters[char.lower()] = 1
> else:
> characters[char.lower()] += 1
>
> ```
>
>
Since all 3 times it will give the same result,
it would be better to do this once,
store the value in a variable and use that variable instead of repeating the call.
### Avoid repeated operations -- the bigger picture
An even more important repeated operation could be performed by users of the `TextAnalyzer` class.
Once you create an instance of this class,
the text content it read from the file will normally not change,
but calling `countChars` and `countWords` will recompute the same values over and over again.
If the class is not designed to change the value of the text content after construction,
then it would be better to not compute the character and word counts only once.
### Python conventions
There are common conventions for variable and function naming in Python,
explained in [PEP8](http://www.python.org/dev/peps/pep-0008/).
It's strongly recommended to follow that when coding in Python.
### Simplifications
Instead of this:
>
>
> ```
> if char != ' ' and char != '\n':
>
> ```
>
>
You can write like this:
```
if char not in ' \n':
```
---
Instead of this:
>
>
> ```
> return [x for x in characters.items()]
>
> ```
>
>
You can write like this:
```
return characters.items()
```
---
Instead of this:
>
>
> ```
> if char.lower() not in characters:
> characters[char.lower()] = 1
> else:
> characters[char.lower()] += 1
>
> ```
>
>
You can write like this:
```
c = char.lower()
characters[c] = characters.get(c, 0) + 1
``` | For the counting of characters, you could use the [`collections.Counter`](https://docs.python.org/3/library/collections.html#collections.Counter) class, which was introduced for exactly this. It even has a method [`most_common`](https://docs.python.org/3/library/collections.html#collections.Counter.most_common), which returns the items in order of descending occurrence. Your method would become:
```
from collections import Counter
class TextAnalyzer:
...
def countChars(self):
characters = Counter(char.lower()
for char in self.txtStream
if char not in ' \n')
return characters.most_common()
``` |
32,244,745 | I save users in a DB table via Hibernate and I am using Spring Security to authenticate:
```
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.*;
import org.springframework.security.config.annotation.authentication.builders.*;
import org.springframework.security.config.annotation.web.configuration.*;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
```
And this works perfectly, but there is a point - user is loaded during server start. I need to write method RegisterUser(User user) that add new user to Spring Security in runtime. This method should focus only on this task. I dont know how to start to implement this feature so thanks for any advices! ;)
Ofc User have fields like login, password, role string etc etc...
Please do not post solutions with Spring MVC. This system is RESTful app using Spring Web Boost and Spring Security Boost in version 4.0.x | 2015/08/27 | [
"https://Stackoverflow.com/questions/32244745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1850412/"
] | You can use [Spring Data JPA](https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#reference) for user creation.
```
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
```
usage:
```
User user = new User();
userRepository.save(user);
```
How to authenticate above user:
1. Create custom `AuthenticationProvider`, select user data from your DB and authenticate:
```
@Component
public class MyAuthenticationProvider implements AuthenticationProvider {
@Autowired
private UserRepository userRepository;
@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
final UsernamePasswordAuthenticationToken upAuth = (UsernamePasswordAuthenticationToken) authentication;
final String name = (String) authentication.getPrincipal();
final String password = (String) upAuth.getCredentials();
final String storedPassword = userRepository.findByName(name).map(User::getPassword)
.orElseThrow(() -> new BadCredentialsException("illegal id or passowrd"));
if (Objects.equals(password, "") || !Objects.equals(password, storedPassword)) {
throw new BadCredentialsException("illegal id or passowrd");
}
final Object principal = authentication.getPrincipal();
final UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(
principal, authentication.getCredentials(),
Collections.emptyList());
result.setDetails(authentication.getDetails());
return result;
}
...
```
2. Configure with `WebSecurityConfigurerAdapter` for using above `AuthenticationProvider`:
```
@EnableWebSecurity
public class MyWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
@Autowired
private MyAuthenticationProvider authProvider;
@Override
protected void configure(final HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic();
http.authenticationProvider(authProvider);
}
}
```
refs:
* [Spring Security Architecture](https://spring.io/guides/topicals/spring-security-architecture/)
* [complete code sample](https://github.com/yukihane/stackoverflow-qa/tree/master/en32244745) | use this code to add authority to current user:
```
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("ROLE_NEWUSERROLE');
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken(
SecurityContextHolder.getContext().getAuthentication().getPrincipal(),
SecurityContextHolder.getContext().getAuthentication().getCredentials(),
authorities)
);
``` |
2,044,629 | I have the following function defined on $\mathbb{R}$:
$$f(x) = \begin{cases}
0 & \text{if $x$ irrational} \\
1/n & \text{if $x = m/n$ where $m, n$ coprime}
\end{cases}$$
I want to show that $f$ is continuous at every irrational point, and has a simple discontinuity at every rational point. **I was able to show the first and partially the second** (I showed that $f$ has a discontinuity at every rational point, but got stuck on showing that the discontinuity is simple).
However, I've realized that I can simply show that $\lim\_{t \rightarrow x}f(t) = 0$ for every $x$, and both of the things I want to show follow from this. How can I show this? | 2016/12/05 | [
"https://math.stackexchange.com/questions/2044629",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/391885/"
] | Take any $x$. Let $\epsilon > 0$, and find $N$ such that $\frac1 N < \epsilon$.
Now, I claim that there is a $\delta>0$ such that if $y \in (x-\delta,x+\delta) \backslash \{ x\}$, then $y$ is not of the form $\frac mN$ for any integer $m$. Suppose not. Then, considering $\delta$ going to zero and repeatedly contradicting the statement, we get a sequence $y\_n = \frac {m\_n}N$ such that $y\_n \to x$. Now, $m\_n \to Nx$. However, remember that $m\_n$ are integers, and convergence can only happen in the integers if the sequence is eventually constant! (because different integers are at least $1$ distance from each other). So, $y\_n$ is eventually constant. You can work it out from here.
With this lemma, surely the proof is not too far away, is it? | HINTS: observe that there are **a finite number** of rationals $n/m<1$ for any fixed $m$ (observe that Im not taking into account if $n$ and $m$ are coprime or not).
Now remember that exists infinite rationals of the kind $n/p<1$ where $p$ is prime.
What happen with $m$ when you approximate a number $x$ with a rational $n/m$? |
23,879,410 | For example: if I want the function `equal?` recognize my own type or record, can I add a new behavior of `equal?`? without erasing or overwriting the old one?
Or for example if I want to make the function `"+"` accept also string? | 2014/05/27 | [
"https://Stackoverflow.com/questions/23879410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/450148/"
] | So far the solutions work less than optimal in an R6RS / R7RS environment. I was thinking generics when I started playing around with this, but I didn't want to roll my own type system. Instead you supply a predicate procedure that should ensure the arguments are good for this particular procedure. It's not perfect but it works similar to the other R5RS answers and you never redefine procedures.
I've written everything in R6RS but I imagine it's easily ported to R7RS.
Here's an example:
```
#!r6rs
(import (sylwester generic)
(rename (rnrs) (+ rnrs:+))
(only (srfi :43) vector-append))
(define-generic + rnrs:+)
(add-method + (lambda x (string? (car x))) string-append)
(add-method + (lambda x (vector? (car x))) vector-append)
(+ 4 5) ; ==> 9
(+ "Hello," " world!") ; ==> "Hello, world!"
(+ '#(1) '#(2)) ; ==> #(1 2)
```
As you can see I import `+` by a different name so I don't need to redefine it (which is not allowed).
Here's the library implementation:
```
#!r6rs
(library (sylwester generic)
(export define-generic add-method)
(import (rnrs))
(define add-method-tag (make-vector 1))
(define-syntax define-generic
(syntax-rules ()
((_ name default-procedure)
(define name
(let ((procs (list (cons (lambda x #t) default-procedure))))
(define (add-proc id pred proc)
(set! procs (cons (cons pred proc) procs)))
(add-proc #t
(lambda x (eq? (car x) add-method-tag))
add-proc)
(lambda x
(let loop ((procs procs))
(if (apply (caar procs) x)
(apply (cdar procs) x)
(loop (cdr procs))))))))))
(define (add-method name pred proc)
(name add-method-tag pred proc)))
```
As you can see I use message passing to add more methods. | In R7RS-large (or in any Scheme, really), you can use SRFI 128 comparators, which package up the ideas of equality, ordering, and hashing, in order to make generic comparisons possible. SRFI 128 allows you to create your own comparators and use them in comparator-aware functions. For example, `<?` takes a comparator object and two or more objects of the type associated with the comparator, and returns `#t` if the first object is less than the second object in the sense of the comparator's ordering predicate. |
15,990,344 | I want to select a date (my column is a timestamp type). But when in column is a NULL date, I want to return an empty string. How to do this? I wrote this:
```
SELECT
CASE WHEN to_char(last_post, 'MM-DD-YYYY HH24:MI:SS') IS NULL THEN ''
ELSE to_char(last_post, 'MM-DD-YYYY HH24:MI:SS') AS last_post END
to_char(last_post, 'MM-DD-YYYY HH24:MI:SS') AS last_post, content
FROM topic;
```
But it shows me some errors, dont really know why:
```
ERROR: syntax error at or near "as"
LINE 1: ...ELSE to_char(last_post, 'MM-DD-YYYY HH24:MI:SS') AS last_po...
^
``` | 2013/04/13 | [
"https://Stackoverflow.com/questions/15990344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1612090/"
] | Using the `COALESCE()` function is the nicest approach, as it simply swaps in a substitute value in the case of a NULL. Readability is improved greatly too. :)
```
SELECT COALESCE(to_char(last_post, 'MM-DD-YYYY HH24:MI:SS'), '') AS last_post, content FROM topic;
``` | ```
select coalesce(to_char(last_post, 'MM-DD-YYYY HH24:MI:SS'), '') as last_post, content
from topic;
``` |
3,314,479 | This is a very unspecific and maybe stupid question, so I apologize for that. We recently had an exam that I failed, because I had pretty much no time to practice before that. Now I got to learn all that stuff that I should've known, yet there was one exercise where I have no clue how one would get a result.
>
> Calculate $$\lim\_{n \to \infty}\sqrt{n} \cdot (\sqrt{n+1} - \sqrt{n}).$$
>
>
>
The solution appears to be $\frac{1}{2}$, however I have exactly no clue on how to get to that.
If someone could throw a keyword at me, that would lead me on my path, it could already be very helpful. | 2019/08/05 | [
"https://math.stackexchange.com/questions/3314479",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/693803/"
] | $$\lim\_{n \to \infty}\sqrt{n} \cdot (\sqrt{n+1} - \sqrt{n})=
\lim\_{n \to \infty}\sqrt{n} \cdot \frac{(\sqrt{n+1} - \sqrt{n})}{1}=
\lim\_{n \to \infty}\sqrt{n} \cdot \frac{(\sqrt{n+1} - \sqrt{n})(\sqrt{n+1} + \sqrt{n})}{(\sqrt{n+1} + \sqrt{n})}=
\lim\_{n \to \infty}\sqrt{n}\cdot \frac{n+1-n}{\sqrt{n+1}+\sqrt n}=
\lim\_{n \to \infty}\sqrt{n}\cdot \frac1{\sqrt{n+1}+\sqrt n}= \lim\_{n\to \infty}\frac{\sqrt{n}}{\sqrt n}\cdot\frac1{\sqrt{1+\frac1n}+1}=\lim\_{n \to \infty} \frac1{\sqrt{1+\frac1n}+1}= \frac1{2}$$ | $$\lim\_{h\to0^+}\frac{\sqrt{\dfrac 1h+1}-\sqrt{\dfrac 1h}}{\sqrt h}=\lim\_{h\to0}\frac{\sqrt{h+1}-1}h=\left.(\sqrt{x+1})'\right|\_{x=0}=\frac12.$$ |
23,808,808 | I want to create a dynamic variable in the loop.
I found something about eval and window but I don't know how to use this.
This is my loop and i want to create a 9 variables names from m1 to m9. I mean that the name of variable must be m1 to m9
```
for(i=1; i<10; i++){
var m+i = "Something"
}
```
Please help me with this. Really appreciate. | 2014/05/22 | [
"https://Stackoverflow.com/questions/23808808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3422998/"
] | You don't want to create 9 variables. Trust me. You want to create an object.
```
var m = {};
for(var i=1; i<10; i++){
m[i] = "Something";
}
```
You can also create an array (`m = []`), but since you are starting at `1` and not `0`, I'd suggest an object. | ```
var object = {};
var name = "m";
for(i=1; i<10; i++){
object[name+i] = "Something";
}
console.log(object.m1); // "Something", same for m2,m3,m4,m5...,m9
```
However consider if the `"m"` is really necessary, arrays are way faster:
```
var array = [];
for(i=1; i<10; i++){
array.push("Something");
}
console.log(array[0]); // "Something", same for 1,2,...,8
``` |
158,808 | The same chip can be run at 5v or 3.3v so it's tolerant to 5v so why when I run it at 3.3v can't I send in a 5v signal on an input pin? Curious on what's in the chip that makes this a bad idea. | 2015/03/08 | [
"https://electronics.stackexchange.com/questions/158808",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/61951/"
] | This is to expand on [Olin's comment about protection diodes](https://electronics.stackexchange.com/questions/158808/why-cant-the-atmega328p-accept-5-and-3-3v-signals-at-the-same-time#comment322573_158808).
The protection diode will clamp the 5V input, and it can be damaged in the process.

(fig. 10-1 from p.60 in the [datasheet for ATmega32u4](http://www.atmel.com/Images/Atmel-7766-8-bit-AVR-ATmega16U4-32U4_Datasheet.pdf). Purple scribbles mine.)
On a different note. From the O.P.:
>
> The same chip can be run at 5v or 3.3v, ***so*** it's tolerant to 5v [...]
>
> [emphasis mine, N.A.]
>
>
>
There is a flaw in this reasoning. *5V tolerant* means that an IC can use 5V input *while* it's powered from +3.3V (or some other voltage lower than +5V). If the IC can use a 5V input while it's powered from a +5V supply, that doesn't constitute 5V tolerance. | Look at Table 28.1 Absolute Maximum Ratings - in that table, it says
"Voltage on any Pin except RESET
with respect to Ground ................................-0.5V to VCC+0.5V"
There will be protection diodes on the I/O pins that will prevent the voltage on the pin from going outside those limits. The "Vcc+0.5" limit applies regardless of Vcc. |
6,261,906 | I got a form with multiple comboboxes, where each combobox can be set to different values. Based on the combobox value I want to create a query filter. I want to iterate through all comboboxes and add its value to the filter if it dont say "All".
I want to do something like this:
```
XElement root = XElement.Load(fileName);
IEnumerable<XElement> selectedElements =
from el in root.Elements("OrderNum").Elements("ServiceJob")
where
for(int i = 0; i < combArray.GetLength(0); i++)
{
if(combArray[i].Text != "All")
{
(string)el.Element(combArray[i].AccessibleName) == combArray[i].Text &&
}
}
select el;
```
Any suggestions? | 2011/06/07 | [
"https://Stackoverflow.com/questions/6261906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/787007/"
] | compute how many seconds until the next minute starts, then using `setTimeout` begin rotating the pictures. Use `setInterval` to do so every 60000 milliseconds.
```
var seconds = 60 - new Date().getSeconds();
setTimeout(function(){
console.log('start');
setInterval(function(){
console.log ('iterate over pictures here');
}, 1000 * 60);
}, seconds * 1000);
```
You can read more about both functions [here](http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/) | Place the code below in the BODY of a page:
```
<img />
<script>
var start = new Date().getTime(),
i = 0,
//get the node of the image to change
img = document.getElementsByTagName('IMG')[0];
setInterval(function(){
//what time is now
var now = new Date().getTime();
if(now - start > 60000){
//initialize the counter
start = now;
//overlay with 0's -> substr(-4)
//rotate on 1440 with a modulo -> i++ % 1440
img.src = ('000' + (i++ % 1440 + 1)).substr(-4) + '.jpg';
}
}, 10000); //check every 10 sec
</script>
```
If you start with Javascript a good reference is [MDC](https://developer.mozilla.org/en/javascript) |
7,403 | I've been working on a semi-awkward query in that it uses a very high number of functions given its relatively small size and scope. I was hoping to get some feedback on any ways I could format or re-factor this better?
```
select Name ,
avg(TimeProcessing / 1000 + TimeRendering / 1000 + TimeDataRetrieval / 1000) as 'Current Month' ,
isnull(count(TimeProcessing), 0) as 'Sample' ,
min(l2.[Avg Exec Previous Month]) as 'Previous Month' ,
isnull(min(l2.[Sample Previous Month]), 0) as 'Sample' ,
min(l3.[Avg Exec Two Months Ago]) as 'Two Months ago' ,
isnull(min(l3.[Sample Two Months Ago]), 0) as 'Sample'
from marlin.report_execution_log l
inner join marlin.report_catalog c on l.ReportID = c.ItemID
left outer join ( select l2.ReportID ,
avg(TimeProcessing / 1000 + TimeRendering
/ 1000 + TimeDataRetrieval / 1000) as 'Avg Exec Previous Month' ,
count(TimeProcessing) as 'Sample Previous Month'
from marlin.report_execution_log l2
where TimeEnd between dateadd(MONTH, -2,
getdate())
and dateadd(MONTH, -1,
getdate())
group by l2.ReportID
) l2 on l.ReportID = l2.ReportID
left outer join ( select l3.ReportID ,
avg(TimeProcessing / 1000 + TimeRendering
/ 1000 + TimeDataRetrieval / 1000) as 'Avg Exec Two Months Ago' ,
count(TimeProcessing) as 'Sample Two Months Ago'
from marlin.report_execution_log l3
where TimeEnd between dateadd(MONTH, -3,
getdate())
and dateadd(MONTH, -2,
getdate())
group by l3.ReportID
) l3 on l.ReportID = l3.ReportID
group by l.ReportID, Name
order by Name
``` | 2012/01/03 | [
"https://codereview.stackexchange.com/questions/7403",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/9360/"
] | You might want to use Common Table Expression or Should use meaningful table alias in Join.
You might also want to use indexes on your date column with <= and >= operator instead of between.
Surround your column names in [] instead of single quotes. | I agree with Nil; it seems like this might be a good situation to use a Common Table Expression.
I haven't tested this out, but below is my attempt to rewrite this query using a CTE:
```
with ReportByMonth (ReportID, [Year], [Month], [Avg Exec], [Sample]) as
(
select ReportID ,
avg(TimeProcessing / 1000 + TimeRendering / 1000 + TimeDataRetrieval / 1000) as [Avg Exec] ,
datepart(YEAR, TimeEnd) as [Year] ,
datepart(MONTH, TimeEnd) as [Month] ,
count(TimeProcessing) as [Sample]
from Marlin.report_execution_log
group by
ReportID,
datepart(YEAR, TimeEnd),
datepart(MONTH, TimeEnd)
)
select Name ,
CurrentMonthReport.[Avg Exec] as [Current Month Avg Exec] ,
isnull(CurrentMonthReport.[Sample], 0) as [Current Month Sample] ,
PreviousMonthReport.[Avg Exec] as [Previous Month Avg Exec] ,
isnull(PreviousMonthReport.[Sample], 0) as [Previous Month Sample] ,
TwoMonthAgoReport.[Avg Exec] as [Two Months Ago Avg Exec] ,
isnull(TwoMonthAgoReport.[Sample], 0) as [Two Months Ago Sample]
from marlin.report_catalog c
inner join ReportByMonth CurrentMonthReport on
CurrentMonthReport.ReportID = c.ItemID
and CurrentMonthReport.Year = datepart(YEAR, getdate())
and CurrentMonthReport.Month = datepart(MONTH, getdate())
left outer join ReportByMonth PreviousMonthReport on
PreviousMonthReport.ReportID = c.ItemID
and PreviousMonthReport.Year = datepart(YEAR, dateadd(MONTH, -1, getdate()))
and PreviousMonthReport.Month = datepart(MONTH, dateadd(MONTH, -1, getdate()))
left outer join ReportByMonth TwoMonthAgoReport on
TwoMonthAgoReport.ReportID = c.ItemID
and TwoMonthAgoReport.Year = datepart(YEAR, dateadd(MONTH, -2, getdate()))
and TwoMonthAgoReport.Month = datepart(MONTH, dateadd(MONTH, -2, getdate()))
order by
Name
;
```
EDIT: I changed my query to try to match the behavior OP's original query. I changed the join for CurrentMonthReport from "left outer join" to "inner join". This means that if a particular report has not been run during this month, then it won't show up in the result.
I also included use of the isnull function and added an order by clause. |
9,709,374 | I'm just getting started with Knockout.js (always wanted to try it out, but now I finally have an excuse!) - However, I'm running into some really bad performance problems when binding a table to a relatively small set of data (around 400 rows or so).
In my model, I have the following code:
```
this.projects = ko.observableArray( [] ); //Bind to empty array at startup
this.loadData = function (data) //Called when AJAX method returns
{
for(var i = 0; i < data.length; i++)
{
this.projects.push(new ResultRow(data[i])); //<-- Bottleneck!
}
};
```
The issue is the `for` loop above takes about 30 seconds or so with around 400 rows. However, if I change the code to:
```
this.loadData = function (data)
{
var testArray = []; //<-- Plain ol' Javascript array
for(var i = 0; i < data.length; i++)
{
testArray.push(new ResultRow(data[i]));
}
};
```
Then the `for` loop completes in the blink of an eye. In other words, the `push` method of Knockout's `observableArray` object is incredibly slow.
Here is my template:
```
<tbody data-bind="foreach: projects">
<tr>
<td data-bind="text: code"></td>
<td><a data-bind="projlink: key, text: projname"></td>
<td data-bind="text: request"></td>
<td data-bind="text: stage"></td>
<td data-bind="text: type"></td>
<td data-bind="text: launch"></td>
<td><a data-bind="mailto: ownerEmail, text: owner"></a></td>
</tr>
</tbody>
```
**My Questions:**
1. Is this the right way to bind my data (which comes from an AJAX method) to an observable collection?
2. I expect `push` is doing some heavy re-calc every time I call it, such as maybe rebuilding bound DOM objects. Is there a way to either delay this recalc, or perhaps push in all my items at once?
I can add more code if needed, but I'm pretty sure this is what's relevant. For the most part I was just following Knockout tutorials from the site.
**UPDATE:**
Per the advice below, I've updated my code:
```
this.loadData = function (data)
{
var mappedData = $.map(data, function (item) { return new ResultRow(item) });
this.projects(mappedData);
};
```
However, `this.projects()` still takes about 10 seconds for 400 rows. I do admit I'm not sure how fast this would be *without* Knockout (just adding rows through the DOM), but I have a feeling it would be much faster than 10 seconds.
**UPDATE 2:**
Per other advice below, I gave **jQuery.tmpl** a shot (which is natively supported by KnockOut), and this templating engine will draw around 400 rows in just over 3 seconds. This seems like the best approach, short of a solution that would dynamically load in more data as you scroll. | 2012/03/14 | [
"https://Stackoverflow.com/questions/9709374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392044/"
] | A solution to avoid locking up the browser when rendering a very large array is to 'throttle' the array such that only a few elements get added at a time, with a sleep in between. Here's a function which will do just that:
```
function throttledArray(getData) {
var showingDataO = ko.observableArray(),
showingData = [],
sourceData = [];
ko.computed(function () {
var data = getData();
if ( Math.abs(sourceData.length - data.length) / sourceData.length > 0.5 ) {
showingData = [];
sourceData = data;
(function load() {
if ( data == sourceData && showingData.length != data.length ) {
showingData = showingData.concat( data.slice(showingData.length, showingData.length + 20) );
showingDataO(showingData);
setTimeout(load, 500);
}
})();
} else {
showingDataO(showingData = sourceData = data);
}
});
return showingDataO;
}
```
Depending on your use case, this could result in massive UX improvement, as the user might only see the first batch of rows before having to scroll. | **If using IE, try closing the dev tools.**
Having the developer tools open in IE significantly slows this operation down. I'm adding ~1000 elements to an array. When having the dev tools open, this takes around 10 seconds and IE freezes over while it is happening. When i close the dev tools, the operation is instant and i see no slow down in IE. |
8,223,570 | Here's my string:
`NANA TEKA KAOE FLASK LSKK`
How do I make it so that it'll look like this:
`HASH = {NANA => undef, TEKA => undef, KAOE => undef, ...`
Of course I could always split this into an array first
then loop through each value then assign them as hash
keys... but If there's a shorter/simpler way to do that?
Thanks in advance! | 2011/11/22 | [
"https://Stackoverflow.com/questions/8223570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/423856/"
] | `@hash{ split /\s+/, $string } = ();` | I doubt if this is the most succinct way to do it, but it seems to work:
```
use warnings;
use strict;
my $string = "NAN TEKA KAOE FLASK LSKK";
my %hash = map { ($_ => undef) } split /\s+/, $string;
foreach my $key (keys %hash)
{
printf "$key => %s\n", (defined($hash{$key})) ? $hash{$key} : "undef";
}
``` |
1,856 | I have an autoranging multimeter and many AA batteries.... how do I interpret the readings when deciding to keep or discard AA (1.5 volt) batteries? | 2010/03/13 | [
"https://electronics.stackexchange.com/questions/1856",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/-1/"
] | Look up voltage curves for the chemistry of your batteries. Depends on the exact battery, but you can gauge how much power is left based on the voltage:

From this graph, when it reads 1.0V, there is roughly 20% power left, and when it reads 0.8V, roughly 5% power left. Of course, it's hard to extract 100% of the power from a battery, since many devices require a certain voltage level to operate, and when it drops too low, they cannot run. Depends on the design of the device. | I am assuming Alkaline batteries -- In the Energizer datasheets
the capacity is specified down to 0.8V. I would discard them
if they are less the 0.8V. If it is a battery that I may not
check too often then I might set the limit at a volt or so. |
575,647 | According to [Merriam-Webster](https://www.merriam-webster.com/words-at-play/sympathy-empathy-difference):
>
> In general, 'sympathy' is when you share the feelings of another; 'empathy' is when you understand the feelings of another but do not necessarily share them.
>
>
>
This seems at odds with the information given in the answers to [How can empathy be distinguished from sympathy?](https://english.stackexchange.com/questions/343402/how-can-empathy-be-distinguished-from-sympathy), which states that:
>
> With sympathy, you feel sorry that someone else has experienced something bad even if you have no idea how they feel. With empathy, if they are sorrowful, you feel their sorrow.
>
>
>
Is Merriam-Webster wrong? | 2021/09/26 | [
"https://english.stackexchange.com/questions/575647",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/97984/"
] | Merriam-Webster's view of how *sympathy* and *empathy* differ has evolved over time. In the past eighty years, MW has attempted on three occasions (that I'm aware of) to distinguish between the two terms, and each time it has thoroughly revamped its explanation.
---
***'Sympathy' and 'empathy' in Webster's Dictionary of Synonyms (1942)***
MW's *Webster's Dictionary of Synonyms* (1942) addresses *empathy* and *sympathy* in a bundle of synonyms headed by *pity*:
>
> **Pity, compassion, commiseration, ruth, condolence, sympathy, empathy, bowels** agree in meaning a feeling for for the suffering, distress, or unhappiness of another. ... **Sympathy** (etymologically, suffering with) is often used in place of *pity* or *compassion* (as, his plight aroused her *sympathy*) or in place of condolence (as, to offer one's sympathy to a bereaved friend), but in its precise meaning, it implies a power to enter into another's emotions or experiences, whether of a sorrowful or joyful nature, as by sharing them, by truly understanding them, or by being equally affected by them; as, "a boy goes for *sympathy* and companionship to his mother and sisters, not often to his father (*A. C. Benson*); "the rebel, as a human type entitled to respect and often to *sympathy*" (*R. E. N. Dodge*); "Amid the various feelings she was aware of arousing, she let me see that *sympathy*, in the sense of a moved understanding, had always been lacking" (*E. Wharton*); "Ah, then that was it! He was a lonely old man, who didn't want to live in constant reminder of happy times past. ... Tony ... felt a quick *sympathy* with him" (*Arch. Marshall*). *Sympathy* is also applicable to to anything that engages one's interest, sometimes because one is in agreement with its aims, accomplishments, principles, or tenets, and is attached to it (as, "the stepfather was a moderate Pompeian in *sympathies*"—*Buchan*), but more often because one has the imaginative capacity to enter into it and understand it in its true nature (as, "a creative writer can do his best only with what lies within the range and character of his deepest *sympathies*"—*Cather*). **Empathy** applies to the imaginative power which enables a person, especially an artist, to understand the emotions and experiences of others and to sympathize with them. "The active power of *empathy* which makes the creative artist, or the passive power of *empathy* which makes the appreciator of art" (*Rebecca West*).
>
>
>
A fair-minded observer may see a great deal of overlap between *sympathy* as used in the quotation from Willa Cather and *empathy* as defined immediately afterward by Merriam-Webster.
---
***'Sympathy' and 'empathy' in Merriam-Webster's Dictionary of Synonyms (1984)***
Many of the entries in *Merriam-Webster's Dictionary of Synonyms* (1984) are virtually identical to their counterparts in the 1942 edition of the dictionary, aside from a smattering of replaced or additional quotations illustrating how writers use a particular word. But that is not the case with *sympathy* and *empathy*. The first change is that the synonym bundle now appears under *sympathy* instead of *pity*. But the wording of the discussions of both *sympathy* and *empathy* are completely different in 1984 from what they were in 1942:
>
> **Sympathy, pity, compassion, condolence, ruth, empathy** are comparable though often not interchangeable when they mean a feeling for the suffering or distress of another. **Sympathy** is the most general term, ranging in meaning from friendly interest or agreement in taste or opinion to emotional identification, often accompanied by deep tenderness {*sympathy* with my desire to increase my ... knowledge—*Fairchild*} {*sympathies* were ... with the Roman Stoics—*Ellis*} {satire has its roots not in hatred but in *sympathy*—*Perry*} ... **Empathy**, of all the terms here discussed, has the least emotional content; it describes a gift, often a cultivated gift, for vicarious feeling, but the feeling need not be one of sorrow; thus *empathy* is often used as a synonym for some senses of *sympathy* as well as in distinction from *sympathy* {what he lacks is not *sympathy* but *empathy*, the ability to put himself in the other fellow's place—*G. W. Johnson*} *Empathy* is frequently employed with reference to a nonhuman object (as a literary character or an idea, culture, or work of art) {a fundamental component of the aesthetic attitude is *sympathy*, or—more *accurately*—empathy. In the presence of any work of art ... the recipient ... must surrender his independent and outstanding personality, to identify himself with the form or action presented by the artist—*Read*}
>
>
>
In my opinion, the change in MW's understanding of *empathy* between 1942 and 1984 reflects the professionalization of empathy in psychology and psychiatry. From being (in 1942) primarily a power of sympathetic imagination that is most common, in its active form, in creative artists, *empathy* becomes (in 1984) primarily a mental orientation to maximize analytical insight—a cultivated gift of vicarious feeling (one thinks of a psychotherapist trained to glean the feelings of a patient without indulging in them, or of an art appreciator passively identifying with the artist without fully internalizing the artist's emotional onslaught).
---
***'Sympathy' and 'empathy' in Merriam-Webster Online (undated)***
MW's undated online article, [What's the difference between 'sympathy' and 'empathy'?](https://www.merriam-webster.com/words-at-play/sympathy-empathy-difference), if anything, doubles down on the 1984 synonym dictionary's effort to distance *empathy* from a core sense of shared sympathy:
>
> **Sympathy vs. Empathy Difference**
>
>
> The difference in meaning is usually explained with some variation of the following: sympathy is when you share the feelings of another; empathy is when you understand the feelings of another but do not necessarily share them.
>
>
> ...
>
>
> **Empathy is Understanding [whereas 'Sympathy is Sharing']**
>
>
> *Empathy* suggests the notion of projection. You have empathy for a person when you can imagine how they might feel based on what you know about that person, despite not having those feelings explicitly communicated[.]
>
>
> ...
>
>
> *Empathy* can be contrasted with *sympathy* in terms of a kind of remove, or emotional distance:
>
>
>
> >
> > The act or capacity of entering into or sharing the feelings of another is known as **sympathy**. **Empathy**, on the other hand, not only is an identification of sorts but also connotes an awareness of one's separateness from the observed. One of the most difficult tasks put upon man is reflective commitment to another's problem while maintaining his own identity. —*Journal of the American Medical Association*, 24 May 1958
> >
> >
> >
>
>
>
It is not by chance that the quotation that MW has chosen to highlight this proposed distinction comes from the official periodical of the AMA. It would hardly do for a clinician to dispense with emotional distance and perform some sort of Vulcan mind meld with a patient who is suffering emotional trauma or other mental turmoil.
---
***'Empathy' in Merriam-Webster's Eleventh Collegiate Dictionary (2003)***
It seems fair to ask whether everyday nonspecialists use *empathy* in a way that rigidly sequesters it from *sympathy* as the AMA recommends. My sense is that they do not. Still, *Merriam-Webster's Eleventh Collegiate Dictionary* (2003) studiously avoids mentioning the word *sympathy* in either of its two definitions of *empathy*:
>
> **empathy** *n* (1850) **1 :** the imaginative projection of a subjective state into an object so that the object appears to be infused with it **2 :** the action of understanding, being aware of, being sensitive to, and vicariously experiencing the feelings, thoughts, an experience of another of either the past or present without having the feelings, thoughts, and experience fully communicated in an objectively explicit manner; *also* : the capacity for this
>
>
>
I suspect that the vast majority of lay people do not use *empathy* in either of these senses. The first definition is so abstract as to be almost opaque, and the second comes across as stilted, artificial, and clinical.
---
***'Sympathy' and 'empathy' in the American Heritage Dictionary (2010)***
The entry for *empathy* in *The American Heritage Dictionary of the English Language*, fifth edition (2010) does a much better job of approximating what real-world non-experts have in mind when they use the word:
>
> **empathy** *n.* **1.** The ability to identify with or understand another's situation or feelings: *Empathy is a distinctly human capability.* ... **2.** The attribution of one's feelings to an object: *They have empathy for the evacuees who were displaced by the flood.*
>
>
>
In a discussion of a synonym bundle that includes *sympathy* and *empathy*, AHDEL writes as follows:
>
> *pity, compassion, sympathy, empathy, commiseration, condolence.* These nouns signify kindly concern aroused by the misfortune, affliction, or suffering of another. ... *Sympathy* denotes the act of or capacity for sharing in the sorrows or troubles of another: "*They had little sympathy to spare for their unfortunate enemies*" (William Hickling Prescott). *Empathy* is an identification with and understanding of another's situation, feelings, and motives: *Having changed schools several times as a child, I feel empathy for the transfer students.*
>
>
>
Although AHDEL supports the same basic split between "sympathy = sharing" and "empathy = understanding" that MW identifies—and although it, too, avoids using the word *sympathy* in its definitions of empathy—it does so in a way that permits readers to see more easily that *empathy* can involve a strong identification with another person's feelings—what one might be tempted to call *sympathy*.
---
***Conclusion***
Merriam-Webster's approach to the definitions it composes can be startlingly inconsistent. In many instances, it adopts the populist, descriptivist view that the definitions it gives for a word ought to reflect how how people use that word in the real world. But in some instances, it adopts a narrow, specialist-friendly, prescriptivist view of the proper definitions of a word, as though that word existed only in a milieu where all users were aware of and respected its precise, complicated, and nuanced technical meaning. This, I think, is what MW has done in its handling of *empathy* in recent decades, and as a result the meanings it endorses seem poorly matched to the ways in which people in the wild actually use it. | Etymology:
----------
Sympathy:
`2 Greek words`
1. *Sym*: Together
2. *Pathos*: Emotion
Empathy: `Ancient Greek`
From *empatheia*, denoting physical affection or passion [[source]](https://www.etymonline.com/word/empathy)
---
Cambridge Dictionary:
---------------------
Sympathy:
>
> (an expression of) understanding and care for someone else's suffering:
>
>
>
Empathy:
>
> the ability to share someone else's feelings or experiences by imagining what it would be like to be in that person's situation
>
>
>
Contradicts Merriam-Webster, but let's look at other dictionary entries:
---
Collins Dictionaries:
---------------------
Sympathy:
>
> If you have sympathy for someone who is in a bad situation, you are sorry for them, and show this in the way you behave towards them.
>
>
>
Empathy:
>
> Empathy is the ability to share another person's feelings and emotions as if they were your own.
>
>
>
This concurs with Cambridge, but not M-W.
---
Oxford Dictionaries:
--------------------
Sympathy:
>
> feelings of pity and sorrow for someone else's misfortune.
>
>
>
Empathy:
>
> the ability to understand and **share** the feelings of another.
>
>
>
---
As you can already see from other answers above, the words "empathy" and "sympathy" are differently defined by dictionaries. How readers will distinguish between the two will be, at least in part, how the author relays the meanings through their sentences. |
1,423,876 | Given this expression
$\displaystyle{8 \over {\sqrt 5 + 1}}$
I multiply the nominator and denominator by the conjugate:
$\displaystyle{{8 \over {\sqrt 5 + 1}} \times {{\sqrt 5 - 1}\over{\sqrt 5 -1}}}$
$\displaystyle={{8\sqrt 5 - 8} \over {\sqrt 25 - \sqrt 5 + \sqrt 5 - 1}}$
$\displaystyle={{8 \sqrt 5 - 8} \over 4}$
$={{2 \sqrt 5} -8}$
But the answer in the textbook is:
${2 \sqrt 5 -2}$
I can't see the discrepancy on my end. | 2015/09/06 | [
"https://math.stackexchange.com/questions/1423876",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/248332/"
] | We can write $\displaystyle \frac{8}{\sqrt{5}+1} = \frac{8}{\sqrt{5}+1} \times \frac{\left(\sqrt{5}-1\right)}{\left(\sqrt{5}-1\right)} = \frac{8(\sqrt{5}-1)}{(\sqrt{5})^2-(1)^2} = \frac{8(\sqrt{5}-1)}{4}= 2\sqrt{5}-2$ | \begin{align}
\ {{8 \over {\sqrt 5 + 1}} \times {{\sqrt 5 - 1}\over{\sqrt 5 -1}}}
\\ \ 8 \times {(\sqrt 5 - 1)} \over {(\sqrt 5 + 1)\times {(\sqrt 5 - 1)}}
\\ \ 8 \times \sqrt 5 - 8 \over {(\sqrt 5)^2 - 1^2}
\\ \ 8 \times \sqrt 5 - 8 \over {4}
\\ \ 2 \times \sqrt 5 - 2
\end{align} |
59,230,929 | I want to initialize `true` for `checkForBST(node* rootptr)` function. What should i do? I know variable initialization but I always get confused in function initialization. Below is my `checkForBST(node* rootptr)` function:
```
bool checkForBST(node* rootptr){
queue <node*> Q;
int parent;
int child1;
int child2;
node* parentadr;
Q.push(rootptr);
do{
parent=Q.front()->data;
parentadr= Q.front();
if(Q.front()->left !=NULL) {child1= Q.front()->left->data;} else{child1=-1;}
if(Q.front()->right !=NULL) {child2= Q.front()->right->data;} else{child2=-1;}
Q.pop();
if(child1>child2){return false;}
if(parentadr->left != NULL){Q.push(parentadr->left);}
if(parentadr->right != NULL){Q.push(parentadr->right);}
}while(!Q.empty());
}
``` | 2019/12/07 | [
"https://Stackoverflow.com/questions/59230929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11781785/"
] | * You want to put the CSV values to the active Spreadsheet.
+ In your situation, the CSV values are large which is 106,974 rows and 13 columns.
* You want to achieve this using Google Apps Script.
If my understanding is correct, how about this answer? In this answer, I would like to propose 2 patterns. Please think of this as just one of several possible answers.
Pattern 1:
----------
In this pattern, the CSV data is directly put to the active Spreadsheet using Sheets API. When [the benchmark for CSV Data to Spreadsheet using Google Apps Script is measured, it was found that the process of Sheets API is faster than that of Spreadsheet service which is using in your script.](https://gist.github.com/tanaikech/030203c695b308606041587e6da269e7) So as one of pattern, I proposed this way.
### Sample script:
When your script is modified for using Sheets API, it becomes as follows. [Before you run the script, please enable Sheets API at Advanced Google services.](https://developers.google.com/apps-script/guides/services/advanced#enabling_advanced_services)
```
function importCSVFromWeb() {
var csvUrl = "https://drive.google.com/uc?export=download&id=xxxxxxxxxxxxxxxxxxxxxxxxxx";
var csvContent = UrlFetchApp.fetch(csvUrl).getContentText();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetId = ss.getSheetByName('data').getSheetId();
var resource = {requests: [
{updateCells: {range: {sheetId: sheetId}, fields: "*"}},
{pasteData: {data: csvContent, coordinate: {sheetId: sheetId}, delimiter: ","}}
]};
Sheets.Spreadsheets.batchUpdate(resource, ss.getId());
}
```
* Please set the file ID of the CSV file to the variable of `csvUrl`.
Pattern 2:
----------
In this pattern, the CSV data is converted to Spreadsheet using the method of Files: copy of Drive API and copy the sheet to the active Spreadsheet.
### Sample script:
When your script is modified, it becomes as follows. Before you run the script, please enable Drive API at Advanced Google services.
```
function importCSVFromWeb() {
var fileIdofCSVFile = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
var id = Drive.Files.copy({title: "temp", mimeType: MimeType.GOOGLE_SHEETS}, fileIdofCSVFile).id;
var sheetName = "data";
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(sheetName).setName(sheetName + "_temp");
var tempSheet = SpreadsheetApp.openById(id).getSheets()[0];
var copiedSheet = tempSheet.copyTo(ss).setName(sheetName);
ss.deleteSheet(sheet);
DriveApp.getFileById(id).setTrashed(true);
}
```
* Please set the file ID of the CSV file to the variable of `fileIdofCSVFile`.
Note:
-----
* In your script, it supposes that the CSV file of `https://drive.google.com/uc?export=download&id=xxxxxxxxxxxxxxxxxxxxxxxxxx` is publicly shared. Please be careful this.
References:
-----------
* [Benchmark: Importing CSV Data to Spreadsheet using Google Apps Script](https://gist.github.com/tanaikech/030203c695b308606041587e6da269e7)
* [Advanced Google services](https://developers.google.com/apps-script/guides/services/advanced)
* [Method: spreadsheets.batchUpdate](https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate)
* [PasteDataRequest](https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#pastedatarequest)
* [Files: copy](https://developers.google.com/drive/api/v2/reference/files/copy)
Added: Pattern 3
----------------
In this sample script, the script of pattern 2 was modified. In this case, Drive API and Sheets API are used. So please enable both APIs at Advanced Google services.
### Sample script:
```
function importCSVFromWeb() {
var fileIdofCSVFile = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
var id = Drive.Files.copy({title: "temp", mimeType: MimeType.GOOGLE_SHEETS}, fileIdofCSVFile).id;
var sheetName = "data";
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(sheetName);
sheet.clear();
SpreadsheetApp.flush();
var tempSheet = SpreadsheetApp.openById(id).getSheets()[0];
var copiedSheet = tempSheet.copyTo(ss).getSheetId();
var resource = {requests: [
{copyPaste: {
source: {sheetId: copiedSheet, startRowIndex: 0, startColumnIndex: 0},
destination: {sheetId: sheet.getSheetId(), startRowIndex: 0, startColumnIndex: 0}
}},
{deleteSheet: {sheetId: copiedSheet}}
]};
Sheets.Spreadsheets.batchUpdate(resource, ss.getId());
DriveApp.getFileById(id).setTrashed(true);
}
``` | This function allows you to break up your array as you requested. You need to run initializeForAppCSVData first and setup the page length. It will setup the timebased trigger for you and you can adjust the time if necessary. Once the function gets to array.length it automatically deletes the trigger.
If you wish you can setup a periodic trigger to run the initializeForAppCSVData() function.
```
function initializeForAppCSVData() {
var csvUrl = "https://drive.google.com/uc?export=download&id=xxxxxxxxxxxxxxxxxxxxxxxxxx";
var csvContent = UrlFetchApp.fetch(csvUrl).getContentText();
var array = Utilities.parseCsv(csvContent);
/*var array=Utilities.parseCsv(DriveApp.getFileById("id").getBlob().getDataAsString());*/
PropertiesService.getScriptProperties().setProperty("StartIndex", 0);
PropertiesService.getScriptProperties().setProperty("PageLength", 1000);
PropertiesService.getScriptProperties().setProperty("ArrayLength", array.length);
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Data');
sh.clearContents();
setupTimeBasedTrigger();
}
function appendArrayData() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Data');
var csvUrl = "https://drive.google.com/uc?export=download&id=xxxxxxxxxxxxxxxxxxxxxxxxxx";
var csvContent = UrlFetchApp.fetch(csvUrl).getContentText();
var array = Utilities.parseCsv(csvContent);
/*var array=Utilities.parseCsv(DriveApp.getFileById("id").getBlob().getDataAsString());*/
var startIndex=Number(PropertiesService.getScriptProperties().getProperty("StartIndex"));
var pageLength=Number(PropertiesService.getScriptProperties().getProperty("PageLength"));
var arrayLength=Number(PropertiesService.getScriptProperties().getProperty("ArrayLength"));
if((startIndex + pageLength)<arrayLength) {
var start=startIndex;
var end=startIndex+pageLength;
}else{
var start=startIndex
var end=arrayLength;
deleteTrigger('appendArrayData');
}
var vA=[];
for(var i=start;i<end;i++) {
vA.push(array[i]);
}
sh.getRange(startIndex+1,1,vA.length,vA[0].length).setValues(vA);
PropertiesService.getScriptProperties().setProperty("StartIndex", startIndex+pageLength);
}
function setupTimeBasedTrigger() {
if(!isTrigger('appendArrayData')) {
ScriptApp.newTrigger('appendArrayData').timeBased().everyMinutes(5).create();
}
}
function deleteTrigger(triggerName){
var triggers=ScriptApp.getProjectTriggers();
for (var i=0;i<triggers.length;i++){
if (triggerName==triggers[i].getHandlerFunction()){
ScriptApp.deleteTrigger(triggers[i]);
}
}
}
function isTrigger(funcName){
var r=false;
if(funcName){
var allTriggers=ScriptApp.getProjectTriggers();
for(var i=0;i<allTriggers.length;i++){
if(funcName==allTriggers[i].getHandlerFunction()){
r=true;
break;
}
}
}
return r;
}
``` |
59,414,874 | i am stuck with this issue:
i configured kubeadm (cluster on one dedicated server for now).
And i installed elasticsearch using helm. it is nearly working fine, except for storage. The chart is using the default StorageClass for dynamic provisioning of PVs.
So i created a default StorageClass (kubernetes.io/gce-pd / pd-standard) and activated the DefaultStorageClass admission plugin in apiserver to enable dynamic provisioning.
But this still doesn't work. The pods still have the FailedBinding event "no persistent volumes available for this claim and no storage class is set".
I checked the helm chart of elasticsearch and it does not specify a StorageClass for its PVC, so it should work.
Also, i'm missing something else: i can't understand where kubernetes will allocate the PV on disks, i never configured it anywhere. And it's not in the StorageClass too.
I've checked that the dynamic provisioning is working, as it inserts the default StorageClass in the PVC definition:
```
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
annotations:
volume.beta.kubernetes.io/storage-provisioner: kubernetes.io/gce-pd
creationTimestamp: "2019-12-19T10:37:04Z"
finalizers:
- kubernetes.io/pvc-protection
labels:
app: kibanaelastic-master
name: kibanaelastic-master-kibanaelastic-master-0
namespace: elasticsearch
resourceVersion: "360956"
selfLink: /api/v1/namespaces/elasticsearch/persistentvolumeclaims/kibanaelastic-master-kibanaelastic-master-0
uid: 22b1c23a-312e-4b56-a0bb-17f2da372509
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 30Gi
storageClassName: slow
volumeMode: Filesystem
status:
phase: Pending
```
So what else should i check?
Any clue ? | 2019/12/19 | [
"https://Stackoverflow.com/questions/59414874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/299674/"
] | The one that you must use is `std::vector::size_type`. it is usually `std::size_t` but standard doesn't specify it. it is possible one implementation uses another type. You should use it whenever you want to refer to `std::vector` size.
`uint`, `uint64_t` and even `size_t` must not be used because in every implementation and platform the underlying vector implementation may use different types. | If you need an equality or ordinal comparison only, the best type would be the one used by vector's implementation, meaning
```
std::vector<MyType>::size_type compareVar
```
This guarantees that the type you use matches the type of vector's implementation regardless of the platform.
Note that since the type is unsigned, computing the difference between vector's size and `compareVar` would require some caution to avoid incorrect results when subtracting a larger value from a smaller one. |
14,935,323 | In my app , I am displaying all audio files using `MediaStore` and `ListAdaptor` and `CursorLoader` . But it shows all audio files (m4a,wav,ogg). I only want to show mp3 files . How can I do so ?
```
String[] from = {MediaStore.MediaColumns.TITLE};
int[] to = {android.R.id.text1};
CursorLoader cursorLoader = new CursorLoader(this,sourceUri,null,null,null,MediaStore.Audio.Media.TITLE);
Cursor cursor = cursorLoader.loadInBackground();
startManagingCursor(cursor);
ListAdapter adapter = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_1,cursor,from,to,CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
setListAdapter(adapter);
``` | 2013/02/18 | [
"https://Stackoverflow.com/questions/14935323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/971683/"
] | Please try below code
```
ContentResolver cr = context.getContentResolver();
Uri uri = MediaStore.Files.getContentUri("external");
String[] projection = null;
String sortOrder = null;
String selectionMimeType = MediaStore.Files.FileColumns.MIME_TYPE + "=?";
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("mp3");
String[] selectionArgsMp3 = new String[]{ mimeType };
Cursor allmp3Files = cr.query(uri, projection, selectionMimeType, selectionArgsmp3, sortOrder);
``` | See [THIS](http://alvinalexander.com/blog/post/java/how-implement-java-filefilter-list-files-directory) example, which displays only provided file extensions list. |
2,231 | It would be neat if you could see a users "User Rank" or "User Percentile Rating" within their profile. It could just be something like "Top 25%", "Within Top 250 Users", or "Rank: 4500 out of 6500 users", and would easily tell you where you rank based on score compared to all other users of SO.
This would increase the "game-iness" of SO, and would be another thing in addition to Score that would keep users wanting to increase their score. It would be like *"Man I only rank within the top 1500 users, damn I need to get my score up to be within the top 500. That's be awesome! Gotta go answer more questions."*
I know there's a similar request [here](https://meta.stackexchange.com/questions/1738/user-ranking-on-stackoverflow), but it's not the same as what I'm suggesting. | 2009/07/03 | [
"https://meta.stackexchange.com/questions/2231",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/7831/"
] | I was going to ask for the same feature and I found this as a related question. I think it would be fun to have the following variables:
* Reputation
* Rank
* Percentile rank
With the following values available:
* Current
* Highest | I like the numeric ranks.
I think named ranks would work too, but I can't really come up with suitable ones that I like other than **Newbie**, **Student** and **Freshman** (these aren't meant to be programming specific)
I was thinking something like
```
Newbie 1-500
Student 500-1k
Freshman 1k-5k
Graduate 5k-20k
``` |
6,051 | I am wondering if it is better to start to ride a fixie with a relatively low gear, and as experience comes, switch to a higher gear, or if the advised practice would be to start with a higher gear, and then perhaps change it to a lower gear.
I know you need to be strong to go uphill with a high gear, but you also need experience to go downhill fast with a low gear, so which would be considered more "expert"?
EDIT: I am not planning to ride on a track, rather on open road with rolling terrain and possibility of hills (not extra-steep, I care about my knees). | 2011/09/13 | [
"https://bicycles.stackexchange.com/questions/6051",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/2355/"
] | In general I would recommend starting low. Your legs will go through an adjustment period and you may find that your knees get sore from a larger gear. After you've ridden for a few weeks pay attention to how you're riding. If you're in a hilly area are you struggling to get up the hills? Do you find that your cadence is regularly high enough that your hips are bouncing on the saddle? There are both indications that you should adjust your gearing high or low respectively.
It's can be cheaper to replace a track cog than a front chain ring so start with 16T in the back and then pick a chainring that gets you into the gear you're looking for. With any luck, if you do need to make an adjustment up or down switching the rear cog won't force you to change your chain length. | Just to provide a little perspective, track bikes on velodrome run 81" (=48x16) at a minimum. This is used as a "warm-up" gear ratio and is considered very light. After the warm-up the gears go into the 90's for specific work-outs or competition. Generally speaking, higher gear ratios are used for solo time-trial events like the flying 200m where riders wind-up and max-out at a particular cadence. Lower gears are used for points races where riders need to accelerate often and modulate their speed.
81" is borderline miserable on the road if there are any hills or stop-and-go traffic. Anything higher is not practical on the road unless you're a dare-devil and are willing to ride through intersections without stopping or have legs like the incredible hulk.
I have a utility bike set-up as a fixed and it is 40x16 (=67.5"). This is low enough for hills and for trails but decidedly NOT a work-out bike.
A good practical range for the street would be high-60's to high-70's depending on your terrain and what you're willing to push. If you're new to this I recommend a high-60's ratio and set it up so that the rear axle is near the front limit of the drop-out. You can then get smaller cogs and experiment with higher gear ratios as needed. Swapping out cogs should be easy with a little practice. |
44,429,996 | I'm trying to use a component I created inside the AppModule in other modules. I get the following error though:
>
> "Uncaught (in promise): Error: Template parse errors:
>
>
> 'contacts-box' is not a known element:
>
>
> 1. If 'contacts-box' is an Angular component, then verify that it is part of this module.
> 2. If 'contacts-box' is a Web Component then add 'CUSTOM\_ELEMENTS\_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
>
>
>
My project structure is quite simple:
[](https://i.stack.imgur.com/7O7Cw.png)
I keep my pages in pages directory, where each page is kept in different module (e.g. customers-module) and each module has multiple components (like customers-list-component, customers-add-component and so on). I want to use my ContactBoxComponent inside those components (so inside customers-add-component for example).
As you can see I created the contacts-box component inside the widgets directory so it's basically inside the AppModule. I added the ContactBoxComponent import to app.module.ts and put it in declarations list of AppModule. It didin't work so I googled my problem and added ContactBoxComponent to export list as well. Didn't help. I also tried putting ContactBoxComponent in CustomersAddComponent and then in another one (from different module) but I got an error saying there are multiple declarations.
What am I missing? | 2017/06/08 | [
"https://Stackoverflow.com/questions/44429996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6213413/"
] | In my case, my app had multiple layers of modules, so the module I was trying to import had to be added into the module parent that actually used it `pages.module.ts`, instead of `app.module.ts`. | The problem in my case was missing component declaration in the module, but even after adding the declaration the error persisted. I had stop the server and rebuild the entire project in VS Code for the error to go away. |
41,157,092 | ```
vector<int> input = {1, 2, 3, 4, 17, 117, 517, 997};
cout<< "input vector at index -1 is: " << input[-1] <<endl;
```
Using the above the code, the result will be: input at index -1 is: 0.
However, if we use follwoing :
```
vector<int> input = {1, 2, 3, 4, 17, 117, 517, 997};
cout<< "input vector at index -1 is: " << input.at(-1) <<endl;
```
The result would be :
input at index -1 is: libc++abi.dylib: terminating with uncaught exception of type std::out\_of\_range: vector.
Can some one explain the reason to me? Thank you. | 2016/12/15 | [
"https://Stackoverflow.com/questions/41157092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7300250/"
] | The `at` member does range-checks and responds appropriately.
The `operator []` does not. This is undefined behavior and a bug in your code.
This is explicitly stated in the docs. | The first is undefined behavior. Anything could happen. You aren't allowed to complain, no matter what happens.
The second, an exception is thrown and you don't catch it, so `std::terminate()` is called and your program dies. The end. |
18,591 | I know i am going to make a very basic question, but: how to you manage
all sound effects recorded on the dialogue mono track with the boom mic, do they stay there while everything else is rerecorded in stereo ?
the issue is about creating a stereo image of all ambients effects etc
(the final target is a 2.1 mix) | 2013/03/18 | [
"https://sound.stackexchange.com/questions/18591",
"https://sound.stackexchange.com",
"https://sound.stackexchange.com/users/5697/"
] | There is a small sample from the Purcell book available that covers PFX and guide tracks. It is available form the Focal site: <http://www.focalpress.com/uploadedFiles/Books/Book_Media/Film_and_Video/Dialogue%20Editing.pdf> | You might want to read the Book by John Purcell 'Dialogue editing...' which is about cutting and editing dialogue tracks.
If you cut out PFX from the dialogue track, you should fill that gap with roomtone. That way you can mix (and pan) those PFX independently from the dialogue track. |
54,380,301 | the following code throws a NullPointerException and I'm not sure why. If someone could point me to the error it would be much apprecciated.
The code from the MainActivity, the error is in line 4:
```
private void init(){
this.createClassifier();
this.takePhoto();
}
private void createClassifier(){
try {
classifier = ImageClassifierFactory.create(
getAssets(),
Constants.GRAPH_FILE_PATH,
Constants.LABELS_FILE_PATH,
Constants.IMAGE_SIZE,
Constants.GRAPH_INPUT_NAME,
Constants.GRAPH_OUTPUT_NAME);
}catch (IOException e) {
Log.e("MainActivity", e.getMessage());
}
}
private Classifier classifier;
...
private final void classifyAndShowResult(final Bitmap croppedBitmap){
runInBackground((new Runnable(){
public final void run(){
Result result = classifier.recognizeImage(croppedBitmap);
showResult(result);
}
}));
}
```
There are different methods calling init(), so I can't figure out why classifier doesn't get initialised.
The result class:
```
public class Result {
private String result;
private float confidence;
public Result(String result, float confidence) {
this.result = result;
this.confidence = confidence;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public float getConfidence() {
return confidence;
}
public void setConfidence(float confidence) {
this.confidence = confidence;
}
}
```
the classifier Interface:
```
public interface Classifier {
Result recognizeImage(Bitmap bitmap);
```
and the initiated recognizeImage:
```
public Result recognizeImage(Bitmap bitmap){
preprocessImageToNormalizedFloats(bitmap);
classifyImageToOutputs();
PriorityQueue outputQueue = new PriorityQueue(getResults());
Object queue = outputQueue.poll();
return (Result)queue;
}
```
The error code was: java.lang.NullPointerException: Attempt to invoke interface method 'classifier.Result classifier.Classifier.recognizeImage(android.graphics.Bitmap)' on a null object reference
ImageClassifier Constructor:
```
public ImageClassifier(String inputName, String outputName, long imageSize, List labels, int[] imageBitmapPixels, float[] imageNormalizedPixels, float[] results, TensorFlowInferenceInterface tensorFlowInference) {
this.inputName = inputName;
this.outputName = outputName;
this.imageSize = imageSize;
this.labels = labels;
this.imageBitmapPixels = imageBitmapPixels;
this.imageNormalizedPixels = imageNormalizedPixels;
this.results = results;
this.tensorFlowInference = tensorFlowInference;
}
```
ImageClassifierFactory Class:
```
public class ImageClassifierFactory {
public final static Classifier create(AssetManager assetManager, String graphFilePath, String labelsFilePath, int imageSize, String inputName, String outputName) throws IOException {
List labels = getLabels(assetManager, labelsFilePath);
ImageClassifier im = new ImageClassifier(inputName, outputName, (long)imageSize, labels, new int[imageSize * imageSize], new float[imageSize * imageSize * COLOR_CHANNELS], new float[labels.size()], new TensorFlowInferenceInterface(assetManager, graphFilePath));
return im;
}
```
} | 2019/01/26 | [
"https://Stackoverflow.com/questions/54380301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10956565/"
] | We don't really have all of the pieces together for that – yet.
I'd take a look through this issue: <https://github.com/dart-lang/sdk/issues/34343>
I'll find the right person on the team to reply here with more details. | We can build Dart project to a native app via `dart2native`.
For example we have `main.dart`:
```
import 'package:ansicolor/ansicolor.dart';
main(List<String> arguments) {
AnsiPen greenPen = AnsiPen()..green();
AnsiPen greenBackGroundPen = AnsiPen()..green(bg: true);
AnsiPen redTextBlueBackgroundPen = AnsiPen()..blue(bg: true)..red();
AnsiPen boldPen = AnsiPen()..white(bold: true);
AnsiPen someColorPen = AnsiPen()..rgb(r: .5, g: .2, b: .4);
print(greenPen("Hulk") + " " + greenBackGroundPen("SMASH!!!"));
print(redTextBlueBackgroundPen("Spider-Man!!!") + " " + boldPen("Far From Home!!!"));
print(someColorPen("Chameleon"));
print('\x1B[94m' + "hahAHaHA!!!" + '\x1B[0m');
}
```
And `pubspec.yaml` as
```
name: colored_text_test
description: A sample command-line application.
environment:
sdk: '>=2.1.0 <3.0.0'
dependencies:
ansicolor: ^1.0.2
dev_dependencies:
test: ^1.0.0
```
We can use command `dart2native.bat bin\main.dart` and get `main.exe` as executable output.
Also we can specify name by using `-o` option: `dart2native main.dart -o my_app` |
62,914,318 | I came across this code snippet from a blog who was asking for it's output and an explanation.
```
#include<stdio.h>
int main()
{
int *const volatile p = 5;
printf("%d\n",5/2+p);
return 0;
}
```
Here's what I understand so far:
1.The const and volatile keywords don't contribute in context of the output
2.This code is a bad one as it performs arithmetic operation between an int\* and an int without a proper cast.
3.I initially assumed the output should be undefined. The blog stated the answer to be 13 (which what i experimentally found).
Q.What I don't understand is how was 13 obtained, was it the outcome of an undefined behavior from the compiler?
4.I used gdb and determined that the crux lies in the operation `p+2` , where p is the pointer (holding value 5) and 2 is the outcome of integer division (5/2). | 2020/07/15 | [
"https://Stackoverflow.com/questions/62914318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6698587/"
] | It is undefined behavior indeed, but not due to the arithmetic. Due to the wrong conversion specifier to print a pointer - `%d` instead of `%p` with an argument cast to `void *` - and to initialize a pointer by an non-zero `int` value.
To the arithmetic itself:
If the size of an `int` is `4`/ `sizeof(int) == 4` (as it seems to be on your platform) the result is `13` because you increment the pointer value by 2.
You increment by `2` because at `5/2` is happening integer arithmetic and the fraction part of `2.5` will be discarded.
When starting from `5`, it adds 2 `4`er steps.
```
sizeof(int) == 4
5 + (sizeof(int) * 2) == 13
```
OR
`5` + `8` = `13`.
But as said above, it is undefined behavior due to the wrong conversion specifier and to assign a pointer by an non-zero `int` value.
---
For the integer initialization of the pointer:
["Pointer from integer/integer from pointer without a cast" issues](https://stackoverflow.com/q/52186834/12139179)
For the wrong conversion specifier:
[How to print the address value of a pointer in a C program?](https://stackoverflow.com/questions/48309094/) | Depending on the fact that the sizeof(int) == 4, then the command
```
int *const volatile p = 5;
```
assigns to the pointer, as initial address, (something like) 0x0005
5 is not a value, but the address, as you have not allocated some memory for it. Then, on the result of printf(), the result is 2+p, which means pointer arithmetics. The pointer is of type int, therefore, you add on its address 2 positions away. Thus, 2 sizeof(int) further is 2 \* 4 = 8. Conclusively, the address where the pointer points is 5+8 = 13.
For example, you can remove the keywords *volatile and const* to understand that they do not affect the result. Also, you print out the address where the pointer refers, but not the subject of it(or the result of de-referencing to that address) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.