text:
Q: Parsing JSON into Jackson using a stream/object approach I have a JSON file which can have multiple types.
For example:
{
    "dog": {
        "owner" : "John Smith",
        "name" : "Rex",
        "toys" : {
            "chewtoy" : "5",
            "bone" : "1"
        }
    },
    "person": {
        "name" : "John Doe",
        "address" : "23 Somewhere Lane"
    }
    // Further examples of dogs and people, and a few other types.
}

I want to parse these into objects. ie. I want to create a Dog object with owner/name/toys attributes, and person with name/address attributes, and use Jackson to read through and create objects out of them.
The ordering matters - I need to know that Rex came before John Doe, for example. I would prefer to do with a stream like approach (ie. read and parse Rex into the Dog object, do something with it, then discard it, then move onto to John Doe). So I need a stream based approach.
I can't figure out how to use both the stream reading API (to go through in order) and the ObjectMapper interface (in order to create Java objects out of JSON) to accomplish this.

A: To do this, you need to use an object mapper with your factory
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;
...
private static ObjectMapper mapper = new ObjectMapper();
private static JsonFactory factory = mapper.getJsonFactory();

Then create a parser for the input.
JsonParser parser = factory.createJsonParser(in);

Now you can mix calls to parser.nextToken() and calls to parser.readValueAs(Class c).  Here is an example that gets the classes from a map:
Map<String, Class<?>> classMap = new HashMap<String, Class<?>>();
classMap.put("dog", Dog.class);
classMap.put("person", Person.class);

InputStream in = null;
JsonParser parser = null;
List<Object> results = new ArrayList<Object>();
try {
  in = this.getClass().getResourceAsStream("input.json");
  parser = factory.createJsonParser(in);
  parser.nextToken();// JsonToken.START_OBJECT
  JsonToken token = null;
  while( (token = parser.nextToken()) == JsonToken.FIELD_NAME ) {
    String name = parser.getText();
    parser.nextToken(); // JsonToken.START_OBJECT
    results.add(parser.readValueAs(classMap.get(name)));
  }
  // ASSERT: token = JsonToken.END_OBJECT
}
finally {
  IOUtils.closeQuietly(in);
  try {
    parser.close();
  }
  catch( Exception e ) {}
}


text:
Q: How to add a Modal popup to lit element Project I am developing a project using lit. Already developed two web components using lit.
I need to add image gallery, carousal, and also modal popup to open when click on a button inside those components.
And I saw that https://opensource.adobe.com/spectrum-web-components/components/card/ has already developed those components using lit. I installed one of those component to my lit project. But styles are no showing.
The question is, can I use those spectrum web components to lit project and why is styling now working.
Here is my component code with spectrum button,
import { LitElement, html, css} from 'lit';

import '@spectrum-web-components/button/sp-button.js';
import '@spectrum-web-components/button/sp-clear-button.js';
import { Button, ClearButton } from '@spectrum-web-components/button';

class plans_component extends LitElement {

    static properties = {
       ...
    }

    static styles = [
        ...

    ]

    constructor() {
        super();
...

    }

    render() {

        return html `
        <sp-button size="xl">Extra Large</sp-button>

       `
    }

}

customElements.define('plans-component', plans_component);

Thanks in advance.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Calculate confidence interval for 1 dimension random data I want to know how to calculate the given confidence interval for 1 dimension (this could simplify the question) random data.
The situation is like this: suppose I have 50 random points of data from 1 to 100 (not normally distributed), and I want to know the min range that we have for  90% of the data points located in that range.
This is quite similar to the confidence interval for normal distribution.
Is there any one can help me on this?
Thanks.

A: I believe this question would be more suited to the mathematics stackexchange, but since it is here I'm gonna roll with it.
You don't specify in which programming language you want to achieve this, therefore I believe your problems lie elsewhere, in the theoretical realm of the subject. Thus the best I can do is to point you to good topics about your question.
After doing some research, this is what I found:

*

*Wikipedia's page on Confidence Intervals: https://en.wikipedia.org/wiki/Confidence_interval

*Khan Academy Confidence interval explained (I highly recomend it !): https://www.khanacademy.org/math/probability/statistics-inferential/confidence-intervals/v/confidence-interval-1

*Stat Treck summary on Confidence intervals: http://stattrek.com/estimation/confidence-interval.aspx
With this in mind, I also took the liberty of checkign other StackOverflow questions. And I found something that I believe is exactly what you need:

*

*Java calculate confidence interval
Hope it helps!


text:
Q: Review audit detection scripts - acceptable? I noticed that there's a userscript on StackApps which detects review audits and warns you about them (It can also be done 100% reliably by monitoring the AJAX requests to /review) and there's at least a few people interested / using them or similar scripts, judging from comments on a recent MSO post.
Is using a script to avoid audits  acceptable ?
I think that using something like this is cheating the system, and makes robo-reviewing too easy - should this be deleted from StackApps, or the system changed so that it's no longer possible to detect audits client side ?

A: The purpose of audits is twofold:

*

*As an educational tool to help you learn to use the particular review queue.

*As a tool to prevent mistakes due to fatigue or carelessness.

If you already know how to use the queue and you don't make mistakes, then audits are unnecessary.
OTOH, if you don't care that you make mistakes and use a tool to prevent the system from detecting them... Then that's a problem.
Toying with the idea of dialing back audit frequency and just auto-banning people whose reviews are too far outside of the norm.


text:
Q: Writing to read only files from C# I have Word Add-in, which keeps updating "winword.exe.config.xml" file present at "C:\program files\microsoft office\.
I need to write changes to this file,update few parameters while running MS word.
when the User is "Administrator", the changes are updated successfully in the file without any problem.
In case of Non - Admin accounts(they do not have the file permission), the changes are not reflected as the write permission is not there.
Is there any way i can write to these files successfully from C# code for Non-Admin accounts also, without asking user to change the permission of the file.

A: If you are in control of the add-in then you simply need to choose a different location for the config file. A location to which a standard user has write permissions.
If you are not in control of the add-in, then you have two viable options:

*

*Always run Word as administrator.

*Add an ACL to the config file to grant write access to standard users.

You ask:

Is there any way I can write to these files successfully from C# code for non-admin accounts also, without asking user to change the permission of the file.

No there is not. Just imagine if there was a way to do this. That would completely negate the utility of file system security.


text:
Q: The best way to automate test with selenium web driver, to check email from gmail? I would like to know the best way to automate a test with selenium web driver, to validate an email sent by an application.
I've tried to automate, but the "Captcha" validation appears and i cannot pass that screen. I'm using java.


text:
Q: Trailing route polyline on marker move event I am using leaflet and pubnub libraries to move marker smoothly on Google maps, with real-time data. This functionality is working fine and marker moves smoothly on map from one point to next point.
But I could not find a way to draw a route polyline from marker to destination and trailing line with marker move event. I want to show route line same as Uber, from car icon to destination and trailing line with car movement.
Any help would be appreciated.
I am using the following pubnub SDK:
https://www.pubnub.com/developers/eon/map/bus/
Here is my pubnub object initialization code:
var connectline = 0;
var lastlng = [40.80523269999999, -73.7412536];
var pubnub = new PubNub({
    publishKey: 'pub-c-5e4c8233-c59b-448c-a809-9c09f61715XX',
    subscribeKey: 'sub-c-74a7e51a-ad14-11e4-a808-02ee2ddab7XX'
});

var trip = '134386886'; // '134386875';
var channel = 'TRIP_' + trip;

alert("channel name=" + channel);

var map = eon.map({
    pubnub: pubnub,
    id: 'map',
    options: {
        center: new L.LatLng(40.80523269999999, -73.7412536),
        zoom: 15
    },
    mbId: 'ianjennings.l896mh2e',
    mbToken: 'pk.eyJ1IjoiaWFuamVubmluZ3MiLCJhIjoiZExwb0p5WSJ9.XLi48h-NOyJOCJuu1-h-Jg',
    channels:[channel],
    message: function (data) {
        map.setView(data[trip].latlng, 15);

    },
    transform: function(m) {
        var a = {};
        a[m.common.trip_id] = {
            latlng: [m.common.latitude, m.common.longitude],
            data: m.common
        }
        return a;
    },
    rotate: true,
    // history: true,
    marker: function (latlng, data) {
        var icon = new Icon();
        var parisKievLL = [lastlng, latlng];
        var marker = L.Marker.movingMarker(parisKievLL, [10000], {icon:icon}).addTo(map);
        lastlng = latlng;
        // alert('marker data=' + JSON.stringify(data));
        // alert('market latlng' + JSON.stringify(latlng));
        // var latlng = [data.latitude, data.longitude];
        var addressMarker = L.marker([40.80523269999999, -73.7412536]).addTo(map);
        marker.bindPopup('car #:' + data.device_id);
        return marker;
    }
});


text:
Q: hashMap - hashCode & equals method return type I'm working on a Card game on Java and I'm trying to compare the key from a hashMap to an element in an ArrayList (both are objects). hashCode() and equals() are overridden but an error showed up and I'm not sure which part of it is wrong.
Here's the Cards class
class Cards implements Comparable<Cards> {
    public String suit;
    public String face;

    public Cards() {

    }

    //Create Cards object
    public Cards (String suit, String face){
        this.suit = suit;
        this.face = face;
    }

    //Return card suit
    public String getSuit() {
        return suit;
    }

    //Return card face
    public String getFace() {
        return face;
    }

    @Override
    public int compareTo(Cards currentCards) {
        if (getSuit().compareTo(currentCards.getSuit()) > 0) {
            return 1;
        } else if ((getSuit().compareTo(currentCards.getSuit())) < 0){
            return -1;
        } else if ((getSuit().compareTo(currentCards.getSuit())) == 0){
            if (getFace().compareTo(currentCards.getFace()) > 0){
                return 1;
            } else if (getFace().compareTo(currentCards.getFace()) < 0){
                return -1;
            }
        }
        return 0;

    }

    @Override
    public boolean equals(Object o) {
        if (o == this)
            return true;
        if (!(o instanceof Cards))
            return false;
        Cards other = (Cards)o;
        boolean suitEquals = (this.suit == null && other.suit == null) ||
                        (this.suit != null && this.suit.equals(other.suit));
        boolean faceEquals = (this.face == null && other.face == null) ||
                        (this.face != null && this.face.equals(other.face));
        return suit && face;

    }

    @Override
    public int hashCode() {
        int result = 17;
        if (suit != null) {
            result = 31 * result + suit.hashCode();
        }
        if (face != null) {
            result = 31 * result + face.hashCode();
        }
        return result;
    }

}

