text:
Q: Uncertain how to properly filter when certain fields do not always exist I am trying to filter based on a field that, on some objects, does not exist. I was under the impression that ES would match objects that don't have that field.
Ultimately, I am trying to filter as such:

*

*Field A will always exist, and should match on any of tags 1,2,3

*When it exists, either Field B or C must match any of tags 5,6,7

*When it exists, Field B must match any of tags 10, 11, 12

*When it exists, Field B or C must NOT have any of tags 15, 16, 18.

In this case, all my tags are strings. In addition, fields B and C are inside of another. I am uncertain if that matters.
Essentially, my object is:
{ a: ["some", "tags", "here"],
    X : {
        B: ["more", "tags", "here"],
        C: ["even", "more", "here"]
    }
}

I am trying to essentially build a whitelist and blacklist filtering system.
However, when filtering this way, I do not get any results that do not contain the field.
How do I properly format this filter?

A: Elasticsearch treats a null or non-existing field as not matching a query/filter on that field, so those results will not be returned by a standard query/filter. However, it is possible to set up a query that accomplishes what you are wanting, if I'm understanding you correctly. You can use a combination of "or", "not", and "exist" filters. I'll show you the basic idea with a few examples.
First, create an index and add some docs, with various fields missing from various docs:
curl -XPUT "http://localhost:9200/test_index"

curl -XPUT "http://localhost:9200/test_index/docs/1" -d'
{
    "a": ["some", "tags", "here"],
    "X" : {
        "B": ["more", "tags", "here"],
        "C": ["even", "more", "here"]
    }
}'

curl -XPUT "http://localhost:9200/test_index/docs/2" -d'
{
    "a": ["some", "tags", "here"]
}'

curl -XPUT "http://localhost:9200/test_index/docs/3" -d'
{
    "a": ["some", "tags", "here"],
    "X" : {
        "B": ["more", "tags", "here"]
    }
}'

curl -XPUT "http://localhost:9200/test_index/docs/4" -d'
{
    "a": ["some", "tags", "here"],
    "X" : {
        "C": ["even", "more", "here"]
    }
}'

If I want to retrieve the docs that contain the field "X.B" (with any value), I can use the following query:
curl -XPOST "http://localhost:9200/test_index/docs/_search" -d'
{
   "query": {
      "filtered": {
         "query": {
            "match_all": {}
         },
         "filter": {
             "exists": {
                "field": "X.B"
             }
         }
      }
   }
}'

This will return docs "1" and "3".
On the other hand, if I want to return only the docs that do NOT have the field "X.B", then I can use this query:
curl -XPOST "http://localhost:9200/test_index/docs/_search" -d'
{
   "query": {
      "filtered": {
         "query": {
            "match_all": {}
         },
         "filter": {
            "not": {
               "filter": {
                  "exists": {
                     "field": "X.B"
                  }
               }
            }
         }
      }
   }
}'

This returns docs "2" and "4".
Now, if I want to return docs that either do not have the field "X.B", or that field matches the term "here", you can use an "or" filter as follows:
curl -XPOST "http://localhost:9200/test_index/docs/_search" -d'
{
   "query": {
      "filtered": {
         "query": {
            "match_all": {}
         },
         "filter": {
            "or": [
               {
                  "term": { "X.B" : "here" }
               },
               {
                  "not": {
                     "filter": {
                        "exists": {
                           "field": "X.B"
                        }
                     }
                  }
               }
            ]
         }
      }
   }
}'

In this case all four docs are returned, because they all match one of the two possible conditions.
This doesn't completely satisfy your use-case, but it should be enough to get you started.
Here is a runnable example you can play with (you will need ES installed and running at localhost:9200, or supply another endpoint):
http://sense.qbox.io/gist/f1a644db97c89996f2b44f49793a2c76bae3155c

A: The problem is not what you think it is. Or at least, there is another problem too. The difference you are seeing is due to how "relatedProfiles" is being analyzed.
Look at this gist: http://sense.qbox.io/gist/eec5dc038167ddd5d845a8ea8413a065f6e63f8f. I've defined the index in two different ways, the first (testfeed1) implicitly, and the second (testfeed2) with your explicit mapping. It's instructive to remove all but the first part of your query and run it against each index:
When I build the index the first way (no explicit mapping), and then search with only the filter on "relatedProfiles" : ["LinkedIn/4505"], I don't get a result:
curl -XPOST "http://localhost:9200/testfeed1/feedItem/_search" -d'
{
   "query": {
      "match_all": {}
   },
   "filter": {
      "terms": {
         "relatedProfiles": [
            "LinkedIn/4505"
         ]
      }
   }
}'

...
{
   "took": 2,
   "timed_out": false,
   "_shards": {
      "total": 2,
      "successful": 2,
      "failed": 0
   },
   "hits": {
      "total": 0,
      "max_score": null,
      "hits": []
   }
}

When I build the index the second way, with an explicit mapping (in which "relatedProfiles" is set to "index": "not_analyzed"), and then do the same search, I do get a result:
POST /testfeed2/feedItem/_search
{
   "query": {
      "match_all": {}
   },
   "filter": {
      "terms": {
         "relatedProfiles": [
            "LinkedIn/4505"
         ]
      }
   }
}

...
{
   "took": 1,
   "timed_out": false,
   "_shards": {
      "total": 2,
      "successful": 2,
      "failed": 0
   },
   "hits": {
      "total": 1,
      "max_score": 1,
      "hits": [
         {
            "_index": "testfeed2",
            "_type": "feedItem",
            "_id": "Metabase/16411941826",
            "_score": 1,
            "_source": {
               "source": "Metabase/16411941826",
               "relatedProfiles": [
                  "LinkedIn/4505",
                  "Facebook/113470526913",
                  "CrunchBase/company/scholastic"
               ],
               "timestamp": "2014-01-08T00:49:35-05:00",
               "type": "News",
               "content": {
                  "title": "Opening doors for children, teachers",
                  "description": "class became published authors, chosen to put together the Florida section of "Fifty Great States Scrapbook," published by Scholastic Books. Their book signing was at Barnes & Noble. "I saw an advertisement in the instructor magazine and decided to",
                  "url": "http://ct.moreover.com/ct?haid=8437fcfcdbaa900a138916017501692f42b5c333349b4&co=f000000011632s-1177024037&u1=SET&u2=56637",
                  "source": "St Augustine Herald"
               },
               "language": "en"
            }
         }
      ]
   }
}

The difference is in how the "relatedProfiles" field is analyzed. In the second case, it isn't analyzed at all, so "LinkedIn/4505" matches exactly, and the result is returned. In the first case, though, since no analyzer is specified the standard analyzer is used. And so the tokens end up being "linkedin" and "4505" (as you can see if you search for those tokens, like line 34 of the gist). Since we are using a terms filter in the above query, no analysis is done on the filter terms text, and "LinkedIn/4505" doesn't match any tokens, so no results are returned.
Make sense?


text:
Q: Android 3D Carousel integration to my application in android I am new to Android Programming.I integrate the Android 3D Carousel app into my application using following link
http://www.codeproject.com/Articles/146145/Android-3D-Carousel
It works fine.
But my requirement is instead of I need to place the multiple buttons as one view as shown in attached screen shot.
Please suggest me how can I proceed?
Thanks in
advance

A: Before asking anything have you tried anything first. Can you post the code you tried and from there we can move forward

A: write your adapter like this
package com.example.uitest;

import java.util.ArrayList;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Toast;

public class  CarouselAdapter  extends BaseAdapter {

    private ArrayList<String> array;
    private Activity mContext;

    LayoutInflater inflator=null;
    public CarouselAdapter(Activity context,ArrayList<String>array) {
        mContext = context;
        this.array=array;
    }

    /*public void setData(ArrayList<Integer> data) {
        mData = data;
    }*/

    @Override
    public int getCount() {
        return array.size();
    }

    @Override
    public Object getItem(int pos) {
        return array.get(pos);
    }

    @Override
    public long getItemId(int pos) {
        return pos;
    }

