text:
Q: Google geocoding API security I am asking this question after extensively reading Google's recommended approach, but I do have a problem with all these approaches, let me explain the situation.
I use combination of geolocation and geocoding API to know the approximate state location and then display relevant content. The geolocation API needs to be called obviously from the browser to get appropriate geolocation of the user. Google provides HTTP Referrer based restriction for this API. I know someone can easily spoof the referrer and make calls with the same API key. I do not see a huge advantage even though Google recommends this.
On the other hand Google does not allow HTTP Referrer for geocoding API, but it does allow that for the MAPS JavaScript API. But again if you are not using Google maps then using that API is violation of Google's terms. Now google recommends to move the code that uses geocoding web services API to be on the back-end so that your key will be protected. But since ultimately I need to deliver the result to a front-end web application that is publicly accessible and I can only make a browser based Ajax call to first get the geolocation to feed to geocoding, I ultimately need to make an Ajax call to get my geocoding information. Then someone can easily just latch onto my end-point to piggy back on and call the geocoding API as much as they want. So for situations like this I want to know what is the ideal and secured way to deal with. May be there are other APIs that might be an ideal situation for this.

A: In my case, I am not doing any maps so it's all purely server-side to get latitudes, longitudes and driving distance between two points. This today from Google support which might help and if you're using maps, then the links may provide further insight.

Regarding API restrictions, please note that HTTP referrers will not
  work on Geocoding API since HTTP referrers can only be used for client
  side services. In other words, Geocoding is a web service API and
  should only be used on server-side implementation. IP address
  restrictions should be used for web service APIs. However, if you are
  using the Geocoding API in a website, IP address restriction would not
  work. Please check the suitable restrictions for each API in the
  following link:
https://developers.google.com/maps/api-key-best-practices#api_key_table
To make this work, you should create a separate key and use the new
  one in your Geocoding API request URL. You may add a restriction to
  this key by using an "API restriction", and restrict it to Geocoding
  API only. If you don't want to create another key, you may keep using
  your current one but make sure to change your implementation and use
  the client side Geocoding service from the Maps JavaScript API. In
  that case, please refer to this documentation:
https://developers.google.com/maps/documentation/javascript/geocoding
Another suggestion would be to get a static IP address from your ISP,
  especially if you are planning to use it on a public website. For
  development purposes, a sound solution would be to get three separate
  keys: one for the staging and tests, another for server-side requests
  and a third one for client-side requests. That way, you are making
  sure your API key is protected.


text:
Q: Compact set and function with no extremum I have to find compact set $D\subset\mathbb{R}^2$ with non-empty interior and differentiable function $f:D\rightarrow\mathbb{R}$ which don't have local extremum in every interior point of $D$. Any hints?

A: $$D=\left[0,{\pi\over2}\right]^2, f(x,y)=\sin x$$ makes sure the extremums are on the boundary and $f$ is differentiable.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is class correlation? I am referring to iris.arff dataset that comes with Weka distribution. There are 3 classes and 4 attributes. It gives below information regarding the 4 attributes-
%                  Min  Max   Mean    SD   Class Correlation
%    sepal length: 4.3  7.9   5.84  0.83    0.7826
%     sepal width: 2.0  4.4   3.05  0.43   -0.4194
%    petal length: 1.0  6.9   3.76  1.76    0.9490  (high!)
%     petal width: 0.1  2.5   1.20  0.76    0.9565  (high!)

How is the last column computed?
After googling class correlation I found Intraclass_correlation Not sure if it's the same thing, also how can a single class correlation number be given when the number of classes is three?

A: The "Class Correlation" is Pearson Correlation Coefficient between target variable and the other variables. i.e. corr(Species, sepal length) = 0.7826
Here is the R output (i do not have Weka handy):
> iris2 <- data.frame(iris$Sepal.Length, iris$Sepal.Width, iris$Petal.Length, iris$Petal.Width, as.numeric(iris$Species))
> head(iris2)
  iris.Sepal.Length iris.Sepal.Width iris.Petal.Length iris.Petal.Width as.numeric.iris.Species.
1               5.1              3.5               1.4              0.2                        1
2               4.9              3.0               1.4              0.2                        1
3               4.7              3.2               1.3              0.2                        1
4               4.6              3.1               1.5              0.2                        1
5               5.0              3.6               1.4              0.2                        1
6               5.4              3.9               1.7              0.4                        1
> cor(iris2)
                         iris.Sepal.Length iris.Sepal.Width iris.Petal.Length iris.Petal.Width as.numeric.iris.Species.
iris.Sepal.Length                1.0000000       -0.1175698         0.8717538        0.8179411                0.7825612
iris.Sepal.Width                -0.1175698        1.0000000        -0.4284401       -0.3661259               -0.4266576
iris.Petal.Length                0.8717538       -0.4284401         1.0000000        0.9628654                0.9490347
iris.Petal.Width                 0.8179411       -0.3661259         0.9628654        1.0000000                0.9565473
as.numeric.iris.Species.         0.7825612       -0.4266576         0.9490347        0.9565473                1.0000000

The last column as.numeric.iris.Species is yours Class Correlation from Weka. The numbers do not match exactly. This could be cause by:

*

*different data set size

*different discretisation method (i.e I use setosa = 1, versicolor = 2, and virginica = 3)

A: Weka is open sourced software, so you can find it out from its source code comment:
"Evaluates the worth of an attribute by measuring the correlation (Pearson's) between it and the class.
Nominal attributes are considered on a value by value basis by treating each value as an indicator. An overall correlation for a nominal attribute is arrived at via a weighted average."
link
Use 'sepallength' as an example:

*

*make a real vector v1, each element is petal length, e.g. [5.1, 4.9, 4.7, ..., 5.9]

*make a real vector v2, each element is class indicator, e.g. [1, 1, 1, ...., 1, 2, 2, 2,...2, 3, 3, 3, ... 3]    (there are 50 ones, 50 twos and 50 threes representing three iris class and each class have 50 observations).

*calculate Pearson correlation between v1 and v2.
For more information, read this Weka source code if you want to re-implement the calculation. link.


text:
Q: htaccess redirect subdomain to subdirectory I have a multisite with drupal, I created a site which at first should be accessible in multiple ways (subdomains and paths), but now I want keep just one of them; so I whould redirect all the others. Right now I have:
aaa.domain.com/
bbb.domain.com/
domain.com/aaa/
domain.com/bbb/
www.domain.com/aaa/
www.domain.com/bbb/
And I want to redirect all of them to http://www.domain.com/bbb/
I tried to write:
RewriteCond %{HTTP_HOST} ^aaa.domain.com$ [OR]

RewriteCond %{HTTP_HOST} ^bbb.domain.com$ [OR]

RewriteCond %{HTTP_HOST} ^www.domain.com\/aaa$ [OR]

RewriteRule ^/?$ "http\:\/\/www\.domain\.com\/bbb\/" [R=302,L]

I will use 302 and no 301 until it work as expected.
If I entern aaa.domain.com it works as expected, but if I enter
http://aaa.domain.com/page/1
it don't work
I have read anything I can about htaccess, but I am missing something.
Thanks

A: Add the following to your .htaccess file in the root of your domain.com site.
RewriteEngine On
RewriteBase /

#if request is not on  www.domain.com
RewriteCond %{HTTP_HOST} !^www\.domain\.com$ [NC]
#and it is not for a folder starting with /bbb/
RewriteCond %{REQUEST_URI} !^/bbb/ [NC]
#redirect to www.domain.com/bbb/
RewriteRule .* http://www.domain.com/bbb/ [L,R=301]


text:
Q: Minimum distance of the linear code $\{0,1\}$
Let $H$ be a check matrix for a linear code $C$. Then the minimum distance
  of $C$ is $d \in \mathbb N$ such that there exists a set of $d$, but no set of $d-1$, linearly dependent columns in $H$.

1) Am I right to surmise from the above thorem that $C$ has minimum distance $1$ iff. $H$ contains a column of zeros?
2) Consider the linear code $\{0,1\}$ whose minimum distance is clearly $1$. Its check matrix $H$ is the $0$x$1$ zero matrix, so $H$ has $0$ linearly dependent columns. This contradicts the above theorem, doesn't it?

A: Your observation in (1) looks correct. The empty set is never linearly dependent, and a set with one vector can only be linearly dependent if that vector is zero.
For (2), while a $0 \times 1$ matrix has zero rows, it does have one column. In this case, the one column is the zero vector (of the zero-dimensional vector space), and so your $H$ does have a zero column.

A: 1) is right, and here is the way to think about it. Suppose you have two codewords that are exactly the minimum distance apart, say $x$ and $y$. This means that there is a vector $e$ such that $x+e=y$ and $e$ has weight $d$.
Since $e=y-x$, $e$ is in the code, and so multiplying it with the parity check results in the zero matrix. The $d$ entries witness that the corresponding $d$ columns are linearly dependent. The existence of a smaller nonzero weight codeword would contradict the definition of $d$ as the mininum distance, so every set of $d-1$ columns must be linearly independent.
If the code has distance 1, it contains a codeword of weight 1. Of course, for this to have zero product with the parity check matrix, the corresponding column must be zero.
2) As you've found out already, there is no contradiction with 1), it's just that the $d-1$ statement breaks down since you can't talk about "a set of $-1$ LI vectors", and there is this 0 dimension degeneracy.
At any rate, this concern is just academic since the usefulness of the generator matrix and parity check matrix disappear for linear codes $d=1$. For such a code you can instantly identify all codewords and dual codewords, and the code neither detects nor corrects errors.


text:
Q: Have you ever installed the ScoutMaps-iOS-SDK and ScoutMaps-iOS-SDK Tools via CocoaPods? Now, I have an issue with integrating SKMaps iOS SDK and Tools.
I did integrate your SDK and Tools using cocoapods, not manually.
But it's not working.
Here's the screenshot of error I got finally.
cocoapods directory tree
x86_64 errors I got from building pod.proj
Is it possible to integrate SKMaps iOS SDK and Tools via cocoapods?
Or, shall I have to integrate them manually from Demo project that I've downloaded?
I did research on Skobbler developer forums, but no related questions/answers.
Dear Ando, I know you are an expert in SKMaps.
Please let me know if you have ever experienced this before.
Hope your kindly support.
Best.

A: Integration with cocoapods worked fine for me.
Be sure that you opened and are trying to build .xcworkspace file of your project created after you run "pod install".


text:
Q: Typescript event emitter typings I'm implementing event emitter but ran into a problem with typescript typing. Please tell me how to make this work.
export type IEventMap = {
    "mount": () => void;
    "mounted": () => void;
    "unmount": () => void;
    "unmounted": () => void;
    "test1": (stringArg: string) => void;
    "test2": (numberArg: number) => void;
};

