text:
Q: Python request SSLError: bad handshake on https://gcm-http.googleapis.com Trying to make a Python request to GCM API but certificates aren't verified.
requests and certifi packages are updated

*

*Python 2.7.6

*certifi==2017.4.17

*requests==2.18.1

*pyOpenSSL==17.1.0

Tried to call other servers and return are OK:

*

*r = requests.get('https://graph.facebook.com/spotify') [OK]

*r = requests.get('https://graph.facebook.com/spotify', verify=certifi.where()) [OK]

*r = requests.get('https://gcm-http.googleapis.com') [NOK]

*r = requests.get('https://gcm-http.googleapis.com', verify=certifi.where()) [NOK]

Error message: bad handshake: Error([('SSL routines', 'SSL3_GET_SERVER_CERTIFICATE', 'certificate verify failed')],)

A: I came across some interesting results when researching this problem.  It seems to me that this could be the problem.  Let me know.
TL;DR
Try using certifi.old_where().  If that works, then you really should upgrade to a newer version of OpenSSL on your server.
Sources
GitHub:
https://github.com/certifi/python-certifi/issues/32
From @Lukasa

Can you confirm whether or not this is the same problem as #26? That is, try passing certifi.old_where() to the verify argument of requests.
...
To be clear, there is no fix for this from Python-land other than using certifi.old_where() or upgrading OpenSSL. The OpenSSL on your system is too old to properly verify cross-signed TLS certificates, and three is no way for that problem to be resolved on my end. Your system is being put at significant risk if you use certifi.old_where() because you are continuing to base your trust on 1024-bit RSA certificates, which have been being deprecated since 2012 and are subject to several known attacks already.

certifi Docs:
https://pypi.python.org/pypi/certifi

1024-bit Root Certificates
Browsers and certificate authorities have concluded that 1024-bit keys are unacceptably weak for certificates, particularly root certificates. For this reason, Mozilla has removed any weak (i.e. 1024-bit key) certificate from its bundle, replacing it with an equivalent strong (i.e. 2048-bit or greater key) certificate from the same CA. Because Mozilla removed these certificates from its bundle, certifi removed them as well.
Unfortunately, old versions of OpenSSL (less than 1.0.2) sometimes fail to validate certificate chains that use the strong roots. For this reason, if you fail to validate a certificate using the certifi.where() mechanism, you can intentionally re-add the 1024-bit roots back into your bundle by calling certifi.old_where() instead. This is not recommended in production: if at all possible you should upgrade to a newer OpenSSL. However, if you have no other option, this may work for you.


text:
Q: Multiple HTTP requests in Angular So this my controller:
app.controller('dbCtrl', function($scope, $http) {
$http.get("http://private-abc.apiary-mock.com/bus")
.success(function(response) {
 $scope.network = response.networkupdates;});
 });

What I wanted to do next is call a 2nd HTTP request, I guess in terms of best practice would it be best to create a 2nd controller to call the 2nd HTTP or would it be best to include the 2nd HTTP call in this current controller (and if so, how?)
Thanks.

A: So one of the cool aspects of using promises is that they can be chained. So in your case, you are calling:
$http.get("http://private-abc.apiary-mock.com/bus")

Which returns a promise that you can then chain to another promise like so:
var requests = $http.get("http://private-abc.apiary-mock.com/bus").then(function(response) {
    $scope.network = response.networkupdates;
    // make second get call and return it to chain the promises
    return $http.get("some-other-endpoint").then(function(otherResponse) {
        // you can do something here with the response data
        return otherResponse;
    });
});

What you have now is two chained promises that will return the final value, so if you call this later:
requests.then(function(otherResponse) {
    // or you can do something here
    doSomething(otherResponse);
});

As far as best practices for Angular, I would say you are better off creating a service or factory to handle any and all http requests. Controllers are really just meant to bind data to the view; services are where your business logic and data population should happen.

A: You can make your $http calls in the same controller.
The $http service is a function which takes a single argument — a configuration object — that is used to generate an HTTP request and returns a promise with two $http specific methods: success and error. It internally uses $q (a promise/deferred implementation inspired by Kris Kowal's Q).
If your two $http are independent of each other you use the $q.all to "join" the results of your http calls.
Example :
$q.all([
    $http.get("http://private-abc.apiary-mock.com/bus"),
    $http.get('/someUrl')
  ]).then(function(results) {
     $scope.network = results[0];
     $scope.whatevername= results[1]

  });
}

If your http calls are dependent on one another then you can use the concept of chaining.
for example:
$http.get("http://private-abc.apiary-mock.com/bus").then(function(result) {
    $scope.network = result.networkupdates;
    return $http.get("someurl").then(function(res) {
        return res;
    });
});

For refernce of q you can see https://github.com/kriskowal/q
For refernce of  $q service you can see https://docs.angularjs.org/api/ng/service/$q

redpajama_set_name: RedPajamaStackExchange


text:
Q: No DNS resolution and Internet access from Kubernetes POD on Windows I've built a cluster (v1.15.4) on hyper-v with
- linux node (master)
- linux node (worker)
- windows node (worker)
- networking - flannel (host-gw)
- mac spoofing enabled for vms

deployed win-webserver.yaml to test if windows is working.
https://kubernetes.io/docs/setup/production-environment/windows/user-guide-windows-containers/
kubectl get pods -o wide
NAME                             READY   STATUS    RESTARTS   AGE   IP           NODE   NOMINATED NODE   READINESS GATES
win-webserver-7779dc4df7-58qs2   1/1     Running   0          18m   10.42.2.41   node01   <none>           <none>
win-webserver-7779dc4df7-mb4sf   1/1     Running   0          18m   10.42.2.43   node01   <none>           <none>
win-webserver-7779dc4df7-w5kjt   1/1     Running   0          18m   10.42.2.44   node01   <none>           <none>
win-webserver-7779dc4df7-wm245   1/1     Running   0          18m   10.42.2.45   node01   <none>           <none>

kubectl get svc
NAME            TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)        AGE
kubernetes      ClusterIP   10.43.0.1      <none>        443/TCP        122m
win-webserver   NodePort    10.43.91.255   <none>        80:30378/TCP   72m

Deployment ran fine however containers running on windows can't resolve dns and access internet.
DNS request from windows pod
DNS request timed out.
timeout was 2 seconds.
Server:  UnKnown
Address:  10.43.0.10

DNS request timed out.
timeout was 2 seconds.
DNS request timed out.

Also can't access pods from linux using service.
curl http://10.43.91.255 --connect-timeout 30
curl: (28) Connection timed out after 30000 milliseconds

Flannel logs
kubectl logs -n kube-system pod/kube-flannel-8dqcc -c kube-flannel
I1015 12:48:40.437400       1 main.go:527] Using interface with name eth0 and address 192.168.x.x
I1015 12:48:40.437491       1 main.go:544] Defaulting external address to interface address (192.168.x.x)
I1015 12:48:40.538336       1 kube.go:126] Waiting 10m0s for node controller to sync
I1015 12:48:40.538380       1 kube.go:309] Starting kube subnet manager
I1015 12:48:41.538500       1 kube.go:133] Node controller sync successful
I1015 12:48:41.538539       1 main.go:244] Created subnet manager: Kubernetes Subnet Manager - node02
I1015 12:48:41.538551       1 main.go:247] Installing signal handlers
I1015 12:48:41.538676       1 main.go:386] Found network config - Backend type: vxlan
I1015 12:48:41.538751       1 vxlan.go:120] VXLAN config: VNI=4096 Port=4789 GBP=false DirectRouting=false
W1015 12:48:41.539007       1 device.go:84] "flannel.4096" already exists with incompatable configuration: vtep (external) interface: 2 vs 3; recreating device
I1015 12:48:41.632647       1 main.go:317] Wrote subnet file to /run/flannel/subnet.env
I1015 12:48:41.632666       1 main.go:321] Running backend.
I1015 12:48:41.632675       1 main.go:339] Waiting for all goroutines to exit
I1015 12:48:41.632695       1 vxlan_network.go:60] watching for new subnet leases
E1015 13:01:19.765370       1 vxlan_network.go:101] error decoding subnet lease JSON: invalid MAC address
E1015 13:11:30.468144       1 vxlan_network.go:101] error decoding subnet lease JSON: invalid MAC address

Any suggestion appreciated.
Update
I managed to get my cluster working. Reason for the communication failure was that I had two networks connected to each of kubernetes machines.
linux master - internet facing eth0 (192.168.6.2) eth1 (192.168.3.12)
linux worker - internet facing eth0 (192.168.6.3) eth1 (192.168.3.13)
windows node - internet facing Ethernet_LB (192.168.6.4) Ethernet_FW (192.168.3.14)

Virtual Switch on windows was created on Ethernet_FW which had no internet connection.
After running Wireshark and tdcdump I was able to find out that
 - pods on master send traffic to windows pods via eth0
 - pods on windows node send traffic to linux pods visa Ethernet_FW
 - pods from windows send traffic to the internet via Ethernet_FW
That caused communication failure between pods.
I was able to configure windows node to create Virtual Switch on Ethernet_LB which had internet access and this interface (Ethernet_LB) was accepting packets from master and linux worker.
For cluster creation I used this resource https://kubernetes.io/docs/setup/production-environment/windows/user-guide-windows-nodes/
I had to put proper interface name into config file
"InterfaceName" : "Ethernet_LB"

A: This is a community wiki answer posted for better visibility. Feel free to expand it.
As already confirmed by @dzup4uk, Reason for the communication failure was that there was two networks connected to each of kubernetes machines.
linux master - internet facing eth0 (192.168.6.2) eth1 (192.168.3.12)
linux worker - internet facing eth0 (192.168.6.3) eth1 (192.168.3.13)
windows node - internet facing Ethernet_LB (192.168.6.4) Ethernet_FW (192.168.3.14)

Virtual Switch on windows was created on Ethernet_FW which had no internet connection.
After running Wireshark and tdcdump I was able to find out that

*

*pods on master send traffic to windows pods via eth0

*pods on windows node send traffic to linux pods visa Ethernet_FW

*pods from windows send traffic to the internet via Ethernet_FW
That caused communication failure between pods.
I was able to configure windows node to create Virtual Switch on Ethernet_LB which had internet access and this interface (Ethernet_LB) was accepting packets from master and linux worker.

It was required to put proper interface name into config file
"InterfaceName" : "Ethernet_LB"

The Kubernetes cluster v1.19.7 was build using Windows Server 2019 with the latest updates as WIndows worker nodes.
For cluster creation this resource was used:

*

*Adding Windows nodes

Other useful resources:

*

*Windows Server release information

*Windows 10 and Windows Server 2019 update history


text:
Q: Creating line graph using categorical data Trying to display "Grades" over inspection year, and the count is just the observations in the data frame.
Creating a quick table:
table(mydata1$Grade,mydata1$Inspection.Year)

Creating a quick barchart:
ggplot(mydata1, aes(fill=Grade , x=Inspection.Year)) +
  geom_bar()

I want to do the same thing with a line graph, but no luck with
ggplot(mydata1, aes(fill=Grade , x=Inspection.Year)) +
  geom_line()

any thoughts?
Thanks!

A: Suppose your data looks something like this:
mydata1 = data.frame(
Inspection.Year=sample(2000:2005,100,replace=TRUE),
Grade=sample(LETTERS[1:3],10,replace=TRUE))

You need to tally your counts and plot them on the y-axis, so something like below:
library(dplyr)

