text:
Q: Not able to read InputStream from RS232 Bluetooth module I am trying to read values from a weighing machine connected to bluetooth module(M143 RS232 Bluetooth Serial Adapter purchased from eBay).I am able to connect the device and i am getting Socket object.But the InputStream is blocking and not able to read data from the stream(inputstream.available() is always returns zero).There is no issue when i write something to the OutputStream.I tried using BufferedReader but no change.Following is the code i tried.
InputStream inputStream = socket.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
   total.append(line).append('\n');
}
//code is not reaching here it is blocking in the while loop
if(outputStream!=null){
  outputStream.flush();
  outputStream.close();
}

A: Are you opening sockets for connection in different threads. There should be 3 threads for connection. This is valid for non-Bluetooth LE. Bluetooth Connectitivty

*

*Connection Thread

*Accept Thread

*Connected Thread

If you use these threads, you will be able to get data using connected thread and you can pass data to main thread using handler, callback or BroadcastReceiver. I use all three of them seamlessly.
If you wish to check whether it works or not, download Bluetooth Terminal app from Play Store. It exactly uses Threads and Handler to display data. You can find one of the Bluetooth Terminal source code too. One of them is open source.
For BLE you can try this link. There are working samples associated with guides.
If you want to be sure your BT device works, download a BT terminal program pc or/and Android and test your device.

A: It is important to note that .read() or .readline() only halts reading when there is a newline or EOF, end of file.
However, socket connection does not have EOF unless the socket transfer is done.
so you could do the two following cases:
1) Change the other side(weighing machine in your case) to add \n or \r after each data transfer to let the Android side know one full set of data was sent.
This keeps the benefit of socket connection.
and you could do
while ((line = r.readLine()) != null) {
    //do what you want to do with line
    //... you dont need string builder in this case
}

2) Halt each connection from the other side after each data transfer. This is not recommended because it is not anymore a socket transfer when you cut after every data transfer. Also it might cause TIME_WAIT and hinder further connections.
I was able to do the first case to solve my problem when I was in your shoes.

A: The execution blocking in reading of InputStream is because of if no bytes are coming from the Socket,the existing thread will wait for a byte to come from the Socket.

A: Communication via bluetooth with other android devices or microcontrollers such as Arduino Android Smooth Bluetooth
// This thread runs during a connection with a remote device.
// It handles all incoming and outgoing transmissions.
private class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket, String socketType) {
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the BluetoothSocket input and output streams
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }


text:
Q: jquery ajax statusCode: 502 function never called Is it incorrect to handle 502 errors in the statusCode: setting? For example:
        $.ajax({
            url : '/path/to/url/',
            type : 'get',
            contentType : 'application/json',
            statusCode : {
                                502: function(){
                                    steal.dev.log('server stopped');
                                }
                            },
            success : function(data) {
                            steal.dev.log('ajax success');
            },
            error : function(jqXHR, textStatus, errorThrown){
                                steal.dev.log('ajax error');
                            },
            complete : function(data){
                                steal.dev.log('ajax complete');
                            }
        });

Thanks.

A: Yeah, the only way the function was called was from the error callback. I guess you can't handle 502's from statusCode.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Create a site to answer on campaign I'm new at site on force.com so I don't have a full vision about it.
I created a site. My need is to display the campaign and then the contact can check the website and answer if he participates or not.
for that, I created two custom objects with master details refering to campaign and contact, because we can't access standard objects on site.
If the contact participates, the field Participate__c on the custom object will change to YES for instance.
Any idea how to do this please?


text:
Q: How can I create multiple node cassandra cluster on local windows machine using VM I have used CCM to create a multiple node cluster on local machine. But to get a better idea and since I am evaluating Cassandra versus other NoSql technologies, I would like to set up a multiple node Cassandra cluster on my local windows 7 machine using VM or something like that. I have downloaded and installed OVA from below:
http://www.planetcassandra.org/install-cassandra-ova-on-vmware/
But that is a single node. How can I create a cluster with multiple nodes ?
Thanks.

