text:
Q: JavaScript .click doesnt work in IE 11 I have been trying to get this code working for multi select option sets for dynamic crm. My problem here is that this code works effortlessly in Chrome, does exactly what I want it to but in IE the .click event returns false no matter what, if the check boxes are checked or unchecked.
All this code does is take a option set and converts it to a multi select list and sets value into the two fields "l1s_trainingmodulesvalues" holds the value of the option selected and "l1s_trainingmodules" holds the label of the option selected.
Can some one have a look at what I have been doing wrong.

<title></title>

<meta charset="utf-8">
<form>

</form>

A: Your checkbox variable does not refer to a checkbox element. It's a label (var checkbox = "<input type=\"checkbox\"  name =\"r\">" + rText  + "
"), which does not have a checked state.
Inside your click handler, change
if ($(this).is(':checked'))

to
if ($(this).find('input').is(':checked'))


text:
Q: Golang Reverse Proxy gives 404 when request is proxied to a mock server I created a simple Reverse Proxy Setup using gin-Gonic Routing.
When I try to proxy a local server address it works properly.
But then I tried with a mock server(hosted on the internet) it gives me 404.
So the Flow is
 Request on /config url --> create a new ReverseProxy
This is a reverse Proxy snippet mapped to /Config path
Code snippet:
lib used : "net/http/httputil"

I created a mock server on https://www.mockable.io/
and used http type address.

func serveReverseProxy(target string, res http.ResponseWriter, req *http.Request) {
    // parse the url
    url, _ := url.Parse(target)

    // create the reverse proxy
    proxy := httputil.NewSingleHostReverseProxy(url)

    originalDirector := proxy.Director
    proxy.Director = func(req *http.Request) {
        originalDirector(req)
        req.Header.Set("x-forwarded-host", url.Host)
        req.Header.Set("x-forwarded-server", req.Host)

    }
    //ServeHttp is non blocking and uses a go routine under the hood
    log.Info("Proxy Request to: ",url )
    proxy.ServeHTTP(res, req)
}

Will anyone help me what might be the possible reason I am doing wrong?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android If condition In a android app, I click a button a flag is set to 1 and then I check if its set to 1 to do something. but its not working!
public class MainActivity extends Activity {
    Button button1;
    TextView text1;
    int flag=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);;
        text1 =(TextView) findViewById(R.id.text1);
        button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                flag = 1;
            }
        });

    if(flag == 1 ){
        text1.setText("Manoj Kumar S");

    }
}

This logic doesn't seem to work! Why?

A: Probably you want something like this
public class MainActivity extends Activity {
Button button1;
TextView text1;
int flag=0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);;
    text1 =(TextView) findViewById(R.id.text1);
    button1 = (Button) findViewById(R.id.button1);
    button1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            flag = 1;
            updateTextView();
        }
    });
}

 private void updateTextView() {
   if(flag == 1 ){
    text1.setText("Manoj Kumar S");
   }

 }

}

A: just move the line inside onClick
public class MainActivity extends Activity {
Button button1;
TextView text1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);;
    text1 =(TextView) findViewById(R.id.text1);
    button1 = (Button) findViewById(R.id.button1);
    button1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            text1.setText("Manoj Kumar S");
        }
    });

}

A: In Java, all executable code must be in a method.
if(flag == 1 ){

    text1.setText("Manoj Kumar S");

}

This code is not in a method, and will never be run.  Move it into a method, perhaps as Blackbelt has shown.

A: I also think the logic isn't right there because buttons are event driven as stated by A--C.Try with some different things..
int flag=0;
button1.setOnClickListener(new OnClickListener() {
    public void onClick(View v)
    {
              flag=1;
              test();
    }
});
private void test()
{
    if(flag==1)
        text1.setText("Do your stuff..");
}


text:
Q: How do we know the location of entangled particles after leaving the source so that we can set up our measurement devices? Studying the Bell Inequality and was wondering how exactly experiments like Bell's are conducted. I understand the premise of the experiment to be that an entangled pair of photons or other quantum particles are ejected from a source in equal and opposite direction and energy. So, we set up a filter on one end and then one exactly opposite and wait for the particles to pass through the misaligned filters.
My question is: how do we know where to set the filters? How do we know where the photon will travel? I mean this extremely literally. We have a source emitting entangled photons in the center, and then have a detector which can only measure in one location. Surely the photons do not always travel through that location, only some, and it is only out of those some that we can base our measurements on. Do we just set a filter up in some arbitrary location and only consider the ones that do actually pass through one or the other? I feel like it should be totally unpredictable in which direction entangled photons will leave a source, and it should be random whether or not the photon even travels to the detector.
This matters to me because a model I conceived to attempt to explain the Bell inequalities appears to work but only if I admit that, when a photon is detected here or there, it isn't really there, but rather, similar to how a photon that passes, say, a polarization filter in the X direction is not really perfectly aligned with X, but rather, is more X than not X. So, by some potentially miniscule difference, the photon will be detected as if in this location or that. In other words, when I detect a photon here, it is not really true that the photon moved like a sort of ball linearly from the source to my detector, rather, the photon traveled in a totally unknowable path until measuring, and if I measure a photon at point X, it is not because the photon really is at point X, but rather has some quality that makes it more X than not X.
Even if I have failed to explain my thoughts in the third paragraph, I still need to know how experiments like Bell's are conducted. How can we set up our measuring devices to be sure that the particles will actually encounter them, or are we not sure and can only conduct measurements on particles that happen to pass through them, at random?
I am seeing a link similar to the Uncertainty Principle in which we might be able to know some aspect of the polarization of particles, but at the cost of losing some ability to know their actual location.

A: If you know that momentum and energy are conserved, you can prove that the directions of the two photons must be correlated. In fact, they are so strongly correlated that knowing the direction and energy of one tells you what the direction and energy of the other must be. So you set up one detector at one point, then you know to put your other detector at some other corresponding point, such that you either have each detectors being hit by a photon or neither detector being hit by a photon. Then you have to ignore all of the cases in which no photons arrive at the detectors, which may make you worry a little about loopholes in Bell's inequalities, but that's surmountable.


text:
Q: Find an algorithm to win this battle against crime! A crime committed in a city and the suspect starts to run away. A map of the city is given. At the moment, there are some police cars at some given places and they try to stop the suspect. The car of police and the suspect have a same maximum speed. The suspect can only pass a point if he reaches it earlier than any police car. There are several exits in the map, and the suspect evades if he reaches any of them. Find an algorithm allocating the police cars so that no path can the suspect take to evade.
For example, below is a possible city map.

White circle is where the suspect starts, black circles are police cars, and little squares are exits. In this situation, suspect can be stopped. A possible plan is police car A goes to A', B stays and C goes to C'.

An equivalent description of my problem could be:

A chemical factory (marked by the white circle) explodes and poisonous fluid starts to flow at each possible direction at speed v, and the rescue teams (marked by black circles) whose maximum speed is also v are trying to block it. The little squares are villagers they are protecting.

My Thoughts
If we have n police cars, a highly inefficient approach is to list all possible k-element subsets P of vertices such that:

a) k <= n;
b) Remove all vertices in P in the map will cause any exit unreachable to the suspect;
c) Remove any proper subset of P will let at least one exit reachable to the suspect.

Then we can easily determine if every vertex in P can be covered by a police no later than the suspect.
But how do I list all the possible Ps?

@Lior Kogan:
Look at this map:

If it is a turning game in which both sides knowing other's strategy, the police will win because he can just guard the side where the suspect go.
But in my problem, the police loses because he'll never know which side the suspect may choose.

A: Edit2: Based on your clarifications:
I couldn't find any research concerning the exact posed problem.
Another close subject is virus spread and inoculation in networks. Here are some papers:

*

*Inoculation strategies for victims of viruses and the sum-of-squares partition problem

*Worm Versus Alert: Who Wins in a Battle for Control of a Large-Scale Network?

*Protecting Against Network Infections: A Game Theoretic Perspective
I think that the posed problem is very interesting. Though I believe it is NP-hard.
Sorry for being unable to help any further.
--
Edit1: Changed from Cops and Robbers game to Graph guarding game.
New answer:
This is a variant of the Graph Guarding game.
A team of mobile agents, called guards, tries to keep an intruder out of an assigned area by blocking all possible attacks. In a graph model for this setting, the agents and the intruder are located on the vertices of a graph, and they move from node to node via connecting edges.
See: Guard Games on Graphs and How to Guard a Graph?
In your variant, there are two differences:

*

*You are trying to guard more than one area

*Each guarded area is a single node

--
Original answer:
This is a variant of the well studied Cops and Robbers game.
The Cops and Robbers game is played on undirected graphs where a group of cops tries to catch a robber. The game was defined independently by Winkler-Nowakowski and Quilliot in the 1980s and since that time has been studied intensively. Despite of that, its computation complexity is still an open question.
The problem of determining if k cops can capture a robber on an undirected graph, as well as the problem of computing the minimum number of cops that can catch a robber on a given graph were proven to be NP-hard.
Here are some resources:

*

*Chapter 6 of The Game of Cops and Robbers on Graphs

*On tractability of Cops and Robbers game

*Complexity of Cops and Robber Game

*Talks on GRASTA 2011 (see ch.3)

A: Now I have a clearer view of my problem. Although simpler than the Cops and Robbers Game or Graph Guarding game, it is nevertheless an NP-hard problem.
Two separate tasks this problem can actually be divided into:

Task a) Find a possible set of vertices that cuts the suspect unreachable to any exits.
Task b) Validate if this set of vertices can be all in-timely covered by police cars.

Now we are going to prove that Task a) is NP-complete.
First we consider when there is only one exit. Look at this simple map:

Assign False to a vertex if it is blocked by police and True if it's passable. We know that the suspect can evade if A & (B | D) & C == True. Now we clearly see that Task a) is equivalent to the famous NP-complete Boolean satisfiability problem.
If we have several exits, simply create several boolean expressions and connect them with AND(&).
Task b) is simply a bipartite graph matching problem, can be easily solved by Hungarian algorithm. It's time complexity is O(n^4).
So this whole problem is an NP-hard.


text:
Q: ajax show container not animating as expected I am writing a plugin for showing ajax content.It is wrapped in a ajax-content-wrap.I have applied jquery animate() but not smooth with auto height.And fade() function is also animating.But when i use a specific height animate() works and fadeIn() does not works.
my html codes are below

      //here to show contents from external files

My jquery
$('.ajax-content-show').animate({height:'200px'}, function(){
    $(this).fadeIn('slow', function(){
      $(this).fadeIn('slow').load(url);
    })
});

My css
.ajax-content-show{
   padding: 20px 20px;
   display: block;
   border: 1px solid #eee;
   margin: 10px 0;
}

A: If I understand what you are trying to acheive here is a solution:
$('.ajax-content-show').animate({
    height: '200'
}, 500, "linear",

function () {
    $('.ajax-content-show').hide(0, function () {
        $('.ajax-content-show').load(url, function () {
            $('.ajax-content-show').fadeIn('slow')
        });
    });
});

If not, can you explain (in steps) what you require, first make "div" 200px then fade in "loaded page" or do them both simultaneously?
Note: Don't need to include the 'px' when setting the height property, JQuery assumes pixels as a default.

A: May this you want ?
See snippet.

$(".ajax-content-show").load("https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js", function(){
  $(this).slideDown(10000); // change the time, or just remove it if you think too slow.
  $(this).addClass("loaded");
});
.ajax-content-show{
  padding: 20px 20px;
  display: none;
  border: 1px solid #eee;
  margin: 10px 0;
  height: auto;
  opacity: 0;
  transition: opacity 5s ease;
  max-height: 500px; /* This just for show that sliding is working */
}
.ajax-content-show.loaded {
  opacity: 1;
}

      //here to show contents from external files


