text:
Q: Jenkins pipeline assign variable multiple times Is it possible to re-assign the variable value a few times inside IF in one script block?
I have a script block where I need to pass variable values to different environments:
script {
    if (env.DEPLOY_ENV == 'staging') {
        echo 'Run LUX-staging build'
        def ENV_SERVER = ['192.168.141.230']
        def UML_SUFFIX = ['stage-or']
        sh 'ansible-playbook nginx_depl.yml --limit 127.0.0.1'

        echo 'Run STAGE ADN deploy'
        def ENV_SERVER = ['192.168.111.30']
        def UML_SUFFIX = ['stage-sg']
        sh 'ansible-playbook nginx_depl.yml --limit 127.0.0.1'

        echo 'Run STAGE SG deploy'
        def ENV_SERVER = ['stage-sg-pbo-api.example.com']
        def UML_SUFFIX = ['stage-ba']
        sh 'ansible-playbook nginx_depl.yml --limit 127.0.0.1'
    }
}

But I receive an error in Jenkins job on second variable assignment:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 80: The current scope already contains a variable of the name ENV_SERVER
@ line 80, column 11.
                    def ENV_SERVER = ['192.168.111.30']
         ^

WorkflowScript: 81: The current scope already contains a variable of the name UML_SUFFIX
 @ line 81, column 11.
                    def UML_SUFFIX = ['stage-sg']
         ^

Or perhaps any other ways to multiple assignment inside one IF part of script block.

A: Using def defines the variable.  This is only needed on the first call.
so removing the def on the other calls should work
script {
  if (env.DEPLOY_ENV == 'staging') {
      echo 'Run LUX-staging build'
      def ENV_SERVER = ['192.168.141.230']
      def UML_SUFFIX = ['stage-or']
      sh 'ansible-playbook nginx_depl.yml --limit 127.0.0.1'

      echo 'Run STAGE ADN deploy'
      ENV_SERVER = ['192.168.111.30']
      UML_SUFFIX = ['stage-sg']
      sh 'ansible-playbook nginx_depl.yml --limit 127.0.0.1'

      echo 'Run STAGE SG deploy'
      ENV_SERVER = ['stage-sg-pbo-api.example.com']
      UML_SUFFIX = ['stage-ba']
      sh 'ansible-playbook nginx_depl.yml --limit 127.0.0.1'
  }
}

The variables will only be scoped to the if block, so you wont have access to them outside that block.


text:
Q: Node.js: How would you recreate the 'setTimeout' function without it blocking the event loop? I've done a lot of searching to try and find out how to create non-blocking code in Node.js. Unfortunately, every example I've found is grounded to a function that, in the end, already has a built in callback. So I wanted to create my own function with a callback, but for some reason it blocks the event loop. This didn't block the event loop:
function foo(response){
    setTimeout(function(){
        response.writeHead(200, {"Content-Type": "text/plain"});
        response.write("bar");
        response.end();
    }, 7000);
}

But this did :
function foo(response){
    function wait(callback, delay){
            var startTime = new Date().getTime();
        while (new Date().getTime() < startTime + delay);
        callback();
    }
    wait(function(){
        response.writeHead(200, {"Content-Type": "text/plain"});
        response.write("bar");
        response.end();
    }, 7000);
}

What fundamental aspect of non-blocking code am I missing?
Edit:
My goal to recreate setTimeout is more of a mental exercise I thought I'd try so I can understand the even loop a little better. Right now I'm worried that if I have some rather heavy server side code that's doing some raw processing in JavaScript, I won't know how to stop it from halting my event loop.
After reading your answers and thinking about this a bit further, I think a more accurate question would probably be this: If I'm doing heavy processing on my server with JavaScript, how do I stop that from interrupting the event loop?
It's my first time posting on here, so I didn't know what kind of response I was gonna get. So far, this is awesome. Thanks, guys.
Edit 2:
Hey, so thanks again everyone for the advice. I ended up trying out process.nextTick like Raynos suggested... and it worked! I managed to create my own non-blocking timer with a callback. The code isn't perfect, but for those who are curious, this is how it looks:
var timer = {};

function delay(callback, length){
    if(!timer.startTime){
        timer.startTime = new Date().getTime();
        timer.callback = callback;
        timer.length = length;
    }
    if(new Date().getTime() < timer.startTime + timer.length){
        process.nextTick(delay);
    } else {
        timer.callback();
        timer = {};
    }
}

function list(response){
    delay(function(){
        console.log("callback");
        exec("dir", function (error, stdout, stderr) {
            response.writeHead(200, {"Content-Type": "text/plain"});
            response.write(stdout);
            response.end();
        });
    }, 7000);
}

Not really intending to use this code. But the process of learning how to do this definitely helped me understand some key concepts about non-blocking.
And for those of you still curious about non-blocking, you should check out Raynos' article.

A: In order to not block the event loop your code has to eventually return to the event loop and allow it to continue processing.  Unless your code actually returns to the event loop then it can't dequeue the next message and process it.  This code won't exit for the given time period and hence never returns control to the event loop.

A: You've got most of the correct idea - you want to write a function that will execute quickly and then return control back to the main event loop. Instead of the function itself idly waiting (in your case by literally sitting in a while loop and sleeping), it registers a callback -- typically with setTimeout -- and then returns. Then, when the timeout is called it wakes back up and executes whatever function it needs to.
function foo(response){
    function wait(callback, delay){
            var startTime = new Date().getTime();
        // this will block the event loop until this condition is true
        while (new Date().getTime() < startTime + delay);
        //then the callback is called
        callback();
        //then it goes back to the event loop
    }
    wait(function(){
        response.writeHead(200, {"Content-Type": "text/plain"});
        response.write("bar");
        response.end();
    }, 7000);
}

A: maybe a wrapper is what you want?
function wait(callback, delay){
    setTimeout(callback, delay);
}

A: When you call a function you don't start a new thread. Therefore running a while loop inside the wait function will block execution.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get customschema data I am new to this new world of programming with GAS, I have not programmed anything for a long time and the change of structure is a bit complicated to understand. I have an app-script that reads the data of the domain users and it works very well, but it doesn't bring me the customschema fields. I've searched quite a bit in the documentation, until I found something that seemed to work.
I created a function and tried to retrieve the fields I need and it works. What it does is look up a user and fetch the data.
Then I wanted to use that function but passing it the userkey of the user in question and then return one of the fields. But it stopped working, it only brought the normal data, but from the customschema, nothing.
My function is:
function LeeUser() {
  var iuserEmail = "user@midominio.com";
  var test = {
  "name": {
    "familyName": "",
    "givenName": ""
  },
  "password": "",
  "primaryEmail": "",
  "orgUnitPath": "",
  "emails":[{
    "type": "work",
    "address": "",
  }],
    "customSchemas": {
    "Organizacion_Interna": {
      "NombreFuncionario": "",
      "FechaCaducidad": ""
    }
  },
  };
  try {
    test = AdminDirectory.Users.get(iuserEmail,{"projection": "full"});
    console.log(test.customSchemas.Organizacion_Interna.FechaCaducidad);
  } catch (err) {
    Logger.log('Failed with error %s', err.message);
  }

}

But when I change
function LeeUser(userEmail) {
  var iuserEmail = userEmail;
  var test = {
  "name": {
    "familyName": "",
    "givenName": ""
  },
  "password": "",
  "primaryEmail": "",
  "orgUnitPath": "",
  "emails":[{
    "type": "work",
    "address": "",
  }],
    "customSchemas": {
    "Organizacion_Interna": {
      "NombreFuncionario": "",
      "FechaCaducidad": ""
    }
  },
  };
  try {
    test = AdminDirectory.Users.get(iuserEmail,{"projection": "full"});
    return test.customSchemas.Organizacion_Interna.FechaCaducidad;
  } catch (err) {
    Logger.log('Failed with error %s', err.message);
  }
}

It tells me that the field is not defined.
what's the problem?
Any suggestion
Thanks in advance.


text:
Q: Showing that $\left (\frac{\sin x}{x} \right )^3\geq \cos^{2}x$
Show that $$\left (\frac{\sin x}{x}  \right )^3\geq \cos^{2}x,\forall x\in \left ( 0;\frac\pi2 \right )$$

Firstly, I had use the differentiation of $f(x)=\left (\frac{\sin x}{x}  \right )^3- \cos^{2}x$,but I think it very complex: $$f'(x)=3\left ( \frac{\sin x}{x} \right )^2\frac{x\cos x-\sin x}{x^2}+\sin2x$$ Or I can't prove it be positive in $ \left ( 0;\frac\pi2 \right )$
Secondly, I had use the convex function, but function $f(x)=\left (\frac{\sin x}{x}  \right )^3-\cos^{2}x$ isn't convex or concave in all $ \left ( 0;\frac\pi2 \right )$

A: It is enough to consider:
$$ f(x)= \sin^3(x)-x^3\cos^2(x) $$
and prove it is an increasing function over $I=\left(0,\frac{\pi}{2}\right)$ by studying:
$$ g(x)=\frac{f'(x)}{\cos(x)} = -3x^2\cos(x)+2x^3\sin(x)+3\sin^2(x).$$
$g(x)> 0$ follows from $\frac{\sin x}{x}> 1-\frac{x^2}{6}$ and $\cos(x)< 1$ over $I$.

A: Since all the quantities involved are positive, you can shift around the terms to get an equivalent inequality:
$$\tan^2x\sin x\ge x^3\tag{i}$$
Now consider the function $f(x)=\tan^2x\sin x - x^3$.
Its derivative is $f'(x)=\tan^2 x\cos x+2\tan x \sin x\sec^2 x-3x^2=g(x)-3x^2$.
Using the AM-GM inequality on the $g(x)$, we get :
$$g(x)\ge 3\tan^2x(\sec x)^{1/3}\tag{ii}$$
From (ii) we can say that $$f'(x)\ge 3(\tan^2x(\sec x)^{1/3}-x^2)\tag{iii}$$
Finally using the inequalities $\tan x>x$ and $\sec x >1$ on (iii) we get that $f'(x)\ge0$.
Now that it is known that f(x) is an increasing function, $$f(x)>f(0)\implies \tan^2x\sin x\ge x^3$$

A: Start with
$$
1-\cos(x)\ge0\tag{1}
$$
For $x\ge0$, successive integration yields
$$
x-\sin(x)\ge0\tag{2}
$$
and
$$
\frac{x^2}2-1+\cos(x)\ge0\tag{3}
$$
and
$$
\frac{x^3}6-x+\sin(x)\ge0\tag{4}
$$
and
$$
\frac{x^4}{24}-\frac{x^2}2+1-\cos(x)\ge0\tag{5}
$$
From $(4)$, we get
$$
\frac{\sin^3(x)}{x^3}\ge1-\frac{x^2}2+\frac{x^4}{12}-\frac{x^6}{216}\tag{6}
$$
From $(5)$, we get
$$
\cos(x)\le1-\frac{x^2}2+\frac{x^4}{24}\tag{7}
$$
Subtracting $(7)$ from $(6)$ yields
$$
\frac{\sin^3(x)}{x^3}-\cos(x)\ge\frac{x^4}{24}-\frac{x^6}{216}\tag{8}
$$
and for $|x|\le3$, $\frac{x^4}{24}-\frac{x^6}{216}\ge0$. Thus for, $x\in\left[0,\frac\pi2\right]$,
$$
\frac{\sin^3(x)}{x^3}\ge\cos(x)\ge\cos^2(x)\tag{9}
$$

A: We can have a stronger one which is easier:
Let $f(x)=\tan{x}\sin{x} -x^2,x\in[0,\pi/2),$
$$f'(x)>0\implies \tan{x}\sin{x}>x^2,x\in(0,\pi/2).$$
$$f'(x)=\sin{x}\dfrac{\cos^2{x}+1}{\cos^2{x}}-2x>0\iff \dfrac{\tan{x}}{x}> \dfrac{2}{\cos{x}+\dfrac{1}{\cos{x}}} $$
which is true, because:
$$\dfrac{\tan{x}}{x}>1,\cos{x}+\dfrac{1}{\cos{x}}>2 \implies \dfrac{2}{\cos{x}+\dfrac{1}{\cos{x}}}<1,\forall x\in(0,\pi/2).$$
it is trivial that
$$\dfrac{\tan{x}}{x} \cdot\tan{x}\sin{x}>x^2,x\in(0,\pi/2).$$


text:
Q: Counter decreasing by half when it should be decreasing by 1 I'm working on a project in the Unity engine and I've come across an issue that I cannot understand. I have an ammo counter that decreases the amount of ammo available by 1, each time the player clicks the left mouse button. Instead of doing this though, it decreases by half (rounded down). I'm not entirely sure why this happens as the only decremental value is " ammoCount -= 1; " My code for the script is below:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class ShootGun : MonoBehaviour {

public Text Ammo;

public int ammoCount = 30;

void FixedUpdate ()
{
    if(Input.GetButtonDown("Fire1"))
    {
        for(int i = 1; i <= ammoCount; i++)
        {
            ammoCount -= 1;
            Debug.Log ("Ammo remaining: " + ammoCount);
            Ammo.text = " " + ammoCount;

            Vector3 gunRayOrigin = transform.position;
            float gunRayDistance = 50f;

            Ray gunRay = new Ray ();
            gunRay.origin = gunRayOrigin;
            gunRay.direction = Vector3.down;

            if(Physics.Raycast(gunRayOrigin, gunRay.direction, gunRayDistance)) {
                Debug.Log("Bullet Hit");
            }

        }
    }

}

}