A: This can be done using Vagrant to create the VM or with docker containers (although on Windows you'll need a more powerful command line that the one that comes with the OS, like the git shell that comes with Git or Cygwin).
For example, in:
Website: http://joeljacobson.github.io/vagrant-ansible-cassandra/
Github: https://github.com/joeljacobson/vagrant-ansible-cassandra
You can find the instructions (and scripts) to provision a 3 node DSE Cassandra cluster with Opscenter using Ansible and Vagrant.
Or you can also search for other similar projects on Github.

A: This is achieved by creating multiple copies of same ova file in different folders and importing them individually in to VMware player. Once the node has started up, can manipulate config files to create a cluster of nodes.


text:
Q: Verifying no solution of a system of differential (and algebric) equations How can I verifying in a simple way that the following system of differential (and algebric) equations has not solution? The unknown quantities are $Q_d,C_d,C_a,C_i$ and the boundary conditions are $Q_d(0)=0$ and so on. The quantities $Q_a,k_a,k_d,k_o$ are positive constants.
$$\frac{d\left( Q_d C_d \right) }{dx} = k_d \left( C_i - C_d \right)$$
$$\frac{dQ_d }{dx} = k_o \left( C_d - C_i \right)$$
$$Q_a \frac{dC_a }{dx} = k_a (C_a-C_i)$$
$$k_a (C_a-C_i) = k_d \left( C_i - C_d \right)$$
Thank you so much for your time.


text:
Q: Run dart code when a template's contents are instantiated bar is @observable.  When its value changes, new spans are instantiated.
<template iterate="foo in bar">
   <span>{{foo}}</span>
</template>

Is it possible to run dart code right after new spans are created?  I tried to run the code right after changing the value of bar, but at that moment the template still contains old spans.
Thank you for your help!

A: Using the timer to schedule the code to run instead of running the code directly seems to solve my problem.
bar = newValue;
Timer.run(() {
  // run code here
});

The callback seems to be called after new spans are instantiated.


text:
Q: How did Kylo Ren's helmet lock up? In The Force Awakens, prior to interrogating Rey, Kylo Ren removed his helmet. Before he took it off, a small casing in the front of the mask moved upwards.

Was this some kind of a locking mechanism, or what was the purpose of this function? If it got stuck somehow, would it have been impossible for Kylo to remove the mask?

A: Through a face mask hinged mechanism driven by servomotors.
According to the Canon reference book Star Wars: The Force Awakens: The Visual Dictionary, the small casing, you mention, that moves upward in the front of Kylo Ren's helmet, is a face mask connected to the helmet via articulated arms driven by servomotors; a hinged mechanism sealed the mask to the helmet. Although Kylo wore the helmet to make himself appear more intimidating, on rare occasions he would remove it via the servomotors to stare down his opponents with unrestrained malice in his eyes.

https://starwars.fandom.com/wiki/Kylo_Ren%27s_helmet


text:
Q: What is the advantage of embedding a linked list into a data structure? While reading about kernel data structures in FreeBSD, I stumbled on the MBuf. The MBuf contains a pointer to the next MBuf in a chain of MBuf's, implementing a linked list. Each MBuf itself also contains data specific to that node in the linked list.
I'm more familiar with designs that segregate the container type from the value type (consider std::list, or System.Collections.Generic.LinkedList). I'm struggling to understand the value proposition of embedding container semantics into the data type - what efficiencies are gained? Is it really all about eliminating the node instance pointer storage?

A: Consider you have an iterator/pointer to a node in your list. In order to fetch the data you have to:

*

*read the pointer to data from the node

*dereference the pointer you have just read and read the actual data

On the other hand, if the list concept is "embedded" within your data structure, you can read your object in a single memory operation as it is together with the node itself.
Another issue with separated list node and its data, is that the list node itself is small (usually just 2 or 3 pointers). As a result, the memory overhead of keeping such a small structure in memory can matter. You know -- operations such as new or malloc actually consume more memory than they allocate -- the system uses their own tree structures to keep track of where memory is free and where it is not.
In such scenarios, it is beneficial to group things up into a single allocation operation. You could try to keep several list nodes in small bundles, or you can try to connect each node with the data it allocates.
Similar strategy can be seen with intrusive pointers (versus shared pointers), or std::make_shared that packs object and smart pointer data together.

zett42 makes a comment that std::list<T> keeps T together with the node data. This achieves the single memory block as I explained above, but has a different problem: T cannot be polymorphic. If you have a class A and its derivative B, then node<B> is not a derivative of node<A>. If you try hard to insert B into std::list<A>, your object will:

*

*In the best case, cause a compile error (no constructor A::A(const B&))

*In the worst case silently slice B copying only a part representing A into the node.

A typical solution if you want to hold polymorphic objects in a single list is to actually have std::list<A*> instead of std::list<A>. But then you end up with the extra indirection I explained above.
An alternative is to make an intrusive list (e.g. boost::intrusive::list), where the node information is actually a part of A object. Then each node can be a derivative of A without a problem.

A: One big advantage of Intrusive linked list is that you can create a list of preexisting objects without any new allocations. To do this with a std::list of pointers will require memory allocation.
Boost has an intrusive list implementation with justification for use. http://www.boost.org/doc/libs/1_63_0/doc/html/intrusive.html

A:
what efficiencies are gained? Is it really all about eliminating the node instance pointer storage?

I would say less cache misses and then better overall performance (even though linked lists aren't usually cache friendly data structures).
That way, you don't have to follow one more pointer to find your data somewhere in memory and bring them near to your processor for each node.
Moreover, if you construct your nodes in a contiguous area of memory and manage them with a couple of pointers (let's call them a free list and an in-use list, does it sound familiar?), you can have a boost in terms of performance (at least as long as the list doesn't contain many items, otherwise the risk is to jump back and forth in memory). In and deletions have constant time in this case (unless you have to search a node in the list before to insert in a specific position, of course), that is another advantage.

A: One of the key advantages of an intrusive list is that you can have a single node belong to multiple lists cheaply.
You could have, for instance, a collection of items sorted in 3 different ways, corresponding to its entries on 3 different lists. That would be quite clunky to do with std::list, for instance.
The other big advantage in my mind, as @doron mentions, is that list management requires 0 allocations, once you have the objects themselves created.
Boost has some decent discussion of intrusive vs. non-intrusive data structures, with pros and cons.


text:
Q: convert NSDictionary to NSString I am trying to put the content of an NSDictionary into an NSString for testing, But have no idea how to achieve this. Is it possible? if so how would one do such a thing?
The reason I am doing this, Is I need to check the content of a NSDicitonary without the debugger running on my device. as I have to delete the running app from multitasking bar of the ios so I can see if the values I am saving into the dictionary are still available afterwards.

A: Above Solutions will only convert dictionary into string but you can't convert back that string to dictionary.
For that it is the better way.
Convert to String
NSError * err;
NSData * jsonData = [NSJSONSerialization  dataWithJSONObject:yourDictionary options:0 error:&err];
NSString * myString = [[NSString alloc] initWithData:jsonData   encoding:NSUTF8StringEncoding];
NSLog(@"%@",myString);

Convert Back to Dictionary
NSError * err;
NSData *data =[myString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary * response;
if(data!=nil){
 response = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&err];
}

A: You can call [aDictionary description], or anywhere you would need a format string, just use %@ to stand in for the dictionary:
[NSString stringWithFormat:@"my dictionary is %@", aDictionary];

or
NSLog(@"My dictionary is %@", aDictionary);

A: You can use the description method inherited by NSDictionary from NSObject, or write a custom method that formats NSDictionary to your liking.

A: if you like to use for URLRequest httpBody
extension Dictionary {

    func toString() -> String? {
        return (self.compactMap({ (key, value) -> String in
            return "\(key)=\(value)"
        }) as Array).joined(separator: "&")
    }

}

// print:
Fields=sdad&ServiceId=1222


text:
Q: Regarding Visual Force Page standard Controller tags Visual force Page standard Controller code:
<apex:page standardController="Account">
<apex:commandButton action="{!Cancel}" value="Back"/>
<apex:commandButton action="{!Save}" value="Save" />

The above code is Standard Controller Code, which contains standard commandbutton action such as cancel and save
custom object:
<apex:page standardController="Visit__c">
<apex:commandButton action="{!Cancel}" value="Back"/>
<apex:commandButton action="{!SaveNavigate}" value="Save">

The above code contains save and Navigate Option,how they are adding functionality of action called {!SaveNavigate} Manually in custom object.

A: Every StandardController has the same available methods, and SaveNavigate is not one of them. In order to define such a method, you would need to Build a Controller Extension. Without specifying the extensions attribute on your <apex:page>, your included examples should fail to compile.
Markup
<apex:page standardController="MyObject__c" extensions="MyExtension">
    <apex:form>
        <apex:commandButton value="Custom" action="{!saveNavigate}" />
    </apex:form>
</apex:page>

Code
public with sharing class MyExtension
{
    public MyExtension(ApexPages.StandardController controller)
    {
        // any necessary constructor logic
    }
    public PageReference saveNavigate()
    {
        // do stuff
    }
}


text:
Q: jqGrid Export To Excel in ASP.net 2.0 hey i am not using MVC pattern. I am only using ASP.net 2.0 C#. I am using jqGrid 3.6 version.
I know that there is one property excelexport which need to be set true and we have to add one custom button and the on click of that button i have to call jqgrid.excelExport method. but i have to send on complex object to the page how do i send it? I dont want to send the search parameters as query string because my search parameters are going to be too long.

A: You can create this in the C# code:
protected void btnExcel_Click(object sender, EventArgs e)
    {

        string codigo;
        codigo = hdnHtml.Value;

        StringBuilder sb = new StringBuilder();

        StringWriter sw = new StringWriter(sb);

        HtmlTextWriter htw = new HtmlTextWriter(sw);

        Page pagina = new Page();

        HtmlForm form = new HtmlForm();

        Response.Clear();

        Response.Buffer = true;

        Response.ContentType = "application/vnd.ms-excel";

        Response.AddHeader("Content-Disposition", "attachment;filename=Visor.xls");

        Response.Charset = "UTF-8";

        Response.ContentEncoding = Encoding.Default;

        pagina.EnableEventValidation = false;

        pagina.DesignerInitialize();

        pagina.Controls.Add(form);

        pagina.RenderControl(htw);

        Response.Write(codigo);

        Response.End();

    }

}
In the code behind you can repeat this.
Add to propiertes of page:

validateRequest="false"

 <asp:Button ID="btnExcel" runat="server" Text="Export"
                    onclick="btnExcel_Click" /> //create a button

<asp:HiddenField ID="hdnHtml" runat="server" /> // create a  hiddenField

$('[id$=btnExcel]').hide(); // hide the button with jquery function

function exportXls() {

    var tbody = $("#jQGrid_Visor").html();
    var thead = $(".ui-jqgrid-htable").html();
    var htmlTable = "<table>" + thead + tbody + "</table>";
    var strCopy = htmlTable;
    $('[id$=hdnHtml]').val(strCopy); // fill the hidden with the table content
    $('[id$=btnExcel]').click(); // click button hidden
}

In my case I have a menu with the right button that fires the event exportXls, if you want you can leave with C# not hide the button
var eventsMenu = {
            bindings: {
                'actualizar': function(rowid) {
                    //alert('Accion [Actualizar] del elemento ' + t.id);
                    jQuery('#jQGrid_Visor').setGridParam(rowid).trigger("reloadGrid");
                },
                **'exportar': function(rowid) {
                    //alert('Accion [Exportar] del elemento ' + rowid.id);
                    exportXls();**
                },
                'full': function(t) {
                    // alert('Accion [Full Screen] del elemento ' + t.id);
                    window.open("./frmBrwVisorMantencionFullScreen.aspx?cod_flota=" + $('[id$=hdnCodFlota]').val(), "Full_Screen", "scrollbars=NO,Resizable=NO,toolbar=no,location=no,directories=no,status=no,menubar=no,fullscreen=yes");
                },
                'paste': function(t) {
                    alert('Accion [Pegar] del elemento ' + t.id);
                },
                'delete': function(t) {
                    alert('Accion [Eliminar] del elemento ' + t.id);
                }
            }
        };


text:
Q: how I could allocate this struct? (C) I have a struct defined this way:
typedef struct _rule {
    char * patr_ent[100];
    int num_patr_ent;
    char * plan_sal[100];
    int num_plan_sal;
    int ult;
} Rule;

And a variable consisting of an array of Rules:
Rule list_of_rules[100];

What I want to do is just: allocate memory for one "Rule" of list_of_rules -> modify the attributes of this Rule (print scan whatever) -> allocate for the next Rule, etc...
Should I do it this way?
Rule* list_of_rules; /* instead of  Rule list_of_rules[100] */

And allocate:
list_of_rules[0] = malloc (sizeof(struct _rule));

And then do the operations needed?

A: In C, if you write Rule list_of_rules[100];, memory is allocated for every Rule.

If number of Rules are not known at first:
Rule* list_of_rules;
int total=250;
list_of_rules=malloc (sizeof(struct _rule)*total);

A: Your initial proposition is ok:
Rule list_of_rules[100];

As said, your memory is already allocated.
You can also do this if you want to use malloc:
Rule * list_of_rules = malloc(100*sizeof(Rule));

EDIT: considering your comment, I guess you want something like this:
Rule * list_of_rules[100]; // List of POINTERS on Rule
for(unsigned int i=0; i<100; i++)
{
     list_of_rules[i] = malloc(sizeof(Rule));
}

A: Why don't malloc only one struct and then use realloc each type you need to increase the size of the list_of_rules if you want a dynamic mem?
(sorry I can't add comment to the first answer)
EDIT
You can do this I think :
Rule* list_of_rules[100]; //Or any size needed

list_of_rules = (Rule**) malloc( 100*sizeof(Rule*) );

for(unsigned int i=0; i<100; ++i)
{
     list_of_rules[i] = (Rule*) malloc ( sizeof(Rule)) ;
}

A: This code is OK:
Rule *list_of_rules = (Rule *)malloc(sizeof(Rule) * 100);

Hope this could help you.

A: As replied earlier by @Rikayan-Bandyopadhyay

In C, if you write Rule list_of_rules[100];, memory is allocated for every Rule.

But for dynamic memory allocation as you asked for you can allocate (increase currently allocated) memory using realloc() like
Rule* list_of_rules=NULL;
int ruleCounter=1;
/*For further dynamic allocation realloc can be used*/
while(<conditon to stop allocation>){
    list_of_rules= (Rule *)realloc(sizeof(Rule)*ruleCounter);
    /*list_of_rules[ruleCounter-1] is the new rule added dynamically.*/
}


text:
Q: How to create multiple subsets of DataFrame with loop Base DataFrame
df = pd.DataFrame(np.random.randint(0,10,size=(100,6)),columns =
['red','blue','yellow','green','purple','total'])

How do I code this with a loop?
df_x = df[df.columns[[y,5]]]

I'd like to apply this logic to a dataframe with many more columns, but for simplicity sake, boiled down the question into this.
Below is desired output, 5 new dataframes created (Assuming I don't have to type all the 5 lines)
df_red = df[df.columns[[0,5]]]
df_blue = df[df.columns[[1,5]]]
df_yellow = df[df.columns[[2,5]]]
df_green = df[df.columns[[3,5]]]
df_purple = df[df.columns[[4,5]]]

A: You can do with groupby axis =1 and pd.concat
variables = locals()
for x , y  in df.iloc[:,:-1].groupby(level=0,axis=1):
    variables["df_{0}".format(x)] =pd.concat([y,df.iloc[:,[-1]]],axis=1)

df_red.head()

Out[566]:
   red  total
0    4      7
1    7      9
2    6      7
3    4      2
4    5      8


text:
Q: setState() is not working inside useEffect(); I fetched some data from my Mongo database which is returned as an object inside my useEffect hook function i.e.response in my code. I then declare a state myorders and wanted to set its value coming from the API.And finally. I wanted to map these data into different rows in my UI.
But the problem is when I try to setState in the component by passing the fetched orders in the setState() function, it returns an empty object. The console.log(state) shows an empty array.
code
import React, { useEffect, useState } from "react";
import { useRouter } from "next/router";

const Orders = () => {
  const router = useRouter();
  const [myorders, setMyorders] = useState();

  useEffect(() => {
    const fectOrders = async () => {

        let a = await fetch(`${process.env.NEXT_PUBLIC_HOST}/api/myorders`, {
          method: "POST", // or 'PUT'
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ token: localStorage.getItem("token") }),
        });
        let response = await a.json();
        console.log("RES = ",response)
        setMyorders(response.myorders)
        console.log("MY = ",myorders)
      }

      if (!localStorage.getItem("token")) {
        router.push("/");
      } else {
        fectOrders();
      }
  }, []);

  return (

My Orders

                .
                .
                .

  );
};

export default Orders;

ANd I got these values

As you can see that API is returning value but setState() is not working.
What To Do?

A: I had add myorders as dependency in useEffect which solves the problem,
So my useEffect is like this
  useEffect(() => {
    const fectOrders = async () => {

        let a = await fetch(`${process.env.NEXT_PUBLIC_HOST}/api/myorders`, {
          method: "POST", // or 'PUT'
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ token: localStorage.getItem("token") }),
        });
        let response = await a.json();
        console.log("RES = ",response)
        //setMyorders(response.myorders)
        console.log("MY = ",myorders)
        return response.myorders;
      }

      if (!localStorage.getItem("token")) {
        router.push("/");
      } else {
        fectOrders().then((ord)=>setMyorders(ord)).catch((err)=>console.log(err));
      }
  }, [myorders]);


text:
Q: Combining Vue-i18n Single File Component syntax with root messages I'm experimenting with the excellent vue-i18n plugin for Vue. It has a neat feature that allows me to embed translations directly into the template that needs them. However if I use them, I'm unable to access the root translation node. Is this model supported or am I just doing it wrong?
main.js
import VueI18n from 'vue-i18n';
Vue.use(VueI18n);
const i18n = new VueI18n({
  locale: 'en',
  messages: {
    en: {
      'company-name': 'billy-bob\'s fine steaks.'
    }
  }
});

Sample.vue
<i18n>
  {
    "en": {
      "title": "@:company-name - yeee hawwww!!!"
    }
  }
</i18n>

<template>

    <site-header :title="$t('title')"></site-header>

</template>