    @Override
    public View getView(int arg0, View convertview, ViewGroup arg2) {
        if(convertview==null)
        {
            ViewHolder holder=new ViewHolder();
            convertview=mContext.getLayoutInflater().inflate(R.layout.carousellayout,null);
            holder.btn1=(Button)convertview.findViewById(R.id.button1);
            holder.btn2=(Button)convertview.findViewById(R.id.button2);
            holder.btn3=(Button)convertview.findViewById(R.id.button3);
            holder.btn4=(Button)convertview.findViewById(R.id.button4);
            convertview.setTag(holder);
        }
        ViewHolder hold=(ViewHolder)convertview.getTag();
        hold.btn1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Toast.makeText(mContext, "Clicked on button 1", Toast.LENGTH_SHORT).show();
            }
        });
        hold.btn2.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Toast.makeText(mContext, "Clicked on button 2", Toast.LENGTH_SHORT).show();
            }
        });
        hold.btn3.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Toast.makeText(mContext, "Clicked on button 3", Toast.LENGTH_SHORT).show();
            }
        });
        hold.btn4.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Toast.makeText(mContext, "Clicked on button 4", Toast.LENGTH_SHORT).show();
            }
        });

        return convertview;
    }

    static class ViewHolder
    {
        Button btn1,btn2,btn3,btn4;
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: create a new dataframe column using the data from other column on condition I have a data frame that looks like this
    Name        Default Expression    Override Expression
0   AACT_NAM        pystr                   pyint
1   ACCT_CCY        pystr
2   ACCT_TYP        pystr

I want to create a column, _faker_method_ that would contain specially transformed data by checking if Override Expression has value and use it, if there is some value or
use Default Expression column if there is no value.
I tried to do like this
df['_faker_invocation_'] = df['Override Expression'].apply(lambda x: render_faker_expresison(df['Name'], x) if x else df['Default Expression'])

But logs should me that the function render_faker_expression recieves whole column with index (and thus it fails in my app)
0                           ACCT_NAM
1                           ACCT_CCY
2                           ACCT_TYP

How to perform the action I need?

A: You're not sharing render_faker_expression (or at least its signature) which makes it hard to pin down the problem. But since it seems to expect a scalar value instead of a series, I guess you want to apply your lambda function row-wise:
df['_faker_invocation_'] = df.apply(lambda row: render_faker_expresison(row['Name'], row['Override Expression'])
                                                if row['Override Expression']
                                                else row['Default Expression'], axis=1)

With the following dummy function:
def render_faker_expresison(n, x):
    return x + "_fake_" + n

This gives us:
        Name Default Expression Override Expression   _faker_invocation_
ID
0   AACT_NAM              pystr               pyint  pyint_fake_AACT_NAM
1   ACCT_CCY              pystr                None                pystr
2   ACCT_TYP              pystr                None                pystr


text:
Q: Open Sharepoint folder with windows explorer from CRM 2011 I've been struggling with this issue for a while now,
and hope maybe someone in the community can provide a resolution.
I have a requirement which is to put a button on the a CRM account form which will have the same logic as the Open With Explorer button in a Sharepoint document library. The logic is required as the users have to do several click in order to get to this button, and open the required account's folder in windows explorer, which are:

*

*Click Documents in navigation of the form, to open SP integration

*Click documents in the SP view

*Click library

*Click the Open With Explorer button

The CRM is integrated with Sharepoint, and when the folder is opened in windows explorer it has the following sample link
http://{sharepoint}/CRM/7F9F72A1-4591-E011-AC6C-00155D773703/Documents/
Where the GUID 7F9F72A1-4591-E011-AC6C-00155D773703, is the account id in CRM.
From my research i have found that the javascript function that achieves this is
NavigateHttpFolder from the sp.js in Sharepoint.
From this function, and this link About Web Folder Behaviors
I've completed the following function.
var httpFolderDiv = document.createElement("SPAN");

function NavigateToFolder() {

    document.body.appendChild(httpFolderDiv);
    httpFolderDiv.onreadystatechange = NavigateToFolder;
    httpFolderDiv.id = "navDiv";
    httpFolderDiv.addBehavior("#default#httpFolder");
    if (httpFolderDiv.readyState == "complete") {
        httpFolderDiv.onreadystatechange = null;
        var link = "";
        var account = "";
        var accountid = "";
        var id = Xrm.Page.data.entity.getId().replace("{", "").replace("}", "");
        link = "http://{sharepoint}/CRM/" + id + "/Documents/";

        try {
             httpFolderDiv.navigateFrame(link, "_blank");
        } catch (c) {
            alert(c.toString());
        }

    }
}

This function opens up the folder from Sharepoint in windows explorer, but with limitation if only that folder was previously opened directly from Sharepoint.
I believe that the logic I am missing in the code, is that I don't do mapping of the folder, the way sharepoint does.
I am aware that this folder can be mapped manually as a network drive, Connecting WebDAV Server Using Web folders, but this will not do the trick for me as this will have to be done on every client.
How can I achieve this by grabbing the complete logic from SP, or maybe running a console command from javascript to map the folder prior to opening it with the above function.

A: I know it's been a while, since this has been posted, but I stumbled upon it while searching for the exact same problem.
Here's what worked for me in SharePoint 2013:
<a href='#' onClick="javascript:CoreInvoke('NavigateHttpFolder', '[path to site]/[library name]/', '_blank');">
Click to open in Explorer
</a>

It's essentially the same function used by SharePoints own functionality.


text:
Q: How can I use my own customID as id for ForEach in indices mode in SwiftUI? I made a CustomStruct which it makes own customID, I could use this customID as id for ForEach in  item mode, then I tried to use my own customID as id for ForEach in indices mode, but it gives error, It says Int has no member of customID, which my all reason of making customID was and is to not using Int as id, but using my own customID. How could I solve this issue?
    struct ContentView: View {

    @State var arrayOfCustomStruct: [CustomStruct] = [CustomStruct]()

    var body: some View {

        Spacer()

//        VStack {
//
//            ForEach (arrayOfCustomStruct, id: \.customID) { item in
//
//                Text( String(item.customID) )
//
//            }
//
//        }

        VStack {

            ForEach (arrayOfCustomStruct.indices, id:\.self) { index in // << here I want this happen: ----->  id: \.customID

                Text( String(arrayOfCustomStruct[index].customID) )

            }

        }

        Spacer()

        HStack {

            Spacer()

            Button("add new item") {

                arrayOfCustomStruct.append( CustomStruct(name: "New Item")   )

            }

            Spacer()

            Button("remove an item") {

                if arrayOfCustomStruct.count > 0 {
                    arrayOfCustomStruct.remove(at: arrayOfCustomStruct.count-1 )
                }

            }

            Spacer()

        }.padding()

    }
}

struct CustomStruct {

    init(name: String) {
        CustomStruct.indexOfId += 1
        self.name = name
    }

    private static var indexOfId: UInt64 = 0
    let customID: UInt64 = CustomStruct.indexOfId
    var name: String

}

Update: customID in Int has completely deferent personality than customID in CustomStruct! It is NOT perfect as CustomStruct.
    extension Int {

    private static var indexOfId: Int = -1
    var customID: Int {

        Int.indexOfId += 1
        return Int.indexOfId
    }

}

A: If you want to have both indices and id by item, you can use enumerated, like
ForEach (Array(arrayOfCustomStruct.enumerated()), id:\.1.customID) { index, item in

    Text( String(arrayOfCustomStruct[index].customID) )

}


text:
Q: como medir a velocidade no tráfego da banda larga móvel no 3g ou no wifi do celular programaticamente no iphone No app, já estou fazendo a coleta do tráfego no iphone, agora preciso verificar como medir a velocidade no tráfego da banda larga móvel no 3g ou no wifi do celular programaticamente.
Por exemplo:
A cada 1 minuto ou 10 minutos, ou mais, preciso saber qual é a velocidade média que os dados estão sendo entregues tanto para download ou upload, tanto pela rede wifi quanto pela rede 3g/4g do celular.
Por favor, alguém sabe como fazer isso no iphone?


text:
Q: what's the use of transformer_weights in scikit-learn pipeline? It's just a little question of scikit-learn's pipeline.
In the class sklearn.pipeline.FeatureUnion , there is a transformer_weights option .

transformer_weights: dict, optional
  :    Multiplicative weights for features per transformer. Keys are transformer names, values the weights.

I saw the use in an example that give different weight to different feature.
    transformer_weights={
        'subject': 0.8,
        'body_bow': 0.5,
        'body_stats': 1.0,
    },

It's nonsense to me, because the classifier will learn the weighting for you later. Why bother using it at all?

A: If you use a linear classifier with penalty, this will change the amount of penalty applied to each block of features.
Scaling features up will mean they will be less penalized relative to the other features.


text:
Q: From ArrayFire to OpenGL on AMD? Is it possible to go from ArrayFire to OpenGL and back using an AMD graphics card?
There is an article on how to do it using CUDA. Any hints on using a similar method for OpenCL, so it can be used cross-platform?
Update
What I would like to do in the end is take an af::array, convert it to an OpenGL texture and render it with my custom shader to the screen or to another texture (assuming a given OpenGL context, for example from Qt).

A: As far as I know, the OpenGL-OpenCL interop via cl_khr_gl_sharing is not supported by the newest ArrayFire (at least for Intel graphic cards (Iris and so on)).
For me it looks like the cl_khr_gl_sharing is generally not supported by ArrayFire.

A: This is not possible so far. There is a github issue on the official bugtracker, though.


text:
Q: XML pulled into dataset excludes some elements Here's the code I'm using to pull the xml from a webservice:
 string ServerURl = "xxX"
 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ServerURl);
 request.ContentType = "application/xml+atom";
 request.Credentials = CredentialCache.DefaultCredentials;
 HttpWebResponse response = (HttpWebResponse)request.GetResponse();
 var datastream = response.GetResponseStream();
 XmlReader reader = XmlReader.Create(datastream);
 ds.ReadXml(reader);

There are two types of elements that get returned formatted like:
<m:table>
   <d:Identification m:type="Edm.Int32">12346</d:Identification>
   <d:EmployeePhone m:type="Edm.Int32">123456</d:EmployeePhone>
   <d:EmployeeName>Joe Doe</d:EmployeeName>

I noticed all the rows with the m:type don't get returned, how do I include those as well?


text:
Q: How to release or distribute an application that uses mikro-orm? In the configuration I have to specify the paths to .js and .ts files defining entities:
MikroORM.init({
    ...
    entitiesDirs: ["build/entities"],
    entitiesDirsTs: ["src/entities"],
});

So, when I will go to release or distribute the application. Will I need distribute the typescript code too? or will I need distribute only the cache generated? or will I need distribute both? or... none?

A: As of MikroORM v2.2
Now you can work with default metadata provider, it will require entity source files only if you do not provide entity or type options in your decorators (you can use entity callback to use reference to entity class instead of using string name in type, handle for refactoring via IDE like webstorm).
Original answer:
You should ship the typescript code too, and let the cache regenerate on the server - cache would be rebuilt anyway as it checks absolute path to cached entity for invalidation.
You could implement your own cache adapter or metadata provider to get around this, if you don't want to ship the typescript code.
This is how you could implement custom metadata provider that simply throws error when the type option is missing:
import { MetadataProvider, Utils } from 'mikro-orm';
import { EntityMetadata } from 'mikro-orm/dist/decorators';

export class SimpleMetadataProvider extends MetadataProvider {

  async loadEntityMetadata(meta: EntityMetadata, name: string): Promise<void> {
    // init types and column names
    Object.values(meta.properties).forEach(prop => {
      if (prop.entity) {
        prop.type = Utils.className(prop.entity());
      } else if (!prop.type) {
        throw new Error(`type is missing for ${meta.name}.${prop.name}`)
      }
    });
  }

}

Then provide this class when initializing:
const orm = await MikroORM.init({
  // ...
  metadataProvider: SimpleMetadataProvider,
});

The value of type should be JS types, like string/number/Date... You can observe your cached metadata to be sure what values should be there.
Also keep in mind that without TS metadata provider, you will need to specify entity type in @ManyToOne decorator too (either via entity callback, or as a string via type).


text:
Q: Compare dates of an array using moment or dayjs library in javascript I need to compare the date values of an array.
I will always get two dates values in array. If date range is not in between 5 years need to display error message.
filterAry = [
  {type: 'date', name: 'fromDate',  value:['15/02/2017']},
  {type: 'date', name: 'toDate',  value:['15/02/2023']},
  {type: 'string', name: 'code',  value:'new role'}
];

