text:
Q: Why does regression model theory not use measure-theoretic sigma-field type notation but counting process models do? I have been studying counting process theory for time to recurrent event processes and am interested in the explicit use of the conditioning set in the model notation;
$$E[dN(t)|\mathcal{F}_{t^{-}}]=\lambda(t)dt$$
where $\lambda(t)$ is called the intensity of the risk of an event at time $t$. Where $\mathcal{F}_{t^{-}}$ is a sigma-field representing all relevant information about the counting process up to "just before" time $t$. Typically the sigma-field $\mathcal{F}_{t^{-}}$ is thought of as being genrated by a random covariate process $\mathcal{F}_{t^{-}}=\sigma(X(s):s<t)$ that contains the counting process history itself, and a Cox PHM type model is employed
$E[dN(t)|\mathcal{X}_{t^{-}}]=\lambda(t)dt=Y(t)\lambda_{0}(t)\exp(X(t)\beta)$
and given the "total information" in the conditioning information the recurrent events within individual subjects (people in a medical study or clinical trial say) are independent. This model is known as the Anderson-Gill model (1982, Annals of Statistics: Cox's regression model for counting processes). Given this conditional independence within subjects and assumed independence between subjects, my understanding is that the entire sample of event times can be modelled as per the standard Cox model and inference is valid. The key step is that the "compensator" $\Lambda(t)=\int_{0}^{t}\lambda(u)du$ renders the residuals $M_{\lambda}(t)$
$M_{\lambda}(t):=N(t)-\Lambda(t)$
a zero-mean martingale with respect to a filtration $(\mathcal{F}_{s})_{0\leq s <t}$ allowing the above model to be derived.
In constrast omitting some "dynamic" covariates such as event history leads to marginal models in the sense that lack of predictive information in the regression component means dependence within subjects will remain in the residuals and conditioning on this set (say $Z(t)\subset X(t)$ with sigma field $\mathcal{Z}_{t}\subset \mathcal{X}_{t}$) leads to the use of the model
$E[dN(t)|\mathcal{Z}_{t^{-}}]=\psi(t)dt=Y(t)\psi_{0}(t)\exp(Z(t)\beta)$
where for $\Psi(t)=\int_{0}^{t}\psi(u)du$ the residuals
$M_{\psi}(t):=N(t)-\Psi(t)$
are generally not a zero mean martingale. These models have been studied by Lin et al (2000, J. R. Statist. Soc: Semiparametric regression for the mean and rate functions of recurrent events) and inference proceeds by "naively" fitting a Cox PHM model as per the Anderson-Gill model and then correcting the variance of the resulting parameter estimator.
This approach of Lin for marginal models is redolent of Generalized estimating equations(GEE) for longitudinal data and this finally brings me to my question. The concept of conditioning sets and dependence of model residuals will surely hold too in the longitudinal setting? That is if total information was available and if one was permitted to use it (i.e. not in a randomised controlled trial for risk of bias) then model residuals would be conditionally independent within subjects and OLS regression could be used as opposed to (say) mixed effects models that model the covariance within subjects?
Mathematically I am wondering why the counting process notation is not used in presenting regression models. For example the standard for OLS regression is
$Y_{i} = X_{i}\beta + e$
where $e_{i}\sim N(0,\sigma^{2})$ and where the $X_{i}$ are modelled as fixed. This implies of course $E[Y_{i}|X_{i}]=X_{i}\beta$ which is the same [?] as assuming $X_{i}$ is random, independent of $e_{i}$ and that $e_{i}|X_{i}\sim N(0,\sigma^{2})$. The point is that the combination of the model, the covariate set and the residuals/errors are all linked: if $Y_{i}$ is cholesterol levels and $X_{i}$ intake of food and/or nutritional information etc., then $e_{i}\sim N(0,\sigma^{2})$ is plausible but if $X_{i}$ is the price of coffee in Brazil then clearly not. What in essence is being stated is surely something akin to counting process models? For example
$E[Y_{i}|\mathcal{X}_{t}]=X_{i}\beta$
where
$M_{i}:=Y_{i}-X_{i}\beta$
is a zero mean process with respect to a sigma-field $\mathcal{X}_{t}$;
$E[M_{i}|\mathcal{X}_{t}]=0$.
In this notation for repeated measures $Y_{i,j}$ for $i=1,...N$ subjects at times $j=1,...,n_{i}$, and if $X_{i}$ represents total information then conditional on $\mathcal{X}_{t}$ the entire set of observations $\{Y_{i,j}\}_{i,j}$ can be modelled as per OLS regression (in the spirit of Anderson-Gill models) but typically (due to lack of total information, or a preference for marginal models - they are easier to interpret) we use $\mathcal{Z}_{t}$ and model within-subject dependence.
Is the lack of sigma-field/conditioning set type notation for regression models because it is for some reason not relevant, or is it for convinience?
Update
Given the helpful response to this question I can now refine my question it a little and offer some of my own thoughts;
The time-series regression book provided develops the theory of Generalized Linear Models (GLMs) for the stochastic processes $(Y_{t})_{t\geq 0}$ and $(X_{t})_{t\geq 0}$ where the X's are a covariate process that incude past response history. Thus the theory appears to be precisely the same as the theory for counting process models (albeit with different models). For example $Y_{t}$ is assumed distributed from the exponential family;
$Y_{t}\sim f(y_{t}|\theta_{t},\phi,\mathcal{F}_{t})=\exp\left\{\frac{y_{t}\theta_{t}-b(\theta_{t})}{\alpha_{t}}+c(y_{t}|\phi)\right\}$
as per standard GLM notation - but obviously here there is a family of distributions indexed by $t$. The standard assumptions are made but conditional on the sigma field representing full covariate history (including response history);
$\mu_{t}=E[Y_{t}|\mathcal{F}_{t}]$
where $\mathcal{F}_{t}=\sigma\left\{Y_{t-1},Y_{t-2},...,X_{t-1},Y_{t-2,...}\right\}$. The difference with the counting process theory is that the times here are discrete instead of continuous. The mean $\mu_{t}$ is mapped onto the real line through the link function $g_{t}$;
$g(\mu_{t})=\eta_{t}=X_{t-1}\beta $
The mean and variance functions are related as per usual;
$\mu_{t}=b^{'}(\theta_{t})$
and
$Var[Y_{t}|\mathcal{F}_{t}]=\alpha_{t}(\phi)b^{''}(\theta_{t})$
In terms of inference the book focuses on partial likelihood which starts from the position of treating the pair $(Y_{t},X_{t})$ as random and factoring the joint density as follows
$f_{\theta}(x_{1},y_{N},...,x_{N},y_{N})=f_{\theta}(x_{1})\left[\prod_{t=2}^{N}f_{\theta}(x_{t}|d_{t})\right]\left[\prod_{t=1}^{N}f_{\theta}(y_{t}|c_{t})\right]$
where here the $N$ variables are on the same subject (subject index $i$ say dropped for clarity) and where $d_{t}=(y_{1},x_{1},...,y_{t-1},x_{t-1})$ and $c_{t}=(y_{1},x_{1},...,y_{t-1},x_{t-1},x_{t})$. The main idea is to drop the first two terms on the RHS the $X_{t}$ and hope that not too much information is lost about $\theta$. Obviously the story is that conditions are imposed to ensure this and of much interest is how reasonable or not these are. The partial likelihood is then defined as
$PL(\theta|y_{1},...,y_{N})=\left[\prod_{t=1}^{N}f_{\theta}(y_{t}|c_{t})\right]$
but since the $c_{t}$ include the past values of both $X_{t}$ and $Y_{t}$ (information that generates $\mathcal{F}_{t}$ then the densities in the right hand product are (presumably) defined to be conditional densities w.r.t the filtration $\mathfrak{F}:=(\mathcal{F}_{t})_{t\geq 0}$ - i.e. $\mathcal{F}_{t}\subset \mathcal{F}_{t+1}$ for all $t\geq 0$ and each $Y_{t}$ is measurable $\mathcal{F}_{t}/\mathbb{R}$
$PL(\theta|y_{1},...,y_{N})=\left[\prod_{t=1}^{N}f_{\theta}(y_{t}|\mathcal{F}_{t})\right]$
The martingale property that is central to the $M(t)$ in the counting process models appears in the score function $S_{N}(\beta)$ of the partial-likelihood which is a product involving the term $(Y_{t+1}-\mu_{t+1}(\beta))$ [... to be completed shortly]

A: In regression, the predictors $x$ is most often taken as given constants, not as random.  The name design matrix comes from that, the statistician has chosen (designed) the $x$ values where the observations is taken. This viewpoint is especially relevant for design of experiments.
In counting process models, time dependence is important, and the sigma-algebras is used there. So you could expect, maybe, that the same notation could be useful in regression settings where time dependence is an issue. Sometimes, one uses lagged values of the response $y$ in modeling time dependence. Now, the response $y$ becomes part of the predictors $x$, and the supposition that $y$ is random while $x$ is deterministic becomes "problematic".
And there is indeed a book "Regression Models for Time Series Analysis" (Wiley) that uses measure-theoretic notation.


text:
Q: Portforwarding docker container to localhost I'm trying to create a docker container so that I can connect to localhost:8180. But when ever I do following command and try to go to localhost I don't get any result
docker run -it -p 8180:8180 solrtest bash

My dockerfile is the following
FROM centos:7
COPY src/ /home/src/
RUN yum install -y \
   java-1.8.0-openjdk \
   java-1.8.0-openjdk-devel

ENV JAVA_HOME /usr/lib/jvm/java-1.8.0-openjdk/

RUN cd /home/src
RUN java -jar /home/src/app-solr-5-installer.jar -d "/home/app-solr"
RUN /home/app-solr/bin/app-solr start
EXPOSE 8180

The application itself is started so there is no issue and I expose the 8180 port. So I'm not very clear what is going wrong?

A: You need to change your Dockefile in the following way:
FROM centos:7
COPY src/ /home/src/
RUN yum install -y \
   java-1.8.0-openjdk \
   java-1.8.0-openjdk-devel

ENV JAVA_HOME /usr/lib/jvm/java-1.8.0-openjdk/

RUN cd /home/src
RUN java -jar /home/src/app-solr-5-installer.jar -d "/home/app-solr"

EXPOSE 8180

CMD /home/app-solr/bin/app-solr start

After building, you can run it:
docker run -d -p 8180:8180 solrtest

You should not use -it bash option in this case because it means allocation tty and attach to bash. It will not run your application:
-t              : Allocate a pseudo-tty
-i              : Keep STDIN open even if not attached

More info here: https://docs.docker.com/engine/reference/run/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Erro ao usar SQL com javascript Gostaria de saber o que está de errado com essas linhas, especialmente na query, pois não está a funcionar:
pool.query('SELECT * FROM `info` WHERE `id` = 1', function(err, row1) {
    var jogo = row1[0].jogo;
    var numerojogadores = row1[0].numerojogadores;
    // Se o numero de jogadores for 2 ou mais começa...
    if (numerojogadores > 1) {
        // Inicio do Contador
        socket.broadcast.emit('count', count);
        count--;
        console.log(count);
        // Fim do Contador
    }
    if (count === 0) {
        var novojogo = "jogo2";
        pool.query('UPDATE info SET jogo = novojogo WHERE id = 1', function(err) {
            console.log(err);
            count = 60;
        });
    }
});


text:
Q: Creating hashmap/map from XML resources I'm making an application where a web service fetches (amongst other) a bunch of codes from a webservice (I.e BEL, FRA, SWE). During runtime I want to translate these codes to their apporiate names to display to users (I.e Belgium, France, Sweden). There can be a lot of these codes, so i'm wondering if there is any approriate way to store the (code, name) entry as a some sort of map in the XML resources in Android, so I can quickly fetch the name by the given code?
It's all about speed here, since the map can have a few hundred entries.

A: Today I came across the same problem and studying developer.android.com for a long time didn't help since Android resources cannot be hashes (maps), only arrays.
So I found 2 ways:

*

*Have a string array of values like "BEL|Belgium", parse those string early in the program and store in a Map<>

*Have 2 string arrays: first with the values of "BEL", "FRA", "SWE" and second with "Belgium", "France", "Sweden".
Second is more sensitive cause you have to synchronize changes and order in both arrays simultaneously.

A: Also you can define a map in XML, put it in res/xml and parse to HashMap (suggested in this post). If you want to keep key order parse to LinkedHashMap. Simple implementation follows:
Map resource in res/xml:
<?xml version="1.0" encoding="utf-8"?>
<map linked="true">
    <entry key="key1">value1</entry>
    <entry key="key2">value2</entry>
    <entry key="key3">value3</entry>
</map>

Resource parser:
public class ResourceUtils {
    public static Map<String,String> getHashMapResource(Context c, int hashMapResId) {
        Map<String,String> map = null;
        XmlResourceParser parser = c.getResources().getXml(hashMapResId);

        String key = null, value = null;

        try {
            int eventType = parser.getEventType();

            while (eventType != XmlPullParser.END_DOCUMENT) {
                if (eventType == XmlPullParser.START_DOCUMENT) {
                    Log.d("utils","Start document");
                } else if (eventType == XmlPullParser.START_TAG) {
                    if (parser.getName().equals("map")) {
                        boolean isLinked = parser.getAttributeBooleanValue(null, "linked", false);

                        map = isLinked ? new LinkedHashMap<String, String>() : new HashMap<String, String>();
                    } else if (parser.getName().equals("entry")) {
                        key = parser.getAttributeValue(null, "key");

                        if (null == key) {
                            parser.close();
                            return null;
                        }
                    }
                } else if (eventType == XmlPullParser.END_TAG) {
                    if (parser.getName().equals("entry")) {
                        map.put(key, value);
                        key = null;
                        value = null;
                    }
                } else if (eventType == XmlPullParser.TEXT) {
                    if (null != key) {
                        value = parser.getText();
                    }
                }
                eventType = parser.next();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return map;
    }
}

A: I've found Vladimir's answer quite compelling so I implemented his first suggestion:
public SparseArray<String> parseStringArray(int stringArrayResourceId) {
    String[] stringArray = getResources().getStringArray(stringArrayResourceId);
    SparseArray<String> outputArray = new SparseArray<String>(stringArray.length);
    for (String entry : stringArray) {
        String[] splitResult = entry.split("\\|", 2);
        outputArray.put(Integer.valueOf(splitResult[0]), splitResult[1]);
    }
    return outputArray;
}

using it is straight forward. In your strings.xml you have a string-array like so:
<string-array name="my_string_array">
    <item>0|Item 1</item>
    <item>1|Item 4</item>
    <item>2|Item 3</item>
    <item>3|Item 42</item>
    <item>4|Item 17</item>
</string-array>

and in your implementation:
SparseArray<String> myStringArray = parseStringArray(R.array.my_string_array);

A: I think the safest and cleanest approach hasn't been posted yet, so here's my $0.02:
How about creating an enum type in the code that references the string resource id for its display value:
public enum Country {
   FRA(R.string.france),
   BEL(R.string.belgium),
   SWE(R.string.sweden),
   ...;

   @StringRes public int stringResId;

   Country(@StringRes id stringResId) {
       this.stringResId = stringResId;
   }
}

Then in strings.xml:
<string name="france">France</string>
...

And when you receive an item from the web service:
Country country = Country.valueOf(countryCodeFromServer);
context.getResources().getString(country.stringResId);

Build time checks will ensure that each country has a resource for each locale, which you won't have if you maintain the list as an array resource.

A: It might be late for you, but for anyone else interested.
If your 3 digit country codes are valid ISO 3166-1 alpha-3 codes
Locale locale = new Locale("", "SWE");
String countryName = locale.getDisplayCountry();

This gives full country name with correct language.

A: I had a similar requirement, and I solved it in a way that is more powerful than the current solutions.
First create a resource that is an array of country arrays:
<array name="countries_array_of_arrays">
    <item>@array/es</item>
    <item>@array/it</item>
</array>

Then for each country add an array with the country info:
<array name="es">
    <item>ES</item>
    <item>ESPAÑA</item>
</array>
<array name="it">
    <item>IT</item>
    <item>ITALIA</item>
</array>

Some notes:

*

*The name values (es, it) on each country array must match the ones in countries_array_of_arrays (you'll get an error if it doesn't).

*The order of the items on each array must be the same for all the arrays. So always put the country code first, and the country name second, for example.

*You can have any number of strings for each country, not just the country code and name.
To load the strings on your code do this:
TypedArray countriesArrayOfArrays = getResources().obtainTypedArray(R.array.countries_array_of_arrays);
int size = countriesArrayOfArrays.length();
List<String> countryCodes = new ArrayList<>(size);
List<String> countryNames = new ArrayList<>(size);
TypedArray countryTypedArray = null;
for (int i = 0; i < size; i++) {
    int id = countriesArrayOfArrays.getResourceId(i, -1);
    if (id == -1) {
        throw new IllegalStateException("R.array.countries_array_of_arrays is not valid");
    }
    countryTypedArray = getResources().obtainTypedArray(id);
    countryCodes.add(countryTypedArray.getString(0));
    //noinspection ResourceType
    countryNames.add(countryTypedArray.getString(1));
}
if (countryTypedArray != null) {
    countryTypedArray.recycle();
}
countriesArrayOfArrays.recycle();

Here I'm loading the resources to 2 List but you can use a Map if you want.
Why is this more powerful?

*

*It allows you to use string resources and hence translate the country names for different languages.

*It allows you associate any type of resource to each country, not just strings. For example, you can associate a @drawable with a country flag or an <string-array> that contains provinces/states for the country.
Advanced example:
<array name="it">
    <item>IT</item>
    <item>ITALIA</item>
    <item>@drawable/flag_italy</item>
    <item>@array/provinces_italy</item>
</array>

Note that I haven't tried this but I've seen it in other questions. In such case you would use countryTypedArray.getDrawable(2) to get the drawable, for example.
Simplification:
If you are only using strings for the country array, you can use an <string-array (instead of an <array>) like this:
<string-array name="it">
    <item>IT</item>
    <item>ITALIA</item>
</string-array>

And you can simplify a bit the for-loop code by directly getting an String[] instead of a TypedArray:
String[] countryArray = getResources().getStringArray(id);
countryCodes.add(countryArray[0]);
countryNames.add(countryArray[1]);

A note on having 2 <string-array>:
Initially I was thinking of having 2 <string-array> (one for the country code and another for the country name) as mentioned on another answer. However, with 2 <string-array> you have to make sure that the number and order of the items match. With this solution you don't. It's safer in this regard. Note that, as I've said, the order of the items on each country array matters: always put the country code and country name in the same order!


text:
Q: c# truly H-I-D-E files We know that by this code we can hide a file:
File.SetAttributes(path, FileAttributes.Hidden);

But the problem is that you can see these kind of hidden files by choosing "Show hidden files, folders, and drivers" in Folder Options in Windows Control Panel.
How can we make a file (like a .mkv file) hidden which can only be seen by our programs permission?
Thanks!


text:
Q: Why String + CharSequence is successful? String s = txtShow.getText().toString();
Button btn = (Button)findViewById(v.getId);
txtShow.setText(s+btn.getText());

The third line in above code.I find that two different datatypes are added together,that is,String + CharSequence.I run my program,there are no error.Why?
I think the third line should be
txtShow.setText(s+btn.getText().toString());

isn't? What is the difference?

A: Like the comment of @Euporie sad the return type of getText is CharSequence
The concatenation with the plus operator are converted to the StringBuilder usage.
StringBuilders append method accept a Parameter of Type CharSequence thats why no error
appears.
Editable implements the CharSequence interface and it will work too.

A: First Off all as said by   @Euporie
btn.getText() return CharSequence
And for your Information Editable and String both implements CharSequence


text:
Q: How to print string in C++ using getline Why this doesn't print the first word of sentence?
#include <iostream>
#include <string>

int main()
{
    std::string sentence;
    std::cout<<"Enter sentence: ";
    std::cin>>sentence;
    std::getline(std::cin,sentence);
    std::cout<<sentence;
    return 0;
}

If I enter

"This is text"

output would be

" is text"

A: You dont need the first cin (std::cin>>sentence;), this will solve your problem
#include <iostream>
#include <string>

int main()
{
    std::string sentence;
    std::cout<<"Enter sentence: ";
    std::getline(std::cin,sentence);
    std::cout<<sentence;

    return 0;
}

A: std::cin>>sentence;

This line of code takes the first word you input.
Remove it and you are good to go


text:
Q: Distinguish between local cache callback and server reached callback in Firebase I was building a chat application in Android using Firebase. When we use Firestore SDK, it triggers any listeners on updates as soon as data is written into local Firestore cache. Since I have included server-time in the field, a second trigger will occur when the data has actually reached server, since server-time gets updated there. Is there a possible way for me to distinguish between these two triggers, so that, I can update the user that the message reached the server (like WhatsApp).
If this is absolutely not possible, I have two options:

*

*Use custom cloud functions to send the message, so that listener triggers only after data has reached the server. Until then, I can show pending status for user.

*Use custom cloud functions that triggers on Firestore writes at that location, and sets a flag, which indicates the data has reached the server.

If I have choose, which is better?

A: You can determine whether a snapshot is guaranteed to be up-to-date with the server by checking the isFromCache() and hasPendingWrites() methods in its metadata.


text:
Q: Speeding up a dependent loop I will use this simple made-up, self-contained function, which is supposed to get as inputs: the initial position, force, time step and number of iterations; and return as outputs: the time and position vectors.
function [time,pos] = example(pos0, force, N, dt)

clc;

pos = zeros(N+1,3);
vel = zeros(N,3);
pos(1,:)=pos0;

for i = 1:N

        time(i+1) = i*dt;

        % solver finds the velocities given forces and previous positions
        vel(i,:) = force./(norm(pos(i,:)+1));

        % evolution calculates new positions using new velocities
        pos(i+1,:) = pos(i,:) + vel(i,:)*dt;

end

end

How could I speed the for loop up, given that parallel computation is not an option (the loop entries depend on the previous iteration)? Would vectorising be an option? How would I go about it?


text:
Q: Android Volley JSON parse exception I'm trying to build a Login page using volley on Android.
The request is working fine with GET, but I'm getting an error with POST.
I've looked into many similar questions here but none solved my issue.
My java code :
    final String username = user_name.getText().toString();
    final String password = pass_word.getText().toString();

    String url = "http://192.168.2.6/api_test/login.php";
    final StringBuilder resp = new StringBuilder();
    resp.append("Response: ");

    final ProgressDialog pDialog = new ProgressDialog(this);
    pDialog.setMessage("Please wait...");
    pDialog.show();
    //RequestQueue queue = Volley.newRequestQueue(this);
    JsonObjectRequest req = new JsonObjectRequest(Request.Method.POST,url,null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try{
                resp_txt.setText("Response is : " + response.toString());

            }
            catch (Exception ex){
                resp_txt.setText("Error");
            }
            pDialog.hide();
        }

        }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            resp_txt.setText(error.toString());
            pDialog.hide();
    }
    }){
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("username", username);
            params.put("password", password);
            return params;
        }
    };

