text:
Q: Any better way to solve the error handling in windows phone using json.net? I work on a Windows phone 7.1 project target on wp7 and wp8.
I successfully fetch data from a REST api using C#.
The API response me with 1 json, but it can be 2 structures.One for the correct result and one for the error message. Each of them have completely different structure.
and the HTTP status is all the same ---> 200
I translate them into 2 C# classes for the further deserializing.
What I want is to handle them differently, but you know, the deserializing needs a target C# class for the json. But How can I know which type of json does the API response me? I can figure it by my eye but how can the C# codes figure out.
What I thought is handle it with a try catch.
try
{
  //Deserializing the correct result
}
catch ( Exception ex)
{
  //Deserializing the ERROR result
}

Is there any better way for solving this?

A: As Alaa Masoud mentioned in the comments, if your REST API method returns a different status code for success than error (usually 200 for success or 4xx for error), you can look at that before deserializing to decide which class to use.  This would be the best way to do it.
If your method returns the same status code in each case, there are a couple of other ideas you could try:

*

*You could use Linq to Json instead of deserializing into a fixed class.  In other words, use JObject.Parse(), then walk the JSON looking for the properties you're interested in.

*You could define your fixed class to have properties of both the error and success JSON structure, then set the NullValueHandling option on the deserializer to Ignore.  This will allow the deserializer to fill in the properties for which it finds values int the JSON without throwing errors.  Then you can simply check the object for the success or error values.  Obviously, this solution isn't as "clean" but it could work in a pinch.


text:
Q: How can I use a type parameter determined via the functional dependency of an instance constraint as the RHS of an associated type family equation? I have a typeclass like this:
class (Coercible a b) => Foo a b | a -> b

I would like to declare the following instance of Generic:
data Thing a
  where
  Thing :: Foo a b => b -> Thing a

-- If the @b@ uniquely determined by @a@ is @Generic@, so is @Thing a@ ...
instance (Foo a b, Generic b) => Generic (Thing a)
  where
  type Rep (Thing a) = Rep b

Unfortunately this does not compile, the error message being:
[typecheck] [E] • Type variable 'r' is mentioned in the RHS,
    but not bound on the LHS of the family instance
• In the type instance declaration for 'Rep'
  In the instance declaration for 'Generic (UnvalidatedData v)'

I know that what I want is possible at a semantic level, because if I use a type family instead of a functional dependency as follows:
class (Coercible a (B a)) => Foo' a
  where
  type B a :: Type

I can declare:
data Thing a
  where
  Thing :: Foo' a => B a -> Thing a

