text:
Q: how to handle runtime permission auth in android M I want to know the best practise to ask user for permission check and the code to run if user declines that particular permission access.

A: This example set states for CONTACTS permission
private static final int PERMISSIONS_REQUEST_READ_CONTACTS = 1;
private static String[] PERMISSIONS_CONTACT = {Manifest.permission.READ_CONTACTS}

if (checkSelfPermission(PERMISSIONS_CONTACT)) {
   Log.i(TAG,
           "Contact permissions have already been granted. Displaying contact details.");
} else {
   Log.i(TAG, "Contact permissions has NOT been granted. Requesting permission.");
   requestPermissions(PERMISSIONS_CONTACT, PERMISSIONS_REQUEST_READ_CONTACTS);
}

…

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
   switch (requestCode) {
       case PERMISSIONS_REQUEST_READ_CONTACTS: {
           if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
               // permission was granted, yay! do the
               // calendar task you need to do.
               Log.d(TAG, "permission granted");
           } else {
               // permission denied, boo! Disable the
               // functionality that depends on this permission.
               Log.d(TAG, "permission denied");
           }
           return;
       }
   }
}

You can follow the link
http://www.applicoinc.com/blog/android-m-permissions-review/

A: Dexter is an Android library that simplifies the process of requesting permissions at runtime.
Usage of Dexter

A: Some hint:

*

*Always check for permission before calling operations on Google Play Services because they require permission but the management is in charge of you;

*Don't ask for granted permissions: when you call request permissions with multiple permissions the system doesn't care if one or two permissions are already granted, the dialog is shown for all! So keep track only of permissions really needed. It could be strange for user grant already granted permissions;

*Always check if it's needed to show a reason to the user using the method shouldShowRequestPermissionRationale() it could be not really obvious why you are asking a permission;

*Send a notification to the user if you are checking for permission in background, in a service for example and allow it to grant the permission going with a tap in the app details system activity directly.

A: Take a look here - there's a flowchart that explains the whole process quite well.
Bottom line is that according to Android's documentation, you should always check and ask for permission if you don't have it (Android will automatically return DENIED in the callback if the user said to never ask again) and you should display a short message if the user has already declined you once in the past but hasn't marked the never ask again option.

A: For Example Camera Run time permission :
This Code you have to put in to camera button click
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            givePerMissons();

        } else {
            openCamera();
        }
     public void givePerMissons() {
        if ((Utils.checkPermission(MainActivity.this, Manifest.permission.CAMERA)) {
            openCamera();
} else {
            Utils.givePermisson(MainActivity.this, Manifest.permission.CAMERA, Utils.PERMISSOIN);

            if (!Utils.permissionsList.isEmpty()) {
                requestPermissions(Utils.permissionsList.toArray(new String[Utils.permissionsList.size()]), Utils.PERMISSOIN_CODE);
            }
        }
    }
@Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Utils.PERMISSOIN_CODE: {
                if ((Utils.checkPermission(MainActivity.this, Manifest.permission.CAMERA)) {
                    openCamera();
                } else {
                    Toast.makeText(getApplicationContext(),"Write Your message",Toast.LENGTH_LONG).show();
                }
            }
        }
    }

This Code you have to put in your utils Class:
public static final List<String> permissionsList = new ArrayList<String>();

public static void givePermisson(Context context, String permisson, String permissonType) {

        int per = context.checkSelfPermission(permisson);
        if (per != PackageManager.PERMISSION_GRANTED) {
            permissionsList.add(permisson);

        } else if (per != PackageManager.PERMISSION_DENIED) {
        }
    }

