text:
Q: Connect to wifi AP programmatically with Huawei We are working in an application where we connect to several wifi AP.
The only device where we located the problem is a Huawei device, concretely Huawei P20 PRO (Android 9.1).
We are able to connect to wifi AP not protected with password, but if it is protected, we are not able to establish the connection with the Wifi AP.
Here is a extract of the code we are using:
private void connect(WifiConfiguration wifiAP) {

        WifiManager wifi = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        SharedPreferences prefs =
                context.getSharedPreferences(prefs_pass_dic, Context.MODE_PRIVATE);
        String pass = prefs.getString(wifiAP.SSID.replace("\"",""), "");
        WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        wifiManager.disconnect();

        wifiAP = createAPConfiguration(wifiAP.SSID.replace("\"", ""), pass.trim(), getSecurityType(wifiAP));

        int res = wifi.addNetwork(wifiAP);
        if (res == -1) {
            for (WifiConfiguration cc : wifiManager.getConfiguredNetworks()) {
                if (cc.SSID.equals(wifiAP.SSID))
                    res = cc.networkId;
            }
        }

        boolean b = wifi.enableNetwork(res, true);
        Log.d(TAG, "# enableNetwork returned " + b);
        wifi.reconnect();

        wifi.saveConfiguration();
}

private WifiConfiguration createAPConfiguration(String networkSSID, String networkPasskey, String securityMode) {
        WifiConfiguration wifiConfiguration = new WifiConfiguration();

        wifiConfiguration.SSID = "\"" + networkSSID + "\"";
        wifiConfiguration.priority = getMaxPriority(context) + 1;
        if (securityMode.equalsIgnoreCase("OPEN")) {

            wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);

        } else if (securityMode.equalsIgnoreCase("WEP")) {

            wifiConfiguration.wepKeys[0] = "\"" + networkPasskey + "\"";
            wifiConfiguration.wepTxKeyIndex = 0;
            wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);

        } else if (securityMode.equalsIgnoreCase("PSK")) {

            wifiConfiguration.preSharedKey = "\"" + networkPasskey + "\"";
            wifiConfiguration.hiddenSSID = true;
            wifiConfiguration.status = WifiConfiguration.Status.ENABLED;
            wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
            wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.WPA);

        } else {
            Log.i("wifi", "# Unsupported security mode: " + securityMode);

            return null;
        }

        return wifiConfiguration;
    }

Anyone suffered a similar problems?


text:
Q: C function accessing private ivar of Objective-C class According to this comment:

C functions inside @implementation blocks have the unique property of
  being able to access private and protected ivars directly. Thus, from
  my own experience, it's become a strong idiom to place C functions
  that "belong" to a class inside the corresponding implementation.

My code, defining a private instance variable in the implementation only as suggested by this answer:
With the brackets:
@implementation ViewController{
MyTest *tt;
}

void testf(){
    NSLog(@"hello back from c++ into obj c land");
    [tt testcf: 5];
}

...

Will not build; the compiler indicates that tt in testf is undeclared. If I remove the brackets, then the C function works fine.
But... if I remove the brackets, do I understand that actually this is no longer an instance variable, but sneakily it is a global variable, disconnected from the class, despites its placement in the @implementation? It would appear that this is indeed true, since I can do this as the end:
@end

void testf2(){
    NSLog(@"hello back from c++ into obj c land");
    [tt testcf: 5];
}

And the compiler does not contain about tt being out of scope. So -- how to declare a private instance variable in an implementation and have it truly be an instance variable, but also have a C function be able to access it? For the purposes of this question, I am trying to get this to work based on the linked comments/answers without using the id pointer of the object itself.

A: You will need to pass a reference to self to the C-function:
void testf(ViewController *vc){
    NSLog(@"hello back from c++ into obj c land");
    [vc->tt testcf: 5];
}

and call it like this:
- (void)someMethodInViewController
{
    testf(self);
}

However it's not clear why you are using C-functions at all.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ELK Stack - Remote servers' logs parsed and classed correctly, but dumped to stout not elasticsearch As the (lengthy) topic suggests, my remote servers sends logs to the logstash server.
Here the logstash configs:
Input:
[root@tool01 conf.d]# cat 01-lumberjack-input.conf
input {
  lumberjack {
    port => 5000
    type => "logs"
    ssl_certificate => "/etc/pki/tls/certs/logstash-forwarder.crt"
    ssl_key => "/etc/pki/tls/private/logstash-forwarder.key"
  }
}

Type:
[root@tool01 conf.d]# cat 10-syslog.conf
    filter {
      if [type] == "syslog" {
        grok {
          match => { "message" => "%{SYSLOGTIMESTAMP:syslog_timestamp} %{SYSLOGHOST:syslog_hostname}     %{DATA:syslog_program}(?:\[%{POSINT:syslog_pid}\])?: %{GREEDYDATA:syslog_message}" }
          add_field => [ "received_at", "%{@timestamp}" ]
          add_field => [ "received_from", "%{host}" ]
        }
        syslog_pri { }
        date {
          match => [ "syslog_timestamp", "MMM  d HH:mm:ss", "MMM dd HH:mm:ss" ]
        }
      }
    }

Output:
[root@tool01 conf.d]# cat 30-lumberjack-output.conf
output {
  elasticsearch { host => localhost }
  stdout { codec => rubydebug }
}

The local logs are working fine as metioned, but all the logs from remote is sent to stdout:
[root@tool01 logstash]# tail -n 19 logstash.stdout
{
             "message" => "Nov 29 20:16:44 foreman dhcpd: DHCPACK on 192.168.50.100 to 3c:4a:92:12:1c:cb via eth0",
            "@version" => "1",
          "@timestamp" => "2014-11-29T20:16:44.000Z",
                "type" => "syslog",
                "file" => "/var/log/messages",
                "host" => "foreman.ics.dmz",
              "offset" => "3511785",
    "syslog_timestamp" => "Nov 29 20:16:44",
     "syslog_hostname" => "foreman",
      "syslog_program" => "dhcpd",
      "syslog_message" => "DHCPACK on 192.168.50.100 to 3c:4a:92:12:1c:cb via eth0",
         "received_at" => "2014-11-29 07:16:46 UTC",
       "received_from" => "foreman.ics.dmz",
"syslog_severity_code" => 5,
"syslog_facility_code" => 1,
     "syslog_facility" => "user-level",
     "syslog_severity" => "notice"
}

This may be a stupid question, but I only have the shipper installed on the client server, do I need to have logstash running there as well?
Thanks in advance!

A: Things are more confusing than I first anticipated.
For example, this log:
Dec  2 10:39:12 foreman dhcpd: DHCPACK on 192.168.50.52 to 6c:ad:f8:26:b1:68 (Chromecast) via eth0

The list view under the graph lists the time correctly, but the bargraph has the entry at 23:39:12?
A lag of 13 hours sounds unbelievable, but 13h to the second sounds more like a timezone issue?
Yet all are running with the same date as verified by date

A: Some more information:
[root@tool01 tmp]# curl -s XGET http://192.168.50.241:9200/logstash-2014.12.03/_search?pretty=true | tail -n 15; TZ=UTC date
{
  "_index": "logstash-2014.12.03",
  "_type": "syslog",
  "_id": "bOVXPpf9SFOKKPgx7PWfCA",
  "_score": 1.0,
  "_source": {
    "message": "Dec  3 00:06:30 foreman dhcpd: DHCPREQUEST for 192.168.50.251 from 00:15:5d:32:14:09 via eth0",
    "@version": "1",
    "@timestamp": "2014-12-03T00:06:30.000Z",
    "type": "syslog",
    "file": "/var/log/messages",
    "host": "foreman.ics.dmz",
    "offset": "3756888",
    "syslog_timestamp": "Dec  3 00:06:30",
    "syslog_hostname": "foreman",
    "syslog_program": "dhcpd",
    "syslog_message": "DHCPREQUEST for 192.168.50.251 from 00:15:5d:32:14:09 via eth0",
    "received_at": "2014-12-02 11:06:31 UTC",
    "received_from": "foreman.ics.dmz",
    "syslog_severity_code": 5,
    "syslog_facility_code": 1,
    "syslog_facility": "user-level",
    "syslog_severity": "notice"
  }
},
{
  "_index": "logstash-2014.12.03",
  "_type": "syslog",
  "_id": "5axCp7UgRxmunclFqlgKNw",
  "_score": 1.0,
  "_source": {
    "message": "Dec  3 00:06:30 foreman dhcpd: DHCPACK on 192.168.50.251 to 00:15:5d:32:14:09 via eth0",
    "@version": "1",
    "@timestamp": "2014-12-03T00:06:30.000Z",
    "type": "syslog",
    "file": "/var/log/messages",
    "host": "foreman.ics.dmz",
    "offset": "3756982",
    "syslog_timestamp": "Dec  3 00:06:30",
    "syslog_hostname": "foreman",
    "syslog_program": "dhcpd",
    "syslog_message": "DHCPACK on 192.168.50.251 to 00:15:5d:32:14:09 via eth0",
    "received_at": "2014-12-02 11:06:31 UTC",
    "received_from": "foreman.ics.dmz",
    "syslog_severity_code": 5,
    "syslog_facility_code": 1,
    "syslog_facility": "user-level",
    "syslog_severity": "notice"
  }
},
{
  "_index": "logstash-2014.12.03",
  "_type": "syslog",
  "_id": "m_MuAZPcS8ixmCn5getvyg",
  "_score": 1.0,
  "_source": {
    "message": "Dec  3 00:06:30 spacewalk dhclient[906]: DHCPREQUEST on eth0 to 192.168.50.240 port 67 (xid=0x421c37e1)",
    "@version": "1",
    "@timestamp": "2014-12-03T00:06:30.000Z",
    "type": "syslog",
    "file": "/var/log/messages",
    "host": "spacewalk.ics.dmz",
    "offset": "269907",
    "syslog_timestamp": "Dec  3 00:06:30",
    "syslog_hostname": "spacewalk",
    "syslog_program": "dhclient",
    "syslog_pid": "906",
    "syslog_message": "DHCPREQUEST on eth0 to 192.168.50.240 port 67 (xid=0x421c37e1)",
    "received_at": "2014-12-02 11:06:33 UTC",
    "received_from": "spacewalk.ics.dmz",
    "syslog_severity_code": 5,
    "syslog_facility_code": 1,
    "syslog_facility": "user-level",
    "syslog_severity": "notice"
  }
}
Tue Dec  2 19:19:14 UTC 2014

So it seems the data is buffered before being written to EL?


text:
Q: Passing arbitrary binary data from C# application to another application using command line arguments For academic purposes I want to try to exploit an strcpy function with a buffer overflow attack using C#, by passing some arbitrarily long string, that contains a specific binary data (raw bytes).
I am trying something similar to this C# code, but that obviously doesn't work:
static void Main(string[] args)
{
    string cPath = @"C:\Debug";
    var strCmdText =
        "0xCA" + "0xCA" + + "0xCA" + "0xCA" + "0xCA" + ...;
    string filename = Path.Combine(cPath, "Buffer.exe");
    var proc = System.Diagnostics.Process.Start(filename, strCmdText);
}