text:
Q: Export parquet file schema to JSON or CSV I need to extract schema of parquet file into JSON, TXT or CSV format.
That should include column name, datatype from parquet file.
For example:
{"id", "type" : "integer" },
 {"booking_date""type" : "timestamp", "format" : "%Y-%m-%d %H:%M:%S.%f" }

A: We can read the schema from the parquet file using .schema and convert to json format finally save as textfile.
input parquet file:
spark.read.parquet("/tmp").printSchema()
 #root
 #|-- id: integer (nullable = true)
 #|-- name: string (nullable = true)
 #|-- booking_date: timestamp (nullable = true)

Extract the schema and write to HDFS/local filesystem:
spark.sparkContext.parallelize( #converting from string to rdd
[spark.read.parquet("/tmp").schema.json()] #read schema of parquetfile
 ).repartition(1).\
saveAsTextFile("/tmp_schema/") #saving the file into HDFS

Read the output file from hdfs:
$ hdfs dfs -cat /tmp_schema/part-00000
{"fields":[{"metadata":{},"name":"id","nullable":true,"type":"integer"},{"metadata":{},"name":"name","nullable":true,"type":"string"},{"metadata":{},"name":"booking_date","nullable":true,"type":"timestamp"}],"type":"struct"}


text:
Q: Best way to make N-number of api calls in Angular 9 synchronously (i.e) sequentially I am having a service method to API call in below way:-
getUsers(id){
  return this.http.get(`${env.apiURL}/id`)
}

Now I need to call this method for a list of users present in an Array which is like:-
userId=[1,2,3,4,5,6,7,8,9]

I need to get all the API call results and printed for that I made use of fork-join in below way:-
    let user1= this.http.get(baseurl+'users/userId[1]');
    let user2= this.http.get(baseurl+'users/userId[2]');//In the similar way I have 10 values

    forkJoin([user1, user2]).subscribe(results => {
      // results[0] is our user1
      // results[1] is our user2
    });

But in the above way I was unable to make API calls Sequentially i.e Synchronously all API calls went parallelly which is not my use case.
Is there any best way to make the above n(variable number of users) API calls sequentially?
Note:-I am also having another scenario to keep a delay of 500ms after every API calls is it possible.I tried using
pipe(throttletime(500)) //this i added after forkJoin operation

But All of the API calls went at once

A: There are many ways to accomplish this task.  Here are a couple of them:

Method 1:
  users$ = from(this.userIds).pipe(
    concatMap(id => this.getUser(id)),
    take(this.userIds.length),
    toArray()
  );

Steps:

*

*from - creates observable that emits each array element individually

*concatMap - maps the ID to an observable, subscribes to it, and emits the results.  will only allow a single getUser(id) subscription at a time (synchronously)

*take - instructs our stream how many values to take before completing

*toArray - collects emissions and emits them as an array upon completion

Method 2:
  users$ = from(this.userIds).pipe(
    concatMap(id => this.getUser(id)),
    scan((all: User[], user) => ([...all, user]), []),
  );

Steps:

*

*from

*concatMap

*scan - accumulate emissions into a single array. emits every time a new value is received

Either of these should work fine, but there is a difference in behavior.  Method #1 will emit only one time, after all individual calls have completed.  Method #2 will emit once for every emission.  (If only a single emission is desired, reduce could be used instead)
Check out this StackBlitz to see the differences in output between the two methods.

A: you can achieve this by using concatmap operator to make requests in a specific order.
please refer => https://rxjs-dev.firebaseapp.com/api/operators/concatMap


text:
Q: Fazer validação de IP no javascript / html O usuário informa o ip no campo  e gostaria que completasse com os "." .. Alguém tem alguma ideia de como montar?

            Informe o valor do IP:

            <input type="text" id="ip" name="ip" value="">