public static boolean checkPermission(Context context, String permission) {

        try {
            PackageManager pm = context.getPackageManager();

            if (pm.checkPermission(permission, context.getPackageName()) == PackageManager.PERMISSION_GRANTED) {
                return true;
            } } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

A: if ( ActivityCompat.shouldShowRequestPermissionRationale (this, Manifest.permission.CAMERA) || ActivityCompat.shouldShowRequestPermissionRationale (this,
                        Manifest.permission.RECORD_AUDIO) ) {
Toast.makeText (this,
                R.string.permissions_needed,
                Toast.LENGTH_LONG).show ();

    } else {

        ActivityCompat.requestPermissions (
                this,
                new String[]{Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO},
                CAMERA_MIC_PERMISSION_REQUEST_CODE);

    }


text:
Q: Waiting for several Requests to finish At my pageload I have to retrieve three JSONs (for loadJSON() please see PS)
$(document).ready(function() {
    loadJSON("JSON1.json",function(json){
        json1 = json:
        console.log("JSON1 loaded");
    });
    loadJSON("JSON2.json",function(json){
        json2 = json:
        console.log("JSON2 loaded");
    });
    loadJSON("JSON3.json",function(json){
        json3 = json:
        console.log("JSON3 loaded");
    });

    //doing stuff after all three have loaded (PSEUDO:)
    waitTillFinished(doingStuff(json1, json2, json3));
});

Then I need to run a function combining the results of the three JSONs (the doingStuff function) therefore it has to wait till all three have finished.
I though of a function that does the active waiting and fire a callback, e.g. doingStuff.
How can I do that?
I am in search for some kind of semaphore pattern here. How is this typically done in JS?
Already Tried:
A jQuery construction:
$( document ).ready(function() {
  $.when(
    loadJSON("JSON1.json",function(json){
        json1 = json;
        console.log("JSON1 loaded");
    }),
    loadJSON("JSON2.json",function(json){
        json2 = json;
        console.log("JSON2 loaded");
    }),
    loadJSON("JSON3.json",function(json){
        json3 = json;
        console.log("JSON3 loaded");
    })
  ).then(
    doingStuff(json1, json2, json3);
  );
});

This does not wait for the calls to finish. That is totally understood, since loadJSON function have finished, only the callbacks haven't fired yet.
A use of "status-semaphores"
var status1 = $.getJSON("JSON1.json"[..]); //shortend [..]
var status2 = $.getJSON("JSON2.json"[..]); //shortend [..]
var status3 = $.getJSON("JSON3.json"[..]); //shortend [..]

status1.complete(function(){
  status2.complete(function(){
    status3.complete(doingStuff(json1, json2, json3)
  }
}

This does work, but it does not scale. For two calls it would have considered this solution, three already has a smell. But I expect to get even more Calls when the app is growing.
PS:
The loadJSON() function is a helper function for loading and logging the request stuff:
function loadJSON(requestURL, callback){
  var xobj = new XMLHttpRequest();
  xobj.overrideMimeType("application/json");
  xobj.open('GET', requestURL, true);
  xobj.onreadystatechange = function(){
      if (xobj.readyState == 4){
          if(xobj.status == 200){
              callback(JSON.parse(xobj.responseText));
          } else {
              console.error(xobj.statusText);
          }
      }
  }
  xobj.onerror = function(e){
      console.error(xobj.statusText);
  }
  xobj.send();
}

A: Your code using $.when would work if loadJSON returned a promise/deferred, like jQuery's getJSON does. So:
$( document ).ready(function() {
  $.when(
    $.getJSON("JSON1.json"),
    $.getJSON("JSON2.json"),
    $.getJSON("JSON3.json")
  ).then(function(data1, data2, data3) { // Note naming, once they're parsed (which
    doingStuff(data1, data2, data3);     // getJSON does), they're not JSON anymore
  });
});

or actually, we don't need the wrapper function if doingStuff takes the three parameters in the order we pass the calls to $.when:
$( document ).ready(function() {
  $.when(
    $.getJSON("JSON1.json"),
    $.getJSON("JSON2.json"),
    $.getJSON("JSON3.json")
  ).then(doingStuff);
});

Note I've used then instead of done. Unusually, the then callback will be called with discrete arguments for each result (whereas a normal then calls its callback with just one argument). Note that if you use done instead, you'll get three discrete arguments, but they're arrays where each array has the data, textStatus, and jqXHR object that resulted from the $.getJSON call.
Or we could use Promise.all (on any major modern browser):
$( document ).ready(function() {
  Promise.all([
    $.getJSON("JSON1.json"),
    $.getJSON("JSON2.json"),
    $.getJSON("JSON3.json")
  ]).then(function(results) {
    doingStuff(results[0], results[1], results[2]);
  });
});

Note we pass the promises as an array, and get back an array. In ES2015+ we could use destructuring in the parameter list of the then callback:
$( document ).ready(function() {
  Promise.all([
    $.getJSON("JSON1.json"),
    $.getJSON("JSON2.json"),
    $.getJSON("JSON3.json")
  ]).then(([data1, data2, data3]) => {
    doingStuff(data1, data2, data3);
  });
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Complicated string aggregation in BigQuery I am trying to complete a user journey path in BigQuery, but struggling with some complexities in the problem.
The original data looks like this for one user:

Each flattened quote represents a separate conversion (quote = conversion), so I need 3 separate user journeys.
Journey 1: "Paid Search - Pure Brand > Paid Search - Brand Hyrbid > Conversion"
Journey 2: "Paid Search - Pure Brand > Paid Search - Brand Hyrbid > Conversion" (the user gets 2 quotes in one session, so journey 1 and journey 2 represent 2 separate conversions with the same path)
Journey 3: "Paid Search - Pure Brand > Paid Search - Brand Hyrbid > Organic Search > Conversion"
It would also be fine if journey 3 ends up looking like:
Journey 3: "Paid Search - Pure Brand > Paid Search - Brand Hyrbid > Conversion > Organic Search > Conversion"
At the moment the closest I've got is:

The issue here is that although 2 of the conversions happen in visit number 2, they are listed here sequentially. This means that when you split by each conversion I end up with:

The fourth row isn't so much of an issue as it could be dropped, but I need row 2 and 3 to incorporate the previous visits.
Here is the code I'm working with:
with table_a as (SELECT date, fullVisitorId, visitnumber, visitid, clientId, istruedirect, number_of_pages_in_session, flattened_quote, CASE WHEN flattened_quote IS NOT NULL THEN REPLACE(channel, channel, CONCAT(channel, " > Conversion abcdef10")) ELSE channel END as channel
FROM `source_table`
ORDER BY fullVisitorId, date, visitnumber),

table_b as (SELECT
  fullVisitorId,
  #flattened_quote,
  STRING_AGG(channel, ' > ') AS channelgrouping_path,
  ARRAY_AGG (
    STRUCT(flattened_quote)
  ) AS Values
FROM table_a
GROUP BY fullVisitorId)

select SPLIT(channelgrouping_path, "abcdef10") as split_into_each_journey
from table_b
where fullvisitorid = "1004040222968994500" # this is just using one visitor ID for validation, will be removed

If anyone has any tips on how to GROUP BY differently or something to achieve this I would really appreciate it.


text:
Q: Possible to check if a Listview (jQuery Mobile) contains a Collapsible? I have a random number of collapsibles inside a listview element.
What I would like to know is that if there is a way of "knowing" if the listview has any collapsibles in it before proceeding to the next page.
This Fiddle pretty much represents what I have so far.
I would like some sort of client side validation that would check if the "user" has added "medicines" to the list (in a collapsible form) before proceeding.
I've tried playing around with this bit of code:
$("#medListLi").find('div[data-role=collapsible]')....;

But can't seem to know how to properly approach a solution.
Maybe I'm looking at solving this in the wrong way, any suggestions will be very much appreciated.

A: I think you want a JavaScript condition that will evaluate to true if your #medListLi contains a collapsible element:
if ( $("#medListLi").find('div[data-role=collapsible]').length ) {
    //yup, their is something collapsible in here
}

This code does the following:

*

*select the element with an id of #medListLi within that element,

*find any div that has a data-role attribute set to "collapsible"

*jQuery returns any such elements in an array; the .length
JavaScript property will return a 0 or some positive number, which gets evaluated to false (for 0) or true (for any other positive number).

A: The selector that you provided just needed .length attached to it like this:
$("#medListLi").find('div[data-role=collapsible]').length

When using a jQuery selector adding .length to the end always returns the number of matched elements.
So the above will return 0 if there are no collapsibles 1 if there is one etc...
To use this in an if statment all you need to do is:
if ($("#medListLi").find('div[data-role=collapsible]').length > 0) {
    // submit
} else {
    // error (no collapsibles)
}


text:
Q: How to set only vertical padding? Sometimes I would like to set top and bottom padding explicitly on an element but leave left and right padding to the unchanged browser default. I know I can write
.myElement { padding-top: 20px; }
.myElement { padding-bottom: 20px; }

but this way I need to repeat both the selector .myElement and the length value twice - or rather copy and paste the whole line and switch left with right.
I was hoping to find something less redundant, so I tried to use padding with two values and replace the second length with inherit. That's not good CSS, I know, it was an attempt, but it doesn't work either (sets horizontal padding to 0):
.myElement { padding: 20px inherit; }

See here: http://jsfiddle.net/185ty3yp/
Any advice how to do it better?

A: These days you can do it like this:
.myElement { padding-block: 20px; }

Browser support

A: you can use padding-block property to set vertical padding and padding-inline to set horizontal padding.
padding-block: 20px; /*vertical padding */
padding-inline: 20px; /*horizontal padding*/

The same goes for margin, use margin-block to set vertical margin and margin-inline to set horizontal margin.
margin-inline: auto; can be used to center a div.

A: If I understand what you want : you're looking for a way to only assign vertical padding with padding property (and keep original horizontal padding if it's set).
So you already have the answer :
.myElement { padding-top: 20px; padding-bottom: 20px;  }

You can't do that only with padding property, or you'll need to set horizontal value.
Or, you can consider using CSS preprocessors (such as Sass or Less), it will surely helps you to achieve this.

A: #ul1, #ul2{
  padding:20px 0; /* top and bottom 20px, left and right 0 */
}

http://www.w3schools.com/css/css_padding.asp
you can only set padding to either a fixed length or a percent, no other values I'm afraid

A: I understand one of the reasons for finding vertical padding might be wanting just to change one place in future modification.  If so, we can try:
.element{
    --title-vertical-padding: 20px;
    padding-top: var(--title-vertical-padding);
    padding-bottom: var(--title-vertical-padding);
}

A: try this code  DEMO
#ul1, #ul2 {
    background-color: cyan;
    padding-top: 20px;
    padding-bottom: 20px;
}

#ul2 {
    background-color: yellow;
}

A: You can try like this
padding: 20px 50px 75px 100px;

//top padding is 20px
//right padding is 50px
//bottom padding is 75px
//left padding is 100px

In your case you can apply like this if it is common for any ul
ul
{
  padding-top: 20px;
  padding-bottom: 20px;
}

any specific places you can override this css.
check Demo


text:
Q: Using Redis transaction vs redlock to solve the Lost Update Problem I'm working with a Redis cluster having 2+ nodes. I'm trying to figure out which tool best fits for handling concurrency - transaction or locking. Transactions are well documented, but I didn't find a good best-practice-example on redlock. I also wonder why two tools exist and what's the use case for each.
For simplicity, let's assume I want to do a concurrent increment and there is no INCR command in Redis.
Option 1. Using Transactions
If I understand correctly, NodeJS pseudocode would look like this:
 transactIncrement = async (key) => {
      await redisClient.watch(key);
      let value = redisClient.get(key);
      value = value + 1;
      const multi = await redisClient.multi();
      try {
        await redisClient.set(key, value, multi);
        await redisClient.exec(multi);
      } catch (e) {
        // most probably error thrown because transaction failed
        // TODO: think if it's a good idea to restart in every case, introducing a potential infinite loop
        // whatever, restart
        await transactIncrement(key);
      }
    }

Bad things I can see above are:

*

*try-catch block

*possibility to use transactions with multiple keys is limited on redis cluster

Option 2. Redlock
Is it true that trying to lock a resource that's already locked would not cause a failure immediately? So  that redlock tries N times before erroring?
If true then here's my pseudocode:
redlockIncrement = async (key) => {
  await redlock.lock(key, 1);
  // below this line it's guaranteed that other "threads" are put on hold
  // and cannot access the key, right?
  let value = await redisClient.get(key);
  value = value + 1;
  await redisClient.set(key, value);
  await redlock.unlock(key);
}

Summary
If I got things right then redlock is definitely a more powerful technique. Please correct me if I'm wrong in the above assumptions. It would also be really great if someone provides an example of code solving similar problem because I couldn't find one.

A: Redlock is useful when you have a distributed set of components that you want to coordinate to create an atomic operation.
You wouldn't use it for operations that affect a single Redis node. That's because Redis already has much simpler and more reliable means of ensuring atomicity for commands that use its single-threaded server: transactions or scripting. (You didn't mention Lua scripting, but that's the most powerful way to create custom atomic commands).
Since INCR operates on a single key, and therefore on a single node, the best way to implement that would be with a simple Lua script.
Now, if you want to use a sequence of commands that spans multiple nodes neither transactions nor scripting will work. In that case you could use Redlock or a similar distributed lock. However, you would generally try to avoid that in your Redis design. Specifically, you would use hash tags to force certain keys to reside on the same node:

Hash tags are a way to ensure that multiple keys are allocated in the same hash slot. This is used in order to implement multi-key operations in Redis Cluster.


text:
Q: Infinite tensor products Let $A$ be a commutative ring and $M_i, i \in I$ be a infinite family of $A$-modules. Define their tensor product $\bigotimes_{i \in I} M_i$ to be a representing object of the functor of multilinear maps defined on $\prod_{i \in I} M_i$ (this exists by the usual construction). Thus there is a universal multilinear map $\otimes : \prod_{i \in I} M_i \to \bigotimes_{i \in I} M_i$. Some years ago, I wanted to examine this infinite tensor product, but in the literature I could not find anything going beyond some natural isomorphisms (e.g. associativity) or the submodule consisting of tensors which become eventually constant a specific element of $\prod_{i \in I} M_i$ which yields a colimit of finite tensor products (denoted $U_x$ below). In general, it seems to be quite hard to describe $\bigotimes_{i \in I} M_i$. For example, for a field $K$, $K \otimes_K \otimes_K ...$ has dimension $|K^*|^{\aleph_0}$ (see below) and you cannot write down a basis, which might be scary when you see it the first time. The point is that multilinear relations cannot be applied infinitely many times at once: For example in $K \otimes_K \otimes_K ...$, we have $x_1 \otimes x_2 \otimes ... = y_1 \otimes y_2 \otimes ...$ if and only if $x_i = y_i$ for almost all $i$ and for the rest we have $\prod_i x_i = \prod_i y_i$.
Before posing my question, I provide some results.
1.1. Assume that $M_i$ are torsionfree $A$-modules (meaning $am=0 \Rightarrow a=0 \vee m=0$). In this case, we may decompose $\bigotimes_{i \in I} M_i$ as follows: Define $X = \prod_{i \in I} M_i \setminus \{0\}$ and let $x \sim y \Leftrightarrow \{i : x_i \neq y_i\}$ finite. Then $\sim$ is an equivalence relation on $X$. Let $R$ be a set of representatives (this makes this description ugly!). Then there is a canonical map
$H : \text{Mult}(\prod_{i \in I} M_i,-) \to \prod_{x \in R} \lim_{E \subseteq I \text{~finite}} \text{Mult}^x(\prod_{i \in E} M_i,-)$,
where $\text{Mult}^x$ indicates that the transition maps of the limit are given by inserting the entries of $x$, and it is not hard to show that $H$ is bijective. Thus
$\bigotimes_{i \in I} M_i = \bigoplus_{x \in R} U_x$,
where $U_x = \cup_{E \subseteq I \text{~finite}} \bigotimes_{i \in E} M_i \otimes \otimes_{i \notin E} x_i$ is the colimit of the finite tensor products $\otimes_{i \in E} M_i$ (the transition maps given by tensoring with entries of $x$). The canonical maps $\otimes_{i \in E} M_i \to U_x$ don't have to be injective; at least when $A$ is a PID, this is the case. Remark that $U_x$ only depends on the equivalence class of $x$, so that the decomposition into the $U_x$ is canonical, whereas the representation of $U_x$ as direct limit (including the transition maps!) depends really on $x$.
1.2 If $M_i = A$ is an integral domain, we get $\bigotimes_{i \in I} A = \oplus_{x \in R} U_x$, where $U_x$ is the direct limit of  copies $A_E$ of $A$, for every finite subset $E \subseteq I$, and transition maps $\prod_{i \in E' \setminus E} x_i : A_E \to A_{E'}$ for $E \subseteq E'$. $U_x$ is just the localization of $A$ at the $x_i$.
1.3 If $A$ is a field, and $M_i$ has basis $B_i$, then $B_x = \cup_{E \subseteq I} \bigotimes_{i \in E} B_i \otimes \otimes_{i \notin E} x_i$ is a basis of $U_x$ and thus $\cup_{x \in R} B_x$ is a basis of $\bigotimes_{i \in I} M_i$. According to this question, this has cardinality $\max(|X|,|I|,\max_i(\dim(M_i)))$.
1.4 If $A_i$ are $A$-algebras, then $\bigotimes_{i \in I} A_i$ is a $A$-algebra. If the $A_i$ are integral domains, then it is a graded algebra by the monoid $X/\sim$ with components $U_x$.
If $A=A_i=K$ is a field with $U=K^x$, then there is a vector space isomorphism between $\bigotimes_{i \in I} K$ and the group algebra $K[U^I / U^{(I)}]$. A sufficient, not neccessary, condition for the existence of a $K$-algebra isomorphism is that $U^{(I)}$ is a direct summand of $U^I$, which is quite rare (see this question). Nevertheless, we can ask if these $K$-algebras isomorphic. In some sense I have proven this already locally (subalgebras given by finitely generated subgroups of the group $U^I / U^{(I)}$ are isomorphic, in a terribly uncanonical way). Many questions I'm currently posing here are addressed to this problem.
2.1 What about interchanging tensor product with duals? Let $(V_i)_{i \in I}$ be a family of vector spaces over a field $K$. For elements $\lambda_i \in K$, define their infinite product $\prod_{i \in I} \lambda_i$ to be the usual product if $\lambda_i=1$ for almost all $i$, and otherwise to be $0$. This yields a multilinear map $\prod : K^I \to K$ and thus a linear map
$\delta : \bigotimes_{i \in I} V_i^* \to (\bigotimes_{i \in I} V_i)^*, \otimes_i f_i \mapsto (\otimes_i x_i \mapsto \prod_{i \in I} f_i(x_i)).$
Then it can be shown that $\delta$ is injective, but the proof is pretty fiddly.
2.2 Let $W_i$ be another family of vector spaces over a field $K$. Then there is a canonical map
$\alpha : \bigotimes_{i \in I} \operatorname{Hom}(V_i,W_i) \to \operatorname{Hom}(\bigotimes_{i \in I} V_i, \bigotimes_{i \in I} W_i).$
Is $\alpha$ injective? This is known when $I$ is finite.
3 What about other properties of finite tensor products, do they generalize? For example let $J_i, i \in I$ be a family of index sets and $M_{i,j}$ be a $A$-module where $i \in I, j \in J_i$. Then there is a canonical homomorphism
$\delta : \bigoplus_{k \in \prod_{i \in I} J_i} \bigotimes_{i \in I} M_{i,k(i)} \to \bigotimes_{i \in I} \oplus_{j \in J_i} M_{i,j}$.
It can be shown that $\delta$ is injective, but is it also bijective (as in the finite case)?
4 The description of the tensor product given in 1.1 depends on a set of representatives and is not handy when you want to prove something. Are there better descriptions?
Remark that in this question I'm not interested in infinite tensor products defined in functional analysis or just colimits of finite ones. I'm interested in the tensor product defined above (which probably every mathematician regards as "the wrong one"). Any hints about their structure or literature about it are appreciated.

A: Coincidentally, I started a work in 2009 concerning infinite tensor products of complex vector spaces, $^*$-algebras and Hilbert spaces. The resulting article has just been accepted for publication and I put it in the arxiv: https://arxiv.org/abs/1112.3128. In the article, I got a similar result as your 1.1 (for vector spaces) and obtained a positive answer to your question 2.2 (when $K$ is the complex filed).


text:
Q: Where does the frame pointer point after set up? Despite looking at textbooks trying to grasp this, I'm having trouble.
    0x08048b29 <func+0>: push   %ebp
    0x08048b2a <func+1>: mov    %esp,%ebp
    0x08048b2c <func+3>: push   %ebx
    ...
    0x08048b30 <phase_2+7>: lea    -0x28(%ebp),%eax

In the lea instruction, I understand that %eax gets the value at 0x28 before %ebp, but where is that exactly? Is it 0x8048b29 - 0x28 (0x28 before the beginning of the function) or what?

A: The ebp register is typically used within a function to access any arguments passed to the function.  Before this function is called, any arguments not passed by register are pushed onto the stack.  At the start of this function, the calling function's base pointer is saved.
(1)    0x08048b29 <func+0>: push   %ebp
The new top of the stack is copied into ebp to serve as the base pointer in this function.
(2)    0x08048b2a <func+1>: mov    %esp,%ebp
Finally, ebx is saved, which was likely a variable passed to the function in a register.
(3)     0x08048b2c <func+3>: push   %ebx
After all of this function entry code, the ebp register is pointing into the middle of the stack.  Above it on the stack (toward the newest pushed items) is the ebx value that was pushed in #3 above.  Below it on the stack are the old ebp from the calling function (saved in #1 above) and MOST importantly... any arguments passed to this function via the stack (done before the function was called).
(4)     lea    -0x28(%ebp),%eax
The final instruction is referring to one of those arguments passed by the stack.  ebp ends up pointing into the stack, not at any of the functions code addresses.  This is pretty normal for ebp, it is most often used as a pointer into the stack.

A: Look at this from the context of calling that function. The code which does so looks something like:
caller+...: push argN
caller+...: ...
caller+...: push arg0
caller+...: call func

i.e. the arguments are put onto the stack in such order that, on entry to func(), the stack will have the following layout:
[esp+(N*4)] : argN
...         : arg(N-1)...arg2
[esp+4    ] : arg1
[esp      ] : <return address to caller()+...>

Then you perform the push %ebp; mov %esp, %ebp sequence, which changes %esp (by -4) so that your layout now is:
[ebp+4+(N*4)][esp+(N*4)] : argN
...                      : arg(N-1)...arg2
[ ebp+8     ][esp+8    ] : arg1
[ ebp+4     ][esp+4    ] : <return address to caller()+...>
[ ebp       ][esp      ] : <saved %ebp of caller>

The code then goes on to push a few more registers on the stack - since that grows downwards each time %esp is changed by -4. Ultimately (which you haven't shown in your disassembly but it'll be there) you'll have an instruction subl $..., %esp. Which is what allocates space for your local variables. The final stack layout is something like:
[ebp+4+(N*4)][         ] : argN
...                      : arg(N-1)...arg2
[ ebp+8     ][         ] : arg1
[ ebp+4     ][         ] : <return address to caller()+...>
[ ebp       ][         ] : <saved %ebp of caller>
[ ebp-4     ][         ] : <saved %ebx of caller>
[ ebp-8     ][         ] : ...
...                      : region for local variables
[ ebp-??    ][ esp     ] : end of stack for func()

Any address between [esp ... ebp-4] is within what's called the stack frame for your function, and it contains either a register saved on behalf of the caller (like ebx in the case of the disassembly shown by you) or local variables.
Hence, when in your code you see any access to %ebp - XX it's in the local variable space, if you see %ebp + YY it's within the space that contains the function arguments.


text:
Q: Remove Item from GridView onClick from another Activity UPDATED my code..
I would like to remove an Item from my GridView ( Main activity ) when I click on the btn Button from the ( Day03 activity).
Here are my Activities :
public class Main extends Activity {
GridView gridView;
public static int deletePos;

static ArrayAdapter adapter;

static final String[] numbers = new String[] { "1", "2", "3", "4", "5",
        "6", "7" };
static final String[] activities = new String[] { "Day01", "Day02",
        "Day03", "Day04", "Day05", "Day06", "Day07" };

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.grid);

    gridView = (GridView) findViewById(R.id.grid1);

    adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, numbers);

    gridView.setAdapter(adapter);

    gridView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub

            String val = activities[arg2]; // arg2 is the index of item
            Class ourClass = null;
            try {
                ourClass = Class.forName("com.example.cahllenge." + val);
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Intent intent = new Intent(Main.this, ourClass);

            deletePos = arg2;
            adapter.notifyDataSetChanged();

            startActivity(intent);

        }
    });

}