-- If the @B a@ uniquely determined by @a@ is @Generic@, so is @Thing a@ ...
instance (Foo' a, Generic (B a)) => Generic (Thing a)
  where
  type Rep (Thing a) = Rep (B a)

Unfortunately associated type families do not show up at all in the kinds of typeclasses, so it is not possible to do higher order reasoning over associated type families when passing classes around. For this reason I would prefer to use a functional dependency instead of a type family.
What (if anything) is the closest working approximation of Foo, Thing and Thing's Generic instance that uses a multi-parameter typeclass?

A: The best I could come up with is to use both functional dependencies and a type family and try to get a best-of-both-worlds situation:
class (Coercible a b, b ~ B a) => Foo a b | a -> b where
  type B a :: Type

data Thing a where
  Thing :: Foo a b => b -> Thing a

instance (Foo a b, Generic b) => Generic (Thing a) where
  type Rep (Thing a) = Rep (B a)

It's not super elegant, but the use of b ~ B a in the constraint for Foo means that you cannot accidentally screw up instances of Foo.  For instance, you can write:
instance Foo (Sum a) a where
  type B (Sum a) = a

but if you try to write, say, type B (Sum a) = Int, you'll get a an error arising from the superclasses of an instance declaration.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get memory usage of open file descriptors I know how to find number of files currently open using - lsof | wc -l or for a particular PID or for an user.
Is it possible to list the corresponding PID's and how many file descriptors and memory are they using ?
I hope I made it clear. Thanks in advance.

A: From man ps:
rss   resident set size
size      memory size in kilobytes

Just call ps ax -o pid,rss,size to get processes with resident size and memory size.  As for file descriptors, we can count number of files in /proc/<PID>/fd/* directory for each process:
ps -A -opid | sudo xargs -n1 -I{} /bin/bash -c 'echo {} $(ls /proc/{}/fd | wc -l);'


text:
Q: line plot by month and year using FacetGrid I have this dataset:

year
month
victims

2016
7
4869

2016
8
4817

2016
9
4900

2016
10
4873

2016
11
4461

2016
12
4908

2017
1
4717

2017
2
4489

2017
3
4733

2017
4
4549

2017
5
4928

2017
6
4767

2017
7
4713

2017
8
4992

2017
9
4885

2017
10
5049

2017
11
4861

2017
12
4667

....
I want to plot the number of victims by year and month
I used this code :
sb.lineplot(data=number_victims,  x='month', y='victims', hue='year')
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5), title = 'month', title_fontsize = 12)

this is the result:

I tried to use FacetGrid to get a better view of each year
this is my code :
g = sb.FacetGrid(number_victims, col="year", margin_titles=True, col_wrap=3, height=3, aspect=2)
g.map_dataframe(
    sb.lineplot, x="month", y="victims"
)
g.fig.subplots_adjust(top=0.8)
g.fig.suptitle('The overall trend of victims number by month and year');

and this is the result :

So I have 2 questions:

*

*How to sort the months in the first graph? (to start from 1 to 12)

*Why in the second graph the name of months are from 1 to 10 ? and in 2016 it suppose to start from month #7 not #1, how can I fix that?

Thank you so much.


text:
Q: How to refer to the a properties accessor and mutator (getter/setter) I am wondering if there is a high performant way to refer to a properties getter or setter. For example, how would I fill in the details for the second example class below
public class Example
{
    public Example()
    {
        Action<int> setter = SetX;
        Func<int> getter = GetX;
    }
    public int GetX() { return 0; }
    public void SetX(int value){}
}

public class Example2
{
    public Example2()
    {
        Action<int> setter = ...;
        Func<int> getter = ...;
    }
    public int X
    {
        get{ return 0; }
        set{}
    }
}

I know I could create lamdas myself like so: Action<int> setter = x => X = x . However one of the reasons I wish to do this is to compare the references themselves in other parts of the application. So I actually wish to use the references to identify the particular property.
For example, I would want this to succeed :
var example = new Example();
Func<int> something = example.GetX;
Func<int> somethingElse = example.GetX;
bool equality = something.Equals(somethingElse);

Only with using properties.
I imagine this could be accomplished with reflection, however it would be likely for many of these operations to occur 30 times a second or so throughout my application, so I am hesitant to use a solution like that rather then just declaring GetX and SetX methods, even though that seems clumsy.
The end goal is to create a syntaticly simple way to both set a field, and inform those who have been linked up that it has been set, and to avoid the use of strings to accomplish it. Here's an example not using Properties, however the linkages would be made with additional abstractions
public class Example
{
    public event Action<Delegate> Change;

    int x = 0;
    public int GetX() { return x; }
    public void SetX(int value)
    {
        SetField(ref x, value, GetX);
    }

    protected void SetField<T>(ref T t, T value, Func<T> getter)
    {
        if (!EqualityComparer<T>.Default.Equals(getter(), value))
        {
            t = value;
            if(Change != null)
                Change(getter);
        }
    }
}

var example = new Example();
example.Change += getter =>
{
    Func<int> getX = example.GetX;
    if (getter.Equals(getX))
    {
        this.Log("x changed to: " + getX());
    }
};

example.SetX(5); // change is logged

A: I think reflection is the only way to do this:
public Example2()
{
    var prop = this.GetType().GetProperty("X");
    Action<int> setter = (Action<int>)Delegate.CreateDelegate(typeof(Action<int>), this, prop.GetSetMethod());
    Func<int> getter = (Func<int>)Delegate.CreateDelegate(typeof(Func<int>), this, prop.GetGetMethod());
}

But as you said, reflection is not particularly fast. You could define internal getters / setters as methods and bind to those, but that's not exactly what you were asking for either:
public Example2()
{
    Action<int> setter = this.GetX;
    Func<int> getter = this.SetX;
}

private int GetX() { return 0; }
private void SetX(int value) { }

public int X
{
    get { return GetX(); }
    set { SetX(value); }
}


text:
Q: Reconstructing D3 Animated Choropleth with a new Map and Data I am trying to recreate the D3.js example: "Yet another animated choropleth map":
http://bl.ocks.org/rgdonohue/9280446
Only, I am attempting to use a different map with different data. The map I am using is of US counties and the data is 2 years worth of median household values by county. I am running into an error in displaying my map. The error:
TypeError: counties[i].properties is undefined
Arises in the following function (see link above for original function):
function processData(error, us, countyData) {
  var counties = us.objects.counties.geometries;  // store the path in variable for ease
  for (var i in counties) {    // for each geometry object
    for (var j in countyData) {  // for each row in the CSV
      if(counties[i].properties.id == countyData[j].id) {   // if they match
        for(var k in countyData[i]) {   // for each column in the a row within the CSV
          if(k != 'name' && k != 'id') {  // let's not add the name or id as props since we already have them
            if(attributeArray.indexOf(k) == -1) {
               attributeArray.push(k);  // add new column headings to our array for later
            }
            counties[i].properties[k] = Number(countyData[j][k])  // add each CSV column key/value to geometry object
          }
        }
        break;  // stop looking through the CSV since we made our match
      }
    }
  }
  d3.select('#clock').html(attributeArray[currentAttribute]);  // populate the clock initially with the current year
  drawMap(us);  // let's mug the map now with our newly populated data object
}

I believe what is happening is that 'us' is undefined for some reason. The original example uses the map world-topo.json which I haven't been able to find the source for.  My map is http://d3js.org/us-10m.v1.json.
Original code:
world.objects.countries.geometries

which I changed to:
us.objects.counties.geometries

In Bostock's original Choropleth example he uses the same US map that I am using and references it as 'us', but it doesn't seem to be working for me:
svg.append("g")
.data(topojson.feature(us, us.objects.counties).features)

I realize I don't have a very  good understanding of D3 - I'm more of a code hacker and not a developer. I'm just trying to experiment with some visualizations and have little experience with javascript/d3. Any help would be appreciated.
My entire program:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>d3 choropleth map</title>

      <button id="play">play</button>
      year

Example data from countiesRandom.csv:
id,2010,2015
01001,141300,133900

A: In regards to:

I am running into an error in displaying my map. The error: TypeError:
  counties[i].properties is undefined

We need to examine both the referenced world topojson and US topojson.
In the world topojson, the geometries are defined like this:
"geometries":[
{"type":"Polygon","id":1,"arcs":[[0,1,2,3,4,5,6,7]],"properties":{"admin":"Afghanistan","id":"AFG"}},
{"type":"Polygon","id":4,"arcs":[[16,17,18,19,20]],"properties":{"admin":"Albania","id":"ALB"}},

There is a properties attribute to each geometry.
In the US topojson you reference, the geometries are defined like this:
"geometries":[
{"type":"Polygon","arcs":[[0,1,2,3,4]],"id":"05089"},
{"type":"Polygon","arcs":[[5,6,7,8,9]],"id":"06079"},
{"type":"Polygon","arcs":[[10,11,12,13,14,15,16]],"id":"17111"},

There is no properties attribute assigned to each geometry. So, when you call for the properties of a geometry, it'll return undefined.
So instead of using counties[i].properties.id, you might find more success with counties[i].id.

It may also be worth noting, if you are comparing examples, that the conversion from topojson to geojson (topojson.feature(us, us.objects.counties).features) will modify the structure of the data as well:

d3.json("//d3js.org/us-10m.v1.json",function(error,us) {
  console.log("Number of county geometries:");
  console.log(us.objects.counties.geometries.length);
  console.log("Example county id:");
  console.log(us.objects.counties.geometries[0].id);
});

d3.json("//d3js.org/us-10m.v1.json",function(error,us) {
  var geojson = topojson.feature(us, us.objects.counties).features;
  console.log("Number of features");
  console.log(geojson.length);
  console.log("Example county ID");
  console.log(geojson[0].id);

});


text:
Q: ListView is not updated after filtering in ListFragment I have a listview and an edittext for filtering. I am able to filter and save result in String[] subItems but listview is not updated. I searched on Google but I didn't find solution.
Here is code snippet.
OnActivityCreated
    public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    setRetainInstance(true);
    setHasOptionsMenu(true);

    lv = getListView();
    lv.setTextFilterEnabled(true);
    lv.setCacheColorHint(Color.TRANSPARENT);
    lv.setFastScrollEnabled(true);

    lv.setDivider(getResources().getDrawable(android.R.color.black));
    lv.setDividerHeight(1);
//lv.setBackgroundColor(Color.parseColor("#f7f9c3")); //#ffddb0
    lv.setBackgroundDrawable(getResources().getDrawable(R.drawable.merge));
    lv.setScrollingCacheEnabled(false);
    lv.setSmoothScrollbarEnabled(false);

   adapter  = new IconicAdapter();

    setListAdapter(adapter);

  }

OnCreateView
     @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
  {
      View view = inflater.inflate(R.layout.toc, null);

      filterText = (EditText) view.findViewById(R.id.editTextFilter);
      filterText.addTextChangedListener(filterTextWatcher);
      return view;
  }

FilterTextWatcher
private TextWatcher filterTextWatcher = new TextWatcher() {

    public void afterTextChanged(Editable s) {

    }

    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
    }

    public void onTextChanged(CharSequence s, int start, int before,
            int count) {
        adapter.getFilter().filter(s);
        adapter.notifyDataSetChanged();
    }

};

Custom ListView Class
 public class IconicAdapter extends ArrayAdapter {

  public String[] allItems;
  public String[] subItems;
  //public ArrayList <String> allItems = new ArrayList<String>();
  //public ArrayList <String> subItems = new ArrayList<String>();

  private TOCFilter filter;

TextView tx = null;

IconicAdapter() {
super(getActivity(), R.layout.toc_list, Constants.TOC);

this.subItems = new String[Constants.TOC.size()];
this.subItems = Constants.TOC.toArray(this.subItems);
    this.allItems = this.subItems;
}

@Override
public Filter getFilter() {
    if (filter == null){
      filter  = new TOCFilter();
    }
    return filter;
  }

@Override
public int getCount() {
//return Constants.TOC.size();
    return subItems.length;
    }

@Override
 public String getItem(int position) {
     return subItems[position];
 }

public View getView(int position, View convertView,ViewGroup parent) {
        //LayoutInflater inflater= getLayoutInflater();
    View row = getActivity().getLayoutInflater().inflate(R.layout.toc_list, parent, false);
    //View row=inflater.inflate(R.layout.toc_list, parent, false);
        try
        {
            tx=(TextView)row.findViewById(R.id.mainList);

            tx.setText(Constants.TOC.get(position).toString());
            tx.setTextSize(Constants.txtSize);
            tx.setTextColor(Color.BLACK);
        if(Constants.UKDebug)
        {
            if(position == 0 || position == 1)
            {
               Log.d("iconicadapter", Constants.TOC.get(position) + "");
            }
        }

            }
            catch (Exception e) {Log.d("main","iconadapter"); e.printStackTrace();}
        return(row);

    }

Filter Class which is part of customer listview adapter
private class TOCFilter extends Filter{

    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
         FilterResults results = new FilterResults();
         ArrayList<String> i = new ArrayList<String>();
         String[] contents;

          if (constraint!= null && constraint.toString().length() > 0) {

              for (int index = 0; index < allItems.length; index++) {
                  String si = allItems[index];
                  if(si.toLowerCase().startsWith(constraint.toString())){
                    i.add(si);
                  }
              }
              contents = new String[i.size()];
              i.toArray(contents);
              results.values = contents;
              results.count = contents.length;
          }
          else{
              synchronized (allItems){
                  results.values = allItems;
                  results.count = allItems.length;
              }
          }
          return results;
    }

    @Override
    protected void publishResults(CharSequence constraint,
            FilterResults results) {
        // TODO Auto-generated method stub
        subItems =  (String[]) results.values;
        notifyDataSetChanged();
    }
}

Your help is highly appreciated.

A: I solved the problem by following following tutorial.
http://justcallmebrian.com/?p=149


text:
Q: SRSS if / else SWITCH I have a bar graph which I would like to have different colours for each category.
So far I'm doing it with a SWITCH but I couldn't see how / if it's possible to put an else on the end there.
My code looks like this:
    =SWITCH(
Fields!Style_Name.Value = "Vagabond Pale Ale", "CornflowerBlue",
Fields!Style_Name.Value = "This Is Lager", "Orange",
Fields!Style_Name.Value = "Punk IPA", "#00AFDB",
Fields!Style_Name.Value = "Nanny State", "White",
Fields!Style_Name.Value = "Jet Black Heart", "DimGray",
Fields!Style_Name.Value = "Dead Pony Club", "SeaGreen",
Fields!Style_Name.Value = "5am Red Ale", "Maroon",
Fields!Style_Name.Value = "KingPin", "Orange",
Fields!Style_Name.Value = "Jack Hammer", "LimeGreen",
Fields!Style_Name.Value = "Libertine Black Ale","#7e000000",
Fields!Style_Name.Value = "Hardcore IPA","MidnightBlue",
Fields!Style_Name.Value = "Cocoa Psycho", "Indigo",
Fields!Style_Name.Value = "Elvis Juice", "Red")

A: Just add in the end
    True, "Yourcolor"
  =SWITCH(
Fields!Style_Name.Value = "Vagabond Pale Ale", "CornflowerBlue",
Fields!Style_Name.Value = "This Is Lager", "Orange",
Fields!Style_Name.Value = "Punk IPA", "#00AFDB",
Fields!Style_Name.Value = "Nanny State", "White",
Fields!Style_Name.Value = "Jet Black Heart", "DimGray",
Fields!Style_Name.Value = "Dead Pony Club", "SeaGreen",
Fields!Style_Name.Value = "5am Red Ale", "Maroon",
Fields!Style_Name.Value = "KingPin", "Orange",
Fields!Style_Name.Value = "Jack Hammer", "LimeGreen",
Fields!Style_Name.Value = "Libertine Black Ale","#7e000000",
Fields!Style_Name.Value = "Hardcore IPA","MidnightBlue",
Fields!Style_Name.Value = "Cocoa Psycho", "Indigo",
Fields!Style_Name.Value = "Elvis Juice", "Red",
**True, "Black"**
)


text:
Q: Error Running Playframework2 Web Application When I run my playframework2 web application using IntelliJ idea
[frontend] $ run 9000

I get this error message:
Path(C:\Users\Dell\IdeaProjects\frontend\logs\application.log) is not a directory so descendants can not be called on itis not a directory
[trace] Stack trace suppressed: run last compile:run for the full output.
[error] (compile:run) java.lang.reflect.InvocationTargetException
[error] Total time: 2 s, completed 17 avr. 2015 23:22:42

A: Seems to do with incorrectly terminated Java/JVM.
Try seeing if you can find something like a zombie Java instance in the process manager, or alternatively try again after a reboot.


text:
Q: I have two question about "stock up" & "dress shirts"
NEW YORK — Perry Ellis is not a brand that makes men nervous or causes them to titter. Even if a work-a-day guy doesn't wear Perry Ellis clothes, he probably recognizes the name from those times he has wandered through a department store looking to stock up on dress shirts. Perry Ellis is not niche; it is mass. And its creative director, Michael Maccari designed a spring 2016 collection that was welcoming to a wide swath of men. Board shorts, crewneck sweaters, lean — but not tight — suits. Rich colors but nothing too psychedelic.

It is saying dress shirts , and it looks like as if the word *dress** acts as an adjective. What does the writer really mean by saying dress shirts?
Is stock up here s noun?
Thank you in advance.

A: "Stock up" is a set term meaning to "increase the quantity of an item you have."
So, if it's winter and you won't be able to get to the grocery store because there's a major snow storm coming, you would "stock up" on food and other supplies so that you wouldn't starve when you couldn't go out.
In this case, a man who is starting a new job (as an example) may "stock up" on essential items like dress shirts as he will likely need at least five to get through the work week.
A "Dress shirt" is (usually) a men's business shirt.
It's usually long-sleeved, button-up with a collar and often worn with a tie, though you can have a "Short-sleeved dress shirt":


text:
Q: Chain rule for functional derivates with the same variables I am following an online course where we should sometimes compute functional derivatives. The scope of the course is density functional theory, so we have the density $n(r)$ and we have functionals of the form $F[n(r)]$.
$$n(r) = \sum_i \Psi_i^*(r)\Psi_i(r)$$
In the course we need to perform derivatives with respect to $\Psi_i^*(r)$ not with respect to $n(r)$. One quick result is that:
$$\frac{\delta n(r)}{\delta \Psi_i^*(r)} = \frac{\delta \Psi_i^*(r)}{\delta \Psi_i^*(r)} \Psi_i(r) = \Psi_i(r)$$
One of the students used the chain rules for functional derivatives:
$$\frac{\delta F[n(r)]}{\delta \Psi_i^*(r')} = \int \frac{\delta F[n(r)]}{\delta n(r)}\frac{\delta n(r)}{\delta \Psi_i^*(r')}dr = \int \frac{\delta F[n(r)]}{\delta n(r)}\delta(r - r')\Psi_i(r) dr = \frac{\delta F[n(r)]}{\delta n(r')}\Psi_i(r')$$
Which is a really helpful result because it allows to compute derivatives directly with respect to $n(r)$ and still get what we want by just multiplying by $\Psi_i(r')$.
Now the problem I have, is that, in this line he introduced a new variable $r'$ while it shouldn't, the derivative should be with one variable $r$ everywhere, and I believe that this is not valid when the variables are the same (the integral doesn't vanish.).
What I did is that I used the functional derivative definition of composed function $F[g(f(r))]$ and adapted to each functional I needed to derive which lead to the same results with more work
While I acknowledge that the first solution is faster, I wouldn't be able to find it by myself because it doesn't make so much sense to me.
Any thoughts?

A: Some of your expressions are problematic, if not meaningless, and maybe that's at the heart of your confusion. Fair warning: I would use the mainstream definition of the functional derivative used in physics, very often not math, as, e.g. in Largangian mechanics. Drop the different indices i, and the summation over them, since they don't enter the problem and just contribute extraneous functions which act like numerical coefficients in ordinary calculus.
You then pretend n(r) itself is a functional(which depends on some "parameter" r, even though not on the argument r' entering in the variation of the function you are about to differentiate it with respect to!), which you may differentiate unambiguously, to obtain the canonical expression,
$$  n(r)= \int\!\! dr' ~n(r') \delta(r'-r) ~~~\leadsto  \\
\frac{\delta n(r)}{\delta  \Psi^*(r')} = \int\!\! dr' ~  \Psi^*(r') \Psi(r') \delta(r'-r)   = \Psi (r')  \delta(r-r'),  \tag{1}$$
a function of r and r'.
Now, switch gears and think of n(r) as a function, again, entering in a functional F[n]. Since the functional  F does not depend on the argument of this function, we skip the "dummy" argument r of it.  Then, the functional derivative of it is the following  function of r',
$$\frac{\delta F[n]}{\delta \Psi^*(r')} = \int \frac{\delta F[n]}{\delta n(r)}\frac{\delta n(r)}{\delta \Psi^*(r')}dr = \int \frac{\delta F[n]}{\delta n(r)}\delta(r - r')\Psi(r') dr = \frac{\delta F[n]}{\delta n(r')}\Psi(r')~.\tag{2}$$
You might think of this as the directional functional derivative of F in the direction of $\frac{\delta n(r)}{\delta \Psi^*(r')}$.
Test-drive it with an overly silly easy functional, such as
$$
F[n]=  \int\!\! dr   ~ n(r)^5 =  \int\!\! dr   ~ \Psi^*(r)^5 \Psi(r) ^5 .
$$
Directly, you have the function
$$
\frac{\delta F[n]}{\delta \Psi^*(r')} = 5\Psi^*(r')^4 \Psi(r') ^5 ,
$$
but, by use of (2), you also get the same function
$$
\frac{\delta F[n]}{\delta \Psi^*(r')} = \int\!\!dr~ 5n(r)^4  \delta(r - r') \Psi(r')  =   5\Psi^*(r')^4 \Psi(r') ^5.
$$

*

*When in doubt, use finite-dimensional vectors, and take  vector derivatives
of scalar functions thereof, and only at the very end take the number of components j to go to infinity and utilize a continuous variable r for them.
So, (2) is something like $$\partial F(y)/\partial x_i^* =\sum_j \partial F /\partial y_i~~ \partial y_j/\partial x_i^* = \sum_j \partial F /\partial y_i~~   x_i \delta_{ij} ,$$ which might illustrate the necessity of two variables before their ultimate merge.


text:
Q: Rust serde parse Vec of substruct Is it possible to just extract the Message struct of this json items array?
My goal is to get a Vec of Message(s) if there are multiple entries in items.
{
  "items": [
    {
      "Message": {
        "data": "data",
        "header": "header"
      },
      "structx": {
        "val": 1
      },
      "val1": "test"
    }
  ]
}

As of now i have those structs to deserialize the above.
#[derive(Debug, Deserialize, Serialize)]
struct Items {
    items: Vec<Message>,
}

#[derive(Debug, Deserialize, Serialize)]
struct Message {
    #[serde(rename = "Message")]
    msg: Payload,
}

#[derive(Debug, Deserialize, Serialize)]
struct Payload {
    header: String,
    data: String,
}

I deserialize like that:
let x = json_string; // the above json
let msg: Items = serde_json::from_str(&x)?;

This works but maybe it could be made cleaner.
I thought of something like this(which does not work) so that i could remove the unnecessary structs(Items, Message):
let msg: Vec<Payload> = serde_json::from_str(&x)?;

A: There is 3 solutions:

*

*Deal with it

*Implement custom Deserialize

*Use unsafe and #[repr(transparent)]:

use serde::{Deserialize, Serialize};

#[derive(Debug, Deserialize, Serialize)]
#[repr(transparent)]
struct Items {
    items: Vec<Message>,
}

#[derive(Debug, Deserialize, Serialize)]
#[repr(transparent)]
struct Message {
    #[serde(rename = "Message")]
    msg: Payload,
}

#[derive(Debug, PartialEq, Deserialize, Serialize)]
struct Payload {
    header: String,
    data: String,
}

fn main() {
    let raw = r#"{
    "items": [{
        "Message": {
            "data": "data",
            "header": "header"
        },
        "structx": {
            "val": 1
        },
        "val1": "test"
    }]
}"#;

    let msg: Items = serde_json::from_str(&raw).unwrap();
    let payloads: Vec<Payload> = unsafe { std::mem::transmute(msg) };

    assert_eq!(
        payloads,
        vec![Payload {
            data: String::from("data"),
            header: String::from("header")
        }]
    );
}


text:
Q: Why is my event variable undefined on input? HTML:
<input (input)="test(1, $event)">
Typescript:
test(index: number, event?) {
    console.log(event);
}

I'm trying to see if the user hits their backspace key on the input, but I can't get any of the user input using the $event variable. What am I doing wrong?

A: Use keydown / keypress/ keyup Keyboardevent to identify the user interaction with keyboard.
Angular event bindings respond to any DOM event. Example usage of keydown event:
  <input (keydown)="onKeydown($event)">

onKeydown(event) {
  console.log("event.key:" + event.key)
  if (event.key === "Backspace") {
    console.log(event);
  }
}

Other option, Trigger the keydown event for specific key. In the following example, the event will trigger only if the backspace pressed.
<input (keydown.backspace)="onKeydownBackspace($event)">

onKeydownBackspace(event) {
  console.log("event.key:" + event.key)
}


text:
Q: UrlRewriter.NET - simple rewrite rule, but how? I have just installed the sample from Urlrewriter.net, but I can't seem to figure out
the rule for accomplishing my problem.
Very simple:
If the user is navigated to this page:
http://localhost/UrlRewriteTest/Default.aspx?PageID=33

The Url should look like:
http://localhost/UrlRewriteTest/33

or maybe
http://localhost/UrlRewriteTest/33.aspx

What am I doing wrong? Here is my web.config:
<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="rewriter" requirePermission="false" type="Intelligencia.UrlRewriter.Configuration.RewriterConfigurationSectionHandler, Intelligencia.UrlRewriter"/>
  </configSections>
    <system.web>
    <httpModules>
      <add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter"/>
    </httpModules>
    <compilation targetFramework="4.0"/>
    <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
  </system.web>
  <rewriter>
    <rewrite url="~/(.+)" to="~/Default.aspx?PageID=$1"/>
  </rewriter>
    <system.webServer>
        <modules runAllManagedModulesForAllRequests="true">
            <add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule" />
        </modules>
        <validation validateIntegratedModeConfiguration="false" />
    </system.webServer>
</configuration>

That is the first step. More ideally PageID should be passed to a database
and return the pagename instead of an ID, and the URL should end up looking
like this:
http://localhost/UrlRewriteTest/thename/

Best regards.

A: You can read Scott Guthrie's article about Url Rewriting @ http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx.


text:
Q: MariaDB update error inner join and select I hope you can help me again, thanks already for pointing me to the right direction with creating the check digit for the new IBAN in Germany. I am now trying to update our membership database with the newly calculated BIC and IBAN but seem to have a problem with the UPDATE statement on the MariaDB MySQL database, despite the fact that I think I got the syntax right.
All I am trying to do is set the two fields "konto_bic" and "konto_iban" in the table "mitglieder" from the SELECT statement which creates a temporary table called b with the columns "id", "bic" and "iban". The "id" is the same in the two tables.
Here is my first try:
update a
set a.`konto_bic` = b.`BIC`, a.`konto_iban` = b.`IBAN`
from `mitglieder` a
INNER JOIN (SELECT m.`id`, m.`nachname`, m.`vorname`, m.`konto_bank`, m.`konto_blz`, m.`konto_nummer`, k.`bic` AS 'BIC', CONCAT('DE',LPAD(98-MOD(CONVERT(CONCAT(m.`konto_blz`,LPAD(m.`konto_nummer`,10,'0'),'1314','00'), decimal(24)),97),2,'0'),m.`konto_blz`,LPAD(m.`konto_nummer`,10,'0')) AS 'IBAN'
FROM `mitglieder` m
LEFT JOIN `konvert_bic_blz` k
ON m.`konto_blz` = k.`blz`
ORDER BY m.`nachname`, m.`vorname`) b
ON a.`id` = b.`id`

However, this produced an error and I tried this instead:
update `mitglieder` a
set a.`konto_bic` = b.`bic`, a.`konto_iban` = b.`iban`
FROM (SELECT m.`id` as 'id', k.`bic` as 'bic', CONCAT('DE',LPAD(98-MOD(CONVERT(CONCAT(m.`konto_blz`,LPAD(m.`konto_nummer`,10,'0'),'1314','00'), decimal(24)),97),2,'0'),m.`konto_blz`,LPAD(m.`konto_nummer`,10,'0')) AS 'iban'
FROM `mitglieder` m
LEFT JOIN `konvert_bic_blz` k
ON m.`konto_blz` = k.`blz`) b
WHERE a.`id` = b.`id`

That also did not get me any further (error from DB).
Can anyone see what my syntax error might be?
Thank you in advance for your help
Stephan

A: Try below SQL
UPDATE `mitglieder` a,
       (SELECT m.`id` AS 'id',
               k.`bic` AS 'bic',
               CONCAT('DE',LPAD(98-MOD(CONVERT(CONCAT(m.`konto_blz`,LPAD(m.`konto_nummer`,10,'0'),'1314','00'), decimal(24)),97),2,'0'),m.`konto_blz`,LPAD(m.`konto_nummer`,10,'0')) AS 'iban'
        FROM `mitglieder` m
        LEFT JOIN `konvert_bic_blz` k ON m.`konto_blz` = k.`blz`) b
SET a.`konto_bic` = b.`bic`, a.`konto_iban` = b.`iban`
WHERE a.`id` = b.`id`

UPDATE Syntax
http://dev.mysql.com/doc/refman/5.0/en/update.html

A: I tried this on MariaDB 10.2.6 :
SET sql_mode = 'ANSI_QUOTES'

UPDATE "test"."user" AS "a"
INNER JOIN "test"."user_profile" AS "c" ON "c".user_id = "a".id
INNER JOIN "test"."profile" AS "d" ON "d".id = "c".profile_id
SET "a".firstname = 'laurent'
WHERE "a".id = 3;

And it works :)


text:
Q: C++ Template int and strings #include <string>
#include <iostream>

using namespace std;

template <class T>
class Tyler{
    T first, second;
    public:
        Tyler(T a, T b)
        {
            first = a;
            second = b;
        }
        int larger();
        string larger();

};

template <class T>
int Tyler<int>::larger()
{
    cout << "int larger" <<endl;
    return(first>second?first:second);
}

template <class T>
string Tyler<string>::larger()
{
    cout << "string larger" <<endl;
    if(first.compare(second) > 0)
        return(first);
    return(second);
}

int main()
{
    Tyler<int> tobj(7,77);
    Tyler<string> tstr("Seven", "test");

    cout << tobj.larger() <<endl;
    cout << tstr.larger() <<endl;

}

I am learning C++ (templates in particular) and trying to understand. What if I wanted to create the two functions below and the "larger" function will perform different depending on which datatype is specified in the class instantiated in main. I have only seen examples that use int and float.

A: First, you appear to be trying to specialize the function, so your declarations are not right.  You should have this declaration.
T larger();

You want each Tyler object to have only a single larger function, that does different things depending on T.  Next, the definitions:
int Tyler<int>::larger()

Here, you're creating a template specialization.  It's a template function (well, sort of), so it does need the template bit atop it, but this specialization requires no template parameters, so...
template<>
int Tyler<int>::larger()

Why is that useful?  Well, because sometimes a specialization can have template parameters...
template<class T, class Allocator>
vector<T,Allocator> Tyler<  vector<T,Allocator>  >::larger()


text:
Q: memory alignment of classes I´m working on a memory manager using help of the book Game Engine Architecture.
At the moment I´m reading about memory alignment (in the book and web) and I´m not sure how the alignment is used correctly for classes. I understand the concept of memory alignment (e.g. a 4 byte data chunk should be located at an address ending with 0x0, 0x4, 0x8 or 0xC) but at the allocateAligned()-function in the book is a comment that says that the alignment has to be power of two. If i have a class that has two int´s and one char, sizeof(classs) tells me, that the class is 12 bytes big. So, would you pass 32 as alignment? Would it not be a waste of memory and maybe lead to fragmentation?
My question is, how do classes have to be aligned correctly, could you explain me it more detailed (what happens if you want to align bigger data chunks, like 121 bytes) and does it make sense for the bigger chunks to be aligned (because the processor fetches only 8 bytes in one call, if I´m informed right)?

A: The alignment of a type can never be greater than the size of a type.  This is because in an array, there can be no padding between elements.
Just as importantly, though, the alignment of a type may be smaller than the size of the type.
Let's consider your class type:  it has three members, two 4-byte integers and one 2-byte integer.  Let's assume that the alignment of a 4-byte integer is 4 bytes and the alignment of a 2-byte integer is 2 bytes (this is common).  In this case, the alignment of your class type is only 4 bytes.  It can be located on any 4-byte boundary and each of its members will be correctly aligned.
This is why your class type has two bytes of padding:  12 is evenly divisible by four, but 10 is not.  If your class had no padding, its size would only be 10 bytes, and in an array of elements half of the objects would be misaligned.

A: A type's alignment can be smaller than, but not bigger than, its size.  On a typical 32-bit implementation, your
struct X {
    int a;
    int b;
    char c;
};

would likely have sizeof(X) == 12 and alignof(X) == 4.  Obviously you can't have an X every four bytes because they would then overlap, but the alignment means that 0x1000, 0x1004, 0x1008, and 0x100c are all potential places you might begin an X.
Note that the type size as returned by sizeof is always a multiple of the alignment, since sizeof specifies the number of bytes between array elements, and you wouldn't want the first entry in an array to be aligned but not the second.


text:
Q: meteor form validation using parsley I have no clue how this is going, I have followed the steps on meteor parsley package.
I want the form not the get submitted if there is no valid input. though it show undefined when added for the url, but I want to restrict form from submitting until it satisfies the condition.

<form class="form-horizontal" role="form" id="addItem" data-parsley-validate>

  Listing URL

    <input  type="url"
            class="form-control"
            id="listing_url"
            placeholder="Enter the listing URL"
            data-required='true'
            data-type='url'
            data-trigger='change'/>

        <button class="btn btn-danger btn-md">Clear</button>
        <button class="btn btn-success btn-md pull-right submit">Submit</button>

    Template.addItem.events({
  'click .submit': function() {
    var current_date = moment().format("DD-MM-YYYY hh:mm");
    var insertform = {
      created_at: current_date,
      url: $('#url').val()
    }
        console.log('insertform:', insertform);
        insertForm.insert(insertform);
  }
})
Template.addItem.onRendered = (function () {
  // Setup parsley form validation
  // replace form with the id of your form
  $('#addItem').parsley({trigger: 'change'});
});

A: You need to check if the form's valid and then run your submit code.
    var formValid = $('#addItem').parsley('validate')
    if (formValid)
    {
        var current_date = moment().format("DD-MM-YYYY hh:mm");
        var insertform = {
            created_at: current_date,
            url: $('#url').val()
         }
        console.log('insertform:', insertform);
        insertForm.insert(insertform);
    }


text:
Q: How to calculate predicted R Sq in R I was trying to calculate the predicted R square in R programming language for a multiple linear regression model, like one we get in Minitab.
go through this link it gives how it's done in Minitab. But I am not aware how it's done in R
https://statisticsbyjim.com/regression/interpret-adjusted-r-squared-predicted-r-squared-regression/

A: Please check: predicted R squared computation
#PRESS - predicted residual sums of squares

PRESS <- function(linear.model) {
  #' calculate the predictive residuals
  pr <- residuals(linear.model)/(1-lm.influence(linear.model)$hat)
  #' calculate the PRESS
  PRESS <- sum(pr^2)

  return(PRESS)
}

pred_r_squared <- function(linear.model) {
  #' Use anova() to get the sum of squares for the linear model
  lm.anova <- anova(linear.model)
  #' Calculate the total sum of squares
  tss <- sum(lm.anova$'Sum Sq')
  # Calculate the predictive R^2
  pred.r.squared <- 1-PRESS(linear.model)/(tss)

  return(pred.r.squared)
}

I tested on a random model:
model <- lm(disp ~ mpg, mtcars)
pred_r_squared(model)
#0.6815513

A: The linear model has a summary function, which can be used as follows:
set.seed(0)
y <- 1:10
x <- runif(10)
summary(lm(y~x))

#Call:
#lm(formula = y ~ x)

#Residuals:
#    Min      1Q  Median      3Q     Max
#-5.1468 -1.7243 -0.1631  1.6937  4.5146

#Coefficients:
#            Estimate Std. Error t value Pr(>|t|)
#(Intercept)    3.931      2.561   1.535    0.163
#x              2.472      3.720   0.664    0.525

#Residual standard error: 3.126 on 8 degrees of freedom
#Multiple R-squared:  0.0523,   Adjusted R-squared:  -0.06616
#F-statistic: 0.4415 on 1 and 8 DF,  p-value: 0.5251

You can specifically get the R-squared or adjusted R-squared with:
summary(lm(y~x))$r.squared

or
summary(lm(y~x))$adj.r.squared


text:
Q: Host ASP.NET Core on IIS I'm trying to host an asp.net core web application, but for some reason it wont work. My other core app's work, but not this one. I've set the application pool .net clr version to no managed code.
this is what I get in event viewer:
"Application 'MACHINE/WEBROOT/APPHOST/FFU CORE' with physical root 'C:\Users\Administrator\Documents\WWWROOT\Customer\core_FFU\' failed to start process with commandline '"dotnet" .\WEB_CORE_MODERN_2017.dll', ErrorCode = '0x80004005 : 80008083."
any help will be higly appreciated!

A: *

*Can you host via IIS Express in Visual Studio?

*Are you updated to the latest SDK and runtime? https://github.com/dotnet/core/blob/master/release-notes/download-archive.md

*Make sure you have the latest .net core windows hosting installed.

Similar question: here


text:
Q: Lightning:Checkboxgroup select only one option How do I select only one entry from a lightning:checkboxgroup, meaning, I can do an either - or, but not select two options at once? I have two checkboxes in my group, and v.value gives the order according to the options set in the options attribute, but then I cannot find out which is the latest value selected. See description of lightning:inputcheckbox:https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/aura_compref_lightning_checkboxGroup.htm.

A: If you need to be able to find out which is the latest value selected - you could keep a "backup copy" of the state whenever it's changed, so that on the next change you can compare to see what's different.

A: You can use change handler to identify the changes between old and new values.
<aura:handler name="change" value="{!v.checkboxValue}" action="{!c.checkboxHandler}"/>

Bind an action "checkboxHandler" which will be triggered whenever value of checkbox will change. Please find the below example which will help you to solve your problem.
Component:-
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
<aura:attribute name="options" type="List" default="[
                                                    {'label': 'Blue', 'value': 'Blue'},
                                                    {'label': 'Red', 'value': 'Red'},
                                                    {'label': 'Green', 'value': 'Green'}

                                                    ]"/>
<aura:attribute name="checkboxValue" type="List"/>
<aura:handler name="change" value="{!v.checkboxValue}" action="{!c.checkboxHandler}"/>

<lightning:checkboxGroup
                         aura:id="mygroup"
                         name="checkboxGroup"
                         label="Checkbox Group"
                         options="{! v.options }"
                         value="{! v.checkboxValue }"
                         required="true" />

Controller.js
 ({
    checkboxHandler: function (cmp, event, helper) {
    var oldValue= event.getParam("oldValue");
    var newValue = event.getParam("value");
    console.log("old value: " + oldValue);
    console.log("new value: " + newValue);
    // Identify the new checkbox value
    if(oldValue.length < newValue.length){
        alert('new value--'+helper.getDifference(oldValue, newValue));
    }
   }
});

Helper.js:- A utility method is written here which compares two arrays and returns the difference
({
    getDifference : function(oldValue, newValue) {
    var result = [];
    for (var i = 0; i < newValue.length; i++) {
        if (oldValue.indexOf(newValue[i]) === -1) {
            result.push(newValue[i]);
        }
    }
    for (i = 0; i < oldValue.length; i++) {
        if (newValue.indexOf(oldValue[i]) === -1) {
            result.push(oldValue[i]);
        }
    }
    return result;
}
})

I hope it helps. Please mark it as answer if it resolve your issue and can help other community members. Cheers !!!


text:
Q: Tree View WIKI replacement solution for SharePoint like Confluence? I keep my Process Documents on SVN and I want to create a Wiki page includes the information about these files. We use SharePoint in the company for basic document sharing and team sites. As it is mentioned in
https://stackoverflow.com/questions/256407/what-are-your-biggest-complaints-about-sharepoint SharePoint Wiki lacks of usability. I need an easy to use wiki tool which is capable of showing the content like WikiPedia contents and it would be great if I could have the SharePoint tree view  and Active Directory authentication also. I googled it and found Atlassian's Confluence and it seems that this product is capable of the requirements. We use Jira for issue tracking, so we can use it's reporting in dashboards. I need and it has a Wiki part which displays wiki pages in tree view. It should be like http://www.atlassian.com/software/confluence/images/tour/full/page_tree.png http://www.atlassian.com/software/confluence/images/tour/full/page_tree.png
Does anyone used Confluence or have an idea for other products which meets my requirements

A: Have you considered our Confluence Sharepoint connector? It sounds like that's what your after, it will allow you to use Sharepoint for all the other features, but use Confluence as your wiki http://www.atlassian.com/sharepoint/.
Seeing that you already use Jira, you could use Confluence and leverage off some level of integration between the two products.
Let me know if you have any questions.
Sherif Mansour (@sherifmansour)
Confluence Product Manager


text:
Q: Error while installing ng-bootstrap in angular v-13 Throwing the below error while trying to install ng-bootstrap in angular version 13
Error :

These are the other details respective to the node, npm and os

Angular CLI: 13.0.2, Node: 16.13.0, Package Manager: npm 8.1.0, OS:
darwin x64

Found a similar question here
Error when installing ng add @ng-bootstrap/ng-bootstrap
and tried to use the solution given in the answers, but doesn't work for me.
Much appreciate any help with this problem.

A: Try this
ng add @ng-bootstrap/ng-bootstrap --legacy-peer-deps

A: This fixed the issue for me
npm config set legacy-peer-deps true

which means it allows installing legacy packages.


text:
Q: I want to Fetch data from a url and display it in front end. When I did it in postman it was working fine. But in the below JS code I getting an err async function postData(url = '', data = {}) {
    const response = await fetch(url, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            "X-Auth-Token": 'abc'
        },
        body: JSON.stringify(data)
    });
    console.log(response.json());
}

postData('url', { answer: 42 });

Error:
Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body.
at postData (index.js:3:28)
at index.js:14:1

A: As the error pointing out you are using the GET method and you could not add a body to it. If you want to store data I would suggest to use POST
You could read more about the http verbs here


text:
Q: Calculating expectation, infinite fair coins tosses Let's say I am tossing an infinite amount of fair coins independently (one side is $H$, and one side is $T$).
What's the expectation of the number of tosses until I see two following coins such that the first is $H$ and the second is $T$?

A: Use the law of total expectation to solve this question.
$$\mathbb E[\text{#number of tosses}] = P(\text{H throws first})*\mathbb E[\text{T is thrown}+1] + P(\text{T throws first})*\mathbb E[\text{#number of tosses} +1]$$.
Note that the "$+1$" is because of the "turn wasted". The probabiliies we get $H$ or $T$ at the first turn is $0.5$ for each, and the expectation of $T$ is thrown is geometric with $p=0.5$. If we get $T$ at the first turn we need to "start all over again" (but remember we already "wasted" one turn).
Therefore:
(Let us write $\mathbb E[\text{#number of tosses}] = X$)
$$X = 0.5 * (2+1) + 0.5(X + 1)$$
$$ X = 1.5 + 0.5X + 0.5$$
$$0.5X = 2$$
$$ X=4$$

A: In general, for an unfair coin with $P(H)=p$ and $P(T)=q=1-p$  The expected time for getting the sequence "HT" is
$$
\mathbb{E}\{\tau(HT)\} = \frac1{pq}
$$
But, this is the trivial result.  Try the same for "HH" (or "TT") sequences and you'll get surprised.

A: Let $X$ be the number of flips required to observe two consecutive coins $HT$. For any non-negative integer $k$, $X>k$ iff the first $k$ tosses are: $j$ $T$s and then $k-j$ $H$s with $j=0,1,2,\dots,k$. Hence
$$P(X>k)=\frac{k+1}{2^k}$$
which implies that
$$E(X)=\sum_{k\geq 0}P(X>k)=\sum_{k\geq 0}\frac{k+1}{2^k}=\frac{1}{(1-\frac{1}{2})^2}=4.$$


text:
Q: How can one escape dates in ExpressJS to MySQL without messing up the format of the date? I have an API written in express. I am trying to add a simple endpoint with a pretty straightforward query that runs correctly in the MySQL terminal. However, when I pass the query my parameters (start and end dates), the query doesn't work when I send a GET request using Postman. This is where my query is in my API:
var db = require('../../dbconnection');
var PORegister = {
  getPORegister:function(start,end,callback) {
    return db.query("SELECT * FROM purchase_orders WHERE PODate BETWEEN '?' AND '?' ORDER BY PODate DESC",[start,end],callback);
  }
}
module.exports = PORegister;

And here is my routing in Express:
var express = require('express');
var router = express.Router();
var PORegister = require('../../models/reports/PORegister');

router.get('/:start/:end',(req,res,next) => {
  PORegister.getPORegister(req.params.start,req.params.end,(err,rows) => {
    if (err) res.json(err);
    else res.json(rows);
  })
})
module.exports = router;

I have console logged in the routing file and I know that my req.params are coming in formatted as I wish, (YYYY-MM-DD), this is the format which has worked in MySQL for me. Something is going wrong when I pass these parameters into the query and I do not understand what it is.


text:
Q: How to Do MultiDimensional Autocomplete JQuery/Angular Right now I have an autocomplete directive with two types of inputs: a general and a more specific category (e.g. states vs cities, categories of business (retail) vs lines of business (retail banking) etc.)  I have a window that presents cartouches/buttons with all the added elements that are only of the latter, more specific kind (which can then be individually removed.  In other words, whenever a user enters a general category (e.g. "California"), what shows up would be "San Francisco, Los Angeles, Sacramento" which can each be individually removed.
Something like this:

OK, so what I would like is to make the autocomplete reflect this in the obvious way: to present a two-level tree, wherein if the cursor is on the higher branch, all the leaves are highlighted (to reflect that they will all be added), and where the leaves can be individually chosen.
In other words, something very vaguely like the Bootstrap multilevel select, but for autocomplete.
I have read through the Jquery and Bootstrap docs (and obviously many SO posts), and can't find anything that specifically addresses this issue. Is there any plugin out there I am missing?  Or how would I go about hacking into the Jquery autocomplete to create this behavior?  Thanks!

A: I opted to just change the appearance of the dropdown (to include a list of the sub-branches.)  This is done very trivially (as the jQuery docs recommend)
  .data( "ui-autocomplete" )._renderItem = function( ul, item ) {
                //custom redefinition of item.label
                return $( "

" )
                    .data( "item.autocomplete", item )
                    .append( ""+ item.label + "" )
                    .appendTo( ul );
            };


text:
Q: Background colors in Chrome and Atom are no longer uniform Ever since upgrading to macOS Sierra, previously solid background colors in Atom and on certain websites in Chrome are now not uniform. It almost looks like I highlighted stuff with my cursor or something.
It only happens when I plug my mac into an external monitor. If I am working on just my macbook pro screen, everything is normal. When I plug my HDMI into an external monitor, the non-uniform backgrounds start again — including on my macbook pro screen, if mirrored. The HDMI and monitor were checked with other laptops of mine, and the problem never came up. I also tried a different HDMI with the mac, and same problem.
Certain apps like Safari, do not display this problem at all. I've included a screenshot for example:

A: Try disabling hardware acceleration on Chrome settings. Turn off filevault, check for icc color profiles. In utilities > ColorSync and verify to see errors. It's the GPU i guess, Chrome will active the discrete GPU. Atom is a Chrome App (not shure?). Hope it helps. Looking for a better solution too.


text:
Q: jQuery disabling login submit button if username field is empty I am trying to disable the submit button if the username textbox field is empty.
$("#txtUserName").bind("input propertychange change keyup  paste", setButtonState);
var setButtonState = function () {
    if ($("#txtUserName").val().trim() == "") {
        $("#login").attr("disabled", true);
    }
    else {
        $("#login").removeAttr("disabled");
    }
}

The above code is working fine in all scenarios except that,when the user selects username which is saved earlier(autocomplete).
I cannot set the autocomplete off option for the textbox.
How can I catch the event when user selects text in autocomplete usernames?

A: Just bind your input field to the additional event select, which is fired when a user selects something from his autocompletion.
This would be your code then. I just added select and rearranged your code a little bit. Also I run setButtonState() once at the domready to be sure it's disabled.
var setButtonState = function () {
    if ($("#txtUserName").val().trim() == "") {
        $("#login").attr("disabled", true);
    }
    else {
        $("#login").removeAttr("disabled");
    }
}
$("#txtUserName").bind("input propertychange change keyup paste select", setButtonState);
setButtonState();

I have also updated the jsfiddle to demonstrate it.


text:
Q: CodeIgniter pagination returns correct limit, but has same content each page The issue faced by the poster in codeigniter pagination - results remain same on every page is exactly where I find myself currently. Using the following code below, I'm returning a listing of all db table items but only getting the 10 results of the 1st paginated page on every subsequent page;
Articlelist.php (controller)
 //Get Article listing from DB table
 function index($page='')
 {
    $config = array();
    $config['base_url'] = base_url() . 'articlelist/index/';
    $config['total_rows'] = $this->article_model->record_count();
    $config['per_page'] = 10;
    $config['uri_segment'] = 3;

    $this->pagination->initialize($config);

    $page = $this->uri->segment(3);
    $data['results'] = $this->article_model->getList($page * $config['per_page']);
    $data['links'] = $this->pagination->create_links();

    $this->load->view('articles_list', $data);
 }

Article_model.php
//COUNT ALL ARTICLES IN DB TABLE
    function record_count()
    {
      return $this->db->count_all('articles');
    }

    //GET ALL ARTICLES BY ID
    function getList($limit)
    {
       $limit = 10;
       $this->db->limit($limit);
       $query = $this->db->get('articles');

           if($query->num_rows() > 0)
           {
              foreach ($query->result() as $row)
              {
                $data[] = $row;
              }
                return $data;
            }
                return false;
    }

Resulting in the following views (and notice in the URL bar that returned identical results);

....and so on...

...and (annoyingly) so on...

it's annoying simply for the fact that the pagination functionality is delivered without a hitch, and yet, the return of results from the articles DB never deviate from those ten returned results. Is there something I'm missing? Of course the sustained consultation within the 3.0.6 documentation didn't shake loose any insight on my current issue. Stumped...even tried removing the return false; from the end of my function getList, but, to no avail. Trying to remain patient and examine alternate code formatting, but this is the most stable of what was written previously.
And to those who might see something based on the loaded views' foreach;
articles_list.php
<?php
echo '
';
echo '
';
echo '
';
echo '
';

if (!empty($results) && isset($results) && count($results) > 0){
  foreach ($results as $data){
    echo '
Title: <?php echo base_url().'articlelist/view/'.$data->article_id.'">'. $data->title. '
Author: '.$data->name.'
Category: '.$data->category.'
Clicks: '.$data->clicks.'

';
  }
}
else
{
  echo '
No Articles.
';
}
echo '

'.$links.'

';

echo '

';
?>

Hopefully THAT should be enough to go on.
*UPDATE**
I want to thank @pradeep for his efforts, which is helping point me to the possibility that this is a routing-based issue. The route for the article listing page is set as $route['articlelist'] = 'articlelist/index';. My misery index is heightened by the fact that I'm really not shaking much loose consulting the docs and have been ruthlessly searching down other documentation clarification. And to compound all this, the article URL redirection to view the referenced content embedded in the link works flawlessly. And as I'm able to add/edit/delete content, this is the only element sticking in my craw as of present.
An "Oh...My Aching Head" Update
Using the solution proffered by @Sonu Bamniya;
function index()
 {
    $config = array();
    $config['base_url'] = base_url('articlelist/index/');
    $config['total_rows'] = $this->db->get('articles')->num_rows();
    $config['per_page'] = 10;
    $config['uri_segment'] = 3;

    $this->pagination->initialize($config);

    $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
    $data['results'] = $this->article_model->getList($page , $config['per_page']);
    $data['links'] = $this->pagination->create_links();

    $this->load->view('articles_list', $data);
 }

with the end results being;

1st Page Results

2nd Page Results
These results are completely identical to my previous coding further up in the post. I've even gone so far as to re-comb documentation searching for the needle to pierce this ballooning issue.
What am I missing?!?!? (pounds skull)
CAPITULATION
As I have to cede to practicality, for the time being, I'm counting out the totality of the content in the articles table and listing it to the page  without limit (as I don't have thousands of articles at the moment). I'm cutting myself slack by placing a Back To Top link at page bottom. I'm sure I'll have figured out a pagination solution before I get up to over one hundred articles. I'm so sick of wrestling with this, I'm just going to skip it for awhile. ;{

A: its because you are setting $limit = 10; in your model, so limit always updated to 0 to 10;.
change your controller part:
$config['per_page'] = 10;
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data['results'] = $this->article_model->getList($page , $config['per_page']);

and in model fetch data using
function getList($page='0' , $limit='10')
{
 $this->db->limit($limit, $page);
 $query = $this->db->get('articles');

   if($query->num_rows() > 0)
   {
      foreach ($query->result() as $row)
      {
        $data[] = $row;
      }
        return $data;
    }
}

A: $config['use_page_numbers'] = FALSE;
Check this in the config

A: Use POST instead of GET in model and controller.


text:
Q: CSS: Center Element Vertically with Flex and Grid I tried many types of styles and never worked. Margin-top: 10px moves it but not exactly center. I'm using flex within the grid. I tried changing the height and width in certain classes and still didn't work.
**HTML**

home

about

services

**CSS**

:root {
--background-color: black;
--body-color: #fff;
}
body {
margin: 0;
font-family: arial;
color:  var(--body-color);
background: var(--background-color);
}

.navbar {
position: sticky;
}

/*Mobile Nav*/

@media screen and (max-width: 700px) {

.navbar__menu {
display: grid;
grid-template-columns: auto;
}

.navbar__item {
height: 80px;
}

.navbar__links {
display: flex;
background: grey;
height: 20px;
width: 80px;
}

I tried align-items: center, align-self: center, and margin: auto does not work. It's a mix of grid and flex.


text:
Q: Если написать GUI с помощью GPL-библиотеки - будет ли моя программа автоматом gpl и open source? Допустим хочу написать десктопное приложение с графическим интерфейсом НЕ open source. С закрытыми исходниками. Далее встаёт вопрос по поводу соблюдения лицензий:
Qt ныне дико платная либо под GPL и LGPLv3. GTK идёт под LGPL 2.1. JavaFX вообще под GPL v2.0 with Classpath (также не понимаю, что под этим исключением путей понимается).
Т.е. перечисленные библиотеки/фреймворки, как я это понимаю, требуют от тебя, что если твой графический интерфейс написан на них, то твой графический интерфейс (а вместе с ним выходит и вся программа) становятся open source. Прав я или нет?
При этом у LGPL есть пункт, что ты можешь применить LGPL-библиотеку к своей проприетарной программе, прилинковывая её. Но: если твоя программа буквально написана с помощью этой библиотеки, то без этой библиотеки она в принципе работать не будет и линковкой это не назовёшь.
Если всё правильно понимаю, нужно искать библиотеку для написания GUI под лицензией apache 2.0 или MIT/BSD? Или можно использовать в том числе перечисленные выше с соблюдением каких-то условий?

A: Qt стала странной последнее время, но все же. Если не хочется платить, то есть два варианта - GPL - тут да, нужно свои сорцы открывать. Но тут есть один момент. Можно сорцы не открывать "для всех", а только для Ваших пользователей, если они попросят. Но тут много тонкостей. Второй вариант - LGPL. И если отбросить все, то если использовать динамическую линковку (скопировать оригинальные dll/so от компании), то исходники Вашей программы не нужно открывать. С продажами чуточку сложнее, но тоже решаемо. Больше деталей тут https://www.quora.com/What-LGPL-license-mean-and-what-are-the-restrictions-Frameworks-like-QT-and-wxWidgets-are-lincensed-LGPL-Can-I-use-them-to-create-GUI-for-an-commercial-application
Что делать, если хочется использовать GPL,  а код открывать не хочется и иметь поменьше проблем? Вынесите весь свой важный код в отдельную библиотку (dll/so) или даже процесс и общайтесь с ним через сокет/пайп/что то свое. Готово. В этом случае, исходники UI можно выложить на сайте и скорее всего не будет никаких проблем. Более того, другие пользователи даже могут улучшать это все. Приблизительно так поступает NVidia и все ок.

ответ на вопрос в заголовке - да, если Ваша программа использует GPL компонент (линукется с ним), то она должна быть тоже GPL https://www.whitesourcesoftware.com/resources/blog/top-10-gpl-license-questions-answered/ но она не станет автоматом такой (Вам нужно все таки указать это).


text:
Q: How to write select plSQL script by filtering the value in Partition and then subpartition I have a table which has Partitions and subpartitions. I have to first filter the results of Partition's High_Value (TO_DATE(' 2020-03-29 00:00:00', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN')) with less than some date value and then in the result set filter with Subpartion High value with some text value and if the condition satisfy's then drop that sub partition. I have written the code until given below, but not sure how to proceed further. Can someone please help on how to declare d_tmp and then loop through each subpartion and check
DECLARE
CURSOR get_parts IS
select partition_name, high_value
from ALL_TAB_PARTITIONS
where table_name = 'TempTable';
l_tmp LONG;
d_tmp DATE;
BEGIN
  FOR part_rec IN get_parts
  LOOP
    l_tmp := part_rec.high_value;
    EXECUTE IMMEDIATE 'SELECT ' || SUBSTR(l_tmp, 1, 90) || ' FROM DUAL' INTO d_tmp;
    DBMS_OUTPUT.PUT_LINE( to_char(d_tmp, 'DD-MM-YYYY'));

  END LOOP;