and the comparison we're trying to work
/**Creating Cards object*/
String[] SUIT = new String[]{ "d", "c", "h", "s" };
String[] FACE = new String[]{ null, "A", "2", "3", "4", "5", "6", "7", "8", "9", "X", "J", "Q", "K" };
Cards[] cardDeck = new Cards[52];
int index = 0;

  for (int i = 0; i <= 3; i++) {
      for (int j = 1; j <= 13; j++) {
          cardDeck[index] = new Cards(SUIT[i], FACE[j]);
          index++;
      }
  }

/**Player 1 in hand*/
ArrayList<Cards> player1 = new ArrayList<Cards>();
int j=0;

for (int i = 0; i <18; i++){
        player1.add(i, cardDeck[j++]);
    }

for(Cards n : player1){
    if (Points.containsKey(n)){
        System.out.println("Card points: " + Points.get(n));
    }
}

Error:
click to see picture of error

A: You are trying to use two String objects as boolean objects:
Replace return suit && face; in your equals method with return suitEquals && faceEquals.


text:
Q: horizontal scrollable list fully centered with dynamic width items I'm trying to make an horizontal list to be centered, with its items to be centered too regarding the main parent (the window, or body) ; and because i don't know what kind and how many items i will have generated into that list, i'd need the items to be dynamic in width and the list scrollable so i can browse over all of them.
My attempts so far are good, i'm getting either : a centered list with non-centered items of dynamic width ; and a fully centered scrollable list with fixed width items.
The core idea is basically achieved by using:
ul {
  width: 100%;
  overflow-x: scroll;
  overflow-y: hidden;
  white-space: nowrap;
}

li {
  display: inline-block;
}

Then the centering is made by wrapping the
 into a
, and making the
 scroll the
 instead of the
 scrolling the
. It allows to add % based margins to the

div {
  width: 100%;
  overflow-x: scroll;
  overflow-y: hidden;
  white-space: nowrap;
}

ul {
  margin: 0 50%;
}

li {
  display: inline-block;
}

For items to be centered by width, the idea is to use translateX(-50%) with a little twist: as i don't want my list to have extra space at the end of the scrolling, I'm removing the last item from the flow by positioning it in absolute at the end ; that way, the
 width looks like the sum of the items width minus one item.
ul {
  position: relative;
  margin: 0 50%;
}

li {
  display: inline-block;
  width: some_number;
  transform: translateX(-50%);
}

li:last-child {
  position: absolute;
  left: 100%;
}

But how to keep it that way without setting the width is a mystery to me.
Any ideas out there ?
Here's my fiddle with some comments in the CSS section : https://jsfiddle.net/11gkrju0/
I'd like not to use javascript at all for that as it is only a matter of styling, but messing with the dom is a totally viable option.
Thanks all for reading,

A: Ok so it's a bit tricky. The resolved fiddle is here with comments which i'm gonna describe here too. https://jsfiddle.net/11gkrju0/7/
First thing to notice, i added a vertical-align: top; to my
s to make sure there's no vertical gap at some point.
Then.
Boundaries for a non centered list are easy to catch:
+-----+---+---------+
|  A  | B |    C    |
+-----+---+---------+
^                   ^
a                   b

For a centered list, they change a little bit :
+-----+---+---------+
|  A  | B |    C    |
+-----+---+---------+
^  ^           ^    ^
a  c           d    b

To make the scroll right, we need to change the width of the
 from A->B to C->D. As its width is dynamicly calculated by its children width, we need to alter the children.
We can see that only the first and last children are the ones to be altered. As the text defines the width of each children, we cannot change the width property, but we can divide by 2 some defined values much more easily : font-size, padding.
li {
  font-size: 12px;
  padding: 0 50px;
}

li:first-child, li-last-child {
  font-size: 6px;
  padding: 0 25px;
}

Now the list may look more like
+---+---+-----+
| a | B |  c  |
+---+---+-----+
^  ^       ^  ^
a  c       d  b

But then the problem is that the text and padding are smaller now. What we can do is to proxy the real buttons into an :after with the little trade of adding a text attribute to the li to feed the content property.

A

B

C

With that in the DOM, we can write that kind of CSS to create fake buttons which looks just like the real one (not to mention, hide the real one...)
li {
  position: relative;
  background: transparent;
  color: transparent;
}

li:after {
  display: block;
  overflow: hidden;
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  content: attr(text);
  color: #000;
}

Almost there, almost there...
The first and last children have been altered, and so their pseudo-child too... Side effect is that the width will be calculated for a 6px font-size. So we need to set back the width to twice needed, and reset the font-size to prevent inheritance.
li:first-child:after, #d li:last-child:after {
  font-size: 12px;
  width: 200%;
}

Finally (yay), we pad the first element to half of its width to prevent collision with the 2nd one.
li:first-child:after {
  left: -100%;
}

We could have used transform: translateX(-50%); as well, but we're already manipulating absolute values so there's no need to apply an other layer of calculation on that.
Hoping it'll help someone.


text:
Q: VBA replacing ALL placeholders in Outlook html template with userform textbox and combobox I'm not a programmer, but I like to create little macros for saving time on iterative tasks. Right now I was trying to create an userform able to replace on an HTML template few placeholders.
The code I've made so far:
Private Sub CommandButton1_Click()

    Dim OutApp As Object
    Dim OutMail As Outlook.MailItem

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = Application.CreateItemFromTemplate("C:\path\ciccio.oft")

    With OutMail
        .To = TextBox4.Text
        .CC = ""
        .BCC = ""

        .HTMLBody = Replace(.HTMLBody, "###PLACEHOLDER1###", TextBox1.Text)
        .HTMLBody = Replace(.HTMLBody, "###PLACEHOLDER2###", ComboBox1.Text)

        Unload UserForm2
        .Display
    End With

    Set OutMail = Nothing
  Set OutApp = Nothing

End Sub

This works good on a plain text body, but on the HTML body just refuses to replace all ..
and seems even a little random.. so something is replaced and the rest not.
Any help?

A: Solved.
The issue is in how is formatted the html body. I've edited the placeholder words in other file and then copy directly on the template, saving it.


text:
Q: Jquery links good practice Have this
something

and then I handle it in Jquery code. This displays the # in browser status bar when hover. Is this a good practice for production, other alternatives?
Thanks

A: You can use event.preventDefault() to stop links from redirecting the page:
HTML:
Let's go to DisneyLand!

jQuery:
$("a").click(function(e){
//jQuery passes in the event object as e
e.preventDefault();
alert("LOL, you really thought you were going?");
});

http://jsfiddle.net/TrXAs/

A: You don't even have to define the href attribute. Usually I will just code like this:
Link

or
$('#blah').click(function(){...});
...
Link

Check the specifications:
http://www.w3.org/TR/2003/WD-xhtml2-20030506/mod-hypertext.html
http://www.w3.org/TR/html401/struct/links.html#edef-A
There are more I'm sure but I suppose it really depends on the doctype you're using. Anyway long story short it's not bad practice to not specify the href attribute and a validator should pass it. And yeah... # in the address bar always looks messy to me.

A: Hash sign appearing in the url isn't really that wrong, but the other effect you may notice is your page being scrolled to it's top after clicking a link.
To fix that, in the function which responds to your event you should use event.preventDefault() (assuming you're catching event parameter):
$(element).click( function(event) {
    event.preventDefault();
    // your code...
})

or use return false:
$(element).click( function(event) {
    // your code...
    return false;
})


text:
Q: (change) angular not after first element angular 6 Good afternoon, I am implementing a simple image upload. I am facing one with a problem.
Problem scenario
1 - when selecting multiple files and adding them to a this.listFile list
2 - There is a method to remove an element through its index
3 - When I remove all the elements from the list, and redo the previous steps, the onChange () method no longer works.
Demo Project:
https://stackblitz.com/edit/upload-form?embed=1&file=src/app/app.component.ts

Demo Code
import { Component, OnInit } from "@angular/core";
import {
  FormBuilder,
  FormGroup
} from "@angular/forms";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  public formCatalogSeller: FormGroup;
  public listFile: Array<any>;

  constructor(private fb: FormBuilder) {
    this.listFile = [];
  }

  ngOnInit() {
    this.initForm();
  }

  public removerFile(idx: string): void {
    const index = this.listFile.indexOf(this.listFile[idx]);
    if (index > -1) {
      this.listFile.splice(index, 1);
    }
  }

  public onChange(event) {
    const selectedFiles = <FileList>event.target.files;

    for (let i = 0; i < selectedFiles.length; i++) {
      this.listFile.push({ name: selectedFiles[i].name });
    }
  }

  private initForm(): void {
    this.formCatalogSeller = this.fb.group({
      images: []
    });
  }
}

A: the solution to the problem was just to clean the input file
ex:
@ViewChild("inputFile") myInputVariable: ElementRef;

public removerFile(idx: string): void {
    const index = this.listFile.indexOf(this.listFile[idx]);
    if (index > -1) {
      this.listFile.splice(index, 1);
      this.myInputVariable.nativeElement.value = "";
    }
  }


text:
Q: How to open Images in Stflacon Library in recycler View? Here is the library dependency:
implementation 'com.github.stfalcon:stfalcon-imageviewer:0.1.0'

Here is the adapter class of the Recycler View:
public class QuotesAdapter extends RecyclerView.Adapter<QuotesAdapter.ViewHolder> {
    List<QuotesModel> quotesModelList;
    Context context;

    public QuotesAdapter(List<QuotesModel> quotesModelList, Context context) {
        this.quotesModelList = quotesModelList;
        this.context = context;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(context).inflate(R.layout.quotes_layout,
                parent, false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

        QuotesModel quotesModel = quotesModelList.get(position);
        holder.cardView.setAnimation(AnimationUtils.loadAnimation(context,R.anim.item_animation_fall_down));

        Picasso.get().load(quotesModel.getImages()).fit().centerCrop().placeholder(R.drawable.placeholders).into(holder.imageView);
    }

    @Override
    public int getItemCount() {
        Log.e("Size of Quotes is :",String.valueOf(quotesModelList.size()));
        return quotesModelList.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        CardView cardView;
        ImageView imageView;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            cardView = itemView.findViewById(R.id.cardView);

            imageView = itemView.findViewById(R.id.images);
        }
    }
}

How can I open these images in "imageView" with this library for full-screen images?


text:
Q: Ignore a database when running a loop that compares two databases I'm writing a MS SQL query that takes one database and compares it to many other databases, using a loop. I want to ignore the comparison of when it gets to comparing itself. Is there a way to do that?

A: Maybe something like this would help?
Database Comparison Tool


text:
Q: Ajax send and adds hidden characters I want to send something from one php site to another.
At the first site, everything seems fine.
The string seems like

--show="author,book,text/n

but when i check the string after receiving it looks like

--show="author,book,text/r/n

