text:
Q: How to implement multiple popups? I have a problem to implement multiple popups. I get this script from net, it's correct when I apply to a single popup but not if i do copies of this. You can see it in: Dendrosite. In the margin left menu (Sinopsi/Fitxa/Autors) i implemented correcly in one (Sinopsi) but now I can implement to other (Fitxa/Autors)
HTML:

Javascript:

var popupStatus = 0;

//loading popup with jQuery magic!
function loadPopup(){
    //loads popup only if it is disabled
    if(popupStatus==0){
        $("#backgroundPopup").css({
            "opacity": "0.7"
        });
        $("#backgroundPopup").fadeIn("fast");
        $("#popupContact").fadeIn("fast");
        popupStatus = 1;
    }
}

//disabling popup with jQuery magic!
function disablePopup(){
    //disables popup only if it is enabled
    if(popupStatus==1){
        $("#backgroundPopup").fadeOut("fast");
        $("#popupContact").fadeOut("fast");
        popupStatus = 0;
    }
}

//CONTROLLING EVENTS IN jQuery
$(document).ready(function(){

    //LOADING POPUP
    //Click the button event!
    $("#go").click(function(){
        //centering with css
        //load popup
        loadPopup();
    });

    //CLOSING POPUP
    //Click the x event!
    $("#popupContactClose").click(function(){
        disablePopup();
    });
    //Click out event!
    $("#backgroundPopup").click(function(){
        disablePopup();
    });
    //Press Escape event!
    $(document).keypress(function(e){
        if(e.keyCode==27 && popupStatus==1){
            disablePopup();
        }
    });

});

and CSS:

#backgroundPopup{
display:none;
position:fixed;
_position:absolute; /* hack for internet explorer 6*/
height:100%;
width:100%;
top:0;
left:0;
z-index:1;
}
#popupContact{
    margin-top: -104px;
    margin-left:102px;
    display:none;
    position:fixed;
    _position:absolute; /* hack for internet explorer 6*/
    height:288px;
    width:600px;
    z-index:9;
    padding:12px;
    background-color:  #333;
    filter: alpha(opacity=20); opacity: .5
}
#popupContact h1{
    font-family:Arial, Helvetica, sans-serif;
    font-size:20px;
    color:#FFF;
    text-shadow: 0px 1px 1px #000;
    padding-bottom:10px;
    margin-bottom:30px;
    border-bottom-width: 1px;
    border-bottom-style: solid;
}

#popupContact h3{
    font-family: Arial, Helvetica, sans-serif;
    font-size: 12px;
    color: #FFF;
    text-align: justify;
}

#popupContactClose{
    font-size:18px;
    line-height:14px;
    right:6px;
    top:4px;
    position:absolute;
    color: #ffeb70;
    font-weight:700;
    display:block;
    cursor: pointer;
    font-family: Arial, Helvetica, sans-serif;
}

Thanks!

A: The reason it didn't work was that for every #go #go1 #go2 popup links, you need three separate event handlers, not just one. That's why multiple boxes pop-ups when you click on one, and none pop-ups when you click on the other two.
To get this to work I would rewrite the popup script to support multiple popups. But you can simply do this procedurally without using functions.
HTML (Merge the code below with yours. The IDs, Class names relate to the javascript)

Sinopsi

Popup 1x

Fitxa

Popup 2x

Autors

Popup 2x

JavaScript

CSS (make sure the popups loaded hidden.)
.popup{display:none}

Good luck mate, the site looks good btw. You should really learn more about jQuery, it's pretty powerful and really easy to use compared to just JavaScript. I'd think you'll enjoy it.
http://jquery.com/
http://api.jquery.com/click/
p.s. Don't get to worried about all those anonymous functions function(){//do stuff}, it's just a shorthand of function bar(){//do stuff} $('.open').click(bar)


text:
Q: update multiple home screen widget from activity I have 2 widgets on my home screen. I know how to update the single widget from my Main activity. The following code updates my single widget when i press the back button on my Main activity.
@Override
public void onBackPressed() {
    Intent intent = new Intent(this, todo_widget.class);
    intent.setAction("android.appwidget.action.APPWIDGET_UPDATE");
    int[] ids = AppWidgetManager.getInstance(getApplication())
            .getAppWidgetIds(
                    new ComponentName(getApplication(),         todo_widget.class));
    intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);
    sendBroadcast(intent);}

But both the widgets are not updating  if i put my code like this :-
@Override
public void onBackPressed() {
    Intent intent = new Intent(this, todo_widget.class);
    intent.setAction("android.appwidget.action.APPWIDGET_UPDATE");
    int[] ids = AppWidgetManager.getInstance(getApplication())
            .getAppWidgetIds(
                    new ComponentName(getApplication(),     todo_widget.class));
    intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);
    sendBroadcast(intent);
    Intent intent1 = new Intent(this, todo_widget2.class);
    intent1.setAction("android.appwidget.action.APPWIDGET_UPDATE");
    int[] ids1 = AppWidgetManager.getInstance(getApplication())
            .getAppWidgetIds(
                    new ComponentName(getApplication(), todo_widget2.class));
    intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids1);
    sendBroadcast(intent1);
    this.finish();
}

please someone help me out of this. How do I update both the widgets when i press the back button or when my Main activity is created?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Deploy API Management with Function App - Terraform I have got an Azure HTTP Function App deployed via Terraform, I would like to manage access to the HTTP function via API management. I can see how to created API management via Terraform, however I cannot see how to marry my function app upto my API management. Via the console this is very simple. How can I do this via terraform?

A: Below is the terraform code to add your Azure function as a backend to Azure API Management:
resource "azurerm_api_management_backend" "example" {
name = "sample-backend"
resource_group_name = data.azurerm_resource_group.example.name
api_management_name = data.azurerm_api_management.example.name
protocol = "http"
url = "https://${azurerm_function_app.example.name}.azurewebsites.net/api/"
credentials {
header = {
"x-functions-key" = "${data.azurerm_function_app_host_keys.example.default_function_key}"
}
}
}

Refer to Royarin blog article for more information on adding the Functions or Web API as an API in Azure APIM as backend.


text:
Q: How to replace one identifier in an expression with another one via Rust macro? I'm trying to build a macro that does some code transformation, and should be able to parse its own syntax.
Here is the simplest example I can think of:
replace!(x, y, x * 100 + z) ~> y * 100 + z

This macro should be able to replace the first identifier with the second in the expression provided as third parameter. The macro should have some understanding of the language of the third parameter (which in my particular case, as opposed to the example, wouldn't parse in Rust) and apply recursively over it.
What's the most effective way to build such a macro in Rust? I'm aware of the proc_macro approach and the macro_rules! one. However I am not sure whether macro_rules! is powerful enough to handle this and I couldn't find much documentation in how to build my own transformations using proc_macro. Can anyone point me in the right direction?

A: Solution with macro_rules! macro
To implement this with declarative macros (macro_rules!) is a bit tricky but possible. However, it's necessary to use a few tricks.
But first, here is the code (Playground):
macro_rules! replace {
    // This is the "public interface". The only thing we do here is to delegate
    // to the actual implementation. The implementation is more complicated to
    // call, because it has an "out" parameter which accumulates the token we
    // will generate.
    ($x:ident, $y:ident, $($e:tt)*) => {
        replace!(@impl $x, $y, [], $($e)*)
    };

    // Recursion stop: if there are no tokens to check anymore, we just emit
    // what we accumulated in the out parameter so far.
    (@impl $x:ident, $y:ident, [$($out:tt)*], ) => {
        $($out)*
    };

    // This is the arm that's used when the first token in the stream is an
    // identifier. We potentially replace the identifier and push it to the
    // out tokens.
    (@impl $x:ident, $y:ident, [$($out:tt)*], $head:ident $($tail:tt)*) => {{
        replace!(
            @impl $x, $y,
            [$($out)* replace!(@replace $x $y $head)],
            $($tail)*
        )
    }};

    // These arms are here to recurse into "groups" (tokens inside of a
    // (), [] or {} pair)
    (@impl $x:ident, $y:ident, [$($out:tt)*], ( $($head:tt)* ) $($tail:tt)*) => {{
        replace!(
            @impl $x, $y,
            [$($out)* ( replace!($x, $y, $($head)*) ) ],
            $($tail)*
        )
    }};
    (@impl $x:ident, $y:ident, [$($out:tt)*], [ $($head:tt)* ] $($tail:tt)*) => {{
        replace!(
            @impl $x, $y,
            [$($out)* [ replace!($x, $y, $($head)*) ] ],
            $($tail)*
        )
    }};
    (@impl $x:ident, $y:ident, [$($out:tt)*], { $($head:tt)* } $($tail:tt)*) => {{
        replace!(
            @impl $x, $y,
            [$($out)* { replace!($x, $y, $($head)*) } ],
            $($tail)*
        )
    }};

    // This is the standard recusion case: we have a non-identifier token as
    // head, so we just put it into the out parameter.
    (@impl $x:ident, $y:ident, [$($out:tt)*], $head:tt $($tail:tt)*) => {{
        replace!(@impl $x, $y, [$($out)* $head], $($tail)*)
    }};

    // Helper to replace the identifier if its the needle.
    (@replace $needle:ident $replacement:ident $i:ident) => {{
        // This is a trick to check two identifiers for equality. Note that
        // the patterns in this macro don't contain any meta variables (the
        // out meta variables $needle and $i are interpolated).
        macro_rules! __inner_helper {
            // Identifiers equal, emit $replacement
            ($needle $needle) => { $replacement };
            // Identifiers not equal, emit original
            ($needle $i) => { $i };
        }

        __inner_helper!($needle $i)
    }}
}

fn main() {
    let foo = 3;
    let bar = 7;
    let z = 5;

    dbg!(replace!(abc, foo, bar * 100 + z));  // no replacement
    dbg!(replace!(bar, foo, bar * 100 + z));  // replace `bar` with `foo`
}

It outputs:
[src/main.rs:56] replace!(abc , foo , bar * 100 + z) = 705
[src/main.rs:57] replace!(bar , foo , bar * 100 + z) = 305

How does this work?
There are two main tricks one need to understand before understanding this macro: push down accumulation and how to check two identifiers for equality.
Furthermore, just to be sure: the @foobar things at the start of the macro pattern are not a special feature, but simply a convention to mark internal helper macros (also see: "The little book of Macros", StackOverflow question).

Push down accumulation is well described in this chapter of "The little book of Rust macros". The important part is:

All macros in Rust must result in a complete, supported syntax element (such as an expression, item, etc.). This means that it is impossible to have a macro expand to a partial construct.

But often it is necessary to have partial results, for example when dealing token for token with some input. To solve this, one basically has an "out" parameter which is just a list of tokens that grows with each recursive macro call. This works, because macro input can be arbitrary tokens and don't have to be a valid Rust construct.
This pattern only makes sense for macros that work as "incremental TT munchers", which my solution does. There is also a chapter about this pattern in TLBORM.

The second key point is to check two identifiers for equality. This is done with an interesting trick: the macro defines a new macro which is then immediately used. Let's take a look at the code:
(@replace $needle:ident $replacement:ident $i:ident) => {{
    macro_rules! __inner_helper {
        ($needle $needle) => { $replacement };
        ($needle $i) => { $i };
    }

    __inner_helper!($needle $i)
}}

Let's go through two different invocations:

*

*replace!(@replace foo bar baz): this expands to:
macro_rules! __inner_helper {
    (foo foo) => { bar };
    (foo baz) => { baz };
}

__inner_helper!(foo baz)

And the inner_helper! invocation now clearly takes the second pattern, resulting in baz.

*replace!(@replace foo bar foo) on the other hand expands to:
macro_rules! __inner_helper {
    (foo foo) => { bar };
    (foo foo) => { foo };
}

__inner_helper!(foo foo)

This time, the inner_helper! invocation takes the first pattern, resulting in bar.
I learned this trick from a crate that offers basically only exactly that: a macro checking two identifiers for equality. But unfortunately, I cannot find this crate anymore. Let me know if you know the name of that crate!

This implementation has a few limitations, however:

*

*As an incremental TT muncher, it recurses for each token in the input. So it's easy to reach the recursion limit (which can be increased, but it's not optimal). It could be possible to write a non-recursive version of this macro, but so far I haven't found a way to do that.

