text:
Q: Sequelize restrict update if many-to-many relation established In general I have a goal to restrict any update of an entity if it's binded to anything.
To be specific I have two models: Order and Good. They have many-to-many relation.
const Good = sequelize.define('good' , { name:Sequelize.STRING });
const Order = sequelize.define('order' , { });
//M:N relation
Good.belongsToMany(Order, { through: 'GoodsInOrders' });
Order.belongsToMany(Good, { through: 'GoodsInOrders' });

I have tried to set onUpdate: 'NO ACTION' and onUpdate: 'RESTRICT' inside belongsToMany association defining but it has no effect.
Here is the code to reproduce my manipulations with goods and order
//creating few goods
const good1 = await Good.create({ name:'Coca-Cola' });
const good2 = await Good.create({ name:'Hamburger' });
const good3 = await Good.create({ name:'Fanta' });

//creating an order
const order = await Order.create();

//adding good1 and good2 to the order
await order.addGoods([good1,good2]);

//It's ok to update good3 since no orders contains It
await good3.update( { name:'Pepsi' });

//But I need to fire an exeption if I try to update any goods belonged to order
//There should be an error because we previously added good1 to order
await good1.update( { name:'Sandwich' });

I have no clue how to restrict it in a simple way.
Surely we always can add beforeUpdate hook on Good model but I would like to avoid this kind of complications.
I will be glad to any ideas.

A: As I said I was looking for simpler alternative to hooks but many researches after all led me to nowhere.
My solution was to declare the beforeUpdate hook inside Good model so inital definition
const Good = sequelize.define('good' , { name : Sequelize.STRING } );

was transformed into this
const Good = sequelize.define('good', {
    name: Sequelize.STRING
}, {
    hooks: {
        beforeUpdate: async (instance, options) => {
            if ((await instance.getOrders()).length)
                return Promise.reject('error');
            return Promise.resolve();

        }
    }
});

So here we add the hook that fires every time before update particular good.
It makes inner request of list of orders that contains current good.
(await instance.getOrders()).length

And depends on the result it either fire an exception if the list isn't empty or  just return resolved promise that means that everything ok and current good can be updated.


text:
Q: What caused Eve to die?
Possible Duplicate:
What happened to the Female Krogan?

When playing curing the genophage, Eve (the Krogan female) had been killed while the cure was being made, but apparently other people had her survive. What caused this change in storyline and does it affect later play?

A: Eve dies if Mordin did not have access to Maelon's data from the Mass Effect 2 mission Old Blood.
There are two ways that he wouldn't have access: If you completed the mission in ME2, but chose to destroy the data, or if you never completed the mission in ME2. The latter of these is the default assumption in a New Game without an imported save.
Without Maelon's data, Mordin is unable to effectively counteract the immunodeficiency that is a side effect of the experimental Genophage cure to which Eve was exposed. Since Mordin is unable to treat her, Eve doesn't make it.
The only way to keep Eve alive is to complete Old Blood on an imported character, and save the data.
Eves survival has two major effects:

*

*If Eve dies, there is a -50 modifier on Krogan War Assets. Her survival prevents this.

*If Eve survives, you are unable to convince Mordin to sabotage the cure -  the only way to do so is to kill Mordin yourself. You monster.

A: I think its related to a descision of the second game, like says this question, a default Shepard :

Shepard did not help Mordin, as such no chance was made to save or
  destroy the genophage cure data.

I did help Mordin save the genophage cure data. And stopped the mad salarian scientist that did barbaric experiments to cure the genophage.
So in your save, Eve had to suffer longer those barbaric experiments, resulting in her death. That's my guess.

redpajama_set_name: RedPajamaStackExchange


text:
Q: TreeView Drag & Drop help - _Invalid FORMATETC structure_ exception I'm trying to implement Drag & Drop functionality with source being a TreeView control. When I initiate a drag on a node, I'm getting:
Invalid FORMATETC structure (Exception from HRESULT: 0x80040064 (DV_E_FORMATETC))
The ItemDrag handler (where the exception takes place), looks like:
private void treeView_ItemDrag(object sender,
        System.Windows.Forms.ItemDragEventArgs e)
{

        this.DoDragDrop(e.Item, DragDropEffects.Move);
}

Does anyone know the root cause of this and how to remedy it? (.NET 2.0, Windows XP SP2)

A: In case it helps anyone else - I encountered this problem with the WPF TreeView (not Windows Forms as listed in the question) and the solution was simply to make sure to mark the event as handled in the drop event handler.
    private void OnDrop(object sender, DragEventArgs e)
    {
        // Other logic...

        e.Handled = true;
    }

A: FORMATETC is a type of application clipboard, for lack of a better term.  In order to pull off some of the visual tricks of draging around the tree node, it has to be copied into this clipboard with its source description.  The source control loads its info into the FORMATETC clipboard and sends it to the target object.  It looks like the error occurs on the drop and not on the drag. The DV in DV_E_FORMATETC typically indicates the error occurrs on the drop step.
The destination doesn't look like it likes what you are droping on it. The clipboard may be corrupt or the drop destination may not be configured to understand it.
I recommend you try one of two things.

*

*Remove the original tree structure and destination. Dump your dlls.  Close everything.  Open up and put the treeview and destination back on the form.  It may have just been poorly formed and not fully populating the FORMATETC structure.

*Try putting another treeview and droping to that.  If you are droping to another tree and it works you know your oranges to oranges work and it isn't the treeview.  It may be the destination if it is a grid or listview.  You may need to change those structures to be able to receive the drop.

Not that it helps but the structure is something like this:
typedef struct tagFORMATETC
{
  CLIPFORMAT      cfFormat;
  DVTARGETDEVICE  *ptd;
  DWORD           dwAspect;
  LONG            lindex;
  DWORD           tymed;
} FORMATETC, *LPFORMATETC;