I am trying moment to get the difference between two dates also filtering the array values based on type='date' first.
filterAry.forEach(item => {
    if (item.type === 'date') {
        if(item.name === 'fromDate'){
                date1 = moment(item.value[0],'DD/MM/YYYY')
         }
         else{
                date2 = moment(item.value[0],'DD/MM/YYYY');
         }
         if(date1 && date2){
                dateVal3 = date2.diff(date1, 'years');
         }
}

My code is not working and also I am not sure how to write the code without hard coded values.I need difference of the to and from dates and if it is greater than 5 years should display error message. Kindly help me how to achieve this.

A: i think the problem begin from the fact that that you're doing assignments and comparing values inside the foreach, try to deconstruct it a bit and use maybe something like Array.filter to filter down the initial array and map to get the values extracted like this:

  const filterAry = [
    { type: 'date', name: 'fromDate',  value:['15/02/2017'] },
    { type: 'date', name: 'toDate',  value:['15/02/2023'] },
    { type: 'string', name: 'code',  value:'new role' }
  ]
  // find the elements that contains dates
  const dates = filterAry.filter((el) => el.type === 'date')

  // store them as regular values instead of arrays with 1 cell
  const [dateStart, dateEnd] = dates.map((el) => moment(el.value[0], 'DD/MM/YYYY'))
  // calculate year diff
  const yearDiff = moment(dateEnd).diff(dateStart, 'years')

  console.log(yearDiff) // 6

A: You can use Array.prototype.reduce to loop over the values in the array to find the to and from dates, then test them. You can also use Array.prototype.some, but it needs to be wrapped in a function to store interim results so is more-or-less the same as reduce anyway.
However, for large arrays some may have performance advantages as it can exit as soon as it's found toDate and fromDate. The below reduce example optimised a bit so that if the result true or false has already been calculated it just skips to the next value, but it will still iterate over all elements in the array.

// Helpers
// Parse dd/mm/yyyy format timestamp
function parseDMY(s) {
  let [D,M,Y] = s.split(/\D/);
  return new Date(Y, M-1, D);
}

// Add years to a date
function addYears(years, date = new Date()) {
  let d = new Date(date);
  d.setFullYear(d.getFullYear() + 5);
  // If date was 29 Feb, make d 28 Feb not 1 Mar
  if (d.getDate() != date.getDate()) {
    d.setDate(0)
  }
  return d;
}

// Sample data
let arr = [
  {type: 'date', name: 'fromDate',  value:['15/02/2017']},
  {type: 'date', name: 'toDate',  value:['15/02/2023']},
  {type: 'string', name: 'code',  value:'new role'}
];

// Test if toDate and fromDate are within 5 years
// result is true if they're within 5 years
let result = arr.reduce((acc, obj) => {
  if (acc !== true && acc !== false) {
    if (obj.type = 'date') {
      acc[obj.name] = parseDMY(obj.value[0]);
    }
    if (acc.fromDate && acc.toDate) {
      acc = acc.toDate < addYears(5, acc.fromDate);
    }
  }
  return acc;
}, Object.create(null));

console.log(result); // false

The above has no error handling or exception management, that should be added.


text:
Q: What fs-type should I use in parted when creating an exFAT partition? When I try to create a partition with parted and a filesystem type of 'exFAT', I encounter the following error:
parted: invalid token: exFAT
What fs-type should I use when creating a partition destined for an exFAT filesystem?
Thanks!

A: NTFS
I discovered the answer in the man page for the mkfs.exfat utility, which states:
Note that if this is an MBR partition then the file system type should be set to 0x07 (NTFS/exFAT) otherwise other operating systems may refuse to mount the file system.
In parted, this is accomplished with the 'NTFS' fs-type.

A: 0x07 when using fdisk.
You can list all supported partitions type with the command: l


text:
Q: Pass a closure capturing constructor argument to base class constructor I want to derive a class from System.IO.BinaryWriter, and call it's constructor with a custom Stream, an implementation of which captures a constructor argument of the derived type. For the life of me, I cannot figure out whether even this is possible at all. What I am essentially trying to do, slightly trimmed to be an MCV, is
type HashingBinaryWriter private
     (hasher   : System.Security.Cryptography.HashAlgorithm,
      stream   : System.IO.Stream) =
   inherit System.IO.BinaryWriter(stream)

   let unsupp() = raise(System.NotSupportedException())
   let hash_stream =
      { new System.IO.Stream() with
         member __.CanRead = false
         member __.CanSeek = false
         member __.CanWrite = true
         member __.Length = unsupp()
         member __.Position with get() = unsupp() and set(_) = unsupp()
         member __.Seek(_,_) = unsupp()
         member __.SetLength _ = unsupp()
         member __.Read(_,_,_) = unsupp()
         member __.Flush() = ()
         member __.Write(buffer, offset, count) =
            hasher.TransformBlock(buffer, offset, count, null, 0) |> ignore
      }

   new(hasher) = new HashingBinaryWriter(hasher, hash_stream)
   // Or, alternatively
   new(hasher) as me = new HashingBinaryWriter(hasher, me.hash_stream)

The last line fails to compile because hash_stream is undefined, in either form. Apparently, as this answer suggests, the scope of constructor arguments is different from that of class declaration body, but I need to understand what is going on here (and if possible the why behind the F# design decision).
Indeed, I can see some workarounds (convert hash_stream to a private property, for example), but my vocabulary of F# idioms is lacking this one. My second question is, then, what would be the idiomatic way of doing this.

A: There are multiple ways to do this - and I guess the right choice depends on how your complete implementation will look.
If you wanted something that is as close to the version in your question as possible, then you can just move unsupp and hash_stream inside the constructor:
type HashingBinaryWriter private
     (hasher   : System.Security.Cryptography.HashAlgorithm,
      stream   : System.IO.Stream) =
    inherit System.IO.BinaryWriter(stream)

    new(hasher : System.Security.Cryptography.HashAlgorithm) =
        let unsupp() = raise(System.NotSupportedException())
        let hash_stream =
            { new System.IO.Stream() with
                member __.CanRead = false
                member __.CanSeek = false
                member __.CanWrite = true
                member __.Length = unsupp()
                member __.Position with get() = unsupp() and set(_) = unsupp()
                member __.Seek(_,_) = unsupp()
                member __.SetLength _ = unsupp()
                member __.Read(_,_,_) = unsupp()
                member __.Flush() = ()
                member __.Write(buffer, offset, count) =
                  hasher.TransformBlock(buffer, offset, count, null, 0) |> ignore
            }
        new HashingBinaryWriter(hasher, hash_stream)

I guess that this can easily get ugly if your implementation of hash_stream gets longer. In that case, it would make more sense to do what John suggests in the comments and move the implementation of the stream outside of the class, perhaps into a helper module:
let unsupp() = raise(System.NotSupportedException())

let createHashStream (hasher : System.Security.Cryptography.HashAlgorithm) =
    { new System.IO.Stream() with
        member __.CanRead = false
        member __.CanSeek = false
        member __.CanWrite = true
        member __.Length = unsupp()
        member __.Position with get() = unsupp() and set(_) = unsupp()
        member __.Seek(_,_) = unsupp()
        member __.SetLength _ = unsupp()
        member __.Read(_,_,_) = unsupp()
        member __.Flush() = ()
        member __.Write(buffer, offset, count) =
          hasher.TransformBlock(buffer, offset, count, null, 0) |> ignore
    }

type HashingBinaryWriter private
     (hasher   : System.Security.Cryptography.HashAlgorithm,
      stream   : System.IO.Stream) =
    inherit System.IO.BinaryWriter(stream)
    new(hasher : System.Security.Cryptography.HashAlgorithm) =
        new HashingBinaryWriter(hasher, createHashStream hasher)


text:
Q: How can I download Airwatch iOS SDK? Maybe a bit stupid question, but how to download AirWatch iOS SDK?
I can't download AirWatch SDK. I am logged in (https://code.vmware.com, and https://resources.workspaceone.com/) but get an error

"An error occurred retrieving resource with UID xxxxxxxxxxxx. You may
  not have access to view this resource."

on resources.workspaceone.com.
Anybody who have did it already, could you please give an advice?

A: You should have an paid account for downloading the Complete AIRWatch SDK kit which include the required SDK & their documentation.

A: Open https://resources.workspaceone.com/ in safari browser to avoid errors. In chromes i am also getting some weird error. see attached screen shot.


text:
Q: What is more efficient: one big table or separate non-related smaller ones I am kind of new to SQL and web-programming right now, so I am doing a little project for myself to get to know every aspect of developing a website (yup, from frontend to backend and sql).
So the point is that potentially I may have a lot of data in my table, like over 3k rows [elements] (relatively a lot) with a bunch of columns [properties] as well. And I know from the beginning that it could be split on, say, four tables. For example, by color.
Each element of each color has the same amount of keys and keys itself
So the question is how I could estimate the ratio of time:memory efficiency in this case. I do understand that it is much quicker to search for information in a smaller table, but I have no idea how do SQL tables are stored. For instance, how much additional memory each table costs without.

A: 3,000 rows is small for SQL.  You don't want to split large tables, because SQL has strong capabilities for handling larger data.  Three come to mind:

*

*Sophisticated query optimizers.

*Indexes.

*Table partitions.

In addition, the way that data is stored incurs overhead for small tables -- not large ones.  Rows are stored on data pages.  And data pages are typically measured in thousands of bytes.  So, a small row with 100 bytes still occupies one data page -- even if the page could store one hundred such records.  And the overhead for reading the data page is the same.
In summary.  Your table isn't big.  And SQL is optimized for larger tables.  So, no need to change your data model.


text:
Q: Why can't $|x-2|$ be less than zero? Just confused with the concepts in Absolute Value.
So we know that to solve absolute value equations such,
$$|x-2| = 5 \tag1$$
In this case we have, $x-2 = 5$ and $x-2 = -5$. then solve for $x$.
However,
$$|x-2| = -5 \tag2$$
Here is no solution.

Why can't the absolute value be less than zero?

Is it from a graph that we cannot get negative values from the $y$-axis? Are there any other explanations?
A proof is highly appreciated.

A: Saying " the absolute value of number $N$ is equal to $5$" means " I do not know what number is $N$ , but I know for sure that the distance from $N$ to $0$ is $5$ units".

Defining intuitively the absolute value as a distance explains why the
absolute value cannot be negative .

In your example, it is the number $x-2$ that plays the role of $N$.
Also, when $N$ is positive the distance from $N$ to $0$ is $N-0$ and when $N$ is negative, the distance from $N$ to $0$ is $0-N $.
Consequently, the general formula is as follows, and you simply have to apply it mechanically  , by replacing $A$ by your specific number $5$, and   $N$ by your specific number : $x-2$ :

$|N| = A $
$\iff  [ N-0 = A \space $ OR $\space  0-N =A ] $
$\iff [ N=A \space $ OR $\space 0-N =A]$
$\iff [ N=A \space \mathbb {OR}\space  -N = A ]$

So, your equation means:

(1) $(x-2)- 0 = 5 \implies x-2= 5 \implies x=7$
OR
(2)$ 0 - (x-2) = 5 \implies -x +2 =5 \implies -x = 3 \implies x=-3$
The solution set of the equation is : $\{ -3, 7\}$.

A: What's called absolute value of  a number is just the numbers's distance from zero.  As such it's always non-negative. Furthermore $|a-b|$ is the distance from $a$ to $b$.
Your first equation, $|x-2|=5$ reads: "The distance from $x$ to $2$ equals $5$.", hence $x=-3$ or $x=7$.  Now the second equation, $|x-2|=-5$, reads: "The distance from $x$ to $2$ equals $-5$.", which is impossible.

A: By definition we have,$$|x|=\begin{cases}x&\text{ if }x\geqslant0\\-x&\text{ if }x<0,\end{cases}$$and therefore we always have $|x|\geqslant0$.
In order to solve the equation $|x-2|=5$ you can consider two possibilities:

*

*$x\geqslant2$. Then $|x-2|=5$ is the same thing as $x-2=5$. So, $x=7$.

*$x<2$. Then $|x-2|=5$ is the same thing as $-(x-2)=5$. So, $x=-3$.

A: The absolute value of a number returns the non-negative part of it, even if the number is negative.
So you need to consider two cases, one where the term inside the absolute value is negative and one where it is positive:
Case 1:
$|x-2| = x-2$
Case 2:
$|x-2| = 2-x$
Your second equation is wrong, remember that you already removed the absolute value when you stated that $x-2 = -5$ (considered the second possibility), and not $|x-2|$ = $-5$, because the absolute value only returns the magnitude(length), not direction, hence there exists no such thing as a negative length.

A: The definition of the absolute value function is defined as
$$|x|=\begin{cases}x&\text{ if }x\geq0\\-x&\text{ if }x<0,\end{cases}.$$
So if $|x-2|=-5$ has no solutions because the function $|x-2|$ is defined to be greater than $0$ no matter what.
However, $0<-5$, so it has no solutions.

I hope this helped.

A: To expand on @michael.hoppe's answer: $|a|$ is in fact the distance from $a$ to $0$ because you can see that $$|a|=|a-0|$$
To get $a$'s distance to any other number $b$, just substitute the $0$ with $b$. So the distance on a line from $a$ to $b$ is $|a-b|$.
The intuition behind $|a-b|\geq0$ is that a distance is always positive, as others have said. Of course, the real reason for this is the way $|x|$ is defined, so
$$|a-b|=\begin{cases}
a-b, \quad &\text{if} \;\;a-b\geq 0\\
-(a-b)=b-a \quad &\text{if}\;\; a-b<0
\end{cases}$$


text:
Q: getting error when call put, delete methods in dot net core when call put, delete methods I get this error No 'Access-Control-Allow-Origin' but there is no error with get, post methods
this occurs when publish on server but on my computer I don't have any errors
this is code in startup file
 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }
        app.UseAuthentication();
        app.UseHttpsRedirection();
        app.UseCors("corsPolicy");

        app.UseStaticFiles();
        app.UseMvc();
    }

services.AddCors(options =>
        {
            options.AddPolicy("corsPolicy", builder =>
            {
                builder.AllowAnyMethod().AllowAnyOrigin().AllowAnyHeader().AllowCredentials();
            });
        });

controller code
namespace ContinuationProjLast.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [EnableCors("corsPolicy")]

public class marksController : ControllerBase
{
    private readonly ProductionRefContext _context;

    public marksController(ProductionRefContext context)
    {
        _context = context;
    }
[HttpPut("{id}")]

    public async Task<IActionResult> Putmark(int id, mark mark)
    {
        if (id != mark.ID)
        {
            return BadRequest();
        }

        var mm = _context.mark.Where(x => x.devicemark == mark.devicemark && x.devicecategory == mark.devicecategory).FirstOrDefault();
        if (mm == null)
        {

            _context.Entry(mark).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!markExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return NoContent();
        }
        else
        {
            return BadRequest();

        }

    }

the same thing happens with delete method.
Can I get any help?

A: Iis server doesn't support put http verb by nature,
There are additional setting needs to be done.
I changed them to post verb and worked well in production

A: I removed WebDAV publishing from iis , Go to
control panel > Programs and Features > turn windows features on or off >IIS > World wide web services > Common HTTP Features  > WebDAV publishing
the problem has been solved


text:
Q: Checking Dataframe columns for negative values I'm new to python and used the following code to list all of the columns in my dataframe and identify which columns may contain null values:
df.isnull().any()
Is there similar code that to check for columns which may contain negative values? I was trying to insert '<0' into the above code but probably getting the syntax wrong and couldn't find any other answers on-line.
Any ideas are much appreciated!

A: You could just do:
s = df.min(axis=0)
s[s < 0]

This creates a Series containing the minimum values for each column and then shows only those which are less than zero.
Example output for:
df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [-1, 2, 3], 'col3': [1, -2, 3]})