A: We assume that the target application uses single-byte characters as its argv. So...
 1. Test application
Our test application is called Buffer.exe and its source code is:
void print_str(char* str)
{
    size_t length = strlen(str);
    printf("Line: '%s'\n", str);
    printf("Len : '%d'\n", length);
    printf("Hex :", length);

    for (size_t i = 0; i < length; i++)
    {
        printf("\t0x%02x", str[i]);
    }

    printf("\n");
}

int main(int argc, char* argv[])
{
    for (int i = 1; i < argc; i++)
    {
        char* str = argv[i];
        printf("Argument #%d:\n", i);
        print_str(str);
    }

    printf("Press enter to exit\n");
    getchar();
}

It just prints the passed arguments both as strings and as hex values, so for arguments "a1" "b2" it will print

Argument #1:
Line: 'a1'
Len : '2'
Hex :   0x61    0x31
Argument #2:
Line: 'b2'
Len : '2'
Hex :   0x62    0x32
Press enter to exit

 2. Main "ingredients"
What we need are:

*

*A way to turn bytes to analogous "single byte characters" (actually they will still be 2-byte UTF-16 chars on the C# side, but [OS should pass them to our receiver]/[Buffer.exe should interpret] as single byte characters with the same binary value we started on the C# side)  - for that we need Encoding.Default (as corrected by @Tom Blodget) property and its Encoding.GetString method.

*A way to ensure that our argument line is correctly escaped (so that 0x20-Space won't split our big argument into multiple and other particularities won't affect the command line either) - for simplicity we will just escape an entire line with quotes, but for a proper solution(at least on Win32) see https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/.

 3. Implementation
Our argument creating application is the following:
public static String BytesToCommandLineArgument(Byte[] array)
{
    var ascii = Encoding.Default.GetString(array);
    // "Escape" it here. Disclaimer - it is actually a wrong way to escape a command line argument.
    // See https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/
    // for a way to do it correctly at least on Win32
    return String.Format("\"{0}\"", ascii);
}

public static  void Main()
{
    try
    {
        var bytes = new Byte[] { 0x10, 0x31, 0x13, 0x61, 0x20 };

        using (var process = Process.Start(
            fileName: "Buffer.exe",
            arguments: BytesToCommandLineArgument(bytes)))
        {
            process.WaitForExit();
        }
    }
    catch (Exception exc)
    {
        Console.WriteLine(exc);
    }
    Console.WriteLine("Press any key...");
    Console.ReadKey(true);
}

 4. Testing
As you can see our test byte array contains spaces and newlines, so we can at least be sure that our solution won't strip them (though as I've said something like quote on the end will break it).

Argument #1:
Line: '►1‼a '
Len : '5'
Hex :   0x10    0x31    0x13    0x61    0x20
Press enter to exit

P.S.1: Don't forget that this solution escapes command line incorrectly - https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/! It may not cause any issues on most of the data in the possible dataspace, but it will certainly do on some data.
P.S.2: How do you convert Byte Array to Hexadecimal String, and vice versa? may be of use for you if you have a need to input the data dynamically.


text:
Q: What is a g-frame? I am reading A quick trip through knot theory (link to pdf!) by R.H. Fox, in particular the section of branched covering (section 8 pag. 26 into the document). When he describes his algorithm to find the fundamental group of a branched covering, he says he considers a g-frame. What is a g-frame?
I report here the relevant part of the section:

EDIT Reading carefully the section, I have understood that the g is the number of branches of the covering. So my question no is: what is a frame?

A: What I gathered by trying to follow the proof (and also by studying the second figure on the page), is that a $g$-frame is $g$ intervals with their first endpoints all identified.  Or in other words, a cone on $g$ points.  The first figure on the page is meant to illustrate this topological space:

Fox's idea was to glue this into $\Sigma-\Lambda$, which only changes the fundamental group by a free product by a free group, to avoid needing to choose representative paths to the points $p_0,\dots,p_{g-1}$ lying over the basepoint in the covering space $\Sigma-\Lambda$.
In other words, if $\pi:\Sigma-\Lambda\to S-L$ is the covering map and $*\in S-L$ is the chosen basepoint, then what Fox does is construct a new space $(\Sigma-\Lambda)\cup C\pi^{-1}(*)$, where $C\pi^{-1}(*)$ denotes the cone of the set $\pi^{-1}(*)$, and the union is meant to identify $\pi^{-1}(*)\subset \Sigma-\Lambda$ with $\pi^{-1}(*)\subset C\pi^{-1}(*)$.  He "coned off" a fiber.
For completeness, here is the second figure on the page, showing the covering along with the attached "$g$-frame":


text:
Q: Connecting two agents of an agent based model in anylogic I am trying to connect two agents in AnyLogic for my agent based model. Can someone please tell me how to do that ?
I tried some of the literature available at (https://anylogic.help/anylogic/interaction/index.html). But it didnot help.

A: Connections types, either single or collection of links depend on the links settings inside your agent and this in turn isset by the space and environment settings where you agents live.

You can connect two agents using connectTo(Agent a) and disconnect using disconnect() (which will disconnect from all connected agents) and get the connected agent using getConnectedAgent()
If you connected multiple agents to each other you can use  LinkedList<Agent> getConnections() to get all the agents it is connected to.
Read more here
Check out this model on the cloud and the details of the example here


text:
Q: batch обработка файлов с пробелами в имени нужно пройтись по файлам у которых есть пробелы в именах
for %%i in (*.mp3) do
   ffmpeg -i %%i -codec:a libmp3lame -b:a 128k %%~ni_128.mp3
)

скрипт не может найти файл изза пробела. что делать чтобы имя читалось полностью?

A: Используйте кавычки
ffmpeg -i "%%i" -codec:a libmp3lame -b:a 128k "%%~ni"_128.mp3


text:
Q: iOS: play audio file at a specific time and stop after a specific duration I have an audio file with length of 500 miniseconds for my app. I want app users to play the audio at minisecond 100 (by pressing a button) and the audio will automatically stops at minisecond 150. This is a code that I have done so far:
    AVAudioPlayer *audioPlayer = [[[AVAudioPlayer alloc]
                   initWithContentsOfURL:[NSURL fileURLWithPath:filePath]
                   error:nil] autorelease];
    [audioPlayer setCurrentTime:100.00f];
    [audioPlayer play];

Would you please help me with the stopping part? Thank you

A: You could create an instance of NSTimer with the desired play interval, then when the timer fires, stop audio.  Create the timer on the main thread, and in a place in your code in an applicable area where you can get a reference for the audioPlayer.  Make sure you handle interruptions, IE, User pauses or stops audio somehow, or if the audioPlayer is deallocated somewhere, your app goes into the background, or whatever else you need to handle, by invalidating and disposing of the timer.  See the docs for information on NSTimer.  http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nstimer_Class/Reference/NSTimer.html


text:
Q: How do I enter combat in Mass Effect? I am playing Mass Effect as an Infiltrator with the Sole Survivor background.
It seems every time I try to enter combat I get killed, instantly. I managed to make it past the railway station (where you disarm the bombs) and to get to Fist, but in both cases it was bordering on frustrating rather than fun.
At the moment I have resorted to sending my squad in while I hide or snipe as they can respawn when killed.
How can I enter the fray myself without being killed almost instantly?

A: You are an infiltrator, you aren't supposed to be able to tank enemies.  I don't know exactly what skills you've allocated, but here are some things that may help you out:

*

*Put some points into electronics, each point gives you a boost to shield strength.

*You can try assigning more points into tactical armor until you can wear medium armor.

*Your weapons are pistols and sniper rifles.  Stay in hiding, and pop out to shoot a single shot against an enemy (try to go for a headshot), before going back into hiding.

*If you have enough points into electronics, you'll unlock damping which can stun enemies for a short duration.  Also, try starting out fights by using overload to quickly take out enemy shields.

*If your shields are down, stay under cover until it recharges, or you will die very fast.

*Try to use tankish followers, such as Ashley.

Now, against the Fist fight, he will never wander out of his room, so you can just use the side of the doors for cover and pop out, shoot 1 turret, and then retreat until your shields come back up.

A: LOL this is funny. Exactly in this moment I'm playing Mass Effect 1, Infiltrator, Survivor.
At the beginning, the game is a bit harder because you got low skills. Use pistols + marksman and assasination + sniper. As yx said, you should go for medium armor.
yx is spot on. What I can tell you however is this: don't worry, the game will become more fun as soon as you reach about level 10. The Infiltrator rocks. You become extremely powerful later, I believe this is a late-game character, but I may be wrong (maybe all characters get very strong late-game, but I think that in the case of the the Infiltrator, this is more pronounced).
Don't despair, keep at it. Mass Effect rocks ::- D.


text:
Q: Not really understanding the self keyword in the declaration of the global variable in the below code snippet for leetcode problem 297 This below is the part I am confused about:
class Codec:

    def deserialize(self, data):
        vals = data.split(",")
        self.i = 0

        def dfs():
            if vals[self.i] == "N":
                self.i += 1
                return None
            node = TreeNode(int(vals[self.i]))
            self.i += 1
            node.left = dfs()
            node.right = dfs()
            return node

        return dfs()

What I don't get is why it can't just be:
class Codec:

    def deserialize(self, data):
        vals = data.split(",")
        **i = 0**

        def dfs():
            if vals[**i**] == "N":
                **i += 1**
                return None
            node = TreeNode(int(vals[**i**]))
            **i += 1**
            node.left = dfs()
            node.right = dfs()
            return node

        return dfs()