and the Day03 activity
   public class Day03 extends Activity {
Button btn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    btn = (Button) findViewById(R.id.ok);

    btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            int deletePos = Main.deletePos;
            Main.adapter.remove(deletePos);
            Main.adapter.notifyDataSetChanged();

        }
    });
}

A: Hi First of all it's not good practice to delete the grdView item from another activity. anyhow if you want to delete it from another activity you can try this(Nothing is impossible). This may give you some trick to solve your problem.
create one deletegridViewItem(){} method in your MainActivity and from your Day03 Activity if you click the button then call deletegridViewItem() method. you need to manage which item should be deleted.Hope this will help you.
See this one edited one.....
hey try this might give you some clue... do not call
adapter.notifyDataSetChanged(); after deletePos = arg2; just call your startActivityForResult(intent, REQUEST_CODE); before this put you deletePos in intent using intent.putExtra-- next at your day03 activity onclick of button call finish method like this
 @Override
 public void finish() {
 // Prepare data intent
 Intent data = new Intent();
 data.putExtra("put deletepos back to intent ");

 // Activity finished ok, return the data
 setResult(RESULT_OK, data);
 super.finish();
}

next in your mainActivity handle onActivityresult() method of intent and in onActivityResult method call remove method. and notify Dataset method...

A: If you really wanna do this, and without using static I'd do it like this:
on your main activity create a onNewIntent()
@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    int deleteMe = intent.getIntExtra('hasDeleted', 0);
    if (deleteMe > 0) {
        // delete numbers if it was List or update setAdapter with new numbers list
        adapter.notifyDataSetChanged();
    }
}