Eu tentei essa expressão regular: ^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.)(3)(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$
Mas acabou não funcionando!

A: Você pode usar o jQuery Mask Plugin. Veja:

// jQuery Mask Plugin v1.14.0
// github.com/igorescobar/jQuery-Mask-Plugin
(function(b){"function"===typeof define&&define.amd?define(["jquery"],b):"object"===typeof exports?module.exports=b(require("jquery")):b(jQuery||Zepto)})(function(b){var y=function(a,e,d){var c={invalid:[],getCaret:function(){try{var r,b=0,e=a.get(0),d=document.selection,f=e.selectionStart;if(d&&-1===navigator.appVersion.indexOf("MSIE 10"))r=d.createRange(),r.moveStart("character",-c.val().length),b=r.text.length;else if(f||"0"===f)b=f;return b}catch(g){}},setCaret:function(r){try{if(a.is(":focus")){var c,
b=a.get(0);b.setSelectionRange?(b.focus(),b.setSelectionRange(r,r)):(c=b.createTextRange(),c.collapse(!0),c.moveEnd("character",r),c.moveStart("character",r),c.select())}}catch(e){}},events:function(){a.on("keydown.mask",function(c){a.data("mask-keycode",c.keyCode||c.which)}).on(b.jMaskGlobals.useInput?"input.mask":"keyup.mask",c.behaviour).on("paste.mask drop.mask",function(){setTimeout(function(){a.keydown().keyup()},100)}).on("change.mask",function(){a.data("changed",!0)}).on("blur.mask",function(){n===
c.val()||a.data("changed")||a.trigger("change");a.data("changed",!1)}).on("blur.mask",function(){n=c.val()}).on("focus.mask",function(a){!0===d.selectOnFocus&&b(a.target).select()}).on("focusout.mask",function(){d.clearIfNotMatch&&!p.test(c.val())&&c.val("")})},getRegexMask:function(){for(var a=[],c,b,d,f,l=0;l<e.length;l++)(c=g.translation[e.charAt(l)])?(b=c.pattern.toString().replace(/.{1}$|^.{1}/g,""),d=c.optional,(c=c.recursive)?(a.push(e.charAt(l)),f={digit:e.charAt(l),pattern:b}):a.push(d||
c?b+"?":b)):a.push(e.charAt(l).replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"));a=a.join("");f&&(a=a.replace(new RegExp("("+f.digit+"(.*"+f.digit+")?)"),"($1)?").replace(new RegExp(f.digit,"g"),f.pattern));return new RegExp(a)},destroyEvents:function(){a.off("input keydown keyup paste drop blur focusout ".split(" ").join(".mask "))},val:function(c){var b=a.is("input")?"val":"text";if(0<arguments.length){if(a[b]()!==c)a[b](c);b=a}else b=a[b]();return b},getMCharsBeforeCount:function(a,c){for(var b=0,d=0,
f=e.length;d<f&&d<a;d++)g.translation[e.charAt(d)]||(a=c?a+1:a,b++);return b},caretPos:function(a,b,d,h){return g.translation[e.charAt(Math.min(a-1,e.length-1))]?Math.min(a+d-b-h,d):c.caretPos(a+1,b,d,h)},behaviour:function(d){d=d||window.event;c.invalid=[];var e=a.data("mask-keycode");if(-1===b.inArray(e,g.byPassKeys)){var m=c.getCaret(),h=c.val().length,f=c.getMasked(),l=f.length,k=c.getMCharsBeforeCount(l-1)-c.getMCharsBeforeCount(h-1),n=m<h;c.val(f);n&&(8!==e&&46!==e&&(m=c.caretPos(m,h,l,k)),
c.setCaret(m));return c.callbacks(d)}},getMasked:function(a,b){var m=[],h=void 0===b?c.val():b+"",f=0,l=e.length,k=0,n=h.length,q=1,p="push",u=-1,t,w;d.reverse?(p="unshift",q=-1,t=0,f=l-1,k=n-1,w=function(){return-1<f&&-1<k}):(t=l-1,w=function(){return f<l&&k<n});for(;w();){var x=e.charAt(f),v=h.charAt(k),s=g.translation[x];if(s)v.match(s.pattern)?(m[p](v),s.recursive&&(-1===u?u=f:f===t&&(f=u-q),t===u&&(f-=q)),f+=q):s.optional?(f+=q,k-=q):s.fallback?(m[p](s.fallback),f+=q,k-=q):c.invalid.push({p:k,
v:v,e:s.pattern}),k+=q;else{if(!a)m[p](x);v===x&&(k+=q);f+=q}}h=e.charAt(t);l!==n+1||g.translation[h]||m.push(h);return m.join("")},callbacks:function(b){var g=c.val(),m=g!==n,h=[g,b,a,d],f=function(a,b,c){"function"===typeof d[a]&&b&&d[a].apply(this,c)};f("onChange",!0===m,h);f("onKeyPress",!0===m,h);f("onComplete",g.length===e.length,h);f("onInvalid",0<c.invalid.length,[g,b,a,c.invalid,d])}};a=b(a);var g=this,n=c.val(),p;e="function"===typeof e?e(c.val(),void 0,a,d):e;g.mask=e;g.options=d;g.remove=
function(){var b=c.getCaret();c.destroyEvents();c.val(g.getCleanVal());c.setCaret(b-c.getMCharsBeforeCount(b));return a};g.getCleanVal=function(){return c.getMasked(!0)};g.getMaskedVal=function(a){return c.getMasked(!1,a)};g.init=function(e){e=e||!1;d=d||{};g.clearIfNotMatch=b.jMaskGlobals.clearIfNotMatch;g.byPassKeys=b.jMaskGlobals.byPassKeys;g.translation=b.extend({},b.jMaskGlobals.translation,d.translation);g=b.extend(!0,{},g,d);p=c.getRegexMask();!1===e?(d.placeholder&&a.attr("placeholder",d.placeholder),
a.data("mask")&&a.attr("autocomplete","off"),c.destroyEvents(),c.events(),e=c.getCaret(),c.val(c.getMasked()),c.setCaret(e+c.getMCharsBeforeCount(e,!0))):(c.events(),c.val(c.getMasked()))};g.init(!a.is("input"))};b.maskWatchers={};var A=function(){var a=b(this),e={},d=a.attr("data-mask");a.attr("data-mask-reverse")&&(e.reverse=!0);a.attr("data-mask-clearifnotmatch")&&(e.clearIfNotMatch=!0);"true"===a.attr("data-mask-selectonfocus")&&(e.selectOnFocus=!0);if(z(a,d,e))return a.data("mask",new y(this,
d,e))},z=function(a,e,d){d=d||{};var c=b(a).data("mask"),g=JSON.stringify;a=b(a).val()||b(a).text();try{return"function"===typeof e&&(e=e(a)),"object"!==typeof c||g(c.options)!==g(d)||c.mask!==e}catch(n){}};b.fn.mask=function(a,e){e=e||{};var d=this.selector,c=b.jMaskGlobals,g=c.watchInterval,c=e.watchInputs||c.watchInputs,n=function(){if(z(this,a,e))return b(this).data("mask",new y(this,a,e))};b(this).each(n);d&&""!==d&&c&&(clearInterval(b.maskWatchers[d]),b.maskWatchers[d]=setInterval(function(){b(document).find(d).each(n)},
g));return this};b.fn.masked=function(a){return this.data("mask").getMaskedVal(a)};b.fn.unmask=function(){clearInterval(b.maskWatchers[this.selector]);delete b.maskWatchers[this.selector];return this.each(function(){var a=b(this).data("mask");a&&a.remove().removeData("mask")})};b.fn.cleanVal=function(){return this.data("mask").getCleanVal()};b.applyDataMask=function(a){a=a||b.jMaskGlobals.maskElements;(a instanceof b?a:b(a)).filter(b.jMaskGlobals.dataMaskAttr).each(A)};var p={maskElements:"input,td,span,div",
dataMaskAttr:"*[data-mask]",dataMask:!0,watchInterval:300,watchInputs:!0,useInput:function(a){var b=document.createElement("div"),d;a="on"+a;d=a in b;d||(b.setAttribute(a,"return;"),d="function"===typeof b[a]);return d}("input"),watchDataMask:!1,byPassKeys:[9,16,17,18,36,37,38,39,40,91],translation:{0:{pattern:/\d/},9:{pattern:/\d/,optional:!0},"#":{pattern:/\d/,recursive:!0},A:{pattern:/[a-zA-Z0-9]/},S:{pattern:/[a-zA-Z]/}}};b.jMaskGlobals=b.jMaskGlobals||{};p=b.jMaskGlobals=b.extend(!0,{},p,b.jMaskGlobals);
p.dataMask&&b.applyDataMask();setInterval(function(){b.jMaskGlobals.watchDataMask&&b.applyDataMask()},p.watchInterval)});

$('#ip').mask('0ZZ.0ZZ.0ZZ.0ZZ', {
  translation: {
    'Z': {
      pattern: /[0-9]/, optional: true
    }
  }
});

            Informe o valor do IP:

            <input type="text" id="ip" name="ip" value="">

Links
Mask Plugin
Repositório no Github


text:
Q: How can I choose specific list with Python? loc = list(pyautogui.locateAllOnScreen('img.png'))

It returns list like this:
[Box(left=1315, top=509, width=137, height=35), Box(left=455, top=511, width=137, height=35)]

My question is how can I choose just first list or just second list. Right now I know how to
select only random one with:
if loc
    loc = choice(loc)

A: Your example shows just one list.However if you meant tuple or any iterator just go with loc[0] for first and loc[1] for next and so on.


text:
Q: Количество таблиц в базе MySQL влияет на скорость базы и следовательно скорости сайта? Когда много инфы в базе имеет смысл много таблиц в ней создавать и хранить все в разных местах для распределения нагрузки на базу... чтобы сайт справлялся с нагрузками?
A: Господа развели холивар!
Далее скромное ИМХО:
 1. Таблицы должны быть нормализованы (связи многое-ко-многим, в частности)
 2. Не имеет значение количество таблиц! Главное - правильные запросы и индексы!


text:
Q: If every Terminator was designed for a specific purpose, what was the T-1000 designed for (role in the future)? From the many kinds of Terminators in the franchise, we learned that the T-800 were used for infiltration.
What exactly were the T-1000s used for?
From the Universal Studios promotion, it was shown that these HUGE spider liquid terminators were mainly for protecting the base, so one could say the last line of defense?

A: The T-1000 was a far better, infiltration and assault design than the T-800 making the earlier design obsolete from a production standpoint. Their overall durability eclipsed the T-800 and their mutability allowed them to, once they were able to get into a facility keep changing their appearance, destabilizing a facility due to hesitation. This meant more rebel facilities to be taken out with less effort on Skynet's part.

*

*Though neither design could fool the enhanced senses of a dog, the T-1000 was far better at dispatching a dog silently. (metallic darts, spears, etc.)

*Infiltration with the T-1000 was easier as well. Rather than having to pretend to be a wandering soldier or refugee with a particular face, like the T-800 had to do, the T-1000 could catch a soldier on an operation, torture him for a few minutes (to get his vocal parameters) feign injury and fall in line when the soldiers were on their way home. Gather a few more faces of people along the way and sneak past the defenses to a facility much greater ease.

*The T-1000 took less damage, could withstand more damage, could repair themselves in the field longer and could be used to take out multiple facilities if they were able to stay embedded longer due to their ability to take on new forms.

*The T-1000 was the gift that kept on giving. No worrying about pesky organic flesh going bad, no need to worry about upgrades, or software design errors causing slip ups which broke cover. If cover was broken, learn from the experience, get a new face and try again. This is the ultimate infiltration device, a device with a thousand faces and the reflexes of a human killing machine.
Given the range of effectiveness of the T-1000 unit, there must have been an overwhelming reason more of these units didn't see implementation. They were likely more resource intensive to create than an entire army of T-800s. Skynet may have only produced one and chose to send that one back in time, since in the early 21st century, it likely theorized there was no weaponry there capable of stopping it.

A: The purpose of the T-1000 was also infiltration.
The 800 series terminators are likely easy to recognize and it is expensive to keep coming up with new flesh suits, while the T-1000 can simply transform into a new disguise, or kill someone and take their place.
We see more evidence of this in the Terminator universe in The Sarah Connor Chronicles TV show, where the T-1001 is successfully passing as a human, showing emotion and acting much more in line with a human being.


text:
Q: Set a Boolean as a mysql record indicates if other record exists before chosen timeStamp range basic table is similar to:

mysqlTable:
          visitorID   ,park          ,DateTimeStamp
          8369        ,Birmingham    ,12/27/2018 03:26:38 PM
          8369        ,Birmingham    ,12/28/2018 11:27:32 AM
          8828        ,Central       ,01/02/2019 10:01
          8828        ,Central       ,01/04/2019 9:50
          8825        ,Central       ,12/21/2018 09:47:27 AM
          8821        ,Central       ,12/26/2018 10:11:40 AM
          8821        ,Central       ,02/03/2019 10:00:59 AM
          8821        ,Central       ,01/02/2019 10:04
          88281       ,Central       ,01/04/2019 9:53

From this table i'm creating a new one where i'm counting visitor's ID in a specific park, then grouping the visits by the visitorID and the date of the visit in a specific period of time.

mysql query:

SELECT COUNT(*)AS visits,dateTimeStamp,visitorID
FROM parkVisits
WHERE
    dateTimeStamp BETWEEN '2019-01-01 00:00:01' AND '2019-01-04 23:59:59'
    AND park ='Central'
GROUP BY visitorID, CAST(dateTimeStamp AS DATE);

my result:

mysql table:

visits   ,dateTimeStamp     ,visitorID
2        ,01/02/2019 10:01  ,8828
1        ,01/02/2019 10:04  ,8821
1        ,01/04/2019 9:53   ,88281

I would like to have a column where a Boolean indicates if the visitor has visited anytime before the specified date of it's row.
I was thinking about comparing the earliest dateTimeStamp on table to the earliest given date, but a situation can occur where the first visit and the returning visit occurred during the given period.
expected:

mysql table:

visits   ,dateTimeStamp   ,visitorID    ,returningVisitor
2        ,01/02/2019 10:01,  8828       ,TRUE
1        ,01/02/2019 10:04,  8821       ,FALSE
1        ,01/04/2019 9:53,   88281      ,FALSE

EDIT:
i'm using MySQL 5.6.40

A: Assuming that you are running MySQL 8.0, you could use an inner query with window function FIRST_VALUE to pick up the timestamp of the first visit in the analyzis period. Then in the outer query, an EXISTS clause with a subquery can be used to check if the current visitor has ever visited the same park before.
SELECT
    x.visits,
    x.dateTimeStamp,
    x.visitorID,
    EXISTS (
        SELECT 1 FROM parkVisits WHERE park = x.park AND visitorID = x.visitorID AND dateTimeStamp < x.dateTimeStamp
    ) returningVisitor
FROM (
    SELECT DISTINCT
        COUNT(*) OVER (PARTITION BY p.visitorID) visits,
        FIRST_VALUE(p.dateTimeStamp) OVER (PARTITION BY p.visitorID ORDER BY p.dateTimeStamp) dateTimeStamp,
        p.visitorID,
        p.park
    FROM parkVisits p
    WHERE
        p.dateTimeStamp BETWEEN '2019-01-01 00:00:01' AND '2019-01-04 23:59:59'
        AND p.park ='Central'
) x
ORDER BY 1 desc, 2

In this db fiddle with your sample data, it returns :
| visits | dateTimeStamp       | visitorID | returningVisitor |
| ------ | ------------------- | --------- | ---------------- |
| 2      | 2019-01-02 10:01:00 | 8828      | 0                |
| 1      | 2019-01-02 10:04:00 | 8821      | 1                |
| 1      | 2019-01-04 09:53:00 | 88281     | 0                |

NB : I think the returning visitor is 8821, and not 8828 as shown in your question.
If you are running a lower version of MySQL, that does not support window functions, you can use a GROUP BY clause in the subquery, like :
SELECT
    x.visits,
    x.dateTimeStamp,
    x.visitorID,
    EXISTS (
        SELECT 1 FROM parkVisits WHERE park = x.park AND visitorID = x.visitorID AND dateTimeStamp < x.dateTimeStamp
    ) returningVisitor
FROM (
    SELECT DISTINCT
        COUNT(*) visits,
        MIN(p.dateTimeStamp) dateTimeStamp,
        p.visitorID,
        p.park
    FROM parkVisits p
    WHERE
        p.dateTimeStamp BETWEEN '2019-01-01 00:00:01' AND '2019-01-04 23:59:59'
        AND p.park ='Central'
    GROUP BY p.visitorID, p.park
) x
ORDER BY 1 desc, 2

See this db fiddle.


text:
Q: Are rifts different if you open them in different acts? In the new expansion, does it matter which act you are in when you open a rift? Does it change anything if you open a rift in a different act?

A: Nephalem rifts are a randomized dungeons system. It doesn't matter where you open the rift or the difficuly in which you open it, the place of the rift and the number of level is decided at random.
From the Diablo Wikia

The layouts stem from taking the tilesets and dungeons of the game and
  re-organizing/shuffling them. Monsters are likewise re-shuffled, found
  in combinations otherwise not present. The rifts have 1-10 levels.
  Each level is effectively a different dungeon, with a different
  monster combination.[4] They are accessed via Nephalem Obelisks.


text:
Q: How to set logstash.conf? I'm using elasticsearch 5.1.1 with logstash for using mysql.
logstash.conf
input {
    jdbc {
            jdbc_driver_library => "lib/mysql-connector-java-5.1.33.jar"
            jdbc_driver_class => "com.mysql.jdbc.Driver"
            jdbc_connection_string => "jdbc:mysql://localhost:3306/test"
            jdbc_user => "test"
            jdbc_password => "test"
            statement => "SELECT * FROM test"
            schedule => "* * * * *"
                type => "test"
       }
    jdbc {
            jdbc_driver_library => "lib/mysql-connector-java-5.1.33.jar"
            jdbc_driver_class => "com.mysql.jdbc.Driver"
            jdbc_connection_string => "jdbc:mysql://localhost:3306/test"
            jdbc_user => "test"
            jdbc_password => "test"
            statement => "SELECT * FROM test2"
            schedule => "* * * * *"
                type => "test2"
        }
}

output {
        elasticsearch {
                hosts => ["localhost:9200"]
                 index => "test"
                document_type => "%{type}"
                document_id => "%{test_id}"
        }
}

$ bin/logstash -f logstash.conf
It worked.
But I want to add this options.
{
  "settings": {
    "index": {
      "analysis": {
        "analyzer": {
          "korean": {
            "type": "custom",
            "tokenizer": "seunjeon_default_tokenizer"
          }
        },
        "tokenizer": {
          "seunjeon_default_tokenizer": {
            "type": "seunjeon_tokenizer",
            "index_eojeol": false,
            "user_words": [
              "abc"
            ]
          }
        }
      }
    }
  }
}

How to add this option to conf file?
And If I add more tables which have different column, how to set document_id dynamically?

A: Regarding the first question:

How to add this option to conf file?

I believe the index settings can be set in two different ways

*

*At index creation via index templates

*After index creation in real time via index settings updates
In your case, I suppose the first alternative is better. For that you need to create an index template containing the settings you want to apply to your index or indices when they are created. The value of the "template" key has to match the name of the indices you will be creating ("test" in your example).
I don't think you can add index settings to the logstash configuration file directly. You can upload the template using the REST API (PUT _template/template_name endpoint) or let logstash load your template.
If you want to have logstash create the template, you can refer to a template file in the logstash configuration in the elasticsearch block using the template option. The template file referenced in the logstash config file has to be stored in the same host where logstash is running. You can use the template_overwrite option to control whether or not an existing index template will be overwritten.
The logstash configuration will look like:
output {
    elasticsearch {
            hosts => ["localhost:9200"]
            index => "test"
            document_type => "%{type}"
            document_id => "%{test_id}"
            template => "path/to/the/template/file"
    }

}

The template file would contain:
{
  "template": "test",
  "settings" : {
   "index":{
     "analysis":{
       "analyzer":{
         "korean":{
           "type":"custom",
           "tokenizer":"seunjeon_default_tokenizer"
         }
       },
       "tokenizer": {
         "seunjeon_default_tokenizer": {
           "type": "seunjeon_tokenizer",
           "index_eojeol": false,
           "user_words": ["abc"]
         }
       }
     }
   }
  }
}

You may also want to include mappings in your index template
Hope this helps!
(note that I didn't try this specific scenario)


text:
Q: Display JSON/YAML hierarchy as a tree in HTML? I have YAML data that looks sort of like this, but ~150k of it:
---
all:
  foo: 1025
  bar:
    baz: 37628
    quux:
      a: 179
      b: 7

...or the same thing in JSON:
{"all":{"bar":{"baz":"37628","quux":{"a":"179","b":"7"}},"foo":"1025"}}

I want to present this content in an expandable JavaScripty HTML tree view (examples: 1, 2) to make it easier to explore. How do I do this?
I guess what I really want to figure out is how to take this YAML/JSON data, and automatically display it as a tree (with hash keys sorted alphabetically). So far, I've been tussling with YUI's tree view, but it doesn't accept straight JSON, and my feeble attempts to massage the data into something useful don't seem to be working.
Thanks for any help.

A: You can convert your JSON data to nicely nested DIVs with this. I haven't tested it with a wide number of datasets, but it seems to work.
function renderJSON(obj) {
    'use strict';
    var keys = [],
        retValue = "";
    for (var key in obj) {
        if (typeof obj[key] === 'object') {
            retValue += "
" + key;
            retValue += renderJSON(obj[key]);
            retValue += "
";
        } else {
            retValue += "
" + key + " = " + obj[key] + "
";
        }

        keys.push(key);
    }
    return retValue;
}

A: I finally came up with a super-elegant way to do this in about 5 lines of code, based on the fact that the simple YAML looks a lot like Markdown.
We're starting off with this:
---
all:
  foo: 1025
  bar:
    baz: 37628
    quux:
      a: 179
      b: 7

Use regexps (in this case, in Perl) to remove the starting ---, and put hyphens before the key on each line:
$data =~ s/^---\n//s;
$data =~ s/^(\s*)(\S.*)$/$1- $2/gm;

Voila, Markdown:
- all:
  - foo: 1025
  - bar:
    - baz: 37628
    - quux:
      - a: 179
      - b: 7

Now, just run it through a Markdown processor:
use Text::Markdown qw( markdown );
print markdown($data);

And you get an HTML list -- clean, semantic, backwards-compatible:

all:

foo: 1025

bar:

baz: 37628

quux:

a: 179

b: 7

YUI Treeview can enhance existing lists, so we wrap it all up:

    <link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/combo?2.6.0/build/treeview/assets/skins/sam/treeview.css">

all:

foo: 1025

bar:

baz: 37628

quux:

a: 179

b: 7

So this all works out to about 5 lines of code (turn YAML into Markdown, turn Markdown into an HTML list, and place that HTML list inside a template HTML file. The generated HTML's progressively-enhanced / degradable, since it's fully viewable on non-JavaScript browsers as a plain old list.

A: Version 2.6 of YUI's TreeView now does take a JavaScript object but not in this format and won't sort it automatically.  You would have to use YUI's JSON utility to convert it to an actual JavaScript which you will have to traverse.  Your sample will have to be converted to something like this:
{label:"all", children[
    {label:"bar", children:[
        {label:"baz: 37628"},
        {label:"quux", children[
            {label:"a: 179"},
            {label:"b: 7"}
        ]},
        {label:"foo: 1025"}
    ]}
]}

I've probably missing some comma or something.  Your incoming data might not be sorted so you will have to sort each array.  Then, you just need to pass this object as the second argument to the TreeView constructor and the tree should appear.


text:
Q: How to use tidyr package to average replicate data for different time points and plot each separately? I have a data set of >100 different samples. Samples are from different genotypes (e.g. X, Y, Z) and 4 different time points (T0,1,2,3) with 3 biological replicates (R1,2,3). I'm measuring values for 50 different genes (in rows).
structure(list(Gene = structure(1:2, .Label = c("A", "B"), class = "factor"),
X_T0_R1 = c(1.46559502, 0.220140568), X_T0_R2 = c(1.087642983,
0.237500819), X_T0_R3 = c(1.424945196, 0.21066267), X_T1_R1 = c(1.289943948,
0.207778662), X_T1_R2 = c(1.376535013, 0.488774258), X_T1_R3 = c(1.833390311,
0.182798731), X_T2_R1 = c(1.450753714, 0.247576125), X_T2_R2 = c(1.3094609,
0.390028842), X_T2_R3 = c(0.5953716, 1.007079177), X_T3_R1 = c(0.7906009,
0.730242116), X_T3_R2 = c(1.215333041, 1.012914813), X_T3_R3 = c(1.069312467,
0.780421013), Y_T0_R1 = c(0.053317766, 3.316414959), Y_T0_R2 = c(0.506623748,
3.599442788), Y_T0_R3 = c(0.713670106, 2.516735845), Y_T1_R1 = c(0.740998252,
1.444496448), Y_T1_R2 = c(0.648231834, 0.097957459), Y_T1_R3 = c(0.780499252,
0.187840968), Y_T2_R1 = c(0.35344654, 1.190274584), Y_T2_R2 = c(0.220223951,
1.367784148), Y_T2_R3 = c(0.432856978, 1.403057729), Y_T3_R1 = c(0.234963735,
1.232129062), Y_T3_R2 = c(0.353770497, 0.885122768), Y_T3_R3 = c(0.396091395,
1.333921747), Z_T0_R1 = c(0.398000559, 1.286528398), Z_T0_R2 = c(0.384759325,
1.122251177), Z_T0_R3 = c(1.582230097, 0.697419716), Z_T1_R1 = c(1.136843842,
0.804552001), Z_T1_R2 = c(1.275683837, 1.227821594), Z_T1_R3 = c(0.963349308,
0.968589683), Z_T2_R1 = c(3.765036263, 0.477443352), Z_T2_R2 = c(1.901023385,
0.832736132), Z_T2_R3 = c(1.407713024, 0.911920317), Z_T3_R1 = c(0.988333629,
1.095130142), Z_T3_R2 = c(0.618606729, 0.497458337), Z_T3_R3 = c(0.429823986,
0.471389536)), .Names = c("Gene", "X_T0_R1", "X_T0_R2", "X_T0_R3",
"X_T1_R1", "X_T1_R2", "X_T1_R3", "X_T2_R1", "X_T2_R2", "X_T2_R3",
"X_T3_R1", "X_T3_R2", "X_T3_R3", "Y_T0_R1", "Y_T0_R2", "Y_T0_R3",
"Y_T1_R1", "Y_T1_R2", "Y_T1_R3", "Y_T2_R1", "Y_T2_R2", "Y_T2_R3",
"Y_T3_R1", "Y_T3_R2", "Y_T3_R3", "Z_T0_R1", "Z_T0_R2", "Z_T0_R3",
"Z_T1_R1", "Z_T1_R2", "Z_T1_R3", "Z_T2_R1", "Z_T2_R2", "Z_T2_R3",
"Z_T3_R1", "Z_T3_R2", "Z_T3_R3"), class = "data.frame", row.names =
c(NA, -2L))

For each gene (i.e. each column), I want to plot a graph with an average of replicates of each genotype + SE
expected final graph look
I would like to do this by creating a new data frame; containing for each set of replicates the mean and Std Error.
How is this possible using tidyr package? How can I include Std Error?
How can I improve this coding?
data.mean<- data.frame(matrix(nrows=50))
for(col in seq(1,length(colnames(data)), by=3))
{data.mean <-cbind(data.mean,apply(subset(data, select=seq(col,length.out =   3)),1,mean, na.rm = TRUE))
colnames(data.mean)[ncol(data.mean)] <- colnames(data)[col]}

A: First we need to whip the data into a sensible format. This does the job:
(longdata <- dataset %>%
  gather(key, value, -Gene) %>%
  separate(key, c("Genotype", "Time", "Replicate")))
#> # A tibble: 72 x 5
#>    Gene  Genotype Time  Replicate value
#>    <fct> <chr>    <chr> <chr>     <dbl>
#>  1 A     X        T0    R1        1.47
#>  2 B     X        T0    R1        0.220
#>  3 A     X        T0    R2        1.09
#>  4 B     X        T0    R2        0.238
#>  5 A     X        T0    R3        1.42
#>  6 B     X        T0    R3        0.211
#>  7 A     X        T1    R1        1.29
#>  8 B     X        T1    R1        0.208
#>  9 A     X        T1    R2        1.38
#> 10 B     X        T1    R2        0.489
#> # ... with 62 more rows

It will turn out easier to pre-compute the measures we want to plot:
(longdata <- longdata %>%
  group_by(Gene, Genotype, Time) %>%
  summarize(Ave = mean(value), SE = sd(value)/sqrt(n())) %>%
  ungroup() %>%
  mutate(Time = factor(Time), Genotype = factor(Genotype)))
#> # A tibble: 24 x 5
#>    Gene  Genotype Time    Ave     SE
#>    <fct> <fct>    <fct> <dbl>  <dbl>
#>  1 A     X        T0    1.33  0.120
#>  2 A     X        T1    1.50  0.169
#>  3 A     X        T2    1.12  0.265
#>  4 A     X        T3    1.03  0.125
#>  5 A     Y        T0    0.425 0.195
#>  6 A     Y        T1    0.723 0.0392
#>  7 A     Y        T2    0.336 0.0620
#>  8 A     Y        T3    0.328 0.0482
#>  9 A     Z        T0    0.788 0.397
#> 10 A     Z        T1    1.13  0.0903
#> # ... with 14 more rows

I changed some of the variables into factors because the plotting needs it that way.
Now the plots, with "errorbars" in this case defined as +/- one standard error because you didn't specify, but it can be changed.
longdata %>%
  ggplot(aes(x = Time, y = Ave, fill = Genotype)) +
  geom_bar(position = position_dodge(), stat = "identity") +
  geom_errorbar(aes(ymin = Ave - SE, ymax = Ave + SE),
                width = 0.1,
                position = position_dodge(0.9)) +
  facet_wrap(~ Gene)


text:
Q: adding multiple rows with mysql- array? I'm trying to build a shopping cart by adding the products to the database table "shopping cart" and then get them moved to table "orders". I was told I should make an array of the rows in the shopping cart table to and then loop the INSERT query to put them in the orders table, but can someone explain how? I also read something about "implode" but I'm not really getting that either.
if(isset($_POST['button']))
{
    $query = "SELECT * from members WHERE username='$username'";
    while(list($id, $username, $password, $voornaam, $tussenvoegsel, $achternaam, $adres, $postcode, $telefoonnummer) = mysql_fetch_row($resultaat))
    {
        $adres=$adres2;
        $postcode=$postcode2;
        $query="SELECT * from winkelwagen WHERE username='$username'";
        while(list($username, $diernr, $dier, $aantal, $prijs) = mysql_fetch_row($resultaat))
            $query = "INSERT INTO bestelling (username, leveradres, postcode, dier, aantal)
                    VALUES ('$username', '$adres', '$postcode', '$dier', '$aantal')";
    }
}

A: Well, it could be done simplier with a more complex INSERT statement:
if(isset($_POST['button']))
{
   $query = "INSERT INTO bestelling (username, leveradres, postcode, dier, aantal) ".
            "  SELECT username, adress, postcode, dier, aantval ".
            "    FROM winkelwagen ".
            "   WHERE user_name=? ";
   $stmt = $mysqli->prepare($query);
   $stmt->bind_param("s",$username);
   $stmt->execute();
 }

Make sure $mysqli containis a valid mysqli database connection
I'm sorry I don't know dutch (is it dutch?), so I'¡m not sure I picked up the correct table and field names.... but I hope you get the idea


text:
Q: Finding Non-Empty Cell, Insert Row below, Cut Range and Paste in inserted Row I am new to programming and am self taught, so please excuse my ignorance and mistakes.  I am trying to write a macro to find non-empty cells in column F Rows 1 to 1000 (F1:F1000), then (if data is present) insert a row beneath the value, then cut the  values from column F through J and paste the values in the newly created rows from column A to E.  It would then go to the next non-empty cell in column F and repeat.  Once it's done with column F it would go to column K Rows 1 to 1000, if data is present insert a row beneath the value, then cut the values from dolumn K through O and paste the values in the newly created rows from column A to E.  It would repeat like this through column IP (finding something in column IE, insert row beneath and cut values from IE to IP and paste in A:E.
My code is below.  Any help would be appreciated.
Sub JW_Barcode()

Application.Calculation = xlCalculationManual

Dim rng As Range
For Each rng In Range("F1:F1000")
    If rng.Value <> "" Then
        rng.Offset(1, 0).EntireRow.Insert
    End If
Next
Dim a As Integer
For a = 1 To 1000
On Error GoTo NextColumn
With Columns("F:J")
    .Find(what:="*", after:=.Cells(1, 1), LookIn:=xlValues).Activate
End With
Selection.Cut
With Columns("A:E")
    .Find(what:="", after:=.Cells(1, 1), LookIn:=xlValues).Activate
End With
ActiveSheet.Paste
Next a
NextColumn:

Dim rng2 As Range
For Each rng2 In Range("K1:K1000")
    If rng2.Value <> "" Then
        rng2.Offset(2, 0).EntireRow.Insert
    End If
Next
Dim b As Integer
For b = 1 To 1000
On Error GoTo NextColumn2
With Columns("K:O")
    .Find(what:="*", after:=.Cells(1, 1), LookIn:=xlValues).Activate
End With
Selection.Cut
With Columns("A:E")
    .Find(what:="", after:=.Cells(1, 1), LookIn:=xlValues).Activate
End With
ActiveSheet.Paste
Next b
NextColumn2:

Etc... until it gets to find value in column IE, cut IE:IP and paste in A:E in newly created row.


text:
Q: How to access values deep inside a python list? I am trying get the definitions of certain words using this code:
import requests

url = requests.get("https://api.dictionaryapi.dev/api/v2/entries/en_US/fish")

a = url.text()

print(a)

The link in the above code snippet returns some values like this:
[{"word":"fish","phonetics":[{"text":"/fɪʃ/","audio":"https://lex-audio.useremarkable.com/mp3/fish_us_1.mp3"}],"meanings":[{"partOfSpeech":"noun","definitions":[{"definition":"A limbless cold-blooded vertebrate animal with gills and fins and living wholly in water.","example":"the sea is thick with fish"}]},{"partOfSpeech":"intransitive verb","definitions":[{"definition":"Catch or try to catch fish, typically by using a net or hook and line.","synonyms":["go fishing","angle","cast","trawl"],"example":"he was fishing for bluefish"}]}]},{"word":"fish","phonetics":[{"text":"/fɪʃ/","audio":"https://lex-audio.useremarkable.com/mp3/fish_us_1.mp3"}],"meanings":[{"partOfSpeech":"transitive verb","definitions":[{"definition":"Mend or strengthen (a beam, joint, mast, etc.) with a fish."}]},{"partOfSpeech":"noun","definitions":[{"definition":"A flat plate of metal, wood, or another material that is fixed on a beam or across a joint in order to give additional strength, especially on a ship's damaged mast or spar as a temporary repair."}]}]}]

Now, I want to get the first definition from the above result. How do I get it?

A: try this.
s = [...]
for i in s:
    print(i['word'],[ k['definition'] for j in i['meanings'] for k in j['definitions']])

A: Complex JSON documents and queries to such documents pose a similar problem than manipulating XML documents; One can use a custom set of list comprehensions and utility functions, but one should use a specialized tool.
To manipulate JSON documents in Python, you may have a look at jsonpath_ng:

*

*The item(s) you want to extract are defined using a JSONPath expression, the equivalent of XML's XPath

*You just add / update your JSONPath expression(s) to extract more / new items

In the next example, the JSONPath expressions defined in QUERIES are ran one by one on your JSON document:
import requests
import jsonpath_ng
import json

URL = 'https://api.dictionaryapi.dev/api/v2/entries/en_US/fish'
QUERIES = {
    'First kind, first meaning, first definition': jsonpath_ng.parse('[0].meanings[0].definitions[0].definition'),
    'All kind, first definitions': jsonpath_ng.parse('[*].meanings[0].definitions[0].definition'),
    'All definitions': jsonpath_ng.parse('[*].meanings[*].definitions[*].definition')
}

if __name__ == '__main__':
    jsdata = requests.get(URL).json()
    for name, query in QUERIES.items():
        print(f'--- {name} ---')
        for match in query.find(jsdata):
            print(json.dumps(match.value, indent=2))
        print()


text:
Q: Bluetooth doesn't start up properly when I start up Basically, Bluetooth via my USB dongle doesn't work until after I manually /etc/init.d/bluetooth restart a few times. Is there a way to have it start automagically so I don't have to do this each and every boot?

A: Go to Startup Applications and make sure that Bluetooth Manager is enabled.

A: you can but this command in the startup application choose add new and put this in the command filed.


text:
Q: How to deprecate a function input argument and maintain backward compatibility I would like to change the input arguments of a function. This will also lead to changes within the function body.
What's a pythonic way to mark an input argument "deprecated" and maintain backward compatibility at the same time? Here's a toy example:
from typing import List

# original function
def sum_numbers(numbers: List[int]):
    return sum(numbers)

# function with changed input arguments and function body
def sum_numbers(a: int, b: int) -> int:
    return a + b

The user should be able to call sum_numbers either with numbers: List[int] argument or by using a: int, b: int. However, I want to submit a DeprecationWarning when the user uses the original call method.

A: An option is to overload the function using multipledispatch module:
from multipledispatch import dispatch

@dispatch(int, int)
def sum_numbers(a, b):
    print("Deprecated")
    return a + b

@dispatch(list)
def sum_numbers(numbers):
    return sum(numbers)

A: An alternative to multipledispatch is to take in *args or have an optional arg and dispatch internally:
# original function
def sum_numbers(a, b=None):
    if isinstance(a, list):
        warnings.warn("...", DeprecationWarning, stacklevel=2)
        return sum(numbers)
    return a + b

then for typing purposes you can use typing.overload:
@typing.overload
def sum_numbers(numbers: list[int]) -> int:
    """deprecated"""
@typing.overload
def sum_numbers(a: int, b: int) -> int:
    ...

(note that as documented the overloads should come first and the actual implementation last)


text:
Q: How to create a PIVOT using two tables I have two tables:
Table1:
+---------------+--------+--------+--------+--------+--------+--------+--------+--------+
|     Category  |  Name  |  Goal  |  WK40  |  WK41  |  WK42  |  WK43  |  WK44  |  WK 45 |
+---------------+--------+--------+--------+--------+--------+--------+--------+--------+
|     Data      |  Data  |  Data  |  Data  |  Data  |  Data  |  Data  |  Data  |  Data  |
+---------------+--------+--------+--------+--------+--------+--------+--------+--------+

Table2:
+-------+--------+--------+--------+--------+-------+
|  W1   |   W2   |   W3   |   W4   |   W5   |   W6  |
+-------+--------+--------+--------+--------+-------+
| WK40  |  WK41  |  WK42  |  WK43  |  WK44  |  WK45 |
+-------+--------+--------+--------+--------+-------+

In Table 1, the WK40, WK41 etc. column names are dynamic (i.e., these column names change every week depending on the current week of the year & then shows the last 6 weeks). Table 1 has all the required data.
In Table 2, the column names are W1, W2, ...W6 and the column name here is static. But the data in each column (WK40, WK41....) changes every week based on the current week.
I want to create a table like this:
+---------------+--------+--------+--------+--------+--------+--------+--------+---------+
|     Category  |  Name  |  Goal  |   W1   |   W2   |   W3   |   W4   |   W5   |   W6    |
+---------------+--------+--------+--------+--------+--------+--------+--------+---------+
|     Data      |  Data  |  Data  |  Data  |  Data  |  Data  |  Data  |  Data  |  Data   |
+---------------+--------+--------+--------+--------+--------+--------+--------+---------+

I've never used PIVOT before so need help creating one for this. Thanks.


text:
Q: Combining data from three tables in one view in Django I have done a lot of searches and found some amazing answers on this topic for the last couple of days while I try to figure this out. But none of those worked for me, as it seems the situation is different than the earlier posted answers, or not working with my version of Django. So here goes:
I need to get data from 3 tables and displayed certain columns on a webinterface. I have no problem getting one table, but the other two (linked by foreign keys) I can't seem to get into the view. The code I have is as follows (mind you, I am learning python and django):
models.py:
class students(models.Model):
    date_created = models.DateTimeField()
    project = models.ForeignKey('projects',models.SET_NULL,blank=True,null=True,)
    name = models.TextField()
    return_date = models.TextField()

class sysinfo(models.Model):
    student = models.ForeignKey('students',models.SET_NULL,blank=True,null=True,)
    machine = models.TextField(blank=True, null=True)
    version = models.TextField(blank=True, null=True)
    platform = models.TextField(blank=True, null=True)
    hostname = models.TextField(blank=True, null=True)

class projects(models.Model):
    project_name = models.TextField()
    date_created = models.DateTimeField()
    date_closed = models.DateTimeField(blank=True, null=True)

views.py
from django.shortcuts import render
from front.models import students, projects, sysinfo

# Create your views here.
def index(request):
    list_students = students.objects.select_related('projects','sysinfo').order_by('-last_seen')
    return render(request, 'main/home.html',{'students': list_students})

This shows the student id and the date created and return date on the webinterface, but I can't seem to figure out to get the project name from the projects table, or the system information from sysinfo.
I have tried adding .values('projects__project_name','sysinfo__hostname'...etc.) to the views.py select_related line. But I only get errors saying that my choices are the fields in the students table.
I have lost track of everything I tried, but safe to say, the documentation by now is really not making any sense to me anymore. (The fact I create an account for SO just to ask this question should say plenty :P)
Thanks in advance all

A: First let's fix the query. You want to use select_related for projects and prefetch_related for sysinfo (note that with your model a student has zero, one or many sysinfo). Also you want to use the foreignkey field name for selected_related and the reverse relationship name (in your case the default sysinfo_set) for sysinfo. And finally, you have no last_seen field in your students model...
def index(request):
    list_students = students.objects.select_related('project').prefetch_related('sysinfo_set')

Now in your template:

  {% for student in students %}

    {{ student.name }}
    {{ student.project.project_name }}

       {% for sysinfo in student.sysinfo_set.all %}
       {{ sysinfo.host_name }}
       {% endfor %}

  {% endfor %}

As a side note: the Python convention is to use CamelCase for class names, and the Django convention is to use singular for models names, so your models should be named Student, Project and SysInfo.


text:
Q: How to put a comparison in a multidatatrigger How can we put a comparison in a MultiDataTrigger? Ina normal DataTrigger, we could put it as such:
<i:Interaction.Triggers>
       <ei:DataTrigger Binding="{Binding Count}" Comparison="LessThan" Value="5">
           <ei:ChangePropertyAction PropertyName="IsEnabled" Value="False"/>
       </ei:DataTrigger>
 </i:Interaction.Triggers>

But how do we put a comparison like this in a MultiDataTrigger condition? I searched, but couldn't find any solution. Please help. Thanks.

A: You can use PropertyChangedTrigger (msdn):
In the below example we check condition is greater than 1 and less than 100 for Count property:
<TextBlock x:Name="textBlock" Background="Green" Text="{Binding Path=Count}">
    <i:Interaction.Triggers>
        <ei:PropertyChangedTrigger Binding="{Binding Path=Count}">
            <i:Interaction.Behaviors>
                <ei:ConditionBehavior>
                    <ei:ConditionalExpression>
                        <ei:ComparisonCondition LeftOperand="{Binding Count}" Operator="NotEqual" RightOperand="{x:Null}" />
                        <ei:ComparisonCondition LeftOperand="{Binding Count}" Operator="GreaterThan" RightOperand="1" />
                        <ei:ComparisonCondition LeftOperand="{Binding Count}" Operator="LessThan" RightOperand="100" />
                    </ei:ConditionalExpression>
                </ei:ConditionBehavior>
            </i:Interaction.Behaviors>
            <ei:ChangePropertyAction PropertyName="Background">
                <ei:ChangePropertyAction.Value>
                    <SolidColorBrush Color="Red"/>
                </ei:ChangePropertyAction.Value>
            </ei:ChangePropertyAction>
        </ei:PropertyChangedTrigger>
    </i:Interaction.Triggers>
</TextBlock>

A: You can create a converter in the binding that returns true or false depending on what you want. Then instead of 'Value="5"', you should put
Value={StaticResource True}

and you define the static resource
<Application.Resources>
    ...
    <s:Boolean x:Key="True">True</s:Boolean>
    <s:Boolean x:Key="False">False</s:Boolean>
</Application.Resources>


text:
Q: C# Platform-invoke, c-style union with reference and value types I am trying to Marshall the following structure
struct OpalMessage {
  OpalMessageType m_type;   ///< Type of message
  union {
    const char *             m_commandError;       ///< Used by OpalIndCommandError
    OpalParamGeneral         m_general;            ///< Used by OpalCmdSetGeneralParameters
    OpalParamProtocol        m_protocol;           ///< Used by OpalCmdSetProtocolParameters
    OpalParamRegistration    m_registrationInfo;   ///< Used by OpalCmdRegistration
    OpalStatusRegistration   m_registrationStatus; ///< Used by OpalIndRegistration
    OpalParamSetUpCall       m_callSetUp;          ///< Used by OpalCmdSetUpCall/OpalIndProceeding/OpalIndAlerting/OpalIndEstablished
    const char *             m_callToken;          ///< Used by OpalCmdHoldcall/OpalCmdRetrieveCall/OpalCmdStopRecording
    OpalStatusIncomingCall   m_incomingCall;       ///< Used by OpalIndIncomingCall
    OpalParamAnswerCall      m_answerCall;         ///< Used by OpalCmdAnswerCall/OpalCmdAlerting
    OpalStatusUserInput      m_userInput;          ///< Used by OpalIndUserInput/OpalCmdUserInput
    OpalStatusMessageWaiting m_messageWaiting;     ///< Used by OpalIndMessageWaiting
    OpalStatusLineAppearance m_lineAppearance;     ///< Used by OpalIndLineAppearance
    OpalStatusCallCleared    m_callCleared;        ///< Used by OpalIndCallCleared
    OpalParamCallCleared     m_clearCall;          ///< Used by OpalCmdClearCall
    OpalStatusMediaStream    m_mediaStream;        ///< Used by OpalIndMediaStream/OpalCmdMediaStream
    OpalParamSetUserData     m_setUserData;        ///< Used by OpalCmdSetUserData
    OpalParamRecording       m_recording;          ///< Used by OpalCmdStartRecording
    OpalStatusTransferCall   m_transferStatus;     ///< Used by OpalIndTransferCall
    OpalStatusIVR            m_ivrStatus;          ///< Used by OpalIndCompletedIVR
  } m_param;
};

over to C#. The obvious problem is the two strings which will inevitably be reference types.
So, I tried this:
    [StructLayout(LayoutKind.Explicit)]
    public struct OpalMessageStrUnion
    {
      [FieldOffset(0)]
      [MarshalAs(UnmanagedType.LPStr)]
      public string m_commandError;       ///< Used by OpalIndCommandError

      [FieldOffset(0)]
      [MarshalAs(UnmanagedType.LPStr)]
      public string m_callToken;          ///< Used by OpalCmdHoldcall/OpalCmdRetrieveCall/OpalCmdStopRecording
    }

    [StructLayout(LayoutKind.Explicit)]
    public struct OpalMessageUnion
    {
      [FieldOffset(0)]
      public OpalParamGeneral m_general;            ///< Used by OpalCmdSetGeneralParameters

      [FieldOffset(0)]
      public OpalParamProtocol m_protocol;           ///< Used by OpalCmdSetProtocolParameters

      [FieldOffset(0)]
      public OpalParamRegistration m_registrationInfo;   ///< Used by OpalCmdRegistration

      [FieldOffset(0)]
      public OpalStatusRegistration m_registrationStatus; ///< Used by OpalIndRegistration

      [FieldOffset(0)]
      public OpalParamSetUpCall m_callSetUp;          ///< Used by OpalCmdSetUpCall/OpalIndProceeding/OpalIndAlerting/OpalIndEstablished

      [FieldOffset(0)]
      public OpalStatusIncomingCall m_incomingCall;       ///< Used by OpalIndIncomingCall

      [FieldOffset(0)]
      public OpalParamAnswerCall m_answerCall;         ///< Used by OpalCmdAnswerCall/OpalCmdAlerting

      [FieldOffset(0)]
      public OpalStatusUserInput m_userInput;          ///< Used by OpalIndUserInput/OpalCmdUserInput

      [FieldOffset(0)]
      public OpalStatusMessageWaiting m_messageWaiting;     ///< Used by OpalIndMessageWaiting

      [FieldOffset(0)]
      public OpalStatusLineAppearance m_lineAppearance;     ///< Used by OpalIndLineAppearance

      [FieldOffset(0)]
      public OpalStatusCallCleared m_callCleared;        ///< Used by OpalIndCallCleared

      [FieldOffset(0)]
      public OpalParamCallCleared m_clearCall;          ///< Used by OpalCmdClearCall

      [FieldOffset(0)]
      public OpalStatusMediaStream m_mediaStream;        ///< Used by OpalIndMediaStream/OpalCmdMediaStream

      [FieldOffset(0)]
      public OpalParamSetUserData m_setUserData;        ///< Used by OpalCmdSetUserData

      [FieldOffset(0)]
      public OpalParamRecording m_recording;          ///< Used by OpalCmdStartRecording

      [FieldOffset(0)]
      public OpalStatusTransferCall m_transferStatus;     ///< Used by OpalIndTransferCall

      [FieldOffset(0)]
      public OpalStatusIVR m_ivrStatus;          ///< Used by OpalIndCompletedIVR

    }

    /// <summary>
    /// Message to/from OPAL system.
    /// This is passed via the OpalGetMessage() or OpalSendMessage() functions.
    /// </summary>
    [StructLayout(LayoutKind.Explicit)]
    public struct OpalMessage
    {
      //this guy is an enumeration b.t.w.
      /// <summary>
      /// type of message
      /// </summary>
      [FieldOffset(0)]
      public OpalMessageType m_type;

      [FieldOffset(4)]
      public OpalMessageUnion m_param;

      [FieldOffset(4)]
      public OpalMessageStrUnion m_strParam;
    }

However, I am still getting the marshaling error telling me that this won't work because I am mixing an object with non-object types in the same memory location. I am now assuming that the structures themselves (i.e. OpalParamGeneral and the like) also cannot mix reference and value types even though they are laid out sequentially?
Doing a separate function call for each structure is not an option by the way. I would rather write a COM wrapper than do that.

A: The [StructLayout(LayoutKind.Explicit)] attribute is unusual, it affects the layout of a structure not only when it is marshaled but also affects the layout of the managed version of a struct.  Which can be quite handy, it allows implementing unions in a managed language even when the language itself doesn't support it.
They cause trouble however, the garbage collector has a problem with them.  It needs to be able to find references to reference types and cannot do so reliably in a union.  Since it cannot tell exactly what type is referenced.  It is also a reliability problem, you could overlap a reference type with, say, an IntPtr and discover the address of the object that way.
The CLR class loader checks for this condition and throws a TypeLoadException if overlap occurs.
The workaround for this is clear, you need to make sure to only use blittable types.  All of your OpalXxx types need to be structures that themselves contain only blittable types.  The workaround for the strings is to declare them as IntPtr instead and use the Marshal class to convert the values.  More about blittable types in this MSDN library article.


text:
Q: JavaScript trim all own property key names of an object? How to trim all own (not inherited) property keys / names of an object? To trim the key name, not the property's value.
PS. Closest similar question I found is about trimming property values: javascript : trim all properties of an object
EDIT: This question was suggested as a possible duplicate. However, I'm explicitly needing to trim just the key name, not the value: Trim white spaces in both Object key and value recursively

A: As far as i understood, Object.keys() or Object.entries() should do the job.

const obj = { "a " : 1 , "   b " : 2 };

const trimmed = Object.entries(obj).reduce((acc, curr) => {
  let [key, value] = curr;
  // Checking if the key is a string
  acc[typeof key === "string" ? key.trim() : key] = value;
  return acc;
}, {});

console.log(trimmed); // -> { a: 1, b: 2 } notice the trimmed keys

A: You could test if the key is a string (and not Symbol) and trim this value and get a new object with Object.fromEntries

const
    obj = { "a " : 1 , "   b " : 2 },
    trimmed = Object.fromEntries(Object.entries(obj).map(([k, v]) => [
        typeof k === 'string' ? k.trim() : k,
        v
    ]));

console.log(trimmed);


text:
Q: SharePoint Organization Profiles I noticed that SharePoint User Profile Service now includes a definition for Organization Profiles.  I think this is a really interesting new feature, but I'm not sure how it is used inside of SharePoint 2010.  I found some information concerning the people picker, but not much outside of that.
So I am wondering if anyone is using Organization Profiles and if so how?

A: I seem to remember hearing that this is a feature that was supposed to more substantial but basically got cut from the 2010 release. So I don't think you can do much with them in this version of SharePoint.

A: Organization Profiles were not fully realized or documented in the 2010 system. If you're planning on using them, don't. They're deprecated in 2013 and no longer available so any investment today will be lost tomorrow in this space.


text:
Q: Python Pandas Pass Argument to Group by two or more columns I'm trying to use a function to group by several columns by passing the columns into the function but I can't seem to get the correct syntax and I keep getting errors.
The code works when passing one column to group.
Any advice would be most welcome.
The code is:
groupby = (['HxHorse', 'Jockey', 'Trainer'])
avgof = 'Hrs'
avgcol = 'Hrsmean'
colname = 'Hrs'
df_racecard = getagg(df_racecard, df_hrsall, groupby, avgof, avgcol, colname)

And the function is:
def getagg(df_racecard, df_hrsall, groupby, avgof, avgcol, colname):
    hrs_agg = df_hrsall.groupby([groupby], as_index=False).agg({avgof: ['mean']})
    hrs_agg.columns = ["".join(x) for x in hrs_agg.columns.ravel()]
    hrs_agg.rename(columns = {avgcol:colname}, inplace = True)
    df_racecard = pd.merge(left=df_racecard, right=hrs_agg[[groupby, colname]], left_on='Horse', right_on='HxHorse', how='left')
    df_racecard = df_racecard.drop(['HxHorse'], axis=1)
    return df_racecard

The function works with :
groupby = 'HxHorse'
avgof = 'Hrs'
avgcol = 'Hrsmean'
colname = 'Hrs'
df_racecard = getagg(df_racecard, df_hrsall, groupby, avgof, avgcol, colname)

It seems to fail at:
df_hrsall.groupby([groupby]

I've tried variations of groupby = (['HxHorse', 'Jockey', 'Trainer']) such as groupby = [['HxHorse'], ['Jockey'], ['Trainer']]


text:
Q: Scipy's fmin sticks only on inf only sometimes I'm using Scipy's fmin search to compute the log of the likelihood of a distribution's fit to some data. I'm using fmin to search for the parameters that maximize the log likelihood, like so:
j = fmin(lambda p:-sum(log(likelihood_calculator(data, p))), array([1.5]), full_output=True)

(likelihood_calculator takes data and a parameter and spits out an array of likelihood values for each data point.)
If we start that search with a parameter that yields a likelihood of 0, the loglikelihood is -inf, so the -sum is inf. fmin should run away from the initial parameter, but instead it sticks on that value for the maximum number of calls, then returns it:
In [268]: print j
(array([ 1.5]), inf, 67, 200, 1)

I thought this was perhaps a problem with fmin's handling of infs, but if we remove the likelihood calculator and just hand a 0 directly, we get better behavior:
In [269]: i = fmin(lambda p: -sum(log(p)), array([0]), full_output=1)
Warning: Maximum number of function evaluations has been exceeded.

In [270]: i
Out[270]: (array([  3.16912650e+26]), -61.020668415892501, 100, 200, 1)

This same correct behavior happens if we use an array of zeros, if those zeros are floats, or if we use fmin_bfgs. The same incorrect behavior with the function call continues if we use fmin_bfgs, but fmin works CORRECTLY if we start with a parameter that doesn't yield a 0 likelihood (and thus any infs).
Thoughts? Thanks!
Update:
If there's a broad area of parameters that result in zeros, we can push the parameter value up to the edge. If the parameter is near enough the edge, fmin will get out of zeroland and start searching.
Ex. p<1 = Inf, then at p=.99 fmin will work, but not at p=.95

A: Maybe your update answers the question. Since fmin uses a downhill gradient algorithm, it searches in a neighborhood of the initial guess for the direction of steepest descent. If you are deep enough into a parameter-region where the function always returns inf then the algorithm can not see which direction to go.


text:
Q: How do I set use_ssl param when running a web request through a proxy? I'm using Rails 4.2.7.  How do I set the "use_ssl" parameter when sending a web request through a proxy?  I have this
    res1 = Net::HTTP.SOCKSProxy(TCPSocket::socks_server, TCPSocket::socks_port).start(uri.host, uri.port) do |http|
      http.use_ssl = (uri.scheme == "https")
      resp = http.get(uri, initheader = headers)
      status = resp.code.to_i
      if status == 302 || status == 301
        redirect = resp['location']
      end
      content = resp.body
      content_type = resp['content-type']
      content_encoding = resp['content-encoding']
    end

But when I get to this line — "http.use_ssl = (uri.scheme == "https")" I get the exception
IOError: use_ssl value changed, but session already started
    from /Users/davea/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/net/http.rb:758:in `use_ssl='
    from /Users/davea/Documents/workspace/myproject/app/helpers/webpage_helper.rb:96:in `block in get_content'
    from /Users/davea/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/net/http.rb:853:in `start'
    from /Users/davea/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/net/http.rb:584:in `start'
    from /Users/davea/Documents/workspace/myproject/app/helpers/webpage_helper.rb:94:in `get_content'
    from /Users/davea/Documents/workspace/myproject/app/helpers/webpage_helper.rb:33:in `get_url'
    from (irb):1
    from /Users/davea/.rvm/gems/ruby-2.3.0/gems/railties-4.2.7.1/lib/rails/commands/console.rb:110:in `start'
    from /Users/davea/.rvm/gems/ruby-2.3.0/gems/railties-4.2.7.1/lib/rails/commands/console.rb:9:in `start'
    from /Users/davea/.rvm/gems/ruby-2.3.0/gems/railties-4.2.7.1/lib/rails/commands/commands_tasks.rb:68:in `console'
    from /Users/davea/.rvm/gems/ruby-2.3.0/gems/railties-4.2.7.1/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
    from /Users/davea/.rvm/gems/ruby-2.3.0/gems/railties-4.2.7.1/lib/rails/commands.rb:17:in `<top (required)>'
    from bin/rails:4:in `require'
    from bin/rails:4:in `<main>'

A: according to this test sample, line 109:
https://github.com/astro/socksify-ruby/blob/master/test/tc_socksify.rb#L109
I'd try something like this:
res1 = Net::HTTP.SOCKSProxy(TCPSocket::socks_server, TCPSocket::socks_port).start(
  uri.host, uri.port, :use_ssl => (uri.scheme == "https")) do |http|

  resp = http.get(uri, initheader = headers)
  status = resp.code.to_i
  if status == 302 || status == 301
    redirect = resp['location']
  end
  content = resp.body
  content_type = resp['content-type']
  content_encoding = resp['content-encoding']
end

if you don't have a valid SSL cert, you can disable SSL validation like this (not recommended for production!)
https://github.com/astro/socksify-ruby/blob/master/test/tc_socksify.rb#L110

A: Have you tried using the use_ssl before start like shown below
res1 = Net::HTTP.SOCKSProxy(TCPSocket::socks_server, TCPSocket::socks_port)
res1.use_ssl = (uri.scheme == "https")
res1.start(uri.host, uri.port) do |http|
  resp = http.get(uri, initheader = headers)
  status = resp.code.to_i
  if status == 302 || status == 301
    redirect = resp['location']
  end
  content = resp.body
  content_type = resp['content-type']
  content_encoding = resp['content-encoding']
end


text:
Q: Gson conversion to Json with two date format is not working I have two date formats which are from server Json . yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd are my date formats.
So I tried to convert this Json to Gson with following codes.
GsonBuilder gsonBuilder = new GsonBuilder().registerTypeAdapter(Date.class, new DateDeserializer());
Gson gson = gsonBuilder.create();

These are my date formats,
private static final String[] DATE_FORMATS = new String[] {
            "yyyy-MM-dd'T'HH:mm:ss",
            "yyyy-MM-dd"
};

private class DateDeserializer implements JsonDeserializer<Date> {

     @Override
     public Date deserialize(JsonElement jsonElement, Type typeOF,
                                JsonDeserializationContext context) throws JsonParseException {
          for (String format : DATE_FORMATS) {
                try {
                  return new SimpleDateFormat(format, Locale.US).parse(jsonElement.getAsString());
                } catch (ParseException e) {
                }
          }
          throw new JsonParseException("Unparseable date: \"" + jsonElement.getAsString()
                    + "\". Supported formats: " + Arrays.toString(DATE_FORMATS));
      }

}

Update
This is my Json object,
{
  "idpatient": 56,
  "diabetesType": null,
  "language": null,
  "customId": "CUS790",
  "diabetesOther": null,
  "firstName": "Niro",
  "lastName": "Wije",
  "email": "sahirml@gmail.com",
  "dob": "1989-10-11",
  "parentEmail": null,
  "gender": "male",
  "diagnosedDate": "2016-11-11",
  "height": 0,
  "weight": 0,
  "heightUnit": null,
  "weightUnit": null,
  "theme": "Lite",
  "userName": "weera",
  "password": "asdf9999",
  "dateCreated": 1478880594000,
  "lastUpdated": 1478880594000
}

Then I tried to convert a Json object to Gson object by using this. I got following error log.
11-11 16:11:17.735 28072-28072/my.api.example W/System.err: com.google.gson.JsonParseException: Unparseable date: "1478880594000". Supported formats: [yyyy-MM-dd'T'HH:mm:ss, yyyy-MM-dd]
11-11 16:11:17.755 28072-28072/my.api.example W/System.err:     at my.api.example.activities.LoginActivity$DateDeserializer.deserialize(LoginActivity.java:180)
11-11 16:11:17.755 28072-28072/my.api.example W/System.err:     at my.api.example.activities.LoginActivity$DateDeserializer.deserialize(LoginActivity.java:168)
11-11 16:11:17.755 28072-28072/my.api.example W/System.err:     at com.google.gson.TreeTypeAdapter.read(TreeTypeAdapter.java:58)
11-11 16:11:17.755 28072-28072/my.api.example W/System.err:     at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:103)
11-11 16:11:17.755 28072-28072/my.api.example W/System.err:     at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:196)
11-11 16:11:17.755 28072-28072/my.api.example W/System.err:     at com.google.gson.Gson.fromJson(Gson.java:810)
11-11 16:11:17.755 28072-28072/my.api.example W/System.err:     at com.google.gson.Gson.fromJson(Gson.java:775)
11-11 16:11:17.755 28072-28072/my.api.example W/System.err:     at retrofit.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:36)
11-11 16:11:17.755 28072-28072/my.api.example W/System.err:     at retrofit.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:24)
11-11 16:11:17.755 28072-28072/my.api.example W/System.err:     at retrofit.OkHttpCall.parseResponse(OkHttpCall.java:148)
11-11 16:11:17.755 28072-28072/my.api.example W/System.err:     at retrofit.OkHttpCall.access$100(OkHttpCall.java:29)
11-11 16:11:17.755 28072-28072/my.api.example W/System.err:     at retrofit.OkHttpCall$1.onResponse(OkHttpCall.java:94)
11-11 16:11:17.755 28072-28072/my.api.example W/System.err:     at com.squareup.okhttp.Call$AsyncCall.execute(Call.java:168)
11-11 16:11:17.755 28072-28072/my.api.example W/System.err:     at com.squareup.okhttp.internal.NamedRunnable.run(NamedRunnable.java:33)
11-11 16:11:17.755 28072-28072/my.api.example W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
11-11 16:11:17.755 28072-28072/my.api.example W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
11-11 16:11:17.755 28072-28072/my.api.example W/System.err:     at java.lang.Thread.run(Thread.java:841)
11-11 16:11:17.755 28072-28072/my.api.example D/LOGIN_ACTIVITY:  ERROR_MESSAGE Unparseable date: "1478880594000". Supported formats: [yyyy-MM-dd'T'HH:mm:ss, yyyy-MM-dd]