The above returns local variable 'i' referenced before assignment, but I am not understanding why I need the self keyword if I have declared i to be a global variable already. Perhaps my understanding of the self keyword needs some updating (self is a representation of the instance of the Codec class, but i doesn't need to be attached to this instance in my opinion -- should be able to be a standalone global variable, no?). Or maybe it is the way I declared the global variable i, input appreciated!
See above, it describes my approach and what I tried.


text:
Q: what is one word meaning two people who are of the exact same age?
Possible Duplicate:
Word for two people who are the same age

I notice this discussion was closed back in February but I need to re-open it because I heard the answer on the radio today. It was on NPR, the show "Says You!" Unfortunately, I didn't hear the first part of the discussion, when they spelled it. The pronunciation though sounded like, "yeeling." It made me think of the word "yearling," but with a definite long e in the middle. I went to the "Says You" website to try to get the spelling but their site is woefully behind: the latest episode is June 2012.
I tried entering "yeeling" in Google Chrome's search engine but got no good hits.
Did anyone else hear Says You today and know how to spell this word?


text:
Q: Android Studio throws 'error: failed linking file resources' I was making an icon pack for my own phone. I was done with all the required icons. After a few days, I installed more apps and had to create icons for those too. I created, and imported all the icons in the drawable folder but suddenly, Android Studio starting throwing the error: error: failed linking file resources.
This is the actual error:
Android resource linking failed
C:\Users\Hrishikesh\Documents\Android\Projects\Icons\app\src\main\res\layout\icon_picker.xml:15: error: resource drawable/grid_selector (aka com.kh.icons:drawable/grid_selector) not found.
C:\Users\Hrishikesh\Documents\Android\Projects\Icons\app\src\main\res\mipmap-anydpi-v26\ic_launcher.xml:5: error: resource drawable/unicon (aka com.kh.icons:drawable/unicon) not found.
error: failed linking file resources.

But, I have both the files in the drawable folder. The grid_selector as well as unicon. Android Studio even shows them, is able to open them, etc. Also, the files in which these files are linked (like, the icon_picker.xml) aren't giving any errors. This error only comes up when I run the app to test on my phone.
What do I do?


text:
Q: Creating a JSON Tree from a string hierarchy Given these 4 variables,
var el1 = {name:'ronaldo', team: 'europe/spain/realmadrid'}
var el2 = {name:'messi', team: 'europe/spain/barcelona'}
var el3 = {name:'gerald', team: 'europe/england/liverpool'}
var el4 = {name:'unknown english', team: 'europe/england'}

I need to produce this JSON tree hierarchy,
{
    "text":"europe",
    "leaf":false,
    "children":[
        {
            "text":"spain",
            "leaf":false,
            "children":[
                {
                    "text":"realmadrid",
                    "leaf":false,
                    "children":[
                        {
                            "text":"ronaldo",
                            "leaf":true
                        }
                    ]
                },
                {
                    "text":"barcelona",
                    "leaf":false,
                    "children":[
                        {
                            "text":"messi",
                            "leaf":true
                        }
                    ]
                }
            ]
        },
        {
            "text":"england",
            "leaf":false,
            "children":[
                {
                    "text":"unknown english",
                    "leaf":true
                },
                {
                    "text":"liverpool",
                    "leaf":false,
                    "children":[
                        {
                            "text":"gerald",
                            "leaf":true
                        }
                    ]
                }
            ]
        }
    ]
}

A: It'd be waaay easier if somehow el1-el4 were combined into a single object, like
var data = []
data[0] = {name:'ronaldo', team: 'europe/spain/realmadrid'}
data[1] = {name:'messi', team: 'europe/spain/barcelona'}
data[2] = {name:'gerald', team: 'europe/england/liverpool'}
data[3] = {name:'unknown english', team: 'europe/england'}

That way you can at least loop through them quickly when processing.
It'd also be useful to know why you need to have this stored as a JSON Tree. I mean, not all the nodes are the same kind of thing, right? The first level is continent, then country, then team name, and the leaves are individual soccer players. That's a fairly confusing data structure and I'm not sure how it would be useful. Either way, it may be more useful to translate it into a fielded structure first and then generate the tree.
Edit:
Okay, so I thought about it a bit more and I think maybe something like this may do it.
var data = [];
data[0] = {name:'ronaldo', team: 'europe/spain/realmadrid'};
data[1] = {name:'messi', team: 'europe/spain/barcelona'};
data[2] = {name:'gerald', team: 'europe/england/liverpool'};
data[3] = {name:'unknown english', team: 'europe/england'};

var tree = {};
function fillTree(name,steps) {
   current = null;
   for (var y = 0; y < steps.length; y++) {
      if (y==0) {
         if (!tree.children||typeof tree.children == 'undefined'){
            tree = { text: steps[y], leaf: false, children: [] };
         }
         current = tree.children;
      } else {
         current.push({ text: steps[y], leaf: false, children: [] })
         current = current[current.length - 1].children;
      }
   }
   current.push({ text: name, leaf: true })
}

for (x=0; x < data.length; x++) {
  steps =data[x].team.split('/');
  fillTree(data[x].name,steps)
}

This creates a JavaScript object. I leave it to you to convert this to JSON.
Update:
Yeah, I see that the old script would have always put a record in at the second level even if it already existed. This is the new improved FillTree function:
var tree = {};
function fillTree(name,steps) {
   var current = null,
   existing = null,
   i = 0;
   for (var y = 0; y < steps.length; y++) {
      if (y==0) {
         if (!tree.children||typeof tree.children == 'undefined'){
            tree = { text: steps[y], leaf: false, children: [] };
         }
         current = tree.children;
      } else {
         existing = null;
         for (i=0; i < current.length; i++) {
            if (current[i].text === steps[y]) {
               existing = current[i];
               break;
            }
         }
         if (existing) {
            current = existing.children;
         } else {
            current.push({ text: steps[y], leaf: false, children: [] });
            current = current[current.length - 1].children;
         }
      }
   }
   current.push({ text: name, leaf: true })
}

The easiest way to convert this object into JSON, apparently, is to use JSON.stringify(tree) although apparently this is not uniformly supported (see the JavaScript JSON Page).

A: in case you agree to have children as object/hash instead of array, here is my solution based on Jordan's https://stackoverflow.com/a/2299268/214420

var el1 = {name:'ronaldo', team: 'europe/spain/realmadrid'}
var el2 = {name:'messi', team: 'europe/spain/barcelona'}
var el3 = {name:'gerald', team: 'europe/england/liverpool'}
var el4 = {name:'unknown english', team: 'europe/england'}

data = [el1,el2,el3,el4]
tree = {};
for(var i =0; i < data.length;i++){
    var steps = data[i].team.split('/');

    steps.push(data[i].name)
    var current = tree;

    for(var j = 0 ; j < steps.length;j++){
        var step = steps[j]
        current.leaf = false;
        current.children = current.children || {};
        current = current.children
        current[step] = current[step] || {text:step,leaf:true}
        current = current[step];
    }
}

A: Create your flat data array and than process on data for finding nested json
like
[{"itemname": "item1","settingkey": "key1","settingvalue": "value1"}, {"itemname": "item2","settingkey": "key2","settingvalue": "value2"},];

and then process this
var keys = Object.keys(dataMap);

var json = [];
for (var key in keys) {
        var innerJson = {};
        innerJson["name"] = keys[key];
        var innerMap = dataMap[keys[key]];

        if (innerMap instanceof Array) {
            innerJson["size"] = innerMap[0];
        } else if (innerMap instanceof Object) {

            var child = processHirarchiachalData(innerMap);
            innerJson["children"] = child;
        }
        json.push(innerJson);

}


text:
Q: Why is this lua dijkstra's algorithm not working in some cases? Im using Dijkstra algorythm code from this site: https://rosettacode.org/wiki/Dijkstra%27s_algorithm#Lua
Unfortunately It doesnt work for current edges table.
I have determined that the problem disappears when I delete the connection from 35 -> 36, but It doesnt solve the problem.
-- Graph definition
local edges = {
  [34] = {[35] = 1,[37] = 1,},
  [35] = {[34] = 1,[36] = 1,[46] = 1,},
  [36] = {[35] = 1,[37] = 1,},
  [37] = {[34] = 1,[36] = 1,},
  [38] = {[46] = 1,},
  [46] = {[35] = 1,[38] = 1,},
}

-- Fill in paths in the opposite direction to the stated edges
function complete (graph)
    for node, edges in pairs(graph) do
        for edge, distance in pairs(edges) do
            if not graph[edge] then graph[edge] = {} end
            graph[edge][node] = distance
        end
    end
end

-- Create path string from table of previous nodes
function follow (trail, destination)
    local path, nextStep = destination, trail[destination]
    while nextStep do
        path = nextStep .. " " .. path
        nextStep = trail[nextStep]
    end
    return path
end

-- Find the shortest path between the current and destination nodes
function dijkstra (graph, current, destination, directed)
    if not directed then complete(graph) end
    local unvisited, distanceTo, trail = {}, {}, {}
    local nearest, nextNode, tentative
    for node, edgeDists in pairs(graph) do
        if node == current then
            distanceTo[node] = 0
            trail[current] = false
        else
            distanceTo[node] = math.huge
            unvisited[node] = true
        end
    end
    repeat
        nearest = math.huge
        for neighbour, pathDist in pairs(graph[current]) do
            if unvisited[neighbour] then
                tentative = distanceTo[current] + pathDist
                if tentative < distanceTo[neighbour] then
                    distanceTo[neighbour] = tentative
                    trail[neighbour] = current
                end
                if tentative < nearest then
                    nearest = tentative
                    nextNode = neighbour
                end
            end
        end
        unvisited[current] = false
        current = nextNode
    until unvisited[destination] == false or nearest == math.huge
    return distanceTo[destination], follow(trail, destination)
end

-- Main procedure
print("Directed:", dijkstra(edges, 34, 38, true))
print("Undirected:", dijkstra(edges, 34, 38, false))

I recieve the output of inf, 38 with current egdes table content but when I delete the connection between 35 -> 36 it gives an good output - 3, 34 35 46 38
For easier understand im uploading the graphic representation of edges table: https://i.imgur.com/FFF22C1.png
As you can see the route is corrent when we start from 34 -> 35 -> 46 -> 38 but as I sad It works only when connection from 35 to 36 is not existing.
Why it is not working in the case showed in my code?

A: This is an example of Dijkstra algorithm implementation
-- Graph definition
local edges = {
   [34] = {[35] = 1,[37] = 1,},
   [35] = {[34] = 1,[36] = 1,[46] = 1,},
   [36] = {[35] = 1,[37] = 1,},
   [37] = {[34] = 1,[36] = 1,},
   [38] = {[46] = 1,},
   [46] = {[35] = 1,[38] = 1,},
}
local starting_vertex, destination_vertex = 34, 38

local function create_dijkstra(starting_vertex)
   local shortest_paths = {[starting_vertex] = {full_distance = 0}}
   local vertex, distance, heap_size, heap = starting_vertex, 0, 0, {}
   return
      function (adjacent_vertex, edge_length)
         if adjacent_vertex then
            -- receiving the information about adjacent vertex
            local new_distance = distance + edge_length
            local adjacent_vertex_info = shortest_paths[adjacent_vertex]
            local pos
            if adjacent_vertex_info then
               if new_distance < adjacent_vertex_info.full_distance then
                  adjacent_vertex_info.full_distance = new_distance
                  adjacent_vertex_info.previous_vertex = vertex
                  pos = adjacent_vertex_info.index
               else
                  return
               end
            else
               adjacent_vertex_info = {full_distance = new_distance, previous_vertex = vertex, index = 0}
               shortest_paths[adjacent_vertex] = adjacent_vertex_info
               heap_size = heap_size + 1
               pos = heap_size
            end
            while pos > 1 do
               local parent_pos = (pos - pos % 2) / 2
               local parent = heap[parent_pos]
               local parent_info = shortest_paths[parent]
               if new_distance < parent_info.full_distance then
                  heap[pos] = parent
                  parent_info.index = pos
                  pos = parent_pos
               else
                  break
               end
            end
            heap[pos] = adjacent_vertex
            adjacent_vertex_info.index = pos
         elseif heap_size > 0 then
            -- which vertex neighborhood to ask for?
            vertex = heap[1]
            local parent = heap[heap_size]
            heap[heap_size] = nil
            heap_size = heap_size - 1
            if heap_size > 0 then
               local pos = 1
               local last_node_pos = heap_size / 2
               local parent_info = shortest_paths[parent]
               local parent_distance = parent_info.full_distance
               while pos <= last_node_pos do
                  local child_pos = pos + pos
                  local child = heap[child_pos]
                  local child_info = shortest_paths[child]
                  local child_distance = child_info.full_distance
                  if child_pos < heap_size then
                     local child_pos2 = child_pos + 1
                     local child2 = heap[child_pos2]
                     local child2_info = shortest_paths[child2]
                     local child2_distance = child2_info.full_distance
                     if child2_distance < child_distance then
                        child_pos = child_pos2
                        child = child2
                        child_info = child2_info
                        child_distance = child2_distance
                     end
                  end
                  if child_distance < parent_distance then
                     heap[pos] = child
                     child_info.index = pos
                     pos = child_pos
                  else
                     break
                  end
               end
               heap[pos] = parent
               parent_info.index = pos
            end
            local vertex_info = shortest_paths[vertex]
            vertex_info.index = nil
            distance = vertex_info.full_distance
            return vertex
         end
      end,
      shortest_paths
end

local vertex, dijkstra, shortest_paths = starting_vertex, create_dijkstra(starting_vertex)
while vertex and vertex ~= destination_vertex do
   -- send information about all adjacent vertexes of "vertex"
   for adjacent_vertex, edge_length in pairs(edges[vertex]) do
      dijkstra(adjacent_vertex, edge_length)
   end
   vertex = dijkstra()  -- now dijkstra is asking you about the neighborhood of another vertex
end
if vertex then
   local full_distance = shortest_paths[vertex].full_distance
   local path = vertex
   while vertex do
      vertex = shortest_paths[vertex].previous_vertex
      if vertex then
         path = vertex.." "..path
      end
   end
   print(full_distance, path)
else
   print"Path not found"
end


text:
Q: BlazeDS: Converting action script type Class (for an embded image) to Java I am using BlazeDS for my flex3 application and I need to transfer an embedded image from actionscript to java. Any hint on how to do that? To what java class does actionScript's Class type correspond?
Thanks

A: In one of my projects I have done this by serializing the image (PNG) to a byte array and transferring the array, and then reconstruct it.


text:
Q: How to change AJAX response HTML and then continue replacemant in jQuery? I have an AJAX that gets new HTML and replaces the form data in response.html.  There is one attribute that I need changed before the replacement.
Here is my try but I cant get it right:
success: function(response, status, xhr) {
    if (response.data.html !== null) {
        var newdata = response.data.html;
        if(firstload == 1){
            var newhtml  = $(newdata).find('.trigger').attr('data-firstload',0);
            // now I need to replace newdata
        }
        $(container).html(newdata);
    }
}

A: You can create a jQuery object containing the new HTML, update it, then append it. Try this:
success: function(response, status, xhr) {
    if (response.data.html !== null) {
        var $newHtml = $(response.data.html);

        if (firstload == 1)
            $newHtml.find('.trigger').attr('data-firstload', 0);

        $(container).empty().append($newHtml);
    }
},


text:
Q: ASP.Net URL Page Helper for ASP.Net Identity Account Confirmation does not create the correct URL The following code from https://learn.microsoft.com/en-us/aspnet/core/security/authentication/accconfirm?view=aspnetcore-3.1&tabs=visual-studio
EmailConfirmationUrl = Url.Page(
"/Account/ConfirmEmail",
pageHandler: null,
values: new { area = "Identity", userId = userId, code = code, returnUrl = returnUrl },
protocol: Request.Scheme);

generates the wrong URL (below). It should have /Identity/Account/ConfirmEmail as path. How do I fix code above so that I get the right path?
https://localhost:5001/?area=Identity&userId=d83c48d3-2715-4dc1-84d7-6e1c1cb0ae4a&code=Q2ZESjhGeERhR0hlUThoTHNqRU9iU3hLTDRJcUtaTVI0S2UrSFFMbjQvL0lhUVVkZ1dqL2dPWkVNQ3lHdGkweU5CWmdSdXM4NVE3Z0hhMWp0TWJGU0h4bFh6ZmhGVWRkNm5MbTg2VXRhTjNpTWozSUVreVlmMEdyUUF0QUJ2MVdNV0Y5aWtTRW05bGdMcXhqTk93TkoxeXNaSW9qWFhkeHN1TkNRK0lISXJnVjVIRFJNTVNaTWRDR1FjaVhoRDFXNllqcnVpYXV2ajNONlp5L1BBUnVKdzkreEt2aFh5emMxa0lhWmNJWk0zcG9DSmN2bzRwODl5Uko2NmRleVNCVUtyQnl5dz09&page=%2FAccount%2Fhttps%3A%2FBlazorWorld.com%2FAccount%2FConfirmEmail

A: Please see answer to a previously asked question.
Essentially Url.Page is for Razor actions.  Url.Action is for MVC.  Which type of pages are you using in your application?
If this helps you out, be sure to go give Ryan an upvote on his answer.


text:
Q: MKV file has no sound on Xbox One I've got an MKV file that runs perfectly with VLC player on Windows 8.1. I want to play this file on my Xbox One. When I try to play it directly from a server, it can access the MKV fine, but there is no sound! As a possible work around, I used VLC Player to convert the MKV file into an MP4 format, but now it has no sound at all, even when I play it on my PC.
Note: this question has a similar title but it does not address the same issue. VLC playing mkv file without sound
This is a similar issue but I am not using Chrome or Youtube, it appears to be a sound or media format issue (it also has no solution): YouTube web no sound but VLC has sound

A: MKV and MP4 are container formats. Internally they contain video and audio which could have been encoded in a variety of formats, commonly referred to as codecs.
Examples of video codecs include h.264 and mpeg2. Examples of audio codecs include MP3 and AAC. There a many more codecs and some are more widely supported than others.
It appears that your file contains an audio format which the Xbox One does not support. Converting the file from MKV to MP4 probably only changed the container format leaving the audio and video contained inside unaltered, so your problem was not fixed.
You need to transcode the audio using a program such as Handbrake (GUI) or ffmpeg (command line) to a codec supported by the Xbox One.

A: Microsoft is pretty lame as it's just a software issue, you have to degrade to no hd audio
add no-hd sound track


text:
Q: Cleaning up after killing a running docker container My goal is to write a docker image that runs a python script that produces a lot of csv files full of random numbers, which once finished, are to be written to an external storage drive, after which the container quits. Assume that it writes so many of these csv files that they cannot be stored into memory.
What I'm worried about are the cases where the container encounters an error  and quits (or is made to quit by the user), and then it creates a bunch of garbage files that have to be manually cleaned.
First solution is to mount a fast drive (like an SSD) directly into the container and write to it. After it is done, it transfers the data from this SSD to the external storage drive. The bad thing about this one is that if the container quits unexpectedly, it will leave garbage on the SSD.
Second solution was to create a volume using the SSD, start a container with this volume, and then pretty much do the same as the first solution. In this case, if the container dies unexpectedly, what happens to the volume? Will it auto quit as well? Can it be configured to auto quit thereby deleting any garbage that was created?
In case you're curious, the final goal is to use these containers with some sort of orchestration system.

A:
What I'm worried about are the cases where the container encounters an error and quits (or is made to quit by the user), and then it creates a bunch of garbage files that have to be manually cleaned.

Note that you may configure your ENTRYPOINT Python script to automatically perform the necessary cleanup.
To give you some guidelines/examples of that approach:

*

*I gave one such example (implemented in Bash, namely with a trap) in this SO answer.

*Another possible example (implemented in Python) is given in this blog article.

Note that beyond the graceful termination of your containers, you may want to setup a restart policy, such as always or unless-stopped. See for example this codeship blog article.

First solution is to mount a fast drive (like an SSD) directly into the container and write to it. After it is done, it transfers the data from this SSD to the external storage drive. The bad thing about this one is that if the container quits unexpectedly, it will leave garbage on the SSD.
Second solution was to create a volume using the SSD, start a container with this volume, and then pretty much do the same as the first solution. In this case, if the container dies unexpectedly, what happens to the volume? Will it auto quit as well?

Albeit the two solutions you present wouldn't be necessary to address the main question of this thread, I have to mention that in general, it is a best practice to use volumes in production, rather than using a mere bind-mount. But of course using any of these two approches (-v volume-name:/path or a bind-mount -v /path:/path) is way better than not using the -v option at all, because I recall that writing data directly in the writable layer of the container implies this data will be lost if the container is recreated from the image.

A:
What I'm worried about are the cases where the container encounters an error and quits (or is made to quit by the user), and then it creates a bunch of garbage files that have to be manually cleaned.

If you write your intermediate files into the container filesystem, rather than to a persistent volume, then docker can do all the hard work for you. Simply run your container with the remove option (--rm). E.g. if you did:
docker run --rm -v /path/to/external/storage:/final/result your_image

Then your application can write to anywhere other than /final/result, and upon exit of the container (successful or any other error condition), the container will be automatically deleted by the docker daemon. On successful completion of your task, write your content to /final/result to be persisted after the container exits. This path is completely made up and you'll likely want to adjust this for your usage.
Note that if you are running on a desktop environment (mac/windows) and not native linux, then there is an issue with the VM disk expanding with usage and not shrinking as files are deleted. This is the nature of VM filesystems that allocate upon usage and outside of docker's control. In that scenario, you'd likely want the entire setup running with an external volume and configuring your entrypoint to cleanup any temporary files left over from the last run of your container.


text: Q: Magento set other order status as default for payment method invoice i have question about the order status process logic. magento set an order after set the order as shipped to payed. but i have a payment method "invoice" which allows the clients to pay after recieve the order, so magento set the order state for me incorrect. is there a way to handle that?


text:
Q: beginner php mysql - return boolean if row contain specific value Ok so basically I'm trying to create a simple web app
I want to check if one element is inside the table, and if inside I want to return a boolean value, like for example if "abc" is inside the table named "name" then return YES.
Here's my code, not working:
error_reporting(E_ALL);

$mysql = mysqli_connect(/* PRIVATE DATA */) or die ("ERROR CONNECTING TO THE DB");

if(isset($_POST['submit'])) {

    $theAddress = $_POST['youtubeURL'];

    $result = "SELECT * FROM data WHERE youtubeURL = '" . $theAddress . "'";

    $query = mysqli_query($mysql, $result);

    if (!$query) {
        printf("Error");
    } else {
        printf("NO ERROR");
    }

AND HERE'S THE NON-WORKING PART :
    while($row = mysqli_fetch_array($query)) {

        if ($row == 0) {

            echo "NO RESULT LIKE THIS";

        }else {

            echo "AT LEAST ONE RESULT LIKE THIS";
        }
    }

}

A: First, learn to use parameters queries.  They really are no harder to use than stuffing a string value into a query.
Second, if you want to know if something exists, then write the query just to do that.  The simplest query is probably:
SELECT EXISTS (SELECT 1 FROM data WHERE youtubeURL = ?) as exists_flag

This will return 1 if something matches.  Just run the query and read the single value that is returned.
Note that returning select * to check for existence is an anti-pattern.  You are returning way more data from the database than you need (both in terms of rows and columns).  That is usually not a good idea.

A: It should be like this.
//in case you want to see total of the wors
if(mysqli_num_rows($query) == 0) {
    echo "NO RESULT LIKE THIS";
} else {
    echo "AT LEAST ONE RESULT LIKE THIS";
}

 //in case you want to check for each of the row
 while($row = mysqli_fetch_array($query)) {
        if (empty($row)) {
            echo "NO RESULT LIKE THIS";
        } else {
            echo "AT LEAST ONE RESULT LIKE THIS";
        }
 }

A: You need to use mysqli_num_rows to count the rows ..
$result = "SELECT * FROM data WHERE youtubeURL = '" . $theAddress . "'";

$query = mysqli_query($mysql, $result);

if(mysqli_num_rows($query)) {
    echo "AT LEAST ONE RESULT LIKE THIS";
} else {
    echo "NO RESULT LIKE THIS";
}


text:
Q: "Thickening" an arc on a 2-manifold What is the argument for the fact that each arc in the interior of a 2-manifold can be "thickend" to obtain a 2-cell containing the arc in its interior and being disjoint from any preassigned compact set in the complement of the arc? Thanks in advance!

A: Suppose that $S$ is the surface, $\alpha$ is the arc, and $K$ is the compact set.
Proof 1: Find an arc $\alpha'$ so that $\gamma = \alpha \cup \alpha'$ is a Jordan curve (+).  The Jordan/Schoenflies [J/S] theorems provide an annulus (or Möbius) neighbourhood $A$ of $\gamma$ and a homeomorphism on $A$ making $\gamma$ "straight".  Shrink $A$ as needed to avoid $K$ and then use $A$ to find the desired two-cell.
Proof 2: Let $T$ be the double branched cover of $S$, branched over the two points of $\partial \alpha$.  Let $\beta$ and $\beta'$ be the two preimages of $\alpha$ in $T$.  So the union $\gamma = \beta \cup \beta'$ is a Jordan curve.  Apply [J/S] to find an annulus neighbourhood $A$ of $\gamma$.  Shrinking $A$ as needed, we may assume that it is disjoint from the preimage of $K$.  We further arrange matters so that $A$ is invariant under the deck transformation, as are two of its cutting arcs (meeting $\gamma$ in exactly the points $\partial \beta$). So the image of $A$ is the desired two-cell.

Of course, in Proof 1, sentence (+) is saying that endpoints of $\alpha$ are "accessible".  Showing such things is part of various proofs of [J/S]. The branched cover trick in Proof 2 is designed to avoid (+).  However, I'll guess that no proof can avoid using [J/S], or at least some of its "working parts".


text:
Q: Ordinal arithmetic washing line Let $\eta$ be the order type of $\mathbb{Q}$.
I'm trying to calculate $(1+ \eta) \cdot (\eta + 1)$ and $(\eta + 1) \cdot (1+ \eta)$. So for the first one I'm thinking that you just do this
$(1+\eta) \cdot (\eta + 1) = (1+ \eta) \cdot \eta + (\eta + 1) \cdot 1= \eta + \eta + 1= \eta +1$.
Was wondering is this correct. It's hard to think about ordinal arithmetic. I was under the impression you think about it with the washing line method. So left side of the multiplication is the washing line and the right hand side is the clothes.
It's just $(1+\eta) \cdot (1+ \eta)= (1+\eta) \cdot 2$ by similar reasons. However, I this can't be possible. Or maybe I'm doing something wrong.

A: Remember that when you multiply order types, you have the left but not the right distributive law. Thus, $(1+\eta)\cdot(\eta+1)=(1+\eta)\cdot\eta+1+\eta$, and $(\eta+1)\cdot(1+\eta)=\eta+1+(\eta+1)\cdot\eta$. For any further simplification, we must see what $(1+\eta)\cdot\eta$ and $(\eta+1)\cdot\eta$ look like.
Suppose that $\langle X,\preceq\rangle$ is a linear order of type $(1+\eta)\cdot\eta$. Then by the definition of $(1+\eta)\cdot\eta$ we can decompose $X$ into pairwise disjoint sets $X_q$ for $q\in\Bbb Q$ in such a way that

*

*if $p,q\in\Bbb Q$ with $p<q$, $x\in X_p$, and $y\in X_q$, then $x\prec y$, and

*each $X_q$ is ordered in type $1+\eta$ by $\preceq$ and hence is order-isomorphic to $\Bbb Q\cap[0,1)$ with its usual order.

Note that each $X_q$ is densely ordered by $\preceq$: if $x,y\in X_q$ with $x\prec y$, there is a $z\in X_q$ such that $x\prec z\prec y$.
Clearly $X$ is countably infinite. Now let $x\in X$ be arbitrary; $x\in X_q$ for some $q\in\Bbb Q$. Choose any $y\in X_{q-1}$ and $z\in X_{q+1}$ and note that $y\prec x\prec z$, so that $x$ is neither a first or last element of $\langle X,\preceq\rangle$. Since $x\in X$ was arbitrary, $\langle X,\preceq\rangle$ has no first or last element.
Finally, let $x,y\in X$ with $x\prec y$; there are $p,q\in\Bbb Q$ such that $x\in X_p$ and $y\in X_q$. Clearly $p\le q$. If $p<q$, let $r$ be any rational number between $p$ and $q$; then for each $z\in X_r$ we have $x\prec z\prec y$. If $p=q$, use the earlier observation that $X_p$ is densely ordered to conclude that there is a $z\in X_p$ such that $x\prec z\prec y$. It follows that $\preceq$ densely orders $X$.
Thus, $\langle X,\preceq\rangle$ is a dense linear order without endpoints and is therefore order-isomorphic to $\Bbb Q$; that is, it has order type $\eta$.
We can now conclude that $(1+\eta)\cdot(\eta+1)=(1+\eta)\cdot\eta+1+\eta=\eta+1+\eta$. Now the set $\Bbb Q^-$ of negative rationals has order type $\eta$, as does the set $\Bbb Q^+$ of positive rationals, so $\Bbb Q=\Bbb Q^-\cup\{0\}\cup\Bbb Q^+$ has order type $\eta+1+\eta$, and $\eta+1+\eta=\eta$. (Or you could argue as before that $\eta+1+\eta$ is a countable dense order type without endpoints.) The final conclusion is that $$(1+\eta)\cdot(\eta+1)=\eta\;.$$
That was pretty detailed, and the other one is quite similar, so I'll leave it to you.


text:
Q: Aws STS assume role for calling API Gateway I am trying to call an api gateway route using StsClient assumeRole (php aws sdk 3). Everything works OK, except that I do not know how to not 'hardcode' the sts user's session ARN in the role policy.
Here is my code for the serverless:
Resources:
  ApiGatewayPolicy:
    Type: AWS::IAM::Policy
    Properties:
      PolicyName: my-policy-apigateway
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Action:
              - execute-api:Invoke
            Resource:
              Fn::Join: [ "", [ "arn:aws:execute-api:", { "Ref": "AWS::Region" }, ':', { "Ref": "AWS::AccountId" }, ':', { "Ref": "ApiGatewayRestApi" }, '/*/GET/routeName/*/*/*' ] ]
            Effect: Allow
      Roles:
        - Ref: IamRoleApiGatewayExecution

and the STS policy (with STS and not IAM user's ARN):
Resources:
  IamRoleApiGatewayExecution:
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              AWS:
                Fn::Join: [ "", [ "arn:aws:sts::", { "Ref": "AWS::AccountId" }, ':assumed-role/YYYYYYYYYYYYY/XXXXXXXXXXXXXXXXXXXXXXXXXXX' ] ]
            Action: sts:AssumeRole

I do call the route with php aws sdk (another project):
        $stsClient = new StsClient([
            'region' => 'eu-west-1',
            'version' => 'latest',
        ]);
        $ARN = "arn:aws:iam::.........:role/dating-crop-dev-IamRoleApiGatewayExecution-..........";

        $sessionName = uniqid('api-gateway-access-');
        $result = $stsClient->assumeRole([
            'RoleArn' => $ARN,
            'RoleSessionName' => $sessionName,
        ]);
........

And as I said everything works fine, except that I don't know how to make the XXXXXXXXXXXXXXXXXXXXXXXXXXX dynamic, otherwise I have to update it after some hours (worst practice :) ).
Thanks for any suggestion.

A: I have solved the issue by replacing the sts user ARN by the IAM role ARN in the role's policy. So
            Principal:
              AWS:
                Fn::Join: [ "", [ "arn:aws:sts::", { "Ref": "AWS::AccountId" }, ':assumed-role/YYYYYYYYYYYYY/XXXXXXXXXXXXXXXXXXXXXXXXXXX' ] ]

becomes:
            Principal:
              Service: apigateway.amazonaws.com
              AWS:
                Fn::Join: [ "", [ "arn:aws:iam::", { "Ref": "AWS::AccountId" }, ':role/myRoleName' ] ]

and it works well.


text:
Q: How to SUM values for DISTINCT values of another column and GROUP BY date? How can we SUM amount for each activity only on same date and output a row for each date? This query is not working.
SELECT SUM(amount), type, date FROM table GROUP BY DISTINCT date;

Table
+----+------------+-----------+---------+
| id |    date    | activity  | amount  |
+----+------------+-----------+---------+
| 1  | 2017-12-21 | Shopping  | 200     |
| 2  | 2017-12-21 | Gift      | 240     |
| 3  | 2017-12-23 | Give Away | 40      |
| 4  | 2017-12-24 | Shopping  | 150     |
| 5  | 2017-12-25 | Give Away | 120     |
| 6  | 2017-12-25 | Shopping  | 50      |
| 7  | 2017-12-25 | Shopping  | 500     |
+----+------------+-----------+---------+

Required Result
+------------+-----------+------+-----------+
|    date    | Shopping  | Gift | Give Away |
+------------+-----------+------+-----------+
| 2017-12-21 | 200       | 240  |           |
| 2017-12-23 |           |      | 40        |
| 2017-12-24 | 150       |      |           |
| 2017-12-25 | 550       |      | 120       |
+------------+-----------+------+-----------+

A: Use:
select `date`,
  sum(if (activity='Shopping', amount, null)) as 'Shopping',
  sum(if (activity='Gift', amount, null)) as 'Gift',
  sum(if (activity='Give Away', amount, null)) as 'Give Away'
from table
group by `date`

A: You can try this. It returns exact result that you want
SELECT t.date,
    SUM(t.shopping_amount) AS shopping,
    SUM(t.gift_amount) AS gift,
    SUM(t.give_away_amount) AS give_away
FROM
(
    SELECT p.`date`, p.`activity`, p.`amount` AS shopping_amount,
        0 AS gift_amount, 0 AS give_away_amount
    FROM products p
    WHERE p.`activity` = 'Shopping'

    UNION

    SELECT p.`date`, p.`activity`, 0 AS shopping_amount,
        p.amount AS gift_amount, 0 AS give_away_amount
    FROM products p
    WHERE p.`activity` = 'Gift'

    UNION

    SELECT p.`date`, p.`activity`, 0 AS shopping_amount,
        0 AS gift_amount, p.amount AS give_away_amount
    FROM products p
    WHERE p.`activity` = 'Give Away'
) t
GROUP BY t.date

A: Hmmm, you can't pivot your results into column headers unless you know all possible values as demonstrated by slaasko but you can get the results using sql into a form which can be pivoted using your display tool ( e.g. slice of BI tool).
SELECT SUM(amount), activity, date FROM table GROUP BY date, activity;


text:
Q: Batch Script related issue I have written following script which works absolutely fine on my system.
@echo off

setlocal enabledelayedexpansion

FOR /F %%i IN ('wmic /node:%1 computersystem get Name') DO SET A=%%i
FOR /F %%i IN ('wmic /node:%1 computersystem get Domain') DO SET B=%%i
FOR /F %%i IN ('wmic /node:%1 computersystem get UserName') DO SET C=%%i
FOR /F %%i IN ('wmic /node:%1 computersystem get Manufacturer') DO SET D=%%i
FOR /F "delims=" %%i IN ('wmic /node:%1 computersystem get Model') DO SET E=%%i
FOR /F %%i IN ('wmic /node:%1 computersystem get SystemType') DO SET F=%%i
FOR /F %%i IN ('wmic /node:%1 bios get SerialNumber') DO SET G=%%i
FOR /F "delims=|" %%i IN ('wmic /node:%1 os get Name') DO SET H=%%i
FOR /F %%i IN ('wmic /node:%1 os get TotalVisibleMemorySize') DO (SET J=%%i)

SET /a J=%J%/1024

FOR /F "delims=" %%i IN ('wmic /node:%1 cpu get Name') DO SET K=%%i
echo %A%,%B%,%C%,%D%,%E%,%F%,%G%,%H%,%J% MB,%K% >> output.csv

But, with some modifications in it which are shown below, it doesn't display any information.
@echo off

setlocal enabledelayedexpansion

ping -n 1 %1 | find "TTL=" > NUL
IF NOT ERRORLEVEL 1 (

FOR /F %%i IN ('wmic /node:%1 computersystem get Name') DO (SET A=%%i)
FOR /F %%i IN ('wmic /node:%1 computersystem get Domain') DO (SET B=%%i)
FOR /F %%i IN ('wmic /node:%1 computersystem get UserName') DO (SET C=%%i)
FOR /F %%i IN ('wmic /node:%1 computersystem get Manufacturer') DO (SET D=%%i)
FOR /F "delims=" %%i IN ('wmic /node:%1 computersystem get Model') DO (SET E=%%i)
FOR /F %%i IN ('wmic /node:%1 computersystem get SystemType') DO (SET F=%%i)
FOR /F %%i IN ('wmic /node:%1 bios get SerialNumber') DO (SET G=%%i)
FOR /F "delims=|" %%i IN ('wmic /node:%1 os get Name') DO (SET H=%%i)
FOR /F %%i IN ('wmic /node:%1 os get TotalVisibleMemorySize') DO (SET J=%%i)

SET J=%J%/1024

FOR /F "delims=" %%i IN ('wmic /node:%1 cpu get Name') DO (SET K=%%i)

echo %A%,%B%,%C%,%D%,%E%,%F%,%G%,%H%,%J%,%K% >> output.csv

)

It is not giving any error either. But, the generated output.csv file contains no data.

A: Change
IF NOT ERRORLEVEL 1 (

to
IF NOT %ERRORLEVEL%==1 (

Although, I'm not sure the ping reply looks the same when IPv6 is used instead of IPv4.  You may want to investigate this further (e.g., is TTL part of an IPv6 reply?).  For instance:
c:\>ping localhost

Pinging Laptop_Name [::1] with 32 bytes of data:
Reply from ::1: time<1ms
Reply from ::1: time<1ms
Reply from ::1: time<1ms
Reply from ::1: time<1ms

Ping statistics for ::1:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 0ms, Maximum = 0ms, Average = 0ms

A: Delayed expansion
When the cmd parser reaches a line of a block of lines (lines surounded in parenthesis), all variable reads are replaced with the value they have at parse time, before executing the lines in the block. If the value of the variable changes inside the block, this change is not seen in the lines where the value is readed, as this read was replaced with the value of the variable before the change.
So, in your second code, the variables are changing its value, but in the final echo to the output file, as the variable reads where replaced with the value before the value change, no data is output. The variables did not have any value before the start of block execution.
If you want to maintain this style of code, you need to enable delayed expansion, and change the sintax in the variable reads that need its reads / value expansion delayed until execution time.
setlocal enabledelayedexpansion
....
if not errorlevel 1 (
    ....
    echo !a!, !b!, !c!
)

Arithmetic
SET J=%J%/1024 should be SET /A J=!J!/1024, arithmetic requires SET /A
PING
As JamesL indicates in his answer, in the case of IPv6, there is no "TTL=" data in the output of the ping command.
In ipv4 ping command set errorlevel if any packed is lost. And you will not get packets lost when pinging a non active same subnet machine. So the best way of testing for active machine in ipv4 is to test for TTL= value in output.
In ipv6, there is not TTL output, but now, pinging a same subnet non active machine you obtain all packet lost. And the errorlevel is only set if ALL the packets are lost. If any packet reaches its target, errorlevel is not set
So, for ipv4, test TTL=, for ipv6 test errorlevel
WMIC
While this way of retrieving data is correct and will work, is more efficient to retrieve all possible data in a single query (as you did in your previous questions). The six calls for computersystem data should be written as a single wmic call.


text:
Q: Could not find com.github.scottyab:showhidepasswordedittext:0.6 I am trying to add this dependency
 com.github.scottyab:showhidepasswordedittext:0.6. in an android app. On building the project I am having this error critically
Error:A problem occurred configuring project ':app'.
> Could not resolve all dependencies for configuration ':app:_debugApkCopy'.
   > Could not find com.github.scottyab:showhidepasswordedittext:0.6.
     Required by:
         push:app:unspecified

Please what am I doing wrong. Kindly assist

A: latest version of dependency is :
dependencies {
    compile 'com.github.scottyab:showhidepasswordedittext:0.8'
}

and don't forgot to add maven repo in the project-level build.gradle file
allprojects {
    repositories {
        maven {
            url "https://jitpack.io"
        }
    }
}

for more information check here


text:
Q: Spring - Injecting resources in per-scoped (perthis - pertarget) aspect In my Spring web application, I'm trying to inject a resource in  a perthis-scoped AspectJ aspect. Injection works well using a singleton aspect, but fails using a perthis scoped one. I tried using both @Autowire annotation or xml <property> tag.
Here is my code.
Aspect (for @Configurable I tried both autowire=Autowire.BY_TYPE and autowire=Autowire.BY_NAME):
@Aspect(
    "perthis(org.mypackage.aop.aspects.TestAspect.participateAroundPointcut())")
@Component
@Scope("prototype")
@Configurable()
public class TestAspect {

    private static final Logger logger = LoggerFactory.getLogger(TestAspect.class);

    @Autowired
    private CommonService commonService;

    @Pointcut("execution(* org.mypackage.TestService.method(..))")
    public void participateAroundPointcut(){}

    @Around("participateAroundPointcut()")
    public void testAround(ProceedingJoinPoint joinPoint) throws Throwable{
        logger.debug("Pre-execution; commonService==null: "+(commonService==null)+";");
        joinPoint.proceed();
        logger.debug("Post-execution");
    }
}

CommonService:
@Service
@Scope("request")
public class CommonService {
    private String value = "commonValue";
}

and beans' xml configuration:
<context:component-scan base-package="org.mypackage" />
<aop:aspectj-autoproxy proxy-target-class="true"/>
<context:spring-configured />
<bean id="testAspect" class="org.mypackage.aop.aspects.TestAspect" scope="prototype" factory-method="aspectOf"/>
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />

And output confirming that commonService is not autowired:
DEBUG: org.mypackage.aop.aspects.TestAspect - Pre-execution; commonService==null: true;
DEBUG: org.mypackage.TestService - Executing method
DEBUG: org.mypackage.aop.aspects.TestAspect - Post-execution

Some configuration/annotation may be overloaded (for example i'm using both @Scope("prototype") and scope="prototype" in xml), because I tried all the possibilities.
However, setting singleton scope and removing perthis (and making CommonService singleton-scoped too) the field is correctly autowired.
Any help would be appreciated.
EDIT:
Removing scope="prototype" from TestAspect xml bean definition I get the following exception:
java.lang.IllegalArgumentException: Bean with name 'testAspect' is a singleton, but aspect instantiation model is not singleton
at org.springframework.aop.aspectj.annotation.BeanFactoryAspectJAdvisorsBuilder.buildAspectJAdvisors(BeanFactoryAspectJAdvisorsBuilder.java:121)
at org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator.findCandidateAdvisors(AnnotationAwareAspectJAutoProxyCreator.java:86)
at org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator.shouldSkip(AspectJAwareAdvisorAutoProxyCreator.java:107)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessBeforeInstantiation(AbstractAutoProxyCreator.java:275)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInstantiation(AbstractAutowireCapableBeanFactory.java:894)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.resolveBeforeInstantiation(AbstractAutowireCapableBeanFactory.java:866)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:451)

Although TestAspect class is annotated with @Scope("protptype"), the bean is recognized like a singleton, causing the error. It seems that the container doesn't take into account the @Scope annotation, while it works for all other beans. Maybe @Configurable isn't detected too, causing the autowiring error?


text:
Q: Octave manipulating images I am trying to resize and rotate an image using octave. However when I try get the following error:
Index exceeds matrix dimension... Anyone see what I am doing wrong?
I=imread('c:/cg/img/Lena.jpg'); % 128 x 128 uint
I2=rgb2gray(I);

alfa=.5;

for i=1:round(256*alfa)
  for j=1:round(256*alfa)

    is=round(i/alfa);
    js=round(j/alfa);

    if (is<1) is=1;  endif;
    if (js<1) js=1;  endif;

 I3(i,j)=I2(is,js);

   end
end

imwrite(I3,"c:/cg/lenax0.5.jpg","jpg");

for i=1:256
   for j=1:256
     I4(i,j)=I3(257-j,i);         %90
     I5(i,j)=I3(257-i,257-j);     %180
     I6(i,j)=I3(j,257-i);         %270
    end
end

I7=[I3 I4; I5 I6];
imshow(I7);
imwrite(I7,"c:/cg/lena_rotate_90_180_270.jpg","jpg");

A: Figured it out error was here I had the size wrong.
for i=1:256
   for j=1:256
     I4(i,j)=I3(257-j,i);         %90
     I5(i,j)=I3(257-i,257-j);     %180
     I6(i,j)=I3(j,257-i);         %270
  end
end

I had the size wrong needed to be
for I=1:128 ect...

A: I can't make much sense of your code but yes, you're doing something wrong. You're not using the functions of the image package to imrotate and imresize. Don't forget to load the image package before calling those functions pkg load image.


text:
Q: Simple JQuery syntax issue There is the part of my code which works perfectly
var image_mini = $('#map_mini');
var image_full = $('#map_full');

function state_change(data) {
   // This is just part of code which show idea
   image_mini.mapster(data.state);
}

// This is full block of code, works correct
$("#map_full").mapster(
     $.extend({}, options, {
         onStateChange: state_change
     })
);

Now I need to enhance function state_change so, that it fill recive second agrument with image variable, which will be use insted of the directly writed image_mini.
Something like this (the code below is WRONG), but with CORRECT syntax code:
function state_change(data, working_image) {
  working_image.mapster(...);
}

$("#map_full").mapster(
     $.extend({}, options, {
         onStateChange: state_change, image_mini
     })
);

I feel me lamer, but I haven't found example of correct sintax for passing two variables in such onStateChange... I tried some ideas, but it didn't work correctly.
Please help!
==============================
Added later:
Looks like my idea wasn't understood correctly, so I write more of code:
var image_mini = $('#map_mini');
var image_full = $('#map_full');

function state_change(data, working_image) {
  working_image.mapster(data.state);
}

$("#map_full").mapster(
     $.extend({}, options, {
         onStateChange: state_change, image_mini
     })
);
$("#map_mini").mapster(
     $.extend({}, options, {
         onStateChange: state_change, image_full
     })
);

This is idea of what I want: both images must be crosslinked, so changes on one will be showed on both of them.
onStateChange: state_change, image_full

This is WRONG, I ask about correct syntax for the task.

A: It might not be as pretty, but you can do this using:
$.extend({}, options, {
    onStateChange : function (e) {
        state_change(e, image_mini);
    }
})

EDIT
To explain, your first version of code reads like this:
function state_change(data) {
    // ...
}
// ...
$.extend({}, options, {
    onStateChange : state_change
})

What happens here is that whenever onStateChange fires, it calls the state_change function. If this follows general jQuery parlance, then that function gets passed the jQuery event object as the function's first parameter. In this case, that event object would resolve as the data argument in your state_change function declaration.
My code above, follows the same logic:
onStateChange : function (e) {
}

So when onStateChange fires, it'll call that anonymous function, and pass in the event object as the first argument. This will resolve as e inside the handler function. Therefore:
onStateChange : function (e) {
    state_change(e, image_mini);
}

... performs mostly the same thing with respect to the event object. When the onStateChange event fires, the handler gets the event object as e, which it will then pass to the call to state_change. That'll resolve to data inside state_change as a result, and will not change how you use the original function much.
This way, however, we're free to pass in additional arguments into the call to state_change, like throwing in image_mini or whatever.

A: You are dropping image_mini in as a new item in the JSON object you are defining. That won't work. If you are looking to have it reference the map, you should be able to move that param into the first line of the state_change function
Because jQuery is going to do a basic function call of the question, you should have something like this:
    function state_change(data) {
    var image_mini = $("#mapMini");
    fullStateChange( data, image_mini );
}

function fullStateChange( data, image_mini ) {
    // Do stuffs here

    // This is just part of code which show idea
    image_mini.mapster(data.state);
}

// This is full block of code, works correct
$("#map_full").mapster(
      $.extend({}, options, {
            onStateChange: state_change
      })
);


text:
Q: Find users who have visited URL A and B with SQL? Let's say you have a table with user, url, datetime, in which each row is a website visit.
How to find users who have visited both an URL contaning string pattern A and visited an URL containing string pattern B?
The fact it's "containing a string pattern ...", and not a simple equality makes it impossible to use a query with something like
url in ('action1.php', 'action2.php')

like in SQL querying a customer ID who ordered both product A and B.

A: You can use group by and having:
select user
from t
where url like '%a%' or
      url like '%b%'
group by user
having sum(url like '%a%') > 0 and
       sum(url like '%b%') > 0;

If you don't want to repeat the comparisons, you can leave out the where clause or use:
select user
from (select t.*, (url like '%a%') as has_a, (url like '%n%') as has_b
      from t
     ) t
where has_a or has_b
group by user
having sum(has_a) > 0 and
       sum(has_b) > 0;

A: Assuming "/testing" and "/staging" are the two URL patterns. You can use this
SELECT   user
FROM     `table`
WHERE    url LIKE '%/testing%' or
         url LIKE '%/staging%'
GROUP BY user
HAVING   (COUNT(url LIKE '%/testing%') > 0 and COUNT(url LIKE '%/staging%') > 0)

If you need more info on pattern matching you can do a search on "pattern matching SQL" and "SQL regular expression".


text:
Q: Keras - preprocessing and scaling for forked architecture I have data set that has two inputs x1,x2 and output that has 1 binary value (0,1) and 45 real numbers (output vector has 46 attibutes in summary). I would like to use different loss functions for this 1 binary value and 45 real numbers, namely binary crossentropy and mean squared error.
My knowledge of Keras is very limited, so I am not even sure if this is the architecture I want. Is this the right way of doing this?
first, preprocessing:
# load dataset
dataframe = pandas.read_csv("inputs.csv", delim_whitespace=True,header=None)
dataset = dataframe.values
# split into input (X) and output (Y) variables
X = dataset[:,0:2]
Y = dataset[:,3:]

x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=0.2,
random_state=123)
y_train_L, y_train_R = y_train[:,0], y_train[:,1:]
y_train_L = y_train_L.reshape(-1,1)
scalarX, scalarY_L, scalarY_R = MinMaxScaler(), MinMaxScaler(), MinMaxScaler()
scalarX.fit(x_train)
scalarY_L.fit(y_train_L)
scalarY_R.fit(y_train_R)

x_train = scalarX.transform(x_train)
y_train_L = scalarY_L.transform(y_train_L)
y_train_R = scalarY_R.transform(y_train_R)

where y_train_L  is left part are just binary values and y_train_R are real numbers. I had to split them because when defining architecture:
# define and fit the final model

inputs = Input(shape=(x_train.shape[1],))
first =Dense(46, activation='relu')(inputs)

#last
layer45 = Dense(45, activation='linear')(first)
layer1 = Dense(1, activation='tanh')(first)
out = [layer1,layer45]
#end last

model = Model(inputs=inputs,outputs=out)
model.compile(loss=['binary_crossentropy','mean_squared_error'], optimizer='adam')
model.fit(x_train, [y_train_L,y_train_R], epochs=1000, verbose=1)

Xnew = scalarX.transform(x_test)
y_test_L, y_test_R = y_test[:,0], y_test[:,1:]
y_test_L = y_test_L.reshape(-1,1)
y_test_L=scalarY_L.transform(y_test_L)
y_test_R=scalarY_R.transform(y_test_R)
# make a prediction
ynew = model.predict(Xnew)

loss=['binary_crossentropy','mean_squared_error'] expects two different arrays in model.fit(x_train, [y_train_L,y_train_R])
then i have to do all the 'funny' tricks to get predicted values and compare them next to each other because ynew = model.predict(Xnew) return list of two lists, one for binary values and one for real numbers.
ynew = model.predict(Xnew)
# show the inputs and predicted outputs
print("SCALED VALUES")
for i in range(len(Xnew)):
    print("X=%s\n P=%s,%s\n A=%s,%s" % (Xnew[i], ynew[0][i], ynew[1][i], y_test_L[i], y_test_R[i]))

inversed_X_test = scalarX.inverse_transform(Xnew)
inversed_Y_test_L = scalarY_L.inverse_transform(y_test_L)
inversed_Y_test_R = scalarY_R.inverse_transform(y_test_R)
inversed_y_predicted_L = scalarY_L.inverse_transform(ynew[0])
inversed_y_predicted_R = scalarY_R.inverse_transform(ynew[1])
print("REAL VALUES")
for i in range(len(inversed_X_test)):
    print("X=%s\n P=%s,%s\n A=%s,%s" % (inversed_X_test[i], inversed_y_predicted_L[i],inversed_y_predicted_R[i], inversed_Y_test_L[i],inversed_Y_test_R[i]))

questions:

*

*Can I achieve this in cleaner way?

*How can I measure loss? I would like to create chart of loss values during trening.

A: 1) The way you define your model seems correct and there is no 'cleaner' way of doing it (I would argue that Keras' functional API is as clean as it gets)
2) To visualize training loss, store the history of training in a variable:
history = model.fit(...)

This history object will contain the train and validation losses for each epoch, you can use itto make plots.
3) In your classification output (layer1), you want to use a sigmoid activation instead of tanh. The sigmoid function returns values between 0 and 1, tanh returns values between -1 and 1. Your binary_crossentropy loss function expects the former.


text:
Q: Debugging NullReference exception from WCF client internals We have a WCF service and roughly the following client code:
bool success = false;
IClientChannel proxy = null;
try
{
  var client = channelFactory.CreateChannel(new EndpointAddress(url));
  proxy = client as IClientChannel;
  proxy.Open();
  client.MyWcfMethod(a, b, c);
  proxy.Close();
  success = true;
}
finally
{
  if (!success)
    proxy.Abort();
}

It seems to work fine, but on our beta environment, once in ~70000 calls a NullReferenceException is thrown. We log the exception and all the data around carefully, and it looks like it does not depend on data in any way. If I repeat the call immediately after the exception (just a while until success), it goes smoothly.
The exception appears so rare, that I can't reproduce, trace or debug it. Exception seems to be thrown immediately at the time of call, no server code is called.
Here is the stack trace:
Object reference not set to an instance of an object. Server stack trace:
at System.Xml.Linq.ElementWriter.WriteElement(XElement e)
at System.Xml.Linq.XElement.WriteTo(XmlWriter writer)
at System.Xml.Linq.XElement.System.Xml.Serialization.IXmlSerializable.WriteXml(XmlWriter writer)
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteIXmlSerializable(XmlWriterDelegator xmlWriter, Object obj, XmlSerializableWriter xmlSerializableWriter)
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteIXmlSerializable(XmlWriterDelegator xmlWriter, Object obj)
at System.Runtime.Serialization.XmlDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context)
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle)
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle)
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
at WriteCallContextToXml(XmlWriterDelegator , Object , XmlObjectSerializerWriteContext , ClassDataContract )
at System.Runtime.Serialization.ClassDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context)
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle)
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle)
at System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectContent(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectContent(XmlWriterDelegator writer, Object graph)
at System.Runtime.Serialization.XmlObjectSerializer.WriteObjectContentHandleExceptions(XmlWriterDelegator writer, Object graph)
at System.Runtime.Serialization.DataContractSerializer.WriteObjectContent(XmlDictionaryWriter writer, Object graph)
at System.ServiceModel.Channels.XmlObjectSerializerHeader.OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
at System.ServiceModel.Channels.MessageHeader.WriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
at System.ServiceModel.Channels.MessageHeaders.WriteHeaderContents(Int32 headerIndex, XmlDictionaryWriter writer)
at System.ServiceModel.Channels.Message.WriteMessagePreamble(XmlDictionaryWriter writer) at System.ServiceModel.Channels.Message.OnWriteMessage(XmlDictionaryWriter writer) at System.ServiceModel.Channels.BufferedMessageWriter.WriteMessage(Message message, BufferManager bufferManager, Int32 initialOffset, Int32 maxSizeQuota)
at System.ServiceModel.Channels.BinaryMessageEncoderFactory.BinaryMessageEncoder.WriteMessage(Message message, Int32 maxMessageSize, BufferManager bufferManager, Int32 messageOffset)
at System.ServiceModel.Channels.HttpOutput.SerializeBufferedMessage(Message message)
at System.ServiceModel.Channels.HttpOutput.Send(TimeSpan timeout)
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.SendRequest(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout) at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message) Exception rethrown at [0]: at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at IMyService.MyWcfMethod(int a, string b, double c)
at MyClientClass.Process()