and on the other activity after your finish onClick:
Intent intent = new Intent(Day03.this, Main.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
intent.putExtra("hasDeleted", toDeleteNumber);
startActivity(intent);
finish();


text:
Q: Htaccess rewrite (Cond and) Rule to rewrite these I've been struggling with this as I'm not so good in rewriting.
I want a URLs like these:
http://www.example.com/d/page1
http://www.example.com/d/page2
http://www.example.com/d/anythinghere

to always resolve (rewrite) to this:
http://www.example.com/dir.php

or maybe event better to:
http://www.example.com/dir

which in turn should be rewritten to /dir.php
For those who would like to know why is this needed:
I need to have my AngularJS non-single-page-app work without hashbangs where I need my pagination or anything - I want to have distinctive page URLs in order for the Web spiders to crawl my content properly.
So I'm hoping that I will be able, by making such requests resolve always in my page where AngularJS is dir.php to have links: Go to page 3
I'm still not sure if this is going to work at all. Anyway, the purpose of this rewrite thing is to force the server not to go away from this page when such a link is clicked. This just struck me: but it would create at least a page reload, wouldn't it? If so, that's really bad...

A: RewriteRule ^/d/(.*)$ dir.php/$1
RewriteRule ^/dir/(.*)$ dir.php/$1

First rule will change everything afer /d/ to /dir.php
Second rule will forward everything after /dir/ to /dir.php

A: on your menu change the link
Your Menu

to
Your Menu

in the. htaccess file try this
RewriteEngine On
RewriteRule ^dir dir.php

A: Actually, all my previous attempts were valid - the thing is I was getting broken layout so I assumed rewrites weren't completely correct. It turned out including <base href="/"> rectified the thing by forcing the paths to be relative to the root.


text:
Q: Git checkout ambiguous behavior Sometimes when I have some modified files (tracked) in my Working Directory and I am trying to checkout to another branch, Git does not complain and moves to the new branch by carrying these unstaged files.
Some other times, it complains about these files (changes will be lost) and I have to use
git checkout -f

as to move to another branch. The problem is it does not make sense to me why Git behaves differently under the same(?) circumstances. From my point, I should expect always to complain since there are unstaged files in the Working Directory since git checkout updates it.


text:
Q: C++/CLI generates ugly-looking raise_XXX methods for events I'm writing my custom events in C++/CLI (I pretty much only care about the add/remove methods) as such:
    event EventHandler<XyzEventArgs^> ^Xyz
    {
        void add(EventHandler<XyzEventArgs^> ^handler);
        void remove(EventHandler<XyzEventArgs^> ^handler);
        void raise(Object ^sender, XyzEventArgs ^e);
    }

Everything works great, but when I look at Intellisense under C#, it shows an ugly-looking public raise_Xyz method.
Any ideas on how to hide that without making my events private?
Any help greatly appreciated.
EDIT:

I was able to eliminate the public
  raise_Xyz methods by marking them with
  a different visibility modifier
  (internal in my case). This pretty
  much means that the events cannot be
  raised from outside of the class.
  That's fine with me. I have noticed,
  however, that even simple events
public:
event EventHandler ^XXX;

generate raise_XXX methods and
  they are protected. Is there any way
  of preventing that from happening?

A: note that this is true for the ECMA-372 specification. c# 4 changes the event mechanism scaffold created by the compiler so the C++/CLI ones may also change
Because the events are handled by the compiler generating the relevant scaffold (or allowing you to do your own scaffold for them) there will, by necessity, be a bunch of methods generated to do this.
C++/CLI differs from most other .Net languages in that it's event sugar allows sub classes to raise events declared on the base class.
    public ref class Class1
    {
    public:
        event EventHandler^ MyEvent;
    };

    public ref class Class2 : Class1
    {
    public:
        void Foo()
        {
            this->MyEvent(this, gcnew System::EventArgs());
        }
    };

This compiles (and runs) just fine. compare to c# equivalent
    public class Class1
    {
        public event EventHandler MyEvent;
    }

    public class Class2 : Class1
    {
        public void Foo()
        {
        base.MyEvent(this, new System::EventArgs());
        }
    }

which will refuse to compile saying:

The event 'Class1.MyEvent' can only
  appear on the left hand side of += or
  -= (except when used from within the type 'Class1')

For C++/CLI to do this it must expose the raise_Xxx method as protected. Exposing the underlying delegate field which maintains the event by default would be dangerous as well as disallowing the flexibility of a class to implement events its own way without an automatic delegate backing field.
If you don't want subclasses to be able to do this (or see it) then making it internal is an effective solution for code which is outside the assembly.
note that the C++ CLI spec defines the naming convention for the event scaffolding

18.2.2 Member names reserved for events
For an event E (§18.5), the following names are reserved:

*

*add_E

*remove_E

*raise_E

So this is not something which can be changed


text:
Q: integeClassification based on objective function and multiple/multi-level constraints Here is the problem I am trying to solve. Let us assume that I have information on say 10000 different apples (weight, height, girth to simplify).
I have n different buyers who are all willing to pay a different price for apples say P1, P2, P3... Pn as long as the apples match their constraints. The buyers have 3 seperate levels of constraints
1) Constraints on individual apples (min weight, min height etc) that they are willing to buy
2) Constraints on the average apples allocated to them (min avg weight, min avg height etc)
3) # of apples they can buy
I would like to maximize the total price paid to me by selling these apples.
My thought process so far has been fairly basic,(and I need to fill in details on how to do some of these steps)
Step 1 Identify the set of potential buyers for each apple based on Constrains in 1)
Step 2 Start by putting each apple in the max price bucket till it is filled and then the next highest price and so on
Step 3 Move apples to match the constraints on the average apples for each buyer.
My question is
1) Is this the right basic approach or are there better general ways to solve such problems?
2) Are there ways to think about optimal strategy for 3 above?
3) How do I test to find if I have a reasonable solution and not stuck at some local maxima?


text:
Q: Chart.js - How to move x axis tick marks position to above the x axis I drew a line chart and want to move x axis tick marks position, but I can not find related configuration. Please see the picture below.
AS-IS/TO-BE
Here is my code
<script src="https://cdn.jsdelivr.net/npm/chart.js/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js">

<canvas id="myChart" style="height:500px"></canvas>

chart = new Chart(document.getElementById("myChart"), {
        type: 'line',
        data: {
            datasets: [{
                label: "Count",
                pointStyle: 'circle',
                showLine: true,
                fill: false,
                lineTension: 0,
                borderColor: '#7265ce',
                pointRadius: 4,
                pointBorderWidth: 1,
                pointBackgroundColor: '#7265ce',
                data: data
            }]
        },
        options: {
            parsing: {
                xAxisKey: 'timestamp',
                yAxisKey: 'value'
            },
            spanGaps: false,
            responsive: false,
            scales: {
                x: {
                    bounds: 'ticks',
                    type: 'time',
                    time: {
                        parser: 'yyyyMMddHHmmss',
                        unit: 'minute',
                        stepSize: 5,
                        displayFormats: {
                            minute: 'HH:mm',
                            second: 'mm:ss'
                        }
                    },
                    title: {
                        display: false,
                        text: 'Timestamp'
                    },
                    grid: {
                        drawOnChartArea: false,
                        lineWidth: 1
                    },
                    ticks: {
                        display: true,
                        color: '#cecece'
                    }
                },
                y: {
                    type: 'linear',
                    display: true,
                    ticks: {
                        padding: 10,
                        autoSkip: true,
                        maxTicksLimit:2,
                        color: '#cecece'
                    },
                    title: {
                        display: false,
                        text: 'Count',
                        align: 'end'
                    },
                    grid: {
                        drawOnChartArea: false
                    },
                }
            }
        }
    });
});

    let data = [
    { "timestamp": "20230109150000", "value": 10 },
    { "timestamp": "20230109150100", "value": 17 },
    { "timestamp": "20230109150200", "value": 92 },
    { "timestamp": "20230109150300", "value": 60 },
    { "timestamp": "20230109150400", "value": 50 },
    { "timestamp": "20230109150500", "value": 91 }
    ];

Is it possible?
Is there any configuration in chartjs?
I'm using v3.9.1
Sorry for my poor english.


text:
Q: MySql #1005 Can't create table (errno: 150) Annoying MySQL error to create and altering table
MySQL said:
#1005 - Can't create table `school`.`exams` (errno: 150 "Foreign key constraint is incorrectly formed")

------------------------
LATEST FOREIGN KEY ERROR
------------------------
2020-04-12 15:42:01 0x3a24 Error in foreign key constraint of table school/exams:
there is no index in referenced table which would contain
the columns as the first columns, or the data types in the
referenced table do not match the ones in table. Constraint:
,
  CONSTRAINT `exams_ibfk_1` FOREIGN KEY (`exam_id`) REFERENCES `result` (`exam_id`) ON DELETE NO ACTION ON UPDATE NO ACTION


text:
Q: Infinite Scrolling Not working in Google Chrome I have the following script that causes the page to fetch more records from the database and load them at the end of the page. It's working well in Safari 10.0 on Mac but not with Google Chrome 53.0.2785.143. If I resize the Chrome browser window down to almost smartphone size it does then start to work.
There's nothing in the Console when it's not working so there aren't any errors to debug. If I watch the web server log there are no requests when I attempt to scroll down the page so nothing is happening at all.
Here's the script:

< script type = "text/javascript" >
  var skip = 20;
var action = "<?php echo $action ?>";
$(window).scroll(function() {
  if ($(window).scrollTop() == $(document).height() - $(window).height()) {
    loadArticle(skip);
    skip += 20;
  }
});

function loadArticle(pageNumber) {
  $('#inifiniteLoader').show('fast');
  $.ajax({
    url: "getMoreEvents.php",
    type: 'POST',
    data: "action=" + action + "&skip=" + skip,
    success: function(html) {
      $('#inifiniteLoader').hide('1000');
      $("#content").append(html); // This will be the div where our content will be loaded
    }
  });
  return false;
} < /script>