export type IEventNames = keyof IEventMap;
export type IEventFn<K extends IEventNames> = IEventMap[K];
export type IEventListeners = { [K in IEventNames]?: Set<IEventFn<K>> };

export default class Events {

    private readonly listeners: IEventListeners = {};

    public on <K extends IEventNames> (eventName: K, callback: IEventFn<K>) {

        if (!this.listeners[eventName]) {
            this.listeners[eventName] = new Set();
        }

        this.listeners[eventName].add(callback);

    }

    public off <K extends IEventNames> (eventName: K, callback: IEventFn<K>) {

        if (this.listeners[eventName]) {
            this.listeners[eventName].delete(callback);
        }

    }

    public emit <K extends IEventNames> (eventName: K, ...args: Parameters<IEventFn<K>>) {

        if (this.listeners[eventName]) {
            this.listeners[eventName].forEach(callback => callback(...args));
        }

    }

}

// test

const events = new Events();

events.on("mount", () => {
    console.log("mount");
});

events.on("test1", arg => {
    console.log(arg);
});

events.on("test2", arg => {
    console.log(arg);
});

events.emit("mount");
events.emit("test1", "test string");
events.emit("test2", 1);

Errors

Type 'Set<IEventFn>' is not assignable to type
'IEventListeners[K]'.   Type 'Set<IEventFn>' is not assignable to
type 'Set<() => void> & Set<() => void> & Set<() => void> & Set<() =>
void> & Set<(stringArg: string) => void> & Set<(numberArg: number) =>
void>'.
Type 'Set<IEventFn>' is not assignable to type 'Set<() => void>'.
Type 'IEventFn' is not assignable to type '() => void'.
Type '(() => void) | (() => void) | (() => void) | (() => void) | ((stringArg: string) => void) | ((numberArg: number) => void)'
is not assignable to type '() => void'.
Type '(stringArg: string) => void' is not assignable to type '() => void'.

Object is possibly 'undefined'. Object is possibly 'undefined'. Object
is possibly 'undefined'.

A spread argument must either have a tuple type or be passed to a rest
parameter.

Playground link

A: *

*interchangeable callbacks should actually be rest-args, so

export type IEventFn<K extends IEventNames> = (...a: Parameters<IEventMap[K]>) => void;

fixes half of errors

*ts doesn't remember type if if by whatever reason, just use ?.
this.listeners[eventName]?.delete(callback);

*ts doesn't want do assign mismatching types, type down so types match

let l: { [KK in K]?: Set<IEventFn<KK>> } = this.listeners;
(l[eventName] ??= new Set<IEventFn<K>>()).add(callback);

playground


text:
Q: Anaconda keeps caching modules How can I prevent Anaconda from caching my module? Every time that I make a change in a specific file in my codebase (for which the containing folder has a __init__.py file), python does not recognize those changes and keeps executing the previous version of the file, which happens to be cached at anaconda3/lib/python3.6/site-packages/"the name of the main module".

A: If you are doing development of a package, it is best to use the develop option to one of the installers. This creates a link to the development directory, rather than copying files, so you can test your updated code. For instance, if you have a directory like:
project
|── setup.py
|── package_name/
    |── __init__.py
    |── module.py

You can install in development mode by running one of the following commands in the directory with setup.py (and note that the dots . at the ends of the commands are important):

*

*conda develop . (requires conda-build to be installed)

*

*Uninstall with conda develop --uninstall .

*pip install -e .

*

*Uninstall with pip uninstall package_name

*python setup.py develop

*

*Uninstall with python setup.py develop --uninstall
In your situation, what you should do is remove the installed package, either with conda or pip, depending on how you installed it, and then use the develop mode to incorporate changes in your code.
Note that you will need to restart the Python interpreter (if you're running in interactive mode) every time you want to use the changed code. Another option is to use IPython and the autoreload extension, although note the caveats about using that in the documentation.
Also related: Python setup.py develop vs install


text:
Q: Invalid MIT-MAGIC-COOKIE-1 key - Ryzen 5 & Nvidia I am using a dual-boot Ubuntu 20.04 on a Lenovo Ideapad Gaming with Ryzen 5 and NVidia Geforce. First, I didn't manage to get Ubuntu installed. I tried to use the second answer in this thread nouveau stalled at ffff error message while trying to convert Windows 10 laptop to Ubuntu, which solved my issues.
If I use mpirun, this error pops up:
Invalid MIT-MAGIC-COOKIE-1 key.

I tried to use xhost +local: but that did not work unfortunately. I also tried to switch the driver to X.org. If I do this and reboot, all options are grey and the only option available is a manually installed driver (which is then also selected).
Moreover, if I run the command nvidia-settings, I get the following errors:
(nvidia-settings:4351): GLib-GObject-CRITICAL **: 15:16:53.124: g_object_unref: assertion 'G_IS_OBJECT (object)' failed

ERROR: nvidia-settings could not find the registry key file. This file should
       have been installed along with this driver at
       /usr/share/nvidia/nvidia-application-profiles-key-documentation. The
       application profiles will continue to work, but values cannot be
       prepopulated or validated, and will not be listed in the help text.
       Please see the README for possible values and descriptions.

** Message: 15:16:53.170: PRIME: No offloading required. Abort
** Message: 15:16:53.171: PRIME: is it supported? no

I think the magic cookie is perhaps due to mistakes in the drivers but I do not know how to proceed further. Any help is very much welcome.


text:
Q: Need to extract data from Mono I have a mono content out of this i need to get the data to variable.
private String name;
 var result = Mono.just("surendra")

      .subscribe(x -> name=x);

  LOG.info("Hello " + name);

Tried the above code to get the value but it is showing as null.
Can you please help me the way i can get the content from Mono with non blocking way Thanks in Advance:)


text:
Q: How to change HwndSource RootVisual I have a HwndSource and I have two WPF user controls, I would like to set one of them the RootVisual of this HwndSource and sometimes switch between these two WPF user controls.
Just wonder am I able to do that?
My two WPF user controls are: m_media, m_stored,
First time I just new the HwndSource object and use HwndSource.RootVisual = m_media to set the root visual, then I want to change its root visual to m_stored, can anybody tell me how to do that?
Thank you very much everybody.


text:
Q: Stacking Numpy arrays of different length using padding a = np.array([1,2,3])
b = np.array([4,5])

l = [a,b]

I want a function stack_padding such that:
assert(stack_padding(l) == np.array([[1,2,3],[4,5,0]])

Is there a standard way in numpy of achieving
EDIT: l could have potentially many more elements

A: I think itertools.zip_longest with fill_value=0 can work for you:
import itertools

a = np.array([1,2,3])
b = np.array([4,5])

l = [a,b]

def stack_padding(l):
    return np.column_stack((itertools.zip_longest(*l, fillvalue=0)))

>>> stack_padding(l)
array([[1, 2, 3],
       [4, 5, 0]])

A: With numpy.pad:
a = np.array([1,2,3])
b = np.array([4,5])

l = [a,b]

max_len = max([len(arr) for arr in l])
padded = np.array([np.lib.pad(arr, (0, max_len - len(arr)), 'constant', constant_values=0) for arr in l])

A: If you don't want to use itertools and column_stack, numpy.ndarray.resize will also do the job perfectly. As mentioned by jtweeder, you just need to know to resulting size of each rows. The advantage to use resize is that numpy.ndarray is contiguous in memory. Resizing is faster when each row differs alot in size. The performance difference is observable between the two approaches.
import numpy as np
import timeit
import itertools

def stack_padding(it):

    def resize(row, size):
        new = np.array(row)
        new.resize(size)
        return new

    # find longest row length
    row_length = max(it, key=len).__len__()
    mat = np.array( [resize(row, row_length) for row in it] )

    return mat

def stack_padding1(l):
    return np.column_stack((itertools.zip_longest(*l, fillvalue=0)))

if __name__ == "__main__":
    n_rows = 200
    row_lengths = np.random.randint(30, 50, size=n_rows)
    mat = [np.random.randint(0, 100, size=s) for s in row_lengths]

    def test_stack_padding():
        global mat
        stack_padding(mat)

    def test_itertools():
        global mat
        stack_padding1(mat)

    t1 = timeit.timeit(test_stack_padding, number=1000)
    t2 = timeit.timeit(test_itertools, number=1000)
    print('With ndarray.resize: ', t1)
    print('With itertool and vstack: ', t2)

The resize method wins in the above comparison:
>>> With ndarray.resize:  0.30080295499647036
>>> With itertool and vstack:  1.0151802329928614


text:
Q: What is the range of a Mage's Alter Time?
Alter Time
Alter the fabric of time, causing the caster to return to their current location, health, mana, buffs, and debuffs, when cast a second time, or after 6 sec.
Effect negated if the caster dies within the 6 sec before the effect occurs or moves too far away.

When looking at the spell or the buff for Alter Time, neither actually mentions the range that counts as "too far away." How many yards away from the casting position is a Mage allowed to move before Alter Time no longer works?

A: This thread (based on user testing) states that the maximum range that this will work over is 100 yards - seemingly. They're speculating that this essentially works as 'whatever distance you cover while the effect is up' but won't undo actions like taking a portal, for example.
Keep in mind it is beta though, so is subject to change.


text:
Q: ¿Es posible obtener un entero desde int *x? busco una manera de solucionar este problema. Tengo una funcion llamada encolar que recibe como parámetros:
int extraer(pila *S, int *x)

Lo que hace es guardar el valor extraído de una pila en el segundo parámetro, es decir, "int *x". El problema es que después necesito ese valor como entero "int x" para ingresarlo como parámetro a esta función:
insertar(pila *S, int x)

No encuentro la manera de obtener un entero a partir de *x. Gracias de antemano

A:
¿Es posible obtener un entero desde int *x?

Si el puntero apunta hacia al valor, solo es cuestión de desreferenciar el puntero.
int a = 10;
int *b = &a;

printf("%d\n",*(b));

De esta manera obtienes el valor al que apunta, y no el valor que almacena el puntero (la dirección de memoria).


text:
Q: Por que o getter retorna null? No meu projeto de android studio eu tenho uma classe de getters and setters para me ajudar, mas por algum motivo na main activity quando chamo o db.busca() (que está na classe de operações da base de dados) que coloca um token no u.setToken("vem da BD").
Depois na MainActivity se eu der user.getToken() ele vem null, eu já tive a testar se eu der um user.getToken() na classe da Base de Dados funciona tudo ok, mas na MainActivity resulta null.
Em alguns casos eu quero que retorne null mas quando não devia retornar null e sim um token ele retorna null
Classe da Base de Dados:
    public void busca(){
    String[] colunas = new String[]{"token", "nome"};
    Cursor cursor = db.query("user", colunas, null, null, null, null, "token ASC");
    if(cursor.getCount() > 0){
        cursor.moveToFirst();
        do{
            Utilizador u = new Utilizador();
            u.setToken(cursor.getString(0));
            u.setNome(cursor.getString(1));
        }while(cursor.moveToNext());
    }
}

Classe Utilizador:
package imm.pt.immflix;

    public class Utilizador {
        private String nome;
        private String mail;
        private String token;
        private String foto;
        private int typeService;

        public String getNome() {
            return nome;
        }

        public void setNome(String nome) {
            this.nome = nome;
        }

        public String getMail() {
            return mail;
        }

        public void setMail(String mail) {
            this.mail = mail;
        }

        public String getToken() {
            return token;
        }

        public void setToken(String token) {
            this.token = token;
        }

        public String getFoto() {
            return foto;
        }

        public void setFoto(String foto) {
            this.foto = foto;
        }

        public int getTypeService() {
            return typeService;
        }

        public void setTypeService(int typeService) {
            this.typeService = typeService;
        }
    }

Classe MainActivity:
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            getSupportActionBar().hide();
            TextView tvtitle = findViewById(R.id.tvTitle);
            ObjectAnimator anime = ObjectAnimator.ofFloat(tvtitle, "alpha", 0f, 1f);
            anime.setDuration(2000);
            anime.start();
            DB db = new DB(this);
            db.busca();
            Utilizador user = new Utilizador();
            token = user.getToken();
            if(token == null){
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent = new Intent(MainActivity.this, Login.class);
                        intent.putExtra("isNew", true);
                        startActivity(intent);
                        finish();
                    }
                }, 3000);
            }else{
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent = new Intent(MainActivity.this, Login.class);
                        intent.putExtra("isNew", false);
                        startActivity(intent);
                        finish();
                    }
                }, 3000);
            }

        }