And my php code :
    class response{
public $name = "";
    }
    $e = new response();
    $username = $_POST['username'];
    $password = $_POST['password'];
    $result = mysqli_query($con,"SELECT name FROM users  where    username='$username' and password='$password'");
    header('Content-Type: application/json;charset=utf-8');
    if (mysqli_num_rows($result) > 0) {

    while($row = mysqli_fetch_assoc($result)) {
    $e->name = $row["name"];
    echo json_encode($e);
    }
    }
    else{
    echo "false";
     }

Error I'm getting is :
    ParseError: org.json.JSONException: Value <br of type java.lang.String cannot be converted into JSON object.

It works perfectly with GET.


text:
Q: Why does sed command contain at symbols I don't understand why the following sed command contains an @ symbol:
sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd

I've looked at /etc/pam.d/sshd for the before/after effects of this command:
BEFORE:
...
# Set the loginuid process attribute.
session    required     pam_loginuid.so
...

AFTER:
...
# Set the loginuid process attribute.
session optional pam_loginuid.so
....

Is the @ symbol possibly part of regex or sed syntax?
Could not find any doco on this.
Note: The above sed command is actually part of a Dockerfile RUN command in tutorial:
https://docs.docker.com/examples/running_ssh_service/

A: From the sed manual

The syntax of the s (as in substitute) command is 's/regexp/replacement/flags'. The / characters may be uniformly replaced by any other single character within any given s command. The / character (or whatever other character is used in its stead) can appear in the regexp or replacement only if it is preceded by a \ character.