A: $(window).scroll(function() {
  if ($(window).scrollTop() >= $(document).height() - $(window).height()) {
    loadArticle(skip);
    skip += 20;

A: I had the exactly same issue. It was working on every browser that I tried and even on chrome running at local server, but not when I was deploying my project to Heroku running at https secure server. It's pretty annoying this behavior of what appears to be a bug on Chrome.
The solution is call the function before page end, with a small "gap".
The solution is here:
solution by Vytaliy Makovyak


text:
Q: Move macro forward when caught/stuck in process I have written a macro that uses the paping.exe program to cycle through a list of device IP addresses by sending pings and recording their return values. While the macro works as intended for the majority of the time, there are spare moments when the ping command appears to be stuck or caught up and stops moving forward.  This causes me to have to manually break the execution and start the process over.
From a more broad perspective, is there a way to handle this runtime error.  My thought was to break the list of devices into groupings, and if the program becomes stuck, I could tell the macro to move forward to the next grouping.  While just an idle idea, I wanted to reach out to the community for advice, tips and ideas on ways I could more eloquently handle this issue.  The list of devices that I am pinging is set to grow in time as well.
Public Sub getPingStatusCode(IPvalue As String, portValue As String)

ret = WshShell.Run("C:\Users\*******\paping.exe " & IPvalue & " -p " & portValue & " -c " & pingCount & " -t " & pingTime, 0, True)  'CHANGEEEEEEE
totalCounter = totalCounter + 1

Select Case ret
    Case 0: strResult = "Connected"
    Case 1: strResult = "Fail"
    Case 11001: strResult = "Buffer too small"
    Case 11002: strResult = "Destination net unreachable"
    Case 11003: strResult = "Destination host unreachable"
    Case 11004: strResult = "Destination protocol unreachable"
    Case 11005: strResult = "Destination port unreachable"
    Case 11006: strResult = "No resources"
    Case 11007: strResult = "Bad option"
    Case 11008: strResult = "Hardware error"
    Case 11009: strResult = "Packet too big"
    Case 11010: strResult = "Request timed out"
    Case 11011: strResult = "Bad request"
    Case 11012: strResult = "Bad route"
    Case 11013: strResult = "TTL expired transit"
    Case 11014: strResult = "TTL expired reassembly"
    Case 11015: strResult = "Parameter problem"
    Case 11016: strResult = "Source quench"
    Case 11017: strResult = "Option too big"
    Case 11018: strResult = "Bad destination"
    Case 11032: strResult = "Negotiating IPSEC"
    Case 11050: strResult = "General failure"
    Case Else: strResult = "Unknown host"
End Select

'if statement on return value for bolding and font color
'and counters
If ret = 0 Then 'CONNECTED

    With pingSheet.Cells(i, 4)
        .Value = strResult
    End With
    totalOn = totalOn + 1
    onOff = 1

    'set the rawDataSheet value to connected status...assumes that the sheet starts with all rawdata values as "connected"
    rawDataSheet.Cells(4, i).Value = strResult

ElseIf ret = 1 Then 'FAILED

    With pingSheet.Cells(i, 4)
        .Value = strResult
        .Font.Color = vbRed
        .Font.bold = True
    End With
    failCounter = failCounter + 1
    onOff = 0

    'give RawData sheet a "down since" date value
    If rawDataSheet.Cells(4, i).Value = "Connected" Then
        rawDataSheet.Cells(4, i).Value = Now
    End If

    ''''''''''''''
    pdfDeviceDump

Else

    With pingSheet.Cells(i, 4)
        .Value = strResult
        .Font.Color = vbRed
        .Font.bold = True
    End With
    failCounter = failCounter + 1
    onOff = 0

End If

End Sub

A: I could not get paping.exe to run on my machine so I wrote some code using ping.exe instead.
In principle one can shell out and redirect output to file and then pick up the file later when finished.  We use Windows API calls to wait for a process to finish.
Option Explicit

Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
Private Declare Function WaitForSingleObject Lib "kernel32.dll" (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long

Private Const INFINITE = &HFFFF
Private Const PROCESS_ALL_ACCESS = &H1F0FFF

Sub TestShellAndRedirectPingToFile()

    Dim vIPAddresses As Variant
    vIPAddresses = Array("bbc.co.uk", "wikipedia.org", "cnn.com")

    Dim dicFilesToPickUp As Scripting.Dictionary
    Set dicFilesToPickUp = ShellAndRedirectPingToFile(vIPAddresses)

    Dim vKeyLoop As Variant
    For Each vKeyLoop In dicFilesToPickUp.Keys
        Dim lPID As Long
        lPID = dicFilesToPickUp.Item(vKeyLoop)

        Dim hProc As Long
        hProc = OpenProcess(PROCESS_ALL_ACCESS, 0&, lPID)

        Debug.Print "Waiting on " & vKeyLoop & " (" & lPID & ")"
        WaitForSingleObject hProc, INFINITE
        CloseHandle hProc '* be nice and close handles
    Next
    Debug.Print "Done! Files ready to read."

End Sub

Function ShellAndRedirectPingToFile(ByVal vIPAddresses As Variant) As Scripting.Dictionary

    Dim dicFilesToPickUp As Scripting.Dictionary
    Set dicFilesToPickUp = New Scripting.Dictionary

    Dim sTempFolder As String
    sTempFolder = Environ$("TEMP")
    If Right$(sTempFolder, 1) <> "\" Then sTempFolder = sTempFolder & "\"

    Dim vAddressLoop As Variant
    For Each vAddressLoop In vIPAddresses
        Dim sTempFile As String
        sTempFile = sTempFolder & vAddressLoop & ".txt"

        Dim sCmd As String
        sCmd = Environ$("comspec") & " /S /C ping.exe " & vAddressLoop & " > " & sTempFile

        Dim lPID As Long
        lPID = VBA.Shell(sCmd)
        dicFilesToPickUp.Add sTempFile, lPID
    Next

    Set ShellAndRedirectPingToFile = dicFilesToPickUp

End Function


text:
Q: How to pass phone audio to Dualshock 4 controller that is connected by Bluetooth? I have my Dualshock 4 connected over Bluetooth to my phone. Everything works fine, but I want to use the controller's audio jack instead of the phones. When I connect the headset to the controller, nothing happens and the audio still outputs from my phone speakers.
How do I make it so the audio goes to the headset connected to the controller which is connected via Bluetooth to the phone?
Additional information:

*

*Controller: Official Dualshock 4

*Phone: Huawei mate 20 lite

A: You can't use Bluetooth audio with any device when you are using a DualShock 4. The Headphone Jack only works when connected to a PS4.


text:
Q: Artifactory Remote Repository I'm new to Artifactory. I'm trying to understand better how the remote repository cache mechanism works.
Right know I have 3 imported remote repositories at the system:

*

*google-code-cache.

*java.net-cache.

*jcenter-cache.
At the first two (google and java), After I'm entering to the remote url and downloading an artifact it seems to be saved at the repository-cache.
At jcenter that doesn't work. even if I'm downloading a file the file doesn't goes to the cache.
Can anyone help me understand better the logic behind the cache mechanism - when does it save the artifacts at the cache and when it's don't?
Thanks,
Nadav

A: First of all, with JCenter you don't need the other repositories. You'll be able to retrieve all the artifacts from java.net and google-code directly from jcenter.
Second, the easiest way to configure remote repositories is using the configuration import functionality. Just click on the Import button. The default server to import from will be repo.jfrog.org, which is a good choice, since it has a lot of remote repos to choose. Select 'jcenter' from the list of the proposed repositories and it will be added to your Artifactory and configured correctly.


text:
Q: Advanced favorite and ignored tags management Currently the management of favorite and ignored tags is clunky and error-prone. Deletion of several tags at once requires an unnecessary amount of random mouse movement, which could be accomplished instead via keyboard actions.
I propose the following mutually independent changes:

*

*The tags are sorted in a list, where tags can be browsed with the arrow keys and selected individually or in groups by toggling the 'manage' state of a tag with Space, a ^-click or a ⌘-click, e.g. like the country selection list here.
Alternatively the 'manage' state could be toggled by Space or a simple left click.
Actions such as removal or rearrangement of the selected tags would be performed via a menu.

*Tags can be rearranged by drag-and-drop.

*Tags can be sorted via a separate menu.

*Tags can be edited in plain text, separated by newlines, commas or spaces.

*There should be a notice that wildcards (*) are accepted in tags.
(Originally posted Cross-site management of favorite and ignored tags but question split up and moved here for narrowing down the topic.)

A:
The tags are sorted in a list, where tags can be browsed with the arrow keys and selected individually or in groups

Individually? Then click on the tag itself. If in groups, what is the purpose to do so? The only reason I see is to move between "Favorite Tags" and "Ignored Tags" and to delete the selected tags. No need here. It would also be easier to make checkboxes so you can select the tags easier rather than using arrow keys (you might use them to go up and down a page).

Tags can be rearranged by drag-and-drop.

Can't find a good reason why. No need here since I don't personally think you chose that many tags...

Tags can be sorted via a separate menu.

I like where the tags are being managed in the right hand side of the page. It's easily accessible and also really easy to use. Why waste time using another window when you can control it from a nice section devoted to tags?

Tags can be edited in plain text, separated by newlines, commas or spaces.

No no no! It would seriously look terrible (no offense intended) and ruin the look of the oval-shaped tags. Even some are even color-coded to distinguish different pre-set groups of tags (the status- series, etc.)

There should be a notice that wildcards (*) are accepted in tags.

Let's add that into the Help Center in the page where tag creation rules are discussed shall we?


text:
Q: Cross-site posting feature I sometimes have questions that are suitable for 2 or more Stack Exchange sites. For example, a question on configuring a development database for a website.
This question could be posted on Database Administrators or Stack Overflow.
Wouldn't it be a good feature if you can post the question on one site, then just register it as a 'cross-site post' so that the question and all its answers can be visible on all the sites that it is marked for.
This will cut down on cross-site posting, and allow the same question to be answered by experts with different expertise.
This will promote cross site collaboration, as different users from different sites will be able to see how other parties are answering or commenting on the same question.

A: You could tailor your question for each site:

*

*for stack overflow ask about the programmatic issue

*for database admin ask about configuring the database.
Make sure your question is different on each site.

A: You can register in multiple sites and in this way, someone who is an expert in programming and database administration can have an account on both sites, so there is nothing that prevents users to answer your question on either site. That makes the feature request useless.
Cross-posting isn't necessarily bad, but usually it is best to post on one site. Just copying a question to another site seems the wrong thing to do. There should be some distinction in them: the question should either emphasize programming or database administration. And you can't emphasize with your feature request.


text:
Q: I added successfully a column to previous table using MySQL database dynamically I added successfully a column to previous table using MySQL database dynamically, But when I  fill up the form run and send it to the the database  in my local server it shows:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'forge. posts' doesn't exist (SQL: select count(*) as aggregate from ` posts` where ` slug ` = hihello)

My code of migration table 'posts'
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('body');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('posts');
    }
}

for inserting a new column called 'slug' in the 'post' table
 <?php

 use Illuminate\Database\Schema\Blueprint;
 use Illuminate\Database\Migrations\Migration;

class AddSlugToUsers extends Migration
{

    public function up(){

      Schema::table('posts',function(Blueprint $table){
        $table->string('slug')->unique()->after('title');

      });

    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down(){

     Schema::table('posts',function(Blueprint $table){
     $table->dropColumn('slug');
        });

    }
   }

Successfully inserted 'slug' column but problem is posting the form to the database.
<?php

namespace App\Http\Controllers;
            use Illuminate\Http\Request;
             use App\Http\Requests;
           use App\Http\Controllers\Controller;
          use App\Post;
         use Session;

          class PostController extends Controller
          {
        /**
         * Display a listing of the resource.
         *
         * @return \Illuminate\Http\Response
         */
           public function index()
            {
            $posts = Post::orderBy('id', 'desc')->paginate(10);
            return view('posts.index')->withPosts($posts);
            }

        /**
         * Show the form for creating a new resource.
         *
         * @return \Illuminate\Http\Response
         */
             public function create()
             {
            return view('posts.create');
             }

        /**
         * Store a newly created resource in storage.
         *
         * @param  \Illuminate\Http\Request  $request
         * @return \Illuminate\Http\Response
         */
             public function store(Request $request)
            {
            // validate the data
            $this->validate($request, array(
                    'title' => 'required|max:255',
                    'slug'
                   =>'required|min:5|alpha_dash|min:5|max:255|unique:
             posts, slug ',
                    'body'  => 'required'));

            // store in the database
            $post = new Post;

            $post->title = $request->title;
            $post->slug =  $request->title;
            $post->body = $request->body;

            $post->save();

            Session::flash('success', 'The blog post was successfully
            save!');

            return redirect()->route('posts.show', $post->id);
             }

        /**
         * Display the specified resource.
         *
         * @param  int  $id
         * @return \Illuminate\Http\Response
         */
            public function show($id)
             {
            $post = Post::find($id);
            return view('posts.show')->withPost($post);
             }

        /**
         * Show the form for editing the specified resource.
         *
         * @param  int  $id
         * @return \Illuminate\Http\Response
         */
            public function edit($id)
            {
            // find the post in the database and save as a var
            $post = Post::find($id);
            // return the view and pass in the var we previously created
            return view('posts.edit')->withPost($post);
            }

        /**
         * Update the specified resource in storage.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  int  $id
         * @return \Illuminate\Http\Response
         */
            public function update(Request $request, $id)
             {
            // Validate the data
            $this->validate($request, array(
                    'title' => 'required|max:255',

             'slug'=>'required|alpha_dash|min:5|max:255|unique:posts,slug',
                    'body'  => 'required'
                ));
            // Save the data to the database
            $post = Post::find($id);

            $post->title = $request->input('title');
            $post->title=$request->input('slug');
            $post->body = $request->input('body');

            $post->save();

            // set flash data with success message
            Session::flash('success', 'This post was successfully saved.');

            // redirect with flash data to posts.show
            return redirect()->route('posts.show', $post->id);
           }

         /**
         * Remove the specified resource from storage.
         *
         * @param  int  $id
         * @return \Illuminate\Http\Response
         */
            public function destroy($id)
            {
            $post = Post::find($id);

            $post->delete();
            //for sesssion
            Session::flash('success', 'The post was successfully deleted.');
            return redirect()->route('posts.index');
               }
            }

A: 'forge. posts' this looks like there is a space before table name posts. Did you check your model if there is a s


text:
Q: Copy zip file and unzip using puppet in windows 10 I'm trying to copy one file using puppet in windows.
Code is as below :-
file { 'D:\mycopy\folder\filename':
          ensure => present,
          mode => '0660',
          source => "d:\temp\test.zip",
}

It is giving me below error
Cannot use opaque urls' file:\d:   est\test.zip
I want to unzip also after copy. Thanks.

A: Puppet recognizes both backslashes (\) and forward slashes (/) as path separators in Windows file names.  Although Windows shells want the former, the latter is a lot safer to use in Puppet manifests.
In this case, the two appearances of \t in your double-quoted path string will be interpreted as escape sequences representing the tab character.  You could solve that issue in this case by doubling the backslashes, by switching to a single-quoted string, or by switching to forward slashes.  As a matter of style, I would both switch to single quotes (because there are no variable interpolations or single quotes in the string content) and switch to forward slashes:
However, the actual diagnostic about opaque URLs is a clue to another issue: Puppet accepts URLs as values of File's source parameter, and it is interpreting your absolute filename as a URL with scheme 'd'.  To work around this, you should express the source via a file: URL:
  source => 'file://d:/temp/test.zip'


text:
Q: Transform of XML Message doesn't change schema I am working on a project that requires me to transform a message and replace the old namespaces with new namespaces.  I have that component working correctly.  I do not have the schema attribute changing.  I can do it separately but I cannot change the schema namespace and the element namespaces.  What am I missing here?
Here is the message:
<ns1:SupportNotificationMsg xsi:schemaLocation="http://namespace1.com:8081/Organization/SupportServices SupportServices.xsd"
          xmlns:ns3="http://namespace3.com/Common"
          xmlns:ns1="http://namespace1.com:8081/Organization/SupportServices"
          xmlns:ns2="http://namespace2.com:8081/Organization/"
          xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing"
          xmlns:j="http://www.it.ojp.gov/jxdm/3.0.3"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
         <ns2:SupportNotification>
          <ns3:MessageHeader>
           <ns3:MessageSender>
            <ns3:OrganizationName>ORG</ns3:OrganizationName>
            <ns3:ApplicationName>SEARCH</ns3:ApplicationName>
            <ns3:ContactName>Support</ns3:ContactName>
            <ns3:ContactPhoneNumber>111-222-3333</ns3:ContactPhoneNumber>
           </ns3:MessageSender>
           <ns3:MessageSentDateTime>2017-03-17T12:14:33</ns3:MessageSentDateTime>
          </ns3:MessageHeader>
          <ns2:SupportID>11243</ns2:SupportID>
          <ns2:IdSetting idKey="123456">
           <ns2:IdName ns2:code="APP1">ApplicationName</ns2:IdName>
           <ns2:IdTypeText ns2:code="HLP">HelpDesk</ns2:IdTypeText>
           <ns2:Setting settingKey="3091062">
            <ns2:SupportDateTimes>2017-03-17T08:30:00-05:00</ns2:SupportDateTimes>
            <ns2:SupportSettingStatus>Open</ns2:SupportSettingStatus>
           </ns2:Setting>
          </ns2:IdSetting>
     </ns2:SupportNotification>
</ns1:SupportNotificationMsg >

Here is the transform:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:NS1="http://namespace1.com:8081/Organization/SupportServices"
    xmlns:NS2="http://namespace2.com:8081/Organization/"
    xmlns:NS3="http://namespace3.com/Common"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    version="1.0">
    <xsl:output method="xml" indent="yes"/>
    <xsl:strip-space elements="*"/>
    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="NS1:*">
        <xsl:element name="{local-name()}"
            namespace="http://newnamespace1.com/Organization/SupportServices">
            <xsl:attribute name="xsi:schemaLocation">http://newnamespace1.com/Organization/SupportServices SupportServices.xsd</xsl:attribute>
            <xsl:copy-of select="@*" />
            <xsl:apply-templates />
        </xsl:element>
    </xsl:template>

    <xsl:template match="NS2:*">
        <xsl:element name="{local-name()}"
            namespace="http://newnamespace2.com/Organization/">
            <xsl:copy-of select="@*" />
            <xsl:apply-templates />
        </xsl:element>
    </xsl:template>

    <xsl:template match="NS3:*">
        <xsl:element name="{local-name()}"
            namespace="http://newnamespace3.com/Common">
            <xsl:copy-of select="@*" />
            <xsl:apply-templates />
        </xsl:element>
    </xsl:template>

</xsl:stylesheet>

I have added
<xsl:template match="/attribute::xsi:schemaLocation"/>

or
<xsl:template match="/@xsi:schemaLocation[. =  'http://namespace1.com:8081/Organization/SupportServices SupportServices.xsd']">
    <xsl:attribute name="xsi:schemaLocation">http://newnamespace1.com/Organization/SupportServices SupportServices.xsd</xsl:attribute>
</xsl:template>

It will validate even with the old schema but I'd really like to change it for my own best practice.
Any insight is greatly appreciated.
Thank you,
Dave

A: You can use the following XSLT to transform your structure as requested.  I have added some comments to the stylesheet to hopefully help explain the transformations.  Let me know if this isn't clear or still misses the mark in some way.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:NS1="http://namespace1.com:8081/Organization/SupportServices"
  xmlns:NS2="http://namespace2.com:8081/Organization/"
  xmlns:NS3="http://namespace3.com/Common"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  version="1.0"
>

<xsl:output method="xml" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="@* | node()">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="NS1:*">
    <!-- Add element with namespace -->
    <xsl:element name="ns1:{local-name()}"
        namespace="http://newnamespace1.com/Organization/SupportServices">
            <!-- Copy all of the namespaces from the source xml but exclude
                 the ns1, ns2, ns3 original namespaces from the source xml
                 document -->
            <xsl:copy-of select="namespace::*[not(name()='ns2')
              and
               not(name()='ns3')
              and
               not(name()='ns1')]"/>
        <xsl:apply-templates select="@* | node()"/>

    </xsl:element>
</xsl:template>

<xsl:template match="NS2:*">
    <xsl:element name="ns2:{local-name()}"
        namespace="http://newnamespace2.com/Organization/">
        <xsl:apply-templates />
    </xsl:element>
</xsl:template>

<xsl:template match="NS3:*">
    <xsl:element name="ns3:{local-name()}"
        namespace="http://newnamespace3.com/Common">
        <xsl:apply-templates />
    </xsl:element>
</xsl:template>

<!-- replace xsi:schemaLocation attribute -->
<xsl:template match="@xsi:schemaLocation">
  <xsl:attribute name="xsi:schemaLocation">http://newnamespace1.com/Organization/SupportServices SupportServices.xsd</xsl:attribute>
</xsl:template>
</xsl:stylesheet>


text:
Q: i cant recive any response from success: function(status) This is my ajax part
    $.ajax({
        type:"GET",
        data: 'name='+ value,
        url: "master/Valid.jsp",
        success: function(status){
              if(status)
                   return true;
              else
                   return false;
        }
    });

this is my valid.jsp page
    <%
   String s1 = request.getParameter("name");
    int check =  new DBDepartment().addDepartment(s1, 1);
     if(check==1)
        return false; //in this line it shows error
    %>

how can we send return the value either true or false.

A: Not sure about the $.ajax, But try to use $.post or $.get
in login.jsp
//html
<form method="get" action="valid.jsp" id="login">

        Username:
        <input type="text" name="username" id="username">

        Password:
        <input type="text" name="password" id="password">

        <input type="submit" name="button" id="button" value="Submit" >

</form>

//ajax
$('#login').submit(function(evt) {
        evt.preventDefault();
        var formData = $(this).serialize();
        $.get('valid.jsp',formData,processData);
        function processData(data) {
            if (data.trim()=='pass') {
                $('#formwrapper').html('
You have successfully logged on!
');
            } else {
                if (! $('#fail').length) {
                    $('#formwrapper').prepend('
Incorrect login information. Please try again
');
                }
            }
        } // end processData

    });

in valid.jsp
<%
String user = request.getParameter("username");
String pass = request.getParameter("password");
if(user.equalsIgnoreCase("007")&&pass.equals("secret")){
    out.print("pass");
}else{
    out.print("fail");

}
%>


text:
Q: Correct way to implement piecewise function in pandas / numpy I need to create a function to pass to curve_fit.  In my case, the function is best defined as a piecewise function.
I know that the following doesn't work, but I'm showing it since it makes the intent of the function clear:
def model_a(X, x1, x2, m1, b1, m2, b2):
    '''f(x) has form m1*x + b below x1, m2*x + b2 above x2, and is
    a cubic spline between those two points.'''
    y1 = m1 * X + b1
    y2 = m2 * X + b2
    if X <= x1:
        return y1    # function is linear below x1
    if X >= x2:
        return y2    # function is linear above x2
    # use a cubic spline to interpolate between lower
    # and upper line segment
    a, b, c, d = fit_cubic(x1, y1, x2, y2, m1, m2)
    return cubic(X, a, b, c, d)

The problem, of course, is that X is a pandas Series, and the form (X <= x1) evaluates to a series of booleans, so this fails with the message "The truth value of a Series is ambiguous."
It appears that np.piecewise() is designed for exactly this situation: "Wherever condlist[i] is True, funclist[i](x) is used as the output value."  So I tried this:
def model_b(X, x1, x2, m1, b1, m2, b2):
    def lo(x):
        return m1 * x + b1
    def hi(x):
        return m2 * x + b2
    def mid(x):
        y1 = m1 * x + b1
        y2 = m2 * x + b2
        a, b, c, d = fit_cubic(x1, y1, x2, y2, m1, m2)
        return a * x * x * x + b * x * x + c * x + d

    return np.piecewise(X, [X<=x1, X>=x2], [lo, hi, mid])

But this fails at this call:
return np.piecewise(X, [X<=x1, X>=x2], [lo, hi, mid])

with the message "IndexError: too many indices for array".  I'm inclined to think it's objecting to the fact that there are two elements in condlist and three elements in funclist, but the docs specifically state that the extra element in funclist is treated as the default.
Any guidance?

A: This piece of code in NumPy's definition of np.piecewise is list/ndarray-centric:
# undocumented: single condition is promoted to a list of one condition
if isscalar(condlist) or (
        not isinstance(condlist[0], (list, ndarray)) and x.ndim != 0):
    condlist = [condlist]

Thus, if X is a Series, then condlist = [X<=x1, X>=x2] is a list of two Series.
Since condlist[0] is neither a list nor an ndarray, condlist is "promoted" to a list of one condition:
condlist = [condlist]

Since this is not what we want to happen, we need to make condlist a list of NumPy arrays before passing it to np.piecewise:
X = X.values

For example,
import numpy as np
import pandas as pd
def model_b(X, x1, x2, m1, b1, m2, b2):
    def lo(x):
        return m1 * x + b1
    def hi(x):
        return m2 * x + b2
    def mid(x):
        y1 = m1 * x + b1
        y2 = m2 * x + b2
        # a, b, c, d = fit_cubic(x1, y1, x2, y2, m1, m2)
        a, b, c, d = 1, 2, 3, 4
        return a * x * x * x + b * x * x + c * x + d
    X = X.values
    return np.piecewise(X, [X<=x1, X>=x2], [lo, hi, mid])

X = pd.Series(np.linspace(0, 100, 100))
x1, x2, m1, b1, m2, b2 = 30, 60, 10, 5, -20, 30
f = model_b(X, x1, x2, m1, b1, m2, b2)


text:
Q: .NET c#: Why does Visual studio expect me to put my files in c:\...\myConsoleApplication\bin\Debug I'm new to .NET programming and I get the following exception when trying to load an xml file that's located in my project's root.
Can someone please explain to me why the program is looking for my file in the bin folder?
Here's the exception:

An unhandled exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll
  Additional information: Le file'c:\users\u957974\documents\visual studio 2015\Projects\XMLINQConsoleApplication\XMLINQConsoleApplication\bin\Debug\contacts.xml' est not found.

A: Visual Studio doesn't know that your application needs that file to run. You have to tell it.
To do this, right-click the file in Solution Explorer. Choose "Properties".
Under Properties, find "Copy to Output Directory", and select "Copy if newer".

A: Because that is where the output of your program will compile. The resulted .exe file (assuming this is a console app) will be generated in bin/Debug/.
If you want to load the file from the root of your project, use a relative path like XElement.Load("../../contacts.xml")

A: A relative file path is resolved from the current directory. The current directory when running the application from Visual Studio is the application directory.
But be aware that current directory can change at any time by several operations like OpenFileDialog

A: Bin folder is the working directory of any .Net project which you create.The Bin folder contains all the compiled assemblies. It has all the referenced Dlls and resources which the project is using. Since you have not specified the path for your Xml file it is trying to find it in the current directory and hence the exception.
You can try specifying the path like :
Xelement Xmldoc =  XElement.Load("../../contacts.xml")

A: Give path like this
   Xelement Xmldoc = Xelement.Load("~/COntracts.xml");


text:
Q: Add new key value to a map in golang template $ hugo version
Hugo Static Site Generator v0.54.0 darwin/amd64 BuildDate: unknown
$ cat layouts/t/code.html
  ...
  {{- $json := getJSON $path -}}
  {{- if eq $action "edit" -}}
    {{- $json.nestedMap["action"] = "update" -}}
  {{- end -}}
  ...
  <script type="module">
    import App from "/code.js";
    new App({{ $json.nestedMap | jsonify }});
  </script>

$json.nestedMap is map[string]interface {}

but got error parse failed bad character U+005B '['
Thanks for any tips.

A: The error you are getting is because the [ character is unexpected.
Indeed, this syntax does not work inside templates:
$json.nestedMap["action"]

You must instead use the index function like this to access a map element:
index $json.nestedMap "action"

But, AFAIK that syntax would not allow you to actually set the key, just access it.
One way to modify the map inside a template would be to define some method in a wrapper struct then call that method from the template.
For example:
type mapWrapper struct {
    TheMap map[string]interface{}
}

func (m *mapWrapper) SetMapValue(key, value string) string {
    m.TheMap[key] = value
    return ""
}

Then in the template:
{{- .SetMapValue "key2" "value2" }}

Full working example on playground:
https://play.golang.org/p/8bT4jjYwuzg

A: As @eugenioy said, there is no built-in way to do this, and you need to use a function for that.
Luckily, there's a widespread library of commonly-used templates functions called Sprig, which provides that: http://masterminds.github.io/sprig/dicts.html


text:
Q: Cannot create bundled product in magento 1.9 - tabs are empty/blank I cannot create bundled products in my recently upgrade (1.5 -> 1.9) magento.
When I go to created a bundled product, the "Product Information" tabs are all empty/blank like this:

I cannot see any errors in system.log or exception.log, I even checked for errors in JS Console in chrome as well as nginx/php-fpm logs (there were nothing in there).
Any idea why this is? How can I fix this?

A: This happens when Mage_Bundle is disabled. Make sure its enabled.


text:
Q: Callback Url for twitter I am creating an android application in which I have to integrate twitter for uploading picture on it using twitter4j library.
I am not able to specify callback Url on twitter for application.
Please help me.

A: You should use intent filters to get callback in case of twitter as
requestToken = twitterFactory.getInstance()
                    .getOAuthRequestToken("oauth://com.example.twitter"); //note that "oauth" is your scheme name, "com.example.twitter" is your host name  on your intent-filter

To the activity where you want to get you callback after authorization add following intent filter
<activity android:name=".TwitterActivity"
              android:label="@string/app_name">
    <intent-filter>
        <action android:name="android.intent.action.VIEW"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <category android:name="android.intent.category.BROWSABLE"/>
        <data android:scheme="oauth" android:host="com.example.twitter"  />
    </intent-filter>
</activity>

And in your Activity where you want to get callback to (in this case TwitterActivity) get your verifier as
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith("oauth://com.example.twitter")) {
    String verifier = uri.getQueryParameter("oauth_verifier");
    // request for access token using requestToken and verifier which are used to login second time
}

Here important thing to notice is
-> first of all you ask for request token by calling web api
-> that request token can used to authorize your user
-> after authorization you browser loads certain Url which can start your activity as you have added intent-filter to your activity with corresponding host name and scheme name (i.e. host = "oauth", scheme="com.example.twitter")
-> you can get you access tokens from the loaded Url i.e. extracting  verifier from it and using your request token
for detail code please visit https://bitbucket.org/hintdesk/android-how-to-tweet-in-twitter-within-android-client/src/f8923a4a641313cae7243da51530b472730c2439?at=default


text:
Q: jQuery/Ajax detect if child nodes exist Here is what I am looking into doing... I have not found anyone looking for this so I apologize if this is a duplicate that I have missed somewhere.
Scenario
Reading in an XML file. The names of the nodes can be dynamic (they don't always follow the same node names). For instance:
<course_title></course_title>
<course_subtitle></course_subtitle>

However, they can ALSO have nested nodes within them so it could be
<course_title>
    <course_prefix>
</course_title>

So with that, I need to be able to detect if in fact there IS a nested node or not. So what I am wondering is, is there a way to detect whether a node has nested children without manually going through the children using something like
$(xmlFile).children().children().children(); //not ideal if you dont know how nested something is

A: Check the length of the selector to see if it contains any elements :
$(xmlFile).children().length

or to check for specific nodeName :
$(xmlFile).find('course_prefix').length

A: if ($(node).hasChildNodes()) {
    // It has at least one child node
}


text:
Q: Installing curl inside nginx docker image The following Dockerfile few lines suppose to install curl inside the nginx custom image to run under ubuntu.
The second group of code is an attempt to convert the task to do the same but to run on Amazon Linux.
Any suggestion as to what would be the yum equivalent to the rest of the apt-get command?
-no-install-recommends curl && rm -rf /var/lib/apt/lists/*
//Dockerfile for ubuntu
FROM nginx
RUN apt-get update && apt-get install -y -no-install-recommends curl \
    && rm -rf /var/lib/apt/lists/*

//Dockerfile for Amazon linux
FROM nginx
RUN yum update && yum install -y curl

A: if you're asking how to get the Amazon Linux-based Dockerfile to install curl without prompting you, you can add -y to yum update:
//Dockerfile for Amazon linux
FROM nginx
RUN yum -y update && yum install -y curl

A: -no-install-recommends curl
should be
--no-install-recommends curl
you forgot to put double-dash

A: For Nginx image use Debian as OS use below : -
FROM nginx
RUN apt-get update && apt-get install -y curl && apt-get clean


text:
Q: x and Y must have the same first dimensions I am trying to graph the running average of the first 1,000 points of the data (number of sunspots per month). I am supposed to use Y_k=t/2r(sum from m=-r to r of Y_k+m) where r=5 and y_k is the number of sunspots. I have this so far. I have already imported all the built in functions
   if part == 'C':
    y = data[:,1]
    x = data[:,0]

    x_2 = x[:1000]
    y_Average_Sunspot = np.empty(1000,float)

    y_Avg = y[:1000]
    x_Avg = x[:1000]

    y_n5 = (y_Avg)-5
    y_n4 = (y_Avg)-4
    y_n3 = (y_Avg)-3
    y_n2 = (y_Avg)-2
    y_n1 = (y_Avg)-1
    y_1 = (y_Avg)+1
    y_2 = (y_Avg)+2
    y_3 = (y_Avg)+3
    y_4 = (y_Avg)+4
    y_5 = (y_Avg)+5

    y_Average = (y_5)+(y_4)+(y_3)+(y_2)+(y_1)+(y_n1)+(y_n2)+(y_n3)+(y_n4)+(y_n5)+(y_Avg)

    y_Average_Sunspots = y_Average/10

    plt.plot(x_2,y,label='First Thousand Months',color='y')
    plt.plot(x_Avg, y_Average_Sunspot,label='Running Average', color='k')
    plt.xlim(0,1000)
    plt.ylim(0,1000)
    plt.xlabel('Time (months)')
    plt.ylabel('Number of Sunspots')
    plt.legend(loc=9)
    plt.show()

The problem is when I import it says that x and y need to have the same first dimension. I have checked the shape and size of every array  in this program and they are all the same.
the Full Error Trace back
ValueError                                Traceback (most recent call last)
 in ()
----> 1 ps.plot_sunspots('C')
/home/loberhel/ASTR260/HW2/plot_sunspot.pyc in plot_sunspots(part)
    111
    112
--> 113         plt.plot(x_2,y,label='First Thousand Months',color='y')
114         plt.plot(x_Avg, y_Average_Sunspot,label='Running Average',

color='k')
    115         plt.xlim(0,1000)
/usr/lib64/python2.7/site-packages/matplotlib/pyplot.pyc in plot(*args,
**kwargs)
   2985         ax.hold(hold)
2986     try:
-> 2987         ret = ax.plot(*args, **kwargs)
2988         draw_if_interactive()
2989     finally:
/usr/lib64/python2.7/site-packages/matplotlib/axes.pyc in plot(self, *args,
**kwargs)
4135         lines = []
   4136
-> 4137         for line in self._get_lines(*args, **kwargs):
4138             self.add_line(line)
4139             lines.append(line)
/usr/lib64/python2.7/site-packages/matplotlib/axes.pyc in
_grab_next_args(self, *args, **kwargs)
315                 return

316             if len(remaining) <= 3:

--> 317                 for seg in self._plot_args(remaining, kwargs):
318                     yield seg

319                 return

/usr/lib64/python2.7/site-packages/matplotlib/axes.pyc in _plot_args(self, tup, kwargs)
    293             x = np.arange(y.shape[0], dtype=float)
    294
--> 295         x, y = self._xy_from_xy(x, y)
    296
    297         if self.command == 'plot':
/usr/lib64/python2.7/site-packages/matplotlib/axes.pyc in _xy_from_xy(self, x, y)
    235         y = np.atleast_1d(y)
236         if x.shape[0] != y.shape[0]:

--> 237             raise ValueError("x and y must have same first dimension")
238         if x.ndim > 2 or y.ndim > 2:

239             raise ValueError("x and y can be no greater than 2-D")

ValueError: x and y must have same first dimension


text:
Q: Execute an action for all component of a rule in bison I have the following rule in my bison file :
affectation: VAR '=' expr ';'
    | VAR PLUSEQ expr ';'
    | VAR MINUSEQ expr ';'
    ;

I would like the parser to display the variable name and its content every time an affectation is done. For that, I use the action {printf("%s:%s\n",$1, $3);}. However, as there are 3 forms of affectation, is there a way to apply this action to all the components without writting :
affectation: VAR '=' expr ';'
      {printf("%s:%s\n",$1, $3);}
    | VAR PLUSEQ expr ';'
      {printf("%s:%s\n",$1, $3);}
    | VAR MINUSEQ expr ';'
      {printf("%s:%s\n",$1, $3);}
    ;

A: Basically, the answer is no. In most use cases, the three productions would have different semantics, so it would be normal for their to be three different actions, although they might share code. (As always, refactoring the shared code can reduce the need for duplication.)
If the three rules were really semantically identical, you could collect the different operators into a prefix rule:
aff_pfx: VAR '=' | VAR PLUSEQ | VAR MINUSEQ
affectation: aff_pfx expr ';' { handle($1, $2); }

That relies on the default action copying $$ = $1 in all the productions for aff_pfx, so it is not fully general. Also, it completely erases any distinction between the three syntaxes, which seems unlikely to be correct.
If you are just trying to produce a trace of the parse,take a look at bison's built-in debugging features.


text:
Q: Permission to save a file to disk with python script I have this test code that just saves an XML file to a folder. I wanted to schedule a crontab job to have it running every minute, but I can only get permission to save the XML to disk when I use sudo and type my password. When I schedule it with crontab it prints the string but doesn't save the file. How could I have it working?
#!/usr/bin/python

import sys
import time
from socket import *
from xml.dom.minidom import Document

def main(args):
       doc     = Document()
       with open("/Users/lucasp/Desktop/LogsXML" + time.strftime("%Y-%m-%d-%H.%M.%S", time.localtime()) + ".xml", "w") as f:
           f.write("doc")
       string = "File saved! : LogsXML/" + time.strftime("%Y-%m-%d-%H.%M.%S", time.localtime()) + ".xml"
       print string

if __name__ == '__main__':
        sys.exit (main (sys.argv))

A: Fix the permissions before you run the script: Find out the uid cron runs with (probably "crontab"). Use chown (probably as root) to change the gid of the file LogsXML to that group, and grant group write access to the file. E.g.,
sudo chown lucasp:crontab ~lucasp/Desktop/LogsXML
chmod g+w ~lucasp/Desktop/LogsXML

(If the script needs to create new files, chown the directory and grant write and execute access with chown g+wx <directory>).


text:
Q: ConcurrencyException private static HashMap<String, FileInfo> sFileInfoObjectList = new CacheLinkedHashMap<String, FileInfo>();

public static synchronized FileInfo getFileInfoForProvider(...) {
 FileInfo foundFileInfo = null;

 (...)

 foundFileInfo = sFileInfoObjectList.get(hashEntryKey);

 (...)

 sFileInfoObjectList.put(hashEntryKey, foundFileInfo);

 (...)
}

public static synchronized void removeFileInfoForProvider(final int providerId) {
    Thread thread = new Thread() {
        @Override
        public void run() {
            Iterator<Entry<String, FileInfo>> it = sFileInfoObjectList.entrySet().iterator();
            while (it.hasNext()) {
                Entry<String, FileInfo> pair = it.next();
                FileInfo info = pair.getValue();
                if (providerId == info.mProvider) {
                    it.remove();
                }
            }
        }
    };
}

I am getting a ConccurentModificationException in the run() method. I tried following and it did not work:
public void run() {
    synchronized(sFileInfoObjectList) {
        Iterator<Entry<String, FileInfo>> it = sFileInfoObjectList.entrySet().iterator();
        while (it.hasNext()) {
            Entry<String, FileInfo> pair = it.next();
            FileInfo info = pair.getValue();
            if (providerId == info.mProvider) {
                it.remove();
            }
        }
    }
}

A: The run() is not in a synchronized block because it is run on another thread.  You could use synchronized in your run method but it would be much simpler to use a concurrent collection which does throw this error. E.g. ConcurrentHashMap.
BTW: I wouldn't start a thread each time as it could be more expensive than just iterating over the collection.  I would use a thread pool, or do it in the current thread.

Replace your method with this
public static void removeFileInfoForProvider(final int providerId) {
    Thread thread = new Thread() {
        @Override
        public void run() {
            removeFileInfoForProvider0(providerId);
        }
    };
    thread.start();
}

static synchronized void removeFileInfoForProvider0(final int providerId) {
    Iterator<Entry<String, FileInfo>> it = sFileInfoObjectList.entrySet().iterator();
    while (it.hasNext()) {
        Entry<String, FileInfo> pair = it.next();
        FileInfo info = pair.getValue();
        if (providerId == info.mProvider) {
            it.remove();
        }
    }
}

A: You haven't synchronized remove() call for the Map. If multiple threads try to call run() same time, it will throw ConcurrentModificationException which is the reason in your case.
You may need to use either synchronized on run()  (or) use concurrent collection like ConcurrentHashMap


text:
Q: Issue with Probability Integral Transform I currently have a survivability function of the form:
$S = A*e^{-(t/\theta)^\beta}$ and I would like to sample its PDF using PIT. Due to the definition of the survival function, I know that that the CDF of the PDF is: $F = 1-A*e^{-(t/\theta)^\beta}$. If I then invert the CDF I get that $t = \theta*[-ln((1-F)/A)]^{1/\beta}$. With a uniform distribution for $1-F$, I can plug that into my inverted CDF to get a sampling of my original PDF.
However, for the given survival function, $A=0.8$ and $\beta=0.5$, so for values of the uniform distribution that are larger than $A$, the $ln$ will be positive which ultimately leads to the inverted CDF producing an imaginary number. How am I supposed to sample the PDF if some of my outputs are imaginary?

A: For $A=0.8$ the distribution function looks something like this:

You are complaining that for a random number less than $0.2$ the inverse spits out a complex number. You, unfortunately, handle the method mechanically. If your random number is between $0$ and $0.2$ then you have to ignore the inverse of the cdf. The PIT spits out a zero. The cdf above tells you that the probability that the result is zero is $0.2$
This cdf tells that  $20\%$ of the life times is $0$??? Yes, $20\%$ of the newborn ones are stillborn ones.


text:
Q: Access to fetch a '(localhost)' from origin '(localhost)' has been blocked by CORS policy El error completo

Access to fetch at '(url de facebook)' (redirected from
'http://localhost:4000/auth/facebook') from origin
'http://localhost:3000' has been blocked by CORS policy: Response to
preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. If an opaque response serves your needs, set the request's
mode to 'no-cors' to fetch the resource with CORS disabled

Busque solución y me decían que dentro de las cabeceras del servidor(en mi caso node.js) escribiera esto:
header("Access-Control-Allow-Origin", "*");

header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

Aclaro que ya tengo instalada la dependencia cors e inicializado.
Entiendo para que es, pero mi problema es cuando hago una petición en especifica de facebook de la dependencia passport, desde el mismo servidor me trae los datos. El problema es cuando lo solicito al frontend, esto no ocurre si solicito otra petición distinta, no sé a que se deba.
import express from "express";
import cors from "cors";
import morgan from "morgan";
const app = express();

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.use( cors({ origin: "localhost:3000", credentials: true  }) );
app.use(express.json());
app.use(morgan("tiny"));
app.use(express.urlencoded({ extended: true }));

const passport = require("passport");
require("./src/routes/Facebook")(passport);

app.use(passport.initialize());
app.use(passport.session());

/* Rutas de Passport */
// Ruta para desloguearse
app.get("/logout", function (req, res) {
  req.logout();
  res.redirect("http://localhost:3000/");
});
// Ruta para autenticarse con Facebook (enlace de login)
app.get(
  "/auth/facebook",
  passport.authenticate("facebook", { scope: "email" })
);

app.get(
  "/auth/facebook/callback",
  passport.authenticate("facebook", {
    successRedirect: "http://localhost:3000/",
    failureRedirect: "http://localhost:3000/login",
  })
);

app.set("puerto", process.env.PORT || 4000);
app.listen(app.get("puerto"), () => {
  console.log("Listen: " + app.get("puerto"));
});

module.exports = app;


text:
Q: Problems with Creating Bar Plot In R Image of Problematic Barplot
Hello everyone, this is my first time posting on Stack Exchange and I will start off by saying that I am a beginner at coding, (like, really a beginner).
I am having issues creating a barplot for one of my classes. (I have attached an image of this problematic barplot in this post).
As you will be able to see, there are two problems with it:
(1) The legend practically blocks out the whole fourth plot
and
(2) I just can't get there to be one color per leaf shape, (there are multiple leaf shapes represented by one color, in other words. I have 13 leaf shapes, I would like 13 different colors, one per shape).
Lastly, here is the code I used to generate the plot:
barplot(shape_biome_table,beside=T,legend.text = T,col=c(1:13),
      main="Leaf Shapes By Biome Type",
      xlab="Leaf Shape",ylab="Frequency",las=1,
      args.legend=list(x="topright"))

If someone can please help me in figuring out what needs to be done to solve these two issues I would be very appreciative. And, as I mentioned previously, I am not very well versed in coding jargon, so please try to make your explanation as easy as possible to understand.
Thank you very much!

A: R's native plotting support is a bit cumbersome. Perhaps the first thing is to try ggplot2. I've tried to make a guess at what your data looks like.
library(tidyverse)
library(ggplot2)

shape_biome_table <- tribble(
~leaf.shape, ~biome,
"Acicular", "Hawaiian Natives",
"Acicular", "Hawaiian Natives",
"Acuminate", "Hawaiian Natives",
"Aristate", "Mediterranean" )

ggplot(shape_biome_table, aes(x = leaf.shape, fill = leaf.shape)) +
  geom_bar() +
  facet_grid(. ~ biome)