col2   -1
col3   -2
dtype: int64

If you really just want the column names, you can do:
list(s[s < 0].keys())

Which will give you:
['col2', 'col3']


text:
Q: How to make Logstash write internal logs to a file? Context
I am building a program that will pass an Apache log file into Logstash and output the result (after parsing and filtering) to an external database (Elastic, MongoDB, etc.).
Basically, the program will execute following command:
gunzip -c -k "somefile.gz" | logstash -f "logstash.conf"

With logstash.conf containing:
input {
    stdin {}
}
filter {
    # ...
}
output {
    mongodb {
        # ...
    }
}

But, to help future debug/forensic, I want to grab whatever Logstash says during it's process.
By default, it seems Logstash outputs it's internal log messages to stdout, as an example, the following command:
logstash -e "input { generator { count => 3 } } output { null {} }"

Outputs:
Sending Logstash's logs to /usr/share/logstash/logs which is now configured via log4j2.properties
[2018-03-28T22:42:53,484][INFO ][logstash.modules.scaffold] Initializing module {:module_name=>"fb_apache", :directory=>"/usr/share/logstash/modules/fb_apache/configuration"}
[2018-03-28T22:42:53,515][INFO ][logstash.modules.scaffold] Initializing module {:module_name=>"netflow", :directory=>"/usr/share/logstash/modules/netflow/configuration"}
[2018-03-28T22:42:54,222][WARN ][logstash.config.source.multilocal] Ignoring the 'pipelines.yml' file because modules or command line options are specified
[2018-03-28T22:42:55,092][INFO ][logstash.runner          ] Starting Logstash {"logstash.version"=>"6.2.3"}
[2018-03-28T22:42:55,795][INFO ][logstash.agent           ] Successfully started Logstash API endpoint {:port=>9600}
[2018-03-28T22:42:58,225][INFO ][logstash.pipeline        ] Starting pipeline {:pipeline_id=>"main", "pipeline.workers"=>4, "pipeline.batch.size"=>125, "pipeline.batch.delay"=>50}
[2018-03-28T22:42:58,407][INFO ][logstash.pipeline        ] Pipeline started succesfully {:pipeline_id=>"main", :thread=>"#<Thread:0x35d85de2 run>"}
[2018-03-28T22:42:58,559][INFO ][logstash.agent           ] Pipelines running {:count=>1, :pipelines=>["main"]}
[2018-03-28T22:42:58,867][INFO ][logstash.pipeline        ] Pipeline has terminated {:pipeline_id=>"main", :thread=>"#<Thread:0x35d85de2 run>"}

Adding --log.level=debug gives at lot more: the same as previous command, plus a lot more, including the following message-related log:
[2018-03-28T22:44:30,671][DEBUG][logstash.pipeline        ] filter received {"event"=>{"@timestamp"=>2018-03-28T22:44:30.567Z, "sequence"=>1, "@version"=>"1", "message"=>"Hello world!", "host"=>"5e26a941934f"}}
[2018-03-28T22:44:30,679][DEBUG][logstash.pipeline        ] output received {"event"=>{"@timestamp"=>2018-03-28T22:44:30.567Z, "sequence"=>1, "@version"=>"1", "message"=>"Hello world!", "host"=>"5e26a941934f"}}
[2018-03-28T22:44:30,680][DEBUG][logstash.pipeline        ] filter received {"event"=>{"@timestamp"=>2018-03-28T22:44:30.568Z, "sequence"=>2, "@version"=>"1", "message"=>"Hello world!", "host"=>"5e26a941934f"}}
...

Lots of noise but it will be useful when tracking down an error.
Problem
I had trouble directly capturing the stdout and stderr of the logstash command in my program, but anyway, I find it easier to ask Logstash to directly write to a log file.
According to the documentation adding the --path.logs=/tmp to the logstash command should make it write log file to /tmp but it does not. I get no log file in /tmp after the following command ends (nor during it executes):
logstash \
    --path.logs=/tmp \
    --log.level=debug \
    -e "input { generator { count => 3 } } output { null {} }"

So: How make logstash write it's log messages (not the data it processes) to a file?


text:
Q: Merge 2 images onto new image: can someone explain this code? I'm trying to write a code to merge 2 photos side by side onto a new image, and I found this script online--however, I have no idea how it works.  Where do I input the image files that I want to merge?  Can someone please explain this code to me?  Thanks!!
from PIL import Image
import sys

if not len(sys.argv) > 3:
    raise SystemExit("Usage: %s src1 [src2] .. dest" % sys.argv[0])

images = map(Image.open, sys.argv[1:-1])
w = sum(i.size[0] for i in images)
mh = max(i.size[1] for i in images)

result = Image.new("RGBA", (w, mh))

x = 0
for i in images:
    result.paste(i, (x, 0))
    x += i.size[0]

result.save(sys.argv[-1])

A: It is very easy. You open the images with names provided in sys.argv (arguments to the program):
images = map(Image.open, sys.argv[1:-1])

You calculate the new width (sum of all width for opened images, which is i.size[0])
w = sum(i.size[0] for i in images)

The height, which should be equal to the height of the highest image (this way it can fit each)
mh = max(i.size[1] for i in images)

Create an image with calculated dumentions
result = Image.new("RGBA", (w, mh))

For each image opened, insert it (with paste function) to the point of x pixels from the left and 0 from the top and add the width of inserted image to x so that the next one is adjacent, not overlapping
x = 0
for i in images:
    result.paste(i, (x, 0))
    x += i.size[0]

Save the image
result.save(sys.argv[-1])

The error processing you see at the top has nothing to do with the process of merging images, but rather asserts that there is a correct number of arguments to the program


text:
Q: Java Simple RPG game(does not run) This code does not run for some reason.
This is a simple RPG game.
`
        import java.util.Scanner;
    public class My_first_RPG {
        double exp;
        double attack;
        double vitality;
        double armor;
        double mana;

        int skill() {
            return (int) (attack*mana);
        }
    }
    class character {
        public static void main(String args[])
            throws java.io.IOException {
            My_first_RPG Mage = new My_first_RPG();
            My_first_RPG Warrior = new My_first_RPG();
            My_first_RPG Archer = new My_first_RPG();
            My_first_RPG Dwarven_Mech = new My_first_RPG();
            My_first_RPG Steel_Golem = new My_first_RPG();
            int world[][] = new int[10][10];
            world[1][1]=2;

            Mage.attack = 75;
            Mage.vitality = 1;
            Mage.armor = 10;
            Mage.mana = 200;

            Warrior.attack = 100;
            Warrior.vitality = 2;
            Warrior.armor = 20;
            Warrior.mana = 100;

            Archer.attack = 65;
            Archer.vitality = 1;
            Archer.armor = 15;
            Archer.mana = 150;

            Dwarven_Mech.attack = 125;
            Dwarven_Mech.vitality = 0.5;
            Dwarven_Mech.armor = 5;
            Dwarven_Mech.mana = 75;

            Steel_Golem.attack = 50;
            Steel_Golem.vitality = 0;
            Steel_Golem.armor = 30;
            Steel_Golem.mana = 50;

            System.out.println("Choose your Hero.");
            System.out.println("1. Mage");
            System.out.println("2. Warrior");
            System.out.println("3. Archer");
            System.out.println("4. Dwarven Mech");
            System.out.println("5. Steel Golem");

            Scanner sc = new Scanner(System.in);
            int choice = sc.nextInt();

            switch(choice) {
                case 1:
                    System.out.println("You are now a Mage.");
                case 2:
                    System.out.println("You are now a Warrior.");
                case 3:
                    System.out.println("You are now a Archer.");
                case 4:
                    System.out.println("You are now a Dwarven Mech.");
                case 5:
                    System.out.println("You are now a Steel Golem.");
            }
        }
        class Grasslands {

        }

    }

`
Even though i have the public static void main, the code cannot run.
Is there a problem? Also, the array and the class Grasslands arent finished yet.