A: When doing drag and drop with list and treeview controls you have to make sure that you removing and inserting the list items correctly. For example, using drag and drop involving three ListView controls:
    private void triggerInstanceList_DragOver(object sender, DragEventArgs e)
    {
        SetDropEffect(e);
    }

    private void triggerInstanceList_DragEnter(object sender, DragEventArgs e)
    {
        SetDropEffect(e);
    }

    private void SetDropEffect(DragEventArgs e)
    {
        if (e.Data.GetDataPresent(typeof(ListViewItem)))
        {
            ListViewItem itemToDrop = e.Data.GetData(typeof(ListViewItem)) as ListViewItem;
            if (itemToDrop.Tag is TriggerTypeIdentifier)
                e.Effect = DragDropEffects.Copy;
            else
                e.Effect = DragDropEffects.Move;
        }
        else
            e.Effect = DragDropEffects.None;
    }

    private void triggerInstanceList_DragDrop(object sender, DragEventArgs e)
    {
        if (e.Data.GetDataPresent(typeof(ListViewItem)))
        {
            try
            {
                ListViewItem itemToDrop = e.Data.GetData(typeof(ListViewItem)) as ListViewItem;
                if (itemToDrop.Tag is TriggerTypeIdentifier)
                {
                    ListViewItem newItem = new ListViewItem("<new " + itemToDrop.Text + ">", itemToDrop.ImageIndex);
                    _triggerInstanceList.Items.Add(newItem);
                }
                else
                {
                    _expiredTriggers.Items.Remove(itemToDrop);
                    _triggerInstanceList.Items.Add(itemToDrop);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
        }
    }

you will note that at the end of the DragDrop event I am either moving the ListViewItem or creating a copy of one.


text:
Q: How to slice JSON object in Python How to slice a JSON object in Python I have a JSON object which looks like:
{
  "value": [
    {
      "name": "b648e43a-6fd8-4b70-9981-28942473e0c3",
      "id": "xxxxxxxxxxxxxxxxxxxxxxxx",
      "etag": "W/\"1c08986f-3337-4c06-815e-aab31b4b196d\"",
      "location": "eastus",
      "tags": {
        "type": "aks-slb-managed-outbound-ip"
      },
      "zones": [
        "2",
        "1",
        "3"
      ],
      "properties": {
        "provisioningState": "Succeeded",
        "resourceGuid": "3bd20fd5-ffa3-4321-8309-354c252bec22",
        "ipAddress": "xxxx.xxxx.xxxx.xxx",
        "publicIPAddressVersion": "IPv4",
        "publicIPAllocationMethod": "Static",
        "idleTimeoutInMinutes": 30,
        "ipTags": [],
        "ipConfiguration": {
          "id": "xxxxxxxxxxxxx"
        }
      },
      "type": "Microsoft.Network/publicIPAddresses",
      "sku": {
        "name": "Standard",
        "tier": "Regional"
      }
    },
    {
      "name": "kubernetes-a40f77cc30dd047928d4e7fdf3c20a12",
      "id": "xxxxxxxxxxxxx",
      "etag": "W/\"057c51ec-33a8-4bb6-9e02-50146f55b66c\"",
      "location": "eastus",
      "tags": {
        "kubernetes-cluster-name": "kubernetes",
        "service": "kube-system/ingress-nginx-public-controller"
      },
      "zones": [
        "1",
        "2",
        "3"
      ],
      "properties": {
        "provisioningState": "Succeeded",
        "resourceGuid": "ab07866e-19c1-4542-ab46-27306b7e7652",
        "ipAddress": "xxx.xxx.xxx.xxx",
        "publicIPAddressVersion": "IPv4",
        "publicIPAllocationMethod": "Static",
        "idleTimeoutInMinutes": 4,
        "ipTags": [],
        "ipConfiguration": {
          "id": "xxxxxxx"
        }
      },
      "type": "Microsoft.Network/publicIPAddresses",
      "sku": {
        "name": "Standard",
        "tier": "Regional"
      }
    }
  ]
}

I need to get "ipConfiguration" block. I tried changing the JSON block in Python dict and look for key value pair but "ipConfiguration" block is deep inside another dict. Can somebody help in figuring out how to get out "ipConfiguration" block data into a variable.

A: I have stored your json data in a file & tried to get all ipConfiguration's id in a variable. Please find the code snippet for the same.
Code :-
import json

ipConfiguration_ids = []
with open('sample.json', 'r') as json_file:
    json_dict = json.loads(json_file.read())
    for value in json_dict['value']:
        ipConfiguration_ids.append(
            value['properties']['ipConfiguration']['id'])
print(ipConfiguration_ids)

Output:-
['xxxxxxxxxxxxx', 'xxxxxxx']


text:
Q: WCF ServiceHost BaseAddresses does not contain all IIS host header values, when multiple Host Headers set in IIS I have a WCF service that has bee working for a long time, hosted in IIS6 (Windows Web Server 2003).
I am trying to add a 2nd host header value in IIS (previously there was only 1).
So now in IIS, lets say I have configured:
IP: All Available, Port: 80, Host: x.test.com
IP: All Available, Port: 80, Host: y.test.com

In my application, I have this WCF config property set:
<serviceHostingEnvironment multipleSiteBindingsEnabled="true">
</serviceHostingEnvironment>

And I have a custom ServiceHostFactory:
public class MySuperServiceHostFactory : ServiceHostFactory
{
    protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
    {
        //...
    }
}

In the parameter Uri[] baseAddresses, WCF seems to only ever pass me whatever the first value is in the IIS configuration. So for this example, baseAddresses is a Uri[1] with the one value http://x.test.com/MyService.svc.

The same thing happens if I specify HTTP and HTTPS host headers in IIS. So back to the same example, lets say for HTTP traffic we set:
IP: All Available, Port: 80, Host: x.test.com
IP: All Available, Port: 80, Host: y.test.com

And for SSL traffic we run the command:

cscript.exe c:\Inetpub\AdminScripts\adsutil.vbs set /w3svc/12345/SecureBindings ":443:secureA.test.com" ":443:secureB.test.com"

So now my site should have 4 possible addresses.
However now WCF just passes me the first host from each type of connection, so my Uri[] now contains 2 elements:
http://x.test.com/MyService.svc
https://secureA.test.com/MyService.svc

Anyone have any insight as to why this happens?

Edit:
This link "How can WCF support multiple IIS Binding specified per site ?" at the very bottom says:

Solution in .Net Fx4.0: BaseAddressPrefixFilters
Beta2 Fix
In the current  Beta2 release of the .NET Framework, we added  support
  for multiple site binding  . Just set the binding in IIS site and the
  service will inherit the address
Final RTM Fix
In the final bits, we decided to make it an opt-in due to application
  compatability reasons. In order to enable multiple site binding, you
  need to set multipleSiteBindingEnabled to true in your application.
  Multiple site binding is supported only for Http protocol. The address
  of endpoints in the configuration file need to be complete URI. When
  porting your 3.0 or 3.5 workaround to 4.0 you need to keep this
  particular aspect.
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />

That very last bit is what I am doing. I am using .NET4's added ability to set multiple host headers in IIS, with multipleSiteBindingsEnabled="true" set in my configuration.
This actually works fine if you leave the rest of WCF alone and let it do its default thing for constructing the service endpoints.
However, my issue is that all the multiple host headers aren't actually passed in to a custom ServiceHostFactory implementation, so it seems difficult or impossible to manually set up your own endpoints on all base addresses.
Perhaps this is just a bug in .NET 4?

A: In your custom classes are you manually adding the other end points? I do believe the way it is engineered you need to do so manually...
See http://msdn.microsoft.com/en-us/library/ms751515.aspx
With this notion it seems that if the EndPoint it is the config then it will be added for you. Since your config is empty you must add the endpoint's manually.
See WCF Self Host Service - Endpoints in C#


text:
Q: Outputting script output values from jenkins to a file I have my jenkins pipeline working and calling Ps scripts.
    env.output= powershell(returnStdout: true, script: '.\\scripts\\script.ps1 -target_servername')

I would like to save the env.output to an automatically generated file within the workspace directory.
    so like %workspace%\logs\%jobname%_%job_no%.log

And I would like to append details onto the file.

A: Your are alreaddy using powershell. So i think the Add-Content Commandlet is the perfect tool for your. Just switch to a multiline powershell script.


text:
Q: How do you use the Google+ SIgn In button to get a oauth token? I'm trying to use the G+ SignInButton to get a oauth token for sending to a web service to authenticate with that service. I'm having a lot of problems getting through the Google documentation on this, as it seems to be trying to do a lot more than simple authentication, and their section on oauth seems to be specific to using it to access Google services, which isn't what I'm doing.
Implementing the Facebook login button was fairly simple, install the library, implement the button, the callback gives you a token. Is there some G+ equivalent I'm just not finding? This is all feeling ridiculously complicated for such a simple task, in addition to the fact that I can't get it working.


text:
Q: Switching from WiFi connection to 3g causes connection to hang? I have an application which connects to a web service. I can connect to the web service any number of times without any problem using WIFI or 3G provided that I stay loyal to my connection type during the life cycle of my application. That is if I don't switch from WIFI to 3G. If I switches from WIFI to 3G, I can't get a response anymore. My connection just keeps on waiting for response.
I tried 4 scenarios below. I'm only having problem with the 3rd scenario. What could be the problem?
1st Scenario: Connection is always on WIFI (Ok)

*

*Application connects to a web service using WIFI.

*Response was received successfully.

*Application connects again to a web service using WIFI.

*Response was receive successfully.

2nd Scenario: Connection is always on 3G (Ok)

*

*Application connects to a web service using WIFI.

*Response was received successfully.

*Application connects again to a web service using WIFI.

*Response was receive successfully.

3rd Scenario: Connection switches from WIFI to 3G (No response)

*

*Application connects to a web service using WIFI.

*Response was received successfully.

*Connection was switched to 3G. WIFI is disabled. 3G is enabled.

*Application connects again to a web service using 3G.

*No was response or error was received. Application keeps on waiting for response. Last log was displayed before getResponseCode was called.

4th Scenario: Connection switches from 3G to WIFI (Ok)

*

*Application connects to a web service using 3G.

*Response was received successfully.

*Connection was switched to WIFI. 3G is disabled. WIFI is enabled.

*Application connects again to a web service using WIFI.

*Response was receive successfully.

My guess is by default, HttpURLConnection thinks WIFI as a better connection type compare to 3G. So when the connection is switched from WIFI to 3G, HttpURLConnection refuses to acknowledge 3G and still tries to connect using WIFI. On the other hand, HttpURLConnection allows switching from 3G to WIFI since WIFI is a better connection type. Am I correct with this? If so, how do I allow switching from WIFI to 3G?
Below is a snippet of my code: (I call it every time I connect to a web service.)
//open new connection
httpsURLConnection = (HttpURLConnection) ((new URL(url)).openConnection());
httpsURLConnection.setDoInput(isDoInput);
httpsURLConnection.setDoOutput(isDoOutput);

try
{
    //supply parameters
    OutputStreamWriter wr = new OutputStreamWriter(httpsURLConnection.getOutputStream());
    wr.write(data);
    wr.flush();

    if(httpURLConnection != null)
    {
        if (httpsURLConnection.getResponseCode() == HttpsURLConnection.HTTP_OK) //connection hangs here
        {
            //some code
        }
        else
        {
            //some code
        }
    }

}catch(Exception e)
{

}

A: I'm not sure why but adding System.setProperty("http.keepAlive", "false") on the code solves the problem.
According to the Android Developers Blog (androids-http-clients), HttpURLConnection has a bug prior to Froyo and it can be solved by disabling connection pooling just like above. However, I'm using Gingerbread so I'm not sure why HttpURLConnection is still misbehaving on my application.
To others: If you can provide more explanation, please don't hesitate to edit my post.

A: when you make a connection on wifi and it switches back to 3G, do you see any connection drop exceptions?
From what i know, if you open a connection on wifi the same connection can't be used for 3G. you need to teardown existing connection and reestablish new connection on 3G.
I am guessing your problem could be because you haven't set any connection timeouts for your requests and as a result when connection drops it takes a long time for HttpUrlConnection to realize ur connection is lost.
I have put together utility libraries on http connections with some default timeouts, see if this can help you anyway
https://github.com/nareshsvs/android-libraries


text:
Q: public_suffix requires Ruby version >= 2.3 while installing fastlane Getting following error public_suffix requires Ruby version >= 2.3. while installing fastlane
i am using ruby 3.0
ruby -v
ruby 3.0.0p0 (2020-12-25 revision 95aff21468) [x86_64-linux]

Installing fastlane
sudo gem install fastlane

getting below error
ERROR:  Error installing fastlane:
public_suffix requires Ruby version >= 2.3.

A: https://github.com/weppos/publicsuffix-ruby/blob/v4.0.6/public_suffix.gemspec#L23
specifies that public_suffix requires a ruby version >= 2.x - so I believe that it will not, unfortunately, permit 3.x as a dependency.
See In a ruby .gemspec file, how do I specify multiple versions of a dependency?
This is something that needs to be done by the gem maintainer.  It's also a fanstastic example of dependency hell in the wild.


text:
Q: Reshape 3-d array to 2-d I want to change my array type as pd.DataFrame but its shape is:
array_.shape
(1, 181, 12)

I've tried to reshape by the following code, but it didn't work:
new_arr = np.reshape(array_, (-1, 181, 12))

How can I change its shape?

A: NumPy array dimensions can be reduced using various ways; some are:
using np.squeeze:
array_.squeeze(0)

using np.reshape:
array_.reshape(array_.shape[1:])

or with using -1 in np.reshape:
array_.reshape(-1, m.shape[-1])

# new_arr = np.reshape(array_, (-1, 12))    # <==   change to your code

using indexing as Szczesny's comment:
array_[0]

A: You may want to erase the -1 parameter from the reshape() function to get a final output shape of (181, 12)
import numpy as np

m = np.array([[[1]*12]*181])
n = np.reshape(m, (181, 12))
print(m.shape, n.shape)

Output:
(1, 181, 12) (181, 12)


text:
Q: Run an App made in React native in an Emulator Android S.O. Ubuntu: 20.04
I'm trying to run a app than I downloaded, but when I try to "yarn run android".
The next message
A problem occurred evaluating project ':react-native-community_async-storage'.
> Plugin with id 'com.android.library' not found.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1s

This is the code ofbuilScrip in file build.gradle.
buildscript {
if (project == rootProject) {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.0'
    }
}

}
please, help!!


text:
Q: ASP.NET MVC Custom Routing Based on Query Params We're migrating a legacy app to .NET MVC and have to maintain backwards compatibility for the old URLs.  Consider a forum application where URLs look like this
http://example.com/forums?page=ForumsList - shows a list of all forums
http://example.com/forums?page=Threads&forumId=1 - shows list of threads in forum 1
http://example.com/forums?page=Posts&forumId=1&threadId=1 - shows posts in forum 1, thread 1.

I'd like to map those same URLs to actions in my controllers, i.e.
public ActionResult ForumsList(){}
public ActionResult Threads(string forumId){}
public ActionResult Posts(string forumId, string threadId){}

Without duplicating this maintenance nightmare that we had in our legacy system
public ActionResult Index(string page){
    if (page == "Forums"){
         return Forums();
    }
    else if (page == "Threads){
         return Threads(Request.Params["forumId"]);
    }
    else if (page == "Posts"){
         return Posts(Request.Params["forumId"], Request.Params["threadId"]);
    }
    // oh, there's more.  a lot more.
}

All the documentation I can find on custom routing seems to suggest that it can only parse the path portion of a URL, not the params.  I tried the following, to no avail:
        routes.MapRoute(
            name: "TestRoutes",
            url: "{controller}/?page={action}",
            defaults: new {controller = "Forums", action = "ForumsList"});

Anything else I can do?

A: Actually, you don't need to do anything special. By default, the modelbinder will attempt to attach anything in the query string as parameters to the action method. You would just have to use one action to handle/proxy all the requests:
public class ForumsController : Controller
{
    public ActionResult Index(string page, int? forumId, int? threadId)
    {
        ...
    }
}

With just the default route of:
routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

Will work just fine.
The main bit of the URL, /forums would match ForumsController, and the default action of Index would be used, since it wasn't specified in the URL. The id parameter is optional. Then, each of the items in the querystring will be set for the same-named parameters of the action. The forumId and threadId parameters need to be nullable ints to allow passing just the page parameter for something like your /forums?page=ForumsList URL.
While you could simply set up your application to work this way in general, I'd actually recommend keeping this particular action as a clearinghouse. First, I'd create a custom route, so you don't have to devote your Index action to this:
routes.MapRoute(
    name: "OldForums",
    url: "forums",
    defaults: new { controller = "OldForums", action = "RedirectToNewURLs" }
);

Then:
public class OldForumsController : Controller
{
    public ActionResult RedirectToNewURLs(string page, int? forumId, int? threadId)
    {
        if (page == "ForumList")
        {
            return RedirectToActionPermanent("Index", "Forums");
        }

        if (page == "Threads")
        {
            return RedirectToActionPermanent("Threads", "Forums", { id = forumId });
        }

        // etc
    }
}

These redirects would point to your new nice forum URLs such as /forums/{id}/threads. So, if a user enters through an old URL, they just get redirected to the new version, and all new users get sent to the good URLs from the start.
EDIT
Actually, I forgot to point out that the one complication with this approach is that you can't actually use the URL /forums for your actual forums index. You could use something like /forums/all to differentiate or just do something like singularize it, i.e. forum. All the other routes would work fine with the forums prefix because only that string itself would be matched by the custom route. Something like forums/1, for example, would fall through to the default route.


text:
Q: Python Websocket - with time and message limit I am getting the data from websocket (ws://localhost:8080) and doing command line args with that. code mentioned below..
python datapy.py -i 127.0.0.1 -p 8080
from websocket import create_connection
#import ConfigParser
#from test import settings
import sys
import argparse
import socket

parser = argparse.ArgumentParser()
parser.add_argument('-i', dest='ip' , help='host name / IP')
parser.add_argument('-p', dest='port' , type=int, help='port')
parser.add_argument('-t', dest='time' , type=int, help='Time (in seconds) to keep reading data from websocket. After this process will be exit. Default value is 0. For 0 it will run infinitely')
parser.add_argument('-m', dest='msg' , type=int, help='Number of message. Process will exit after receiving Number of messages. Default is 0, means runs for ever.')
args = parser.parse_args()
print(args.ip)

#ws://%s:%s" % (args.ip,args.port)
url = "ws://%s:%s" % (args.ip,args.port)
ws = create_connection(url)
print "Receiving data from the socket..."
for each in ws:
    result =  ws.recv();
    print "Received '%s'" % result
ws.close();

Console:
C:\Users\556718\Desktop\pythonprac>python datapy.py -i 127.0.0.1 -p 8080
127.0.0.1
Receiving data from the socket...
Received 'sound'
Received 'eokeoe'
Received 'mdmmd'
Received 'ssss'
Received 'tttt'

As mentioned in argparse, I want to pass -m and -t - like
python data.py -i 127.0.0.1 -p 8080 -m 5 --> It will limit to only 5 messages in the console..
python data.py -i 127.0.0.1 -p 8080 -t 120 --> Send me the messages until 120 seconds - after that exit ....
python data.py -i 127.0.0.1 -p 8080 -m 5 -t 120 --> for limiting to 120 seconds (2 minutes) and 5 messages - either of the condition

Can anyone help me in this

A: I couldn't test, but something along these lines should work.
from websocket import create_connection
#import ConfigParser
#from test import settings
import sys
import argparse
import socket
import time

parser = argparse.ArgumentParser()
parser.add_argument('-i', dest='ip' , help='host name / IP')
parser.add_argument('-p', dest='port' , type=int, help='port')
parser.add_argument('-t', dest='time' , type=int, help='Time (in seconds) to keep reading data from websocket. After this process will be exit. Default value is 0. For 0 it will run infinitely')
parser.add_argument('-m', dest='msg' , type=int, help='Number of message. Process will exit after receiving Number of messages. Default is 0, means runs for ever.')
args = parser.parse_args()
print(args.ip)

#ws://%s:%s" % (args.ip,args.port)
url = "ws://%s:%s" % (args.ip,args.port)
ws = create_connection(url)
print "Receiving data from the socket..."
tstart = time.time()
nbmsg = 0
for each in ws:
    result =  ws.recv();
    nbmsg += 1
    if args.time is not None:
        if time.time() > tstart + args.time:
            print('Time limit reached.')
            sys.exit()
    if args.msg is not None and nbmsg >= args.msg:
        print('Message limit reached')
        sys.exit()
    print "Received '%s'" % result
ws.close();


text:
Q: How to count a nesting of lambda expressions and anonymous methods? I tried to parse code and count a nesting, but i have a problems with lambda Expression and anonymous methods. I tried to use VisitSimpleLambdaExpression() and VisitAnonymousMethodExpression() but it didn't help me. Tell me anyone another idea for counting nesting of Lambda Expressions and anonymous methods? My current code:
class NestingLevelVisitor : SyntaxVisitor<int>
{
    public override int VisitMethodDeclaration(MethodDeclarationSyntax node)
    {
        return Visit(node.Body);
    }

    public override int VisitBlock(BlockSyntax node)
    {
        if (node.Statements.Select(Visit).Count() == 0)
            return 0;
        return node.Statements.Select(Visit).Max();
    }

    public override int VisitExpressionStatement(ExpressionStatementSyntax node)
    {
        return 0;
    }

    public override int VisitAnonymousMethodExpression(AnonymousMethodExpressionSyntax node)
    {
        int result = Visit(node.Block);
        return result + 1;  //dont works
    }

    public override int VisitSimpleLambdaExpression(SimpleLambdaExpressionSyntax node)
    {
        Console.WriteLine(node.Body);
        int result = Visit(node.Body);
        return result + 1;  //dont works
    }
}

UPD:
this example demonstrate a lambda expression with braces:
class Program
{
    static void Main()
    {
        int m = 0;
        document =>
        {
            return new InsertRequest(nominalType, document);
        };
    }
}

and nesting = 1
but if i use construction like this:
bool f2()
         {
                int a = 1;
                Func< bool, bool> not = b =>!b;
                return 1;
         }

nesting is not changing
this method contains a anonymous method and nesting of this method = 1:
static void Main()
{
    Printer p = delegate(string j)
    {
        System.Console.WriteLine(j);
    };
    p("The delegate using the anonymous method is called.");
    p = new Printer(TestClass.DoWork);
    p("The delegate using the named method is called.");
}

A: When the syntax visitor encounter a node kind that doesn't have overridden Visit method, it simply returns 0.
And you don't override VisitLocalDeclarationStatement, so that's exactly what happens, no matter what expression is inside that statement.
What you need to handle complex expressions inside local declarations is something like:
public override int VisitLocalDeclarationStatement(
    LocalDeclarationStatementSyntax node)
{
    return node.Declaration.Variables.Select(Visit).Max();
}

public override int VisitVariableDeclarator(VariableDeclaratorSyntax node)
{
    if (node.Initializer == null)
        return 0;

    return Visit(node.Initializer.Value);
}

You will also need similar code for all cases when a lambda can appear inside another expression.
This is the reason why my original NestingLevelVisitor throws an exception is DefaultVisit: this way, you can detect node kinds that you don't handle yet and you are forced to explicitly specify how to handle them (instead of defaulting everything to "return 0").


text:
Q: Python: Inverse Replace Function
I have no idea about how I explain this, but here goes...
>>> x = 'qwertyHelloWorldasdfg'
>>> x = inversereplace(x, 'HelloWorld', 'a')
>>> print x
aaaaaaHelloWorldaaaaaa

>>> y = 'qwertyHelloWorld'
>>> y = inversereplace(y, 'qwerty', '')
>>> print y
qwerty

In the function above, it replaces everything in x that is not Not the 2nd argument with the 3rd Argument.
How would I go about doing this?
If there is already a function that does this then please let me know.
Thanks in advance,
~DragonXDoom

A: This should work:
def inversereplace(text, word, repl):
    parts = text.split(word)
    return word.join(repl*len(x) for x in parts)

A: def inversereplace(s, p, q):
   s = s.split(p)
   s = map(lambda x: q * len(x), s)
   return p.join(s)


text:
Q: Sed command on Linux only matches 1, where on Solaris multiple matches are found note I'm a beginner with SED.
We make use of sed-command which looks in the output of a clearcase command and obtains the names of users with a view:
<clearcase output> | sed -n "/Development streams:/,// s/[^ ]* *Views: *\([^_ ]*\)_.*/\1/p"

(Example clearcase output:
Project:              project:xx0.0_xx0000@/xxxx/xxxxx_xxxxxxxx0
Project's mastership: XXXXXXXXX@/xxxx/xxxxx_xxxxxxxx0
Project folder:       folder:XX0.0@/xxxx/xxxxx_xxxxxxxx0 (RootFolder/Xxxxxxxx/XX0.0)
Modifiable components:component:00000000000@/xxxx/xxxxxx_xxxxxxxx0
                      component:xxxxxxx_xxxxxxx@/xxxx/xxxxxx_xxxxxxxx0
                      component:xxxxxxxxxxxxxx_x@/xxxx/xxxxxx_xxxxxxxx0
                      component:xxxxx@/xxxx/xxxxxx_xxxxxxxx0
                      component:xxxxxx_xxxxxxxxxxx@/xxxx/xxxxxx_xxxxxxxx0

Integration stream:   stream:xx0.0_xx0000_integration@/xxxx/xxxxx_xxxxxxxx0 (FI: nemelis)
Integration views:    olduser_xx0.0_xx0000_int - Properties: dynamic ucmview readwrite nshareable_dos
                      nemelis_xx0.0_xx0000_int - Properties: dynamic ucmview readwrite nshareable_dos
                      otheruser_xx0.0_xx0000_int - Properties: dynamic ucmview readwrite nshareable_dos

Development streams:  stream:nemelis_xx0.0_xx0000@/xxxx/xxxxx_xxxxxxxx0 [unlocked] - No rebase or delivery is pending.
                       Views:nemelis_xx0.0_xx0000
                      stream:otheruser_xx0.0_xx0000_streamidentifier@/xxxx/xxxxx_xxxxxxxx0 [unlocked] - No rebase or delivery is pending.
                       Views:otheruser_xx0.0_xx0000_streamidentifier

)
On Solaris it will output:
nemelis
otheruser
But on (Redhat-)Linux only the first name is given.
(Note: I've looked on Stackoverflow and found comments that Sed is always greedy on Posix / Gnu and that Perl should be used (see Non greedy regex matching in sed?). Thus I've tried to fix it with Perl, but than I ran into a forrest of problems with the p at the end, using "//", "|", missing operator before < token >, etcetera, hence my post here)

A: Not sure what you're trying to achieve by specifying the address as //.  You probably imply that it should be end of file or a blank line.  Use $ as the address in the former case, and /^$/ in the latter.
The following might work for you:
sed -n "/Development streams:/,$ s/[^ ]* *Views: *\([^_ ]*\)_.*/\1/p"

From the manual:

$
 This address matches the last line of the last file of input, or
 the last line of each file when the `-i' or `-s' options are
 specified.


text:
Q: VS2013 ASP.NET Could not load type '[solution].[application]' Probably heard of it before, well I can't fix it. I am trying to have a website with one .aspx page, the rest is build in html and php. php is used as a 'master' page. the .aspx page is completely separate from the rest of the site, it only uses it's stylesheet,fonts and images.
Steps to this problem:

*

*Create ASP.NET Empty Web Application

*Add a few buttons, textboxes etc.. edit some stuff in the main.aspx.cs

*Right click on Solution, Publish to local folder

*Upload it to your hosting website and go to ~.com/main.aspx

*Getting This Error message:
Could not load type 'Vergelijkcuracao.students'.
Line1: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="students.aspx.cs"  Inherits="Vergelijkcuracao.students" %>

Things I've tried:
This article: Debug has stopped, local web server is off.
 The aspx.cs is after publishing indeed NOT in the saved directory, de bin folder is present but there is no aspx.cs ether. Manually dropping the aspx.cs on the server doesn't fix the problem.
Same article also suggests to check the output path: it is set to bin\
How do I correctly publish it to the hosts server? In Debug AND on a IIS local Web Site it works...
When I Choose a different way: Instead of New Project:

*

*Choose Open Website (because I already made a site in html)

*Browse to the directory, and open it

*Add new item: Web Forms

*Design this page with the stylesheet, make it like I want it

*Also include AJAX Toolkit for 2 SliderExtender's

*Works perfectly fine in Compile mode AND in IIS local Web server.

*Upload to Server, getting this error:
Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies.
Line 3:  <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="AjaxControlToolkit" %>

For more info on this error go to my previous article, still no solution for it. Showing Web.Config there aswell. Strange part: In my last solution, the aspx.cs is present in published directory...

A: So easy yet so hard to find:
As I was saying, on a local IIS Web Site it was working, so I found it very strange to mess with web.config. It works locally, why not on a hosting Website:
Solution: Go to your hosting control panel, in my case to the application tab, select the folder of your website and click 'Convert Folder to Application'.
Pretty obvious now you think of it, In the IIS manager you do exactly the same, I thought that the hosting website would do it automatically.
This Also helped for the Other topic Gives the same answer btw, still a bit strange that it works without a aspx.cs located on the server...
Hosting: http://somee.com
Using it for testing my websites, they offer a free limited hosting (sorry purpose is not to advertise it)


text:
Q: passenger_wsgi.py on dreamhost to get pylons working This is what I found that in theory should work from git hub.com passenger-pylons-wsgi-example
import os, sys
sys.path.append('/home/user/test.sample.com/Helloworld')
os.environ['PYTHON_EGG_CACHE'] = '/home/user/tmp'

from paste.deploy import loadapp

def application(environ, start_response):
    environ['SCRIPT_NAME'] = environ['PATH_INFO']
    application = loadapp('config:/home/user/test.sample.com/production.ini')
    return application(environ, start_response)

Tried it on dreamhost and I get:

An error occurred importing your
  passenger_wsgi.py

I also tried the virtual environment but it didn't seem to work either.
mind you after following the instructions I have python 2.6 but no activate in the virtual directory.
Any ideas?
I also tried adding:
from fcgi import WSGIServer

and after the def application:
server = WSGIServer(application)
server.run()

But still get the same error.  I wish it was a bit more descriptive so I could debug the passenger_wsgi

A: Finally found my answer:
import os, sys
INTERP = "/home/user/local/bin/python"
if sys.executable != INTERP: os.execl(INTERP, INTERP, *sys.argv)
sys.path.append('/home/user/test.sample.com/Helloworld')
os.environ['PYTHON_EGG_CACHE'] = '/home/user/tmp'

from paste.deploy import loadapp

def application(environ, start_response):
    environ['SCRIPT_NAME'] = environ['PATH_INFO']
    application = loadapp('config:/home/denat/test.sample.com/production.ini')
    return application(environ, start_response)

The difference here is that the virtual environment was setup with pylons but wasn't using it.  From the wiki on dreamhost I needed to add the following lines:
INTERP = "/home/user/local/bin/python"
if sys.executable != INTERP: os.execl(INTERP, INTERP, *sys.argv)

I now have a working pylons app! Yay!
I know others have been looking for this so I hope this helps them.


text:
Q: Datos repetidos al recorrer un array y mostrarlos en una lista Tengo el siguiente código: (también disponible en Codepen)

const agregar=document.querySelector('#agregar')
const inputAgregar=document.querySelector('#inputAgregar')
const listaUl=document.querySelector('#listaUl')

var datosArray=[]

agregar.addEventListener('click', function() {
  if (inputAgregar.value=='') {
    alert('Esta vacio')
    inputAgregar.focus()
  } else {
    datosArray.push(inputAgregar.value)
    inputAgregar.value=''
    inputAgregar.focus()
    mostrar(datosArray)
  }
})

function mostrar(datosArray) {
  for( i of datosArray) {
    var listaLi=document.createElement('li')
    listaUl.appendChild(listaLi)
    listaLi.innerText=datosArray
    console.log(datosArray)
  }
}
<input type="text" id="inputAgregar">

  <button id="agregar">Agregar</button>

¿Por qué me salen los datos repetidos al recorrer un array y mostrarlos en una lista en JavaScript?

A: Tu código tiene varios detalles:

*

*El primero es que para evitar errores y por buenas prácticas debe ir ; al final de cada sentencia.

*El segundo detalle es que tus variables tienen el mismo nombre de id, muchos navegadores usan el id como una variable global por lo que al final puede salir error al querer crear una constante con ese mismo nombre.

*Por último tu error está, en que estás recorriendo el array y agregando todo el array a cada li  en vez de cada elemento del array y tampoco estás limpiando el elemento ul para volver a agregar todos de nuevo cada vez que se llama al método mostrar.

const agregarVar = document.querySelector('#agregar');
const inputAgregarVar = document.querySelector('#inputAgregar');
const listaUlVar = document.querySelector('#listaUl');

var datosArray = [];

agregarVar.addEventListener('click', function() {
  if (inputAgregarVar.value == '') {
    alert('Esta vacio');
    inputAgregar.focus();
  } else {
    datosArray.push(inputAgregarVar.value)
    inputAgregarVar.value = '';
    inputAgregarVar.focus();

    mostrar(datosArray);

  }
});

function mostrar(datosArray) {
  listaUlVar.innerHTML = '';
  for (elemento of datosArray) {
    var listaLi = document.createElement('li');
    listaUlVar.appendChild(listaLi);
    listaLi.innerText = elemento;
    console.log(elemento);

  }

}
<input type="text" id="inputAgregar">

  <button id="agregar">Agregar</button>


text:
Q: How to list partition in a dialog menu? Is there any way to allow the user to select a partition from dialog's menu (--menu) selection feature? If so, how do you do it?
Of course, this does not work:
dialog --menu "Select a partition" 0 0 0 $(fdisk -l)

A: Your dialog should be fine, so the question is "How to print partititions?"
Instead of fdisk, I'd use lsblk, which has cleaner output and can be run by unprivileged user.
But lsblk is still printing too much, we can limit it using --output to include only the information we're interested. Add -n to omit printing header.
lsblk -n --output TYPE,KNAME

Then use awk to filter only devices where TYPE is part and print a counter instead:
lsblk -n --output TYPE,KNAME | awk '$1=="part"{print i++,$2}'

So in total, something like this should work:
dialog --menu "Select partition :" 20 40 4 \
  $(lsblk -n --output TYPE,KNAME | awk '$1=="part"{print i++,$2}')


text:
Q: Reading and modifying special characters in VB.Net I'm trying to read in a set of files using VB.Net (latest) that are using extended special characters as delimiters for data such as the upside down letter tack (Unicode: U+02D4) and the Z with a u on top "Ž" (Unicode: U+017D), replacing certain characters that shouldn't be there (such as :), and then rewriting the data back to the original file.
The problem I've ran into is that using IO.File.ReadAllLines using UTF8 doesn't recognize the Ž character especially.  I need either that character to be present in the file or the upside down letter tack to be present, as these represent delimiters in the files I'm interpreting.  Thank you in advance for any help!
Edit: Also, I'm not being paid to write this program.  I'm a data entry employee (still) and I'm trying to make life easier here at work. But I am looking to try to transition into programming.
Here's some of the code I'm using:
    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles RemoveDelimiters.Click
            files = IO.Directory.GetFiles(recdirectory.Text)
            If (IsNothing(files)) Then
                MsgBox("Please select a directory before attempting to parse files!")
            Else
                For Each file As String In files
                    Dim extension As String = System.IO.Path.GetExtension(file)
                    If (extension <> ".exe" And extension <> ".bat" And extension <> ".txt" And extension <> ".0") Then
                        'Dim text As String = IO.File.ReadAllText(file)
                        Dim text As String = IO.File.ReadAllText(file, System.Text.Encoding.UTF8)
                        Dim stext
                        stext = Microsoft.VisualBasic.Left(text, 300)
                        text = text.Replace(":", "")
                        text = text.Replace("`", "")
                        text = text.Replace("P*!GS*IA*FDE*", "P*:!GS*IA*FDE*")
                        'For Atkore files
                        'MsgBox(stext)
                        'text = text.Replace(ChrW(65533), ChrW(724))
                        'text = text.Replace(ChrW(65533), ChrW(381))
                        If (text.IndexOf("?") > -1) Then
                            MsgBox("found ? in file: " & file)
                        End If
                        If (text.IndexOf("P*:!GS*IA*FDE*") < 0) Then
                            If (text.IndexOf("GS*IA*FDE*") > -1) Then
                                text = text.Insert(text.IndexOf("GS*IA*FDE*") - 1, ":")
                            End If
                            If (text.IndexOf("GS*IM*FDE*") > -1) Then
                                text = text.Insert(text.IndexOf("GS*IM*FDE*") - 1, ":")
                            End If
                            If (text.IndexOf("GS*IM*FDE*") < 0 And text.IndexOf("GS*IA*FDE*") < 0) Then
                                MsgBox("Header not found for file: " & vbCrLf & file)
                            End If
                        End If
                        IO.File.WriteAllText(file, text, System.Text.Encoding.UTF8)
                    End If
                Next
                MsgBox("The operation has been completed!")
            End If
        End Sub


text:
Q: apostrophes and possession So I was taught that I should use apostrophes when something possesses something else, but I'm not sure about the use of it's in the following situation:

...and they found their way to a castle.  It's walls were made of pure gold.

My question is, should I use It's because the apostrophe means that the castle has possession of the wall, or should I not because it's is generally understood to be a concatenation of "it is"?  Or perhaps I should use Its' walls?

A: "It's" is a contraction of "it is" ("it's about time") or "it has" ("it's been two years"). "Its" Is the possessive (belonging to it).
Beware of simple rules. In English, if it's simple, it's probably incomplete.

A: I wouldn't ponder too much about the fine point on the possessive pronoun used for the castle's wall.
This is what I mean:
I decided not to buy that house after I discovered its roof leaked like a sieve.
I just stated the house's roof leaked; you have another way of stating something being part of something else, that is by way of using the preposition of:
I decided not to buy that house after I discovered the roof of the house leaked like a sieve.
Also, keshlam has a very important point: [it's] does not denote possession, in this case possessive pronoun that should be used there is "its"
Remember this example always:
It's a wise dog that scratches its own fleas!
I learned that from Strunk & White many many years ago.


text:
Q: Eclipse IDE Screen Recording Using XBox Game Bar on Windows 10 Using Eclipse IDE means many modals windows will appear (classes creator, preferences, ...).
When I use XBox Game Bar, only Eclipse main window is recorded, the rest is invisible.
Same applies to Notepad ++ (e.g View -> Summary).
Is there a way to include everything related to Eclipse in the recording?


text:
Q: Return row which have only single value - MySQL
Hello all,
I have multiple rows with same APP_UID value but they might have different IS_DELAYED value ( YES/NO ).
I want if all the rows for a given APP_UID contains IS_DELAYED set to YES then return APP_UID and another derived/new column COMPLETED_ON_TIME set as TRUE else if any one row for a given APP_UID contains IS_DELAYED as NO return APP_UID with COMPLETED_ON_TIME column as FALSE

A: This works because TRUE > FALSE so the GROUP BY, will give you the right answer
i added another row, so that you can see the better, there are two APP_UID

CREATE TABLE table1 (
  `APP_UID` VARCHAR(32),
  `TAS_UID` VARCHAR(32),
  `DEL_FINISR_DATE` VARCHAR(19),
  `DEL_TASX_DUE_DATE` VARCHAR(19),
  `IS_DELAYED` VARCHAR(3)
);

INSERT INTO table1
  (`APP_UID`, `TAS_UID`, `DEL_FINISR_DATE`, `DEL_TASX_DUE_DATE`, `IS_DELAYED`)
VALUES
  ('7843186355f2feef3785b24027357425', '2187105555f2d16842de705093498513', '2020-08-09    19:49:15', '2020-08-07  12:41:00', 'YES'),
  ('7843186355f2feef3785b24027357425', '4687454845f2d16841e8b94080324338', '2020-08-09    12:42:05', '2020-08-10  17:00:00', 'NO'),
  ('7843186355f2feef3785b24027357425', '5835200885f2d1683e38d34012502360', '2020-08-09    19:49:54', '2020-08-10  17:00:00', 'NO'),
  ('7843186355f2feef3785k24027357425', '5835200885f2d1683e38d34012502360', '2020-08-09    19:49:54', '2020-08-10  17:00:00', 'NO');

SELECT `APP_UID`, MAX(CASE WHEN `IS_DELAYED` = 'YES' THEN 'TRUE'
WHEN `IS_DELAYED` = 'NO' THEN 'FALSE'
END) COMPLETED_ON_TIME
FROM table1
GROUP BY `APP_UID`

APP_UID                          | COMPLETED_ON_TIME
:------------------------------- | :----------------
7843186355f2feef3785b24027357425 | TRUE
7843186355f2feef3785k24027357425 | FALSE

db<>fiddle here

A: The next approach can be used in this case:
SELECT
    `APP_UID`,
    IF (
        GROUP_CONCAT(DISTINCT `IS_DELAYED` ORDER BY `IS_DELAYED`) = 'YES', -- 'YES' , 'NO' or 'NO,YES' result possible
        'TRUE',
        'FALSE'
    ) AS `COMPLETED_ON_TIME`
FROM `TBL`
GROUP BY `APP_UID`;

db<>fiddle


text:
Q: Get 'highestCommittedUSN' attribute of a Domain Controller via LDAP I am currently working on a PHP script that will be polling Active Directory to pick out modified objects (people/users), via LDAP.
I'm able to filter on uSNChanged when I have the value, like so:
$previousUsn = '1234';
$ldapCon = ldap_connect('ldap-host');
$ldapBind = ldap_bind($ldapCon, 'ldap-user', 'ldap-password');
$sr = ldap_search($ldapCon, "ou=Users,dc=foo", "uSNChanged >= $previousUsn");

According to this, I should be able to retrieve a highestCommittedUSN attribute that  could be used for the initial run of the script. I've been looking around to find out how this can be done using PHP & LDAP, but to no avail.
Alternatively, feel free to suggest completely different methods of retrieving changes in AD.

A: ldap_read(...) seems to do the trick:
function getHighestCommittedUsn() {
    ldap_bind(...);
    $sr = ldap_read($ldapCon, null, "(highestcommittedusn=*)", array("highestcommittedusn"));
    $rs = ldap_get_entries($ldapCon, $sr);

    return $rs[0]["highestcommittedusn"][0];
}

A: Try setting the search base (second argument) in your ldap_search call to "". That attribute is on a pseudo object called RootDSE.

A: Perhaps if the biffins function hasn't been initialised correctly? Hmmm try changing the variable type of c_willygham


text:
Q: ps2pdf produces unreadable text with gnuplot epslatex terminal I'm using the gnuplot epslatex terminal to generate LaTeX files which I then convert to .pdf files using latex→dvips→ps2pdf. The .ps file produced by dvips is fine (the first image). However, once I run ps2pdf on the file, it garbles the text (second image). What could be causing this issue?

The gnuplot code used to generate the latex file looks like this:
reset

set terminal epslatex size 5.0,3.5 standalone header "\\usepackage{cmbright}\n" color colortext
set output '$0.tex'

# Line styles
set border linewidth 2
set style line 1 linecolor rgb '#FF0000' linetype 1 linewidth 3 # red
set style line 2 linecolor rgb '#FF8080' linetype 1 linewidth 2 # ltred
set style line 3 linecolor rgb '#00FF00' linetype 1 linewidth 3 # green
set style line 4 linecolor rgb '#80FF80' linetype 1 linewidth 2 # ltgreen

# Axis labels
set xlabel '$$t$$ (sec)'
set ylabel 'Events per second'

# Axis ranges
#set yrange [0:25]
set xrange[0:100]

# Tics in latex format
set format '$$%g$$'

# Key
set key right

plot "$1" index 0 using 1:2 with lines linestyle 1 title 'Underlying Function $$S_A$$',    "$1" index 1 using 1:2 with lines linestyle 2 title '$$s_A$$ counts',    "$2" index 0 using 1:2 with lines linestyle 3 title 'Underlying Function $$S_B$$',    "$2" index 1 using 1:2 with lines linestyle 4 title '$$s_B$$ counts'

The resulting LaTeX file is converted to a .pdf with
latex -interaction=nonstopmode file.tex
dvips -o file.ps file.dvi
ps2pdf file.ps

I managed to fix the tics appearing in the .pdf by changing the tics format from set format "%g" to set format "$$%g$$", which makes me think it might be something to do with that. I tried removing all math sections from the file, but the issue did not go away. For whatever reason, gnuplot complains ("../plots/twostreams.plt", line 22: Invalid substitution $%) if I only use a single $ to initiate math blocks, which appears to be the way to do it according to this link. Incidentally, the example on that page can be converted to .pdf without any issues. The only difference that I can see is that I am using the call function of gnuplot to pass in files as parameters.
Edit: After a little further poking around, I found that changing the font to another font I'm using (the libertine package) ended up producing plots as expected. I've not tried anything new, but I am on a new system, and the cmbright font still does not render correctly.


text:
Q: Looping through json object from a checkbox loop I have a json object thats being loaded through a checkbox in an ng-repeat. It lists possible services and I'm trying to get access to the ones that have been checked when I submit the form.
I'm loading the checkbox through:
<label style="margin-right:10px" ng-repeat="item in dsServces">
    <input
        type="checkbox"
        name="selectedFruits"
        value="{{item.DefaultServiceID}}"
        ng-model="expense.dsService[item.DefaultServiceName]"
    > {{item.DefaultServiceName}}
</label>

I can see the expense is being built by testing with:
{{ expense.dsService }}

returns (when a couple are selected)
{"Email":true,"Backups":true}

But I can't work out how to loop through so it says just the service name so I can add them against the customer.
In the back end I have:
$scope.expense = {
    tags: []
};

And on the submit:
 angular.forEach($scope.expense, function(item) {
    console.log(item);
});

Which spits out  Object {Email: true, Backups: true} but I can't work out to have a loop where it just returns which ever objects are true.
My main aim is to have something like
angular.forEach(forloop) {
    //service.item should be like 'Email' whatever the item.DefaultServiceName is
    // the loop should be all items that are checked
    addService(service.item);
});

A: If I am understanding properly, you want to push the key values of the object into an array. If that is the case, just make a little change to your forEach()
Like so:
// The first parameter is what you want to loop through
// Second is the iterator, you can separate out the key and values here
// The third is the context, since I put the array we want to push to in here
// we just need to call `this.push()` within the iterator
angular.forEach($scope.expense, function(value, key) {
  this.push(key);
}, $scope.expense.tags);

Let me know if this helps.


text:
Q: Rank values from table based on temporal sequences of values I have a table similar to this one, representing which drivers were driving different cars at certain times.
CAR_ID    DRIVER_ID    DT
  10          A      10:00
  10          A      12:00
  10          A      14:00
  10          B      16:00
  10          B      17:00
  10          B      20:00
  10          A      21:00
  10          A      22:00
  20          C      15:00
  20          C      18:00

Where DT is a datetime. I'm trying to have something similar to what I would obtain using a DENSE_RANK() function but generating a new number when there is a change on the column DRIVER_ID between two drivers. This would be my expected output:
CAR_ID    DRIVER_ID    DT    RES
  10          A      10:00    1
  10          A      12:00    1
  10          A      14:00    1
  10          B      16:00    2
  10          B      17:00    2
  10          B      20:00    2
  10          A      21:00    3    #
  10          A      22:00    3    #
  20          C      15:00    4
  20          C      18:00    4

Using DENSE_RANK() OVER (PARTITION BY CAR_ID, DRIVER_ID ORDER BY DT) AS RES I get the two elements marked with a # as members of the same group as the first three rows, but I want them to be different, because of the "discontinuity" (the car was driven by another driver from 16:00 to 20:00). I can't seem to find a solution that doesn't include a loop. Is this possible?
Any help would be greatly appreciated.

A: This can be done with lag and running sum.
select t.*,sum(case when prev_driver = driver then 0 else 1 end) over(partition by id order by dt) as res
from (select t.*,lag(driver_id) over(partition by id order by dt) as prev_driver
      from tbl
     ) t

A: You need to do.a row_number partitioned by car and ordered by dt. Also you need to do a row_number partitioned by car and driver and ordered by dt. Subtracting the second of these from the first gives you a unique "segment" number - which in this case will represent the continuous period of possession that each driver had of each car.
This segment number value has no Intrinsic meaning - it is just guaranteed to be different for each segment within the partition of cars and drivers. Then use this segment number as an additional partition for whatever function you are trying to apply.
As a note, however, I couldn't work out how you got the results you've displayed for RES from the code you quote, and thus I'm not exactly sure what you are trying to achieve overall.


text:
Q: Save all files content from a directory and sub directory into a single file with Windows cmd/Powershell So, I have a folder with sub folders with files of different types (php,js,html). I would like to know if there is a command on windows powershell/cmd to save all files content of my directory into a single file. In brief, I would like to do a recursive cat > save.txt on windows.
Thank you in advance

A: Use Get-ChildItem to recursively discover any files in the folder hierarchy, then pipe those to Get-Content (for reading) and finally pipe the output from those calls to Set-Content (for writing the whole thing back to disk).
Get-ChildItem path\to\root\folder -Recurse -File |Get-Content |Set-Content path\to\save.txt

Note: Unlike cat, Get-Content reads the files as text/strings by default, so this will work well for text-encoded files (like js, php and html source files), but won't work on binary files

A: From the command prompt:
You can use the copy command with the + character to concatenate multiple files:
copy file1.txt + file2.txt save.txt.
To concatenate all files in a directory use the for command in combination with dir /b (/b means bare format, only files names)
for /f %f in ('dir *.* /b') do @type %f>>save.txt
Or recursively, using /s for directory and all subdirectories in combination with /a:-d to exclude directories in the output.
for /f %f in ('dir *.* /b /s /a:-d') do @type %f>>save.txt
Using PowerShell:
Concatenate list of files:
Get-Content .\file1.txt,.\file2.txt | Out-File Save.txt
Concatenate all files in a directory:
(Get-ChildItem -File | ForEach-Object { Get-Content $_ } ) | out-file save.txt
Concatenate all files recursively:
(Get-ChildItem -File -Recurse | ForEach-Object { Get-Content $_.FullName } ) | out-file save.txt
Note: for binary files you may want to add the /b switch to the copy command or if using PowerShell add -Raw to Get-Content


text:
Q: Paper '12mm' is not supported by 'DYMO LabelWriter DUO Label I'm working on a small project that requires printing directly to a DYMO printer using their SDK. I've made other projects before using the same method:

*

*Find DYMO

*Get .label file

*Set label variable object(s)

*Print label

However, I receive the following error from the VB.NET program when calling the label.Print() method:
Paper '12mm' is not supported by 'DYMO LabelWriter DUO Label'
I receive the error delayed, so I'm assuming that the Print() method runs in a separate thread. Therefore I'm also assuming that the error occurs in the Print() method. This method is also the only point that the Label and IPrinter objects are provided in a single method according to the list above.
This error does not make sense, as the DYMO software has successfully printed labels using the same .label template. Is there possibly an incompatibility issue with the V8.+ of the SDK/Software and this model? If so, how/where can I determine a compatible version?
Insight on the fixing the error would be greatly appreciated or even any leads on documentation of error handlers with the DYMO SDK (all I've found are old samples of how to use the SDK).


text:
Q: php syntax error when try to use phpactiverecord library I have code
ActiveRecord\Config::initialize(function($cfg) {
  $cfg->set_model_directory("models");
  $cfg->set_connections(array("development" => "mysql://root:123@localhost/server"));
}

$server = new Server;

Why I get error

[Sun Nov 04 22:11:49 2012] [error] [client 127.0.0.1] PHP Parse error:  syntax error, unexpected T_VARIABLE in Server.php on line 27

on $server = new Server;
How to escape it?

A: You have syntax error on the preceding line - you function is not finished. Try
 ActiveRecord\Config::initialize(function($cfg) {
  $cfg->set_model_directory("models");
  $cfg->set_connections(array("development" => "mysql://root:123@localhost/server"));
});

$server = new Server;

i.e. put ); on the preceding line.


text:
Q: How to sum up all values in a listbox column and display it in a textblock? How do I got about summing up the amount in the red box and display it in the textblock (yellow box)?

As you can see from the image below, I have bind my observable collection to the Listbox in order to display the data in the listbox

In addition, I have also defined the data template for the listbox.

A: You have to add another property (e.g. Sum) into your ViewModel, bind it into your TextBlock and calculate it's value every time ToDoBills collection changes.
You can use LINQ to calculate the sum:
Sum = ToDoBills.Sum(i => i.Amount);

Update
You probably already implement INotifyPropertyChanged interface on your ViewModel class, so use it to update Sum property value when collection is changed:
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    if(propertyName == "ToDoBills")
        UpdateSumValue();
}

private void UpdateSumValue()
{
     Sum = ToDoBills.Sum(i => i.Amount);
}


text:
Q: Do browsers run PHP scripts without my input? I have a PHP script that I run to update a database of mine - it is held on a remote webserver, so I make changes to that PHP script and then run it to dump the results into the database.  It works fine - except I have been noticing that the PHP script is running when I don't want it to.
That is - when I DO NOT type in the URL with the specific GET variables required for it to work, the script seems to be running anyways.  So my question is do browsers request URLs without me asking them to?
The problem is the script takes a very long time to run and it seems when the requests (from some other source) are run that it doesn't complete - which leaves my database only partially full and effectively useless.  What I have noticed, however, is that it is only the one set of tables from a specific request that I have been running that are getting "randomly" run.
EDIT:
I have a script that requires multiple variables be passed to it through GET.  I will run it at one point in the day (say 2pm) it takes a very long time to complete, almost 2 hours.  It completes fine and all is good.  Then a few hours later, WITH NO INPUT FROM ME, it runs again - with the exact same variables passed to it but does not complete.
My suspicion is that my browser is re-requesting the URL for some reason, or Google is or something, I'm just looking to see if anyone has any idea what could be causing this.
EDIT 2:
Realized I'm an idiot.  What's happening is my computer goes to sleep and when it wakes up the browser refreshes instead of using the stale data.

A: They are run without input on a browser if you:

*

*include javascript timeout to refresh/reload the page

*basically write code inside the script to call itself whether one time, a few times, or at intervals

*your browser is not "normal", due to whatever reason

*a malware on you machine grabs the url from the browser and forces the browser to call it again and again

*etc


text:
Q: Reorder PHPDoc / Symfony annotations with csfixer Is there a way with php-cs-fixer to define an order for Symfony annotations/PHPDoc ?
Here is two examples of a controller method and an entity property :
 /**
     * @Security()
     *
     * @ParamConverter()
     *
     * @Rest\Post()
     * @Rest\View()
     *
     * @param Request      $request
     * @param xxxInterface $item
     *
     * @return \FOS\RestBundle\View\View
     */
public function myAction(Request $request, xxxInterface $item)

and
/**
 * @var itemInterface
 * @ORM\ManyToOne()
 * @ORM\JoinColumn()
 * @JMS\Groups()
 * @JMS\AccessType()
 * @MyCustomAssert\Assert1
 */
protected $item;

For methods, I want to set the order to @Security, @ParamConverter, @Rest then PHPDoc and for properties, I always want @MyCustomAssert at the end.
Is this something possible with php-cs-fixer ?

A: I think it isn't possible with php-cs-fixer (https://mlocati.github.io/php-cs-fixer-configurator/?version=2.9#version:2.15 might help searching)
However the slevomat coding standard for php code sniffer includes a sniff "SlevomatCodingStandard.Commenting.DocCommentSpacing" which allows you to configure annotationsGroups
The phpcbf script can reorder your annotations using this snif.


text:
Q: What does canonical mean when used in sentence? I just heard someone said "a canonical horrible idea"
I have been googling and still unable to understand exactly what "canonical" means when not used in programming language.
Can someone explain me what "canonical" actually means?

A: canonical
adjective Also ca·non·ic.
1 pertaining  to,  established  by, or  conforming  to a canon or canons.
2 included  in  the  canon of  the   Bible.
3 authorized;   recognized;   accepted; canonical   works.
https://www.dictionary.com/browse/canonical
In short - authoritative
So, "a canonical horrible idea" would be an authoritatively horrible idea.
At least, that feels like the intent

A: As in  such a bad idea that it is one of  several bad ideas which have come up so often that they are popularized as well known bad ideas.


text:
Q: Populating a data frame from another data frame that in which some values match I have a large data frame in which specific columns and some headers match with the headers of a recently created data frame (I show both below). I want to extract data from the large data frame and populate the new one according to the matches.
The large data frame :
print(complete_df.head(2))
Unnamed: 0_x_x  #_x_x                Coin  Price_x_x  1h_x  24h_x   7d_x  \
0             NaN      1   Bitcoin  BTC  BTC    $61,700  1.7%   8.8%  25.7%
1             NaN      2  Ethereum  ETH  ETH  $1,942.39  0.9%  11.5%  26.2%

      24h Volume_x           Mkt Cap_x  Last 7 Days_x  ...  \
0  $66,511,145,853  $1,147,780,011,087            NaN  ...
1  $32,515,724,095    $223,366,485,336            NaN  ...

   Twitter Followers_y  Unnamed: 0_y_y #_y_y  Price_y_y  All-Time High Price  \
0                  NaN             NaN     1    $61,700              $61,533
1                  NaN             NaN     2  $1,942.73            $2,042.93

   Since All-Time High      All-Time High Date  Vol/Mcap Market Cap Dominance  \
0                 0.0%  Mar 13, 2021 5 minutes    0.0578               60.59%
1                -5.0%    Feb 20, 2021 21 days    0.1451               11.79%

   COIN
0   BTC
1   ETH

The recently create data frame is empty and only contained the header as shown below
print(new)

Empty DataFrame
Columns: [Time, BTC_Price_x_x, BTC_Mkt Cap_x, BTC_24h Volume_x, BTC_Contributors_x, BTC_Commits in Last 4 Weeks_x, BTC_Reddit Subscribers_x, BTC_FB Likes_x, BTC_Market Cap Dominance, ETH_Price_x_x, ETH_Mkt Cap_x,...]

Can you see how the header of the new data frame is the combination of the values contained in the last column (COIN) of the  complete_df + '_' + 'some headers of the complete_df ' data frame? For example, first header of new data frame is BTC_Price_x_x = BTC+ '_' + Price_x_x.
What I want is to populate the new data frame with its corresponding value
Time      BTC_Price_x_x  BTC_Mkt Cap_x        BTC_24h Volume_x   ...  ETH_Price_x_x ...
Index     $61,700        $1,147,780,011,087   $66,511,145,853    ...  $1,942.39     ...


text:
Q: wxt terminal on gnuplot via cygwin How can I compile gnuplot on cygwin such that it will have the wxt terminal type? I have tried adding possible dependencies such as libwx_gtk3u3.0_0,mingw64-x86_64-wxWidgets3.0, libcairo-devel, libpango1.0-devel, and mingw64-x86_64-pango1.0 while simultaneously reinstalling gnuplot, but gnuplot still says wxt is an unknown or ambiguous terminal type. Which packages do I need to install in cygwin to accomplish this? Can I accomplish this with the gnuplot package included with cygwin?
I believe the windows version of gnuplot uses wxt by default, but I wish to use gnuplot within a cygwin shell.


text:
Q: Button group/solo Center I want to center this button on PC / Mobile as a container. I tried the following on CSS and HTML.

    <button class="btn1">Jeudi 12</button>
    <button class="btn1">Dimanche 13</button>
    <button class="btn1">Jeudi 12</button>
    <button class="btn1">Dimanche 13</button>
    <button class="btn1">Jeudi 12</button>

A: Is it suitable for your needs?

.container {
  display: flex;
  justify-content: space-between;
 }

 .container2 {
  display: flex;
  justify-content: center;
 }

Space between buttons

    <button class="btn1">Jeudi 12</button>
    <button class="btn1">Dimanche 13</button>
    <button class="btn1">Jeudi 12</button>
    <button class="btn1">Dimanche 13</button>
    <button class="btn1">Jeudi 12</button>

Center aligned buttons

    <button class="btn1">Jeudi 12</button>
    <button class="btn1">Dimanche 13</button>
    <button class="btn1">Jeudi 12</button>
    <button class="btn1">Dimanche 13</button>
    <button class="btn1">Jeudi 12</button>


text:
Q: Converting a json string into a .NET Object in Xamarin I have read several other people who have had this question, and I have attempted those approaches. However, I am getting odd results I cannot pin down.
I am using http://json2csharp.com/# to build the classes I use with the convert method.
in my code I am using the following libraries
using System;
using RestSharp;
using Newtonsoft.Json;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using System.Collections.Generic;
using ZXing;
using ZXing.Mobile;

I have a method built up to take the json string from my api call and convert it into c# objects using Json.NET
public void convert(String response)
{
    Console.WriteLine("Response: " + response);
    Console.WriteLine("Check 1");
    var list = JsonConvert.DeserializeObject<List<RootObject>>(response);
    Console.WriteLine("Check 2");
    Console.WriteLine(list);
    Console.WriteLine("Check 3");
    for (int i = 0; i < list.Count; i++) // Loop with for.
    {
        Console.WriteLine("Check 4");
        Console.WriteLine("Pass: " + i);
        Console.WriteLine(list[i]);
    }
    Console.WriteLine("Check 5");
}

public class Item
{
    public string barcode { get; set; }
    public string name { get; set; }
    public string upvotes { get; set; }
    public string downvotes { get; set; }
    public string updated { get; set; }
}

public class RootObject
{
    public List<Item> items { get; set; }
}

Here is an example dataset from the API I am calling
{
  "items":[
   {
     "barcode": "12345",
     "name": "xxx",
     "upvotes": "0",
     "downvotes": "0",
     "updated": "1465103701673"
  },
  {
     "barcode": "1234",
     "name": "xxx",
     "upvotes": "0",
     "downvotes": "0",
     "updated": "1465103697375"
   },
   {
     "barcode": "123",
     "name": "xxx",
     "upvotes": "0",
     "downvotes": "0",
     "updated": "1465103688554"
   }
]}

No errors pop in the error log.
If I try adding debugging as soon as I hit the line
var list = JsonConvert.DeserializeObject<List<RootObject>>(response);

I get the message "Frame not in Module"
The code only goes as far as Check 1 and then seems to stop. Below is my Debug log from Visual Studio on what happens after I call convert.
    06-05 16:32:59.391 D/Mono    ( 3672): Assembly Ref addref PennyGeneral[0x813fcad0] -> Newtonsoft.Json[0x82201ac8]: 2
    06-05 16:32:59.391 D/Mono    ( 3672): The request to load the retargetable assembly mscorlib v2.0.5.0 was remapped to mscorlib v2.0.5.0
    06-05 16:32:59.391 D/Mono    ( 3672): Assembly Ref addref Newtonsoft.Json[0x82201ac8] -> mscorlib[0x76d8a880]: 12
    Response: {"items":[{"barcode": "12345","name": "xxx","upvotes": "0","downvotes": "0","updated": "1465103701673"},{"barcode": "1234","name": "xxx","upvotes": "0","downvotes": "0","updated": "1465103697375"},{"barcode": "123","name": "xxx","upvotes": "0","downvotes": "0","updated": "1465103688554"}]}
    06-05 16:32:59.392 I/mono-stdout( 3672): Response: {"items":[{"barcode": "12345","name": "xxx","upvotes": "0","downvotes": "0","updated": "1465103701673"},{"barcode": "1234","name": "xxx","upvotes": "0","downvotes": "0","updated": "1465103697375"},{"barcode": "123","name": "xxx","upvotes": "0","downvotes": "0","updated": "1465103688554"}]}
    Check 1
    06-05 16:32:59.393 I/mono-stdout( 3672): Check 1
    06-05 16:32:59.393 D/Mono    ( 3672): Remapped public key token of retargetable assembly System.Core from 7cec85d7bea7798e to b77a5c561934e089
    06-05 16:32:59.393 D/Mono    ( 3672): The request to load the retargetable assembly System.Core v2.0.5.0 was remapped to System.Core v2.0.5.0
    06-05 16:32:59.394 D/Mono    ( 3672): Unloading image System.Core.dll [0x85f686d0].
    06-05 16:32:59.394 D/Mono    ( 3672): Image addref System.Core[0x85f660f0] -> System.Core.dll[0x82d98df8]: 4
    06-05 16:32:59.395 D/Mono    ( 3672): Config attempting to parse: 'System.Core.dll.config'.
    06-05 16:32:59.395 D/Mono    ( 3672): Config attempting to parse: '/Users/builder/data/lanes/3236/ee215fc9/source/monodroid/builds/install/mono-armv7/etc/mono/assemblies/System.Core/System.Core.config'.
    06-05 16:32:59.395 D/Mono    ( 3672): Assembly Ref addref Newtonsoft.Json[0x82201ac8] -> System.Core[0x82df1b18]: 4
    06-05 16:32:59.427 D/Mono    ( 3672): Remapped public key token of retargetable assembly System from 7cec85d7bea7798e to b77a5c561934e089
    06-05 16:32:59.427 D/Mono    ( 3672): The request to load the retargetable assembly System v2.0.5.0 was remapped to System v2.0.5.0
    06-05 16:32:59.428 D/Mono    ( 3672): Unloading image System.dll [0x85fb77d0].
    06-05 16:32:59.428 D/Mono    ( 3672): Image addref System[0x85fb94b0] -> System.dll[0x830252a0]: 4
    06-05 16:32:59.428 D/Mono    ( 3672): Config attempting to parse: 'System.dll.config'.
    06-05 16:32:59.428 D/Mono    ( 3672): Config attempting to parse: '/Users/builder/data/lanes/3236/ee215fc9/source/monodroid/builds/install/mono-armv7/etc/mono/assemblies/System/System.config'.
    06-05 16:32:59.428 D/Mono    ( 3672): Assembly Ref addref Newtonsoft.Json[0x82201ac8] -> System[0x8302f6e0]: 4
    06-05 16:32:59.475 D/Mono    ( 3672): Remapped public key token of retargetable assembly System.Runtime.Serialization from 7cec85d7bea7798e to b77a5c561934e089
    06-05 16:32:59.475 D/Mono    ( 3672): The request to load the retargetable assembly System.Runtime.Serialization v2.0.5.0 was remapped to System.Runtime.Serialization v2.0.5.0
    06-05 16:32:59.476 D/Mono    ( 3672): Image addref System.Runtime.Serialization[0x86002d60] -> System.Runtime.Serialization.dll[0x86002098]: 1
    06-05 16:32:59.476 D/Mono    ( 3672): Assembly System.Runtime.Serialization[0x86002d60] added to domain RootDomain, ref_count=1
    06-05 16:32:59.476 D/Mono    ( 3672): AOT module 'System.Runtime.Serialization.dll.so' not found: dlopen failed: library "/data/app-lib/PennyGeneral.PennyGeneral-2/libaot-System.Runtime.Serialization.dll.so" not found
    06-05 16:32:59.477 D/Mono    ( 3672): AOT module '/Users/builder/data/lanes/3236/ee215fc9/source/monodroid/builds/install/mono-armv7/lib/mono/aot-cache/arm/System.Runtime.Serialization.dll.so' not found: dlopen failed: library "/data/app-lib/PennyGeneral.PennyGeneral-2/libaot-System.Runtime.Serialization.dll.so" not found
    06-05 16:32:59.477 D/Mono    ( 3672): Unloading image data-0x8602f008 [0x86002f78].
    06-05 16:32:59.478 D/Mono    ( 3672): Config attempting to parse: 'System.Runtime.Serialization.dll.config'.
    06-05 16:32:59.478 D/Mono    ( 3672): Config attempting to parse: '/Users/builder/data/lanes/3236/ee215fc9/source/monodroid/builds/install/mono-armv7/etc/mono/assemblies/System.Runtime.Serialization/System.Runtime.Serialization.config'.
    06-05 16:32:59.478 D/Mono    ( 3672): Assembly Ref addref Newtonsoft.Json[0x82201ac8] -> System.Runtime.Serialization[0x86002d60]: 2
    Loaded assembly: System.Runtime.Serialization.dll [External]
    06-05 16:32:59.478 D/Mono    ( 3672): Assembly Ref addref System.Runtime.Serialization[0x86002d60] -> mscorlib[0x76d8a880]: 13
    06-05 16:32:59.500 D/Mono    ( 3672): Assembly Ref addref System.Core[0x82df1b18] -> System[0x8302f6e0]: 5
    Loaded assembly: Anonymously Hosted DynamicMethods Assembly [External]
    Thread finished: <Thread Pool> #5
    06-05 16:33:09.774 D/Mono    ( 3672): [0x834fab30] worker finishing
    06-05 16:33:09.781 D/dalvikvm( 3672): threadid=16: bye!
    The thread 'Unknown' (0x5) has exited with code 0 (0x0).
    Thread finished: <Thread Pool> #7
    06-05 16:33:37.391 D/Mono    ( 3672): [0x85274538] worker finishing
    06-05 16:33:37.398 D/dalvikvm( 3672): threadid=20: bye!
    The thread 'Unknown' (0x7) has exited with code 0 (0x0).
    Thread finished: <Thread Pool> #8
    06-05 16:33:53.046 D/Mono    ( 3672): [0x851f1b60] worker finishing
    06-05 16:33:53.052 D/dalvikvm( 3672): threadid=19: bye!
    The thread 'Unknown' (0x8) has exited with code 0 (0x0).
    Thread finished: <Thread Pool> #3
    06-05 16:33:59.536 D/dalvikvm( 3672): threadid=15: bye!
    The thread 'Unknown' (0x3) has exited with code 0 (0x0).
    Thread started: <Thread Pool> #10
    Thread started: <Thread Pool> #11
    06-05 16:34:39.062 D/dalvikvm( 3672): threadid=15: interp stack at 0x83950000
    06-05 16:34:39.064 D/dalvikvm( 3672): threadid=16: interp stack at 0x83970000
    06-05 16:34:39.065 D/Mono    ( 3672): [0x834fa728] worker starting
    Thread finished: <Thread Pool> #11
    06-05 16:34:59.711 D/Mono    ( 3672): [0x834fa728] worker finishing
    06-05 16:34:59.717 D/dalvikvm( 3672): threadid=16: bye!
    The thread 'Unknown' (0xb) has exited with code 0 (0x0).

A: Your root object stores the collection of items. Change it to...
var root = JsonConvert.DeserializeObject<RootObject>(response);
var list = root.items;


text:
Q: Snowflake Parent Child Hierarchy Weighting I have a table with three columns illustrating a weighted parent child hierarchy relationship e.g.
Table

parent
child
weight

a
b
0.4

a
c
0.6

b
d
0.2

b
e
0.2

b
f
0.6

The hierarchy dictates that b and c are components of a, with weighting 0.4 and 0.6 respectively.
Child b also has subcomponents d, e, and f with weights 0.2, 0.2, and 0.6.
I'm able to illustrate the hierarchy using a connect by query mapping parent = prior child.
Resulting Table

hierarchy
parent
child
weight

a
a
b
0.4

a
a
c
0.6

a to b
b
d
0.2

a to b
b
e
0.2

a to b
b
f
0.6

I need to supplement this table with an additional column showing the true weight of the lowest level child c,d,e,f to the highest parent a.

parent
child
scaled_weight

a
c
0.6

a
d
0.08

a
e
0.08

a
f
0.24

What's the best way to map the parent to the lowest level children with their "true" weights?

A: So we start with how to find the "true parents" which is the rows where the parent is not in the child column, thus a LEFT JOIN that matches nothing:
with data(parent, child, weight) as (
    SELECT * FROM VALUES
        ('a','b',0.4),
        ('a','c',0.6),
        ('b','d',0.2),
        ('b','e',0.2),
        ('b','f',0.6)
)
select a.*
from data as a
left join data as b
    on a.parent = b.child
where b.child is null;

gives:

PARENT
CHILD
WEIGHT

a
b
0.4

a
c
0.6

now, we can put this into a recursive CTE so solve for us.
select a.parent,
    a.child,
    a.weight,
    array_construct(a.parent, a.child) as path
from data as a
left join data as b
    on a.parent = b.child
where b.child is null

union all

select r.parent
    ,d.child
    ,d.weight * r.weight as weight
    ,array_append(r.path, d.child) as path
from rec_cte as r
join data as d
    on r.child = d.parent

which gives:

PARENT
CHILD
WEIGHT
PATH

a
b
0.4
[   "a",   "b" ]

a
c
0.6
[   "a",   "c" ]

a
d
0.8
[   "a",   "b",   "d" ]

a
e
0.8
[   "a",   "b",   "e" ]

a
f
2.4
[   "a",   "b",   "f" ]

now it seems you also want the first row to not show as it's part of the a,b,d, a,b,e, and a,b,f rows
which presently, I am stumped on. so will stop here for now..
Common parent removal:
with recursive rec_cte as (
    select a.parent,
        a.child,
        a.weight,
        array_construct(a.parent, a.child) as path,
        null::TEXT as del_p,
        null::TEXT as del_c
    from data as a
    left join data as b
        on a.parent = b.child
    where b.child is null

    union all

    select r.parent
        ,d.child
        ,d.weight * r.weight as weight
        ,array_append(r.path, d.child) as path
        ,r.parent as dep_p
        ,d.parent as del_c
    from rec_cte as r
    join data as d
        on r.child = d.parent
), to_deletes as (
    select r.del_p, r.del_c, r.del_p is null, r.del_p = '', r.del_p is not null
    from rec_cte as r
)
select
    r.parent,
    r.child,
    r.weight,
    r.path
from rec_cte as r
left join to_deletes as d
    on r.parent = d.del_p and r.child = d.del_c
where d.del_p is null

gives:

PARENT
CHILD
WEIGHT
PATH

a
c
0.6
[   "a",   "c" ]

a
d
0.8
[   "a",   "b",   "d" ]

a
e
0.8
[   "a",   "b",   "e" ]

a
f
2.4
[   "a",   "b",   "f" ]


text:
Q: Multithreading in rabbitmq-library for java When i run this code:
public static void main(String[] args) throws IOException, TimeoutException {
        MainRabbit main = new MainRabbit();

        for (int i = 0; i < 5; i++) {
            Connection connection = main.createConnection();
            Channel channel = connection.createChannel();
            channel.basicConsume("queueName", new CustomConsumer());
        }

    }

    private ExecutorService es = Executors.newFixedThreadPool(2);

    private ConnectionFactory connectionFactory = createConnectionFactory();

    private ConnectionFactory createConnectionFactory() {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost");
        return connectionFactory;
    }

    private Connection createConnection() throws IOException, TimeoutException {
        return connectionFactory.newConnection(es);
    }

I see that I have 2 separate threads for each tcp-connection to the rabbitmq. In the screenshot below, this is the AMQP Connection thread and the thread from the pool called "pool-2".

Additionally, because I specified the value 2 in the ExecutorsService, then 2 more threads were created in the pool called "pool-1".

*

*Where did "pool-2" come from?

*What does es mean in connectionFactory.newConnection(es)?
JavaDocs says "executor thread execution service for consumers on the connection".
Does this mean that all consumers of this tcp-connection will work in a maximum of 2 threads in my example?

*How to start processing incoming messages in several threads at once, so that, for example, 10 different messages from the same queue are processed in parallel?

A: Each connection in RabbitMQ (or rather in AMQP) is treated as a separate, bidirection stream of data. In thread-based languages is normal to associate a connection with a thread as well as not sharing threads among channels (that are "lightwight connections")
docs from cloudamqp, well established rabbitmq-as-a-service provider
The main reason is to have independent workers for upstream and downstream message flows. This will prevent lagging on heavy-load conditions and backpressure mechanism will keep to works, since the client will continue to exchange ack messages
In general, however, you don't really need to set up multiple connections per client. Let your library do the job. You could be concerned because consumed messages trigger long running job, so multiplex them through a thread pool when they are received, each thread in the pool will process a message


text:
Q: Different approaches to evaluate this determinant How to evaluate this determinant $$\det\begin{bmatrix}
a& b&b &\cdots&b\\ c  &d &0&\cdots&0\\c&0&d&\ddots&\vdots\\\vdots &\vdots&\ddots&\ddots& 0\\c&0&\cdots&0&d
\end{bmatrix}?$$
I am looking for the different approaches.

A: Your (upper) arrowhead matrix can be decomposed as follows:
$$\begin{pmatrix}a&b&b&\cdots&b\\c&d&0&\cdots&0\\c&0&d&\ddots&\vdots\\\vdots &\vdots&\ddots&\ddots&0\\c&0&\cdots&0&d\end{pmatrix}=\color{red}{\begin{pmatrix}a-b-c&&&&\\&d&&&\\&&d&&\\&&&\ddots&\\&&&&d\end{pmatrix}}+\color{blue}{\begin{pmatrix}1&c\\&c\\&c\\&\vdots\\&c\end{pmatrix}}\cdot\color{magenta}{\begin{pmatrix}b&b&b&\cdots&b\\1&&&&\end{pmatrix}}$$
Now, one can then use the Sherman-Morrison-Woodbury formula for determinants:
$$\det(\color{red}{\mathbf A}+\mathbf{\color{blue}{U}\color{magenta}{V^\top}}) = \det(\mathbf I + \color{magenta}{\mathbf V^\top}\color{red}{\mathbf A}^{-1}\color{blue}{\mathbf U})\det(\color{red}{\mathbf A})$$
to yield
$$\begin{align*}
&\begin{vmatrix}a&b&b&\cdots&b\\c&d&0&\cdots&0\\c&0&d&\ddots&\vdots\\\vdots &\vdots&\ddots&\ddots&0\\c&0&\cdots&0&d\end{vmatrix}\\
&=\det\left(\mathbf I+\color{magenta}{\begin{pmatrix}b&b&\cdots&b\\1&&&\end{pmatrix}}\color{red}{\begin{pmatrix}\frac1{a-b-c}&&&\\&\frac1d&&\\&&\ddots&\\&&&\frac1d\end{pmatrix}}\color{blue}{\begin{pmatrix}1&c\\&c\\&\vdots\\&c\end{pmatrix}}\right)\color{red}{(a-b-c)d^{n-1}}\\
&=\det\left(\mathbf I+\color{magenta}{\begin{pmatrix}b&b&\cdots&b\\1&&&\end{pmatrix}}\color{orange}{\begin{pmatrix}\frac1{a-b-c}&\frac{c}{a-b-c}\\&\frac{c}{d}\\&\vdots\\&\frac{c}{d}\end{pmatrix}}\right)\color{red}{(a-b-c)d^{n-1}}\\
&=\det\left(\mathbf I+\color{green}{\begin{pmatrix}\frac{b}{a-b-c}&bc\left(\frac1{a-b-c}+\frac{n-1}{d}\right)\\\frac1{a-b-c}&\frac{c}{a-b-c}\end{pmatrix}}\right)\color{red}{(a-b-c)d^{n-1}}\\
&=\frac{bc(1-n)+ad}{d(a-b-c)}(a-b-c)d^{n-1}\\
&=(bc(1-n)+ad)d^{n-2}
\end{align*}$$

A: If the dimension of the matrix is $2$, it's only $ad-bc$. If it's $\geq 3$, and $d=0$ the determinant is $0$. If $d\neq 0$, do $C_1\leftarrow C_1-\frac cdC_j$, $2\leq j\leq n$. The first column becomes $\pmatrix{a-(n-1)\frac{bc}d\\\ 0\\\ \vdots\\\ 0}$, and the determinant is $d^{n-1}\left(a-(n-1)\frac{bc}d\right)=d^{n-2}(ad-(n-1)bc)$.

A: Let $A_n=(a_{ij})$ be the $n\times n$ matrix with
$$
a_{ij}=\left\{\matrix{a&i=j=1\\b&i=1\ne j\\c&i\ne1=j\\d&i=j\ne1\\0&\text{otherwise}}\right.
$$
and $\Delta_n=\det A_n$. Then ($\Delta_1=a$ according to my definition above, which may differ from your implicit definition), $\Delta_2=ad-bc$ and for $n\ge2$,
$$
\Delta_{n+1}=d\,\Delta_n-bc\,d^{n-1}=\left(\Delta_n-bcd^{n-2}\right)d
$$
expanding on the bottom row (or equivalently the rightmost column, but with the matrix below transposed and with $c$ in stead of $b$).
This is because the $n\times n$ below has determinant
$$\det\begin{bmatrix}
b&b &\cdots&b&b\\
d &0&\cdots&0&0\\
0&d&\ddots&\vdots&0\\
\vdots&\ddots&\ddots&0&0\\
0&\cdots&0&d&0
\end{bmatrix}
= (-1)^{n-1}bd^{n-1}\,,
$$
and is multiplied by $(-1)^nc$ from $a_{n+1,1}=c$,
giving the second term above. Thus
$$
\eqalign{
\frac{\Delta_{n+1}}{d^{n-1}}&=
\frac{\Delta_{n}  }{d^{n-2}}-bc
\quad
\text{and}
\quad
\frac{\Delta_1}{d^{-1}}=ad
\quad
\implies
\\\\
\frac{\Delta_{n}}{d^{n-2}}&=
ad-(n-1)bc
\qquad
\implies
\\\\
\Delta_{n}&=\big[ad-(n-1)bc\big]d^{n-2}
}
$$
for $n\ge1$ by induction.


text:
Q: Portable browser as default browser in Windows 8.1 Is there any way to make a portable browser the default browser of Windows 8.1? Apparently the registry tricks of Windows 7 are not working in Windows 8 and 8.1!

A: You can make so without hassling all those techy registry tricks.
Most modern browsers have ability to make it default.
For example for Google Chrome go to

Settings -> Default browser --> Make Google Chrome the default browser

and it will do everything for you.
Actually, my case is Windows 7. And it's annoying to be unable to open links in a default browser, when your browsers are portable.
When i fix my Windows 8.1, i can tell about it, too. May be i am wrong about Windows 8(.1). But it shouldn't differ too much, may be some latest portable browser of choice version could help.
If it won't just try several browsers, and at least one would fit.
All browser's developers couldn't be wrong about not been able to set several registry values according to their product.


text:
Q: BootstrapVue b-form-group label binding, label not showing New to Vue.js, cannot get form group label to show in component. Am trying to create a component to save myself some time as will need to use this a lot of times.
Thanks
 <ZComplianceField :mylabel="foo" :property="user.applicationForm.rating" :isEditing="isEditing"></ZComplianceField>

<template>
  <b-form-group
    label-cols="4"
    label-cols-lg="2"
    label-size="sm"

  >
  <template slot="label">{{ mylabel }}</template>
    <b-form-input
      size="sm"
      type="text"
      v-model="property"
      :disabled="!isEditing"
      :class="{view: !isEditing}"
    ></b-form-input>
  </b-form-group>
</template>

<script>
export default {
  name: "ZComplianceField",

  props: {
    mylabel: {
      required: true
    },
    property: {
      required: true
    },
    isEditing: {
      required: true
    }
  }
};
</script>

'''

A: The problem is that you´re binding your value <ZComplianceField :mylabel="foo"></ZComplianceField>.
Notice that you have a : in-front of mylabel. The : is shorthand for v-bind, which binds a data property.
What you want is to remove the :, so that your foo is treated a string.
Your other option is to define foo in your data and set it to a string.
{
  ...
  data() {
    return {
      foo: "Some Label"
    }
  }
  ...
}


text:
Q: Поместить список файлов в архив как список файлов в папке поместить в архив?, не саму папку с содержимым, а именно содержимое засунуть в архив
DIRECTORY = f'{g}'
    result = os.listdir(DIRECTORY)

    patoolib.create_archive(f"{file_name_without_extension}.rar", (f"{g}/{result}",))

выдаёт ошибку

patoolib.util.PatoolError: file `10-lines/['белый цвет', 'красный цвет', 'синий цвет']' was not found

A: предварительно нужно установить библиотеку pip install zipfile
import zipfile
import os
dir = os.listdir('')
archive = zipfile.ZipFile('test.zip', 'w')
for file in dir:
   archive.write(file, compress_type=zipfile.ZIP_DEFLATED)
archive.close()


text:
Q: Survival analysis: time to event I am trying to fit a model for a loan portfolio which have been acquired over several years, each of the loan has one of the several term periods (different performance window) over which the loan needs to be paid off. A few number of loans have charged off before the term expired and a few after the term.
The event is chargeoff (1) or not (0).
How should I define time to event? For chargeoffs, the time to event is Time to chargeoff. For non-chargeoffs, should the time be till the end of their respective term or end of the maximum term of all the terms? I tried former definition, and used Cox proportional hazard model in SAS, but my expect vs actual survival curves are way off. Any help is appreciated.
Thanks.


text:
Q: How to auto scroll down iframe to bottom without jquery I'm trying to scroll down an iframe (local file .html) but isn't working.
I've tried this code, but the iframe stays in the same position (the scroll bar):
<html>

<head>

<title>Untitled Document</title>

<script>
var myIframe = document.getElementById('01');
myIframe.onload = function () {
    myIframe.contentWindow.scrollTo(200, 300);
}

</SCRIPT>

</head>

<body>

<iframe id="01" src="Content.html" name="iframe2" width="150" heigth="200"></iframe>

</body>

</html>


text:
Q: How update orders by using woocommerce api in node js exports.UpdateOrder = (req, res) => {
  const data = {
    status: "completed"
  };
  WooCommerce.put("orders/3217", data)
    .then((response) => {
      res.json(JSON.parse(response.body));
    })
    .catch((error) => {
      console.log(error.response.data);
    });
};

getting error
TypeError: WooCommerce.put(...).then is not a function

A: Perhaps try using promisified methods such as in this example https://www.npmjs.com/package/woocommerce-api#promified-methods

Promified Methods
  Every method can be used in a promified way just adding Async to the method name. Like in:

WooCommerce.getAsync('products').then(function(result) {
  return JSON.parse(result.toJSON().body);
});


text:
Q: Getting name of parameterized class in scala using shapeless I want to get the name of a class passed as a parameter to a function using shapeless. I've tried this:
def sayMyName[T](t: T): String = Typeable[T].describe // error: class type required but T found

If T is replaced with a concrete type, there's no problem. Is it possible to make something like this work using shapeless?

A: You just need to add Typeable typeclass as context bound of your type T:
def sayMyName[T: Typeable](t: T): String = Typeable[T].describe

sayMyName("") //String

You could also explicitly declare implicit parameter:
def sayMyName[T](t: T)(implicit typeable: Typeable[T]): String = Typeable[T].describe

By adding context bound you're asking the compiler to wait with resolving Typeable
typeclass until sayMyName is called with the concrete type, not resolve it right away (which is impossible, since the real type of T is not yet known at this point).


text:
Q: Is there a way to close a specific tab on a browser? I am fairly new to Python and I am trying to close a specific tab from a browser. I have tried to close the process using the PID but my code does not seem to find the process. I am getting a FileNotFoundError When I look up on the task manager, there is no process with the PID that is in the "print".  Am I missing something?
import time
import subprocess

p = subprocess.Popen("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe http://www.youtube.com")
time.sleep(10)
print(p.pid)
subprocess.Popen(['taskkill/F/T/PID', str(p.pid)])

I am using Python3.7 on Win10.


text:
Q: Issue with the format in anytime package library("anytime")

This works well:
anytime("08/24/2014 01:28:00")
anytime("2014/08/24 01:28:00")

[1] "2014-08-24 00:28:00 NZST"

This doesn't:
anytime("24/08/2014 01:28:00")
anytime("2014/24/08 01:28:00")

[1] NA

What is the reason for this and what would be the options (using anytime package ONLY)?

A: We can add the formats with addFormats in anytime if that formats are not in the default list of formats by using
getFormats()
#[1] "%Y-%m-%d %H:%M:%S%f"    "%Y/%m/%d %H:%M:%S%f"    "%Y%m%d %H%M%S%f"
#[4] "%Y%m%d %H:%M:%S%f"      "%m/%d/%Y %H:%M:%S%f"    "%m-%d-%Y %H:%M:%S%f"
#[7] "%Y-%b-%d %H:%M:%S%f"    "%Y/%b/%d %H:%M:%S%f"    "%Y%b%d %H%M%S%F"
#[10] "%Y%b%d %H:%M:%S%F"      "%b/%d/%Y %H:%M:%S%f"    "%b-%d-%Y %H:%M:%S%f"
#[13] "%d.%b.%Y %H:%M:%S%f"    "%Y-%B-%d %H:%M:%S%f"    "%Y/%B/%d %H:%M:%S%f"
#[16] "%Y%B%d %H%M%S%f"        "%Y%B%d %H:%M:%S%f"      "%B/%d/%Y %H:%M:%S%f"
#[19] "%B-%d-%Y %H:%M:%S%f"    "%d.%B.%Y %H:%M:%S%f"    "%a %b %d %H:%M:%S%F %Y"
#[22] "%Y-%m-%d"               "%Y%m%d"                 "%m/%d/%Y"
#[25] "%m-%d-%Y"               "%Y-%b-%d"               "%Y%b%d"
#[28] "%b/%d/%Y"               "%b-%d-%Y"               "%Y-%B-%d"
#[31] "%Y%B%d"                 "%B/%d/%Y"               "%B-%d-%Y"

If we check the format that gives NA, it is not in the getFormats list
c("%d/%m/%Y %H:%M:%S", "%Y/%d/%m %H:%M:%S") %in% getFormats()
#[1] FALSE FALSE

So, we can add the formats with addFormats and apply the anytime
anytime::addFormats(c("%d/%m/%Y %H:%M:%S", "%Y/%d/%m %H:%M:%S"))
anytime("24/08/2014 01:28:00")
#[1] "2014-08-24 01:28:00 IST"
anytime("2014/24/08 01:28:00")
#[1] "2014-08-24 01:28:00 IST"

Update
In the latest version of anytime, there are 41 formats in getFormats()
length(getFormats())
#[1] 41

But, the format specified in the OP's post is still not included and would have to follow the addFormats route