Any help would be greatly appreciated, as I'm still getting the hang of C#.

A: You're decrementing the counter in a for loop. By decreasing the loop's upper bound and increasing the iteration variable i you basically halve the upper bound (ammoCount).
In this case, I see no reason why a loop would be necessary.

A: You are decrementing it inside a for loop.
If we simplify down to this:
for(int i = 1; i <= ammoCount; i++)
{
     ammoCount -= 1;
}

and take an initial ammoCount of 6, the first time you enter the loop you have:
i = 1, ammoCount = 6

But then you subtract one from ammoCount, and the loop adds one to i. So the next loop you have
i = 2; ammoCount = 5

But then you subtract one from ammoCount, and the loop adds one to i. So the next loop you have
i = 3; ammoCount = 4

But then you subtract one from ammoCount, and the loop adds one to i. So the next loop you have
i = 4; ammoCount = 3

And the loop completes (because now i <= ammoCount is no longer true). And ammoCount is half what it was.
It looks like Input.GetButtonDown("Fire1") only returns true when the button has been pressed and released, so this is a "push the button and fire all ammo" scenario, rather than "fire until out of ammo or the key is released".
So you are wanting it to keep firing while there is any ammo left (hint hint).

A: FixedUpdate is an event that happens in a fixed interval and should be used mainly for scenarios when you're dealing with physics. I don't think this is the case (some may argue that you're using raycast, but I'm not sure personally if that counts). You want to react on the users button press, so in my opinion you should use Update event instead.
GetButtonDown() returns true if the user pressed and released the button. What you should be doing instead is to use GetButton() to know if the button is held down. If yes, keep firing, if not, do nothing. Otherwise you have to press the button repeatedly, which again is probably not the desired behavior.
Let's now look at what happens when you press the button. Every time the user does the action, you start to decrease the ammo count until it reaches zero. Not sure what kind of game you're creating, but that doesn't sound right. What I'd expect instead would be to decrease the count while the user keeps the button pressed. In the Update event just check if ammo count is higher than zero and if yes, do the raycast check if it hit.
It would look like this:
void Update()
{
   if(Input.GetButton("Fire1"))
   {
       if (ammoCount > 0)
       {
           ammoCount--;
           // do raycast and so on
       }
   }
}


text:
Q: Query for a match or return a null join I have two tables one is the orders table with customer,items ordered
2nd table is the item info showing tag along items. Im making sure that the tag along item and the item its tagged along to are on both on the account, they do not need to be on the same order number 11 12.
BC-customer
MC-order number
oitem-item on customer account
http://www.sqlfiddle.com/#!2/c6906c/4
CREATE TABLE orders
    (`bc` int, `mc` int,`OITEM` varchar(3))
;

INSERT INTO orders
    (`BC`, `MC`,`OITEM`)
VALUES
    (1, 11, 'HPB'),
    (1, 11, 'HPU'),
    (1, 11, 'TCU'),
    (1, 11, 'CPB'),
    (1, 11, 'HPU'),
    (1, 12, 'CPS'),
    (2, 11, 'CPA'),
    (2, 12, 'CPS'),
    (2, 12, 'TCU')
;

CREATE TABLE item_desc
    (`item` varchar(3), `tag` varchar(3))
;

INSERT INTO item_desc
    (`item`, `tag`)
VALUES
    ('FSU', 'CPS'),
    ('HPU', 'CPB'),
    ('FSU', 'CPB'),
    ('TCU', 'CPA')
;

I need to return a match or else show the null value: Here is the query I have written problem is I am showing both a match and a null value because CPS can be tag along to HPU or FSU.
select a.bc, a.mc, a.oitem as CP, b.tag, b.item, c.oitem as CP_Item
from orders a
left join item_desc b
on a.oitem = b.tag

left join orders c
on b.item = c.oitem

where a.oitem like 'CP%'
group by a.bc,a.mc,a.oitem,b.tag,b.item,c.oitem;

Currently Results Show:
BC  MC  CP  TAG ITEM    CP_ITEM
1   11  CPB CPB FSU     (null)
1   11  CPB CPB HPU     HPU
1   12  CPS CPS FSU     (null)
2   11  CPA CPA TCU     TCU
2   12  CPS CPS FSU     (null)

I want end result to show me the match and if no match than null but not both null and match because one match makes the account valid:
BC  MC  CP  TAG ITEM    CP_ITEM
1   11  CPB CPB HPU     HPU
1   12  CPS CPS FSU     (null)
2   11  CPA CPA TCU     TCU
2   12  CPS CPS FSU     (null)

A: You're almost there.  Simply remove the b.item, c.oitem from your GROUP BY and you're all set.
select a.bc, a.mc, a.oitem as CP, b.tag, b.item, c.oitem as CP_Item
from orders a
left join item_desc b
on a.oitem = b.tag

left join orders c
on b.item = c.oitem

where a.oitem like 'CP%'
group by a.bc,a.mc,a.oitem,b.tag

http://www.sqlfiddle.com/#!2/c6906c/8


text:
Q: Make multiple iframes drag, resize and minimize like a regular window I'm working on a Dashboard for work where I have multiple iframes open on one web page, each iframe having a different site. I have been able to get the div's holding the iframes to resize and drag, but I cant for the life of me get it to minimize when I press the top left image. Here's what I have so far:

// JavaScript Document
$(function () {"use strict";
 $("#framewrap") .resizable() .draggable();
});
.body_padding {
    padding: 16px;
}
#framewrap {
    padding-right: 10px;
    padding-left: 10px;
    padding-bottom: 28px;
    background-color: #277099;
    width: 512px;
    height: 90px;
    -webkit-box-shadow: 2px 2px 16px -2px;
    box-shadow: 2px 2px 16px -2px;
    border-radius: 12px;
    position: absolute;
}
#frame {
    width: 100%;
    height: 100%;
    background-color: #fff;
}

<link href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" rel="stylesheet"/>

          Window 1

The idea is that I can press the minimize button on the right, and it changes the height and width of the wrapper div to a height of 90px and a width of 256px. I'd need to have multiple iframes open at once in one page that can individually move, resize, and minimize as needed. Any help is appreciated Thanks!!

A: To extend this a bit for multiple windows, I switched a few of your ID based elements to class based elements.  You also had jQuery included a few times and I simplified that.
I think this should get you going.  It is basically a simple toggle of a minimize class on your container.

// JavaScript Document
$(function() {
  "use strict";
  $(".framewrap").resizable().draggable();
  $(".framewrap .actionIcon").on("click", function() {
    $(this).closest(".framewrap").toggleClass("min");
  });
});
.body_padding {
  padding: 16px;
}

.framewrap {
  padding-right: 10px;
  padding-left: 10px;
  padding-bottom: 28px;
  background-color: #277099;
  width: 512px;
  height: 90px;
  -webkit-box-shadow: 2px 2px 16px -2px;
  box-shadow: 2px 2px 16px -2px;
  border-radius: 12px;
  position: absolute;
}

.framewrap span {
  color: #FFFFFF;
  font-size: small;
  font-style: normal;
  font-weight: 100;
}