A: It appears that the i18n definitions are merged together so that, in the component, you would have access to both the parent and child i18n definitions, with the child definitions overriding the parents where there was any overlap (for example, if you had a title key in the parent and the child, the child's would be used).
However the syntax you are using clearly doesn't work. In this case I think I would define a computed that combines the two translated values and use that.
computed:{
    title(){
        return this.$t("company-name") + this.$t("title")
    }
}

And then just use the computed value in your template.
<template>

    <site-header :title="title"></site-header>

</template>


text:
Q: Assign static method to DependencyProperty of delegate type in xaml I have dependency property of delegate type in my class MyEditBox:
public delegate int LengthFilterDelegate(string text, int length);

public static readonly DependencyProperty LengthFilterProperty =
    DependencyProperty.Register("LengthFilter", typeof(LengthFilterDelegate), typeof(MyEditBox),
    new PropertyMetadata(new LengthFilterDelegate(lengthFilter)));

public LengthFilterDelegate LengthFilter
{
    get { return ((LengthFilterDelegate)(GetValue(LengthFilterProperty))); }
    set { SetValue(LengthFilterProperty, value); }
}

private static int lengthFilter(string text, int length)
{
    return 10;
}

and I want to assign static method of another class as value for it using style setter:
<Style TargetType="myns:MyEditBox">
    <Setter Property="LengthFilter" Value="{x:Static myns:TextWidthAutocadResolver.Resolve}"/>
</Style>

where TextWidthAutocadResolver class such as:
public static class TextWidthAutocadResolver
{
    public static int Resolve(string text, int length)
    {
        return 5;
    }
}

but for  some reason compiler cannot find Resolve method. What am doing wrong?


text:
Q: Calculate field average There is a timeseries data stored in MongoDB, here is the document stored every minute:
{ "_id" : ObjectId("54b7f78b33f0f76f26e49d79"), "timestamp" : ISODate("2015-01-15T17:23:23.215Z"),
    "sensors_data" : {
        "sen1" : { "@name" : "sensor-1", "@id" : "sen1", "value" : 10 },
        "sen2" : { "@name" : "sensor-2", "@id" : "sen2", "value" : 27 },
        "sen3" : { "@name" : "sensor-3", "@id" : "sen3", "value" : 19 },
        "sen4" : { "@name" : "sensor-4", "@id" : "sen4", "value" : 25 },
    }
}

I need a query which calculates the averages of the value fields for every subdocument (sen1, sen2, etc.) resulting something like:
{ "averages": { "sen1": "11.5", "sen2": "26", "sen3": "19.2", "sen4": "26.5" } }

A: Aggregation framework is used to get the desired output.
   db.test.aggregate(
    {
   $group:
     {
       _id: null,
       sen1: { $avg: "$sensors_data.sen1.value" },
       sen2: { $avg: "$sensors_data.sen2.value" },
       sen3: { $avg: "$sensors_data.sen3.value" },
       sen4: { $avg: "$sensors_data.sen4.value" }
      }
 }
 )

OUTPUT (for sample data):
{
"result" : [
    {
        "_id" : null,
        "sen1" : 11,
        "sen2" : 28.5,
        "sen3" : 24,
        "sen4" : 38.5
    }
],
"ok" : 1
}


text:
Q: Categorization of Gaussian primes I'm reading Neukirch's text on Algebraic Number Theory, and we are proving that any Gaussian primes are in the form of $1 + i$ or $a + bi$ where $a^2 + b^2 = $a prime $p$ or $p = 3 \mod 4$.
I understand the steps to show that these are indeed Gaussian primes, but I'm not very clear on his proof on any Gaussian prime take one of the forms. The argument was that for any prime $\pi \in \mathbb{Z}[i]$,
$$ N(\pi) = \pi \cdot \overline{\pi} = p_1 \cdot p_r.$$
Then we claim that $\pi | p_i$ for some $i$. Why is this claim true? How do we know that $\pi$ must divide a rational prime?

A: The definition of $\pi$ being prime is that if $\pi$ divides $ab$ then $\pi$ divides $a$ or $\pi$ divides $b$.  So if $\pi$ divides $p_1\cdot\cdot
\cdot p_r \in \Bbb{Z}$, it must divide one of the $p_i$.  I would say to use induction of $r>2$ but in the instant case you will only ever have $r=1$ or $r=2$.

A: Does Neukirch explain what $\overline \pi$ is? If $\pi = 1 - i$, then $\overline \pi = 1 + i$, and vice-versa. And since $(1 - i)(1 + i) = 2$, it follows that $$\frac{2}{1 - i} = 1 + i$$ and $$\frac{2}{1 + i} = 1 - i.$$
Along similar lines you can prove it for purely real primes that are composite in $\mathbb{Z}[i]$.

A:
I'm reading Neukirch's text on Algebraic Number Theory, and we are proving that any Gaussian primes are in the form of $1 + i$ or $a + bi$ where $a^2 + b^2$ is a prime $p$ or $p \equiv 3 \bmod 4$.
I understand the steps to show that these are indeed Gaussian primes, but I'm not very clear on his proof on any Gaussian prime take one of the forms.

Assuming you have quoted Neukirch exactly, he's missing some primes of the above forms multiplied by units other than 1. Namely:

*

*$(1 + i)i = -1 + i$, which is a prime of norm 2,

*$(1 + i)(-1) = -1 - i$, which is another prime of norm 2, and...

*$(1 + i)(-i) = 1 - i$, which is yet another prime of norm 2.

If $a$ and $b$ are both purely real nonzero integers, then $a^2$ and $b^2$ are both purely real positive integers. So we could say that $-a + bi$, $-a - bi$ and $a - bi$ are all implied. If $a$ and $b$ are of opposite parity, then $a^2 + b^2 \equiv 1 \bmod 4$ and $a^2 + b^2$ is purely real and positive.
This means that if $\pm a \pm bi$ are primes, then they all have a norm that is a prime among the purely real integers, a positive prime that is 1 more than a multiple of 4. But of course that prime is not prime among the Gaussian integers, but, well, um... composite (snobbery is the only reason I can think of to not use that word in a unique factorization domain).
So if $p$ is a positive prime among the purely real integers, and 1 less than a multiple of 4, then there's no solution to $a^2 + b^2 = p$, and so $p$ is also a prime among the Gaussian integers. And we see that $pi$, $-p$ and $-pi$ are also primes. e.g., 7, $7i$, $-7$, $-7i$.

The argument was that for any prime $\pi \in \mathbb{Z}[i]$,
$$ N(\pi) = \pi \cdot \overline{\pi} = p_1 \cdot p_r.$$
Then we claim that $\pi \mid p_i$ for some $i$. Why is this claim true? How do we know that $\pi$ must divide a rational prime?

Because, like the others have already said, $\pi \overline \pi$ is a purely real number, 1 more than a multiple of 4, that is prime among the purely real integers. For example, $(2 - i)(2 + i) = 5$. Then obviously both $2 - i$ and $2 + i$ are Gaussian divisors of 5.
I think you also need to look at Gaussian integers with even norms. If $a$ and $b$ are both even, then obviously $a^2 + b^2$ is a multiple of 4 and $a + bi$ is divisible by 2. In instead $a$ and $b$ are both odd, then the norm is divisible by 2 but not by 4, and so much less obviously $a + bi$ is divisible by $1 + i$ but not by 2.


text:
Q: Socket.io cross domain issue I have a front end angularJS application(client) working in apache server and its API calls are send to a backend application(server) running in NodeJS. Now I want to have a socket connection between the client and the server.
I am using cors npm module for cross domain issue but its not working.
I have seen several solutions regarding this but none of them are working for me.
Here is my server side code:
var cors = require('cors')
var app = express();
var http = require('http');

app.use(cors({
origin: true,
credentials: true
}));

var server = http.createServer(app);
var io = require('socket.io')(server);
io.on('connection', function(socket)
{
console.log(":::::::::::::::::::::SOCKET:::::::::::::::::::::")

socket.on('message', function(data) {
    console.log(data); })
});

The server is working at http://localhost:8000/
Here is my client side code:
function socket() {
        var socket = io.connect('http://localhost:8000/');
  return {
     on: function(eventName, callback) {
        socket.on(eventName, callback);
     },
     emit: function(eventName, data) {
        socket.emit(eventName, data);
     },
     getSocket: function() {
        return socket;
     },
     removeAllListeners: function() {
        socket.removeAllListeners();
     }
  };
  }

I created the above factory in angularJS and called it inside a function as shown below:
var socket=PermitFactory.socket();
socket.emit('message', 'ssss');

The error I get in the browser console is:
socket-io.js:4948 GET http://localhost:8000/socket.io/?EIO=3&transport=polling&t=LhvWuIr 404 (Not Found)
And in the server console:
GET /socket.io/?EIO=3&transport=polling&t=LhvUygM 404 18.881 ms - 1153
Please Help!!!

A: you are getting 404 (Not Found) this means the problem is in your url not cors .
http://localhost:8000/ is the server up ?? the socket server .. if so then wss and ws before the  wss://localhost:8000/ or wss://localhost:8000/

A: Allow Cross domain on your server side scripting, put it on app.js
//Access-Control-Allow-Origin
app.use(function(req,res,next){
    res.header('Access-Control-Allow-Origin', '*');
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
    res.header("Access-Control-Allow-Credentials",true);
    res.header("Access-Control-Allow-Methods","POST,GET,OPTIONS");
    next();
});

app.use(cors());

Plugin for google chrome Allowing cros origin
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en

A: Try this method on your client side this will work.
var socket = io('https://localhost:8000/', { transports: ['websocket'] });


text:
Q: Combining items from several lists with pagination I am trying to come up with an algorithm for getting items for a news feed from several sources.
There are multiple lists of data: S1, S2, ... Sn. Each of these lists has a certain known amount of items, Q1, Q2, ... Qn. I need to show these items with pagination, with a certain amount from each list per page, P1, P2, ... Pn, with total amount of items per page T = sum(P). I get items from lists using offset and limit (in reality, they are SQL tables). Obviously, at some point i shall run out of items of a particular type, in which case i need to fill the blanks with items from other lists to get exactly T items for each page except the last one which can have less than T items.
Here's a concrete example for N=2, Q1=27, Q2=95, P1=10, P2=20, T=10+20=30:

==========================================================================
| Page | From S1 | S1 offset | S1 limit | From S2 | S2 offset | S2 limit |
==========================================================================
|  1   |   10    |     0     |    10    |    20   |     0     |    20    |
|  2   |   10    |    10     |    10    |    20   |    20     |    20    |
|  3   |    7    |    20     |    (7)   |    23   |    40     |    23    |
|  4   |    0    |     0     |    (0)   |    30   |    63     |    30    |
|  5   |    0    |     0     |    (0)   |     2   |    93     |    (2)   |
==========================================================================

The numbers in parenthesis are not really important, because i can live with asking the SQL table for more entries than it has.
Ideally, i'm looking for an algorithm that can give me offsets and limits for a given page.
Any ideas?


text:
Q: Getting a clean installation of Windows 10 without installation media Recently, I decided that I wanted to do a full wipe of all my stuff and return to a fresh Windows 10 installation. (with the anniversary update)
The laptop I am using originally came with Windows 8, so I fear that using Factory reset will cause me to downgrade all the way. I've noticed options to restore the computer and keep all your files, but that is not what I want to do. I do not have a restore point I can use to do this and I do not have a Windows 10 installation disk.
Is there a way I can blank slate installation of Windows 10 with the Anniversary Update installed?

A: Your best bet (IMO) is to get the Windows 10 installation media.
You can simply download the media creation tool from MS, use it to put the Windows 10 installer onto a USB key, boot from said USB key, and do a full reinstall.


text:
Q: Comparing two nested dictionaries and storing the differences of their values into a new dictionary I have one dictionary (long_dict) filled with 3 categories of data of different persons. I am trying to compare the values of a specific category (category_2) and store their differences separately into a new dictionary.
long_dict = {

'PERSON1':{
'category_1' :{
},
'category_2': {
'a': 20,
'b': 40,
'c': 60,
'd': 45
},
'category_3': {
}
},

'PERSON2': {
'category_1' :{
},
'category_2': {
'a': 30,
'b': 10,
'c': 40,
'd': 55
},
'category_3': {
}
},

'PERSON3': {
'category_1' :{
},
'category_2': {
'a': 60,
'b': 10,
'c': 35,
'd': 25
},
'category_3: {
}
},
'PERSON4': {
'category_1' :{
},
'category_2': {
'a': 30,
'b': 15,
'c': 65,
'd': 55
},
'category_3': {
}
}
}

