text:
Q: Who is calling the Java Thread interrupt() method if I'm not? I've read and re-read Java Concurrency in Practice, I've read several threads here on the subject, I've read the IBM article Dealing with InterruptedException and yet there's something I'm simply not grasping which I think can be broken down into two questions:

*

*If I'm never ever interrupting other threads myself, what can trigger an InterruptedException?

*If I'm never ever interrupting other threads myself using interrupt() (say because I'm using other means to cancel my working threads, like poison pills and while (!cancelled) style loop [as both explained in JCIP]), what does an InterruptedException then mean?  What am I supposed to do upon catching one?  Shutdown my app?

A: As others have pointed out, interrupting a thread (actually, interrupting a blocking call) is usually used for purposes of exiting cleanly or cancelling an ongoing activity.
However, you should not treat an InterruptedException alone as a "quit command". Instead, you should think of interrupts as a means to control the running status of threads, much in the same way as Object.notify() does. In the same way that you'd check the current state after waking up from a call to Object.wait() (you don't assume that the wakeup means your wait condition has been satisfied), after being nudged with an interrupt you should check why you were interrupted. There is usually a way to do this. For example, java.util.concurrent.FutureTask has an isCancelled() method.
Code sample:
public void run() {
    ....
    try {
        .... // Calls that may block.
    } catch (InterruptedException e) {
        if (!running) {  // Add preferred synchronization here.
            return; // Explicit flag says we should stop running.
        }
        // We were interrupted, but the flag says we're still running.
        // It would be wrong to always exit here. The interrupt 'nudge'
        // could mean something completely different. For example, it
        // could be that the thread was blocking on a read from a particular
        // file, and now we should read from a different file.
        // Interrupt != quit (not necessarily).
    }
    ....
}
public void stop() {
    running = false; // Add preferred synchronization here.
    myThread.interrupt();
}

A: The Thread interrupt mechanism is the preferred way to get a (cooperating) thread to respond a request to stop what it is doing.  Any thread (including the thread itself I think) could call interrupt() on a Thread.
In practice, the normal use-cases for interrupt() involve some kind of framework or manager telling some worker thread to stop what they are doing.  If the worker thread is "interrupt aware" it will notice that it has been interrupted via an exception, or by periodically checking its interrupted flag.  On noticing that it has been interrupted, a well-behaved thread would abandon what it is doing and end itself.
Assuming the above use-case, your code is likely to be interrupted if it is run within a Java framework or from some worker thread.  And when it is interrupted, your code should abandon what it is doing and cause itself to end by the most appropriate means.  Depending on how your code was called, this might be done by returning or by throwing some appropriate exception.  But it probably should not call System.exit().  (Your application does not necessarily know why it was interrupted, and it certainly does not know if there are other threads that need to be interrupted by the framework.)
On the other hand, if your code is not designed to run under the control of some framework, you could argue that the InterruptedException is an unexpected exception; i.e. a bug.  In that case, you should treat the exception as you would other bugs; e.g. wrap it in an unchecked exception, and catch and log it at the same point you deal with other unexpected unchecked exceptions.  (Alternatively, your application could simply ignore the interrupt and continue doing what it was doing.)

1) If I'm never ever interrupting other threads myself, what can trigger an InterruptedException?

One example is if your Runnable objects are executed using an ExecutorService and shutdownNow() is called on the service.  And in theory, any 3rd-party thread pool or thread management framework could legitimately do something like this.

2) If I'm never ever interrupting other threads myself using interrupt() ... what does an InterruptedException then mean? What am I supposed to do upon catching one? Shutdown my app?

You need analyze the codebase to figure out what is making the interrupt() calls and why.  Once you have figured that out, you can work out what >>your<< part of the app needs to do.
Until you know why InterruptedException is being thrown, I would advise treating it as a hard error; e.g. print a stacktrace to the log file and shut down the app.  (Obviously, that's not always the right answer ... but the point is that this is "a bug", and it needs to be brought to the attention of the developer / maintainer.)

3) How do I find out who / what is calling interrupt()?

There is no good answer to this.  The best I can suggest is to set a breakpoint on the Thread.interrupt() and look at the call stack.

A: The problem with the question is "I". "I" usually refers to a single instance of a class. I mean by that, that any particular piece of low-level code (class) should not rely upon the implementation of the entire system. Having said that you do have make some "architectural" decisions (like what platform to run on).
Possible unexpected interrupts coming from the JRE are canceled tasks in java.util.concurrent and shutting down applets.
Handling of thread interrupts is usually written incorrectly. Therefore, I suggest the architectural decision to avoid causing interrupts where possible. However, code handling interrupts should always be written correctly. Can't take interrupts out of the platform now.

A: You could learn this by creating your own thread class (extending java.lang.Thread) and overriding interrupt() method, in which you record the stacktrace into, say, a String field, and then transfer to super.interrupt().
public class MyThread extends Thread {

    public volatile String interruptStacktrace; // Temporary field for debugging purpose.

    @Override
    public void interrupt() {
        interruptStacktrace = dumpStack(); // You implement it somehow...

        super.interrupt();
    }
}

A: If you decide to integrate your code with other libraries, they can call interrupt() on your code. e.g. if you decide in the future to execute your code within an ExecutorService, then that may force a shutdown via interrupt().
To put it briefly, I would consider not just where your code is running now, but in what context it may run in the future. e.g. are you going to put it in a library ? A container ? How will other people use it ? Are you going to reuse it ?

A: As already mentioned, another library can interrupt your threads. Even if the library doesn't have explicit access to the threads from your code, they can still get the list of threads that are running and interrupt them that way with the following method.

A: I think I understand why you are a bit confused about interruption. Please consider my answers in line:

If I'm never ever interrupting other threads myself, what can trigger an InterruptedException?

Firstly you may interrupt other threads; I know that in JCiP it is mentioned that you should never interrupt threads you do not own; however, this statement has to be properly understood. What it means is that your code which might be running in any arbitrary thread should not handle interruption because since it is not the owner of the thread it has no clue of its interruption policy. So you may request interruption on other threads, but let its owner take the course of interruption action; it has the interruption policy encapsulated within it, not your task code; at least be courteous to set the interruption flag!
There are many ways why there could be interruptions still, may be timeouts, JVM interrupts etc.

If I'm never ever interrupting other threads myself using interrupt() (say because I'm using other means to cancel my working threads, like poison pills and while (!cancelled) style loop [as both explained in JCIP]), what does an InterruptedException then mean? What am I supposed to do upon catching one? Shutdown my app?

You need to be very careful here; if you own the thread which threw InterruptedException (IE), then you know what to do upon catching it, say you may shutdown your app/service or you may replace this killed thread with a new one! However, if you do not own the thread then upon catching IE either rethrow it higher up the call stack or after doing something (may be logging), reset the interrupted status so that the code which owns this thread, when control reaches it, may learn that the thread was interrupted and hence take actions as it will since only it knows the interruption policy.
Hope this helped.

A: The InterruptedException says that a routine may be interrupted, but not necessarily that it will be.
If you don't expect the interrupt then you should treat it as you might any other unexpected exception. If it's in a critical section where an unexpected exception could have heinous consequences, it might be best to try and clean up resources and gracefully shutdown (because getting the interrupt signals that your well-engineered application that doesn't rely on interrupts is being used in a way it wasn't designed, and so there must be something wrong). Alternatively, if the code in question is something non-critical or trivial, you might want to ignore (or log) the interrupt and keep going.


text:
Q: How can I configure Manjaro in GRUB2 without re-running the Manjaro installer? I reinstalled the Ubuntu boot-loader one day, and it showed an entry for Manjaro, but it kernel panicked on boot.
After re-running the Manjaro installer, the kernel was fixed, but GRUB ignored Ubuntu.
I recently installed OpenSUSE and the same predicament is occurring again; so how would I go about fixing this kernel panic without having to reinstall GRUB2?

A: That is possibly considered as a bug, but for Manjaro perhaps it is a feature, making Manjaro the prefered boot OS for your system.  A panic situation occurs when it gets upset by another installer.
I remember hearing on the Linux Luddites podcast that the Manjaro installer does something similar to this, perhaps on purpose.
It is directly addressed by the Majaro team, here, in a very involved discussion, which doesn't seem quite resolved, even yet.
You have to restore GRUB in one way or another (for just a couple of examples), after installation, if you do not like this behavior.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Aptana 3.0 no syntax hints for jQuery I'm using Aptana 3.0.
How to enable jQuery syntax tips (intellisence)?
THIS IS NOT DUPLICATE.
That answer is for version 2.0.
There is not menu called Code Assist in 3.0.

A: That is bug.
I submited it to bug site.

A: The instructions suggesting that you download the jQuery "bundle" do seem to "work". Ish.
I did my best to document the workarounds here: http://karoshiethos.com/2012/05/11/hacking-code-assist-in-aptana-3-javascript/


text:
Q: Tab panes losing width in Bootstrap 4 I've created tabbed content in my project with three tabs. For each tab pane, the pane loses width. For example the first tab pane is the full 100% width, however each pane onwards loses 100-200px consecutively.
For example:

*

*The first pane is 1140px (full width of the container)

*The second pane is: 1004px width

*The third pane is: 794px width

I've checked for missing divs and I don't believe the use of rows and columns within the tab panes is the cause of the issue. I've also tried setting width: 100% to the tab panes with no luck.
I can't understand why this is happening.

            Serviced & managed offices

            Meeting Rooms

            Virtual Offices

State of the art internet & phone packages

Fully furnished and ready for you to move in and make your home

No hidden costs - your monthly fee covers everything from all your utilities to cleaning

Great value and truly affordable prices

No long contracts - choose from a few days to as long as you want giving you total control of your business' finances

State of the art internet & phone packages

Fully furnished and ready for you to move in and make your home

State of the art internet & phone packages

Below is the JS Fiddle:
https://jsfiddle.net/graeme95/qo6tj819/2/

A: .tab-content {
  width: 100%;
}

Also noticed that your grid only starts at lg. Mobile first!