It means this method is not working for my date formats.
How could I handle this exception ?
Have any ideas ?

A: As per the error, you shared the server is returning date in
Milliseconds and not the format your expected.
com.google.gson.JsonParseException: Unparseable date: "1478880594000". Supported formats: [yyyy-MM-dd'T'HH:mm:ss, yyyy-MM-dd].
First you need to convert to Date, then format as per your requirement.

A: update this line
return new SimpleDateFormat(format, Locale.US).format(new Date(jsonElement));

hope this will work.

A: From the logs, I can see that you are not passing java.util.Date, but a timestamp (long) and you are registering type adapter for java.util.Date class.


text:
Q: How can I retrieve similar rows from different tables in the same query? Let's say I have two or more tables filled with users and I want to retrieve all users from those tables in the same query.
Tables share some columns and those columns that have the same name are the ones I'm trying to retrieve.
Something like:
SELECT name, age FROM users1;
SELECT name, age FROM users2;
etc.

Note: this is just an example and not the real problem. I cannot combine those tables into one.

A: You can use UNION:

UNION is used to combine the result from multiple SELECT  statements into a single result set.
The column names from the first SELECT statement are used as the column names for the results returned. Selected columns listed in corresponding positions of each SELECT statement should have the same data type.

An example:
mysql> SELECT 1 as ColumnA,'a' as ColumnB
    -> UNION
    -> SELECT 2, 'b'
    -> UNION
    -> SELECT 3, 'c';
