text:
Q: getting no resource identifier found error I'm trying to compile iven-feed-reader project, but in the Android manifest file I keep getting this error:
Error:(16) No resource identifier found for attribute 'roundIcon' in package 'android'

Android manifest.xml:
 <application
    android:allowBackup="false"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:theme="@style/Theme_iven" >
    <uses-library
        android:name="com.sec.android.app.multiwindow"
        android:required="false" />

Usually i try to rebuild/clean project to fix this error but it's not working this time.
Below are the dependencies i'm using
compile 'com.android.support:appcompat-v7:24.0.0'
compile 'org.jsoup:jsoup:1.10.2'
compile 'com.android.support:support-v4:24.0.0'
compile 'com.github.bumptech.glide:glide:3.7.0'

How to fix this error?

A: Have you added this below line in your manifest tag ?
xmlns:android="http://schemas.android.com/apk/res/android"


text:
Q: GDB layer not loading properly Working in v10.3, I have a .gdb with two layers; a point layer and an annotation layer. The dataset was handed to me a few days ago, and I have been editing and adding points to the point layer daily. But now, the layer doesn't load properly; all data point seem to plot on the map, but the attribute table is only showing 59 of 82 records, I get an error message when I add a definition query ("Error reading OID from table. Reading rows has been stopped. Check that the datasource is valid."). Did I break it?
I tried bringing the layer into a blank map and exporting all the data points to another layer.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Simple Login implementation for Dojo MVC Is there any example on how to implement a simple login page/dialog? I have been trying to do it with dojo boilerplate (check my previous questions : Layout implementation for Dojo MVC). So far, I have been able to display my dialog box. But I want to be able to get my data and on click event want to have an alert box for example (with his content).
My view:
<form action="Login" method="post" validate="true" id="loginForm">

      Login
      <input class="cell" type="text" trim="true" dojoType="dijit.form.TextBox" value="" name="login" id="userId"/>

      Password
      <input class="cell" type="password" trim="true" dojoType="dijit.form.TextBox" value="" name="password" id="password"/>

            <button dojoType="dijit.form.Button" type="submit" id="LoginButton" onClick="connect">Ok</button>

            <button dojoType="dijit.form.Button" type="submit" onclick="document.Login.reset()" id="Cancel">Cancel</button>

            <button dojoType="dijit.form.Button" type="submit" onclick="showDialog();" id="resetPassword"> Show Dialog </button>

</form>

My Widget module/class
define([
    "dojo/_base/declare",
    "dijit/_Widget",
    "dijit/_TemplatedMixin",
    "dijit/_WidgetsInTemplateMixin",
    "dojo/text!app/views/Login/Login.html",
    "dijit/Dialog",
    "dijit/form/Button",
    "dijit/form/TextBox"
], function(
    declare,
    _Widget,
    _TemplatedMixin,
    _WidgetsInTemplateMixin,
    template,
    Dialog
){
    return declare([_Widget, _TemplatedMixin, _WidgetsInTemplateMixin, Dialog], {

        templateString: template
    });
});

Now, if you check the HTML the element id LoginButton should call in this case a "connection" function. Which should show (on an alert box) the username and password current input.
Where do I put my function? kind of...
    connect : function(){
    alert("username :" + dom.byId("userId").value()
+ "  Password: " + dom.byId("password").value());
    }

EDIT: New code
define([
    "dojo/_base/declare",
    "dijit/_Widget",
    "dojo/dom",
    "dijit/_TemplatedMixin",
    "dijit/_WidgetsInTemplateMixin",
    "dojo/text!app/views/Login/Login.html",
    "dijit/Dialog",
    "dijit/form/Button",
    "dijit/form/TextBox"
], function(
    declare,
    dom,
    _Widget,
    _TemplatedMixin,
    _WidgetsInTemplateMixin,
    template,
    Dialog
){
    return declare("login", [_Widget, _TemplatedMixin, _WidgetsInTemplateMixin, Dialog], {

        templateString: template,

        postCreate: function() {
           this.inherited(arguments);
           // make reference to widget from the node attachment
           this.submitButton = dijit.getEnclosingWidget(this.submitButtonNode);
           // override its onSubmit
           this.submitButton.onClick = function(){
             alert("username :" + dom.byId("userId").value()
                 + "  Password: " + dom.byId("password").value());
           };
        },
        // and a sample on how to implement widget-in-template stateful get/setter pattern
        // e.g. if submitbutton label should change on some event, call as such:
        // dijit.byId('loginForm').set("submitLabel", "Sendin login, please wait");
        _setSubmitLabelAttr : function(value) {
            return this.submitButton.set("label", value);
        },
        _getSubmitLabelAttr : function() {
            return this.submitButton.get("label");
        },
    });
});

My main.js:
define([ 'dojo/has', 'require', 'dojo/_base/sniff'], function (has, require) {
    var app = {};

    if (has('host-browser')) {

        require([ './views/Login', 'dojo/domReady!' ], function (Login) {
            app.login = new Login().placeAt(document.body);

            app.login.startup();

            // And now…
            app.login.show();
        });
    }
    else {
        console.log('Hello from the server!');
    }
});

A: I would like to add my solution: http://jsfiddle.net/phusick/tG8Sg/
It is a bit twisted due to constrains of jsFiddle, but the main principles are the same as I employ in my coding.
First of all, the login process (or any other form processing) is encapsulated inside the dialog and it communicate with the rest of the application thought emitting evens via dojo/Evented. This is how it works:
var loginDialog = new LoginDialog({ controller: loginController});
loginDialog.startup();
loginDialog.show();

loginDialog.on("cancel", function() {
    console.log("Login cancelled.");
});

loginDialog.on("error", function() {
    console.log("Login error.");
});

loginDialog.on("success", function() {
    console.log("Login success.");
    console.log(JSON.stringify(this.form.get("value")));
});

As you can see in the jsFiddle, there are two templates dialog-template and login-form-template which I assemble inside the LoginDialog constructor. The reason is I would normally have also a class wrapping dijit/form/Form to do some magic beyond standard dijit/form/Form validation and data serialization, but since login is simple and it'd be a mess in the single file of jsFiddle, I got rid of it. The advantage of separating a form from a dialog is you can use the same form (i.e. View) together with all the form ad hoc code somewhere else, e.g. in a ContentPane. The form is there just to display and gather data to/from user, it should not directly communicate with Model, i.e. web service, there is a Controller for that purpose:
var LoginController = declare(null, {

    constructor: function(kwArgs) {
        lang.mixin(this, kwArgs);
    },

    login: function(data) {
        // simulate calling web service for authentication
        var def = new Deferred();
        setTimeout(lang.hitch(this, function() {
            def.resolve(data.username == this.username && data.password == this.password);
        }), 1000);
        return def;
    }
});

Create an instance of LoginController:
// provide username & password in the constructor
// since we do not have web service here to authenticate against
var loginController = new LoginController({username: "user", password: "user"});

and pass it to LoginDialog constructor as yet seen above:
var loginDialog = new LoginDialog({ controller: loginController});

Finally LoginDialog class:
var LoginDialog = declare([Dialog, Evented], {

    READY: 0,
    BUSY: 1,

    title: "Login Dialog",
    message: "",
    busyLabel: "Working...",

    // Binding property values to DOM nodes in templates
    // see: http://www.enterprisedojo.com/2010/10/02/lessons-in-widgetry-binding-property-values-to-dom-nodes-in-templates/
    attributeMap: lang.delegate(dijit._Widget.prototype.attributeMap, {
        message: {
            node: "messageNode",
            type: "innerHTML"
        }
    }),

    constructor: function(/*Object*/ kwArgs) {
        lang.mixin(this, kwArgs);
        var dialogTemplate = dom.byId("dialog-template").textContent;
        var formTemplate = dom.byId("login-form-template").textContent;
        var template = lang.replace(dialogTemplate, {
            form: formTemplate
        });

        var contentWidget = new (declare(
            [_Widget, _TemplatedMixin, _WidgetsInTemplateMixin],
            {
                templateString: template
            }
        ));
        contentWidget.startup();
        var content = this.content = contentWidget;
        this.form = content.form;
        // shortcuts
        this.submitButton = content.submitButton;
        this.cancelButton = content.cancelButton;
        this.messageNode = content.messageNode;
    },

    postCreate: function() {
        this.inherited(arguments);

        this.readyState= this.READY;
        this.okLabel = this.submitButton.get("label");

        this.connect(this.submitButton, "onClick", "onSubmit");
        this.connect(this.cancelButton, "onClick", "onCancel");

        this.watch("readyState", lang.hitch(this, "_onReadyStateChange"));

        this.form.watch("state", lang.hitch(this, "_onValidStateChange"));
        this._onValidStateChange();
    },

    onSubmit: function() {
        this.set("readyState", this.BUSY);
        this.set("message", "");
        var data = this.form.get("value");

        // ask the controller to login
        var auth = this.controller.login(data);

        Deferred.when(auth, lang.hitch(this, function(loginSuccess) {
            if (loginSuccess === true) {
                this.onLoginSuccess();
                return;
            }
            this.onLoginError();
        }));
    },

    onLoginSuccess: function() {
        this.set("readyState", this.READY);
        this.emit("success");
    },

    onLoginError: function() {
        this.set("readyState", this.READY);
        this.set("message", "Please try again.");
        this.emit("error");
    },

    onCancel: function() {
       this.emit("cancel");
    },

    _onValidStateChange: function() {
        this.submitButton.set("disabled", !!this.form.get("state").length);
    },

    _onReadyStateChange: function() {
        var isBusy = this.get("readyState") == this.BUSY;
        this.submitButton.set("label", isBusy ? this.busyLabel : this.okLabel);
        this.submitButton.set("disabled", isBusy);
    }
});

Please see templates at the aforementioned jsFiddle. They should be in separate files required via dojo/text! normally. I put them into

   <form dojoType="app.widget.MyWidget">

This will do following:

*

*load the dojotoolkit (dojo/dojo.js)

*create a namespace called 'app' which has a subspace 'widget'

*render body (the simple form dom node)

*call script ondomready, requireing app.widget.MyWidget

*MyWidget requires the dependencies

*parser.parse instantiates the <form dojoType="mywidget">

A: With the help of mschr. I came accross this particular solution.
define([
"dojo/_base/declare",
"dojo/dom",
"dijit/_Widget",
"dijit/_TemplatedMixin",
"dijit/_WidgetsInTemplateMixin",
"dojo/text!app/views/Login/Login.html",
"dijit/Dialog",
"dijit/form/Button",
"dijit/form/TextBox"

], function(
    declare,
    dom,
 _Widget,
_TemplatedMixin,
_WidgetsInTemplateMixin,
template,
Dialog
){
    return declare([_Widget, _TemplatedMixin, _WidgetsInTemplateMixin, Dialog], {

        templateString: template,

        postCreate: function() {
           this.inherited(arguments);
           // make reference to widget from the node attachment
           //this.submitButton = this.getChildren()[ButtonIndex];
           // override its onSubmit
             /*alert("username :" + dom.byId("userId").value()
                 + "  Password: " + dom.byId("password").value());*/
            dojo.connect(this.loginButton, 'onclick', this._login);
        },
        // and a sample on how to implement widget-in-template stateful get/setter pattern
        // e.g. if submitbutton label should change on some event, call as such:
        // dijit.byId('loginForm').set("submitLabel", "Sendin login, please wait");
        _login : function() {
            var value = dom.byId("userId").value;

            if(value)
                alert("username: " + value);
        },
        // and a sample on how to implement widget-in-template stateful get/setter pattern
        // e.g. if submitbutton label should change on some event, call as such:
        // dijit.byId('loginForm').set("submitLabel", "Sendin login, please wait");
        _setSubmitLabelAttr : function(value) {
            return this.submitButton.set("label", value);
        },
        _getSubmitLabelAttr : function() {
            return this.submitButton.get("label");
        },
    });
});


text:
Q: How to iterate through all the ENV variables printing key and value? I'd like to iterate through the variables in env printing:
name: ${name} value: ${value}