END;

A: You are most of the way there. You just loop around the sub partitions for that partition
DECLARE
CURSOR get_parts IS
select partition_name, high_value
from ALL_TAB_PARTITIONS
where table_name = 'TEMPTABLE';
l_tmp LONG;
d_tmp DATE;

l_tmp2 LONG;

BEGIN
  FOR part_rec IN get_parts
  LOOP
    l_tmp := part_rec.high_value;
    EXECUTE IMMEDIATE 'SELECT ' || SUBSTR(l_tmp, 1, 90) || ' FROM DUAL' INTO d_tmp;
    DBMS_OUTPUT.PUT_LINE( to_char(d_tmp, 'DD-MM-YYYY'));

    for i in (
      select subpartition_name, high_value
      from ALL_TAB_SUBPARTITIONS
      where table_name = 'TEMPTABLE'
      and partition_name = get_parts.partition_name
      )
    loop
      l_tmp2 := i.high_value;
      --
      -- your checks
      --
      if [checks passed] then
        execute immediate 'alter table TEMPTABLE drop subpartition '||i.subpartition_name;

    end loop;

  END LOOP;
END;


text:
Q: iOS kAudioFileUnsupportedDataFormatError while creating Audio File for recording I am using ExtAudioFileCreateWithURL and consistently get a runtime kAudioFileUnsupportedDataFormatError error when creating a Stereo LPCM Float32 Wave file. I insist that the same procedure works fine with a Mono (single channel) file. Any hints?
Here's the code snippet:
let audioType: AudioFileTypeID = kAudioFileWAVEType
var recordingFormatStream = CAStreamBasicDescription(sampleRate: sampleRate, numChannels: 2, pcmf: .Float32, isInterleaved: false)!