there is the problem, somehow it adds /r in the end.
First php:
$(document).ready(function() {
    $("#column_button").click(function(){
        var selected = [];
        $.each($("input[name='checkbox_columns']:checked"), function(){
           selected.push($(this).val());
        });

        var data = new FormData();
        data.append("data", "--show=" + selected);
        //alert(JSON.stringify(selected));
        var ajax = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
        ajax.addEventListener("load", statusHandler2, false);
        ajax.open( 'post', 'showParameter.php', true );
        ajax.send(data);
        _("column_button").disabled=true;
    });
});

Second php:
if(!empty($_POST['data'])){
    $data = $_POST['data'];}

So selected shows it right, but if i check the $data in the second php, it's wrong.

A: This appears to be an issue where the servers are using different line ending types. Unix systems (Linux, BSD, etc) use \n (LF) by default, MacOS uses \r (CR)  where as Windows systems use \r\n (also known as CRLF). You may need to change your character encoding on one of the servers to the other.
CR = carriage return
LF = line feed
You could use code that will substitute the CRLF or CR with just an LF. This page shows how you can achieve this simply.


text:
Q: ExecCommand justifycenter affect the newline I used the
document.execCommand('justifycenter', false).

And it worked, it added the new style in the
.
Just like this
blablabla
.
But the new line also had the same style "text-align: center;"
How to solve this problem?
Thanks!


text:
Q: What is the winforms control that Visual Studio uses as a properties editor? What is the winforms control that Visual Studio uses as a properties editor? It is a two column table with the names on the left side and the editible value on the right side.

A: It is a PropertyGrid.


text:
Q: Objects not show when change iPhone size storyboard to universal in Xcode 7 iOS Objective C I have iPhone app and storyboard is done.
and every view in story board has iPhone size.
Now i tried to set any any size for views but it has problem.
when change size to iPad (any any) , all of objects in views will disappear and then running app , not showing anything in iPad view.
I don't wanna using another storyboard.
Target Device is Universal and i am using Objective C.
Thank you
Help me.

A: Update:
Resolve the issue with cells not appearing on iPad, needed to add the UICollectionViewDelegateFlowLayout methods for iPad.
Original:
If you get the size classes to regular width and height (iPad size classes), then set the constraints for your objects, I assume they are a width and height of 0, that's why you can't see them.
I think it's better to build constraints for (any, any) and then create specifically for iPhone or iPad if necessary, if you are creating a universal app.
Let if know if you encounter problems, hope this helps, good luck.


text:
Q: Python pandas plot TypeError I have a data frame that looks like:
         CreateDate                Store       Orders_am        Orders_pm
0       2018-01-21                  2001           56               2
1       2018-01-21                  2002           51               4
2       2018-01-21                  2003           85               0

dtypes for the data frame are:
CreateDate        datetime64[ns]
Store             int64
Orders_am         int64
Orders_pm         int64

I'm trying to create a simple plot using the following:
plt.plot(df.groupby("Store").plot(x="CreateDate", y="Orders_am"))

But it's throwing the following error:
TypeError: float() argument must be a string or a number, not 'AxesSubplot'

I'm assuming that it's choking on CreateDate - but I can't figure out how to solve it.

A: pandas is more than just a library to make some good formatting. This is also a wrapper for matplotlib. pandas is, in other words, a higher level of abstraction for matplotlib. Doing df.groupby("Store").plot(x="CreateDate", y="Orders_am") should be enough.
However, if you would have wanted to use plt.plot(), you could have done it like any other plot, and specify the Xs and Ys into the function, such as, for instance...
store = df.groupby("Store")
plt.plot(store['CreateDate'], store['Orders_am'])


text:
Q: How to make a Q-Q Plot with a Student-t distribution Working in Matlab...
I have a long vector of data vec that I want to make a Q-Q plot of against a Student-t distribution for various values of t. I know qqplot(vec) produces a plot against a normal distribution. I know from here that I can use other distributions by inserting them as a second parameter qqplot(vec,dis).
I can make other distributions with makedist (see mathworks.com/help/stats/makedist.html) but Student-t isn't an option there that I can see. There are the functions tpdf, tcdf etc. about Student-t (see http://www.mathworks.com/help/stats/students-t-distribution-1.html) but how do I use them to make a distribution item to use in the Q-Q plot? Or is there another technique to get the plot I want?

A: I haven't used Matlab in about a decade, so I can't give specific syntax.  That said, if vec has length n you should be able to create a vector of t-values corresponding to quantiles i / (n+1) for i=1,...,n using tinv.  Then do a qqplot of vec vs. the t-vector.


text:
Q: Diversificar as postagens no WordPress por categorias Estou usando este código para exibir as notícias na página inicial de um site, só que eu queria exibir:
4 noticias de Cat1 + 3 de Cat2 + 3 de Cat3

          <?php
          if (have_posts('order=DESC')) : while (have_posts('numberposts=10')) : the_post('category_name=cat1');
          ?>

                <?php the_post_thumbnail( ); ?>

<a title="<?php the_title(); ?>" href="<?php echo get_permalink(); ?>">
<?php title_limite(55); ?>

                <?php the_excerpt_max_charlength(180); ?>

               <a title="Ver o post completo de: <?php the_title(); ?>" href="<?php echo get_permalink(); ?>" class="plus-destaq"> +
              <?php the_time( get_option( 'date_format' ) ); ?>

          <?php endwhile; ?>
          <?php endif; ?>

Esse código só exibe a Cat1, eu tentei replicar o código mudando o the_post('category_name=cat1'); mas aí da um erro e exibe 10 posts 3 vezes da cat1. Como faço para escrever sem conflito? Dá para fazer dentro desse código mesmo?

A: Você pode fazer loops secundários usando WP_Query
<?php while ( have_posts() ) : the_post(); ?>
<?php /* LOOP PRIMARIO */ ?>
<?php endwhile; ?>

<?php
# Vide http://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters
$args_cat1 = array();
$cat_query = new WP_Query( $args_cat1 );
if ( $cat_query->have_posts() ) :
    while ( $cat_query->have_posts() ) : $cat_query->the_post();
        the_title();
        if ( has_post_thumbnail() ) {
        }
    endwhile;
endif;

A: Olha, não testei do seu jeito... mas consegui usando query_posts(''); e também <?php wp_reset_query(); ?>  ai ficou assim:

Federadas da AMB

             <?php
          query_posts('cat=10'); //AQUI EU DETERMINEI A CATEGORIA QUE VAI APARECER
          if (have_posts('order=DESC')) : while (have_posts('')) : the_post('');
          ?>

                <?php the_post_thumbnail( ); ?>

<a title="<?php the_title(); ?>" href="<?php echo get_permalink(); ?>">
<?php title_limite(55); ?>

                <?php the_excerpt_max_charlength(180); ?>

               <a title="Ver o post completo de: <?php the_title(); ?>" href="<?php echo get_permalink(); ?>" class="plus-destaq"> +
              <?php the_time( get_option( 'date_format' ) ); ?>

          <?php endwhile; ?>
          <?php endif; ?>
          <?php wp_reset_query(); //AQUI EU RESETO A QUERY QUE ESTAVA ARMAZENANDO A CATEGORIA ?>

Sociedades de Especialidade

             <?php
          query_posts('cat=9');//AQUI EU DETERMINO OUTRA CATEGORIA
          if (have_posts('order=DESC')) : while (have_posts('')) : the_post('');
          ?>

                <?php the_post_thumbnail( ); ?>

<a title="<?php the_title(); ?>" href="<?php echo get_permalink(); ?>">
<?php title_limite(55); ?>

                <?php the_excerpt_max_charlength(180); ?>

               <a title="Ver o post completo de: <?php the_title(); ?>" href="<?php echo get_permalink(); ?>" class="plus-destaq"> +
              <?php the_time( get_option( 'date_format' ) ); ?>

          <?php endwhile; ?>
          <?php endif; ?>
          <?php wp_reset_query(); //AQUI EU RESETO A QUERY QUE ESTAVA ARMAZENANDO A CATEGORIA ?>


text:
Q: How to add Crypto Certificate in IBM Datapower using API Call I want to add crypto certificate in IBM Datapower using API Call. How can I implement this Kindly help me. I already read all the documentation about REST Management Interface and XML Management Interface I did not found any good information.

A: You need to do this in two separate steps, upload the file/s and then create the IDCRED/CERT objects.
Using SOMA (XML Management) you'd use dp:set-file and with the REST management you'd need to base64 encode the file and use the endpoint /mgmt/filestore/{domain}/{directory}/{filename}.
After the file/s is/are uploaded you can go ahead and create the CERT object/s point to the files.
Have a look at the awesome Config-Manager which can help you with a number of tasks; https://github.com/ibm-datapower/datapower-configuration-manager


text:
Q: Pandas is sorting integer in a wierd way like string Even when a column in a pandas df is int.. It is being sorted like a string or in a weird way.
n_frames  video        img
-----------------------------
1         Videos482    1.jpg
10        Videos482    2g.jpg
11        Videos482    2d.jpg
2         Videos482    1q.jpg
1         Videos484    234.jpg
100       Videos484    34.jpg

What I want is: See the n_frames column.
n_frames  video        img
-----------------------------
1         Videos482    1.jpg
2         Videos482    1t.jpg
10        Videos482    2g.jpg
11        Videos482    1q.jpg
1         Videos484    234.jpg
100       Videos484    34.jpg

When I check df.dtypes I get:
n_frames   int32

My code:
print(df.dtypes)
df = df.groupby('video')
df.apply(lambda _df: _df.sort_values(by=['n_frames']))
df.apply(lambda _df: _df.to_csv("rubbish.csv", index=False ))

So basically. I want to groupby the video keeping the n_frames in increasing accending order.
Upper data is small form of original.
Original>
n_frames,trainTest,classes,vdo_noext,img
1,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 1.jpg
10,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 10.jpg
100,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 100.jpg
101,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 101.jpg
102,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 102.jpg
103,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 103.jpg
104,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 104.jpg
105,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 105.jpg
106,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 106.jpg
107,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 107.jpg
108,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 108.jpg
109,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 109.jpg
11,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 11.jpg
110,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 110.jpg
111,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 111.jpg
112,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 112.jpg
113,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 113.jpg
114,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 114.jpg
115,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 115.jpg
116,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 116.jpg
117,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 117.jpg
118,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 118.jpg
119,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 119.jpg
12,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 12.jpg
120,1,1,train/Normal/Normal_Videos482_x264,train/Normal/Normal_Videos482_x264@ 120.jpg

Update: n_frames column dtype was never a string and integer even before I converted into int..
Why is integer being sorted in that wierd way?