text:
Q: How call method from second activitty and return value I have two activity, first on activity "LoginActivity",and second activity "student_ activity".
Please till me how call method "call" from second activity and return value bool to first activity for know user if id and password correct or not correct.
First activity get id and password from "edittext" then send id and password to method in second activity for sure from data from server.
code first activity is :
    public class LoginActivity extends Activity{
        EditText EdtId;
        EditText EdtPassword;
        Button btn1;
        SharedPreferences prefs;
          @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.login);
                 prefs = this.getSharedPreferences(this.getApplicationContext().getPackageName(), Context.MODE_PRIVATE);
                EdtId=(EditText)findViewById(R.id.IdStudent);
                EdtPassword=(EditText)findViewById(R.id.PasswordStudent);
                 btn1=(Button)findViewById(R.id.btnLogin);

                 btn1.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        createLoginSession(Integer.parseInt(EdtId.getText().toString()),EdtPassword.getText().toString());
//here call second activity for sure from data
                         Intent intent = new Intent(LoginActivity.this,tofi.android.Student_Activity.class);
                            startActivity(intent);
                            finish();
                        startActivity(new Intent(LoginActivity.this,com.jcxavier.widget.test.BadgeButtonTestActivity.class));
                    }
                });
            }
    //this method store data in SharedPreferences for get this data in second activity
         public void createLoginSession(int id, String password){
             SharedPreferences.Editor editor = prefs.edit();
             editor.putInt("id", id);
             editor.putString("password", password);
             editor.commit();
            }
    }

code second activity is:
   public class Student_Activity {
SharedPreferences prefs = this.getSharedPreferences(this.getApplicationContext().getPackageName(), Context.MODE_PRIVATE);
     public void onCreate(Bundle icicle) {
                super.onCreate(icicle);
                setContentView(R.layout.program_student);
                NewsLoader call = new NewsLoader();
    call.execute(this, true);
            }
               private Context context;
            private boolean pullFromServer = false;
            class NewsLoader extends AsyncTask<Object, Void, List<student>> {
                private Context context;
                private boolean pullFromServer = false;

                protected List<student> doInBackground(Object... params) {
                    context = (Context) params[0];
                    pullFromServer = (Boolean) params[1];
                    dataSource.open();
                    if (pullFromServer) {
    //get attribute from SharedPreferences
                        int id = prefs.getInt("id", 24);
                        String password = prefs.getString("password","wce");
    // studentHandler class for sure password content method call for send to server and //return value if correct or not correct and return value type bool.
                        bool s;
                        s = StudentHandler.getInstance().call(context,id,password);
        }
        }
     }

A: 1. Call startActivityForResult() (documentation) and override onActivityResult() (documentation) in the first activity.
2. In the second activity perform whatever validation you need to do (this could also be done in the first activity by passing the data via an Intent) and call setResult(int resultCode, Intent data) (documentation) and then finish(); from the second activity.
If using startActivityForResult() is not feasible for your situation, then you can simply use setResult() and startActivity(), pass any data you need via an Intent, and validate it in onActivityResult().
I just skimmed over this, but here's an example of it in action.


text:
Q: TFLite got same result whatever feed any image I try to deploy it in Android TFLite, but whatever I feed any image, the Interpreter always send me the same result
I used tf.keras built a FaceNet model and try to deploy it in Android TFLite, the processing of the transforming(from tf.keras to tflite) was smoothed.
I try to use the tflite python api to do the inference, it works. But when I try to deploy it in Android, whatever I feed any image, the Interpreter always send me the same result.
There are the inference code in Android.
// Init
Activity activity = (Activity) othersMap.get("activity");
modelFile = loadModelFile(activity);
tfLite = new Interpreter(modelFile, tfliteOptions);
useCPU();
imgData = ByteBuffer.allocateDirect(
                    DIM_BATCH_SIZE * DIM_IMG_SIZE_X * DIM_IMG_SIZE_Y * DIM_PIXEL_SIZE * 4);
imgData.order(ByteOrder.nativeOrder());
embeddingArray = new float[1][128];

// DetectImage
Bitmap bmp = Bitmap.createBitmap(src.width(), src.height(),
                    Bitmap.Config.ARGB_8888);
Utils.matToBitmap(src, bmp);
convertBitmapToByteBuffer(bmp);

tfLite.resizeInput(0, new int[]{1, 96, 96, 3});
tfLite.run(imgData, embeddingArray);

// Inference
float[][] embededFace = detector.detectImage(faceMat);
float[][] embededZN = detector.detectImage(znMat);
Log.e(TAG, "--------------");
Log.e(TAG, Arrays.deepToString(embededFace));
Log.e(TAG, Arrays.deepToString(embededZN));
Log.e(TAG, "--------------");

And there are the inference code in python, it works.
img = cv.imread('zn.jpg')
img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
img = cv.resize(img, (96, 96), interpolation=cv.INTER_CUBIC)
img = np.around(img/255.0, decimals=12)
x_train = np.array([img]).astype(np.float32)

input_shape = input_details[0]['shape']
input_data = x_train
interpreter.set_tensor(input_details[0]['index'], input_data)

interpreter.invoke()
output_data = interpreter.get_tensor(output_details[0]['index'])
print(output_data)

There are the result by using tflite android inference api(using zn.jpg and jzx.jpg)
2019-03-26 15:01:46.346 11635-11823/org.blackwalnutlabs.angel.facedetection E/MainActivity: --------------
2019-03-26 15:01:46.347 11635-11823/org.blackwalnutlabs.angel.facedetection E/MainActivity: [[0.13254969, 0.06506284, -0.12454985, -0.033946857, 0.13087335, 0.24849732, 0.13556245, -0.04702322, -0.1379856, -0.007572789, 0.019669764, 0.012697782, 0.13016781, -0.08282088, 0.07000842, -0.13634653, -0.033497285, 0.06713182, -0.056609895, 0.13066444, 0.031595007, 0.010904907, 0.06502004, 0.055475105, -0.042641174, -0.11620673, -0.13694304, -0.1973542, 0.023469506, 0.105563894, -0.018650757, 0.03307536, -0.098828435, 0.08058539, 0.08887855, 0.0022337863, 0.0055133225, 0.05411017, -0.044450507, -0.082797125, 0.07151169, -0.068259895, -0.09238541, 0.051023263, -0.26672673, 0.062153224, 0.089065045, 0.1272812, -0.15051614, 0.093154915, -0.04973236, -0.055004556, 0.028005369, 9.352369E-4, 0.021919679, -0.019822104, -0.02774606, 0.12849025, -0.051899977, -0.08593918, -0.08694194, 0.10073202, 0.20436272, -0.19222663, 0.084071614, -0.011063285, 0.037152126, 0.03323839, -0.13506632, -0.026216896, 0.012508951, 0.06862544, -0.023205, 0.013072543, -0.031873662, 0.025892422, -0.061958347, -0.06703131, 0.10233366, 0.06788932, -0.02056665, 0.0018195248, -0.07498662, -0.05542643, -0.01115404, 0.009607625, 0.029644933, -0.020729594, 0.0023015668, 0.09378674, 0.18983097, -0.11676965, -0.01661709, -0.019705301, -0.11590064, -0.13303259, 0.0070525194, 0.056587018, 0.02837071, -0.045306873, 0.105889864, 0.0897621, 0.0022198055, 0.043863844, -0.16235375, 0.06855683, -0.04233673, 0.10779853, -0.019658986, 0.096174344, 0.14861028, 0.09041121, -0.03691038, -0.040842745, -0.044187892, 0.06624289, -0.13923372, -0.038001977, -0.018037193, 0.114912674, -7.4458803E-4, -0.122649185, -0.010618781, 0.11189667, -0.03145326, 0.036915697, -0.0388509, -0.096018195]]
2019-03-26 15:01:46.347 11635-11823/org.blackwalnutlabs.angel.facedetection E/MainActivity: [[0.13254969, 0.06506284, -0.12454985, -0.033946857, 0.13087335, 0.24849732, 0.13556245, -0.04702322, -0.1379856, -0.007572789, 0.019669764, 0.012697782, 0.13016781, -0.08282088, 0.07000842, -0.13634653, -0.033497285, 0.06713182, -0.056609895, 0.13066444, 0.031595007, 0.010904907, 0.06502004, 0.055475105, -0.042641174, -0.11620673, -0.13694304, -0.1973542, 0.023469506, 0.105563894, -0.018650757, 0.03307536, -0.098828435, 0.08058539, 0.08887855, 0.0022337863, 0.0055133225, 0.05411017, -0.044450507, -0.082797125, 0.07151169, -0.068259895, -0.09238541, 0.051023263, -0.26672673, 0.062153224, 0.089065045, 0.1272812, -0.15051614, 0.093154915, -0.04973236, -0.055004556, 0.028005369, 9.352369E-4, 0.021919679, -0.019822104, -0.02774606, 0.12849025, -0.051899977, -0.08593918, -0.08694194, 0.10073202, 0.20436272, -0.19222663, 0.084071614, -0.011063285, 0.037152126, 0.03323839, -0.13506632, -0.026216896, 0.012508951, 0.06862544, -0.023205, 0.013072543, -0.031873662, 0.025892422, -0.061958347, -0.06703131, 0.10233366, 0.06788932, -0.02056665, 0.0018195248, -0.07498662, -0.05542643, -0.01115404, 0.009607625, 0.029644933, -0.020729594, 0.0023015668, 0.09378674, 0.18983097, -0.11676965, -0.01661709, -0.019705301, -0.11590064, -0.13303259, 0.0070525194, 0.056587018, 0.02837071, -0.045306873, 0.105889864, 0.0897621, 0.0022198055, 0.043863844, -0.16235375, 0.06855683, -0.04233673, 0.10779853, -0.019658986, 0.096174344, 0.14861028, 0.09041121, -0.03691038, -0.040842745, -0.044187892, 0.06624289, -0.13923372, -0.038001977, -0.018037193, 0.114912674, -7.4458803E-4, -0.122649185, -0.010618781, 0.11189667, -0.03145326, 0.036915697, -0.0388509, -0.096018195]]
2019-03-26 15:01:46.347 11635-11823/org.blackwalnutlabs.angel.facedetection E/MainActivity: --------------

There are the result by using tflite python inference api(using zn.jpg and jzx.jpg)
[[ 0.11388897  0.0725093  -0.02605356 -0.01048064  0.13486011  0.2478467
   0.14440472 -0.08799922 -0.09042776 -0.01699087 -0.01304216 -0.00571998
   0.08452216  0.0200549   0.15689915 -0.19767451  0.01055939  0.04823723
  -0.0236162   0.03551559 -0.03713445  0.07919028  0.00384108  0.07863859
   0.01265915 -0.16044462 -0.1557556  -0.08875822 -0.00050363  0.09660906
   0.04116863  0.02890096 -0.13043067  0.05401503  0.11558161  0.04363808
   0.01493979 -0.02636928 -0.0312182  -0.06017392  0.11421517 -0.02729253
  -0.0982411  -0.03221652 -0.22682378  0.09350454  0.00194081  0.1348505
  -0.08131604  0.01773626 -0.02530179 -0.00231936  0.09337027 -0.03695107
   0.00894977  0.01499904 -0.08354656  0.15669909 -0.05902651 -0.01955242
  -0.09552951  0.14642344  0.10130911 -0.20985658  0.07511081  0.05583977
   0.08974755  0.03895326 -0.17041707  0.01303602  0.07159603  0.08509548
  -0.01078814 -0.01519361 -0.02482661  0.07998506 -0.06343063 -0.12341296
   0.10723062  0.0521314   0.00146189  0.02375979 -0.02791258 -0.04265117
   0.02753739 -0.0534174   0.04096378 -0.04856863 -0.07195448  0.1120934
   0.1552053  -0.09029299  0.07750953  0.00552343 -0.13981637 -0.13607475
   0.0221287  -0.03371112  0.04638224 -0.01829939  0.11707122  0.12880346
  -0.00621982 -0.00639387 -0.17476223  0.07756975 -0.02970012  0.00726423
  -0.0368601   0.13965365  0.17757982  0.02349343 -0.04115034 -0.03476189
  -0.06320279  0.04965549 -0.14846669  0.01701067 -0.05107493  0.10043616
   0.02471918 -0.14686176 -0.05839831  0.07405312  0.02949061  0.07611959
  -0.0424039  -0.09250365]]

[[ 0.07983646  0.18764469 -0.1073711  -0.05049998  0.00499822  0.12150028
   0.08042646 -0.01210295 -0.05991281 -0.04436503  0.05246051 -0.01235358
   0.08685836 -0.13629174 -0.02383062 -0.06484984 -0.04617283 -0.04979375
  -0.10104349  0.14407381  0.03841608 -0.02601014 -0.02829801  0.02454884
  -0.04299033 -0.00861871 -0.03450659 -0.12293942  0.09096454  0.08878913
  -0.03709067  0.05936524 -0.01129172  0.09354664  0.02958448 -0.03306518
   0.10459264  0.15117857 -0.02248681 -0.08084158  0.06213554 -0.16485777
   0.03646875  0.11903016 -0.11887202  0.1105961   0.177684    0.04797998
  -0.24575731  0.05616427 -0.06487465  0.02870647 -0.03513253  0.04599205
   0.09469782 -0.02022276 -0.11111834  0.03512118 -0.04118481 -0.17735724
  -0.08443499 -0.04586984  0.1915695  -0.09305634  0.01631605 -0.00732839
   0.05056106 -0.02879676 -0.07254668 -0.05057898 -0.05678427 -0.06486657
  -0.05519347  0.04775465  0.09962408 -0.04996048 -0.02798802  0.07482754
   0.05294487  0.09077998 -0.02322999  0.03212555 -0.07331605 -0.06148532
   0.02072088  0.03205773 -0.01099079 -0.01667416  0.06782145  0.12291647
   0.13593872 -0.18584044 -0.08280354 -0.04093247 -0.08853628 -0.08608698
   0.05808447  0.05453911  0.05205403 -0.11206362 -0.01309075  0.06881329
   0.01091391  0.12481726 -0.19396386  0.06527282 -0.06483501  0.23652825
   0.00085458 -0.05038064  0.10557921  0.1129869  -0.16408154 -0.00994272
  -0.00418024 -0.03208672 -0.13337857 -0.15857975  0.06981471  0.08215429
   0.03227568  0.02853267  0.06400527  0.15060182  0.0306827  -0.04676049
   0.0670058  -0.10612144]]


text:
Q: wxpython + follow selection in objectlistview in a second objectlistview I have a objectlistview which gives me some data after I've done some filtering on it (mediamonkey-style if someone knows it). Now I have a second screen where I have to show the same objectlistview (same result of the filtering). This step I already programmed. Now when the user select a row on objectlistview 1, I need the second obectlistview to show the same selection.
Is this possible and how do you do it? maybe it is something like: getselection of objectlistview 1, and see where it is in objectlistview 2 and select it?
tx in advance
EDIT:
Update: I send a pubsubmessage on selection in objectlistview1, to objectlistview2, but can you give a cell the focus/selection programmatically?

A: Okay, I've solved it this way (I don't know if it is the best way, but it works :) ). I use GetSElectedObject() and SelectObject().
On item selection in OLV-1:
def on_item_selection(self, event):

    pub.sendMessage("CellSelectionItemlist",
                Container(master=self, origin=self.itemlist,data=self.OLV-1.GetSelectedObject()))