A: O user.getToken() está a ser usado logo após a instanciação do objecto user.
Utilizador user = new Utilizador();
token = user.getToken();

Como não foi atribuído nenhum valor ao campo token user.getToken() retorna nulo.
Com os elementos disponibilizado julgo que o método busca() deveria retornar um Utilizador para poder ser utilizado na classe Activity:
public Utilizador busca(){
    String[] colunas = new String[]{"token", "nome"};
    Cursor cursor = db.query("user", colunas, null, null, null, null, "token ASC");
    if(cursor.getCount() > 0){
        cursor.moveToFirst();
        do{
            Utilizador u = new Utilizador();
            u.setToken(cursor.getString(0));
            u.setNome(cursor.getString(1));
        }while(cursor.moveToNext());
        return u;
    }
    return null;
}

O código na Activity deverá ser alterado para:
DB db = new DB(this);
Utilizador user = db.busca();

Já que há a possibilidade da query retornar nada, adicione um teste para verificar isso.
Não sei se a query poderá retornar mais de um Utilizador ou não, caso retorne, o método deverá retornar uma lista de Utilizador.
Não estive a ver se há mais alguma coisa "errada".


text:
Q: How to configure custom login page with Azure Active directory authentication in ASP.NET MVC 4.5 I am using Azure Active directory to authenticate the users. When I click on OpenConnectId in home page, it is getting redirected to Microsoft login page. Are there any options to use custom login page instead and may be call the authentication API from here.
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(new CookieAuthenticationOptions() {
                LoginPath = new PathString("/Account/Login")
            });
            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId = "xxxx",
                Authority = "xxx",
                RedirectUri = "Account/login",

            });


text:
Q: Unexpected behavior of FTS Postgresql Following select
select name, plainto_tsquery('russian', name) tbl_tokens, plainto_tsquery('russian', 'корневые продукты') const_tokens
from product_catalog.product p
WHERE 1=1
  and id = 1

returns next recordset

name
tbl_tokens
const_tokens

Корневой продукт
'корнев' & 'продукт'
'корнев' & 'продукт'

tbl_tokens and const_tokens is equal
But query:
select name, plainto_tsquery('russian', name) tbl_tokens, plainto_tsquery('russian', 'корневые продукты') const_tokens
from product_catalog.product p
WHERE 1=1
    and id = 1
    and name @@ plainto_tsquery('russian', 'корневые продукты');

returns empty result and I don't understand the reason
Russian dictionary and config are present:
select d_t.dictname, d_t.dictinitoption, d_t.tmplname, n.nspname, n.nspacl
from
      (select d.dictname, d.dictinitoption, d.dictnamespace, t.tmplname
       from pg_ts_dict as d join pg_ts_template as t on (d.dicttemplate=t.oid)) as d_t
            join pg_namespace as n on (d_t.dictnamespace=n.oid)

dictname
dictinitoption
tmplname
nspname
nspacl

russian_stem
language = 'russian', stopwords = 'russian'
snowball
pg_catalog
{postgres=UC/postgres,=U/postgres}

gin index is present, but not used. EXPLAIN show Seq Scan (may by for very small table)
CREATE INDEX idx_fts_name
    ON product_catalog.product USING gin
    (to_tsvector('russian'::regconfig, name::text))
    TABLESPACE pg_default;

A: Figured out the problem
instead of
'name @@ plainto_tsquery('russian', 'корневые продукты');'

i used
'to_tsvector('russian'::regconfig, name::text) @@ plainto_tsquery('russian', 'корневые продукты');'

it's working and gin index is used after growing the table "product"


text:
Q: Generalized Schur polynomial from block Toeplitz matrices By using the Jacobi-Trudi identity, one may interpret banded Toeplitz matrices, and minors of such matrices in terms of Schur polynomials, see for example
http://www-stat.stanford.edu/~cgates/PERSI/papers/toeplitz02.pdf
Now, my question is as follows: Is there a similar way to interpret banded block Toeplitz matrices in terms of Schur polynomials? (Maybe one needs to have some generalized version of Schur polynomials, or matrix-valued "polynomials?")


text:
Q: Change UIBarbuttonItems Color How can I set UIBarButtonItem's color to green? I'm using iOS 4, there is no tint property. please help me.

A: Please try the below code.
self.navigationController.navigationBar.tintColor = [UIColor greenColor];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:nil action:NULL];

