text:
Q: How to Build a definition and publish test results for a Java project with maven, Junit and selenium on Visual Studios Team Services VSTS I have an automation script that uses maven POM.xml to import all the dependencies needed from selenium and junit. The main test uses selenium to open a browser, verify some information, close the browser and the test ends.

*

*When run as Junit it works fine:              run as Junit test

*When run as Maven Test it works fine as well: run as maven test
In both scenarios, the program opens the browser and navigates through the website as it should do for an automated test.
Now I need to integrate it to VSTS so I can visualize the overall pass/fail test on the VSTS dashboard but I'm not familiarized with this tool too much yet.
So far this is what I have managed to do:

*

*Deploy an agent on my WindowsPC (I want to execute and deploy the project on an Azure VM or another azure instance later on) NOTE: this is the same pc I'm successfully running the program using eclipse as shown in the screenshoots above. https://learn.microsoft.com/en-us/vsts/build-release/actions/agents/v2-windows?view=vsts

*Create a build definition on VSTS but when I queue the definition the build fails: build definition and the build fail.
I don't know why it can't find mt config.txt file since it is located on the same hosted agent in that same directory. I'll appreciate if someone is capable of guiding me through this process so I can run the program from the VSTS and visualize the overall tests that fail and pass on the VSTS dashboard.
UPDATE: I moved the config.txt file to the public directory and the build was successful(I still need to fix this issue because I do not want my work in a public folder).
Now the problem I have is that even though the build is successful and it looks like it is running my "3 tests", When I look at my pc, nothing is happening. it should open chrome and take a screenshot, then open Firefox and take another screenshot and finally open internet explorer and take another screenshot and save each test on different folders but it is only generating folders for chrome and internet explorer (but still those folders does not have the screenshot I'm asking, maybe because the browser is not being open on the computer.)
Here is the log: https://drive.google.com/open?id=1S_MhAUmzj8i9phPQiqS06s0_1cCRrbF0

*

*test output report generated on my computer

*test output on vsts

A: Look at the error message. The error message tells you precisely what the problem is: java.io.FileNotFoundException: Y:\Automation Team\CopaQA\Architecture\local\config.txt (The system cannot find the path specified)
You need to not rely on hard-coded paths.
You say you registered a build agent against your VSTS account... but did you change the agent queue for your build? If the agent queue is "Hosted", you're using Microsoft's hosted agent.

A:
I don't know why it can't find mt config.txt file since it is located on the same hosted agent in that same directory.

It turns out that Java.IO. can't read files located on a shared network drive, I solved this by using the UNC path to that file (//"computername"/"directory"/"file.txt")

Now the problem I have is that even though the build is successful and
  it looks like it is running my "3 tests", When I look at my pc,
  nothing is happening.

It took me a little reading to realize that to perform UI tests my agent needs to be set up in INTERACTIVE MODE. it can be done following this guide: https://learn.microsoft.com/en-us/vsts/build-release/actions/agents/v2-windows?view=vsts


text:
Q: Python; Line number not repeating in script after looking for ASCII character TL;DR - I need a line number count to repeat, but it's not.
I've looked to see if there's anything that can answer my specific question, and I've gotten a lot of help and nearly have this solved, but just have a question on what is returning for me.
I have a file with a list of peoples' names. It contains a column for Given Name, Surname, and through that I can obtain the full name. What I am trying to do is ascertain whether or not a non-ASCII character is in the name, what character that is, and what line number in the file that name may be found.
Here's a snippet of my code:
with open('testFile.txt', 'r') as myFile:
    for l in lastName:
        if 0 <= ord(l) <= 127:
            pass
        else:
            for num, line in enumerate(myFile, start=1):
                if lastName in line:
                    print('Line number:', num)
            print('Unicode Character:', l, '\n')
    for f in firstName:
        if 0 <= ord(f) <= 127:
            pass
        else:
            for num, line in enumerate(myFile, start=1):
                if firstName in line:
                    print('Line number:', num)
            print('Unicode Character:', f, '\n')

The results work 'okay' but they're not complete. For example, if my file had three names:

*

*Hélen Duçére

*Mike Johnson

*Aïda Flannery

My results look like this:
Line Number: 1
Unicode Character: é

Unicode Character: ç

Unicode Character: é

Line Number: 3
Unicode Character: ï

Is there something obvious in my code to identify exactly why I'm not getting a repeat of the Line Number for that ç or the second é character? Is there a simpler way to write this?

A: This code is a little more compact.
The sub method of regex arranges to substitute patterns that match its first parameter with the value of its second parameter, in the value of its third. The pattern [a-zA-Z ] looks for a single ascii character or a blank. Thus the sub will replace non-ascii characters or blanks with empty strings.
import re

with open ('will.txt') as will:
    for n, line in enumerate(will):
        remaining = re.sub(r'[a-zA-Z ]', '', line.rstrip())
        if remaining:
            print ('Line number:', n+1, 'non-ascii', remaining)

Edit: Making use of KyrSt's comment, the regex should contain some other characters, including, for instance, "'" and "-".
Edit 2: After exhaustive discussion with KyrSt, I've come to the conclusion that he's right, the regex should be [\x00-\x7F]

A: I think there is a simpler way to approach this. Including the parsing of the names and providing you set an appropriate value for variable delimiter below, the code you want could be like this
line_number = 0
with open('testFile.txt', 'r') as myFile:

    line = myFile.readline().replace('\n','')

    while line != '':

        line_number += 1

        firstName, lastName = line.split(delimiter)

        for l in firstName:
            if ord(l) > 127 or ord(l) < 0:
                print('Line number:', line_number)
                print('Unicode Character:', l, '\n')

        for l in lastName:
            if ord(l) > 127 or ord(l) < 0:
                print('Line number:', line_number)
                print('Unicode Character:', l, '\n')

        line = myFile.readline().replace('\n','')

redpajama_set_name: RedPajamaStackExchange


text:
Q: What does exit code 6 mean in Jenkinsfile? I am getting exit code 6 when I trying to invoke Post action on Flowdock API.
I am trying to integrate Flowdock with Jenkins. It's working when I run it as post build job. But it's failing with exit code 6 when I am converting it into Jenkinsfile
def flowdockURL = "https://api.flowdock.com/v1/messages/team_inbox/${apiToken}"
    def payload = JsonOutput.toJson([source : "Jenkins",
                                     project : env.JOB_BASE_NAME,
                                     from_address: fromAddress,
                                     from_name: 'CI',
                                     subject: subject,
                                     tags: tags,
                                     content: content,
                                     link: env.BUILD_URL
                                     ])
    sh """#!/bin/bash
        echo "Sending Flowdock notification..."
        curl --header "Content-Type: application/json" -X POST -s -d \'${payload}\' ${flowdockURL}
    """

I am expecting it to create a tag in flowdock. But it fails. Error is as follows
ERROR:
[Pipeline] sh
Sending Flowdock notification...
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
ERROR: script returned exit code 6
Finished: FAILURE

A: The exit code is from curl, not from Jenkins. According to this it means "Couldn't resolve host"

A: I'm not too familiar with Jenkinsfile, but as far as I found in this link:
Job Exit Status
Code 6: SIGABRT The program called the abort() function. This is an emergency stop.


text:
Q: cocoalibspotify error when attempting to play certain tracks I'm attempting to play the top tracks from the result of an SPArtistBrowse using cocoalibspotify. Most of the time this works flawlessly, but occasionally I get the following error:
Error Domain=com.spotify.CocoaLibSpotify.error Code=3 "The track cannot be played"

This happens only for specific tracks, and for affected tracks it is consistent and repeatable (e.g. the top track for Armin van Buren, spotify:track:6q0f0zpByDs4Zk0heXZ3cO, always gives this error when attempting to play using the code below). The odd thing is, if I use the simple player sample app and enter an affected track's URL, the track plays fine; so my hunch is it has something to do with the track being loaded from an SPArtistBrowse.
Here is the code I am using to play tracks:
- (void)playTrack
{
    SPTrack *track = [self.artistBrowse.topTracks objectAtIndex:self.currentTrackIndex];

    [SPAsyncLoading waitUntilLoaded:track then:^(NSArray *tracks) {
        [self.playbackManager playTrack:track callback:^(NSError *error) {

            if (error) {
                self.currentTrackIndex++;
                if (self.currentTrackIndex < self.artistBrowse.topTracks.count) {
                    [self playTrack];
                } else {
                    [self.activityIndicator stopAnimating];
                    self.activityIndicator.alpha = 0;
                    self.nowPlayingLabel.text = @"Spotify Error";
                }
            } else {
                [self.activityIndicator stopAnimating];
                self.activityIndicator.alpha = 0;
                self.nowPlayingLabel.text = track.name;

                // Set "Now Playing" info on the iOS remote control
                MPNowPlayingInfoCenter *infoCenter = [MPNowPlayingInfoCenter defaultCenter];
                NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
                [dic setValue:track.name forKey:MPMediaItemPropertyTitle];
                [dic setValue:self.artistLabel.text forKey:MPMediaItemPropertyArtist];
                infoCenter.nowPlayingInfo = dic;
            }
        }];
    }];
}

A: The artist browse should affect anything - a track is a track. However, if you can reliably reproduce it, please fork CocoaLibSpotify and add a failing unit test to the unit test suite - that way we can fix it.
It's also possible that the Spotify playback service was unavailable right at the wrong time, but that's a fairly rare occurrence.


text:
Q: Navigation property without referential integrity constraint in Entity Framework 6 In EF 6 (code first), is it possible to have a navigation property set-up without enforcing a referential integrity constraint?
For example:
public class Person{

    public IList<Pet> Pets { get; set; }

}

public class Pet{

    public int OwnerId { get; set; }
    public Person Owner { get; set; }

}

So in the example above I'd like to be able to add a Pet with an OwnerId, even if that owner does not exist in the Owners table.
Thanks
Matt

A: You can define the relationship using the fluent API.
modelBuilder.Entity<Pet>
    .hasOptional(p => p.Owner)
    .willCascadeOnDelete(false);

This will configure the relational property as optional, and will ensure that cascade delete does not take effect.  You can create a Pet without an Owner, and deleting an Owner will not delete the associated Pets.
However you cannot assign Pet.OwnerId to an OwnerId that doesn't exist in the Owner table.  If you truly need to have some way of tracking invalid OwnerId values, you either need to have a separate property which you manually update with an arbitrary value, or you would need to define these objects without using a navigation property, and perform your lookups manually.
It would be an exceptional situation where you would need to supply an arbitrary value for OwnerId that doesn't match the Owner table;  In 99% of all cases, an optional relationship which accepts a valid OwnerId or null is all that is necessary.
The OwnerId property isn't actually necessary on the Pet object, but if it is present, it should be set to int? to be nullable.

A: Short Answer: Don't use EF. The whole point of Object Relational Mappers is to ensure you have valid data as well as help with retrieving/persisting it
All you really want is some sort of mapper.
Long Answer: Curious myself


text:
Q: xcode6 (swift)- Build archive is fail I have a problem. I've written a project with swift. Project is working, not error. But when I'm archiving for send to apple, the project have read errors. Any help would be greatly appreciated! (my project have avfoundation.framework)
Errors:
1- CoreAudioKit/CoreAudioTypes.h file not found
2- AudioToolbox/AudioFormat.h file not found
3- Could not build Objective-c module AVFoundation


text:
Q: How do I get a Unix Executable File to run from anywhere, like Java or Git? I've just created my first Command Line Tool in Xcode.
What do I have to do, or where do I have to put the final output file, so that I can run it from anywhere from within terminal, without having to go to the directory the actual Unix Executable File is in.
An example of this is the Java and Git executables, which I can run in the terminal regardless of the location I'm in.

A: You can add the location into your executable path.
Step 1: Use an editor to open ~/.profile
Step 2: Add the actual path into the file. For example, I added /Users/work/documents/fun/scripts into it and my ~/.profile looks like
export PATH=/usr/local/sbin:/opt/local/bin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/Users/work/documents/fun/scripts:$PATH

Step 3: Restart terminal, and issue which command. You should see the path of your program, and should be able to run the program regardless of your location.
which git
=> /usr/bin/git

Or another way, move the program into the existing executable path. To see existing executable path.
echo $PATH


text:
Q: Modal Logic Question: In S5 modal logic is p and □◊¬p a contradiction? In S5 modal logic is p and □◊¬p a contradiction?
Intuitively, I feel like it is because if it is possible that ¬p then we can't already have p.
If my intuition is correct, how do I show this? If not could someone show me why my intuition is wrong?

A: No. Consider the Kripke frame with two worlds, both accessible to themselves and each other. And let one world have $p$ true, and the other false. The world where $p$ is true has $p\land\square\lozenge\lnot p$ true.
As for the intuition, I would say that just cause something is definitely possibly not the case doesn't imply it's not the case. "p" does not intuitively translate to "we already have $p$"… this way of thinking seems suited to Kripke semantics for intuitionistic logic, but not S5.


text:
Q: Possible ways of geting Sim State as UNKNOWN Can anybody explain, what are possible ways of getting Sim State as UNKNOWN.

A:
public static final int SIM_STATE_UNKNOWN
SIM card state: Unknown. Signifies that the SIM is in transition
  between states. For example, when the user inputs the SIM pin under
  PIN_REQUIRED state, a query for sim status returns this state before
  turning to SIM_STATE_READY.

Also  look at the implementation of the getSimState() method from the TelephonyManager class.
    public State getState() {
      if (mState == null) {
      switch(mPhone.mCM.getRadioState()) {
          /* This switch block must not return anything in
           * State.isLocked() or State.ABSENT.
           * If it does, handleSimStatus() may break
           */
          case RADIO_OFF:
          case RADIO_UNAVAILABLE:
          case SIM_NOT_READY:
          case RUIM_NOT_READY:
              return State.UNKNOWN;
          case SIM_LOCKED_OR_ABSENT:
          case RUIM_LOCKED_OR_ABSENT:
              //this should be transient-only
              return State.UNKNOWN;
          case SIM_READY:
          case RUIM_READY:
          case NV_READY:
              return State.READY;
          case NV_NOT_READY:
              return State.ABSENT;
      }
  } else {
      return mState;
  }

  Log.e(mLogTag, "IccCard.getState(): case should never be reached");
  return State.UNKNOWN;
}

So State.UNKNOWN would be returned whenever radio state is one of RADIO_OFF or RADIO_UNAVAILABLE. Then State.UNKNOWN will be converted to SIM_STATE_UNKNOWN constant by TelephonyManager.getSimState() method.
As a conclusion: getSimState will return SIM_STATE_UNKNOWN whenever the sim state is transitioning from one to another (e.g. When Airplane mode is turned on, between the transitions of Sim State, it will be in SIM_STATE_UNKNOWN).
Reference: Sim State.


text:
Q: Compiling .dproj files from command line I am using Embarcadero Delphi XE2 and I've got a project that I want to compile from command line. I managed to do it with dcc32 on a .dpr, but I had to set some settings.
From what I think, the file .dproj has all the necessary paths and stuff so I wouldn't need to set those variables, so my question is:
Is it possible to compile a delphi command line project from a .dproj file?
Greetings.

A: Yes. It's actually very simple.
Use the Windows Start button to launch Embarcadero RAD Studio XE2->RAD Studio Command Prompt, which sets up the proper environmental variables and search path entries. Then switch to your project folder and simply type MSBuild and hit Enter, which will execute the compiler with the current project file.
If you have more than one .dproj file in the folder, just add it's name after MSBuild, as in MSBuild MyMainProj.dproj.


text:
Q: Get the name of both carriers on Android when the phone is dual Sim Card I need to get the name of the operator of the SIM Card in Android phones with DUAL SIM system, the data of the SIM Card Set as main, I can already get. But the data from the SIM card that is not the main I'm having trouble getting. And I need a lot of that to apply to the project I'm working on, because I need to list both carriers that are present on the phone.
Currently what I was able to evolve was this code
public final class TelephonyInfo {

private static TelephonyInfo telephonyInfo;
private String imsiSIM1;
private String imsiSIM2;
private boolean isSIM1Ready;
private boolean isSIM2Ready;
private String networkOperatorOne;
private String networkOperatorDual;

public String getImsiSIM1() {
    return imsiSIM1;
}

/*public static void setImsiSIM1(String imsiSIM1) {
    TelephonyInfo.imsiSIM1 = imsiSIM1;
}*/

public String getImsiSIM2() {
    return imsiSIM2;
}

/*public static void setImsiSIM2(String imsiSIM2) {
    TelephonyInfo.imsiSIM2 = imsiSIM2;
}*/

public boolean isSIM1Ready() {
    return isSIM1Ready;
}

/*public static void setSIM1Ready(boolean isSIM1Ready) {
    TelephonyInfo.isSIM1Ready = isSIM1Ready;
}*/

public boolean isSIM2Ready() {
    return isSIM2Ready;
}

/*public static void setSIM2Ready(boolean isSIM2Ready) {
    TelephonyInfo.isSIM2Ready = isSIM2Ready;
}*/

public String getNetworkOperatorOne() {
    return networkOperatorOne;
}

/*public void setNetworkOperatorOne(String networkOperatorOne) {
    this.networkOperatorOne = networkOperatorOne;
}*/

public String getNetworkOperatorDual() {
    return networkOperatorDual;
}

/*public void setNetworkOperatorDual(String networkOperatorDual) {
    this.networkOperatorDual = networkOperatorDual;
}*/

public boolean isDualSIM() {
    return imsiSIM2 != null;
}

private TelephonyInfo() {
}

public static TelephonyInfo getInstance(Context context){

    if(telephonyInfo == null) {

        telephonyInfo = new TelephonyInfo();

        TelephonyManager telephonyManager = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE));

        telephonyInfo.imsiSIM1 = telephonyManager.getDeviceId();
        telephonyInfo.imsiSIM2 = null;

        telephonyInfo.networkOperatorOne =telephonyManager.getNetworkOperator();
        telephonyInfo.networkOperatorDual = null ;

        try {
            telephonyInfo.imsiSIM1 = getDeviceIdBySlot(context, "getDeviceIdGemini", 0);
            telephonyInfo.imsiSIM2 = getDeviceIdBySlot(context, "getDeviceIdGemini", 1);
            telephonyInfo.networkOperatorOne = getCarrierName(context,"getCarrierName",0);
            telephonyInfo.networkOperatorDual = getCarrierName(context,"getCarrierName",1);
        } catch (GeminiMethodNotFoundException e) {
            e.printStackTrace();

            try {
                telephonyInfo.imsiSIM1 = getDeviceIdBySlot(context, "getDeviceId", 0);
                telephonyInfo.imsiSIM2 = getDeviceIdBySlot(context, "getDeviceId", 1);
                telephonyInfo.networkOperatorOne = getCarrierName(context,"getCarrierName",0);
                telephonyInfo.networkOperatorDual = getCarrierName(context,"getCarrierName",1);
            } catch (GeminiMethodNotFoundException e1) {
                //Call here for next manufacturer's predicted method name if you wish
                e1.printStackTrace();
            }
        }

        telephonyInfo.isSIM1Ready = telephonyManager.getSimState() == TelephonyManager.SIM_STATE_READY;
        telephonyInfo.isSIM2Ready = false;

        try {
            telephonyInfo.isSIM1Ready = getSIMStateBySlot(context, "getSimStateGemini", 0);
            telephonyInfo.isSIM2Ready = getSIMStateBySlot(context, "getSimStateGemini", 1);
            telephonyInfo.networkOperatorOne = getCarrierName(context,"getCarrierName",0);
            telephonyInfo.networkOperatorDual = getCarrierName(context,"getCarrierName",1);
        } catch (GeminiMethodNotFoundException e) {

            e.printStackTrace();

            try {
                telephonyInfo.isSIM1Ready = getSIMStateBySlot(context, "getSimState", 0);
                telephonyInfo.isSIM2Ready = getSIMStateBySlot(context, "getSimState", 1);
                telephonyInfo.networkOperatorOne = getCarrierName(context,"getCarrierName",0);
                telephonyInfo.networkOperatorDual = getCarrierName(context,"getCarrierName",1);
            } catch (GeminiMethodNotFoundException e1) {
                //Call here for next manufacturer's predicted method name if you wish
                e1.printStackTrace();
            }
        }
    }

    return telephonyInfo;
}