In other file:
def __init__(self, parent, id):
    pub.subscribe(self.on_Cell_Selection, "CellSelectionItemlist")

def on_Cell_Selection(self,message):

    selectedCell = message.data.data
    self.MACellList.SelectObject(selectedCell, ensureVisible=True,deselectOthers=True)


text:
Q: In mongodb, why is it faster to query indexed subdocument array than indexed first level documents? So this is how my database looks like:
> show dbs
admin   0.203125GB
local   0.078125GB
profiler    63.9228515625GB
> use profiler
switched to db profiler
> show collections
documents
mentions

A document in mentions is like this:
> db.mentions.findOne()
{
    "_id" : ObjectId("51ec29ef1b63042f6a9c6fd2"),
    "corpusID" : "GIGAWORD",
    "docID" : "WPB_ENG_20100226.0044",
    "url" : "http://en.wikipedia.org/wiki/Taboo",
    "mention" : "taboos",
    "offset" : 4526
}

A document in documents looks like this:
> db.documents.findOne()
{
    "_id" : ObjectId("51ec2d981b63042f6ae4ca0b"),
    "sentence_offsets" : [
        ..................
    ],
    "docID" : "WPB_ENG_20101020.0002",
    "text" : ".........",
    "verb_offsets" : [
    .............
    ],
    "mentions" : [
        {
            "url" : "http://en.wikipedia.org/wiki/Washington,_D.C.",
            "mention" : "Washington",
            "ner" : "ORG",
            "offset" : 122
        },
        ...................
    ],
    "corpusID" : "GIGAWORD",
    "chunk_offsets" : [
        .................
    ]
}

There are 100 million documents in mentions and 1.3 million in documents. Each mention appearing in mentions should also appear once in some document's mentions array. The reason I store mention info in documents was to avoid going into mentions to retrieve context. Yet when I query mentions only, I thought it should be faster to have an independent collection, mentions.
However, after I experimented index on both mentions.url/mentions.mention and documents.mentions.url/documents.mentions.mention, and query the same url/mention in both collections, I found it was twice as fast to get response from documents collection than from mentions collection.
I am not sure how the index works internally, but I assume both indexes have same size since there are equal number of mentions in both collections. Thus they should have same response time?
I was trying something like
> db.mentions.find({url: "http://en.wikipedia.org/wiki/Washington,_D.C."}).explain()

so there shouldn't be difference in network overhead.
Here is the output of
> db.mentions.find({mention: "Illinois"}).explain()

{
"cursor" : "BtreeCursor mention_1",
"isMultiKey" : false,
"n" : 4342,
"nscannedObjects" : 4342,
"nscanned" : 4342,
"nscannedObjectsAllPlans" : 4342,
"nscannedAllPlans" : 4342,
"scanAndOrder" : false,
"indexOnly" : false,
"nYields" : 14,
"nChunkSkips" : 0,
"millis" : 18627,
"indexBounds" : {
    "mention" : [
        [
            "Illinois",
            "Illinois"
        ]
    ]
},
"server" : "----:----"
}

and that of
> db.documents.find({"mentions.mention": "Illinois"}).explain()

{
"cursor" : "BtreeCursor mentions.mention_1",
"isMultiKey" : true,
"n" : 3102,
"nscannedObjects" : 3102,
"nscanned" : 3102,
"nscannedObjectsAllPlans" : 3102,
"nscannedAllPlans" : 3102,
"scanAndOrder" : false,
"indexOnly" : false,
"nYields" : 8,
"nChunkSkips" : 0,
"millis" : 7862,
"indexBounds" : {
    "mentions.mention" : [
        [
            "Illinois",
            "Illinois"
        ]
    ]
},
"server" : "----:----"
}

And the stats (yeah, I restored the collection and haven't indexed documents.url yet):
> db.documents.stats()
{
    "ns" : "profiler.documents",
    "count" : 1302957,
    "size" : 23063622656,
    "avgObjSize" : 17700.985263519826,
    "storageSize" : 25188048768,
    "numExtents" : 31,
    "nindexes" : 2,
    "lastExtentSize" : 2146426864,
    "paddingFactor" : 1,
    "systemFlags" : 1,
    "userFlags" : 0,
    "totalIndexSize" : 3432652720,
    "indexSizes" : {
        "_id_" : 42286272,
        "mentions.mention_1" : 3390366448
    },
    "ok" : 1
}
> db.mentions.stats()
{
    "ns" : "profiler.mentions",
    "count" : 97458884,
    "size" : 15299979084,
    "avgObjSize" : 156.98906509128506,
    "storageSize" : 17891127216,
    "numExtents" : 29,
    "nindexes" : 3,
    "lastExtentSize" : 2146426864,
    "paddingFactor" : 1,
    "systemFlags" : 0,
    "userFlags" : 0,
    "totalIndexSize" : 15578411408,
    "indexSizes" : {
        "_id_" : 3162125232,
        "mention_1" : 4742881248,
        "url_1" : 7673404928
    },
    "ok" : 1
}

I would appreciate if someone can tell me why this is happening. :]

A:
There are 100 million documents in mentions and 1.3 million in
  documents.

There are an equal number of index entries in both indexes because you told us you store mention both in documents and in mentions.
So index access time is the same.  The way you can measure that is by running a covered index query from both - meaning you only want to get back the values that are stored in the index:  db.x.find({url:"xxx"}, {_id:0, "url":1}) says find matching document and only return the value of url from it.  If those two are not equal across the two connections, maybe something is unusual about your set-up, or one of the indexes can't fit in RAM or another measuring related issue.
If those two are the same but fetching the documents is consistently faster on documents collection, I would check and see why - complete explain output can show where the time is being spent - and whether more of one collection than the other happens to live in RAM, for example.