mydata1 %>% count(Inspection.Year,Grade)
# A tibble: 17 x 3
   Inspection.Year Grade     n
             <int> <fct> <int>
 1            2000 A        11
 2            2000 B         6
 3            2000 C         1
 4            2001 A         8

And to plot this:
mydata1 %>% count(Inspection.Year,Grade) %>%
ggplot()+geom_line(aes(x=Inspection.Year,y=n,col=Grade))

Or something similar to the "fill" in geom_bar, you set y=1, and use stat_summary to sum up the 1s per Grade / Year, which will give you n:
ggplot(mydata1, aes(col=Grade , x=Inspection.Year,y=1))+ stat_summary(geom="line",fun.y=sum)

Both give the plot below:


text:
Q: how to stretch the icon in google map api v3 Here is my code...
The problem is, I don't know how to stretch the image of icon.
I just want to know if there's a way to stretch the image of icon? if there is, please tell me..thanks in advance
var image = {
    url: 'images/arrive.png'
    size: new google.maps.Size(40, 40)
};

var markerOptions = {
  map: map,
  position: new google.maps.LatLng(lati, longti),
  icon: image};

A: Use Like
 var icon = {
     url: "../res/sit_marron.png", // url
     size: new google.maps.Size(width, height), // size
     origin: new google.maps.Point(0,0), // origin
     anchor: new google.maps.Point(anchor_left, anchor_top) // anchor
 };

 position = new google.maps.LatLng(latitud,longitud)
 marker = new google.maps.Marker({
  position: position,
  map: map,
  icon: icon
 });

Markers

A: Use scaledSize Property of Google Maps API.
The size of the entire image after scaling, if any. Use this property to stretch/shrink an image or a sprite.
You can see here about scaledSize .

A: Put this on your code,
 origin: new google.maps.Point(0,0),
 anchor: new google.maps.Point(anchor_left, anchor_top)


text:
Q: Where to ask about programming ethics? I'm a developer. I usually ask on Stack Overflow.
I have a situation, or "story", that involves: programming ethics, employer-employee relationship, company stocks, code property and taking decisions.
So, there are a few meta-questions:

*

*On what Stack Exchange site can I post this situation?

*Is it wrong to ask for opinions? because there might not be an accepted answer. Should I ask something very concrete at the end of my story?

A: You should probably ask at The Workplace. They do field software development workplace questions, a notable example being Project Manager asks for complete 100% confidence everytime committing code. They have a [software industry] tag, except it seems people tend to not use it, even for IT or software development industry questions.
Programmers accepts a range of subjective programming questions, but this stuff appears to be off topic there:

general workplace issues, office politics, and job hunting (check out The Workplace instead)


text:
Q: What exactly is a linear extension ( in intuitive terms)? Definitions

*

*$X=\{(1,i_1),(2,i_2),...,(n,i_n)\}$. Here $i_1,i_2,...,i_n$ is permutation $\sigma $ of $\{1,2,...,n\}.$

*$R$ is a relation defined as follows $$(k,i_k)R(l,i_l)\iff k\leq l\text{ and }i_k\leq i_l.$$

*The dimension of the poset $(X,R)$ is the smallest number of linear extensions whose intersection is $(X,R)$.

Problem: Prove that the dimension of the partial order set $(X,R)$ is $2$, provided that $i_1,i_2,..,i_n$ is not the identity permutation $1,2,...,n$.
My Attempt:
 It is easy to see that the dimension of $(X,R)$ is $1$ when $\sigma=1,2,3,...,n$. Now suppose that $\sigma\neq 1,2,3,...,n.$ Then we have to show that the dimension of $(X,R)$ is $2$. I am guessing that a constructive proof is required for this problem where we need to construct two different sets of linear extensions, but this seems very difficult. So if you are aware of alternative approaches then any hints or suggestions would be much appreciated.
Here is the original problem text from Introductory Combinatorics by Richard A. Brualdi.

A: Standard lexicographic order, $L_1$, and colexicographic order, $L_2$, defined by
$$
\begin{aligned}
(a,b)L_1(c,d)&\Longleftrightarrow a<c\text{ or } (a=c\text{ and }b\le d),\\
(a,b)L_2(c,d)&\Longleftrightarrow b<d\text{ or } (b=d\text{ and }a\le c),
\end{aligned}
$$
are linear orders.  When applied to your set $X$, these reduce to
$$
\begin{aligned}
(a,b)L_1(c,d)&\Longleftrightarrow a\le c,\\
(a,b)L_2(c,d)&\Longleftrightarrow b\le d,
\end{aligned}
$$
since the cases $a=c$ and $b=d$ only arise when $(a,b)=(c,d)$.  You can check that both are linear extensions of $R$, that is, that $(a,b)R(c,d)\Longrightarrow (a,b)L_1(c,d)$ and $(a,b)R(c,d)\Longrightarrow (a,b)L_2(c,d)$.  You can also check that the intersection of $L_1$ and $L_2$ is $R$.


text:
Q: Making object models in solution based on third party ElasticSearch solution When you deal with JSON, it's really easy to make C# models. You either Paste special in Visual Studio, or you use one of the many available tools online.
ElasticSearch responses obviously are JSON, meaning, if you can get the responding JSON, you're good to go. However, if you just have a connection-string and simply want to "map" all the ElasticSearch objects into your C# code - how do you do it?
My question:
Is there a way to see all fields/data in an ElasticSearch instance, and then easily get the JSON, so you can get strongly typed models?

A: You can query elasticsearch for mappings. Mapping will contain all information you need to build model in C# (but you will still have to build it by hand I think). Example using database from your previous question:
var settings = new ConnectionSettings(new Uri("http://distribution.virk.dk/cvr-permanent"));
var client = new ElasticClient(settings);
// get mappings for all indexes and types
var mappings = client.GetMapping<JObject>(c => c.AllIndices().AllTypes());
foreach (var indexMapping in mappings.Indices) {
    Console.WriteLine($"Index {indexMapping.Key.Name}"); // index name
    foreach (var typeMapping in indexMapping.Value.Mappings) {
        Console.WriteLine($"Type {typeMapping.Key.Name}"); // type name
        foreach (var property in typeMapping.Value.Properties) {
            // property name and type. There might be more useful info, check other properties of `typeMapping`
            Console.WriteLine(property.Key.Name + ": " + property.Value.Type);
            // some properties are themselves objects, so you need to go deeper
            var subProperties = (property.Value as ObjectProperty)?.Properties;
            if (subProperties != null) {
                // here you can build recursive function to get also sub-properties
            }
        }
    }
}


text:
Q: Allocate Space for object I am trying to load 2.5 million in my database  in sql server 2008 but i keep on getting the below error.
Additional information: Could not allocate space for object 'dbo.DwH_Staging_Table' in database 'TestDB2' because the 'PRIMARY' filegroup is full. Create disk space by deleting unneeded files, dropping objects in the filegroup, adding additional files to the filegroup, or setting autogrowth on for existing files in the filegroup.
How to solve this problem.

A: Your hard drive section is full. You need more space to do that query. Try shrink database/files to free-up some space temporary:
http://technet.microsoft.com/en-us/library/ms189080(v=sql.105).aspx


text:
Q: Building Interactive games for video calls in React-Native I'm trying to create a react-native video call app using agora.io and was looking to create some interactive games that users can play on the call like the ones that Facebook messenger offers. Are there any resources out there that I can refer to or any tutorials? Any help would greatly be appreciated.
Thanks

A: Hey you can check out the following links to help you get started with adding Agora.io RTE SDK to your react native project.
Agora React-Native Quickstart
React-Native API reference
You can also read up about how you can build games in react-native.


text:
Q: Bash script hangs when called from php or python I'm a novice at bash and I wrote a bash script that reads a large syslog file from end to start, looks for the entries that belong to a given minute (the minute before the last) and then counts how many ocurrences each of the given patterns has in that minute.
It doesn't work if run from PHP/Python, but it works if I call it directly like this:
sh /path/to/logparser.sh /path/to/big.log '2013-09-23T08:38' '2013-09-23T08:37' 'MySQL has gone away' 'Unhandled Error timed out'
Below is the code of logparser.sh:
logfile=$1
echo $logfile
shift
minute=$1
echo $minute
shift
minute_before=$1
echo $minute_before
shift
command="tac $logfile | sed -n -e '/$minute/p' -e '/$minute_before/q'"
echo $command
if [ -f $logfile ]; then
    buffer=$(eval $command)
    echo "buffer complete"
    exit 1
fi

Side notes:

*

*I've used buffer=$(eval $command) because buffer=$(tac $logfile | sed -n -e '/$minute/p' -e '/$minute_before/q') hangs even in the command line