+---------+---------+
| ColumnA | ColumnB |
+---------+---------+
|       1 | a       |
|       2 | b       |
|       3 | c       |
+---------+---------+
3 rows in set (0.05 sec)

Also note:

The default behavior for UNION is that duplicate rows are removed from the result. The optional DISTINCT keyword has no effect other than the default because it also specifies duplicate-row removal. With the optional ALL keyword, duplicate-row removal does not occur and the result includes all matching rows from all the SELECT statements.

An example:
mysql> SELECT 1 as x
    -> UNION
    -> SELECT 1;
+---+
| x |
+---+
| 1 |
+---+
1 row in set (0.00 sec)

mysql> SELECT 1 as x
    -> UNION ALL
    -> SELECT 1;
+---+
| x |
+---+
| 1 |
| 1 |
+---+
2 rows in set (0.00 sec)

A: You can use union or union all, depending on what behaviour you want:
select name, age from users1
union
select name, age from users2
union
select name, age from users3

or:
select name, age from users1
union all
select name, age from users2
union all
select name, age from users3

The difference is that union removes duplicates, while union all doesn't.
If you know that there are no duplicates, you should use union all so that the database doesn't have to make the extra work of trying to find duplicates.

A: Try
SELECT name, age FROM users1
UNION
SELECT name, age FROM users2