*macro_rules! macros are a bit strange when it comes to identifiers. The solution presented above might behave strange with self as identifier. See this chapter for more information on that topic.

Solution with proc-macro
Of course this can also be done via a proc-macro. It also involves less strange tricks. My solution looks like this:
extern crate proc_macro;

use proc_macro::{
    Ident, TokenStream, TokenTree,
    token_stream,
};

#[proc_macro]
pub fn replace(input: TokenStream) -> TokenStream {
    let mut it = input.into_iter();

    // Get first parameters
    let needle = get_ident(&mut it);
    let _comma = it.next().unwrap();
    let replacement = get_ident(&mut it);
    let _comma = it.next().unwrap();

    // Return the remaining tokens, but replace identifiers.
    it.map(|tt| {
        match tt {
            // Comparing `Ident`s can only be done via string comparison right
            // now. Note that this ignores syntax contexts which can be a
            // problem in some situation.
            TokenTree::Ident(ref i) if i.to_string() == needle.to_string() => {
                TokenTree::Ident(replacement.clone())
            }

            // All other tokens are just forwarded
            other => other,
        }
    }).collect()
}

/// Extract an identifier from the iterator.
fn get_ident(it: &mut token_stream::IntoIter) -> Ident {
    match it.next() {
        Some(TokenTree::Ident(i)) => i,
        _ => panic!("oh noes!"),
    }
}

Using this proc macro with the main() example from above works exactly the same.
Note: error handling was ignored here to keep the example short. Please see this question on how to do error reporting in proc macros.
Apart from this, that code doesn't need as much explanations, I think. This proc macro version also doesn't suffer from the recursion limit problem as the macro_rules! macro.