From the POSIX specification:

[2addr]s/BRE/replacement/flags
Substitute the replacement string for instances of the BRE in the pattern space. Any character other than <backslash> or <newline> can be used instead of a  to delimit the BRE and the replacement. Within the BRE and the replacement, the BRE delimiter itself can be used as a literal character if it is preceded by a <backslash>.

A: as other says, it is another delimiter than traditionnal / in the s///action. This is usually used when / is found/part of the pattern like searching (or replacing by) a unix path that need to escape the /
s/\/my\/path/\/Your\/path/
# same as
s@my/path@/Your/path@

You often use a character that is not alpha numeric (but you can). The only (logical) constraint is to avoid a special character  (aka special meaning like ^$[]{}()+\*.) for regex that make it difficult to read (but functionnal) and without the feature of this character in the pattern
echo "b(a)l" | sed 's(.)()('

A: These are alternate delimiters for the regular expressions and replacement string.  Handy when your regex or replacement string includes '/'.


text:
Q: Ошибка при работе с Axios Vue.js Здравтсвуйте, возникла проблема, при использовании Axios вместе с Vue.js. Когда отправляю GET запрос к серверу все рабоатет прекрасно:
...
var self
axios.get("/adminRoom/changeTask", {
    params: {
        title : self.changingForm.oldTitle,
        newTitle : self.changingForm.newTitle,
        newTitle : self.changingForm.newDescription,
    }
}).then(function (response) {
    ...
});
...

Но стоит поменять GET на PUT,DELETE или POST как на клиенте так и на серверу так сразе же перестает все работать. ВВот ошибка:
Failed to load resource: the server responded with a status http//:loclahost:8080/adminRoom/changeTask:1 Failed to load resource: the server responded with a status of 400 () of 400 ()