private static String getDeviceIdBySlot(Context context, String predictedMethodName, int slotID) throws GeminiMethodNotFoundException {

    String imsi = null;

    TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

    try{

        Class<?> telephonyClass = Class.forName(telephony.getClass().getName());

        Class<?>[] parameter = new Class[1];
        parameter[0] = int.class;
        Method getSimID = telephonyClass.getMethod(predictedMethodName, parameter);

        Object[] obParameter = new Object[1];
        obParameter[0] = slotID;
        Object ob_phone = getSimID.invoke(telephony, obParameter);

        if(ob_phone != null){
            imsi = ob_phone.toString();

        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new GeminiMethodNotFoundException(predictedMethodName);
    }

    return imsi;
}

private static  boolean getSIMStateBySlot(Context context, String predictedMethodName, int slotID) throws GeminiMethodNotFoundException {

    boolean isReady = false;

    TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

    try{

        Class<?> telephonyClass = Class.forName(telephony.getClass().getName());

        Class<?>[] parameter = new Class[1];
        parameter[0] = int.class;
        Method getSimStateGemini = telephonyClass.getMethod(predictedMethodName, parameter);

        Object[] obParameter = new Object[1];
        obParameter[0] = slotID;
        Object ob_phone = getSimStateGemini.invoke(telephony, obParameter);

        if(ob_phone != null){
            int simState = Integer.parseInt(ob_phone.toString());
            if(simState == TelephonyManager.SIM_STATE_READY){
                isReady = true;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new GeminiMethodNotFoundException(predictedMethodName);
    }

    return isReady;
}

private static String getCarrierName(Context context, String predictedMethodName, int slotID) throws GeminiMethodNotFoundException {

    String carrier = null;

    TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

    try {

        Class<?> telephonyClass = Class.forName(telephony.getClass().getName());

        Class<?>[] parameter = new Class[1];
        parameter[0] = int.class;
        Method sim = telephonyClass.getMethod(predictedMethodName, parameter);

        Object[] obParameter = new Object[1];
        obParameter[0] = slotID;
        Object ob_phone = sim.invoke(telephony, obParameter);

        if (ob_phone != null) {
            carrier = ob_phone.toString();
            if (carrier.equals(TelephonyManager.SIM_STATE_READY)) {
                Log.d("Services", "servicessss" + carrier);
            }

        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new GeminiMethodNotFoundException(predictedMethodName);
    }

    return carrier;
}

private static class GeminiMethodNotFoundException extends Exception {

    private static final long serialVersionUID = -996812356902545308L;

    public GeminiMethodNotFoundException(String info) {
        super(info);
    }
}
}

I need to get this information in this code snippet here.
public void getWidgtesRefernence() {
    listView = (ListView) findViewById(R.id.listView1);
    listView.setOnItemClickListener(this);
    findViewById(R.id.layoutContinue).setOnClickListener(this);
    findViewById(R.id.layoutCancel).setOnClickListener(this);

    LocalPreferences pref = new LocalPreferences(this);
    try {

        TelephonyInfo telephonyInfo = TelephonyInfo.getInstance(this);
        TelephonyManager manager = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
        String op = manager.getSimOperatorName();
        JSONArray operadorasArray = new JSONArray(pref.getPreferenceValueR(LocalPreferences.operadoras));

        for (int i = 0; i < operadorasArray.length(); i++) {
            try {
                JSONObject json = operadorasArray.getJSONObject(i);
                if (op.toLowerCase().contains(json.getString("codigo").toLowerCase())) {
                    operadoras = new JSONArray();
                    operadoras.put(json);
                    if (telephonyInfo.isDualSIM()) {
                      operadoras.put();
                    }
                    break;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        //operadoras = new JSONArray(pref.getPreferenceValueR(LocalPreferences.operadoras));
        listView.setAdapter(new ListAdapterSelectOperator(operadoras, this));
    } catch (Exception e) {
        e.printStackTrace();
    }
}


text:
Q: BlackBerry - BrowserField - NAVIGATION_MODE_NODE - OS 6.0 - Radio buttons don't work [OS 6.0, BrowserField, NAVIGATION_MODE_NODE]
I have a strange problem here...
I must develop an application (6.0) which will use the BrowserField for rendering some HTML files. It will use NAVIGATION_MODE_NODE, the keypad will be used to navigate from a focusable element to another.
I've created a HTML test file here http://dl.dropbox.com/u/1441583/TestPage.html with some input fields.
All of them are working fine, only the radio buttons don't work.

*

*If I don't add "checked="checked"" into a radio button (from a group - all radio buttons are unchecked), the group is skipped (no radio button from the group receives the focus);

*If I check a radio button from a group, only this checked radio button will be focused, but still I cannot select another radio button from the group - the rest of the radio buttons from the group are skipped.
The checkboxes are working fine...
final BrowserFieldConfig browserConfig = new BrowserFieldConfig();
browserConfig.setProperty(BrowserFieldConfig.JAVASCRIPT_ENABLED, Boolean.TRUE);
browserConfig.setProperty(BrowserFieldConfig.ENABLE_COOKIES, Boolean.TRUE);
browserConfig.setProperty(BrowserFieldConfig.ALLOW_CS_XHR, Boolean.TRUE);
browserConfig.setProperty(BrowserFieldConfig.NAVIGATION_MODE, BrowserFieldConfig.NAVIGATION_MODE_NODE);

I'm using 9800 and 9700 emulators (I don't have a 6.0 device), but somebody tested on a real device, and this wrong behavior is present too.
I've tested with www.google.com -> Settings (there are some radio buttons in that page), and the same: I cannot select another radio button from a group...
What I want to implement is: using the BrowserField, I want to navigate between controls using the keys.
Do you have a hint for that?
It's quite urgent...
Thank you very much,
Tibi.
I've tried on a BB 9780, and the combo-box doesn't work!
So, in NAVIGATION_MODE_NODE mode, the radio buttons and combo boxes don't work?
On some 6.0 emulators the combo boxes are working.
Do you have any clue?
Thanks.

A: use BrowserFieldConfig.NAVIGATION_MODE_POINTER, otherwise it doesn't work. It sees your combobox as single node and that is why it is not showing properly.


text:
Q: Why does this jquery dropdown not work? This code seems to show everything correctly but then when launched in the browser, the drop down doesn't work. The hover styling and everything works correctly except for the dropdown.
Thank you.
HTML:
<!doctype html>

<meta charset="utf-8">
<title>GS4 Concept Home Page</title>
<link type="text/css" href="unicss.css" rel="stylesheet"/>

Main Cat 1

Main Cat 2

Sub Cat 2-1

Sub Cat 2-2

Sub Cat 2-3

Sub Cat 2-4

Sub Cat 2-5

Main Cat 3

Sub Cat 3-1

Sub Cat 3-2

Sub Cat 3-3

Sub Cat 3-4

Sub Cat 3-5

Sub Cat 3-6

Sub Cat 3-7

CSS:
@charset "utf-8";
/* CSS Document */
body{
    background-image:url(Images/backgroundmain.jpg);
    min-width:100%;
    font-family: Arial, Helvetica,sans-serif;
    font-size:15px;
}

#header{
    background-color:#474747;
    width:100%;
    display:block;
}

#container{
    margin:auto;
    width:70%;
}

.navigation {
    margin:0;
    padding:0;
    list-style:none;
}

.navigation li {
    float:left;
    width:150px;
    position:relative;
}

.navigation li a {
    background:#262626;
    color:#fff;
    display:block;
    padding:8px 7px 8px 7px;
    text-decoration:none;
    border-top:1px solid #F2861D;
    text-align:center;
    text-transform:uppercase;
}
.navigation li a:hover {
    color:#F2861D;
}

.navigation ul {
    position:absolute;
    left:0;
    display:none;
    margin:0 0 0 -1px;
    padding:0;
    list-style:none;
    border-bottom:3px solid #F2861D;
}

.navigation ul li {
    width:150px;
    float:left;
    border-top:none;
}

.navigation ul a {
    display:block;
    height:15px;
    padding:8px 7px 13px 7px;
    color:#fff;
    text-decoration:none;
    border-top:none;
    border-bottom:1px dashed #6B6B6B;
}

.navigation ul a:hover {
    color:#F2861D;
}

JavaScript:
$(document).ready(function() {
    $('.navigation li').hover(

    function() {
        $('ul', this).fadeIn();
    }, function() {
        $('ul', this).fadeOut();
    });
});

A: Your scripts are in the wrong order.
Instead of

try this:

And also make a nested list, so that your selectors are correct in the main.js file:

Main Cat 1

Main Cat 2

Sub Cat 2-1

Sub Cat 2-2

Sub Cat 2-3

Sub Cat 2-4

Sub Cat 2-5

Main Cat 3

Sub Cat 3-1

Sub Cat 3-2

Sub Cat 3-3

Sub Cat 3-4

Sub Cat 3-5

Sub Cat 3-6

Sub Cat 3-7

A: You can get problems when you use "#" as the href value.


text:
Q: Why is my first panel running twice? I am working on my final project and we are making a quiz to find out what kind of parties people like... but I can't get mine to run sequentially and with this right panels!
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.awt.*;
import javax.swing.ImageIcon;
import java.awt.Dimension;
import javax.swing.JPanel;
import java.awt.GridLayout;
import javax.swing.BoxLayout;
import java.awt.Component;
import java.awt.Container;
import javax.swing.JOptionPane;
import java.applet.Applet;

//This class is where we set up all the questions.
class party{

  int num_questions = 10;
  int panel_number = 0;
  int party_score = 0;
  JFrame frame = new JFrame();
  String AnswerA;
  String AnswerB;
  String AnswerC;
  String AnswerD;
  JButton button1;
  JButton button2;
  JButton button3;
  JButton button4;
  String target_word;
  String user_text;
  String label_text;
  JLabel question_frame;
  JPanel pane;
  JPanel panel;

  public void image_question(){
    //This panel will display four images that the user will choose from.
    panel = new JPanel();
    panel.setLayout(new BorderLayout());
    label_text = "Which party appeals to you the most?";
    question_frame = new JLabel(label_text);
    question_frame.setFont(new Font("Calibri", Font.PLAIN, 20));
    panel.add(question_frame, BorderLayout.NORTH);
    button1 = new JButton();
    JPanel inner = new JPanel();
    inner.setLayout(new GridLayout(0, 2));
    button1.setIcon(new ImageIcon("ball.jpg")); //img1
    button1.setPreferredSize(new Dimension(100, 100));
    button1.setActionCommand("1");
    inner.add(button1);
    button2 = new JButton();
    button2.setIcon(new ImageIcon("christmas_party.jpg"));
    button2.setPreferredSize(new Dimension(100, 100));
    button2.setActionCommand("2");
    inner.add(button2);
    button3 = new JButton();
    button3.setIcon(new ImageIcon("college_party.jpg"));
    button3.setPreferredSize(new Dimension(100, 100));
    button3.setActionCommand("3");
    inner.add(button3);
    button4 = new JButton();
    button4.setIcon(new ImageIcon("kid_party.jpg"));
    button4.setPreferredSize(new Dimension(100, 100));
    button4.setActionCommand("4");
    inner.add(button4);
    panel.add(inner, BorderLayout.CENTER);
    //ImageIcon icon = new ImageIcon("Alex.jpg");
    //frame.getContentPane().add(new JLabel(icon), BorderLayout.EAST);
    //frame.setVisible(true);
    frame.add(panel);

    ActionListener al = new click();

    button1.addActionListener(al);
    button2.addActionListener(al);
    button3.addActionListener(al);
    button4.addActionListener(al);
    frame.setSize(600, 600);
    frame.setVisible(true);
    frame.setBackground(Color.white);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }

  public void multiple_choice_question(){
    //This panel displays a 4 answer multiple choice question that they user will choose from.
    pane = new JPanel();
    pane.setLayout(new BorderLayout());
    label_text = "What music would you prefer at a party?";
    question_frame = new JLabel(label_text);
    pane.add(question_frame, BorderLayout.NORTH);
    JPanel center = new JPanel();
    GridLayout grid = new GridLayout(0,2);
    center.setLayout(grid);
    pane.add(center, BorderLayout.CENTER);
    AnswerA = "1";
    AnswerB = "2";
    AnswerC = "3";
    AnswerD = "4";
    ActionListener al = new click();
    addAButton(AnswerA, center, al, "1");
    addAButton(AnswerB, center, al, "2");
    addAButton(AnswerC, center, al, "3");
    addAButton(AnswerD, center, al, "4");
    frame.add(pane);
    frame.setSize(600, 600);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }

  public void input_question(){
    //This panel will display a question and chance for the user to input their answer.
    user_text = JOptionPane.showInputDialog(null, "Describe your ideal party");
    target_word = "music";
    if (user_text.indexOf(target_word) >=0){
      System.out.println("ho ho ho");
    }
  }

    public void party() {
    panel_number++;
      if (panel_number == 1){
        image_question();
      }

      if(panel_number == 2){
        multiple_choice_question();
      }

      if(panel_number == 3){
        input_question();
      }
    /*  else if (panel_number == 4){
        image_question();
      }

      else if(panel_number == 5){
        multiple_choice_question();
      }

      else if(panel_number == 6){
        input_question();
      }*/

  }

  private static void addAButton(String text, Container container, ActionListener al, String actionCommand) {
       JButton button = new JButton(text);
       button.setAlignmentX(Component.CENTER_ALIGNMENT);
       container.add(button);
       button.addActionListener(al);
       button.setActionCommand(actionCommand);
  }

    public static void main(String args[]) {
        party myGUI = new party();
    myGUI.party();
    }

class ClassParty{
 //This class will read txt documents created by users and suggest a party that everyone would enjoy!
}

class click implements ActionListener{
   public void actionPerformed(ActionEvent event){
     party partier = new party();
      if (event.getActionCommand().equals("1")){
        party_score++;
      }
      else if  (event.getActionCommand().equals("2")){
        party_score++;
      }
      else if  (event.getActionCommand().equals("3")){
        party_score++;
      }
      else if (event.getActionCommand().equals("4")){
        party_score++;
      }
      System.out.println(panel_number);
      frame.dispose();
      party();
      //System.out.println(party_score);

     /* creates a GUI that presents the user with a question with clickable answers that gives you the next question
    when you finish answering. It plays jeapordy theme music and has a picture Alex Trabeck. It has a status bar
    that tells you how close you are to finishing the program. */

  }
}
}

When I run my code it runs the image_question twice and then runs input_question and quits. I can't get the multiple_choice_question to work.

A: I fixed it using debug and stepping through each command.  Debug works great, you should try it.  Debug was key because it showed that multiple_choice_question() was actually getting reached, even though the GUI looked like the first GUI.  It narrowed down the source of the bug.
public void multiple_choice_question(){
    frame=new JFrame();    <----add this and everything seems to be working
    pane = new JPanel();
    pane.setLayout(new BorderLayout());
    label_text = "What music would you prefer at a party?";
     ...


text:
Q: "grab" Post form response with php (response is a txt file) I have a form that posts a file to a site that I don't have control and that site responds with a dynamically generated text file based on the uploaded file. That response is downloaded by the client after the form is submitted. My question is: how can I grab this text file and copy it to my server before it gets to the user?
Possible solution 1: is there a way to change this file's headers and put its content to some hidden div or iframe?
Possible solution 2: I think the best way is that I create a script that gets the form data and then reposts it to the external site and then gets the response and writes this response to my site in a txt file. Unfortunately all my attempts to get this working have failed.
Example of solution 2:
<form action="mysite.com/respostScriptThatGrabsResponse.php" method="post">
    <input type="file" name="filename"/>
    <input type="submit" value="submit"/>
</from>

A: Theory #2 would be the way to go. You could use cURL to post the data to the external site. The most likely obstacle preventing success would be the external site requiring cookie data that only the client would have.


text:
Q: nginx 400 Bad Request (Invalid Hostname) I've configured nginx as a front-end load-balancer across three nodes of a web application I've constructed. nginx continually returns 400/bad request - invalid hostname errors regardless of the values i use in upstream.server and server.server_name. I've tried localhost and 127.0.0.1 for both of those values and issued requests using matching cURL/Postman requests to no avail.
I've also tried setting the value for server.server_name including the port number to better match the incoming HTTP HOST header to no avail.
nginx.conf
events {
  worker_connections  1024;
}

http {
  upstream myapp {
    server 127.0.0.1:8001;
    server 127.0.0.1:8002;
    server 127.0.0.1:8003;
  }

  server {
    listen 8000;
    server_name 127.0.0.1;
    location / {
      proxy_pass http://myapp;
    }
  }
}

cURL requests result in the following (no difference between using localhost and 127.0.0.1).
C:\>curl -v http://127.0.0.1:8000/
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to 127.0.0.1 (127.0.0.1) port 8000 (#0)
> GET / HTTP/1.1
> Host: 127.0.0.1:8000
> User-Agent: curl/7.55.1
> Accept: */*
>
< HTTP/1.1 400 Bad Request
< Server: nginx/1.17.1
< Date: Mon, 22 Jul 2019 14:29:22 GMT
< Content-Type: text/html; charset=us-ascii
< Content-Length: 334
< Connection: keep-alive
<
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii">

Bad Request - Invalid Hostname

HTTP Error 400. The request hostname is invalid.

* Connection #0 to host 127.0.0.1 left intact

A: Try with this configuration:
events {
  worker_connections  1024;
}

http {
  upstream myapp {
    server 127.0.0.1:8001;
    server 127.0.0.1:8002;
    server 127.0.0.1:8003;
  }

  server {
    listen 8000;
    server_name 127.0.0.1;
    location / {
      proxy_pass http://myapp;
      proxy_set_header Host $host;
    }
  }
}

A: I received the same error, but I am using nginx in front of IIS. But it was intermittent. It was every other request that failed which was odd.
Turns out I had bound my IIS hostname to a specific IP (as opposed to all IPs) and IIS was load balancing but failing to resolve the other IP.
Telling IIS to bind to all IPs resolved it. Only took a couple hours to figure that out.


text:
Q: Why is EWS search filter returning fewer emails than I see from outlook? I am using the following code to retrieve emails whose subject contains "MS" and "QW". I see more than 8 emails satisfying the search criteria, but the code returns only two emails. Can anyone help me take a look at what the problem is in here?
     var filter1 = new SearchFilter.ContainsSubstring(ItemSchema.Subject, "MS", ContainmentMode.Substring, ComparisonMode.IgnoreCase);
     var filter2 = new SearchFilter.ContainsSubstring(ItemSchema.Subject, "QW");
     var sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, filter1, filter2);
     var findResults = service.FindItems(WellKnownFolderName.Inbox, sf view);

A: A few things I can see if with the Second search filter you haven't specified the ContainmentMode or ComparsisonMode. You also don't seem to have added them to the SearchFilter Collection. eg you should have
sf.Add(filter1);
sf.Add(filter2);
That Search will yield pretty poor performance on a folder with a large number I would suggest you maybe look at AQS then you can do
service.FindItems(WellKnownFolderName.Inbox, "Subject:MS AND Subject:QW" ,view);
That will search against the Content Indexes and yield better performance.


text:
Q: How to update row-wise filter in Shiny datatable I'm trying to update row-wise filter in datatable basis on the inputs we receive from user on every row, so that only relevant values in sub-sequent inputs can be selected.
I have tried to replicate my scenario using below code, where in if User selects "setosa" as "spieces_selector" hence only "1-50" values should appear in "New_Data_selector". Similarly if a User selects "versicolor" in 2nd row hence for 2nd row "New_Data_selector" should have the values from "51-100".
Would appreciate your help on this.
library(shiny)
library(DT)

iris$New_Data <- c(1:150)

ui <- fluidPage(
  title = 'Selectinput column in a table',
  h3("Source:", tags$a("Yihui Xie", href = "https://yihui.shinyapps.io/DT-radio/")),
  numericInput('num', "enter a number", value = 5, min = 1, max = 10, step = 1),
  DT::dataTableOutput('foo'),
  verbatimTextOutput('sel'),
  actionButton(
    "saveBtn",
    "Submit Request",
    style = "color: #fff; background-color: #282364;
                                     border-color: #2e6da4",
    class = "btn btn-primary"
  )
)

server <- function(input, output, session) {
  data <- reactive({
    df <- head(iris, input$num)

    for (i in 1:nrow(df)) {
      df$species_selector[i] <- as.character(selectInput(paste0("sel1", i),
                                                         "",
                                                         choices = unique(iris$Species),
                                                         width = "100px"))

      df$New_Data_selector[i] <- as.character(selectInput(paste0("sel2", i),
                                                         "",
                                                         choices = unique(iris$New_Data),
                                                         width = "100px"))
    }
    df
  })

  output$foo = DT::renderDataTable(
    data(), escape = FALSE, selection = 'none', server = FALSE,
    options = list(dom = 't', paging = FALSE, ordering = FALSE),
    callback = JS("table.rows().every(function(i, tab, row) {
        var $this = $(this.node());
        $this.attr('id', this.data()[0]);
        $this.addClass('shiny-input-container');
      });
      Shiny.unbindAll(table.table().node());
      Shiny.bindAll(table.table().node());")
  )
  output$sel = renderPrint({
    str(sapply(1:nrow(data()), function(i) input[[paste0("sel", i)]]))
  })

  observeEvent(input$saveBtn, {

    Test_Data <- sapply(1:nrow(data()), function(i) input[[paste0("sel", i)]])
    Test_Data <- as.data.frame(Test_Data)
    print(Test_Data)})

}

shinyApp(ui, server)

A: The following works (based on my earlier answer) - but it's pretty slow. Will need to investigate further.
library(DT)
library(shiny)
library(datasets)
library(data.table)

myIris <- copy(iris)
setDT(myIris)

myIris[, Index := seq_len(.N)]

selectInputIDs_A <- paste0("sel_A", myIris$Index)
selectInputIDs_B <- paste0("sel_B", myIris$Index)

myIris[, selectInputs_A := sapply(selectInputIDs_A, function(x){as.character(selectInput(inputId = x, label = "", choices = unique(myIris$Species), selected = "setosa"))})]
myIris[, selectInputs_B := sapply(selectInputIDs_B, function(x){as.character(selectInput(inputId = x, label = "", choices = unique(myIris[Species == "setosa"]$Index), selected = "setosa"))})]

initTbl <- copy(myIris)

ui <- fluidPage(
  DT::dataTableOutput(outputId = 'my_table')
)

server <- function(input, output, session) {

  displayTbl <- reactive({
    myIris[, selectInputs_A := sapply(selectInputIDs_A, function(x){as.character(selectInput(inputId = x, label = "", choices = unique(Species), selected = input[[x]]))}),]
    myIris[, selectInputs_B := sapply(seq_along(selectInputs_B), function(x){as.character(selectInput(inputId = selectInputIDs_B[x], label = "", choices = unique(myIris[Species == input[[selectInputIDs_A[x]]]]$Index), selected = input[[selectInputIDs_A[x]]]))})]
  })

  output$my_table = DT::renderDataTable({
    DT::datatable(
      initTbl, escape = FALSE, selection = 'none', rownames = FALSE,
      options = list(paging = FALSE, ordering = FALSE, scrollx = TRUE, dom = "t",
                     preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
                     drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } ')
      )
    )
  }, server = TRUE)

  my_table_proxy <- dataTableProxy(outputId = "my_table", session = session)

  observeEvent({sapply(selectInputIDs_A, function(x){input[[x]]})}, {
    replaceData(proxy = my_table_proxy, data = displayTbl(), rownames = FALSE) # must repeat rownames = FALSE see ?replaceData and ?dataTableAjax
  }, ignoreInit = TRUE)

}

shinyApp(ui = ui, server = server)


text:
Q: Crash around pthreads while integrating SQLite into RTP application on VxWorks I am trying to integrate SQLite library into RTP application on VxWorks. I built SQlite and link against it statically. I run simple test that works well on other systems. The test is realy primitive one: sqlite_open(), sqlite_exec(), sqlite_close(). Parameters are correct (works on other systems).
I experience SIGSEGV (signal code 11). I traced down to the point of crash with "printf()s" and discovered that it crashes after pthread_mutex_lock() call. What is interesting - it returns from the function call and then crashes. I checked the stack size (having a taskDelay() afore actual crash). Stack is big enough and far from its limit.
I try to build SQlite with SQLITE_HOMEGROWN_RECURSIVE_MUTEX and without. And I build all the time with SQLITE_THREADSAFE 1.
If someone has experienced something like that and managed to fix it - please let me know.
Here are few details, jut to outline them.

*

*VxWorks wersion: 6.8

*SQlite sources: 3.7.16.1

*Development environment: Windriever

*CPU Architecture: PowerPC

Thanks in advance

A: I have found it. I had no pthreads in my VxWorks OS. Now it works.
The strange thing is that there is no way to verify that while building an application against pthreads library.
There is no easy way to do that, but at least some kind of "stub" function, rhater than SIGSEGV. Or am I asking too much for that kind of money?


text:
Q: Replace one python object with another everywhere How do I replace a python object everywhere with another object?
I have two classes, SimpleObject and FancyObject. I've created a SimpleObject, and have several references to it. Now I'd like to create a FancyObject, and make all those references point to the new object.
a = SimpleObject()
some_list.append(a)
b = FancyObject()

a = b is not what I want, it just changes what a points to. I read the following would work, but doesn't. I get an error "Attribute __dict__ is not writable":
a.__dict__ = b.__dict__

What I want is the equivalent of (pseudo-C):
*a = *b

I know this is hacky, but is there any way to accomplish this?

A: There's no way. It'd let you mutate immutable objects and cause all sorts of nastiness.
x = 1
y = (x,)
z = {x: 3}
magic_replace(x, [1])
# x is now a list!
# The contents of y have changed, and z now has an unhashable key.

x = 1 + 1
# Is x 2, or [1, 1], or something stranger?

A: You can put that object in global namespace of separate module and than monkey patch it when you need.
objstore.py:
replaceable = object()

sample.py:
import objstore

b = object()

def isB():
     return objstore.replaceable is b

if __name__ == '__main__':
     print isB()#False
     objstore.replaceable = b
     print isB()#True

P.S. Rely on monkey patching is a symptom of bad design

A: PyJack has a function replace_all_refs that replaces all references to an object in memory.
An example from the docs:
>>> item = (100, 'one hundred')
>>> data = {item: True, 'itemdata': item}
>>>
>>> class Foobar(object):
...     the_item = item
...
>>> def outer(datum):
...     def inner():
...         return ("Here is the datum:", datum,)
...
...     return inner
...
>>> inner = outer(item)
>>>
>>> print item
(100, 'one hundred')
>>> print data
{'itemdata': (100, 'one hundred'), (100, 'one hundred'): True}
>>> print Foobar.the_item
(100, 'one hundred')
>>> print inner()
('Here is the datum:', (100, 'one hundred'))

Calling replace_all_refs
>>> new = (101, 'one hundred and one')
>>> org_item = pyjack.replace_all_refs(item, new)
>>>
>>> print item
(101, 'one hundred and one')
>>> print data
{'itemdata': (101, 'one hundred and one'), (101, 'one hundred and one'): True}
>>> print Foobar.the_item
(101, 'one hundred and one')
>>> print inner()
('Here is the datum:', (101, 'one hundred and one'))

A: You have a number of options:

*

*Design this in from the beginning, using the Facade pattern (i.e. every object in your main code is a proxy for something else), or a single mutable container (i.e. every variable holds a list; you can change the contents of the list through any such reference). Advantages are that it works with the execution machinery of the language, and is relatively easily discoverable from the affected code. Downside: more code.

*Always refer to the same single variable. This is one implementation of the above. Clean, nothing fancy, clear in code. I would recommend this by far.

*Use the debug, gc, and introspection features to hunt down every object meeting your criterion and alter the variables while running. The disadvantage is that the value of variables will change during code execution, without it being discoverable from the affected code. Even if the change is atomic (eliminating a class of errors), because this can change the type of a variable after the execution of code which determined the value was of a different type, introduces errors which cannot reasonably be anticipated in that code. For example
a = iter(b) # will blow up if not iterable
[x for x in b] # before change, was iterable, but between two lines, b was changed to an int.

More subtly, when discriminating between string and non-string sequences (because the defining feature of strings is that iterating them also yields strings, which are themselves iterable), when flattening a structure, code may be broken.
Another answer mentions pyjack which implements option 3. Although it may work, it has all of the problems mentioned. This is likely to be appropriate only in debugging and development.

A: Take advantage of mutable objects such as a list.
a = [SimpleObject()]
some_list.append(a)
b = FancyObject()
a[0] = b

Proof that this works:
class SimpleObject():
    def Who(self):
        print 'SimpleObject'

class FancyObject():
    def Who(self):
        print 'FancyObject'

>>> a = [SimpleObject()]
>>> a[0].Who()
SimpleObject
>>> some_list = []
>>> some_list.append(a)
>>> some_list[0][0].Who()
SimpleObject
>>> b = FancyObject()
>>> b.Who()
FancyObject
>>> a[0] = b
>>> some_list[0][0].Who()
FancyObject


text:
Q: Pacman maze in Java So I'm building the pacman game in Java to teach myself game programming.
I have the basic game window with the pacman sprite and the ghost sprites drawn, the pacman moves with the arrow keys, doesn't move beyond the walls of the window, etc. Now I'm trying to build the maze, as in this picture:

Without giving me the direct/complete solution to this, can someone guide me as to how this can be built? I'm talking only about the boundaries and the pipes('T' marks) here which you can't go through and you have to go around. Not the dots which the pacman eats yet.
Here are my questions:
1) What's the most efficient algorithm/method for creating this maze? Will it have to be drawn each time the paint() method is called or is there a way to draw it only at the start of the game and never again?
2) How will this actually be drawn to the screen? I assume the fillRect() will be used?
3) Any hints on collision detection (so the pacman/ghosts can't go through the walls) would be helpful.
4) Any hints on how the vacant space between the pipes will be calculated so the dots can be filled between them will also be very helpful.
Thanks

A: *

*You can paint the map into a BufferedImage and just drawImage that on every paint(). You'll get quite reasonable performance this way.

*If you are happy with the walls being solid, you can draw each square wall block with fillRect. If you wish to get the same look as in the picture, you need to figure how to draw the lines in the right way and use arcs for corners.

*The Pacman game map is made of squares and Pacman and the ghosts always move from one square to the neighbouring square in an animated step (i.e. you press right, the pacman moves one square to the right). That means that collision detection is easy: simply don't allow moves to squares that are not empty.

*I do not understand what you are trying to ask here.

A: 1) Just to give my advice on redrawing. Something that you can do if you find redrawing the entire image is slow, is determine only the elements that have changed on the screen and redraw those. An approach for this would be the following: Determine the sprites that have moved. Determine (approximate) a rectangle around those sprites. Redraw those rectangles only. This way you are only refreshing parts of the screen and not the whole screen. This should result in an increase in performance over redrawing the entire screen.
The other answers have been reasonable for the other questions you have asked.

A: I wouldn't do it that way.
I'd draw the graphical map and then create a 2D data array which represents the map. The data map would be responsible for determining collisions, eating dots, where candy is and where the ghosts are. Once all the logic for everything is handled just use the 2D array to display everything in their proper pixel coordinates over the graphical map.
For example the user is pressing the left key. First you determine that pacman is at element 3, 3. Element 3, 2 contains information denoting a wall so you can implement the code to make him ignore the command.
EDIT:
Each element would represent about where a dot could be. For example:
No, looking at the board I would say the array would look something like this.
d,d,d,d,d,d,d,d,d,d,d,d,w,w,d,d,d,d,d,d,d,d,d,d,d,d
d,w,w,w,w,d,w,w,w,w,w,d,w,w,d,w,w,w,w,w,d,w,w,w,w,d
p,w,w,w,w,d,w,w,w,w,w,d,w,w,d,w,w,w,w,w,d,w,w,w,w,p
d,w,w,w,w,d,w,w,w,w,w,d,w,w,d,w,w,w,w,w,d,w,w,w,w,d
d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d

And so on. You might want to pick a more flexible data structure than just characters however since some areas need to contain a bunch of different information. IE even though the ghost spawning area is blank, pacman isn't allowed in there. The movement of the ghosts and pacman is different for the side escapes, the candy spawn point is a blank spot but if you want to remain flexible you'll want to denote where this is on a per map basis.
Another thing you'll want to remember is that pacman and the ghosts are often inbetween points so containing information that represents a percentage of a space they're taking up between 1,2 and 1,3 is important for collision detection as well as determining when you want to remove dots, powerups and candy from the board.


text:
Q: how to fill with a texture in html5 (and still be able to change the color?) I'm creating an html5 canvas drawing app.
I want to paint with a gritty texture.  I know that I can use fill with a specific image as a texture, but then the color is locked to that image.  I still want to be able to change the color via a color picker.  I just want the grittiness to come through.
What solutions are available?

A: Read about my answer to "tinting" an image here: How can I use a gradient map to tone a HTML5 canvas with an image in the canvas.
You can always very easily manipulate the pixel data of an image to give off a different hue than its original hue (or no hue at all if you average the RGB, getting a gray-scale image).
So that's at least one option.
What you'd do here: Instead of using an image as the texture, draw the image to a temporary canvas and then modify the hue of that entire canvas with your color picker, than use that canvas as your pattern. (both images and canvases are valid input for creating patterns)


text:
Q: How to display Jupyterlab output in new tab? I am trying to get an output tab in Jupyterlab that shows the output of my code. Right now I can right-click on a cell output in the notebook and create an output view -- but this view does not update as I execute additional cells. Is there a way to do this (a setting or extension)?
I envision something like the Python extension in VS Code that allows you to split the screen and run cell code on the left and see the output on the right.

A: Just right-click the tab which shows the name of the file you are editing.
In the popup window select New View for Notebook.
A new tab (in a new window) will be opened and the output(s) of your file will be shown there.
Here after, if you give additional codes and run them, you will see that the output is updated in the New view.
Particularly, when you have a cell with markdown format, your input in that cell   will be rendered (as you type) in the new view as a formatted one!

A:
Right now I can right-click on a cell output in the notebook and create an output view

That's right.

but this view does not update as I execute additional cells.

That's right too. It is THE view of THE output for the cell you selected. If you produce some new output on THAT cell, it will update. Each cell has its own output area.

Is there a way to do this (a setting or extension)?

I'd suggest you explore the "output" widget. I can be very versatile once you learn to use it well (easier said than done).
https://ipywidgets.readthedocs.io/en/stable/examples/Output%20Widget.html

but this view does not update as I execute additional cells. Is there a way to do this (a setting or extension)?

Yes.
https://github.com/xiaohk/stickyland
This extension allows (among other things) to have one/multiple cells to rerun every time you run any cell.
The 2+1 guys there made a brilliant extension that works flawlessly. I can't praise them enough.

I envision something like the Python extension in VS Code that allows you to split the screen and run cell code on the left and see the output on the right.

That is also available.

It is under View > Render side by side

You are mixing up too many things.
See this:
https://github.com/jupyter/notebook/issues/2897


text:
Q: An Authentication object was not found in the SecurityContext - Servlet 3 with Async Support Using Spring 3.2 with Async Support. The security context is lost once inside the anonymous Callable method
@RequestMapping(value = "/home", method = RequestMethod.GET)
public Callable<String> home(final Model model) {
    return new Callable<String>() {
        @Override
        public String call() throws Exception {
            model.addAttribute("homeService", homeService.findId(1));
            return "home";
        }
    };
}

This is security decorator applied to a bean inside the servlet-context.xml
<beans:bean id="homeService" class="example.service.HomeServiceImpl" scope="request">
    <security:intercept-methods>
        <security:protect access="ROLE_USER" method="find*"/>
    </security:intercept-methods>
</beans:bean>

This is the error because a security context doesn't exist:
org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext

A: Upgrade to Spring Security 3.2.0 RC1 was the solution.
This article mentions Spring Security 3.2 being compatible with Servlet 3 Async Support.

Associating SecurityContext to Callable's
  More technically speaking,
  Spring Security integrates with WebAsyncManager. The SecurityContext
  that is used to process the Callable is the SecurityContext that
  exists on the SecurityContextHolder at the time
  startCallableProcessing is invoked.

Maven dependency:
<dependencies>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>3.2.0.RC1</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>3.2.0.RC1</version>
    </dependency>
</dependencies>

<repositories>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>http://repo.spring.io/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>
<repositories>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>http://repo.spring.io/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>


text:
Q: How to make a transparent (alpha) gradient mask to make one layer fade into transparency in Android? I want to makes one layer fade into the beneath layers (or transparency depends on how you see it) according to a gradient. A so-called transparent (alpha) gradient mask. I am looking for a solution similar to this but on android instead of ios:

I have tried this solution but as mentioned in the comments, the overlay is not making the layer beneath transparent, it only makes it fade to a specified color.
Any suggestions?

A: You could use Android-FadingEdgeLayout library.
Or here's a subclassed framelayout based on the said lib:
public class AlphaGradientLayout extends FrameLayout {

    private static final int DEFAULT_GRADIENT_SIZE_DP = 80;

    public static final int FADE_EDGE_TOP = 1;
    private static final int DIRTY_FLAG_TOP = 1;

    private static final int[] FADE_COLORS = new int[]{Color.TRANSPARENT, Color.BLACK};

    private boolean fadeTop;
    private int gradientSizeTop;
    private Paint gradientPaintTop;
    private Rect gradientRectTop;
    private int gradientDirtyFlags;

    public AlphaGradientLayout(Context context) {
        super(context);
        init(null, 0);
    }

    public AlphaGradientLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs, 0);
    }

    public AlphaGradientLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs, 0);
    }

    private void init(AttributeSet attrs, int defStyleAttr) {
        int defaultSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DEFAULT_GRADIENT_SIZE_DP,
                getResources().getDisplayMetrics());

        if (attrs != null) {
            TypedArray arr = getContext().obtainStyledAttributes(attrs, R.styleable.AlphaGradientLayout, defStyleAttr, 0);
            int flags = arr.getInt(R.styleable.FadingEdgeLayout_fel_edge, 0);

            fadeTop = (flags & FADE_EDGE_TOP) == FADE_EDGE_TOP;

            gradientSizeTop = arr.getDimensionPixelSize(R.styleable.FadingEdgeLayout_fel_size_top, defaultSize);

            if (fadeTop && gradientSizeTop > 0) {
                gradientDirtyFlags |= DIRTY_FLAG_TOP;
            }

            arr.recycle();
        } else {
            gradientSizeTop = defaultSize;
        }

        PorterDuffXfermode mode = new PorterDuffXfermode(PorterDuff.Mode.DST_IN);
        gradientPaintTop = new Paint(Paint.ANTI_ALIAS_FLAG);
        gradientPaintTop.setXfermode(mode);

        gradientRectTop = new Rect();
    }

    @Override
    public void setPadding(int left, int top, int right, int bottom) {
        if (getPaddingTop() != top) {
            gradientDirtyFlags |= DIRTY_FLAG_TOP;
        }
        super.setPadding(left, top, right, bottom);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        if (h != oldh) {
            gradientDirtyFlags |= DIRTY_FLAG_TOP;
        }
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        int newWidth = getWidth(), newHeight = getHeight();
        boolean fadeAnyEdge = fadeTop;
        if (getVisibility() == GONE || newWidth == 0 || newHeight == 0 || !fadeAnyEdge) {
            super.dispatchDraw(canvas);
            return;
        }

        if ((gradientDirtyFlags & DIRTY_FLAG_TOP) == DIRTY_FLAG_TOP) {
            gradientDirtyFlags &= ~DIRTY_FLAG_TOP;

            int actualHeight = getHeight() - getPaddingTop() - getPaddingBottom();
            int size = Math.min(gradientSizeTop, actualHeight);
            int l = getPaddingLeft();
            int t = getPaddingTop();
            int r = getWidth() - getPaddingRight();
            int b = t + size;
            gradientRectTop.set(l, t, r, b);
            LinearGradient gradient = new LinearGradient(l, t, l, b, FADE_COLORS, null, Shader.TileMode.CLAMP);
            gradientPaintTop.setShader(gradient);
        }

        int count = canvas.saveLayer(0.0f, 0.0f, (float) getWidth(), (float) getHeight(), null, Canvas.ALL_SAVE_FLAG);
        super.dispatchDraw(canvas);
        if (fadeTop && gradientSizeTop > 0) {
            canvas.drawRect(gradientRectTop, gradientPaintTop);
        }
        canvas.restoreToCount(count);
    }
}

Then move the items that you want faded inside this layout
And here's what you should get


text:
Q: Mongoose findOneAndUpdate on model What's the purpose of a Mongoose schema if I'm doing an upsert with findOneAndUpdate call?
Everything I can find seems to indicate if I do a findOneAndUpdate, I need to reference the base schema instead of an instance.
Here's my setup:
const PersonSchema = new mongoose.Schema({
  ssn: {
    type: Number,
    unique: true,
  },
  first: String,
  last: String
})

const Person = mongoose.model("Person", PersonSchema)
const person = new Person({ssn: 123456789, first: "Foo", last: "Bar"})

If I just do a save (and that ssn exists already, I'll get a 'unique' violation).
person.save();

Instead, I'm finding out that I need to do something like
const options = { upsert: true, new: true }
const query = { ssn: 123456789 }

Person.findOneAndUpdate(
  query,
  {
    ssn: 123456789,
    first: "Foo",
    last: "Bar"
  },
  options)

OR
const options = { upsert: true, new: true }
const query = { ssn: 123456789 }

const newPerson = Object.assign({}, person._doc)

// delete this so I don't get a conflict with Mongoose on the _id during insert
delete newPerson._id

Person.findOneAndUpdate(query, newPerson, options)

It seems like findOneAndUpdate doesn't care about the specific model (or instance) and is simply just a mechanism to get to the underlying MongoDB method.
Is that the case? Or am I missing something that should be obvious?


text:
Q: in a MEAN.js stack, where can i configure the jshint warnings? im developing a mean-stack based application, and suddenly im getting 750 errors in 150 pages because of jshint, none of these errors create a problem in the sense that the code is breaking, so this huge list just junks up my console with warnings that 'require' is undefined.
i know this is somewhat of a stupid question but ive been looking for hours and i dont find any file that resembles something that i can work with.
where are the jshint configuration files in a mean.js stack based application? what is the path?

A: Just create a .jshintrc file. jshint will obey rules defined in a .jshintrc file in a root directory and it will also apply any rule overrides defined in .jshintrc files found in your project's subdirectories.
The format looks like this:
{
    "bitwise"       : false,    // Prohibit bitwise operators (&, |, ^, etc.).
    "curly"         : true,     // Require {} for every new block or scope.
    "eqeqeq"        : true      // Require triple equals i.e. `===`.
}

The full set of options are defined here: http://jshint.com/docs/options/


text:
Q: Defining Legendre polynomials in terms of a sinusoidal function for $|x| \leq 1$ Would it be possible to define Legendre polynomials in terms of a sinusoidal function for $|x|\leq 1$ in a similar manner to Chebyshev polynomials being defined as $T_n(x) = \cos(n \cos^{-1}(x))$?
Thanks.

A: No doubt that $x=\cos\theta$ is a meaningful substitution for the Legendre polynomials. The functions $P_n(\cos\theta)$ were already considered by Legendre in the spherical harmonic expansion of the Newton potential.
However, the substitution is not so happy as for the Chebyshev polynomials. Here below is what you get from the generating function of the Legendre's polynomials -not bad after all, but there may be something better.
$$P_n(\cos\theta)=4^{-n}\sum_{k=0}^n{2k \choose k}{2n-2k\choose n-k}\cos\big((2n-k)\theta\big).$$


text:
Q: How to check and download files from S3 bucket in a specific interval? I want to implement the following once a file is uploaded to aS3 Bucket

*

*Download the file to a windows server

*Run a 3rd party exe to process the file and generate an output file on a Windows Server

What is the best approach to implement this using .Net Core?
Solution 1:

*

*Create a Lambda function to Trigger an API

*API will download the file and process

Solution 2:

*

*Create an executable to download the file from s3 bucket

*Create a lambda function trigger an executable

Solution 3:

*

*Create a service to check and download files from s3 bucket

*The downloaded file will be processed by the service

Solution 4:

*

*Use AWS Lambda to push the file to SQS

*Create an application to monitor SQS.

Please let me know the best solution to implement this. Sorry for asking this non-technical question.

A: The correct architecture approach would be:

*

*Create a trigger on the Amazon S3 bucket that sends a message to an Amazon SQS queue when the object is created

*A Windows server is continually polling the Amazon SQS queue waiting for a message to appear

*When a message appears, use the information in the message to download the object from S3 and process the file

*Upload the result to Amazon S3 and optionally send an SQS message to signal completion (depending on what you wish to do after a file is processed)

This architecture is capable of scaling to large volumes and allows files to be processed in parallel and even across multiple servers. If a processing task fails and does not signal completion, then Amazon SQS will make the message visible again for processing.


text:
Q: Implementing vertical UIScrollView After 2 days behind the implementation of a UIScrollView, I give up to do it by myself, despite It should be simple but I am not able to make it.
I need a vertical scrollview with Autolayout (I have 2 backgrounds images that need to scale), I have Xcode 7.2, iOs deployment target 9.0 and I am using the storyboard
The scrollview is a "new account" form with a lot of content, So it can have a fixed height
I tried lots of options but no one of them work, at the momment I have a scrollview with a "content view" with all of the components.
Problems:
1.- How can I put more content in the scrollview? If I try to put more compoments(more than the height of ViewControler), it automatically moves my components to be inside the ViewController rectangle
2.- How I can make it scrollable? If I pin the content view to the top, bottom, left, right and make it with fixed height (like 1000) it doesn't scroll
Any help would be appreciated

A: Scrollview will scroll until the end of last UI object. But this is not the default behaviour of the scrollview. You should explicitly set the contentSize on your scrollview. Check below example.
-(void)addImage {
  int count = 20;
  UIScrollView * scView = [[UIScrollView alloc] init];
  scView.frame = CGRectMake(30, 60, self.view.frame.size.width, 60);
  UIButton * btn;
  UIImageView * imgV;
  float imgWidth = 44;
 for(int i=0;i<count;i++) {
   imgV = [[UIImageView alloc] init];
   imgV.frame = CGRectMake(i*imgWidth, 0, imgWidth, 44);
   imgV.image = [UIImage imageNamed:@"gitar"];
   [scView addSubview:imgV];
 }
[scView setContentSize:CGSizeMake(imgWidth*count, 50)];
[scView setBackgroundColor:[UIColor redColor]];
[self.view addSubview:scView];
}

What the above method does is, it will add 20 images in scrollview and at the end after adding all the images to scrollview in for loop I set contentSize to Scrollview. This step makes my scrollview to scroll until the content available. My example showing for Horizontal scroll, you have to change this behaviour to vertical scroll.


text:
Q: SQL Greater than specific time on the previous day A shift in our plant is defined as starting at 4am and continues until 2 am on the following day.
At 3 am on a given day I want to get all the records for the previous shift.
The query below gets me the previous day upto now but also includes 12am to 2 am on the "previous previous" shift. How do i get the query to get data ONLY after 4am ?
select
    *
    from yourTable
    WHERE TimeStamp >= dateadd(day,datediff(day,1,GETDATE()),0)

A: DECLARE @yesterday DATE = GETDATE()-1
DECLARE @time TIME = '04:00:00'
DECLARE @shiftstart DATETIME = CAST(@yesterday AS DATETIME) + CAST(@time AS DATETIME)

select
    *
    from yourTable
    WHERE TimeStamp >= @shiftstart

A: The logic is to subtract 2 hours from the shift time and use the date portion.  A simplistic implementation is:
where cast(dateadd(hour, -2, TimeStamp) as date) = cast(dateadd(day, -1, GetDate()) as date)

Sometimes, it is more efficient to do all the arithmetic on the "constant" (i.e. getdate()):
where TimeStamp >= dateadd(hour, 2, cast(GetDate() as Date))

Note:  the appropriate function for this logic is dateadd() not datediff().


text:
Q: Unable to run IIS Express after Updating Visual Studio 2019 - 16.0.1 I switched from the visual studio from 2015 to 2019, everything works fine but after their first update I got the mentioned error.

A: After googling, I found the solution here just follow the steps


text:
Q: How to set up indexed view when SELECTing TOP 1 with ORDER BY from different tables I am struggling to setup an indexed view in the following scenario so that the following query performs without two clustered index scans. Whenever I create an index view for this query and then use it, it seems to ignore any index I put on it:
    -- +++ THE QUERY THAT I WANT TO IMPROVE PERFORMANCE-WISE +++

    SELECT TOP 1 *
    FROM    dbo.TB_test1 t1
            INNER JOIN dbo.TB_test2 t2 ON t1.PK_ID1 = t2.FK_ID1
    ORDER BY t1.somethingelse1
           ,t2.somethingelse2;

    GO

The table setup is as follows:

*

*two tables

*they are joined by an inner join by the query above

*and ordered by a column from the first and then a column from the second table by the query above; only TOP 1 is selected

*(in the script below there are also some lines to generate test data, just in case it helps reproducing the problem)
-- +++ TABLE SETUP +++

CREATE TABLE [dbo].[TB_test1]
    (
     [PK_ID1] [INT] IDENTITY(1, 1)  NOT NULL
    ,[something1] VARCHAR(40) NOT NULL
    ,[somethingelse1] BIGINT NOT NULL
        CONSTRAINT [PK_TB_test1] PRIMARY KEY CLUSTERED ( [PK_ID1] ASC )
    );

GO

create TABLE [dbo].[TB_test2]
    (
     [PK_ID2] [INT] IDENTITY(1, 1)  NOT NULL
    ,[FK_ID1] [INT] NOT NULL
    ,[something2] VARCHAR(40) NOT NULL
    ,[somethingelse2] BIGINT NOT NULL
        CONSTRAINT [PK_TB_test2] PRIMARY KEY CLUSTERED ( [PK_ID2] ASC )
    );

GO

ALTER TABLE [dbo].[TB_test2]  WITH CHECK ADD  CONSTRAINT [FK_TB_Test1] FOREIGN KEY([FK_ID1])
REFERENCES [dbo].[TB_test1] ([PK_ID1])
GO

ALTER TABLE [dbo].[TB_test2] CHECK CONSTRAINT [FK_TB_Test1]

GO

-- +++ TABLE DATA GENERATION +++

-- this might not be the quickest way, but it's only to set up test data

INSERT INTO dbo.TB_test1
        ( something1, somethingelse1 )
VALUES  ( CONVERT(VARCHAR(40), NEWID())  -- something1 - varchar(40)
          ,ISNULL(ABS(CHECKSUM(NewId())) % 92233720368547758078, 1)   -- somethingelse1 - bigint
          )

GO 100000

RAISERROR( 'Finished setting up dbo.TB_test1', 0, 1) WITH NOWAIT

GO

INSERT INTO dbo.TB_test2
        ( FK_ID1, something2, somethingelse2 )
VALUES  ( ISNULL(ABS(CHECKSUM(NewId())) % ((SELECT MAX(PK_ID1) FROM dbo.TB_test1) - 1), 0) + 1 -- FK_ID1 - int
          ,CONVERT(VARCHAR(40), NEWID())  -- something2 - varchar(40)
          ,ISNULL(ABS(CHECKSUM(NewId())) % 92233720368547758078, 1)   -- somethingelse2 - bigint
          )

GO 100000

RAISERROR( 'Finished setting up dbo.TB_test2', 0, 1) WITH NOWAIT

GO

The indexed view should probably be defined as follows and the resulting TOP 1 query is below. But what indexes do I need so that this query performs better than without the indexed view?
    CREATE VIEW VI_test
    WITH SCHEMABINDING
    AS
        SELECT  t1.PK_ID1
               ,t1.something1
               ,t1.somethingelse1
               ,t2.PK_ID2
               ,t2.FK_ID1
               ,t2.something2
               ,t2.somethingelse2
        FROM    dbo.TB_test1 t1
                INNER JOIN dbo.TB_test2 t2 ON t1.PK_ID1 = t2.FK_ID1

    GO

    SELECT TOP 1 * FROM dbo.VI_test ORDER BY somethingelse1,somethingelse2

    GO

A:
It seems to ignore any index I put on it

Unless you're using SQL Server Enterprise Edition (or equivalently, Trial and Developer), you will need to use WITH (NOEXPAND) on the view reference in order to use it. In fact, even if you are using Enterprise, there are good reasons to use that hint.
Without the hint, the query optimizer (in Enterprise Edition) may make a cost-based choice between using the materialized view or accessing the base tables. Where the view is as large as the base tables, this calculation may favour the base tables.
Another point of interest is that without a NOEXPAND hint, view references are always expanded to the base query before optimization begins. As optimization progresses, the optimizer may or may not be able to match the expanded definition back to the materialized view, depending on previous optimization activity. This is almost certainly not the case with your simple query, but I mention it for completeness.
So, using the NOEXPAND table hint is your main option, but you might also think about just materializing the base table keys and the columns needed for ordering in the view. Create a unique clustered index on the combined key columns, then a separate nonclustered index on the ordering columns.
This will reduce the size of the materialized view, and limit the number of automatic updates that must be made to keep the view synchronized with the base tables. Your query can then be written to fetch the top 1 keys in the required order from the view (ideally with NOEXPAND), then join back to the base tables to fetch any remaining columns using the keys from the view.
Another variation is to cluster the view on the ordering columns and table keys, then write the query to manually fetch the non-view columns from the base table using the keys. The best option for you depends on the broader context. A good way to decide is to test it with the real data and workload.
Basic solution
CREATE VIEW VI_test
WITH SCHEMABINDING
AS
    SELECT
        t1.PK_ID1,
        t1.something1,
        t1.somethingelse1,
        t2.PK_ID2,
        t2.FK_ID1,
        t2.something2,
        t2.somethingelse2
    FROM dbo.TB_test1 t1
    INNER JOIN dbo.TB_test2 t2
        ON t1.PK_ID1 = t2.FK_ID1;
GO
-- Brute force unique clustered index
CREATE UNIQUE CLUSTERED INDEX cuq
ON dbo.VI_test
    (somethingelse1, somethingelse2, PK_ID1, PK_ID2);
GO
SELECT TOP (1) *
FROM dbo.VI_test WITH (NOEXPAND)
ORDER BY somethingelse1,somethingelse2;

Execution plan:

Using a nonclustered index
-- Minimal unique clustered index
CREATE UNIQUE CLUSTERED INDEX cuq
ON dbo.VI_test
    (PK_ID1, PK_ID2)
WITH (DROP_EXISTING = ON);
GO
-- Nonclustered index for ordering
CREATE NONCLUSTERED INDEX ix
ON dbo.VI_test (somethingelse1, somethingelse2);

Execution plan:

There is a lookup in this plan, but it is only used to fetch a single row.
Minimal Indexed View
ALTER VIEW VI_test
WITH SCHEMABINDING
AS
    SELECT
        t1.PK_ID1,
        t2.PK_ID2,
        t1.somethingelse1,
        t2.somethingelse2
    FROM dbo.TB_test1 t1
    INNER JOIN dbo.TB_test2 t2
        ON t1.PK_ID1 = t2.FK_ID1;
GO
-- Unique clustered index
CREATE UNIQUE CLUSTERED INDEX cuq
ON dbo.VI_test
    (somethingelse1, somethingelse2, PK_ID1, PK_ID2);

Query:
SELECT TOP (1)
    V.PK_ID1,
    TT1.something1,
    V.somethingelse1,
    V.PK_ID2,
    TT2.FK_ID1,
    TT2.something2,
    V.somethingelse2
FROM dbo.VI_test AS V WITH (NOEXPAND)
JOIN dbo.TB_test1 AS TT1 ON TT1.PK_ID1 = V.PK_ID1
JOIN dbo.TB_test2 AS TT2 ON TT2.PK_ID2 = V.PK_ID2
ORDER BY somethingelse1,somethingelse2;

Execution plan:

This shows the table keys being retrieved (a single row fetch from the view clustered index in order) followed by two single-row lookups on the base tables to fetch the remaining columns.


text:
Q: $\sum (B_{t_{i}^{n}}+B_{t_{i-1}^{n}})^{2} \left( \left(B_{t_{i}^{n}}-B_{t_{i-1}^{n}}\right)^2-[t^n_{i}-t^n_{i-1}]\right)$ converges in probability Let $T > 0$, $B$ be a Brownian motion and consider a sequence of partitions $\{0=t_{0}^{n}<...<t_{l(n)}^{n}=T\}, \; n \in \mathbb N$ such that the mesh tends to $0$ as $n \to \infty$.
How can I show that $\sum\limits_{i = 1}^{l(n)}(B_{t_{i}^{n}}+B_{t_{i-1}^{n}})^{2} \left(\left(B_{t_{i}^{n}}-B_{t_{i-1}^{n}}\right)^2-(t^n_{i}-t^n_{i-1})\right)$ converges in probability as $n \to \infty$?
Of course I know that $E[\left(B_{t_{i}^{n}}-B_{t_{i-1}^{n}}\right)^2-(t^n_{i}-t^n_{i-1})]=0$ and $B_{t}^2-t$ is a martingale but there is no independence or other notions that will help me prove $L^{2}$ convergence and by extension convergence in probability.
Any tips/hints appreciated.

A: Write $\Delta B_i = B_{t^n_i} - B_{t^n_{i-1}} $ and $\Delta t_i = t^n_i - t^n_{i-1}$. Then we may decompose the sum into three parts:
\begin{align*}
\sum_{i=1}^{l(n)} (2B_{t^n_{i-1}} + \Delta B_i)^2 \bigl( (\Delta B_i)^2 - \Delta t_i \bigr)
= S_{1,n} + S_{2,n} + S_{3,n},
\end{align*}
where
\begin{align*}
S_{1,n} &= 4 \sum_{i=1}^{l(n)} B_{t^n_{i-1}}^2 \bigl( (\Delta B_i)^2 - \Delta t_i \bigr) \\
S_{2,n} &= \sum_{i=1}^{l(n)} 4B_{t^n_{i-1}}(\Delta B_i) \bigl( (\Delta B_i)^2 - \Delta t_i \bigr) \\
S_{3,n} &= \sum_{i=1}^{l(n)} (\Delta B_i)^2 \bigl( (\Delta B_i)^2 - \Delta t_i \bigr).
\end{align*}
1. For the first sum, note that for $i < j$,
\begin{align*}
&\mathbb{E}\bigl[ B_{t^n_{i-1}}^2 \bigl( (\Delta B_i)^2 - \Delta t_i \bigr) B_{t^n_{j-1}}^2 \bigl( (\Delta B_j)^2 - \Delta t_j \bigr) \bigr] \\
&= \mathbb{E}\bigl[ B_{t^n_{i-1}}^2 \bigl( (\Delta B_i)^2 - \Delta t_i \bigr) B_{t^n_{j-1}}^2 \mathbb{E}\bigl[ (\Delta B_j)^2 - \Delta t_j \bigm| \mathcal{F}_{t^n_{j-1}} \bigr] \bigr] \\
&= 0.
\end{align*}
Also, by the independence,
\begin{align*}
&\mathbb{E}\bigl[ \bigl( B_{t^n_{i-1}}^2 \bigl( (\Delta B_i)^2 - \Delta t_i \bigr) \bigr)^2 \bigr]
= \mathbb{E}[ B_{t^n_{i-1}}^4 ] \mathbb{E}\bigl[ \bigl( (\Delta B_i)^2 - \Delta t_i \bigr)^2 \bigr]
= C (t^n_{i-1})^2 \Delta t_i^2
\end{align*}
for some absolute constant $C>0$. (We may choose $C = \mathbb{E}[B_1^4]\mathbb{E}[(B_1^2-1)^2]$, although its value is not important here.) Combining altogether, it follows that
$$ \mathbb{E}\bigl[ S_{1,n}^2 \bigr]
= C \sum_{i=1}^{l(n)} (t^n_{i-1})^2 \Delta t_i^2
\leq CT^3 \Bigl( \max_{1\leq i \leq l(n)} \Delta t_i \Bigr). $$
This tells that $S_{n,1} \to 0$ in $L^2$.
2. For the second sum, note that
$$ \mathbb{E} \bigl[ \bigl\lvert B_{t^n_{i-1}}(\Delta B_i) \bigl( (\Delta B_i)^2 - \Delta t_i \bigr) \bigr\rvert \bigr] \leq C_2 (t^n_{i-1})^{1/2} (\Delta t_i)^{3/2} $$
for another absolute constant $C_2 = \mathbb{E}[\lvert B_1\rvert]\mathbb{E}[\lvert B_1(B_1^2 - 1)\rvert] > 0$, and so,
$$ \mathbb{E} \bigl[ \bigl\lvert S_{2,n} \bigr\rvert \bigr] \leq C_2 T^{3/2} \Bigl( \max_{1\leq i \leq l(n)} \Delta t_i \Bigr). $$
This shows that $S_{2,n} \to 0$ in $L^1$.
3. A similar reasoning shows that $S_{3,n} \to 0$ in $L^1$ as well.
Therefore the original sum converges to $0$ in probability.


text:
Q: BrowserMob + selenium + java. How to create new response filter during on test scenario? I need to create one more response filter during one test scenario. But now when I do this both filters work at the same time. How could I stop or override the previous one without stopping current browser instance?
Code example:
proxy.addResponseFilter((response, contents, messageInfo) -> {
        if (messageInfo.getOriginalUrl().contains(keyWord)) {
            contents.setTextContents(newResponse);
        }
    });

A: It's not currently possible to remove a javascript filter after you've added it, unfortunately. The new REST API that is currently in development will support this, though. There's an issue open to track this: https://github.com/lightbody/browsermob-proxy/issues/326


text: Q: Algorithm used for variance of WeightedData There are multiple definitions of the sample variance of weighted data in the literature.  Which one does Mathematica use? An equation in terms of the   arguments provided to WeightedData[] would be best.


text:
Q: Grid of magick images in R Goal here is to have images set up in a grid-like fashion using magick read and annotated images. I can get the images read, annotated, and in the groups of 3 (i.e. 3 columns). I just can't figure out how to stack the groups together.
This is the desired result, but isn't flexible (?) and image_ggplot() is painfully slow:
grid.arrange(image_ggplot(annotated_images[[1]]),image_ggplot(annotated_images[[2]]),
             image_ggplot(annotated_images[[3]]),image_ggplot(annotated_images[[4]]),
             image_ggplot(annotated_images[[5]]),image_ggplot(annotated_images[[6]]),
             image_ggplot(annotated_images[[7]]),image_ggplot(annotated_images[[8]]),
             image_ggplot(annotated_images[[9]]),image_ggplot(annotated_images[[10]]),
             image_ggplot(annotated_images[[11]]),ncol=3)

Here's my attempt to build it up from ground:
newlogo <- image_read("https://jeroen.github.io/images/Rlogo.png")
images=rep(newlogo,11)
chunk_images=split(images, ceiling(seq_along(images)/3))
annotated_images=lapply(images,function(x){
  image_annotate(image_read("https://jeroen.github.io/images/Rlogo.png"), paste0('Random Number: ',rnorm(1)), color = 'white',boxcolor='grey10', size = 23)
})
list_of_rows=lapply(chunk_images,function(x){image_append(c(image_annotate(x, paste0('Random Number: ',rnorm(1)), color = 'white',boxcolor='grey10', size = 23)))})
#list_of_rows[1] == 3 images side-by-side
#list_of_rows[2] == 3 images side-by-side
#list_of_rows[3] == 3 images side-by-side
#list_of_rows[4] == the remaining 2 images

I want to stack the list_of_rows on top of each other, neither of these are working:
lapply(list_of_rows,function(x){image_append(x,stack=T)})
do.call(c,list_of_rows)

Just looking for a flexible way to arrange anywhere from 4-32 images in the number of columns I can control (won't know the total number of images each time).

A: As suggested in the comments by @fmw42, you can control the column arrangement using the function image_montage and the tile parameter
newlogo <- "https://jeroen.github.io/images/Rlogo.png"
images=rep(newlogo,11)
img <- magick::image_read(images) %>%
  magick::image_montage(tile = '3')


text:
Q: Using list item or variable as source of Data Binding I have a question about data binding in WP7 using c# code.
If I have custom class, everything is clear. I'm set Source property to my class instance and Path property to a property inside that class. Like this (and it works)
Binding binding = new Binding()
{
  Source = myclass,
  Path = new PropertyPath("myproperty"),
  Mode = BindingMode.TwoWay
};
myButton.SetBinding(dp, binding);

Now, how can I bind simple structures such as Boolean variable or single item from List<>?
If I'll write Source = myBoolean or Source = List[5] what should I write into Path property? (Note that I need TwoWay binding, thus setting a Path property is mandatory)
Final solution:
To bind a variable, this variable should be a public property and INotifyPropertyChanged should be implemented. List can be replaced for ObservableCollection for this purpose.
All the rest should looks like in nmaait's answer and entire code should be like this:
public partial class Main : PhoneApplicationPage, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private Boolean _myBoolean { get; set; }
    public Boolean myBoolean
    {
        get { return _myBoolean; }
        set { _myBoolean = value; OnPropertyChanged("myBoolean"); }
    }
    ObservableCollection<Int32> myList { get; set; }

    public Main()
    {
        InitializeComponent();

        this.Loaded += new RoutedEventHandler(Main_Loaded);
    }

    protected void OnPropertyChanged(String name)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(name));
    }

    void Main_Loaded(object sender, RoutedEventArgs e)
    {
        myBoolean = false;
        myList = new ObservableCollection<int>() { 100, 150, 200, 250 };

        Binding binding1 = new Binding()
        {
            Source = this,
            Path = new PropertyPath("myBoolean"),
            Mode = BindingMode.TwoWay
        };
        myButton.SetBinding(Button.IsEnabledProperty, binding1);

        Binding binding2 = new Binding()
        {
            Source = myList,
            Path = new PropertyPath("[1]"),
            Mode = BindingMode.TwoWay
        };

        myButton.SetBinding(Button.WidthProperty, binding2);
    }

    private void changeButton_Click(object sender, RoutedEventArgs e)
    {
        myList[1] +=50;
        myBoolean = !myBoolean;
    }
}

A: Your source is the data context, so you wouldn't really be setting the source as the boolean itself but setting the Source as the Class/Element that the boolean belongs to like you have already done. The Path is going to be myBoolean or List[5].
If the boolean is in the current class you can do
Binding binding = new Binding()
{
  Source = this,
  Path = new PropertyPath("myBoolean"),
  Mode = BindingMode.TwoWay
};
myButton.SetBinding(dp, binding);

What exactly are you trying to achieve by binding to a list item. If your list changes then you wouldn't want to bind to a specific index, you can bind to the selected item like this though. Give some more info on what you need to achieve by binding to a specific list item.
Binding binding = new Binding()
{
  Source = List,
  Path = new PropertyPath("SelectedItem"),
  Mode = BindingMode.TwoWay
};
myButton.SetBinding(dp, binding);


text:
Q: Glassfish doesn't bring up EntityManager if DAO is not Stateless I have an EAR application with an EJB module, that contains one persistence unit and many EJBs (as service and DAO layer).
@Stateless
public class BranchDAO {
    @PersistenceContext
    private EntityManager entityManager;
}

But DAOs as Stateless beans are not recommended. So I create this annotation using CDI:
@Dependent
@Stereotype
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface DAO {
}

After my DAO is changed to not use @Stateless:
@DAO
public class BranchDAO {
    @PersistenceContext
    private EntityManager entityManager;
}

But the Glassfish doesn't bring up the entity manager when the application starts. And when I call the DAO, the entity manager is in an illegal state.

java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName null

This error only occurs in Glassfish 3, but not in JBoss AS 6. Using JBoss AS 6 I can see the Hibernate logs in startup (but I don't see them with Glassfish).
As a temporary solution I created an Stateless bean with the content below. It's not beautiful solution, but works fine in Glassfish.
@Stateless
@Startup
public class AutoStartEntityManager {

    @PersistenceContext
    private EntityManager entityManager;

}

So, how I can force Glassfish to bring up EntityManager when I'm not using @Stateless in my DAO?

A: Try specifying explicitly the unitName:
@PersistenceContext(unitName="yourJPAUnitName")
private EntityManager manager;

(A sidenote - are you sure you need the DAO in dependent scope? Shouldn't it be singleton?)


text:
Q: Getting error "property 'style' of undefined" when delete a full column of datatable dynamically using javascript This is my html code for table.

             User Name
             Status
             Date
             time
             TaskName
             Location

This my javascript Code:
function dataTableManipulate(mainArray){
        table =  $("#log-details").DataTable({
            data: mainArray,
            "searching": true,
            "info": false,
            "lengthChange":false,
           "columnDefs": [{
               "targets": [5],
                render : function (data, type, row) {
                       return '<button class="btn btn-primary btn-xs " id = "btnShow">Show Map</button>';
                }
           }]
        });
        $('#tbl_details_length').after($('.datepic-top'));
    }

$("#activitylog").click(function(){
    tableData = generalMainArray
    $('#log-details').dataTable().fnDestroy();
    $('table tr').find('td:eq(4),th:eq(4)').remove();
    dataTableManipulate(tableData);
});

Note: activitylog is a button.
I want to remove TaskName column from Datatable on  activitylog button click.Any one help me for delete that column from datatable


text:
Q: Heroku discord bot keeps restarting So I just recently made a discord.js bot and am currently hosting it on Heroku. However I've noticed that roughly every hour my heroku application will just randomly restart, in turn causing my bot to shut off briefly and turn back on. No reason whatsoever, no errors at all. Anyone know why this is and if there's a way to stop it?
Here's a log of what it says when it restarts:
2020-12-19T08:42:47.712115+00:00 heroku[worker.1]: Cycling
2020-12-19T08:42:47.714177+00:00 heroku[worker.1]: State changed from up to starting
2020-12-19T08:42:49.171040+00:00 heroku[worker.1]: Stopping all processes with SIGTERM
2020-12-19T08:42:49.364823+00:00 heroku[worker.1]: Process exited with status 143
2020-12-19T08:42:50.597052+00:00 heroku[worker.1]: Starting process with command `node index.js`
2020-12-19T08:42:51.347038+00:00 heroku[worker.1]: State changed from starting to up
2020-12-19T08:42:53.932302+00:00 app[worker.1]: Bot started!
2020-12-20T09:18:11.938012+00:00 heroku[worker.1]: Cycling
2020-12-20T09:18:11.945355+00:00 heroku[worker.1]: State changed from up to starting
2020-12-20T09:18:14.978039+00:00 heroku[worker.1]: Starting process with command `node index.js`
2020-12-20T09:18:15.635278+00:00 heroku[worker.1]: State changed from starting to up
2020-12-20T09:18:16.613701+00:00 heroku[worker.1]: Stopping all processes with SIGTERM
2020-12-20T09:18:16.745918+00:00 heroku[worker.1]: Process exited with status 143
2020-12-20T09:18:18.344454+00:00 app[worker.1]: Bot started!

A: Heroku Dynos restart (cycle) every 24 hours, check the logs and you see it happens on different days.
There is nothing you can do, all Dyno types have this behaviour. One workaround is to restart the Dyno yourself (at least once a day) so you can control when this happens.