text:
Q: UrlConection not getting JSON response Hello all i am trying to open one URL using thread in activity on button click. i prepare one thread in onClick method. i wrote code. it is working but in response i am not getting response properly. It should return JSON response but its returning half string. My code is
@Override
public void onClick(View arg0) {
    new Thread(new Runnable() {

        @Override
        public void run() {

            try {
                url = new URL("https://api.metwit.com/v2/weather/?location_lat=22.03&location_lng=75.65");
                URLConnection conn = url.openConnection();
                BufferedReader br = new BufferedReader(
                           new InputStreamReader(conn.getInputStream()));

                String inputLine;
                while ((inputLine = br.readLine()) != null) {
                    s.append(inputLine);

                }
                //br.close();
                Log.i("####$$$", s.toString());
                JSONObject jsonObject = new JSONObject(s.toString());

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    }).start();

}

and i am getting response like
{"objects": [{"weather": {"status": "partly cloudy", "measured": {"wind_speed": 2.056, "wind_direction": 240.0, "temperature": 316.0, "humidity": 8}}, "timestamp": "2013-07-13T08:07:47.397932", "sun_altitude": 1.309306025505066, "geo": {"type": "Point", "coordinates": [75.65, 22.03]}, "icon": "https://api.metwit.com/v2/icons/partly_sunny"}, {"sources": ["weatherbug", "wwo", "meteoblue"], "weather": {"status": "cloudy", "measured": {"wind_speed": 5, "wind_direction": 280, "temperature": 300, "humidity": 76}}, "timestamp": "2013-07-13T09:00:00", "sun_altitude": 1.0995509624481201, "geo": {"type": "Point", "coordinates": [75.5859375, 21.97265625]}, "icon": "https://api.metwit.com/v2/icons/cloudy"}, {"sources": ["weatherbug", "wwo", "meteoblue"], "weather": {"status": "rainy", "measured": {"wind_speed": 5, "wind_direction": 280, "temperature": 300, "humidity": 76}}, "timestamp": "2013-07-13T12:00:00", "sun_altitude": 0.38399845361709595, "geo": {"type": "Point", "coordin

what is wrong i am not getting.

A: You can use droidQuery to handle everything:
$.with(myButton).click(new Function() {
    @Override
    public void invoke($ droidQuery, Object... params) {
        $.ajax(new AjaxOption().url("https://api.metwit.com/v2/weather/?location_lat=22.03&location_lng=75.65")
                               .type("GET")
                               .dataType("JSON")
                               .context(droidQuery.context())
                               .success(new Function() {
                                   @Override
                                   public void invoke($ droidQuery, Object... params) {
                                       JSONObject json = (JSONObject) params[0];
                                       droidQuery.toast(json.toString(), Toast.LENGTH_SHORT);
                                       //If you want to simplify parsing, consider using:
                                       Map<String, ?> data = $.map(json);
                                       //TODO continue parsing
                                   }
                               })
                               .error(new Function() {
                                   @Override
                                   public void invoke($ droidQuery, Object... params) {
                                       droidQuery.alert("ERROR: " + (String) params[2]);
                                   }
                               }));
    }
});

A: You can try android-query library, then it's easy.
     AQuery aq = new AQuery(this);
     aq.ajax("https://api.metwit.com/v2/weather/?location_lat=22.03&location_lng=75.65",
             JSONObject.class,new AjaxCallback<JSONObject>(){

           @Override
           public void callback(String url, JSONObject object, AjaxStatus status)
           {
             String ret = object.toString();
             System.err.println(ret);
           }

     });

This solution works fine for me.


text:
Q: Clipping Feature Classes by Data View Extents with ArcPy? Have a fully functional script about 90% of the time. It is that 10% that is really bothering me and I cannot seem to deduce a solution.
Script will take the user defined dataframe view extents and clip all layers within extent to a geodatabase. That 10% failure rate occurs when clipping an extent that does not contain one of the features (gate_line, fence_line, or wall_line).
My thinking would be to limit input for clipping to only layers that are found in the view extents, this is where I logically fail.
The current script:
import arcpy, os
from arcpy import env

#overwrite permissions
arcpy.env.overwriteOutput = True

#set map document to current
mxd = arcpy.mapping.MapDocument("CURRENT")
path = mxd.filePath
path = path.replace(os.path.basename(path),"")
arcpy.env.workspace = path

#creates new file geoGDB
arcpy.CreateFileGDB_management(path, "CurrentExtents.gdb")
gdb = path + "CurrentExtents.gdb"
arcpy.env.workspace = gdb

#set dataframe extents as a polygon
df = arcpy.mapping.ListDataFrames(mxd)[0]
dfAsFeature = arcpy.Polygon(arcpy.Array([df.extent.lowerLeft,
                                         df.extent.lowerRight,
                                         df.extent.upperRight,
                                         df.extent.upperLeft]), df.spatialReference)

lyrs = arcpy.mapping.ListLayers(mxd,"",df)

exportLayers = []
for lyr in lyrs:
    if lyr.isFeatureLayer == True:
        layerRplc = lyr.longName
        replace = [".", "\\"]
        result = arcpy.GetCount_management(lyr)
        count = int(result.getOutput(0))
#Only include non-blank features
        if count != 0:
            for item in replace:
                layerRplc = layerRplc.replace(item, "_")
            outFC = os.path.join(gdb,layerRplc)
            exportLayers.append(outFC)
            if arcpy.Exists(outFC):
                arcpy.Delete_management(outFC)
            arcpy.AddMessage("Getting our clip on...." + outFC)
            clip = arcpy.Clip_analysis(lyr, dfAsFeature, outFC)
#removes empty fc's from gdb
            clipRes = arcpy.GetCount_management(clip)
            clipCount = int(clipRes.getOutput(0))
            if clipCount == 0:
                arcpy.Delete_management(clip)
            del replace
    del lyr

del mxd
del df

Script is run in desktop from catalog with a saved mxd directory as the defined workspace.
Just started coding recently!


text:
Q: How to implement Copy to ClipBoard (Trigger Windows Ctrl+C Event) functionality? I need to implement a Copy to ClipBoard functionality in my screen
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>

$(document).on("click", "#inputbtn", function () {

var text = $("#comment").val();

    });

</script>
</head>
<body>

Enter Comment: <input type="text" id="comment"><br> </br>

 <input type="button" id = "inputbtn" value="Copy It ClipBoard">

</body>
</html>

Not having any idea how to continue further on this
I have seen this link
http://www.htmlgoodies.com/beyond/javascript/article.php/3458851
which isn't working in Chrome
Is this can be done without using any plugins
Thanks in advance .


text:
Q: Count number of balls in each bin, given a two-element sequence of balls and bins If I have a list:
{ball,ball,BINDIVIDER,ball,ball,ball,BINDIVIDER,BINDIVIDER,ball,BINDIVIDER,ball}

The balls and bins can be in any permutation.
Then, the following is clear: in bin one I have 2 balls, in bin two I have 3 balls, in bin three I have 0 balls, in bin four I have 1 ball, and in bin five I have 1 ball.
Can I put a list like this (above) into Mathematica, and get the counts of the balls in each bin? So, in this case I would put in {1,1,2,1,1,1,2,2,1,2,1}, and get out {2,3,0,1,1}.
Each output is a list with as many entries as bindividers, plus 1 (so just the number of bins).
I have tried using SequenceSplit, but this does not understand that empty gaps between two bins contain zero balls, instead splitting the list into concurrent sequences.

A: If we were to use 0 instead of 2 as the bin divider...
list = {1, 1, 2, 1, 1, 1, 2, 2, 1, 2, 1} /. 2 -> 0

(* {1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1} *)

... then we could write:
Total /@ Split[list, # != 0 &]

(* {2, 3, 0, 1, 1} *)

Update
Taking account of subsequent comments and the updated question...
count[list_] := Total /@ Split[Append[list, 0], # != 0 &]

count[{0, 1, 1, 0}]
(* {0, 2, 0} *)

and
# -> count[#] & /@ Tuples[{0, 1}, 5] // Column

A: I do not believe the current answers correctly produce the result you appear to be after (which seems to be a "stars and bars" representation).
This would be one way to do this:
bincnts = (Join[{0}, PositionIndex[#][0], {Length[#] + 1}] //
     Rest[#] - 1 - Most[#] &) &;

To illustrate the difference, I'll use the currently most upvoted answer (though a spot check on another answer yields the same):
All possible configurations with two dividers (hence 3 bins) (N.B.: I've used zero instead of 2 as the divider):
test = Permutations[{0, 0, 1, 1, 1, 1, 1}]

{{0,0,1,1,1,1,1},{0,1,0,1,1,1,1},{0,1,1,0,1,1,1},{0,1,1,1,0,1,1},{0,1,1,1,1,0,1},{0,1,1,1,1,1,0},{1,0,0,1,1,1,1},{1,0,1,0,1,1,1},{1,0,1,1,0,1,1},{1,0,1,1,1,0,1},{1,0,1,1,1,1,0},{1,1,0,0,1,1,1},{1,1,0,1,0,1,1},{1,1,0,1,1,0,1},{1,1,0,1,1,1,0},{1,1,1,0,0,1,1},{1,1,1,0,1,0,1},{1,1,1,0,1,1,0},{1,1,1,1,0,0,1},{1,1,1,1,0,1,0},{1,1,1,1,1,0,0}}

Current answer results:
Table[StringLength /@ StringSplit[l, "0"], {l,
  StringJoin @@@ (Map[ToString, test, {2}])}]

{{5},{1,4},{2,3},{3,2},{4,1},{5},{1,0,4},{1,1,3},{1,2,2},{1,3,1},{1,4},{2,0,3},{2,1,2},{2,2,1},{2,3},{3,0,2},{3,1,1},{3,2},{4,0,1},{4,1},{5}}

bincnts results:
bincnts /@ test

{{0,0,5},{0,1,4},{0,2,3},{0,3,2},{0,4,1},{0,5,0},{1,0,4},{1,1,3},{1,2,2},{1,3,1},{1,4,0},{2,0,3},{2,1,2},{2,2,1},{2,3,0},{3,0,2},{3,1,1},{3,2,0},{4,0,1},{4,1,0},{5,0,0}}

Note that the latter correctly accounts for the actual number of bins that must logically be present.
Compared to using stringsplit or total on list split, this is quite performant:

with considerable advantage on large cases:

A: It works if the data are given as a string instead of as a list:
StringLength /@ StringSplit["11211122121", "2"]
(*    {2, 3, 0, 1, 1}    *)

The conversion to string, if required, can be done with
StringJoin @@ ToString /@ {1, 1, 2, 1, 1, 1, 2, 2, 1, 2, 1}
(*    "11211122121"    *)

To address @ciao's concern, add the All option:
StringLength /@ StringSplit["11211122121", "2", All]
(*    {2, 3, 0, 1, 1}    *)

StringLength /@ StringSplit["11211122112", "2", All]
(*    {2, 3, 0, 2, 0}    *)

A: Not directly.
{1, 1, 2, 1, 1, 1, 2, 2, 1, 2,
     1} //. {x___, 2, 2, y___} :> {x, 2, 3, 2, y} //
   SequenceSplit[#, {2}] & // # /. {3} :> 0 & // Map[Length]

A: Split[{1, 1, 2, 1, 1, 1, 2, 2, 1, 2, 1}, SameQ] /.
  {x : {1 ..} :> Length[x]} /.
  {x : {2 ..} :> Sequence @@ ConstantArray[0, Length[x] - 1]}

Note: your example has no divider as the first or last element. If an initial or final sequence of 1s can be empty -- that is, if the first or last element can be a bin divider -- the answer changes

A:  list = {1, 1, 2, 1, 1, 1, 2, 2, 1, 2, 1} /. 2 -> 0;

A variation on ciao's approach for integer input with 0 as bin divider:
ClearAll[binCounts1]
binCounts1 = Differences @ Random`Private`PositionsOf[ArrayPad[#, {1, 1}], 0] - 1 &;

binCounts1[list]

 {2, 3, 0, 1, 1}

A much slower alternative using SequenceCases:
ClearAll[binCounts2]
binCounts2 = SequenceCases[ArrayPad[#, {1, 1}],
  {0, a : Except[0] ..., 0} :> Length[{a}], Overlaps -> True] &;

binCounts2[list]

 {2, 3, 0, 1, 1}

Using ciao's test:
binCounts1 /@ test == binCounts2 /@ test == bincnts /@ test

True


text:
Q: Retrieve json object in text file using powershell I have 1000 number of JSON objects in text file. I want to retrieve only one JSON object for a particular duns number using PowerShell.
{
   "organization":{
      "duns":"024330410",
      "dunsControlStatus":{
         "operatingStatus":{
            "description":"Active",
            "dnbCode":9074
         },
         "isMarketable":false,
         "isMailUndeliverable":false,
         "isTelephoneDisconnected":null,
         "isDelisted":false,
         "subjectHandlingDetails":[

         ],
         "fullReportDate":"2018-02-10"
      },
      "primaryName":"SRP Trucking LLC",
      "multilingualPrimaryName":[

      ],
      "tradeStyleNames":[

      ],
      "websiteAddress":[

      ],
      "telephone":[

      ],
      "fax":[

      ],
      "primaryAddress":{
         "language":{

         },
         "addressCountry":{
            "name":"United States",
            "isoAlpha2Code":"US",
            "fipsCode":"US"
         },
         "continentalRegion":{
            "name":"North America"
         },
         "addressLocality":{
            "name":"LAKE HAVASU CITY"
         },
         "minorTownName":null,
         "addressRegion":{
            "name":"Arizona",
            "abbreviatedName":"AZ",
            "fipsCode":"04"
         },
         "addressCounty":{
            "name":"MOHAVE",
            "fipsCode":"015"
         },
         "postalCode":"864035343",
         "postalCodePosition":{

         },
         "streetNumber":null,
         "streetName":null,
         "streetAddress":{
            "line1":"25 SOUTHWESTER LN",
            "line2":null
         },
         "postOfficeBox":{

         },
         "latitude":34.488798,
         "longitude":-114.301529,
         "geographicalPrecision":{
            "description":"Street Address Centroid",
            "dnbCode":30257
         },
         "isRegisteredAddress":false,
         "isResidentialAddress":null,
         "statisticalArea":{
            "cbsaName":"Lake Havasu City-Kingman AZ",
            "cbsaCode":"29420",
            "economicAreaOfInfluenceCode":"092",
            "populationRank":{
               "rankNumber":"7",
               "rankDnBCode":10959,
               "rankDescription":"100,000 to 249,999"
            }
         },
         "locationOwnership":{

         },
         "premisesArea":{
            "measurement":2915.0,
            "unitDescription":"Square Foot",
            "unitDnBCode":3848,
            "reliabilityDescription":"Modelled",
            "reliabilityDnBCode":9094
         },
         "isManufacturingLocation":null
      },
      "multilingualPrimaryAddress":[

      ],
      "registeredAddress":{

      },
      "mailingAddress":{

      },
      "stockExchanges":[

      ],
      "thirdPartyAssessment":[

      ],
      "registrationNumbers":[

      ],
      "industryCodes":[
         {
            "code":"484110",
            "description":"General Freight Trucking, Local",
            "typeDescription":"North American Industry Classification System 2017",
            "typeDnBCode":30832,
            "priority":1
         },
         {
            "code":"1622",
            "description":"Trucking",
            "typeDescription":"D&B Hoovers Industry Code",
            "typeDnBCode":25838,
            "priority":1
         },
         {
            "code":"4212",
            "description":"Local trucking operator",
            "typeDescription":"US Standard Industry Code 1987 - 4 digit",
            "typeDnBCode":399,
            "priority":1
         },
         {
            "code":"42120000",
            "description":"Local trucking, without storage",
            "typeDescription":"D&B Standard Industry Code",
            "typeDnBCode":3599,
            "priority":1
         },
         {
            "code":"E",
            "description":"Transportation, Communications, Electric, Gas and Sanitary Services",
            "typeDescription":"D&B Standard Major Industry Code",
            "typeDnBCode":24657,
            "priority":1
         }
      ],
      "businessEntityType":{
         "description":"Unknown",
         "dnbCode":0
      },
      "controlOwnershipDate":"2015",
      "startDate":"2015",
      "controlOwnershipType":{

      },
      "isAgent":null,
      "isImporter":null,
      "isExporter":null,
      "numberOfEmployees":[
         {
            "value":1,
            "informationScopeDescription":"Consolidated",
            "informationScopeDnBCode":9067,
            "reliabilityDescription":"Modelled",
            "reliabilityDnBCode":9094,
            "employeeCategories":[

            ],
            "trend":[

            ]
         },
         {
            "value":1,
            "informationScopeDescription":"Individual",
            "informationScopeDnBCode":9066,
            "reliabilityDescription":"Modelled",
            "reliabilityDnBCode":9094,
            "employeeCategories":[

            ],
            "trend":[

            ]
         }
      ],
      "financials":[
         {
            "financialStatementToDate":"2016-10-01",
            "financialStatementDuration":null,
            "informationScopeDescription":null,
            "informationScopeDnBCode":null,
            "reliabilityDescription":"Modelled",
            "reliabilityDnBCode":9094,
            "unitCode":"Single Units",
            "accountantName":null,
            "yearlyRevenue":[
               {
                  "value":57815.0,
                  "currency":"USD",
                  "trend":[

                  ]
               }
            ]
         }
      ],
      "mostSeniorPrincipals":[
         {
            "givenName":"Debbie",
            "familyName":"Pickering",
            "fullName":"Debbie Pickering",
            "namePrefix":null,
            "nameSuffix":null,
            "gender":null,
            "jobTitles":[
               {
                  "title":"Owner"
               }
            ],
            "managementResponsibilities":[
               {
                  "description":"Owner",
                  "mrcCode":"A0A1"
               }
            ]
         }
      ],
      "currentPrincipals":[

      ],
      "socioEconomicInformation":{
         "isMinorityOwned":null,
         "isSmallBusiness":true
      },
      "isStandalone":true,
      "corporateLinkage":{

      }
   }
}

A: PS direct have to JSON cmdlets which can serve your purpose:
Take the JSON string in a variable as $variable1, then use:
$variable1 | ConvertFrom-Json
and later you can use Convertto-Json to convert that to JSON also with where-object
Hope it helps. Just formed the answer from Tomalak


text:
Q: Control/Close 3rd party applications in iOS I have a situation where I have to close other running/suspended applications in iOS, from my application. Is there a way to achieve this in iOS 8.
Initial impression is that I have to increase the memory usage of my app so that iOS closes out other running/suspended applications, but is there a better way to accomplish this?
Thanks in Advance.

A: I don't believe this would be possible to shut apps down from within your own app and if it was I believe Apple would reject your App under the App Store Review Guideline 2.6

2.6 Apps that read or write data outside its designated container area will be rejected

I believe it will get rejected under this because it will have to read and/or write data outside of the Apps designated container area which isn't allowed. Apps work in a sandboxed mode so they aren't aware of any other Apps running on the device and can't (Not Jailbroken) interact with them except for using URL Schemes.
As for the idea of upping your App memory usage until it starts shutting other apps down idea probably say that your App will also fall at risk of crashing if the memory gets too high which would result in it not being very friendly for users and I believe Apple would actually reject this as well. I can't figure out exactly which rule in the guidelines they would reject it for if they found your App doing this but if it was to crash because of the high memory usage they'd certainly reject it under 2.1 and 2.2:

2.1 Apps that crash will be rejected
2.2 Apps that exhibit bugs will be rejected

So I'm sorry to say I don't believe there is any good way to do this that would still allow your App into the Apple App Store.


text:
Q: Change horizontal spacing for subscripts in equation environment I would like to adjust the spacing prior and after a subscript to reduce the required horizontal space.
With this small mwe
\documentclass{scrbook}
\usepackage{amsmath}
\begin{document}
    \begin{equation}
        \begin{pmatrix}
            a \\ b \\ c
        \end{pmatrix}_\text{SCR}
        = x
    \end{equation}
\end{document}

I get this:

I would like however to adjust the horizontal spacing before the subscript and make the spacing after the subscript away that it actually overlaps with the euqality sign.

A: I'm not really sure you want to do it, because it will be confusing your reader.
\documentclass{scrbook}
\usepackage{amsmath,mathtools}

\begin{document}

\begin{equation}
\begin{pmatrix}
  a \\ b \\ c
\end{pmatrix}_{\!\!\mathrlap{\mathrm{SCR}}}
= x
\end{equation}

\end{document}

The \!\! is for moving the subscript nearer the parenthesis (I always use square brackets for matrices because they give less typographic problems).
You can give the subscript some width, which will be less confusing, with \mathmakebox instead of \mathrlap (note that \mathrlap{...} is equivalent to \mathmakebox[0pt][l]{...}).
\documentclass{scrbook}
\usepackage{amsmath,mathtools}
\begin{document}

\begin{equation}
\begin{pmatrix}
  a \\ b \\ c
\end{pmatrix}_{\!\!\mathmakebox[1em][l]{\mathrm{SCR}}}
= x
\end{equation}

\end{document}

Adjust the length (here 1em) to your needs.


text:
Q: How to copy the text from the UIwebview I Have some text in my webview which I loaded from a html page.  Now If i want to select a particular word from the Webview then the selected word should be higlighted.
Can we acheive this type of functionality in the weebview?

A: Search and highlight text in UIWebView
SearchWebView.h:
@interface UIWebView (SearchWebView)

- (NSInteger)highlightAllOccurencesOfString:(NSString*)str;
- (void)removeAllHighlights;

@end

SearchWebView.m:
@implementation UIWebView (SearchWebView)

- (NSInteger)highlightAllOccurencesOfString:(NSString*)str
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"SearchWebView" ofType:@"js"];
    NSString *jsCode = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    [self stringByEvaluatingJavaScriptFromString:jsCode];

    NSString *startSearch = [NSString stringWithFormat:@"MyApp_HighlightAllOccurencesOfString('%@')",str];
    [self stringByEvaluatingJavaScriptFromString:startSearch];

    NSString *result = [self stringByEvaluatingJavaScriptFromString:@"MyApp_SearchResultCount"];
    return [result integerValue];
}

- (void)removeAllHighlights
{
    [self stringByEvaluatingJavaScriptFromString:@"MyApp_RemoveAllHighlights()"];
}

@end


text:
Q: What is the difference in how C and Java handle out of bounds arrays access? In Java, we get a beautiful exception when attempting to access and array out of bounds, but in C that's not the case:
#include <stdio.h>

int main() {
    int x[10] = {1,2,3}; // After the third index, I know that the rest are 0.
    int i = 0;
    while (i<99) { // Here I exceed the size of the array,
        printf("%d",x[i]); // printing non-existent indexes.
        i++;
    }
    return 0;
}

And the output is:
12300000001021473443840268687241986531780216078041842686812-12686816199941806157
0338438-2199933010019993299657804184019993359001214734438441990611-819265930944-
8192925345321-122881852697619690479012147344384268694020027537742147344384145346
587600214734438400102686884-819226869482003047601567625672026869562002753732-120
02706633004199040214734438402020893505321130682200320201752380100000243875924666
4687366080-21479789413447414207980
Process returned 1 (0x1)   execution time : 0.719 s
Press any key to continue.

Technically, what exactly happened? It's not exactly an "int size overflow", right?

A: In C Accessing outside the bounds of the array is undefined behavior and the result is unpredictable, it could appear to work correctly, it could seg-fault, etc... The draft C99 standard in Annex J.2 Undefined behavior and lists the following bullet:

An array subscript is out of range, even if an object is apparently accessible with the
  given subscript (as in the lvalue expression a[1][7] given the declaration int
  a[4][5]) (6.5.6).

section 6.5.6 paragraph 8, which is normative gives the details.
On the other hand the Java Language Specification section 10.4 makes accessing an array out of bounds an exception:

All array accesses are checked at run time; an attempt to use an index that is less than zero or greater than or equal to the length of the array causes an ArrayIndexOutOfBoundsException to be thrown.

Java and C have different design philosophies. Java goes out of it's way to avoid undefined behavior while C and C++ give latitude to the implementation. A few good articles on this:

*

*Why Language Designers Tolerate Undefined Behavior

*Philosophy behind Undefined Behavior

*Undefined behaviour in Java

A: Just to add to what Shafik has already said:

Technically, what exactly happened? It's not exactly an "int size
  overflow", right?

The array is occupying 10 * sizeof(int) bytes of memory. When you're printing array values at an index beyond this size boundary, you're actually accessing parts of memory that have not been allocated for the array. It could be anything. It could be other variable's values; it could be instructions; it could be protected memory that you have no business accessing.

A: This is not an int size overflow but overflow in memory access.
When you declare x[10] in memory it will allocate address and store 0 for 10 times:
x[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}

As you declare:
x[10] = {1, 2, 3}

it is assigned as {1, 2, 3, 0, 0, 0, 0 , 0, 0 , 0}
But you are printing beyond allocated memory so there can be anything stored which is not in hand of your program.
I ran your program and also printed the addresses and values of x[i]s and I can see addresses and values like:
x[0] =  0x7fff4b1b6290:  1
x[1] =  0x7fff4b1b6294:  2
x[2] =  0x7fff4b1b6298:  3
x[3] =  0x7fff4b1b629c:  0
x[4] =  0x7fff4b1b629c:  0
x[5] =  0x7fff4b1b62a0:  0
x[6] =  0x7fff4b1b62a4:  0
x[7] =  0x7fff4b1b62a8:  0
x[8] =  0x7fff4b1b62ac:  0
x[9] =  0x7fff4b1b62b0:  0
x[10] =  0x7fff4b1b62b4: 0
x[11] =  0x7fff4b1b62b8: 11
x[12] =  0x7fff4b1b62bc: 293
x[13] =  0x7fff4b1b62c0: 0
x[14] =  0x7fff4b1b62c4: 0
x[15] =  0x7fff4b1b62c8: 212348189

So you can see till x[9] you are getting right output but after that it will just print the value at the next address and that is random values.

A: In computer programming, bounds checking is any method of detecting whether a variable is within some bounds before it is used. It is usually used to ensure that a number fits into a given type (range checking), or that a variable being used as an array index is within the bounds of the array (index checking). A failed bounds check usually results in the generation of some sort of exception signal.
Refer: http://lelanthran.com/deranged/?p=182

A: The people designing C wanted the language as fast and flexible as possible, so the runtime does just what the programmer said, even if its destructive.  In Java, the designers protect the programmer from doing something stupid, so every time you access an array it first checks to see if the access is within bounds.
One approach is not necessarily better than another, but each approach is better at doing different things.


text:
Q: Greater Rift Keystone drop rate and requirements? The Greater Rift Keystone drop rate is 100% for T6 and maybe 75% for T1, lower for lower difficulties and chance of 2 dropping in higher difficulties. Is there any empirical data that confirms rates?
Edit: drop rates were changed in a hotfix on Sept 3, 2014:

The drop rate for Key of Trials has been significantly increased (9/3)

Edit: difficulty requirement was removed in patch 2.3 on Aug 25, 2015:

Generic Greater Rift Keystones now drop and can drop at any difficulty level

Confirmed level 70 required.
I'd still like to know approximate drop rates on all difficulties if anyone has data/insight.

A: This may be just an approximate answer. But as far as I tested it, I've checked it on my game.
You reference that T6 will provide a 100% drop chance. As far as I tested it, this won't be true. I have played some T6 portals and I gt some keys, which is great, but also some runs without any key.
There is a reference on the net which says it could be 100%. But in my experience they are much lower. As everytime were a percentage chance exists, it won't be possible to pin it down to an exact value without viewing the code. But regarding my drop chance experiences the drop chance base seems to be like the drop rate for the infernal machine which is described below.

*

*Torment I: 25%

*Torment II: 28%

*Torment III: 33%

*Torment IV: 38%

*Torment V: 43%

*Torment VI: 50%


text:
Q: Ubuntu 16.04 External Display Stopped Working (Black) I've been running Ubuntu on my laptop for a couple of years and upgraded to 16.04 several months ago with no problems.  I go out on site regularly so often plug my laptop into external screens through HDMI as well as using an VGA adapter to connect to projectors.
I've never had a problem with the 2nd screen until yesterday.  When I plug in a monitor, whether directly (HDMI) or via the VGA adapter dongle Ubuntu recognizes it but nothing displays.
My displays shows 2 screens "Build in display" and "Goldstar company 23" just like it always has and I've tried switching primary, secondary and mirror to no avail.  I've also tried powering up with it plugged in, not plugged in, different monitors, different cables, checking to see if something in the BIOS has been disabled and tried pressing the various monitor buttons to flips between on off external mirror etc.
I've even just reinstalled Ubuntu 16.04 again to see if something had gone adrift in the background and I get the same thing.
Thanks for your help!
xrandr shows:
Screen 0: minimum 8 x 8, current 1920 x 1080, maximum 32767 x 32767
LVDS1 connected primary 1280x720+0+0 (normal left inverted right x axis y axis) 293mm x 164mm
   1366x768      60.00 +
   1360x768      59.80    59.96
   1280x720      60.00*
   1024x768      60.00
   1024x576      60.00
   960x540       60.00
   800x600       60.32    56.25
   864x486       60.00
   640x480       59.94
   720x405       60.00
   680x384       60.00
   640x360       60.00
DP1 disconnected (normal left inverted right x axis y axis)
HDMI1 connected 1920x1080+0+0 (normal left inverted right x axis y axis) 510mm x 290mm
   1920x1080     60.00*+  50.00    59.94
   1920x1080i    60.00    50.00    59.94
   1680x1050     59.88
   1280x1024     60.02
   1280x960      60.00
   1152x864      59.97
   1280x720      60.00    50.00    59.94
   1024x768      60.00
   800x600       60.32
   720x576       50.00
   720x480       60.00    59.94
   640x480       60.00    59.94
VGA1 disconnected (normal left inverted right x axis y axis)
VIRTUAL1 disconnected (normal left inverted right x axis y axis)

lspci shows
00:00.0 Host bridge: Intel Corporation 3rd Gen Core processor DRAM Controller (rev 09)
00:02.0 VGA compatible controller: Intel Corporation 3rd Gen Core processor Graphics Controller (rev 09)
00:14.0 USB controller: Intel Corporation 7 Series/C210 Series Chipset Family USB xHCI Host Controller (rev 04)
00:16.0 Communication controller: Intel Corporation 7 Series/C210 Series Chipset Family MEI Controller #1 (rev 04)
00:1a.0 USB controller: Intel Corporation 7 Series/C210 Series Chipset Family USB Enhanced Host Controller #2 (rev 04)
00:1b.0 Audio device: Intel Corporation 7 Series/C210 Series Chipset Family High Definition Audio Controller (rev 04)
00:1c.0 PCI bridge: Intel Corporation 7 Series/C210 Series Chipset Family PCI Express Root Port 1 (rev c4)
00:1c.1 PCI bridge: Intel Corporation 7 Series/C210 Series Chipset Family PCI Express Root Port 2 (rev c4)
00:1c.2 PCI bridge: Intel Corporation 7 Series/C210 Series Chipset Family PCI Express Root Port 3 (rev c4)
00:1d.0 USB controller: Intel Corporation 7 Series/C210 Series Chipset Family USB Enhanced Host Controller #1 (rev 04)
00:1f.0 ISA bridge: Intel Corporation HM77 Express Chipset LPC Controller (rev 04)
00:1f.2 SATA controller: Intel Corporation 7 Series Chipset Family 6-port SATA Controller [AHCI mode] (rev 04)
00:1f.3 SMBus: Intel Corporation 7 Series/C210 Series Chipset Family SMBus Controller (rev 04)
02:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8101/2/6E PCI Express Fast/Gigabit Ethernet controller (rev 05)
03:00.0 Network controller: Intel Corporation Centrino Wireless-N 2230 (rev c4)

A: I know this has been a while so thank you to everyone who tried to help.  It turned out it was a hardware problem with the HDMI socket.  Nothing to do with Ubuntu!

A: Mine does the same thing, except the exturnal monitor turns itself off (saying no input) ONLY after I have logged in. Until then it displays normally.
If I open monitor settings to sort the problem, I can make the laptop detect the screen and configure it. However, on pressing Apply, both screens go black and do not restore settings as they should after the 30 second "keep this configuration?" dialogue.
The problem became apparent the second time I logged in. I updated Ubuntu 2 days ago
I am running Ubuntu 16.04 LTS on an Asus N56V.
edit
I fixed mine just now by switching my graphics driver to "using X.Org X Server..."

A: Boot with "Advanced options for Ubuntu" and select another kernel (old kernel).
--


text:
Q: Server side or Clint side API call? If you're working with React.js, what is the best way to make an API call? For example, if I'm trying to get some book data from google books API should I do this on the client side with React.js or on the server side. Why would it be better to do it on one side vs the other? Thanks.

A: You can do something like this.
const express = require('express');
const app = express();
const path = require('path');
const fs = require('fs');
const proxy = require('http-proxy-middleware');

app.use(
  '/api',
  proxy({
    target: 'http://api.books.com',
    changeOrigin: true,
    ws: true,
    pathRewrite: { '^/api': '' },
  })
);

const index = fs.readFileSync(path.resolve('./build', 'index.html'), { encoding: 'utf-8' });

app.get('*', (req, res) => {
  res.contentType('text/html').send(index);
});

const server = app.listen(3000, function() {
  const host = server.address().address;
  const port = server.address().port;

  console.log('The server is running at http://%s:%s/', host, port);
});

And call like this (throw proxy), to not have problems with CORS or to replace server after.
fetch('/api/get-books')


text:
Q: Backup cassandra keyspace using nodetool I am using Cassandra on Ubuntu 14.04. From the documentation, I could see that running the command:
nodetool snapshot <keyspace name>

creates a snapshot of my keyspace.
The output of the command is:
nodetool snapshot my_keyspace
Requested creating snapshot(s) for [my_keyspace] with snapshot name [1455455429118]
Snapshot directory: 1455455429118

As per the docs, the snapshots should be present in the directories:
/var/lib/cassandra/data/my_keyspace/<table names>/snapshots/1455455429118

However, there is some hash value at the end of the table name.
I am not sure where that came from and also not sure whether that value will always be same or not. For example, the table name is user_agents, the snapshot directory is:
/var/lib/cassandra/data/my_keyspace/user_agents-147c8cc0d31c11e5aacb3b02dd594b59/snapshots/1455455429118

I am not sure what 147c8cc0d31c11e5aacb3b02dd594b59 represents.
I am trying to automate this process and if I don't know about this random hash value, it won't be possible to know which directory to pick. Is there any way to disable this or decipher this from the output of nodetool command ?

A: From the Documentation.
Taking a snapshot
Snapshots are taken per node using the nodetool snapshot command. To take a global snapshot, run the nodetool snapshot command using a parallel ssh utility, such as pssh.

A snapshot first flushes all in-memory writes to disk, then makes a
  hard link of the SSTable files for each keyspace. You must have enough
  free disk space on the node to accommodate making snapshots of your
  data files. A single snapshot requires little disk space. However,
  snapshots can cause your disk usage to grow more quickly over time
  because a snapshot prevents old obsolete data files from being
  deleted. After the snapshot is complete, you can move the backup files
  to another location if needed, or you can leave them in place.

Run the nodetool snapshot command, specifying the hostname, JMX port, and keyspace.
$ nodetool -h localhost -p 7199 snapshot mykeyspace

The snapshot is created in data_directory_location/keyspace_name/table_name/snapshots/snapshot_name directory. Each snapshot directory contains numerous .db files that contain the data at the time of the snapshot.

Cassandra flushes the node before taking a snapshot, takes the
  snapshot, and stores the data in the snapshots directory of each
  keyspace in the data directory. If you do not specify the name of a
  snapshot directory using the -t option, Cassandra names the directory
  using the timestamp of the snapshot, for example 1391460334889. Follow
  the procedure for taking a snapshot before upgrading Cassandra. When
  upgrading, backup all keyspaces. For more information about snapshots,
  see Apache documentation .

If you did not specify a snapshot name, Cassandra names snapshot directories using the timestamp of the snapshot. If the keyspace contains no data, empty directories are not created.
Example: Single table snapshot
Take a snapshot of only the playlists table in the music keyspace. On Linux, in the Cassandra bin directory, for example:
$ ./nodetool snapshot -cf playlists music

Requested creating snapshot(s) for [music] with snapshot name [1391461910600]
Snapshot directory: 1391461910600

Cassandra creates the snapshot directory named 1391461910600 that contains the backup data of playlists table in
/var/lib/cassandra/data/music/playlists-bf8118508cfd11e3972273ded3cb6170/snapshots

nodetool <options> snapshot (
  ( -cf <table> | --column-family <table> )
  ( -t <tag> | --tag <tag> )
  -- ( <keyspace> ) | ( <keyspace> ... )
)

*

*options are:

*( -h | --host )  |

*( -p | --port )

*( -pw | --password )

*( -u | --username )

*-cf, or --column-family, followed by the name of the table to be backed up.

*-t or --tag, followed by the snapshot name.

*-- Separates an option and argument that could be mistaken for a option.

*keyspace is one keyspace name that is required when using the    -cf
option, or one or more optional keyspace names, separated by a space.
UPDATE::
/var/lib/cassandra/data/music/playlists-bf8118508cfd11e3972273ded3cb6170/snapshots

Here in playlists-bf8118508cfd11e3972273ded3cb6170 , -bf8118508cfd11e3972273ded3cb6170 is UUID

So it is generating in that way.Ad There are some options to monitor the sstables that are being written, and incrementally backup those files.
Check out tablesnap, & cassandra snapshotter .


text:
Q: set own video frame in the main screen on facetime is it possible, when using facetime, to increase the size of my own video frame? as in skype where I can set my own video frame in the main screen and my friend video as the little frame in the corner. I couldn't find an option for that, I can only move the little frame across the screen, but can't increase the size.
thanks

A: No, the size can not be changed. You can provide feedback to Apple here:

*

*https://www.apple.com/feedback/iphone.html


text:
Q: JPQL JOIN between 2 tables I'm trying to join two tables but I can't manage to find a proper JPQL query.
Here's a light version of the two tables I have, there's a FK between the two id_persona columns.
TABLE macchine

marca (String) -- targa (String) -- id_persona (int)

TABLE persone

nome (String) -- id_persona (int)

What I'd like is to achieve joining them on id_persona but there's no way I can guess the query sintax and google isn't of any help.
For example, how can I get that every "targa" linked by an "id_persona" to a given "nome"?

Persona
    @Entity
    public class Persone implements Serializable {
     private static final long serialVersionUID = 1L;

     @Id
     @GeneratedValue(strategy=GenerationType.IDENTITY)
     @Column(name="id_persona")
     private int idPersona;

     private String cognome;

     private Timestamp data_nascita;

     private String nome;

     @OneToMany(mappedBy="persona")
     @JoinColumn(name="id_persona")
     private Set<Macchine> macchina;
    }

-
Macchine
@Entity
public class Macchine implements Serializable {
 private static final long serialVersionUID = 1L;

 @Id
 @GeneratedValue(strategy=GenerationType.IDENTITY)
 @Column(name="id_persona")
 private int idPersona;

 private String targa;

 private String marca;

 @ManyToOne(fetch=FetchType.LAZY)
 private Persone persona;
}

--
Query
public static List<Macchine> selectPM(){
        Query selectAll = em.createQuery("SELECT m FROM Macchine m");
        @SuppressWarnings("unchecked")
        List<Macchine> jObj = selectAll.getResultList();
        return jObj; //Join Objective
    }

I edited the answer because I made some changes in the project. I have new tables which I linked.
This is the error I'm getting now:
Error compiling the query [SELECT m.id_persona, m.targa, m.marca FROM Macchine m], line 1, column 9: unknown state or association field [id_persona] of class [model.Macchine]


text:
Q: facebook invite notification not working in ios I am using the AppInvite in Facebook SDK for iOS.The problem is the end Users/Friends whom the AppInvite is sent to, don't receive the push notifications The Users dont have the App installed.And the Applink url is working fine.
The app is running in production mode, have already added the users as TestUsers also.

A: From Facebook docs at App invites
If the person already has the app installed, they will not receive a push notification.
So make sure you uninstall the application from the device which receiving the invitation.


text:
Q: Flutter: Mystery padding above keyboard when TimeDilation > 1.0 I have a mystery padding above the keyboard when TimeDilation > 1.0 and I come to the screen with my keyboard on, from another screen.
Screenshot
The padding seems to be proportional to the time dilation when timeDilation >1.0 and < 3.0.  It seems to be constant at the same height for timeDilation values >= 3.0.
If I change the routing so that FirstScreen never gets generated, the bug is avoided.  Similarly, the bug can be worked around by forcing a screen redraw.
What is the cause and how do I need to change my code, to fix this bug?
MRTC:
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart' show timeDilation;
import 'package:keyboard_actions/keyboard_actions.dart';

void main() async {
  // set the system top-level property [timeDilation] to control the animation speed
  timeDilation = 3.0;

  WidgetsFlutterBinding.ensureInitialized();

  runApp(
    MyApp(),
  );
}

class MyApp extends StatefulWidget {
  MyApp({Key? key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      initialRoute: '/',
      onGenerateRoute: (RouteSettings settings) {
        final routes = <String, WidgetBuilder?>{
          '/': (_) => FirstScreen(),
          '/screen2': (_) => SecondScreen(),
        };
        final builder = routes[settings.name]!;
        return MaterialPageRoute(
          builder: builder,
          settings: settings,
        );
      },
    );
  }
}

// ----------------------------------------------------------

class FirstScreen extends StatefulWidget {
  FirstScreen({Key? key}) : super(key: key);

  @override
  _FirstScreenState createState() => _FirstScreenState();
}

class _FirstScreenState extends State<FirstScreen> {
  @override
  void initState() {
    WidgetsBinding.instance?.addPostFrameCallback((_) {
      Navigator.of(context).pushNamed('/screen2');
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold();
  }
}

// ----------------------------------------------------------

class SecondScreen extends StatefulWidget {
  @override
  _SecondScreenState createState() => _SecondScreenState();
}

class _SecondScreenState extends State<SecondScreen>
    with RouteAware, WidgetsBindingObserver {
  FocusNode? focusNode;

  ValueNotifier<String>? _stringValueNotifier;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addObserver(this);
    this._stringValueNotifier = ValueNotifier<String>('');
    this._stringValueNotifier!.addListener(() {});
  }

  @override
  void dispose() {
    _stringValueNotifier?.dispose();

    WidgetsBinding.instance!.removeObserver(this);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    this.focusNode = FocusNode();

    return Scaffold(
      body: KeyboardContent(
        focusNode: this.focusNode!,
        stringValueNotifier: this._stringValueNotifier!,
      ),
    );
  }
}

// ----------------------------------------------------------

class KeyboardContent extends StatelessWidget {
  final FocusNode focusNode;
  final ValueNotifier<String> stringValueNotifier;

  /// A container for an on-screen keyboard
  /// The widget automatically gets rebuilt on value change, triggered
  /// when a keyboard button is pressed.
  KeyboardContent({
    required this.focusNode,
    required this.stringValueNotifier,
  });

  KeyboardActionsConfig _buildConfig(BuildContext context) {
    List<Widget Function(FocusNode)> toolbarButtons = [];

    return KeyboardActionsConfig(
        keyboardActionsPlatform: KeyboardActionsPlatform.ALL,
        keyboardBarColor: Colors.grey[200]!,
        //nextFocus: false,
        actions: [
          KeyboardActionsItem(
            focusNode: focusNode,
            displayActionBar: false,
            displayDoneButton: false,
            toolbarButtons: toolbarButtons,
            footerBuilder: (_) => CueKeyboard(),
          )
        ]);
  }

  @override
  Widget build(BuildContext context) {
    if (!focusNode.hasPrimaryFocus) focusNode.requestFocus();
    return Container(
      decoration: BoxDecoration(color: Colors.blue),
      child: KeyboardActions(
        config: _buildConfig(context),
        child: Container(
          padding: EdgeInsets.only(left: 15, right: 15),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              KeyboardCustomInput<String>(
                focusNode: focusNode,
                notifier: stringValueNotifier,
                builder: (context, keyboardTapVal, hasFocus) {
                  return Container(
                      margin: EdgeInsets.only(top: 100),
                      height: 800,
                      width: 100,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(32.0),
                          color: Colors.green));
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class CueKeyboard extends StatefulWidget implements PreferredSizeWidget {
  static final double _keyboardHeight = 184.0;

  CueKeyboard({
    Key? key,
  }) : super(key: key);

  @override
  _CueKeyboardState createState() => _CueKeyboardState();

  @override
  Size get preferredSize => Size.fromHeight(CueKeyboard._keyboardHeight);
}

class _CueKeyboardState extends State<CueKeyboard> {
  dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Wrap(
      children: [
        Column(
          children: [Text("Keyboard")],
        ),
      ],
    );
  }
}

flutter doctor
$ flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 2.8.1, on Microsoft Windows [Version 10.0.19044.1466], locale en-GB)
[√] Android toolchain - develop for Android devices (Android SDK version 32.0.0)
[√] Chrome - develop for the web
[√] Android Studio (version 2020.3)
[√] VS Code (version 1.63.2)
[√] Connected device (4 available)

• No issues found!

flutter run --verbose
$ flutter run --verbose
[  +53 ms] executing: [C:\flutter/] git -c log.showSignature=false log -n 1 --pretty=format:%H
[  +84 ms] Exit code 0 from: git -c log.showSignature=false log -n 1 --pretty=format:%H
[        ] 77d935af4db863f6abd0b9c31c7e6df2a13de57b
[        ] executing: [C:\flutter/] git tag --points-at 77d935af4db863f6abd0b9c31c7e6df2a13de57b
[  +24 ms] Exit code 0 from: git tag --points-at 77d935af4db863f6abd0b9c31c7e6df2a13de57b
[        ] 2.8.1
[   +6 ms] executing: [C:\flutter/] git rev-parse --abbrev-ref --symbolic @{u}
[  +15 ms] Exit code 0 from: git rev-parse --abbrev-ref --symbolic @{u}
[        ] origin/stable
[        ] executing: [C:\flutter/] git ls-remote --get-url origin
[  +11 ms] Exit code 0 from: git ls-remote --get-url origin
[        ] https://github.com/flutter/flutter.git
[  +70 ms] executing: [C:\flutter/] git rev-parse --abbrev-ref HEAD
[  +14 ms] Exit code 0 from: git rev-parse --abbrev-ref HEAD
[        ] stable
[  +47 ms] Artifact Instance of 'AndroidGenSnapshotArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'AndroidInternalBuildArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'IOSEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'FlutterWebSdk' is not required, skipping update.
[   +7 ms] Artifact Instance of 'WindowsEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'WindowsUwpEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'MacOSEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'LinuxEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'LinuxFuchsiaSDKArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'MacOSFuchsiaSDKArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'FlutterRunnerSDKArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'FlutterRunnerDebugSymbols' is not required, skipping update.
[  +48 ms] executing: C:\Users\md844\Android\SDK\platform-tools\adb.exe devices -l
[  +40 ms] List of devices attached
           emulator-5554          device product:sdk_phone_x86 model:Android_SDK_built_for_x86 device:generic_x86 transport_id:11
[   +6 ms] C:\Users\md844\Android\SDK\platform-tools\adb.exe -s emulator-5554 shell getprop
[  +33 ms] Artifact Instance of 'AndroidInternalBuildArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'IOSEngineArtifacts' is not required, skipping update.
[   +2 ms] Artifact Instance of 'WindowsEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'WindowsUwpEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'MacOSEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'LinuxEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'LinuxFuchsiaSDKArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'MacOSFuchsiaSDKArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'FlutterRunnerSDKArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'FlutterRunnerDebugSymbols' is not required, skipping update.
[  +66 ms] Skipping pub get: version match.
[  +40 ms] Found plugin integration_test at C:\flutter\packages\integration_test\
[  +82 ms] Found plugin integration_test at C:\flutter\packages\integration_test\
[   +6 ms] Generating C:\Users\md844\source\repos\ucue_keyboard_bug\android\app\src\main\java\io\flutter\plugins\GeneratedPluginRegistrant.java
[  +41 ms] ro.hardware = ranchu
[  +13 ms] Using hardware rendering with device Android SDK built for x86. If you notice graphics artifacts, consider enabling software rendering with
"--enable-software-rendering".
[  +24 ms] Initializing file store
[   +9 ms] Skipping target: gen_localizations
[   +4 ms] gen_dart_plugin_registrant: Starting due to {InvalidatedReasonKind.inputChanged: The following inputs have updated contents:
C:\Users\md844\source\repos\ucue_keyboard_bug\.dart_tool\package_config_subset}
[  +23 ms] Found plugin integration_test at C:\flutter\packages\integration_test\
[   +2 ms] gen_dart_plugin_registrant: Complete
[   +1 ms] Skipping target: _composite
[   +2 ms] complete
[   +4 ms] Launching lib\main.dart on Android SDK built for x86 in debug mode...
[   +3 ms] C:\flutter\bin\cache\dart-sdk\bin\dart.exe --disable-dart-dev C:\flutter\bin\cache\artifacts\engine\windows-x64\frontend_server.dart.snapshot --sdk-root
C:\flutter\bin\cache\artifacts\engine\common\flutter_patched_sdk/ --incremental --target=flutter --debugger-module-names --experimental-emit-debug-metadata
-DFLUTTER_WEB_AUTO_DETECT=true --output-dill C:\Users\md844\AppData\Local\Temp\flutter_tools.f728f2b7\flutter_tool.9d976d\app.dill --packages
C:\Users\md844\source\repos\ucue_keyboard_bug\.dart_tool\package_config.json -Ddart.vm.profile=false -Ddart.vm.product=false --enable-asserts --track-widget-creation
--filesystem-scheme org-dartlang-root --initialize-from-dill build\c075001b96339384a97db4862b8ab8db.cache.dill.track.dill --enable-experiment=alternative-invalidation-strategy
[   +7 ms] executing: C:\Users\md844\Android\SDK\build-tools\32.0.0\aapt dump xmltree C:\Users\md844\source\repos\ucue_keyboard_bug\build\app\outputs\flutter-apk\app.apk
AndroidManifest.xml
[   +8 ms] Exit code 0 from: C:\Users\md844\Android\SDK\build-tools\32.0.0\aapt dump xmltree C:\Users\md844\source\repos\ucue_keyboard_bug\build\app\outputs\flutter-apk\app.apk
AndroidManifest.xml
[        ] N: android=http://schemas.android.com/apk/res/android
             E: manifest (line=2)
               A: android:versionCode(0x0101021b)=(type 0x10)0x1
               A: android:versionName(0x0101021c)="0.0.1" (Raw: "0.0.1")
               A: android:compileSdkVersion(0x01010572)=(type 0x10)0x1d
               A: android:compileSdkVersionCodename(0x01010573)="10" (Raw: "10")
               A: package="uk.co.cuedspeech.ucue.debug" (Raw: "uk.co.cuedspeech.ucue.debug")
               A: platformBuildVersionCode=(type 0x10)0x1d
               A: platformBuildVersionName=(type 0x10)0xa
               E: uses-sdk (line=7)
                 A: android:minSdkVersion(0x0101020c)=(type 0x10)0x17
                 A: android:targetSdkVersion(0x01010270)=(type 0x10)0x1e
               E: uses-permission (line=14)
                 A: android:name(0x01010003)="android.permission.INTERNET" (Raw: "android.permission.INTERNET")
               E: application (line=22)
                 A: android:label(0x01010001)="uCUE" (Raw: "uCUE")
                 A: android:icon(0x01010002)=@0x7f080000
                 A: android:name(0x01010003)="io.flutter.app.FlutterApplication" (Raw: "io.flutter.app.FlutterApplication")
                 A: android:debuggable(0x0101000f)=(type 0x12)0xffffffff
                 A: android:extractNativeLibs(0x010104ea)=(type 0x12)0x0
                 A: android:appComponentFactory(0x0101057a)="androidx.core.app.CoreComponentFactory" (Raw: "androidx.core.app.CoreComponentFactory")
                 E: activity (line=29)
                   A: android:theme(0x01010000)=@0x7f0a0000
                   A: android:name(0x01010003)="uk.co.cuedspeech.ucue.MainActivity" (Raw: "uk.co.cuedspeech.ucue.MainActivity")
                   A: android:launchMode(0x0101001d)=(type 0x10)0x1
                   A: android:configChanges(0x0101001f)=(type 0x11)0x40003fb4
                   A: android:windowSoftInputMode(0x0101022b)=(type 0x11)0x10
                   A: android:hardwareAccelerated(0x010102d3)=(type 0x12)0xffffffff
                   E: meta-data (line=43)
                     A: android:name(0x01010003)="io.flutter.embedding.android.NormalTheme" (Raw: "io.flutter.embedding.android.NormalTheme")
                     A: android:resource(0x01010025)=@0x7f0a0001
                   E: meta-data (line=53)
                     A: android:name(0x01010003)="io.flutter.embedding.android.SplashScreenDrawable" (Raw: "io.flutter.embedding.android.SplashScreenDrawable")
                     A: android:resource(0x01010025)=@0x7f040002
                   E: intent-filter (line=57)
                     E: action (line=58)
                       A: android:name(0x01010003)="android.intent.action.MAIN" (Raw: "android.intent.action.MAIN")
                     E: category (line=60)
                       A: android:name(0x01010003)="android.intent.category.LAUNCHER" (Raw: "android.intent.category.LAUNCHER")
                 E: meta-data (line=67)
                   A: android:name(0x01010003)="flutterEmbedding" (Raw: "flutterEmbedding")
                   A: android:value(0x01010024)=(type 0x10)0x2
[   +8 ms] executing: C:\Users\md844\Android\SDK\platform-tools\adb.exe -s emulator-5554 shell -x logcat -v time -t 1
[  +13 ms] <- compile package:ucue_keyboard_bug/main.dart
[  +55 ms] --------- beginning of main

[...]

[  +49 ms] --------- beginning of main
           01-30 13:39:27.586 I/cmd     (25596): oneway function results will be dropped but finished with status OK and parcel size 4
[   +6 ms] executing: C:\Users\md844\Android\SDK\platform-tools\adb.exe -s emulator-5554 shell am start -a android.intent.action.RUN -f 0x20000000 --ez
enable-background-compilation true --ez enable-dart-profiling true --ez enable-checked-mode true --ez verify-entry-points true
uk.co.cuedspeech.ucue.debug/uk.co.cuedspeech.ucue.MainActivity
[  +34 ms] Starting: Intent { act=android.intent.action.RUN flg=0x20000000 cmp=uk.co.cuedspeech.ucue.debug/uk.co.cuedspeech.ucue.MainActivity (has extras) }
[   +1 ms] Waiting for observatory port to be available...
[ +360 ms] W/FlutterActivityAndFragmentDelegate(25618): A splash screen was provided to Flutter, but this is deprecated. See flutter.dev/go/android-splash-migration for migration
steps.
[  +21 ms] Observatory URL on device: http://127.0.0.1:39329/Bg_xE12sSvQ=/
[        ] executing: C:\Users\md844\Android\SDK\platform-tools\adb.exe -s emulator-5554 forward tcp:0 tcp:39329
[  +16 ms] 60159
[        ] Forwarded host port 60159 to device port 39329 for Observatory
[   +4 ms] Caching compiled dill
[  +24 ms] Connecting to service protocol: http://127.0.0.1:60159/Bg_xE12sSvQ=/
[ +252 ms] Launching a Dart Developer Service (DDS) instance at http://127.0.0.1:0, connecting to VM service at http://127.0.0.1:60159/Bg_xE12sSvQ=/.
[ +116 ms] DDS is listening at http://127.0.0.1:60162/57G22rjDLdI=/.
[  +43 ms] Successfully connected to service protocol: http://127.0.0.1:60159/Bg_xE12sSvQ=/
[  +56 ms] DevFS: Creating new filesystem on the device (null)
[  +32 ms] DevFS: Created new filesystem on the device (file:///data/user/0/uk.co.cuedspeech.ucue.debug/code_cache/ucue_keyboard_bugULKJZB/ucue_keyboard_bug/)
[   +2 ms] Updating assets
[  +67 ms] Syncing files to device Android SDK built for x86...
[   +1 ms] <- reset
[        ] Compiling dart to kernel with 0 updated files
[   +2 ms] <- recompile package:ucue_keyboard_bug/main.dart 027f4494-050d-4ec8-becc-6f960203b371
[        ] <- 027f4494-050d-4ec8-becc-6f960203b371
[ +114 ms] Updating files.
[        ] DevFS: Sync finished
[        ] Syncing files to device Android SDK built for x86... (completed in 120ms)
[        ] Synced 0.0MB.
[   +1 ms] <- accept
[   +3 ms] Connected to _flutterView/0xe290b860.
[   +2 ms] Flutter run key commands.
[   +1 ms] r Hot reload.
[        ] R Hot restart.
[        ] h List all available interactive commands.
[        ] d Detach (terminate "flutter run" but leave application running).
[        ] c Clear the screen
[        ] q Quit (terminate the application on the device).
[        ]  Running with sound null safety
[        ] An Observatory debugger and profiler on Android SDK built for x86 is available at: http://127.0.0.1:60162/57G22rjDLdI=/
[ +491 ms] I/eech.ucue.debu(25618): Waiting for a blocking GC ProfileSaver
[ +242 ms] The Flutter DevTools debugger and profiler on Android SDK built for x86 is available at: http://127.0.0.1:9101?uri=http://127.0.0.1:60162/57G22rjDLdI=/

pubspec.yaml
name: ucue_keyboard_bug
description: Demo app showing the keyboard bug when time dialation=3

publish_to: 'none' # Remove this line if you wish to publish to pub.dev
version: 0.0.1+1

environment:
  sdk: '>=2.12.0-0 <3.0.0'

dependencies:
  flutter:
    sdk: flutter
  flutter_localizations:
    sdk: flutter
  keyboard_actions: ^3.4.0
  pedantic:
  uuid: ^3.0.1

# Temporary dependencies
dependency_overrides:

dev_dependencies:
  flutter_test:
    sdk: flutter
  integration_test:
    sdk: flutter

analyzer:
  strong-mode: true
  language:
    enableSuperMixins: true

# The following section is specific to Flutter.
flutter:
  uses-material-design: true


text:
Q: show options in select tag when a specific option is selected in other select tag from json I have 3 select tags in my HTML document , and when i select 1st option from the 1st select tag, i want to show some other options in the second select tag which is hidden, but i need to load those options from external file like json.
how can i do this ?
for e.x i have this object
var object = {
    usa: {
        californina: ['san fransisco',
                       'san diego'
        ],nevada: ['las vegas',
                    'reno']
     }
}

when i select usa option in the 1st select tag, i want to show the states (california,nevada) in the second select box, and when i choose nevada option i want to show the city(las vegas, reno) in the 3d select tag!
i want all those options to be kept in external json file!
how can i load the json file?

A: Having a json like this: {"resource":"A","literals":["B","C","D"]} and taking account you want read a external JSON file, you can follow the different answers for this post: How to read an external local JSON file in Javascript.
After you read the information that you need, you can or append the options to your(s) select(s) (What is the best way to add options to a select from an array with jQuery?) or replace all the option and append again(How to remove and replace select options using jquery?)
Probably, you want add some events to do something after the user select an option. For that, use this post jquery select change event get selected option
I hope this will help you,
Best Regards


text:
Q: The set of subgroups of $F_2$ This question came up in our algebraic topology class and our Professor didn't know the answer. I also couldn't find an answer so far.

What is the cardinality of the set of subgroups of $F_2$?

Here $F_2 = \mathbb Z * \mathbb Z$ denotes the free group on two generators. The cardinality of the set of subgroups is clearly bounded below by $\aleph_0$ (as $F_2$ contains subgroups of all countable ranks) and above by $2^{\aleph_0}$.

A: It is clear that there are $2^{\aleph_0}$ subgroups of the free group $F_\infty$ on countably many generators (because each subset of a free generating set generates a different subgroup). In addition, it is well known that $F_2$ contains a subgroup that is not finitely generated. Since all subgroups of a free group are free, this subgroup is isomorphic to $F_\infty$. Then every subgroup of this $F_\infty$ is also a subgroup of $F_2$, which means that $F_2$ has $2^{\aleph_0}$ subgroups. (However, this simple argument does not prove Andy Putman's stronger statement that there are $2^{\aleph_0}$ normal subgroups.)


text:
Q: Getting Tap/Touch Position when selecting a TableView cell hope to get some help here because this is something that really makes me mad...
I have a view with a tableView, and when I tap a cell I want to present a popOver window pointing the arrow to the cell I tapped.
the things that I think I need is:
1- the position of the cell in the screen (not in the view, because on large tables the Y value of the cell's rect could be grater than screen hight)
or
2- a CGPoint or something similar that represents the point in the screen I tapped.
I can't figured this out, and makes me really mad!!!
Any help will very very very very usefull.
Have a nice day.

A: Take a look at the UIView method convertPoint:toView: (using nil as the toView argument).
If I trigger a UIPopoverController from a cell tap, I usually just have it come from the cell, thus:
[popover presentPopoverFromRect:cell.frame inView:cell permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];

A: Thank you Paull!!! the UIView method you recommend is very useful.. but I really didn't use it :D.
You give me an idea when passing the cell as the view to present the popover, I was using "self.view", and I've changed it to self.tableView and it works perfect! jeje
Thank you so much!!!
You're the SH@# ;)


text:
Q: Having Trouble Making a Button in Xamarin.Mac/XCode-Storyboard Let me start off by saying I am new to XCode, but already very experienced in C#. I am having trouble getting the outlet for this button, and every time I try to Control drag it under ViewControl it only lets me do action! I have been googling for about 3 hours and trying to find tutorials, but everyone else's code looks different by default :(

A: You are trying to drag into the ViewController.m file, you need to be in the header file (ViewController.h) to create an Outlet.
Change the file being edited:

Now Ctrl-Drag into the .h file:


text:
Q: using group by in oracle not for count(*) but for min() function how to use group by for 3 columns it is showing an error that it is not a group by expression.
here is the query.
select
   brewer.name as brewer,beer.name as beer,count(ratings.score) as LowestRating
from ratings,beer,brewer
where ratings.beer=beer.id and beer.brewer=brewer.id
group by brewer,beer;

A: You should GROUP BY by columns, not whole tables:
select
     brewer.name as brewer,
     beer.name as beer,
     count(ratings.score) as LowestRating
  from
    ratings,
    beer,
    brewer
where
  ratings.beer = beer.id
  and beer.brewer = brewer.id
group by brewer.name, beer.name;


text:
Q: Authenticated routes with React and PassportJS I am using the following stack :

*

*React

*React router v4

*PassportJS

*NodeJS backend with Express and
Express session

I have successfully setup PassportJS based login and registration authentication. All pages in my app are protected routes - they can only be viewed by a logged in user.
So, my question is, for each route, how do I check if the user is currently logged in or not. I understand that express session provides server-side session management, but I'm wondering if there's a way to avoid making an API request to the backend on each page load to verify if the session of the current user exists.
My App.js file:
import React, { Component } from 'react';
import './App.css';
import { BrowserRouter, Route, Switch, Link } from 'react-router-dom';
import AsyncAuthPage from 'components/AsyncAuthPage/index.js'

const NoMatch = () => (

Path not found

);

const HomePage = () => (

WELCOME!

);

class App extends Component {
  render() {
    return (

      <BrowserRouter>
        <Switch>
          <Route path="/login" component = {AsyncAuthPage} />
          <Route path="/home" component = {HomePage} />
          <Route path="*" component={NoMatch} />
        </Switch>
        </BrowserRouter>

    );
  }
}

export default App;

The AsyncAuthPage component implements PassportJS based authentication. In the above sample, I would like to protect Homepage route with authentication. How can this be done? After a user has successfully logged in, the following needs to be taken care of :

*

*The parent App.js needs to know that login was successful

*All pages should try to avoid making an API call to the backend (on
componentDidMount or page load) as much as possible, to verify if current user is logged in.

*Should work on page reload too


text:
Q: ResultConsumedException with Micronaut and Neo4j: Cannot access records on this result any more as the result has already been consumed I'm attempting to get a simple app working with Micronaut 1.3.5 and Neo4J 4.0.0. I'm using the io.micronaut.configuration:micronaut-neo4j-bolt:2.0.0 driver. I have code like this:
public Stream<Map<String, Object>> findAll() {
   try (Session s = driver.session()) {
       String stmt = "MATCH (n:Product) RETURN n";
       return s.readTransaction(tx -> tx.run(stmt)).list(r -> r.asMap()).stream();
   }
}

And I'm getting the following exception:
result has already been consumed or the query runner where the result is created has already been closed.
org.neo4j.driver.exceptions.ResultConsumedException: Cannot access records on this result any more as the result has already been consumed or the query runner where the result is created has already been closed.

I've done some googling and found a few things that would suggest this is normal behavior, but nothing that discusses the actual solution. I'm assuming it has something to do with the async nature of the driver/session.

A: The way that would work is,
Stream<Map<String, Object>> stream = s.readTransaction(tx -> {
    Result result = tx.run(stmt);
    return result.list(r -> r.asMap()).stream();
 });

The results need to be processed within the readTransaction
There are bunch of examples at https://github.com/neo4j/neo4j-java-driver/tree/4.1/examples/src/main/java/org/neo4j/docs/driver which you may find useful


text:
Q: Using Convolution neural network for semantic image segmentation I am naive to python and this is my first attempt so please bear with me if my question seems to be too basic.
I would like to use convolutional neural network to perform semantic segmentation to 9 satellite images.
I have so far been successful in importing the images one by one and converting them to grayscale.
I would like to do the following process :
convolution- 16 filters, 33 filter size
pooling- 22 filter size
output- 4 classes
testing and validation 80:20
any lead on this could be helpful. kindly guide !

A: Here is the code, only the model part:
import tensorflow as tf
from tensorflow.keras import Conv2D, Dense, Flatten, MaxPool2D

# Declare your desired things here
num_filter=32
kernel_size=(3,3)
strides=(1,1)
padding="valid"
input_shape=(width,height,channel)

model = tf.keras.Sequential([
   Conv2D(num_filter, kernel_size, strides=strides, input_shape=input_shape),
   MaxPool2D(),
   Flatten(),
   Dense(4, activation="softmax")
])

Here is a useful link: ConvNet TensorFlow guide


text:
Q: taglib-ruby how to add and edit tags via active storage? I am trying to build an application where I can upload mp3s and pull the current meta data info and change it and write to it if need be. Taking it one step at a time how do I simply read the meta data in when a song is created?
The song model has_many_attached :files
The files upload to the public/uploads directory. I'm at a loss at this point in hwo to do the rest with taglib-ruby.

A: It might make more sense to use an API for your application, and you'll have less effort.


text:
Q: Android hide list item and remove space ( release space ) I have a list view with headers. In my list view I have two header and under each header I have items. What I want to do is to hide items when user clicked on header. And on click that header again the items will be visible. I have an interface and then model classes which implements this interface for both header and data. I have hide the items but unable to hide space. Here is my code of onListItemClick().
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    UserAddress userAddress = (UserAddress) parent.getItemAtPosition(position);
                    if (userAddress instanceof LocationHeader) {
                        for (int i = 0; i < getListView().getCount(); i++) {
                            View listItemView = getListView().getChildAt(i);
                            if (listItemView.findViewById(R.id.tv_list_header) != null) {

                            } else {

                                if (listItemView.getVisibility() == View.VISIBLE) {
                                    listItemView.setVisibility(View.GONE);

                                } else {
                                    listItemView.setVisibility(View.VISIBLE);
                                     listItemView.setVisibility(View.GONE);

                                }
                            }

                        }
                    }

I have also tried to get the main layout of my adapter items and hide it. But it also worked the same way. Also tried this and this ,but same result. I do not want to remove items , and refill them again. Is there any way around? or I have to do this remove and add approach ? Any help would be highly appreciated. Thanks


text:
Q: Search variable code to know the stop-loss of our trade of the day Search variable code to know the stop-loss of our trade of the day
It is not for a strategy but an indicator
Could you help me?
Thank you very much
I did not see anything in the pinescript tutorials that matched

A: No, in pinescript you can't retrieve the value of the stop loss used until you record it before enter the trade.


text:
Q: Minimizar janela jfx Minha janela está sem as bordas do sistema.
primaryStage.initStyle(StageStyle.UNDECORATED);

Criei um botão para minimizar a janela mas encontro exception ao atribuir para a minha stage:
@FXML
void btnMinimizarOnAction(ActionEvent event) throws IOException
{
    Stage stage = (Stage) btnMinimizar.getScene().getWindow();
    stage.setIconified(true);
}

Existe alguma outra forma de fazer isso?

A: Podem existir maneiras diferentes de obter o Stage, mas o método setIconified(true) deve ser chamado.


text:
Q: jQuery: I dont understand what "i" is in .each(function(i) I'm trying to understand this jquery code, I understand all of it: the modulo, loop etc., except for what "i" means in .each(function(i). I've tried searching but this code doesn't return good search results. Does it represent each img that has an id of #photos? If so isn't that the same as the variable currentPhoto. Any help with understanding this or a link to useful info would be greatly appreciated.
function rotatePics(currentPhoto) {  //number is index of current photo
  var numberOfPhotos = $('#photos img').length;
  currentPhoto = currentPhoto % numberOfPhotos;

  $('#photos img').eq(currentPhoto).fadeOut(function() {
    // re-order the z-index
$('#photos img').each(function(i) {
  $(this).css(
    'zIndex', ((numberOfPhotos - i) + currentPhoto) % numberOfPhotos
  );
});
$(this).show();
setTimeout(function() {rotatePics(++currentPhoto);}, 4000);
  });
}

Thanks in advance!
Edit:
In case anyone going through the jquery: novice to ninja book has the same doubts:
(i) is 0 based and currentPhoto is 1 based, so for example the 1st img element would look like this(assuming there are 6 photos total):
((6        -       0) +      1        %     6
((numberOfPhotos - i) + currentPhoto) % numberOfPhotos

always adding 1 makes sure the remainder is always 1, thus making sure that the z-index is always 1.
Thanks for everybodies help!

A: i is the index position of the current element within the jquery collection

A: The definition might help.

A: each() function is documented here http://api.jquery.com/each/
By using jquery selectors you will have a list of objects, and i will be the index of these elements in dom creation order.

A: 'i' should represent the index within the loop.


text:
Q: How to increase the length of a TextField while pressing "Enter" in Flutter? I have a textfield of maxLength set to 150. However, I want to textField's maxLine property to increase by 1 as I press enter. How can I achieve this please?
Find my code below:
child: Padding(
                      padding: const EdgeInsets.all(20.0),
                      child: TextField(
                        maxLines: 5,
                        maxLength: 150,
                        controller: _userAboutController,
                        decoration: InputDecoration(
                          helperText: '(Optional)',
                          labelText: user.about,
                          icon: Image.asset(
                            "Assets/images/country.png",
                            height: 40.0,
                          ),
                          focusedBorder: UnderlineInputBorder(
                            borderSide:
                            BorderSide(color: secondaryColor, width: 2.0),
                          ),
                      ),
                    ),
                  ),

A: *

*Declare  int maxLines = 5

*When enter pressed, add increment for maxLines.
maxLines ++;

*Finally change textField
maxLines: 5 to maxLines ;


text:
Q: Dynamic String Size I am trying to decode a base64 encoded string.
I wrote the following piece of code for that:
String bytesEncoded = "rO0ABXNyADZ6YS5jby5zYi5wYXltZW50cy50by5pbnN0cnVjdGlvbi5CYXRjaEZpbGVVcGxvYWRD"
+ "UlVEVE8dnJ9z1jdsQwIAB0wAEGFic29sdXRlUGF0aE5hbWV0ABJMamF2YS9sYW5nL1N0cmluZztM"
+ "AAliYXRjaFR5cGVxAH4AAUwAFmN1c3RvbWVyUGF5bWVudFR5cGVLZXl0ABBMamF2YS9sYW5nL0xv"
+ "bmc7TAAhZW5jb2RlZEJ5dGVTdHJlYW1QYXltZW50QmF0Y2hGaWxlcQB+AAFMAAhmaWxlTmFtZXEA"
+ "fgABTAAIZmlsZVR5cGVxAH4AAUwABmlzc3Vlc3QAJEx6YS9jby9zYi9jb3JlL2NvbW1vbi90by9J"
+ "c3N1ZUxvZ1RPO3hyAB96YS5jby5zYi5jb3JlLnRvLkFic3RyYWN0Q1JVRFRP9ka5cD8D+JUCAAJK"
+ "AA12ZXJzaW9uTnVtYmVyTAAGYWN0aW9ucQB+AAF4cP//////////dAAGdXBsb2FkdACYQzpcbkJv"
+ "bF9Mb2FkVGVzdGluZ1xQZXJmb3JtYW5jZVRlc3RpbmdcbkJPTFxDVkFcUmVsZWFzZTE1XE1pc2Mg"
+ "RG9jc1xGaWxlcyBmb3IgVXBsb2FkXG5Cb2wgUHJvcCBSMTMtIERvbWVzdGljIGFkaG9jIDA4MDgy"
+ "MDE0IFRhbnphbmlhQmVuMiBWYWxpZCBQZXJmMi54bWx0AAdQYXltZW50c3IADmphdmEubGFuZy5M"
+ "b25nO4vkkMyPI98CAAFKAAV2YWx1ZXhyABBqYXZhLmxhbmcuTnVtYmVyhqyVHQuU4IsCAAB4cAAA"
+ "AAAAJKWidANsSDRzSUFBQUFBQUFBQU1WVlhXL1RNQlI5UitJL1JIMHZUanNZcmVSbFN0TU5LcUZS"
+ "MnNJUWIzZk9YV3Nwc1lmamxKVmZqeE5ucVowR05DUWtwS3J4T2ZmNmZweHJKL1R5TWMrQ1BhcUNT"
+ "M0V4R0wwS0J3RUtKbE11dGhlRHo1dnI0V1FRRkJwRUNwa1VlREVRY25BWnZYeEJaNkRaTHFKSldX"
+ "aVpvNnJoQ3UrakZXWUlCUVliRUQ5QmNBakNTVGdaaDZQWHdSTFZmVENtNUdRTFhZaENxNUpwVThJ"
+ "eG9rTldUZzRjaG1FNE9zYnBPTklPTnM0bS9URDVGdHR0WGZjVmZpKzV3dlRxRVZsWnNYUFFHRlVW"
+ "RDhPSitWSFM3MEdYU2pJc0NpUFV4d2RiK2tQTDNFQ08wUnJWbmpQOGdIdk1LT2tZSGVjdmtKVVkz"
+ "VWlWZytkbmVVcE9FeVU3VUZzc1pnZ0tWYlIrSHhzMVBJcHVGSWdDT3BJNlpLT01JMlBINkViWUhC"
+ "NHdtbFBTcFdnaVM2RlJMVUhwUTcySm5EQlhqMndIWW91cldqUGl3eWVVU0tHVkNXeGo5TEtmU3Fu"
+ "aEtEN3A0QmE2cG9qR2pGVUZtVzdxZW9sOTJBRVErMGptaTVzeXY2dEVJODY2MmRuQWFYaHUxQXFu"
+ "MC9Fb1BLZkVOOUxGSFZSNW0wZWI4K21rWVJybk5lT2N2cGF6T3QralNrcWx6TTA3UkxQYlpTTzF5"
+ "M3JxUDMrK3c3OGJjdktNSVF1K1JjV2haOVpMT09Rb3pMeWdxQWZSd2Y5MkdLT3o2ZmpOMlg4YWh0"
+ "dTZpWjFXQ2RPbWw3a1J1dENjeGVsT3NxZkdsdEs4UkxNNFRaVzV5YVlodS9qQVJkVzdoOVphSWVw"
+ "R0ZSZllFSWxNNjNlQ0F6YnloMmo4ajh1NlFuVllsM2R6dnVlRnZSbDlaTU1kclczMHRscml0eHR2"
+ "c2RMcW1nc1FqRU5XeWNoMWFjK2lOODVqaEhiVkpHbmE4TkJza1VScjh6ZTdmZmVWa2dyUm1WR2U3"
+ "ZFpTNmRyRkRQN3MvSzJ4K1RRbC9iV1FwdEpGVlh5T0tRZDErR1B4ZFU2YjJldWpvMGV2NENlaS9h"
+ "YW1ubUw4cTAyOHp5R3hIOXBmc2pQKzlLZ0hBQUE9dABDbkJvbCBQcm9wIFIxMy0gRG9tZXN0aWMg"
+ "YWRob2MgMDgwODIwMTQgVGFuemFuaWFCZW4yIFZhbGlkIFBlcmYyLnhtbHBw";

byte[] decodedBytes = Base64.decodeBase64(bytesEncoded);
System.out.println("decodedBytes " + new String(decodedBytes));

The output that i get for this shows as below:
System.out: decodedBytes '

Now my issue is, i want to know if this is due to variable length. If yes is there a way to increase the length?
I am new to java and did this by searching from internet. Please ignore if i am being very naive.
I tried to just convert a part of the encoded string (just the last line. shown below) and it showed me the string properly.
String bytesEncoded = "YWRob2MgMDgwODIwMTQgVGFuemFuaWFCZW4yIFZhbGlkIFBlcmYyLnhtbHBw";

byte[] decodedBytes = Base64.decodeBase64(bytesEncoded);
System.out.println("decodedBytes " + new String(decodedBytes));

Output for the same below:
System.out: decodedBytes adhoc 08082014 TanzaniaBen2 Valid Perf2.xmlpp

A: The decoded bytes simply don't denote a string in the default character encoding (which may vary from platform to platform).
It could be it doesn't even denote a string at all (which seems likely in your case). But if so, you should always specify the encoding explicitly like this:
String s = new String(bytesDecoded, charsetName);
// or
String s = new String(bytesDecoded, charset);

The constructor of String can take any length of a byte array, that is not the problem.
Here's an example that charset matters:
String s = "Hi éáű!";
Systme.out.println(s); // Prints "Hi éáű!" obviously

byte[] b = s.getBytes(StandardCharsets.UTF_8);

// Next line also prints "Hi éáű!", charsets match:
System.out.println(new String(b, StandardCharsets.UTF_8));

// Next line prints "Hi éáű!", decoded with a different charset!
System.out.println(new String(b, StandardCharsets.ISO_8859_1));

Also note that the String constructor does not interpret BOM sequences (e.g. if your decoded byte array starts with a byte order mark sequence, it will not be processed properly but interpreted as bytes of the string).

A: The byte block you are trying to convert is definitely not a string of text, but binary data of some kind.
It contains multiple 0-valued bytes, which usually denote a string terminator and that's the reason why your original code only shows two characters.

A: Use apache commons Codec. It has a Base64 class.
use it like so:
import org.apache.commons.codec.binary.Base64;
[..]
byte[] decoded = Base64.decodeBase64(base64string);

Maven artifact:
<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.9</version>
</dependency>

A: Since the decoded bytes actually contain a binary file (with small text parts), you probably do not mean to treat the decoded bytes as encoded text characters, which is what String(byte[]) will do for you.
Instead you may want to print only the printable characters (by printing out the bytes char-by-char, and testing each char to see if it's displayable), like described in this topic or by displaying it as a string of hexadecimal characters, like described in this topic