Any ideas on where to search for the answer?

A: It sounds like it could be a threading issue - maybe the WCF client code is reusing the same serializer instance for multiple calls, and it's breaking stuff.
Can you try putting your call to client.MyWcfMethod() inside a lock block?
e.g.:
private static readonly object _wcfSync = new object();
...

  lock (_wcfSync)
  {
    client.MyWcfMethod(a, b, c);
  }


text:
Q: Launch android.intent.action.BOOT_COMPLETED through ADB Is it possible to launch the action:
android.intent.action.BOOT_COMPLETED
using ADB. Currently, I need to restart my device and wait until the OS broadcasts this message. Would be nice if I could do it without requiring a reboot.

A: adb shell am broadcast -a android.intent.action.BOOT_COMPLETED

A: You need to specify the package name before the class name (then you may write it without the package) like this:
./adb shell am broadcast -a android.intent.action.BOOT_COMPLETED -c android.intent.category.HOME -n net.fstab.checkit_android/.StartupReceiver

A: Why not send that broadcast yourself (or a different one that will run your Receiver) just for dev purposes, and once you are done developing whatever feature you are working on, remove that call?


text:
Q: How to profile the number of exceptions generated, categorized by exception class or line of code I'm using a number of open-source third-party libraries, and a flight recording shows that the code is generating tens of thousands of exceptions per second.
How can I track down which type of exception is being thrown, and where in the source code it's being thrown, so that I can see if I can fix the third-party code myself?
Java Mission Control does not show any breakdown of exception types or sources, as far as I can see.
Please do not recommend expensive commercial profilers, as this is for an open source project.