A: note also that 'union all' will be much faster than 'union.


text:
Q: Copy emails with a specific Gmail label to Spreadsheet, without duplicates I am trying to make a script that takes an email within a certain label and puts it into Google Sheets. I'm using this function at the moment:
function getMessagesWithLabel() {
 var destArray = new Array();
  var threads = GmailApp.getUserLabelByName('Facebook').getThreads(0,10);

  for(var n in threads){
        var msg = threads[n].getMessages();
        var destArrayRow = new Array();
        destArrayRow.push('thread has '+threads[n].getMessageCount()+' messages');
          for(var m in msg){
                     destArrayRow.push(msg[m].getSubject());
           }
  destArray.push(destArrayRow);
        }
Logger.log(destArray);
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getActiveSheet();
if(ss.getLastRow()==0){sh.getRange(1,1).setValue('getMessagesWithLabel() RESULTS')};
sh.getRange(ss.getLastRow()+1,1,destArray.length,destArray[0].length).setValues(destArray)
}

This works at grabbing all the emails in the 'Facebook' label but grabs all the emails every time, creating duplicates every time it runs. I would like for it to just create a new line every time a new one is put into the 'Facebook' label.

A: Four thoughts for you to explore.

*

*Use GmailMessage.getDate() to filter out messages you've already handled. Store the time that the script runs in ScriptProperties and reload it as your threshold next time.