err = ExtAudioFileCreateWithURL(audioFileRecordingURL,
                                    audioType,
                                    &recordingFormatStream,
                                    nil,
                                    AudioFileFlags.EraseFile.rawValue,
                                    &audioRecordingAudioFile)

noting that audioFileRecordingURL and audioRecordingAudioFile are correctly typed and set.
For the records, the recordingFormatStream contains:
mFormatFlags = kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked | kAudioFormatFlagIsFloat | kAudioFormatFlagIsNonInterleaved
mFormatID = kAudioFormatLinearPCM
mSampleRate: 44100.0
mBytesPerPacket: 4, mFramesPerPacket: 1, mBytesPerFrame: 4, mChannelsPerFrame: 2, mBitsPerChannel: 32, mReserved: 0

I insist that if I change the numChannels to 1, everything is fine! Using iOS 9.3 SDK.

A: After much struggle: The ExtAudioFile methods in SDK do not accept non-interleaved audio. I believe that this is somehow new!
Thanks to this post: Using ExtAudioFileWriteAsync() in callback function. Can't get to run


text:
Q: Another: Object is possibly 'null', why does Typescript 'strictNullChecks' complain in callback? Why does the strictNullChecks rule complain in the forEach callback function? While in the for block it understands that the instance is a string.
class Case {
  instance: string | null = null;