A:
Java Mission Control does not show any breakdown of exception types or sources, as far as I can see.

That is not correct, Java Mission Control does provide that information.
First you need to enabled tracing of exceptions in Flight Recorder (by default only java.lang.Error descendants are traced).
See flight recorder settings screen shot below.

Once recorder you need to go to "Exceptions" report.
There you would find breakdown of exceptions by class. "Stack Trace" view would allow to get exact stack traces.

I little JMC live hack: bring context menu on "Stack Trace" view and select "Distinguish Frames By" > "Line Number" (see on screenshot above). That would allow you to see line numbers.
If you prefer CLI tools take a look at SJK (disclaimer, this is my own OSS profiler). E.g. command below would produce SVG flame graph of exceptions from you JFR dump. There are also few other report types.
java -jar sjk.jar ssa -f dump.jfr --jfr-event THROW --flame > throw_flame.svg

A:
Please do not recommend expensive commercial profilers, as this is for an open source project.

Some commercial profilers offer free licenses for open-source projects, like JProfiler.
In JProfiler, there is a probe that shows exceptions grouped by exception class with back traces to the call stacks where they were thrown.

Disclaimer: My company develops JProfiler.


text:
Q: Iterating through a dictionary, and getting max, min, and average values from the value For the get_gc_stats( ) function:
The first value in the returned list will be the minimum GC value in the dictionary
The second value in the returned list will be the maximum GC value in the dictionary
The third value in the returned list will be the average GC value from the dictionary
Assuming the dictionary is:
dna_dict = {
  'TAGC' : [0.5, 4],
  'ACGTATGC' : [0.5, 8],
  'ATG' : [0.3333333333333333, 3],
  'ACGGCTAG' : [0.625, 8]
}