I am looking to build a dict which stores the differences of values; something like this.
result = {

'PERSON1':{
'PERSON2' :{
'diff_a': ...,
'diff_b': ...,
'diff_c': ...,
'diff_d': ...
},
'PERSON3': {
'diff_a': ...,
'diff_b': ...,
'diff_c': ...,
'diff_d': ...
},
'PERSON4': {
'diff_a': ...,
'diff_b': ...,
'diff_c': ...,
'diff_d': ...
}
},
'PERSON2':{
'PERSON1' :{
'diff_a': ...,
'diff_b': ...,
'diff_c': ...,
'diff_d': ...
},
'PERSON3': {
'diff_a': ...,
'diff_b': ...,
'diff_c': ...,
'diff_d': ...
},
'PERSON4': {
'diff_a': ...,
'diff_b': ...,
'diff_c': ...,
'diff_d': ...
 }
 },
'PERSON3':{
'PERSON1' :{
'diff_a': ...,
'diff_b': ...,
'diff_c': ...,
'diff_d': ...
},
'PERSON2': {
'diff_a': ...,
'diff_b': ...,
'diff_c': ...,
'diff_d': ...
},
'PERSON4': {
'diff_a': ...,
'diff_b': ...,
'diff_c': ...,
'diff_d': ...
}
},

'PERSON4':{
'PERSON1' :{
'diff_a': ...,
'diff_b': ...,
'diff_c': ...,
'diff_d': ...
},
'PERSON2': {
'diff_a': ...,
'diff_b': ...,
'diff_c': ...,
'diff_d': ...
},
'PERSON3': {
'diff_a': ...,
'diff_b': ...,
'diff_c': ...,
'diff_d': ...
}
}
}

So far, I've tried this:
abc = dict()
xyz = dict()
fin = dict()
i = 0
for k, v in long_dict.items():
for a, b in long_dict.items():
    if k != a:
        for k2, v2 in v.items():
            for a2, b2 in b.items():
                if k2 == a2 == "category_2":
                    for k3, v3 in v2.items():
                        for a3, b3 in b2.items():
                            if k3 == a3:
                                abc[k3] = abs(v3-b3)
        xyz[a] = abc
        i+=1
        if i > 3:
            fin[k] = xyz
            i=0

And, this is what I get on print(fin):
{'PERSON2': {'PERSON2': {'a': 30, 'b': 5, 'c': 30, 'd': 30}, 'PERSON3': {'a': 30, 'b': 5, 'c': 30, 'd': 30}, 'PERSON4': {'a': 30, 'b': 5, 'c': 30, 'd': 30}, 'PERSON1': {'a': 30, 'b': 5, 'c': 30, 'd': 30}}, 'PERSON3': {'PERSON2': {'a': 30, 'b': 5, 'c': 30, 'd': 30}, 'PERSON3': {'a': 30, 'b': 5, 'c': 30, 'd': 30}, 'PERSON4': {'a': 30, 'b': 5, 'c': 30, 'd': 30}, 'PERSON1': {'a': 30, 'b': 5, 'c': 30, 'd': 30}}, 'PERSON4': {'PERSON2': {'a': 30, 'b': 5, 'c': 30, 'd': 30}, 'PERSON3': {'a': 30, 'b': 5, 'c': 30, 'd': 30}, 'PERSON4': {'a': 30, 'b': 5, 'c': 30, 'd': 30}, 'PERSON1': {'a': 30, 'b': 5, 'c': 30, 'd': 30}}}

A: A more efficient way of comparing and storing the values would be to only compare and store each unique comparison once (rather than comparing and storing the same comparison for each dict key involved in the comparison). You could use itertools.combinations to keep it fairly simple and access each comparison by a tuple key (the approach below assumes that the each of the compared category dicts contains the same keys - if not, then you would have to add some additional checking).
from itertools import combinations

d = {'PERSON1':{'category_1' :{}, 'category_2': {'a': 20, 'b': 40, 'c': 60, 'd': 45}, 'category_3': {}}, 'PERSON2': {'category_1' :{}, 'category_2': {'a': 30, 'b': 10, 'c': 40, 'd': 55}, 'category_3': {}}, 'PERSON3': {'category_1' :{}, 'category_2': {'a': 60, 'b': 10, 'c': 35, 'd': 25}, 'category_3': {}}, 'PERSON4': {'category_1' :{}, 'category_2': {'a': 30, 'b': 15, 'c': 65, 'd': 55}, 'category_3': {}}}

compare = {}
for a, b in combinations(sorted(d.keys()), 2):
    acat = d[a]['category_2']
    bcat = d[b]['category_2']
    compare[(a, b)] = {k: abs(acat[k] - bcat[k]) for k in acat}

print(compare)
# {('PERSON1', 'PERSON2'): {'a': 10, 'b': 30, 'c': 20, 'd': 10}, ('PERSON1', 'PERSON3'): {'a': 40, 'b': 30, 'c': 25, 'd': 20}, ('PERSON1', 'PERSON4'): {'a': 10, 'b': 25, 'c': 5, 'd': 10}, ('PERSON2', 'PERSON3'): {'a': 30, 'b': 0, 'c': 5, 'd': 30}, ('PERSON2', 'PERSON4'): {'a': 0, 'b': 5, 'c': 25, 'd': 0}, ('PERSON3', 'PERSON4'): {'a': 30, 'b': 5, 'c': 30, 'd': 30}}


text:
Q: PHP Wordpress: Handling user submitted data? Okay, so I have a form for user submitted data and I'd like some feedback on security (using PHP on wordpress):
What I want from my form:

*

*Text data (paragraph long). No need for anything but alphanumeric and some English punctuation, but also want to be able to handle other languages at a basic level.

*Image data (multiple images).

I start with a form that takes in the data. I have a function that strips most stuff, but I want to keep ' (single quote) and ! (exclamation mark). I am also curious about what basic step I can take to protect my MySQL database before the data gets added?
I found this function for stripping, but still takes away (single quote and exclamation mark):
function strip_punctuation( $content )
{

$urlbrackets    = '\[\]\(\)';
$urlspacebefore = ':;\'_\*%@&?!' . $urlbrackets;
$urlspaceafter  = '\.,:;\'\-_\*@&\/\\\\\?!#' . $urlbrackets;
$urlall         = '\.,:;\'\-_\*%@&\/\\\\\?!#' . $urlbrackets;

$specialquotes  = '\'"\*<>';

$fullstop       = '\x{002E}\x{FE52}\x{FF0E}';
$comma          = '\x{002C}\x{FE50}\x{FF0C}';
$arabsep        = '\x{066B}\x{066C}';
$numseparators  = $fullstop . $comma . $arabsep;

$numbersign     = '\x{0023}\x{FE5F}\x{FF03}';
$percent        = '\x{066A}\x{0025}\x{066A}\x{FE6A}\x{FF05}\x{2030}\x{2031}';
$prime          = '\x{2032}\x{2033}\x{2034}\x{2057}';
$nummodifiers   = $numbersign . $percent . $prime;

return preg_replace(
    array(
    // Remove separator, control, formatting, surrogate,
    // open/close quotes.
        '/[\p{Z}\p{Cc}\p{Cf}\p{Cs}\p{Pi}\p{Pf}]/u',
    // Remove other punctuation except special cases
        '/\p{Po}(?<![' . $specialquotes .
            $numseparators . $urlall . $nummodifiers . '])/u',
    // Remove non-URL open/close brackets, except URL brackets.
        '/[\p{Ps}\p{Pe}](?<![' . $urlbrackets . '])/u',
    // Remove special quotes, dashes, connectors, number
    // separators, and URL characters followed by a space
        '/[' . $specialquotes . $numseparators . $urlspaceafter .
            '\p{Pd}\p{Pc}]+((?= )|$)/u',
    // Remove special quotes, connectors, and URL characters
    // preceded by a space
        '/((?<= )|^)[' . $specialquotes . $urlspacebefore . '\p{Pc}]+/u',
    // Remove dashes preceded by a space, but not followed by a number
        '/((?<= )|^)\p{Pd}+(?![\p{N}\p{Sc}])/u',
    // Remove consecutive spaces
        '/ +/',
    ),
    ' ',
    $content );
}

Any ideas how to get ' (single quote) and ! (exclamation point) back as allowed? Also, what is the easiest way to protect the MySQL database before entry?
Thanks!


text:
Q: problema com Jquery-Mask estou com um problema criei uma mascara para um campo que deve receber tanto um cpf como um cnpj ela funciona normal desde que o usuário não copie e cole o cnpj, quando ele copia o cpnj para o campo em branco ele não vem completo porem se você selecionar o que está no campo e colar novamente ele vem completo, não tenho a menor ideia do que pode está causando isso.
var cpfOuCnpjComportamento = function (val) {
        if (val.length > 14)
            return '00.000.000/0000-00';
        else
            return '000.000.000-009';
    };
    var cpfOuCnpjOptions = {
        onKeyPress: function (val, e, field, cpfOuCnpjOptions) {
            field.mask(cpfOuCnpjComportamento.apply({}, arguments), cpfOuCnpjOptions);
        }
    };

    $('.cpfOuCnpj').mask(cpfOuCnpjComportamento, cpfOuCnpjOptions);

A: Recomendo que utilize o plugin jQuery masked input, ele é melhor que o mask plugin.
Exemplo de uso do masked input funcionando com um esquema semelhante de CPF e CNPJ em um mesmo campo:

jQuery(function($){
  $('.cpf-cnpj').change(function(){
    var campo = $(this).val();
    if (campo == "cpf"){
      $("#label-cpf-cnpj").html('CPF');
      $("#InputCpf-cnpj").mask("999.999.999-99");
    }
    else if (campo == "cnpj"){
      $("#label-cpf-cnpj").html('CNPJ');
      $("#InputCpf-cnpj").mask("99.999.999/9999-99");
    }
  });
});

<input type="radio" class="cpf-cnpj" id="cpf-cnpj" name="cpf/cnpj" value="cpf"> CPF

<input type="radio" class="cpf-cnpj" id="cpf-cnpj" name="cpf/cnpj" value="cnpj"> CNPJ

CPF/CNPJ <input type="text" id="InputCpf-cnpj" name="cpf/cnpj">

Fiz alguns testes aqui copiando e colando CPFs e/ou CNPJs completos com o plugin em questão e funciona normalmente.
Exemplo de uso do mask plugin para visualizar a diferença entre os dois:

jQuery(function($){
  $('.cpf-cnpj').change(function(){
    var campo = $(this).val();
    if (campo == "cpf"){
      $("#label-cpf-cnpj").html('CPF');
      $("#InputCpf-cnpj").mask("999.999.999-99");
    }
    else if (campo == "cnpj"){
      $("#label-cpf-cnpj").html('CNPJ');
      $("#InputCpf-cnpj").mask("99.999.999/9999-99");
    }
  });
});

<input type="radio" class="cpf-cnpj" id="cpf-cnpj" name="cpf/cnpj" value="cpf"> CPF

<input type="radio" class="cpf-cnpj" id="cpf-cnpj" name="cpf/cnpj" value="cnpj"> CNPJ

CPF/CNPJ <input type="text" id="InputCpf-cnpj" name="cpf/cnpj">

Observe que utilizando o masked input, quando o usuário clica no campo a máscara já é exibida inteira facilitando para o mesmo a visualização de quantos dígitos deverá inserir no campo, diferente do mask plugin, em que a máscara só vai aparecendo aos poucos à medida que o usuário vai inserindo os dígitos do CPF ou CNPJ.
Edit: Segue então novo exemplo sem utilizar o radio para selecionar CPF ou CNPJ:

$(document).ready(function () {
    $("#InputCpf-cnpj").mask("999.999.999-99?99999");

    $('#InputCpf-cnpj').keyup(function (e) {

        var query = $(this).val().replace(/[^a-zA-Z 0-9]+/g,'');

        if (query.length == 11) {
            $("#label-cpf-cnpj").html('CPF');
            $("#InputCpf-cnpj").mask("999.999.999-99?99999");
        }

        if (query.length == 14) {
            $("#label-cpf-cnpj").html('CNPJ');
            $("#InputCpf-cnpj").mask("99.999.999/9999-99");
        }
    });
});

CPF/CNPJ<input id="InputCpf-cnpj" type="text">