  greeting() {
    this.instance = "Hi there";
    const arr = [1, 2, 3];
    const istance = this.instance;
    arr.forEach(() => {
      // Object is possibly 'null'.
      console.log(this);

      this.instance.charAt(1);
    });

    for (const x of arr) {
      this.instance.charAt(1);
    }
  }
}


text:
Q: Media in CSS are not working with max width I;m trying media query in scss but is not working. I have code like this
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<style>
body {
  background: red;
}

@media (min-width: 460px) {
  body {
    background: yellow;
  }
}
@media (max-width: 459px) {
  body {
    background: black;
  }
}
</style>

now no media query is working for width 459px and background is red... (black is on max 458 and yellow on 460)
but when I changed to
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<style>
body {
  background: red;
}

@media (min-width: 460px) {
  body {
    background: yellow;
  }
}
@media (max-width: 460px) {
  body {
    background: black;
  }
}
</style>

then black background is working for 459px but on 460px two media queries are working...
how to fix that on max-width I will have only black background and on min-width only yellow?

A: I would do it differently: Define a general rule first and then one media query for smaller screens, like this:
body {
  background: yellow;
}

@media (max-width: 460px) {
  body {
    background: black;
  }
}

Or the other way round, using a mobile-first approach:
body {
  background: black;
}