.framewrap .actionIcon {
  display: inline-block;
  float: right;
  height: 18px;
  width: 18px;
  background-image: url(http://findicons.com/files/icons/2711/free_icons_for_windows8_metro/128/minimize_window.png);
  background-size: cover;
  background-position: center center;
}

.framewrap.min {
  height: 90px !important;
  width: 256px !important;
}

.framewrap.min .actionIcon {
  background-image: url(http://findicons.com/files/icons/2711/free_icons_for_windows8_metro/128/maximize_window.png);
}

.frame {
  width: 100%;
  height: 100%;
  background-color: #fff;
}
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />

    Window 1


text:
Q: When is the most efficient time to populate a large select dropdown in Javascript? I've been struggling with this for a bit. I'm using backbone to render models, and chosen plugin for my dropdowns.
When a new collection comes in, the jQuery slideDown effect is used to render each model. Each model has a select dropdown that needs to be populated with over 600 options.
The problem I'm running into is that if I populate the dropdowns first, then the slideDown animation is choppy, and in fact is usually just ignored (suddenly my models appear, no animation.)
Another option I've tried is rendering the models first, appending only the model's value for the specific dropdown, and then setting it's selected value. Then, a setTimeout is called and the rest of the options are populated (behind the scenes). However in that case there ends up being an obvious, annoying delay. If I don't set the Timeout, then it tries to fill dropdowns that don't yet exist.
Am I missing something in how to do this efficiently? I'm caching my list of options for the select dropdown. I've tried both looping through all the options into a string and replacing the html of the dropdown, and looping through each option and appending one at a time.
I think my problem has more to do with the combination of animation and 600+ options for the dropdowns. Ideally, after the model appears, it would immediately populate the dropdown list with no delay.

A: You don't necessarily need a timeout. You could create your own event in backbone.
initialize: function () {
  // When our event is triggered, load the dropdowns.
  this.on( 'doneWithThings', this.loadDropdowns );
},

// render the view
render: function () {
  // Whatever it is that you do when rendering.
  // When you're done rendering, trigger an event.
  this.trigger( 'doneWithThings' );
},

loadDropdowns: function () {
  // Load them!
}

Other things I would try...
Keep the options in the client-side (JS array), but don't draw them to the screen unless the user has expanded that slideDown section of the screen. Again, raise an event when the slideDown effect happens.

A:
Ideally, after the model appears, it would immediately populate the
  dropdown list with no delay.

Dont know blackbone but if there is some animation,you could look at  jquery .promise()
$(":animated").promise().done(function() {
    //load data
  });


text:
Q: linear program with zeros Hi, I want to be able to solve a linear program that has constraints that are either zero or a range. An example below in LP_Solve-like syntax shows what I want to do. This doesnt work. In general all the decision variables Qx can be 0 or a <= Qx <= b where a > 0 and b > a. All decision variables must be integers.

max: 0.2 Q1 + 0.4 Q2 + 0.6 Q3 + 0.8 Q4 + 0.4 Q5 + 0.6 Q6 + 0.6 Q7 + 0.7 Q8;
Q1 = 0 or Q1 >= 5;
Q2 = 0 or Q2 >= 1;
Q3 = 0 or Q3 >= 1;
Q4 = 0 or Q4 >= 1;
Q5 = 0 or Q5 >= 1;
Q6 = 0 or Q6 >= 1;
Q7 = 0 or Q7 >= 9;
Q8 = 0 or Q8 >= 1;
Q4 <= 30;
Q1 + Q2 + Q3 + Q4 + Q5 + Q6 + Q7 + Q8 <= 50;

How would I rewrite this to work? Is there a particular solver that should be used for this kind of task?

A: You can use the following modelling trick to transform you problem in a integer linear program: for each constraint of the type
$$ Q_i = 0 \text{ or } L_i \le Q_i \le M_i$$
(on an integer variable $Q_i$) introduce a new binary variable $B_i$ and write
$$ L_i B_i \le Q_i \le M_i B_i $$
If, as in your example, you have no explicit value for $M_i$, simply use a large upper bound on the values of $Q_i$ (for example $50$ in your situation). Also, the constraint $Q_i = 0 \text{ or } Q_i \ge 1$ is redundant.
You can then solve the resulting program with any integer programming solver, such as lp_solve or glpk.
By the way, the solution to your example is easily seen to be obtained with $Q_4=30$ and $Q_8=20$.


text:
Q: Uploading images in djangorestframework How can I upload images in Django?
If I now want to upload my image I have to first bring the image to the media folder then type the name of the image to include the image in the API but I want to add the images, not in that way I want to upload the image.
Here is My models.py
   class Project(models.Model):
       title = models.CharField(max_length=300)
       body = models.TextField(max_length=5000)
       header_image = models.ImageField(default="default.jpg")
       demo = models.URLField(null=True, blank=True)
       code = models.URLField(null=True, blank=True)

here is my views:
@api_view(["POST"])
def addProject(request):
    data = request.data
    project = Project.objects.create(
    title=data["title"],
    body=data["body"],
    header_image=data["header_image"],
    demo=data["demo"],
    code=data["code"],
    )
    serializer = ProjectSerializer(project, many=False)
    return Response(serializer.data)

and here is my serializers:
class ProjectSerializer(serializers.ModelSerializer):
comments = serializers.SerializerMethodField()

class Meta:
    model = Project
    fields = '__all__'

    def get_comments(self, obj):
        comment = obj.comments.all()
        serializer = CommentSerializer(comment, many=True)
        return serializer.data

How can I upload my image in the API without manually dragging the folder in the media folder and typing the image file name?


text:
Q: how handle 12-bit image from MIPI camera? Actually, I use a Gige camera. That camera provide images in unsigned char*, this mean a bit depth of 8. I develop in c/c++.
I am going to receive a new one, but that camera is different. This one provides void*, with a bit depth of 12. Can I cast the void* like that :
unsigned short* img ;
img = (unsigned short*) camera.GetImage() ; /**camera.GetImage() is void*/

It is new for me, and I have been never using raw format. Does cast is a good idea ? I need to access at each pixel, and I don't how handle pixel with void*.
I suggest to cast with unsigned short* because of the depth. The pixel of the camera are encoded on 12. If I cast with unsigned char*, I would lose information.
Thank you for your help !
UPDATE
Thank you a lot for all your details. As I am a beginner, your answer help me a lot to find other ways to investigate.
I am working on jetson TX2, and the bit location is a reflection of the actual hardware.
For my part, the pixel data is concatenated in 16bits. The output of the jetson TX2 is :
              ONE PIXEL

|              16 bits                          |
D5-D4-D3-D2-D1-D0-D11-D10-0-0-D11-D10-D9-D8-D7-D6

My goal is not to display the image. Below the explanation of my process :

1 - Take 5 times the same image ;
2 - Calculation of the average image ;
3 - Bad pixels correction ;
4 - Flat field correction ;
4 - Send final image through socket ;

In a thread, I acquire images. In an other thread, I apply image processing and in an other one, I send image through socket. I implemented all the process.
I didn't use libraries like openCV because I did some specifics process. I need to handle all pixels of the image, and I wonder if it is very efficient to convert the .raw in unsigned short*, to adapt the image to my code.
The 'packing' was never a question because my previous camera provides images in an unsigned char*. Do you think that I should convert the void* into unsigned short* ?
Thank you for your help

A: There is not enough information in your post to answer your question.
Here are the possible packing for 12-bits pixels:
Efficient packing

Bit0     Bit11     Bit23      Bit35        Bit47     Bit59     Bit71     Bit83      Bit95
[ Pixel0   | Pixel1  | Pixel2    | Pixel3  | Pixel4   | Pixel5  | Pixel6  |  Pixel7 ]  (that is 8 pixels per 96bits or 3 32-bits word)

Easy to use packing

Bit0    Bit11     Bit23    Bit32     Bit43     Bit55     Bit63
[ Pixel0   | Pixel1  | 0    | Pixel3  | Pixel4   | 0      ]  (that is 2 pixels per 32-bits word)

Dumb packing

Bit0    Bit11     Bit16    Bit27     Bit31
[ Pixel0   |  0    | Pixel1  |  0      ]  (that is 1 pixels per 16-bits word)

You have to read the datasheet of your camera to figure which packing is being used. Once this is done, you also need to figure out the endianness of the data for transmitting the data words. For example, in a little endian system, you'll the least significant byte first. For a big endian system, you'll get the most significant byte first. You'll need to adapt your pixel extraction code to fit your machine's endianness.
Extracting pixel is done quite simply once you have figured out the packing and endianness with bit shifting and mask.
Since you have asked for a C++ solution, here's a any-bit extractor from a memory stream, you'll need to adjust for the packing and endianness:
struct BitStream
{
    const uint8 * begin;
    const uint8 * end;
    size_t pos;
    BitStream(const uint8 * bits, size_t len) : begin(bits), end(bits + len), pos(0) {}
    // get value from bitstream coded on len bits
    uint32 get(uint8 len)
    {
        size_t byte_offset = pos/8;
        uint8 bit_pos = pos % 8;
        uint8 bit_avail = 8 - bit_pos;
        if (begin+byte_offset >= end) return 0;
        if (bit_avail >= len)
        {
            uint32 value = begin[byte_offset];
            uint8 mask = ~(0xff << len) << bit_pos;
            value = value & mask;
            value = value >> bit_pos;
            pos = pos + len;
            return value;
        }
        else
        {
            uint32 value = get(bit_avail);
            value = value | (get(len - bit_avail)<<bit_avail);
            return value;
        }
    }
    void skip(uint8 len) { pos += len; }
    bool done() const { return (begin + pos/8) >= end; }
};

If there is endianness mismatch between the camera and your machine, you'll need to swap the returned pixel like this:
BitStream bs((const uint8*)camera.getImage(), camera.getImageLen());
// Get pixel
uint16 pixel = (uint16)bs.get(12);
// Comment the line below if the endianness is the same
pixel = ((pixel & 0xFF00) >> 8) | (pixel << 8);
// Skip the stuffing zero bits depending on packing format, here I assume dumb packing
bs.skip(4);

A: Thank you for updating your question.
If, as it now seems, each 12-bit pixel is fully contained in a 16-bit unsigned short with 4-bits of padding, then "yes" unsigned short is definitely the way to go. I don't know if your environment has uint16_t or not but that is guaranteed to be exactly 16-bits (which I feel is better) whereas unsigned short is "at least" 16-bits.
Now you just need to do some ANDing and shifting...


text:
Q: How to select data from table on the basis of other i have 2 tables T1 and T2. Here T1 contains blogs and T2 contains list of users who liked post.
T1 database schema post_id,post
AND
T2 database schema post_id,user_id
I want to select only those posts that is at least 10 users liked.

A: SELECT T1.post_id, T1.post, COUNT(T2.user_id]) as Total
FROM T1 JOIN T2 ON T1.post_id = T2.post_id
GROUP BY T1.post_id, T1.post
HAVING Total >= 10

A: you can group your selection and then use having
SELECT posts.*, COUNT(likes.id) as likesCount
FROM posts, likes
GROUP BY posts.id HAVING (likesCount >= 10)

A: In table T2 the post_id which occurs more than 10 is your desired post, so you can pick the posts which have post_id occurring at atleast 10 rows in your table T2

A: Can you use a subselect?
SELECT post_id,COUNT(post_id) AS count,
(SELECT post FROM T1 where post_id=T2.post_id) AS post
GROUP BY post_id
HAVING count >= 10

A: With purpose to have best performance and avoid "cartesian product" use join, like this:
SELECT p.post_id, COUNT(l.user_id) AS TotalLikesCount
FROM posts AS p
JOIN likes AS l ON p.post_id = l.post_id
GROUP BY p.post_id
HAVING TotalLikesCount >= 10

A: You can select posts using join.
SELECT p.post_id, p.post, count(pl.user_id) as likes
FROM `post` as p
join post_likes as pl on p.post_id = pl.post_id

where 1 group by pl.post_id
having likes >= 10;


text:
Q: Merge PDF's to a common PDF without whitespace PDF-Framework Java/C# I am looking for a PDF-Framework in Java which can merge several PDF's to one common PDF. Additionally I don't want have spaces between the several PDF's in the common PDF. The common PDF must to be a fluent file. Any tip is welcome!!!
File1.pdf       File2.pdf
a               a
b               b
c               c
d               d
                e
                f
                g

Common.pdf
a
b
c
d   //ignore the 3 whitespace lines
a
b
c
d
e
f
g

A: What you are looking for is a tool, which merges halfway through the page? I don't think such a tool exists, cause you would lose stuff like headers and footers in the subsequent pages and images that would be lost in the page overlap as well.
If you're OK with using a tool that merges at the end of each PDF (so with page breaks) you should look at building your own library around QPdf, which is an open-source tool and best in class imho.


text:
Q: Machine Learning Joblib Prediction I got some saved models from this repo github repo, I am trying to make predictions from the models,I am new to machine learning. this is what I have.
this is the notebook I am using notebook
import joblib
from sklearn.feature_extraction.text import CountVectorizer
import numpy as np
from sklearn.preprocessing import OneHotEncoder
import pandas as pd

model_mnb = joblib.load("/content/decision_tree.joblib")
model_dec = joblib.load("/content/gradient_boost.joblib")
model_gra = joblib.load("/content/mnb.joblib")
model_forest = joblib.load("/content/random_forest.joblib")

print(model_mnb, model_dec, model_gra, model_forest)

sample = ["I have Fever", "I have headache", "I have sore limbs"]

encoder = OneHotEncoder(sparse=False)
test_data = encoder.fit_transform(sample)
model_mnb.predict(test_data)

I am getting:
ERROR:  Expected 2D array, got 1D array instead:

A: It is likely a result of your sample variable being, well, a sample. If you were to predict multiple samples you would need a nested list, which is probably what the predict() function expects. Try just adding a pair of square brackets around your test_data variable or perhaps earlier on the sample variable.


text:
Q: Using Selenium through python how can I get the name of the button? <li id="add-to-cart" class="">
    <input type="button" value="Add to Cart" class="primary" name="add-to-cart">
</li>

I want to print value
Output: Add to Cart

A: Here my solution:
first get elements inside < li> (Maybe there will be more than one):
elements = browser.find_elements_by_xpath("//li[@id='add-to-cart']//input")

for e in elements:
    print(e.get_attribute("name"))

A: From Selenium docs:

*

*find the button element using one of the find_element_by... methods on a driver (or on a parent WebElement)

*read the name of the button or value of an input using .get_attribute(attribute_name)

*read the text using property .text


text:
Q: Dealing with non active transaction in log file and shrinking I have posted the first part of my question here & I don't want to flood my question with a loads of information and would force people to alter their answers for my each question.
I think I am lacking the knowledge about how logs works, so I would appreciate if anyone can redirect me to tutorial or book which can tells me deep about it. However, I am confused about

*

*I understand that I get error because my log file was filled when SQL was either trying to run an active transaction or was trying to create checkpoints.

but I have large enough space for log file (i.e. 200 GB); so is there any way I can remove entries from log file for all transaction other than active transaction. Because at max my transaction will not exceed 10 GB at any instance.

*

*It is recommend not to shrink log file
But then how can I ensure that my future transactions (i.e queries) will run smoothly? Does SQL Server shrink/flush/delete data from log by itself?

*What is the best practice to deal with log file size?
I already have 200GB allocated for log file and I can ask for more. Isn't that enough? and if I keep increasing my drive size then some other day I will be on the same position where I am today.

A: To understand Transaction Log architecture you have few good articles

*

*Understanding Logging and recovery in SQL Server

*Transaction Log physical architecture
I would ask you to take some time and read these articles specially the first one.

so is there any way I can remove entries from log file for all transaction other than active transaction. Because at max my transaction will not exceed 10 GB at any instance.

No you cannot. In simple recovery the space held by committed transaction is re-utilized in transaction log file. When transaction commits checkpoint truncates the logs and when log is truncated the space used by previous transaction will now be re-utilized by new one so log file will not have to grow instead use the space already there. The problem here is long running transaction  you must focus on it, this is holding log hostage and not allowing it to truncate there by increasing space.

It is recommend not to shrink log file But then how can I ensure that my future transactions (i.e queries) will run smoothly? Does SQL Server shrink/flush/delete data from log by itself?

Yes its recommended not shrink log file. You need to make sure you do not run any transaction which does huge data manipulations. You can do whatever data manipulation you like but make sure amount of rows this manipulation is dealing is not too big. Log file just reacts to what you are running so you have control in it. Make sure after each data manipulation you manually run checkpoints
SQL Server will never shrink data and log files by itself for that you have DBCC SHRINKFILE command.

What is the best practice to deal with log file size?

The article How to set Log file size will help you set optimum value. Basically you have to spend some time looking at transaction log growth and see how much it grows in a day or week. Currently as per your previous question the autogrowth and initial size of both data and log files are not good. You must refer to to this article to set correct autogrowth setting


text:
Q: Does spark structured streaming job fails if dependency jars are updated? If I update a jar which is being used in a running structured streaming job, will this running job fail ?

A: Given that:

When using spark-submit, the application jar along with any jars
included with the --jars option will be automatically transferred to
the cluster.

then the current invocation cannot fail.


text:
Q: Error waiting for a debug connection: Bad state: No element Flutter VS Code Updated vscode today after that created new flutter projects are showing error
Error waiting for a debug connection: Bad state: No element
Error waiting for a debug connection: Bad state: No element

A: I have to try a clean project and it's work for me
flutter clean


text:
Q: Converting Checkbox Status Check from Materialize to Bootstrap 4 We just moved over from using Materialize to using Bootstrap 4, and, being a total novice with Bootstrap, I've run into some complications with getting my function that checks the status of some checkboxes on one of our pages to work.
Here's my old code that worked with Materialize:
HTML:
{{#each relList}}

     <input type="checkbox" id="{{this.eguid}}">
     {{this.cluster_value}}

{{/each}}

I'm using Meteor to iterate through "relList" and create a checkbox for each item in, with that checkbox having the same id as the current element.
jQuery:
$(document).ready(function () {
    //getting eguid on checkbox change
    $(":checkbox").change(function () {
        var notChecked = [], checked = [];
        $(":checkbox").map(function () {

            this.checked ? checked.push(this.id) : notChecked.push(this.id);
        });
        getDetails(checked);
    });
})

Here I'm listening for any changes to checkboxes and pushing the id of any checkbox that is changed into the arrays notChecked and checked, depending on whether the box was checked/unchecked.
I've done of the obvious of changing over the Materialize checkbox classes to Bootstrap ones, but for some reason my jQuery implementation doesn't seem to work with it no matter what I do. I'm not sure if my issue is with how I've converted over the HTML or if I need to make some changes to my jQuery.
If anyone could offer some insights into how to change my HTML/jQuery to get this working again, I would appreciate it.

A: You want to keep track of the changes so create a function to call that stores the values of the checked / unchecked arrays.
Then call them on :checkbox .change function with jquery.. the arrays will be kept up to date that way.
I included buttons to show you the array is kept up to date with each change.
Fiddle:
https://jsfiddle.net/remix1201/c6nxrwoq/
HTML:
<input type="checkbox" class="checkItems" value="1" checked="checked" />
<input type="checkbox" class="checkItems" value="2" />
<input type="checkbox" class="checkItems" value="3" />
<input type="checkbox" class="checkItems" value="4" />
<input type="checkbox" class="checkItems" value="5" />
<input type="checkbox" class="checkItems" value="6" />
<input type="checkbox" class="checkItems" value="7" />
<input type="checkbox" class="checkItems" value="8" />

<button id="chk1">checked</button>
<button id="chk2">not checked</button>

JS:
function boxChange(type){
    var checkedValues = $('input:checkbox:checked.checkItems').map(function() { return this.value; }).get();
    var uncheckedValues = $('input:checkbox:not(:checked).checkItems').map(function() { return this.value; }).get();

  if(type == "not"){
        return uncheckedValues;
    } else {
        return checkedValues
    }
}

$(":checkbox").change(function() {
    boxChange();
    boxChange("not");
});

// Only Needed For Buttons

$("body").on("click", "button#chk1", function() {
    alert (boxChange());
});

$("body").on("click", "button#chk2", function() {
    alert (boxChange("not"));
});


text:
Q: Can't call method "capture2" on unblessed reference if($var ==1){
    function($host);}
#OTHER PROCESSING
#***
#****
# ****
$hostForSsh =$host;
my $whatever ="xyz"
my $something= $ssh->capture2(qq(/user/somePlace $whatever) );#--line A

The function above runs perfectly when value of $var passed is 1 but gives
Can't call method "capture2" on unblessed reference -->error on line A if $var =0.

A: Solved! Problem was in $ssh only! Actually, I forgot to pass the $ssh object in the particular function and i did not notice this as many arguments were being passed to the function.


text:
Q: Capacitor on USB cable? I was messing around with a USB camera. I wanted to change the cable because is trimmed but as I was cutting it I saw a small thing (image below). As I was trying to cut the casing and see what it has inside I saw a spark. I tried to connect it with another cable but I don't know if I'm gonna damage the camera or the USB port.

What is it and can I connect the camera without it?

A: It is a ferrite bead and acting as a choke, or very small valued inductor. It is acting on all the conductors of the cable together, so it is blocking common-mode noise from entering or exiting the connected device.
The USB connection will absolutely work fine without the ferrite bead present. USB cables are normally sold without it.
It was likely packaged with your device because the device was found to be emitting EMI, and the cable was determined to be the source of the emission. It was cheaper to add a choke to the cable than to do any additional work on the design of the camera itself.
A single ferrite bead acts as a low-pass filter, but it rolls off at frequencies well above the highest frequency used by USB. Furthermore, the effect is applied only to common-mode signals. The USB data is on a differential pair, and both conductors are passing through the same core, along with the power conductors. So the USB data will see very little effect from the bead, while EMI will be blocked by the bead.
Lots more than you want to know can be found by reading data sheets. Here is some documentation from one maker. Discussion of common mode starts around page 8 in that PDF.

A: Its a ferrite bead, designed to suppress high frequency noise on the cable.
You can use it without it, but you might get issues with USB data transfer.

A: I guess you're talking about the ferrite bead:

Source: Wikipedia - Ferrite bead
Its purpose is to prevent interference at high frequencies signals.
It may also work without it and with a cable as short as possible.

A: It's a ferrite bead choke, which is used to suppress unbalanced high-frequency signals, typically caused by EM interference. It is essentially a form of passive low-pass filter.
Imaging devices such as scanners and cameras often have such filters on their USB cables because otherwise the EM interference from the cable may introduce noise in the sensor and, thus, the stored image. CCD sensors are often quite susceptible to noise.
Bottom line is that, while the USB connection will probably work fine even without the filter, any pictures that you take while connected to the PC may suffer a degree of degradation in quality.


text:
Q: Replacing the 'reset' button with a normal star when using RateIt for jQuery Using rateit, a plugin for jQuery, to replace a select element with stars.
The problem is that the reset button takes the place of the first star and when the resetable variable is set to false, the first select option simply isn't available, but when it is true, the hover & selected effects don't work as a user will expect.
I have tried changing the image of the reset button but it behaves incorrectly.
Here is is with resetable set to false. The first star is gone, and my minimum selection value is 2
Here it is with resetable set to true, see how the first star hover/selected effect doesn't work as expected, but I can get my first value.

A: When you use the Rateit plugin to progressively enhance a select list you need to include a option for 0 i.e. no stars. Do this and everything starts to work nicely.
http://jsfiddle.net/ru2wh/7/


text:
Q: SQLAlchemy: выборка по независимому регистру букв День добрый!
Предположим, есть таблица с одной колонкой:
 Товар:
    Апельсиновый сок
    Сок с апельсином
    /----/

Есть строки кода для поиска:
    q = request.args.get('q') # указывает к примеру url запрос q 'апельсин',
                              # где буква 'a' с маленькой буквы
    /----/
    res = Table.query.filter(Table.name.contains(q))

В результате получаем: сок с апельсином.
Как сделать так, что бы он находил все поля содержащие слово апельсин независимо от регистра букв. В данном случае находил и сок с апельсином, и апельсиновый сок.

A: res = Table.query.filter(Table.name.ilike('%' + q + '%'))


text:
Q: OBD2 Reading Enhanced Parameters with Python (ex. Injector Pulsewidth) I'm working on a project to capture instantaneous fuel consumption and I'd like to use injector pulsewidth.
I'm using pyserial to get the parameters connected to a bluetooth OBD reader.
For example, to get speed I type:
import serial

ser = serial.Serial('COM6',38400,timeout=1)

ser.write('01 0D \r')

speed_hex=ser.readline()

print speed_hex

To call any other standard OBD2 parameter, I'd just type it's 4 digit code followed by \r. This also worked for me with RPM, etc...
However I need fuel injector pulsewidth from a GMC vehicle which is code 125A, but typing '12 5A \r' doesn't give me any data. I suspect because it's part of the extended parameters and I'm not typing it correctly.
Can someone help me figure out how to get this parameter? I know it's available for my truck because I am comparing it with a windows GUI software which was able to obtain logical values for this parameter.
Thanks in advance.


text:
Q: How to install splinter on python3 on win10 I'm new to python and I've found that some people have used python 3.6 and splinter to complete some projectsclick here to see, but I found that some people said that it's not compatible to python 3...and some people said that some special operations can get it installed.
I am confused...

A: use the following command:-
C:\ python -m pip install splinter

or
C:\ pip install splinter


text:
Q: updating jlabel I am having trouble updating a jlabel in a method.  here is my code:
    JLabel curStatus = new JLabel("");
JButton jbtnSubmit;

public static void main(String[] args) {
    test gui = new test();
    gui.startGUI();
    // gui.setCurStatus("testing!"); << seems to work here,
    //but when i call it from another class, it doesn't want to run.
}

// Set up the GUI end for the user
public void startGUI() {
    // These are all essential GUI pieces
    new JTextArea("");
    final JFrame jfrm = new JFrame("my program");
    jfrm.setLayout(new FlowLayout());
    jfrm.setSize(300, 300);
    jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    jbtnSubmit = new JButton("Submit");

    jfrm.add(jbtnSubmit);
    jfrm.add(curStatus);
    jfrm.setVisible(true);
}

public void setCurStatus(String inCurStatus) {
    curStatus.setText(inCurStatus);
    curStatus.setVisible(true);
}

what is happening, is that the label, curStatus is not appearing.  for example, here is a call:
gui1.setCurStatus("Now running diagnostics... Please wait!");

A: Your problem appears to be one of misplaced references.
Here is how you create your GUI:
  public static void main(String[] args) {
     test gui = new test();
     gui.startGUI();
     // gui.setCurStatus("testing!"); << seems to work here,
     // but when i call it from another class, it doesn't want to run.
  }

You create your "test" object (which should be named "Test" by the way to conform to Java naming conventions) inside of  your main method. Since it is declared inside of main, this variable has scope only inside of main and is visible no where else.
You then tell us that you are calling the method like so:
gui1.setCurStatus("Now running diagnostics... Please wait!");

The gui1 variable refers to a test class object but it likely refers to a different object than the test object that is being displayed since the original displayed test object is only refered to by a variable local to the main method.
To solve this, you must make sure to call setCurStatus on the currently displayed test object. How to do this depends on the rest of your code, something you've refused to show us despite our requests for you to do so.
Edit: Based on your latest bit of posted code (which still won't compile for me since it is missing a method, createTasksFile(), my assumptions are correct, you are calling setCurStatus(...) on a gui object that is not the displayed one:
  public static String[] runDiagnostics() throws IOException {

     gui gui1 = new gui(); // (A)
     gui1.setCurStatus("Now running diagnostics... Please wait!");

On line (A) you create a new gui object and call setCurStatus on it, but it is not the GUI object that is being displayed but a completely different and unrelated object. It's only relation is that it is an object of the same class as the one being displayed but that's it. The solution is to get a reference to the displayed GUI and call this method on that object, and that object only.
Also, Robin's assumptions are correct, in that even if you fix this, you're going to be stuck with a Swing concurrency issue. The JLabel won't update because the Swing thread is trying to open a file:
  public static String[] runDiagnostics() throws IOException {

     gui gui1 = new gui();
     gui1.setCurStatus("Now running diagnostics... Please wait!");

     int i = 0;
     int errorsI = 0;
     File f = new File("tasks.txt");
     String[] errors = { "", "", "", "", "" };

     // try to create the file three times
     do {
        f.createNewFile();
        i++;
     } while (!f.exists() && i < 3);

So we're both right. The solution to this is to open your file on a background thread, a SwingWorker would work nicely here.
Edit 2
So to fix the reference problem, pass a reference of the gui into the runDiagnostics method using a gui parameter. Then call the setCurStatus method on this parameter.  For example:
  public static String[] runDiagnostics(gui gui1) throws IOException {

     //!! gui gui1 = new gui(); // !! no longer needed
     gui1.setCurStatus("Now running diagnostics... Please wait!");

You would have to pass the GUI in when calling the method:
        //!! results = taskBckg.runDiagnostics();
        results = taskBckg.runDiagnostics(gui);

Also, please edit all your code so that it follows Java naming conventions. All class names should begin with a capital letter. This makes it much easier for others to understand what your code is doing.

A: I will have a guess as well based on the message you are trying to display, since the question lacks some essential information. Based on the

"Now running diagnostics... Please wait!"

message, I will assume you are running diagnostics and trying to update the UI on the same thread. The code you posted contains no obvious mistakes which would explain why your call
gui1.setCurStatus("Now running diagnostics... Please wait!");

would not update the label contents.
What you have to do is all explained in the Swing concurrency tutorial. The main point is that you update the UI on the Event dispatch thread, and you never perform heavy calculations on that thread since that will block the UI, leading to a terrible user experience. Heavy calculations should be done on a worker thread, for example by using the SwingWorker class, and only the update of the UI (for example for reporting progress) should happen on the EDT.
With this information and links you should be able to find all relevant information. Also on this site you will find multiple examples on how to use SwingWorker to perform background calculations and updating the UI, like for example my answer on a previous question


text:
Q: Get the IP from Mac Address in C# Is there any way to get the IP (or the hostname) that corresponds to a specific MAC address?
What I have found so far is to get the hostname from an IP and vice versa using the System.Net.Dns.

A: You can use this class
public class IPMacMapper
{
    private static List<IPAndMac> list;

    private static StreamReader ExecuteCommandLine(String file, String arguments = "")
    {
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.CreateNoWindow = true;
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        startInfo.UseShellExecute = false;
        startInfo.RedirectStandardOutput = true;
        startInfo.FileName = file;
        startInfo.Arguments = arguments;

        Process process = Process.Start(startInfo);

        return process.StandardOutput;
    }

    private static void InitializeGetIPsAndMac()
    {
        if (list != null)
            return;

        var arpStream = ExecuteCommandLine("arp", "-a");
        List<string> result = new List<string>();
        while (!arpStream.EndOfStream)
        {
            var line = arpStream.ReadLine().Trim();
            result.Add(line);
        }

        list = result.Where(x => !string.IsNullOrEmpty(x) && (x.Contains("dynamic") || x.Contains("static")))
            .Select(x =>
            {
                string[] parts = x.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                return new IPAndMac { IP = parts[0].Trim(), MAC = parts[1].Trim() };
            }).ToList();
    }

    public static string FindIPFromMacAddress(string macAddress)
    {
        InitializeGetIPsAndMac();
        IPAndMac item = list.SingleOrDefault(x => x.MAC == macAddress);
        if (item == null)
            return null;
        return item.IP;
    }

    public static string FindMacFromIPAddress(string ip)
    {
        InitializeGetIPsAndMac();
        IPAndMac item = list.SingleOrDefault(x => x.IP == ip);
        if (item == null)
            return null;
        return item.MAC;
    }

    private class IPAndMac
    {
        public string IP { get; set; }
        public string MAC { get; set; }
    }
}

and use it as
string ipAddress = IPMacMapper.FindIPFromMacAddress("some-mac-address");
string macAddress = IPMacMapper.FindMacFromIPAddress("some-ip-address");

A: What you're looking for is reading the computer's ARP list.
Then parse it to find the requested MAC address...
Notice that arp -a has both the IP and MAC so you just need to match the requested one.
Here is an example of how it is done in C#


text:
Q: Query optimization (from joining two tables) Alright so I have this query which regularly shows up in mysql slow log:
    (
        SELECT  user_visit_logs.date,user_visit_logs.user_id,invalid_hits,
                unique_hits,non_unique_hits,earned,sites_surfed,earnings
            FROM  user_visit_logs
            LEFT OUTER JOIN  surfer_stats
               ON  user_visit_logs.user_id = surfer_stats.user_id
              AND  user_visit_logs.date = surfer_stats.date
            WHERE  user_visit_logs.user_id = '218'
    )
    UNION
    (
        SELECT  surfer_stats.date,surfer_stats.user_id,invalid_hits,unique_hits,
                non_unique_hits,earned,sites_surfed,earnings
            FROM  user_visit_logs
            RIGHT OUTER JOIN  surfer_stats
               ON  user_visit_logs.user_id = surfer_stats.user_id
              AND  user_visit_logs.date = surfer_stats.date
            WHERE  surfer_stats.user_id = '218'
    )

Which basically joins daily data from two tables, as follows:
+------------+---------+--------------+-------------+-----------------+--------++--------------+----------+
|           DATA FROM TABLE 1                                                  ||    DATA FROM TABLE 2    |
+------------+---------+--------------+-------------+-----------------+--------++--------------+----------+
|    date    | user_id | invalid_hits | unique_hits | non_unique_hits | earned || sites_surfed | earnings |
+------------+---------+--------------+-------------+-----------------+--------++--------------+----------+

As you can see, "date & user_id" are the common columns on which both tables are joined.
The data is then used to generate a HTML table through PHP using mysqli_fetch_assoc.
Mysql explain extended output:
+----------+-------------+-----------------+------+------------------+---------+---------+------------------------------------+------+----------+------------+
|    id    | select_type | table           | type | possible_keys    | key     | key_len | ref                                | rows | filtered | Extra
+----------+-------------+-----------------+------+------------------+---------+---------+------------------------------------+------+----------+------------+
|    1     | PRIMARY     | user_visit_logs | ref  | user_id,LinkDate | user_id | 8       | const                              | 30   | 100.00   |
+----------+-------------+-----------------+------+------------------+---------+---------+------------------------------------+------+----------+------------+
|    1     | PRIMARY     | surfer_stats    | ref  | user_id,date     | user_id | 8       | const                              | 6    | 100.00   | USING WHERE
+----------+-------------+-----------------+------+------------------+---------+---------+------------------------------------+------+----------+------------+
|    2     | UNION       | surfer_stats    | ref  | user_id          | user_id | 8       | const                              | 6    | 100.00   |
+----------+-------------+-----------------+------+------------------+---------+---------+------------------------------------+------+----------+------------+
|    2     | UNION       | user_visit_logs | ref  | user_id,LinkDate | LinkDate| 11      | const,rotate_ptp.surfer_stats.date | 1    | 100.00   |
+----------+-------------+-----------------+------+------------------+---------+---------+------------------------------------+------+----------+------------+
|    NULL  | UNION RESULT| <union1,2>      | ALL  | NULL             | NULL    | NULL    | NULL                               | NULL | NULL     |
+----------+-------------+-----------------+------+------------------+---------+---------+------------------------------------+------+----------+------------+

So question is, is there a way to further optimize this query?
Thanks.
Indexes for TABLE 1 (user_visit_logs):
+-------------+-------+--------+--------+---------------+-------------+-----------+------+
|    Keyname  | Type  | Unique | Packed | Column        | Cardinality | Collation | Null |
+-------------+-------+--------+--------+---------------+-------------+-----------+------+
|    PRIMARY  | BTREE | Yes    | No     | id            | 29097       | A         | No   |
+-------------+-------+--------+--------+---------------+-------------+-----------+------+
|    user_id  | BTREE | No     | No     | user_id       | 4849        | A         | No   |
+-------------+-------+--------+--------+---------------+-------------+-----------+------+
|    LinkDate | BTREE | No     | No     | user_id, date | 4849, 29097 | A         | No   |
+-------------+-------+--------+--------+---------------+-------------+-----------+------+

Indexes for TABLE 2 (surfer_stats):
+-------------+-------+--------+--------+---------------+-------------+-----------+------+
|    Keyname  | Type  | Unique | Packed | Column        | Cardinality | Collation | Null |
+-------------+-------+--------+--------+---------------+-------------+-----------+------+
|    PRIMARY  | BTREE | Yes    | No     | id            | 235428      | A         | No   |
+-------------+-------+--------+--------+---------------+-------------+-----------+------+
|    user_id  | BTREE | No     | No     | user_id       | 78476       | A         | No   |
+-------------+-------+--------+--------+---------------+-------------+-----------+------+
|    date     | BTREE | No     | No     | date          | 1183        | A         | No   |
+-------------+-------+--------+--------+---------------+-------------+-----------+------+

user_visit_logs
CREATE TABLE `user_visit_logs` (
 `id` int(255) NOT NULL AUTO_INCREMENT,
 `user_id` bigint(20) NOT NULL,
 `date` date NOT NULL,
 `invalid_hits` int(50) NOT NULL,
 `unique_hits` int(255) NOT NULL,
 `non_unique_hits` int(255) NOT NULL,
 `earned` varchar(120) NOT NULL,
 PRIMARY KEY (`id`),
 KEY `user_id` (`user_id`),
 KEY `LinkDate` (`user_id`,`date`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=604253 DEFAULT CHARSET=latin1

surfer_stats
CREATE TABLE `surfer_stats` (
 `id` bigint(20) NOT NULL AUTO_INCREMENT,
 `user_id` bigint(20) NOT NULL,
 `date` date NOT NULL,
 `sites_surfed` int(11) NOT NULL,
 `earnings` decimal(10,8) NOT NULL,
 PRIMARY KEY (`id`),
 KEY `user_id` (`user_id`),
 KEY `date` (`date`)
) ENGINE=InnoDB AUTO_INCREMENT=235787 DEFAULT CHARSET=latin1

A: You have the intersection twice, then go through a de-dup process (UNION DISTINCT).  Instead, see the code for FULL OUTER JOIN in
        SELECT  vl.date, vl.user_id, invalid_hits, unique_hits, non_unique_hits,
                earned, sites_surfed, earnings
            FROM  user_visit_logs AS vl
            LEFT OUTER JOIN  surfer_stats AS ss
               ON  vl.user_id = ss.user_id
              AND  vl.date = ss.date
            WHERE  vl.user_id = '218'
    )
    UNION  ALL   -- avoid dedup pass
    (
        SELECT  ss.date, ss.user_id, invalid_hits, unique_hits, non_unique_hits,
                earned,sites_surfed, earnings
            FROM  user_visit_logs AS vl
            RIGHT OUTER JOIN  surfer_stats AS ss
               ON  vl.user_id = ss.user_id
              AND  vl.date = ss.date
            WHERE  ss.user_id = '218'
              AND  vl.user_id IS NULL   -- avoid dup
    )

Also, have this on both tables:
INDEX(user_id, date)

Note that the (255) after INT means nothing.  Any INT is a 4-byte (32-bit)` integer.
earnings cannot be bigger than 99.99999999 ?


text:
Q: Django transforming function based view into class based view Im trying to convert a fucntion based views into a class based views but have hit a wall with this function.
@login_required(login_url=settings.LOGIN_URL)
def list_bugs_view(request, id):

queryset = Bug.objects.filter(project=id)
project = Project.objects.filter(id=id)

context = {
    'bug_list': queryset,
    'project': project
}

return render(request, 'bugs/bug_list.html', context)

{% extends 'base.html' %}

<-- bug_list.html -->

{% block content %}

{{ project.name }}

            Bug ID
            Name
            Status
            Severity
            Creator
            Created
            Actions

        {% for bug in bug_list %}

                {{ bug.id }}
                {{ bug.name }}
                {{ bug.status }}
                {{ bug.severity }}
                {{ bug.bug_creator }}
                {{ bug.bug_created }}

        {% endfor %}

{% endblock %}

I have already used the generic.ListView to convert another function based view but do not know how to filter the bugs by project which is reciving an id from:
# Class based view responsible for creating a project.
class ProjectCreateView(LoginRequiredMixin, CreateView):
model = Project
template_name = 'projects/project_create.html'
form_class = ProjectForm
success_url = '/projects/create'

# This come from LoginRequiredMixin
# Redirects page to LOGIN_URL page (the value of which is set in settings.py) when the user tires accessing the projects/project_create page but is not logged in.
login_url = settings.LOGIN_URL

def form_valid(self, form):
    return super().form_valid(form)

def get_success_url(self):
    return reverse('projects:project_list')

project_list.html
{% extends 'base.html' %}

{% block content %}

            Project ID
            Name
            Created
            Creator
            Bugs
            Actions

        {% for project in project_list %}

                {{ project.id }}
                {{ project.name }}
                {{ project.project_created }}
                {{ project.project_creator }}
                View

                    Details
                    Update
                    Delete

        {% endfor %}

{% endblock %}

I really am struggling with understanding how to make this work like the other.

A: This looks more like a DetailView [Django-doc] where you additionally pass a queryset to the context:
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import DetailView

class ListBugsView(LoginRequiredMixin, DetailView):
    pk_url_kwarg = 'id'
    template_name = 'bugs/bug_list.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['queryset'] = Bug.objects.filter(project_id=self.kwargs['id'])
        return context


text:
Q: How to make strings not repeat in a random word generator I am making a random string generator, however I am having issues making the strings not repeat when generating
Here's the Code:
import random
import string

repeat = True

pp = input("What's your text? ").lower()
pl = len(pp)

while repeat == True:
    letters = string.ascii_lowercase
    result_str = ''.join(random.choice(letters) for i in range(pl))
    print(result_str)
    if result_str == pp:
        repeat = False

How can I make the strings always different from one another
I've tried searching it up on google, but got no result I was happy with.

A: You can try like below. In the below example, I suppose you want the length of each string==10 and you want to generate 10 strings that don't have repeating. In each iteration, we generate a random string and if generated string doesn't exist in seen we add generate string to seen and increase one-time cnt. Until cnt < count_not_repeated_string we continue to generate random strings.
import random
import string

pl = 10
count_not_repeated_string = 10
cnt = 0
seen = set()

while cnt < count_not_repeated_string:
    letters = string.ascii_lowercase
    result_str = ''.join(random.choice(letters) for i in range(pl))
    if not result_str in seen:
        seen.add(result_str)
        cnt += 1
print(seen)

Output:
{'pmyolioqqh', 'lufictzhov', 'jifdiwvupa', 'eafmoxmiqx', 'ktdfmekwoa', 'vtpjtittgt', 'rvvfdreuox', 'crfgbveazn', 'jntmlfhixy', 'gkhxcfuydy'}


text:
Q: SPFx - React - OfficeUI Fabric - Assign value from SharePoint List Item to DatePicker and DropDown Controls Thank you for your reply. I have values stored in SharePoint list. Now I want to provide edit functionality to user so when user selects particular item, I'm showing user the fields in editable mode with existing values fetched from SharePoint list. In readItem() method, I'm able to set Text field and Date field but not able to set selected value (which is stored in SP list under that column) to Dropdown and PeoplePicker and checkbox.
In .ts file:
export interface IProjectName {
        name: string;
firstdate: Date;
dpselectedItem?: { key: string | number | undefined };
dpselectedItems: IDropdownOption[];
pplPickerType:string;
userIDs: number[];
userManagerIDs: number[];
Items:IDropdownOption[];

}

In .tsx file I have below code under Constructor,
this.state = {
      name: "",
firstdate: null,
      dpselectedItem: undefined,
      dpselectedItems: [],
      userIDs: [],
      userManagerIDs: [],
      pplPickerType: "",
      Items: this._getItems()

    };
  }

Public componentDidMount(){

    this.readItem(itemID);
    }
  }

To get DropDown values I've method as below

private _getItems() {
    return [
      { key: ABC', text: ABC },
      { key: 'DEF', text: 'DEF' },
      { key: 'GHI', text: GHI }
    ]
}

Under render:
public render(): React.ReactElement<…>
{
return(

                <Dropdown
                  placeHolder="Select an Option"
                  label=""
                  defaultValue="Select an Option"
                  id="component"
                  selectedKey={dpselectedItem ? dpselectedItem.key : undefined}
                  ariaLabel="Basic dropdown example"
                  options={this.state.getItems}
                  onChanged={this._changeState}
                />

                Assigned To

                <PeoplePicker
                  context={this.props.context}
                  personSelectionLimit={1}
                  groupName={""}
                  showtooltip={false}
                  isRequired={false}
                  selectedItems={this._getManager}
                  principalTypes={[PrincipalType.User]}
                  ensureUser={true}
                  defaultSelectedUsers={[this.state.AssignedTo]}
                />

)

private _changeState = (item: IDropdownOption): void => {
     this.setState({ dpselectedItem: item });
}

private readItem(itemID: number): void {

    pnp.sp.web.lists.getByTitle("List Title").items.getById(itemID).get().then((item: any) => {

        this.setState({ name: item.Title});

let strfirstDate = new Date(item.firstDate);
      this.setState({ firstdate: strfirstDate });

    //this.setState({ dpselectedItem: item.TypeofCA }) //Not working
//PeoplePicker

});

Thanks,

A: All of the controls listed below have numerous more properties than what I have demonstrated.  I have only shown the properties necessary to set values from your state into these controls, please refer to the linked docs for the additional required and optional parameters.  Also note that each of these will require imports at the top of you component file.
Within the render() method of your react component, you would use the firstDate value from your state with a DateTimePicker as follows:
<DateTimePicker label="DateTimePicker1" value={this.state.firstDate} />

You didn't specify what state value you to use in a dropdown, but Dropdown would look something like this:
<Dropdown selectedItem={this.state.thingWeWantSelected} />

And a PeoplePicker would look something like:
<PeoplePicker selectedItems={this.state.peopleWeWantSelected} />


text:
Q: Error when trying to read a csv file and specifying a column as numeric: scan() expected 'a real', got '"14.3"' I am using a work machine that runs windows 7 and I am using R version 3.5.1 (2018-07-02).  This is my first post to stackexchange and I am not an experienced programmer.
I have a .csv file that has many columns, so I am trying to read in only a few specific columns. I run into trouble when I try to read in some of the columns as numeric.
I have a work-around (specify all of the columns as character, and then convert the ones I need to numeric later), but I am very curious why my first way doesn't work.
If I use the code
col_to_read<-rep("NULL",46)
col_to_read[c(11,17,23)]<-"numeric"
col_to_read[2]<-"character"
col_to_read[5]<-"factor"

data<-read.csv("outcome-of-care-measures.csv",colClasses=col_to_read)

I get
Error in scan(file = file, what = what, sep = sep, quote = quote, dec = dec,  :
  scan() expected 'a real', got '"14.3"'

I have looked for similar questions asked on stackexchange and google, but the proposed solutions didn't work for me.  This may be because my error is slightly different that than the others.  Usually they report something like
 scan() expected 'a real', got '14.3'

So the number doesn't have the additional set of quotes.
There are many columns in this data set, and the column names are very long so its hard to post what the data looks like in notepad, but the first row goes something like this
"010001","SOUTHEAST ALABAMA MEDICAL CENTER","1108 ROSS CLARK CIRCLE","","","DOTHAN","AL","36301","HOUSTON","3347938701","14.3",

This isn't the full row of data, I stopped at the 14.3 which is the first column I want to specify as numeric.
I have tried a number of read.csv and read.table permutations, one of which includes setting dec="," but I just get the same error.  I do not live in a locale where commas are used for decimals.  If I do not specify anything for colClasses, the fields I want to be numeric will by default be read as factor.
The output of sessionInfo() is
R version 3.5.1 (2018-07-02)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] swirl_2.4.3

loaded via a namespace (and not attached):
 [1] httr_1.3.1      compiler_3.5.1  magrittr_1.5    R6_2.2.2        tools_3.5.1     RCurl_1.95-4.11
 [7] yaml_2.2.0      stringi_1.1.7   stringr_1.3.1   digest_0.6.17   testthat_2.0.0  rlang_0.2.2
[13] bitops_1.0-6


text:
Q: Equivalent of System.Character.TCharHelper.IsWhiteSpace / IsLetter / IsNumber for AnsiChar What is the equivalent of System.Character.TCharHelper.IsWhiteSpace / IsLetter / IsNumber for AnsiChar (UTF8)?

A: In general, it does not make sense to ask whether a single UTF-8 element (single byte) represents a whitespace. That's because UTF-8 is a variable length encoding and a code point may require more than a single byte to define it.
So you cannot ask whether or not a single byte is a whitespace, unless it encodes an ASCII character, i.e. < 128.
What you would need to do is to take the sequence of bytes that encode the code point of interest, and convert them into a UTF-32 value in a UCS4Char variable. Then pass that to the UCS4Char overload of TCharHelper.IsWhiteSpace.
However, that approach is not well supported by the Delphi libraries. The simplest way to do what you wish in Delphi is:

*

*Convert your UTF-8 string to be a native UTF-16 Delphi string.

*Use TCharHelper.IsWhiteSpace(str, index) to query for the code point at position index.

A: If your question goes as to how to check if a UTF8-string variable is all white spaces, you can use the following RECORD HELPER:
TYPE
  U8StringHelper  = RECORD HELPER FOR UTF8String
                      FUNCTION IsAllWhiteSpaces : BOOLEAN;
                    END;

FUNCTION U8StringHelper.IsAllWhiteSpaces : BOOLEAN;
  VAR
    C : CHAR;
    S : UnicodeString;

  BEGIN
    S:=Self;
    FOR C IN S DO IF NOT C.IsWhiteSpace THEN EXIT(FALSE);
    Result:=TRUE
  END;

Then you can use it as in:
VAR
  U8 : UTF8String;

BEGIN
  U8:='  '#13#10;
  IF U8.IsAllWhiteSpaces THEN WRITELN('Yes') ELSE WRITELN('No');
  U8:='  X'#13#10;
  IF U8.IsAllWhiteSpaces THEN WRITELN('Yes') ELSE WRITELN('No');
END.

This will write out "Yes" followed by "No".
But please beware, that by defining your own helper for the UTF8String type, you are eliminating the access to any that may have been defined by the system. If that is a problem, you'll have to make a standard function instead:
FUNCTION IsAllWhiteSpaces(CONST U8 : UTF8String) : BOOLEAN;
  VAR
    C : CHAR;
    S : UnicodeString;

  BEGIN
    S:=U8;
    FOR C IN S DO IF NOT C.IsWhiteSpace THEN EXIT(FALSE);
    Result:=TRUE
  END;

and use it as follows:
VAR
  U8 : UTF8String;

BEGIN
  U8:='  '#13#10;
  IF IsAllWhiteSpaces(U8) THEN WRITELN('Yes') ELSE WRITELN('No');
  U8:='  X'#13#10;
  IF IsAllWhiteSpaces(U8) THEN WRITELN('Yes') ELSE WRITELN('No');
END.

I'll leave the making of the other IsXXX functions up to the reader...

A: Okay - after we have finally determined the proper question, the easiest way for you is to simply cast-up the AnsiChar variable to a proper UNICODE char and then do your thing.
VAR
  A : AnsiChar;

BEGIN
  IF CHAR(A).IsLetter THEN ...
END.

HOWEVER: working with individual characters from a UTF-8 string is not advisable, as many characters (by the very nature of UTF-8) consists of TWO characters. You are therefore not able to decide if a single AnsiChar from UTF-8 string is anything, as it can merely be a "prefix"/"escape" character, and the actual character is the following character from the string.
So the best way would be to have your UTF8-String and assign it to a UNICODE string variable, and then use the proper CHAR type to iterate over it.
If your question is how to "convert" an AnsiString encoded in UTF-8 into a UNICODE string, you can use the following routine:
FUNCTION AnsiUTF8toUNICODE(CONST S : AnsiString) : STRING;
  BEGIN
    Result:=UTF8ToUnicodeString(RawString(S))
  END;


text:
Q: Hashtags for posts with swift using parse I have a uitextfield for tags. My Parse "Post" Class has a column for the tags when the user is creating the posts. I want the textfield for tags to be saved to the data base in such a way that I can query that column in the Posts class and also be able to show them in the app separated with "#" right after the keyboard is dismissed or when they hit the space bar.
Basically the same functionality as stack overflows tags when creating this question, but for ios!

A: Your tags should really be a class, and your column of tags should be an array of pointers (not strings).
As the user types you can query for the matching tags and display these options. If no match is found you can create and save a new tag. Then add the tag to the array of pointers (add unique method).
When querying for your objects you can use the includes key option to have the array of tag pointers downloaded at the same time so you have the tag names to display.
To query by tag you get the tag object and then query for objects where the tags array contains that tag object.


text:
Q: C#.Net Core 3.1 HttpRequest timeout or SSL connection issue Ok i have the following code
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
clientHandler.UseProxy = false;

using (HttpClient client = new HttpClient(clientHandler))
{
    var reqUri = string.Format("{0}/{1}?getBIC=true&validateBankCode=true", AppSettings.Instance.ValidationSettings.IBANValidationUri, iban);
    Logger.Instance.LogInfo("IBAN Validation: Sending request");
    using (HttpResponseMessage res = await client.GetAsync(reqUri))
    {
        using (HttpContent content = res.Content)
        {
            if (content != null)
            {
                Logger.Instance.LogInfo("IBAN Validation: Reading data");
                var data = res.Content.ReadAsStringAsync();
                if (!string.IsNullOrEmpty(data.Result))
                {
                    result = JsonConvert.DeserializeObject<IBANValidationResult>(data.Result);
                }

            }
        }
    }
}

Now this code simply makes a rquest to the openiban api to get the specific bank information from a IBAN number.
This code runs on a ASP.NET Core 3.1 Web API that is running on a IIS Server.
Now we have 3 exact same server with the same web api.
The problem:

*

*when i call the service from a browser on server 1, the service works fine i get the response etc.

*when i call the service from a browser on server 2 it works also fine.

*when i call the service from a browser on server 3 it takes too long and then i receive following error on the backend:

ERROR: The SSL connection could not be established, see inner
exception
ERROR: Authentication failed because the remote party has closed the
transport stream.

The funny thing is: This issue does not depend on one server, sometimes the server 3 works but then server 2 does not work, sometimes server 1 does not work an the other servers are working.
Does anybody have a clue what is going on here?
PS: The SSL certificates are installed on the server
Thanks a lot


text:
Q: how to connect android phone(client) to laptop using only one ip address(static)? I am doing a android project. I want to connect my client(android phone) using ip address to my laptop(server). I am using ip address of wireless modem(MTS). Each time i reconnect the ip address changes. So how can I keep this ip address constant so that only one ip address can be used for connection via wireless internet connection?

A: If client IP is fix then here's an approach
1)Write a code listening to port in android client
2)In the server, write a client to connect to android port send the server IP to the android
Then you can continue with your normal approach
OR
You can use UPNP for your case where upnp server broadcast its info to all the clients in the network.But implementation will be a bit extensive in this case.

A: The ip-address of your modem is given by your provider and will most likely change everytime you reconnect.
So my answer would be you can´t. This makes the question far off topic, you might wanna take it off.


text:
Q: fetching all values from Hashes with Multiple Values Per Key in perl how to fetch all the values and print it, in the code follows multiple values per key
%ages = (
" Michael Caine" => {39,34,11,12},
" Dirty Den" => {34,56,76,58},
" Angie" => {27,56,78,89}
);

@keys = keys %ages;
@val = values %ages;
print @keys;
print @val; #it will not work in case of multiple values per key

A: You have three problems.

*

*You are using hashrefs, not arrayrefs

*You aren't assigning anything to @val (at least, you weren't before you edited the question)

*You aren't doing anything to dereference your references

Such:
use v5.10;

my %ages = (
" Michael Caine" => [39,34,11,12],
" Dirty Den" => [34,56,76,58],
" Angie" => [27,56,78,89]
);

foreach my $key (keys %ages) {
    say $key;
    say @{$ages{$key}};
}

A: %ages = (
" Michael Caine" => [39,34,11,12],
" Dirty Den" => [34,56,76,58],
" Angie" => [27,56,78,89],
);

@keys = keys %ages;
@val = values %ages;
print "@keys\n";
print "@{$_}\n" for @val;

A: Bhargav Gor, bhai, this is a common way of storing multiple values for a key.
But,

*

*keep in mind that this is an anonymous hash i.e key-value pair: {39,34,11,12} = ("39"=>34, "11"=>12)

*and this is an anonymous array: [39,34,11,12]
You have used 1. which means you are using another hash as a value for the %ages hash, i.e
%ages =
" Michael Caine" => ("39"=>34,"11"=>12),
" Dirty Den" => ("34"=>56,"76"=>58),
" Angie" => ("27"=>56,"78"=>89)

If you want to extract the values for the key "39" of key " Michael Caine"
print %{$ages{" Michael Caine"}}->{"39"}  #prints 34

if really you want such a structure, then this is how you can display all values
foreach(keys %ages) {
  $name = $_;
  foreach(keys %{$ages{$name}}) {
    print %{$ages{$name}}->{$_},",";
  }
  print "\n";
}
#output:
#>34,12,
#>56,58,
#>56,89,

I do not think that you wanted this kind of a stucture, you probably wanted to use an array,
(an anonymous array).
%ages = (
" Michael Caine" => [39,34,11,12],
" Dirty Den" => [34,56,76,58],
" Angie" => [27,56,78,89]
);

Now you can easily display output like this:
foreach(keys %ages) {
  $name = $_;
  foreach( @{$ages{$name}} ) {
    print $_,",";
  }
  print "\n";
}
#output:
#>39,34,11,12,
#>34,56,76,58,
#>27,56,78,89,

I'm sorry I have to rush, sorry for typos, hope you understand what you should do for such a storage


text:
Q: How to cast parcelable array list to array list of objects that implement parcelable? I have a class cholesterolMonitor that implements parcelable.
In my cholesterolMonitor:
 @Override
    public void writeToParcel(Parcel dest, int flags) {
    }
 @Override
        public CholesterolMonitor createFromParcel(Parcel in) {
            return new CholesterolMonitor(in);
        }

But everytime I try to cast it into an array list of monitors I get an error?For example in one method:
this.objectList= (ArrayList<Monitor>) getArguments().getParcelableArrayList(listKey);

I get inconvertible type: cannot cast array list of parcelable to array list of monitors?
After Googling I know why, but I'm not sure how to fix it.


text:
Q: Destructor behaviour in c++ I simply don't get why the destructor is being called when the object is passed as a parameter to a constructor of another class.
This is the part of code where the problem shows up:
Ocean* sea=new Ocean(4,3,7);
sea->print();
RunLengthEncoding* s2= new RunLengthEncoding(*sea);
sea->print();

the code of the constructor:
RunLengthEncoding::RunLengthEncoding(Ocean sea)
{
oceanEncoding = new MyLinkedListD();
height = sea.height();
width=sea.width();
starveT=sea.starveTime();
int length=1;
int cellType=sea.cellContents(0,0);
int hunger=sea.sharkFeeding(0,0);
for(int row=0;row<height;row++){
    for(int col=0;col<width;col++){
        if(row==0&&col==0){
            cellType=sea.cellContents(col,row);
            hunger=sea.sharkFeeding(col,row);
        }
        else{
            if(sea.cellContents(col,row)==cellType && ((cellType==Ocean::SHARK && hunger==sea.sharkFeeding(col,row))|| cellType!=Ocean::SHARK)){
                    length++;
            }
            else{
                oceanEncoding->add(cellType,length,hunger);
                cellType=sea.cellContents(col,row);
                length=1;
                hunger=sea.sharkFeeding(col,row);
            }
        }
    }
}
oceanEncoding->add(cellType,length,hunger);
internalPointer=oceanEncoding->getHead();
check();

}

A: The constructor is taking its argument by value.  A copy is made, used, and then destroyed when the constructor returns.
Take the argument by reference (const reference is best).

A: RunLengthEncoding(*sea);

This takes a value. Not a pointer to a value, nor a reference to a value. The compiler inserts code to create a value and passes it to the function. Inside the function, if you modify the value it doesn't change the one you imagine you are passing in. After the function is called the value is destroyed.
*sea is not passed into the function. It can not be modified inside the function.

A: Since the constructor is taking its argument by value once the function is over the object goes out of scope and is thus destroyed. Since you cannot change the argument of the constructor the object will always be destroyed so the only way around this is to create a new copy of the object allocated on the heap (so it won't be destroyed) however this isn't really good coding practice


text:
Q: Need help to post tweets from another viewcontroller I am Using Outh to add Twitter to my app.
Below are two UIViewControllers for login and posting tweets respectively.
1.SettingViewcontroller
 2.DetailViewcontroller
This code for  login to  twitter with SettingViewcontroller.
 - (void)switchAction1:(UISwitch*)sender
   {
   if (sender.on){
       if(_engine)
       return;

      _engine = [[SA_OAuthTwitterEngine alloc] initOAuthWithDelegate:self]
   _engine.consumerKey = @"###";
    _engine.consumerSecret = @"###";

   UIViewController *controller =[SA_OAuthTwitterController  controllerToEnterCredentialsWithTwitterEngine: _engine delegate: self];

   DetailViewcontroller *detobj=[[DetailViewcontroller alloc]init];

 detobj.detail_enginne=_engine;

   [detobj release];

    [self presentModalViewController: controller animated: YES];
   }
  if(!sender.on)
  {

NSLog(@"Logout section");

    }
}

And In DetailViewcontroller Iam doing like this for posting.
    if(buttonIndex == 1)
{

    if(detail_enginne!=nil)
    {
      NSLog(@"engine availble");

               NSString *str=@"hai twitterrrrrrrrrrr";

             [detail_enginne sendUpdate:str];

    }
    else{
        NSLog(@"Engine not availabele");
             }
}

Here Iam unable  to send tweets from DetailViewcontroller.
How to achive this?

A: in DetailViewcontroller.m
#import "SettingViewcontroller.h"

replace
 [_enginnne sendUpdate:str];

to
[[[self parentViewController] _enginnne] sendUpdate:str];


text:
Q: How to get ajax data to render on component in react flux store? I'm trying to get data from flux store to render on some components. How to do that in flux store. Here, i have added my sample code, which i have tried.
import EventEmitter from 'events';
var newData;
class EventLists extends EventEmitter {
    getAll() {
        $.ajax({
            url:url,
            type:'GET',
            contentType: 'application/json; charset=UTF-8',
            dataType:'json',
            success:function(data) {
                newData = data;
            }
        });
        return newData;
    }
};

const eventLists = new EventLists;

export default eventLists;


text:
Q: 1M records database query optimization I have a table of users with around 1 million records "contacts".
And we keep a log of the emails we sent in another table "log_sent" which is also around 1M records.
We need to find which users havn't received our newsletter yet.
So i am using the following query to get the next user we need to send to:
SELECT contact.*
FROM contacts AS contact
LEFT JOIN log_sent AS sent ON sent.contact_id = contact.id
WHERE sent.id IS NULL
LIMIT 0 , 1

This is what the EXPLAIN query returns:
id | select_type | table   | type | possible_keys | key        | key_len | ref                        | rows    | Extra
  1 | SIMPLE      | contact | ALL  | NULL          | NULL       | NULL    | NULL                       | 1031628 |
1 | SIMPLE      | sent    | ref  | contact_id    | contact_id | 4       | admin_marketing.contact.id | 1       | Using where; Not exists

The log_sent table has contact_id indexed.
The contacts table has id as the primary index.
This query take about 1.8 seconds to execute.
And the log_sent table is growing so this will be problematic. How can I optimize this query.
For what i understand it seems that the query is search all 1 million records in the contacts table. But there is really no index i can use to limit the number of users used.
Or maybe i'm missing something ?

A: If you really only need a single row, rewriting the query so it uses a not exists clause might make a difference:
SELECT contact.*
FROM contacts AS contact
WHERE NOT EXISTS ( SELECT 1 FROM log_sent AS sent WHERE sent.contact_id = contact.id )
LIMIT 1

If it doesn't I'd suggest reversing your logic. Create a "sending" table, and fill it up when an email needs to be sent. Delete from it (and add to your logs table) as you send new emails.

A:
invisal, this wouldn't work since we send different newsletters at
  different times. So i would need to add a new field for every campaign
  we're going to do

Then do like what @Denis has suggested. You do not need to create new table for every different newsletters. Here is the mock-up schemas:

contacts (contact_id, ...)
newsletter_campaign (campaign_id, campaign_name)
newsletter_sending (campaign_id, contact_id)
newsletter_log (campaign_id, contact_id, send_date)

Create New Campaign

*

*Insert all the contacts into newsletter_sending with a single query:

*INSERT INTO newsletter_sending SELECT {$new_campaign_id}, contact_id
FROM contacts;.

Sending a newsletter to a contact

*

*Remove contact from the newsletter_sending list and add to log

*DELETE FROM newsletter_sending WHERE campaign_id = {$campaign_id} AND contact_id = {$contact_id}

*INSERT INTO newsletter_log VALUES({$campaign_id, {$contact_id}, NOW())
Query users that haven't received your newsletter

*

*SELECT * FROM newsletter_sending WHERE campaign_id = {$campaign_id}
Query users that have received your newsletter

*

*SELECT * FROM newsletter_log WHERE campaign_id = {$campaign_id}
The reason that I insist you to change is because your current schema does not scale. It will getting slower and slower when contact and log are getting bigger and bigger


text:
Q: Oracle Apex - Date effective non-overlapping dates via validation and interactive grid - How to refer to interactive grid current row values I'm trying to create a validation on create and update of an interactive editable grid in Oracle Apex 5.1. I right click the effective_start_date column and then choose Create Validation. From here I then set Type to No Rows returned with the idea of doing a select where there are other rows for the same date range as the current row being created or updated.
I have the following query:
select *
from   my_table c
where  c.salary_band = :salary_band
and    c.id != :id
and    c.effective_start_date <= :effective_end_date
and    c.effective_end_date   >= :effective_start_date

However this does not work as expected (error when there are overlapping dates for a salary band). Even when I comment out the last two lines it does not error on a duplicated salary band value. My assumption is that I am not referring to the current row values of the interactive grid entered during the create or update incorrectly although no error is thrown when I create the validation. How do I refer to the current row values entered in the interactive grid or what am I doing wrong here?

A: Turned out to be the :id that does not exist when creating, the other values work fine.


text:
Q: Accessing Map Interface Object created in Main class Consider the following two classes :
Class A begins here is a separate java file in the same package:
public class A {

public void putIntoMap(int a[]){
  Map <Integer, Integer> intMapObject = new HashMap<Integer,Integer>();
      for (int i = 0 ; i < a.length ; i++){

          // some code here
       }
       intMapObject.put(a[i], count);
}

}

Class B begins here is a separate java file in the same package:
public class B {

    public static void main(String args[]){

    A a = new A();

    a.putIntoMap(arr); // assume arr is an array I already have

    // Now I need to do loop over the Map and I need the `intMapObject`  //object from above class A

// I need to do something like this

for (Map.Entry<Integer,Integer> e : intMapObject.entrySet()){

  // some code here

     }

}

How do I access intMapObject object in class B ?

A: You can't access variables declared in another method. Ever.
But that doesn't mean you can't pass objects from one method to another. In this case, I suggest making putIntoMap return the new map:
// in A
public Map<Integer, Integer> putIntoMap(int a[]){
  Map <Integer, Integer> intMapObject = // ...
  // some code to put the stuff in the map here

  return intMapObject;
}

// in B
A a = new A();
Map<Integer, Integer> theMap = a.putIntoMap(arr);
for(Map.Entry<Integer, Integer> e : theMap.entrySet()) {
    // some code here
}

Note that this does not pass the actual object, but a reference to it. In Java, objects are not stored in variables.


text:
Q: am not getting list items individually nodes=['a','b','c','d','e','f','g']
G.add_edges_from([('a','f'),('a','d'),('a','b'),('a','e'),('b','g'),('b','e'),('b','c'),('c','b'),('c','d'),('d','a'),('d','c'),('e','b'),('e','a'),('f','a'),('g','b')])
nodlen=len(nodes)
for i in range(nodlen):
    print(G.neighbors(nodes[i]))

I am getting the entire list (as below), but I need to access the individual elements from this list.
['e', 'b', 'f', 'd']
['e', 'c', 'g', 'a']
['b', 'd']
['c', 'a']
['b', 'a']
['a']
['b']

A: The Graph.neighbors() method returns a bog-standard Python list object. Just index into it:
neighbors = G.neighbors(nodes[i])
print('First neighbor', neighbors[0])

or loop over it to get to each individual element of the list.
In Python, you usually do not generate indices to access all elements in a list, you just loop over the list itself; the for construct is a Foreach loop:
nodes=['a','b','c','d','e','f','g']
G.add_edges_from([('a','f'),('a','d'),('a','b'),('a','e'),('b','g'),('b','e'),('b','c'),('c','b'),('c','d'),('d','a'),('d','c'),('e','b'),('e','a'),('f','a'),('g','b')])

for node in nodes:
    print('Neighbors for', node)
    for neighbor in G.neighbors(node):
        print('    ', neighbor)
    print()

A: nodes=['a','b','c','d','e','f','g']
G.add_edges_from([('a','f'),('a','d'),('a','b'),('a','e'),('b','g'),('b','e'),('b','c'),('c','b'),('c','d'),('d','a'),('d','c'),('e','b'),('e','a'),('f','a'),('g','b')])
nodlen=len(nodes)
for i in range(nodlen):
    all_items = G.neighbors(nodes[i])
    for one in all_items:
        print one