*I've used -e '/$minute_before/q' in sed because I couldn't get `-e '/$minute/!q' to work

But when I run it from PHP via pasthru() or from Python via subprocess.Popen().communicate() it hangs. If I check the processes with ps -ef r I see that tac is still running.
Here's the PHP code that calls the bash script:
$env           = $argv[1];
$service_name  = $argv[2];
$logfile       = $argv[3];
$minute        = $argv[4];
$minute_before = $argv[5];

$command = 'sh '.dirname(__FILE__).'/logparser.sh ';

$n = count($argv);
for($i=3; $i<$n; $i++){
    $command .= ' ' . escapeshellarg($argv[$i]);
}
$command .= "\n";
echo "\npassthru {$command}";
passthru($command, $out);
var_dump($out);
exit();

Here's the Python code that calls the bash script:
env           = sys.argv[1]
service_name  = sys.argv[2]
logfile       = sys.argv[3]
minute        = sys.argv[4]
minute_before = sys.argv[5]

args = ['sh', '%s/logparser.sh' % os.getcwd()]

for i in range(3, len(sys.argv)):
    args.append(sys.argv[i])

print args
output = subprocess.Popen(args, stdout=subprocess.PIPE).communicate()
print output

Other stuff that I've rules out:

*

*exec permissions: both PHP and Python can run and get the results of linux commands like whoami

*file permissions: both PHP and Python run perfectly for a simpler bash script, e.g. a file containing the date liunx command; the log file has read permissions for all

*bad params: I've compared in the bash script the params send by PHP/Python and the params sent via command line, they're identical

How could I make it work called from PHP/Python?

A: None of your codes seem to pass your logfile to your shell script, the logfile variable is unset in your shell making tac wait input from stdin instead.
Like in your python code, perhaps you need to do it like this:
for i in range(1, len(sys.argv)):
    args.append(sys.argv[i])

Likewise in your php code:
$n = count($argv);
for($i=1; $i<$n; $i++){
    $command .= ' ' . escapeshellarg($argv[$i]);
}

The actual cause why the logfile's path is not passed to your shell script may be different but generally that's the basic reason why the script is hanging.


text:
Q: Change Font(Text) Color using Color Picker in Vue js I want to change font(text) color when user pick it from color picker,I had made this but it wont work,
<textarea :class="changeColor"></textarea>
<v-color-picker class="ma-2" hide-inputs @click="changeColor('color')"></v-color-picker>
 changeColor(val){ this.color = val}

A: To dynamically assign a css color value to a html element you can use :style="{}" .
Like this
<template>
<div>
   <textarea :style="{color:color}"></textarea>
   <v-color-picker v-model="color" />
</div>
</template>

<script>
  export default {
    data() {
      return {
        color : '#FFFFFF'
      }
    }
  }
</script>


text:
Q: Add EditText to another LinearLayout from non children layout dynamically I want to have two layouts on screen. One scrollable, another should contain a button which could add stuff to scrollable layout and always should be visible. I am not sure if I am going in the right direction, but so far I have this and my code work in way i wasn't expecting. If I click buttonSPAddText EditText appears in same line as buttons. I expect it to appear below them in another layout, linearLayoutSPTextHolder.
Here is my xaml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:p1="http://schemas.android.com/apk/res/android"
    p1:orientation="vertical"
    p1:minWidth="25px"
    p1:minHeight="25px"
    p1:layout_width="match_parent"
    p1:layout_height="match_parent"
    p1:id="@+id/linearLayoutSPMain">
    <LinearLayout
        p1:orientation="horizontal"
        p1:minWidth="25px"
        p1:minHeight="25px"
        p1:layout_width="match_parent"
        p1:layout_height="51.0dp"
        p1:id="@+id/linearLayoutSPButtonHolder"
        p1:layout_weight="1">
        <Button
            p1:text="AddText"
            p1:layout_width="wrap_content"
            p1:layout_height="match_parent"
            p1:id="@+id/buttonSPAddText"
            p1:layout_weight="1" />
        <Button
            p1:text="Do nothing"
            p1:layout_width="wrap_content"
            p1:layout_height="match_parent"
            p1:id="@+id/buttonSPDoNth"
            p1:gravity="center_vertical"
            p1:layout_weight="1" />
    </LinearLayout>
    <ScrollView
        p1:minWidth="25px"
        p1:minHeight="25px"
        p1:layout_width="match_parent"
        p1:layout_height="wrap_content"
        p1:id="@+id/scrollViewSPText"
        p1:layout_weight="6">
        <LinearLayout
            p1:orientation="vertical"
            p1:minWidth="25px"
            p1:minHeight="25px"
            p1:layout_width="match_parent"
            p1:layout_height="wrap_content"
            p1:id="@+id/linearLayoutSPTextHolder"
            p1:scrollbars="horizontal" />
    </ScrollView>
</LinearLayout>

and my activity:
namespace TiesaDrasaAndroid
{
[Activity (Label = "SelectPlayersActivity")]
public class SelectPlayersActivity : Activity
{
    private int _textBoxId = 1000;
    private LinearLayout  _layout = null;

    protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);
        SetContentView (Resource.Layout.SelectPlayers);

        _layout = (LinearLayout)FindViewById(Resource.Id.linearLayoutSPTextHolder);
        _layout.Orientation = Orientation.Vertical;
        Button addPl = FindViewById<Button>(Resource.Id.buttonSPAddText);

        addPl.Click  += delegate {
                        this.CreateUserTextBox ();
        };
    }
    private void CreateUserTextBox()
    {
        var textbox = new EditText (this);
        textbox.Id = _textBoxId;
        textbox.SetWidth (100);
        _textBoxId++;
        _layout.AddView (textbox);

    }
}

A: This code is working for me very well:
public class MainActivity extends Activity {
    private int _textBoxId = 1000;
    private LinearLayout _layout = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        _layout = (LinearLayout) findViewById(R.id.linearLayoutSPTextHolder);
//      _layout.setOrientation(LinearLayout.VERTICAL);
        Button addPl = (Button) findViewById(R.id.buttonSPAddText);

        addPl.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                CreateUserTextBox();
            }
        });
    }

    private void CreateUserTextBox() {
        LayoutParams lpView = new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT);
        EditText textbox = new EditText(this);
        textbox.setId(_textBoxId);
        textbox.setText(_textBoxId + "");
        textbox.setLayoutParams(lpView);
        _textBoxId++;
        _layout.addView(textbox);

    }
}


text:
Q: UIWebView not playing video loaded with NSMutabaleURLRequest I am trying load NSMutableURLRequst in UIWebview. Webview not lading video content.
if i tried to get data from NSMutableURLRequst and saved into DocumentDirectory webview playing video perfectly.But video files are very large size. I have to be play in Webview without downloading. I am unable to find the issue. Can any one please help in this issue. Thanks in Advance.
Code I have used:
    NSMutableURLRequest *request =  [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:GET_METHOD];
[request setValue:@"application/video" forHTTPHeaderField:@"Content-Type"];
// setting header keys
[request setValue:[NSString stringWithFormat:@"Authorization value" forHTTPHeaderField:@"authorizationKey"];

the above code is for creating Request.
I just simply load this request into UIWebview by usgin following line.
[videoWebView loadRequest:request]


text:
Q: operator call syntax in C++ Whether there can be a situation where the syntax
if (first == second) // ...

is different from that?
if (first.operator==(second)) // ...

I don't think so, but just want to know it.

A: a == b

is sometimes equivalent to
a.operator==(b)

and sometimes equivalent to
operator==(a,b)

and sometimes equivalent to neither, if the meaning ends up being the "built-in" meaning of == for non-class types.
Whenever the compiler sees ==, if at least one type involves a user-defined type, it searches for member operators (must not be hidden in the scope of a's class type) and non-member operators (using argument dependent lookup) and built-in meanings (since a class might have an implicit conversion to an ordinary type with built-in comparison).  If more than one could make sense, it goes to the rules for overload resolution.

A: If you mean "when are the two syntaxes not equivalent", then the answer is when the equality operator is not a member of whatever type first is. Obviously the second variant will not work for types without a member operator==. That includes built-in types.
When a member operator does exist for the type of first, then the two differ because the non-member operator could allow type conversions for both first and second, whereas the example with the member operator can only allow a conversion for second.

A: One illustration to a situation in which the two statement have different effects is where you  have implicit conversions of first. For example:
struct my_int
{
    int num;

    my_int(int num) : num(num) {}
};

bool operator==(const my_int& a, const my_int& b)
{
    return a.num == b.num;
}

In this case, the following is a valid C++ code:
my_int a(1);
int x = 1;

if (x == a) {
    std::cout << "Equal\n";
}

Where compiling this code:
my_int a(1);
int x = 1;

if (x.operator==(a)) {
    std::cout << "Equal\n";
}

Gives a compile error like the following:

conversion.cpp: In function 'int main()': conversion.cpp:21:16: error:
  request for member 'operator==' in 'x', which is of non-class type
  'int'

A: The second won't work with primitives. However, both forms will work with custom-built types who have that operator overloaded publicly.

A: If your question is based on syntax alone, then it depends on the type of the parameters. Consider the following code:
#include <iostream>

using namespace std;

class a {

public:

  a(){
  }

  int operator ==(const a& v){
    cout << "member operator" << endl;
    return false;
  }

};

int operator ==(a &v1, a &v2){
    cout << "external operator" << endl;
    return true;
}

int main(){

  a a1, a2;

  if (a1 == a2 && a1.operator==((const a&)a2)) {
    cout << "done" << endl;
  }

}

In this setting, both operators are being called.
If the function type parameters are the same, it seems that the method will be prefered.


text:
Q: Minimum and maximum of random variable Let $X$ be random variable such that $\begin{align} F_X(x) = 1- e^{-x} \end{align}$ if $x \ge 0$ and $F_X(x)=0$ in other case. Find distribution function $Y= \min(1,X)$, $Z=\max(1,X)$.
If I have to find $\max(X,Y)$ or $\min(X,Y)$ ($X,Y$ - random variable) I don't have any problem. But in this case I have number - what should I do?

A: Let $Y=\min(1, X)$. We find $F_Y(y)$.
If $y\le 0$, then
$$F_Y(y)=\Pr(Y\le y)=\Pr(\min(1,X)\le y)=\Pr(X\le y)=0.$$
Now let $0\lt y\lt 1$.
Then
$$F_Y(y)=\Pr(Y\le y)=\Pr(\min(1,X)\le y)=\Pr(X\le y)=1-e^{-y}.$$
If $y\ge 1$, then for sure $\min(1,X)\le 1$, and therefore $F_Y(y)=1$.
Note that $Y$ does not have continuous distribution. The function $F_Y(y)$ is continuous almost everywhere, but there is a sudden jump at $1$. There is a point mass at $1$, which is equal to the probability $e^{-1}$ that $X\ge 1$.
We leave it to you to do max. The analysis is similar to the one for min.


text:
Q: Spark Window Functions That depend on itself Say I have a column of sorted timestamps in a DataFrame. I want to write a function that adds a column to this DataFrame that cuts the timestamps into sequential time slices according to the following rules:

*

*start at the first row and keep iterating down to the end

*for each row, if you've walked n number of rows in the current group OR you have walked more than time interval t in the current group, make a cut

*return a new column with the group assignment for each row, which should be an increasing integer

In English: each group should be no more than n rows, and should not span more than t time
For example: (Using integers for timestamps to simplify)
INPUT
     time
---------
        1
        2
        3
        5
       10
      100
     2000
     2001
     2002
     2003

OUTPUT (after slice function with n = 3 and t = 5)
     time | group
----------|------
        1 |     1
        2 |     1
        3 |     1
        5 |     2 // cut because there were no cuts in the last 3 rows
       10 |     2
      100 |     3 // cut because 100 - 5 > 5
     2000 |     4 // cut because 2000 - 100 > 5
     2001 |     4
     2002 |     4
     2003 |     5 // cut because there were no cuts in the last 3 rows

I have a feeling this can be done with window functions in Spark. Afterall, window functions were created to help developers compute moving averages. You'd basically calculate an aggregate (in this case average) of a column (stock price) per window of n rows.
The same should be able to be accomplished here. For each row, if the last n rows contains no cut, or the timespan between the last cut and the current timestamp is greater than t, cut = true, o.w. cut = false. But what I can't seem to figure out is how to make the Window Function aware of itself. That would be like the moving average of a particular row aware of the last moving average.


text:
Q: Black Screen + Freeze after a couple minutes of gameplay (Windows 8) Since this morning I'm getting random freezes after a couple of minutes of gameplay. It started with Battlefield 3, which made my screen turn black and I had to push the reset button since CTRL+ALT+DEL didn't work anymore. I also noticed that the power led on my monitor was blinking, which indicates that it doesn't get signal.
Anyway, I restarted the computer, put everything at stock settings (no overclock) and tried again. It happened a couple of more times in Battlefield 3, so in anger I blamed the game and uninstalled it. Then I went on to play Tomb Raider, same thing happened. I ran Aida64 for 30 minutes, Furmark for a short while and all without problems. It's just within games that it shuts down between like 10 seconds and 2 minutes after starting. I opened up the case, reseated my graphics card, switched places of my two memory sticks and hoped for the best. Same thing is happening.


text:
Q: Vue3 v-for Maximum recursive updates exceeded in component  New to Vue and JS. I have a vue page myLists which takes an array of lists (containing media IDs for a title) which I used to make axios API calls and build a carousel (using vue3-carousel package) in the child with the return data sent as a prop. I'm currently dealing with a "Maximum recursive updates exceeded in v-for component  " warning that I believe has to do with how I make my API calls. Here is the relevant code below:
Parent "myLists", has multiple lists (each list has movies) and fetches data from api using axios:
<template>
  <div v-if="isReady">
    <List v-for="list of theList" :key="list.id" :aList="list"></List>
  </div>
</template>

export default {
  setup() {
    const theList = ref([]);

    for (var myList of myLists) {
      const aList = ref([]);

      for (var ids of myList) {
        var apiLink = partLink + ids;

        axios.get(apiLink).then((response) => {
          aList.value.push({
            title: response.data.original_title || response.data.name,
            overview: response.data.overview,
            url: "https://image.tmdb.org/t/p/w500" + response.data.poster_path,
            year: response.data.first_air_date || response.data.release_date,
            type: ids[1],
            id: response.data.id,
          });
        });
      }
      theList.value.push(aList.value);
    }
    return { theList };
  },

  computed: {
    isReady() {
      //make sure all lists are loaded from the api before rendering
      return this.theList.length == myLists.length;
    },
  },

Child component "List" (not including script tag as I don't think it's too relevant) takes the fetched data as a prop and builds a carousel with it:
<template>
  <Carousel :itemsToShow="4.5" :wrapAround="true" :breakpoints="breakpoints">
    <Slide v-for="slide of aList" :key="slide">
      <img
        @click="showDetails"
        class="carousel__item"
        :src="slide.url"
        alt="link not working"
        :id="slide"
      />
    </Slide>

    <template #addons>
      <Navigation />
      <Pagination />
    </template>
  </Carousel>
</template>

Don't know what's causing the error exactly. I have a feeling it could be how I do all my API calls, or maybe it's something else obvious. Anyone have a clue?

A: The fix was actually absurdly simple, I was on the right track. The component was trying to render before my data was ready, so simply adding a
"v-if="list.length!==0"

directly on my Carousel component (within my List component), as opposed to the parent, fixed my issue.
I assumed that props are automatically ready when passed to a child if I used a v-if in my parent, turns out I was wrong, and that there's a delay.
Found the solution on the github issues page:
https://github.com/ismail9k/vue3-carousel/issues/154


text:
Q: Integration code editor with React Native App I'd like to add a code editor to my React Native app, but I have not found a code editor for this.  Ace Editor and Monaco works only with react but not with react native. Does React Native or Expo SDK support Ace or Monaco?

A: If I understand the question correctly, you are asking for suggestions for a code editor package that will work in a React Native application, out of the box.
To answer your question directly: no, monaco-editor, ace and Codemirror do not explicitly support React Native.
With that said, it is certainly possible to integrate those editors into a React Native application using a wrapper and/or additional hacks to handle edge cases.  This user has integrated monaco in RN apps but has not provided example code.


text:
Q: Errors copying files to external drive I back up my data on NTFS Windows formatted external hard drives (different brand names), cloning each drive to protect against hardware failure. I copy from Mac, Windows, Linux, or Android machines onto one HDD and then make a clone of the HDD with my Mac OS X. I buy the HDDs in pair so they are also physically the same.
I was not aware of the challenges of copying to Windows NTFS HDDs with Mac OS X, and copy-pasted across HDDs without special care. I have had the XtraFinder app installed and apparently it allows me to copy onto NTFS without warning or error messages.
But there are problems with some of the copied files (The problems have nothing to do with a size limitation, as this can happen with files of just a few MBs).
Example of problems: I have 2 identical hard drives straight out of the box (brand new WD Ultra Passport, not faulty), HD1 and HD2. First, I copy a video from my Windows computer onto HD1. Secondly, I copy the same video from HD1 to HD2 using the Finder on Mac OS X. Result: The video can be played off HD1 but not off HD2. Whether I try to play the video on the Mac or a Windows or Android machine, same result. So the video copied from HD1 to HD2 appears to be seriously corrupted.
The corruption is a little subtle because FreeFileSync does not detect differences between the files on the HDDs. It's only when I try to play the video from the cloned HDD that I get an error message.

*

*Is there a way to detect the corrupted files?

*Is there a fix for the corrupted files?
I have tested this with mkv and mp4 video formats and standard image formats (photos taken with my cameras or phones). Some videos are copied without trouble, other videos are broken after being copied. With images, problems tend to affect a random number of them rather than all of them, maybe 1 in 20 or so. There are no problems at all if I copy with my Windows machines.
This problem has occurred with a dozen or so hard drives. They are formatted as "Windows NT Filesystem" (as read from "Get Info" menu) The problem has occured with previous versions of the OS (Mavericks and Mountain Lion). I have usually backed up with FreeFileSync, to copy large number of files at a time, and the problem has occurred that way too, not just copy-paste via the Finder.

MacBook Air, OS X Yosemite (10.10.3)
P.S. I have asked the question on apple discussions, but have not received answers at the time of posting here.


text:
Q: How to get only the unit names using systemctl? When I do
systemctl list-units --all --state=loaded

I get the output in of each unit with columns as
UNIT     LOAD   ACTIVE   SUB       DESCRIPTION

I need only the UNIT in output.
I tried adding --property=UNIT but it still prints all columns.
Tried --output=json-pretty , didn't work.
I have to match a particular unit in the output but my regex is failing so it'll be helpful if I get only the list of units so it'll be easy to compare strings.
The regex I am using is fgrep "input_from_user".service
Any suggestion on regex or the command?

A: Once you have the JSON output, you could use jq or Python or anything that understands JSON. For example, filtering using jq:
systemctl list-units --output json |
  jq -r --arg pattern input_from_user '.[].unit | select(test($pattern))'


text:
Q: visual studio C# как установить zip из github скачал например библиотеку с гитхаба. как добавить ее в проект на c#?

A: Нужно выполнить вот эту команду в PM Console.
Install-Package WebSocketSharp -Pre
Tools -> NuGet Package Manager -> Package Manager Console - в самой Visual Studio


text:
Q: Android : getParcelableArrayList error (out of Memory) I have a question about parcelable class (android).
Until now, I have passed a DoubleArray between 2 Intent whithout any problem:
new double[] latLong = new double[]{loc.getLatitude(),loc.getLongitude()};
...
intent.putExtra(Site.LATTITUDE, latLong);
...
startActivityForResult(intent, this.ACCESS_GOOGLE);

Today, I tried to add new data for the same activities using parcelable class.
My parcelable class:
package common;

import android.os.Parcel;
import android.os.Parcelable;

public class Site implements Parcelable {

    private int id;
    private String site_name;
    private int category ;
    private double latitude;
    private double longitude;

    /**
     *
     * @param id
     * @param site_name
     * @param category
     */
    public Site(int id, String site_name, int category,double latitude, double lonngitude){
        this.id=id;
        this.site_name=site_name;
        this.category=category;
        this.latitude=latitude;
        this.longitude=longitude;

    }

    public Site(Parcel in){
        readFromParcel(in);
    }

    @Override
    public int describeContents() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(this.id);
        dest.writeString(this.site_name);
        dest.writeInt(this.category);
        dest.writeDouble(this.latitude);
        dest.writeDouble(this.longitude);
    }

    /**
     *
     * @param in
     */
    private void readFromParcel(Parcel in) {
        this.id     = in.readInt();
        this.site_name  = in.readString();
        this.category   = in.readInt();
        this.latitude   = in.readInt();
        this.longitude  = in.readInt();
    }

   public static final Parcelable.Creator CREATOR =
        new Parcelable.Creator() {

            public SiteGoogle createFromParcel(Parcel in) {
                return new Site(in);
            }

            public SiteGoogle[] newArray(int size) {
                return new Site[size];
            }
        };

    /* GETTER / SETTER */

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getSite_name() {
        return site_name;
    }

    public void setSite_name(String site_name) {
        this.site_name = site_name;
    }

    public int getCategory() {
        return category;
    }

    public void setCategory(int category) {
        this.category = category;
    }

    public double getLatitude() {
        return latitude;
    }

    public void setLatitude(double latitude) {
        this.latitude = latitude;
    }

    public double getLongitude() {
        return longitude;
    }

    public void setLongitude(double longitude) {
        this.longitude = longitude;
    }

}

I put some Site objects(above class) in a java ArrayList, and pass this list to my second Activity with the below code :
ArrayList<Site> sitesForMap = new ArrayList<Site>();

for(int i=0; i<sites.size();i++){

    SiteGoogle site = new SiteGoogle(
            sites.get(i).getId(),
            sites.get(i).getSite_name(),
            sites.get(i).getCat(),
            sites.get(i).getLatitude(),
            sites.get(i).getLongitude());

    sitesForGoogle.add(site);
}

//put data in the intent
intent.putExtra(Site.LATTITUDE, latLong); //first data that worked well until now
intent.putParcelableArrayListExtra(Site.JSON_ARRAY, sitesForMap);   //my new data
startActivityForResult(intent, this.ACCESS_GOOGLE);

This code is executed perfectly(sitesForMap and latLong are not null) but in the second Activity, when I try to instance the first Double[] parameter,
an error occured .
Bundle bundle = getIntent().getExtras();
double[] adresse = (double[]) bundle.getDoubleArray(Site.LATTITUDE);    //worked well until today
List<Site> sitesList = bundle.getParcelableArrayList(Site.JSON_ARRAY);

Error :
11-04 03:00:47.248: D/AndroidRuntime(642): Shutting down VM
11-04 03:00:47.248: W/dalvikvm(642): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
11-04 03:00:47.350: E/AndroidRuntime(642): FATAL EXCEPTION: main
11-04 03:00:47.350: E/AndroidRuntime(642): java.lang.OutOfMemoryError
11-04 03:00:47.350: E/AndroidRuntime(642):  at android.os.Parcel.readArray(Parcel.java:1476)
11-04 03:00:47.350: E/AndroidRuntime(642):  at android.os.Parcel.readValue(Parcel.java:1810)
11-04 03:00:47.350: E/AndroidRuntime(642):  at android.os.Parcel.readListInternal(Parcel.java:2017)
11-04 03:00:47.350: E/AndroidRuntime(642):  at android.os.Parcel.readArrayList(Parcel.java:1461)
11-04 03:00:47.350: E/AndroidRuntime(642):  at android.os.Parcel.readValue(Parcel.java:1792)
11-04 03:00:47.350: E/AndroidRuntime(642):  at android.os.Parcel.readMapInternal(Parcel.java:2008)
11-04 03:00:47.350: E/AndroidRuntime(642):  at android.os.Bundle.unparcel(Bundle.java:208)
11-04 03:00:47.350: E/AndroidRuntime(642):  at android.os.Bundle.getDoubleArray(Bundle.java:1431)
11-04 03:00:47.350: E/AndroidRuntime(642):  at alij.ne.jp.GoogleMapActivity.onCreate(GoogleMapActivity.java:111)
11-04 03:00:47.350: E/AndroidRuntime(642):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-04 03:00:47.350: E/AndroidRuntime(642):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
11-04 03:00:47.350: E/AndroidRuntime(642):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
11-04 03:00:47.350: E/AndroidRuntime(642):  at android.app.ActivityThread.access$2300(ActivityThread.java:125)
11-04 03:00:47.350: E/AndroidRuntime(642):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
11-04 03:00:47.350: E/AndroidRuntime(642):  at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 03:00:47.350: E/AndroidRuntime(642):  at android.os.Looper.loop(Looper.java:123)
11-04 03:00:47.350: E/AndroidRuntime(642):  at android.app.ActivityThread.main(ActivityThread.java:4627)
11-04 03:00:47.350: E/AndroidRuntime(642):  at java.lang.reflect.Method.invokeNative(Native Method)
11-04 03:00:47.350: E/AndroidRuntime(642):  at java.lang.reflect.Method.invoke(Method.java:521)
11-04 03:00:47.350: E/AndroidRuntime(642):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
11-04 03:00:47.350: E/AndroidRuntime(642):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
11-04 03:00:47.350: E/AndroidRuntime(642):  at dalvik.system.NativeStart.main(Native Method)
11-04 03:03:10.460: I/Process(642): Sending signal. PID: 642 SIG: 9
11-04 03:03:11.099: D/dalvikvm(652): GC_EXTERNAL_ALLOC freed 792 objects / 61464 bytes in 48ms

Someone knows what is the problem ?
Thank you for reading my message !

A: Your readFromParcel and writeToParcel methods doesn't match.
@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeInt(this.id);
    dest.writeString(this.site_name);
    dest.writeInt(this.category);
    dest.writeDouble(this.latitude);
    dest.writeDouble(this.longitude);
}

private void readFromParcel(Parcel in) {
    this.id     = in.readInt();
    this.site_name  = in.readString();
    this.category   = in.readInt();
    this.latitude   = in.readInt(); // <-------- this
    this.longitude  = in.readInt(); // <-------- and this
}

A double uses 8 bytes, and an int uses 4 bytes on the parcel. A parcel doesn't contain type information (except if you use writeValue and readValue), so if you mismatch the read and write methods, an unexpected value will be read and it will mess the whole parcel.
If you really want an int, use (int) in.readDouble() instead of in.readInt().


text:
Q: SamAccountName from csv with employeeid I have this working script:
    Import-CSV -Path "$home\desktop\Script\fi13.04.20.csv" | ForEach-Object {

    Get-ADUser -Filter "employeeid -like '*$($_.employeeid)*'"  -Properties employeeid | select employeeid,name,SamAccountName

} | Export-CSV "$home\desktop\Script\fi-san-out.csv" -Encoding UTF8 -NoTypeInformation

I give to him a CSV file with employeeid and have back file with SamAccountName...
Я даю ему файл с employeeid и получаю обратно файл with certain parameters.
And this is an improved version-
$csv = Import-CSV -Path "$home\desktop\Script\fi13.04.20.csv"

$csvOutput = "$home\desktop\Script\fi-san-out.csv"

$object = @()

foreach($employee in $csv){

    $ADUserObject = Get-ADUser -Filter "employeeID -eq '$($employee.employeeID)'" -Properties samAccountName, displayName ,employeeID  -ErrorAction SilentlyContinue

    if($ADUserObject){

        $object += New-Object psobject -Property @{

            displayName = $ADUserObject.displayName

            samAccountName = $ADUserObject.SamAccountName

            employeeID = $ADUserObject.employeeID

        }

    }else{

        Write-Host "No employee found for $($employee.employeeId)" -ForegroundColor Red

    }

}

if($object){

    $object | Select-Object displayName, samAccountName, employeeID | Export-Csv -Path $csvOutput -Delimiter "," -Encoding UTF8 -NoTypeInformation

}

The first version produces much more results because if the employeeID contains an error "for example, the employeeID in CSV 12345 and employeeID in ActiveDirectory 123456", it gives the result.
In the improved version, it throws an error with any inaccurate ID.
The question is how to change the improved version so that it produces a result even with an error(like in the example)?
I am just starting to learn PS and I wrote an improved version with the help.

A: Result
$csv = Import-CSV -Path "$home\desktop\Script\ID.csv"

$csvOutput = "$home\desktop\Script\tz-san-out.csv"

$object = @()

foreach($employee in $csv){

    $ADUserObject = Get-ADUser -Filter "employeeID -like '*$($employee.employeeID)*'" -Properties samAccountName, displayName ,employeeID  -ErrorAction SilentlyContinue

    if($ADUserObject){

        $object += New-Object psobject -Property @{

            displayName = $ADUserObject.displayName

            samAccountName = $ADUserObject.SamAccountName

            employeeID = $ADUserObject.employeeID

        }

    }else{

        Write-Host "No employee found for $($employee.employeeId)" -ForegroundColor Red

    }

}

if($object){

    $object | Select-Object displayName, samAccountName, employeeID | Export-Csv -Path $csvOutput -Delimiter "," -Encoding UTF8 -NoTypeInformation

}


text:
Q: Считать текст из входящего письма Битрикс Столкнулся с такой проблемой, не могу понять, как можно считать текст из письма в облачном битриксе. Весь процесс происходит так: Письмо приходит на почту, которая привязана к битриксу. В настройках отмечено, что по входящему письму создается лид. Далее я пытаюсь просмотреть все поля лида на предмет нахождения текста письма, но его там нет. Подскажите, пожалуйста, как можно это узнать.

A: Текст письма не сохраняется непосредственно в поле лида.
Вместо этого создается сущность "Дело", которая прикреплена к данному лиду. И уже в этой сущности можно получить текст письма.
Но сделать это можно только с использованием REST API. Штатных способов в битриксе пока нет.
Ссылка на документаций по API API Дела


text:
Q: My Google action is deployed but still it shows test version when using it in google assistant My google action is deployed and is usable. But when I am using,  it shows test version.
And also, reviews of users are also not saved.

A: You can switch which version you're using for your account by going to the simulator and selecting the "Change version" control and selecting one of the non-test versions.


text:
Q: Reactive Extensions: buffer until subscriber is idle I have a program where I'm receiving events and want to process them in batches, so that all items that come in while I'm processing the current batch will appear in the next batch.
The simple TimeSpan and count based Buffer methods in Rx will give me multiple batches of items instead of giving me one big batch of everything that has come in (in cases when the subscriber takes longer than the specified TimeSpan or more than N items come in and N is greater than count).
I looked at using the more complex Buffer overloads that take Func<IObservable<TBufferClosing>> or IObservable<TBufferOpening> and Func<TBufferOpening, IObservable<TBufferClosing>>, but I can't find examples of how to use these, much less figure out how to apply them to what I'm trying to do.

A: Does this do what you want?
var xs = new Subject<int>();
var ys = new Subject<Unit>();

var zss =
    xs.Buffer(ys);

zss
    .ObserveOn(Scheduler.Default)
    .Subscribe(zs =>
    {
        Thread.Sleep(1000);
        Console.WriteLine(String.Join("-", zs));
        ys.OnNext(Unit.Default);
    });

ys.OnNext(Unit.Default);
xs.OnNext(1);
Thread.Sleep(200);
xs.OnNext(2);
Thread.Sleep(600);
xs.OnNext(3);
Thread.Sleep(400);
xs.OnNext(4);
Thread.Sleep(300);
xs.OnNext(5);
Thread.Sleep(900);
xs.OnNext(6);
Thread.Sleep(100);
xs.OnNext(7);
Thread.Sleep(1000);

My Result:
1-2-3
4-5
6-7

A: What you need is something to buffer the values and then when the worker
is ready it asks for the current buffer and then resets it. This can
be done with a combination of RX and Task
class TicTac<Stuff> {

    private TaskCompletionSource<List<Stuff>> Items = new TaskCompletionSource<List<Stuff>>();

    List<Stuff> in = new List<Stuff>();

    public void push(Stuff stuff){
        lock(this){
            if(in == null){
                in = new List<Stuff>();
                Items.SetResult(in);
            }
            in.Add(stuff);
        }
    }

    private void reset(){
        lock(this){
            Items = new TaskCompletionSource<List<Stuff>>();
            in = null;
        }
    }

    public async Task<List<Stuff>> Items(){
        List<Stuff> list = await Items.Task;
        reset();
        return list;
    }
}

then
var tictac = new TicTac<double>();

IObservable<double> source = ....

source.Subscribe(x=>tictac.Push(x));

Then in your worker
while(true){

    var items = await tictac.Items();

    Thread.Sleep(100);

    for each (item in items){
        Console.WriteLine(item);
    }

}

A: The way I have done this before is to pull up the ObserveOn method in DotPeek/Reflector and take that queuing concept that it has and adapt it to our requirements. For example, in UI applications with fast ticking data (like finance) the UI thread can get flooded with events and sometimes it cant update quick enough. In these cases we want to drop all events except the last one (for a particular instrument). In this case we changed the internal Queue of the ObserveOn to a single value of T (look for ObserveLatestOn(IScheduler)). In your case you want the Queue, however you want to push the whole queue not just the first value. This should get you started.

A: Kind of an expansion of @Enigmativity's answer. I have used this to solve the problem:
public static IObservable<(Action ready, IReadOnlyList<T> values)> BufferUntilReady<T>(this IObservable<T> stream)
{
    var gate = new BehaviorSubject<Guid>(Guid.NewGuid());

    void Ready() => gate.OnNext(Guid.NewGuid());

    return stream.Publish(shared => shared
        .Buffer(gate.CombineLatest(shared, ValueTuple.Create)
            .DistinctUntilChanged(new AnyEqualityComparer<Guid, T>()))
        .Where(x => x.Any())
        .Select(x => ((Action) Ready, (IReadOnlyList<T>) x)));
}

public class AnyEqualityComparer<T1, T2> : IEqualityComparer<(T1 a, T2 b)>
{
    public bool Equals((T1 a, T2 b) x, (T1 a, T2 b) y) => Equals(x.a, y.a) || Equals(x.b, y.b);
    public int GetHashCode((T1 a, T2 b) obj) => throw new NotSupportedException();
}

The subscriber receives a Ready() function to be called when ready to receive next buffer. I don't observe each buffer on the same thread to avoid cycles, but I guess you could break it some other place, if you need each buffer to be handled on the same thread.


text:
Q: Adding a django variable to css I'm generating a PDF, with django. In my css I use @bottom-left to show the pages, and I would like @bottom-right to show the date and hour when the pdf was generated. I would like to pass this date that I have in a variable to this "content: datetime". Does anyone know if it's possible, and if not, any other alternatives?
@page {
    size: letter;
    @bottom-left {
        content: counter(page) " of " counter(pages);
        font-family: 'Prompt', sans-serif;
        font-weight: 300;
        font-size: 9px;
        color: #868484;
    }
    @bottom-right {
        content: 'datetime';
        font-family: 'Prompt', sans-serif;
        font-weight: 300;
        font-size: 9px;
        color: #868484;
    }
}


text:
Q: Anyone commiting (regenerating snapshot artifacts) forces others to rebuilt their projets to keep what they are working on. It's the correct behavior? I encounter this situation at work :

*

*I checkout a projet and start developing on it.

*Others snapshots artifacts are downloaded at build time, coming in handy to create the whole application.

*During the day, others developers are working. Some commits changes.

*The night, snapshot artifact repository receives new snapshots artifacts including them.

*In the morning, if I wan't to ensure my own project to retain its own behavior, I have to recompile it, and any sub-projets I have checkout to modify them. Else, snapshots artifacts mingle in my current application and its behavior isn't the one I have left the day before, under Eclipse.

Is it the correct behavior of Maven that I am seeing ?
Myself, I do not have any -U update-snapshot-dependencies written anywhere in my Maven settings. Could admins have enforced it somewhere causing what I'm seeing ?
Shouldn't a setting take place to force local artifacts to override snapshots ones, if it's possible ?

A: The behavior is correct and I believe it plays in your favor. It's better discovering integration problems sooner that later. If you discover that your code isn't working with other colleagues code it's a lot easier to solve the issue immediately while the context is fresh in your heads. Postponing it for few days will only increase the time necessary to do a proper integration.


text:
Q: Запрос на получение ссылки Как получить href ссылку из https://bookvoed.ee/search?q=white+fang?
x = soup.findAll("div", {"class": "o-row"})
for link in x:
    link = link.find('a').get('href')
    print(link)

Код выводит не то, что нужно

A: Причина в том, что ваш поиск возвращал первый тег <a>, а т.к. поиск был только по тегу, то и получали первый попавшийся.
Нужно было в поиске указывать class='title'.
CSS-селектор:

*

*.o-row – поиск элементов с class="o-row"

*a.title – поиск элементов с <a class="title">
Пример:
from urllib.parse import urljoin

from bs4 import BeautifulSoup
import requests

rs = requests.get('https://bookvoed.ee/search?q=white+fang')
root = BeautifulSoup(rs.content, 'html.parser')

for row in root.select('.o-row'):
    a = row.select_one('a.title')
    href = urljoin(rs.url, a.get('href'))
    title = a.get_text(strip=True)
    print(title, href)

# White Fang https://bookvoed.ee/goods/4496177
# Белый клык = White Fang https://bookvoed.ee/goods/6807168
# The Call of the Wild and White Fang https://bookvoed.ee/goods/8654867
# White Fang [= Белый Клык] https://bookvoed.ee/goods/451827
# Call of the Wild & White Fang https://bookvoed.ee/goods/4914246

PS.
В href хранятся относительные ссылки, поэтому для удобства добавил код конвертирования в абсолютные ссылки через urljoin


text:
Q: Comparing a std::string_view and a substring string_view Let's say that we have a string_view and another string_view that is a subset of the first string_view:
using namespace std; // just to shorten the example...

string_view s{"abc def"};
auto t = s.substr(4);
auto u = s.substr(0, 4);

cout << *(s.begin() + 4) << "  " << *t.begin() << '\n';
cout << ((s.begin() + 4) == t.begin());
cout << (s.end() == t.end());
cout << ((s.begin() +5) == t.begin());
cout << ((s.begin() +5) == (t.begin() + 1));
cout << ((s.begin() + 4) == u.end()); // true

All the comparisons would work on Linux under gcc (9 HEAD) and clang (8 HEAD). Under Windows Visual c++ (15.7.6) the comparison of two iterators is not allowed (in debug mode you get an assert error cannot compare incompatible string_view iterators for equality).
Next is pointer comparison:
string_view s{"abc def"};
char const*& it{...}; // contains pointer to some location in s
auto t = s.substr(4);

it == s.end(); // works in gcc/clang - fails to compile in Visual studio

So when you try to fix it in Visual C++ you want to compare addresses it == &*s.end() but this fails as end() iterator is not supposed to be dereferenced (UB if I remember correctly) so you get cannot dereference end string_view iterator.
boost::string_view supports it == s.end() comparison so I'm surprised that the std implementation is more limiting (and thereby far less user friendly for cross platform work)
I understand that iterator comparison of two different containers is UB but string_view is not a container (it doesn't own underlying memory) it's some form of a smart pointer so I would expect the language to allow me to compare such iterators trusting me that the views are pointing to a different (or same) subset of the same container.
So my question is how can I make something like this work with string_view only?
(Meaning without needing to create a custom range class that will contain two iterators as this would defeat the purpose of using std::string_view in the first place)

A: You appear to want to work with raw pointers.
If you want to work with raw pointers, use .data() instead of .begin() and .data()+.size() instead of end().
These pointers behave like you want string view iterators to behave.
If you need iterators back, ptr-.data()+.begin() reconstructs an iterator (and it-begin()+.data() round trips back to ptr).


text:
Q: how to test bits of an integer in Assembly How do I test for the least significant bit that's unset if I'm given an integer N.
My first attempt (gas syntax):
#define N      %ecx
#define return %eax

 /* prototype:
  * int leastSigUnsetBit(unsigned int N)
  */

.text
.global leastSigUnsetBit
leastSigUnsetBit:

movl N, 4(%esp)

movl $-1, return
Loop:
    inc return
    bt return, N
    jc Loop
ret

A: You can test the lsb set using bsf (bit scan forward) or even better using tzcnt
I hope you are aware of the fact that bsf will return undefined data when the operand is zero.  tzcnt fixes that.
If you want to test the LSB that's unset, you just invert the input using not and then test for the LSB set.
Note that tzcnt is both (nearly) reverse compatible and faster than bsf. tzcnt will be read by an old cpu as rep bsf reg,reg, however tzcnt modifies the flags differently from bsf:
bsf: ZF=0 -> input was 0.
tzcnt: ZF=0 -> output is 0, CF=0 -> input was zero.

The best solution is to use tzcnt, but make sure you've tested that the cpu supports tzcnt (or it will execute a bsf and your code will give incorrect results).
;Intel syntax
mov eax,not(-1)
tzcnt edx,eax     ;edx = 32
mov eax,[random]
not eax
tzcnt eax,eax

The other alternative is to test whether the operand is zero and adjust accordingly.
bsf does alter the flags correctly, you can use that to compensate.
From: http://www.felixcloutier.com/x86/BSF.html

BSF
  .....
  Flags Affected
The ZF flag is set to 1 if all the source operand is 0;

not eax
mov edx,32
bsf eax,eax
cmovz eax,edx         //force result to 32 if zero inputted.

Note that as a matter of principle I don't write AT&T syntax, you'll have to reverse the operands where applicable.
tzcnt runs a lot faster than bsf (because the cpu does not it does not have to do undefined behaviour emulation).


text:
Q: Find maximum value of $\left|u-2i\right|^2+2\left|v+i\right|^2$ with conditions. $u$ and $v$ are two complex numbers such that $\left|u^2+uv-2v^2-3i\left(u+2v+2\right)+8\right|=44$ and $\left|u+2v\right|=6$. Find maximum value of $T=\left|u-2i\right|^2+2\left|v+i\right|^2$.
I have tried and get some interesting things, but haven't known how to do next, can you help me?
We can easily have $\left|\left(u+2v\right)\left(u-v\right)-3i\left(u+2v\right)-6i+8\right|=44$. With $u+2v=x$ and $u-v-3i=y$, we have $|xy-6i+8|=44$ and $|x|=6$. Interestingly, $v=\frac{x-y}{3}-i$ and $u=\frac{x+2y}{3}+2i$. Now we only need to find max of $|x+2y|^2+2|x-y|^2$.

A: Substituting $\alpha = 6i-8$, $z = xy - \alpha$ and $w=x^2$ you can reduce to maximize
$$|w+2z+2\alpha|^2 + 2|w-z-\alpha|^2  =
6(z\overline\alpha + \overline z\alpha)
$$
where we have removed the constant factors coming from $|w|=36$ and $|z|=44$. Adding again $|z|^2$ and $9|\alpha|^2$ you get to maximize
$$|z+3\alpha|^2$$
but since $|z|$ is constant, you have the maximum for $z=|z|\alpha/|\alpha|$. Notice that $w$ (and thus $x$) does not affect the problem anymore, so we can fix any $|x|=6$, and then compute $y$ from $z$.
retrace back the substitutions to find $u,v$.


text:
Q: woocommerce_cart_updated hook is not working as expected - WooCommerce I have a plugin that uses woocommerce_cart_updated hook to do something when the cart contents change.
woocommerce_cart_updated seems to be fired on every page load.

Is there any way to restrict this hook in some pages like
my-account.?

Is there any single hook that I can call on any cart updated ( add , remove / update quantity/restore).?

By using different hooks - there is some workaround for this.
do_action( 'woocommerce_add_to_cart', $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data );
do_action( 'woocommerce_cart_item_removed', $cart_item_key, $this );
do_action( 'woocommerce_cart_item_restored', $cart_item_key, $this );
do_action( 'woocommerce_after_cart_item_quantity_update', $cart_item_key, $quantity, $old_quantity );

Is there any option to get the pagename or slug in the callback
function of this hook. ( woocommerce_cart_updated ). So I can restrict this action in some pages.?

But as far as I can tell — it's being run even when the session variables haven't been updated. It's being fired all the time, no matter what.


text:
Q: multiple ng-repeat with ng-if expression i have installments lists of banks comes with json and i want to repeat the list that whetever bank support installment count or not on payment page. list must be count up to 9 starting from 2.
this is the json (includes only first bank)
    [{
      "Installments": [{
        "InstallmentId": 9,
        "InstCount": 2,
        "InstRate": 0,
        "BankId": 1,
        "Info": false
      }, {
        "InstallmentId": 10,
        "InstCount": 3,
        "InstRate": 0,
        "BankId": 1,
        "Info": false
      }, {
        "InstallmentId": 11,
        "InstCount": 4,
        "InstRate": 7.30,
        "BankId": 1,
        "Info": false
      }, {
        "InstallmentId": 12,
        "InstCount": 5,
        "InstRate": 0,
        "BankId": 1,
        "Info": false
      }, {
        "InstallmentId": 13,
        "InstCount": 7,
        "InstRate": 4.50,
        "BankId": 1,
        "Info": false
      }, {
        "InstallmentId": 14,
        "InstCount": 9,
        "InstRate": 11.28,
        "BankId": 1,
        "Info": false
      }],
      "BankId": 1,
      "BankName": "Garanti",
      "IsInstallments": false,
      "BankLogo": "img/bank/cards-01.png"
    }, {
      "Installments": [...],
      "BankId": 2,
      "BankName": "Advantage",
      "IsInstallments": false,
      "BankLogo": "img/bank/cards-05.png"
    }, {
      "Installments": [...],
      "BankId": 3,
      "BankName": "Finansbank",
      "IsInstallments": false,
      "BankLogo": "img/bank/cards-03.png"
    }]

this is the html markup:

{{i}} TAKSİT

disabled

disabled

{{bank.Installments[i-2].InstCount}} TAKSİT

 {{ newPrice | number:2 }} TL

  {{ installedPrice | number:2 }} TL X {{bank.Installments[i-2].InstCount}} ay

this is what i get (screenshot):
http://aslanbakan.com/down/bank-error.PNG
this is what i want to achive (screenshot):
http://aslanbakan.com/down/bank-achive.PNG
I don't know where i did the mistake.

A: As far as I can understand, you want to display only those banks that have an Installment.
You checked for
bank.Installments[i-2].InstCount == undefined

But you need to check the typeof attribute equals undefined, like this:
typeof bank.Installments[i-1].InstCount === 'undefined'

Updated the pen you provided: http://codepen.io/anon/pen/dozpBE


text:
Q: WebView Local Html And Canvas? So as for experiments, I was messing around with the WebView component and playing around with loading in local HTML files. Now what i want to figure out, is say i have a canvas element within my Local HTML file, and i'm rendering a game in the canvas. How do I communicate my React-Native code with the local HTML's canvas script? I've searched up how to communicate with HTML webview code and react-native and they say that WebView has a prop called injectedJavaScript that requires a string of code to execute to the webview. Check the docs here. https://facebook.github.io/react-native/docs/webview
But how on earth would I handle a game from the canvas code in this instance with just the injectJavaScript prop??? Is there another way of allowing communication between my react-native code and the local HTML/JS webview code???
Side note also check this website, which also enhances my explanation of what i want aswell. Although i'm still not sure how to properly do my game/canvas code with stringified js code...
https://www.undefinednull.com/2015/12/27/injecting-custom-javascript-into-react-natives-webview/
Any of your guys's answers are worth so much too me right now, i've been trying to figure this thing out for a week now...

A: For communication between Java or Kotlin code to Javascript in Android in a WebView the only way would be via the annotation @JavascriptInterface which basically provides the defined method to the JavaScript code.
You can also call functions defined in Javascript from your Java / Kotlin code. However, I would advise you to bind those functions to window. So you have a function in JS like: window.test().
There is also this great Article in the Android documentation which explains how to implement this.


text:
Q: Icon not displaying in flutter Ok, so I'm trying to implement a custom icon in flutter but it's not rendering the image.
enter image description here
Font code:
fonts:
      family: icon
      fonts:
            asset: assets/fonts/MyFlutterApp.ttf

Icon code:
icon: new Icon(const IconData(0xe800, fontFamily: 'icon'))


text:
Q: Custom Page tagging in Google Analytics I want to have custom page tags, which are different from URLs I have, in my Google Analytics report page.
For instance,

*

*Actual URL : /news/today_news.php

*Page tag on Google Analytics : /news/today_news.php/Category.News/TodayNews

How can I make the custom page tag with Google Analytics Data Collection API?

A: There are several straightforward ways to do this (change the GA default name for a given page on your GA-tracked Site).
I. Passing the custom name in as a parameter to "_trackPageview"
This is probably the most common way to do this and probably the most straightforward.
The primary GA Method, _trackPageview, is usually called without passing in any parameters, i.e., pageTracker._trackPageview().
You can however, pass in a string for the name you wish to use for that page. In other words, find the call to _trackPageview on each page whose name you wish to change and insert your new name as a string between the parentheses, e.g.,
pageTracker._trackPageview("the_new_name_for_this_page");

Strictly speaking, the parameter you pass in actually changes the Request URI value to the string you passed in.
To verify: open the relevant Profile in your GA account, then click "Content" in the left-hand side menu, then "Top Content." This will cause a Table to render in the main viewing window of the GA Browser. The left-most column of that Table displays the Page (actually the Request URI). Check the contents of this column for your re-named pages.
GA uses two ways to identify pages in their Reports under the "Content" rubric--by Request URI and by Page Title. The Table displayed when you click on "Top Content" for instance, shows the former in the left-most column (the column is named "Page.") On the other hand, the Table displayed when you click the Report just below "Top Content", which is "Content by Title", shows pages by their title ("Page Title" is the left-most column header). "Page Title" here just refers to whatever appears between the title tag in the head of your page. In other words, the two techniques i just mentioned will not affect the Page's Title (the report "Content by Title" will not be changed).
II. Use a "Filter"
For instance, GA has a custom filter type called a "search and replace" filter, which is probably the best option among the GA filter types. The advantage of this techniques is that it doesn't require any code in the page.
Click "Analytics Settings" > "Profile Settings" (top left in the orange navigation bar), then scroll until you see "Filters Applied to this Profile"; click "+ Add Filter" to the far right. Because each filter type (pre-defined versus custom, which in turn is comprised of six different filter types) is set differently, it's probably best if i just refer you to a relevant GA resource.
III. Use "Custom Variables"
This is technique requires the most effort (though it's still not difficult); it's also the most sophisticated of the three techniques; for instance, using CVs you can re-map a given page to more than one name, which is useful when you want to group your content hierarchically. So for instance, you might wish give a particular page in your e-commerce Site three labels, to describe merchandise category, sex, and Brand, e.g., "Footwear", "Men's", and "Teva", or "Footwear/Mens/Teva". So for instance,
pageTracker._setCustomVar(
        1,                     // 'Index' for this CV (an integer, 1-5)
       "MerchandiseCategory",  // 'Name' for this CV
       "Footwear",             // 'Value'--set upon call to _trackPageview
        3,                    // 'Scope' an integer, 1-3, use '3' here because
                             //  i have scoped this particular CV to 'page level'
                             //  (1 and 2 are for visitor and session, respectively)
)

The code above initializes the CV, so it needs to be placed before your call to _trackPageview, because it's that call that sets the value of this variable.
After you've done this, and data has been recorded for your CVs, then you can begin using them. Remember, CVs are not Reports per se, rather than are indeed 'variables' which is much better because you can use them to create any reports you wish through the "Custom Reporting" feature in GA.
For instance, click "Custom Reporting" in the middle of the left-hand navigation panel in the GA Browser (once you have selected a particular profile). Then click "Custom Reports" then "+ Create new custom report" in the top right hand corner. Now click "Dimensions", the green navigation 'button' on the left-hand side, then click "Visitors." Scroll through the values for the 'Visitor' Dimension, and near the end of the list you will see additional values reserved for Custom Variables. If for instance, you had defined a CV called "Visitor Type" with possible values of "RegisteredUser" and "Prospect", that CV would show up here and therefore be available for you to use to create Custom Reports.
Here's what i believe is the Google Analytics Team's most useful explanation of Custom Variables.
And here is an excellent Blog post from a GA Consultant on CVs.


text:
Q: macOS Sierra Virtual-host not working About a month ago I updated my Macbook Pro from El capitan to Sierra.
From that moment my mysql and apache wound't work anymore.
I managed to fix those two (mysql only works now with sudo mysql.server start).
But my Vhost still won't work. So far I've managed to work on my projects local trough surfing to: localhost/projects/projectname.
Which is an issue sometimes with the paths that are configured inside a website.

A: Apparently the httpd-vhost.conf and hosts file that are used by apache on Sierra are in an other location than on El Captain.
So I was using the wrong one.


text:
Q: Has the VB.NET compiler warning BC42324 been removed in VS2013? I recently installed VS2013 (alongside a previous VS2010 installation) and noticed I no longer receive the compiler warning 'BC42324' (text below) when compiling identical VB.NET code (I recompiled back in VS2010 to confirm warning is still shown):

Using the iteration variable in a query expression may have
  unexpected results.  Instead, create a local variable within the loop
  and assign it the value of the iteration variable.

Documentation on MSDN seems to suggest the warning is still included. I see/don't-see the warning with the following code :
Dim Numbers = {0, 1}
For Each index In Numbers
  Dim SumPlusIndex = Aggregate x In Numbers Select x + index Into Sum()
Next

Has this warning genuinely been removed? Is so how come? If not could there be other environmental differences between my VS2010 and VS2013 installation that might cause the difference?

A: Yes, that's the infamous capture the for loop variable bug.  It has bitten many programmers so Microsoft decided to do something about it.  They solved it for a For Each loop, but not a For loop.  You can still trigger the warning like this:
Sub Main()
    For ix As Integer = 1 To 10
        Dim dlg = Sub()
                      Console.WriteLine(ix)    '' Eek!
                  End Sub
        '' etc...
    Next
End Sub


text:
Q: Extend Object Type and Overwrite Property in Flow In TypeScript, I am able to do the following:
interface MyObj {
    a: 'foo' | 'bar'
}

interface MyExtObj extends Pick<MyObj, Exclude<keyof MyObj, 'a'>> {
    a: MyObj['a'] | 'baz'
}

const test: MyExtObj = {
    a: 'baz' // Works fine, as well as 'foo' and 'bar'
}

Is it possible to do that with Flow object types and if so, how? The following example fails...
/* @flow */

type MyObj = {
    a: 'foo' | 'bar'
}

type MyExtObj = MyObj & {
    a: $PropertyType<MyObj, 'a'> | 'baz'
}

const test: MyExtObj = {
    a: 'baz' // Cannot assign object literal blah blah ...
}

A: Like this?
/* @flow */

type MyObj = {|
    a: 'foo' | 'bar'
|}

type MyExtObj = {|
    ...MyObj,
    a: $PropertyType<MyObj, 'a'> | 'baz'
|}

const test: MyExtObj = {
    a: 'baz' // Cannot assign object literal blah blah ...
}

You can test here

A: This also works, in case you don't want to make MyObj exact for some reason:
/* @flow */

type MyObj = {
    a: 'foo' | 'bar'
}

type MyExtObj = {|
    ...$Exact<MyObj>,
    a: $PropertyType<MyObj, 'a'> | 'baz'
|}

const test: MyExtObj = {
    a: 'baz' // Cannot assign object literal blah blah ...
}


text:
Q: Make safari open new tab from context menu in background In Mac OS Safari, when we select a word, open the context menu and run 'Search with google', the result comes in a new tab and it becomes the active tab automatically. Is there someway for that tab to open in background?

There is an option in tab preferences but that doesnt apply to tabs opened from context menu.


text:
Q: Load test on Azure I am running a load test using JMeter on my Azure web services.
I scale my services on S2 with 4 instances and run JMeter 4 instances with 500 threads on each.
It starts perfectly fine but after a while calls start failing and giving Timeout error (HTTP status:500).
I have checked HTTP request queue on azure and found that on 2nd instance it is very high and two instances it is very low.
Please help me to success my load test.

A: I assume you are using Azure App Service. If you check the settings of your App, you will notice ARR's Instance Affinity will be enabled by default. A brief explanation:

ARR cleverly keeps track of connecting users by giving them a special cookie (known as an affinity cookie), which allows it to know, upon subsequent requests, to which server instance they were talking to. This way, we can be sure that once a client establishes a session with a specific server instance, it will keep talking to the same server as long as his session is active.

This is an important feature for session-sensitive applications, but if it's not your case then you can safely disable it to improve the load balance between your instances and avoid situations like the one you've described.
Disabling ARR's Instance Affinity in Windows Azure Web Sites

A: It might be due to caching of network names resolution on JVM or OS level so all your requests are hitting only one server. If it is the case - add DNS Cache Manager to your Test Plan and it should resolve your issue.
See The DNS Cache Manager: The Right Way To Test Load Balanced Apps article for more detailed explanation and configuration instructions.


text:
Q: Inverse Transform Sampling from Discrete Uniform Distribution I understand that in simulation, inverse transform sampling means that I first generate a uniformly distributed value $u$ and then use $F^{-1}(u)$ to get a value according to the distribution $F$. If I need a sample size of 1000, then I repeat the above process 1000 times (i.e., 1000 iterations). I am wondering whether the following approach works.
Instead of generating uniformly distributed random values in the 1000 iterations, I get 1000 values equally spaced between 0 and 1, i.e., $0,0.001,0.002,...,0.999,1$ and use each of these values in each iteration. In this case, I get the most "representative" uniformly distributed value and the corresponding $F^{-1}()$ of these values has a histogram that perfectly matches the theoretical PDF. Is this method valid? If not, what are the issues? Thanks.


text:
Q: Django - Query parameter takes model type? RelatedObjectDoesNotExist: Posting has no textbook I have installed this Django app: http://django-auditlog.readthedocs.io/en/latest/_modules/auditlog/models.html#LogEntry
The log entries are setup with two different models which are below:
class Posting(models.Model):
    textbook = models.ForeignKey(Textbook)
    condition = models.CharField(max_length=200)
    price = models.DecimalField(max_digits=5, decimal_places=2)
    user = models.ForeignKey(User)
    image = models.ImageField(upload_to='postingpics/%Y/%m/%d', default="/textchange/nophoto.png")
    post_date = models.DateTimeField('date_posted')
    comments = models.CharField(max_length=50, default="")

    def __str__(self):
        return str(self.textbook)

    def was_posted_recently(self):
        return self.post_date >= timezone.now() - datetime.timedelta(days=1)
    was_posted_recently.admin_order_field = 'post_date'
    was_posted_recently.boolean = True
    was_posted_recently.short_description = 'Posted recently'

class Wishlist(models.Model):
    textbook = models.ForeignKey(Textbook)
    user = models.ForeignKey(User)
    wish_date = models.DateTimeField('date_wish')

    def __str__(self):
        return str(self.textbook)

    def was_wished_recently(self):
        return self.wish_date >= timezone.now() - datetime.timedelta(days=1)
    was_wished_recently.admin_order_field = 'date_wish'
    was_wished_recently.boolean = True
    was_wished_recently.short_description = 'Wished recently'

auditlog.register(Posting)
auditlog.register(Wishlist)

So in the database the model EntryLog is getting a row each time something happens to Posting or Wishlist whether that be delete, create, or update.
I am trying to complete the query below because I want to count the number of occurrences that a Posting is deleted. Separately I will do the same query for Wishlist.
LogEntry.objects.filter(action=2 , content_type=Posting).count()

content_type is of type Foreign key for the record.
When I run this query I get the error message:
RelatedObjectDoesNotExist: Posting has no textbook.

This makes me think that Posting is the wrong value to put in for content_type. Am I thinking about this correctly? Should the value for content_type be something different? I understand usually when you refer to a Foreign Key you are querying on the Foreign keys fields like Posting__condition or something like that.
Thanks in advance.

A: The content_type argument should be a ContentType object, not a model class.
Instead of doing doing this manually you should use the LogEntryManagers get_for_model method:
LogEntry.objects.get_for_model(Posting).filter(action=2).count()


text:
Q: How to preserve inventory when migrating from BDS to Realms? I have been running a BDS Minecraft server in windows. I now want to move my and my friend's world to Realms. I took the level folder out of the worlds folder and put it in the minecraftWorlds folder on my iPad using iFunBox. I made a copy of the world to test with. While the world is the same, I have lost my inventory. How can I preserve my and my friend's inventories?

A: The "local" player inventory is separate from remote player inventories. You don't need to worry about your friends encountering this problem provided your account owns the realm as they will always be "remote" players and have their inventory match up.
I have not tested whether uploading a world file where you are a remote player to a realm owned by you would give your player the same problem or whether realms is smart enough to reconcile the inventories. An easy work-around is simply to dump your inventory into a chest, save and quit, then upload the world.


text:
Q: Fill arrays with data from block of string in java I want to fill 4 arrays with specific data from block string
I got blocks like this

00:0035:0063:1705211023:00:
  11::7027661000300976376:
  99:59:07027661000300976376:::::
  05:11:10000:::00 09:11:8510 07:::::1490:::
  99:65:00:00:00:00:00:01000000000002140331410062269000000126300000000
  99:64:00:00:00:00:00:00000355600200000000022700000000000000000001
  99:01:227:1490:30:0:0:0:0:0:1:0:324
  ****Segundo Ticket PANGUI**** 99:00:35:63:1705211023:0:1:19353:63895896:1490:0:::::
  99:150:0|1|H014|35|63|210517102100|

and I want to check if  00:.. , 05:11:.. ,  99:65.. , 99:64... and 99:01...headers exists and stores data for specific field from each row, for example in line or row 99:65.. I will store the last field. If no exists one or more, I must be store zero, something like this
if exist 99:11 then Arr11 =specificfieldfrom9911, else arr11 = "0"
So that for each block have a structure or set of arrays that identifies the fields of each block
Arr00
Arr0511
Arr9965
Arr9964
Arr9901
how can I achieve this? any help would be great.

A: after you get the individual string you can use startsWith("") method on the strings. Eg. Assuming the string that came is on a variable called inputString you can use
if(inputString.startsWith("99:65")){
//do what you want to do
}

i hope this helps


text:
Q: SchemaFactoryConfigurationError when trying to generate the JAXWS I am trying to access SOAP web service written using C# .NET Framework with a java client application. Therefore in my client program I have added a web service client and gave the WSDL url. When I click next I am getting the following error.
Stack Trace
    javax.xml.validation.SchemaFactoryConfigurationError: Provider for class javax.xml.validation.SchemaFactory cannot be created
    at javax.xml.validation.SchemaFactoryFinder.findServiceProvider(SchemaFactoryFinder.java:414)
    at javax.xml.validation.SchemaFactoryFinder._newFactory(SchemaFactoryFinder.java:218)
    at javax.xml.validation.SchemaFactoryFinder.newFactory(SchemaFactoryFinder.java:145)
    at javax.xml.validation.SchemaFactory.newInstance(SchemaFactory.java:213)
    at com.sun.tools.xjc.api.impl.s2j.SchemaCompilerImpl.bind(SchemaCompilerImpl.java:234)
    at com.sun.tools.xjc.api.impl.s2j.SchemaCompilerImpl.bind(SchemaCompilerImpl.java:94)
    at com.sun.tools.ws.processor.modeler.wsdl.JAXBModelBuilder.bind(JAXBModelBuilder.java:142)
    at com.sun.tools.ws.processor.modeler.wsdl.WSDLModeler.buildJAXBModel(WSDLModeler.java:2244)
    at com.sun.tools.ws.processor.modeler.wsdl.WSDLModeler.internalBuildModel(WSDLModeler.java:191)
    at com.sun.tools.ws.processor.modeler.wsdl.WSDLModeler.buildModel(WSDLModeler.java:137)
    at com.sun.tools.ws.wscompile.WsimportTool.buildWsdlModel(WsimportTool.java:381)
    at com.sun.tools.ws.wscompile.WsimportTool.run(WsimportTool.java:198)
    at com.sun.tools.ws.wscompile.WsimportTool.run(WsimportTool.java:179)
    at com.sun.tools.ws.ant.WsImport2.execute(WsImport2.java:835)
    at com.sun.istack.tools.ProtectedTask.execute(ProtectedTask.java:103)
    at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:292)
    at sun.reflect.GeneratedMethodAccessor96.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
    at org.apache.tools.ant.Task.perform(Task.java:348)
    at org.apache.tools.ant.Target.execute(Target.java:435)
    at org.apache.tools.ant.Target.performTasks(Target.java:456)
    at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1393)
    at org.apache.tools.ant.Project.executeTarget(Project.java:1364)
    at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
    at org.apache.tools.ant.Project.executeTargets(Project.java:1248)
    at org.apache.tools.ant.module.bridge.impl.BridgeImpl.run(BridgeImpl.java:286)
    at org.apache.tools.ant.module.run.TargetExecutor.run(TargetExecutor.java:555)
    at org.netbeans.core.execution.RunClassThread.run(RunClassThread.java:153)
Caused by: java.util.ServiceConfigurationError: javax.xml.validation.SchemaFactory: jar:file:/C:/Program%20Files/Java/jdk1.8.0_05/lib/M%20yWebLib/xercesImpl.jar!/META-INF/services/javax.xml.validation.SchemaFactory:1: Illegal provider-class name: http\://www.w3.org/2001/XMLSchema=com.sun.org.apache.xerces.internal.jaxp.validation.xs.SchemaFactoryImpl
    at java.util.ServiceLoader.fail(ServiceLoader.java:239)
    at java.util.ServiceLoader.fail(ServiceLoader.java:245)
    at java.util.ServiceLoader.parseLine(ServiceLoader.java:272)
    at java.util.ServiceLoader.parse(ServiceLoader.java:307)
    at java.util.ServiceLoader.access$200(ServiceLoader.java:185)
    at java.util.ServiceLoader$LazyIterator.hasNextService(ServiceLoader.java:357)
    at java.util.ServiceLoader$LazyIterator.access$600(ServiceLoader.java:323)
    at java.util.ServiceLoader$LazyIterator$1.run(ServiceLoader.java:396)
    at java.util.ServiceLoader$LazyIterator$1.run(ServiceLoader.java:395)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.util.ServiceLoader$LazyIterator.hasNext(ServiceLoader.java:398)
    at java.util.ServiceLoader$1.hasNext(ServiceLoader.java:474)
    at javax.xml.validation.SchemaFactoryFinder$2.run(SchemaFactoryFinder.java:403)
    at javax.xml.validation.SchemaFactoryFinder$2.run(SchemaFactoryFinder.java:399)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.xml.validation.SchemaFactoryFinder.findServiceProvider(SchemaFactoryFinder.java:399)
    ... 29 more

If you need my XML I can post that as well.
As I am quite new to programming please give me a detailed answer. Thanks in advance.

A: Add the java client in the default package. Because the WSDL file will create some new packages. Therefore you have to add the web service client to the default package.


text:
Q: Angular Controls/ generating array from number I have a number in my application value is 6,
by using this value i have to create an array of [1, 2, 3, 4, 5, 6] using javascript/typescript
i have tried this in my application
 this.builder.group({
          'staff': this.builder.group({
          staff: [false],
          id: [this.staffData[i].users[j].id],
          labelName: [this.staffData[i].users[j].name],
          controlname: ['staff'],
          cssclass: ['error'],
          checked: [false],
          customcss: ['test1'],
          dayid: this.selectedDay,
          number: Array(this.appointmentsData.numberofSlots).fill().map((x,i) => i)})
})

but i am  getting  number as 0 in browser console.
in VSCode also it is showing excepted 1-3 arguments but got 0 (i think it is for fill() method as i am passing 0 values , but i am unable to understand what to pass for fill() arguments)  please help me

A: Array.apply(null, {length: N}).map(Number.call, Number)


text:
Q: a tutorial for making a flexible database for CMS I want to make one, flexible cms that will serve all my websites without me having to touch the code.
I want it to be very flexible from a forum website thruogh simple CMS to recursive categories tree.
A link to some guide about planning the database and PHP code could be very helpful!

A: A great idea would be to look at some of all the excellent CMS implementation that already exists as open source. How do they do it ? What are the weaknesses and strength with each approach ?
Unless you are doing this to learn - remember that writing a CMS is a solved problem, for any cases I can come up with (in order words - think twice, do you really need to roll your own ?).

A: try www.thetutlage.com , i found some awesome tutorials there like making quiz system and a lot, he also has a video series on cms system in php which is about 30 videos lonng


text:
Q: How to force JTable to NOT invert text in the case it contains arabic characters? I have the following text:
وزا.word
But when displaying it on my JTable it looks like this:
word.وزا
In every JLabel or TextArea or any other input it does look like the original text:
وزا.word
ONLY on the JTable I am having such problem.
I do not care if it is making sense or not, and yes I know the Arabic Language is written from right to left. My guess is Java is detecting it and automatically inverting it, but I do not want it to.
Note: I have no idea what وزا means, and for practical purposes I don't care. It's also irrelevant for this case wether وزا.word does not make sense and word.وزا does or viceversa.
Note 2: The text, reversed or not is always aligned to the left (as I expect it to).
Thanks in advance.

A: At a guess, your default Locale is giving the default renderer a ComponentOrientation that is inconsistent with your other settings. You might try creating a custom renderer having the preferred orientation using one of the approaches suggested here.
Addendum: java.text.Bidi supports bidirectional reordering; you may be able to use unicode format control code points, as suggested in this Q&A.


text:
Q: Firebase realtime database returns all children instead of the single indicated one by OrderByKey().EqualTo(xxx) I keep public profiles from my users like this:

Using the Unity SDK, I try to fetch a subset of the profiles with this query:
var profileDbRef = GetSharedDBInstance().RootReference.Child("profiles");
Query q = profileDbRef.OrderByKey();
userIds.ForEach(uId => q.EqualTo(uId));
q.GetValueAsync().ContinueWithOnSuccess(snapshot => {
    var profiles = (Dictionary<string, object>)snapshot.Value;
    // here profiles dictionary contains ALL my users, not the ones included in userIds list.
}

I receive all my users in the resulting snapshot. Not sure what's happening here? Is there a bug in the Unity SDK?

A: Turns out q.EqualTo(uId) returns a new query object. So the fix was to change this one line to update the q variable.
userIds.ForEach(uId => q = q.EqualTo(uId));