text:
Q: Validate date with jquery and help user I make a jQuery function which should check user value. The date format what I need is "YYYY-MM-DD". I want to insert "-" in the users text when the length is 5 and 8. What I make:

$(document).ready(function(){
    $('input[type=date]').keydown(function(){
         var leng = $(this).val().length;
         var content = $(this).val();
         if(leng == 5){
            $(this).text(content+"-");
         }else if(leng == 8){
            $(this).text(content+"-");
         }
    });
});
<input type="date" name="openDatePerm1" class="form-control"
       id="openDatePerm1" placeholder="YYYY-MM-DD" maxlength="10">

It isn't insert "-" when it should (it do it never). What I do wrong?

A: You should use $(this).val(content+"-");

A: You just need to assign by using $(this).val(..), and not $(this).text(..), then just shift your variables by one, so (leng == 4) rather than (leng == 5) and (leng == 7) rather than (leng == 8)

$(document).ready(function(){
    $('input[type=date]').keydown(function(){
         var leng = $(this).val().length;
         console.log(leng)
         var content = $(this).val();
         if(leng == 4){
            $(this).val(content+"-");
         }else if(leng == 7){
            $(this).val(content+"-");
         }
    });
});

<input type="date" name="openDatePerm1" class="form-control" id="openDatePerm1" placeholder="YYYY-MM-DD" maxlength="10">

A:
make a jQuery function which should check user value. The date format
  what I need is "YYYY-MM-DD"

It is not necessary to insert "-" at input type="date" value . If this.checkValidity() returns true , input value should be valid , including "-" between each YYYY , MM , DD . To view resulting string use this.value , to view value as Date string use this.valueAsDate . To make certain that each YYYY , MM , DD are set , try also setting minlength attribute to 10

$(document).ready(function(){
    $("input[type=date]").change(function() {
         console.log(this.checkValidity(), this.value, this.valueAsDate)
    });
});
input[type="date"]:invalid ~ label[for="input"]:after {
  color:red;
  content:"Invalid date ";
}

<input type="date" name="openDatePerm1" class="form-control" id="openDatePerm1" placeholder="YYYY-MM-DD" maxlength="10" minlength="10">

Alternatively, using pattern attribute with RegExp
(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))

See HTML5 Pattern - Dates

$(document).ready(function() {
  $("input[type=text]").change(function() {
    console.log(this.checkValidity(), this.value, this.valueAsDate)
  });
});
input[type="text"]:invalid ~ label[for="input"]:after {
  color: red;
  content: "Invalid date. Required date format: YYYY-MM-DD ";
}

<input type="text" name="openDatePerm1" class="form-control" id="openDatePerm1" placeholder="YYYY-MM-DD" maxlength="10" minlength="10" pattern="(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))">

A: Your solution almost got it right, here a small tweak to yours.
1- the correct function to use is $(this).val(content+"-"); using the function val() not text() as in your example:  $(this).text(content+"-");
2- users might need to delete/erase using backspace, then there should be an exception for it. Otherwise the function will keep re-adding the previous content and the user won't be able to delete his input.
3- the number of chars are: 4 and 7 not 5 and 8. Because the first '-' should be inserted after exactly 4 digits e.g. 1999 then '-'. After that the month which is two digits added to the year plus one hyphen 4+1+2 is 7 digits in total.
Here is a working solution:
DEMO

    $(document).ready(function() {

      $('input[type=date]').keydown(function() {
        //Capture the field object
        $field = $(this);
        //Verify if the user is trying to delete or add new chars
        $('html').keyup(function(e) {
          if (e.keyCode == 8) {} else {
            //alert("here");
            //Call the function that will count the chars and add '-'
            addDash($field);
          }
        });
      });

      function addDash($field) {
        var leng = $field.val().length;
        var content = $field.val();
        if (leng == 4) {
          $field.val(content + "-");
        } else if (leng == 7) {

          $field.val(content + "-");
        }
      }
    });

<input type="date" name="openDatePerm1" class="form-control" id="openDatePerm1" placeholder="YYYY-MM-DD" maxlength="10">


text:
Q: Show snackbar after startactivity I created a sign-out button in my app.
Once the user clicks sign out, it signs out and moves the log-in activity.
I had like that once the user clicks on sign-out, it will move to the log-in page and then show the snackbar saying "you have been signed out successfully".
How can I make the snackbar appear only after it moved to the new activity? Because right now it won't show since it changes the activity.
public void signOut(){

    auth.signOut();

    AuthUI.getInstance()
            .signOut(this)
            .addOnCompleteListener( task -> {
                Intent intent = new Intent(ChangePassActivity.this, SignInActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                        Intent.FLAG_ACTIVITY_CLEAR_TASK |
                        Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);

                Pop_Snack("you have been signed out successfully");

                finish();
            } );
}

public void Pop_Snack(String text){
    Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content),text,Snackbar.LENGTH_SHORT);
    View sbView = snackbar.getView();
    sbView.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));

    TextView tv = (TextView) (snackbar.getView()).findViewById(com.google.android.material.R.id.snackbar_text);
    Typeface font = ResourcesCompat.getFont(getBaseContext(), R.font.assistant);
    tv.setTypeface(font);
    tv.setTextSize( 14 );

    snackbar.setAnchorView(findViewById( R.id.bottom_navigation ));

    snackbar.setDuration( 5000 );
    snackbar.show();
}

Thank you

A: You can create a static boolean variable isloggedOut default to false in the activity where you want to show Snackbar . When you Logged out from the activity set that boolean  variable to true and check in the onCreate  method of the new Activity where you want to show Snackbar.
if(isloggedOut){
Snackbar snackbar = Snackbar.make(view, "Text to display",
Snackbar.LENGTH_LONG);
    snackbar.show();
}

In your signout method
public void signOut(){

auth.signOut();

AuthUI.getInstance()
        .signOut(this)
        .addOnCompleteListener( task -> {
            Intent intent = new Intent(ChangePassActivity.this, SignInActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                    Intent.FLAG_ACTIVITY_CLEAR_TASK |
                    Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            NewActivity.isloggedOut = true;

            finish();
        } );

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using a state string as a className with React using modular CSS I'm using CSS modules in a React project. I would like to be able to use className={this.state.boxClassName} in my first returned div, rather than hard-coding className={classes.trigger}, as you can see I have done below.
However, when I do this, upon inspecting the page in chrome, the div (which is just a css-styled square) does not receive the proper reference to the css file.
When using the this.state version, I see
 and no square, whereas when I hard code it, I see, correctly,
 (this format with a hashed ending comes from the way css modules in React is configured) and the square properly rendered.
How, then, can I work around this, to be able to refer to the state for the className, given the use of css modules? I'm new and this is my first question here, so thanks for bearing with me, and any assistance is much appreciated.
import React, { Component } from 'react';
import classes from './Box.css';

class Box extends Component {
    state = {
        boxClassName: 'classes.trigger',
    }

    render() {
        return(

        );
    }
}

export default Box;

A: You can set boxClassName to just be the key you want to access from the classes object.
class Box extends Component {
    state = {
        boxClassName: 'trigger',
    }

    render() {
        return(

        );
    }
}

A: It seems like your only issue is that you are setting this.state.boxClassName to specifically the string 'classes.trigger', rather than the value of classes.trigger.
Try modifying your code to something like this:
import React, { Component } from 'react';

import classes from './Box.css';

class Box extends Component {

    state = {
        boxClassName: classes.trigger,
    }

    render() {
        return(

        );
    }
}

export default Box;

A: When you set the boxClassName to 'classes.trigger', you're setting it to that string literal, which is why it appears that way in the css. I'm not completely familiar with react-css-moduels, but you should be able to set boxClassName = classes.trigger (without the quotes)


text:
Q: How to async return from aiohttp server handler? I am running a http server to handle slack API calls which arrive at the events endpoint. The slack documentation suggests that the app (this server) needs to acknowledge the receipt of the request within 3 seconds (which can be achieved by an empty body and status=200). My processing of the request takes way more than 3 seconds so I want to return immediately as soon as I receive the request with a blank response and then process the data. This is the code I am using:
from aiohttp import web

routes = web.RouteTableDef()
app = web.Application()

async def process(data):
    # Do Some Processing which takes more than 5 seconds

@routes.post('/events')
async def handle_event(request):
    post_data = await request.json()
    await process(post_data)

    return web.Response(body="", status=200)
    # I want to do this immediately then process() data afterwards

app.add_routes(routes)
web.run_app(app, port=3000)

How do I return immediately and then process the data (which includes some database queries and sending a slack message using the API, too)
I tried creating a asyncio task but the return does not happen until this task finishes executing (which is understandable):
    process_task = asyncio.create_task(process)
    await task


text:
Q: Adding timestamps to pandas series I'm trying to write a code that will count a number of records in a .csv file in a single hour. So, for example:
 data = pd.read_csv('2021-07-30.csv',  parse_dates=['time'], infer_datetime_format=True)
    datafiltr = data[data.lane == "Lane 4 Op2"]
    datafiltr['time'] = pd.to_datetime(datafiltr['time'])
    df = datafiltr['time'].groupby(datafiltr.time.dt.to_period("H")).agg('count')

Prints:
2021-08-13 13:00    18
2021-08-13 14:00    10
2021-08-13 15:00     2
2021-08-13 16:00     1
2021-08-13 17:00     2
2021-08-13 18:00     4

It works superbly but I need to store data in a 12-hour timespan. Something like this will be ideal:
2021-08-13 13:00    18
2021-08-13 14:00    10
2021-08-13 15:00     2
2021-08-13 16:00     1
2021-08-13 17:00     2
2021-08-13 18:00     4
2021-08-13 19:00     0
2021-08-13 20:00     0
...

But I have no idea how to approach this, please send help.

A: have you tried with resampling, but at least one of your time sample should be of max time to consider till there
df.set_index('time').resample('H').agg('count')

out:
    1   2
0
2021-08-13 13:00:00 1   1
2021-08-13 14:00:00 1   1
2021-08-13 15:00:00 1   1
2021-08-13 16:00:00 1   1
2021-08-13 17:00:00 1   1
2021-08-13 18:00:00 1   1
2021-08-13 19:00:00 0   0
2021-08-13 20:00:00 0   0
2021-08-13 21:00:00 0   0
2021-08-13 22:00:00 0   0


text:
Q: How to isolate two containers connected to the same bridge? I have several LXD containers which are bound to a single bridge (the default lxdbr0 or another one, it does not matter). The host itself has another two interfaces, one ultimately connecting it to Internet and another one to which a WiFi AP is attached.
The data flows are orchestrated by Shorewall (which builds the appropriate iptable rules).
The restrictions I put in place work fine for traffic between the containers to Internet or to the AP network (and between the AP network and Internet). The problem I have is that inter-container traffic does not seem to be affected by the iptable rules. Even with a plain REJECT policy for the container IP, I still manage to ping the IP of another container (and nothing else, including its own gateway - which is expected).
My understanding is that the bridge itself works on ISO/OSI layer 2. In that case firewalling would not affect the traffic.
At the same time, it has an IP, which is the gateway for the containers (the containers all have an address from the same 10.20.30.0/24 network, 10.20.30.254 being the IP of the bridge). Since this is now layer 3 communication, shouldn't the traffic go though iptables?

A: Instead of using a bridge, use router mode in the lxc networking. A bridge connects all the veth NICs attached to it together, by design, as if it were a physical network hub.
If you create the NICs in the containers like this.
lxc.net.0.veth.pair = vethXX
lxc.net.0.veth.mode = router

each NIC is independant.
Each container needs its own subnet, typcially lxc containers share 10.0.3.X  but in this mode you need a subnet per container.
Now you can route traffic as if the veth interfaces were physical NICs and nftables firewall will work, if you do want to allow traffic between containers for something specific.
Traffic between lxc like this can be filtered with the forward chain
table ip filter {
    chain forward {
        type filter hook forward priority filter; policy drop; # defailt to block everything

        # allow only what you want, e.g. ping
        icmp type echo-request accept
        icmp type echo-reply accept
    }
}

You can turn off the lxcbr0 bridge if you use router mode.

A: Not an ideal answer if you have lot of containers but you can use the shorewall hosts file with an entry for each host, ie with a /32 network like this:
/etc/shorewall/interfaces:
#ZONE  INTERFACE   OPTIONS
...
lxc    lxc-br0     ...,routeback,bridge

/etc/shorewall/zones:
#ZONE       TYPE       OPTIONS         IN          OUT
fw          firewall
lxc         ipv4
lxc12:lxc   ipv4

/etc/shorewall/hosts:
#ZONE     HOSTS                              OPTIONS
lxc12     lxc-br0:192.168.0.12/32

/etc/shorewall/rules:
######################################################################################################################################################################################################
#ACTION         SOURCE          DEST            PROTO   DEST    SOURCE          ORIGINAL        RATE            USER/   MARK    CONNLIMIT       TIME            HEADERS         SWITCH          HELPER
#                                                       PORT    PORT(S)         DEST            LIMIT           GROUP
#Allow host web server to proxy requests to the container
Web(ACCEPT)     $FW     lxc12


text:
Q: Resize HTML elements on Android orientation change I am trying to bind an event in Javascript to either the orientationchange or resize events in Android in order to change the width/height of some elements for my web app. In the event, I use window.innerHeight and window.innerWidth to get the current height and width of the window.
This works great on iOS and desktop devices, but on Android it seems that it calls this event before changing the values in the window variable. Therefore, when someone switches from portrait to landscape, I still get the values for portrait and therefore cannot resize correctly. Does anyone know what the problem is, and how I can fix it?

A: I have fixed the problem. It turns out that the resize event works correctly, but the orientationchange event does not. I was testing to see if the orientationevent was present, and then binding to that if possible. I have changed my code over to only use the resize event, and have achieved the desired effect.
I'm not sure if this is unique to my code or not, but that's what fixed it for me.

A: My investigation showed that this Android webview bug ("orientationchange" fires 20-150ms before changing the window.innerHeight Javascript value) exists when you modify the default user agent of the web view. Don't ask me how one is related to another, though.
But to solve your probelm, you can do one of the following:
1) get rid of the following useragent modification from your code
webView.getSettings().setUserAgentString("custom-user-agent");
2) use "resize" event instead of "orientationchange" event