A: Difficult to say without the data to hand but I would switch the rows around like so:
df = df.groupby('video')
df['n_frames'] = df['n_frames'].astype(int)
df.apply(lambda _df: _df.sort_values(by=['n_frames']))
df.apply(lambda _df: _df.to_csv("rubbish.csv", index=False ))

In other words, change the data type after the groupby


text:
Q: How do I use a method of a class who's object I'm using in another class? Basically something like this
class Key:

    def __init__(self, pressed):
        '''(Key, bool) -> NoneType
        '''
        self._pressed = pressed

    def change_press_state(self):
        self._pressed = not self._pressed

class KeyBoard:

    def __init__(self, how_many):
        '''(KeyBoard, int) -> NoneType
        Makes a Keyboard of 'how_many' keys.
        '''

        self._keys = []
        for i in range (0, how_many):
            self._keys.append(KeyBoard(False))

    def switch_status_of_key(self, index_of_key):
        '''(KeyBoard) -> NoneType
        Presses key if isn't and stops pressing key if it is.
        '''

How would I call change_press_state on the specific key the user wants to switch in switch_status_of_key?
I was thinking something like
self._keys[key] = self._keys[key].flip()

But obviously not because I'm getting errors.

A: self._keys.append(KeyBoard(False))

should be:
  self._keys.append(Key(False))

and
def switch_status_of_key(self, index_of_key):
        '''(KeyBoard) -> NoneType
        Presses key if isn't and stops pressing key if it is.
        '''
        self._keys[index_of_key].change_press_state()


text:
Q: Creating SASS override for white labelled application I'm running a white label application where many brands are using a set of SASS variables. But over the time, it happens that additional variables needs to be added for a given breakpoint in order to allow more flexibility. Thus, in order to keep backward compatibility, I assign the current value to the newly created variable ($test--large). For the brand, to be able to customize style for large breakpoint.
The issue is that it doesn't work the way i'd expect it to work. If at brand level, I change $test, i'd like $test--large to also have the new value assignment.
Hope it makes sense, if not what would you suggest. Knowing that we have many brands and it would be painful to redefine all the new variables.
$test: blue !default;
$test--large: $test !default;  // new variable

$test: green; // Override from brand

.text {
  color: $test;

  // Newly added piece

  @include breakpoint(large) {
      color: $test--large; //result will be blue but i'd expect it to be green
  }

}