@media (min-width: 460px) {
  body {
    background: yellow;
  }
}

Both ways there is certainly no width where two seetings would collide, and no width where no setting would apply at all.


text:
Q: threads and high level languages can someone tell me why if i use threads it's better to use an low level languages like c++
and not c# and JAVA? someone asked me that in an interview and i did'nt know the answer

A: It's news to me. Higher level languages provide easy to use abstractions over thread management, for example.
I expect the interviewer's point would make sense in context. It's dependent on the problem in hand - the level of timing control you need if you're writing a computer game or software for an engine management system may be greater than if you are writing a conference room booking system.
You trade off the low-level control and the associated learning curve and risk you get with lower-level languages for ease of use, safety and productivity of higher-level languages.

A: I don't think this is necessarily true. In Java (I can't comment on C#) a thread maps directly to a native thread. From here:

The Java HotSpot™ virtual machine
  currently associates each Java thread
  with a unique native thread. The
  relationship between the Java thread
  and the native thread is stable and
  persists for the lifetime of the Java
  thread.

plus you have the additional high level constructs such as the Executor framework.
Going forwards, functional languages (such as F# and Scala) encourage immutability, which contribute to a safer threaded environment.
There may well be scenarios where a low-level language offers more control (as for most requirements), but I suspect those will be fairly specialised situations. You have to balance that against the safety/productivity that the higher-level languages offer.
EDIT : From your comments supplementing the question, this may relate to running a garbage collector and consequent garbage-collection pauses and the impact on providing real-time performance and predictability. Threading in C/C++ may well offer some benefits in this area since a garbage collection cycle is not going to kick off during some critical time-dependent code. For this reason (amongst others) Java can't be considered as a real-time platform.

A: like most answers : it depends.  languages  with built in threading facilities like C# and Java
will do some or most of the work  needed for thread usage and synchronization for you.
with C++ you have  do it yourself but you can employ better optimization techniques for your specific OS and platform

A: Will you use threads or not - depends solely on application, not on language. And language is a function of design.
C++ provides more control, c# provides more abstraction, Java provides simplification, but in the end they all work the same way.


text:
Q: Combine two lists into csv I have two files, a.txt and b.txt. Let's say:
a.txt contains:
123
234
345
456

and b.txt contains:
012
023
034
045

I need to combine them into the following:
123,012
234,023
345,034
456,045

Any idea on how can I do it in basic sh?

A: The simplest would be to use the paste command.
$ paste -d"," a.txt b.txt
123,012
234,023
345,034
456,045

A: As Shawn points out, paste is definitely the correct tool to use.  If you want to do it strictly in the shell:
while read a; read -u 3 b; do echo $a,$b; done < a.txt 3< b.txt


text:
Q: log4net BufferingForwardingAppender appender looks like not working in .net core 2.1 I am doing logging for my .net core console application from log4net. simple RollingFileAppender file logging works. Now i wanted to extend it via bufferforwardingappender but logs not adding in the file.
Please let me know what could be configuration error in my log4net settings
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender" >
    <file value="NetMQBroker" />
    <encoding value="utf-8" />
    <appendToFile value="true" />
    <datePattern value="_yyyyMMdd'.log'" />
    <staticLogFileName value="false" />
    <rollingStyle value="Composite"/>
    <maxSizeRollBackups value="-1"/>
    <maximumFileSize value="10MB"/>
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
    <filter type="log4net.Filter.LevelRangeFilter">
      <acceptOnMatch value="true" />
      <levelMin value="DEBUG" />
      <levelMax value="FATAL" />
    </filter>
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%d{yyyy-MM-dd HH:mm:ss.fff}	%p	AuthCoreApi	%t	%property{Ip}	%property{Context}	%property{ContextId}	%c{1}	%m%n" />
    </layout>
  </appender>
  <appender name="MyBufferingAppender" type="log4net.Appender.BufferingForwardingAppender">
    <bufferSize value="1" />
    <lossy value="true" />
    <appender-ref ref="RollingLogFileAppender" />
  </appender>
  <root>
    <level value="ALL" />
    <appender-ref ref="MyBufferingAppender" />
     <!--<appender-ref ref="RollingLogFileAppender" />-->
  </root>
</log4net>

A: It looks like lossy value is the culprit. have set it to false and logs get output
<lossy value="false" />


text:
Q: ubuntu 12.04 LTS 64-bit for Intel Core 2 Duo laptop? I would like to download ubuntu 12.04 LTS (64-bit). The iso file says "ubuntu-12.040desktop-amd64.iso" will it work with Intel Core2 Duo laptop?

A: All Intel Core 2 Duo and Intel Core i3, i5 and i7 support either 32 Bit or 64 bit. You will not have a problem with this. With what you might have a problem is with the amount of memory you need. For 32 Bit the minimum for a good running system is 512MB, the maximum is 4GB. For 64Bit the minimum recommended is 2GB and the maximum is "let your imagination fly!!!". I have tested 64Bit versions on 1GB and they can run very slow sometimes. The more memory the better.
If your Core 2 Duo laptop has at least 4 GB of ram I would recommend 64 bit but since it is a laptop and the more memory you have in a 64 bit the better, I would recommend sticking with the 32 Bit version. You actually don't loose to try both but for your case I would go more with the 32 Bit version (Except if it is some kind of 4GB+ Ram Laptop).

A: Yes
That is the ISO for the 64bit version. It should work fine

A: If you got at least 2GB of RAM I highly suggest to go for the 64 bit installation. In theory it is faster than the 32 bit version. If you have 4GB or more than it is actually required to use all the available memory.
In the past there were some problems with 64 bit Ubuntu, mainly because lots of applications didn't support 64 bit yet. Nowadays however, the problems are mostly solved and I never experienced any problems running 64 bit Ubuntu.

A: Yes.  I too have a laptop with an Intel Core2 Duo, and that's the file I used; it is running great!  That's the 64-bit version, and despite its name it works on Intel
CPU's as well as on AMDs.

A: I got 3 GB RAM on Core 2 duo laptop (old T61) and running 64-bit 12.04 LTS. It works absolutely fine until you run eclipse and web server.
I am planning to revert to 32-bit.


text:
Q: SSR API cookies set/delete I can pass cookies on ssr in getInitialProps using
req?.headers?.cookie

I can read them in api route, also i can set them if request was not ssr using
res.setHeader('Set-Cookie', ...)
But how to set/delete them if request was from getInitialProps (SSR) in API resolver?
// Api handler
const handler = async (req: NextApiRequest, res: NextApiResponse): Promise<void> => {
  console.log(req.headers.cookie) // works on ssr/client

  res.setHeader('Set-Cookie', ['testSSR2=2; path=/; expires=Thu, 01 Jan 2021 00:00:01 GMT;']) // works on client request only

  res.json({ data: 'test' })
}

A: Ok, this seems to work:
If fetch request was made by server, than we clone (with some parsing) 'Set-Cookie' header to res header.
import fetch from 'isomorphic-unfetch'
import { IncomingMessage, ServerResponse } from 'http'

const payload = (body: any, cookies?: any): object => {
  const headers = {
    Accept: 'application/json',
    'Content-Type': 'application/json',
    cookie: cookies || ''
  }

  return {
    method: 'POST',
    headers,
    credentials: 'same-origin',
    body: JSON.stringify(body)
  }
}

type ApiRes<ExpectedData> = Partial<{ data: ExpectedData }>
type AnyObj = { [key: string]: any }

const fetchAPI = <Body = AnyObj, ExpectedData = AnyObj>(
  apiAction: string,
  body: Body,
  req?: IncomingMessage,
  res?: ServerResponse
): Promise<ApiRes<ExpectedData>> => {
  return new Promise((resolve) => {
    fetch(`mysite/api/some`, payload(body, req?.headers?.cookie))
      .then((raw) => {
        if (req && res) {
          const setCookies = raw.headers.get('Set-Cookie')

          if (setCookies !== null) {
            res.setHeader('Set-Cookie', setCookies.split(';, '))
          }
        }

        return raw.json()
      })
      .then((parsed: ApiRes<ExpectedData>) => resolve(parsed))
      .catch((err) => {
        console.log(err)
      })
  })
}


text:
Q: How to generate numerical relative waveforms representing gravitational wave strain for different masses? I have read in many sources that Numerical relativity produces a general solution for the waveforms which are to be expected by LIGO data to identify the different masses which are observed .
Can anyone tell me how to perform numerical relativity to generate waveforms for any two given set of masses ?

A: There are specialized codes such as the SpEC (and others). The easiest way to learn how to use these would be to join a research program with numerical relativity experts.
There are many precalculated waveforms produced by such codes also available for use such as in the SXS catalog.
In addition, there are many models which can be used to generate gravitational waveforms, which are derived from post-newtonian theory and/or fits to numerical relativity simulations. Many of these can be produced by the PyCBC package. There are some interactive examples that one can try in the browser.


text:
Q: How to copy table to another table? I have a table with 1 000 000 records:
CREATE TABLE [dbo].[x2](
    [session_id] [uniqueidentifier] NOT NULL,
    [node_id] [uniqueidentifier] NOT NULL,
    [id] [int] IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_x2] PRIMARY KEY CLUSTERED
(
    [id] ASC
));