I am going through this problem and I am getting confused on what to do. I think I need to go through each value in the dictionary and get the max, min, and average of the number that is in index 0. However I need more guidance.
This is my code
def get_gc_stats(dna_dict):
for key, value in dna_dict.items():
    for i in value[0]:

A: You can use make a long list of all the "GC" values and then the use min(), max(), and divide the sum of all values by the length of the list to get the values you would like.
dna_stats = {
  'TAGC' : [0.5, 4],
  'ACGTATGC' : [0.5, 8],
  'ATG' : [0.3333333333333333, 3],
  'ACGGCTAG' : [0.625, 8]
}

def get_gc_stats(dna_dict):
  gc_values = []
  for value in dna_dict.values():
    gc_values.extend(value)
  return [min(gc_values), max(gc_values), sum(gc_values) / len(gc_values)]

print(get_gc_stats(dna_stats))

A: dna_stats = {
  'TAGC' : [0.5, 4],
  'ACGTATGC' : [0.5, 8],
  'ATG' : [0.3333333333333333, 3],
  'ACGGCTAG' : [0.625, 8]
}

If you need to collect all of the first values, you can use a list comprehension.
first_vals = [v[0] for v in dna_stats.values()]
# [0.5, 0.5, 0.3333333333333333, 0.625]