`

A: It looks like when you assign $test to $test--large, the variable is being passed by value, not reference. Hence when you reassign $test to green, you need to also reassign $test--large, e.g. like this:
$test--large: $test

or
$test--large: green

A: I wanted to avoid this solution because it will require me to change it in all my project.
The variables override need to happen before and not after the !default values
I'm still wondering if it isn't possible without interchanging the variable import order
$test: green; // Override from brand

$test: blue !default;
$test--large: $test !default;  // new variable

.text {
  color: $test;

  // Newly added piece

  @include breakpoint(large) {
      color: $test--large; //result will be green as expected
  }

}


text:
Q: If esp points to the top of the stack, where does ebp point to? I am having some trouble understanding how the esp and ebp registers are used.
Why do we do:
pushl %ebp
movl %esp, %ebp

at the start of every function? What is ebp holding when it is pushed for the first time?

A:
Why do we do:

This has historic reasons. In 16-bit code ...

*

*... the x86 CPUs did not allow all registers to be used for memory addressing.

*... addresses were relative to the "segments" (e.g. 16*ss or 16*ds).

Because sp could not be used to access memory directly (e.g. 10(%sp) - this is not possible in 16-bit code), you first had to copy sp to another register and then access the memory (e.g. copy sp to bp and then do 10(%bp)).
Of course it would also have been possible to use bx, si or di instead of bp.
However, the second problems are the segments: Using one of those registers would access the segment specified by the ds register. To access memory on the stack, we would have to do ss:10(%bx) instead of 10(%bx). Using bp implicitly accesses the segment that contains the stack (which is faster and the instruction is one byte shorter compared to explicitly specifying a segment).
In 32-bit (or 64-bit) code all this is not necessary any more. I just compiled a function with a modern C compiler. The result was:
movl    12(%esp), %eax
imull   8(%esp), %eax
addl    4(%esp), %eax
ret

As you can see, the ebp register is not used.
However, there are two reasons why ebp is still used in modern code:

*

*It's easier to create the function. You know that the first argument is always located at 8(%ebp) even if your function contains push and pop instructions. Using esp the location of the first argument changes with every push or pop operation.

*Use of the alloca function: This function will modify the esp register in a way that may even be unpredictable for the compiler! So you'll need a copy of the original esp register.

An example for the use of alloca:
push %ebp
mov %esp, %ebp
call GetMemorySize  # This will set %eax

# ---- Start of alloca() ----
# The alloca "function" will reserve N bytes on the
# stack while the value N is calculated during
# the run-time of the program (here: by the function
# GetMemorySize)
or $3, %al
inc %eax

# This has the same effect as multiple "push"
# instructions. However, we don't know how many
# "push" instructions!
sub %eax, %esp

mov %esp, %eax
# From this moment on, we would not be able to "restore"
# the original stack any more if we didn't have a copy
# of the stack pointer!
# ---- End of alloca() ----

push %eax
mov 8(%ebp), %eax
push %eax
call ProcessSomeData
mov %ebp, %esp
pop %ebp

# Of course we need to restore the original value
# of %esp before we can do a "ret".
ret

A: At the start of every function ebp is pointing wherever the calling function wanted it, it's not relevant to the current function until the code for the current function chooses to use it.  ebp is just a stack frame pointer in case you choose to have a stack frame.  The notion is that YOU CAN use ebp to have a non-moving reference to the stack for your function while you are free to continue to add or remove items on the stack using esp.  If you were to not use a stack pointer and were to continue to use esp as the reference to the stack then where a particular item on the stack is over the course of your function varies relative to esp.  If you set ebp before you start using the stack (other than to save ebp) then you have a fixed relative address to the parameters on the stack that your function cares about, like passed parameters, local variables, etc.
You are perfectly free to use eax or edx or any other register as a stack frame pointer within your function, ebp is there as a general purpose register for you to use for stack frames since x86 has historically had a stack dependency (return addresses, and old calling conventions were stack based).  Other instruction sets with more registers might simply choose a register for the compiler implementation as the function pointer/stack frame pointer. If you have the option and choose to use a stack frame.  It burns a register you could be using for other things, burns more code and execution time.  Like using other general purpose registers, ebp is non volatile per the calling conventions being used today, you need to preserve it and return it the way you found it.  So what it points to is specific to the function.  What it pointed to when your function was entered was specific to the calling function.
A particular compiler implementation may choose to have stack frames and may choose how it uses ebp.  And if it is always used the same way when enabled then with that toolchain you might have a debugger or other tool that can take advantage of that.  For example if the first thing in the function is to push ebp on the stack then the return address to the calling function within any function relative to ebp is fixed (well unless there was some tail optimization then maybe its the caller of the caller (of the caller (of the caller))).    You are burning a register and stack space and code space for this feature but, like compiling for debugging you can compile with a stack frame during development to use these features.
The reason why you start with a push is that is a good way to use the frame pointer and define a consistent location. Pushing it on the stack as the first thing you do 1) preserves ebp so you don't crash the calling function(s) 2) defines a consistent reference point addresses below ebp are the return address and calling parameters at a fixed offset for the duration of the function.  Local variables are at fixed addresses above ebp for a scheme like this.  Compilers, as well as humans, are more than capable of not needing to do this, my first parameter might be at esp-20 at one point in the code and I may then go push 8 bytes more on the stack now that same parameter is at esp-28, just code it as such.
But for debugging purposes debugging the code produced and at times for example finding the return address at a fixed offset. Burning another register, is IMO lazy but, can definitely help debug and increase the quality of the compiler output.  Find bugs in the output of the compiler faster, and help folks trying to read the code understand it faster with less effort.  With a stack frame pointer used properly all parameters and local variables are at a fixed offset to the stack frame pointer through the duration of the function between the points where the stack frame pointer is setup and cleaned up.  Push pointer to save it set frame pointer to stack pointer with or without an offset.  To the pop of the frame pointer before a return.

A: During execution of the function, various objects can be pushed onto the stack. The push decrements %esp (or %rsp if you are using 64-bit hardware) to point to the next available memory on the stack, while %ebp (or %rbp) maintains an unchanging pointer to the start of the function's stack frame so that, relative to %ebp, the function is able to find its various objects already stored on the stack.
Early, 8-bit CPUs like the old 6502 from the 1970s and 1980s had no %ebp. Lacking %epb, consider this C code:
int a = 10;
++a;
{
    int b = 20;
    --b;
    a += b;
}

The a is stored at the 0(%esp), except that, when b is pushed onto the stack, the a, which has not actually moved, is now at 4(%esp). Do you see the problem?
Using %ebp, the a is always at -4(%ebp) and the b when in scope is at -8(%ebp).

A: Ebp points to the old function's Ebp. Example: If you called some function from main function and then code execution will start execute this function that function's Ebp register will point to main's Ebp register


text:
Q: jQuery append content of multiple URLs in array with .get/ajax is it possible to append content of each URL in the array to given container from the list of URls with jQuery?
Like this:

Contact 1

Contact 2

Contact 3

Contact 4

I know how to get an array of URLs with jQuery:
$(document).ready(function() {
    var allLinks = $('li.contacts a').map(function(i,el) { return $(el).attr('href');     });
    console.log($(allLinks));
});

ok, I have an array of URLs in allLinks variable. I now want to append, say, content of #content element of each of this URLs with .get() function.
How to loop from 1st to the last one URL from array and append their content to my current page? It should basically end like this:

//#content of URL1
//#content of URL2
//#content of URL3
//#content of URL4

List of URLs is generated dynamically (this isn't problem).
I have tried this:
$(document).ready(function() {
    var allLinks = $('li.contacts a').map(function(i,el) { return $(el).attr('href'); });
    console.log($(allLinks));

  var curr  = 0;
        if (curr++ > allLinks.length) curr = 0;

        $.get(allLinks[curr],function(data){
        var myContent = $(data).find('#content').children();
            jQuery('#wrapper').append(myContent);
   });
});

But without success. Any clue?

A: Updated answer: (Load clicked href into div)
$('.contacts a').click(function() {
  var url= $(this).attr('href');
  $('#currentpage').html('loading...');
  $.ajax({
     url: url
  }).success(function(data) {
     $('#currentpage').html(data);
  });
  return false;
});
//JSBin http://jsbin.com/ucobuv/3/edit
//No need for the allLinks variable here

old answer: (load all links)
(function getContent(i) {
    $.ajax({
        url: allLinks[i++]
    }).success(function(data) {
        $('#currentpage').append(data);
        if(allLinks[i]) getContent(i);
    });
})(0);
//JSBin http://jsbin.com/ucobuv/1/edit


text:
Q: Angular template within template Lets see if I can describe my setup here...
I'm designing an angular app, as of now everything is all one page. Basically, when the user clicks a button, the controller sets which
"<ng-include>"

tag is visible. So my html looks something like this.

            <ng-include= "home.html">

            <ng-include= "profile.html">

And then in my controller, I'm just setting the proper "showHome", "showProfile", etc... as appropriate. My question is, this seems like a terrible way to scale, and this is my first attempt at an app like this.
So to reiterate. I want to give the user the appearance of a single page app, while swapping in html templates. Any ideas? Multiple pages would be ok, but I want to keep the same navbar at the top of every page.

A: I'd use ui-router instead.
It is a popular alternative for ngRoute and supports nested templates really well.


text:
Q: Express error: write after end I'm having issues with this code I'm trying to write. For some reason I get the error listed in the title. I'm pretty sure this is an issue with the async concept. How can I fix this?
pokeRouter.get('/sightings/:value([a-z]+)', function (req, res) {
var test = {};
pokemon.find().each(function(err, item) {
    if (item == null) {
        res.end();
    } else if ((req.params.value == item.type1) || (req.params.value == item.type2)) {
        sightings.find({pokedex_id: item._id}).toArray(function(err, docs) {
            if (docs == null) {
                return null;
            }
            res.write(JSON.stringify(docs));
        });
    }
});
});

A: Most likely you have an item in your find() list (not at the end) that is null. At that point you end the response (res.end()). However there are one or more items after that null item which are not null, causing a res.write(). This is what is causing your 'write after end' error. Make sure you only call res.end() after you have finished writing your entire response.


text:
Q: Plotting on a geographical map the provenience of our patients I am trying to put on a Italian geographical map a dot reporting the provenience ('provincia') of our patients. Ideally, the dot size should be proportional to the number of patients coming from that 'provincia'. An example of the list I would like to plot is the following.
MI  8319
CO  537
MB  436
VA  338
BG  310
PV  254
CR  244
NO  210
RM  189
CS  179

In the first column there is the 'provincia' code: MI (Milano), CO (Como), MB (Monza-Brianza), etc. In the second column there is the number of patients from that 'provincia'. So the output should be an Italian political map where the biggest dot is around the city of Milano (MI), the second biggest dot is near the city of Como (CO), the third one is around the city of Monza-Brianza (MB),etc.
 Is there any package that could do the plot I am looking for? I found a tool that could do the job here, but apparently they expect that I load the geographical coordinates in order to do the plot.
https://www.littlemissdata.com/blog/maps
Thanks in advance.

A: Here is one way to handle your task. You have the abbreviations for Italian province. You want to use them to merge your data with polygon data. If you download Italy's polygons from GADM, you can obtain data that contain the abbreviations. Specifically, the column, HASC_2 is the one. You need to merge your data with the polygon data. Then, you want to create another data set which contains centroid. You can draw a map with the two data sets.
library(tidyverse)
library(sf)
library(ggthemes)

# Get the sf file from https://gadm.org/download_country_v3.html
# and import it in R.

mysf <- readRDS("gadm36_ITA_2_sf.rds")

# This is your data, which is called mydata.
mydata <- structure(list(abbs = c("MI", "CO", "MB", "VA", "BG", "PV", "CR",
"NO", "RM", "CS"), value = c(8319L, 537L, 436L, 338L, 310L, 254L,
244L, 210L, 189L, 179L)), class = "data.frame", row.names = c(NA,
-10L))

   abbs value
1    MI  8319
2    CO   537
3    MB   436
4    VA   338
5    BG   310
6    PV   254
7    CR   244
8    NO   210
9    RM   189
10   CS   179

# Abbreviations are in HASC_2 in mysf. Manipulate strings so that
# I can join mydata with mysf with the abbreviations. I also get
# longitude and latitude with st_centroid(). This data set is for
# geom_point().

mysf2 <- mutate(mysf, HASC_2 = sub(x = HASC_2, pattern = "^IT.", replacement = "")) %>%
         left_join(mydata, by = c("HASC_2" = "abbs")) %>%
         mutate(lon = map_dbl(geometry, ~st_centroid(.x)[[1]]),
                lat = map_dbl(geometry, ~st_centroid(.x)[[2]]))

# Draw a map

ggplot() +
geom_sf(data = mysf) +
geom_point(data = mysf2, aes(x = lon, y = lat, size = value)) +
theme_map()

A: UPDATE ON INSET MAP
This is an update following different suggestion on using inset maps, which I think it would be the best solution for yout question and comments:
library(sf)
library(cartography)

EU = st_read("~/R/mapslib/EUROSTAT/NUTS_RG_03M_2016_3035_LEVL_3.geojson")
IT = subset(EU, CNTR_CODE == "IT")
mydata <-
  structure(list(
    abbs = c("MI", "CO", "MB", "VA", "BG", "PV", "CR",
             "NO", "RM", "CS"),
    value = c(8319L, 537L, 436L, 338L, 310L, 254L,
              244L, 210L, 189L, 179L),
    nuts = c("ITC4C","ITC42","ITC4D","ITC41",
             "ITC46", "ITC48","ITC4A","ITC15",
             "ITI43","ITF61")
  ),
  class = "data.frame",
  row.names = c(NA, -10L))

patients = merge(IT, mydata, by.x = "id", by.y = "nuts")

#Get breaks for map
br=getBreaks(patients$value)
#Delimit zone
#Based on NUTS1, Nortwest Italy
par(mar=c(0,0,0,0))
ghostLayer(IT[grep("ITC",IT$NUTS_ID),], bg="lightblue")
plot(st_geometry(EU), col="grey90", add=TRUE)
plot(st_geometry(IT), col = "#FEFEE9", border = "#646464", add=TRUE)
choroLayer(
  patients,
  var = "value",
  breaks = br,
  col = carto.pal(pal1 = "red.pal", n1 = length(br)-1),
  legend.pos = "topleft",
  legend.title.txt = "Total patients",
  add = TRUE,
  legend.frame = TRUE
)
labelLayer(patients,txt="abbs", halo=TRUE, overlap = FALSE)

#Inset
par(
  fig = c(0, 0.4, 0.01, 0.4),
  new = TRUE
)
inset=patients[patients$abbs %in% c("RM","CS"),]
ghostLayer(inset, bg="lightblue")
plot(st_geometry(EU), col="grey90", add=TRUE)
plot(st_geometry(IT), col = "#FEFEE9", border = "#646464", add=TRUE)
choroLayer(
  patients,
  var = "value",
  breaks = br,
  col = carto.pal(pal1 = "red.pal", n1 = length(br)-1),
  legend.pos = "n",
  add = TRUE
)
labelLayer(patients,txt="abbs", halo=TRUE, overlap = FALSE)
box(which = "figure", lwd = 1)

#RESTORE PLOT

par(fig=c(0,1,0,1))

OLD ANSWER
Following my comment on plotting labels, maybe with circles is not the best option for your map, given the concentration. I suggest you to use another kind of map for that, as chorolayer, I leveraged on https://stackoverflow.com/users/3304471/jazzurro for the dataframe.
    library(sf)
    library(cartography)

    EU = st_read("~/R/mapslib/EUROSTAT/NUTS_RG_03M_2016_3035_LEVL_3.geojson")
    IT = subset(EU, CNTR_CODE == "IT")
    mydata <-
      structure(list(
        abbs = c("MI", "CO", "MB", "VA", "BG", "PV", "CR",
                 "NO", "RM", "CS"),
        value = c(8319L, 537L, 436L, 338L, 310L, 254L,
                  244L, 210L, 189L, 179L),
        nuts = c("ITC4C","ITC42","ITC4D","ITC41",
                 "ITC46", "ITC48","ITC4A","ITC15",
                 "ITI43","ITF61")
      ),
      class = "data.frame",
      row.names = c(NA, -10L))

    patients = merge(IT, mydata, by.x = "id", by.y = "nuts")

    #Options1 - With circles
    par(mar = c(0, 0, 0, 0))
    plot(st_geometry(IT), col = "#FEFEE9", border = "#646464")
    propSymbolsLayer(
      x = patients,
      var = "value",
      col = carto.pal(pal1 = "red.pal", n1 = 6),
      legend.title.txt = "Total patients",
      add = TRUE
    )

    #Option 2 - Chorolayer with labels
    par(mar = c(0, 0, 0, 0))
    plot(st_geometry(IT), col = "#FEFEE9", border = "#646464")
    choroLayer(
      patients,
      var = "value",
      col = carto.pal(pal1 = "red.pal", n1 = 6),
      legend.title.txt = "Total patients",
      add = TRUE
    )
    #Create labels
    patients$label = paste(patients$abbs, patients$value, sep = " - ")
    labelLayer(
      patients,
      txt = "label",
      overlap = FALSE,
      halo = TRUE,
      show.lines = TRUE,
      )

Data from
https://ec.europa.eu/eurostat/cache/GISCO/distribution/v2/nuts/nuts-2016-files.html


text:
Q: Can't select DataRow from DataTable I'm trying to prevent inserting duplicated data into MS Access table like below,
MS Access table(Record) with Columns: Situation, Check_Item, and starts with no data in the table.
DataTable from DataSet is filled with the query "SELECT * FROM Record WHERE Situation = 'A'".
Then I try to do this process,
DataRow = DataTable.Select("Check_Item = '"+InputTextBox.Text"'");
If (DataRow.Length == 0)
{
  Use OleDbCommand to insert InputTextBox.Text string to Check_Item of Record table.
}

Result:
First time key in(e.g. 123456), because there is no data in the table, so 123456 is inserted into Record table.
But at the second time key in 123456, then it still be inserted into Record table.
What happened in this process??

A: Assuming your DataTable variable has name table, and that you created it and linked it correctly to your MS Access database then:
DataRow[] rows = table.Select("Check_Item = '"+InputTextBox.Text"'"); //Selects all rows where the condition is met.
If (rows.Length == 0)
{
   //No row met the condition so create a new one and add it to the table.
   DataRow newRow = table.NewRow(); //Creates a new row with the same schema (columns) as the table.
   newRow["Check_Item"] = InputTextBox.Text; //Assigns the value.
   table.Rows.Add(newRow); //Adds the new row to the row collection of the table.
   table.AcceptChanges(); //Commits and persist the changes done to the table.
}

Be sure to check this and also the official docs for DataTable.


text:
Q: DP algorithm for covering the distance between two points with a set of intervals Question:
Given $n$ points on the $x$-axis, We are asked to provide a dynamic programming algorithm to cover the distance between the first and the last point with $k$ closed intervals such that the conditions written below hold:

(i) The endpoints of these $k$ intervals are chosen from the given $n$ points.  (For example, If $2,3,4,5$ are given, We should provide a way to cover the interval $[2,5]$. But we cannot choose the interval $[2,2.5]$ because $2.5$ is not in the given set.)
(ii) Our algorithm should guarantee that the length of the biggest interval is the minimum possible value.
(iii) The time complexity of our algorithm should be of $O(nk)$.

Note:  It is valid to use intervals with length $0$.
My try:
Obviously, The first point between the given $n$ points should be one of the endpoints of one of my covering intervals. So, I should decide for the other endpoint of this interval. What I mean is I have to choose one of the remaining $n-1$ points to be the other endpoint. So, It seems like each time that I'm picking an interval, I should decide for only one of its endpoints.
But, The problem is that this method results in an algorithm of $O(n^2\times k)$ which is not enough because the question asks for $O(nk)$.
Any idea?
Thanks in advance


text:
Q: Are there alternatives to the Microsoft Visual Basic Power Packs? For the last several years, I used the Microsoft Visual Basic Power Packs 3.0 to draw basic shapes onto my WinForms.
However, today when I had to set up my new PC for development, I cannot visit the Microsoft site for the download and it seems that all links that would previously point to the file for download has been removed. While I know Visual Basic is being "phased out" or ignored by Microsoft for future development, is there a way I can reinstate this functionality or find a different power pack that will do the same? I'd rather not redo the program I've been working on for years by hand into C#.)

A: You can use GDI+ to draw shapes. Here are various draw methods under the Graphics class:

*

*https://learn.microsoft.com/en-us/dotnet/api/system.drawing.graphics.drawellipse

*https://learn.microsoft.com/en-us/dotnet/api/system.drawing.graphics.drawrectangle

*https://learn.microsoft.com/en-us/dotnet/api/system.drawing.graphics.drawline
This is certainly isn't all inclusive, I left many of them out. You will need to determine which method you'll need to use from this list: https://learn.microsoft.com/en-us/dotnet/api/system.drawing.graphics#methods
Generally what you would do is handle the Paint event of the control you wish to draw on and then leverage the PaintEventArgs argument. Here is an example of drawing a simple rectangle on a form:
' vb.net
Private Sub Form1_Paint(sender As Object, e As PaintEventArgs) Handles MyBase.Paint
    Dim r = New Rectangle(5, 5, 100, 100)
    Using rectangleBorder = New Pen(Color.Black, 1)
        e.Graphics.DrawRectangle(rectangleBorder, r)
    End Using
End Sub

// c#
private void Form1_Paint(object sender, PaintEventArgs e)
{
    var r = new Rectangle(5, 5, 100, 100);
    using (var rectangleBorder = new Pen(Color.Black, 1))
    {
        e.Graphics.DrawRectangle(rectangleBorder, r);
    }
}


text:
Q: Java string to json object I'm trying to use Json with android
I have a link that returns a Json string
InputStream is = new URL(url).openStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);

but, on making a new JSONObject(jsonText); it crushes.
Here is my URL : http://igorsdomain.byethost3.com/getUser.php?username=SailorBoogy&password=qwerty&event=2222
This is the object returned : {"ID":"23","Username":"SailorBoogy","Password":"qwerty","eventID":"6"}
I tried also to JSONObject(jsonText.replaceAll("\"" , "\\\\\""));
but it didn't work.
What's the problem ? am I using it wrong ?
Json Libraries :

org.json.JSONException;
  org.json.JSONObject;
  org.json.JSONStringer;

A: I strongly recommend you to use networking libraries such as Volley,Loopj,Okhttp for network operations.
Here is code for your problem.
class LongOpreation extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {

        String str = "";

        try {
            str = sendGetRequest();

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return str;
    }

    public String sendGetRequest() throws MalformedURLException {
        StringBuilder response = new StringBuilder();
        String requrl = "";
        requrl = "http://igorsdomain.byethost3.com/getUser.php?username=SailorBoogy&password=qwerty&event=2222";
        response = requestExecuter(requrl);

        return response.toString();

    }

    @Override
    protected void onPostExecute(String result) {
        try {
            JSONObject jsonObject = new JSONObject(result);
            System.out.println("json-----------------------"+jsonObject);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    @Override
    protected void onPreExecute() {

    }
    public StringBuilder requestExecuter(String str) {
        StringBuilder response = new StringBuilder();
        try {
            URL url = new URL(str);

            HttpURLConnection httpconn = (HttpURLConnection) url
                    .openConnection();
            httpconn.setConnectTimeout(5000);
            httpconn.setReadTimeout(10000);

            if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                BufferedReader input = new BufferedReader(
                        new InputStreamReader(httpconn.getInputStream()));
                String strLine = null;
                while ((strLine = input.readLine()) != null) {
                    response.append(strLine);

                }
                input.close();
            }
            } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return response;
    }
}

Simpley callnew LongOperation().execute(""); and you are done

A: First OF all Get your json in network thread like asynchronousTask.
 DefaultHttpClient   httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost(http://someJSONUrl/jsonWebService);
// Depends on your web service
httppost.setHeader("Content-type", "application/json");

InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();

inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();

String line = null;
while ((line = reader.readLine()) != null)
{
    sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}

And than parse it like this
try {
        JSONObject jObject = new JSONObject(result);
        Log.d("username", jObject.getString("Username"));
        Toast.makeText(getApplicationContext(), jObject.getString("Username"), Toast.LENGTH_LONG).show();
        Log.d("Password", jObject.getString("Password"));
        Log.d("eventID", jObject.getString("eventID"));
    } catch (JSONException e) {
        e.printStackTrace();
    }

For more info checkthis

A: Without the LogCat it's hard to say, but probably you are doing network operations on MainThread, and Android is complaining with that (because it's a blocking operation, so the UI will freeze) by throwing a android.os.NetworkOnMainThreadException. If this is the case you can solve by doing this operation in another thread (e.g. by using an AsyncTask, or an external library, such as AndroidAsyncHttp)


text:
Q: Block "Confirm Form Resubmission" I have a form in my webpage, if one of the fields is filled and the page reloads then appears
"Confirm Form Resubmission".

I think that it looks ugly, I dont wanna this call in my webpage.

So my question is:
• What i have to do to avoid or block that call.

• Which language i have to use.

Sorry for my english.

A: When someone submits a form, save $_POST in a $_SESSION variable, then redirect the user to the same page. When you actually process the form itself, then you can delete the $_SESSION variable.

A: You can either force reload the page in PHP like this
echo '<meta http-equiv="refresh" content="0">'

Alternatively, you can send it to another page in PHP, like this
header( 'Location: path/to/file.php' );


text:
Q: I'm not able to install gatsby-plugin-transition-link with npm
I am currently trying to install gatsby-plugin-transition-link with npm. But it keeps throwing these error's. I have tried to research and fix the problem. But nothing I have tried has worked at all. Does anyone know what the problem could be? Thank you in advance.

A: This looks like a dependency issue with React 17 or v3 of gatsby, there are a few issues like this one in the gatsby-plugin-transition-link repository. Some gatsby plugins may require some fine tuning when making this jump to React 17 or v3, the documentation can be found here.


text:
Q: Insert guest Edition qemu/kvm | linux host, windows guest It always takes me a lot of time to find the qemu guest edition for windows.
Simmilar as in virtual box, where it is called "insert Guest edition" there is a feature for qemu windows hosts. You just need to get the signed iso.
I'm going to collect here ways in how to retrieve that.

A: Most promising page is that one:
https://github.com/virtio-win/virtio-win-pkg-scripts/blob/master/README.md
You'll find the tutorial here:
https://linuxhint.com/install_virtio_drivers_kvm_qemu_windows_vm/
It refers to a outdated Fedorra page, where Fedorra tells you, that they have issues with signing the drivers for windows.
You can find the link to the masterpage regarding kvm/qemu here:
https://www.linux-kvm.org/page/WindowsGuestDrivers/Download_Drivers


text:
Q: how to allow f() to take decimal values Firstly, I need to sum the student mark before converting it to a percentage. So Ive managed to sum up their mark and somehow managed to convert it to percentage thru this method.
students = MarkAtt.objects.values('studName__VMSAcc').annotate(mark=Sum('attendance'), percentage=(F('mark')/1100) * 100)

However, I realised that the F() does not take decimal value. It only takes the integer value. This would cause an error to my percentage calculation if the value 'mark' is less than 100.
For example: 600/1100 = 0.54545 then it will only take 0 to multiple with 100. And output '0' instead of 54%.
How do I allow the function take decimal value?
EDITED:
def file_load_view(request):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="studFinal-attendance.csv"'
    writer = csv.writer(response)
    writer.writerow(['Student Name', 'Attendance'])

    students = MarkAtt.objects.values('studName__VMSAcc').annotate(mark=Sum('attendance'),
    percentage=(Cast('mark', FloatField())/1100) * 100)

    #convert the students query set to a values list as the writerow expects a list/tuple
    students = students.values_list('studName__VMSAcc','percentage')

    for student in students:
        writer.writerow(student)
    return response

A: You can use Cast [Django-doc] to to specify to what type it should be converted, and thus let Django do the inference:
from django.db.models import FloatField
from django.db.models.functions import Cast

students = MarkAtt.objects.values('studName__VMSAcc').annotate(
    mark=Sum('attendance'),
    percentage=(Cast('mark', FloatField())/1100) * 100
)
and you can convert it to a decimal field at the end to use a specific number of digits:
from django.db.models import DecimalField, FloatField
from django.db.models.functions import Cast

students = MarkAtt.objects.values('studName__VMSAcc').annotate(
    mark=Sum('attendance'),
    percentage=Cast(
        (Cast('mark', FloatField())/1100) * 100,
        output_field=DecimalField(max_digits=20, decimal_places=2)
    )
)


text:
Q: pd.cut binning not working properly for partial numerical integration There is a similar question on Stack, but it was never answered: When using cut in a pandas dataframe to bin it, why is the binning not properly done?
I am have a dataset that I need to integrate the area under a curve, but rather than integrating the entire area under the curve at once, I am integrating partial areas at a specified interval of 5m. I.e, the area under the curve from 0-5m, 5 - 10m, 10 - 15m, etc.
However, it seems that my code is skipping the area between the last point of an interval and the first point of the next interval.
Here is a subset of my dataframe:

SITE    XSNO   XDIST   VERT SUB    YEAR      X     Z SOURCE     EW  \
6749  LOL  LOL006    30.0 -159.0  LI  1978.0   0.30  0.00     JF  False
6750  LOL  LOL006    98.0 -155.0  LI  1978.0   0.98  0.04     JF  False
6751  LOL  LOL006   148.0 -155.0  OD  1978.0   1.48  0.04     JF  False
6752  LOL  LOL006   196.0 -133.0  OD  1978.0   1.96  0.26     JF  False
6753  LOL  LOL006   222.0  -92.0  OD  1978.0   2.22  0.67     JF  False
6754  LOL  LOL006   242.0 -191.0  OD  1978.0   2.42 -0.32     JF  False
6755  LOL  LOL006   320.0 -246.0  LI  1978.0   3.20 -0.87     JF  False
6756  LOL  LOL006   383.0 -256.0  LI  1978.0   3.83 -0.97     JF  False
6757  LOL  LOL006   478.0 -262.0  LI  1978.0   4.78 -1.03     JF  False
6758  LOL  LOL006   558.0 -269.0  LI  1978.0   5.58 -1.10     JF  False
6759  LOL  LOL006   610.0 -271.0  LI  1978.0   6.10 -1.12     JF  False
6760  LOL  LOL006   670.0 -264.0  LI  1978.0   6.70 -1.05     JF  False
6761  LOL  LOL006   698.0 -308.0  BR  1978.0   6.98 -1.49     JF  False

max_x = max (df.X)
interval_range = pd.interval_range(start = 0, end = max_x + 5, freq=5, closed = 'left')
df['bins'] = pd.cut(df.X, bins = interval_range)

area = df.groupby(['bins', 'YEAR']).apply(lambda i: integrate.simps(i.Y, x = i.X))

For this subset of the data frame, my code is skipping the area between X = 4.78 and X = 5.58. I need to find a way to incorporate this into my results, I'm having trouble conceptualizing this.


text:
Q: How can I change a TextEditor's size and maintain the ability that it can autoresize when user zoom app window? guys.I'm a new developer of MacOS with SwiftUI.
I need to change the default size of TextEditor, and frame(width:height:)modifier will make the view fixed. frame(minWidth:idealWidth:minHeight:idealHeight:maxWidth:maxHeight) modifier seems not working.
Here's my sample code:
struct ContentView: View {
@State var input: String = ""
var body: some View {
    TextEditor(text: $input)
}

}
Which will generate a 600 * 400 TextEditor View.
enter image description here
All I want is the TextEditor has a initial 500 * 600 frame and it will change size when user zoom the app window.
Thank you.

A: try something like this:
struct ContentView: View {
    @State var input: String = ""
    var body: some View {
        TextEditor(text: $input)
            .frame(minWidth: 100, idealWidth: 500, maxWidth: .infinity, minHeight: 100, idealHeight: 600, maxHeight: .infinity)
            .scaledToFit()
            .border(.red)
    }
}


text:
Q: Image is not uploaded to defined folder in node.js I have a small HTML template and what I want is to upload image from one location to another. After selecting and clicking on the upload button, response gives me "Uploaded successfully" But the image is not in the destination folder. Please look into the below code.
HTML
<form id="frmUploader" enctype="multipart/form-data" action="book/api/Upload/" method="post">
    <input type="file" name="imgUploader" multiple />
    <input type="button" name="submit" id="btnSubmit" value="Upload" onclick="upload()"/>
</form>

index.js
function upload() {
    axios.post(baseUrlLocal+'/book/api/Upload', {headers: headers})
    .then(response => {
        console.log(response.data.success)
        if (response.data.success) {
            console.log("hi: "+response)
        // $.notify("New Book is Added to your Library", "success");

    }
        })
        .catch(function (error) {
            console.log(error)
            // $.notify("Please check all the details","warn");
        });
}`