text:
Q: Replace only "functor" in JavaScript I'd like to replace only the "functor" function of a JavaScript object. The following code demonstrates the problem:
// PART 1: Declaration
function obj() {
    return obj.a + " " + obj.b;
};
obj.a = "a";
obj.b = "b";
confirm(obj()); // output: "a b";

// PART 2: Modification
// now replace only functor
// (not working this way as it replaces the whole object)
obj = function () {
    return obj.b + " " + obj.a;
};
confirm(obj()); // expected output: "b a";

I need this because I don't have access to PART 1 and need to modify the object's function...
Is there a way to do this in JavaScript?
Copying (e.g. with a for-loop) is not working as it does not copy all hidden attributes...
UPDATE: Modified code that it is not undefined...
UPDATE2: This seem to work for this example: (requires jQuery)
obj = $.extend(function() { return obj.b + " " + obj.a; }, obj);
confirm(obj()); // output: "b a";

(However it didn't solve my problem...)

A: You need to have an object and a function referring to each other, and then you only change the function part of it.
var obj = function() {
    var x = function() {return x.f();};
    x.f = function() { return x.a + " " + x.b; };
    return x;
}();

obj.a = "a";
obj.b = "b";

alert(obj());

To change the function, just change obj.f:
obj.f = function () {
    return obj.b + " " + obj.a; //swap the order.
};

alert(obj());

EDIT: Missed the part where you said that you don't have access to Part1, so this solution won't work for you, but have left this here in case it helps someone else, and because it allows you to use obj() directly.

A: You need to invert your function / object. That is make an object and put a function inside it. This will mean that in order to call the function you will need to specify the object thus :
obj = {
  functor : function () {
    return this.a + " " + this.b;
  }
};
obj.a = "a";
obj.b = "b";
confirm (obj.functor ()); // output: "a b";

// PART 2: Modification
// now replace only functor
obj.functor = function () {
    return this.b + " " + this.a;
};
confirm (obj.functor()); // expected output: "b a";

A: I would wrap it like this (paste this code into Chrome's console):
// PART 1 - exactly as provided

function obj() {
    return obj.a + " " + obj.b;
};
obj.a = "a";
obj.b = "b";
console.log(obj()); // output: "a b";

// PART 2 - object is used in different context

var API = {
    setObj: function(obj) {
        this._obj = obj;
    },
    useObj: function() {
        console.log("API: " + this._obj());
    }
}

API.setObj(obj);
API.useObj();

// PART 3 - wrapping obj, changing it's default behavior

objWrapper = function(obj) {

    var wrappedObj = function() {
        return wrappedObj.b + " " + wrappedObj.a;
    }

    var i;
    for(i in obj) {
        if(obj.hasOwnProperty(i)) {
            wrappedObj[i] = obj[i];
        }
    }

    return wrappedObj;
}
obj = objWrapper(obj);
console.log(obj()); // expected output: "b a";
console.log(obj.a);
console.log(obj.b);
obj.c = "c";
console.log(obj.c);

// PART 4 - checking different context

API.setObj(obj);
API.useObj();

This is the only way you can make it work. You will have to update every reference to this function, so if you can't simulate API.setObj(obj); then you can't make it work. You can't redefine only body of a function. Maybe in the future they will add it, as it could be really helpful indeed, and it will make JS more functional programming language.
I replaced confirm dialogs into console.log as it was annoying!;)
Hope it will help!


text:
Q: Morphism of non-commutative algebras Disclaimer: this question is a "big picture" one that comes from my personal thoughts in physics. If it doesn't fit this site, please tell me.
While having a walk, I thought a bit about what made the flow of time irreversible considering the minus sign of the component $g_{00}$ of the metric tensor in the Minkowski spacetime with sign convention $(-+++)$.
One can easily figure out that whenever $i>0$, there exists $j$ such that $g_{jj}=\sqrt{g_{ii}}$, as if the square roots behaved like directions of the components of space-time that are freely available inside a single section of a timeline. Taking a square root of $g_{00}=-1$ leads to a number that is not any of the $g_{ii}$ and thus we somehow leave the considered section. This is a bit analogous to a non normal field extension that does not contain all conjugates of the primitive element generating it.
While saying that to mathematician friend of mine, he told me that according to Alain Connes, irreversibility emerges from the non commutativity of the "true" quantum geometry. I heard of works suggesting space-time at a tiny scale has dimension 2, like the dimension of $C$ over $R$ as a vector space. On the other hand, space-time at macroscopic scale has dimension 4 like the quaternion skew field.
So my question is moreorless this one: can gravity be seen as a process consisting in going from a non-commutative complex operator algebra (on the quantum side) to a pseudoriemannian manifold locally isomorphic to a quaternion algebra (on the relativistic one)? Is some notion of morphisms of non-commutative algebras potentially relevant here? Is it anyhow related to a scale factor increasing?
See also: https://math.stackexchange.com/questions/821881/riemann-zeta-function-quaternions-and-physics?r=SearchResults
Edit: I also expect space-time to be $\mathcal{C}^{0}$ at tiny scale in the purely quantum realm, then $\mathcal{C}^{1}$ with a smooth fractal structure (see computer rendering of Nash's embedding theorem) at a scale where quantum effects and gravity are of similar importance, and finally $\mathcal{C}^{2}$ as scale keeps increasing together with the intensity of gravity with regard to quantum effects.


text:
Q: How to get a histogram for each image in a multidimensional raster? A ".crf" file was created, and using this I calculated NDVI on each image in my multidimensional raster, using Band Arithmetic Properties. Then NDVI histogram appears while using Classify and Standard Deviation method. My problem is that, histogram represents each image in my multidimensional raster, and it doesn't change when a new NDVI image with another date and time shows up (See Image 2&3). Is there any way, to make the histogram change simultaneously with date and time?
I would like to see the change of standard deviation and instead of calculating NDVI values one by one for 10 different images, I would like to do it using a multidimensional raster.
Image 1: Using ".CRF" file to calculate NDVI values on each image in my multidimensional raster.

Image 2: NDVI Values on 04.07.2019,and histogram representation.

Image 3: NDVI Values on 26.08.2021,and histogram representation.


text:
Q: 'End of statement expected' erro no pyCharm Tenho um método bem simples, que recebe um parâmetro booleano e altera uma global para o valor negado do parâmetro.
Porém, utilizando a IDE PyCharm, ela retorna um erro no trecho global state = not x
state = False

def change_state(x):
    global state = not x

O que significa esse erro? Qual seria a forma correta do código?

A: O problema é que a atribuição do valor da variável global está na mesma linha.
O correto seria assim:
state = False

def change_state(x):
    global state
    state = not x
    print(state)

change_state(state)

Resultado:
True


text:
Q: Building websites that will be localized Does anyone have some guidelines or links to articles when designing a website that needs to be localized in 20+ languages?
The initial translation isn't so much the problem, rather ongoing maintenance (i.e. when an update is made on the English site, how are people notified that new translations are required).
Thanks in advance!

A: Here are some web sites dedicated to internationalization and globalization:
http://www.i18nguy.com/
http://multilingual.com/guides.php (they heavily push vendors, but their guides tend to be worth a read)
Google searches on i18n (internationalization) and l10n are often useful as well.
You asked about designing the site though, so I assume you're talking about coding best practices.  In general, you want to reuse as much as possible.  That means:

*

*Separating all text into resource files (.Net handles this naively, in PHP you can use a template to sub in text, your language may vary)

*(Really 1-a) Don't put text in images.  This will just cause headaches later since images will cease to be reusable.  You'll have to update an image any time text changes and that's often not worth it.

*Fluid/liquid layouts are preferred.  German text can be 30% larger than English, Asian languages can be significantly smaller than English, etc.

*Use a standard character set for web pages (i.e. utf-8).  That will minimize rendering problems between the languages.
That's sort of the easy part.  The hard part is managing it.  Depending on your source control system, you can likely write or acquire a tool that will alert the appropriate party.
Content management systems are built to help you manage changes automatically.  Good CMSes are often pricey, however.  The above sites can point you at features of those you may look for help you manage your sites.

A: Many SCMs support triggers that can fire when committing changes and can take action if, e.g. a .pot file was changed, to send email to the appropriate parties.


text:
Q: Binding complex objects to a DataGrid Say I have an ObservableCollection (type MyRow) (called Rows) of rows. In MyRow I have a bunch of properties, including an ObservableCollection (type MyRowContents) (called Contents) - which is basically a list of all of the contents that will be in that row. MyRowContents also has several properties, including DisplayContents (string).
For example... for DataGrid with 2 rows, and 3 columns the data structure would be 2 "Rows", and each would contain 3 "Contents".
What do I have to do in the DataGrid in the XAML so that the cell contents display Rows[i].Contents[j].DisplayContents?
EDIT:
Hi, sorry for not being clear enough in the initial message. I am trying to make a data grid that is capable of displaying data dynamically (from a database table that is unknown ahead of time).
I have used this as a guide: http://pjgcreations.blogspot.com.au/2012/09/wpf-mvvm-datagrid-column-collection.html - and I can display the columns dynamically.
    <DataGrid ItemsSource="{Binding Rows}" AutoGenerateColumns="False"
              w:DataGridExtension.Columns="{Binding ElementName=LayoutRoot, Path=DataContext.Columns}" />

I just don't know how to display the row data dynamically.
MyRow is:
public class MyRow
{
    public int UniqueKey { get; set; }
    public ObservableCollection<MyRowContents> Contents { get; set; }
}

MyRowContents is:
public class MyRowContents
{
    public string ColumnName { get; set; } // Do I need this?
    public object DisplayContents { get; set; } // What I want displayed in the grid cell
}

I have a public property ObservableCollection Rows in my view model, which as you can see is what I am binding to in the ItemsSource. But I don't know how to get the "DisplayContents" of each MyRowContents to display in the appropriate cell in the grid view.
Given that I can display the column names dynamically, this assumption can be made: the order of the items in Contents (in MyRow) will match the order of the columns.
Thanks

A: First of all you have to put row ID in RowContent so your app logic should be similar to:
RowContent.cs :
public class RowContent
{
    //public string ColumnName { get; set; } "you dont need this property."

    public int ID;  //You should put row ID here.
    public object DisplayContents { get; set; } "What is this property type, is string or int or custom enum??"
}

RowViewModel.cs :
public class RowViewModel
{
    public ObservableCollection<MyRowContents> Contents { get; set; }
}

Now you have to put your Collection in Window.DataContext to be able to bind it in DataGrid
MainWindow.xaml.cs :
public partial class MainWindow : Window
{
    private RowViewModel rvm = new RowViewModel(); //Here i have made new instance of RowViewModel, in your case you have to put your ViewModel instead of "new RowViewModel();";

    public MainWindow()
    {
        InitializeComponent();

        DataContext = rvm; // this is very important step.
    }
}

Last step is in window XAML.
MainWindow.xaml :
<DataGrid ItemsSource="{Binding Path=Contents}" AutoGenerateColumns="false">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Row ID" Binding="{Binding Path=ID,UpdateSourceTrigger=PropertyChanged}"/>
        <DataGridTextColumn Header="your row header" Binding="{Binding Path=DisplayContents,UpdateSourceTrigger=PropertyChanged}"/>
    </DataGrid.Columns>
</DataGrid>

There is Five types of DataGridColumn, you have to select appropriate type depending on the type of DisplayContents property.


text:
Q: rake db:create and db:migrate work but application hangs I'm new to ruby on rails and amazon aws, and am having this issue: I can connect to my database from the command line using this command:
mysql -h aaynj18bcvo3e.clqvrttlitbb.us-east-1.rds.amazonaws.com -P 3306 -u ebroot -p

and can also successfully db:create and db:migrate. The issue is that when I try to connect to localhost:3000/users/new my application hangs. I CAN however, see the default rails HTML page when I access localhost:3000/.
I was able to verify that the database and table I created actually exist now.
At this point, I'm not even trying to deploy the app, I just want to be able to connect to the remote database when I'm in development mode.
Please help - Thanks :)

A: when you access " localhost:3000 ", it shows all the information about your Database.
and simply if there is a rails icon on the screen, the database connected successfully,
other wise its not...
This is the simple one to know the database configure and whether connected or not...


text:
Q: Recognize if not enough resources during timeframe i need an idea how to solve the following problem.
Lets say i have one group with given timeframe (8:00-12:00) and i can assign resources (people) to it. Each resource can have a custom timeframe (like 9-10, 9-12,8-12 etc.) and could be assigned multiple times.
Tables
Groups
ID,
TITLE,
START_TIME,
END_TIME,
REQUIRED_PEOPLE:INTEGER
PeopleAssignments
ID,
USER_ID,
GROUP_ID,
START_TIME,
END_TIME
Now i have the rule that at any given time during the group timeframe that there have to be like like 4 people assigned. Otherwise i want to get a warning.
I am working with ruby & sql (Postgres) here.
is there an elegant way without iterating through the whole timeframe and checking if count(assignments) > REQUIRED_PEOPLE

A: In any case you need to query number of assignment in DB. There is no other way to find how many times a group assign to people.
There might be ways to find number of assignment but in the end you have to fire a query to DB.
@group = Group.find(id)
if @group.people_assignments.count >= REQUIRED_PEOPLE
  pus 'warning'
end

You can add extra column in group that hold information how many times that group assign to people. In this way one query to server reduced.
@group = Group.find(id)
if @group.count_people_assigned >= REQUIRED_PEOPLE
  puts 'warning'
end

In second case count_people_assigned is column so no extra query will execute while in first case people_assignments is association so one extra query will fire.
But in second case you have you update group each time you assign group to people. Ultimately extra query. Your choice where you want to reduce query.
My opinion is second case, It will happen rare than first.

A: You can solve this with only SQL too (if you are interested in such answers).
Range types offers great functions and operators to calculate with.
These solutions will give you rows, when there are sub-ranges, where there is some missing people from a given group (and it will give you which sub-range it is exactly & how many people is missing from the required number).
The easy way:
You wanted to try something similar to this. You'll need to pick some interval in which the count() is based on (I picked 5 minutes):
select     g.id group_id, i start_time, i + interval '5 minutes' end_time, g.required_people - count(a.id)
from       groups g
cross join generate_series(g.start_time, g.end_time, interval '5 minutes') i
left join  people_assignments a on a.group_id = g.id
where      tsrange(a.start_time, a.end_time) && tsrange(i, i + interval '5 minutes')
group by   g.id, i
having     g.required_people - count(a.id) > 0
order by   g.id, i

But note that you won't be able to detect missing sub-ranges, when they are less than 5 minutes. F.ex. user1 has assignment for 11:00-11:56 and user2 has one for 11:59-13:00, they will appear to be "in" the group for 11:00-13:00 (so the missing sub-range of 11:56-11:59 will go unnoticed).
Note: the more short the interval is (what you've picked) the more precise (and slow!) the results will be.
http://rextester.com/GRC64969
The hard way:
You can accumulate the result on-the-fly with custom aggregates or recursive CTEs
with recursive r as (
    -- start with "required_people" as "missing_required_people" in the whole range
    select 0 iteration,
           id group_id,
           array[]::int[] used_assignment_ids,
           -- build a json map, where keys are the time ranges
           -- and values are the number of missing people for that range
           jsonb_build_object(tsrange(start_time, end_time), required_people) required_people_per_time_range
    from   groups
    where  required_people > 0
    and    id = 1 -- query parameter
  union all
    select r.iteration + 1,
           r.group_id,
           r.used_assignment_ids || a.assignment_id,
           d.required_people_per_time_range
    from   r
    -- join a single assignment to the previous iteration, where
    -- the assigment's time range overlaps with (at least one) time range,
    -- where there is still missing people. when there are no such time range is
    -- found in assignments, the "recursion" (which is really just a loop) stops
    cross join lateral (
      select     a.id assignment_id, tsrange(start_time, end_time) time_range
      from       people_assignments a
      cross join (select key::tsrange time_range from jsonb_each(r.required_people_per_time_range)) j
      where      a.group_id = r.group_id
      and        a.id <> ALL (r.used_assignment_ids)
      and        tsrange(start_time, end_time) && j.time_range
      limit      1
    ) a
    -- "partition" && accumulate all remaining time ranges with
    -- the one found in the previous step
    cross join lateral (
      -- accumulate "partition" results
      select jsonb_object_agg(u.time_range, u.required_people) required_people_per_time_range
      from   (select key::tsrange time_range, value::int required_people
              from   jsonb_each_text(r.required_people_per_time_range)) j
      cross join lateral (
        select u time_range, j.required_people - case when u && a.time_range then 1 else 0 end required_people
        -- "partition" the found time range with all existing ones, one-by-one
        from   unnest(case
                 when j.time_range @> a.time_range
                 then array[tsrange(lower(j.time_range), lower(a.time_range)), a.time_range, tsrange(upper(a.time_range), upper(j.time_range))]
                 when j.time_range && a.time_range
                 then array[j.time_range * a.time_range, j.time_range - a.time_range]
                 else array[j.time_range]
               end) u
        where not isempty(u)
      ) u
    ) d
),
-- select only the last iteration
l as (
  select   group_id, required_people_per_time_range
  from     r
  order by iteration desc
  limit    1
)
-- unwind the accumulated json map
select     l.group_id, lower(time_range) start_time, upper(time_range) end_time, missing_required_people
from       l
cross join lateral (
  select key::tsrange time_range, value::int missing_required_people
  from   jsonb_each_text(l.required_people_per_time_range)
) j
-- select only where there is still some missing people
-- this is optional, if you omit it you'll also see row(s) for sub-ranges where
-- there is enough people in the group (these rows will have zero,
-- or negative amount of "missing_required_people")
where      j.missing_required_people > 0

http://rextester.com/GHPD52861


text:
Q: Can't test simple Angular 12 guard with Karma I have tried several times, but it seems like I cannot create a unit test for a very basic Guard in Angular 12 which has

*

*canActivate

*canActivateChild

as its main methods.
Please find the following code:
@Injectable({
  providedIn: 'root'
})
export class IsAuthenticatedGuard implements CanActivate, CanActivateChild {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    return this.authService.getIsAuthenticated().pipe(
      tap(isAuth => {
        if (!isAuth) {
          // Redirect to login
          // eslint-disable-next-line @typescript-eslint/no-floating-promises
          this.router.navigate(['/login']);
        }
      })
    );
  }

  canActivateChild(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    return this.canActivate(route, state);
  }
}

The authService call inside the canActivate method shall return an Observable obtained by a BehaviourSubject object using the asObservable() call.
I have tried every possible test, but it seems like no comparison performed (toBe,toEqual, etc.) works for those two methods, nor is the spy on the navigation is triggered when the redirect is performed.
The following is a sample spec.ts class I created following some guides on the web:
function mockRouterState(url: string): RouterStateSnapshot {
  return {
    url
  } as RouterStateSnapshot;
}

describe('IsAuthenticatedGuard', () => {
  let guard: IsAuthenticatedGuard;
  let authServiceStub: AuthService;
  let routerSpy: jasmine.SpyObj<Router>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [SharedModule, RouterTestingModule]
    });
    authServiceStub = new AuthService();
    routerSpy = jasmine.createSpyObj<Router>('Router', ['navigate']);
    guard = new IsAuthenticatedGuard(authServiceStub, routerSpy);
  });

  it('should be created', () => {
    expect(guard).toBeTruthy();
  });

  const dummyRoute = {} as ActivatedRouteSnapshot;
  const mockUrls = ['/', '/dtm', '/drt', '/reporting'];

  describe('when the user is logged in', () => {
    beforeEach(() => {
      authServiceStub.setIsAuthenticated(true);
    });
    mockUrls.forEach(mockUrl => {
      describe('and navigates to a guarded route configuration', () => {
        it('grants route access', () => {
          const canActivate = guard.canActivate(dummyRoute, mockRouterState(mockUrl));
          expect(canActivate).toEqual(of(true));
        });
        it('grants child route access', () => {
          const canActivateChild = guard.canActivateChild(dummyRoute, mockRouterState(mockUrl));
          expect(canActivateChild).toEqual(of(true));
        });
      });
    });
  });

  describe('when the user is logged out', () => {
    beforeEach(() => {
      authServiceStub.setIsAuthenticated(false);
    });
    mockUrls.forEach(mockUrl => {
      describe('and navigates to a guarded route configuration', () => {
        it('does not grant route access', () => {
          const canActivate = guard.canActivate(dummyRoute, mockRouterState(mockUrl));
          expect(canActivate).toEqual(of(false));
        });
        it('does not grant child route access', () => {
          const canActivateChild = guard.canActivateChild(dummyRoute, mockRouterState(mockUrl));
          expect(canActivateChild).toEqual(of(false));
        });
        it('navigates to the login page', () => {
          // eslint-disable-next-line @typescript-eslint/unbound-method
          expect(routerSpy.navigate).toHaveBeenCalledWith(['/login'], jasmine.any(Object));
        });
      });
    });
  });
});