A: In iOS 4:
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setBackgroundImage:[UIImage imageNamed:@"green.png"] forState:UIControlStateNormal];
button.frame=CGRectMake(0.0, 100.0, 60.0, 30.0);
[button setTitle:@"Green" forState:UIControlStateNormal];
[button addTarget:self action:@selector(yourAction) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *myButton = [[UIBarButtonItem alloc] initWithCustomView:button];

Here you need a green image for doing this, you are creating a custom button with this image and set it as the view of UIBarButtonItem.
In iOS 5 you can use:
[[UIBarButtonItem appearance] setTintColor:[UIColor greenColor]];

Please check these links for more:

*

*UIAppearance Protocol

*User interface customization

A: I know this is an old question, but in case anyone is using a customView, you can try:
myButton.customView.tintColor = [UIColor blackColor];

A: In Swift 4
This is how you can add your custom color to UIBarButtonItem
let barButtonItem = UIBarButtonItem.init(
        title: "Paired",
        style: .done,
        target: self,
        action: #selector(self.myAction(sender:))
      )
barButtonItem.tintColor = UIColor.init(red: 247/255, green: 65/255, blue: 126/255, alpha: 1.0)
self.navigationItem.rightBarButtonItem = barButtonItem


text:
Q: How to find eigenvalues & eigenvectors of this 3 by 3 matrix? I have the following $3 \times 3$ matrix
$$\begin{bmatrix} -1 & -3 &-4 \\ 0 & 3 & 0\\ 2 & 1 & 5\end{bmatrix}$$
I found eigenvalues $1$ and $3$ with multiplicity of $2$. How do I find the eigenvectors now?

A: I agree with your eigenvalues, $\lambda=1$ and $\lambda=3$.
As you already have these I'll not put my working for them.
The standard theory is that we now solve,
$$\begin{bmatrix}-1-\lambda & -3 &-4 \\0 & 3-\lambda & 0\\2 &1 &5-\lambda\end{bmatrix} \begin{bmatrix}X \\Y \\Z\end{bmatrix}=\begin{bmatrix}0 \\0 \\0\end{bmatrix}$$
For $\lambda=1$ and let X=1,
$$\begin{bmatrix}-2 & -3 &-4 \\0 & 2 & 0\\2 &1 &4\end{bmatrix} \begin{bmatrix}1 \\Y \\Z\end{bmatrix}=\begin{bmatrix}0 \\0 \\0\end{bmatrix}$$
Middle Row yields $2Y=0$ so $Y=0$
Bottom Row yields $2+Y+4Z=0$ so $Z=-\frac{1}{2}$
$$\begin{bmatrix}1 \\0 \\-\frac{1}{2}\end{bmatrix}$$
which is more conveniently expressed as
$$\begin{bmatrix}2 \\0 \\-1\end{bmatrix}$$
For $\lambda=3$,
$$\begin{bmatrix}-4 & -3 &-4 \\0 & 0 & 0\\2 &1 &2\end{bmatrix} \begin{bmatrix}1 \\Y \\Z\end{bmatrix}=\begin{bmatrix}0 \\0 \\0\end{bmatrix}$$
Top Row yields $-4-3Y-4Z=0$
Bottom Row yields $2+Y+2Z=0$
Solve these simultaneously to get $Y=0$ and $Z=-1$
Thus the eigenvector corresponding to $\lambda=3$ is,
$$\begin{bmatrix}1 \\0 \\-1\end{bmatrix}$$
When we get three real eigenvalues with repetitions it corresponds to one of several types of 3D shear
There is a good tutorial with examples of what can happen with various multiplicities of eigenvectors and what the implications are here : Link https://sites.calvin.edu/scofield/courses/m256/materials/eigenstuff.pdf
Hope this answers your question : it's a while since I did one of these so I enjoyed revising the process.

A: The other vector that you're missing is the solution of
$$
     (A-3I)X = \left[\begin{array}{c}1 \\ 0 \\ -1\end{array}\right]
$$
This vector $X$ satisfies $(A-3I)^2X=0$. This vector, along with the eigenvectors corresponding to eigenvalues $3$ and $1$ will give you want you want.


text:
Q: How do Deep Link into a fragment in an Android App. Is it possible? So is it possible to deep link into a fragment? So my main activity launches different fragments depending on what the user clicks.
So i created a deep link for my main activity with the intent filter in the manifest file. But how would you do this for  fragment??
Any help would be helpful
Thanks.

A: You certainly can do this. You'll need to parse the intent in the activity and use the fragment manager to populate late the fragment you wish. Replace Action and Fragment with your own.
@Override
protected void onNewIntent(final Intent intent) {
    super.onNewIntent(intent);
    parseIntent(intent);
}

private void parseIntent(Intent intent) {
    final String action = intent.getAction();

    if (action != null) {
        if (Action.<ONE>.equals(action)) {
            FragmentManager fm = getFragmentManager();
            Fragment<ONE> fragment = (Fragment<ONE>) Fragment.instantiate(this,
            Fragment<ONE>.class.getCanonicalName(),
            getIntent().getExtras());
            FragmentTransaction ft = fm.beginTransaction();
            ft.add(R.id.fragment_id, fragment);
            ft.commit();
        } else if (Action.<TWO>.equals(action)) {
            FragmentManager fm = getFragmentManager();
            Fragment<TWO> fragment = (Fragment<TWO>) Fragment.instantiate(this,
            Fragment<TWO>.class.getCanonicalName(),
            getIntent().getExtras());
            FragmentTransaction ft = fm.beginTransaction();
            ft.add(R.id.fragment_id, fragment);
            ft.commit();
        }
    }
}

Actions are just strings that should be unique for a given intent. They can be anything. Like:
"myapp.image_included" or
"myapp.link_url" etc

A: If you're using the Android Jetpack Navigation library you can easily create deeplinks for fragments, which makes sense since the whole philosophy of the library is to have a single activity with multiple fragments. You can find the documentation here.
The gist of it is adding a deeplink element in your nav_graph.xml file like this:
<fragment android:id="@+id/a"
    android:name="com.example.myapplication.FragmentA"
    tools:layout="@layout/a">
    <deeplink app:url="www.example.com"
        app:action="android.intent.action.MY_ACTION"
        app:mimeType="type/subtype"/>
</fragment>

And then linking the navigation XML to your manifest adding the following into your AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapplication">

    <application ... >

        <activity name=".MainActivity" ...>
            ...
            <nav-graph android:value="@navigation/nav_graph" />
            ...
        </activity>
    </application>
</manifest>

This will generate all the intent-filters necessary to make use from the deeplinks.
Then you get into FragmentA using intents, i.e.
val intent = Intent().apply {
    data = Uri.parse("www.example.com")
}

Or if you're already in your app, you can use your NavController and simply call findNavController().navigate("www.example.com")

A: yes possible, you can call fragment inside activity(from which activity your going to fragment class) - call inside onCreate method
Intent appLinkIntent = getIntent();
String appLinkAction = appLinkIntent.getAction();
Uri appLinkData = appLinkIntent.getData();

String recipeId = appLinkData.getLastPathSegment();

if(recipeId.equals("mybag")){
  call fragment 1(i am sending link like this -(example)
   www.google.com/mybag)
 }else{
 call fragment 2
}


text:
Q: scala - it is possible to create "Int increment extension method" that can be invoked from any package? I wonder if i can create an implicit increment or "++" operator on "Int" type
that i can be invoked from any scope in my code.
(i.e from any package)
so for exampe:
var x = 4
x++
println(x) // will print 5

thanks.

A: You can create an implicit class at a high level (util package). I was able to achieve this using explicit type ascription:
object RichPrimitive {
  implicit class RichInt(var int: Int) {
    def ++ = int = int + 1
  }
}

import RichPrimitive.RichInt

var x: RichInt = 4 // if you don't do : RichInt, this does not work
x ++

println(x.int) // returns 5

Not entirely sure why the implicit did not take care of it (without it println for x returned a 4).

A: No.

*

*Implicit classes don't allow you to change a variable. Note that this is not the same as mutability vs immutability (i.e. changing a 1 to a 2 is changing a variable, not mutating the Int. To contrast, adding a value to a collection.mutable.Map is mutating the Map, not changing the variable that holds the map)

*Even if they did allow you to change a variable, implicit classes always need to be imported if you want to use them outside the scope where you define them. You might define your implicit class RichInt in a package object for the main package in your code, but if you want to use it from any other package, you'll still need to import it.

That said, @Tanjin's answer is a fair approximation of what you want.


text:
Q: css - float header and footer above content, auto resize background with jquery I'm trying to reproduce a layout similar to bulgari.com as far as the header, footer and auto resizing the background image goes (i know bulgari.com has a flass movie as a background but I need to use an image that auto resizes to the content div).
I'm not very good a decoding css and jquery so if anyone could spare a few minutes, I'd like to know how I can float the header and footer above the content div and also resize the content background image on document load and window resize events.
I've done this so far but it's pretty basic.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-7">
<title>Untitled Document</title>
<link href="css/default.css" rel="stylesheet" type="text/css">
<link href="css/layout.css" rel="stylesheet" type="text/css">

abc

layout.css:
@charset "utf-8";
/* CSS Document */

.bg {
    background: url(../images/thematic.jpg) repeat scroll;
}
.header {
    background: transparent url("../images/trans.png") repeat scroll 0 0;
    height: 80px;
    min-width: 990px;
    width: 100%;
    z-index: 100;
}
.bg-container {
    background: #F00;
}

.footer {
  background: url("../images/trans.png") repeat scroll 0 0 transparent;
  bottom: 0;
  font-size: 10px;
  height: 30px;
  left: 0;
  min-width: 990px;
  overflow: hidden;
  width: 100%;
}
.content {
    width: 990px;
    margin: 0px auto;
    background: #999;
}
.main-container {
    min-height: 500px;
    width: auto;
}

A: is this what you are after? http://jsfiddle.net/7jd7t/
all i did was set the background of the body to fixed, and set the background-size to 100%. No scripting required.
Feel free to let me know if this is not what you are after...

A: Copying another site, can't help you with that.
but as far as floating header and footers go,
If what you want is that they stick to the top and bottom and appear above other content, this can be easily accomplished using pure css.
HTML:

Your header content goes here

Footer content

CSS:
#fixedhead{
position: absolute;
z-index:1000;
top: 0;
bacground-color: rgba(0,0,0,0.5) /*50% transparent black background*/
}
#fixedfoot{
position: absolute;
z-index:1000;
bottom: 0;
bacground-color: rgba(0,0,0,0.5) /*50% transparent black background*/
}


text:
Q: flutter: Access two firecast collection in same widget I am new to Flutter, I am trying to consume two collections in firebase firecast in same widget. but I am unable to fit it.
Flutter document provides a single StreamBuilder fits in a widget reference
return new StreamBuilder<Event>(
  stream: FirebaseDatabase.instance.reference().child('schedules').onValue,
  builder: (BuildContext context, AsyncSnapshot<Event> event) {
    if (!event.hasData)
      return new Center(child: new Text('Loading...'));
      Map<String, Map> schedules = event.data.snapshot.value;
     // Do something with the list of schedules
})

My Desired Output:

I am trying to achieve this scenario.

A: Just wrap it in a Column and add another StreamBuilder:
Column(
  children: <Widget>[
    StreamBuilder(...),
    StreamBuilder(...),
  ],
)


text:
Q: Remove duplicate values from array based on a value in a nested array I would like to compare an array of records in order to find those with a common identity stored in the record. The record is implemented as an associative array. If multiple records exist for any identity, I want to remove the record with lower value from the array.
I'll try to explain it on the example.
Here is example array. You can see there is two times same "ean".
I need to find all arrays with same "ean" and compare their "productCount". Then I need to remove array which has a lower productCount value.
[0] => Array
    (
        [ean] => **6909536610216**
        [productPrice] => 760
        [productCount] => 107
    )

[1] => Array
    (
        [ean] => 6909536610261
        [productPrice] => 779
        [productCount] => 128
    )

[2] => Array
    (
        [ean] => **6909536610216**
        [productPrice] => 920
        [productCount] => 20
    )

function removeduplicateKeys($data){

    $_data = array();

    foreach ($data as $v) {
      if (isset($_data[$v['ean']])) {
        // found duplicate
        continue;
      }
      // remember unique item
      $_data[$v['ean']] = $v;
    }

    $data = array_values($_data);
    return $data;
 }

So output should be
[1] => Array
    (
        [ean] => 6909536610261
        [productPrice] => 779
        [productCount] => 128
    )

[2] => Array
    (
        [ean] => **6909536610216**
        [productPrice] => 920
        [productCount] => 20
    )

Can you help me please? Thank you


text:
Q: How to implement the head function using fst function I admit this is my homework. But I really couldn't find a good solution after working hard on it.
There might be some stupid ways to accomplish this, like:
myHead (x:[]) = x
myHead (x:y:xs) = fst (x, y)

But I don't think that's what the teacher wants.
BTW, error-handling is not required.
Thanks in advance!

A: There's a very natural function that's not in the prelude called "uncons" which is the inverse of uncurried cons.
cons :: a -> [a] -> [a]
uncurry cons :: (a, [a]) -> [a]

uncons :: [a] -> (a, [a])
uncons (x:xs) = (x, xs)

You can use it to implement head as
head = fst . uncons

Why is uncons natural?
You can think of a list as the datatype that's defined through the use of two constructor functions
nil :: [a]
nil = []

cons :: (a, [a]) -> [a]
cons (a,as) = a:as

You can also think of it as the data type which is deconstructed by a function
destruct :: [a] -> Maybe (a, [a])
destruct [] = Nothing
destruct (a:as) = Just (a, as)

It's well beyond this answer to explain why those are so definitively tied to the list type, but one way to look at it is to try to define
nil      :: f a
cons     :: (a, f a) -> f a

or
destruct :: f a -> Maybe (a, f a)

for any other container type f. You'll find that they all have very close relationships with lists.
You can almost already see uncons in the second case of the definition of destruct, but there's a Just in the way. This is uncons is better paired with head and tail which are not defined on empty lists
head [] = error "Prelude.head"

so we can adjust the previous answer to work for infinite streams. Here we can think of infinite streams as being constructed by one function
data Stream a = Next a (Stream a)

cons :: (a, Stream a) -> Stream a
cons (a, as) = Next a as

and destructed by one function
uncons :: Stream a -> (a, Stream a)
uncons (Next a as) = (a, as)

-- a. k. a.
uncons stream = (head stream, tail stream)

the two being inverses of one another.
Now we can get head for Streams by getting the first element of the return tuple from uncons
head = fst . uncons

And that's what head models in the Prelude, so we can pretend like lists are infinite streams and define head in that way
uncons :: [a] -> (a, [a])
uncons (a:as) = (a, as)

-- a. k. a.
uncons list = (head list, tail list)

head = fst . uncons

A: Perhaps you're expected write to your own cons List type, then it might make more sense. Although type synonyms can't be recursive, so you end up using a non-tuple data constructor, making the tuple superfluous.. it would look like:
data List a = Nil | List (a, List a)
        deriving( Show )

head :: List a -> a
head (List c) = fst c

A: Like already said in the comments, this is just a silly task and you won't get something you could call a good implementation of head.
Your solution, for those requirements, is just fine – as the only change I would replace (x:y:xs) with (x:y:_) since xs isn't used at all (which would actually cause a compiler warning in some settings). In fact, you could do that with y as well:
myHead (x:_:_) = fst (x, undefined)