book.js
var Storage = multer.diskStorage({
destination: function(req, file, callback) {
    callback(null, "../public/images/");
},
filename: function(req, file, callback) {
    callback(null, file.fieldname + "_" + Date.now() + "_" +
file.originalname);
}
 });

var upload = multer({
storage: Storage
 }).array("imgUploader", 3);

router.get("/image", function(req, res) {
res.sendFile(__dirname + "/index.html");
});
`router.post("/api/Upload", function(req, res) {
upload(req, res, function(err) {
    if (err) {
        return res.end("Something went wrong!");
    }
    return res.end("File uploaded sucessfully!.");
});
 });`


text:
Q: How to get the lowest price of products? Table structure

The above Table have 10 products with various price from 3 suppliers. I need to pick the supplier who can give the lowest price.
Just i tried with MS Access 2013. I unable to get the lowest price. Your valuable guidance is much appreciate one.
SID = Supplier ID
PCODE = Product Code

Thank you very much for your time

A: I assume cheapest means lowest per-ml price per item
So do the following:

*

*create a query#1 that includes the product, supplier, whatever other
fields you want in the final answer, and a calculated field of the
per-ml price.

*create an aggregate query #2 on query#1, which groups by product and gives the min per_ml_price. Now you have a "table" with the cheapest price for each product.