Error: Request failed with status code 400
at e.exports (spread.js:25)
at e.exports (spread.js:25)
at XMLHttpRequest.l.(anonymous function) (https://unpkg.com/axios@0.18.0/dist/axios.min.js:8:3278)

Спустя какое-то время удалось наладить работу с POST запросами таким методом:
...
var self = this;
const requestParams = new URLSearchParams();
requestParams.append('title', self.addingForm.title);
requestParams.append('description', self.addingForm.description);
axios.post('/adminRoom/tasks/addTask', requestParams).then(function (response) {
    ...
});
...

Но PUT и DELETE также остаются не работоспособными. Может подскажет кто-нибудь, в чем проблема...

A: Для начала вдумчиво прочтите список кодов HTTP
Axios с Vue тут совершенно ни при чем. Вам же 400 бэкенд кидает. Убедитесь, что бэкенд на этом роуте обрабатывает запросы, отличные от GET.


text:
Q: Selenium WebdriverIO execute command fails I am creating a series of Javascript automated tests using Javascript
 / Selenium / WebdriverIO. I am having serious trouble with WebdriverIO's 'execute' command. The command 'execute' is being used due to a fundamental problem whereby an element not in the visible area of a window is not clickable, rendering the automation useless as it fails everytime. To overcome this viewable area issue I'm using 'execute' to 'scrollIntoView' any troublesome element before the 'click' command is called. In simple situations this works fine. Multiple sequential execute commands work unless separated by a click which navigates from PageA to PageB. This navigation seems to break the execute flow. My thoughts are that the execute Javascript is maybe injected into the current page, therefore the navigation destoys the script. I'm really not sure!
Has anyone else had issues like this? If so, please help, its driving me nuts!!
this code works :
module.exports = {
    runMacro: function(){
        browser
            .execute(function() {
                var els = document.getElementsByClassName('img-cnt');
                els[0].scrollIntoView();
            })
            .pause(3000) // for testing purposes
            .execute(function() {
                // this code executes
            })
    }
};

this code doesn't work :
module.exports = {
    runMacro: function(){
        browser
            .execute(function() {
                var els = document.getElementsByClassName('img-cnt');
                els[0].scrollIntoView();
            })
            .click('.img-cnt')
            .pause(3000) // for testing purposes - in real test would for waitForExists or similar
            .execute(function() {
                 // this code doesn't execute
            })
    }
};

thanks!!!!


text:
Q: Prove correctness for this lcm iterative program Studying for finals, trying to solve this problem:

Given positive integers $n$ and $m$, we say that $m$ is a multiple of $n$ iff there is some $k \in N$ such that $m = kn$.
For positive integers $a$, $b$, we define the least common multiple of $a$ and $b$, denoted $lcm(a, b)$, to be the smallest number that is both a multiple of $a$ and a multiple of $b$.
Prove that the following program is correct with respect to its given specification.
Precondition: $a$ and $b$ are positive integers.
Postcondition: Return $lcm(a, b)$.

lcm(a, b)
x=a; y=b
while x \= y:
    if x < y:
        x=x+a
    else:
        y=y+b
return x

My loop invariant so far:
For $k \in N$, define $P(k)$ as such:
$P(k)$: if $a$, $b$ are positive integers and the loop iterates at least $k$ times, then:

*

*$x_k \ge a$ and $y_k \ge b$

*$x_k$ is a multiple of $a$ and $y_k$ is a multiple of $b$

*$x_k \le ab$

I'm not sure if my LI is correct. I'm having a hard time proving the last one (#3) in my induction step and not really sure how to prove partial correctness either (I'm taking the approach of LI + exit condition implies post condition).
Any suggestions please?

A: For $a,b > 1$, we know that $a,b < ab$. Your algorithm adds positive number to either $x$ or $y$, in each step. That means that in each step exactly one of this values grows, so - at one point - you'll get one of these:

*

*$x \ge ab$, $y < ab$; or

*$x < ab$, $y \ge ab$; or

*$x = y$.

Since you worry about $\le ab$, let us assume 1: $x \ge ab$, $y < ab$. Notice that $x = ab$. If this wasn't the case, we'd have $x - b \ge ab$, so the last step wouldn't enlarge $x$ and its value wouldn't get $>ab$, which is a contradiction.
So, $x = ab$, $y < ab = x$.
As long as $y < x$, the algorithm will keep on adding $b$ to $y$. So, your $y$ will be getting values $y_0, y_0 + b, \dots, y_0 + kb$ for some $k \in \mathbb{N}$ ($y_0$ denotes the value that $y$ had when $x$ reached $ab$).
Now, same as with $x$: if $y_0 + kb > ab$, then $y_0 + (k-1)b \ge ab$, because there are no numbers between $y_0 + (k-1)b$ and $y_0 + kb$ that are divisible by $b$. But, we know that $(k-1)b < ab$, so this is a contradiction. Hence, $y_0 + kb = ab = x$ and the algorithm ends.
The same goes for case 2, and the case 3 says only that the algorithm may finish sooner.
You still need to show that the value that the algorithm computes is the least (common multiplier). This can be done by repeating what I did above, but using $m = \operatorname{lcm}(a,b)$ instead of $ab$, thus showing that $x$ and $y$ cannot grow beyond it.


text:
Q: structure in c whose members are also structures I have following structs:
typedef struct stack {
    void* ss_sp;
    size_t ss_size;
    // ...
} stack_t;

typedef struct ucontext {
    ucontext_t* uc_link;
    stack_t uc_stack;
    // ...
} ucontext_t;

typedef struct mythread_type {
    ucontext_t context;
    int ID;
    int status;
} mythread_t;

Now I have an array as follows:
mythread_t mythreads[100];

I want to avoid using
mythreads[0].context.uc_stack.ss_size

for readability reason.
Now I was wondering if the following two blocks of code are equivalent:

*

*block 1
ucontext_t c=mythreads[0].context;
getcontext(&c);
c.uc_stack.ss_size=1024;
c.uc_stack.ss_sp=malloc(1024);

*block 2
ucontext_t* c=&(mythreads[0].context);
getcontext(c);
(c->uc_stack).ss_size=1024;
(c->uc_stack).ss_sp=malloc(1024);

What I want is the context of the mythreads[0] stack to allocate 1024 bytes.

A: The following is copy of mythreads[0].context:
ucontext_t c = mythreads[0].context;

In opposite the following is pointer to mythreads[0] context
ucontext_t* c = &(mythreads[0].context);

As a result the first peace of code makes modification of the copy (it does not enfluence on the mythreads[0] context), the second one modifies the mythreads[0] context.

A: They are not equivalent.
The first block operates on a copy of the information in mythreads[0].context, the second block operates on the information in mythreads[0].context.
You could perhaps achieve overall equivalence if you wrote:
ucontext_t c = mythreads[0].context;
getcontext(&c);
c.uc_stack.ss_size = 1024;
c.uc_stack.ss_sp = malloc(1024);
mthreads[0].context = c;

but there are two extra structure copies in that.


text:
Q: Brave Browser crashed on start On a M1 Mac the Brave Browser quits after a few seconds right after startup.
MacOs: Version 12.4
Brave: Version 1.40.105 Chromium: 103.0.5060.53 (Offizieller Build) (arm64)
What can i do do fix this problem?

A: One workaround is to delete the Preferences file:
~Library/Application Support/BraveSoftware/Brave-Browser/Default/Preferences

To Navigate to ~Library: Open Finder, hold 'option' and click in menu on 'go to'


text:
Q: Cython class executing a list of cython classes of the same kind I have defined a generic class Rule in Cython which expects a cdef method  ̀initialize. I have created a class which is itself defined as a Rule, but it executes the initialize methods of a list of rules:
%%cython

cdef class Rule:
    cdef initialize(self, const int i):
        pass

cdef class Print(Rule):
    cdef int number

    def __init__(self, int number):
        self.number = number

    cdef initialize(self, const int i):
        print(self.number, i)

cdef class ChainRule(Rule):
    cdef list rules
    cdef int number_of_rules, j

    def __init__(self, rules):
        self.rules = rules
        self.number_of_rules = len(rules)

    cdef initialize(self, const int i):
        for j in range(self.number_of_rules):
            self.rules[j].initialize(i)

def run(Rule rule, const int i):
    rule.initialize(i)

The following code works when ̀run` takes Print as input:
rule1 = Print(1)
rule2 = Print(2)

run(rule1, 100)

But the ChainRule class which calls the rules internally does not work:
chain_rule = ChainRule([rule1, rule2])
run(chain_rule, 100)

Error message:
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
/tmp/ipykernel_12612/3538048733.py in <module>
      4 chain_rule = ChainRule([rule1, rule2])
      5
----> 6 run(chain_rule, 100)

_cython_magic_d892e8623ea7126dd1dda2c25ea23c19.pyx in _cython_magic_d892e8623ea7126dd1dda2c25ea23c19.run()

_cython_magic_d892e8623ea7126dd1dda2c25ea23c19.pyx in _cython_magic_d892e8623ea7126dd1dda2c25ea23c19.ChainRule.initialize()

AttributeError: '_cython_magic_d892e8623ea7126dd1dda2c25ea23c19.Pri' object has no attribute 'initialize'

Why does it fail? How can I make it work?
Thank you.
Edit, a working solution:
cdef class ChainRule(Rule):
    cdef list rules
    cdef int number_of_rules, j

    def __init__(self, rules):
        self.rules = rules
        self.number_of_rules = len(rules)

    cdef initialize(self, const int i):
        cdef Rule rule
        for j in range(self.number_of_rules):
            rule = self.rules[j]
            rule.initialize(i)


text:
Q: Add Domain User Account to Local Group Windows Puppet I am trying to set a windows domain user account to the local administrators group that according the puppet documentation is possible.
user { 'DOMAIN\user':
    groups => ['Administrators'],
}

I tried using the SID with no results. I am using the latest Puppet 2.7.19
err: /Stage[main]/Teamcity_base/User[S-1-5-21-1759977473-2015113658-625696398-26
038]/ensure: change from absent to present failed: User update failed: SetInfo
    OLE error code:8007089A in Active Directory
      The specified username is invalid.

    HRESULT error code:0x80020009
      Exception occurred.

A: My current workaround is a custom module to run a batch file with "net localgroup" commands:
net localgroup administrators domain\user /add

My init.pp detects changes to the batch file, using subscribe:
class admin {
  $exe_name = "add_admin_users.bat"
  $location = "puppet:///modules/${module_name}/${exe_name}"
  $on_disk = 'C:\add_admin_users.bat'

  file { $on_disk:
    ensure => file,
    source => $location,
    mode   => '750',
  }

  exec { $on_disk:
    subscribe => File[$on_disk],
    refreshonly => true
  }

}

Not ideal, since it doesn't check for existence of a user before trying to add, but close.


text:
Q: Flutter categories list base on another list of data I have two lists and need to get the category of each word and display it as a group.
my first list is where data is coming from.
final WordsList = [
  {
    'category': 'category-1',
    'words': ['Happy', 'Excited', 'Playful', 'Content', 'Grateful', 'Inspired']
  },
  {
    'category': 'category-2',
    'words': ['Confused', 'Doubtful','Confused']
  },
  {
    'category': 'category-3',
    'words': ['Scared','Horrified']
  },

Then the second list is from the user selection
List userSelection = [Happy, Confused, Doubtful, Scared, Horrified];

What i want to achieve is below.

Category-1
Category-2
Category-3

Happy
Confused
Scared

Doubtful
Horrified

Here is my code so far what I did was iterate the userSelection list and search the words from the word list and was able to retrieve the list but cannot figure out how to display it properly.
void getCategory() {
    var wordsDisplay = [];
    for (var i = 0; i < userSelection.length; i++) {
      wordsDisplay.add(WordsList
          .where((element) => (element["words"].contains(userSelection[i]))));
    }
  }

A: Try this out:
void main() {
  List<Map<String, dynamic>> wordsList = [
    {
      'category': 'category-1',
      'words': [
        'Happy',
        'Excited',
        'Playful',
        'Content',
        'Grateful',
        'Inspired'
      ]
    },
    {
      'category': 'category-2',
      'words': ['Confused', 'Doubtful', 'Confused']
    },
    {
      'category': 'category-3',
      'words': ['Scared', 'Horrified']
    },
  ];

  // using a set to eliminate duplicates like 'Confused' in category-2
  Set<String> userSelection = {
    'Happy',
    'Confused',
    'Doubtful',
    'Scared',
    'Horrified',
  };

  List<Map<String, dynamic>> wordsDisplay = [
    for (final category in wordsList)
      {
        // copy category into a new map
        ...category,
        // overwrite the 'words' key/value pair
        // the items we want are the set intersection of the userSelection
        // and the original words list.
        'words': userSelection.intersection({...?category['words']}),
      },
  ];

  print(wordsDisplay);
}


text:
Q: spring-data-mongodb. How can i dynamically create a database in mongo using spring-data-mongodb library? spring-data-mongodb. How can i dynamically create a database in mongo using spring-data-mongodb library?
I am trying to use Spring-Mongodb-Data module for CRUD operations against Mongo database and going through examples and articles my assumption is that databasename should be pre-defined in spring context xml when defining MongoTemplate bean.
In my case I have an multi-tenant application that will accept requests over http and my application should create the mongodatabase on-the-fly and use the name provided in the input http request to create the database and then load the data into collection in the newly created database.
I am trying to figure out if there is a way to dynamically populate the databasename in MongoTemplate or MongoRepository without having to provide it in spring context.xml?
Please help me.
Thanks
-RK

A: Have you tried the following instead of going through the pre-defined spring context configuration.
MongoTemplate getMongoTemplate(Mongo mongo, String database) {
    return new MongoTemplate(mongo, database);
 }


text:
Q: How to assign a value to each item inside an ordered list with Javascript I'm trying to give a percent matching score like 90% Match to each of my search results.
I haven't found any solutions to write a function in python that would do that so I was wondering if there's a way to create some Javascript code that would automatically assign a random value from 100 to 50% (in reverse order) to every items inside of an ordered list (which are my search results) based on the default order of the list (1,2,3,4..).
A quick example of the html:

<\li>

<\li>

<\li>

<\li>

<\ol>

Now the final expected results should look to something like this:

- Title 1
  Description...
  *100% Match*

- Title 2
  Description...
  *92% Match*

- Title 3
  Description...
  *85% Match*

- Title 4
  Description...
  *56% Match*

Ps; The search results are not all manually added, they all come from a database and an index.
Any ideas on how to achieve this?

A: You can use the python's random library to achieve the random generation of the scores.
import random

results_size = 4
scores = random.sample(range(50, 101), results_size)
scores.sort(reverse=True)
print(scores)

Sample output:
[93, 73, 68, 50]

And then iterate the scores list and assign its current value to the current list element.

A: This part is for generating a random number within the range of 75 - 100:
function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

This part is the example of the code that you can use, you can generate the
 items as many as the number of rows you got from the database by changing the itemLength and you can change the content of the list item by replacing randomInt in listItem.appendChild(randomInt) into the description you would like to put in there.


text: Q: Grub2 won't install on fresh Ubuntu 12.04 LTS Server installation I have a hardware RAID 1 which seems to be recognized find by the Ubuntu installer.  I choose the "Entire Disk - Guided" partition strategy and accept the defaults, writing them to disk.  When it comes to choosing where to put Grub2, however, everything I try fails.  Any advice would be awesome.


text:
Q: when i update to webpack5, there is a error: configuration has an unknown property 'before' when I update webpack 4 to 5, the error exits.
I have a webpackDevServer.js which include the error message 'error'
// webpackDevServer.js
module.exports = function(proxy, allowedHost) {
    return {
        before(app, server) {
            if (fs.existsSync(paths.proxySetup)) {
                // This registers user provided middleware for proxy reasons
                require(paths.proxySetup)(app);
            }

            // This lets us fetch source contents from webpack for the error overlay
            app.use(evalSourceMapMiddleware(server));
            // This lets us open files from the runtime error overlay.
            app.use(errorOverlayMiddleware());

            // This service worker file is effectively a 'no-op' that will reset any
            // previous service worker registered for the same host:port combination.
            // We do this in development to avoid hitting the production cache if
            // it used the same host and port.
            // https://github.com/facebook/create-react-app/issues/2272#issuecomment-302832432
            app.use(noopServiceWorkerMiddleware());
        },
    };
};

I use the above file in a start.js file, when I run the project, I type node scripts/start.js
// start.js
...
const createDevServerConfig = require('../config/webpackDevServer.config');
...
const serverConfig = createDevServerConfig(
      proxyConfig,
      urls.lanUrlForConfig
);
const devServer = new WebpackDevServer(compiler, serverConfig);

then it throws an error
configuration has an unknown property 'before'. These properties are valid:
object { bonjour?, client?, compress?, dev?, firewall?, headers?, historyApiFallback?, host?, hot?, http2?, https?, injectClient?, injectHot?, liveReload?, onAfterSetupMiddleware?, onBeforeSetupMiddleware?, onListening?, open?, openPage?, overlay?, port?, proxy?, public?, setupExitSignals?, static?, stdin?, transportMode?, useLocalIp? }

here is my package.json
"webpack": "^5.20.2",
"webpack-dev-server": "^4.0.0-beta.0",
"webpack-manifest-plugin": "2.0.4",
"workbox-webpack-plugin": "^6.1.0"

A: You have to change before to the onBeforeSetupMiddleware. Link with migration description from v3 to v4. https://github.com/webpack/webpack-dev-server/blob/master/migration-v4.md
In case, something will change on the migration guide, details are attached below
v3:

module.exports = {
  devServer: {
    after: function (app, server, compiler) {
      app.get("/some/path", function (req, res) {
        res.json({ custom: "response" });
      });
    },
  },
};

v4:

module.exports = {
  devServer: {
    onAfterSetupMiddleware: function (devServer) {
      devServer.app.get("/some/path", function (req, res) {
        res.json({ custom: "response" });
      });
    },
  },
};

A: fxxk, I'm stupid, when i search some key word (eg: onBeforeSetupMiddleware), I found the github of webpack-dev-server which tell the changes in new version 4.0.0 beta. https://github.com/webpack/webpack-dev-server/releases


text:
Q: Chinese localization not worked with PHP gettext extension as it works with English I'm already localized a website from Russian to English with PHP and gettext just with wrapping all strings into __($string) function.
It works.
Here's the gists: https://gist.github.com/Grawl/ba8f39b8398791c6a67e
But it don't work with Chinese translation. I just added compiled .mo (and source .po) into locale/zh_CN/LC_MESSAGES/, visit /index.php?locale=zh_CN and don't see it translated at all.
What it wrong with Chinese?
Have I to use other language code or something?
I use zh_CN to map on Chinese like it done in WordPress.
I cannot understand why.

Update:
The problem was in HTML <meta> tag and charset going from server in Windows-1251. Chop russian PHP server.
After I set <meta charset="GBK"> and turned off AddDefaultCharset in .htaccess, Chinese localization finally started to work.
After all, I added these modifications:
.htaccess:
- AddDefaultCharset UTF-8
+ AddDefaultCharset off
+ RewriteRule ^cn index.php?locale=zh_CN&charset=GBK [L]

functions.php, included before <!DOCTYPE html>:
+ $charset=$_GET["charset"];
+ if(!isset($charset)) {
+   $charset="UTF-8";
+ }

head.php, the  tag content:
+ <meta charset="<?=$charset?>">

So, if I does not set charset into get request, it becomes UTF-8, otherwise it goes from get request. For Chiense I set it to GBK, like on Taobao.com, and browser sets up right charset.
But after all I just has cyrillic characters encoded in Chinese glyphs, character by character.
Like this: Сервис и услуги
Becomes this: 褋械褉胁懈褋 懈 褍褋谢褍谐懈
If you paste these Chinese characters into decoder app, chose GB2312 on left (one from Chinese charsets) and UTF-8 on right, you will have ?е?ви? и ??л?ги – some cyrillic characters corrupted but this is obviously an original string, because in translation I have more shorten 服务 for this phrase.
Help me please.

Update 2
I just forgot to set bind_textdomain_codeset(); to $domain, it was messages.
All works on unicode charset. All normal.

A: Summary
I was able to make this work without changing the <meta charset="..."> value away from utf-8. You should also be able to remove the AddDefaultCharset rule from your .htaccess and also remove the &charset=GBK from your RewriteRule. You need to make sure that your .po file is formatted and compiled correctly, and also make sure that server can find it.
Explanation/Example
Setting the <meta charset="..."> tag only tells the browser what character encoding is being used on the page. PHP still needs to know which file to select to replace strings. And in any case, although this documentation suggests otherwise, I think you can still use UTF-8 to do Chinese localization. Here is a simple working example I set up on my system:
<?php
    // initialize locale-related variables
    $locale     = $_GET['locale'] ?: 'en_US';
    $domain     = 'bridges';
    $locale_dir = dirname( __FILE__ ) . '/locale'; // using absolute path!

    // set up locale
    putenv( "LC_ALL=$locale" );
    setlocale( LC_ALL, $locale );
    bindtextdomain( $domain, $locale_dir );
    bind_textdomain_codeset( $domain, 'UTF-8' );
    textdomain($domain);
?><!doctype html>

        <meta charset="utf-8">
        <title><?= _( 'Localization Test' ) ?></title>

<?= _( 'Hello' ) ?>!

My .po file which is located at ./locale/zh_CN/LC_MESSAGES/bridges.po looks like:
msgid ""
msgstr ""
"Project-Id-Version: 1.0\n"
"PO-Revision-Date: 2015-07-20\n"
"Last-Translator: Morgan Benton\n"
"Language-Team: Chinese\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Language: zh_CN\n"

msgid "Localization Test"
msgstr "本土化试"

msgid "Hello"
msgstr "您好"

According to a comment on the gettext() documentation, you should put the character encoding and other relevant headers inside your .po file, e.g.
"Content-Type: text/plain; charset=UTF-8\n"

You can check the syntax of your .po file by running the command msgfmt -c bridges.po -o bridges.mo from your terminal. It will warn you if it thinks anything is wrong with your .po file. As the commenter suggested, I think you do NOT need to have the Chinese system libraries installed.
P.S. I don't know if these Chinese translations are correct or not. This is just what Google Translate gave me! :)


text:
Q: JQgrid: data display strange I got this trouble after try to attach the table into html page:

and the page have css style :
<meta http-equiv="refresh" content="300">
<link href="development-bundle/themes/redmond/jquery.ui.theme.css" rel="stylesheet" type="text/css" media="all">
<link href="development-bundle/themes/redmond/jquery.ui.all.css" rel="stylesheet" type="text/css" media="all">
<link href="development-bundle/themes/redmond/jquery.ui.tabs.css" rel="stylesheet" type="text/css" media="all">
<link href="development-bundle/themes/redmond/jquery.ui.dialog.css" rel="stylesheet" type="text/css" media="all">
<link href="development-bundle/themes/redmond/jquery.ui.datepicker.css" rel="stylesheet" type="text/css" media="all">
  <script type="text/javascript" language="javascript" src="js/jquery-1.8.3.js"></script>
<link rel="stylesheet" type="text/css" media="screen" href="jqGrid/css/ui.jqgrid.css" />
<link rel="stylesheet" type="text/css" media="screen" href="jqGrid/plugins/ui.multiselect.css" />
    <script src="jqGrid/js/i18n/grid.locale-en.js" type="text/javascript"></script>
    <script src="jqGrid/js/jquery.jqGrid.min.js" type="text/javascript"></script>
    <script type="text/javascript" language="javascript" src="js/jquery-ui-1.9.2.custom.min.js"></script>
    <script type="text/javascript" language="javascript" src="development-bundle/ui/jquery.ui.tabs.js"></script>
    <script type="text/javascript" language="javascript" src="development-bundle/ui/jquery.ui.dialog.js"></script>
    <script type="text/javascript" language="javascript" src="jquery-validate/jquery.validate.min.js"></script>
    <script type="text/javascript" language="javascript" src="development-bundle/ui/jquery.ui.datepicker.js"></script>

<style type="text/css">
    #container{ height: 700px;}
    #center_container{
                      background:#DDD;
                      height:700px;
                      width: 1100px;
                      margin: 0 auto;
                      }
    .ui-widget {font-size: 14px;}
    .ui-widget-content{float:left; width:1030px; margin-left:35px;background:#CEF6F5;}
    .ui-tabs .ui-tabs-panel {padding:1em 0em; width:700px; margin: 10px 10px;}
    .ui-jqgrid tr.jqgrow td {
                             white-space: normal !important;
                             font-size:0.8em;
                             height: auto;
                             }
    .ui-jqgrid-titlebar {font-size:2em; color: yellow;}
    .ui-state-highlight { background: yellow !important; }
</style>

A: look at this one :
.ui-widget-content{float:left; width:1030px; margin-left:35px;background:#CEF6F5;}

delete this part :
.ui-widget-content{/*float:left;*/ width:1030px; /*margin:20px auto;*/background:#CEF6F5;}
 div#gbox_list{margin-left:15px;}


text:
Q: Is a template class the best option here and if so how do I go about it? I am trying to include a function pointer as a parameter in a class constructor to allow for any arbitrary function pointer to be stored as a member variable in the class. In the code examples this is shown as function being assigned to FUNCTION which is passed into the constructor and is of type typed_value (*)(typed_value, typed_value). Here typed_value is a kind of std::variant. I would like this to be any kind of function pointer for example,

*

*type_value (*)(typed_value)

*type_value (*)(typed_value, typed_value)

*type_value (*)(typed_value, typed_value, typed_value)
and so on.
The class below inherits from NodeExtended. I do not feel the function of that class is particularly pertainant but I'm happy to add it on request.
#pragma once

#include "NodeExtended.h"
#include <iostream>

class NonterminalNode: public NodeExtended<NonterminalNode>
{
public:
    // Constructor
    NonterminalNode(std::string, std::vector<std::string>, std::string, typed_value (*)(typed_value, typed_value));

    // Destructor
    ~NonterminalNode();

    // Connectors
    void attach(std::vector<Node *>) override;

    // Function type
    typed_value (*function)(typed_value, typed_value);

    // Evaluation
    typed_value evaluate(reference_map_type & reference_map) override;
};

The implementation follows and the class is fairly vanilla except that extern "C" functions are required to import the constructor into a factory class that loads them using dlsym as this class is compiled as a shared library.
#include "NonterminalNode.h"

NonterminalNode::NonterminalNode(std::string NAME, std::vector<std::string> INPUT, std::string OUTPUT, typed_value (*FUNCTION)(typed_value, typed_value)) : NodeExtended(NAME, INPUT, OUTPUT) {
    function = FUNCTION;
}

NonterminalNode::~NonterminalNode() = default;

void NonterminalNode::attach(std::vector<Node *> CHILDREN) {
    children = CHILDREN;
}

typed_value NonterminalNode::evaluate(reference_map_type & reference_map) {
    return function(children[0]->evaluate(reference_map), children[1]->evaluate(reference_map));
}

extern "C" Node * create_object(std::string NAME, std::vector<std::string> INPUT, std::string OUTPUT, typed_value (*FUNCTION)(typed_value, typed_value))
{
    return new NonterminalNode(NAME, INPUT, OUTPUT, FUNCTION);
}

extern "C" void destroy_object(Node * object)
{
    delete object;
}

My first instinct was to template the class but I'm getting all sorts of errors thrown at me. Could somebody walk me through how to do this for this example or perhaps suggest an alternative. For example something like
#pragma once

#include "NodeExtended.h"
#include <iostream>

template <class arity>
class NonterminalNode: public NodeExtended<NonterminalNode<arity>>
{
public:
    // Constructor
    NonterminalNode(std::string, std::vector<std::string>, std::string, arity);

    // Destructor
    ~NonterminalNode();

    // Connectors
    void attach(std::vector<Node *>) override;

    // Function type
    arity function;

    // Evaluation
    typed_value evaluate(reference_map_type & reference_map) override;
};

template <class arity>
inline
NonterminalNode<arity>::NonterminalNode(std::string NAME, std::vector<std::string> INPUT, std::string OUTPUT, arity FUNCTION) : NodeExtended(NAME, INPUT, OUTPUT) {
    function = FUNCTION;
}

Edit 1:
With the above changes I receive the error
error: class 'NonterminalNode<arity>' does not have any field named 'NodeExtended'

Occurring at:

NonterminalNode<arity>::NonterminalNode(std::string NAME, std::vector<std::string> INPUT, std::string OUTPUT, typed_value (*FUNCTION)(typed_value, typed_value)) : NodeExtended(NAME, INPUT, OUTPUT) {

Similarly seen here however, I don't believe the solution applies.

A: The solution to turning a class like this into a template is two fold. It avoid various errors about inheritance and no field name appearing
#pragma once

#include "NodeExtended.h"
#include <iostream>

template <typename arity>
class NonterminalNode: public NodeExtended<NonterminalNode<arity>>
{
public:
    // Constructor
    NonterminalNode(std::string, std::vector<std::string>, std::string, arity);

    // Destructor
    ~NonterminalNode();

    // Connectors
    void attach(std::vector<Node *>) override;

    // Function type
    arity function;

    // Evaluation
    typed_value evaluate(reference_map_type & reference_map) override;
};

template <typename arity>
NonterminalNode<arity>::NonterminalNode(std::string NAME, std::vector<std::string> INPUT, std::string OUTPUT, arity FUNCTION) : NodeExtended<NonterminalNode<arity>>(NAME, INPUT, OUTPUT) {
    function = FUNCTION;
}

template <typename arity>
NonterminalNode<arity>::~NonterminalNode() = default;

template <typename arity>
void NonterminalNode<arity>::attach(std::vector<Node *> CHILDREN) {
    this->children = CHILDREN;
}

template <typename arity>
typed_value NonterminalNode<arity>::evaluate(reference_map_type & reference_map) {
    return function(this->children[0]->evaluate(reference_map), this->children[1]->evaluate(reference_map));
}

*

*The constructor must include all of the template parameters.

NonterminalNode<arity>::NonterminalNode(std::string NAME, std::vector<std::string> INPUT, std::string OUTPUT, arity FUNCTION) : NodeExtended<NonterminalNode<arity>>(NAME, INPUT, OUTPUT) {

instead of
NonterminalNode<arity>::NonterminalNode(std::string NAME, std::vector<std::string> INPUT, std::string OUTPUT, arity FUNCTION) : NodeExtended(NAME, INPUT, OUTPUT) {

*Inherited member variables should use this-> as explained here
template <typename arity>
void NonterminalNode<arity>::attach(std::vector<Node *> CHILDREN) {
    this->children = CHILDREN;
}

instead of
template <typename arity>
void NonterminalNode<arity>::attach(std::vector<Node *> CHILDREN) {
    children = CHILDREN;
}


text:
Q: UITableView didSelectRowAt is not called iOS 10, but works for 9.3.5 There are lots of questions regarding this problem, but the answers I have found so far are not applicable. In this case, the table works correctly in iOS 9.3.5, but not for iOS 10 (or 10.3.1)
I have ruled out:

*

*Not setting up the delegate properly. The delegate performs 3 functions, didSelectRowAt, heightForRowAt, and editActionsForRowAt. The latter is the right-to-left swipe which gives the option to perform the exact same functionality as selecting the row.. These three functions work correctly on v9.3.5 (as tested via simulator and and older iPad I test with.) When I use v10 via the simulator or my iPhone SE, the heightForRowAt, and editActionsForRowAt work but not the didSelectRowAt (and for that matter - I tried willSelectRowAt. It also did not work for v10.)

*Any typographical error (because it works for 9.3.5)

I have not been able to find anything about a Swift change regarding tableView(:didSelectRowAt) from iOS 9 to iOS 10.
Background
I have a view controller with a corresponding xib ("DetailVC"). This xib has a label then a tableview underneath the label. The table's cell is another xib.
The view controller presented via
let uomVC = DetailVC()
self.navigationController?.pushViewController(uomVC, animated: true)

Then within DetailVC, I use a NSFetchedDataController and connect it to tableview via the tableView Data Source delegate. (Core data loads and displays great.)
Code (I'll post additional code as needed/ requested - Swift 3)
viewDidLoad() - partial
let nib: String = "DetailCell"
let reuseID: String = "detailCell"
tableView.register(UINib.init(nibName: nib, bundle: nil), forCellReuseIdentifier: reuseID)

tableView(:cellForRowAt)
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: reuseID) as! IngredientDetailCell
    cell.present(ingredient: _fetchedResultsController.object(at: indexPath))
    cell.isUserInteractionEnabled = true // Added later as a guess per SO suggestions
    return cell
}

For arguments sake - this won't print
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("Selected a row")
    // delegate?.selectedIngredient(_fetchedResultsController.object(at: indexPath))
    // self.navigationController?.popViewController(animated: true)
}

View

A: For completeness in case anyone has this strange situation.
The problem was my UITableViewCell xib. I must have originally designed it as a UIView, then added the UITableViewCell. The hierarchy should begin with the UITableViewCell. I moved the UITableViewCell out from underneath the view (circled in red), deleted the view and re-connected the IBOutlets. It's just strange that it worked with iOS 9.3.5.


text:
Q: Solution for listening to file once/download I have energyshop.se which is a small webshop im doing for a customer. She sells various stuff but she has meditations on .mp3 and on discs. The customers can choose to buy:

*

*a disc which is then sent to their home address.

*one listening to one part of a meditation or one listening to all parts in a meditation

*some items are also available for download for another price.

So question is how do I solve this? We use PayPal at her site to make the payments and I know that after a payment I can redirect the users to a "thankyouforthepurhase"-page if I want to. That leads me to think that one option is to take the users to that page where they can download/listen, but I dont know how to "connect" the shopped item with the isplayed files to be downloaded and/or listene once too and how to limit this. I mean if the page is energyshop.se/thanks someone that have made the purchase can just copy that address and go straight there.
There is also a idea about codes in some way. If they make a purchase they get a code sent to them for download or listening, but how do I generate this code which has to be unique everytime and the password ha to change everytime someone has entered it so someone dont save the code as well.
Well im kinda out of ideas and not sure how to do this. I just wanna wrap this project up but I think I hve to solve this for her.

A: I guess the solution depends on how much control (or security) she feels is required.  If all you need is a reasonable confidence that a user has paid, then you can be much more relaxed about the whole thing.
The 'thanks' page could easily provide the content in concert with the transaction id paypal will return - you can use this to control what is shown.  If you're not too worried about a 'listen-once' item being replayed, or 'download' being downloaded a bunch of times then you can avoid a bunch of edge-case stuff (where download fails or listen-once feed dies halfway, etc) and simply serve links to content based on the transaction.
If its abused then you can put effort into locking down content, serving mp3 streams from one-time links, tracking downloads in a database etc, but that will cost significantly more (in both time and server resources) so if you can, try simple first :)


text:
Q: Get the text of a stored procedure after rename in SQL Server I encountered a strange problem today.... I did an sp_helptext on a stored procedure but the stored procedure name in the CREATE PROCEDURE statement (in the result) did not correspond to the name I used in the sp_helptext statement (see screenshot below). I tried selecting from the sys.all_sql_modules and also OBJECT_DEFINITION but it gave the same result.
In my example below I used InvIRCode_GetByInvIRID but the result gave me InvIRCode_GetListByInvIRID
I did a bit of research and it seems it is a known SQL Server bug and happens when a stored procedure was renamed.
My question is this: How can I get the correct source code for a stored procedure?
The interesting thing is that when I right-click on the sp in the Object Explorer of SQL Server Management Studio and select to script the procedure to a new window, it does give the correct code.

A: Note this warning message is returned by sp_rename:
Caution: Changing any part of an object name could break scripts and stored procedures.

The text in the catalog views is not changed by sp_rename. The proc name will be corrected when you script the proc via SSMS or SMO. You can alter (or drop/create) modules using that script to fix the text in the catalog views after a rename.


text:
Q: Python Pandas Read SQL from IBM DB2 with non ASCII characters I am using Pandas Read Sql in Python for executing sql-statements in IBM DB2 and saving the response in pandas dataframes. Now I am trying to execute a sql-statement containing a non ASCII character, a letter from the Swedish alphabet: 'Å' (others are Å, Ä and Ö) but I am getting this error:
"DatabaseError: Execution failed on sql 'SELECT * FROM DATA_CONFIG WHERE TAG_NAME='Å'': ibm_db_dbi::Error: Error occure during processing of statement"
This is my code:
import ibm_db
import ibm_db_dbi
import pandas as pd

def sqlToFrame(sql): # Function for creating pandas dataframes from SQL-statements
    con = ibm_db.connect(connection_string, "", "")
    conn = ibm_db_dbi.Connection(con)
    return pd.read_sql(sql, conn)

df = sqlToFrame("SELECT * FROM DATA_CONFIG WHERE TAG_NAME='Å'")

I've tried executing the statement in the IDE in the IBM DB2 interface which works perfectly fine. Therefore I am figuring that the problem might be connected to how I establish the connection/the DB2 driver pandas uses. I have tried finding a way to set an encoding but can't find anything. How can I solve this? I also know this is possible because another package that builds upon ibm_db accept these characters. The characters are a from the ISO-8859-1 series

A: Consider parameterizing your query using the params argument of pandas.read_sql and pass the accented character 'Å' with u'' prefix to bind value to the unquoted ? placeholder in SQL query. Do note: params requires a sequence and so below passes a tuple of one item.
Unlike Python 2.x, all strings in Python 3.x are Unicode strings and so accented literals (non-ascii) do not need explicit decoding with u'...'. Hence, why I cannot reproduce your issue in my Python 3.5 running a DB2 SQL query with accented characters.
import pandas as pd
...

# Function for creating pandas dataframes from SQL-statements
def sqlToFrame(sql):
    db = ibm_db.connect(connection_string, "", "")
    con = ibm_db_dbi.Connection(db)

    return pd.read_sql(sql, con, params = (u'Å',))

df = sqlToFrame("SELECT * FROM DATA_CONFIG WHERE TAG_NAME = ?")


text:
Q: Is the biconjugate of a continuous functions also continuous? Let $f:\mathbb{R}^n\to\mathbb{R}$ be given and assume that $|f(x)|\leq C|x|^2$. Is it true that the bi-(convex/Fenchel)-conjugate $f^{**}$ is also continuous.
It was claimed in a book without a proof. Of course I checked the related Fenchel relations but these only provide a semicontinuity result for the (bi)conjugate.

A: $f^{**}\le f$ and $f$ is bounded above on an open set makes $f^{**}$ bounded above on an open set so because $f^{**}$ is convex lower semicontinuous it is continuous on the interior of its domain.


text:
Q: when I type in python bot.py the command wont execute So I am attempting to code a discord bot and when I go to execute the command "python bot.py" the command comes up blank and doesn't execute the command. Anyone know how to fix this?

# bot.py
import os

import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

client = discord.Client()

@client.event
async def on_ready():
    print(f'{'The Ban Hammer has connected to Discord!'})

client.run(TOKEN)

#.env
DISCORD_TOKEN={Discord Token}

A: os.getenv takes a string, the name of the environmental variable to lookup, not the value of the variable. You should use:
TOKEN = os.getenv('DISCORD_TOKEN')

and below
client.run(TOKEN)

Of course you should use a different private token, as the one you just posted is now public information on this website.
Also
f'{The Ban Hammer} has connected to Discord!'

is probably meant to be
'The Ban Hammer has connected to Discord!'

As the inside of the curly braces needs to be valid code.


text:
Q: $f(x) = ab^x$ where $a$ and $b$ are positive constants. $f(5) = 96, f(7) = 384$. What is the value of $a$? What I've figured out so far:
$$
\begin{align}
ab^5 &= 96\\
ab^7 &= 384\\
\frac{384}{96} &= 4\\
4(ab^5) &= ab^7\\
4a\cdot 4b^5 &= ab^7\\
3a\cdot 4b^5 &= b^7\\
3a\cdot 4 &= b^2\\
12a &= b^2
\end{align}
$$
?????

A: Your error is in the line
$$3a \cdot 4b^5 = b^7$$
It appears you've subtracted $a$ from both sides, rather than dividing.

We have
$$\frac{384}{96} = \frac{ab^7}{ab^5} = b^2 \implies b^2 = 4$$
Do you see how to finish from here?

A: If you plug in $f(5)=96$, you will get $$96=ab^5 \tag{A}$$
If you plug in $f(7)=384$, you will get $$384=ab^7 \tag{B}$$
Now, $(\text{B})$ divided by $(\text{A})$ yields $$\frac{386}{84}=\frac{ab^7}{ab^5}$$
and simplifying the above equation gives $$4=b^2$$ Thus $\boxed{b=\pm2}$.
Plug in $b=\pm2$ into either $(\text{A})$ or $(\text{B})$ (I choose $(\text{A})$ below):
$$96=a(\pm2)^5$$ and you will get $\boxed{a=\pm3}$.


text:
Q: Send current geo position on time interval I want to send my current location, but not always, only for every 10 minutes. And also to avoid high battery costs.
Is it available to set timer for this action?
map.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
       @Override
       public void onMyLocationChange(Location loc) {
            sendPosition(loc.getLat(), loc.getLong())
       }

A: You can update a datetime variable each time sendPosition is called. And in the location change event check if the difference between current datetime and the datetime variable is more than 10 minutes before calling sendPosition again.


text:
Q: Ruby: Will optimistic locking work using update_all? I am trying to implement the Optimistic Locking for Race Condition. For that, I added an extra column lock_version in the Product: Model through migration.
#Product: Model's new field:
    #  attribute_1
    #  lock_version                       :integer(4)      default(0), not null
before_validation :method_1, :if => :recalculation_required_attribute

def method_1
    ####
    ####
    if self.lock_version == Product.find(self.id).lock_version
       attributes["lock_version"] += 1
       attributes["updated_at"] = Time.now
       Product.where(:id => self.id).update_all(attributes)
       self.attributes = attributes
    end
end

Product Model has an attribute_1. If recalculation is required for attribute_1 then before_validation: method_1 will call.
I am using optimistic locking using lock_version.  However, update_all will not increase the lock_version and can't self.save! because it will
trigger the before_validation: method1 for infinite times.
If I do like following will optimistic locking work using update_all?
attributes["lock_version"] = 1 +1
attributes["updated_at"] = Time.now
Product.where(:id => self.id).update_all(attributes)

You can check more information on lock_version


text:
Q: Absolute positioned div dynamically extending beyond relative parent div I have an absolute positioned div inside a relative positioned div. Both of these live inside of a parent div I can't change, which has an explicitly set width of 150px. I want my absolute positioned div to be able to extend beyond this 150px width. I also need this to be dynamic - i.e. I don't want to have to explicitly set a width anywhere, I want the behavior you'd normally get by setting max-width and having the contents of the absolute positioned div fill the available space. Is this possible?

.outerContainer {
  width:150px;/*can't be changed*/
}

.innerContainer {
  position: relative;
}

.absolutely {
  position: absolute;
}

.item {
  display:inline-block;
}

              first item

              second item

              third item

              fourth item

jsfiddle version:
https://jsfiddle.net/3xbpzp7b/

A: What you can do is to add a fixed width to the .innerContainer element which functions as a kind of max-width for .absolutely as you describe it. If there's more content inside .absolutely, it will wrap, if there's less, it will become less wide.

.outerContainer {
  width:150px;/*can't be changed*/
}

.innerContainer {
  position: relative;
  width: 250px;
}

.absolutely {
  position: absolute;
  background: #fb9;
}

.item {
  display:inline-block;
}

              first item

              second item

              third item

              fourth item


text:
Q: WordPress Acceso a Dashboard por IP en HTACCESS tengo un portal web insitucional en WordPress al cual le limité el acceso a Dashboard por IP utilizando lo siguente:
<FilesMatch "^(wp-login\.php)">
Order Allow,Deny
Allow from 10.X.X.A
Allow from 10.X.X.B
Allow from 10.X.X.C
Allow from 10.X.X.D
Allow from 10.X.X.E
Allow from 10.X.X.F
</FilesMatch>

Hasta alli todo bien, solo que ahora tengo un grupo de personas que necesitan acceder desde una VPN de otro proveedor que les asigna direcciones IP por DHCP por lo que necesito abrir para la subred 192.X.X.0/255 y he intentado lo siguiente:
 Allow from 192.X.X.0/255

Obtengo un 500 Internal Server Error
Allow from 192.X.X

También obtengo un 500 Internal Server Error
Alguna idea..???
Saludos Leo


text:
Q: Uploadig multiple files with different requirements in multer I have a route that expects a multipart form and in this multipart form, there are two files that are going to be uploaded.
1- a video file that should have a size limit of 2GB and is going to be directly saved on disk in public/videos
2- a thumbnail which is an image that should have a size limit of 20MB and is going to be saved in memory to be resized with sharp and saved into a different directory which is public/video/thumbnails
I tried to use upload.fields([ { name: 'video', maxCount: 1 }, { name: 'thumbnail', maxCount: 1 } ]) . but it doesn't satisfy. These two files should have different size limits and I want one to be stored in disk directly and the other one in memory.
It looks like I need two different multer().single() on the same route.
Is it possible with multer to do this? or any other multipart parsers?


text:
Q: Truncated If Statement C++ (Turning letters to numbers) I am trying to change a series of letters into numbers with C++ and have started by making this code.
However, it appears that the math that calculates the digit1 variable is never getting executed.
Any thoughts?
#include <iostream>
#include <string>

using namespace std;

int main()
{
    int qtyofnumbers, num, digit1, counter;
    char letters, upperlower;

    cout << "Enter a letter: ";
    cin >> letters;

    for (counter = 0; counter < 8; counter++)
    {
        if (counter == 3)
            cout << "-";

        num = static_cast<int>(letters) - static_cast<int>('A');

        if (0 <= num && num < 26)
            digit1 = (num / 3) + 2;

        if (((num / 3 == 6 ) || (num / 3 == 7)) && (num % 3 == 0))
            digit1 = digit1-1;

        if (digit1 > 9)
            digit1 = 9;

        cin >> letters;
    }

    cout << digit1;

    return 0;
}

A: My guess is that the problem is in your input. Are you entering capital letters or lowercase letters? Their ASCII codes are different. So, you probably want to change the code from
num= static_cast<int>(letters)-static_cast<int>('A');

to something like
if (num >= 'a')
    num = letters - 'a';
else
    num = letters - 'A';

Also, as mentioned by @jtbandes, use the curly braces { and }. Whitespace does not determine scope in C++. Even if it's for only one line of code after your if-statement, it'll save you headaches in the future.

A: Is the static cast necessary? I recommend using a string stream or just traversing the string character by character using .at() and relying on the ascii values for conversion. http://web.cs.mun.ca/~michael/c/ascii-table.html.


text:
Q: In a string containing nested parenthesis, how to obtain the whole parenthesis using str_extract? Given a string
x <- "Really long (distraction) wine name (Country A)"

I'm able to extract "(Country A)" using str_extract(x, '\\([^()]+\\)$').
However when it comes to nested parenthesis, such as "Wine name (Country A (State))", running that code gives me NA. How can that be avoided and why is it happening?

A: You can use ?R like:
x <- c("Really long (distraction) wine name (Country A)"
     , "Wine name (Country A (State))")
regmatches(x, regexpr("(\\(([^()]|(?1))*\\))$", x, perl=TRUE))
#[1] "(Country A)"         "(Country A (State))"

Where a(?1)z is a recursion which match one or more letters a followed by exactly the same number of letters z.


text:
Q: How to generate a random boolean in Dart I've seen people generate random booleans in Dart before, but I can't remember how to do it.
I just found the answer so I'm adding it below Q&A style.

A: You can generate a random boolean with Random:
import 'dart:math';

final randomNumberGenerator = Random();
final randomBoolean = randomNumberGenerator.nextBool();

If you want to generate a stream of random booleans you can continue to call nextBool().


text:
Q: What does it mean for (placement_params) the parentheses after new operator and before type in c++? What does the first parenthesis do?
// TArray<struct FBatchedLine> BatchedLines;      // declared in LineBatchComponent.h

new(BatchedLines) FBatchedLine(Start, End, Color, LifeTime, Thickness, DepthPriority);

The new operator reference says it is a placement_params:

If placement_params are provided, they are passed to the allocation function as additional arguments

I suppose it creates the object directly at the end of the given array BatchedLines, but I am not sure to understand fully how it works.
When are placement_params useful?
Note
For those who have an access to the github UnrealEngine repo, here is the source file.

A: This is placement new syntax. It constructs an object of type FBatchedLine at the memory pointed to by BatchedLines with the constructor arguments (Start, End, Color, LifeTime, Thickness, DepthPriority). After the call, BatchedLines can be used to reference the constructed object.
Informally, you could imagine invoking the constructor with BatchedLines being this.

A: The text: palcement_params is not explained in the reference C++ page. According to English meaning: where to put the pointer usually a location inside an array.  Here is a code example from boost
T* buffer;
size_t write_index;
new (buffer + write_index) T(t); // copy-construct

Essentially, you put a new object of type T into the write_index location of buffer.


text:
Q: .NET Core application auth with identityserver4 The authentication part was done using Identity Server 4, now I want to change the clientId and clientSecret, and use the new credentials, but in the backend I can't find the client configuration and I don't know how it's configured. Could you help me ? Thanks.
I checked the database, there is a table called ClientSecrets
there is a clientId and a value column with hashed value (maybe base64), and other columns also, but I didn't understand what's going on.


text:
Q: Remote Mysql Server connection by PHP While i execute following code:
$db_host = "<IP>";  // Host name
$db_user = "<usr>";  // User name of your database
$db_password = "<pass>";     // Password of your database
$db_name="<db name>";   // Database name

$con = mysql_connect($db_host,$db_user,$db_password);
mysql_select_db($db_name) or die("Cannot select database...");

It shows following errors:
Warning: mysql_connect() [function.mysql-connect]: OK packet 6 bytes shorter than expected in C:\wamp\www\limosbusesjets\connection.php on line 21
Warning: mysql_connect() [function.mysql-connect]: mysqlnd cannot connect to MySQL 4.1+ using old authentication in C:\wamp\www\limosbusesjets\connection.php on line 21
    Cannot select database...

A: These errors generally happen when one is using PHP 5.3, and its new mysqlnd driver to connect to MySQL (which is often the case with PHP 5.3, as it's one of the new stuff introduced with 5.3 -- and "mysqlnd" is mentionned in your second error) : with those, you cannot connect to a MySQL database using the old-passwords system.
Which means you'll have to change the way your MySQL server deals with passwords, to switch to the "new" authentication system.
See, for instance :

*

*Resolving the "OK packet 6 bytes shorter than expected"

*MySQL PHP incompatibility.

*Backward Incompatible Changes
Not sure it's what is causing the problem in your case, but that's one common MySQL related thing, with PHP 5.3, for those errors...


text:
Q: Why is 'Allow Snapshot Isolation' set to TRUE on the master and msdb databases? Why is the database property Allow Snapshot Isolation set to TRUE on the master and msdb databases, but FALSE on other system databases? The default option for this property is also FALSE when creating user databases.

A: I would imagine that it is enabled to minimize blocking in the master and msdb databases of the system processes.  It is disabled in user databases because in user databases it can greatly increase the disk IO requirements of the tempdb database.


text:
Q: How do I query_posts in cat=1 AND not in cat=2 Let's say I have 3 categories, College (cat=1), Corporate (cat=2), and Idea of the Week (cat=3)
There is a home page for College and a home page for Corporate.
On the College home page, in one section I want to show recent post that is in College but not not in Idea of the Week.
My initial attempt:
<?php query_posts( 'cat=1&cat=-3' ); the_post(); ?>'

but this appears to pull post found in EITHER cat 1 OR cat 3.
Same home page, in a second section I want to show recent post that is in College AND in Idea of the Week.
I'm using:
<?php query_posts( array( 'category__and' => array(1,3), 'posts_per_page=1&orderby=date&order=DESC' )); the_post(); ?>

This seems to work as needed. Is there a similar 'category_and_not' function that I can use for the first query?

A: First, never use query_posts, use WP_Query for additional queries, or pre_get_posts to alter the main query.
Refer to WP_Query in Codex for a complete list of available arguments. You want to use category__not_in in this case:
$args = array(
    'category__in' => array(1),
    'category__not_in' => array(2)
);
$query = new WP_Query( $args );


text:
Q: Forwarding of a specific port I tried forwarding a specific ip:port to a specific ip:port on a linux machine. I used iptables with the following command:
iptables -t nat -A OUTPUT -p tcp -d 10.0.2.5 --dport 80 -j DNAT --to-destination 69.31.21.42:80

10.0.2.5 is an arbitrary address that I chose to see if the command works, and 69.31.21.42 is an address of a public web site.
I then verified that the the forwarding worked: I ran nmap -p 80 10.0.2.5 and got a positive result. Very good so far. However, I then tried running nmap -p 81 10.0.2.5, and also got a positive result. That's not what I expected, as I wanted port 80 only to be forwarded. I ran iptables -t nat -L and noticed that indeed, the entire 10.0.2.5 host is mapped to 69.31.21.42:80:
Chain OUTPUT (policy ACCEPT)
target     prot opt source     destination
DNAT       tcp  --  anywhere   ip-10-0-2-5.ec2.internal  tcp dpt:http to:69.31.21.42:80

What's missing in my iptables command? Why isn't --dport working?

A: You need to use POSTROUTING chain for do what you want to do.
iptables -t nat -A POSTROUTING -p tcp -d 10.0.2.5 --dport 80 -j SNAT --to 69.31.21.42:80

man iptables
and POSTROUTING (for altering packets as they  are  about  to  go
                  out)

A: First of all please know that it's not possible to forward TCP IP:Port to another IP:Port. This is only possible with UDP and there's a separate Perl script for that.
Yes you can forward an IP directly to another machine, not a specific port.


text:
Q: Error while compiling statement: FAILED: SemanticException [Error 10002] - MAKE SELECT WITH MAX ON HIVE I'm trying to execute this select to return only the most recent inserted records
i'm using HIVE
co_junta_comer and co_informacao can repeat but é need the most recent record
select *
from reference_data.reference_data_novajunta A
where A.ts_inclusao IN
  (select max(row2.ts_inclusao)
   from reference_data.reference_data_novajunta row2
   where A.co_junta_comer = row2.co_junta_comer
     AND row2.co_informacao = A.co_informacao)

i'm getting the ERROR
Error while compiling statement: FAILED: SemanticException [Error 10002]: line 4:28 Invalid column reference 'co_junta_comer'`

A: Use row_number():
select rdn.*
from (select rdn.*,
             row_number() over (partition by co_junta_comer, co_informacao order by ts_inclusao desc) as seqnum
      from reference_data.reference_data_novajunta rdn
     ) rdn
where seqnum = 1;


text:
Q: Proving the polynomial identity $\,\, w[z,t]=\sum_{k=0}^{n}w_k(z)t^{n-1}.$ I appreciate any suggestions you can give me to prove the next result:
Let $w_0(z)=1$ and for $k\geq 1$ $$w_k(z)=z^k+b_1z^{k-1}+b_2z^{k-2}+\cdots+b_k.$$
Let $w(z)=z^{n+1}+b_1z^n+\cdots+b_nz+b_{n+1}.$
If $\,\,\displaystyle w[z,t]=\frac{w[z]-w[t]}{z-t}\,\,$ show that $\,\,\displaystyle w[z,t]=\sum_{k=0}^{n}w_k(z)t^{n-1}.$


text:
Q: How do I use the Google Maps coordinate system? I don't understand how the coordinate system works in the plotGoogleMaps package.
For example, lets say I wanna plot these coordinates (Eiffel Tower):
lat <- 48.858264 # y
lon <- 2.294557 # x

Here's my code:
coords <- data.frame(lon, lat)
coordinates(coords) <- ~ lat + lon
proj4string(coords) <- CRS('+init=epsg:28992')
plotGoogleMaps(coords, filename = 'map.htm')

However the location I obtain is completely different to what i was expecting. What am I doing wrong?
Edit:
Inverted lat and lon

A: You seem to provide EPSG:4326 coordinates (WGS84) but use the EPSG:28992 in your projection.
Try to change
proj4string(coords) <- CRS('+init=epsg:28992')

to
proj4string(coords) <- CRS('+init=epsg:4326')


text:
Q: Is it possible to use ggiraph interactive functions with ggplots generated using stat_summary I am using stat_summary to generate a column plot from a dataframe. I would like to report the values to the user via tooltips using geom_col_interactive from ggiraph.
I can get the values from the ggplot using ggplot_build and construct a tooltip as below. However, I cannot work out how to use ggiraph with the plot generated using stat_summary to present tooltips interactively. I could of course use the summary_values tibble and generate a different ggplot using geom_col_interactive, but this would defeat the purpose of using stat_summary (which lends itself nicely to faceting). Is there any way to do this?  Or must I use summarySE from Rmisc to generate the tibble to be plotted using geom_col_interactive?
library(tidyverse)

mpg_histogram <- ggplot(mpg, aes(x=as.factor(cyl), fill = as.factor(cyl))) +
  stat_summary(aes(y = hwy), fun = "mean", geom = "bar") +
  stat_summary(aes(y = hwy), fun.data = mean_se,
               geom = "errorbar", width = 0.2, size = 0.2)

summary_values <- ggplot_build(mpg_histogram)$data[[2]]
summary_values <- summary_values %>%
  mutate(mean = round(y,1), sem = round(ymax-y,1)) %>%
  mutate(tooltip = paste("Mean mpg:",mean,"+/-",sem)) %>%
  select(c(mean,sem,tooltip))

A: One approach to achieve your desired result via stat_summary would be to pass the ggiraph:::GeomInteractiveCol to the geom argument. However, be aware that GeomInteractiveCol is not exported by ggiraph and so requires to use :::. Additionally, to have both the mean and the standard error in the tooltip requires to switch to fun.data="mean_se". For convenience I make use of a simple custom function to create the tooltip:
library(ggplot2)
library(ggiraph)

tooltip <- function(y, ymax, accuracy = .01) {
  mean <- scales::number(y, accuracy = accuracy)
  sem <- scales::number(ymax - y, accuracy = accuracy)
  paste("Mean mpg:", mean, "+/-", sem)
}

gg_point <- ggplot(mpg, aes(x = as.factor(cyl), fill = as.factor(cyl))) +
  stat_summary(aes(y = hwy, tooltip = after_stat(tooltip(y, ymax))),
    fun.data = "mean_se", geom = ggiraph:::GeomInteractiveCol
  ) +
  stat_summary(aes(y = hwy),
    fun.data = mean_se,
    geom = "errorbar", width = 0.2, size = 0.2
  )

girafe(ggobj = gg_point)

A: Here are a workaround for not using GeomInteractiveCol() and an alternative/shortcut to after_stat() :
library(ggplot2)
library(ggiraph)

tooltip <- function(y, ymax, accuracy = .01) {
  mean <- scales::number(y, accuracy = accuracy)
  sem <- scales::number(ymax - y, accuracy = accuracy)
  paste("Mean mpg:", mean, "+/-", sem)
}

gg_point <- ggplot(mpg) +
  aes(x = as.factor(cyl), fill = as.factor(cyl), y = hwy,
    tooltip = tooltip(..y.., ..ymax..)
  ) +
  geom_bar_interactive(fun.data = "mean_se", stat = "summary") +
  geom_errorbar_interactive(fun.data = "mean_se", stat = "summary",
    width = 0.2, size = 0.2
  )

girafe(ggobj = gg_point)

I personally prefer to use the geom_ grammar rather than the stat_ one, because it is more consistent with the rest of ggplot code.
And here is a way of doing so in one command with glue(), but for an unknown reason, it still necessitates after_stat():
{ggplot(mpg) +
  aes(x = as.factor(cyl), fill = as.factor(cyl), y = hwy,
    tooltip = glue("Mean mpg: {round(y, 2)} +/- {round(ymax, 2)}") %>% after_stat()
  ) +
  geom_bar_interactive(fun.data = "mean_se", stat = "summary") +
  geom_errorbar_interactive(fun.data = "mean_se",
    stat = "summary", width = 0.2, size = 0.2)
  } %>%
  girafe(ggobj = .)


text:
Q: Single character tag autocomplete for interesting tags The single character URL problem seems fixed, but when trying to add a single character tag (I tried "r" and "c"), the autocomplete does not show it. As written by Eric, it doesn't stop me from adding the tag by simply pressing enter in the form.

A: When you type in that single word, the auto-complete does not suggest it. However, if you just type "C" and hit the Add button, you'll be interested in it.


text:
Q: Angular 1: области передача данных в директивах с transclude и repeat Никак не могу решить такую задачу.
Надо создать табы с разнесенной логикой для навигации и контента (разные директивы), они друг с другом общаются с помощью events.
С директивой навигации никаких проблем нет.
Все вопросы про директиву с отображением контента. Есть директива <tabs> и внутри нее множество директив <tab> с уникальным ключём-атрибутом. Каждый <tab> может содержать другую директиву/expression/просто html. <tab> показывается только когда ключ в её аттрибуте равен переменной у родителя <tabs>. Не получается реализовать такую структуру.

*

*Как передать значение переменной item.key в аттрибут директивы с ng-repeat и ng-transclude? ( пример <tab key="{{item.key}}" repeat="item in items"> )

*Как получить доступ в директиве <tab> к переменной selectedTabKey родителя <tabs>?

var app = angular.module("app", []);
var $ = angular.element;

app.run(function($templateCache, $rootScope) {
  $rootScope.items = [
    {key:1,value:'a'},
    {key:2,value:'b'},
    {key:3,value:'c'}
  ];
});

app.directive( "tabs", function() {
  return {
    restrict: "AE",
    scope: true,
    transclude: true,
    replace: true,
    template: "

",
    link: function(scope, elem, attr, ctrl) {
      scope.selectedTabKey = 2;
      // TODO: changing the selectedTabKey value
      // want to show/hide the related tab
    }
  };
});

app.directive( "tab", function($compile) {
  return {
    restrict: "AE",
    transclude: true,
    replace: true,
    template: "

",
    link: function( scope, elem, attr, ctrl, transclude ) {
      var transc = $(elem[0].querySelector( "[transclude]" ));
      transclude( scope, function( childs ) {
        transc.append( childs );
      });
      transc.attr("ng-repeat", attr.repeat);
      $compile(transc)(scope);
      // todo: access parent's var `selectedTabKey`
      // and make visible the related tab
    }
  };
});

  <tabs>

    <tab key="{{item.key}}" repeat="item in items">

      {{item.value}}
    </tab>
  </tabs>

A: Нашел решение.
Используя свойство require в директиве tab со ссылкой ^^tabs, получаем доступ к контроллеру родителя.
В сниппете функциональность, какую хотел реализовать.

(function(angular) {
  'use strict';

angular.module('app', [])

  .run(function($rootScope){
    $rootScope.items = [
      {key: 1, label: 'label1', value:'content1'},
      {key: 2, label: 'label2', value:'content2'},
      {key: 3, label: 'label3', value:'content3'}
    ]
  })

  .directive('tabsNav', function() {
    return {
      scope: { data: '=?data', id: '@for' },
      replace: true,
      restrict: 'EA',
      controller: 'tabsNavCtrl',
      template: [
        '
',
          '
',
            '{{item.label}}',
          '
',
        '
'
      ].join('')

    };
  })
  .controller('tabsNavCtrl', function($scope, $rootScope) {
    if ($scope.data === null) $scope.data = [];
    $scope.click = function(key) {
      $scope.data.forEach(function(item) {
        item.active = item.key === key;
      });
      return $rootScope.$broadcast('TabsClick', {
        key: key,
        id: $scope.id
      });
    };
  })

  .directive('tabs', function() {
    return {
      restrict: 'E',
      transclude: true,
      scope: { id: '@' },
      controller: ['$scope', function MyTabsController($scope) {
        var panes = $scope.panes = [];

        $scope.$on('TabsClick', function(e, data){
          var id = data.id;
          var key = data.key;
          if ($scope.id == id) $scope.select(key);
        });

        $scope.select = function(key){
            angular.forEach(panes, function(pane) {
              pane.selected = pane.key == key;
          });
        };

        this.addPane = function(paneScope) {
          panes.push(paneScope);
          if (panes.length === 1)
            $scope.select(paneScope.key);
        };
      }],
      template: '

'
    };
  })

  .directive('tab', function() {
    return {
      require: '^^tabs',
      restrict: 'E',
      transclude: true,
      scope: { key: '@' },
      link: function(scope, element, attrs, tabsCtrl) {
        tabsCtrl.addPane(scope);
      },
      template: '

'
    };
  });
})(window.angular);
<!doctype html>

  <meta charset="UTF-8">
  <title>Example - example-directive-tabs-production</title>

  <tabs-nav for='id1' data="items"></tabs-nav>

  <tabs id="id1">
    <tab key="{{item.key}}" ng-repeat="item in items">
      {{item.value}}
    </tab>
  </tabs>


text:
Q: Replace decimals in floating point numbers Someone on this platform has already helped me with generating the following code:
col,row = (100,1000)
a = np.random.uniform(0,10,size=col*row).round(6).reshape(row,col)
mask = (a*1e6+1).astype(int)%10<2
a[mask] += 2e-6

This code ensures that the last decimal is not a 0 or a 9. However, I would like to have no 0's nor 9's in all the decimals that are generated (such that it will not be possible to have a number 1.963749 or 3.459007).
It would be fine for all 0's and 9's to be, for example, replaced by a 2 (1.263742 and 3.452227 considering the example above). I know that the function replace (0, 2) does not work for the decimal numbers. Is there a way to replace these numbers or should the code be rewritten to make this work?

A: An alternative that generates each digit position separately (Try it online!):
a = sum(np.random.randint(1, 9, (row, col)) * 10**e
        for e in range(-6, 1))

With more NumPy (Try it online!):
a = (np.random.randint(1, 9, (row, col, 7)) * [[10.**np.arange(-6, 1)]]).sum(2)

A: Solution using strings (I find it non-elegant but it works).
Assuming this input as pandas DataFrame df:
       col1      col2
0  1.234567  9.999909
1  1.999999  0.120949

You can stack and replace as string:
def rand(x):
    import random
    return random.choice(list('12345678'))

df2 = (df
 .stack()
 .astype(str)
 .str.replace(r'[09](?!.*\.)', rand)
 .astype(float)
 .unstack()
 )

Output:
       col1      col2
0  1.234567  9.665236
1  1.184731  0.128345