When I run the test file, I get something like this:

Expected object to have properties
_subscribe: Function
Expected object not to have properties
source: Observable({ _isScalar: false, source: BehaviorSubject({ _isScalar: false, observers: [  ], closed: false, isStopped: false, hasError: false, thrownE
rror: null, _value: false }) })
operator: MapOperator({ project: Function, thisArg: undefined })
Error: Expected object to have properties
_subscribe: Function ...

Apparently, Karma expects a ScalarObservable of some sort, plus the navigation towards ['/login'] is not detected.
Would you mind giving me some advice on how to perform this test?
Thank you in advance.

A: Here is how I would configure TestBed module and test guard:
describe('IsAuthenticatedGuard', () => {
  const mockRouter = {
    navigate: jasmine.createSpy('navigate'),
  };
  const authService = jasmine.createSpyObj('AuthService', ['getIsAuthenticated']);
  let guard: IsAuthenticatedGuard;

  beforeEach(
    waitForAsync(() => {
      TestBed.configureTestingModule({
        providers: [
          IsAuthenticatedGuard,
          { provide: Router, useValue: mockRouter },
          { provide: AuthService, useValue: authService },
        ],
      }).compileComponents();
    }),
  );

  beforeEach(() => {
    guard = TestBed.inject(IsAuthenticatedGuard);
  });

  describe('when the user is logged in', () => {
    beforeEach(() => {
      authService.setIsAuthenticated.and.returnValue(of(true));
    });

    it('grants route access', () => {
      guard.canActivate({} as ActivatedRouteSnapshot, {} as RouterStateSnapshot).subscribe((result) => {
        expect(result).toBeTrue();
      });
    });

    it('grants child route access', () => {
      guard.canActivateChild({} as ActivatedRouteSnapshot, {} as RouterStateSnapshot).subscribe((result) => {
        expect(result).toBeTrue();
      });
    });
  });
});