*Lastly, you want to find the data that matches the lowest price. (Inner-)Join query#2 and query#1, and output the fields you want (product, supplier, etc.)


text:
Q: Why were Anakin and Obi-Wan the only ones to wear excessive armor? In the canon animated series Star Wars: The Clone Wars, Obi-Wan and Anakin wear a great amount of armor. However, the rest of the Jedi seem to only wear armor on their arms, or even not at all. Why is this?

A: I remember reading/seeing something at some point that alluded to the fact that Obi-Wan wore armor that was similar to the clones because it gave him a more relatable demeanor to the clone troops he was commanding. That he did so because he saw the troopers as more than just "clones" but as individuals (i.e. Rex, Fives, Echo, so on..)

A: From what I know, Anakin and Obi-wan were war heroes. They were kind of poster boys. So the armor was to make them seem heroic I guess. I can't cite anything but I know I remember reading about their war hero status.

A: They weren't the only ones to wear armor and they mainly did it to show that they actually cared for there clone troopers unlike those like Pong krell who greatly mistreated their clones


text:
Q: How to solve "npm ERR! code ELIFECYCLE" in react? When i try to run npm start in my react app i got this ERROR :
$ npm start

> trends@0.1.0 start C:\Users\Administrateur.TEST\Desktop\reactProjects\trends
> react-scripts start