Now getting the min, max and average are straightforward.


text:
Q: Read file and run command in zsh So I generally create job files with a list of commands in it. Then I execute it like so
cat jobFile | while read a; do $a; done

Which always works in bash. However, I've just started working in Mac which apparently uses zsh. And this command fails with "no such file" etc. I've tested the job file by running few lines from it manually, so it should be fine.
I've found questions on zsh read inbut they tend to be reading in from variables e.g. $a=('a' 'b' 'c') or echo $a
Thank you for your answers!

A: In bash, unquoted parameter expansions always undergo word-splitting, so if a="foo bar", then $a expands to two words, foo and bar. As a command, this means running the command foo with an argument bar.
In zsh, parameter expansions to not undergo word-splitting by default, which means the same expansion $a would produce a single word foo bar, treated as the name of the command to execute.
In either case, relying on parameter expansion to "parse" a shell command is fragile; in addition to word-splitting, the expansion is subject to pathname expansion (globbing), and you are limited to simple commands and their arguments. No pipes, lists (&&, ||), or redirections allowed, as everything will be treated as the command name and a sequence of arguments.
What you want in both shells is to simply treat your job file as a shell script, which can be executed in the current shell using the . command:
. jobFile

A: Why are you executing it in such a cumbersome way? Assuming jobFile is a file holding a sequence of bash commands, you can simply run it as
bash jobFile