A: Thank you, @vitaliy.
I adjusted some things in both the guard itself and the test file, and managed to get it through.
Here is the final test file:
describe('IsAuthenticatedGuard', () => {
  const mockRouter = {
    navigate: jasmine.createSpy('navigate')
  };
  const authService = jasmine.createSpyObj<AuthService>('AuthService', ['getIsAuthenticated']);
  let guard: IsAuthenticatedGuard;

  beforeEach(
    waitForAsync(() => {
      void TestBed.configureTestingModule({
        providers: [
          IsAuthenticatedGuard,
          {
            provide: Router,
            useValue: mockRouter
          },
          {
            provide: AuthService,
            useValue: authService
          }
        ]
      }).compileComponents();
    })
  );

  beforeEach(() => {
    guard = TestBed.inject(IsAuthenticatedGuard);
  });

  describe('when the user is logged in', () => {
    beforeEach(() => {
      authService.getIsAuthenticated.and.returnValue(of(true));
    });

    it('grants route access', () => {
      void guard.canActivate({} as ActivatedRouteSnapshot, {} as RouterStateSnapshot).subscribe(result => {
        expect(result).toBeTrue();
      });
    });

    it('grants child route access', () => {
      guard.canActivateChild({} as ActivatedRouteSnapshot, {} as RouterStateSnapshot).subscribe(result => {
        expect(result).toBeTrue();
      });
    });
  });

  describe('when the user is logged out', () => {
    beforeEach(() => {
      authService.getIsAuthenticated.and.returnValue(of(false));
    });

    it('does not grant route access', () => {
      void guard.canActivate({} as ActivatedRouteSnapshot, {} as RouterStateSnapshot).subscribe(result => {
        expect(result).toBeFalse();
        expect(mockRouter.navigate).toHaveBeenCalledWith(['/login']);
      });
    });

    it('does not grant child route access', () => {
      guard.canActivateChild({} as ActivatedRouteSnapshot, {} as RouterStateSnapshot).subscribe(result => {
        expect(result).toBeFalse();
        expect(mockRouter.navigate).toHaveBeenCalledWith(['/login']);
      });
    });
  });
});

A: You do not need the mockRouter as you can add the RouterTestingModule in the imports array and do a
  const router: Router;

  beforeEach(
    waitForAsync(() => {
      void TestBed.configureTestingModule({
        imports: [RouterTestingModule], //ADD THIS HERE
        providers: [
          IsAuthenticatedGuard,
          {
            provide: AuthService,
            useValue: authService
          }
        ]
      }).compileComponents();
    })
  );

  beforeEach(() => {
    guard = TestBed.inject(IsAuthenticatedGuard);
    router = TestBed.inject(Router); //ADD THIS HERE
  });

As you are subscribing in a test you need to add the waitForAsync() because the Test should wait until every observable has been executed and finished.
For example
it('does not grant child route access', waitForAsync(() => {
      guard.canActivateChild({} as ActivatedRouteSnapshot, {} as RouterStateSnapshot).subscribe(result => {
        expect(result).toBeFalse();
        expect(mockRouter.navigate).toHaveBeenCalledWith(['/login']);
      });
    }));

Otherwise it may be that the test has been finished before the subscribe has been called, and you expect nothing.


text:
Q: Test Observable in Angular 2/4 I am developing an Angular based application where I need to do component communication. I am making use of service to achieve the desired working.
I am having hard time at testing the observable. Below are the code snippet for all the class:
TestComponent.ts file
export class TestComponent implements OnInit {

  id: number = -1;
  message: string;

  constructor(private testService: TestService) { }

  ngOnInit() {
    this.testService.test1$
    .subscribe((id: number) => {
      this.id = id;
     });

    this.message= this.testService.getMessage();
  }
}

TestService.ts
export class TestService {

  onTestChange1 = new Subject<number>();

  onTestChange2 = new Subject<string>();

  // Observable string streams
  test1$ = this.onTestChange1.asObservable();
  test2$ = this.onTestChange2.asObservable();

  getTest1() {
    this.onTestChange1.next(1);
  }
  getTest2() {
    this.onTestChange2.next('Hi from 2');
  }

  getMessage(): string {
    return 'Hi';
  }
}