There would be alternatives that look perhaps not quite so useless use of fst, i.e. don't just build a tuple by hand and immediately deconstruct it again:
myHead' [x] = x
myHead' xs = myHead' . fst $ splitAt 1 xs

myHead'' = foldr1 $ curry fst

myHead''' = fromJust . find ((==0) . fst) . zip [0..]

but you could rightfully say that these are just ridiculous.


text:
Q: How can I make my text appear below the navbar? I'm currently coding my first website and I'm experiencing a problem I don't know how to solve. I have a home page with a navbar, and when I put text in the page, it appears cut because the text starts behind the navbar. How can I make the text appear below the navbar?
Here's the code.

body {
   background-attachment: fixed;
   background-color: rosybrown;
}
{% load static %}

<!DOCTYPE html>

   <meta charset= "UTF-8">
   <title>DNA TRANSLATOR</title>
    <meta charset= "UTF-8"/>
    <meta name= "viewport"
   content="width=device-width, initial-scale=1" />

    <link rel="stylesheet" href= '{% static
   "css/style.css" %}'>

  <link rel="stylesheet"
  href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
  integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z"
  crossorigin="anonymous">

        DNA Translator
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation">

        </button>

              Home (current)

              Translator

              Process

        {% block content%}

        {% endblock content%}

A: It is probably duplicate question. But I answer it anyway.
Basicly when you set nav as position: fixed; You must add a padding-top or margin-top to your main container or body to start from the very bottom of the navbar.
So basicly I added padding-top to body (recommanded practice):
body{
      padding-top: 56px;
    }

OR  margin-top or padding-top to .main.container
.main.container{
          margin-top: 56px;
        }

body {
   background-attachment: fixed;
   background-color: rosybrown;
   padding-top: 56px;
}
{% load static %}

<!DOCTYPE html>

   <meta charset= "UTF-8">
   <title>DNA TRANSLATOR</title>
    <meta charset= "UTF-8"/>
    <meta name= "viewport"
   content="width=device-width, initial-scale=1" />

    <link rel="stylesheet" href= '{% static
   "css/style.css" %}'>

  <link rel="stylesheet"
  href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
  integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z"
  crossorigin="anonymous">

        DNA Translator
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation">

        </button>

              Home (current)

              Translator

              Process

        {% block content%}

        {% endblock content%}

        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus id nulla eu imperdiet. Fusce imperdiet tellus eu sem hendrerit, eu consequat leo rhoncus. Nullam vehicula nunc id leo consequat, et bibendum magna fringilla. Proin rhoncus aliquam odio, sed euismod lectus efficitur ut. Nam faucibus nisi ullamcorper, luctus quam id, rutrum nisi. Sed ac interdum ante, ultrices aliquam eros. Nulla arcu urna, lacinia eu accumsan sed, consectetur et dui. Vivamus mi nisl, dapibus vel justo vitae, dignissim ornare nisl. Maecenas condimentum ex id erat consequat porttitor. Duis auctor sed nisl at blandit. Phasellus maximus purus vel efficitur consequat. Donec tempus justo in metus pellentesque dignissim. Nulla facilisi. Aenean vulputate dictum turpis id mattis. Integer turpis metus, fermentum eget blandit elementum, ultrices hendrerit arcu.

A: The text is behind the navbar because you gave it a fixed position with the "fixed-top" class. If you dont want to have a fixed navbar, i think you can just remove that classname.
If you want to have a fixed navbar, you can move your container down with css, use "margin-top" for that with the height of your navbar and your content will be visible right under the navbar.


text:
Q: ArcPad get vbs script location Within arcpad (edit form) I want to get the current location of the vbs script running.  This simple vbs script outside of arcpad works fine.
wscript.echo " " + Wscript.ScriptFullName

However, when I call this statement within a button click event in arcpad is gives and error and says object wscript required.
I also tried this:
Dim sCurPath
sCurPath = CreateObject("Scripting.FileSystemObject").GetAbsolutePathName(".")
Application.MessageBox(sCurPath)

However, I'm getting

C:\Users\username\Desktop

directory (not location of vbs script).
Any ideas of how to find current directory of vbs script running in arcpad edit form?

A: You do not have to specify wsscript......  ArcPad, by default, supports VBscript and Jscript and Python script if you have the python interpreter installed.  Therefore,  just use the regular VBS syntax.


text:
Q: How can I connect remotely without forcing the local user to be disconnected? I am trying to remote control a computer running XP Pro SP3 from my laptop running on W8.1. When I connect, I'm told that by connecting I will terminate the local session - something I don't want to do. Is there a way around this limitation?
I found this message from tsilb posted in 2008
"Windows Server editions support one console plus two remote connections simultaneously. When configured as a Terminal Server, they support one per license. All other editions support one total session, local or remote.
"Are the pre-existing connections local or Domain accounts? Look around in the local or group security policies. If Domain, check the user account properties."
...but I'm afraid I don't understand the terminology he has used and so don't know if it is definitely answering my question.
If this is a limitation of RDC, can you recommend an alternative solution that will allow me to connect while leaving the local user logged in?


text:
Q: Configuring Interactive Login via the registry is not working - Any Ideas? According to all the tutorials I've read, this should cause Windows to prompt for both a username and password at login, but doesn't (Doing this via the registry should result in the same behavior as when these options are set through the group policy editor.):
#set "Interactive login – Display user information when session is locked" to "Do not display user information"
#REF: http://www.sevenforums.com/tutorials/182700-lock-computer-screen-display-user-information-not.html
Set-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System]" -name "DontDisplayLockedUserId" -Value 3

#set "Interactive Login – Do not display last user name" to "Enabled"
Set-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System]" -name "dontdisplaylastusername" -Value 1

The registry keys update but the login prompt still shows the last user name. Rebooting twice didn't help. (I've watched the changes being made with regedit, when I do this through the Security Policy editor and these seem to be the correct registry keys...)
Is there something else that I need to do to get the settings to take? I've tried doing a group policy update after updating the registry, but that just stepped on the changes.
Thanks!

A: I figured this out: The problem was that group policy was updating at logoff and over writing the settings.
The fix was to remove the security permissions for NT AUTHORITY\SYSTEM and then grant the SYSTEM user account only readkey permission to the keys in question.
(I would have posted a copy of my code but I can't figure out how to get code block function to format more than the first line. So, here's the reference source I used: http://www.rubaniuk.com/?p=192)


text:
Q: Get tablespace of a given table in DB2 What is the command to get the name of tablespace of a given table in DB2 database ?

A: On Db2 for LUW you can use this query. You get one row per table data partition (1 row for a non range partitioned table).
SELECT
    SD.TBSPACE AS DATA_SPACE
,   SL.TBSPACE AS LONG_SPACE
,   SI.TBSPACE AS INDEX_SPACE
FROM
          SYSCAT.DATAPARTITIONS P
JOIN      SYSCAT.TABLESPACES   SD ON SD.TBSPACEID = P.TBSPACEID
LEFT JOIN SYSCAT.TABLESPACES   SL ON SL.TBSPACEID = P.LONG_TBSPACEID
LEFT JOIN SYSCAT.TABLESPACES   SI ON SI.TBSPACEID = P.INDEX_TBSPACEID
WHERE
    TABSCHEMA = 'YOUR_SCHEMA'
AND TABNAME   = 'YOUR_TABLE'


text:
Q: libGDX: game universal speed I am new to libGDX,
i'm trying to make a feature in my game where the player clicks on a button and the whole game speed is increased by a factor of 2.
i dont want to change every game element's speed, i'm looking for a global option of controlling the 'game tick' speed.

A: Well to conserve a proper frame independant application (game) you must use the time passed between two frames. Libgdx already gives you this in the render method of your screens if you use Game in the form a a float argument called delta or deltaTime. If you don't, you can still use Gdx.graphics.getDeltaTime() to get it.
If you already do this (you should!). Just multiply it for 2 before the game updates.
@Override
public void render(float delta){
    delta = delta * 2;
    //game logic
    ...
}

A: Agree with Lestat for multiplying delta by 2 (or any needed factor). Just wanted to add a suggestion to distinct code that calculates (object positions, collisions and stuff) from the code that draws the graphics. And when you calculate delta then, based on it's value also calculate how many times your calculation code should be executed, and execute it that many times. And do the drawing after that, just once.
Point is, that if you speed up your time (or you have slow FPS on some devices) you can miss some important time frames. I.e. you have some bullet traveling 5px per frame. And you speed up your time (or frame rate drops) difference between 2 frames (and 2 calculations) can be too big and if you only multiply bullet speed with that delta parameter you movement step can be too big, so your bullet can avoid some (hit) detection and i.e. pass trough the enemy without hitting it. So main idea is to repeat calculation in smaller steps ("game clock") and not miss the action and draw in as more as possible.

A: I wrote this tick timer for doing world updates. It tells the world to update it's state every 50 milliseconds, 20 times a second.
The render method gets called every time for updating unimportant things like particle effects that don't need a world update and the world in its current state and npc entities moving at their given speed.
To increase game speed just modify the game tick treshold ticktime to a lower number. But as Gdx will most likely run 60fps setting it lower than 16 won't have an effect.
// time elapsed in the world in milliseconds
public long time = 0l;
// how long to wait between ticks, in milliseconds
public long ticktime = 50l;
// when did we last send a tick?
public long lastTick=0l;

   @Override
   public void render()
    {
    float delta = Gdx.graphics.getDeltaTime();
    // convert to milliseconds
    time+=(long)(delta*1000);
    // Simple substraction to see if enough time passed for a world update
    if(time - ticktime > lastTick) {
        GameWorld.tick();
        long elapsed = time - lastTick;
        if(elapsed > ticktime) {
            long missed = elapsed / ticktime;
            if(missed > 3l) {
               System.err.println("Warning: skipping "+missed+" ticks");
            }
        }
        lastTick = time - (time % ticktime);
    }
    WorlRenderer.render(delta);


text:
Q: How many temporary variables Frama-C WP plugin can handle? I was trying to generate weakest precondition of a particular program where there are total 44 temporary variables are present. Values of 2 temporary variables are assumed. All other variables are derived from these two variables. Also, there are 2 input variables. Here is a segment of my code.
void main(int err1_10, int err2_10){
    int x_mkfirm1,x_mkfirm2;
    int dist_00=0, dist_10=5, a00=0, a01=0, a10=-1, a11=0, b00=1,b10=0, u=2;
    int K_00=-1, K_01=1, x0_00=0,x0_10=3;
    int x1_00,x2_00,x3_00,....,x20_00;
    int x1_10,x2_10,x3_10,....,x20_10;
    x0_00=x0_00+dist_00;
    x0_10=x0_10+dist_10;
    u=-K_00*x0_00-K_01*x0_10;
    x1_00=a00*x0_00+a01*x0_10+u*b00;
    x1_10=a10*x0_00+a11*x0_10+u*b10;
    u=-K_00*x1_00-K_01*x1_10;
    ...........................
    ...........................
}

The generated weakest precondition comes in terms of x4_10 and so on. There is no mention of x1_00, x1_00 till x3's. Also the inputs are not present in the generated weakest precondition. The output message of frama-c wp shows   Alt-Ergo:0  (interruped: 1). Is there any restriction on number of variables?

A: WP tends to rename variables, thus it's normal that you don't see exactly the same names in the proof obligations than in the original C source. Moreover, from what I see from your code, many of your intermediate variables are in fact constant. This will normally be simplified away by WP before sending the proof obligation to theorem provers. You should just see the resulting value.
Regarding the fact that your proof obligation cannot be discharged by Alt-Ergo, it is basically impossible to answer without having the exact file. There are just too many possibilities, from an error in the spec or the code to having non-linear computations that are generally out of reach for automated theorem provers. Having many intermediate variables is unlikely to play a very important role here, though.


text:
Q: Error al iniciar Payara En netbeans 8.2 Tengo un problema con el servidor payara version 5.
LO descargue y lo agregue directamente desde agregar servidor pero lo inicio y me sale un erro que es este.
Error: no se ha encontrado o cargado la clase principal [9|]--add-
opens=java.rmi.sun.rmi.transport=ALL-UNNAMED
Intente desde los plugins de netbeans pero no me deja me sale que faltan varios plugins los cuales no encuentro.

A: Tengo el mismo inconveniente. He solucionado mediante el uso la ventana cmd de windows inicializando de forma manual utilizando los siguientes comandos
Luego con el localhost:8080 para abrir la consola de payara.


text:
Q: what to do when UX asks for an ugly, convoluted event driven design and you don't know how to implement it in a clean manner? I have been tasked with creating a desktop client application that fetches data from web apis and presents it to the user.
During the last month or so, I've spent most of my time and energy bringing to life the functionality that UX described with two pictures.
Looking at the pictures, it seems like a simple design. There are only 4 controls:
One drop down list that fires a selection event. Another drop down list that is populated based on selected data from the first drop down list and also fires a selection event. Two radio controls that enable or disable the second drop down list. A third drop down list that, depending on which radio button was last selected, is populated with data based on either the first drop down list or the second drop down list.
Doesn't seem hard.
But then when I actually start implementing this design I find that I don't know, for example, what to do with if the user selects radio button B (which is supposed to enable the second drop down list) but the drop down list has no elements; in that case, do I force the first radio button A to be reselected? Do I display an error message? Do I prompt the user for action?
It's these little 'corner' cases that don't necessarily jump at the people who request these designs that make me wonder if I'm in the wrong line of business or if I'm stuck working with people who don't have a clear picture of what they want or don't really know what they want but expect me to fill in the dots without actually doing the UX design myself.
UX is about enhancing the user's experience, not the programmer's experience, I get it, but is this the kind of input that programmers are typically expected to receive from UX? Are programmers always expected to fill in the dots, even when the proper behavior hasn't been explicitly stated?

A: In case of doubt, ask for clarification. Maybe the UX do not know that these "corner cases" are possible.
As for the example that you write, I do not think it so complicated as you paint it. Just from common sense, you have two options:

*

*If there are no items for the dropbox, disable option B. Add a tip (when hovering, or with an icon), stating that option B is disabled because of that.

*If there is something that forbids it (for example, finding out the list of items is expensive and you only want to retrieve them once "option B" is selected, so you don't know before of that if the list is empty), when "option B" is selected change the dropbown to a label that explains that to the user.
Of course, it will depend of how much freedom do you have to do your work. If you have no freedom at all, just do your work as stated and report back possible issues. If no answers come, just do exatly what was asked (of course, at the same time document everything to CYA).

A: You are experiencing a gap in the requirements (what to do when X goes wrong). This is not uncommon, because it is very hard to think of all possibilities up front.
What to do about it is quite simple: you ask the person responsible for the requirements/user stories/etc, to give you guidance on what the desired result should be from user perspective. Then you implement that.
If waiting for the response on your query would dangerously delay the project, then you should implement whatever is easiest to do for now and open an issue to create a proper implementation when the formal answer is known.

A: One of the things I do these days is that I explicitly request the UX designer sketches their designs in front of all of us on the fly. Actually that seems like common sense to me and the first UX Designer I worked with did that, even sketching out her designs over company meetings and we'd talk about it and ask questions like, "What should happen if the user does this?" and because she used very rapid mediums like pencil/pen on paper or marker on whiteboard, it was easy for her to draw out what should happen very quickly on the fly.
And that was such a smooth experience. I took it for granted and thought all UX design collaborations would work like this.
But I worked with two subsequent ones afterwords and one in particular made the most beautiful mockups in Photoshop that practically looked like a final product, except he'd spend a whole week working on it and then the company would pull him to further design our web page and we'd be stuck with basic questions like yours and also like, "Wait, how's the UI supposed to look if it's resized?" And he was too busy to answer them and we were in crunch and we'd just miserably connect all those dots (which is something you might have to do if the designer is not available) only for him to come out of the bunker and become upset that we filled in all these gaps.
As a result I've come to grow a strong distaste for such elaborate and pretty-looking mockups in the beginning, because they take too long for the designer to make and don't answer all those questions we might have. I actually prefer a designer just drawing rectangles and stuff on a whiteboard or notepad or even a paper napkin while we collaborate and work things out. That's very fast and he/she can draw his/her ideas on the fly to show us what should happen in every single case. That's the right way to do it now in my experience if you can find such a designer willing to rapidly sketch and then save the beauty mock-up for later.

Are programmers always expected to fill in the dots, even when the proper behavior hasn't been explicitly stated?

Unfortunately in my experience it usually is the case, but it wasn't with that first designer I mentioned. With her it was so clear what was supposed to happen with every use case, not because she anticipated them all (we did often make her pause sometimes to think about some use case we mentioned), but because she was able to so rapidly sketch things out and talk to us that she could illustrate her solutions to our questions on the fly. That was a proper collaboration, not like, "Here, I spent a week drawing this beautiful picture -- now go code it."


text:
Q: Exec() command in Linux does not perform any action from a PHP page I'm trying to run the following command from a PHP file in a web browser:
 exec('festival --tts /var/www/test.txt &');

Unfortunately, nothing happens.  I thought of trying 'echo' but there is nothing to return to see if the command is working.  I set permissions for test.txt to 777.  I also ran the command in a shell and it works just fine - just not when submitted by a PHP script.  What am I doing wrong?

A: Provide the full path to the festival binary, you can find it out on the console with which festival command, then use it in your exec call, like this:
exec('/usr/bin/festival --tts /var/www/test.txt &');

Update:
You need to make sure the folder where you are creating the file has write permission for the user running php which usually is www-data on debian based distros.

A: If I understand correctly what you're trying to do, you aren't returning the input. The syntax for this is:
exec('command', $output);

where $output is the variable in which the script's output will be stored. Oddly, this output will be returned as an array, so don't forget to implode() it when you're done if you're expecting a string.

A: Does the festival program print any output? If so, try capturing that. Also check the return value.
exec('/usr/bin/festival --tts /var/www/test.txt &', $output, $return);

Dump the output array, like so:
var_dump($output);

Any non-zero return value usually indicates an error:
echo $return;


text:
Q: SQL - If value exists in other table I have 2 tables:
Table A:           Value 1:           Value 2:
id (int)           1                  2
from (varchar)     josh               robert

Table B:           Value 1:           Value 2:
id (int)           1                  2
name (varchar)     josh               robert
surname (varchar)  apple              orange

And there is a keyword "apple". How to choose id from table A if some value from table B contains surname with keyword "apple". In this case result should be 1 (from table A) because josh has keyword apple.
That's what I did:
mysql_query("SELECT id FROM A WHERE from IN (SELECT name FROM B WHERE surname LIKE '%apple%')");`

but it doesn't work.

A: You can use JOIN, e.g.:
SELECT ta.id
FROM tableA ta JOIN tableB tb ON ta.`from` = b.name
WHERE tb.surname = 'apple';

A: from is a reserved keyword. Escape it:
select id
from A
where `from` in (
        select name
        from B
        where surname like '%apple%'
        )

You can also use join:
select a.id
from a
join b on a.`from` = b.name
where b.surname like '%apple%'


text:
Q: Flutter - How to run unit tests over a plugin native code for Android We are building a plugin for flutter that iterable.com here la-haus/iterable-flutter, and we want to test the android implementation of our plugin, we are already able to run tests for the flutter side but not each native implementation tests.
Folders and tests
So we have:

*

*lib/: library implementation, the interace that clients use.

*

*tests/: test for the flutter side of the library

*android/

*

*android/src/test: these are the tests we want to run

What we have tried

*

*Run flutter plugin tests, running flutter test at the root of the project, and it runs test/iterable_flutter_test.dart but not android ones.

*We have seen these docs flutter/wiki/Plugin-Tests, but I still don't figure out how to run them.
Question
How can I run Android implementation android/src/test tests?
Our current issue is https://github.com/la-haus/iterable-flutter/issues/22

A: We were asking us the same question and were surprised to not find any examples of running native tests with flutter - as described in https://github.com/flutter/flutter/wiki/Plugin-Tests (thanks for providing the link btw).
Solution with gradle (without flutter_plugin_tools)
Assumption: the plugin structure got scaffolded by the flutter create --template=plugin --platforms=android ... command.
To run the native tests, make sure that the local gradle property files ./example/android/local.properties and ./android/local.properties are created properly. This can be achieved by running flutter pub get or flutter test in the root directory of the plugin.
Then you're ready to run gradle --project-dir ./example/android test, which executes the test target for all subprojects from the plugin example (which includes the effective plugin code)
Here's an example of a (slightly stripped down) github actions workflow for testing a plugin (name: plgn1):
name: CI/CD, test code

on: [push]

jobs:
  plgn1-plugin:
    runs-on: ubuntu-latest
    defaults:
      run:
        working-directory: ./app/3rdparty/plgn1

    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-java@v2
        with:
          java-version: "11"
          distribution: "adopt"
          cache: 'gradle'
      - uses: subosito/flutter-action@v2
        with:
          flutter-version: "3.0.1"
          channel: "stable"
      - name: Config flutter
        run: flutter config --no-analytics

      - name: "Run flutter pub get"
        run: flutter pub get

      - name: "Run Flutter test(s)"
        run: flutter test

      - name: "Run Flutter test(s) for plugin example"
        run: flutter test
        working-directory: ./app/3rdparty/plgn1/example

      - name: "Run Android test(s) for plugin example"
        run: gradle --project-dir ./example/android --no-daemon test

Skipping flutter_plugin_tools (opinion, own experience)
The way how the plugin tests are described for native-tests sounded quite easy and feasible, but after playing 1h around I lost my patience (and I eventually got the feeling that it's not designed for a flutter plugin like ours).
I skipped eventually flutter_plugin_tools and went on with gradle directly. That's probably not the way how it should be run in the flutter ecosystem, but it's working for us.
Please let me know when you find an easier or more elegant way to run native tests of a flutter plugin!


text:
Q: gvim :make command does not work I am under a Unix environment, working in C++.
I'm opening gvim from a directory in which a makefile called "Makefile" exists. When I try to use ":make" from within vim, I get:
shell returned 2
(1 of 1): make: *** No targets specified and no makefile found.  Stop.

A: Do you have autochdir enabled? That may change to another directory.
Check with :pwd to see if the current directory is what you expect.
Try running :!ls to see if the Makefile exists.

A: Can you check the following options?
:set shell?
:set shelltype?

Finally, check the contents of your shell login file.  For example, if your shell is bash, check ~/.bashrc.  Does this file contain something like the following?
cd ~

Or:
cd /home/${USERNAME}

where ${USERNAME} is (obviously) your username.

A: G'day,
Obvious question, does the Makefile in the current directory work when you enter make on the command line?
Trying to seperate out the make in gvim land from the make env. on the command line.
Also, has makeprg been set to something unexpected? What do you get when you enter:
:set makeprg?

BTW The trailing question mark is necessary.
Edit:

*

*Do you get different behaviour if you enter:
:cd the/dir/i/need/to be/in
and then enter
:make

*

*Is gvim aliased to anything?

HTH
cheers,


text:
Q: Which values of $\alpha$ make this integral convergent? I'm facing problems figuring out which values of $\alpha$ makes
$$
\int_{1}^{\infty}\left(\sum_{j = 1}^{10}x^{j}\right)
^{-\left(n +1\right)/10}\,\frac{-n + 1}{10}\,x^{\alpha}\,\mathrm{d}x
$$
convergent. The problem also states that $n>0$ and $\alpha$ is a real number.
I tried substituting the summation with the geometric series formula but I cannot figure out how to deal with the $n$.

A: The power of $x$ in each part of the integral must be less than $-1$ for the integral to converge. The powers are $$j\frac{-n+1}{10}+\alpha$$ for $j$ from $1$ to $10$
When $\frac{-n+1}{10}$ is positive, the power will be greatest at $j=10$, therefore $$-n+1+\alpha<-1$$$$\alpha<n-2$$
When $\frac{-n+1}{10}$ is negative, the power will be greatest at $j=1$, therefore $$\frac{-n+1}{10}+\alpha<-1$$$$\alpha<\frac{n-11}{10}$$


text:
Q: Spark convert milliseconds to UTC datetime I've got a dataset where 1 column is a long that represents milliseconds. I want to obtain the timestamp (yyyy-MM-dd HH:mm:ss) that this number represents in UTC. Basically I want the same behaviour as https://currentmillis.com/

My question is, is there a way to have Spark code convert a milliseconds long field to a timestamp in UTC? All I've been able to get with native Spark code is the conversion of that long to my local time (EST):
from pyspark import SparkContext
from pyspark.sql import SQLContext
from pyspark.sql import types as T
from pyspark.sql import functions as F

sc = SparkContext()
spark = SQLContext(sc)

df = spark.read.json(sc.parallelize([{'millis':1582749601000}]))

df.withColumn('as_date', F.from_unixtime((F.col('millis')/1000))).show()

+-------------+-------------------+
|       millis|            as_date|
+-------------+-------------------+
|1582749601000|2020-02-26 15:40:01|
+-------------+-------------------+

I've been able to convert to UTC by forcing the timezone of the whole Spark session. I'd like to avoid this though, because it feels wrong to have to change the whole Spark session timezone for a specific use case within that job.
spark.sparkSession.builder.master('local[1]').config("spark.sql.session.timeZone", "UTC").getOrCreate()

I would also like to avoid custom defined functions as I want to be able to deploy this in Scala and Python, without writing language-specific code in each.

A: Use to_utc_timestamp to specify your timezone(EST).
    from pyspark.sql import functions as F
    df.withColumn("as_date", F.to_utc_timestamp(F.from_unixtime(F.col("millis")/1000,'yyyy-MM-dd HH:mm:ss'),'EST')).show()

    +-------------+-------------------+
    |       millis|            as_date|
    +-------------+-------------------+
    |1582749601000|2020-02-26 20:40:01|
    +-------------+-------------------+


text:
Q: Laravel 4 - retry all failed jobs In the laravel 4.2 docs it is said that if I want to retry failed job from the failed jobs table I should do:
php artisan queue:retry 5

where 5 is the job id.
How can I retry all failed jobs at once?

A: I couldn't find an answer to this (I don't think laravel provides this by default) so I wrote a bash script to retry all the jobs I needed:
#!/bin/bash
for i in {53..800}
do
   php artisan queue:retry $i
done

A: One way to do this via artisan is to specify a range. Even if not every ID in the range exists, artisan will still fire all of the failed jobs, skipping over the ones it can't find. For example, if you have a bunch of jobs sparsely populated between IDs 200 and 510 you can do:
php artisan queue:retry  --range 200-510

A: You can retry all failed Jobs by running: php artisan queue:retry all.
here is official doc: https://laravel.com/docs/7.x/queues#retrying-failed-jobs

A: Laravel docs says:

To retry all of your failed jobs, use queue:retry with all as the ID:
php artisan queue:retry all

However this doesn't work for me. I get "No failed job matches the given ID.".
What I did was I ran a command allowing me to execute php:
php artisan tinker

And wrote this:
for ($i = 100; $i <= 150; $i ++) Artisan::call('queue:retry', ['id' => $i]);

Here 100 and 150 are your failed job IDs range. I used to retreive them from DB dynamically but that won't work if you use another queue driver.
What this does is it loops through the IDs in the range you specified and calls a "php artisan queue:retry XXX" command for every single one of them.

A: I've created a command to execute this operation:
https://gist.github.com/vitorbari/0ed093cf336278311ec070ab22b3ec3d

A: You can use :

To retry all of your failed jobs, execute the queue:retry command and pass all as the ID:

php artisan queue:retry all

Source : https://laravel.com/docs/9.x/queues#retrying-failed-jobs
Check the result via :
php artisan queue:failed
> No failed jobs!

Important Note : If you don't have workers, remember to run the queue as this command will only push these fail jobs back to the queue and WILL NOT execute them. (Which makes sense, if you think about it.)

A: Try using the command  below in your CLI :
"php artisan queue:retry"
This command will push all failed queues back to the job table and rerun it again by typing;
"php artisan queue:work"


text:
Q: inotify seems to add a 6 letter code to filenames in its output, before the extension inotify seems to add a 6 letter code to filenames in its output, before the extension.
For example:
"/path/to/directory/ CLOSE_WRITE,CLOSE filename-HzdVai.lyx"
or with --format "%w%f":
/path/to/directory/filename-HzdVai.lyx
This didn't happen with other scripts and I couldn't find any example of this or why this would happen with googling.
code:
inotifywait -m -r -e close_write --exclude '[^l][^y][^x]$' ~/Routines/* ~/Projects/* | while read path msg name
do
    echo "$path $msg $name"
    lyx -e pdf "$path$name.lyx"
done

If it's relevant, I am using Ubuntu 20.4.

A: The intention of the script was to continuously update LyX documents matching pdf files (LyX is a LaTeX-based document processor) so whenever I saved a document it would be compiled automatically
@larks had guessed correctly and tracking move events as well showed that LyX just wrote to the file with the id temporarily, then renamed it.
The final, working, script:
#!/usr/bin/env sh

inotifywait -m -r -e moved_to --exclude '[^l][^y][^x]$' --format "%w%f" ~/Routines/* ~/Projects/* | while read file_path
do
    echo "$file_path"
    lyx -e pdf "$file_path"
done


text:
Q: How does one check for null or an empty result set with MySQL C++ connector? In the following code, the intention is to check for null,but the code keeps throwing exception.
 pstmt = con->prepareStatement("SELECT id FROM test ORDER BY id ASC");
 res = pstmt->executeQuery();
 res->next();
 if(res->isNull(1))
 {
     cout << " In null";
 }
 else
 {
     cout << " Is not Null";
 }

How does one check for null or an empty result set?

A: This is an example of how to fetch data from the database:
sql::Connection *con;
sql::Statement *stmt;
sql::ResultSet  *res;
// ...
stmt = con->createStatement();
// ...

res = stmt->executeQuery("SELECT id, label FROM test ORDER BY id ASC");
while (res->next()) {
  // You can use either numeric offsets...
  cout << "id = " << res->getInt(1); // getInt(1) returns the first column
  // ... or column names for accessing results.
  // The latter is recommended.
  cout << ", label = '" << res->getString("label") << "'" << endl;
}

delete res;
delete stmt;
delete con;

The API for fetching result sets is identical for (simple) statements
  and prepared statements. If your query returns one result set, use
  sql::Statement::executeQuery() or
  sql::PreparedStatement::executeQuery() to run your query. Both methods
  return sql::ResultSet objects. The preview version does buffer all
  result sets on the client to support cursors.

Read more mysql reference
In other words, use either the next() function or previous() function in the sql::ResultSet which is returned by executeQuery().


text:
Q: Cannot run 'uuid-ossp' functions even when it's activated I want to generate a v4 uuid in PostgreSQL using the extension uuid-ossp, so in psql I ran:
CREATE EXTENSION "uuid-ossp";

Then I ran SELECT uuid_generate_v1(); or SELECT uuid_generate_v4(); but I always get this error:
ERROR:  function uuid_generate_v1() does not exist
LINE 1: select uuid_generate_v1();
               ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

So how can I solve this error?

A: There are several possibilities:

*

*you ran CREATE EXTENSION in a different database (postgres?)

*you installed the extension in a schema that is not on the user's search_path.
Use
\dx "uuid-ossp"

in psql to see where the extension is installed.


text:
Q: How can i make "s.Id" and "ascending" in the Linq statement dynamic? How can i make "s.Id" and "ascending" in the Linq statement dynamic?
var orderedList = from s in this.myList orderby s.Id ascending select s;
thanks

A: var param = "Id";
var direction = "asc";

var propertyInfo = myList[0].GetType().GetProperty(param);
var orderById = myList.Select(x => new { item = x, sort = propertyInfo.GetValue(x) })
        .OrderBy(x => direction == "asc" ? x.sort : 0)
        .OrderByDescending(x => direction == "desc" ? x.sort : 0)
        .Select(x => x.item)
        .ToList();

A: You can do this
var param = "Id";
var propertyInfo = typeof(yourObject).GetProperty(param);
var orderById = this.myList.OrderBy(x => propertyInfo.GetValue(x, null));


text:
Q: python requests library not getting the HTML from playstore website? I am trying to access the HTML content from the playstore using the requests library of python. But due to its AJAX calls I am not able to get the correct content. Anyone please help me out on this.

A: This is an extremely common question. You can't work with pages that use AJAX using just requests - you need to use Selenium. Good Luck!
https://selenium-python.readthedocs.io/getting-started.html


text:
Q: QueryDSL usage with different relational databases I have an application which may work with different type of databases(relational dbs). Now it uses hibernate to connect and work with them and for different databases we must use different drivers and write code for each db.
Is it possible with QueryDSL to write unique code for multiple relational databases(all of them have same schemas, tables and field names)? Or any suggestions in order to make my code independent of database type? Any analogues of QueryDSL?
And can I find good tutorials on QueryDSL theme?


text:
Q: Pass All Forms in Project To a Function I want to let a user select a color scheme and have all my forms change to that color.  so I wanted to do something like this:
                  foreach (Form frm in OwnedForms)
        {
            BaseFunctions.ChangeColorScheme(frm);
        }

inside that function, i go through each control.  owned forms and Application.OpenForms were two things that other people said to try, but neither worked.  so im not sure what to do.  i tried to use my namespace, but perhaps im missing something.  I went with Namespace.Forms  but Forms isnt an option

A: Use a configuration file for this task. http://msdn.microsoft.com/en-us/library/system.configuration.configuration.aspx


text:
Q: How do I protect my github website repository from being copied? I built a website on github and would like to protect it from someone copying my repository and running the same website (either online or offline for themselves).
The website is fairly basic and builds on github action, which excute on schedule a Rmarkdown file that produces (updates) the index.html file. I want to avoid people being able to copy and freely execute that Rmarkdown file. I wonder if I could encrypt that specific file, and simply use a secret key with github actions to decrypt it when updating the website. Is this possible and would it be a good solution?
I also thought about having a private repository with my Rmarkdown file and simply push the html file to the public repository via github action, the problem is the github action takes a while to execute and I would quickly run out of the computation time (2000-3000 mins/month) offered by github.

A:
I also thought about having a private repository with my Rmarkdown file and simply push the html file to the public repository via github action

That would have been the first approach, but since the RMarkdown process consumes to much tasks, it needs to be executed elsewhere.
Since other online free plans (like RStudio Cloud) are also limited in their project hours per month, another approach would be to call your own managed server (for instance, a Google Cloud compute engine, or Digital Ocean Droplet) where:

*

*the RMarkdown file would reside (meaning, it would not be in the GitHub repository at all: no need to obfuscate/encrypt anything)

*the process can take place

*the generated index.html can uploaded back to your repository, and the rest of your GitHub action can publish the pages.


text:
Q: Removing files in directory with special characters I tried removing files in directory with special characters using php.
I used the unlink() function and it worked as it is, but when the file contains special chars, it can't locate the file.
Now I use str_replace() function to replace the name.
See example below.
<?php
   //replace "+" sign with space.
   $filename = str_replace("+", " ", $filename);

   $dir = "_resources/docs/";
   unlink($dir . $filename);
?>

It works but how about files with a name like this?
[Vouching_Sample_02]-SMCC_Q3_Vouching_September_Goods_012216.
Is there any good recommendations for this?

A: Try to use this kind of solution.
$name = "This-is_a__test--(name)";
$find = array("-", "_", "--", "(", ")");
$replace = array(" ", " ", " ", " ", " ");
$converted = str_replace($find, $replace, $name);

echo $converted;

Out put: This is a test name
Include what you want to search in fine array.
Include what you want to replace with in replace array.
Else use preg_replace() with regular expression


text:
Q: Issues with calculating gradient descent operation I have this issue when using gradient ascent. I have some synthetic data and after my first iteration the objective function decreases and from the second iteration it keeps on increasing. Is it possible for a convex function. I also have the learning rate very low 0.001. Any suggestions.

A: Sounds like something is probably wrong in your code or you have your step size (learning rate) set too large. If you coded it properly, the objective function at iteration t+1 should always be lower than at iteration t. This feature is what makes it an "ascent" algorithm. We might be able to give you more insight if you provide your code and, better yet, a reproducible example.


text:
Q: Angular: AgGrid will not update rows when subscribing to Observable I am trying to incorporate rxjs and observables into ag grid. For practice, I am following an official ag grid example: https://www.ag-grid.com/javascript-grid-rxjs/
I am currently using Angular 6. I changed the js file to be a ts file and made the appropriate changes. I also do not include any scripts in my index file. I was getting a bunch of MIME errors anytime I called a script. So I converted to code to strictly angular. I believe this is what is causing my issue.
My goal is to have random rows change their values without having to refresh the web page when I subscribe to my updates observable
In the code below you will see there is basically an interval function that chooses random numbers to be displayed. When I run my code, All the data is loaded into my grid, but it does not refresh or update. I subscribe to the updates$ observable to output the updated data, but nothing happens. Here is the code. The onGridReady function is subscribing to the observable.
Component.ts
import { Component, OnInit } from '@angular/core';
import {Model} from '../app/model';
import {Observable} from 'rxjs';
import { HttpClient } from '@angular/common/http';
import {MockServer} from '../app/mockServer'

@Component({
    selector: 'app-root',
    template:
    `<ag-grid-angular
    #agGrid
    style="width: 1000px; height: 1500px;"
    id="myGrid"
    [rowData]="rowData"
    class="ag-theme-balham"
    [columnDefs]="columnDefs"
    [enableRangeSelection]="true"
    [enableColResize]="true"
    [deltaRowDataMode]="true"
    [getRowNodeId]="getRowNodeId"
    (gridReady)="onGridReady($event)"
    ></ag-grid-angular>
` ,
   styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{

  private gridApi;
  private gridColumnApi;
  private rowData: any[];

  private columnDefs;
  private getRowNodeId;

    constructor() {
      this.columnDefs = [
        {
          headerName: "Code",
          field: "code",
          width: 70
        },
        {
          headerName: "Name",
          field: "name",
          width: 300
        },
        {
          headerName: "Bid",
          field: "bid",
          width: 100,
          cellClass: "cell-number",
          valueFormatter: numberFormatter,
          cellRenderer: "agAnimateShowChangeCellRenderer"
        },
        {
          headerName: "Mid",
          field: "mid",
          width: 100,
          cellClass: "cell-number",
          valueFormatter: numberFormatter,
          cellRenderer: "agAnimateShowChangeCellRenderer"
        },
        {
          headerName: "Ask",
          field: "ask",
          width: 100,
          cellClass: "cell-number",
          valueFormatter: numberFormatter,
          cellRenderer: "agAnimateShowChangeCellRenderer"
        },
        {
          headerName: "Volume",
          field: "volume",
          width: 80,
          cellClass: "cell-number",
          cellRenderer: "agAnimateSlideCellRenderer"
        }
      ];
      this.getRowNodeId = data => data.code;
    }

ngOnInit() {

}

onGridReady(params) {
  this.gridApi = params.api;
  this.gridColumnApi = params.columnApi;

  let mockServer = new MockServer();
  const initialLoad$ = mockServer.initialLoad();
  const updates$ = mockServer.allDataUpdates();
  initialLoad$.subscribe(rowData => {
    params.api.setRowData(rowData);
    updates$.subscribe(newRowData => params.api.setRowData(newRowData));

  });

}

}

function numberFormatter(params) {
  if (typeof params.value === "number") {
    return params.value.toFixed(2);
  } else {
    return params.value;
  }
}

Here is the server class. This contains the functions that manipulate the data. For brevity, I am only including the methods that are not working correctly. byRowupdates is what is not working properly
byRowupdates() {
        return Observable.create((observer) => {
            const interval = setInterval(() => {
                let changes = [];
                // make some mock changes to the data
                this.makeSomePriceChanges(changes);
                this.makeSomeVolumeChanges(changes);
               // observer.next(changes);
            }, 1000);
            return () => clearInterval(interval);
        });
    }
    // provides randomised data updates to some of the rows
    // only all the row data (with some rows changed)
    allDataUpdates() {
        return Observable.create((observer) => {
            const interval = setInterval(() => {
                let changes = [];
                // make some mock changes to the data
                this.makeSomePriceChanges(changes);
                this.makeSomeVolumeChanges(changes);
                // this time we don't care about the delta changes only
                // this time we return the full data set which has changed rows within it
                //observer.next(_.cloneDeep(this.rowData));
            }, 1000);

            return () => clearInterval(interval);

        });
    }
    /*
     * The rest of the code exists to create or modify mock data
     * it is not important to understand the rest of the example (i.e. the rxjs part of it)
     */
    backfillData(rowData) {
        // the sample data has just name and code, we need to add in dummy figures
        rowData.forEach((dataItem) => {
            // have volume a random between 100 and 10,000
            dataItem.volume = Math.floor((Math.random() * 10000) + 100);
            // have mid random from 20 to 300
            dataItem.mid = (Math.random() * 300) + 20;
            this.setBidAndAsk(dataItem);
        });
        return rowData;
    }
    makeSomeVolumeChanges(changes) {
        for (let i = 0; i < 10; i++) {
            // pick a data item at random
            const index = Math.floor(this.rowData.length * Math.random());
            const currentRowData = this.rowData[index];
            // change by a value between -5 and 5
            const move = (Math.floor(10 * Math.random())) - 5;
            const newValue = currentRowData.volume + move;
            currentRowData.volume = newValue;
            changes.push(currentRowData);
        }
    }
    makeSomePriceChanges(changes) {
        // randomly update data for some rows
        for (let i = 0; i < 10; i++) {
            const index = Math.floor(this.rowData.length * Math.random());
            const currentRowData = this.rowData[index];
            // change by a value between -1 and 2 with one decimal place
            const move = (Math.floor(30 * Math.random())) / 10 - 1;
            const newValue = currentRowData.mid + move;
            currentRowData.mid = newValue;
            this.setBidAndAsk(currentRowData);
            changes.push(currentRowData);
        }
    }
    setBidAndAsk(dataItem) {
        dataItem.bid = dataItem.mid * 0.98;
        dataItem.ask = dataItem.mid * 1.02;
    }
}

My grid is successfully retrieving the data when it is created, but the grid is not updating new values. I do not have any scripts in my index file. These two classes are doing all the work. I am very confused on how to implement this example properly. Thank you!

A: You are expecting data-binding for grid-data, but it doesn't work like that.
For updating existing data you need to call
rowNode.setData(data)

Replaces the data on the rowNode. When complete, the grid will refresh the the entire rendered row if it is showing.

or
rowNode.setDataValue(colKey, value)

Replaces the data on the rowNode for the specified column. When complete, the grid will refresh the rendered cell on the required row only.

Check doc for more details
*JFI changes through data-binding possible but you would require to make it via node and manipulate with node.data but I'm not recommending using this type of data-update.