A: There are CSS selectors for this:
/*normal styles here */
#wrap {
   width:1024px;
}
@media only screen and (orientation:portrait){
   /* portrait styles here */
   #wrap {
      width:768px;
   }
}

Source: http://matthewjamestaylor.com/blog/ipad-layout-with-landscape-portrait-modes

A: I can confirm that "orientationchange" -event does not work as expected in android 2.2 and 2.3. It says it present when you check for availability but then does not fire. It works in Android 1.6 and 2.1 though. I ended up, just like you, using "resize" -event for all Android versions.

A: Take a look at the question and answers for Detect rotation of Android phone in the browser with JavaScript . It covers a cross platform to detect changes in orientation.
For getting the size of the viewport and/or window cross platform, take a look at http://responsejs.com/ or http://verge.airve.com/.


text:
Q: load a large txt file into a data structure from C++ I would like to load a comma seperaetd txt file into a map data structure from C++ on visual studio 2013 on win7.
Currently, the txt file has 5000 lines and 300 KB.
Each line is delimited by a new line.
I use getline() and It cost me 90 seconds to finish loading the whole file.
The file is like:
      id , value1, value2,  value3 , … // about 50+ columns
      abc,36.1,69.15,96.358 , ….
      pwr, ….

I need the final format in the map >  data structure like: (id is an index in the map and column name is another index.)
    abc     value1    36.1
            value2    69.15
            value3    96.358
               …
    pwr       …

My C++ code:
while (getline(file, aLine))
{
     **UPDATE**
    // split the line by comma
    stringstream ssa(aLine);
    vector<string> line;
    while (ssa.good())
    {
        string asubStr;
        getline(ssa, asubStr, ',');
        line.push_back(asubStr);
    }
    // cast each string to double if needed.
     myMap[id][valueX]  = y ; // X can be 1, 2, 3, … 50,
                             // y is the number of a value column in
                             // the file,
                             //myMap is map <string, map<string, double >>
}

My final file size can be 60MB and 1 million lines.
Is it possible to save all data in a map in C++ ?
And how to load the file very fast into C++ ? 90 secs for 5000 lines is too slow.
In C++, fgets() do not work for me because I do not know number of elements in the file.
I would like to load the file as fast as possible and then process each line in a data structure.
Thanks
More UPDATE
I made a change so that only load each line as a string without doing any split.
set<string> mySet;
while (getline(file, aLine))
{
    mySet.insert(aLine); // this is all what I do in the loop.
}

But, it still took 12 secs for 5000 lines. So, for 1 milion lines, it will take 40 minutes !

A: Some operating systems provide a feature called memory mapping, where the OS treats a file as memory.  The OS handles reading the data into memory.
You may want to consider using block reading.  Read a block of data into memory and search memory.
The idea here is to optimize the data transfer between the file and memory.  Reading one line at a time is not as efficient as reading blocks of 10k or more.
Another technique is to use multiple threads.  Let one thread read data from a file into a buffer.  Another thread processes the data.  A possible third thread outputs the results.
A simple trick is to preallocate the length of a string to some percentage of the longest line.  Don't keep reallocating, or declaring new strings, but reusing this large one.  There is some execution penalty for strings resizing.


text:
Q: Is there a way to optimize this query? declare
  n_docid number;
  n_orgid number;
  n_docstateid number;
  n_docstateversion number;
  n_doctypeid number;
  n_count number;
begin
  for I in (select DOCID from DC_EXP_BO where INF_DATEDOCUMENT > '01.01.17' and
INF_DATEDOCUMENT < '31.12.17')
loop
begin
  select DOCID, DOCSTATEID, DOCTYPEID, DOCSTATE_VERSION into
  n_docid, n_docstateid, n_doctypeid, n_docstateversion from DOC
  where DOCID = I.DOCID;

  select ORGID into n_orgid from ORG
  where systemname = (select distinct RB_CODEGRBS from DC_EXP_BO where DOCID = n_docid);

  select count(*) into n_count from ROUTECONTEXT
  where DOCID = n_docid and ORGID = n_orgid;

  if (n_count = 0) then
  insert into ROUTECONTEXT
    (ROUTECONTEXTID, VERSION, DOCID, LOCALDOCSTATEID, OWNERID, LASTPRINTDATE, PRINTED, RECEIVED, ORGID, ARCHIVE, EXPORTSTATUS, DOCTYPEID, DOCSTATEID, DOCSTATE_VERSION, DELETED)
  values
    (sq_routeContext.NEXTVAL, 0, n_docid, n_docstateid, null, null, 0, 0, n_orgid, 0, 'NOT_EXPORTED', n_doctypeid, n_docstateid, n_docstateversion, 0);
  end if;
exception
  when no_data_found then
continue;
end;
end loop;
end;
/

We wrote datafix for production. And there is a problem.
For statement select can return about 1 million IDs. Is it possible someway to optimize this query?

A: The most effective optimization you can make is to replace the row-by-row inserts and lookups in a loop with a single set-based operation:
insert into ROUTECONTEXT
    (ROUTECONTEXTID, VERSION, DOCID, LOCALDOCSTATEID, OWNERID, LASTPRINTDATE, PRINTED, RECEIVED, ORGID, ARCHIVE, EXPORTSTATUS, DOCTYPEID, DOCSTATEID, DOCSTATE_VERSION, DELETED)
select sq_routeContext.NEXTVAL,
          0,
          DOC.DOCID,
          DOC.DOCSTATEID,
          null,
          null,
          0,
          0,
          org.ORGID,
          0,
          'NOT_EXPORTED',
          DOC.DOCSTATEID,
          DOC.DOCTYPEID,
          DOC.DOCSTATE_VERSION ,
          0
from DC_EXP_BO
    join doc
        on DC_EXP_BO.DOCID = DOC.DOCID
    join org
        on org.systemname =  DC_EXP_BO.RB_CODEGRBS
where DC_EXP_BO.INF_DATEDOCUMENT > date '2017.01.01'
and DC_EXP_BO.INF_DATEDOCUMENT < date '2017.12.31'
and not exists ( select null
                 from ROUTECONTEXT
                 where ROUTECONTEXT.DOCID = doc.docid
                 and ROUTECONTEXT.ORGID = org.orgid
               )
/

Assuming DC_EXP_BO.INF_DATEDOCUMENT is a DATE datatype, using proper date semantics may be more performative and will certainly be safer. But it's a string replace that bit of the WHERE clause with what you posted in your question.


text:
Q: Maximum possible length of string literal in C What is the maximum possible length of string literal in C? If I am not wrong, In Java and .NET, maximum possible length is 2^31 - 1.

A: There is no specified upper bound on the length of a string literal.
The standard requires all implementations to support string literals of at least 4095 characters after concatenation, but compilers are free to support arbitrary long string literals. (The requirement in C90 was 509 characters; C99 increased it to 4095.)


text:
Q: Find input elements but only those which have onclick event Some of my input elements have onclick="setSomeFunction()" which displays or hides the following few div(s).
I can find the input elements via
document.getElementsByTagName("input")
and put those in an array.
But I want to get only the "onclick" inputs into another array.
I have found that you can test for .class, (for example)
if (document.getElementById("someId").class == "block" )

but it seems that if there is no corresponding ".onclick"? Or does my code fail because some input element doesn't have an onclick event at all?
function consoleInputs() {
    var inputs = document.getElementsByTagName("input"); //finds all the input elements
    console.log(inputs); //list all the inputs
    var hasClick; // store all the inputs WITH onclick event here
    var loop = inputs.length; // max rounds in the loop
    var i;
    for (i = 0;i <= loop ;i += 1){
        if ((document.getElementById("inputs[i]").onclick) == ("set"+"*")) {
        hasClick = hasClick + inputs[i]
        }
    }
    console.log(hasClick);
}

I've tried different if statements, but no luck, really... I keep getting the error

Uncaught TypeError: Cannot read property 'onclick' of null

I haven't learned enough about jQuery yet, so please avoid.

A: JavaScript has selector feature that is pretty much similar to jQuery's one.
So you could get all inputs that have onClick attribute by
document.querySelectorAll('input[onClick]')

which will return you array of input elements that have onClick attribute defined.
Edit
CSS have startsWith selector as well, so you can get onclick attributes that starts with set with this
document.querySelectorAll('input[onClick^="set"]')


text:
Q: How would I solve this equation? $x_1^3 - x_1 = x_2^3 - x_2$ I want to find whether the function $h(x)=x^3-x$ is injective or not.
If $\forall x_1, x_2 \in \mathbb R,  f(x_1) = f(x_2) \Rightarrow x_1 = x_2$, then how do I solve this $x_1^3 - x_1 = x_2^3 - x_2$?