*Every message has its own unique ID, so recording that along with the body would give you a key to look up. I think this would be slower than the first option, but could be much faster if you stored key values in ScriptProperties.

*Use search() to match label and time, again keeping track of when the script has run in ScriptProperties.
var threads = GmailApp.search('label:"Facebook" after:"2015/6/1"');

That will give threads with any messages added after the given date, but the threads will also have messages prior to that date. You'll probably still have to use one of the earlier options to filter those out. (Unless, as you've indicated in comments, your thread will have no replies and thus only one message.)

*Once a thread is processed, remove the label you used to categorize it.
var oldLabel = GmailApp.getUserLabelByName('Facebook');
var newLabel = GmailApp.getUserLabelByName('Facebook-processed');
var threads = oldLabel.getThreads(0,10);
for(var n in threads){
  ...
  threads[n].removeLabel(oldLabel).addLabel(newLabel);
}


text:
Q: Can I specify the sub path of a Git repo to require in Gemfile? I want to use master version of grpc's Ruby gem in my project. But it's located in grpc/src/ruby. So I can't just use it with gem 'grpc', github: 'grpc/grpc'.
Is there a solution to add the gem with something like this gem 'grpc', github: 'grpc/grpc', sub_path: 'src/ruby'?

A: What about cloning the Gem repo to your local machine or the server and add it through the path option?
Like so:
gem 'grpc', path: 'path/to/your/local_repo'