'react-scripts' n'est pas reconnu en tant que commande interne
ou externe, un programme exécutable ou un fichier de commandes.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! trends@0.1.0 start: `react-scripts start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the trends@0.1.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Administrateur.TEST\AppData\Roaming\npm-cache\_logs\2020-07-20T07_09_04_578Z-debug.log

I tried other solutions, like using clean cache, deleting node_modules & run npm install again, but still got the same ERROE

A: I suggest doing these three steps:

*

*npm install -g npm@latest to update npm because it is sometimes buggy.

*remove node_modules folder in your project.

*npm install to re-install the project dependencies.

A: I fix the problem by adding C:\Windows\System32\ in PATH SYSTEM VARIABLES


text:
Q: R - LMERConvenienceFunctions I am trying to do a lmer model with drop1, in each step with lowest AIC, and remodelling.
I learned that LMERConvenienceFunction package can do it. But I am having difficulties with commanding the bfFixefLMER_F.fnc
How should I command it?
model:
b <- lmer(metric1~a+b+c+d+e+f+g+h+i+j+k+l+(1|X) + (1|Y), data = dataset)

drop1 (b, test="Chisq")


text:
Q: How to make new pages without repeating everything? (PHP,CSS,HTML) I'm a newbie to "coding", so excuse me if my title describes this situation totally wrong or I just say stupid things.  I've read a few similar questions but I still don't get it!
My question: How do I create new pages, without having to repeat every standard sidebar 'widget', the header, menu, footer etcetera? For example, I want to create an 'About' page, but how do I even start?! I only want to change the content in the middle of the page (that is where the text is supposed to be).
The folders/files in my public_html folder are:

*

*_javascript (contains test, src & lib)

*_images (contains all the images obviously)

*_css (contains index.html file and global.css file)

*index.php (HTML)

*bg.php (you can just exclude this from the list, it's for creating auto-repeating bg)

Maybe it's like creating a new .php file so I can link /about.php in the menu -- but then I need to put every header & footer stuff back in there again, or maybe what I'm saying is totally wrong... It may be simple or very hard; please help me out.

A: You can use php for that with very small changes in your pages.

*

*Change extension of your pages from .html to .php

*Create a file header.php and paste all the header elements there.

*do the same thing for sidebar and footer and name them as sidebar.php and footer.php or whatever you want.

Now create your pages like this:
index.php
<?php
     include(header.php);
     include(sidebar.php);
?>

Your contents here

<?php
     include(footer.php);
?>

By using this ,You need not to write the code for header and all stuff again and again on every page. You can use the same technique for css and js as well.

A: Create header and footer separate  as pages. Then include it in other pages. This saves time and minimizes duplication.
You can do the same for repeating stylesheets and javascripts too. Thus you only need to edit the middle section of pages.

A: As JimL said, the most easy way to do this, is to exclude everything from the main php file, that you may need more than once. This has two main advantages:
- It makes the project easier to maintain
- The files that get used multiple times have to be loaded by the browser just once
From your project structure I conclude, that you know how to exclude JS and css so for php/html it goes like this:

*

*Put just the snippet you want to use several times into its own file (eg about.php)

*Use the snippet whenever you want with: <?php include "about.php" ?>

*Be happy about less work in the future!


text:
Q: Find specific property with reflection by examining its generic type Let's say I have The class
public partial class MyEntities: DbContext
{
     public DbSet<Customer> Customers {get;set;}
     public DbSet<CustomerInfo> CustomerInfos {get;set;}
     public DbSet<Order> Orders {get;set;}
     // etc
}

How can I find the property that has the generic type Customer?
In other words I am looking to create the method:
 public PropertyInfo GetProperty<T>(){
     var allProperties = TypeOf(MyEntities).GetProperties();
     // implementation
 }

If I call the method as GetProperty<Customer>() then I will like to get the first property. If I call the method as GetProperty<Order>() then I will like to get the last property. How can I examine the <Type> with reflection?

A: Use Type.IsGenericType and Type.GetGenericArguments():
public PropertyInfo GetProperty<T>(){
    var allProperties = TypeOf(MyEntities).GetProperties();
    return allProperties.FirstOrDefault(prop => prop.PropertyType.IsGenericType
        && prop.PropertyType.GenericTypeArguments.FirstOrDefault() == typeof(T));
}


text:
Q: full bins with limited capacity after throwing balls Expected  number of full  bins after throwing balls uniformly randomly to bins that have limited capacity
Let us have $N$ bins with the same limited capacity ($N_{max}=C$), in the sense that if a ball is threw into a bin that already has $C$ balls in it, the ball is discarded.
After throwing (uniform random allocation) $L$ balls, what is the expected number of bins that are full?
considerations:

*

*since uniform random allocations, after $L$ launches of balls we should have an uniform distribution of $L/N$ balls in each bin

*if $L<C$, no bin can be full (few balls to have the chance to have one bin full), so the expected number of "full" bins should be 0.

*if $L \in [C,C\cdot N ) $ it should be expected to have  $\dfrac{L}{C}$ full bins, and $N-L/C$ bins remain free to host a new ball.

*if $L>=C\cdot N$ no bin can be filled any more,all the bins reached their capacity. Any attempts of a new launch of a ball is rejected.

This is an idea, is there an analytical closed form way to express that?

A: This answer assumes the model you have described, where balls always choose their target uniformly (and independently of each other) among all bins, even if some are full.
Let $B_i$ denote the number of balls thrown at the $i$th bin after $L$ balls have been thrown.  Since each ball has a $\frac{1}{N}$ chance of being thrown at the $i$th bin, $B_i \sim \textrm{Bin}\left(L, \frac{1}{N} \right)$ is binomially distributed.
The $i$th bin is full if $B_i \ge C$.  Using the probability mass function of the binomial distribution, the probability of this happening is $\sum_{n = C}^L \binom{L}{n} \frac{1}{N^n} \left(1 - \frac{1}{N} \right)^{L - n}$.
By linearity of expectation, the expected number of full bins is the sum of the probabilities that each bin is full.  The bins have the same distribution, and so the expected number of full bins after $L$ balls have been thrown is
$$ N \sum_{n = C}^L \binom{L}{n} \frac{1}{N^n} \left(1 - \frac{1}{N} \right)^{L - n}. $$
Note that this will converge to $N$ as $L \rightarrow \infty$, but will never be equal to $N$, since, as mentioned in the comments, you might get so unlucky as to have all the balls thrown at the same bin.

A: I don't think the third bullet is right, either. If L=C, I would certainly not expect a bin to be full, since the only way that happens is if all L=C balls go into one bin.
Based on the problem description, it seems that the appropriate sample space $S$ is the set of ways to distribute L indistinguishable balls into N distinguishable boxes, independent of the fullness constraint, since any box being full does not prevent attempts to add more balls.
In this sample space, let $A_i$ denote the set of trials with $i \in {1..N}$ such that bin $i$ is full. This occurs whenever bin $i$ has at least C balls, which can happen in $\displaystyle{{L-C+N-1}\choose{N-1}}$ ways.
Now, $A_i$ may contain trials where boxes other than box $i$ are full, so to calculate probabilities we would need to use inclusion/exclusion. But since we only need the expected number of full boxes, I think we can calculate this as $$\frac{1}{|S|}\sum_{i=1}^N |A_i|$$
Every trial with more than one full box gets counted once for each full box, which is exactly the multiple counting needed for the value of the random variable in the expectation calculation. Noting that $|S|=\displaystyle{{L+N-1}\choose{N-1}}$, we get the expectation $$\frac{N\times L!\times(L-C+N-1)!}{(L-C)!\times(L+N-1)!}$$
Note: I'm traveling, without references, but believe this is correct.


text:
Q: Chrome issue with 301 redirect and SSL I am currently experiencing an issue that only occurs in Chrome. If I use https://example.com it won't load in chrome and it will complain with the following message:

This site can't be reached
The webpage at https://example.com/ might be temporarily down or it may
  have moved permanently to a new web address.
  ERR_RESPONSE_HEADERS_TRUNCATED

It works fine in any other browser but Chrome.
If I only use http then it works fine.
I read somewhere that if I use 302 redirect the problem is solved. So I asked the team to test it and it actually solved the issue, however, we are avoiding using 302 and we need to stick with 301.

A: Don't think it's anything to do with 301 or 302. Think it's because you are setting them up differently- in that you are not closing the 301 request properly.
See here:  https://productforums.google.com/forum/m/#!msg/chrome/2tttvx4VCDQ/kUIE1FXxve0J
This works:
"HTTP/1.1 301 Moved Permanently\r\n" + "Location: https://www.example.com" + http.req.url.path_and_query.http_url_safe + "\r\n\r\n"

This doesn't:
"HTTP/1.1 301 Moved Permanently\r\n" + "Location: https://www.example.com" + http.req.url.path_and_query.http_url_safe + "\r\n"


text:
Q: How do you get the traditional blue map marker in your app's map in React Native? I have an option in my app where my user sees their current location, but it is currently represented with a pin. I would like to replace it with the pulsing blue dot that is found on both iOS and Android when you open up your phone's maps app. How can this be achieved without using a "custom image" as my map marker? It may be worth noting that I am using react-native-maps

A: Generally speaking, you can't get the 'standard' iOS or Android Marker to show up in your RN Maps. The next best thing to do would be to use react-native-svg
This would create a 'standard' looking marker, and what I did.
Below is an example as to how you could do this in Expo SDK 43
import Svg, {Path, Circle, Ellipse} from 'react-native-svg'
import MapView, { Marker } from "react-native-maps";

...
const icon = () => {
      return(
        <Svg
          height = {20}
          width = {20}
        >
        <Ellipse
          cx="10"
          cy="10"
          rx="10"
          ry="10"
          fill="blue"
          stroke="#fff"
          strokeWidth="2"
        />
        </Svg>

        )
    }

...
<MapView>
  <Marker
     coordinate={
      //coordinate parameters go here
     }
  >
    <View>
      {(icon())}
    </View>
  </Marker>
 </MapView>

A: On the react-native-map README.md file, there are detailed explanations about customizing the marker.
https://github.com/react-native-maps/react-native-maps#rendering-a-marker-with-a-custom-image
<Marker
  coordinate={{ latitude : latitude , longitude : longitude }}
  image={require('../assets/pin.png')}
/>

A: try the showsUserLocation prop from MapView
https://github.com/react-native-maps/react-native-maps/blob/master/docs/mapview.md
<MapView
 ...
 showsUserLocation={true}
 style={{
   width: Dimensions.get('window').width,
   height: Dimensions.get('window').height
 }}
 ...
/>

A: import Svg, {Path, Circle, Ellipse} from 'react-native-svg'
Make sure expo in package.json is at: "^44.0.0",
and react-native-svg in package.json is at: "^9.3.3",
And then place the following code within the Marker Component.
  <MapView style={styles.map}
  region={mapRegion}
  mapType='hybrid'
  provider={PROVIDER_GOOGLE}
  >
  <Marker coordinate={{ latitude: mapRegion.latitude,
    longitude: mapRegion.longitude}}
    image={require('./bluecircle.png')}
    >
    <View>
    <Svg
    height = {20}
    width = {20}
  >
  <Ellipse
    cx="10"
    cy="10"
    rx="10"
    ry="10"
    fill="blue"
    stroke="#fff"
    strokeWidth="2"
  />
  </Svg>
    </View>
  </Marker>
  </MapView>


text:
Q: Using component area to show various content I have a relatively simple task although I am just a beginner so it's difficult to proceed.
I have a list of users on the left and a right panel to show that users info. The information about the user has an edit button that I want to take over that right panel and then save will return back to the user details.
What is the best approach to go about this?
Should the 2 pages be different components or should I just use javascript to show and hide content? Is there a better approach then either of those?
Sorry I'm new and just trying to get my had around the concept.
Thanks

A: I wrote a simple example for you:

const data = [{
  id: 1,
  name: 'user1',
  age: 21
},{
  id: 2,
  name: 'user2',
  age: 33
}]

const mixin = {
  props: {
    userId: {
      required: true
    }
  },
  data () {
    return {
      user: {}
    }
  },
  methods: {
    loadUser () {
      /*ajax to get user detail data here*/
      setTimeout(_=>{
        this.user = data.filter(o=>o.id==this.userId)[0]
      },10)
    }
  },
  created () {
    this.loadUser()
  },
  watch: {
    userId (newVal) {
      if(newVal){
        this.loadUser()
      }
    }
  }
}

Vue.component('user-viewer',{
  template: `

    name:{{user.name}}

    age: {{user.age}}

    <button @click="edit">edit</button>

`,
  mixins: [mixin],
  methods: {
    edit () {
      this.$emit('switch-edit-mode',true)
    }
  }
});

Vue.component('user-editor',{
  template: `

    name:<input type="text" v-model="user.name">

    age: <input type="text" v-model="user.age">

    <button @click="sendData">save</button>

`,
  mixins: [mixin],
  methods: {
    sendData () {
      /*ajax send user data here*/
      setTimeout(_=>{
        /*false means edit complete,so that user list must be reloaded*/
        this.$emit('switch-edit-mode',false);
      },10)
    }
  }
});

var app = new Vue({
  el: '#app',
  data () {
    return {
      users: [],
      isModify: false,
      userId: null
    }
  },
  methods: {
    toggleModify (modify) {
       this.isModify = modify
       if(!modify){
          this.fetchUsers();
       }
    },
    fetchUsers () {
      /*load your user list data here*/
      this.users = data.map(o=>({
        id: o.id,
        name: o.name
      }))
    }
  },
  created () {
    this.fetchUsers()
  }
})
*{
    padding:0;
    margin:0;
  }
  ul,li{
    list-style:none;
  }
  .main{
    display: flex;
  }
  .user-list{
    width: 250px;
  }
  .user-list>li{
    border:1px solid skyblue;
    border-bottom: none;
  }
  .user-list>li:last-child{
    border-bottom:1px solid skyblue;
  }
  .content-wrapper{
    flex:1;
  }

{{user.name}}

      <component v-if="userId" :is="isModify?'user-editor':'user-viewer'" @switch-edit-mode="toggleModify" :user-id="userId"></component>

please choose a user to view or edit

A: your mixin file:(mixin.js)
export default{
  props: {
    userId: {
      required: true
    }
  },
  data () {
    return {
      user: {}
    }
  },
  methods: {
    loadUser () {
      /*ajax to get user detail data here*/
      setTimeout(_=>{
        this.user = data.filter(o=>o.id==this.userId)[0]
      },10)
    }
  },
  created () {
    this.loadUser()
  },
  watch: {
    userId (newVal) {
      if(newVal){
        this.loadUser()
      }
    }
  }
}

usage:
import mixin from 'mixin.js'
export default{
  ...
  mixins: [mixin]
}


text:
Q: Ping in ASP.NET I can ping using console app, but I want to ping from ASP.NET, the problem is that, ping object doesn't show ping.send(....).
Is it not possible to ping from ASP.NET Web App?
for image please visit : http://coscientech.blogspot.com/2010/09/ping-trouble-aspnet.html
Directives are : using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;

A: Don't know if this is your case, but in general sending raw packet, done by ping, requires administrator rights on Windows. So most likely your ASP.NET page doesn't have enough privileges to send a ping packet. You can check this by copying the logic to regular application and running this application in different conditions. This will show you when Ping would work and when it wouldn't.