A: $$x_1^3 - x_1 = x_2^3 - x_2 $$
$$(x_1-x_2)(x_1^2+x_1x_2+x_2^2-1)=0$$
$$ x_1=x_2 $$ or $$x_1^2+x_1x_2+x_2^2-1=0$$
As you notice, $x_1=1$ and $x_2=-1$ satisfy the  $$x_1^2+x_1x_2+x_2^2-1=0$$

A: $h(x)=x^3-x$ is not injective because $h(1)=h(-1) =0$

A: The cubic in question is an easily factorable polynomial and we can find multiple distinct roots.
$f(x)=x^3-x=x(x^2-1)=x(x+1)(x-1)$
So, $f(1)=f(0)=f(−1)=0 $ despite $1,0,−1$  all being distinct unequal numbers in the domain. This shows that it is not injective.


text:
Q: How to handle return traffic from backend servers using nginx as UDP loadbalancer I am having Nginx server set up as a UDP load balancer. I have a couple of backend servers that are handling the UDP traffic and for each packet the backend server receives, it replies with ACK. I am able to test it and get the response back when sending the request to the backend server directly, but when sending the packet over the nginx load balancer I am not receiving the traffic.
However, what I see, the response is sent back using higher, ephemeral ports.
Is this even possible with Nginx? I am using standard community version, but in case that Plus version supports this behavior, that is also an option. How can I achieve this?
The configuration is pretty straightforward as shown below. The UDP traffic is being load balanced.
stream {
  upstream udp {
    server xx.xx.xx.xx:nnnnn;
     server xx.xx.xx.xx:nnnnn;
  }

  server {
    listen nnnnn udp;
    proxy_pass udp;
    proxy_responses 0;
  }

}

A: TCP/UDP connections from clients use well defined destination port numbers while client's side port numbers are usually ephemeral and that's perfectly fine.
It is the clients who specify source port which will be used by the server to return the data to, therefore it is the client deciding to use ephemeral or a well known port to receive the responses on.


text:
Q: Running powershell like a process to monitor for event changes I would like to have powershell manage network profiles for me depending on where I connect to. Mostly for my three work locations I jump between. I need specific IP off the wireless networks so I can access our servers.
With powershell I can run the scripts to pull SSIDs and then configure the network to set static IPs but is there a way to have powershell monitor for these changes and then set the networks?
EDIT: Can this also be ran in the background so no window needs to be left up?

A: Write a script with a never-ending loop like this:
do
{
    # check whatever you want to check and react to it...

    Start-Sleep -Seconds 30

} until ($false)

Press CRTL+C to terminate


text:
Q: Finding point on a plane closest to a point in $\mathbb{R}^n$ using least squares method? Suppose S is a 2d plane in $\mathbb{R}^3$ s.t. it is the set of all vectors in $\mathbb{R}^3$ with $ax_1+bx_2=0$ (a,b not equal to 0). Let $b=(x_1,x_2,x_3)^T$ be any vector in $\mathbb{R}^3$. How can I use least squares fitting to find the point in S that's closest to b? I understand it will be the projection, but how does least squares  come into play? Do I have to use formula $x_{min}=(A^TA)^{-1}A^Tb$?