I see there is an active issue about the same thing you are asking about on the Bundler Github repo[1]
[1] https://github.com/bundler/bundler/issues/396


text:
Q: Loop Syntax Issues I am coding a series of loops to search one table row by row for data, and if it meets the correct specs within that row it will pull a certain value from said row and place it in a cell I want in a separate table on another chart. I am getting the error saying that there is a "Next" without a "For", but there is (unless I am entirely missing something). It also has the Sub line at the top highlighted (I am trying to run this as a macro). Let me know where I am going wrong here, thanks!
Option Explicit

Sub GraphLoop()

Dim i, g, row, color, roundcount, round, materialcount, material As Long
Dim chartdatacol, chartdatarow As Long

Worksheets("Chart Data").Range("C6:DR10000").Value = ""

        roundcount = 1
        materialcount = 1
        color = 1
        round = 1
        material = 1
        chartdatacol = 3
        chartdatarow = 6
        i = 4

For chartdatacol = 3 To Worksheets("Running Avg Log").Cells(4, cols.Count).End(xlUp).row

Do Until i = Worksheets("Running Avg Log").Cells(Rows.Count, "A").End(xlUp).row

        g = 1

        If Worksheets("Running Avg Log").Cells(i, 1).Value = Worksheets("Chart Data").Cells(chartdatarow, 2).Value _
            And Worksheets("Running Avg Log").Cells(i, 2).Value = round _
            And Worksheets("Running Avg Log").Cells(i, 3).Value = color _
            And Worksheets("Running Avg Log").Cells(i, 4).Value = material Then

            row = chartdatarow

            Worksheets("Chart Data").Cells(row, chartdatacol).Value = _
            Worksheets("Running Avg Log").Cells(i, 6 + Worksheets("Analysis").Range("C5").Value).Value

            chartdatarow = chartdatarow + 1
            i = 4

        Else

            i = i + 1

        End If

Loop

    color = color + 1

    ' loops through ten colors
        If color > 10 Then

            color = 1

        End If

    roundcount = roundcount + 1
    materialcount = materialcount + 1

    ' every ten columns, material changes, every 30 columns, it repeats
        If materialcount = 11 Or 21 Then

            material = material + 1

        End If

        If materialcount > 30 Then

            materialcount = 1
            material = 1

    ' each round's 30 combos is 30 columns
        If roundcount = 31 Then

            round = round + 1

        End If

Next chartdatacol

End Sub

A: You left out an End If here:
If materialcount > 30 Then

        materialcount = 1
        material = 1

' each round's 30 combos is 30 columns

BTW, another correction to make:
    If materialcount = 11 Or 21 Then

should be:
    If materialcount = 11 Or materialcount = 21 Then

A: You had an If without End If
See modified code below , I marked with ********* the place you were missing the End If :
Option Explicit
Dim i, g, row, color, roundcount, round, materialcount, material    As Long
Dim chartdatacol, chartdatarow                                      As Long

Sub GraphLoop()

Worksheets("Chart Data").Range("C6:DR10000").Value = ""

    roundcount = 1
    materialcount = 1
    color = 1
    round = 1
    material = 1
    chartdatacol = 3
    chartdatarow = 6
    i = 4

    For chartdatacol = 3 To Worksheets("Running Avg Log").Cells(4, Columns.Count).End(xlUp).row

        Do Until i = Worksheets("Running Avg Log").Cells(Rows.Count, "A").End(xlUp).row
            g = 1
            If Worksheets("Running Avg Log").Cells(i, 1).Value = Worksheets("Chart Data").Cells(chartdatarow, 2).Value _
                And Worksheets("Running Avg Log").Cells(i, 2).Value = round _
                And Worksheets("Running Avg Log").Cells(i, 3).Value = color _
                And Worksheets("Running Avg Log").Cells(i, 4).Value = material Then

                row = chartdatarow

                Worksheets("Chart Data").Cells(row, chartdatacol).Value = _
                Worksheets("Running Avg Log").Cells(i, 6 + Worksheets("Analysis").Range("C5").Value).Value
                chartdatarow = chartdatarow + 1
                i = 4
            Else
                i = i + 1
            End If
        Loop

        color = color + 1

        ' loops through ten colors
        If color > 10 Then
            color = 1
        End If

        roundcount = roundcount + 1
        materialcount = materialcount + 1

        ' every ten columns, material changes, every 30 columns, it repeats
        If materialcount = 11 Or 21 Then
            material = material + 1
        End If

        If materialcount > 30 Then
            materialcount = 1
            material = 1
            ' each round's 30 combos is 30 columns
            If roundcount = 31 Then
                round = round + 1
            ' **** YOU WERE MISSING the End If here ***
            End If
        End If
    Next chartdatacol

End Sub


text:
Q: Three-digit numbers which all digits on the left are larger than digits on the right
How many three-digit numbers are there in which all digits on the left are larger than digits on the right?

This was a problem from an online test, which I gave a wrong answer. The correct answer is $120$, but here is how I attempted it:
Attempt #1: Understand the problem as "All three-digit numbers $\overline{abc}$ that satify $a>c$".
$b$ can be any digit from $0$ to $9$ so there will be $10$ possible numbers for each of the following cases:

*

*If $a=1$ then $b=0$ ($1$ case)

*If $a=2$ then $b\in{(0;1)}$ ($2$ cases)

*If $a=3$ then $b\in{(0;1;2)}$ ($3$ cases)

*If $a=4$ then $b\in{(0;1;2;3)}$ ($4$ cases)
...

*

*If $a=9$ then $b\in{(0;1;2;3;4;5;6;7;8)}$ ($9$ cases)

So the total number of numbers is $\sum_{x=1}^{9}(x)\times 10=450$ numbers.
Attempt #2 was made after seeking the solution: Understand the problem as "All three-digit numbers $\overline{abc}$ that satify $a>b>c$".

*

*If $a=2$ then $b=1$ and $c=0$.

*If $a=3$ then: if $b=1$ then $c=0$ ($1$ case); if $b=2$ then $c\in{(0;1)}$ ($2$ cases).

*If $a=4$ then: if $b=1$ then $c=0$ ($1$ case); if $b=2$ then $c\in{(0;1)}$ ($2$ cases); if $b=3$ then $c\in{(0;1;2)}$ ($3$ cases)
...

*

*If $a=9$ then: fo4 $b=1$ to $b=8$ the amount of possible cases are $1;2;3;4;5;6;7;8$ respectively.

So the total number of numbers that I calculated is truly $120$ for this case.
Is my interpretion correct or is the problem unclear?

A: If the question wants you to find the number of three digit numbers:
$\over{abc}$
it would have just said "... where the leftmost digit is larger than the rightmost digit."
The word 'are' and the plural 'digits' in "... all digits on the left are larger than digits on the right" indicates that $a>b>c$, at least this is clear to me.