A: Cheguei nesse post meio tarde, mas pode ajudar alguém ainda.
Basta fazer desta forma, passando a formatação mais o numero de possíveis casas e um verificador para cair na próxima formatação. Desta forma funcionará tanto para no caso que o usuário digite normalmente ou de ctrl+v.
Exemplo:
var maskCpjCnpj = function (val) {
return val.replace(/\D/g, '').length < 12 ?  '000.000.000-009999' : '00.000.000/0000-00';
},
ccOptions = {
    onKeyPress: function(val, e, field, options) {
        field.mask(maskCpjCnpj.apply({}, arguments), options);
    }
};

$('.cpf-cnpj-mask').mask(maskCpjCnpj, ccOptions);


text:
Q: Eclipse: program arguments I have a program (called myprogram) that I build with Eclipse; I can start it from the command line as follows:
myprogram < myinifile

As you can you see, I pass as input the ini file "myinifile".
My question is how to pass it the input file when launching the program from within Eclipse using the Run command.
I know I can specify program arguments in Run / Run configurations / Tab: Arguments but how do I specify an input file?
"myinifile" --> doesn't work
"< myinifile" --> doesn't work either

A: You can configure arguments in Run Configurations. In Commons tab you can redirect output in "Standard Input and Output" section. But, it appears there is no option to redirect input.
Read more here - Bug 155411 - [launch] Need a way to assign stdin to a file from Run Dialog
If you have control over the application and can modify it, see Eclipse reading stdin (System.in) from a file for some options.