Simply splitting by line break and iterating does not work, because of multi-line values, e.g.
SERVER_TLS_SERVER_CRT=-----BEGIN CERTIFICATE-----
foo
-----END CERTIFICATE-----

The use case is to workaround Docker limitation that restricts passing multi-line variables via --env-file.

A: Here's the solution from #bash.
unset IFS
args=() i=0
for var in $(compgen -e); do
    printf -v 'args[i++]' -e%s=%s "$var" "${!var}"
done

I initially thought the idea was to output, hence printf %q was necessary, but that's not the case when just building an arguments array, so it can be simplified to this:
unset IFS
args=()
for var in $(compgen -e); do
    args+=( "-e$var=${!var}" )
done

A: You can use env -0 to get a null terminated list of name=value pairs and use a for loop to iterate:
while IFS='=' read -r -d '' n v; do
    printf "'%s'='%s'\n" "$n" "$v"
done < <(env -0)

Above script use process substitution, which is a BASH feature. On older shells you can use a pipeline:
env -0 | while IFS='=' read -r -d '' n v; do
    printf "'%s'='%s'\n" "$n" "$v"
done

A: Old thread, I know.
But for anyone else needing a solution in sh and without -0 support for env:
env | while IFS= read -r line; do
  value=${line#*=}
  name=${line%%=*}
  echo "V: $value"
  echo "N: $name"
done

A: Unfortunately, Bash's compgen or export -p or POSIX's env do not structure their output, making its parsing vulnerable to misinterpretation.  Other languages reading their POSIX-provided list of environment variables can fill the gap.
jq -n 'env'

https://pubs.opengroup.org/onlinepubs/9699919799/functions/exec.html
As for "writing" this to a Docker container, just passing the value on the command line works.  (I see comments to a Docker issue on a new flag to keep existing usage backwards-compatible).
$ export foobar="first line
> second line
> space terminated
> last line"

$ docker run -e "foobar" bash bash -c 'while IFS= read -r line; do echo "<<${line}>>"; done <<< "${foobar}"'
<<first line>>
<<second line>>
<<space terminated >>
<<last line>>


text:
Q: What is "pinchfire"? In A Game of Thrones they mention "pinchfire":

"Inside the manse, the air was heavy with the scent of spices,
  pinchfire and sweet lemon and cinnamon. They were escorted across the
  entry hall, where a mosaic of colored glass depicted the Doom of
  Valyria. Oil burned in black iron lanterns all along the walls."

What is "pinchfire"?

A: Pinchfire is one of several herbs and spices that were seemingly invented by GRRM for his various "Thrones" books to give it an 'other-worldly' feel.
There's a pretty complete list of all plants mentioned in the "A Song of Ice and Fire" series here.
The more obviously fictional ones include;

*

*Pinchfire

*Firepods

*Sting-me-not

*Daggerleaf

*Goldenheart

*Sandbeggar

*Sourleaf

*Spiceflower

*Waspwillow

*Prickly Ben &

*Harpy's Gold
As far as what it actually smells like, it's worth noting that before the advent of deodorant (and toilet paper) herbs and spices were used in great quantities to disguise human smells and to freshen clothing. My personal guess is that pinchfire would be in the same league as cloves or myrrh


text:
Q: Given $x_n$, $y_n=a+1-x_n$, Find the limit of $\frac{y_{n+1}}{y_n}$ My problem
Given $a>0$, $(x_n)_{n\ge1}$ such that
\begin{cases}
x_0=0\\
x_{n+1}=\sqrt{x_n+a(a+1)}, \forall n\in\mathbb{N}
\end{cases}

*

*Prove that $\lim_{n\to+\infty}x_n=a+1$

*$y_n=a+1-x_n$, Find the limit of $\frac{y_{n+1}}{y_n}$
My attempts
First question: straight out easy!. If $x_n<a+1$ then $a+1>x_{n+1} > x_n$ and thus $(x_n)$ ascends and bounded above. Thus it has a limit, which could also be solved out easily $L=a+1$. Otherwise ($x_n>a+1$), the solution is similar with $(x_n)$ bounded below.
Second question: What I did was that:
\begin{align}
a+1-x_{n+1}=a+1-\sqrt{x_n+a(a+1)}\\=\frac{a+1-x_n}{a+1+\sqrt{x_n+a(a+1)}}\end{align}
thus \begin{align}\boxed{\lim{\frac{y_{n+1}}{y_n}}=\frac1{2(a+1)}}\end{align}
Is that true? I doubt my solution to the second problem. If not, what's the solution?


text:
Q: Local Proxy tool which authenticates against NTLM, sits on top of the Java VM and possibly transparently passes through HTTPS requests I'm looking for a local HTTP proxy which I can run locally on my machine. This proxy accepts HTTP and HTTPS request and passes them upstream on to an external corporate proxy. The local proxy needs to fulfill the following requirements:

*

*1: Needs to be a Java program which I can run on a dedicated JVM.

*2: The proxy needs to be able to authenticate upstream via NTLM. (Credentials stored somewhere in the local proxy.)

Bonus:

*

*3: Passes HTTPS requests transparently through, so that the certificates come from the original issuer.

I have tried Zed Attack Proxy, and it does 1 and 2, but not the bonus requirement 3. Also, with ZAP Proxy I have huge reliability troubles.
What is a good other reliable Java proxy for this task?

A: Quite simply not possible.
Authenticating would involve reading what the user says. Passing the original certificates from the original issue makes this impossible. This is the entire purpose of HTTPS

A: I created this Java proxy some time ago using Java AIO:
http://apetrelli.github.io/scafa/
Currently it can use NTLM proxies, no authentication proxies and direct connection.
It is an unfinished work, it uses a lot of memory (160 MB in Linux) and the docs need refreshing.


text:
Q: how to enable a user to select a single row from data set and send that data row to backend for processing using R shiny is it possible in shiny to display a dataset (table) to the user(frontend) and select a "single" row from that dataset to process in the backend.
scenario:
i am developing a simple human activity(sitting, running,walking etc) recognition using sensor data app in R using UCI dataset "https://archive.ics.uci.edu/ml/datasets/Human+Activity+Recognition+Using+Smartphones"
.I will be training a certain classification model say naive bayes using dataset and then out of that dataset I want to give my trained model a single row of that dataset and find(recognize) to what class of activity that row belongs. Each row consists of values for various attributes of sensors for a particular instance.
I'll be developing it as a user interactive app "therefore using shiny" and want my entire dataset to be visible in front end(csv form) along with some option (say checkbox) to select a single row and provide my model in the backend that row to process.
I know this may not appear to be very interactive app but I want to "control from frontend" which row gets processed so that I could predict activity for that particular sensor data.Is it possible somehow??
note:from dataset(visible in frontend) I mean only that csv file which contains some 560 attributes, I have no interest in recognizing person(i.e 1-30)I just want activity.

A: Yes, this is definitely possible. As @s.brunel mentions, it is made exceptionally easy by the DT package.
Below is a toy example where we run the rows that are clicked through the model.
library("shiny")
library("dplyr")
library("DT")
library("rpart")

set.seed(1)

# set an id variable
iris <- iris %>% mutate(id = row_number())

# select a training set
train_iris <- iris %>%
  group_by(Species) %>%
  sample_frac(0.75)

# select the testing rows
test_iris  <- anti_join(iris, train_iris, by = 'id')

# build the model
fit <- rpart(Species ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width, data = test_iris)

ui <- fluidPage(
  DT::dataTableOutput('unscored'),
  DT::dataTableOutput('scored')
  )

server <- function(input, output) {

  # display the data that is available to be scored
  output$unscored <- DT::renderDataTable(test_iris)

  scored_data <- reactive({
    # make sure there are rows to score
    shiny::validate(
      need(length(input$unscored_rows_selected) > 0, "Select rows to score!")
    )

    score_dat <- test_iris[input$unscored_rows_selected, ]
    # return the data with the prediction
    data.table(
      score_dat,
      predicted = predict(fit, score_dat, type = "class")
    )
  })

  # display the scored data once processed by the model
  output$scored <- DT::renderDataTable(scored_data())
}

shinyApp(ui, server)


text:
Q: Magento 2.1 - Flat Catalog module has a limit of 64$d filterable and/or sortable attributes I'm getting the error below during my re-index:

The Flat Catalog module has a limit of 64$d filterable and/or sortable
  attributes.Currently there are 92$d of them.Please reduce the number
  of filterable/sortable attributes in order to use this module

How can I fix it? Is that a limit in MYSQL?
Any help is appreciated.

A: yes, it's limitation of  mysql: A table can contain a maximum of 64 secondary indexes.https://dev.mysql.com/doc/refman/5.7/en/innodb-restrictions.html
Simple solution is not use flat indexex.

A: Another option is to change the default config value, that is currently used, in your own module. Create \Namespace\Module\etc\config.xml and put following into it
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
    <default>
        <catalog>
            <product>
                <flat>
                    <max_index_count>128</max_index_count>
                </flat>
            </product>
        </catalog>
    </default>
</config>


text:
Q: Should I check insert count when using Slick? I have the Users table and want to insert User in it and return Ok or Error to the frontend.
I thought that it's possible to have zero updates when inserting, so I always check for insert count like this:
 // Somewhere in userService
 def add(user: User): Future[Int] = db.run(users += user)
 ...
 // Routes
 onSuccess(add(newUser)) {
    case insertCount if insertCount == 1 =>
      complete(Ok)
    case _ =>
      complete(Error)
 }

But when reading Bootzooka code I find that they don't care about update count:
def add(user: User): Future[Unit] = db.run(users += user).mapToUnit

Should I care about insert count? Or does Future fails if there are no inserts?

A: Nope, not required. Slick throws exception if in case any insert statement fails.
You can safely ignore the returned int value.


text:
Q: Task Scheduler not running HTA files Task Scheduler does not seem to run HTA files. I have the action like this:
Action: "start an application"
program/script path: C:/TestMeeting.hta
Start In: C:/
So it should run the HTA, but when the task is triggered it does nothing. It says that it's status is running. It never stops and I have to manually stop it. Another thing I tried was using "C:\Windows\SysWOW64\mshta.exe" for the program path then put the HTA path in the "Add argument" box. It runs and says it successfully completed but nothing happens.
So how do I run HTA files using Task Scheduler?
Here is the code in the HTA (in case it matters):
<Script Language=JavaScript>
    var window = open("https://ww2.livelesson.com/REMOVED_FOR_SECURITY_REASONS");
    function SignIn() {
    setTimeout(function(){
    try{
    var corral = window.document.getElementsByClassName("loginField coral3-Tab")[0];
    corral.click();
    var text = window.document.getElementsByClassName("coral-Textfield login-textfield coral3-Textfield coral3-Textfield--quiet")[0];
    text.value = "Name";
    var button = window.document.getElementsByClassName("coral3-Button coral3-Button--cta enterRoom")[0];
    button.click();
    closeEveyThing();
    } catch (error) {
    SignIn();
    }
    }, 500);
    }
    function closeEveyThing() {
    setTimeout(function(){
    window.close();
    close();
    },10000);
    }
    SignIn();
    </Script>

UPDATE:
I found out you can run mshta.exe with the path of the HTA as the arguments in bash:
cd
/mnt/c/Windows/System32/mshta.exe C:/TestMeeting.hta

It runs fine so It seems weird that running C:/Windows/System32mshta.exe with C:/TestMetting.hta in the arguments does not work.

A: I still don't know why does not run HTA files, but it can run .bat files.
If you put the following code in an .bat file and run the .bat file it will work.
cd
mshta.exe C:/PATH_TO_HTA/Example.hta


text:
Q: All supplementary subsets of a list in python I am not sure if 'supplementary' is the right word, but I will explain my problem with an example. Let's say our list is:
[1,2,3,4]

What I am trying to find is:
[1], [2], [3], [4]
[1,2], [3], [4]
[1,3], [2], [4]
...
[1,2], [3,4]
[1,3], [2,4]
...
[1,2,3], [4]
[1,2,4], [3]
...
[1,2,3,4]

In other words, I try to get all lists such that they together have all elements of the initial list.
Thanks!

A: You could use Raymond Hettinger's partition recipe to find all partitions. I've modified it slightly to work with Python3. I also added partition_permutations to find the partitions of all permutations of the input, x.
import pprint
import itertools as IT

def partition(iterable, chain=IT.chain, map=map):
    """
    http://code.activestate.com/recipes/576795/ (Raymond Hettinger)
    >>> list(partition('abcd'))
    [['abcd'],
     ['a', 'bcd'],
     ['ab', 'cd'],
     ['abc', 'd'],
     ['a', 'b', 'cd'],
     ['a', 'bc', 'd'],
     ['ab', 'c', 'd'],
     ['a', 'b', 'c', 'd']]
    """
    s = iterable if hasattr(iterable, '__getitem__') else tuple(iterable)
    n = len(s)
    first, middle, last = [0], range(1, n), [n]
    getitem = s.__getitem__
    return [list(map(getitem, map(slice, chain(first, div), chain(div, last))))
            for i in range(n) for div in IT.combinations(middle, i)]

def partition_permutations(iterable, ordered_partitions=False):
    result = set()
    for perm in IT.permutations(iterable):
        for item in partition(perm):
            if ordered_partitions:
                result.add(tuple(item))
            else:
                result.add(tuple(sorted(item)))
    result = [list(map(list, item)) for item in result]
    result = sorted(result)
    return result

x = [1,2,3,4]
result = partition_permutations(x, ordered_partitions=True)
pprint.pprint(result)
print(len(result))

yields 73 items:
[[[1], [2], [3], [4]],
 [[1], [2], [3, 4]],
 [[1], [2], [4, 3]],
 [[1], [2, 3], [4]],
 [[1], [2, 3, 4]],
 [[1], [2, 4], [3]],
 [[1], [2, 4, 3]],
 [[1], [3], [4, 2]],
 [[1], [3, 2], [4]],
 [[1], [3, 2, 4]],
 [[1], [3, 4, 2]],
 [[1], [4, 2, 3]],
 [[1], [4, 3, 2]],
 [[1, 2], [3], [4]],
 [[1, 2], [3, 4]],
 [[1, 2], [4, 3]],
 [[1, 2, 3], [4]],
 [[1, 2, 3, 4]],
 [[1, 2, 4], [3]],
 [[1, 2, 4, 3]],
 [[1, 3], [2], [4]],
 [[1, 3], [2, 4]],
 [[1, 3], [4, 2]],
 [[1, 3, 2], [4]],
 [[1, 3, 2, 4]],
 [[1, 3, 4], [2]],
 [[1, 3, 4, 2]],
 [[1, 4], [2], [3]],
 [[1, 4], [2, 3]],
 [[1, 4], [3, 2]],
 [[1, 4, 2], [3]],
 [[1, 4, 2, 3]],
 [[1, 4, 3], [2]],
 [[1, 4, 3, 2]],
 [[2], [3], [4, 1]],
 [[2], [3, 1], [4]],
 [[2], [3, 1, 4]],
 [[2], [3, 4, 1]],
 [[2], [4, 1, 3]],
 [[2], [4, 3, 1]],
 [[2, 1], [3], [4]],
 [[2, 1], [3, 4]],
 [[2, 1], [4, 3]],
 [[2, 1, 3], [4]],
 [[2, 1, 3, 4]],
 [[2, 1, 4], [3]],
 [[2, 1, 4, 3]],
 [[2, 3], [4, 1]],
 [[2, 3, 1], [4]],
 [[2, 3, 1, 4]],
 [[2, 3, 4, 1]],
 [[2, 4], [3, 1]],
 [[2, 4, 1], [3]],
 [[2, 4, 1, 3]],
 [[2, 4, 3, 1]],
 [[3], [4, 1, 2]],
 [[3], [4, 2, 1]],
 [[3, 1], [4, 2]],
 [[3, 1, 2], [4]],
 [[3, 1, 2, 4]],
 [[3, 1, 4, 2]],
 [[3, 2], [4, 1]],
 [[3, 2, 1], [4]],
 [[3, 2, 1, 4]],
 [[3, 2, 4, 1]],
 [[3, 4, 1, 2]],
 [[3, 4, 2, 1]],
 [[4, 1, 2, 3]],
 [[4, 1, 3, 2]],
 [[4, 2, 1, 3]],
 [[4, 2, 3, 1]],
 [[4, 3, 1, 2]],
 [[4, 3, 2, 1]]]

Note that partition_permutations treats the items inside each partition as
unordered. That is, for example, [[1,4], [2,3]] and [[2,3], [1,4]] are
treated as the same partition. If that is not what you want, then change
result = partition_permutations(x)

to
result = partition_permutations(x, ordered_partitions=True)


text:
Q: Linked List of Structures - How to Edit a Data This is my structure and the node I add. my insert function is okay but when I try to add the Course_Student data later, by searching for the student's uId and add the data to that specific node; my list is deleted and it shows nothing . and then when I add another node the Course_Student data is shown in an odd way.
How can I add My Course_Student data to one specific node later ?
typedef struct stdnt Student ;
typedef struct crs_std Course_Student;

struct crs_std{
    int crs_code;
    char name[20];
    float grade;
    int unt;
};

struct stdnt {
       char firstname[20];
       char lastname[20];
       Course_Student a[10];
       unsigned long long uID;
       int year;
       float avg;
};

struct Linked_list_Student{

    Student s;
    Node_s *next_s ;

This is the function I use to add data to my linked list after inserting data .
void Select_Course(NodePtr_s *startPtr_s, Course_Student cs[10], int id){
    int i;
    NodePtr_s prevPtr_s;
    NodePtr_s currPtr_s;
    for(i=0;i<n;i++){

        if((*startPtr_s)->s.uID == id){

            (*startPtr_s)->s.a[i].crs_code = cs[i].crs_code;
            strcpy((*startPtr_s)->s.a[i].name,cs[i].name);
            (*startPtr_s)->s.a[i].unt = cs[i].unt;

        }

        prevPtr_s = (*startPtr_s);
        currPtr_s = (*startPtr_s)->next_s;

        while(currPtr_s != NULL){

            if(currPtr_s->s.uID == id){

                currPtr_s->s.a[i].crs_code = cs[i].crs_code;
                strcpy(currPtr_s->s.a[i].name,cs[i].name);
                currPtr_s->s.a[i].unt = cs[i].unt;

        }

        prevPtr_s = currPtr_s;
        currPtr_s = currPtr_s->next_s;
        }

    }

}

A: In your for loop:
for(i=0;i<n;i++){

...what is n?  It appears n is probably a global set to 10, for looping through cs?  If so, then your approach is not the best.  It seems you are:
foreach element in cs
    find the correct student record
    add that element from cs to the student record

But it sounds like all elements in cs should get added to the same student record?  If so, you should really be doing:
find the correct student record
foreach element in cs
    add that element to the student record

Please verify that is what you are trying to achieve then I or someone else here can help you with the correct algorithm.
Also, please make sure your indentations are correct so people can easily read your code:
    while(currPtr_s != NULL){

        if(currPtr_s->s.uID == id){

            currPtr_s->s.a[i].crs_code = cs[i].crs_code;
            strcpy(currPtr_s->s.a[i].name,cs[i].name);
            currPtr_s->s.a[i].unt = cs[i].unt;

    }

    prevPtr_s = currPtr_s;
    currPtr_s = currPtr_s->next_s;
    }

should be
    while(currPtr_s != NULL){

        if(currPtr_s->s.uID == id){

            currPtr_s->s.a[i].crs_code = cs[i].crs_code;
            strcpy(currPtr_s->s.a[i].name,cs[i].name);
            currPtr_s->s.a[i].unt = cs[i].unt;

        }

        prevPtr_s = currPtr_s;
        currPtr_s = currPtr_s->next_s;
    }

A: You should use your startPtr_s just to initialize your loop and use Node_s for your temp variable:
void Select_Course(NodePtr_s *startPtr_s, Course_Student cs[10], int id)
{
  Node_s *current = NULL;
  int i;

  /* iterate on each node in your list */
  for (current = *startPtr_s; current != NULL; current = current->next_s) {
    if (current->s.uID != id) continue;

    /* On each node update your data */
    for (i = 0; i < n; i++) {
      current->s.a[i].crs_code = cs[i].crs_code;
      strcpy(current->s.a[i].name,cs[i].name);
      current->s.a[i].unt = cs[i].unt;
    }
  }
}


text:
Q: Are there some other non-degenerated natural bilinear forms on $M_n \otimes M_n$? Let $M_n$ be the space of all $n$ by $n$ matrices. Then a non-degenerated natural bilinear form on $M_n \otimes M_n$ is $tr(AB)$. The reason is as follows.
The natural linear form on $M_n$ is $f: M_n \to \mathbb{C}$, $f(A) = tr(A)$. The reason is as follows. Let $V$ be an $n$-dimensional vector space with a basis $v_1, \ldots, v_n$ and $V^*$ its dual vector space with the dual basis $v_1^*, \ldots, v_n^*$. We have an isomorphism $End(V) = M_n \to V^* \otimes V$ given by $(a_{ij})_{n \times n} \mapsto \sum_{i,j} a_{ij} v_i^* \otimes v_j$. There is a natural pairing $V^* \otimes V \to \mathbb{C}$ given by $(v_i^*, v_j) \mapsto v_i^*(v_j) = \delta_{ij}$. Therefore we have a natural map $M_n \to V^* \otimes V \mapsto \mathbb{C}$ given by $(a_{ij}) \mapsto \sum_{i,j} a_{ij} v_i^* \otimes v_j \mapsto \sum_{ij} a_{ij}\delta_{ij}= \sum_{i}a_{ii} = tr(A)$.
Now consider the natural map $V^* \otimes V \otimes V^* \otimes V \to \mathbb{C}$ given by $(f_1, v_1, f_2, v_2) \mapsto f_1(v_2)f_2(v_1)$. Then we have a map $M_n \otimes M_n \to V^* \otimes V \otimes V^* \otimes V \to \mathbb{C}$ given by $(A, B) \mapsto \sum_{ijkl} a_{ij} v_i^* \otimes b_{kl} v_j \otimes v_k^* \otimes v_l \mapsto \sum_{ij} a_{ij} b_{ji} = tr(AB)$.
Are there some other non-degenerated natural bilinear forms on $M_n \otimes M_n$? Thank you very much.


text:
Q: $n$th-order Hadamard power (or root) of a vector I am familiar with the notation of the $n$th-order Hadamard power
$$
\mathbf{A}^{\circ n}
$$
or root
$$
\mathbf{A}^{\circ \frac{1}{n}}
$$
I wonder if it is sensible to use this notation for vectors as well, that is,
$$
\mathbf{v}^{\circ n} = (v_1^n, v_2^n, \dots, v_N^n)
$$
and
$$
\mathbf{v}^{\circ \frac{1}{n}} = \left(\sqrt[n]{v_1}, \sqrt[n]{v_2}, \dots, \sqrt[n]{v_N}\right)
$$

A: Of course, since your (row) vector
$$\mathbf v= (v_1,v_2,\dots, v_N)$$
is nothing more than a particular case of a matrix $A$ (with one row and $N$ columns).
Hadamard product, which you are "familiar with", deals with matrices (not linear transformations ;-) ), in particular with row or column matrices.


text:
Q: Сохранение в Blob-поля в FireBird Имеется таблица:
CREATE TABLE HOOKNAMES (
HN_ID             SMALLINT NOT NULL PRIMARY KEY,
HN_NAME           VARCHAR(20) NOT NULL,
HN_LEVEL          SMALLINT NOT NULL,
HN_IMAGE          BLOB);

Первые 3 поля заполняю так:
Form1.IBSql1.SQL.Clear;
Form1.IBSql1.SQL.Append('INSERT INTO HOOKNAMES (HN_ID, HN_NAME, HN_LEVEL) ');
Form1.IBSql1.SQL.Append('VALUES ('+TempBuf[3]+', '+TempBuf[0]+', '+TempBuf[1]+')');
Form1.IBSql1.ExecQuery;

Последнее поле пробую добавить следующим образом (пример нашёл на этом сайте):
Form1.HookNamesDS.Edit;
TBlobField(Form1.HookNamesDS.FieldByName('HN_IMAGE')).LoadFromFile('..\bilder\image.png');
Form1.HookNamesDS.Post;

Var HookNamesDS: TIBDataSet;
Получаю ошибку при попытке изменить DataSet, который только для чтения, в нём не задан DataSource, просто выбрана вся таблица через SelectSQL.
Каким образом в данном примере идёт привязка именно к нужной строке?
Каким образом нужно правильно инициализировать DataSet? И как правильно с ним работать?
A: Вам сначала надо добиться, чтоб таблица была модифицируемая. Если вы используете TIBDataSet, то необходимо прописать все sql запросы: SelectSQL, ModifySQL, DeleteSQL, InsertSQL. Если вы добавите компонент на форму, можно задать эти запросы в визуальном редакторе (пкм на компоненте, Dataset editor...), выбираете в нем имя таблицы, запросы создадутся, afair сами. Если вы создаете компонент в рантайме, значит надо прописать эти же запросы в коде. Про тексты запросов писал здесь.
После того как вы получите модифицируемый dataset, уже можно приступать к сохранению blob'ов.
UPD По поводу TIBSQL. Никогда не пишите запросы так. Всегда пользуйтесь параметрами.
UPD2 Если вы добавляете или редактируете несуществующую запись (например, таблица пустая - будет вызван Insert), в этом случае вам надо заполнить и HN_ID. Для изменения, как в вопросе, HookNamesDS.Edit - HN_ID у вас для текущей записи должно быть уже заполнено. В любом случае заполнять надо поле, а не параметр. Параметры будут заполняться сами, этим занимается компонент.
with Form1.HookNamesDS do
begin
  Insert;
  FieldByName('HN_ID').AsString:=TempBuf[3];
  // остальные поля
  TBlobField(FieldByName('HN_IMAGE')).LoadFromFile('..\bilder\image.png');
  Post;
end;

А так, должен работать ваш код из вопроса.


text:
Q: Rewriting SQL queries with GROUP BY and without HAVING using a subquery SQL queries using GROUP BY that does not have a HAVING clause can be rewritten using a subquery. One simple example can be the following:
select A.a_id, sum(B.b_count) Bsum
from A
left join B on A.a_id = B.a_id
group by A.a_id

select A.a_id,
(
    select sum(b.b_count) Bsum
    from B
    where A.a_id = B.a_id
)
from A

Can you give me an example when it can not be done? I mean when a GROUP BY SQL query without HAVING can not be rewritten using subquery behind SELECT?

A: I think this would be difficult where the you want to aggregate AND group by values in the same table.
select A.a_id, sum(B.b_count) Bsum
from A
left join B on A.a_id = B.a_id
group by A.a_id, b.otherVal


text:
Q: Why does keyword "transient" has no effect for Servlet HTTPSession in Java? What does the transient Keyword exactly mean? I have a Class attribute marked as transient:
public class NodeClassifier {

   private transient HashMap<String, Node> nodeCache = new HashMap<>();

...
}

After storing and recovering an NodeClassifier Object into the HttpSession the Attribute still has the Value from previous Session.
Shouldn't it be empty?
The Environment is a plain Servlet running on Glassfish4.

A: transient means that the value will not be serialized (using default Java object serialization), when the object is written out as bytes.
Serialization of a session may or may not happen (it is only needed to pass the session between processes, or to persist it to disk, but usually not needed in a single JVM servlet container that can just keep them in memory), so you should not rely on values being "lost" that way.
If you don't want stuff to survive in the session, don't put it there.
Consider using request attributes instead.


text:
Q: How to disable the "tap dragging"-feature in Ubuntu 18.04 (libinput) without disabling "tap to click"? I can't seem to figure out how to disable the "tap dragging"-feature in Ubuntu 18.04's libinput. By disabling "tap dragging" I mean that I want to disable the dragging-functionality when using tap without actually disabling "Tap-to-click". This way when I want to drag something, I'd have to actually click on the touchpad. While it could be a handy feature for some, I don't really need it and it keeps triggering by accident. If it's any help, I am on Macbook Pro, some late-2013 or early-2014 version.
I've tried to search around for an answer, and checked libinput's manual to figure out the correct configuration. What I found was this:

Option "TappingDrag" "bool"
Enables or disables drag during tapping behavior ("tap-and-drag"). When enabled,
                a tap followed by a finger held down causes  a  single  button  down  only,  all
                motions  of  that  finger  thus  translate  into  dragging motion.  Tap-and-drag
                requires option Tapping to be enabled.

I tried to set this option in /usr/share/X11/xorg.conf.d/40-libinput.conf:
Section "InputClass"
        Identifier "libinput touchpad catchall"
        MatchIsTouchpad "on"
        MatchDevicePath "/dev/input/event*"
        Driver "libinput"
        Option "TappingDrag" "false"
EndSection

Reboot and tap dragging is still there. I also tried to add the same TappingDrag-option to the Touchscreen- and Tablet-sections in the config file with no luck. What am I doing wrong?
I hope someone knows the answer, this is really bugging me. Thanks in advance!

A: GNOME has a setting for this, it is just not accessible in GNOME Control Center.
You can either use terminal or dconf-editor to access this setting.
Terminal:

*

*Turn off tap-and-drag.
gsettings set org.gnome.desktop.peripherals.touchpad tap-and-drag false

*Check if it was successful.
gsettings get org.gnome.desktop.peripherals.touchpad tap-and-drag

dconf-editor:

*

*Install dconf-editor

*Inside dconf-editor navigate to org/gnome/desktop/peripherals/touchpad

*Find tap-and-drag and turn off the setting

A: Since 18.04 is using Xorg instead of Wayland, you should be able to set it this way:
First find the device:
% xinput list
⎡ Virtual core pointer                      id=2    [master pointer  (3)]
⎜   ↳ Virtual core XTEST pointer                id=4    [slave  pointer  (2)]
⎜   ↳ SynPS/2 Synaptics TouchPad                id=12   [slave  pointer  (2)]
⎜   ↳ TPPS/2 IBM TrackPoint                     id=13   [slave  pointer  (2)]
⎣ Virtual core keyboard                     id=3    [master keyboard (2)]
    ↳ Virtual core XTEST keyboard               id=5    [slave  keyboard (3)]
    ↳ Power Button                              id=6    [slave  keyboard (3)]
    ↳ Video Bus                                 id=7    [slave  keyboard (3)]
    ↳ Video Bus                                 id=8    [slave  keyboard (3)]
    ↳ Sleep Button                              id=9    [slave  keyboard (3)]
    ↳ Integrated Camera: Integrated C           id=10   [slave  keyboard (3)]
    ↳ AT Translated Set 2 keyboard              id=11   [slave  keyboard (3)]
    ↳ ThinkPad Extra Buttons                    id=14   [slave  keyboard (3)]

I'm on a thinkpad. Your devices are likely different.
List the properties of the touchpad:
% xinput list-props 12
Device 'SynPS/2 Synaptics TouchPad':
    Device Enabled (140):   1
    Coordinate Transformation Matrix (142): 1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 1.000000
    libinput Tapping Enabled (276): 1
    libinput Tapping Enabled Default (277): 0
    libinput Tapping Drag Enabled (278):    1
    ...

Then disable it:
% xinput set-prop 'SynPS/2 Synaptics TouchPad' 'libinput Tapping Drag Enabled' 0

The way I set this permanently is by putting into a script that runs on login.
I hope that helps. I don't know how to fix it at the system-level, nor on Wayland.


text:
Q: Pass userID in @PrePersist (@PreUpdate) method using Spring Boot and JWT I'm using JWT for authentication in my application and I need to pass the userID to the method @PrePersist in the @Entity classes. How can I do it?
This is my @RestController where pass the JwtToken:
@PostMapping(value = "/car")
public ResponseEntity<GenericResponse<String>> addCar(
        @RequestHeader(value = "Authorization") String token,
        @RequestParam(value = "plate") String plate) {
   // some stuff
}

And this is the PrePersist method in Entity classes:
@PrePersist
public void onPrePersist() {
    creationtime = Timestamp.from(Instant.now());
    //TODO creationuser = userID from token
}

Can I get the token info in Entity? What's the best way to do it?


text:
Q: How to clean dataset with specific rules from excel in r I have a data cleaning question. An example short version of the dataset is below:
df <- data.frame(Text1 = c(NA, "Name","Jack","Jack"),
                 Text2 = c(NA, "District","Leon","Leon"),
                 Text3 = c(NA, "School","Black","Black"),
                 Text4 = c(NA, "Grade",1,1),
                 Scoring = c("Text", "Teacher","Ana","Ana"),
                 Item1 = c("11_ada", "/a/","1.0","0.0"),
                 Text7 = c(NA, "/c/","1.0","1.0"),
                 Text8 = c(NA, "/a/","1.0","1.0"),
                 Item2 = c("10_bada", "/x/","1.0","0.0"),
                 Text10 = c(NA, "/y/","0.0","1.0"),
                 Text11 = c(NA, "/z/","1.0","0.0"))

> df
  Text1    Text2  Text3 Text4 Scoring  Item1 Text7 Text8   Item2 Text10 Text11
1  <NA>     <NA>   <NA>  <NA>    Text 11_ada  <NA>  <NA> 10_bada   <NA>   <NA>
2  Name District School Grade Teacher    /a/   /c/   /a/     /x/    /y/    /z/
3  Jack     Leon  Black     1     Ana    1.0   1.0   1.0     1.0    0.0    1.0
4  Jack     Leon  Black     1     Ana    0.0   1.0   1.0     0.0    1.0    0.0

The first part of the dataset has demographic information. It has also item information with correct (1.0) and incorrect (0.0) responses. I am grabbing this information from an excel file. I need to restructure the first two rows as below. Especially, for the Item information, I need to rename them as 1.1 1.2 1.3 2.1 2.2 2.3. This is just a part of the dataset. Each Item has multiple columns and there are many Items.
How can I clean this dataset as below?

df1

      Name District School Grade Teacher    1.1   1.2   1.3     2.1    2.2    2.3
      Jack     Leon  Black     1     Ana    1.0   1.0   1.0     1.0    0.0    1.0
      Jack     Leon  Black     1     Ana    0.0   1.0   1.0     0.0    1.0    0.0

Also, how can I get this second desired dataset?

df2

      Name District School Grade Teacher    1.1   1.2   1.3     2.1    2.2    2.3
      NA       NA    NA       NA     NA    11_ada 11_ada 11_ada 10_bada 10_bada 10_bada
      Jack     Leon  Black     1     Ana    1.0   1.0   1.0     1.0    0.0    1.0
      Jack     Leon  Black     1     Ana    0.0   1.0   1.0     0.0    1.0    0.0

A: library(janitor)
library(dplyr)
i1 <- cumsum(grepl("Item", names(df)))
i2 <- match(1, i1)
nm1 <-  make.unique(as.character(i1[i1 > 0]))

 row_to_names(df, 2) %>%
  setNames(make.unique(names(.))) %>%
  rename_with(~nm1, i2:last_col())

-output
 Name District School Grade Teacher   1 1.1 1.2   2 2.1 2.2
3 Jack     Leon  Black     1     Ana 1.0 1.0 1.0 1.0 0.0 1.0
4 Jack     Leon  Black     1     Ana 0.0 1.0 1.0 0.0 1.0 0.0

For the second case
i1 <- cumsum(grepl("Item", names(df)))
i2 <- match(1, i1)
nm1 <-  make.unique(as.character(i1[i1 > 0]))
 i3 <- match("Name", df$Text1)
 df[i3, i2:ncol(df)] <- nm1
names(df) <- unlist(df[i3,])
df <- df[-i3,]
i4 <- is.na(df$Name)
df[i4, i2:ncol(df)] <- t(apply(df[i4, i2:ncol(df)], 1,
  function(x) x[!is.na(x)][cumsum(!is.na(x))]))

-output
> df
  Name District School Grade Teacher      1    1.1    1.2       2     2.1     2.2
1 <NA>     <NA>   <NA>  <NA>    Text 11_ada 11_ada 11_ada 10_bada 10_bada 10_bada
3 Jack     Leon  Black     1     Ana    1.0    1.0    1.0     1.0     0.0     1.0
4 Jack     Leon  Black     1     Ana    0.0    1.0    1.0     0.0     1.0     0.0


text:
Q: ChartJs bar chart bar value displaying lower then Y axis value in pdf? I have a created a bar chart by chart js , Below is my code
version : 2.9.4
var xValues = ["Italy", "France", "Spain", "USA", "Argentina"];
var yValues = [3, 5, 8, 9, 5];
var barColors = ["#E85900", "#E85900","#E85900","#E85900","#E85900"];

new Chart("myChart", {
  type: "bar",
  data: {
    labels: xValues,
    datasets: [{
      axis: 'y',
      backgroundColor: barColors,
      data: yValues,
    }]
  },
  options: {
    legend: {display: false},
    scales: {
        xAxes: [{
            barThickness: 65,  // number (pixels) or 'flex'
        }],
        yAxes: [{
            ticks: {
                stepSize: 1,
                beginAtZero:true,
                suggestedMax: 9
            }
        }]
    },
    plugins: {
      datalabels: {
        anchor: 'end',
        align: 'top',
        formatter: Math.round,
        font: {
          weight: 'bold'
        }
      }
    }
  }
});

Output that I got like below in pdf, I am using wkhtmltopdf. But it's fine in html page.

Problem is bar size displaying less then Y axis value. Here bar value 3 is showing under the Y axis value 3. My expectation is it will equal to 3.

A: I had the similar issue while converting html to pdf in IronPdf. I have managed to resolve it by setting animation option to false. So in your case it would be:
var xValues = ["Italy", "France", "Spain", "USA", "Argentina"];
var yValues = [3, 5, 8, 9, 5];
var barColors = ["#E85900", "#E85900","#E85900","#E85900","#E85900"];

new Chart("myChart", {
  type: "bar",
  data: {
    labels: xValues,
    datasets: [{
      axis: 'y',
      backgroundColor: barColors,
      data: yValues,
    }]
  },
  options: {
    animation: false,
    legend: {display: false},
    scales: {
        xAxes: [{
            barThickness: 65,  // number (pixels) or 'flex'
        }],
        yAxes: [{
            ticks: {
                stepSize: 1,
                beginAtZero:true,
                suggestedMax: 9
            }
        }]
    },
    plugins: {
      datalabels: {
        anchor: 'end',
        align: 'top',
        formatter: Math.round,
        font: {
          weight: 'bold'
        }
      }
    }
  }
});


text:
Q: Accessing API from Chrome extension I have a website which I have added as an extension in Google Chrome. What I need is that I have to access a server file from the extension. And I need is that whatever the server file outputs, I need to access the output in the extension.
Here is my manifest.json:
{
    "name": "Calpine Extension",
    "version": "1.0",
    "description": "Log on to calpinemate",
    "manifest_version": 2,
    "browser_action": {
        "default_icon": "icon_128.png"
    },
    "background": {
        "persistent": false,
        "scripts": ["background.js"]
    },

    "browser_action": {
        "default_title": "Test Extension",
        "default_icon": "calpine_not_logged_in.png"
    },

    "externally_connectable": {
        "matches": ["http://calpinemate.com/"]
    }
}

Here is my background.js
chrome.browserAction.onClicked.addListener(function (tab) {
    chrome.tabs.create({ "url": "http://calpinemate.com" });
});

Now what I need is that I have a server file (index.php) which outputs 1. Now what I need is that I want to get this 1 in extension. That is whatever the file outputs I want that output in extension. How can I do that?
Here is my index.php
<?php echo 1 ;?>

I tried this.But still it is only working on Onclick event.Please check  my code.
Here is my background.js
   function getGmailUrl() {
   return "http://calpinemate.com/";
   }
   function isGmailUrl(url) {

      return url.indexOf(getGmailUrl()) == 0;
      }
   chrome.browserAction.onClicked.addListener(gotopage);

      function gotopage(){
      chrome.tabs.query({
       url: "http://calpinemate.com/*",
      currentWindow: true
     }, function(tabs) {
    if (tabs.length > 0) {
        var tab = tabs[0];
        console.log("Found (at least one) Gmail tab: " + tab.url);
        console.log("Focusing and refreshing count...");
        chrome.tabs.update(tab.id, { active: true });
         updateIcon();
    } else {
        console.log("Could not find Gmail tab. Creating one...");
        chrome.tabs.create({ url: getGmailUrl() });
         updateIcon();
    }
      });
    }

        if (chrome.runtime && chrome.runtime.onStartup) {
      chrome.runtime.onStartup.addListener(function() {

       updateIcon();
      });
      } else {
        chrome.windows.onCreated.addListener(function() {

        updateIcon();
           });
         }
     function updateIcon(){

   var req = new XMLHttpRequest();
     req.addEventListener("readystatechange", function() {
         if (req.readyState == 4) {
    if (req.status == 200) {
        localStorage.item=req.responseText;
        //alert(localStorage.item);
        if(localStorage.item==1){
          chrome.browserAction.setIcon({path:"calpine_logged_in.png"});
          chrome.browserAction.setBadgeBackgroundColor({color:[190, 190, 190, 230]});
          chrome.browserAction.setBadgeText({text:""});
        }
        else{
        chrome.browserAction.setIcon({path:"calpine_not_logged_in.png"});
        chrome.browserAction.setBadgeBackgroundColor({color:[190, 190, 190, 230]});
        chrome.browserAction.setBadgeText({text:""});
        }
        // We received the data
        //alert("Data: " + req.responseText);
      } else {
        // Handle the error
        alert("ERROR: status code " + req.status);
      }
    }
   });
       req.open("GET", "http://blog.calpinetech.com/test/index.php", true);
      req.send(null);

}

A: First request permission to access your server:
// In manifest.json
...
permissions: [
   ...
   "*://calpinemate.com/index.php"
],

Then use AJAX to access the data:
var req = new XMLHttpRequest();
req.addEventListener("readystatechange", function() {
    if (req.readyState == 4) {
        if (req.status == 200) {
            // We received the data
            alert("Data: " + req.responseText);
        } else {
            // Handle the error
            alert("ERROR: status code " + req.status);
        }
    }
});
req.open("GET", "https://calpinemate.com/index.php", true);
req.send(null);


text:
Q: How to get latlangs from the arraylist which are near to my current location? I am having list of Latitude and logitudes. Entire latlang is available in the ArrayList.  How to get latlangs from the arraylist which are near to my current location ?
My current location latlang is - 40.711991 , -73.978543
For Example, below Given the entire latlangs, which is available in the ArrayList.
From my location, Around 100 meter, following latlangs are available.
40.709636 , -73.984766
40.717521 , -73.980775
40.718757 , -73.986268
40.717976 , -73.995795
40.716025 , -74.000602
40.7304 , -73.978286
40.729034 , -73.982835
40.730856 , -73.992105
40.709128 , -74.004378
40.709844 ,-73.987985
Following latlangs are out of 100 meter.
40.715504 , -73.922238
40.709193 , -73.901296
40.714203 , -73.868251
40.683879 , -73.875203
40.660704 , -73.8831
40.654454 , -73.896403
I need to show latlangs from the ArrayList which are close to my current location around 100 meter only. Out of 100 meter, I should not show.  How to do that ?  Kindly please help. Thanks in Advance.

A: You can do like
You have to get lat and long one by one from arrayList and then
 //============= for current location ===========
 Location currLoc= new Location("");
 currLoc.setLatitude(currLocLat);
 currLoc.setLongitude(currLocLong);

Do iteration over arraylist, fetch one by one lat and longs and then,
  //============= for arrayList location ===========
  Location arrListLoc= new Location("");
  arrListLoc.setLatitude(arrLisLat1);
  arrListLoc.setLongitude(arrLisLong1);

You will get distance in meter by following method..
  float distanceInMeters = currLoc.distanceTo(arrListLoc);


text:
Q: How to delete multiple lines after a match in ansible? Is there a way in ansible to delete multiple lines after a pattern matched?
For example, I have a file with following contents, and need to delete lines 'bbbbbb', 'cccccc'. However I really do not know what are those two lines as they are generated dynamically. I only know line 'aaaa:'
start contents
aaaa:
    bbbbbb
    cccccc
other contents


text:
Q: Disable "code hiding feature" in IntelliJ Remark: This question is (up to now) not a duplicate. I know how to disable the hints. This is not what I am looking for.
In intelliJ a feature "hides" parts of my code, e.g. variable declarations as "var" or getter methods like in the example below.
The code shows t.message, but the code behind this visual abbrevation is t.getMessage(). How can I disable that feature and always show t.getMessage()?
Abbreviated code:

Real code:

Because I don't know the name of the feature I have no idea what I am looking for. Any ideas?

A: To disable showing val/var instead of variable type
go to Settings | Editor | General | Code Folding
and UnCheck Variable Declaration
And just next to it
Uncheck Getters and setters
to start showing getter Setter method calls with full method name
refer- https://stackoverflow.com/a/48271952/3661654


text:
Q: Get current Hour/Minute/Secong/Millisecond using timezone of some specific city like America/Mexico_City in swift 3 xcode Here, I want to get current Hour/Minute/Secong/Millisecond using timezone of some specific city like America/Mexico_City using swift 3 xcode. I tried to get current Time-hrs/min/sec/millisec of Mexico city like,
    let date = Date()
    var calendar = Calendar.current
    calendar.timeZone = TimeZone.init(identifier: "America/Mexico_City")! /* Something wrong here */

    hrOfDay = calendar.component(.hour, from: date)
    curMin = calendar.component(.minute, from: date)
    curSec = calendar.component(.second, from: date)
    curMillSec = Int(Int64(Date().timeIntervalSince1970 * 1000)) /* this should be fetched using calendar object */
    print("hours = \(hrOfDay):\(curMin):\(curSec):\(curMillSec)")

But I'm unable to get current time of some specific city like MexicoCity. So, Please help me out.

A: TimeZone.init(identifier: "America/Mexico_City")
'America/Mexico_City' is ID, not a name.
so, you can compare to get TimeZone ID by City name from list:
https://raw.githubusercontent.com/dmfilipenko/timezones.json/master/timezones.json

Ref: https://github.com/dmfilipenko/timezones.json

A: SOLVED FINALLY
Step 1:
Using this LINK find the city/country abbreviation abbr.
Step 2:
Using the link mentioned in step 1, you will get JsonObject as response like example for mexico city:
{
"value": "Central Standard Time (Mexico)",
"abbr": "CDT",
"offset": -5,
"isdst": true,
"text": "(UTC-06:00) Guadalajara, Mexico City, Monterrey",
"utc": [
  "America/Bahia_Banderas",
  "America/Cancun",
  "America/Merida",
  "America/Mexico_City",
  "America/Monterrey"
]
}

Step 3: So use this abbr key value like TimeZone.init(abbreviation: "CDT") which is clearly mentioned below.
func initVars(){

    var date = Date()
    var calendar = Calendar.current
    calendar.timeZone = TimeZone.init(abbreviation: "CDT")!
    hrOfDay = calendar.component(.hour, from: date)
    curMin = calendar.component(.minute, from: date)
    curSec = calendar.component(.second, from: date)
    curMillSec = calendar.component(.nanosecond, from: date) // may need to convert NANOSECOND to Millisecond // this should be fetchhed using calendat obj
    print("TESTING Current Time = \(hrOfDay):\(curMin):\(curSec):\(curMillSec)")

}

So Finally, as result you will get like:
TESTING Current Time = 10:39:17:812892973

Current Mexico time: 10:39 AM Thursday, November 16, 2017 (CST) Time in Mexico City, CDMX, Mexico


text:
Q: Paste does not return necessary output in R I have a vector a<-c("cars","balls"), then I want to achieve following output \"cars\",\"balls\" using paste0("\"",a,"\"", collapse = ","). However as an output I have only "'cars'", "'balls'". How I can  I achieve the necessary output?

A: You need   cat(paste0('\\"',a,'\\"', collapse = ","))


text:
Q: count of records that have matched conditions inside a bool query I have an ES query along the lines of  (condition1 or condition2 or condition3....) and otherConditions.
Each condition inside the brackets is  a 'must' clause that searches for all documents that match a given name, location and product.
GET index/type/_count
{
  "query": {
    "bool": {
      "should": [
        {
          "bool": {
            "must": [
              {
                "term": {
                  "NAME": {
                    "value": "name1"
                  }
                }
              },
              {
                "term": {
                  "PRODUCT": {
                    "value": "product1"
                  }
                }
              },
              {
                "term": {
                  "LOCATION": {
                    "value": "location1"
                  }
                }
              }
            ]
          }
        },
        {
          "bool": {
            "must": [
              {
                "term": {
                  "NAME": {
                    "value": "name2"
                  }
                }
              },
              {
                "term": {
                  "PRODUCT": {
                    "value": "product2"
                  }
                }
              },
              {
                "term": {
                  "LOCATION": {
                    "value": "location2"
                  }
                }
              }
            ]
          }
        }
      ],
      "must_not": [
        {
          "exists": {
            "field": "some other condition"
          }
        }
      ],
      "must": [
        {
          "term": {
            "somefield": "value"
          }
        },
        {
          "range": {
            "time": {
              "gte": "now-6M"
            }
          }
        }
      ]
    }
  }
}

Is it possible to get count of  records that matches each of the 'must' clause inside the 'should' clause instead of an overall count using one query?

A: Yes, you can do it using aggregations, in particular filter aggregation. The query might look like this:
POST index/type/_search
{
  "query": {
    "bool": {
      "should": [
        "<clause1>",
        "<clause2>"
      ],
      "must_not": [
        "<mustNotClause3>"
      ],
      "must": [
        "<mustClause4>"
      ]
    }
  },
  "aggs": {
    "clause1": {
      "filter": "<clause1>"
    },
    "clause2": {
      "filter": "<clause2>"
    }
  }
}

Note that we are using _search API here. If you don't need search results, you can set size: 0, this will return you only total count and the aggregations.
In your case the query will literally be this:
POST index/type/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "bool": {
            "must": [
              {
                "term": {
                  "NAME": {
                    "value": "name1"
                  }
                }
              },
              {
                "term": {
                  "PRODUCT": {
                    "value": "product1"
                  }
                }
              },
              {
                "term": {
                  "LOCATION": {
                    "value": "location1"
                  }
                }
              }
            ]
          }
        },
        {
          "bool": {
            "must": [
              {
                "term": {
                  "NAME": {
                    "value": "name2"
                  }
                }
              },
              {
                "term": {
                  "PRODUCT": {
                    "value": "product2"
                  }
                }
              },
              {
                "term": {
                  "LOCATION": {
                    "value": "location2"
                  }
                }
              }
            ]
          }
        }
      ],
      "must_not": [
        {
          "exists": {
            "field": "some other condition"
          }
        }
      ],
      "must": [
        {
          "term": {
            "somefield": "value"
          }
        },
        {
          "range": {
            "time": {
              "gte": "now-6M"
            }
          }
        }
      ]
    }
  },
  "aggs": {
    "clause1": {
      "filter": {
        "bool": {
          "must": [
            {
              "term": {
                "NAME": {
                  "value": "name1"
                }
              }
            },
            {
              "term": {
                "PRODUCT": {
                  "value": "product1"
                }
              }
            },
            {
              "term": {
                "LOCATION": {
                  "value": "location1"
                }
              }
            }
          ]
        }
      }
    },
    "clause2": {
      "filter": {
        "bool": {
          "must": [
            {
              "term": {
                "NAME": {
                  "value": "name2"
                }
              }
            },
            {
              "term": {
                "PRODUCT": {
                  "value": "product2"
                }
              }
            },
            {
              "term": {
                "LOCATION": {
                  "value": "location2"
                }
              }
            }
          ]
        }
      }
    }
  }
}