A: The main method must be inside a public class so that it can be accessed from "outside". See here: What if main method is inside "non public class" of java file?
Note that there can only be one public class per file.


text:
Q: Creating a navigation menu to see where you are on your website I want to create a "navigation" menu - I don't know what they are called and I'm having a hard time googling it as it is not a navigation menu as such or a sub-menu or pull down menu ect.
I just want something showing you where you are on the website, what pages where before and such(like the picture shown below) I am using elementor, would that be a problem?
I really hope you can help me! Thank you!


text:
Q: Creating an object from a text file using arrays, (no ArrayList), InputMismatchException when running I'm working on a project where I have to make an array of objects created from a text file. However whenever I run it, I get
    Exception in thread "main" java.util.InputMismatchException
    at java.base/java.util.Scanner.throwFor(Scanner.java:939)
    at java.base/java.util.Scanner.next(Scanner.java:1594)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
    at CustomerList.main(CustomerList.java:16)

Even though the text file starts with an integer. Please look at my code and give me some insight into what I'm doing wrong.
This is part of the text file that I have to read from:

100
900 Amazon purchasing@amazon.com 20000.0  0.08
210 Nordstrom purchasing@nordstrom.com 50000.0  0.07
10 Rutgers purchasing@rutgers.edu 32000.0  education
520 Alamo purchasing@alamo.com 23000.0  0.05
1 Kean purchasing@kean.edu 158000.5  education
100 Allied purchasing@allied.com 85300.0  0.06
950 JoesInc purchasing@joesinc.com 999999.0  0.03
697 BostonU purchasing@tufts.edu 340020.23  education
310 TruckersInc purchasing@truckersinc.com 55000.0  0.10
820 Clothiers purchasing@clothiers.com 20044.0  0.05
849 RedCross purchasing@redcross.org 48900.2  non-profit
125 ChocolateRus purchasing@chocolate.com 3000.5  0.1

import java.util.*;
import java.math.*;
import java.text.*;
import java.io.*;

public class CustomerList {

public static void main(String[] args)throws IOException {
    File f = new File("custy.txt");
    Scanner in = new Scanner(f);
    Customer[] obj = new Customer[1];
    int count = 0;
    while(in.hasNext() ){
        int id = in.nextInt();
        String name = in.next();
        String email = in.next();
        double balance = in.nextDouble();

        obj[count] = new Customer (id, name, email, balance);
        count++;

    }

    in.close();
    for (int i = 0; i < count; i++)
        System.out.println(obj[i]);
}

}

class Customer {

public int custId;
public String name;
public String email;
public double balance;

public Customer() {

    this.custId = 0;
    this.name = "";
    this.email = "";
    this.balance = 0.0;

}

public Customer(int custId, String name, String email, double balance) {

    this.custId = custId;
    this.name = name;
    this.email = email;
    this.balance = balance;
}

public int getId() {
    return custId;
}

public String getName() {
    return name;
}

public String getEmail() {
    return email;
}

public double getBalance() {
    return balance;
}

public void setName(String name) {
    this.name = name;
}

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

public void setEmail(String email) {
    this.email = email;
}

public void setBalance(double balance) {
    this.balance = balance;
}

public String toString() {
    DecimalFormat dollar = new DecimalFormat("$.00");

    return custId + " " + dollar.format(balance) + name + " " + email + " ";
}

}class TaxExempt extends Customer {
public String exempt;

public TaxExempt() {
    this.exempt = "";
}

public TaxExempt(int custId, String name, String email, double balance, String exempt) {
    super(custId, name, email, balance);
    this.exempt = exempt;

}

public String getExempt() {
    return exempt;
}

public void setExempt(String reason) {
    this.exempt = reason;
}

public String toString() {
    DecimalFormat dollar = new DecimalFormat("$.00");
    return custId + " " + name + " " + dollar.format(balance) + " " + email + " " + exempt;

}

}
class NonExempt extends Customer {
public double tax;
public double afterTax;

public NonExempt() {
    this.tax = 0.0;
    this.afterTax = 0.0;

}

public NonExempt(int custId, String name, String email, double balance, double tax) {
    super(custId, name, email, balance);
    this.tax = tax;

}

public double getTax() {
    return tax;
}

public void setTax(double tax) {
    this.tax = tax;
}

public void setAfterTax() {
    this.afterTax = tax * balance;

}

public String toString() {
    DecimalFormat dollar = new DecimalFormat("$.00");
    String add = "%";
    // System.out.println("Non Exempt: " );
    return custId + " " + name + " " + dollar.format(balance) + " " + email + " " + tax + add + " "
            + dollar.format(afterTax);
}

}

A: Your error is somewhat related to this question: Scanner is skipping nextLine() after using next() or nextFoo()?
Note: Assuming you removed the first 100 in the file
Your app is crashing because when it gets to
double balance = in.nextDouble();

And tries to iterate one more time, there's nothing in that line for
int id = in.nextInt();

To read from, all you need is to include:
in.nextLine();

After
double++;

And you should get your desired output.
Complete code as example:
import java.util.*;
import java.math.*;
import java.io.*;

class Test {
    public static void main(String[] args)throws IOException {
        File f = new File("custy.txt");
        Scanner in = new Scanner(f);
        while(in.hasNext() ){
            int id = in.nextInt();
            String name = in.next();
            String email = in.next();
            double balance = in.nextDouble();
            in.nextLine();

            System.out.println(id + " " + name + " " + email + " " + balance);
        }
        in.close();
    }
}

The above code prints:
900 Amazon purchasing@amazon.com 20000.0
210 Nordstrom purchasing@nordstrom.com 50000.0
10 Rutgers purchasing@rutgers.edu 32000.0
520 Alamo purchasing@alamo.com 23000.0
1 Kean purchasing@kean.edu 158000.5
100 Allied purchasing@allied.com 85300.0
950 JoesInc purchasing@joesinc.com 999999.0
697 BostonU purchasing@tufts.edu 340020.23
310 TruckersInc purchasing@truckersinc.com 55000.0
820 Clothiers purchasing@clothiers.com 20044.0
849 RedCross purchasing@redcross.org 48900.2
125 ChocolateRus purchasing@chocolate.com 3000.5


text:
Q: Jquery - get next element by class and hide current I am trying to implement the showing of part of content(5 positions at each part) by clicking on the "load more" div but stuck with getting the next element by class.