If it contains a sequence of zsh commands, you can likewise run it as
zsh jobFile

If you follow this approach, I would however reflect in the name of the job file, what shell it is intended for, i.e.
bash jobFile.bash
zsh jobFile.zsh

and, if you write a job file so that it is supposed to be compatible with either shell, I would name it jobFile.sh.


text:
Q: HTable is not getting invoked through JAVA API First of all thanks for viewing my question. Currently, I have installed hbase-1.2.3 and hadoop-2.7.3 in a Linux box. When executing the jps, I could see the below process running,
11015 HQuorumPeer
25843 NameNode
26173 SecondaryNameNode
25985 DataNode
11130 HMaster
11267 HRegionServer
11961 Jps

Even, I could login to hbase shell and provide commands to view my tables. Problem is I am trying to call the HBase table through my standalone java program and it stucks there. Below is the output I am seeing when I execute the program. I am not seeing anything there in the other logs (master, region, zookeeper).
Below is my sample program,
  Configuration config = HBaseConfiguration.create();
  config.set("hbase.zookeeper.quorum","localhost");
  config.set("hbase.zookeeper.property.clientPort","2181");

  // Instantiating HTable class
  System.out.println("Entering");
  HTable table = new HTable(config, "test_venkat");
  System.out.println("Exiting");

Logs
Entering
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Oct 06, 2016 12:11:53 PM org.apache.hadoop.hbase.zookeeper.RecoverableZooKeeper <init>
INFO: The identifier of this process is 11863@servername

It hangs after this and it is not printing the Exiting statement. Can anyone please help me on this? What could be the reason? Appreciate your help


text:
Q: Run a shell to check directory exist on the list of servers and get output in a file I have the mentioned script which can check the existence of directory in Linux servers. I could check the directory exist but i want to run this on a list of servers saved in txt file and can gain the output as directory exist or not in an txt file. Please suggest!!
   #!/bin/bash
if [ -d /vat/opt/BESClient ];
then
    echo "The Directory Exists"
else
    echo "The Directory is not present"
fi


text:
Q: Does it make any difference if a Window setTimeout is made to be dependent on jQuery DOM ready? I just have some code which I want executed a few seconds after the page is loaded. For that I could do this..
 setTimeout(function() {
            alert("Now I am free");
    }, 3000);

Or I could make it fire on document ready...
 jQuery(document).ready(function ($) {

   setTimeout(function() {
     alert("Now I am free");
    }, 3000);
});

What is the difference between these two approaches? Which is better?

A: The first approach (just set a delay) has a timing hole in it: the timer could go off before the page has finished loading.
You may consider this unlikely, and it may be unlikely on your system. But consider the visitor whose device has marginal memory capacity, continuous memory faults are occurring because the OS is trying to update itself at the same time as 15 open tabs in the web browser are trying to do background AJAX calls, and the browser is showing "not responding" across the top. And, say, the browser takes another 30 seconds to start responding again. This is not a fictitious, scenario.
Using the document ready mechanism to start the timer guarantees the DOM can be manipulated by call back code when the timer goes off. You could also add an event listener to window "load" event to do the same thing in plain vanilla JavaScript.
Starting the timer in a script block right at the end of the <body> section may also remove the risk of the timer going off too early.


text: Q: Lubuntu loops between the terminal pre-login and an odd, glitchy screen for a couple of frames I installed Gnome on lubuntu and I attempted to change some fonts and clock settings. The problem started when I Logged out and tried to login to Gnome again. I assumed I made at least on mistake by either re configuring fonts or the clock format(I'm betting on the fonts). Restarting the computer now takes lubuntu into a loop between a black screen, a single frame of a glitchy graphic and a single frame of the login terminal. If I could just reset the desktop environments through my installer image via terminal, that might do the trick. I would normally google it but that landed me with no results. Thanks in advance.


text:
Q: SQL updating master table with updates from update table I am trying to update my master table from my updates table, What it wrong with the below query.
UPDATE       master_table
SET          master_table.description = master_table_import.description
FROM         master_table_import
WHERE        master_table.user_id = master_table_import.user_id

A: You are missing a join between the tables. Try something like this:
UPDATE mt SET mt.Description = mti.Description
FROM master_table mt
INNER JOIN master_table_import mti
ON mt.user_id = mti.user_id;

A: It is always good idea to use aliases for tables. To update you have join your target table with source table:
UPDATE       mt
SET          description = mti.description
FROM         master_table mt INNER JOIN master_table_import mti
WHERE        mt.user_id = mti.user_id


text:
Q: Is there an R function for creating a new column to the existing data frame and assign "03" to first 68 rows and "04" to next 68 rows? The current data frame has three columns and 136 rows.  I want to create a new column  with first 68 rows have a fixed value="03" and next 68 rows have a fixed value='04".
select(code, year, value) ->aa1.
I tried this code
aa1 [ , 'month']=  c(rep( '03','1:68'))
aa1 [ , 'month']=  c(rep( '04', '69:136'))

A: you can use rep
x$newvar <- c( rep( "03", 68) , rep( "04", 68) )

Or index
x$newvar2 <- NA
x[ 1:68  , "newvar2" ] <- "03"
x[ 69:136  , "newvar2" ] <- "04"

A: Looks like you need something like this? You need to use rep twice in this case:
aa1[ , 'month']= c(rep('03', 68), rep('04', 68))