TestComponent Spec File:
fdescribe('TestComponent', () => {
  let component: TestComponent;
  let fixture: ComponentFixture<TestComponent>;

  let test: TestMockService;

  beforeEach(async(() => {
    test = new TestMockService();
    TestBed.configureTestingModule({
      declarations: [ TestComponent ],
      providers: [
        {provide: TestService, useValue: test}
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(TestComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should be created', () => {
    expect(component).toBeTruthy();
  });

  it('should message to be true Hi', async(() => {

    const dataStub = fixture.debugElement.injector.get(TestService);
    const spy = spyOn(dataStub, 'getMessage').and.returnValue('Hi');

    fixture.detectChanges();
    fixture.whenStable().then(() => {
      fixture.detectChanges();
      expect(component.message1).toBe('Hi');
    });
  }));

  it('id should be equal to 1', async(() => {
    const dataStub = fixture.debugElement.injector.get(TestService);
    const spy = spyOn(dataStub, 'getTest1').and.returnValue(Observable.of(1));
    fixture.detectChanges();
    fixture.whenStable().then(() => {
      expect(component.id).toBe(1);
    });
  }));

});

The last test where the 'id' is under test is failing and I am not sure why!
I know I am missing something really small and important which is why my code is not working. It would be really great if anyone can help me understand and correct my code.
A prompt response would be appreciated!
Thanks!


text:
Q: express-http-context for next js api I need HTTP context for the next.js API
const httpContext = require("express-http-context");
app.use(httpContext.middleware);
httpContext.set("res", res);

Is there a way to use middleware in next.js 12 to get the same functionality where I can access the API response in any part of the server api


text:
Q: How can I execute a Bash Script with AWS Redshift I'm new to Redshift and quite a beginner in AWS. I have a Redshift Cluster, and I need to execute a bash script- that has some SQLs running inside of it.
Is there any way I can execute my Bash script on my Redshift Cluster? I want to be able to connect to the Redshift Cluster, execute the Bash Script and all the SQLs inside on the cluster.
Can I do this through Lambda? A little detail will be appreciated.

A: This is possible through lambda if you wanna use the bash script. But if you wanna just execute sqls, wrap those sqls in a  .sql script and  use Redshift query scheduler to schedule these via either manual schedule run or cron job schedule run

A: Amazon Redshift is a database. You can connect to it via JDBC or via the Redshift Data API and then run SQL commands against the database. However, it is not a compute platform.
While Amazon Redshift does have the ability to run stored procedures, bash scripts cannot be run.
You would need to run your script on a compute platform (eg an Amazon EC2 instance or your own computer), and it can 'call' the Amazon Redshift cluster to run the SQL.
AWS Lambda can run bash scripts, although you would need to do some setup to support it. You would be better-off rewriting your code to work in a natively-supported language.


text:
Q: Where should I install the boot loader on a second drive? So I recently installed a second hard drive in my laptop. Previously, I had split 1 hard drive into a windows and ubuntu partition, but after running out of space on each, I installed this new hard drive and installed ubuntu 14.04 on it. All of that went smoothly, but now when I load up the boot menu, I'm not seeing the option to boot into this new ubuntu installation.
It seems that my bios is set to only look at the first hard drive? Here are my thoughts:
1) Update my bios to find my second grub install. (don't know how to do that)
2) Reinstall ubuntu with drive 1 as the bootloader location (I'm afraid I'll overwrite the old grub and be unable to boot into my old ubuntu install)
3) Something else?
Sidenote: I'm using windows 10. Not sure if that has anything to do with it.
Any help would be greatly appreciated! Thank you!


text:
Q: Is there a way to hide label elements when the placeholder attribute is supported? I would like the use the placeholder attribute instead of labels in my webpages, but I need to hide the labels when placeholders are supported.  Is this possible with only CSS?
Ideally, I like the equivalent of

label + input {
display: none;
}
-->

A: You'd probably need to use Modernizr to detect placeholder support and then hide the labels. You'd need JavaScript though.
I'm not aware of another way, but others might be.

A: This is not possible with CSS. There is no support for "parent selectors" and there most likely never will be.
If you don't want to use Modernizer, here's a simple test to run with JS:
if (("placeholder" in document.createElement("input"))) {
//placeholder is supported, so hide your label elements or whatever
}


text:
Q: How I can decrease size of vendor.js in angular? I deploy my project in my server, every time I load the page I see that the file vendor.js take 34 s to load and its size is 12Mb, I don't know how to reduce or minify it because I don't find it in my project.
I'm a beginner in angular sorry it is a basic question
I try ng build --prod because I found it in a question but I don't get any result

A: Decrease number of used external libraries


text:
Q: During Paypal test, I can't reach the sandbox.paypal page I am beginner with wordpress. I have add the s2member plugin and my problem is that i have configured the paypal option for the paypal test phase but when I try to make a purchase sandbox refuse the password of the buyer account. I am going to try to explain you what I have done until here:
I created an account on paypal developper, I went into the deshboard and here, two account was already created:
......-buyer@gmail.com
......-facilitator@gmail.com
I went back on s2members and the first thing to do to configure the paypal option is to give my paypal account details.
The first things which is asked is my paypal merchant ID
During the test phase do i have to put my merchant ID or the merchant ID of the buyer account? if I have to put the merchant ID of the buyer account where can I find it? I've looked in the details of the accounts but there is nothing.
After they ask me my paypal email adress: here no problem
After they ask me my Paypal API username, password and signature: same question here, during the test phase do I have to put mine or do I have to put the API information of the buyer account?
For the other configuration option everything seems okay.
One last thing in the code of my paypal button I have substituted this:
https://www.paypal.com/cgi-bin/webscr.
by this:
https://www.sandbox.paypal.com/cgi-bin/webscr
Now when I try to make a purchase I am redirected on a paypal page which tell me:
Paypal cannot find this transaction.the vendor 's website has a problem. Please contact the seller to resolve this issue .
I dont know what to do and how to do.. I hope you can understand what my problem is.
Sorry for my english
Thanks :)

A: You have to sign in here using the email and password of the test account created. Then follow the steps in this link to find the Merchant ID.


text:
Q: Boolean Function throwing unexpected answer in C++ ,Can anyone Explain this
Giving Correct Answer

    bool is_palindrome(string s,int start,int end){
    while(start<=end){
        if(s[start++]!=s[end--]){
            return false;
        }
    }return true;
}

Giving Wrong Answer

bool is_palindrome(string s,int start,int end){
    while(start<=end){
        if(s[start++]==s[end--]){
            return true;
        }
    }return false;
}

Please Explain If Anyone knows the Right Explanation,After Searching, I couldn't find the Appropriate justification for it.

A: Your first code says

*

*If there are at least two unequal characters, it is not a palindrome

*Otherwise, it is a palindrome (i.e. when all the characters "match")

Your second code says

*

*If there are at least two equal characters, it is a palindrome

*Otherwise, it is not a palindrome (i.e. when none of the characters "match")

If you can't see the difference between them, I suggest you think about it until you do; negation is much trickier than people think.
Another way to see the problem is to notice that in order to be sure that something is a palindrome, you must look at all the characters, so you can't return true before you have done that.
On the other hand, in order to be sure that something isn't a palindrome, you only need to find a single mismatch, so you can return false as soon as you do.

A: your second code returns true even if only two characters match, like asda will return true but it's not a palindrome neither is bssw but it returns true. You need to compare every characters, if you want to do in the second way then:
bool is_palindrome(string s,int start,int end){
    while(start<=end){
        if(s[start++]==s[end--]){
            continue;
        }
        else {
            return false;
       }
    }
    return true;
}


text:
Q: Access thrown exception in DataWeave Is it possible to access the exception in Catch Exception Strategy -> Transform Message component ? I know I can access it via MEL #[exception.cause] but I wasn't able to find anything about how to access it in DataWeave.
Thanks a lot.

A: you can set exception in payload (like @Ralph Rimorin suggested) or you can set it as variable and use in dw -
<catch-exception-strategy doc:name="Catch Exception Strategy">
        <logger message="#[exception.message]" level="ERROR" doc:name="Logger"></logger>
        <set-variable variableName="exception" value="#[exception]"
            doc:name="Set Exception to FlowVars"
            doc:description="This is to ensure that exception object is avaiable to Send Support Email component which uses exception from flowVars instead of the one set by mule at #[exception] as it sometimes tend to get lost."></set-variable>
        <dw:transform-message doc:name="Transform Message">
            <dw:set-payload><![CDATA[%dw 1.0
%output application/java
---
{
a:flowVars.exception
}]]></dw:set-payload>
        </dw:transform-message>

    </catch-exception-strategy>

A: @Lukas, if you catch the exception via flow reference, then the calling flow would be able to evaluate the exception using dataweave. Inside the Catch Exception Strategy, try to set the exception as a payload then in the calling flow, which you have the dataweave would process that.


text:
Q: HttpAddUrl fails with ERROR_SHARING_VIOLATION (32L) I am attempting to write a price listener.
the data arrives as a 'push' response, ie: chunked transfer-encoding.
i have decided to use the http server api, as both async wininet and winHTTP read data apis both close the connection if there is no data for a short while.
first of all, am i correct to use the http server api?
second, if i try to, as per the msdn example:
retCode = HttpInitialize(
            HttpApiVersion,
            HTTP_INITIALIZE_SERVER,
            NULL
            );    // return is NO_ERROR

retCode = HttpCreateHttpHandle(
            &hReqQueue,
            0
            );    // return is NO_ERROR

std::wstring url = _T( "http://apidintegra.tkfweb.com:80/" );
retCode = HttpAddUrl(
            hReqQueue,
            url.c_str(),
            NULL
            );    // always fails with ERROR_SHARING_VIOLATION

i always get a sharing violation. do i need to use netsh to configure the connection somehow? if so how? ive seen mention of configuring http.sys, and ive even tried executing the above code as an administrator.
I would be extremely grateful for some help, as there seems very little code out there for this!
Many thanks,
Jon

A: This error happens if the port is already in use by another process. That means another application uses the port (for example IIS or another web server).


text:
Q: Getting dimensions of an Android device in dp I.e. the Samsung S6 Edge has the screen dimensions 1440x2560 pixels.
However, I need them in dp instead. How can I programatically get the dimensions (width and height) of an Android device in dp?

A: You can get DisplayMetrics
   DisplayMetrics metrics = new DisplayMetrics();
   getWindowManager().getDefaultDisplay().getMetrics(metrics);

and access density value:

The logical density of the display. This is a scaling factor for the
  Density Independent Pixel unit, where one DIP is one pixel on an
  approximately 160 dpi screen (for example a 240x320, 1.5"x2" screen),
  providing the baseline of the system's display. Thus on a 160dpi
  screen this density value will be 1; on a 120 dpi screen it would be
  .75; etc.
This value does not exactly follow the real screen size (as given by
  xdpi and ydpi, but rather is used to scale the size of the overall UI
  in steps based on gross changes in the display dpi. For example, a
  240x320 screen will have a density of 1 even if its width is 1.8",
  1.3", etc. However, if the screen resolution is increased to 320x480 but the screen size remained 1.5"x2" then the density would be
  increased (probably to 1.5).


text:
Q: Workaround for lvalue-to-rvalue conversion of the inactive member of a union within relaxed constant expressions Triggering lvalue-to-rvalue conversion of the inactive member of a union is not a constant expression. That is, given the union:
template<class T, class U>
union A {
  constexpr A(T t) : t_{t} {}
  constexpr A(U u) : u_{u} {}
  T t_;
  U u_;
};

and the constexpr function foo:
template<class T, class U>
constexpr auto foo() {
  A<T, U> a(T{});
  return a.u_;
}

the following program:
int main() {
  constexpr auto test = foo<int, double>();
  return 0;
}

fails with the error message:
error: constexpr variable 'test' must be initialized by a
      constant expression
  constexpr auto test = foo<int, double>();
                 ^      ~~~~~~~~~~~~~~~~~~
note: read of member 'u_' of union with active member 't_' is
      not allowed in a constant expression
  return a.u_;
         ^
note: in call to 'foo()'
  constexpr auto test = foo<int, double>();
                        ^
1 error generated.

Is there a workaround to achieve this behavior within constant expressions in C++14? reinterpret_cast isn't allowed either.
Motivation: I'm trying to make google-test's floating-point comparison utility constexpr.

A: No, there is no way to do type punning in constant expressions in C++14. There's no way to do it outside of constant expressions either; the code you showed will have undefined behavior at runtime.
As an example of why this is disallowed in general, consider this:
union U { int *p; size_t n; };
int a;
constexpr U u = { &a };
static_assert(u.n != 0x400e158, "'a' is at my favourite address");

If this were allowed, an implementation would be required to determine the runtime address of a during compilation.


text:
Q: WARNING Connection pool is full, discarding connection: fapi.binance.com WARNING Connection pool is full, discarding connection: fapi.binance.com
i created a bot with ccxt to create orders.i used multithreading for creating orders function im getting this error.


text:
Q: Invoking Javascript on VF Page from Static Resource we have a Javascript sheet saved as a static resource and one of our developers is attempting to invoke a function from it in our visualforce page.
In our visualforce page, we are using:
<apex:includeScript value="{!$Resource.QA_Javascript}"/>

And we are trying to call a function for an onlabelclick on a pageBlockSection Item.
When we put the function in the top of the page within <script> tags it works fine, but we are trying to avoid that to keep the page cleaner. Any help is appreciated.

A: Including
<apex:includeScript value="{!$Resource.QA_Javascript}"/>

should work fine. Make sure that you have put the correct name though. In this case, QA_Javascript needs to be the name of the Static Resource not the name of the file itself.
Then, to reference a named function from your javascript in the onlabelclick call on a pageBlockSectionItem simply write:
<apex:pageBlockSectionItem onLabelClick="YourFunctionName()">
</apex:pageBlockSectionItem>

No need to write the file name before your function call.

A: Found the answer, in QA_Javascript Static resource, I saved the file as a .js, but still included  tags. Since removed and fixed, thanks for all of the help everyone.


text:
Q: Is There a way to recover a severely corrupted EXCEL FILE? I'm currently working on my data using Ms.Excel.
But suddenly the file that I'm working in was broken. when I tried to open it again I get error where it contain "ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ" (See Picture).
Screenshoot Corrupted Excel File
The data was not really big, it's only arround 130KB. Besides, Autorecovery Mode was Turned On every 10 minutes. But I don't know How To use it.
I tried to solve the problem many times using below method:

*

*First, I tried to check the "Ignore .... " in Excel Option.

*Second, I tried Open and Repair the file, but still can't open it.

*Third, I tried to use a third party, Using 2 Software (Stellar Phoenix Excel Repair And Recovery Tools For Excel). but Both not Working.

So I wonder if anyone can help me to get my data back? is there any way to recover the file? or is there a way to get the data within the file?

A: Thank you for all the suggestion you gave me, From the last comment I tried to get and extract the data using Programmer editor and using VBA, but both not give a good result, basically when you tried to extract the data when the file is corrupted it only get a unique character.
So here is my solution, since i'm using windows, I tried to Reinstall my Ms.Office and recover my Excel file on mac, and boom the magic worked.
Once again, thanks for your help.


text:
Q: How to add SQL Server in networks list? After changing my PC name and workgroup, I am no longer able to connect to SQL Server.
Currently in my servers list I have only Home & localhost. Anybody know how to add server to networks list?

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) (Microsoft SQL Server, Error: 53)
The network path was not found


text:
Q: Merge Sort not working correctly? void mergeSubArr(int arr[], int lb, int mid, int ub){
    int temp[size], i = lb, j = mid, k = 0;
    while(i<mid && j<=ub){
        if(arr[i] <= arr[j])
            temp[k] = arr[i++];
        else
            temp[k] = arr[j++];
        k++;
    }
    while(i<mid)
        temp[k++] = arr[i++];
    while(j<=ub)
        temp[k++] = arr[j++];

    for(k=0;k<size;k++)
        arr[k] = temp[k];

}

void mergeArr(int num[], int lb, int ub){
    int mid;
    if((ub-lb)>1){
        mid = (lb+ub)/2;
        mergeArr(num, lb, mid);
        mergeArr(num, mid+1, ub);
        mergeSubArr(num, lb, mid+1, ub);
    }
}

when calling the function mergeArr the output is outputting some other elements which are not initially present in the array? I think there is something wrong with the mergeSubArr function please help me out here in finding a solution.

A: There are basically two things wrong with your algorithm:
You fill the array temp from index 0 on. Later, you need to copy it to arr, but starting at the lower bound. You also shouldn't copy size elements, because you can't be sure that the original array even has size elements. (Thanks, BLUEPIXY, for spotting this one.) You should probably also make sure that size is big enough to hold all elements.
Your upper bound is inclusive. That means that if (ub - lb > 1) catches the case where there are more than two elements. You still have to treat the case where there are two elements, which may be in the wrong order, either by making the above condition ub - lb > 0 or by having an else clause where you swap the elements if they are in the wrong order.
So make these changes:
int temp[size], i = lb, j = mid, k = lb;

Start the temp array from the lower bound.
for(k = lb; k <= ub; k++)
    arr[k] = temp[k];

Copy only the subarray in question.
if (ub - lb > 0) ...

Catch the case where there are two elements, too.
On a personal note, I find the mergesort algorithm much easier when it passes subarrays via pointer arithmetic and length. It forgoes much fiddling with offsets.

A: All are okk. Instead  if((ub-lb)>1) Just replace
if((ub-lb)>0)

OR
if(ub > lb)


text:
Q: Get index of rows after groupby and nlargest I have a large dataframe where I want to use groupby and nlargest to look for the second largest, third, fourth and fifth largest value of each group. I have over 500 groups and each group has over 1000 values. I also have other columns in the dataframe which I want to keep after applying groupby and nlargest. My dataframe looks like this
df = pd.DataFrame({
    'group': [1,2,3,3,4, 5,6,7,7,8],
    'a': [4, 5, 3, 1, 2, 20, 10, 40, 50, 30],
    'b': [20, 10, 40, 50, 30, 4, 5, 3, 1, 2],
    'c': [25, 20, 5, 15, 10, 25, 20, 5, 15, 10]
})

To look for second, third, fourth largest and so on of each group for column a I use
secondlargest = df.groupby(['group'], as_index=False)['a'].apply(lambda grp: grp.nlargest(2).min())

which returns
   group   a
0      1   4
1      2   5
2      3   1
3      4   2
4      5  20
5      6  10
6      7  40
7      8  30

I need columns b and c present in this resulting dataframe. I use the following to subset the original dataframe but it returns an empty dataframe. How should I modify the code?
secondsubset = df[df.groupby(['group'])['a'].apply(lambda grp: grp.nlargest(2).min())]

A: If I understand your goal correctly, you should be able to just drop as_index=False, use idxmin instead of min, pass the result to df.loc:
df.loc[df.groupby('group')['a'].apply(lambda grp: grp.nlargest(2).idxmin())]

A: You can uses agg lambda. It is neater
df.groupby('group').agg(lambda grp: grp.nlargest(2).min())


text:
Q: How can I open an .flp file? For context, opening it with notepad on Windows 10 results in gibberish, except a heading that says "PARSONS TECHNOLOGY RESOURCE DATA FILE". It automatically uses ANSI format, with Unix line feeds.
So far I've tried opening it with VLC Media Player, 7-Zip, Gimp, even Audacity, although it's supposed to be a scan of a document.


text:
Q: Show that $\lim{\sup{A}}$ is finite iff $A$ has a limit point Definition. Let $A$ be a nonempty subset of $\mathbb{R}$. $x \in \mathbb{R}$ is called an almost upper bound of $A$ if there are only finitely many $y \in A$ for which $y \geq x$. Similarly we define almost lower bounds. Define $\lim \sup{A}$ to be the infimum of all almost upper bounds of $A$ and $\lim \inf{A}$ to be the supremum of all almost lower bounds of $A$.

Show that $\lim{\sup{A}}$ is finite iff $A$ has a limit point. Similarly show that $\lim{\inf{A}}$ is finite iff $A$ has a limit point.

I don't see how this statement makes sense. If $A = \{1,2,3\}$ isn't $\lim{\sup{A}}$ finite but doesn't have a limit point?

A: If the set $A$ is finite, then every real number is an almost upper bound. The reason is that for any $x$, it is true that only finitely many members of $A$ exceed or are equal to $x$, since $A$ is finite! So $\limsup A$ is the inf of the entire set of reals, which is not finite. Similarly $\liminf A$ is not finite. So your example is not a counterexample.
However, the statement you are trying to prove appears to be true under the additional assumption that $A$ is bounded.
Proof: Spse $a:=\limsup A$ is finite. Let $\epsilon>0$. Since $a$ is the inf of the set of AUBs, the number $a-\epsilon$ is not an AUB. So there are infinitely many members $y$ of $A$ for which $y\ge a-\epsilon$. Moreover, since only finitely many members of $A$ exceed $a+\epsilon$, there exists a member $y$ of $A$ such that $a-\epsilon<y<a+\epsilon$. Since $\epsilon$ was arbitrary, we've shown that $a$ is a limit point of $A$. (This direction doesn't require $A$ to be bounded.)
To prove the converse, suppose $A$ is bounded. Let $a$ be the sup of the set of limit points of $A$, so that $a$ is finite. There are infinitely many members of $A$ that exceed $a-1$ but only finitely many that exceed $a+1$. It follows that the set of AUBs is nonempty and bounded below. Therefore the inf of the set of AUBs is finite.

A: I think that the statement is false. Consider the set
$$
A=\{1/n\,|\, n\in\mathbb N\setminus\{0\}\}\cup\mathbb N
$$
It has a limit point (i.e. 0) but the $ \limsup$ is not finite.

A: The statement is false . Consider the interval $(0,\infty)$. The set of almost upper bounds of $(0,\infty)$ is empty. And we know  inf $  \varnothing =\infty$

A: I like your definition of limit superior of a set A. I have read the concept of limit superior in the context of limit of functions and limit of sequences. But it appears that your definition takes a general view and defines it for a set of numbers. The usual definition matches your definition if we apply your definition (with slight modifications) on the set of values taken by the function or sequence.
However the problem you mention is not correct. Your problem statement is true only when $A$ is bounded above (if we are dealing with $\limsup A$). Similar statement holds for $\liminf A$ if $A$ is bounded below. I use this assumption in the proof which follows.

Let $A$ be a non-empty set of real numbers which is bounded above. We first prove that if $A$ has a limit point $c$ then $\limsup A$ is finite. Now here is the catch! When we say that $A$ has a limit point $c$ then we don't necessarily mean that $c \in A$, but rather that there is some number $c$ which is a limit point of $A$. It is easy to see that the set $B = \{x \mid x \text{ is a limit point of }A\}$ is non-empty and has a greatest member $M$. We show that $\limsup A = M$. This is done via proving the following statements:

*

*If $\xi > M$ then $\xi$ is an almost upper bound for $A$.

*If $\xi < M$ then $\xi$ is not an almost upper bound for $A$.

Clearly if $\xi > M$ then $\xi$ is not the limit point of $A$ because $M$ by definition is the greatest limit point of $A$. It is now clear via Bolzano-Weierstrass Theorem that there can be only finitely many members of $A$ which are greater than or equal to $\xi$. Thus $\xi$ is an almost upper bound of $A$.
If $\xi < M$ then we can see that there are infinitely many points of $A$ which are so near to $M$ as to exceed $\xi$ and hence $\xi$ is not an almost upper bound of $A$.
Thus we have proved that if there is a limit point $c$ of $A$ then $\limsup A$ exists as a finite real number.
Let's prove the converse. Suppose $\limsup A = M$. Then we just need to prove that $M$ is also a limit point of $A$. This is almost obvious. Let $\epsilon > 0$ be given arbitrarily. Then there is an almost upper bound $M'$ of $A$ with $M \leq M' < M + \epsilon$ so that only finitely many members of $A$ are greater than or equal to $M'$. Further $M - \epsilon < M$ and hence $M - \epsilon$ is not an almost upper bound of $A$. It follows that there are infinitely many members of $A$ which are greater than or equal to $M - \epsilon$. It thus follows that there are infinitely many members of $A$ which lie in $[M - \epsilon, M + \epsilon]$ and since $\epsilon > 0$ is arbitrary it follows that $M$ is a limit point of $A$.