I need to replace the field
[id] [int] IDENTITY(1,1)

with
[id] [bigint] IDENTITY(1,1)

But all data (including id values) should be copied to the new table and id should be IDENTITY but bigint.
I have created the new table
CREATE TABLE [dbo].[x2_new](
    [session_id] [uniqueidentifier] NOT NULL,
    [node_id] [uniqueidentifier] NOT NULL,
    [id] [bigint] IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_x2_new] PRIMARY KEY CLUSTERED
(
    [id] ASC
));

and tried to copy data:
insert into x2_new(session_id,node_id,id)
select session_id,node_id,id from x2;

But it is slow. How to copy data to the new table faster?

A: If both your tables are in same databse, why don't you use Import Data Task feature , select the columns and run the SSIS package immediately..

A: In that case.. you need to do an 'identity_insert OFF' on your destination and insert with your script.. try setting NoLock too.. but is this a one time activity or a repetitive one?


text:
Q: Trying to make a dice roller thats able to roll a die with a specific number of sides a specific number of times via a single input So far, i am using .charAt() to discern the first and 3rd characters in say "1d6", meaning roll a six sided die once. To do this i have made a for loop to use the random class with a range of 1 and the die type (in this case 6), and the loop is supposed to execute it a number of times determined by the input (in this case, 1). Problem is the values im getting are rather random.
import java.util.Scanner;
import java.util.Random;
public class DiceRoller3 {
    public static void main(String[] args) {
    //Creates a new scanner object
    Scanner input = new Scanner(System.in);
    //Creates a new Random object
    Random random = new Random();

    //fluff text
    //System.out.println("What would you like to roll?");

    //Sets dieInput equal to the input the scanner reads.
    String dieInput = input.next();

    //sets noOfDice equal the the first character of the dieInput String
    int noOfDice = dieInput.charAt(0);

    //sets dieType equal to the 3rd character of the dieInput String
    int dieType = dieInput.charAt(2);

    //test to show the value of noOfDice and dieType
    System.out.println(dieInput);
    System.out.println(noOfDice);
    System.out.println(dieType);

    //Loop to roll the die type determined by the input, a number of times
    that is also determined by the input
    for(int x = 1; x <= noOfDice; x++)
    {
        int roll = random.nextInt(dieType) + 1;

        System.out.println(roll);
    }

}

}
When i run this, the the program tells me that the value of noOfDice and dieType are equal to 49 or 50 or some other large number which i'm not understanding why that is the case. the value of dieInput is correct, but when the two characters are read from dieInput they become incorrect. any thoughts on why that could be? as well as any other issues in my code.
Disclaimer: Im rather new to coding, and im trying to do this with what i know (scanner and random for example) i imagine there are more efficient ways to do what i wanna do, but im trying to do it with the tools that i have.

A: Two issues with your code :

*

*Change
// this gets the ASCII value which is why you are getting weird numbers
// ASCII value of 1 is 49
int noOfDice = dieInput.charAt(0);

to
// this gets numeric value of the character
int noOfDice = Character.getNumericValue(dieInput.charAt(0));
int dieType = Character.getNumericValue(dieInput.charAt(2));

*Use this to generate random numbers between 1 and dietype :
int minVal = 1;
int roll = (minVal + random.nextInt(dieType - minVal + 1);

A: With some OOP thinking, I'd write the Dice class. For example:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Dice {

    private static final Random RANDOM = new Random();

    private int sides;

    private Dice(){
        //no Dice constructor without the sides parameter
    }

    public Dice(int sides){
        if (sides <= 0){
            throw new RuntimeException();
        }
        else {
            this.sides = sides;
        }
    }

    public int getSides(){
        return this.sides;
    }

    private int rollMyDice(){
        return  1 + RANDOM.nextInt(this.sides);
    }

    public List<Integer> rollMyDiceManyTimes(int howManyRolling){
        List<Integer> result = new ArrayList<>();
        for (int i = 0; i < howManyRolling; i++){
            result.add(rollMyDice());
        }
        return result;
    }

}