For better view here is example on jsfiddle - https://jsfiddle.net/8ya7bbm2/1/
The problem is in the last line:
size_li = $("#myList li").size();
x=3;
$('#myList li:lt('+x+')').show();
$('.loadMore').click(function () {
    x= (x+5 <= size_li) ? x+5 : size_li;
    $('#myList li:lt('+x+')').slideDown();
    $(this).hide().nextAll('.loadMore').show(); // working
   // $(this).hide().next('.loadMore').show(); NOT WORKING...

The main idea is that after all content will be shown the "load more" must be hidden so that users can understand that this is all of content. At the moment I almost done what I wanted but .next is not working as I expected. When I use .nextAll it works great, but I need only next element by class, not all next elements of that class.
Also maybe this version is a little bit ugly and there is more simplest way to do such thing?

A: You can use .first() to target only first element in matched set:
$(this).hide().nextAll('.loadMore').first().show();

Working Demo

A: next() will not work in this case, because next will check for only immediately following sibling. You can use .nextAll('.loadMore:first') like following.
$(this).hide().nextAll('.loadMore:first').show();


text:
Q: Javascript Cross Subdomain XMLHTTPRequest I'm researching a solution for a bandwidth intensive project I am working on.  It involves doing POST and GET requests client side to different servers at different locations.   All the servers are mine.
The reasoning behind this design is to prevent a single server/location from becoming too busy and slowing down due to the high bandwidth needs of the project.  It mainly involves uploading and downloading large files.
With current technologies I would need to proxy these GET and POST requests server side due to the cross-site scripting restrictions.  That is the very thing I want to avoid, since it would still utilize bandwidth at a single point.
I've been reading about emerging technologies such as CORS and JSON-P that appear to allow this function.  I don't mind the solution being HTML5 only.  I do however want to be able to use JQuery.
Is it correct to assume that these new technologies will allow the function I want?
Where is the best place to start researching these two technologies?
Which one is recommended?

A: You want CORS.  JQuery will play fine with that.  Old browsers, most notably IE<10 will not play nicely but if you can ignore those, go with CORS.


text:
Q: What control flow to implement when I want the user to not name his/her characters chosen with a same name? I am quite new to coding, so simple tasks seems like the mount Everest. I have created a Switch statement for a player to choose 3 out of 4 characters to play with. I' d like him/her to name their characters uniquely.
I tried by adding a "parameter [String]" to the method and inside it, adding each characters name, using a "for Loop" to check if a character has already be named this way.
The thing is that I keep looping and can' t sort out how to name each character uniquely.
If someone has any clue, thanks to answer.
func makeTheTeam(listOfName: [String]) {

    var listOfName = listOfName

    // Presents all the fighter available
    gameAction.charactersPresentation()

    while listOfFighters.count < 3 {

        print("\nInput a number associated to select a fighter:")
        if let userChoice = readLine() {

            print("Name your fighter:")
            if let nameChoice = readLine() {

            switch userChoice {
            case "1":
                listOfFighters.append(Warrior(fighterName: "\(nameChoice)"))
            case "2":
                listOfFighters.append(Wizard(fighterName: "\(nameChoice)"))
            case "3":
                listOfFighters.append(Colossus(fighterName: "\(nameChoice)"))
            case "4":
                listOfFighters.append(Dwarf(fighterName: "\(nameChoice)"))
            default:
                print("You have not chosen three characters to enter the ring!! \n\nEnter a number associated to a fighter...")
            }
         }
      }
   }
}

A: For getting rid of the "unique" names issue, you could:
1- Get the benefit of using Sets, by converting listOfName to a set and check the counts:
if Set(listOfName).count == listOfName.count {
    // unique names, we are good to go
} else {
    // similar names...
}

OR
2- if your desired behavior is to check the array sequentially after adding each element, you could use contains. As an example of the basic usage for it:
var names = [String]()
var inputName = "Jack"

// will append "Jack"
if names.contains(inputName) {
    // name is already exist
} else {
    names.append(inputName)
}

inputName = "Smith"

// will append "Smith"
if names.contains(inputName) {
    // name is already exist
} else {
    names.append(inputName)
}

inputName = "Smith"

// will NOT append "Jack"
if names.contains(inputName) {
    // name is already exist
} else {
    names.append(inputName)
}

Tip:
If makeTheTeam function should receive an unspecific number of strings, I would suggest to declare it as variadic:
func makeTheTeam(listOfName: String...) { // ...


text:
Q: How can I find text mode page buffer in TASM? I'm trying to send some characters to page 1 of text mode by its memory address, but I find no suitable result, I calculated the page 1 address like this "0B800h + 1000h = 0C800h".
This is my code:
        IDEAL

        MODEL   small
        STACK   256

        DATASEG

exCode          DB      0
x_var           db      219

        CODESEG

Start:
        mov     ax, @data       ; Initialize DS to address
        mov     ds, ax          ;  of data segment

        ; Page 1
        mov     ax, 0501h
        int     10h

        ;Page 1 buffer -> es
        mov     ax, 0C800h
        mov     es, ax

        mov     si, offset x_var

        mov     di, (10*80*2)+(10*2)

        cld

        lodsb
        stosb

        ; wait for any key press:
        mov ah, 0
        int 16h

        ;Page 0 again
        mov     ax, 0500h
        int     10h

Exit:
        mov     ah, 04Ch        ; DOS function: Exit program
        mov     al, [exCode]    ; Return exit code value
        int     21h             ; Call DOS.  Terminate program

        END     Start           ; End of program / entry point

A: The problem is in the calculation of the segment. If you are in an 80x25 text mode then each text page is 4096 bytes (01000h) in size. You can't add 01000h to 0b800h. You need to shift 01000h right by 4 bits (or divide by 16 decimal) to convert the value to number of 16 byte paragraphs and then add it to the 0b800h segment value. 01000h shifted right 4 bits is 0100h. Add that to 0b800h and you get 0b900h (0b800h+0100h) as the segment where page 1 starts. Thus:
mov     ax, 0C800h
mov     es, ax

Should be:
mov     ax, 0B900h
mov     es, ax

Notes

*

*When using the BIOS to change video pages you can determine the number of bytes each video page takes by looking at the 16-bit WORD value at memory address 0000h:044ch in the BIOS Data Area (BDA). You can read that value and shift it right 4 bits and then add it to the base video address (0b800h in the case of video mode 03h).


text:
Q: how to create a properties file for error messages thrown ny @Valid annotation in spring I have this class, where the field "nome" can't be empty
public class Utente {
    ......

    @NotEmpty
    @Size(min=2, max=30)
    private String nome;
    .......
}

After the user fills and sends the form I call this method
    @RequestMapping("/formSent")
    public String formSentMethod(Model model, @Valid Utente utente, BindingResult result){
    .....
}

I print the error in the Eclipse's console with this plain code, put inside the formSentMethod method.
    @RequestMapping("/formSent")
    public String formSentMethod(Model model, @Valid Utente utente, BindingResult result){
    .....
    for(ObjectError errore : result.getAllErrors()){
        System.out.println(errore.getDefaultMessage());
    }
    .....
}

So far, I get the default error message "may not be empty", when the user doesn't fill the field "nome".
I tried to customize that message by using a properties file called messages.properties, that I put under WEB-INF/classes, as you can see in this pic
Inside messages.properties I wrote
   NotEmpty.utente.nome = Il nome è obbligatorio

In my XXX-servlet.xml I "call" the properties file this way
<bean class="org.springframework.context.support.ResourceBundleMessageSource" id="messageSource">

            <property name="basename" value="messages" />
    </bean>

<mvc:annotation-driven />

Since it didn't work I even tried editing the basename value this way
<property name="basename" value="WEB-INF/Classes/messages" />

but it didn't work as well.
I keep on getting the default error message and not my customized message "Il nome è obbligatorio". Probably what I wrote in my properties file is not correct. What am I doing wrong?

A: message.properties doesn't reference the class and field, but form name and the field. For example in this html:
<form:form method="POST" commandName="utente" action="customer/signup">
    <form:errors path="*" cssClass="errorblock" element="div" />

            Customer Name :
            <form:input path="nome" />
            <form:errors path="nome" cssClass="error" />

            Customer Age :
            <form:input path="age" />
            <form:errors path="age" cssClass="error" />

            <input type="submit" />

</form:form>

NotNull.utente.nome will be correct, because the form utente contains field nome. The important thing is, it's not based on the class but the path in html.
To access the internationalization from controller, you need MessageSource bean, and use the bean to get the internationalization.
Here is example taken from here to access internationalization message in controller:
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basenames" value="ValidationMessages"/>
</bean>

Inject your MessageSource instance inside your Controller
@Autowired
private MessageSource messageSource;

And to get your message, do as follows
for (Object object : bindingResult.getAllErrors()) {
    if(object instanceof FieldError) {
        FieldError fieldError = (FieldError) object;

        /**
          * Use null as second parameter if you do not use i18n (internationalization)
          */

        String message = messageSource.getMessage(fieldError, null);
    }
}

A: I believe that message's should be placed inside classes but one level up, according to your configuration.
You could also make a absolute path like:

/WEB-INF/classes/messages

or one level up

/WEB-INF/messages

Also, remember that with this configuration, you're not setting default encoding, which may lead to some problems, I suggest set property defaultEncoding to UTF-8


text:
Q: How can you count the number of occurrences of all of the words in a text area using Javascript? If I had a textarea and a user pasted a paragraph into the textarea, can statistics be run on the input using JavaScript on the client side? I was thinking of using an associative array or hash map so array[word] -> # of occurrences, and iterate through word by word but I'm not sure how to do this using client side JavaScript.
I tried searching JavaScript word count but I only get results on counting the total number of words, which is not what I'm looking for. What I am looking for is more keeping a count of each specific word. Can this be done in Javascript or Jquery? If so, how should I go about doing this?

A: Here is an approach for you
// first get an array of words
var words = text.split(' ');

// use Array.prototype.reduce (for example) to
// create statistics
var statistics = words.reduce(function (stat, word) {
    if (!stat[word]) stat[word] = 0;
    stat[word]++;
    return stat;
}, {});

UPDATE: A little example which handles punctuation and upper/lower case, too: http://jsfiddle.net/1pnLzv8h/1/

A: Something like
var arra = ['ab','pq','mn','ab','mn','ab']

function wordCount(arra,val)
{
    var ob={};
    var len=arra.length;
    for(var k=0;k<len;k++)
    {
        if(ob.hasOwnProperty(arra[k]))
        {
            ob[arra[k]]++;
            continue;
        }
        ob[arra[k]]=1;
    }
    return ob[val];
}

alert(wordCount(arra,'ab')); //output 3


text:
Q: Powershell - Should take only set of numbers from file name I have a script that read a file name from path location and then he takes only the numbers and do something with them. Its working fine until I encounter with this situation.
For an example:
For the file name Patch_1348968.vip it takes the number 1348968.
In the case the file name is Patch_1348968_v1.zip it takes the number 13489681 that is wrong.
I am using this to fetch the numbers. In general it always start with patch_#####.vip with 7-8 digits so I want to take only the digits
before any sign like _ or -.
$PatchNumber = $file.Name -replace "[^0-9]" , ''

A: I suggest to use -match instead, so you don't have to think inverted:
if( $file.Name -match '\d+' ) {
    $PatchNumber = $matches[0]
}

\d+ matches the first consecutive sequence of digits. The automatic variable $matches contains the full match at index 0, if the -match operator successfully matched the input string against the pattern.
If you want to be more specific, you could use a more complex pattern and extract the desired sub string using a capture group:
if( $file.Name -match '^Patch_(\d+)' ) {
    $PatchNumber = $matches[1]
}

Here, the anchor ^ makes sure the match starts at the beginning of the input string, then Patch_ gets matched literally (case-insensitive), followed by a group of consecutive digits which gets captured () and can be extracted using $matches[1].
You can get an even more detailed explanation of the RegEx and the ability to experiment with it at regex101.com.

A: You can use
$PatchNumber = $file.Name -replace '.*[-_](\d+).*', '$1'

See the regex demo.
Details:

*

*.* - any chars other than newline char as many as possible

*[-_] - a - or _

*(\d+) - Group 1 ($1): one or more digits

*.* - any chars other than newline char as many as possible.


text:
Q: switch in switch, does the outer case break if inner case break In languages that have switch, usually a break; statement is needed. What if a switch within a switch statement? Is it necessary to put a break; statement in the outer switch when the inner switch has a break;? e.g.:
// outer switch
switch (a) {
    case 1:
        // inner switch
        switch (b) { // this inner switch breaks either way.
            case (2):
                break;
            default:
                break;
        }
        break; // is this outer break still necessary?
    default:
        break;
}

I hope someone can help me to understand the logic more deeply and accurately.

A:
// is this outter break still neccessary?

Yes.
Alternatively you could show the nested switch inside a function and return instead of break. Likely far more readable.

A: Both break statements are useful. This gives the language greater flexibility, and it keeps the language itself simpler to work with.
You seem to be thinking of a simple situation, where the nested switch is choosing which one thing to do. This is often a good design. However, what if more needs to be done? There might be more work to do after breaking out of the inner switch.
// outer switch
switch (a) {
    case 1:
        // inner switch
        switch (b) {
            case 2:
                std::cout << "The b value is acceptable.\n";
                break;
            default:
                std::cout << "The inner default.\n";
                break;
        }
        std::cout << "The first case has finished.\n";
        break;

    default:
        break;
}

If the inner break jumped out of the outer switch in this example, you would never see the output The first case has finished. Limiting the impact of a break allows for more complex code flow. (Not that complex code is desirable, but it's nice to have options.)
On top of that, if your code is not kept simple, it could quickly become difficult to deduce what the impact of a break statement is. You mentioned switch statements, but break statements also affect loops. If a switch is inside a loop, should a break in the switch also break out of the loop? What if the loop was itself inside a switch (that is, if you nest the statements switch - while - switch)? What would you expect a break in the inner switch to do? Exiting everything is unlikely to be desired. Besides, there is already a language feature that allows breaking out of multiple nesting levels (known as return).
There is a design principle that says to keep it simple. If your code is simple, you won't have these monster situations to worry about. At the same time, the principle also applies to language design. If the syntax rules for the language are kept simple (a break statement consistently breaks out of a single statement), then life is easier for the people using the language.


text:
Q: How to resolve this ? ValueError: Cannot have number of splits n_splits=5 greater than the number of samples: n_samples=1 I tried to understand the issue and find the solution, but I don't have anything yet.
Code Snippet:
import sklearn
import pickle
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.metrics import classification_report, confusion_matrix
Y = dataset_df['class']
X = dataset_df.drop(['class'], axis=1)

X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2)

# defining parameter range
param_grid = {'C': [0.1, 1, 10, 100, 1000],
            'gamma': [1, 0.1, 0.01, 0.001, 0.0001],
            'kernel': ['rbf']}

grid = GridSearchCV(SVC(), param_grid, refit = True, verbose = 3)

grid.fit(X_train, y_train)

Full error:

ValueError (Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_728\2392563397.py in
----> 1 grid.fit(X_train, y_train)
c:\users\gurjo\appdata\local\programs\python\python37\lib\site->
packages\sklearn\utils\validation.py in inner_f(*args, **kwargs)
70                           FutureWarning)
71         kwargs.update({k: arg for k, arg in
zip(sig.parameters, args)})
---> 72         return f(**kwargs)
73     return inner_f
74
c:\users\gurjo\appdata\local\programs\python\python37\lib\site->
packages\sklearn\model_selection_search.py in fit(self, X, y,
groups, **fit_params)
734                 return results
735
--> 736             self.run_search(evaluate_candidates)
737
738         # For multi-metric evaluation, store the best_index, best_params_ and
c:\users\gurjo\appdata\local\programs\python\python37\lib\site-packages\sklearn\model_selection_search.py
in _run_search(self, evaluate_candidates)    1186     def
_run_search(self, evaluate_candidates):    1187         """Search all candidates in param_grid"""
-> 1188         evaluate_candidates(ParameterGrid(self.param_grid))    1189     1190
c:\users\gurjo\appdata\local\programs\python\python37\lib\site-packages\sklearn\model_selection_search.py
in evaluate_candidates(candidate_params)
713                                for parameters, (train, test)
714                                in product(candidate_params,
--> 715                                           cv.split(X, y, groups)))
716
717                 if len(out) < 1:
c:\users\gurjo\appdata\local\programs\python\python37\lib\site-packages\sklearn\model_selection_split.py
in split(self, X, y, groups)
332                 ("Cannot have number of splits n_splits={0} greater"
333                  " than the number of samples: n_samples={1}.")
--> 334                 .format(self.n_splits, n_samples))
335
336         for train, test in super().split(X, y, groups):
ValueError: Cannot have number of splits n_splits=5 greater than the
number of samples: n_samples=1.


text:
Q: The variance of two running variances Having 2 sets, and only this data for each one, the running variance, the sum, the running mean and the count. How can I get the merged variance of the 2 sets?
EDIT:
The values of the sets are being updated each time with new ocurrences this ocurrences are not being stored.
The values of the sets are not equal.
I need to merge this 2 sets and get the new variance of this merged set.
EDIT 2:
I think that what I need is the pooled variance, am I correct?
In java would be something like this
Double variance = (((firstAggregate.count - 1) * firstAggregate.variance) + ((secondAggregate.count - 1) * secondAggregate.variance)) / ((otherAggregate.count + secondAggregate.count) - 2);

A: There's no need to merge two sets and compute the variance, it's a time consuming task you can compute the variance for each of them separately, then update the total variance. Updating variance could be done by using an update formula.

$T_1,_m = \sum_{i=1}^{m} x_i \\$
$S_1,_m =  \sum_{i=1}^{m} (x_i - \frac{1}{m}*T_1,_m)^2 \\$
The equation discussed at a pairwise algorithm for computing sample variances paper.

Update
Parallel algorithm


text:
Q: Unable to click entire row in custom Listview I am creating a custom ListView in which I have two identical rows and one is different with a Spinner in it. The problem is that the row with Spinner is not clickable. I can only click on Spinner. Here is my adapter:
@Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        int theType = getItemViewType(position);
        if (convertView == null) {
            holder = new ViewHolder();
            if (theType == 0) {
                convertView = inflat.inflate(R.layout.row_item0, parent, false);
                holder.textView = (TextView) convertView
                        .findViewById(R.id.text);
                holder.sp = (Spinner) convertView.findViewById(R.id.sp);

            } else if (theType == 1) {
                convertView = inflat.inflate(R.layout.row_item1, null);
                holder.textView = (TextView) convertView
                        .findViewById(R.id.text);
            }

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        String it = items.get(position);
        if (it != null) {
            if (theType == 0) {
                holder.textView.setText(it);
                holder.sp.setAdapter(new CategorySpinnerAdapter(
                        getApplicationContext(),
                        R.layout.item_spinner_category, Data.lose_weight_type));
                holder.sp
                        .setOnItemSelectedListener(new OnItemSelectedListener() {

                            @Override
                            public void onItemSelected(AdapterView<?> parent,
                                    View view, int position, long id) {
                                Data.user
                                        .setLose_weight_type(Data.lose_weight_type
                                                .get(position));
                                Data.user.setGoal(Data.goals.get(0));
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> arg0) {
                                // TODO Auto-generated method stub

                            }
                        });
            } else if (theType == 1) {
                holder.textView.setText(it);
            }

        }
        return convertView;
    }

A: You need to add android:descendantFocusability="blocksDescendants" in your layout file of the custom listview or in each of the views add android:focusable="false". If any of the view in custom listview has focusable view then onitemclick does not work.

A: If any clickable widget like Image Button, spinner , button etc are included in adapter then list view item is not clickable.
You can do one things you can make click listener on convert view in adapter class itself. This may not be accurate method, but this works perfectly in this kind of situation


text:
Q: native-crypto encrypt throwing DOMException I am using the native-crypto package which is an API for cross-platform cryptography (so web and node.js).
let crypto = require("native-crypto");

I have generated a public/private key-pair...
keyPair = crypto.generate('P-256');

...and I am trying to encrypt a message like so:
let message = "Hello, World!";
let encrypted = crypto.rsa.encrypt(keyPair.privateKey, message);

However, this is not working, I am receiving a DOMException (in a browser environment) with no further details.
How do I solve this?
Possible issues:

*

*Maybe I am using the incorrect combination of functions

*It could be because my generated key's key_ops only includes ["sign"] but nothing for encrypion.

A: Let's start with the exception...for some reason you're not seeing the error message.
Uncaught (in promise) DOMException: The required JWK member "kty" was missing

Asynchronous vs synchoronous
This first error is because you're trying to use an asynchonous API synchronously.
You need to add the await keyword on the keyPair generate line:
keyPair = await crypto.generate('P-256');

Without the await keyword, a Promise is assigned to keyPair instead of an Object containing kty.
Wrong key type
Once you fix that, you'll see another error:
The JWK "kty" member was not "RSA"

This is because an ECDSA key is being used with RSA encryption.
One more problem
Once you fix that, you'll see one more error
The JWK "key_ops" member was inconsistent with that specified by the Web Crypto call. The JWK usage must be a superset of those requested

I can't help with this one. I suspect that this is an issue with native-crypto. You might have to file a bug report on their github repo. Here is a roughly equivalent example using only the Web Crypto API.
const crypto = window.crypto.subtle;

async function main() {
  const keyPair = await crypto.generateKey(
    {
      name: "RSA-OAEP",
      modulusLength: 4096,
      publicExponent: new Uint8Array([1, 0, 1]),
      hash: "SHA-256"
    },
    true,
    ["encrypt", "decrypt"]
  );

  let message = "hello";

  message = new TextEncoder().encode(message);
  const encrypted = await crypto.encrypt({ name: "RSA-OAEP" }, keyPair.publicKey, message);

  console.log(encrypted);
}

main()


text:
Q: Radius of convergence of Power Series! Given two power series $$\sum_{n=0}^{\infty} a_nx^n, \sum_{n=0}^{\infty} b_nx^n$$ with convergent radius $R_{1}$ and $R_{2}$ respectively. Suppose $R_{1}<R_{2}$,now what about the convergent radius of $\sum_{n=0}^{\infty} (a_n+b_n)x^n$

A: For a power series $\sum_n c_nx^n$, the radius of convergence is $\sup\{R>0, \{c_nx^n\}\mbox{ is bounded if }|x|\leq R\}$.
Let $x$ such that $|x|<R_1$. Then $|(a_n+b_n)x^n|\leq |a_n||x|^n+|b_n||x^n|$ and the sequence $\{(a_n+b_n)x^n\}$ is bounded. Hence the radius of convergence of $\sum_n(a_n+b_n)x^n$ is $\geq R_1$. If we take $|x|\in (R_1,R_2)$, then $\{(a_n+b_n)x^n\}$ is not bounded, as a sum of a bounded sequence with an unbounded one. So the radius of convergence is at most $R_1$.
Conclusion: the radius of convergence of $\sum_n (a_n+b_n)x^n$ is $R_1$.
Now we look at the case $R_1=R_2$. Let $R>R_1$ and $\sum_nc_nx^n$ a series or radius of convergence $R$. By the previous case, $\sum_n(-a_n+c_n)x^n$ has a radius of convergence $R_1$ but $\sum_n(a_n+(-a_n+c_n))x^n$ has a radius of convergence $R$. So the sum of two series of radius of convergence $R_1$ can be of radius of convergence $R\geq R_1$.


text:
Q: HTTP Messages only downstream? What does it means that http messages only flow downstream?, what would be upstream?

A: You need to provide context for the claim if there's any hope of explaining what the author meant. As written, it's not an accurate statement.


text:
Q: How to know if someone has embedded my website into an Android App? I'm recieving request to my php webserver with this content in HTTP_X_REQUESTED_WITH header:
[HTTP_X_REQUESTED_WITH] => com.android.browser
This var is into $_SERVER global var when the website is requested from an Android App but i'm not sure if this is the correct way to detect if someone is embedded my website.
I'm not sure if that request are from any Google built-in app or from any app
that is taking advantage of my work without permission.
EDIT: These type of requests began suddenly in December 2016.
Regards

A:
I'm not sure if that request are from any Google built-in app or from
  any app that is taking advantage of my work without permission.

You really can't be 100% percent sure about it by only looking at that, it might be an app embedding your website, or a legitimate user accessing your website through an android browser. Different browsers send different HTTP headers (for example the one you have noticed) as well as user agents.
For example, if your website is requested via a WebView (the "browser" component you can use in an app that could be used to impersonate your website), you should get this kind of user agent:
Mozilla/5.0 (Linux; Android 5.1.1; Nexus 5 Build/LMY48B; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/43.0.2357.65 Mobile Safari/537.36

The key is wv here, that indicates that the request comes from a WebView (Take a look at https://developer.chrome.com/multidevice/user-agent)
Likewise, Google Spiders (and thousand others) add other headers / user agents.
However, all these things are easily forged, so (imho) at the end of the day it doesn't really pay off to spend too much time and resources on complicated heuristics that, at most, would only ban the most novice impersonators.
I'd suggest you to monitor a little those requests, and if at some point you suspect they're non-legit, just ban them in the server configuration file.


text:
Q: how do i fix the error: No JSON object could be decoded from a zmq DEALER to ROUTER message? I have a DEALER  socket rending to a ROUTER, and once the message arrives, i cant decode it as json, if i print the received text and copy it to a python terminal, i can decode it though, but the receiving code is unable.
here is the code sending:
self._out_socket = self._out_context.socket(zmq.DEALER)
self._out_socket.connect("ipc://testout")
self._out_socket.send_json(bump)

here is the code receiving it:
ip_soc.socket(zmq.ROUTER)
ip_soc.socket.bind("ipc://testout")
ip_stream = ZMQStream(ip_soc.socket)
ip_stream.on_recv(send_res)
#... ioloop start here to wait

when this message is sent:
{'index': 0, 'image_generated': 'false', 'resdict': [], 'result': [' (\\mathrm{\\%i}1) \x05\x05'], '_id': u'1ceb8c99c1a248a48418a6067b335613', 'purpose': 'result'}

here is what i receive:
['\x00k\x8bEg', '{"index":0,"image_generated":"false","resdict":[],"result":[" (\\\\mathrm{\\\\%i}1) \\u0005\\u0005"],"_id":"1ceb8c99c1a248a48418a6067b335613","purpose":"result"}']

if i try to decode it (second part  of above list:)
dictionary  = json.loads(message[1])
im met with this error:
No JSON object could be decoded

what is going wrong?
The same code works fine if i use PUSH and PULL.
The final result i'd like it an N to 1 zmq scheme where multiple independent processes can send to one receiver thats why im trying to use   DEALER-ROUTER.


text:
Q: how to get html page source by C# I want to save complete web page asp in local drive by .htm from url or url but I did not success.
Code
public StreamReader Fn_DownloadWebPageComplete(string link_Pagesource)
{
     //--------- Download Complete ------------------
     //  using (WebClient client = new WebClient()) // WebClient class inherits IDisposable
     //   {

     //client
     //HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(link_Pagesource);

                    //webRequest.AllowAutoRedirect = true;
                    //var client1 = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(link_Pagesource);
                    //client1.CookieContainer = new System.Net.CookieContainer();

                 //   client.DownloadFile(link_Pagesource, @"D:\S1.htm");

              //  }
         //--------- Download Page Source ------------------
 HttpWebRequest URL_pageSource = (HttpWebRequest)WebRequest.Create("https://www.digikala.com");

                    URL_pageSource.Timeout = 360000;
                    //URL_pageSource.Timeout = 1000000;
                    URL_pageSource.ReadWriteTimeout = 360000;
                   // URL_pageSource.ReadWriteTimeout = 1000000;
                    URL_pageSource.AllowAutoRedirect = true;
                    URL_pageSource.MaximumAutomaticRedirections = 300;

                    using (WebResponse MyResponse_PageSource = URL_pageSource.GetResponse())
                    {

                        str_PageSource = new StreamReader(MyResponse_PageSource.GetResponseStream(), System.Text.Encoding.UTF8);
                        pagesource1 = str_PageSource.ReadToEnd();
                        success = true;
                    }

Error :

Too many automatic redirections were attempted.

Attemp by this codes but not successful.
many url is successful with this codes but this url not successful.

A: using (WebClient client = new WebClient ())
{
    string htmlCode = client.DownloadString("https://www.digikala.com");
}

A: using (WebClient client = new WebClient ())
{
    client.DownloadFile("https://www.digikala.com", @"C:\localfile.html");
}

A: here is the way
string url = "https://www.digikala.com/";

using (HttpClient client = new HttpClient())
{
   using (HttpResponseMessage response = client.GetAsync(url).Result)
   {
      using (HttpContent content = response.Content)
      {
         string result = content.ReadAsStringAsync().Result;
      }
   }
}

and result variable will contains the page as HTML then you can save it to a file like this
System.IO.File.WriteAllText("path/filename.html", result);

NOTE you have to use the namespace
using System.Net.Http;

Update if you are using legacy VS then you can see this answer for using WebClient and WebRequest for the same purpose, but Actually updating your VS is a better solution.


text:
Q: How can I push a new Book object into empty array using Class syntax? If a constructor in the class declaration already creates a book object, If i'm thinking about this correctly, all I would need to do is instantiate the object, then push that object into an array. What am I missing here?

class Book{
  constructor(title, author, pages, hasRead, library=[]){
    this.title = title
    this.author = author
    this.pages = pages
    this.hasRead = hasRead
    this.library = library
  }

addBookToLibrary(){
   return this.library.push();
 }
}

//instantiate Book Object
let newBook = new Book();

//push the object into the empty array??
newBook.addBookToLibrary("A book", "Charlie Morton", "500", true);

console.log(newBook.library);

A: As stated, originally you were not passing any arguments to your push method. If you are looking to create an array of arrays like:
[
[
"A book",
"Charlie Morton",
"500",
true
],
[
"Two book",
"Charlie Morton",
"200",
false
]
]
Though I think an array of objects with key:value pairing would make it easier to use.

class Book{
  constructor(title, author, pages, hasRead, library=[]){
    this.title = title
    this.author = author
    this.pages = pages
    this.hasRead = hasRead
    this.library = library
  }

  addBookToLibrary(book){
     return this.library.push(book);
  }
}

//instantiate Book Object
const newBook = new Book();

//push the object into the empty array??
newBook.addBookToLibrary(["A book", "Charlie Morton", "500", true]);
newBook.addBookToLibrary(["Two book", "Charlie Morton", "200", false]);

console.log(newBook.library);


text:
Q: How to mapping all column to pandas directly Here's my data
Id   Column_1   Column_2  Column_3
1        64.7       73.8      53.2
2        94.7       79.8      43.2

The mapping rule, under 60 is 0, 60-80 is 1 80 - 100 is 2,  so the result is
Id   Column_1   Column_2  Column_3
1           1          1         0
2           2          1         0

Regards

A: Use cut for all columns without first:
f = lambda x: pd.cut(x, bins=[-np.inf, 60,80, 100], labels=[0,1,2])
df.iloc[:, 1:] = df.iloc[:, 1:].apply(f)
print (df)
   Id Column_1 Column_2 Column_3
0   1        1        1        0
1   2        2        1        0

Alternative solution for MultiIndex Series by reshape:
df = (pd.cut(df.set_index('Id').stack(),
              bins=[-np.inf, 60,80, 100],
              labels=[0,1,2])
        .unstack())
print (df)
   Column_1 Column_2 Column_3
Id
1         1        1        0
2         2        1        0

Another alternative with numpy.select:
df1 = df.iloc[:, 1:]
m1 = df1.le(60)
m2 = df1.gt(60) & df1.le(80)
m3 = df1.gt(80) & df1.le(100)
df.iloc[:, 1:] = np.select([m1,m2, m3], [0,1,2])


text:
Q: Find out $\mathrm{Aut}\ \mathbb{Z}_{p^n}$ Prove that
$$\mathrm{Aut}\ \mathbb{Z}_{2^n}=\mathbb{Z}_2\times \mathbb{Z}_{2^{n-2}}$$
$$\mathrm{Aut}\ \mathbb{Z}_{p^n}=\mathbb{Z}_{p^{n-1}(p-1)}$$
I figured out that $\mathrm{Aut}\ \mathbb{Z}_n=U(\mathbb{Z}_n)$ and $\lvert U(\mathbb{Z}_n) \rvert=\varphi(n)$, where $\varphi$ is the Euler's totient function, how should I go on?


text:
Q: how to change the position of boxes? this is my code, i want to create box in box in css and html
but when i made it,i couldn't move the boxes, i need a margin from top to put the boxes in the center of the box or moving them in to the main box,how can i do this?
code:

        <ui>
            <div1>hello</div1>
            <div2>bye</div2>
        </ui>

A: <!DOCTYPE html>

This is a heading

Because the image has a z-index of -1, it will be placed behind the text.

Produces: http://www.w3schools.com/css/tryit.asp?filename=trycss_zindex


text:
Q: Find label starting with text with jQuery I have some labels, like:
Some words
Some other words
Yet another words

How can I get labels starting with "Some" (or other text?). I tried
$("label").filter('html^="Some"')
//or
$("label").filter('text^="Some"')

but it doesn't seem to work (returns empty list). It's more complicated in my real problem so maybe I made some other mistake, but maybe I'm doing it totally wrong? Is any of these a good way to do it? What's the best way?

A: I would do this (jsfiddle):
$('label').filter(function(index) {
  return $(this).text().search('Some') == 0;
})...


text:
Q: Kubernetes: Find when a ConfigMap was patched I can easily find when a ConfigMap was created but how do you find out when a ConfigMap was last patched (edited)?
That information does not appear in any of the metadata when I export as YAML.
Deployments have a lastUpdateTime field that we can see, ConfigMaps don't appear to have the same, is that true?
status:
  availableReplicas: 2
  conditions:
  - lastTransitionTime: "2020-01-16T17:48:17Z"
    lastUpdateTime: "2020-01-16T17:48:17Z"

A: By current design config maps are not versioned and so there is no preserving the history and at a given point in time there can be only one version of a ConfigMap in kubernetes. Deployments are versioned and needs history and timestamps for rollout and rollback.

A: As @ArghyaSadhu said, configmaps are not versioned in kubernetes.
If you want to take control of your configmaps versions, you could create a simple entry in the data field like:
apiVersion: v1
kind: ConfigMap
data:
  config.version: "001" <== HERE
...

and increase/modify the version number of this specific data when you do some adjustment or just let your CI/CD process modify it for you.
But it is the only for your control, if you want to implement 'rollback' functionality to your configmaps this must be done using some script from your side.


text:
Q: Alternative to wrapping all callback functions in anonymous functions in CoffeeScript I started using CoffeeScript today and found myself using a pattern like (args...) => @style(args...) a lot when I needed callback function. The context looks roughly like this:
class Parent
  @style: (feature) ->
    if feature
      @insight()

class Child extends Parent
  @insight: ->
    alert 'Sara is awesome'

  @load: ->
    [42].forEach((args...) => @style(args...))

Child.load()

This shows Sara is awesome, which is accurate. If I had only used [42].forEach(@style), style would've ended up with a this referring to the parent class (I think?), which doesn't know insight.
But this is very verbose, and I need a lot of callback functions in my code. Is there a more elegant, idiomatic way to solve this?
(Using forEach in CoffeeScript is bad style I've read, but in my actual code I'm working with various Leaflet functions that I can't just replace with for loops.)

A: First thing to noticed is that you shouldn't call insight from the Parent class. The whole purpose of a class is to provide encapsulation. So the first thing I'd do is to move insight to Parent
To answer your question, the more idiomatic way to solve that is using the fat arrow notation. What the fat arrow does internally is to create an anonymous function to enclosure the this.
That said, the final code should look something like this:
class Parent
  @style: (feature) =>
    if feature
      @insight()

  @insight: ->
    alert 'Sara is awesome'

class Child extends Parent
  @load: ->
    [42].forEach(@style)

Child.load()

Hope that helps.
EDIT
Based on the OP comment:
class Parent
  style: (feature) =>
    if feature
      @insight()

class Child extends Parent
  load: ->
    [42].forEach(@style)

  insight: ->
    alert 'Sara is awesome'

(new Child()).load()


text:
Q: HTML CSS Border I am trying to create a border that surrounds the text of a title:
#headerwrap h1 {
    border: 5px solid red;
    color: #FFFFFF;
    font-family: 'Patua One', cursive;
    font-size: 4em;
    font-weight: 400;
    margin: 1em 0em 3em 0em;
}

The problem is the border is spanning the whole width of the page instead of just the text. I have experimented with display: inline-block; But that makes the border too close to the text.
Is there a way to make the border around the text, and with a custom outset?

A: In addition to inline-block, add some padding:
padding: 0.1em 0.1em

A: Sure just use inline-block and give it some padding.

A: Just use inline-block and add some padding along side with it :)
Just like this
padding: 0.11em 0.1em
UPDATE:
Sorry, I messed up.
THIS is how its done:
padding: 0.1em 0.1em
Do it any size, but just make sure both are the same size.