Note that sum of counts of aggregations clause1 and clause2 may be greater than total count.
Hope that helps!


text:
Q: ESP8266 ICSP design: which circuit design guidelines to avoid fails/damages? I'm working on a project which is all on breadboard right now. I'm close to final version, so I'm planning to design PCB for the release (not commercial use, just for some friends of mine).
The microcontroller is an ESP8266-12E, and I want to be able to program it after it has been soldered to PCB (so ICSP). To achieve that, I planned a pin-strip to expose:

*

*RX

*TX

*GPIO0

*GPIO2 (not sure about that, some schematic don't use it)

*GPIO15

*CHPD

*VCC

*GND

according with programmer schematics you can found online (eg. this or this).
This is how 'programming relevant' pins are used in my project:

*

*RX and TX pins are used for a GPS module connection.

*GPIO2 used as 'debug serial'

*GPIO0 used as output

*GPIO15 not used

I never worked with ICSP so I'm quite confused about some points:

*

*Resistors in programmers schematics (like the second link I post): should I put them on the programmer board (which will be then connected to pin-strip with a cable to program) or should be placed into the PCB?

*Are there any other PCB/schematic design guidelines I must to know to safe perform an In-Circuit-Programming procedure without damage other PCB device/IC or the microcontroller? (eg. pull-up/down, decoupling, etc)

A: First you need to understand which and how these GPIOs are used. You can also check this. In practice, for normal operation and boot from the flash memory, GPIO15 should be LOW, and GPIO0 and GPIO2 should be HIGH at start-up. When you want to load a new image, all you have to do is pull GPIO0 to LOW state during startup, while the two other GPIOs remain as previously, and then the ESP8266 is ready to receive the program over the UART interface.
Additionally, CHPD should be HIGH at all times, otherwise the IC will not run at all. CHPD stand for "CHip Power Down" and although it is badly named, it is active low.
Now, to bring the ESP8266 in the start-up mode which is necessary when you want to program it, you either have to remove power and apply again, send a LOW pulse on the RST pin or send a LOW pulse on the CHPD pin.
Thus, the pull-up/pull-down resistors that you mention should be put on the main PCB. They are, anyway, necessary for the normal operation of the board (like the pull-up on the CHPD pin). Do not rely on the internal pull-up/pull-downs that may be present in the IC.
From the above you can also see that basically only GPIO0 and the UART interface are really necessary for programming the ESP8266. There is no need to use GPIO15 and GPIO2. And the CHPD could be used to reset the IC, but this is not necessary, since you could do the same by removing and re-applying the power supply.
From these pins, I think only the UART interface should be looked closely in your case, since you have it connected to another IC already. If I were you, if I wanted to be 100% sure, I'd probably use some way of interruption (e.g. jumpers or switches) between the ESP8266 and the GPS module. During normal operation you will keep the two ICs connected. But when you want to load a new image, you will need to interrupt this connection so that there is not interference from the GPS module to the signals from your programmer that could make the loading process to fail.
One last friendly advice! Before doing your PCB, just test the circuit you want to implement on the breadboard and confirm it works or do the necessary modifications!


text:
Q: How can I use v-for with computed variable I want use v-for nav items via my authority and another things.
this is my code.
 <template v-for="(subItem, index2) in item.children">
     <v-list-item sub-group  link :to="subItem.link" exact v-if="item.auth === true"  :key="index + '_sub_' + index2">
         <v-list-item-title v-text="subItem.title" ></v-list-item-title>
     </v-list-item>
</template>

i want disable click v-if="item.auth === true
here is my object
children: [
    {name:'menu1', title:'menu1', link:'/company/menu1', auth: () => {return this.currentNav===0 }}, // not work
    {name:'menu2', title:'menu2', link:'/company/menu2', auth: true}, // work
    {name:'menu3', title:'menu3', link:'/company/menu3', auth: this.MyInfo.Auth.menu3Auth === true }, // work, but not changed menu visible on this.MyInfo.Auth.menu3Auth value change.
    {name:'menu4', title:'menu4', link:'/company/menu4', auth: () => {return this.currentNav===4 || this.MyInfo.Auth.menu3Auth === true }},
    {name:'menu5', title:'menu5', link:'/company/menu5', auth: () => {return this.MyInfo.Auth.menu5Auth === false && this.MyInfo.Auth.menu3Auth === true  }
}

but it not work as I thought
how can i fix it?

A: To do conditions on a v-for, move them into a computed property:
computed: {
  authItems() {
    return this.items.children.filter((x) => {
      if (typeof x.auth === 'function') {
        return x.auth();
      }
      return x.auth === true;
    });
  },
},

then
 <template v-for="(subItem, index2) in authItems">
     <v-list-item sub-group  link :to="subItem.link" exact :key="index + '_sub_' + index2">
         <v-list-item-title v-text="subItem.title" ></v-list-item-title>
     </v-list-item>
</template>

It is the way you can treat conditions. In another way, you can do something like it, but it's not so clear:
 <template v-for="(subItem, index2) in item.children.filter((x) => x.auth === true)">
     <v-list-item sub-group  link :to="subItem.link" exact :key="index + '_sub_' + index2">
         <v-list-item-title v-text="subItem.title" ></v-list-item-title>
     </v-list-item>
</template>


text:
Q: How to 'lump' common facet headers in ggplot when using facet_grid I am using facet_grid in package "ggplot2" to facet columns by two variables.  Each facet gets two header stips - one for each conditioning variable.  Each value of the first variable is repeated for all levels of the second variable.  I would like to know if I could have a single header for the first variable spread across all levels of the second variable.
Here is a toy example:
dat <- expand.grid(x=c(0,1), A=c("a1","a2"), B=c("b1","b2","b3"))
dat$y <- rnorm(nrow(dat))
ggplot(dat, aes(x, y)) + geom_point() + facet_grid(~A+B)

Each level of A is repeated in 3 consecutive headers - one for each level of B.  I would like to have just two header strips for A - one covering the first 3 panels, and another for the second 3 panels.
Does anyone know if/how this can be done?


text:
Q: django tables2 checkbox I'm new to programming so this may be a trivial question...
In django-tables2, I'd like to be able to display the column header name when using CheckBoxColumn. Right now, all the checkboxes are displaying for each row, including in the header. I don't mind having a checkbox in the header (I figure that would be a great way to do a "select all" in the long run), but I need the column name to display. Does anyone have a solution for this?

A: Create your own custom checkbox column class that inherits from tables.CheckBoxColumn
then override the render method, then specify the check box together with its label as html response.
class CustomCheckBoxColumn(tables.CheckBoxColumn):

    def render(self, value, record, bound_column):
        return mark_safe(u'column Name<input type=checkbox, … />')

A: Another option is to use the TemplateColumn() instead of CheckBoxColumn()
template = '<input type="checkbox" name="{{record.name}}" />'
checkbox_column_header = tables.TemplateColumn(template)


text:
Q: Adding an if condition to Promise.all I am trying to do the following:
When I am on the cart page and click the CHECKOUT button, then there are 2 things that can happen:
I am redirected to the checkout page
I am asked sometimes to log in again => this is a bug in the app since I am already logged in but it asks me to log in again for some reason.
I need to write a Playwright test for the checkout process.
And in this test, I need to support that buggy behavior since there is no indication it will be resolved any time soon (or whatsoever).
This is what I got so far:
async clickCheckoutBtn() {
    if (this.#isGuest) {
      // redirects to the login page, so we don't have waitForURL like when we are logged in
      await this.#checkoutBtn.click();
    } else {
      // TODO add here somehow to login again if required after clicking the checkout button
      await Promise.all([
        this.page.waitForResponse(
          (response) =>
            response.url().includes('/my-account/addressform') &&
            response.status() === ResponseCode.SUCCESS
        ),

        this.#checkoutBtn.click(),
        this.page.waitForURL(/.*\/delivery-address\/add$/),
      ]);
    }
  }

Now, this is what I would like to do:
await page.getByRole('button').click();
    if(await page.getByPlaceholder('login').isVisible()) {
      await loginPage.login(username, password);
    }
    await page.waitForURL(/.*\/delivery-address\/add$/),

But in the case when I am redirected to the checkout I also need to waitForResponse of the /my-account/addressform. (so after logging in I need to wait for it, but also after direct redirect to the checkout page, I need to wait for it as well)
So I would like to do this somehow inside the Promise.all, but I don't how to do it.
Can you please help?

A: Yes you can do something like below using ternary operator.
Promises are future values which can be captured in variables and moved around in code asynchronously.
var p1 = page.getByRole('button').click();
var p2 = (await page.getByPlaceholder('login').isVisible()) ? loginPage.login(username, password) : Promise.resolve() //else empty promise which will resolve immediately
Promise.all([p1, p2]).then(results => {
       await page.waitForURL(/.*\/delivery-address\/add$/)
});

More abstract version of it for general understanding:
var p1 = functionA();
var p2 = condition ? functionB() : Promise.resolve(); // or empty promise
Promise.all([p1, p2]).then(results => {
      // code to handle results
});


text:
Q: Load configuration constants dynamically invoking the setters? I'm looking for a nice way to set my configuration constants. My idea was to create a singleton with  my config properties. Say mySingletonConf with: URL, USERID, PASSWORD. During the initialization of the sharedInstance, a configuration file should be read to set the properties in mySingletonConf.

*

*Should I use properties for this type of constants? I take they should be class-level properties?

*Is it possible to set the configuration dynamically? I. e.
by reading all Setter-Methods of mySingletonConf, then searching the loaded  configuration (.plist-Dictionary) for the key == property name and then invoke the settter with the value?

It would be nice to have the things set dynamically, in case new constants are needed. Then I would just have to create new properties and adjust the configuration files.
Am I on the right track?
Thanks for any help!

A: NSUserDefaults can take care of a lot of stuff and it ensures that the configuration is user-specific, so if multiple users on the same Mac use your program they can configure your program independently. There is also an object in Interface Builder for binding your user interface elements to, making things even easier. If you do want to make your configuration system-wide, you should use the Core Foundation Preference Utilities.
For storing passwords, you can use Apple's Keychain Services. A user is able to specify which programs are allowed to use the stored password (which would ideally be just yours). Storing passwords in NSUserDefaults is also an option if the password is not of any particular importance.
Don't re-invent the wheel; application-wide user-or-host-specific configuration services are provided for you.

A: Well, it is possible :)
I ended up writing the mentioned Singleton, which has readonly public properties and readwrite access from within the class (used Categories for that, see private setter example).
The vars of the class are filled with values from the .plist file during the initialization. I used the Runtime API to get the list of variables (just search for "objective-c list of variables" on Stackoverflow) and get the value from the loaded.plist dictionary using the var name as key.
The the values can be use almost as constants:
MyConstants* testConstants = [MyConstants sharedInstance];
NSLog(testConstants.PARAM1);


text:
Q: Ipad/Iphone versions, 2 targets, 1 code base I am currently working on a cocos2d game for iOS. Currently I am checking at runtime if it is an ipad or iphone running and adjusting coordinates et.c. for this.
But now I want two versions, one for iPad and one for iPod touch/iPhone. So I want two targets but still use the same codebase.
Currently I check for
UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad

to determine if which device is used. But now I want to check which app/target is used. In case someone uses the iPhone version on the iPad, I do not want it to be adjusted for iPad (the iphone version cost less so should not adjusted for ipad).

A: A good way to change your behavior in different targets whilst using exactly the same code base is to create a pre-processor definition and omit it in one of the targets or set it differently in each of the targets. Then your code can be compiled differently to alter its behaviour based on this definition (for example through conditional compilation if you use an #ifdef directive).

A: If for the iPhone app target you set the target device family to just iPhone, UI_USER_INTERFACE_IDIOM() will always return UIUserInterfaceIdiomPhone, even when on an iPad.


text:
Q: Integral $\int_{-\infty}^\infty\frac{\Gamma(x)\,\sin(\pi x)}{\Gamma\left(x+a\right)}\,dx$ I would like to evaluate this integral:
$$\mathcal F(a)=\int_{-\infty}^\infty\frac{\Gamma(x)\,\sin(\pi x)}{\Gamma\left(x+a\right)}\,dx,\quad a>0.\tag1$$
For all $a>0$ the integrand is a smooth oscillating function decaying for $x\to\pm\infty$. The poles of the gamma function in the numerator are cancelled by the sine factor.
For $a\in\mathbb N$, the ratio of the gamma functions simplifies to a polynomial in the denominator, and in each case the integral can be pretty easily evaluated in a closed form, e.g.
$$\mathcal F(3)=\int_{-\infty}^\infty\frac{\sin(\pi x)}{x\,(x+1)\,(x+2)}\,dx=2\pi.\tag2$$
Can we find a general formula for $\mathcal F(a)$ valid both for integer and non-integers positive values of $a$?

A: To me the most obvious action would be:
$$\int_{-\infty}^\infty\frac{\Gamma(x)\,\sin(\pi x)}{\Gamma\left(x+a\right)} dx=\frac{1}{\Gamma(a)}\int_{-\infty}^\infty B(x,a)\,\sin(\pi x) dx$$
$$\int_{-\infty}^\infty B(x,a)\,\sin(\pi x) dx=\int_{-\infty}^\infty \int_0^1 t^{x-1}(1-t)^{a-1} \sin(\pi x) ~dt~ dx$$
However the integral for $x$ diverges, we can only find the part for $x>0$ (because $\ln t<0$):
$$\int_{0}^\infty t^{x} \sin(\pi x) ~dx=\int_{0}^\infty e^{(\ln t)x} \sin(\pi x) ~dx= \frac{\pi}{\pi^2+\ln^2 t}$$
So we have for the part with $x>0$:
$$\int_{0}^\infty\frac{\Gamma(x)\,\sin(\pi x)}{\Gamma\left(x+a\right)} dx=\frac{\pi}{\Gamma(a)} \int_0^1 \frac{(1-t)^{a-1}}{t(\pi^2+\ln^2 t)} ~dt$$
We can make an obvious substitution:
$$ \int_0^1 \frac{(1-t)^{a-1}}{t(\pi^2+\ln^2 t)} ~dt=\int_0^\infty \frac{(1-e^{-u})^{a-1}}{\pi^2+u^2} du$$
Or we can use the integral representation of the Gregory coefficients somehow (thanks, Jack D'Aurizio!):
$$\displaystyle G_n=(-1)^{n-1}\!\int\limits_0^{\infty}\frac{dx}{(1+x)^n\left(\ln^2 x + \pi^2\right)}$$
If this leads anywhere, I'll edit my post.

A: Interesting question. By using the reflection formula, your integral can be written as a convolution integral:
$$ I(a) = \pi \int_{-\infty}^{+\infty}\frac{dx}{\Gamma(x+a)\Gamma(1-x)}.\tag{1}$$
We may also notice that when $n\in\mathbb{N}$ we have:
$$ \int_{-\infty}^{+\infty}\frac{\sin(\pi x)\,dx}{x(x+1)\cdot\ldots\cdot(x+n)}=\pi\sum_{k=0}^{n}(-1)^k \text{Res}\left(\frac{1}{x(x+1)\cdot\ldots\cdot(x+n)},x=-k\right)\tag{2}$$
where the $RHS$ of $(2)$ equals:
$$ \frac{\pi}{n!}\sum_{k=0}^{n}\binom{n}{k} = \color{red}{\frac{\pi\, 2^n}{n!}}\tag{3} $$
so the most reasonable conjecture is:

$$ I(a) = \pi \int_{-\infty}^{+\infty}\frac{dx}{\Gamma(x+a)\Gamma(1-x)}\stackrel{!}{=}\color{red}{\frac{\pi\, 2^{a-1}}{\Gamma(a)}}.\tag{4}$$

Numerical simulations support $(4)$. Probably it is enough to exploit the log-convexity of the $\Gamma$ function to extend the validity of $(4)$ from $a\in\mathbb{N}$ to $a\in\mathbb{R}^+$.
Update: As a matter of fact, this Sangchul Lee's blogpost proves that the partial fraction decomposition through the residue theorem still works for $a\in\mathbb{R}^+\setminus\mathbb{N}$, setting $(4)$ as an identity. Credits to him for another great piece of cooperative math.
Following Yuriy S' approach,
$$ \int_{-\infty}^{+\infty}B(a,x)\sin(\pi x)\,dx \\=\int_{0}^{+\infty}\int_{0}^{1}\left[(1-t)^{a-1}t^{x-1}\sin(\pi x)+t^{x-a}(1-t)^{a-1}\sin(\pi(a-x))\right]\,dt\,dx$$
leads to an integral that can be easily evaluated through the residue theorem, giving an alterntive proof of $(4)$.

A: Let
$$g(x) = \frac{\Gamma(x)\,\exp(i\pi x)}{\Gamma\left(x+a\right)},\quad a>0$$
and
$$\mathcal G(a)=\int_{-\infty}^\infty g(x)\,dx.$$
The residues of $g$ are along the real line at $z\in-\mathbb N$:
\begin{align}
r_n&=\operatorname*{Res}_{z = -n}g(z) \\
&= \lim_{z\to-n}  (z+n) \frac{\Gamma(z+n+1)}{(z+n)(z+n-1)\cdots(z+1)} \frac{e^{i\pi z}}{\Gamma\left(z+a\right)}\\
&= \frac{e^{-i\pi n}}{\Gamma(a-n)} \frac{(-1)^n}{n!} \\
&= \frac{1}{n! \Gamma(a-n)}
\end{align}
Then, considering a semicircular contour along $\mathbb R$ and $R e^{i\theta}$, indented around each pole, we have
$$\mathcal G(a) = \pi i\sum_{n=0}^\infty r_n = \pi i \frac{1}{\Gamma(a)}\sum_{n=0}^\infty {a-1\choose n} = \pi i \frac{2^{a-1}}{\Gamma(a)}.$$
It is clear that the outer part of the contour makes no contribution since for large $|z|$, $|g(z)| \le \frac{R e^{-\pi y}}{|P_{\lfloor a \rfloor}(z)|}$.
Now take the complex part to conclude
$$\boxed{\mathcal F(a) = \pi\frac{2^{a-1}}{\Gamma(a)}}$$
which is valid for all $a>0$.


text:
Q: I have a problem when I want to install auto py to exe it does not work hi i have a problem when i do "pip install auto-py-to-exe" in cmd
its puts me:
"note: This error originates from a subprocess, and is likely not a problem with pip.
error: legacy-install-failure
  Encountered error while trying to install package.

  greenlet

  note: This is an issue with the package mentioned above, not pip.
  hint: See above for output from the failure.
  [end of output]

note: This error originates from a subprocess, and is likely not a problem with pip.
error: subprocess-exited-with-error
× pip subprocess to install build dependencies did not run successfully.
│ exit code: 1
╰─> See above for output.
note: This error originates from a subprocess, and is likely not a problem with pip. "
I have to do what ? please


text:
Q: Atom text editor colors are changed randomly In the last couple of months, weird thing happen to Atom on my laptop (and also on my mac - recently tested).
Randomly, the colors of the  text editor are being changed completely. Its like the styles.scss is somehow overriden, but it's same as default file, no changes made.
Even clearing window state, or opening on safe mode - doesn't help.
The only thing that helps is re-installing - and also then, after few days of works - suddenly it happens again!
Am i going crazy or this issue is known?
Thank you.


text:
Q: why i am getting error for this one like Unexpected template string expression no-template-curly-in-string  <Card className='my-3 p-3 rounded'>

    <Card.Img src={product.image} variant='top' />

</Card>

here i am posting my code i am getting the error while running npm start
Unexpected template string expression  no-template-curly-in-string

A: You should replace quotes (') to a backtick quotes (`) at your href inside  tag like this.
Before:

After:
<a href={`/product/${product._id}`}>
Here is link to eslint doc page for more information.


text:
Q: Applescript to Launch Chrome (with specifics) I'm really struggling with creating some method of launching a browser window (chrome) on osx with specifics such as window size, no tabs etc. Traditionally I've used vb script through windows with IE which is a pretty simple exercise but I'll be the first to admit, when it comes to macs I struggle greatly.
So here is my wish list.
I need to be able to open a window (ideally in chrome, but any other browser except safari), that has no status bar, no address bar with a given URL, and a specific window size. I did manage something in safari using do javaScript, and attempted the same with chrome using execute javascript and 'window.open' but this failed continually...
Help!

A: I didn't find any way to hide the toolbar in Chrome, but try something like these scripts:
tell application "Google Chrome"
    open location "http://example.com"
    tell window 1 to enter presentation mode
end tell

tell application "Google Chrome"
    tell (make new window)
        set URL of active tab to "http://example.com"
        set bounds to {0, 22, 1200, 900}
    end tell
    activate
end tell

tell application "Safari"
    make new document with properties {URL:"http://example.com"}
    tell window 1
        set bounds to {0, 22, 1200, 900}
    end tell
    activate
end tell
tell application "System Events" to tell process "Safari"
    tell menu "View" of menu bar 1
        if exists menu item "Hide Toolbar" then click menu item "Hide Toolbar"
        if exists menu item "Hide Status Bar" then click menu item "Hide Status Bar"
        if exists menu item "Hide Tab Bar" then click menu item "Hide Tab Bar"
        if exists menu item "Hide Bookmarks Bar" then click menu item "Hide Bookmarks Bar"
    end tell
end tell


text:
Q: LayoutManager doesn't work well with a background-image content pane i'm having a little trouble positioning my components on the container which draws an image as background. why is this so? i want those four buttons aligned vertically somewhere at the right side of the frame. whatever layouting technique i use, the buttons' positions just appear to be unchanged.

here's my background image panel. is there anything in it responsible for this unchangeability of the components? does it lack something?
    static class bgImagePanel extends JPanel {
     Image bgimage = null;

      bgImagePanel(BorderLayout b) {
      MediaTracker mt = new MediaTracker(this);
      bgimage = Toolkit.getDefaultToolkit().getImage("bgimage1.jpg");
      mt.addImage(bgimage, 0);
        try {
         mt.waitForAll();
        } catch (InterruptedException e) {
        }
      }

      @Override
      protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      int imwidth = bgimage.getWidth(null);
      int imheight = bgimage.getHeight(null);
      g.drawImage(bgimage, 1, 1, imwidth, imheight, null);
      }
    }

A: The problem seems to be you never override the default layout manager (FlowLayout) in your bgImagePanel. You should call super(b) or setLayout(b) in its constructor:
public bgImagePanel(BorderLayout b) {
    super(b);
    MediaTracker mt = new MediaTracker(this);
    bgimage = Toolkit.getDefaultToolkit().getImage("bgimage1.jpg");
    mt.addImage(bgimage, 0);
    try {
       mt.waitForAll();
    } catch (InterruptedException e) {}
}


text:
Q: Check if a specific exe file is running I want to know how i can check a program in a specific location if it is running. For example there are two locations for test.exe in c:\loc1\test.exe and c:\loc2\test.exe. I only wanted to know if c:\loc1\test.exe is running and not all instances of test.exe.

A: bool isRunning = Process.GetProcessesByName("test")
                .FirstOrDefault(p => p.MainModule.FileName.StartsWith(@"c:\loc1")) != default(Process);

A: try this... I use it to determine at startup if another process is already running with the same name as the exe I'm trying to start, and then just bring that one to foreground, (and to focus) if it is already running... You could modify it to take a process name and test for that specific name...  This will tell you if there is a process running with a certain name, but not where that process was loaded from ...
If there is a process running with the specified name, then if that process had an exposed accessible method that returns where it was loaded from, you could call that method on the running process, otherwise, I don't know..
But just out of curiosity, why do you care, unless they're different?  And if they're different in some way, code to use that difference (whatever it is) to detect which is loaded.  But if they're the same how can it matter which on-disk image was used to load it?
    [DllImport("user32.dll")]
    private static extern bool SetForegroundWindow(IntPtr hWnd);
    [DllImport("user32.dll")]
    private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
    [DllImport("user32.dll")]
    private static extern bool IsIconic(IntPtr hWnd);

    private const int SW_HIDE = 0;
    private const int SW_SHOWNORMAL = 1;
    private const int SW_SHOWMINIMIZED = 2;
    private const int SW_SHOWMAXIMIZED = 3;
    private const int SW_SHOWNOACTIVATE = 4;
    private const int SW_RESTORE = 9;
    private const int SW_SHOWDEFAULT = 10;

 private static bool IsAlreadyRunning()
    {
        // get all processes by Current Process name
        Process[] processes =
            Process.GetProcessesByName(
                Process.GetCurrentProcess().ProcessName);

        // if there is more than one process...
        if (processes.Length > 1)
        {
            // if other process id is OUR process ID...
            // then the other process is at index 1
            // otherwise other process is at index 0
            int n = (processes[0].Id == Process.GetCurrentProcess().Id) ? 1 : 0;

            // get the window handle
            IntPtr hWnd = processes[n].MainWindowHandle;

            // if iconic, we need to restore the window
            if (IsIconic(hWnd)) ShowWindowAsync(hWnd, SW_RESTORE);

            // Bring it to the foreground
            SetForegroundWindow(hWnd);
            return true;
        }
        return false;
    }

A: You should iterate over all existing processes and then check their MainModule property for the file name you are looking for. Something like this
using System.Diagnostics;
using System.IO;

//...

string fileNameToFilter = Path.GetFullPath("c:\\loc1\\test.exe");

foreach (Process p in Process.GetProcesses())
{
   string fileName = Path.GetFullPath(p.MainModule.FileName);

   //cehck for equality (case insensitive)
   if (string.Compare(fileNameToFilter, fileName, true) == 0)
   {
      //matching...
   }
}

A: This function may help:
using System.Diagnostics;

public bool IsProcessOpen(string name)
{
    foreach (Process clsProcess in Process.GetProcesses()) {
        if (clsProcess.ProcessName.Contains(name))
        {
            return true;
        }
    }
    return false;
}

Source: http://www.dreamincode.net/code/snippet1541.htm

A: This is my improved function :
private bool ProgramIsRunning(string FullPath)
{
    string FilePath =  Path.GetDirectoryName(FullPath);
    string FileName = Path.GetFileNameWithoutExtension(FullPath).ToLower();
    bool isRunning = false;

    Process[] pList = Process.GetProcessesByName(FileName);

    foreach (Process p in pList) {
        if (p.MainModule.FileName.StartsWith(FilePath, StringComparison.InvariantCultureIgnoreCase))
        {
            isRunning = true;
            break;
        }
    }

    return isRunning;
}

and use it  as :
ProgramIsRunning(@"c:\loc1\test.exe");

A: Something like this. GetMainModuleFileName helps to access x64 process from x86.
[DllImport("kernel32.dll")]
public static extern bool QueryFullProcessImageName(IntPtr hprocess, int dwFlags, StringBuilder lpExeName, out int size);

private bool CheckRunningProcess(string processName, string path) {

    var processes = Process.GetProcessesByName(processName);

    foreach(var process in processes) {

        var name = GetMainModuleFileName(process);
        if(name == null)
            continue;

        if(string.Equals(name, path, StringComparison.InvariantCultureIgnoreCase))
            return true;
    }

    return false;
}

// Get x64 process module name from x86 process
private static string GetMainModuleFileName(Process process, int buffer = 1024) {

    var fileNameBuilder = new StringBuilder(buffer);
    int bufferLength = fileNameBuilder.Capacity + 1;

    return QueryFullProcessImageName(process.Handle, 0, fileNameBuilder, out bufferLength)
        ? fileNameBuilder.ToString()
        : null;
}

A: You could use a named mutex, that's named off of the directory structure the program is running in.

A: System.Reflection.Assembly.GetEntryAssembly()

This will bring for you a lot of info about the entry assembly, such as:
System.Reflection.Assembly.GetEntryAssembly().CodeBase;

This will tell the location of the running assembly.


text:
Q: PHP - Outsource switch cases in different files I want a switch-case instruction but outsource all the case-statements in diffenrent files.
Like this:
<?php
switch ($a) {
    foreach (glob("/path/*.php") as $filename) {
            include $filename;
        }
}

and in /path/ there are files like a.php and b.php with contents like
<?php
case 1:
    echo "hello";
    break;

How can I do this?
Edit:
I am using PHP7.1 if this is of interest.

A: Your first code snippet will fail instantly because it is not valid syntax. switch/case statements have a true/false expression system. You can use in_array to retrieve your results. (assuming $a is the file name you are looking for)
Example:
$files = ['/path/to/file.txt','/path/to/file2.txt'];

$a = '/path/to/file.txt';
switch($a) {

    case in_array($a,$files) :
      echo 'test';
    break;

    default :

}

In your example, you can try:
$location = glob("/path/");

switch($a) {

    case in_array($a,$location) :
      include $a;
    break;

    default :

}

This is just example code of what you could do. There are many other ways to accomplish this, but you haven't given all the fact, such as $a values.
However, you may be wanting to run a whole set of files on different values of $a, another example:
switch($a) {
    case 'value_of_something_one' :
      foreach (glob("/path/to/one") as $filename) {
        include $filename;
      }
    break;

    case 'value_of_something_two' :
      foreach (glob("/path/to/two") as $filename) {
        include $filename;
      }
    break;

    default :
}

Hope any of this helps.
PHP Documentation: (switch/case)
http://php.net/manual/en/control-structures.switch.php

A: The only solution I found for this is to change the switch-case to some if-statements:
$a = $_GET['something'];
foreach (glob("/path/*.php") as $filename) {
    include $filename;
}

And then in a.php
if ($a == 1) {
    echo "hello1";
}

in b.php
if ($a == 2) {
    echo "hello2";
}

and so on...


text:
Q: Python: Rename directories with subdirectories I've read a few other posts and tried the code in those answers but can't get mine to work.
This is my file structure:
motherfile g934uth98t
motherfile g934uth98t/kid file fh984bvt34ynt
motherfile g934uth98t/kid file fh984bvt34ynt/something elsee goes here 98573v4985hy4
motherfile g934uth98t/big bad wolf r6b5n656n

The goal is:
motherfile
motherfile/kid file
motherfile/kid file/something elsee goes here
motherfile/big bad wolf

This is my code:
for root, dirs, files in os.walk(".", topdown=True):
    for name in dirs:
        direc = os.path.join(root, name)
        newdirec = '.'
        for part in direc.split('\\')[1:]:
            newdirec += '\\'
            newdirec += ' '.join(part.split()[:-1])
        os.rename(direc,newdirec)

Without the os.rename, and using prints (direc then newdirec), it works fine.
motherfile g934uth98t
motherfile
motherfile g934uth98t/kid file fh984bvt34ynt
motherfile/kid file
motherfile g934uth98t/kid file fh984bvt34ynt/something elsee goes here 98573v4985hy4
motherfile/kid file/something elsee goes here
motherfile g934uth98t/big bad wolf r6b5n656n
motherfile/big bad wolf

However, when it renames, it does the motherfile, but then all the other directories no longer exist (as they're relative to motherfile g934uth98t), so the script ends.
With topdown=False, I get an error:
FileNotFoundError: [WinError 3] The system cannot find the path specified: '.\\motherfile g934uth98t\\kid file fh984bvt34ynt\\something elsee goes here 98573v4985hy4' -> '.\\motherfile\\kid file\\something elsee goes here'
How can I fix this?
EDIT:
Tried this, still no luck, same error (second one). Perhaps it's a Windows file directory format issue?
import os

originaldirs = []
count = 0

def collect():
    global originaldirs
    originaldirs = []
    for root, dirs, files in os.walk(".", topdown=False):
        for name in dirs:
            originaldirs.append(os.path.join(root, name))
    global count
    count += 1

def rename_first():
    target = originaldirs[count]
    print(target)
    newdirec = '.'
    for part in target.split('\\')[1:]:
        newdirec += '\\'
        newdirec += ' '.join(part.split()[:-1])
        newdirec.replace('\\','//')
    # os.rename(target,newdirec)
    print(newdirec)

while True:
    try:
        collect()
        rename_first()
    except IndexError:
        print('Fin')
        break

A: Try this:
from pathlib import Path

for path in Path(".").glob("**/*"):
    if path.is_dir():
        target = path.parent / " ".join(path.name.split()[:-1])
        path.rename(target)