Then, you can test it, (and/or rewrite the code to satisfied your goals):
public class Answer {

    public static void main(String[] args) {

        //test
        Dice dice = new Dice(9);
        System.out.println("I'm rolling the dice with "
                + dice.getSides()
                + " sides "
                + " ELEVEN TIMES "
                + dice.rollMyDiceManyTimes(11));

    }
}

Of course, this is just a template I tried to provide to you...
Some output will be:
I'm rolling the dice with 9 sides  ELEVEN TIMES [9, 4, 5, 2, 8, 7, 3, 8, 2, 1, 4]

A: You want to get the numbers from your string as integers, not chars.  Here is one of many ways
String[] numbers = dieInput.split("d"); // "1d6" split into "1" and "6"
int noOfDie = Integer.parseInt(numbers[0]);
int dieType = Integer.parseInt(numbers[1]);

This will avoid the problem you're running into where you're getting the ascii value (which is also an int) from the char value you're getting back from the string.charAt() method.
Edit:
The numbers array in my snippet represents the result of the split input.  Based on the expected input of two numbers separated by a d such as 1d6 or 3d10, the result would be an array with 2 items in it, the number before the d and the number after it.  If, for example, you called the split method and the input string had multiple d characters, you'd get a bigger array.  For example, 1d6d7 would result in an array with 3 items in it, "1", "6" and "7".  Even though the contents are of type string, I contextually expect them their values to be numbers.  Which is why in the following lines Integer.parseInt() is used to convert the value from a String to an int.  This only works when the value of the string is a valid int.


text:
Q: MathJax with Node partials I'm using Node and Express with MathJax to make a comment system with TeX. The problem is, the TeX is only rendered when the page first loads, or when I refresh the page, but does not load when rendering a partial. Any advice?
Thanks.

A: See the MathJax documentation on dynamic pages, which will suggest that you use
MathJax.Hub.Queue(["Typeset",MathJax.Hub]);

after adding math to the page.
Also, you could check out the MathJax-node project, which implements APIs for interacting with MathJax through node.js programs.


text:
Q: firebase.auth.GoogleAuthProvider.credential is undefined Authenticate Using Google Sign-In
I'm using Firebase to Sign in a user using Advanced: Handle the sign-in flow  manually. I have set up Firebase like so:
firebaseConfig.js
// Config file
import * as firebase from "firebase";

const config = {
      apiKey: "api-key",
      authDomain: "project-id.firebaseapp.com",
      databaseURL: "https://project-id.firebaseio.com",
      projectId: "project-id",
      storageBucket: "project-id.appspot.com",
      messagingSenderId: "sender-id",
      appId: "app-id",
      measurementId: "G-measurement-id",

};

export default !firebase.apps.length ? firebase.initializeApp(config) : firebase.app();

I then import firebase in another file to authenticate and sign in a user.
LoginUser.js
_isUserEqual = (googleUser, firebaseUser) => {
        if (firebaseUser) {
          var providerData = firebaseUser.providerData;
          for (var i = 0; i < providerData.length; i++) {
            if (providerData[i].providerId === firebase.auth.GoogleAuthProvider.PROVIDER_ID &&
                providerData[i].uid === googleUser.getBasicProfile().getId()) {
              // We don't need to reauth the Firebase connection.
              return true;
            }
          }
        }
        return false;
      }

    _onSignIn = googleUser => {
        console.log('Google Auth Response', googleUser);
        // We need to register an Observer on Firebase Auth to make sure auth is initialized.
        var unsubscribe = firebase.auth().onAuthStateChanged(firebaseUser => {
          unsubscribe();
          // Check if we are already signed-in Firebase with the correct user.
          if (!this._isUserEqual(googleUser, firebaseUser)) {
            // Build Firebase credential with the Google ID token.
            var credential = firebase.auth.GoogleAuthProvider.credential(
                googleUser.idToken,
                googleUser.accessToken
            );
            // Sign in with credential from the Google user.
            firebase.auth().signInWithCredential(credential).catch(error => {
              // Handle Errors here.
              var errorCode = error.code;
              var errorMessage = error.message;
              // The email of the user's account used.
              var email = error.email;
              // The firebase.auth.AuthCredential type that was used.
              var credential = error.credential;
              // ...
            });
          } else {
            console.log('User already signed-in Firebase.');
          }
        });
      }

_signInWithGoogleAsync = async () => {
        try {
          const result = await Google.logInAsync({
            androidClientId: "AndroidClientId",
            scopes: ['profile', 'email'],
          });

          if (result.type === 'success') {
            this._onSignIn(result)
            return result.accessToken;
          } else {
            return { cancelled: true };
          }
        } catch (e) {
          return { error: true };
        }
      }

When I execute the authentication, I receive an error:
Possible unhandled Promise Rejection (id: 0):
TypeError: undefined is not an object (evaluating '_firebaseConfig.default.GoogleAuthProvider.credential') showing that firebase.auth.GoogleAuthProvider is undefined.
Screenshot of the error
Are there any reasons as to why this could be the case? Thanks.


text:
Q: How to Assert or Verify Multiple Required Error message at the time on selenium webdriver Problem Description:
I want to verify a Blank Input field Required Error message should be displayed or not. Example like that.
I have Web Element

First Name is required

Last Name is required

Phone Name is required

These Error message I want to verify at the time all message assert or not.
Can you please help me how to assert all error message at the time using selenium web driver.

A: If you want to test all assert at once then you have to add softAssert in your code this will give you final results after check all the fields.
If not when assert failed happens (Assume First name error is invalid) system will throw assertion error after it.
        SoftAssert softAssert = new SoftAssert();
        String ActualErrorMEssage = firstNameerrorXpath.getText;
        String ActualErrorMEssage2 = secondNameNameerrorXpath.getText;
        softAssert.assertEquals(ActualErrorMEssage,ExpectedErrorMEssage);
        softAssert.assertEquals(ActualErrorMEssage2,ExpectedErrorMEssage);
        softAssert.assertAll();

A: If you can see all the error messages, when you don't enter anything into the text boxes and click on submit or register, you can get text of all this error messages and assert them.
But, if your website functionality is like let's say when you don't enter anything it shows only error for the first name field and all the other UI error's are not being shown, then you can't verify all the error messages at a time.
If all the error messages are shown at once, you can take them into a arraylist and by using Assert.assertEquals(expectedArray,actualArray), you can assert everything at once.


text:
Q: Convert a series of character of different single quotes to nvarchar I am working on an SQL query which uses multiple queries which use temp tables to prepare required data to the final report query. An application which uses DevExpress reporting engine, generates a "where" clause automatically according to some pre-settings. The result of the desired filter is something like this:
-- the part "where 1=1" is not generated. it is added for the purpose of visualizing and demonstrating
where 1=1  AND (@inv IN(4)) AND (@date = convert(datetime, '2021-02-21 23:59:59:000', 121) )

I would like to convert the generated filter into a nvarchar for farther string process, but the single quote in the convert function for the date will always ruin any trial of surrounding the statements with single quote(s) for escaping.
so my question is, considering that I have a statement like:
AND (@para1 IN(4)) AND (@date = convert(datetime, '2021-02-21 23:59:59:000', 121) )

how could I deal with it as string of type nvarchar using SQL Server for farther parsing?
knowing that I have no control over the code of the application which generates the filter string
Edit2:
Additionally knowing that adding quotes is only allowed at the beginning and end only,
and the Application which generates the filters is a compiled app. The app takes the original SQL query with a placeholder {0} to fill up the generated filters. Unfortunately, the app does not allow using next placeholder which should be {1}, so I am stuck to use the whole filter string using placeholder {0} only. So, If there is something in SQL or idea that could convert the generated filter string mentioned above to an nvarchar, so that I could write a function to take the values of each filter and reuse them into my SQL query


text:
Q: Prove that $A^t$ complex matrix is unitary. Let $V$ be a vector space over field $\mathbb{C}$ with scalar product $\langle,\rangle$, in which $v\in V$. Let $A$ be an unitary complex matrix, so that $\langle Av,Av\rangle=\langle v,v\rangle$. Is it true $\bar A=A?$
I know $\langle Av,Av\rangle=\langle v,\bar A^tAv\rangle$, so I can infer $\bar A^tA=I$. Therefore $A^{-1}=\bar A^t\implies(A^{-1})^{-1}=(\bar A^t)^{-1}\implies$...The problem rises because I cannot eliminate $t$, since it is not true that only the transpose is the inverse.
However in exercises:

Let A be a complex unitary matrix.
(a) Show that $A^t$ is unitary.

Real case:
$(A^t)^t=A=(A^t)^{-1}$
I tried to solve it as for the real matrix:
Complex case:
$\overline{(A^t)^t}=\bar A=?$ I cannot complete it because of the conjugate
Question:
How can I prove complex matrix $A^t$ is unitary?
Thanks in advance!

A: The matrix $A$ is unitary if and only if its inverse is $\overline A^t$. And if $\overline A^t$ is unitary, then its conjugate (which is $A^t$) is unitary too.

A: Hint: It is useful to note that with matrix multiplication (just as with scalar multiplication), we have $\overline{AB}= \bar A \bar B$.


text:
Q: Use Proguard 5.3 ,default type methods change to public type I want to develop a private SDK(a jar file),some method is default permission,i want it can be called in current package only,like this:
  /* package */
static String getApplicationId() {
    return mApplicationId;
}

but,when use proguard to make jar later,this method change to public type,and the method name like this:
public static String c() {
    return sApplicationId;
}

so i want know how to config proguard file.to make default permission method can't visiable when use this jar by proguard later,thanks

A: You should check your configuration, most likely you have the following setting enabled:
-allowaccessmodification

When obfuscating a library, you normally do not want this enabled, as you experience the effects as described in the question.


text:
Q: MySQL & Basic Maths in PHP Is it possible to call, say;
$timestamp = 1392444177;
$response = $db->prepare("SELECT * FROM carts WHERE timestamp<:timestamp");
$response->execute(array(':timestamp' => $timestamp));
$result = $response->fetchAll(PDO::FETCH_ARRAY);
var_dump($result);

Notice the use of the less than symbol? How could I best perform this? The datatype of column 'timestamp' is currently INT(40).


text:
Q: Is it true that $\inf\{\|x+y\|:x\in X, y\in Y\}\le\inf\{\|x\| +\|y\|:x,y\in X\}$? Let $(X,\|\cdot\|)$ be a normed space. Is it true that $\inf\{\|x+y\|:x,y\in X\}\le\inf\{\|x\| +\|y\|:x,y\in X\}$?
I need it in order to finish a proof. It seems easy, but I don't see the proof. Could anyone please help?

A: Let $\nu=\inf \{\|x+y\|:x,y\in X\}$ and pick $x,y\in X$ arbitrary. Then $$\nu\leq \|x+y\|\leq \|x\|+\|y\|$$ This shows $\nu$ is a lower bound of $\{\|x\|+\|y\|:x,y\in X\}$. Therefore $$\nu \leq \inf \{\|x\|+\|y\|:x,y\in X\}$$ and we're done.