A: Let us first consider the case when it is required to find the point on the
$$\tag{1}
P:\;ax+by+cz=d
$$
closest to the origin. The coordinates of the point $Q$ on the plane described by (1) nearest to the origin are equal to the minimal norm solution of (1):
$$\tag{2}
\left(\begin{array}{c}
x_Q\\y_Q\\z_Q
\end{array}\right)=
\left(\begin{array}{ccc}
a& b &c
\end{array}\right)^+\cdot d
$$
Now consider the case when it is required to find the point on the plane
(1)
closest to some arbitrary point $M(x_M,y_M,z_M)$. After the change of variables
$$
x'=x-x_M,\quad y'=y-y_M,\quad z'= z-z_M
$$
$M$ tranforms into the origin and (1) transforms into
$$
a(x'+x_M)+b(y'+y_M)+c(z'+z_M)=d
$$
or
$$
ax'+by'+cz'=d-ax_M-by_M-cz_M.
$$
According to (2), we obtain
$$
\left(\begin{array}{c}
x'_Q\\y'_Q\\z'_Q
\end{array}\right)=
\left(\begin{array}{ccc}
a& b &c
\end{array}\right)^+\cdot (d-ax_M-by_M-cz_M)
$$
and
$$
x_Q= x'_Q+x_M,\quad y_Q= y'_Q+y_M,\quad z_Q= z'_Q+z_M.
$$
Since $\left(\begin{array}{ccc}
a& b &c
\end{array}\right)$ has linearly independent rows,
$$
\left(\begin{array}{ccc}
a& b &c
\end{array}\right)^+=
\left(\begin{array}{ccc}
a& b &c
\end{array}\right)^T
(\left(\begin{array}{ccc}
a& b &c
\end{array}\right)\left(\begin{array}{ccc}
a& b &c
\end{array}\right)^T)^{-1}
=
\frac1{a^2+b^2+c^2}
\left(\begin{array}{c}
a\\b\\c
\end{array}\right),
$$
thus,
$$
\left(\begin{array}{c}
x_Q\\y_Q\\z_Q
\end{array}\right)=
\frac{d-ax_M-by_M-cz_M}{a^2+b^2+c^2}
\left(\begin{array}{c}
a\\b\\c
\end{array}\right)+
\left(\begin{array}{c}
x_M\\y_M\\z_M
\end{array}\right).
$$


text:
Q: How do I determine a MS Word style's styleId in a macro? A saved word document saves its style definitions in a single location (styles.xml) and references those styles in the document (document.xml) by the styleId. The styleId can be different than the style name. The style name is what is shown via the user interface.
In my macro I have the line Set myStyle = ActiveDocument.Styles("myStyle") and I can browse the properties of myStyle via the watch window, but I cannot locate styleId. Is this possible using a macro?


text:
Q: What does the output `d?????????` in `ls -l` mean? What is the situation why ls -l returns a list of subdirectories in the form below?
 d????????? ? ? ? ?       ? Subdirectory

A tree launched on that directory returns 0 directories, 0 files for example. The system seems to know the name of the subdirectory but cannot find it.
Which missing link confuses ls?
Late note. On directories, thus not on files, see also:

*

*Linux local directory permissions as question-marks for non-root

A: You have read, but not execute/search permissions to the containing directory.
Easy to reproduce with:
mkdir -p foo/bar; chmod -x foo; ls -l foo
ls: cannot access 'foo/bar': Permission denied
total 0
d????????? ? ? ? ?            ? bar

On Linux and BSD, ls is able to get that it's a directory from the d_type field of the directory entry, but not much more.
That may also happen in other situations where ls is not able to access the actual inode, but only the directory entry which points to it (as when the file or directory inode has disappeared before ls was able to stat() it -- see this, or when the it's an inaccessible mount point -- see this).


text:
Q: como conectar ao banco de dados PHPmyadm? ele dar esse erro aqui:
 Uncaught Error: Call to undefined function mysql_connect()
nao consigo fazer a conexao com o banco de dados.

A: Você esqueceu de colocar um "i"...
$con = new mysqli($Conexao, $User $Senha, $Database))
Isso Cria a Conexão Pra ti, onde:$Conexao = localhost (no teu caso)$Database = Nome da tua base de dados...
$consulta = "SUA QUERY";
$resultado = $con->query($consulta );
Isso Executa a Query pra ti.
while($row = $resultado->fetch_assoc()) {
        echo "Dado: ".$row["dado"].";";
 }
Com esse While tu pega os dados que tua consulta Retornou.


text:
Q: Splitting values in a list and making variables of them I have a list which looks like this:
list1 = ['a', '1-1-2020', '100', 'a->:100, b->:100, c->:50, d->:90']
I would like to make 4 variables of a->:100 // b->:100 // c->:50 // d->:90. Something like this:
var1 would be = a->:100 and
var2 would be = b->:100
etc.
my code right now is:
for i in list1:
   z = [x.split(',')[3] for x in list1)
   var1 = z[0]
   var2 = z[1]
   var3 = z[2]
   var4 = z[3]

A: Instead make a dictionary of key value pairs
In [7]: list1
Out[7]: ['a', '1-1-2020', '100', 'a->:100, b->:100, c->:50, d->:90']

In [8]: {i.split("->:")[0].strip():i.split("->:")[1].strip() for i in list1[-1].split(",")}
Out[8]: {'a': '100', 'b': '100', 'c': '50', 'd': '90'}

Update:
If you want to use variables only then
In [21]: list1 = ['a', '1-1-2020', '100', 'a->:100, b->:100, c->:50, d->:90']
In [23]: list1_split = list1[-1].split(",")
In [32]: var1 = list1_split[0].strip()

In [33]: var2 = list1_split[1].strip()

In [34]: var3 = list1_split[2].strip()

In [35]: var4 = list1_split[3].strip()

In [36]: var1
Out[36]: 'a->:100'

In [37]: var2
Out[37]: 'b->:100'

In [38]: var3
Out[38]: 'c->:50'

In [39]: var4
Out[39]: 'd->:90'


text:
Q: actionbutton saving text shiny I have a simple sampling code and I'd like to print the past results (in the current session) in a table below. However, I'm having difficulty figuring it out. Any ideas?
library(shiny)

ui <- shinyUI(pageWithSidebar(
  headerPanel("Randomization"),
  sidebarPanel(p("Click the button to randomize a class"),
    br(),
    actionButton("randomize", "Randomize")
  ),
  mainPanel(
    verbatimTextOutput("vText")
  )
))

server <- shinyServer(function(input, output) {
  video <- c("v1", "v2", "v3")
  output$vText <-  renderText({
    if (input$randomize == 0) {
      return()
  }  else {
    paste(input$randomize, ".", replicate(1, sample(video, 1, replace =   TRUE)))
  }
  })
})

shinyApp(ui = ui, server = server)

For example (using the code above), if I pressed the actionButton 3 times, then below the main text box would say "3. v1" and below that it would have the past sampling (eg. "1. v1, 2. v3")

A: You could store the current text in a session variable. Note the <<- which following a fortune cookie is allowed only for people who would never use it, but here it is protected against misuse by the txt <- "" in the session.
The trickiest part is the carriage-return; maybe someone finds a more elegant method to avoid the double paste.
server <- shinyServer(function(input, output) {
  video <- c("v1", "v2", "v3")
  txt <- ""
  output$vText <-  renderText({
    if (input$randomize == 0) {
      return()
    }  else {
      txt <<- paste0(paste(txt,
            input$randomize, ".", replicate(1, sample(video, 1, replace =   TRUE))),sep = "\n")
      txt
    }
  })
})


text:
Q: The USB flash drive doesn't show on device manager or disk management after using Rufus The USB flash drive doesn't show on device manager or disk management.
I was trying to create bootable drive for installing Windows using Rufus. I followed every step properly and it was going well, but suddenly it terminated itself. Now the USB flash drive is damaged. Windows detects when I insert it but after a while it disconnects itself. It doesn't show on device manager or disk management.
For a few second after inserting, E: and F: show as USB but eventually it disappears. Sometimes I get a message like "USB device not recognised". But it never works.
It's a 64GB USB flash drive and it would be very sad to lose it.


text:
Q: Prove edges of G can be colored by red and blue so that every vertex has the same number of red and blue edges adjacent to it. The problem is given as follow:

Let G be a connected graph having an even number of edges such that all the degrees are even. Prove that the edges of G can be colored by red and blue in such a way that every vertex has the same number of red and blue edges adjacent to it.

My approach is:

Since all degrees are even, then G is not a tree and contains only cycles. This also implies two cycles cannot share a common edge, otherwise one vertex has odd degree. G has even number edges indicates it has even number of cycles which share common vertices. Therefore, G can be colored by red and blue in such a way that every vertex has the same number of red and blue edges adjacent to it.

I don't know if I miss something needs to be clarify in this proof...

My new approach:

G contains a Eulerian circuit because all the degrees are even. Traversing the circuit from a vertex u and coloring the edges blue, red, blue, red....as a sequence. Because G has even number of edges, it has even number of blue and red edges; hence, the color of first edge starting from vertex u is different from the last edge goes back to starting point. Therefore, QED

A: Since it was quite some time ago that I gave a hint in the comments above and the OP has not returned to say that he has figured it out and no other answer has been posted, I will give an extended hint (practically a full solution):

 Depending on strictness and definitions, one might also want to concern yourself with the case that $G$ has exactly one vertex (or even exactly zero vertices).  There is exactly one graph with exactly one vertex, and it has zero edges and can trivially be seen to satisfy all of the conditions.  It is common to see graph theory problems specify that we are interested only in proving results for graphs with at least $n\geq 2$ vertices since the one-vertex graph is so dull and uninteresting.

As $G$ is connected and has every vertex with even degree, there exists an Eulerian circuit (a walk which possibly reuses vertices that starts and ends in the same place which uses every edge exactly once).
Take any such Eulerian circuit with starting and ending point $x$ (where $x$ is a vertex of $G$) and alternately color the edges along the circuit red and blue.
It remains to show the following two things:

*

*Why does every vertex other than $x$ have as many red edges as blue edges?

*Why does $x$ have as many red edges as blue edges?

 Why is the last edge in the circuit a different color than the first edge in the circuit?  (Have we used all of the hypotheses yet in our proof?)

$~$

 Would $x$ have had as many red edges as blue edges if the number of edges in the graph total was in fact odd?  What are the colors of the first and last edge in the circuit in that case?


text:
Q: Is google-cloud-storage pricing dependent on the bucket location? i have dedicated server in canada and would like to use google-cloud-storage as offsite backup.
so i will be pushing/uploading data from canada to google-cloud-storage located in us-east1.
will there be any pricing difference if i create a bucket in us-central1 instead of us-east1 ?
or the pricing is same for any location ?
i ask this becuase i have been using amazon services and their pricing totally depends on the location of amazon server/services .

A: No. Google Cloud Storage charges the same amount for storing data regardless of the location it's stored, and there is no charge for uploading data into Google Cloud Storage.
There are some pricing differences for serving data based on location, but for serving data from Google to outside of Google, us-centra1 and us-east1 are effectively equivalent in this regard.
The pricing details for Google Cloud Storage are published here: https://cloud.google.com/storage/pricing


text:
Q: SAML Assertion not getting Signed from Azure to Oracle ERP Cloud We are exploring to use Azure B2C as IdP for Oracle Cloud ERP. We are using custom Policies to setup this communication channel using this.
For the XXXExtensions.xml file , below are the cryptographic keys that are being used.
      <CryptographicKeys>
        <Key Id="SamlMessageSigning" StorageReferenceId="B2C_1A_SamlIdpCert"/>
        <Key Id="SamlAssertionSigning" StorageReferenceId="B2C_1A_SamlIdpCert"/>
      </CryptographicKeys>

and in the SignINSAML.xml file which extends XXXExtensions.xml and has relying Party information as below
<RelyingParty>
    <DefaultUserJourney ReferenceId="SignUpOrSignInBasedOnGroupWithFgtPswd" />
    <TechnicalProfile Id="PolicyProfile">
      <DisplayName>PolicyProfile</DisplayName>
      <Protocol Name="SAML2" />
    <Metadata>
     <Item Key="WantsSignedAssertions">true</Item>
     <Item Key="WantsSignedRequests">true</Item>
     <Item Key="XmlSignatureAlgorithm">Sha256</Item>
    </Metadata>
      <OutputClaims>
        <OutputClaim ClaimTypeReferenceId="displayName" />
        <OutputClaim ClaimTypeReferenceId="givenName" />
        <OutputClaim ClaimTypeReferenceId="surname" />
        <OutputClaim ClaimTypeReferenceId="signInNames.emailAddress" PartnerClaimType="samlSubId" />
        <OutputClaim ClaimTypeReferenceId="email" DefaultValue="" />
        <OutputClaim ClaimTypeReferenceId="identityProvider" DefaultValue="" />
        <OutputClaim ClaimTypeReferenceId="objectId" />
      </OutputClaims>
      <SubjectNamingInfo ClaimType="samlSubId" ExcludeAsClaim="true" />
    </TechnicalProfile>
  </RelyingParty>

Now coming to the Oracle Part , Oracle expects the assertion to be signed and encrypted. I've not put in the encryption part yet as on the signing part itself we are getting error from Oracle that "Assertion is not signed" .
While testing SSO , we get through the User journeys as expected and SAML response gets posted to Oracle. However , the Signature tag in Assertion is missing as shown below.
  <samlp:Status>
        <samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
    </samlp:Status>
    <saml:Assertion ID="_ffdbgrd2-7c94-4df2-8ee2f-95547e685f70" IssueInstant="2022-09-15T13:43:58.0923925Z" Version="2.0">
        <saml:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">https://myB2CTenant.onmicrosoft.com/SamlApp1</saml:Issuer>
        <saml:Subject>
            <saml:NameID>XXX@gmail.com</saml:NameID>
            <saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
                <saml:SubjectConfirmationData InResponseTo="id-meq56ZIj2Dvmg1Tyrf5V3X9F9rnHIBs315lt0YX4" NotOnOrAfter="2022-09-15T13:48:58.0923925Z" Recipient="https://oracle-tenant.fa.ocs.oraclecloud.com/oam/server/fed/sp/sso"/>
            </saml:SubjectConfirmation>
        </saml:Subject>

As you can see , there are no Signature tag in Assertion which is why oracle is giving the above error. Is there any other part of setup that needs to be considered in Azure ?


text:
Q: How do I execute the code and see the results using twitter util-eval I am trying to compile and execute a "hello world" program using twitter util-eval library. But not able to get results printed.
My intention is not just to compile and execute hello world example, large scala files with dependencies should compile and run.
import com.twitter.util.Eval
object ScalaCompiler3 {
     def main(args: Array[String]): Unit = {
         val eval = new Eval()
         val fileContents = "class Test {\n\n println (\"Hello World!\")\n\n}"
         val compile = eval.apply[Unit](fileContents)
         println(compile)
     }
}

How do I execute the code and see the results? am not able to get proper API documentation for util-eval. Using util-eval_2.11-6.43.0.jar taken from maven

A: As erip mentioned in the comments, the source string you're compiling makes a class, Test, but since you never instantiate the class it never runs the code within.
If you replace:
val fileContents = "class Test {\n\n println (\"Hello World!\")\n\n}"

with:
val fileContents = "println(\"Hello World!\")\n\n}"

That will execute the code you're looking to execute. Best of luck with your project!


text:
Q: Hibernate: java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to database.entity.Dokumenty I have little problem :( When I try do this:
List<Dokumenty> dokumentyList =
        (List<Dokumenty>)dokumentyDAO.getDokumentyByTrasy(((Trasy)routeComboBox.getSelectedItem()).getId());

for (Dokumenty dokumenty : dokumentyList){}

then I get error in for loop:

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to
  database.entity.Dokumenty

My DokumentyDAO looks like this:
public class DokumentyDAO{

    private static volatile DokumentyDAO instance = null;

    private DokumentyDAO() {}

    public static DokumentyDAO getInstance() {
        if (instance == null) {
            synchronized (DokumentyDAO.class) {
                if (instance == null) {
                    instance = new DokumentyDAO();
                }
            }
        }
        return instance;
    }

    public List<Dokumenty> getDokumentyByTrasy(long idTrasy){

        Session session = HibernateUtil.getSessionFactory().openSession();

        Query query = session.createQuery(
                "FROM Dokumenty dokumenty "
                + "left join dokumenty.dostawy dostawy "
                + "left join dostawy.trasy trasy "
                + "left join dostawy.klienci klienci "
                + "where trasy.id = :idTrasy "
                + "and dostawy.aktywny = 'A' ");
               // + "order by klienci.nrKlienta, klienci.nazwaKlienta, dokumenty.nrDok ");

        query.setParameter("idTrasy", idTrasy);

        return query.list();
    }

}

And Dokumenty :
public class Dokumenty  implements java.io.Serializable{

     private long id;
     private Uzytkownicy uzytkownicy;
     private Dostawy dostawy;
     private String nrDok;
     private String typDok;
     private long JWydane;
     private long eurWydane;
     private long h1Wydane;
     private long e2Wydane;
     private long JZwrot;
     private long eurZwrot;
     private long h1Zwrot;
     private long e2Zwrot;
     private Date dataMod;
     private char aktywny;

    public Dokumenty() {
    }

    public Dokumenty(long id, Uzytkownicy uzytkownicy, Dostawy dostawy, String nrDok, String typDok, long JWydane, long eurWydane, long h1Wydane, long e2Wydane, long JZwrot, long eurZwrot, long h1Zwrot, long e2Zwrot, char aktywny) {
        this.id = id;
        this.uzytkownicy = uzytkownicy;
        this.dostawy = dostawy;
        this.nrDok = nrDok;
        this.typDok = typDok;
        this.JWydane = JWydane;
        this.eurWydane = eurWydane;
        this.h1Wydane = h1Wydane;
        this.e2Wydane = e2Wydane;
        this.JZwrot = JZwrot;
        this.eurZwrot = eurZwrot;
        this.h1Zwrot = h1Zwrot;
        this.e2Zwrot = e2Zwrot;
        this.aktywny = aktywny;
    }
    public Dokumenty(long id, Uzytkownicy uzytkownicy, Dostawy dostawy, String nrDok, String typDok, long JWydane, long eurWydane, long h1Wydane, long e2Wydane, long JZwrot, long eurZwrot, long h1Zwrot, long e2Zwrot, Date dataMod, char aktywny) {
       this.id = id;
       this.uzytkownicy = uzytkownicy;
       this.dostawy = dostawy;
       this.nrDok = nrDok;
       this.typDok = typDok;
       this.JWydane = JWydane;
       this.eurWydane = eurWydane;
       this.h1Wydane = h1Wydane;
       this.e2Wydane = e2Wydane;
       this.JZwrot = JZwrot;
       this.eurZwrot = eurZwrot;
       this.h1Zwrot = h1Zwrot;
       this.e2Zwrot = e2Zwrot;
       this.dataMod = dataMod;
       this.aktywny = aktywny;
    }

    public long getId() {
        return this.id;
    }

    public void setId(long id) {
        this.id = id;
    }
    public Uzytkownicy getUzytkownicy() {
        return this.uzytkownicy;
    }

    public void setUzytkownicy(Uzytkownicy uzytkownicy) {
        this.uzytkownicy = uzytkownicy;
    }
    public Dostawy getDostawy() {
        return this.dostawy;
    }

    public void setDostawy(Dostawy dostawy) {
        this.dostawy = dostawy;
    }
    public String getNrDok() {
        return this.nrDok;
    }

    public void setNrDok(String nrDok) {
        this.nrDok = nrDok;
    }
    public String getTypDok() {
        return this.typDok;
    }

    public void setTypDok(String typDok) {
        this.typDok = typDok;
    }
    public long getJWydane() {
        return this.JWydane;
    }

    public void setJWydane(long JWydane) {
        this.JWydane = JWydane;
    }
    public long getEurWydane() {
        return this.eurWydane;
    }

    public void setEurWydane(long eurWydane) {
        this.eurWydane = eurWydane;
    }
    public long getH1Wydane() {
        return this.h1Wydane;
    }

    public void setH1Wydane(long h1Wydane) {
        this.h1Wydane = h1Wydane;
    }
    public long getE2Wydane() {
        return this.e2Wydane;
    }

    public void setE2Wydane(long e2Wydane) {
        this.e2Wydane = e2Wydane;
    }
    public long getJZwrot() {
        return this.JZwrot;
    }

    public void setJZwrot(long JZwrot) {
        this.JZwrot = JZwrot;
    }
    public long getEurZwrot() {
        return this.eurZwrot;
    }

    public void setEurZwrot(long eurZwrot) {
        this.eurZwrot = eurZwrot;
    }
    public long getH1Zwrot() {
        return this.h1Zwrot;
    }

    public void setH1Zwrot(long h1Zwrot) {
        this.h1Zwrot = h1Zwrot;
    }
    public long getE2Zwrot() {
        return this.e2Zwrot;
    }

    public void setE2Zwrot(long e2Zwrot) {
        this.e2Zwrot = e2Zwrot;
    }
    public Date getDataMod() {
        return this.dataMod;
    }

    public void setDataMod(Date dataMod) {
        this.dataMod = dataMod;
    }
    public char getAktywny() {
        return this.aktywny;
    }

    public void setAktywny(char aktywny) {
        this.aktywny = aktywny;
    }

}

Aby idea whats is wrong? I ran out of ideas :/

A: Your are using joins so Hibernate is not returning a list of Dokumenty but instead a list of arrays (think a list of rows), the first entry of each array would be the Dokumenty, the second one the dostawy and so on

A: The issue s that you have not told Hibernate how to map the Dokumenty Java class to the database tables. Thus you get back  untyped Object s in the query
You need a XML mapping or Java annotations (Hibernate docs) to map the Java objects to the database tables including mapping fields to the primary key and associations of objects (these associations tell Hibernate how the tables are related and let Hibernate generate the code to join tables rather than you doing the joins manually as you have done.


text:
Q: Probability Question 2 real numbers are chosen at random in the unit interval find the probabilities Two real numbers are chosen at random in the unit interval.
Find the probability that their sum exceeds 1
= 1/2
Find the probability that one is more than twice the other.
= 1/4
Find the probability that their sum exceeds one and one is more than twice the other.
= 1/8
Find the probability that their sum exceeds one or one is more than twice the other.
= 1/32
Are these the right answers?

A: This answer assumes the two real numbers are independently chosen at random from a uniform distribution.
Call the two random numbers $x$ and $y$. Based on the initial assumption, the joint probability density is equal at all points in the unit square, so all probabilities can be interpreted as the total area enclosed by various regions divided by the area of the unit square ($=1$).
The diagram below represents the various conditions (total greater than one, one number more than twice another, etc.) and the regions induced by them. The shaded area represents the third probability.

Part A
Your answer is correct. It's the area of $\triangle AGD$.
Part B
If one number is twice another, then the point $(x,y)$ lies either on the line $y=2x$ or on the line $x=2y$. Thus,
$$\begin{align}
\mathbf{Pr}[\text{one number} \ge \text{twice other}] &= Area(\triangle OED)+Area(\triangle OBA) \\
&= \frac{1}{2}\cdot1\cdot\frac{1}{2} + \frac{1}{2}\cdot1\cdot\frac{1}{2} = \frac{1}{2}
\end{align}$$
Part C
The two numbers must satisfy both conditions, so the total area is that of the shaded regions in the diagram. Thus,
$$\begin{align}
\mathbf{Pr}[\text{one number} \ge \text{twice other} \text{ AND }x+y\ge1] &= Area(\triangle FED)+Area(\triangle CBA) \\
&= \frac{1}{2}\cdot\frac{1}{3}\cdot\frac{1}{2} + \frac{1}{2}\cdot\frac{1}{3}\cdot\frac{1}{2} = \frac{1}{6}
\end{align}$$
Part D
Now the two numbers only satisfy one or more of the conditions in A and B (in part C they needed to satisfy both). So, you should expect a probability that is greater than the one for part C.
You should be able to work out which region the point $(x,y)$ cannot be in (a triangle none of whose sides are parallel to the axes), and subtract its area from $1$ to get the required probability.


text:
Q: Como verificar se uma data é dia útil? Como verificar se uma data é dia útil ? Abaixo está meu código de exemplo:
void main() {

   var now = new DateTime.now();
   var berlinWallFell = new DateTime.utc(1989, 11, 9);
   var moonLanding = DateTime.parse("1969-07-20 20:18:04Z");  // 8:18pm

   print(now);

   // Colocar aqui uma verificação se é dia útil.

}

A: No geral, dias úteis são aqueles que não são sábado, domingo ou feriado.
Tomando isso por base um modo de se fazer seria:
void main() {
  // Data que está validando se é dia util.
  var data = DateTime(2020,02,25);

  var diaUtil = !ehSabadoOuDomingo(data) && !ehFeriado(data);

  print(diaUtil);
}

bool ehSabadoOuDomingo(DateTime data){
  var diaDaSemana = data.weekday;

  // O "weekday" de uma instancia de data retorna um
  // inteiro referente ao dia da semana. Sábado e domingo
  // são representados respectivamente por 6 e 7.
  return diaDaSemana == 6 || diaDaSemana == 7;
}

bool ehFeriado(DateTime data){

  // Informar a lista de dias no ano que são considerados
  // feriados nacionais. Vai ser necessário pesquisar quais são
  // e ir inserindo aqui nesta lista. Coloquei apenas alguns exemplos.
  var diasDeFeriado = [
    DateTime(2020,01,01),
    DateTime(2020,02,25),
    DateTime(2020,04,21),
  ];

  return diasDeFeriado.contains(data);
}

Este é apenas um exemplo. Pode ser copiado e colado no DartPad para testar.


text:
Q: How to add File image in qr_flutter to generate QR code with that embedded image? I want to do similar think like this ( How to generate QR CODE with logo in flutter ) but instead of using asset image, I want to user pick an image with image_picker package and then store that image in file and use it in QR code as an embedded image. Please anyone help me out.
Thank You

A: Well The Thing you want to achieve has some boilerplate code involved so I would break it down into 2 brief steps:
Step 1: Pick Image as a File using image picker plugin that is, simply store image as File you can achieve it using:
File image = await ImagePicker.pickImage(
    source: ImageSource.camera, imageQuality: 50
  );

You can follow this to perfectly get image
Step 2: Now if you see the type of embedded image is actually an ImageProvider so you can use FileImage() and do:
QrImage(
              data: 'This QR code has an embedded image as well',
              version: QrVersions.auto,
              size: 320,
              gapless: false,
              //You can use image here, Note this image should be of type File
              embeddedImage: FileImage(image),
              embeddedImageStyle: QrEmbeddedImageStyle(
                size: Size(80, 80),
              ),
            ),

Hope this is what you wanted to achieve.

A: You just have to make a variable of the image that you will use for QR :
var image = Image.asset('assets/ur_image.png',);

and then add it in here :
QrImage(
   embeddedImage: image.image,
   data: 'hello',
    version: QrVersions.auto,
    size: 100,
  ),


text:
Q: Changing x-axis in grafana graph to custom time series sent as label of gauge I am working on a project in java using spring boot that requires working on prometheus and grafana.
To send data to prometheus end-point, I am using "gauge" having name "metrices_value" with label "dateAndTime". This gauge contains value of type "Double".
Some examples of "gauge" at api end-point -

*

*metrices_value{dateAndTime="2022-05-13 12:03:48"} 1.0

*metrices_value{dateAndTime="2022-05-13 15:35:18"} 3.0

When I am using "Time series" visualization for "metrices_value" in grafana, then x-axis is showing the time at which prometheus is pulling the data from api end-point.
But, on x-axis, I want to show the custom time that I am sending through gauge as a label i.e, "dateAndTime".
Please let me know how to solve this issue.


text:
Q: Installing a Failover Cluster Instance on a Cluster already in use for Instances hosting Always On I have been asked to install a SQL Server FCI on a 3 nodes cluster already hosting 4 different instances with Always On Availability Groups.
While I am building the lab on my machine, I am wondering if they are any drawback I should be aware of before doing it?

A: I'll answer my own question.
No, there seem to be no drawback sharing same cluster between FCI instances and instances with AlwaysOn Availability groups.
Thanks for you editions, help and support.


text:
Q: Connecting to a laser with Python's socket interface I'm trying to connect over ethernet to a piece of hardware (a laser) which listens for connections on a certain port.  The laser's documentation on this is very minimal; the entirety of it is as follows:

Ethernet TCP/IP Interface:
The IP address of the laser is shown on the front panel. Touching the screen where
the address is shown displays the network setup menu where you can change the
network settings.
The laser listens for connections on port 10001. The command must be sent as a
single string in a single packet. The individual commands are described in "Interface
Commands" on page 3-2.

The commands alluded to are a list of few-character text strings, such as "ABN", which turns the laser on.  I would like to talk to the laser using Python's socket interface.  I've tried to follow the pattern of this tutorial, but to no avail.  Here's an example of what I tried:
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(("192.168.1.223",10001))
s.sendall(b"ABN")

This does nothing.   However, I can talk to the laser using Putty and a raw connection to the same IP and port as above.  This opens a terminal where I can type commands such as "ABN" (which works, turning the laser on) and read the laser's replies.
Question:  What is a Putty "raw" connection doing, and how can I replicate it with Python?

Edit: The laser is an IPG YLR-100-1064-LP-WC.

A: A commenter suggested I add "\r\n" to the end of the text string I send to the laser.  This worked--I can now communicate with the laser.


text:
Q: UIProgressView update fail with UINotification I try to solve this problem for several days now I have to ask you...
I've got a View (and a ViewController) with a UITableview. There is a TableViewController for that table which is generated in the ViewController. The TableViewController calls a DataSyncManager sharedInstant object (which is obviously in a separate class) which starts to sync data with the server.
I do it this way (first the refresh method):
-(void) refresh{
    [serverQueueProgressView setProgress:0.0];
    [syncingLabel setAlpha:0.5];
    [serverQueueProgressView setAlpha:1];
    [self performSelector:@selector(reloadTableViewDataSource) withObject:nil afterDelay:1.0];
}

Then the method reloadTableViewDataSource (of TableViewController) is called:
- (void)reloadTableViewDataSource
{
    [dataSyncManager getEntriesFromServer];
}

dataSyncManager is my sharedInstance.
In the getEntriesFromServer method of dataSyncManager I do the loop with different sync items and call everytime
[[NSNotificationCenter defaultCenter]
     postNotificationName:@"ServerQueueProgress"
     object:progress];

with the proper progress as NSNumber (that part works well). The message is now sent and catched by my ViewController (it works, I checked with a breakpoint, it also gets the right progress-NSNumber and converts it to float):
- (void)serverQueueProgress:(NSNotification *)notification {
    if(![NSThread isMainThread])
    {
        [self performSelectorOnMainThread:_cmd withObject:notification waitUntilDone:NO];
        return;
    }

    [queueProgressView setProgress:[[notification object] floatValue]];
}

This is one solution which I found here on stackoverflow. But the if is always skipped because obviously I'm on main thread.
Unfortunately the UIProgressview doesn't get updated, it just hangs around, but I connected it well in Interface Builder (I checked that by setting the progress in another method of ViewController.
I also tried to catch the Notification with my TableViewController and put in some other solutions, but no chance, the UIProgressView doesn't get updated live. Only after the sync is done.
Here is the mentioned code in TableViewController which also gets executed without errors (I also stepped it to make sure every line gehts executed well):
This is the method called when received a the notification:
- (void)serverQueueProgress:(NSNotification *)notification {
    [self performSelectorOnMainThread:@selector(updateProgress:) withObject:[notification object] waitUntilDone:NO];

    [serverQueueProgressView setProgress:[[notification object] floatValue]];
}

Which also calls updateProgress: of the same class:
- (void)updateProgress:(NSNumber *)newProgressValue {
    [serverQueueProgressView setProgress:[newProgressValue floatValue]];
}

No chance. I tried many ways and implemented some in parallel as you see, but the ProgressView won't get updated live. Only at the end of syncing. What am I doing wrong??
EDIT: Here is my getEntriesFromServer and some other stuff in DataSyncManager:
- (void)getEntriesFromServer
{
    [[NSNotificationCenter defaultCenter]
     postNotificationName:@"SynchingStarted"
     object:nil];

    [self completeServerQueue];
    ...
}

and completeServerQueue is the function which sends messages to my ViewController with the proper progress float value (it's only a dummy for loop, which gets executed properly... I've checked it):
- (void)completeServerQueue {
    NSNumber *progress = [[NSNumber alloc] init];
    for (int i=0; i<15; i++) {
        progress = [[NSNumber alloc] initWithFloat:(100/15*i) ];

        [[NSNotificationCenter defaultCenter]
         postNotificationName:@"ServerQueueProgress"
         object:progress];

        sleep(1);
    }
}

A: my guess is the problem isn't the code you've shown here, but other code in getEntriesFromServer. Are you using NSURLConnection? Something like:
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

then you will get callbacks asynchronously that you can use to update your progress view.

A: also, when you're having trouble, break the problem down a bit. Instead of:
[serverQueueProgressView setProgress:[[notification object] floatValue]];

do this;
float prog = [notification object] floatValue];
[serverQueueProgressView setProgress:prog];

then debugging would give a clue that this isn't working.


text:
Q: Hover text on dropdown - jQuery Is it possible to hover text in dropdown, when the text length is more than width of the dropdown?
 <Select style="width:10px">
  <option>Less than 10 px </option>
  <option> More than 10 px </option>
 </Select>

I want the display text "more than 10 Px" on hover, from my above example.

A: Simply add a "title" tag:
<option title="More than 10 px"> More than 10 px </option>


text:
Q: Pack bitfields into 32 bit register using x86 assembly I am working with RNS in assembler x86 AT&T at the moment. I have to put 5 remainders into one register, %eax. Piece of code:
.macro division number
        mov $0, %ecx

    loop_getremainders:
        mov $0, %edx
        mov number, %eax
        mov dividers(,%ecx,4), %ebx
        div %ebx
        mov %edx, remainders(,%ecx,4)
        inc %ecx
        cmp $5, %ecx
        jne loop_getremainders
        int $0x80
.endm

.section .data
     number: .long 158
     remainders: .long 0,0,0,0,0
     dividers: .long 7,15,31,127,8192

.section .text
    .global _start
    _start:
        division number
        mov $1, %eax
        mov $0, %ebx
        int $0x80

I know that to write 7 in binary i need 3 bits, 15 - 4 bits etc. I want to write every remainder of them in one %eax, "linked" in this order:
111 1111 11111 1111111 1111111111111 (32bits,spaces for better presentation) How to change it from decimal to binary and put these 5 numbers into 1 32bit register?

A: Looks like the shrd instruction would be helpful in this case.
To do it in a loop, you probably need to make a table that contains the shift amounts, since you seem to be needing 3, 4, 5, 7, 13. Something like this:
    xor %eax, %eax                          # accumulator
    movl $5, %edx                           # counter
loop_shift:
    movb shifts(%edx), %cl                  # the shift amount
    movl remainders(, %edx, 4), %ebx        # next remainder
    shrd %cl, %ebx, %eax                    # shift in the bits
    subl $1, %edx
    jnc loop_shift
.data
    shifts: .byte 3, 4, 5, 7, 13


text:
Q: How do you escape a . (full stop) or / so it doesn't change URL's meaning? I have a Web API 2.0 service which defines a particular route:
/api/someEntityGroup/{entityName}

I'm calling this enpoint using Angular $resource service.
The problem is when user wants to provide an entity name with characters that have a specific meaning in URL:

*

*404 Not found - . (full stop), /, +

*400 Bad request - ?, :, &, %, *, <, >
And these are the ones I've encountered. There may be others that may be problematic as well and I'm not even aware of them (yet).
If I use window.escape() function these still don't work, but I mainly get 404 back (the only exception being * which still returns 400 Bad request).
My code
Angular resource creation:
.factory("entityResource", ["$resource", function() {
    return $resource("/api/entities/:id", null, {
        search: {
            method: "GET",
            url: "/api/entities/:name",
            isArray: true
        }
    });
}]);

How I call it in my code:
entityResource.search({ query: scope.name }, function(data) {
    ...
});

My Api controller action:
[RoutePrefix("/api/entities")]
public class EntitiesController: ApiController
{
    [Route("{searchQuery}")]
    public IEnumerable<Interest> Get(string searchQuery)
    {
        return this.interestService.Search(searchQuery);
    }

    ...
}

A: I can shed some light on your 404 Not found issue when using ., /, + characters.
The issue isn't with Angular but rather with Web API and the way it resolves routes. Urls that Web API interprets as being managed resources (e.g. static content, pages etc.) it will try to resolve independently.
Set the following in your web.config to disable this behavior and force WebAPI to run all requests through your modules:
<system.webServer>
   <modules runAllManagedModulesForAllRequests="true" />
</system.webServer>

Just a warning - If your Web API is hosted together with something like MVC or a static website, the above is not recommended as it will force all managed resources (pages, MVC routes, content[css,js,images]) through your API modules and there will be a performance impact. However, if all the API is doing is serving resource routes I would recommend enabling the above.


text:
Q: How to map hidden states to their corresponding categories after decoding in hmmlearn (Hidden Markov Model)? I would like to predict hidden states using Hidden Markov Model (decoding problem). The data is categorical. The hidden states include Hungry, Rest, Exercise and Movie. The observation set include Food, Home, Outdoor & Recreation and Arts & Entertainment. My program is first to train the HMM based on the observation sequence (Baum-Welch algorithm). And then I do the decoding (Viterbi algorithm) to predict the hidden state sequence.
My question is that how I can map the result (non-negative integers) to their corresponding categories like Hungry or Rest. Because of the non-deterministic property of the training algorithm , the parameters are different for every training of the same data. Therefore the hidden state sequence is different every time if I do the map like the following code.
The code is as follows:
from __future__ import division
import numpy as np
from hmmlearn import hmm

states = ["Hungry", "Rest", "Exercise", "Movie"]
n_states = len(states)

observations = ["Food", "Home", "Outdoor & Recreation", "Arts & Entertainment"]

# The number in this sequence is the index of observation
category_sequence = [1, 0, 1, 2, 1, 3, 1]
Location = np.array([category_sequence]).T
model = hmm.MultinomialHMM(n_components=n_states).fit(Location)

logprob, result = model.decode(Location)
print "Category:", ", ".join(map(lambda x: observations[x], Location.T[0]))
print "Intent:", ", ".join(map(lambda x: states[x], result))

A: This is known as label-switching problem. The log-likelihood of the model sums over all of the states and is therefore independent of the particular ordering.
As far as I know, there is no general recipe for dealing with it. Among the things you might try are:

*

*Find a partially labelled dataset, run predict on it and use the predictions to map the state indices to the corresponding labels.

*Come up with heuristics for possible parameter values in each state. This could be tricky to do for Multinomials, but is possible if you model e.g. accelerometer data.

Update: An ad-hoc version of guessing state to label mapping from labelled data.
def guess_labels(hmm, X, labels):
    result = [None] * hmm.n_components
    for label, y_t in zip(labels, hmm.predict(X)):
        assigned = result[y_t]
        if assigned is not None:
            # XXX clearly for any real data there might be
            #     (and there will be) conflicts. Here we just blindly
            #     hope the ``assert`` never fires.
            assert assigned == label
        else:
            result[y_t] = label
    return result


text:
Q: Format decimal value I had this, which works as far as it goes:
worksheet.write(row, column, value)

Then I wanted to make the value display in red, so I did this:
red = workbook.add_format({'color': 'red'})
worksheet.write_rich_string(row,column, str(value), red)

This works, but the problem is that value is a decimal, and it has to be cast to a string for it to work with write_rich_string()
Is there a way to format the value and have it remain a decimal?
In Excel, I would to Conditional Formatting on the entire column.

A: write_number() also accepts a cell format:
red = workbook.add_format({'color': 'red'})
worksheet.write_number(1, 1, 10.24, red)


text:
Q: Pausing Large number of AJAX calls, multiple data sets I am trying to create a web utility that take several large datasets and makes ajax calls to process them and index them into a table for searching. Basically, the data will be broken down into 5 data sets, but for the sake of simplicity, I will reduce the sample data to two sets (basically multi-dimensional arrays).

*

*Inventory Items

*Systems

Let's just say, again for the sake of simplicity, that each dataset has 3 items in it.
JAVASCRIPT PART 1
var inventory = [
  {"id": "1","title": "0002\/840","type": "inventory"},
  {"id": "2","title": "0002\/841","type": "inventory"},
  {"id": "3","title": "0002\/842","type": "inventory"}
];
var systems = [
  {"id": "28","title": "System 1","type": "system"},
  {"id": "54","title": "System 2","type": "system"},
  {"id": "76","title": "System 3","type": "system"}
];

The way it should work is that the code hits the first inventory item, makes an ajax call based on it, waits for the response , and then moves to the second item. It does this over and over again until it reaches the last item, at which point, it moves on to the next data set (systems), and then works its way through those.
Now, I have this working just fine. You can see a fully functional example at the CodePen link below. This version of the JS code has a small delay built in to better demonstrate the issue.
WORKING EXAMPLE

It has now been requested that I add a pause/unpause function. I'm at a little bit of a loss as to how to stop this without freezing the browser, and more so, how to resume where I left off at the correct place in the correct dataset.
I tried adding a paused boolean variable that is toggled on and off, and then a loop in my function that would just wait for the paused variable to be false. This obviously tied up the browser window.
Can anyone shed some light on how I might be able to go about doing pausing and unpausing without freaking out the browser?
Thanks in advance.

REMAINING JAVASCRIPT PART 2
var paused = false;

function PauseIndexing() {
  //paused = true;
}

function BeginIndexing() {
  updateItems(inventory, 'inventory', 0, function () {
    //This gets called when inventory is done
    updateItems(systems, 'systems', 0, function () {
      alert("Inventory and Systems Imported");
    });
  });
}

function updateItems(items, type, x, callback) {

  /* This causes complete freeze as expected*/
  //while (paused) {}

  var item_count = items.length;

  $.post('', {
    item: items[x],
    type: type
  }, function () {
    x++;
    if (x == item_count) {
      callback();
    } else {
      updateItems(items, type, x, callback);
    }
  });

}

A: Here you have to maintain the state of progress using pausedAt = x, then continue from where you left. Below is the changed snippets & the working example link.
function BeginIndexing(x) {
   updateItems(inventory, 'inventory', x, function () {
     pausedAt = x = 0;
    updateItems(systems, 'systems', x, function () {
      alert("Inventory and Systems Imported");
    });
  });
}
function ContinueIndexing(){
  paused = false;
  console.log(pausedAt)
  BeginIndexing(pausedAt);
}
function updateItems(items, type, x, callback) {
if(paused){
  pausedAt = x;
  return
}

Working Pen
or else check the result below

var paused = false;
var pausedAt = 0;
var inventory = [
  {"id": "1","title": "0002\/840","type": "inventory"},
  {"id": "2","title": "0002\/841","type": "inventory"},
  {"id": "3","title": "0002\/842","type": "inventory"},
  {"id": "2","title": "0002\/841","type": "inventory"},
  {"id": "3","title": "0002\/842","type": "inventory"},
  {"id": "2","title": "0002\/841","type": "inventory"},
  {"id": "3","title": "0002\/842","type": "inventory"},
  {"id": "2","title": "0002\/841","type": "inventory"},
  {"id": "3","title": "0002\/842","type": "inventory"}
];
var systems = [
  {"id": "28","title": "System 1","type": "system"},
  {"id": "54","title": "System 2","type": "system"},
  {"id": "76","title": "System 3","type": "system"}
];

function PauseIndexing() {
  paused = true;
  //pausedAt = x;
}

function BeginIndexing(x) {
   updateItems(inventory, 'inventory', x, function () {
     pausedAt = x = 0;
    updateItems(systems, 'systems', x, function () {
      alert("Inventory and Systems Imported");
    });
  });
}
function ContinueIndexing(){
  paused = false;
  console.log(pausedAt)
  BeginIndexing(pausedAt);
}
function updateItems(items, type, x, callback) {
if(paused){
  pausedAt = x;
  return
}
  /* This causes complete freeze as expected*/
  /*
  while (paused) {

  }
 */

  var item_count = items.length;

  setTimeout(function(){
    $.post('http://www.geonames.org/countries/', {
      item: items[x],
      type: type
    }, function () {
      x++;
      console.log(x);
      if (x == item_count) {
        updateBar(item_count, 100, type);
        updateText("Done!", type);
        callback();
      } else {
        var perc = Math.round((x / item_count) * 100);
        updateBar(x, perc, type);
        updateItems(items, type, x, callback);
      }

    });
  }, 500);
}

function updateText(val, type) {
  $('small.' + type + '_name').html(val);
}

function updateBar(x, perc, type) {
  $('.progress.' + type + ' .progress-bar')
    .attr('aria-valuenow', perc)
    .css('width', perc + '%')
    .html(x + ' (' + perc + '%)');
}

function isFunction(functionToCheck) {
  var getType = {};
  return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
}
.progress{background:#333;}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>

Start!

Pause

Continue

9 Inventory Items

            Pending....

                0 (0.00%)

3 Systems

            Pending....

                0 (0.00%)

A: This should do it:
function PauseIndexing(pause) {
  paused = pause;
}

function updateItems(items, type, x, callback) {

  if (paused) {
    return setTimeout(updateItems, 100, items, type, x, callback);
  }

  var item_count = items.length;

  $.post('', {
    item: items[x],
    type: type
  }, function () {
    x++;
    if (x == item_count) {
      callback();
    } else {
      updateItems(items, type, x, callback);
    }
  });

}

Check it out: http://codepen.io/anon/pen/bEbvbJ


text:
Q: Combine multiple lists resulting from a loop I am parsing over elements from multiple html.
I am getting the answer in form of multiple lists.
Here is part of my code:
for index, row in df.iterrows():
    r = driver.get(row['post'])
    soup = BeautifulSoup(r, "html.parser")
    records = []
    comm = [r.nextSibling for r in soup.find_all('div',
    class_=re.compile('_2b05'))]
    data = [''.join(i.stripped_strings) for i in comm if i]
    records.append(data)
    print(records)

    >>>> [['a', 'b', 'c', 'd']] [['x', 'y']]

This formula runs under for loop.
For some reason it doesn't append all lists into the records list. I need to combine all the lists of 'records' into one DataFrame - OR - if possible- all the elements of both lists into a DataFrame.
I tried:
items = list(set(chain.from_iterable(records)))

and
df = pd.DataFrame({'comment': list(item for item in
itertools.chain.from_iterable(records))})

Both results are printed as two separate DataFrames, when I want them to be combined into only one DataFrame that I can transfer to csv.

A: It can be achieved using a function from_records
For example:
>>> records= [['a','b','c'],['x','y']]
>>> df = pd.DataFrame.from_records(records)
>>> df
   0  1     2
0  a  b     c
1  x  y  None

Updated code
>>> records= [[['a','b','c']],[['x','y']]]
>>> for i,item in enumerate(records):
...     if i==0:
...             df1 = pd.DataFrame.from_records(item)
...     else:
...             df1 = df1.append(item, ignore_index=True)
...
>>> df1
   0  1    2
0  a  b    c
1  x  y  NaN

Let me know if this helps!


text:
Q: Smartface publish process stops with AdMob I'm using AdMob in my project. I checked the use AdMob checkbox. When I tried publish my project, publish process stops at "installation packages are creating" step.
I tried it with emulator, the result was same.
What should I do for making it work?

A: The reason for this error used NodeJS component to pack the iOS Publish. In windows environments the NodeJS installer fails to create the npm folder under app Data.
https://github.com/npm/npm/wiki/Troubleshooting#error-enoent-stat-cusersuserappdataroamingnpm-on-windows-7
Basically follow those steps for fix:

*

*Press Win + R keys to open run dialog

*Type %appdata% and press run

*Create a folder named "npm"


text:
Q: Ruby on Rails: can't update with gem update Running gem -v gives:
1.8.11

Running gem update:
Updating installed gems
Updating actionmailer
Fetching: activesupport-3.1.3.gem (100%)
Fetching: activemodel-3.1.3.gem (100%)
Fetching: sprockets-2.0.3.gem (100%)
Fetching: actionpack-3.1.3.gem (100%)
Fetching: actionmailer-3.1.3.gem (100%)
Successfully installed activesupport-3.1.3
Successfully installed activemodel-3.1.3
Successfully installed sprockets-2.0.3
Successfully installed actionpack-3.1.3
Successfully installed actionmailer-3.1.3
Updating activerecord
Fetching: activerecord-3.1.3.gem (100%)
Successfully installed activerecord-3.1.3
Updating activeresource
Fetching: activeresource-3.1.3.gem (100%)
Successfully installed activeresource-3.1.3
Updating childprocess
Fetching: childprocess-0.2.3.gem (100%)
Successfully installed childprocess-0.2.3
Updating columnize
Fetching: columnize-0.3.5.gem (100%)
Successfully installed columnize-0.3.5
Updating cucumber
Fetching: gherkin-2.6.8.gem (100%)
Building native extensions.  This could take a while...
Fetching: cucumber-1.1.3.gem (100%)

(::) (::) (::) (::) (::) (::) (::) (::) (::) (::) (::) (::) (::) (::) (::)

Thank you for installing cucumber-1.1.3.
Please be sure to read http://wiki.github.com/cucumber/cucumber/upgrading
for important information about this release. Happy cuking!

(::) (::) (::) (::) (::) (::) (::) (::) (::) (::) (::) (::) (::) (::) (::)

Successfully installed gherkin-2.6.8
Successfully installed cucumber-1.1.3
Updating devise
Fetching: devise-1.5.2.gem (100%)
Successfully installed devise-1.5.2
Updating factory_girl
Fetching: factory_girl-2.3.2.gem (100%)
Successfully installed factory_girl-2.3.2
Updating jquery-rails
Fetching: jquery-rails-1.0.19.gem (100%)
Successfully installed jquery-rails-1.0.19
Updating json
Fetching: json-1.6.3.gem (100%)
Building native extensions.  This could take a while...
Successfully installed json-1.6.3
Updating json_pure
Fetching: json_pure-1.6.3.gem (100%)
Successfully installed json_pure-1.6.3
Updating multi_json
Fetching: multi_json-1.0.4.gem (100%)
Successfully installed multi_json-1.0.4
Updating passenger
Fetching: passenger-3.0.11.gem (100%)
Successfully installed passenger-3.0.11
Updating rails
Fetching: railties-3.1.3.gem (100%)
Fetching: rails-3.1.3.gem (100%)
Successfully installed railties-3.1.3
Successfully installed rails-3.1.3
Updating rubyzip
Fetching: rubyzip-0.9.5.gem (100%)
Successfully installed rubyzip-0.9.5
Updating sass
Fetching: sass-3.1.11.gem (100%)
Successfully installed sass-3.1.11
Updating selenium-webdriver
Fetching: selenium-webdriver-2.14.0.gem (100%)
Successfully installed selenium-webdriver-2.14.0
Gems updated: activesupport, activemodel, sprockets, actionpack, actionmailer, activerecord, activeresource, childprocess, columnize, gherkin, cucumber, devise, factory_girl, jquery-rails, json, json_pure, multi_json, passenger, railties, rails, rubyzip, sass, selenium-webdriver
Installing ri documentation for activesupport-3.1.3...
Installing ri documentation for activemodel-3.1.3...
Installing ri documentation for sprockets-2.0.3...
Installing ri documentation for actionpack-3.1.3...
Installing ri documentation for actionmailer-3.1.3...
Installing ri documentation for activerecord-3.1.3...
Installing ri documentation for activeresource-3.1.3...
Installing ri documentation for childprocess-0.2.3...
Installing ri documentation for columnize-0.3.5...
Installing ri documentation for gherkin-2.6.8...
Installing ri documentation for cucumber-1.1.3...
Installing ri documentation for devise-1.5.2...
Installing ri documentation for factory_girl-2.3.2...
Installing ri documentation for jquery-rails-1.0.19...
Installing ri documentation for json-1.6.3...
Installing ri documentation for json_pure-1.6.3...
Installing ri documentation for multi_json-1.0.4...
Installing ri documentation for passenger-3.0.11...
Installing ri documentation for railties-3.1.3...
Installing ri documentation for rails-3.1.3...
Installing ri documentation for rubyzip-0.9.5...
Installing ri documentation for sass-3.1.11...
Installing ri documentation for selenium-webdriver-2.14.0...
ERROR:  While executing gem ... (ArgumentError)
    marshal data too short

What should i do ?

A: Did you mean:
gem update --system

Or you wanted to update specific gem:
gem update rails

A: Try making a backup copy of your ~/.gems folder, then purging it, and running the command again.
Ref: http://keyj.wordpress.com/2009/03/20/error-with-rubygems-marshal-data-too-short/


text:
Q: Required/Mandatory fields in Wordpress Admin looking for a solution for Wordpress Admin where fields such as Title, Excerpt, Category are required before being able to publish. Warning message or alert displaying what is missing because it is required. I have found old solutions that work for classic editor, but they do not work with the block editor, and ones that do work for block editor do not work for classic editor . Have not found anything out there that works for both. Looking to plug in some code in the functions.php file. Any help would be appreciated for a jr dev here in Wordpress.
This works for classic editor only
    /** ADD Validation for title */
    function force_post_title_init()
{
    wp_enqueue_script('jquery');
}
function force_post_title()
{
    echo "\n";
}
add_action('admin_init', 'force_post_title_init');
add_action('edit_form_advanced', 'force_post_title');
add_action('edit_page_form', 'force_post_title');

This works on classic editor but on block editor just refreshes back to the same post in draft.
/**
 * Checks for empty post title, if empty sets the post status to draft
 *
 * @param $data
 * @param $postarr
 *
 * @return array
 */
function abc_check_post_title( $data, $postarr ) {
    if ( is_array( $data ) && 'publish' == $data['post_status'] && empty( $data['post_title'] ) ) {
        $data['post_status'] = 'draft';
        update_option( 'abc_post_error', 'empty_title' );
    }

    return $data;
}
add_filter( 'wp_insert_post_data', 'abc_check_post_title', 10, 2 );

/**
 * If the post title was empty, do not show post published message
 */
add_filter( 'post_updated_messages', 'abc_remove_all_messages' );

function abc_remove_all_messages( $messages ) {
    if ( get_option( 'abc_post_error' ) ) {
        return array();
    } else {
        return $messages;
    }
}

/**
 * Show admin notice for empty post title
 */
add_action( 'admin_notices', 'abc_show_error' );
function abc_show_error() {
    $screen = get_current_screen();
    if ( $screen->id != 'post' ) {
        return;
    }
    if ( ! get_option( 'abc_post_error' ) ) {
        return;
    }
    echo '

' . esc_html__( "You need to enter a Post Title in order to publish it.", "wse" ) . '

';
    delete_option( 'abc_post_error' );
}


text:
Q: C/Python Socket Performance? my question simply relates to the difference in performance between a socket in C and in Python. Since my Python build is CPython, I assume it's similar, but I'm curious if someone actually has "real" benchmarks, or at least an opinion that's evidence based.
My logics is as such:

*

*C socket much faster? then write a C
extension.

*not/barely a difference?
keep writing in Python and figure out
how to obtain packet level control
(scapy? dpkt?)

I'm sure someone will want to know for either context or curiosity. I plan to build a sort of proxy for myself (not for internet browsing, anonymity, etc) and will bind the application I want to use with it to a specific port. Then, all packets on said port will be queued, address header modified, and then sent, etc, etc.
Thanks in advance.

A: In general, sockets in Python perform just fine. For example, the reference implementation of the BitTorrent tracker server is written in Python.
When doing networking operations, the speed of the network is usually the limiting factor. That is, any possible tiny difference in speed between C and Python's socket code is completely overshadowed by the fact that you're doing networking of some kind.
However, your description of what you want to do indicates that you want to inspect and modify individual IP packets. This is beyond the capabilities of Python's standard networking libraries, and is in any case a very OS-dependent operation. Rather than asking "which is faster?" you will need to first ask "is this possible?"

A: i would think C would be faster, but python would be a lot easier to manage and use.
the difference would be so small, you wouldn't need it unless you were trying to send masses amount of data (something stupid like 1 million gb/second lol)
joe


text:
Q: My printer is not printing cause of a error message. 16.04 Cannon MX330 I really have had nothing but trouble printing on this setup.  The thing is right now I can print if I start a live version of the OS.  This is the second install I've done on this computer.  The first installation also had printing issues.  The problem is also that I don't really know my way around on Ubuntu.
The printing error message is - There is a missing print filter for printer 'MX330-series'.


text:
Q: url_to_postid returns 0 I'm trying to send the post id to js file to create a localStorage for each post by using their id's as  the key. The problem is when i try this code in php it returns 0, as a result all my pages have the same localStorage. What should i do?
public function button_js(){
    $url     = wp_get_referer();
    $post_id = url_to_postid( $url );

    wp_localize_script( 'likeButton', 'ajax_object',
        array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => $post_id) )
}
add_action('wp_enqueue_scripts',[ $this ,'button_js']);

A: when you are at the post URL, you don't need to work with referer (which is not reliable moreover) but with $GLOBALS["post"] because you are in the PHP code which generate the page
then you can have the post ID with that :
$post_id = $GLOBALS["post"]->ID;


text:
Q: Attribute Assingment/Analysis on Leaflet Map At the moment I'm struggling to combine attributes of my markers and polygons on my leaflet map.
In my map I have bavarian government districts with the name of the districs as attribute. And I have 70 markers to show the location of some mountains in these districts, these points are from an csv table I made. What I wanted to do now is that each point should be assigned the attribute of the corresponding district within it lies. So that the marker popup also shows the name of the district. I don't know whats the easiest way to do this? So I thought about using the turf points within polygon function but I'm not sure how to start.Map with Marker and Polygons.
The second thing I wanted to do, is to highlight the highest mountain. The mountain with the largest number in the second column. Mountain height.
My table is looking like this: (mountain name;mountain height;area;landscape;lat;long)
Bergname;Berghoehe;Landkreis;Gebirge_Landschaft;Latitude;Longitude
Hesselberg;689;Ansbach;Wörnitztal_Fränkische Alb;49.06861780;10.52610990
Dürrenberg;656; Weißenburg-Gunzenhausen;Hahnenkamm; 49.01647480; 10.76511290
...
I hope someone can help me out here, would be much appreciated :)

<!DOCTYPE html>

      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
      <title>Leaflet Map"</title>

      <link rel="stylesheet" href="https://unpkg.com/leaflet@1.4.0/dist/leaflet.css" />

A: You can use turf.booleanContains(district.toGeoJSON(16), marker.toGeoJSON(16)) to check if the marker is in the district and then add the popup.
Add your markers to a FeatureGroup to get it later for the loop
var fg = L.featureGroup().addTo(Karte);

//Papaparse Erweiterung für CSV Tabelle
$.get('./turf.csv', function(csvString) {

            // Use PapaParse to convert string to array of objects
            var data = Papa.parse(csvString, {
                header: true,
                dynamicTyping: true
            }).data;

            // For each row in data, create a marker and add it to the map
            // For each row, columns `Latitude`, `Longitude`, and `Title` are required
            for (var i in data) {
                var row = data[i]
                var marker = L.marker([row.Latitude, row.Longitude], {
                    opacity: 1
                });
                marker._mountainData = row;
                marker.addTo(fg)
            });

And then loop through all districts:
fg.eachLayer((layer) => {
        var districts = geo.getLayers();
        districts.forEach((district) => {
          if (turf.booleanContains(district.toGeoJSON(16), layer.toGeoJSON(16))) {
            var row = layer._mountainData;
            layer.bindPopup(district.feature.properties.YOUR_DISTRICT_NAME_PROPERTY + ";" + row.Bergname + '; ' + row.Berghoehe + '; ' + row.Landkreis + '; ' + row.Gebirge_Landschaft + '; ' + row.Latitude + '; ' + row.Longitude)
            return;
          }
        })

Demo: https://jsfiddle.net/falkedesign/kgwcrLpq/


text:
Q: How to set global variables for exported class methods in node.js I have multiple different files broken out like so:
index.js
utils.js
ClassA/
  index.js
  base.js

utils contains a number of utility functions used everywhere. ClassA/index.js contains the constructor for ClassA as well as requires base.js, then exports ClassA. Base.js exports prototype methods for ClassA.  Here is basically what they look like:
//ClassA/index.js
function ClassA () {
  //constructor stuff
}
ClassA.prototype.constructor = ClassA;
require('./base')(ClassA);
module.exports = ClassA;

//ClassA/base.js
module.exports = ClassA => {
ClassA.prototype.aMethod = function () {
  log('hello');
}

//utils.js
module.exports = {
  log : function (logText) {
    //dostuff
  }
}

So my problem is that I cannot access the log function from within methods in ClassA/base.js.  If I set const log = require('../utils').log at the top of the file, it doesn't work.  It also doesn't work if I place that same line of code within the exports but outside of the method definitions, however it does work if I place it within the method itself (as expected, but this would mean replicating every require statement in any method in which it's needed). Is there any way around using this messy and repetitive route?

A: It was an issue with cyclic dependencies. I changed 'log' to be a method of ClassA and this resolved the issue.  Thanks to Francois P. for pointing me in the right direction.


text:
Q: Calling a method from a click event in a router-link inside a component (Vue.js) I'm trying to achieve with Vue.js a transition between two components. Each component have a button (<router-link>) in order to go to the other component.
Each time, the transition change to 'slide-right' when A->B to 'slide-left' when B->A.
Unfortunately, it goes only in one way, the one I've set as default ('slide-right' in data).
The method is not called from the click event on the <router-link> because I've tried to add test button to call the function and it worked.
How can I call a method from a click event on <router-link> in a component ?
Here is my HTML file:

    <transition :name="direction">
        <router-view />
    </transition>


text:
Q: Should I use k8s statefulsets directly or mysql-operator to deploy master-slave mysql cluster? So I want to deploy a master-slaves MySQL cluster in k8s. I found 2 ways that seem popular:

*

*The first one is to use statefulsets directly from k8s official document: https://kubernetes.io/docs/tutorials/stateful-application/basic-stateful-set/

*The second one is to use operator, i.e. https://github.com/oracle/mysql-operator
Which way is most commonly used?
Also, in statefulsets, if my MySQL master dies, will k8s automatically promote the slave to be the master?
Lastly, when my logic backend app performs an operation (CRUD) to MySQL cluster, how does k8s know which pod to route to, i.e. write operation can only be sent to master while read is sent to all?

A: Users can deploy and maintain a set of highly available MySQL services in k8s based on StatefulSets, the process is relatively complex. This process requires users to familiarize themselves with various k8s resource objects, learn many MySQL operation details and maintain a set of complex management scripts. Kubernetes Operators are designed to reduce the threshold for deploying complex applications on k8s.
Operator hides the orchestration details of complex applications and greatly reduces the threshold to use them in k8s. If you need to deploy other complex applications, we recommend that you use the Operator.
Speaking about master election while using StatefulSet.
Electing potential slave to be a master is not an automatic process - you have to configure this manually using Xtrabackup - here is more information - setting_up_replication.
Take a look: cloning-existing-data, starting-replication, mysql-statefulset-operator.
Useful tools:  vitess for better MySQL networking management and percona-xtradb-cluster that provides superior performance, scalability and instrumentation.


text:
Q: Can we refer different value to ipfs hash? I am experimenting with ipfs these days. And one thing I wanna clarify is that in ipfs everything is referenced using a hash ( content hash). But hashes are very long, hard to remember. Is there any way I can refer the content I am retrieving by its name (I know, it can't be refer by its name) or something else.
And how do I refer the content when using ipfs in my application (JS or Go)? Do I store the hash of every content that is put into the application or there is some other mechanisms to achieve that?

A: Look at DNSLinks, IPNS.
You can use the DNSLinks to have some more readable names for what you put on IPFS.
For what you parse FROM IPFS, you can index that in your app, with a map between hashes and nice names.
You can look at the Github for Javascript.


text:
Q: How does associate in Laravel/Eloquent work? I'm trying to get associate to work.
Relationship on User model:
public function group()
{
    return $this->belongsTo('User');
}

So I do:
$user = new User();
//save user fields
....
$user->save();

$group = Group::find(1);
$user->group()->associate($group);

A new user is inserted, but in the FK of group_id on the user table I am getting null.

A: Associate needs to be before save.
$user = new User();
//save user fields
....
$group = Group::find(1);
$user->group()->associate($group);
$user->save();

A: Well, let say you want to associate a comment with a blog post, because the comment can only be for a specific post we will use associate.
In our Post model we will have this:
public function comments(){
    return $this->hasMany('App\Comment');
}

in our comment model we have this:
         public function post(){
       return $this->belongsTo('App\Post');
    }

In our CommentsController we will have this:
  $comment = new Comment;
  $post=Post::find($post_id);
  $comment->post()->associate($post);
  $comment->save();

Pay attention that you save it only after you associate it with the post.

A: you need to save user after associating
$user->save();

full code
$user = User::create([
   'field1' => $request->field1,
....
]);

$group = Group::find(1);
$user->group()->associate($group);
$user->save();