text:
Q: C# Unity Найти пустые элементы в List и удалить их Есть List, в котором изначально хранится множество ссылок на объекты в юнити.
В процессе выполнения кода, какие-то из объектов перестают существовать, в связи с чем в List`е появляются пустые ссылки, как от них можно разом избавиться?
Вариант с удалением объекта из списка перед его удалением не подходит.
Возможно есть способ как-то проверить каждый элемент списка на null и все элементы с пустыми ссылками - удалить? Через какой-нибудь foreach, но сам допереть не могу...

A: List<string> aa = new List<string> { "sdsds", null, "sdsdsd" };
aa = aa.Where(x => x != null).ToList();

или
aa = aa.FindAll(x => x != null);


text:
Q: How can I use a graphic imported with grImport as axis tick labels in ggplot2 (using grid functions)? I'm hoping I can combine the spiffy importing and drawing powers of grImport with the awesome graphing power of ggplot2, but I simply don't understand the grid system well enough to find an elegant way of achieving what I want.  What I want is to replace the x-axis tick labels in a ggplot2 graph with images imported using grImport.
Since both packages use grid functions, I'm hoping there is a way to use grid.symbols() either within the ggplot2 framework, which would be ideal, or at least on an existing plot in a device.  Does anyone with more knowledge of such things know of a robust way to do this?  Or, can anyone point me to more information to help me learn about grobs, viewports, etc.?  I have read through the free Chapter of Paul Murrel's R graphics book on the Grid graphics model, but I'm not familiar enough with the inner workings of ggplot2 to make the link.
My question is very similar to an existing question about using an image as a plot point, although I'm more interested in the axis labels rather than the plot points.  However, I would be curious as to how similar the two tasks are, and if that solution can be adapted for this purpose.  I wasn't able to figure it out on my own.
This is my first post, so I'm not allowed to post an image, but this code achieves something close to what I want.  Note: this approach uses an ugly, ugly hack that is not portable, and unsatifactory.  The final plot I want to produce will have facets (facet_grid), and the x-axis is for a factor with different pictures at each axis tick, not a continuous variable, which is why I'm looking for a more general / robust solution that doesn't require a lot of trial & error.
library(ggplot2)
## library(grImport)  # not needed for this example, but would be for grid.symbols()

p <- ggplot(mtcars, aes(cyl, mpg)) + stat_summary(fun.data = "mean_cl_boot")
print(p)

## Replace (in this case, overlay) x-axis tick labels with a graphic / grob
iconSize  <- 0.05
iconHt    <- 0.2
padding   <- 0.09    # horizontal padding around axis: I found this by trial & error
tickSp    <- (1-padding)/(4*2)
downViewport("axis_h-5-3")
## I would use grid.symbols() with an imported Picture in place of grid.circle(),
## but the idea is the same: draw a shape at the ticks along the axis.
for (i in 0:(max(mtcars$cyl) - min(mtcars$cyl)) )
{
  grid.circle(x = (padding/2 + tickSp*(i*2)), y = iconHt,
              r = iconSize*(min(mtcars$cyl)+i), gp = gpar(fill="black"))
}

upViewport()

A: For a single panel, it is fairly straight-forward to extract information from the x axis grob, and replace it with your own. I'm not sure how this could be extended cleanly to automatic, multi-panel axes.
library(grid)
library(ggplot2)

p <- qplot(1:12, rnorm(12))
grid.newpage()
g <- ggplotGrob(p)
grid.draw(g)
g0 <- getGrob(g, gPath("axis.text.x"), grep=TRUE)
grid.set(gPath("axis.text.x"),
         pointsGrob(x = g0$x, y=0*g0$x + unit(0.5,"npc"),
                    pch=19, gp=gpar(col=seq_along(g0$x)),
                    name = g0$name), grep = TRUE)

A: Below is a hack to use a custom grob for axis labels.
library(grid)
library(ggplot2)

## convert the labels to some parameter to be used in the custom grob
## here simply an index that will be interpreted as color
mapping <- function(x, ...){
  seq_along(x)
}

library(grImport)

hourglass <- new("Picture",
paths= list(new("PictureFill",
x=c(0, 1, 0, 1),
y=c(0, 0, 1, 1))),
summary= new("PictureSummary",
numPaths=1,
xscale=c(0, 1),
yscale=c(0, 1)))

## bare bones edit of theme_text()
my_axis <- function ()
{
    structure(function(label, x = 0.5, y = 0.5, default.units = "npc", ...) {
      cols <- mapping(label)

      symbolsGrob(hourglass, x, 0*x + unit(0.5, "npc"),
                  use.gc=FALSE,size=unit(5,"mm"), gp=gpar(fill=cols))

    }, class = "theme", type = "custom", call = match.call())
}

qplot(1:12, rnorm(12)) +
  opts( axis.text.x = my_axis(), axis.ticks.margin = unit(0.5, "cm"))

A: here is an example:
# convert ps to RGML
PostScriptTrace(file.path(system.file(package = "grImport"), "doc", "GNU.ps"), "GNU.xml")
PostScriptTrace(file.path(system.file(package = "grImport"), "doc", "tiger.ps"), "tiger.xml")
# read xml
pics <- list(a = readPicture("GNU.xml"), b = readPicture("tiger.xml"))

# custom function for x axis label.
my_axis <- function () {
  structure(
      function(label, x = 0.5, y = 0.5, ...) {
         absoluteGrob(
           do.call("gList", mapply(symbolsGrob, pics[label], x, y, SIMPLIFY = FALSE)),
           height = unit(1.5, "cm"))
    }
)}

qplot(factor(c("a", "b")), 1:2) + opts( axis.text.x = my_axis())


text:
Q: Unable to run the test for the webapps running in cloud/remote server ( application is accessible via browser only through VPN). Getting error Unable to run the test for the webapps running in cloud ( application is accessible via browser only through VPN). Getting error.

A: You must first setup a tunnel from testRigor to your machine, then try accessing the page.

*

*Read the tunnel documentation.

*Set up a tunnel on your machine.

*Request a port from testRigor support

*Then run your test

Docs for setting up a tunnel:
https://docs.google.com/document/d/1MMQ9WBwRTSPUI589PKv5YxiyM7r5rE1K5iP_Dj5xl0Q/edit#


text:
Q: Ansible synchronise module says --out-format is unknown option I have a simple ansible playbook by which i want to rsync folders from target machines onto my ansible host.
---
- hosts: testServers
  sudo: yes
  gather_facts: yes
  tasks:
  - synchronize: mode=pull src=/home/prod/live-tpb/log/ dest=/root/playbooks/backup_live_folders/logs/{{ ansible_hostname }}

but when i run this playbook, it errors out saying

rsync: --out-format=<>%i %n%L: unknown option

The full error generated using the -vvvv option is as below.
failed: [192.168.101.174 -> 127.0.0.1] => {"cmd": "rsync --delay-updates -FF --compress --archive --rsh 'ssh  -S none -o StrictHostKeyChecking=no' --rsync-path=\"sudo rsync\" --out-format='<<CHANGED>>%i %n%L' \"ansible@192.168.101.174:/home/prod/live-tpb/log/\" \"/root/playbooks/backup_live_folders/logs/serverC6174\"", "failed": true, "rc": 1}
msg: rsync: --out-format=<<CHANGED>>%i %n%L: unknown option
rsync error: syntax or usage error (code 1) at main.c(1231) [client=2.6.8]

When I run the command directly too this fails -
[root@server11 backup_live_folders]# rsync --delay-updates -FF --compress --archive --rsh 'ssh  -S none -o StrictHostKeyChecking=no' --rsync-path="sudo rsync" --out-format='<<CHANGED>>%i %n%L'  ansible@192.168.101.174:/home/prod/live-tpb/logs/ /root/playbooks/backup_live_folders/logs/serverC6174
rsync: --out-format=<<CHANGED>>%i %n%L: unknown option
rsync error: syntax or usage error (code 1) at main.c(1231) [client=2.6.8]

This looks like it is a problem with rsync on 14.04. My host machine is RHEL 5.4 and target machine is ubuntu 14.04.
How do i disable the --out-format option from ansible? Has anyone else faced similar problem? If yes, how to work around this issue?
Thanks

A: It was a problem of version. Upgrading rsync on source machine from v2.6.8 to v3.0.7 fixed the issue.
Apologies for the question.


text:
Q: SpriteKit: Scaling Does Not Work Correctly I have created a Scene in ScaleToFill and AspectFit. Both doesn't work as they should that let me think, that the code might be messed up. First of all I show you the two pictures of the modes:
ScaleToFit(Bottom and a little bit of the top is white)
AspectFit(Doesn't use the whole screen)

And following the code I use to create the walls:
    override func didMoveToView(view: SKView) {
    screenHeight = self.size.height
    width = screenHeight / CGFloat(fieldsX)
    print(self.size.height)
    print(self.size.width)
    calculateStartPoint()
    createPositionForWalls()
    fillScreenWithWalls()
}

func fillScreenWithWalls(){
    for(var i = 1; i <= fieldsX; i++){
        for(var j = 1; j <= fieldsY; j++){
            if(fieldArray[j-1][i-1] == 1){
                let xPos = (CGFloat(i) * width - width/2)
                let yPos = screenHeight-(width/2) - CGFloat(j) * width
                addWall(xPos, yPos: yPos)
            }
        }
    }
}

Basically I just scale all fieldsX so they should fit perfectly on the screen and then I add some fieldsY as I want to(I want to have 1 field free in the bottom). Another thing I don't understand is why is the fps and node counter not visible.

A: Using .ResizeFill works somehow. I still don't understand why .AspectFitoutputs the screenshot.


text:
Q: RxJS how to fire two http requests in parallel but wait for first to complete before second value is emitted I have a UI where I display details about a Game.
The view has two tabs, one with the details and one with the screenshots.

To construct the Model for the View, I need to get data from 2 different endpoints:

*

*/games/:id

*/games/:id/screenshots
The behaviour I am trying to achieve is as follow:

*

*I want to parallelize the network requests to both API endpoint

*I want the first request (/games/:id) always to emit first

*I want the second request (/games/:id/screenshots) to emit last, even when it finished before the first one.

I have been able to achieve a working solution, but what I cannot achieve is "parallelize and wait".
This is my current implementation
export class GameService {
  constructor(private http: HttpClient) {}

  private state: GameState = {
    ...initialState,
  };
  private store = new BehaviorSubject<GameState>(this.state);
  private store$ = this.store.asObservable();

findGame(id: string) {
    const game$ = this.http.get<Game>(`${env.BASE_URL}/games/${id}`).pipe(
      delay(1500),
      tap((game) => {
        this.state = { ...this.state, selectedGame: game };
        this.store.next({ ...this.state });
      })
    );

    const screenshots$ = this.http
      .get<APIResponse<{ image: string }>>(
        `${env.BASE_URL}/games/${id}/screenshots`
      )
      .pipe(
        delay(2500),
        map(({ results: screenshots }) => screenshots),
        tap((screenshots) => {
          if (this.state.selectedGame) {
            this.state.selectedGame.screenshots = [...screenshots];
            this.store.next({ ...this.state });
          }
        })
      );

     return game$.pipe(concatMap(() => screenshots$));
  }
}

This line
return game$.pipe(concatMap(() => screenshots$));

allows me to wait for the first request to finish before the second one can emit, but it also means that the network request is not initiated until the first observable emits.
I have tried to use merge but it becomes very complex to determine the shape of the emitted value and the code becomes quite "dirty"
How can I parallelize both requests, but wait for the first to finish before the second one emits?

A: You can use delayWhen.
import { of } from 'rxjs';
import { delay, delayWhen, shareReplay, tap } from 'rxjs/operators';

function getGame() {
  console.log('game requested');
  return of('foo').pipe(
     delay(2500),
     tap(() => console.log('game returned')),
  );
}

function getScreenshots() {
  console.log('screenshots requested');
  return of('bar').pipe(
     delay(1000),
     tap(() => console.log('screenshots returned')),
  );
}

const game$ = getGame().pipe(shareReplay(1));
const screenshots$ = getScreenshots().pipe(
  delayWhen(() => game$),
);

game$.subscribe(() => console.log('game received'));
screenshots$.subscribe(() => console.log('screenshots received'));

Stackblitz: https://stackblitz.com/edit/rxjs-6jmk4j?file=index.ts


text:
Q: PHP 8.1: strftime() is deprecated When upgrading to PHP 8.1, I got an error regarding "strftime".
How do I correct the code to correctly display the full month name in any language?
 $date = strftime("%e %B %Y", strtotime('2010-01-08'))

A: To my dear and late strftime()... I found a way to adapt with IntlDateFormatter::formatObject and here is the link for the references to the schemas:
https://unicode-org.github.io/icu/userguide/format_parse/datetime/#date-field-symbol-table
... For those who want to format the date more precisely
// "date_default_timezone_set" may be required by your server
date_default_timezone_set( 'Europe/Paris' );

// make a DateTime object
// the "now" parameter is for get the current date,
// but that work with a date recived from a database
// ex. replace "now" by '2022-04-04 05:05:05'
$dateTimeObj = new DateTime('now', new DateTimeZone('Europe/Paris'));

// format the date according to your preferences
// the 3 params are [ DateTime object, ICU date scheme, string locale ]
$dateFormatted =
IntlDateFormatter::formatObject(
  $dateTimeObj,
  'eee d MMMM y à HH:mm',
  'fr'
);

// test :
echo ucwords($dateFormatted);

// output : Jeu. 7 Avril 2022 à 04:56

A: I've chosen to use php81_bc/strftime composer package as a replacement.
Here the documentation.
Pay attention that the output could be different from native strftime 'cause php81_bc/strftime uses a different library for locale aware formatting (ICU).

Note that output can be slightly different between libc sprintf and this function as it is using ICU.

A: You can use the IntlDateFormatter class. The class works independently of the locales settings. With a function like this
function formatLanguage(DateTime $dt,string $format,string $language = 'en') : string {
    $curTz = $dt->getTimezone();
    if($curTz->getName() === 'Z'){
      //INTL don't know Z
      $curTz = new DateTimeZone('UTC');
    }

    $formatPattern = strtr($format,array(
        'D' => '{#1}',
        'l' => '{#2}',
        'M' => '{#3}',
        'F' => '{#4}',
      ));
      $strDate = $dt->format($formatPattern);
      $regEx = '~\{#\d\}~';
      while(preg_match($regEx,$strDate,$match)) {
        $IntlFormat = strtr($match[0],array(
          '{#1}' => 'E',
          '{#2}' => 'EEEE',
          '{#3}' => 'MMM',
          '{#4}' => 'MMMM',
        ));
        $fmt = datefmt_create( $language ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
        $curTz, IntlDateFormatter::GREGORIAN, $IntlFormat);
        $replace = $fmt ? datefmt_format( $fmt ,$dt) : "???";
        $strDate = str_replace($match[0], $replace, $strDate);
      }

    return $strDate;
}

you can use format parameters like for datetime.
$dt = date_create('2022-01-31');
echo formatLanguage($dt, 'd F Y','pl');  //31 stycznia 2022

There are extension classes for DateTime that have such functions integrated as methods.
echo dt::create('2022-01-31')->formatL('d F Y','pl');

A: The strftime is obsolete and DateTime::format() provide a quick replacement and IntlDateFormatter::format() provied a more sophisticated slution.
this links will be help you:
https://github.com/modxcms/revolution/issues/15864
https://github.com/php/php-src/blob/1cf4fb739f7a4fa8404a4c0958f13d04eae519d4/UPGRADING#L379-L381
https://www.php.net/manual/en/datetime.format.php

A: strftime is deprecated PHP 8.1, You can use date function.
$date = date("%e F Y", strtotime('2010-01-08'))

A: Hey I have also experienced this issue as well so after some research on PHP's official documentation here what I found!
https://www.php.net/manual/en/function.strftime.php

They are saying that it is depricated and use setlocale() function
this also work same as strftime().
For more information please visit official PHP docs of setlocale() https://www.php.net/manual/en/function.setlocale.php

A: A quick and simple replacement for the deprecated function strftime can be following.
Instead of using (taking the sample from the question)
$date = strftime("%e %B %Y", strtotime('2010-01-08'))
convert that to:
$date = date('d M Y', strtotime('2010-01-08')


text:
Q: Showing NginX welcome page after Dockerizing I have Dockerized my Nextjs App. It builds fine. But after building, it keep showing the nginx welcome page, not the actual home page of my application. Tried many things, it doesn't fix. It remains the same on server too. What is the problem in my setup.
Here I am attaching my files.
This is my Dockerfile
FROM node:14.16.0 as builder

WORKDIR /app

ENV PATH /app/node_modules/.bin:$PATH

COPY ./package.json /app/

RUN npm install

COPY . /app

RUN npm run build

FROM nginx:alpine
COPY --from=builder /app/build /usr/share/nginx/html

RUN rm /etc/nginx/conf.d/default.conf
COPY nginx/nginx.conf /etc/nginx/conf.d

EXPOSE 3000

CMD ["nginx", "-g", "daemon off;"]

This is my Docker-compose.yml
version: "3.8"
services:
  app:
    container_name: kup-frontend
    image: kup-frontend
    build:
      context: .
      dockerfile: ./Dockerfile
    ports:
      - 3000:3000
    volumes:
      - .:/app
      - /app/node_modules
      - /app/build
    restart: unless-stopped
    environment:
      - PORT=3000

This is my nginx.conf file
server {
    listen 3000;
    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}


text:
Q: What battery and solar panel voltage for Arduino Uno weather station? I'm trying to design a weather station with an Arduino Uno using rechargeable batteries and a solar panel. I'm unsure about the specifications of the batteries and solar panel: do I need a 9V battery and a 9V solar panel or 2 x 4.5V batteries, etc? What would be the most efficient setup so that the unit is self sustainable?
In the country I live in there isn't a whole lot of sun each day, does this change the kind of panels I need?

A: I have done something very similar in the past. I used the UNO bootloader on a breadboard design.
I used the jeelib sleepy to power down my chip in between data gathering cycles (30 seconds in my case).
Instead of batteries I eventually settled on x2 2.7V recycled 100F pseudocapacitors and some cheap solar cells from ebay. I stored the data to an SD shield that I also bought from ebay.
The whole setup cost around $20 and has been in operation for over a year.
If you make sure your input voltage is not too high (The datasheet says 5.5v max but mine get up to 6v at times) and your oscillator low enough the whole setup ends up using only a few milliamps on average and will have a wide voltage range. Mine usually dies at around 2.7V clocked a little under 4MHz. The solar cells are wired in sets directly to the capacitors with a blocking diode to slow self discharge during the night.
My design was a little short sighted and if I ever redesign it I will go with smaller solar cells, I did not realise just how efficient the Atmega328p chips actually were so the capacitors reached full charge very quickly and end up over their rating for most of the day. The biggest user of power ended up being the self discharge of my capacitors.
I did some early testing with x2 5.5V 1F capacitors and they were able to get the thing running 24/7 (not running the SD module) in Tasmania. I settled on pseudocapacitors due to their large number of cycles, their cheap price when bought from ebay recycled and the ability to run the SD card module. My original test design used x2 3V 1W solar panels in series from ebay. I did not test their actual power other than in the actual running of the device. When my pseudocapacitors arrived I rewired them into the configuration stated above, put it all in a sistema cookware box and positioned it for full solar coverage from the morning sun. To access the data I simply needed to copy the text file from the SD card to my laptop and then connect+disconnect the reset pin on the barebones board to reset it for gathering more data (The SD library would crash when the card was taken out).

A: I also ended up with the solar/supercap combo; here are a few more details.
Basically it is the classic arduino breadboard design, because the UNO board wastes a LOT of energy for the regulator. Any sleep library will allow very low current usage while waiting.
Supercaps + solar cell is a great way to power this, since :

*

*Charge control is very simple for supercaps (just check voltage),

*They have an almost infinite number of charge/discharge cycles,

*Unlike batteries, they work fine in cold weather

but this only works if you don't need a lot of power for something else. I used much smaller supercaps than Aedazan: two 10F (2.7V max) supercaps in series are more than enough for a long winter night (or even a few days). The solar cell is 6V, 6x6cm.
Now you should make sure that you don't overvoltage the capacitors. Since they are in series, you should make sure that both the middle voltage and the total voltage are where they shoud be.
For the middle voltage, the control is done with a single pin like this :

simulate this circuit – Schematic created using CircuitLab
You use that pin both as input to measure the middle voltage, and as output to discharge the capacitors if necessary. Just allow some time for the caps to recover before measuring again :
boolean discharging = false;
loop() {
  // The caps should get some time to recover after some discharging
  //   before voltage can be read reliably.
  if (discharging) {
    pinMode(A1, INPUT) ;
    discharging = true ;
  }
  else {
    int mid = analogRead(A1) ;   // Read voltage between caps
    if (mid<492){                // If C1 is too charged
      pinMode(A1, OUTPUT) ;      //   Set the pin as output
      digitalWrite(A1, HIGH) ;   //   Connect it to VCC to discharge C1 through R1
      discharging = true ;
    }
    if (mid>522){                // If C2 is too charged
      pinMode(A1, OUTPUT) ;      //   Set the pin as output
      digitalWrite(A1, LOW) ;    //   Connect it to Gnd to discharge C2 through R1
      discharging = true ;
    }
  }
  // Sleep some time...
}

For the total voltage, you have 2 options :

*

*Cheap option (basically free) : use the pin above to discharge alternatively the capacitors when they are full. That works fine if the solar panel max current at the max voltage (about 5V) is less than what the pin can handle (20mA) divided by four (since the pin is in input mode half the time, and discharges only one cap at a time).

*Reliable option (still cheap) : use a simple 431 shunt regulator and two resistors (sorry I didn't find the correct symbol for 431) :

simulate this circuit
The 431 starts swallowing lots of current when the control voltage (taken between resistors) is about 2.5V, ie when the digital pin is above 5V. You could directly connect the above resistor to vcc, but then the 431 would draw some leakage current even when Vcc is only 4V : this would deplete capacitors at night. If you connect it to a digital pin, you can enable the 431 only when Vcc (measured by arduino, no pin needed, google for details) is above, say, 4.8V. In other words, the 431 eats lots of current (up to 100mA) when the pin is HIGH and Vcc is above 5V, a little current (100-400µA) when the pin is HIGH and Vcc is below 5V, and almost no current (about 0.1µA) whenever the pin is LOW.
This may all seem complicated, but it really isn't unless you try to improve the design. The main limitation is the size of available supercaps if you need to power something heavy ; above a few tens of F they get awfully big and expensive...


text:
Q: Tetris clear lines issue I am making a tetris clone for a project. I'm pretty much done but my clear lines class has a bug that I cant shake. I have made a 10*20 grid which I draw the sprites into. When I get a line at the floor it works fine but above that it just deletes the line and moves everything under it down too. This is the code for my clear line class:
public static void ClearLines()
{
    for (int CountY = Game1.LandedBlocks.GetLength(1) - 1; CountY >= 0; CountY--)
    {
        bool clearLine = true;
        for (int CountX = 0; CountX < Game1.LandedBlocks.GetLength(0); CountX++)
        {
            clearLine &= Game1.LandedBlocks[CountX, CountY] != -1;
        }
        if (clearLine)
        {
            for (int CountX = 0; CountX < Game1.LandedBlocks.GetLength(0); CountX++)
            {
                Game1.LandedBlocks[CountX, CountY] = -1;
            }
            for (int y = Game1.LandedBlocks.GetLength(1) - 1; y > 0; y--)
            {
                for (int CountX = 0; CountX < Game1.LandedBlocks.GetLength(0);                   CountX++)
                {
                    Game1.LandedBlocks[CountX, y] = Game1.LandedBlocks[CountX, y - 1];
                }
            }
            CountY++;
            Game1.rows++;
            Game1.score += 100;
        }
    }
}

If anyone could shed some light on what to do I'd really appreciate it. I've tried so much and nothing works :(

A: It looks like the problem is with
            for (int y = Game1.LandedBlocks.GetLength(1) - 1; y > 0; y--)
            {
                for (int CountX = 0; CountX < Game1.LandedBlocks.GetLength(0); CountX++)
                {
                    Game1.LandedBlocks[CountX, y] = Game1.LandedBlocks[CountX, y - 1];
                }
            }

This (I think) moves all the lines down one line. The problem is with the loop boundaries always going to line 0. You should only be moving the lines above whichever line you are clearing. Change the y > 0 to y > lineNumber where lineNumber is the line you cleared.


text:
Q: How to render only the Year when using date picker from OctoberCMS backend? I'm using the date picker from the backend, and I'd like to display only the year that the user has selected. For example, instead of rendering 23-12-2017 on the DOM when is use {{ record.year }}, I'd only like to render the year 2017. How do I do this ? Is there a filter or something ?

A: You can use the date filter for Twig:
{{ record.date|date("Y") }}

By the way, if you are only using the year part of the date, you should also only save the year to the database, not the whole date. This would also mean you wouldn't have to format it in the first place.
And if you need to save the whole date, please consider naming it something other than just year :)


text:
Q: Docker: unable to push to insecure private registry I have tried every fix that I have found on the internet and cant seem to get a solution..
I am able to login to the insecure registry because I have the following in the /etc/sysconfig/docker file:
other_args="--insecure-registry http://10.3.31.105 --insecure-registry http://harbor.ie.local"
Here is my login example:
docker login --username USERNAME --password 'PASSWORD' http://10.3.31.105
WARNING: login credentials saved in /home/svc.jenkins/.docker/config.json
Login Succeeded

My OS version is as follows: Red Hat Enterprise Linux Server release 6.8 (Santiago)
My docker version is as follows:
docker version
Client version: 1.7.0
Client API version: 1.19
Go version (client): go1.4.2
Git commit (client): 0baf609
OS/Arch (client): linux/amd64
Server version: 1.7.0
Server API version: 1.19
Go version (server): go1.4.2
Git commit (server): 0baf609
OS/Arch (server): linux/amd64

The image that I am trying to push is as follows:
10.3.31.105/okreach/springboot                         latest              cb4b8dccc4fd        5 hours ago         292.1 MB
My docker push attempt is as follows:
docker push 10.3.31.105/okreach/springboot:latest
Error response from daemon: invalid registry endpoint https://10.3.31.105/v0/: unable to ping registry endpoint https://10.3.31.105/v0/
v2 ping attempt failed with error: Get https://10.3.31.105/v2/: dial tcp 10.3.31.105:443: connection refused
 v1 ping attempt failed with error: Get https://10.3.31.105/v1/_ping: dial tcp 10.3.31.105:443: connection refused. If this private registry supports only HTTP or HTTPS with an unknown CA certificate, please add `--insecure-registry 10.3.31.105` to the daemon's arguments. In the case of HTTPS, if you have access to the registry's CA certificate, no need for the flag; simply place the CA certificate at /etc/docker/certs.d/10.3.31.105/ca.crt

As you can see, it does not even attempt connecting via http... only https... and adding --insecure-registry as an argument does not work out too well for me:
docker push --insecure-registry=10.3.31.105 10.3.31.105/okreach/springboot:latest
flag provided but not defined: --insecure-registry
See 'docker push --help'.

So if anyone knows the trick to get a successful push to an insecure registry on a RedHat (6.8) system, I would appreciate it :)
Thanks

A: So problem fixed by changing my other_args="--insecure-registry http://10.3.31.105 --insecure-registry http://harbor.ie.local to this other_args="--insecure-registry http://10.3.31.105 --insecure-registry 10.3.31.105
For anyone having the same issue... there is not much detailed online about this when using RHEL (6.8)


text:
Q: NotifyDataSetChanged- RecyclerView -Is it an asynchronous call? I am trying to follow a set of statements after the execution of notifyDataSetChanged on a recyclerview. But when I am debugging my application, the debugger reaches the next few lines after my notifyDataSetChanged before going to the onBindViewHolder of the recyclerview's adapter. So my question is- Is the notifyDataSetChanged an asynchronous call? If yes do we get a callback?
PS: I have already googled this answer and I couldn't find a suitable answer that's why I am asking the community.

A: RecyclerView author here,
When you call notifyDataSetChanged, RecyclerView invalidates the data but does not update the UI until the next animation frame. This is how android view system works. When a widget is invalidated (e.g. changing its data) it requests a layout which means it will be re-measured and re-laid out in the next view traversal. This is done so that we can batch all changes until the next time screen will be updated. This is why notifyDataSetChange does not trigger an onBind instantly.
So yes, you can call this as an async call but that does not mean that you can run it multi-threaded (these are two totally different concepts). You still have to make all changes to your adapter on the main thread. When you change the adapter, you have to notify RecyclerView instantly, which is why notify also has to be on the main thread.
The reason for this limitation is that if the data set is changed during a layout, it is very hard for the layout manager to recover to a stable state (e.g. imagine RecyclerView calls onBind(5) and item 5 is removed in another thread at the same time). Also, accounting for such changes will require a lot of synchronization which will be a big performance penalty without any benefit. This is why all UI components are single threaded.

A: TLDR: No. You can call notifyDatasetChanged() only from the UI thread as indicated here which does the changes to the UI which can only be done on the main thread.This makes the call synchronous.
This call is meant to redraw the ui with the changed elements.It is like calling requestFocus() on a view.
From the documentation:

RecyclerView will attempt to synthesize visible structural change events for adapters that report that they have stable IDs when this method is used. This can help for the purposes of animation and visual object persistence but individual item views will still need to be rebound and relaid out.

Since the views are redrawn because the dataset expects a change,It has to be on the main UI thread(only the main looper(i.e the UI thread) can modify views).
You can have multiple AdapterObservers which can perform actions that you need on the ui.
Also from the documentation:

*

*This event does not specify what about the data set has changed, forcing
       * any observers to assume that all existing items and structure may no longer be valid.
       * LayoutManagers will be forced to fully rebind and relayout all visible views.

The default observer will assume that all the data has been changed since from the source code of Recycler view :
 public final void notifyDataSetChanged() {
        mObservable.notifyChanged();
    }

It is a synchronous call which should be avoided and used as a last resort.

A: I came across this issue because I needed to do some layout reconfiguration based on the size of my recyclerview, and since I had height set to wrap_content, the size was changing whenever its data would change. To effectively respond to layout changes, you can use a short subclass of your layout manager (in my case it was a LinearLayoutManager) and override onLayoutCompleted:
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()){
        @Override
        public void onLayoutCompleted (RecyclerView.State state){
            super.onLayoutCompleted(state);
            // update UI for new layout
        }
    });

In my case I needed to scroll my ScrollView after the size changed on the RecyclerView, and this code did the trick.


text:
Q: Find ${(ab)}^{-1}$ if $a^2=e, b^6=e, ab=b^4a$ where $a,b$ are elements of a group
If $a,b$ are elements of a group and $a^2=e, b^6=e, ab=b^4a$, then find the order of $ab$ and express ${(ab)}^{-1}$ in terms of $a^mb^n$ and $b^ma^n$

I could find the order of $ab$ to be 6 but struggling to find ${(ab)}^{-1}$ in terms of $a^mb^n$ and $b^ma^n$.
Please help me move forward.

A: As indicated in hints beneath the OP,
$$(ab)^{-1}=b^{-1}a^{-1}=b^5a$$
which gives the inverse in the form $b^ma^n$.  To get it in the form $a^mb^n$, use the equation $ab=b^4a$ to obtain
$$(ab)^{-1}=(b^4a)^{-1}=a^{-1}b^{-4}=ab^2$$
Added later: It's worth noting that $(ab)^{-1}=ab^2=b^5a$ implies $(ab)^{-2}=(ab^2)(b^5a)=aba$ and hence (using what the OP found, namely $(ab)^6=e$)
$$e=(ab)^{-6}=(aba)(aba)(aba)=ab^3a$$
from which it follows that $b^3=e$, so the order of $b$ is not $6$. (This was found by orangeskid in more direct fashion.)

A: We have
$$b = a b^4 a = (a b a)^4= (b^4)^4=b^{16}= b^6 \cdot b^6 \cdot b^4 = b^4$$
so $b^3=e$ and $ab= b a$. From here it is easy to see that the order of $ab$ is $\le 6$  (it is in fact the product of the orders of $a$, $b$, these being relatively prime). Moreover, $(ab)^{-1}=a^{-1}b^{-1}=a b^2= b^2 a$.

A: With the information given, you could actually simplify the powers of $ab$ in succession
$(ab)^2 = b^4a\cdot ab = b^5$
$(ab)^3 = ab\cdot b^5 = a$
$(ab)^4 = a\cdot ab = b$
$(ab)^5 = ab\cdot b = ab^2$
Also $(ab)^5 = b\cdot b^4a = b^5a$
And finally  $(ab)^6 = b^5a\cdot ab = b^6=e$ meaning that $(ab)^{-1} = (ab)^5$
[However, also $(ab)^3 = b^5\cdot b^4a = b^3a$ which gives us $b^3=e$, but using that might confuse whoever is marking the question]


text:
Q: Еrror-pаge in Spring good afternoon everyone
my question is banal, but I just can't find the answer,
I need my custom error page to be thrown for any invalid link
I use Java configuration, not web.хml
i added in application.properties
server.error.whitelabel.enabled=false
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration

and created controller
@Controller
public class MyErrorController implements ErrorController {

    @RequestMapping("/error")
    public String handleError() {
        //do something like logging
        return "error404";
    }

    @Override
    public String getErrorPath() {
        return "/error";
    }
}

i used this tutorial https://www.baeldung.com/spring-boot-custom-error-page
and this not work, can u help me?

A: Comment this line in your application.properties file or remove:
   #spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration

It is wrong information in the article from baeldung.com. ErrorMvcAutoConfiguration should be auto-detected in order to auto register custom ErrorController
Update for those people who don't believe and downgrade my answer:
It works!!!


text:
Q: iPhone Development: Global Variables I am very new to Objective-C. I need to make a global variable. I have the files abc.h, abc.m, aaa.h, aaa.m and of course, the app delegate.
I want to declare it in abc.h, use have the user assign it in abc.m and it be used in aaa.m.
I want the variable to be an integer named x. I heard that I can use the App Delegate Somehow.
I want the assigning variable in abc.m to be implemented in the middle of my code.
Since I'm new, please make it simple!!
Thanks in Advance!

A: You can use a property in your application delegate, as you can always get the app delegate instance with:
[ [ UIApplication sharedApplication ] delegate ]

So:
/* AppDelegate.h */
@interface AppDelegate: NSObject < UIApplicationDelegate >
{
    int x;
}
@property( readonly ) int x;
@end

/* AppDelegate.m */
#import "AppDelegate.h"
@implementation AppDelegate
@synthesize x;
@end

This way, you'll be able to use:
[ [ [ UIApplication sharedApplication ] delegate ] x ]

Another approach is to use a global variable, declared as extern in your abc.h file, and defined in the abc.m file.
/* abc.h */
extern int x;

/* abc.m */
int x = 0;

This way, other files will be able to access x, only by including abc.h.
extern tells the compiler that the variable will be defined later (e.g. in another file), and that it will be resolved at link time.

A: Instead of putting all the burden in AppDelegate I'll recommend you to create your own singleton class, and then use it anywhere you want to use. Here is the sample of creation of singleton class: http://www.71squared.com/2009/05/iphone-game-programming-tutorial-7-singleton-class/

A: I'd recommend creating your own singleton class so as to avoid cluttering up the UIApplication delegate. It also makes your code neater. Subclass NSObject and add code a bit like the following:
static Formats *_formatsSingleton = nil;
+ (Formats*) shared
{
    if (_formatsSingleton == nil)
    {
        _formatsSingleton = [[Formats alloc] init];
    }
    return _formatsSingleton;
}

Add ivars and properties to this class as required. You can set default values in an init method, e.g.
- (id) init;
{
    if ((self = [super init]))
    {
        _pgGlobalIntA = 42;   // ivar for an int property called globalInt
        _pgGlobalStringB = @"hey there";   // ivar for an NSString property called globalStringB
    }
    return self;
}

And then to set and access you'd use:
 [[Formats shared] setGlobalIntA: 56];
 NSLog(@"Global string: '%@'", [[Formats shared] globalStringB]);

The class method shared creates an instance of the class if one doesn't exist already. So you don't have to worry about creating it. It'll just happen the first time you try to access or set one of your globals.


text:
Q: randomly selecting between two columns of data in a table in R so I have a table which contains data on a subject taking two versions of a test. What I would like to do is write some code that allows me to randomly select which version of the test to include in the final table and which to discard. Here is some example data:
ID     test1    test2

38762   21       36
37874   17       20
37813   15       17
37738   23       31
37470   25       36
37308   31       32
37039   25       16
36045   16        9

I need this to be as close to random as possible, so any help would be greatly appreciated.
Thanks in advance
EDIT: Desired output:
row.names   ID  test1
    67  38762   21
    218 36045   16

row.names   ID  test2
    108 37874   20
    114 37813   17
    117 37738   31
    140 37470   36
    152 37308   32
    175 37039   16

A: You could something like this: start out by making your three columns a data frame, if the aren't already. Then subset that data frame according to a random vector of 0s and 1s you generated.
 df <- cbind(ID, test1, test2)
 #make vector of 0s and 1s of the length = number of rows of df
 ran <- sample(c(0,1), nrow(df), replace = TRUE)

 group1 <- subset(subset(df, select = c(ID, test1)), subset = ran == 0)
 group2 <- subset(subset(df, select = c(ID, test2)), subset = ran == 1)

A: > df=NULL
> df$ID=sample(38700:38800,10,F)
> df$test1=sample(15:25,10,F)
> df$test2=sample(15:35,10,F)
> df=as.data.frame(df)
> df
      ID test1 test2
1  38784    24    19
2  38747    15    15
3  38791    16    34
4  38721    25    32
5  38769    20    23
6  38706    21    26
7  38702    17    29
8  38761    22    28
9  38763    19    25
10 38740    23    16
> df$ran=sample(2,nrow(df),T)
> df$test=ifelse(df$ran==1,df$test1,df$test2)
> df
      ID test1 test2 ran test
1  38784    24    19   1   24
2  38747    15    15   1   15
3  38791    16    34   1   16
4  38721    25    32   1   25
5  38769    20    23   1   20
6  38706    21    26   1   21
7  38702    17    29   2   29
8  38761    22    28   1   22
9  38763    19    25   1   19
10 38740    23    16   2   16
> df$testchosen=ifelse(df$ran==1,"test1","test2")
> df
      ID test1 test2 ran test testchosen
1  38784    24    19   1   24      test1
2  38747    15    15   1   15      test1
3  38791    16    34   1   16      test1
4  38721    25    32   1   25      test1
5  38769    20    23   1   20      test1
6  38706    21    26   1   21      test1
7  38702    17    29   2   29      test2
8  38761    22    28   1   22      test1
9  38763    19    25   1   19      test1
10 38740    23    16   2   16      test2
>


text:
Q: Use Parse without push notifications I have an app that doesn't use push notifications. However, I'm using Parse for other reasons. When I submit my build I get the warning from iTunes that says:

"Missing Push Notification Entitlement - Your app appears to include
  API used to register with the Apple Push Notification service, but the
  app signature's entitlements do not include the "aps-environment"
  entitlement. If your app uses the Apple Push Notification service,
  make sure your App ID is enabled for Push Notification in the
  Provisioning Portal, and resubmit after signing your app with a
  Distribution provisioning profile that includes the "aps-environment"
  entitlement.  See "Provisioning and Development" in the Local and Push
  Notification Programming Guide for more information. If your app does
  not use the Apple Push Notification service, no action is required.
  You may remove the API from future submissions to stop this warning.
  If you use a third-party framework, you may need to contact the
  developer for information on removing the API."

Is there a way that I can silence this warning for future builds and not get the entitlements?

A: I'm afraid you're stuck with this warning, it is completely fine to just ignore it.


text:
Q: form with spans inline and block in relation to input text Im learning about css and Im trying to draw a form with 3 columns but Im having some difficulties.
First Im using 3 fieldsets and Im floating each one at left, this is correct to do? Or for example should we float the first two columns at left and the last at right?
Then Im trying to do something with the layout but Im with some difficulties to achieve it correctly. The first and second column it is ok I want this layout:
Product                  User

InputTextBelowSpan       InputTextBelowSpan

But it the third column I want something different, with the span and the inputs inline, like this:
Product               User                 hashcod  InputTextInlineWithSpan

InputTextBelowSpan   InputTextBelowSpan    hashcod  InputTextInlineWithSpan

But Im with some difficulties doing this, having the inputs below span in the first and second columns and the inputs inline with the span in the third column. The difficulty is to have all inputs with the same width using percentanges, so the layout ajudsts to the browser width.
Do you know how to do this?
This is what I have:
https://jsfiddle.net/e8fh5beb/
Html:

  <form class="form">

    <fieldset class="form_left">

        Product
        <input type="text"/>

        Cod
        <input type="text"/>

    </fieldset>

    <fieldset class="form_left ">

        User
        <input type="text"/>

        ID
        <input type="text"/>

    </fieldset>

    <fieldset class="form_left last">

        hashcod
        <input class="hashcod" type="text"/>

        hashcod
        <input class="hashcod" type="text"/>

    </fieldset>

  </form>

Css:
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

.container{
  width:100%;
  float:left;
}

.form{
    float:left;
    width: 100%;
}

.form_left{
    float:left;
    border:1px solid yellow;
    width: 32%;
    margin-right: 2%;
}

.form_left.last{margin-right:0;}

fieldset{border:0;}
label{width:100%; margin-bottom: 20px; display: block;}
label span{display:block; margin-bottom: 8px; color:#717f86;}
input{padding: 10px; width: 100%;}

.hashcod{
  display:inline-block;
}


text:
Q: Order MultiIndex columns by string and number in pandas I have a pandas multiIndex dataframe that I want to order by name and number.
A similar dataset, df is created as example:
random= np.random.rand(3,10)
a = [ 'a','b','a','b','a','b','a','b','a', 'b']
b = ['p11_1','p11_1','p1_1','p1_1','p9_1','p9_1','p10_1','p10_1','p1_2','p1_2']
arrays = [a,b]
df = pd.DataFrame(data = random, columns = arrays)

Header layers look like:
   a         b         a  ...         b         a         b
  p11_1     p11_1      p1_1  ...     p10_1      p1_2      p1_2

I can use the a simple sort command but that results in the wrong output:
df = df.sort_index(axis=1)

Header layers look like:
      a                      ...         b
  p10_1     p11_1      p1_1  ...      p1_1      p1_2      p9_1

This orders both layers, but the second layer is not the desired output.
The desired output orders the second layer as follows:
p1_1 < p1_2 < p9_1 < p10_1 < p11_1

and not as:
p10_1 < p11_1 < p1_1 < p1_2 < p9_1

Anything would help!

A: Let us try natsorted
from natsort import natsorted
df=df.reindex(columns=natsorted(df.columns.tolist(), key=lambda element: (element[0], element[1])))
Out[126]:
          a                      ...         b
       p1_1      p1_2      p9_1  ...      p9_1     p10_1     p11_1
0  0.122500  0.339663  0.880657  ...  0.258351  0.777972  0.824912
1  0.506081  0.947983  0.502101  ...  0.626606  0.187132  0.344037
2  0.465429  0.688159  0.396115  ...  0.840099  0.750303  0.932954
[3 rows x 10 columns]

A: You can use regex to extract the digits, convert to int and sort:
import re
new_cols = sorted(df.columns, key=lambda x: (x[0],)+tuple(map(int, re.findall('(\d+)', x[1])) ))

df = df[new_cols]

Output:
          a                                                 b            \
       p1_1      p1_2      p9_1     p10_1     p11_1      p1_1      p1_2
0  0.573945  0.648582  0.018916  0.349072  0.242901  0.672357  0.264832
1  0.362348  0.046961  0.245218  0.971988  0.337589  0.868794  0.357096
2  0.653817  0.882649  0.103931  0.778984  0.777559  0.056299  0.252898

       p9_1     p10_1     p11_1
0  0.645881  0.633993  0.340431
1  0.908928  0.527769  0.862013
2  0.302780  0.497609  0.378155

A: Considering you need to naturally sort the second level, you can call numpy.lexsort:
get_level = df.columns.get_level_values
idx = np.lexsort((
    get_level(1).str.extract(f'p(\d+)', expand=False).astype(int), get_level(0)))

df.iloc[:, idx]

          a                      ...         b
       p1_1      p1_2      p9_1  ...      p9_1     p10_1     p11_1
0  0.879848  0.384629  0.006705  ...  0.296052  0.716751  0.790975
1  0.139579  0.158237  0.737015  ...  0.702624  0.356452  0.557185
2  0.335480  0.133805  0.040322  ...  0.161040  0.622088  0.219986


text:
Q: BASH Script: Why Do My Variables Not Work I'm trying to use some script variables in a BASH script to make my code clearer.
However, for some reason, my variables are not being expanded/used.
Nothing happens when I use the variable with the full command spelled out
This is the script I made :
command1=$SOMEPATH/abc.sh
command2=$SOMEPATH/def.sh input
command3=$SOMEPATH/ghi

 gnome-terminal                                                                   \
 --tab -t "Server 1"  -e 'bash -c "export BASH_POST_RC=\"$command1\"; exec bash"'  \
 --tab -t "Server 2"  -e 'bash -c "export BASH_POST_RC=\"$command2";  exec bash"' \
 --tab -t "Server 3"  -e 'bash -c "export BASH_POST_RC=\"$command3";  exec bash"'

Thanks for any tips

A: Declare your variables in double quotes
command1="$SOMEPATH/abc.sh"
command2="$SOMEPATH/def.sh input"
command3="$SOMEPATH/ghi"

Hope this helps!