text:
Q: Allow setuid on shell scripts The setuid permission bit tells Linux to run a program with the effective user id of the owner instead of the executor:
> cat setuid-test.c

#include <stdio.h>
#include <unistd.h>

int main(int argc, char** argv) {
    printf("%d", geteuid());
    return 0;
}

> gcc -o setuid-test setuid-test.c
> ./setuid-test

1000

> sudo chown nobody ./setuid-test; sudo chmod +s ./setuid-test
> ./setuid-test

65534

However, this only applies to executables; shell scripts ignore the setuid bit:
> cat setuid-test2

#!/bin/bash
id -u

> ./setuid-test2

1000

> sudo chown nobody ./setuid-test2; sudo chmod +s ./setuid-test2
> ./setuid-test2

1000

Wikipedia says:

Due to the increased likelihood of security flaws, many operating systems ignore the setuid attribute when applied to executable shell scripts.

Assuming I'm willing to accept those risks, is there any way to tell Linux to treat the setuid bit the same on shell scripts as it does on executables?
If not, is there a common workaround for this problem? My current solution is to add a sudoers entry to allow ALL to run a given script as the user I want it run as, with NOPASSWD to avoid the password prompt. The main downsides to that is the need for a sudoers entry every time I want to do this, and the need for the caller to sudo some-script instead of just some-script

A: super [ -r reqpath] command [ args ]
Super allows specified users to execute scripts (or other commands) as if they were root; or it can set the  uid,  gid,  and/or  supplementary groups  on  a  per-command  basis  before executing the command.  It is intended to be a secure alternative  to  making  scripts  setuid  root. Super  also  allows  ordinary users to supply commands for execution by others; these execute with  the  uid,  gid,  and  groups  of  the  user offering the command.
Super  consults  a  ``super.tab'' file to see if the user is allowed to execute the requested command.  If permission is  granted,  super  will exec  pgm [ args ],  where  pgm  is the program that is associated with this command.  (Root is allowed execution by default, but can still  be denied  if  a  rule  excludes root. Ordinary  users  are  disallowed execution by default.)
If command is a symbolic link (or hard link, too) to the super program,
then typing % command args is equivalent to typing % super command args (The command must not be super, or super will not recognize  that  it's being invoked via a link.)
http://www.ucolick.org/~will/RUE/super/README
http://manpages.ubuntu.com/manpages/utopic/en/man1/super.1.html

A: If for some reason sudo is not available, you can write a thin wrapper script in C:
#include <unistd.h>
int main() {
    setuid(0);
    execle("/bin/bash","bash","/full/path/to/script",(char*) NULL,(char*) NULL);
}

And once you compile it set it as setuid with chmod 4511 wrapper_script.
This is similar to another posted answer, but runs the script with a clean environment and explicitly uses /bin/bash instead of the shell called by system(), and so closes some potential security holes.
Note that this discards the environment entirely. If you want to use some environmental variables without opening up vulnerabilities, you really just need to use sudo.
Obviously, you want to make sure the script itself is only writable by root.

A: One way of solving this problem is to call the shell script from a program that can use the setuid bit.
its something like sudo.
For example, here is how you would accomplish this in a C program:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
    setuid( 0 );   // you can set it at run time also
    system( "/home/pubuntu/setuid-test2.sh" );
    return 0;
 }

Save it as setuid-test2.c.
compile
Now do the setuid on this program binary:
su - nobody
[enter password]
chown nobody:nobody a.out
chmod 4755 a.out

Now, you should be able to run it, and you'll see your script being executed with nobody permissions.
But here also either you need to hardcode the script path or pass it as command line arg to above exe.

A: You can create an alias for sudo + the name of the script. Of course, that is even more work to set up, since you then have to setup an alias, too, but it saves you from having to type sudo.
But if you don't mind horrible security risks, use a setuid shell as the interpreter for the shell script. Don't know whether that'll work for you, but I guess it might.
Let me state that I advise against actually doing this, though. I'm just mentioning it for educational purposes ;-)

A: I prefix a few scripts that are in this boat thus:
#!/bin/sh
[ "root" != "$USER" ] && exec sudo $0 "$@"

Note that this does not use setuid but simply executes the current file with sudo.

A: Linux ignores the setuid¹ bit on all interpreted executables (i.e. executables starting with a #! line). The comp.unix.questions FAQ explains the security problems with setuid shell scripts. These problems are of two kinds: shebang-related and shell-related; I go into more details below.
If you don't care about security and want to allow setuid scripts, under Linux, you'll need to patch the kernel. As of 3.x kernels, I think you need to add a call to install_exec_creds in the load_script function, before the call to open_exec, but I haven't tested.

Setuid shebang
There is a race condition inherent to the way shebang (#!) is typically implemented:

*

*The kernel opens the executable, and finds that it starts with #!.

*The kernel closes the executable and opens the interpreter instead.

*The kernel inserts the path to the script to the argument list (as argv[1]), and executes the interpreter.

If setuid scripts are allowed with this implementation, an attacker can invoke an arbitrary script by creating a symbolic link to an existing setuid script, executing it, and arranging to change the link after the kernel has performed step 1 and before the interpreter gets around to opening its first argument. For this reason, most unices ignore the setuid bit when they detect a shebang.
One way to secure this implementation would be for the kernel to lock the script file until the interpreter has opened it (note that this must prevent not only unlinking or overwriting the file, but also renaming any directory in the path). But unix systems tend to shy away from mandatory locks, and symbolic links would make a correct lock feature especially difficult and invasive. I don't think anyone does it this way.
A few unix systems (mainly OpenBSD, NetBSD and Mac OS X, all of which require a kernel setting to be enabled) implement secure setuid shebang using an additional feature: the path /dev/fd/N refers to the file already opened on file descriptor N (so opening /dev/fd/N is roughly equivalent to dup(N)). Many unix systems (including Linux) have /dev/fd but not setuid scripts.

*

*The kernel opens the executable, and finds that it starts with #!. Let's say the file descriptor for the executable is 3.

*The kernel opens the interpreter.

*The kernel inserts /dev/fd/3 the argument list (as argv[1]), and executes the interpreter.

Sven Mascheck's shebang page has a lot of information on shebang across unices, including setuid support.

Setuid interpreters
Let's assume you've managed to make your program run as root, either because your OS supports setuid shebang or because you've used a native binary wrapper (such as sudo). Have you opened a security hole? Maybe. The issue here is not about interpreted vs compiled programs. The issue is whether your runtime system behaves safely if executed with privileges.

*

*Any dynamically linked native binary executable is in a way interpreted by the dynamic loader (e.g. /lib/ld.so), which loads the dynamic libraries required by the program. On many unices, you can configure the search path for dynamic libraries through the environment (LD_LIBRARY_PATH is a common name for the environment variable), and even load additional libraries into all executed binaries (LD_PRELOAD). The invoker of the program can execute arbitrary code in that program's context by placing a specially-crafted libc.so in $LD_LIBRARY_PATH (amongst other tactics). All sane systems ignore the LD_* variables in setuid executables.

*In shells such as sh, csh and derivatives, environment variables automatically become shell parameters. Through parameters such as PATH, IFS, and many more, the invoker of the script has many opportunities to execute arbitrary code in the shell scripts's context. Some shells set these variables to sane defaults if they detect that the script has been invoked with privileges, but I don't know that there is any particular implementation that I would trust.

*Most runtime environments (whether native, bytecode or interpreted) have similar features. Few take special precautions in setuid executables, though the ones that run native code often don't do anything fancier than dynamic linking (which does take precautions).

*Perl is a notable exception. It explicitly supports setuid scripts in a secure way. In fact, your script can run setuid even if your OS ignored the setuid bit on scripts. This is because perl ships with a setuid root helper that performs the necessary checks and reinvokes the interpreter on the desired scripts with the desired privileges. This is explained in the perlsec manual. It used to be that setuid perl scripts needed #!/usr/bin/suidperl -wT instead of #!/usr/bin/perl -wT, but on most modern systems, #!/usr/bin/perl -wT is sufficient.
Note that using a native binary wrapper does nothing in itself to prevent these problems. In fact, it can make the situation worse, because it might prevent your runtime environment from detecting that it is invoked with privileges and bypassing its runtime configurability.
A native binary wrapper can make a shell script safe if the wrapper sanitizes the environment. The script must take care not to make too many assumptions (e.g. about the current directory) but this goes. You can use sudo for this provided that it's set up to sanitize the environment. Blacklisting variables is error-prone, so always whitelist. With sudo, make sure that the env_reset option is turned on, that setenv is off, and that env_file and env_keep only contain innocuous variables.

TL,DR:

*

*Setuid shebang is insecure but usually ignored.

*If you run a program with privileges (either through sudo or setuid), write native code or perl, or start the program with a wrapper that sanitizes the environment (such as sudo with the env_reset option).

¹ This discussion applies equally if you substitute "setgid" for "setuid"; they are both ignored by the Linux kernel on scripts

A: You can compile the script with a newer version of shc with the -S argument (enable SETUID) set.
shc -S -f your-script.sh
chmod u+s your-script.sh.x

your-script.sh.x would be the executable that can be used by a regular user.

A: If you want to avoid calling sudo some_script you can just do:
  #!/usr/bin/env sh

  sudo /usr/local/scripts/your_script

SETUID programs need to be designed with extreme care as they run with root privileges and users have large control over them. They need to sanity-check everything. You cannot do it with scripts because:

*

*Shells are large pieces of software which interact heavily with user. It is nearly impossible to sanity check everything — especially since most of the code is not intended to run in such mode.

*Scripts are a mostly quick'n'dirty solution and usually are not prepared with such care that they would allow setuid. They have many potentially dangerous features.

*They depend heavily on other programs. It is not sufficient that the shell was checked. sed, awk, etc. would need to be checked as well

Please note that sudo provides some sanity-checking but it isn't sufficient — check every line in your own code.
As a last note: consider using capabilities. They allow you to give a process running as a user special privileges that would normally require root privileges. However for example, while ping needs to manipulate the network, it does not need to have access to files. Capabilities can optionally be inherited to sub-processes.

A: First, a disclaimer: the OP said "Assuming I'm willing to accept those risks, ...".  I found myself in a similar situation where I had some one-off tasks where I was not concerned with security risks, because it was a short-term situation...  Before you haters downvote, this is what the OP wanted...
So all my solution is is an extension of what Hemant came up with above.  The only difference from his solution is a bit of automation so that you can both hard-code a specific executable you want to launch, but with a one-liner that's sort of like a combination of ln and setuid (e.g. chmod 6755).
Some would say it's overkill for something that you "ought not do in the first place" -- but again, that's what the OP wanted...  About half the code could be deleted if you don't care about debugging options; I wanted the ability to turn on xtrace, and some of the debug features were just to help me develop it...
And to repeat, if it wasn't clear already: just plain sudo is a better option in nearly every case, except for sheer trade-off between laziness and speed...  (I agree with most of the other posts)
Here is the code:
cat > makeSetUIDExecutable <<\ENDSCRIPT
#!/bin/bash

usage() { echo "Usage: $0 -c <command> -o <output> [-u <user>] [-v (verbose)] [-x (xtrace)] [-X (xtrace inherit)]" 1>&2; exit 1; }

PrintArray() {
    local -n arr=$1
    echo -n "$1: "
    for elem in "${!arr[@]}"; do
        echo -n "[${elem@Q}]=${arr[$elem]@Q}, "
    done | sed 's/, $//'; echo
}

PrintVariable() {
    echo "$1: ${!1}"
}

unset makeSetUIDExecutableOpts quotedCommand
declare -A makeSetUIDExecutableOpts

OPTIND=1
while getopts ":c:o:u:vxX" makeSetUIDExecutableOpt; do
    # echo -e "\nProcessing argument...\nmakeSetUIDExecutableOpt = ${makeSetUIDExecutableOpt}\nOPTARG = ${OPTARG}"
    [[ "${makeSetUIDExecutableOpt}" == ":" ]] && usage
    makeSetUIDExecutableOpts["${makeSetUIDExecutableOpt}"]="${OPTARG}"
done

[[ -z "${makeSetUIDExecutableOpts[c]}" ]] || [[ -z "${makeSetUIDExecutableOpts[o]}" ]] && usage

[[ "${makeSetUIDExecutableOpts[x]+-}" ]] &&  {
    set -x
    trap "set +x" EXIT
}

makeSetUIDExecutableOpts[u]="${makeSetUIDExecutableOpts[u]:-root}"
userID=$(id -u "${makeSetUIDExecutableOpts[u]}")

[[ "${makeSetUIDExecutableOpts[X]+-}" ]] &&  quotedCommand="set -x; "
quotedCommand+="${makeSetUIDExecutableOpts[c]//\\\"/\\\\\"}"
quotedCommand="\"${quotedCommand//\"/\\\"}\""

[[ "${makeSetUIDExecutableOpts[v]+-}" ]] &&  {
    echo -e "\nSummary -- Arguments provided:\n"
    PrintArray makeSetUIDExecutableOpts
    echo
    PrintVariable quotedCommand
    echo
}

cat > "${makeSetUIDExecutableOpts[o]}.c" <<ENDSUBSCRIPT
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>

int main()
{

    if( setuid( ${userID} ) ) {
        printf("setuid failed, errno = %i\n", errno);
    }
    system( ${quotedCommand} );
    return 0;
 }

ENDSUBSCRIPT

cc "${makeSetUIDExecutableOpts[o]}.c" -o "${makeSetUIDExecutableOpts[o]}"

sudo chown "${makeSetUIDExecutableOpts[u]}" "${makeSetUIDExecutableOpts[o]}"
sudo chmod 6755 "${makeSetUIDExecutableOpts[o]}"

ENDSCRIPT

Example usage - a rather large command, to prove three-ways that all the user info is as-expected...  Your command can be one word or ten lines...:
printUidGidInfo='set -- $(cat /proc/self/status | grep -P -o "(?<=Uid:|Gid:).*$"); unset outputString; i=1; while [ ${i} -le 4 ]; do outputString=${outputString}"\n"$(id -nu ${1}); shift; i=$(( i + 1 )); done; while [ ${i} -le 8 ]; do temp=$(getent group ${1}); outputString=${outputString}"\n"${temp%%:*}; shift; i=$(( i + 1 )); done; printf "\nReal UID: %s\nEffective UID: %s\nSaved set UID: %s\nFilesystem UID: %s\nReal GID: %s\nEffective GID: %s\nSaved set GID: %s\nFilesystem UID: %s\n\n" ${outputString}'

./makeSetUIDExecutable -c 'echo; echo "id -u -n:"; id -u -n; echo; echo stat -c "User: %U, Group: %G" /proc/$$/; stat -c "User: %U, Group: %G" /proc/$$/; echo; echo "/proc/self/status"; '"${printUidGidInfo}" -o proveUserInfo -v

./proveUserInfo

Output:
id -u -n:
root

stat -c User: %U, Group: %G /proc/10977/
User: root, Group: users

/proc/self/status

Real UID: root
Effective UID: root
Saved set UID: root
Filesystem UID: root
Real GID: users
Effective GID: users
Saved set GID: users
Filesystem UID: users

A: I first found this question, unconvinced by all the answers, here is a much better one, which also allows you to completely obfuscate your bash script, if you are so inclined!
It should be self-explanatory.
#include <string>
#include <unistd.h>

template <typename T, typename U>
T &replace (
          T &str,
    const U &from,
    const U &to)
{
    size_t pos;
    size_t offset = 0;
    const size_t increment = to.size();

    while ((pos = str.find(from, offset)) != T::npos)
    {
        str.replace(pos, from.size(), to);
        offset = pos + increment;
    }

    return str;
}

int main(int argc, char* argv[])
{
    // Set UUID to root
    setuid(0);

    std::string script =
R"(#!/bin/bash
whoami
echo $1
)";

    // Escape single quotes.
    replace(script, std::string("'"), std::string("'\"'\"'"));

    std::string command;
    command = command + "bash -c '" + script + "'";

    // Append the command line arguments.
    for (int a = 0; a < argc; ++a)
    {
        command = command + " " + argv[a];
    }

    return system(command.c_str());
}

Then you run
g++ embedded.cpp -o embedded
sudo chown root embedded
sudo chmod u+s embedded

A: IMPORTANT NOTE: the task described in the original question can be achieved in a safe way using sudo and sudoers configurations. Regardless of negative votes, this answer is going to stay for people that are still committed in running scripts with setuid, also after being warned of security implications. The method described also put bases for writing a more robust treatment of environment, like the one in sudo. Suggestions are welcome in chat.
The below shell script will create an a native wrapper with setuid and a given script embedded.
DISCLAIMER: READ CAREFULLY
To use the following snippet in a safe manner, some assumptions are necessary:

*

*the setuid executables created must be read only;

*the embedded script should be trusted and not being able to create security holes, such as execute another arbitrary script in the filesystem;

*The interpreter of your script, ant the script itself, should not be sensitive to environment manipulation attacks, such as modifying environment variables to force execution of untrusted code;

*The system is not already compromised, such as executables in system PATH reachable directories were already replaced with malicious versions.

If you can't guarantee the above conditions, or if you don't accept the security risks involved in being able to run trusted or non-trusted scripts with setuid, stop reading now. Also the native wrapper is probably incomplete at mitigating some common environment manipulation attacks, so use it at your own risk. Suggestions to improve the code are welcome.
If you read the above warning, and you think you'll be able to guarantee the above conditions, or you can ensure safety of your system by other means, create a file create-setuid-wrapper.sh as it follows:
#!/usr/bin/env bash
set -e

if [[ `id -u` != 0 ]]; then
    echo "Execute this command with super user credentials"
    exit 1
fi

if [[ $# -ne 1 || ! -f $1 ]]; then
    echo "A file argument is necessary"
    exit 1
fi

INPUT=$1
TEMPFOLDER=/tmp/tmpsuidwrapper
TEMPINPUT=$TEMPFOLDER/input.data
TEMPINPUTOBJ=$TEMPFOLDER/input.o
WRAPPERSRC=$TEMPFOLDER/wrapper.c
OUTFILE=$(basename -- "$INPUT")
OUTFILE="${OUTFILE%.*}.bin"

# Create temporary directory and copy the input
mkdir -p $TEMPFOLDER
cp $INPUT $TEMPINPUT

# Write wrapper source
cat > $WRAPPERSRC <<- EOF
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <err.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/wait.h>

extern const char _binary_input_data_start[];
extern  void* _binary_input_data_size;

int main (int argc, char *argv[])
{
    int rc = setuid(0);
    if (rc == -1)
    {
        perror("setuid failed");
        return -1;
    }

    int fd = memfd_create("script", 0);
    if (fd == -1)
    {
        perror("memfd_create failed");
        return -1;
    }

    size_t size = (size_t)&_binary_input_data_size;
    rc = write(fd, _binary_input_data_start, size);
    if (rc == -1)
    {
        perror("write failed");
        return -1;
    }

    // Clean the environment to protect from some common
    // environment manipulation attacks
    // CHECK-ME: Check if some variables unset is actually needed
    // and if more variables should be unset, sanitize
    unsetenv("LD_LIBRARY_PATH");
    unsetenv("LD_PRELOAD");
    unsetenv("BASHENV");
    unsetenv("ENV");
    setenv("PATH", "${PATH}", 1);

    pid_t pid = fork();
    if (pid == 0)
    {
        // Child process, execute the script
        {
            const char * const argv[] = { "script", NULL };
            const char * const envp[] = { NULL };
            int rc = fexecve(fd, (char * const *) argv, (char * const *) envp);
            if (rc == -1)
            {
                perror("fexecve failed");
                return -1;
            }
        }
    }
    if (pid == -1)
    {
        perror("fork failed");
        return -1;
    }

    // Parent process
    wait(NULL);
    return 0;
}
EOF

# NOTE: Crappy 'ld' syntax apparenty doesn't allow to
# specify a name for the symbol being created, so it will
# use path as the name. We move the input to temp folder
# to keep the symbol name short
CWD=`pwd`
cd $TEMPFOLDER
# Create a linkable object with the data to be embedded
ld -r -b binary -o input.o input.data
cd $CWD

# Compile the program and set setuid
cc -fPIC -no-pie -o $OUTFILE $WRAPPERSRC $TEMPINPUTOBJ
chmod 4755 $OUTFILE

# Cleanup
rm -fr $TEMPFOLDER

Then prepare, as an example, a test.py script like the following:
#!/usr/bin/env python3
import getpass
print(getpass.getuser())

Call create_setuid_wrapper.sh with the above test.py . The script will produce an executable test.bin. Ensure your system allow execution of arbitrary executables with setuid (SELinux enabled systems will not). Execution will print root or the name of your super user.
EDIT1: Removed copy to temporary file on the setuid executable. Now the embedded script is just executed directly from memory with a fork and a fexecve.
EDIT2: Attempt to clean the environment from some common environment manipulation attacks. It may be wrong and/or insufficient.


text:
Q: Can a TypeProvider add a Resource to the generated assembly? Is it possible for a generative type provider, when using the ProvidedTypes API, to add resources in addition to types to the assembly?
I'd like to build in specific resources generated along with the concrete types built by my provider.  If this is possible, how would I accomplish it?

A: Does it need to be in the same assembly? You can only generate types, you have no control of the assembly that F# generates, but if it doesn't need to be in the same assembly, maybe you can generate an assembly with resources manually and then use a generated type provider to reference that. But it will probably be a long shot

redpajama_set_name: RedPajamaStackExchange


text:
Q: Add new column to the existing table in Delta lake(Gen2 blob storage) Curious to know, can we add a new column to the existing Delta Lake table stored in the Gen2 blob storage, based on the business use case, i will need to add additional 3 more columns to one of the table in delta lake.
ALTER TABLE doesn't worked for me.

Any help would be appreciated.


text:
Q: Gráfico criado incorretamente Olá,
Eu estou treinando a criação de gráficos no Python com matplotlib. Para isso, estou importando um HTML com histórico de ações da WEGE3.
df_history = pd.read_html("https://br.financas.yahoo.com/quote/WEGE3.SA/history?p=WEGE3.SA")

Tirei os duplicados (só haviam 2):
df_remove = df_history[0].drop_duplicates(subset=['Data'])

E tirei a última linha:
yy = df_remove['Fechamento*'].drop(100)
xx = df_remove['Data'].drop(100)

Defini as labels:
plt.xlabel('Data')
plt.ylabel('Preço')

O problema acontece aqui: Quando eu vou exibir o gráfico, ele fica errado. Eu aumentei o tamanho só para eu ver se os valores de X e Y apareciam corretos no grafico e aparecem, mas o desenho do gráfico mesmo, está errado:
f = plt.figure()
f.set_figwidth(28)
f.set_figheight(28)
plt.plot(xx, yy)
plt.show()

Este é o gráfico (errado) que aparece:

Para confirmar se o gráfico está certo ou errado, eu peguei os mesmo dados e coloquei no Excel.
Este seria o gráfico correto:

Eu perdi um tempo tentando analisar mas eu não encontrei onde está o problema.
Não sei se esta informação é relevante mas, eu estou executando este código no Google Colab.
Obrigado.

A: O que está acontecendo é que tanto xx quanto yy estão preenchidos com strings, ao invés de valores numéricos ou de data. Por isso, quando você plota, matplotlib só está vendo texto. Para resolver, basta converter para os tipos adequados:

*

*yy pode ser convertido para uma série de inteiros usando o método to_numeric(). Precisa também usar o argumento errors='coerce', porque tem alguns valores não disponíveis que não podem ser convertidos diretamente para inteiro.

*xx está com a data escrita por extenso, em português. Talvez funcione num programa como o excel (se ele estiver em português), mas pra converter pra um formato de data que o python entenda você teria que criar uma função dedicada. A alternativa é usar os valores como estão, aí a função plot() vai usá-los como labels do eixo x.

O código fica assim:
# define um tamanho maior para a figura, caso contrário fica impossível de ler os labels
plt.figure(figsize = (20,10))

# plot com os valores de xx no eixo x e yy convertido para inteiros no eixo y
plt.plot(xx, pd.to_numeric(yy, errors='coerce'))

# rotação de 60 graus dos labels para tornar legível
plt.xticks(rotation = 60)

# mostra a figura
plt.show()

Resulta na seguinte figura:

Repare que ficou com uma descontinuidade, referente a um dia em que não tinha a cotação disponível (o argumento errors='coerce' fez que fosse convertido para NaN).


text:
Q: How to construct values from multiple GADTs while parsing json? I have the following data structures:
data Operator :: * -> * where
  StringEquals     :: Operator String
  StringNotEquals  :: Operator String
  NumericEquals    :: Operator Integer
  NumericNotEquals :: Operator Integer

data Variable :: * -> * where
  UserName     :: Variable String
  RequestPath  :: Variable String
  BodyLength   :: Variable Integer

data Value :: * -> * where
  StringValue     :: String -> Value String
  NumericValue    :: Integer -> Value Integer

data Condition a = Condition (Operator a) (Variable a) (Value a)

that will be used in functions like these:
extractVariable :: Variable a -> HttpRequest -> a
evaluate :: Operator a -> Value a -> a -> Bool

I'd like to parse Conditions from a JSON file. I can parse the parts individually, wrapped with Some, but not sure how to construct a Condition from them.
The following works and shows what I'd like to do, but it obviously isn't scalable to write:
import Data.Some

parseCondition :: Some Operator -> Some Variable -> Some Value -> Parser (Some Condition)
parseCondition (Some op@StringEquals) (Some var@UserName) (Some val@(StringValue _)) = return $ mkSome $ Condition op var val
parseCondition (Some op@StringNotEquals) (Some var@UserName) (Some val@(StringValue _)) = return $ mkSome $ Condition op var val
parseCondition (Some op@StringEquals) (Some var@RequestPath) (Some val@(StringValue _)) = return $ mkSome $ Condition op var val
parseCondition (Some op@StringNotEquals) (Some var@RequestPath) (Some val@(StringValue _)) = return $ mkSome $ Condition op var val
parseCondition (Some op@NumericEquals) (Some var@BodyLength) (Some val@(NumericValue _)) = return $ mkSome $ Condition op var val
parseCondition _ _ _ = parseFail "incompatible types"

What's the best way to do this in haskell?

A: Given a Operator a (resp. Variable a, Value a) you know exactly what a is. Using that the standard type that represents complete knowledge of a type a is TypeRep a, express that knowledge in code.
import Type.Reflection -- NOT the other TypeRep

operatorType :: Operator a -> TypeRep a
operatorType StringEquals = typeRep
operatorType StringNotEquals = typeRep
operatorType NumericEquals = typeRep
operatorType NumericNotEquals = typeRep

variableType :: Variable a -> TypeRep a
variableType UserName = typeRep
variableType RequestPath = typeRep
variableType BodyLength = typeRep

valueType :: Value a -> TypeRep a
valueType (StringValue _) = typeRep
valueType (NumericValue _) = typeRep

That is a lot of boilerplate, but the idea is that it now scales as one line per constructor rather than one line per possible combination of three constructors. Also, it looks like it can be automated, though I don't know of any "premade" solution for that.
Now just use the equality test on TypeReps.
import Data.Type.Equality
-- data a :~: b where Refl :: a :~: a
-- testEquality :: TypeRep a -> TypeRep b -> Maybe (a :~: b)

-- data Some f = forall a. Some (f a) -- I guess?
makeCondition :: Some Operator -> Some Variable -> Some Value -> Maybe (Some Condition)
makeCondition (Some op) (Some v) (Some x) = do -- I generally prefer guards for this "proofwork" but in this case a do happens to work
  Refl <- operatorType op `testEquality` variableType v
  Refl <- variableType v `testEquality` valueType x
  return $ Some $ Condition op v x


text:
Q: A good packet proccessing Java library for PostgreSQL packets? I should develop a simple server side proxy to PostgreSQL database.The proxy should sniff the queries and block them or let them go and also send back the database response to user( in reality the upper client JDBC driver).
I want to know is there any good library in Java in order to process packets(or even better SQL packets)?
Thank you in advance

A: You don't want to process "packets" at all. You want to process the PostgreSQL protocol, which is an exchange of messages. These messages are carried over TCP/IP in packets, but you shouldn't be dealing with them at that level if you're writing a proxy.
The only PostgreSQL protocol implementation I'm aware of is part of PgJDBC, and is client-side only. It's also not very generalized.
You will have to write your own using the PostgreSQL protocol documentation for reference. You will find Wireshark's support for dissecting the PostgreSQL protocol very helpful while doing so.
Of course, it sounds like you then want to parse the SQL and make decisions based on the content of the SQL. That would require an SQL parser that understands PostgreSQL's dialect. The only one I'm aware of is the PostgreSQL server's parser, and it's not something you can just separate out and plug into another app, let alone Java code. PgPool-II also contains a very limited parser, but again it's in C and not written as a separate library. Again, you're going to have to write your own.
Implementing the prococol is easy, but implementing a parser and then reasoning about the SQL using the parse tree results is very hard. Don't go there.
If you insist on pursuing this approach you should at minimum start by modifying PgPool-II or  PgBouncer, instead of writing your own proxy from scratch.
A superior approach in my opinion would be to implement a PostgreSQL extension that installs a  planner_hook or post_parse_analyze_hook to try to detect whatever problem you're having and ERROR on those queries. Or modify the core code directly (creating a custom PostgreSQL build) if you can't do what you need to with a hook.
Overall it'd be a lot more sensible to avoid the need for this in the first place by fixing any client applications. Especially as the whole concept of "validating" SQL to ensure it's "SQL injection free" is bunk. You can potentially detect simple and obvious attempts at SQL injection this way, reject multi-statements and statements ending in comments, etc, but generalized detection of SQL injection attacks as distinct from legitimate queries isn't really possible. If it was, database servers would already implement it.


text:
Q: Bootstrap 5 - How to use custom variables for button? What is the best way to use custom variables for button in Bootstrap 5?
#custom.scss
$primary: #1678E5;

@import '../node_modules/bootstrap/scss/bootstrap.scss';

Here, I'm able to change the primary color to #1678E5 across my template. The only thing it fails to do is the link color for button (as it is no longer #ffffff in color for btn-primary)
I know I'm missing something here. So if there is anyone who could point me in the right direction I'd very much appreciate it.
Edit:
Apparently, Bootstrap uses dark text color on lighter color for contrast. So all I did is to change the lower contrast ratio.
$min-contrast-ratio: 3;


text:
Q: Registered Symbol not getting inserted as-is in table I am working on Oracle 10gR2.
The character set for DB is as below:
NLS_NCHAR_CHARACTERSET AL16UTF16
NLS_CHARACTERSET AL32UTF8.
I am getting data to be processed in TXT files. The first step in processing this data is creating external tables based on these flat files. One of the fields (and the columns in DB) in the flat file has String data, which contains ® (registered symbol). This character is visible in the txt file, but when I check the external table, the character is saved as �
I have modified the encoding of the IDE to UTF-8, where I am seeing the output of the query.
The data type for the column is: COL NVARCHAR2(1000)
Please suggest as to what could be causing this?

A: Generally this is caused by incorrect setting of the NLS_LANG environment variable.  The NLS_LANG variable must tell oracle the encoding you are using for your data.  If the NLS_LANG is unset, oracle assumes ASCII text (and your symbol is non-ascii).
If your data is UTF-8, try:
NLS_LANG=.AL32UTF8
For windows/iso try
NLS_LANG=.WE8ISO8859P15
You NEED to determine the encoding of your text file first.  Use a hex editor to determine of the (R) symbol is UTF-8 or not.


text:
Q: "about the latter times" Situation: the student is asking about the possibility of having the next lesson with his teacher at 8:00 instead of usual 8:30. Teacher is answering:

"This Friday, 8:00 is fine. Not sure, though, about the latter times"

Is it okay to say like that? Google on "latter times" seems to return a lot of religious context, but here the teacher is not implying anything religious. He only says that he is not sure if other subsequent lessons after this Friday are also possible to be held at 8:00

A: It is possible that the teacher meant to use 'later', and as an adjective:

later
adjective [ before noun ]
(IN THE FUTURE)
 B2 happening at a time in the future, or after the time you have
  mentioned:
We could catch a later train.
  You can always change your password at a later date.

Later (Cambridge Dictionary)
This is repeated in Oxford:
Later (Oxford Learner's Dictionaries)
'Later' is shown as an adjective in the first 1828 edition of Webster's Dictionary
Later (Webster 1828)
By 1913 it was shown as both adjective and adverb:
Later (Webster 1913)
Although the current Merriam-Webster only says 'later' is an adverb, the current American Heritage Dictionary of the English Language gives both:
Later (American Heritage)

A:
"This Friday, 8:00 is fine. Not sure, though, about the latter times"

Having understood the question better from the comments, I suggest the following
"This Friday, 8:00 is fine. Not sure, though, about the future times"
or simply
"This Friday, 8:00 is fine. Not sure, though, about in future."


text:
Q: C++ boost/multiprecision: fatal error: mpfr.h: No such file or directory I have followed this answer and used Boost.Multiprecision to use high accuracy floating point numbers (examples).
main.cpp
#include <iostream>
#include <boost/multiprecision/mpfr.hpp>  // Defines the Backend type that wraps MPFR

int main(int argc, char** argv)
{
    namespace mp = boost::multiprecision;     // Reduce the typing a bit later...
    typedef mp::number<mp::mpfr_float_backend<300> >  my_float;
    my_float a, b, c; // These variables have 300 decimal digits precision

    return 0;
}

However, I have a serious problem for compilation of this code as I receive the following error:
/usr/include/boost/multiprecision/mpfr.hpp:15:18:
              fatal error: mpfr.h: No such file or directory

Even installing libgmp3-dev and gmplib did not work.
What is wrong?
CMakeLists.txt
cmake_minimum_required(VERSION 2.8.9)
project (main)

# Libraries
set(Boost_USE_STATIC_LIBS OFF)
set(Boost_USE_MULTITHREADED ON)
set(Boost_USE_STATIC_RUNTIME OFF)
find_package(Boost 1.54.0 COMPONENTS filesystem regex system thread date_time wave)

if(NOT Boost_FOUND)
    message( FATAL_ERROR "Boost 1.54.0 not found." )
endif()
include_directories(SYSTEM ${Boost_INCLUDE_DIR})

# Flags
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wfatal-errors -std=c++11")

include_directories(${Boost_INCLUDE_DIRS})

# pre executable commands

add_executable(main
    main.cpp
)

# Link
target_link_libraries(main ${Boost_LIBRARIES})
target_link_libraries(main ${CMAKE_THREAD_LIBS_INIT})

A: If you want to use the MPFR backend you've got to install it separately, make sure it is built, and make sure its headers are in your compiler's INCLUDE path and its binaries (libraries) are in your linker's command line.
(MPFR is not GMP.)

A: You must include the libraries for both gmp and mfr in your cmake file.
In qmake use: LIBS += -lgmp -lmpfr
If you do not know how in cmake, just let qmake make a cmake file, I do not use cmake, but I know it is similar, but forgot how to do it, or I would just do it and post the results, sorry, but of all the things I have forgotten over the years, like where did I put my Memories; but like them, this post is Old, so anyone finding it might find this helpful.
This will satisfy the includes below, and a few more:
 #include <boost/multiprecision/cpp_dec_float.hpp>
 #include <boost/multiprecision/mpfr.hpp>
 #include <boost/multiprecision/gmp.hpp>


text:
Q: I am trying to deploy a simple nodejs app using heroku and its is deployed successfully but giving error on opening the url? By mistake i have deployed two apps using the same repo assuming there is error in the process of deploying , never deployed any app using heroku  so please look into my issue
My index.js
const express = require("express");
const port = process.env.port || 3000;
const path = require("path");

var app = express();
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));

//using middleware to include static files like css and javascript
app.use(express.static("static"));
app.get("/", (req, res) => {
  return res.render("index");
});

app.listen(port, (err) => {
  if (err) {
    console.log("Error found");
    return res.send("Error");
  }
  console.log("Server running on port: ", port);
});

My package.json
{
  "name": "resume_project",
  "version": "1.0.0",
  "description": "**It is a dynamic website containg a resume template to showcase, it has details like my profile ids, some of the projects, Education etc.**",
  "main": "\u001b[A\u001b[A\u001b[Bdhruv singhal\u001b[B\u001b[D\u001b[D\u001b[A\u001b[D\u001b[D\u001b[D\u001b[D\u001b[D\u001b[D\u001b[D\u001b[D\u001b[D\u001b[D\u001b[\u001b[B",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon index.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/dhruv354/resume_project.git"
  },
  "author": "dhruv singhal",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/dhruv354/resume_project/issues"
  },
  "homepage": "https://github.com/dhruv354/resume_project#readme",
  "dependencies": {
    "ejs": "^3.1.6",
    "express": "^4.17.1"
  }
}

heroku logs --tail
 »   Warning: heroku update available from 7.53.0 to 7.53.1.
2021-05-17T11:07:25.647982+00:00 app[api]: Release v1 created by user dhruv.singhal2612@gmail.com
2021-05-17T11:07:25.647982+00:00 app[api]: Initial release by user dhruv.singhal2612@gmail.com
2021-05-17T11:07:26.025509+00:00 app[api]: Enable Logplex by user dhruv.singhal2612@gmail.com
2021-05-17T11:07:26.025509+00:00 app[api]: Release v2 created by user dhruv.singhal2612@gmail.com
2021-05-17T11:08:39.000000+00:00 app[api]: Build started by user dhruv.singhal2612@gmail.com
2021-05-17T11:08:54.990971+00:00 app[api]: Deploy dcaa0bec by user dhruv.singhal2612@gmail.com
2021-05-17T11:08:54.990971+00:00 app[api]: Release v3 created by user dhruv.singhal2612@gmail.com
2021-05-17T11:08:55.000000+00:00 app[api]: Build succeeded
2021-05-17T11:08:55.003479+00:00 app[api]: Scaled to web@1:Free by user dhruv.singhal2612@gmail.com
2021-05-17T11:08:58.272953+00:00 heroku[web.1]: Starting process with command `npm start`
2021-05-17T11:09:00.649752+00:00 app[web.1]: npm ERR! missing script: start
2021-05-17T11:09:00.658516+00:00 app[web.1]:
2021-05-17T11:09:00.658834+00:00 app[web.1]: npm ERR! A complete log of this run can be found in:
2021-05-17T11:09:00.658987+00:00 app[web.1]: npm ERR!     /app/.npm/_logs/2021-05-17T11_09_00_650Z-debug.log
2021-05-17T11:09:00.715950+00:00 heroku[web.1]: Process exited with status 1
2021-05-17T11:09:00.804781+00:00 heroku[web.1]: State changed from starting to crashed
2021-05-17T11:09:00.826182+00:00 heroku[web.1]: State changed from crashed to starting
2021-05-17T11:09:03.431232+00:00 heroku[web.1]: Starting process with command `npm start`
2021-05-17T11:09:06.521982+00:00 app[web.1]: npm ERR! missing script: start
2021-05-17T11:09:06.531997+00:00 app[web.1]:
2021-05-17T11:09:06.532511+00:00 app[web.1]: npm ERR! A complete log of this run can be found in:
2021-05-17T11:09:06.532702+00:00 app[web.1]: npm ERR!     /app/.npm/_logs/2021-05-17T11_09_06_522Z-debug.log
2021-05-17T11:09:06.591767+00:00 heroku[web.1]: Process exited with status 1
2021-05-17T11:09:06.651080+00:00 heroku[web.1]: State changed from starting to crashed
2021-05-17T11:10:08.000000+00:00 app[api]: Build started by user dhruv.singhal2612@gmail.com
2021-05-17T11:10:30.883151+00:00 app[api]: Deploy 6174a3f9 by user dhruv.singhal2612@gmail.com
2021-05-17T11:10:30.883151+00:00 app[api]: Release v4 created by user dhruv.singhal2612@gmail.com
2021-05-17T11:10:31.000000+00:00 app[api]: Build succeeded
2021-05-17T11:10:31.081243+00:00 heroku[web.1]: State changed from crashed to starting
2021-05-17T11:10:34.558759+00:00 heroku[web.1]: Starting process with command `npm start`
2021-05-17T11:10:38.058050+00:00 app[web.1]:
2021-05-17T11:10:38.058089+00:00 app[web.1]: > resume_project@1.0.0 start /app
2021-05-17T11:10:38.058090+00:00 app[web.1]: > nodemon index.js
2021-05-17T11:10:38.058091+00:00 app[web.1]:
2021-05-17T11:10:38.359100+00:00 app[web.1]: [nodemon] 2.0.7
2021-05-17T11:10:38.360054+00:00 app[web.1]: [nodemon] to restart at any time, enter `rs`
2021-05-17T11:10:38.360505+00:00 app[web.1]: [nodemon] watching path(s): *.*
2021-05-17T11:10:38.360612+00:00 app[web.1]: [nodemon] watching extensions: js,mjs,json
2021-05-17T11:10:38.361510+00:00 app[web.1]: [nodemon] starting `node index.js`
2021-05-17T11:10:38.611086+00:00 app[web.1]: Server running on port:  3000
2021-05-17T11:11:34.662337+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
2021-05-17T11:11:34.720677+00:00 heroku[web.1]: Stopping process with SIGKILL
2021-05-17T11:11:34.852653+00:00 heroku[web.1]: Process exited with status 137
2021-05-17T11:11:34.981104+00:00 heroku[web.1]: State changed from starting to crashed
2021-05-17T11:11:36.282468+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=resume-app-dhruv.herokuapp.com request_id=45a83bd8-8665-4e79-b3d2-1b65084534ef fwd="49.34.85.157" dyno= connect= service= status=503 bytes= protocol=https
2021-05-17T11:11:36.584581+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=resume-app-dhruv.herokuapp.com request_id=71aab104-e585-4b9c-b86e-3edbc11365f0 fwd="49.34.85.157" dyno= connect= service= status=503 bytes= protocol=https
2021-05-17T11:11:38.454567+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=resume-app-dhruv.herokuapp.com request_id=cbaded28-9e12-4eb1-8900-2be54e211247 fwd="49.34.85.157" dyno= connect= service= status=503 bytes= protocol=https
2021-05-17T11:12:08.266884+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=resume-app-dhruv.herokuapp.com request_id=e3777d79-c435-443b-9529-95aece6d8c0f fwd="49.34.85.157" dyno= connect= service= status=503 bytes= protocol=https
2021-05-17T11:12:09.396478+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=resume-app-dhruv.herokuapp.com request_id=7a1adc3a-c8cf-4ecf-8afd-a729192e8fda fwd="49.34.85.157" dyno= connect= service= status=503 bytes= protocol=https
2021-05-17T11:14:53.639282+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=resume-app-dhruv.herokuapp.com request_id=73d769ed-89c4-41dc-9349-62e8be14f6c2 fwd="49.34.85.157" dyno= connect= service= status=503 bytes= protocol=https
2021-05-17T11:14:54.202559+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=resume-app-dhruv.herokuapp.com request_id=43d08929-28aa-4b5e-9f7c-cfb569c1921f fwd="49.34.85.157" dyno= connect= service= status=503 bytes= protocol=https
2021-05-17T12:12:37.458250+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=resume-app-dhruv.herokuapp.com request_id=c2f29684-ed66-4782-8f99-096ccb4ac74d fwd="49.34.85.157" dyno= connect= service= status=503 bytes= protocol=https
2021-05-17T12:12:38.779459+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=resume-app-dhruv.herokuapp.com request_id=25e82ee8-cb94-4c52-bcfa-5d9c1854e496 fwd="49.34.85.157" dyno= connect= service= status=503 bytes= protocol=https

Tried other solutions  but not able to solve the problem , i am unable to understand where the whole problem lies

A: Change start script to
"start": "node index.js"

Nodemon is used during development and its not even on your dependencies
Also try to change
process.env.port

to process.env.PORT
usually heroku doesn't want to run any port you like


text:
Q: IE8 not sending Accept-Encoding: gzip, deflate Following on closely from this question SSRS IE8 JavaScript Error Invalid Character ScriptResource.axd I have done some debugging and narrowed the issue down to a gzip, deflate problem.
We have various machines with IE8 installed on them. The problem is, some installations of IE don't seem to add the Accept-Encoding: gzip, deflate to the HTTP Request header when requesting a JavaScript resource via ScriptResource.axd.
Here is the HTTP request off machine 1 (works fine):
GET http://10.x.x.x6/Reports_2/ScriptResource.axd?d=dz2_T_-skCIGFrM350LrrgpIbuyQ3hv0Po2nyTqnjMC_h2orbb8AW34-wlapNOlKQn3w_65Hv8xicNrMgbLAWsuKLkB24a0JnVTM3AD64R_ELK1K6KpCKGgYkO_evQ1uY6IeQkuEpQDrHclftKpS0G8rnJM1&t=4d63fd9d HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
Accept-Language: en-GB
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
Accept-Encoding: gzip, deflate
Proxy-Connection: Keep-Alive
Authorization: Negotiate TlRMTVNTUAADAAAAGAAYAJIAAAAYABgAqgAAABgAGABYAAAAEAAQAHAAAAASABIAgAAAABAAEADCAAAAFYKI4gYBsR0AAAAP5M9BpXhDtQyLRxQO0MslBkQARQBOAEIASQBHAEgAUwBIAEkAUgBFAGEAbAB5ADgANgA3ADcANwBEAEMAQwAwADEAOQA4ADgAOAAW1o72sWx0hAAAAAAAAAAAAAAAAAAAAAD8+dJyp0KpjG5sP9WUlmrk4FptdhpYQAEETsImSmR+ZzMapF8Z91Wv
Host: 10.x.x.x6

And here is the same request made off machine 2 (doesn't work as its returning gzipped data):
GET http://10.x.x.x6/Reports_2/ScriptResource.axd?d=dz2_T_-skCIGFrM350LrrgpIbuyQ3hv0Po2nyTqnjMC_h2orbb8AW34-wlapNOlKQn3w_65Hv8xicNrMgbLAWsuKLkB24a0JnVTM3AD64R_ELK1K6KpCKGgYkO_evQ1uY6IeQkuEpQDrHclftKpS0G8rnJM1&t=4d63fd9d HTTP/1.1
Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*
Accept-Language: en-gb
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E; BRI/2)
Authorization: Negotiate TlRMTVNTUAADAAAAGAAYAIIAAAAYABgAmgAAABgAGABIAAAAEAAQAGAAAAASABIAcAAAAAAAAACyAAAABYKIogUBKAoAAAAPRABFAE4AQgBJAEcASABTAEgASQBSAEUAagBvAG4AOQA0ADYAMQA0AEQAQwBDADAAMQAzADUANgA2APyGLo3yOcCnAAAAAAAAAAAAAAAAAAAAABccpJT8TohKqbhq3PzWDPApr1NmEypAPg==
Connection: Keep-Alive
Pragma: no-cache
Host: 10.x.x.x6

The problem seems to be that IE is not-requesting gzipped data, but its actually getting gzipped data from the server (an then its failing because it doesn't think its gzipped).
If i manually decompress the data returned using zcat or something, i can view the returned JavaScript fine.
What would cause IE8 not to add this header onto the request ??


text:
Q: Unable to json_decode output received from my php webservice? Webservice code:
function login($uname)
        {

            $id=1;
            $link = mysql_pconnect("localhost", "root", "root") or die("Could not connect");
            mysql_select_db("sparq",$link) or die("Could not select database");
            $sql=mysql_query("select username,password from user_login where user_id=1");
            //$result = mysql_query($query);
            $arr = array();
            while($obj = mysql_fetch_object($sql))
                {
                    $arr[] = $obj;
                    }
           // $obj = mysql_fetch_object($sql);
           header("Content-type: application/json");
           echo json_encode($arr);
        }

Code from client:
$url="http://localhost/web.php";
if (isset($_POST['Login']))
    {

            $ch = curl_init($url); // Initialize a CURL session
            curl_setopt($ch, CURLOPT_HEADER, 0); // options for a CURL transfer
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS,"username=".$username );
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $data = curl_exec($ch); // Perform a CURL session
            curl_close($ch);
            $arr =array();
            $arr=json_decode($data,true);
            echo 'I am here';    //echo1
            echo $data;   //echo2

            echo $arr[0]->username; //echo3

I am getting the below output:
I am here //echo1
[{"username":"akhilnk@gmail.com","password":"asdf123"}]  //echo2
Notice: Trying to get property of non-object in F:\xampp\htdocs\webtest\login.php on line 38  //echo3

A: This:
echo $arr[0]->username;

Should be:
echo $arr[0]['username'];

And this:
$arr = array();
while($obj = mysql_fetch_object($sql)) {
  $arr[] = $obj;
}

Should be:
$arr = array();
while($row = mysql_fetch_assoc($sql)) {
  $arr[] = $row;
}

You can't send php objects over json. What javascript (and json) call an object is an associative array in php.

A: Replace:  echo $arr[0]->username; by $arr[0]['username'];


text:
Q: Run a batch file silently, executed at remote desktop login In our office we are using Linux thin client machines, they work very well except the lack of IE, which is a pain because the corporations we deal with are too stupid to update their web apps (no flame wars please).
To solve this problem we have machine in our computer room which users remote desktop into to access internet explorer, this is achieved by running a batch script which opens IE and when it closes logs them off, this setup works well for us.
Even though I have @echo off and the cmd window isn't displaying anything, I would really like that batch file to be executed silently, so the cmd window doesn't appear at all.
Is this possible?
The Ubuntu terminal server client has an option to launch a file / app at login, is there a command I can use to run this batch silently.
I have tried these:
C:\my_batch.bat /NOCONSOLE
C:\my_batch.bat /NOWINDOW
C:\my_batch.bat /B
C:\my_batch.bat /Q

...with no success, perhaps it's the way I am doing it?
Cheers :-)
Edit
The remote desktop platform is a Windows XP machine, nothing entirely special but not a Windows Server setup.

A: Perhaps try
start /b my_batch.bat

the /b parameter is used to
Start application without creating a new window. The
application has ^C handling ignored. Unless the application
enables ^C processing, ^Break is the only way to interrupt
the application

A: Instead of using a batch file, why don't you create a Group Policy that forces the user shell to be Internet Explorer.  This should achieve the behavior you want without any scripts at all.
user configuration -> administrative templates-> system -> custom user interface
Another alternative would be create a vbscript and use that via thw windows scripting host instead of a batch file.  Scripts launched with wscript will not spawn a new window.  What is your batch file doing?  It should be easy enough to simply convert it WSH.

A: If you don't mind the batch file executing whenever any user logs on (i.e. via terminal services or locally), then:

*

*Save your .cmd file to a location where all users have read only access. (e.g. %WINDIR%)

*Launch gpedit.msc from a command prompt

*Navigate to User > Security > Scripts > Logon

*Add a new script, and point it to wherever you saved your .cmd file

The script should run silently without showing a command prompt window.
If you don't want it to run when a user logs on locally, it is probably possible to detect this in your batch file and silently abort the script.

A: You can't run a batch script hidden if run it like this.
But it's possible with a little VBS.
Just execute the VBS file and it will run the Script hidden
Dim oShell
Set oShell = WScript.CreateObject ("WScript.Shell")
oShell.run "cmd /C C:\my_batch.bat",0,false
Set oShell = Nothing

See this msdn article:
http://msdn.microsoft.com/en-us/library/d5fk67ky%28VS.85%29.aspx

A: The remote desktop application is in fact using said batch file as an alternate shell, and I don't think parameters can be passed using this method.
Therefore I will have to live with my console window.


text:
Q: How do I remove all space around a chart in AndroidPlot? I've got a minimalist chart using androidPlot in an application, and have been trying to remove extraneous visual elements. I've got everything done, except that I cannot get rid of some empty spaces around the chart itself within the view. Here's what it looks like with markup turned on, just sitting in the root view of an Activity:

How can I eliminate the black space between the inner chart boundaries and the outer view boundary? Here's my code:

    mDynamicPlot = (XYPlot) findViewById(R.id.dynamicPlot);
    mDynamicPlot.getGraphWidget().setDomainValueFormat(new DecimalFormat("0"));
    mDynamicPlot.addSeries(mCpuData, new LineAndPointFormatter(Color.rgb(51, 204, 255), null, Color.rgb(8, 153, 194)));
    mDynamicPlot.setDomainStepMode(XYStepMode.INCREMENT_BY_VAL);
    mDynamicPlot.setRangeBoundaries(0, 100, BoundaryMode.FIXED);
    mDynamicPlot.setDomainStepValue(10);
    mDynamicPlot.setRangeStepValue(5.0d);
    mDynamicPlot.setRangeValueFormat(new DecimalFormat("#"));

    mDynamicPlot.setTicksPerDomainLabel(Integer.MAX_VALUE);
    mDynamicPlot.getLayoutManager().remove(mDynamicPlot.getLegendWidget());
    mDynamicPlot.getLayoutManager().remove(mDynamicPlot.getRangeLabelWidget());
    mDynamicPlot.getLayoutManager().remove(mDynamicPlot.getDomainLabelWidget());
    mDynamicPlot.getLayoutManager().remove(mDynamicPlot.getTitleWidget());

    mDynamicPlot.getGraphWidget().setMarginTop(10);

    mDynamicPlot.setBackgroundPaint(null);
    mDynamicPlot.getGraphWidget().setBackgroundPaint(null);
    mDynamicPlot.getGraphWidget().setGridBackgroundPaint(null);

    mDynamicPlot.getGraphWidget().setDomainLabelPaint(null);
    mDynamicPlot.getGraphWidget().setDomainOriginLabelPaint(null);

    mDynamicPlot.getGraphWidget().setGridLinePaint(null);
    mDynamicPlot.getGraphWidget().setDomainOriginLinePaint(null);
    mDynamicPlot.getGraphWidget().setRangeOriginLinePaint(null);

    mDynamicPlot.setDrawBorderEnabled(false);

And my XML. The right margin is to offset the left space which I want to get rid of:
<com.androidplot.xy.XYPlot
    android:id="@+id/dynamicPlot"
    android:layout_width="fill_parent"
    android:layout_height="150dp"
    android:layout_marginTop="16dp"
    android:layout_marginRight="10dp"
    title="Dynamic Plot" />

Nothing I do in XML seems to affect the inner bounds, including changing the enclosing layout gravity. I have also tried these, to no effect:

    mDynamicPlot.getRangeLabelWidget().setHeight(0);
    mDynamicPlot.getRangeLabelWidget().setPadding(0, 0, 0, 0);
    mDynamicPlot.getRangeLabelWidget().setMargins(0, 0, 0, 0);

    mDynamicPlot.getLegendWidget().setSize(new SizeMetrics(0, SizeLayoutType.ABSOLUTE, 0, SizeLayoutType.ABSOLUTE));
    mDynamicPlot.getRangeLabelWidget().setSize(new SizeMetrics(0, SizeLayoutType.ABSOLUTE, 0, SizeLayoutType.ABSOLUTE));
    mDynamicPlot.getDomainLabelWidget().setSize(new SizeMetrics(0, SizeLayoutType.ABSOLUTE, 0, SizeLayoutType.ABSOLUTE));

What do I need to do to get rid of all that black space?

A: The Plot itself (mDynamicPlot in your example) is essentially a collection of widgets positioned in a shared space.  The actual class that handles the positioning is LayoutManager.
In addition to positioning, the size of the Widget will also need to be adjusted to fill the entire Plot.  Each Widget keeps track of its own size using an instance of SizeMetrics.  You can modify the size of any Widget by invoking setSize(SizeMetrics newInstance);  The "chart" area you are interested in corresponds to the XYGraphWidget.
I have not personally tested this but I believe the code below should do what you want:
// get a handle to the XYGraphWidget:
Widget gw = mDynamicPlot.getGraphWidget();

// FILL mode with values of 0 means fill 100% of container:
SizeMetrics sm = new SizeMetrics(0,SizeLayoutType.FILL,
                                 0,SizeLayoutType.FILL));
gw.setSize(sm);

// get a handle to the layout manager:
LayoutManager lm = mDynamicPlot.getLayoutManager();

// position the upper left corner of gw in the upper left corner of the space
// controlled by lm.
lm.position(gw, 0, XLayoutStyle.ABSOLUTE_FROM_LEFT,
            0, YLayoutStyle.ABSOLUTE_FROM_TOP);

A: SizeMetrics is no Longer used to set the size, instead Size is used with the same Constructor as SizeMetrics and the same way to use.
new Call looks like this.
Widget gw = mPlot.getGraph();
Size size = new Size(0,SizeMode.FILL,0,SizeMode.FILL);
gw.setSize(size);
gw.position(0, HorizontalPositioning.ABSOLUTE_FROM_LEFT,0, VerticalPositioning.ABSOLUTE_FROM_TOP);


text:
Q: Java generics: Wildcard capture compilation error I get following compilation errors:
The method sort(List<T>, Comparator<? super T>) in the type Collections is not applicable for the arguments (T[], Comparator<capture#1-of ? extends T>) Main.java   /Sorting/src/com/kash/test  line 11
The method sort(List<T>, Comparator<? super T>) in the type Collections is not applicable for the arguments (T[], Comparator<capture#2-of ? super T>)   Main.java   /Sorting/src/com/kash/test  line 15
The method sort(List<T>, Comparator<? super T>) in the type Collections is not applicable for the arguments (T[], Comparator<T>)    Main.java   /Sorting/src/com/kash/test  line 19

when I compile (with JDK 1.7.0 in Eclipse Juno) this code:
package com.kash.test;

import java.util.Collections;
import java.util.Comparator;

// 3 attempts to write a wrapper over: Collections' method
//      public static <T> void sort(List<T> list, Comparator<? super T> c)
public class Main {

    public static <T> void sort1(T[] array, Comparator<? extends T> c) {
        Collections.sort(array, c); // line 11
    }

    public static <T> void sort2(T[] array, Comparator<? super T> c) {
        Collections.sort(array, c); // line 15
    }

    public static <T> void sort3(T[] array, Comparator<T> c) {
        Collections.sort(array, c); // line 19
    }

    public static void main(String[] args) {

    }
}

I have read following but did not really understand much. Any help?

*

*Java Generics: Wildcard capture misunderstanding

*What is PECS (Producer Extends Consumer Super)?

*More reading from thread above:

*

*Can't add value to the Java collection with wildcard generic type

*Java Collections using wildcard

*Generic collection & wildcard in java

*Generics - Cannot add to a List with unbounded wildcard

*What is the difference betwen Collection<?> and Collection<T>
-- edit --
For the picky guys who would want to know why am I doing such stupid things. If you don't care why am I doing this, don't bother the rest.
Why?
I'm writing several implementations (e.g. Quick, Insertion, Heap, Mixed, Intro, Bubble, ...) of following interface:
package com.kash.src;

import java.util.Comparator;
import java.util.List;

/**
 * Interface that provides all sorting functions for all possible representations of a list of Objects (non-primitive
 * types).

 * - {@link List}<{@link Comparable}>

 * - Array of < ? extends {@link Comparable}>

 * - {@link List}< ? > with external {@link Comparator}

 * - Array of < ? > with external {@link Comparator}

 *
 * @author Kashyap Bhatt
 *
 */

public interface Sorter {
    <T extends Comparable<T>> void sort(List<T> list);

    <T extends Comparable<T>> void sort(T[] array);

    <T extends Object> void sort(List<T> list, Comparator<? super T> c);

    <T extends Object> void sort(T[] array, Comparator<? super T> c);
}

So that I can test all my sort implementations and test them. I wanna compare the results with Java's sort implementations, so I'm also writing an implementation of this interface which internally just calls Java's sort methods. That's where I faced the problem.

A: Collections#sort expects a List while you are passing an array.
Do:
public static <T> void sort1(T[] array, Comparator<? extends T> c) {
        Collections.sort(Arrays.asList(array), c); // line 11
}

A: Collections.sort() does not sort arrays, but Lists.

A:
The method sort(List<T>, Comparator<? super T>) in the type Collections is not applicable for the arguments (T[], Comparator<capture#1-of ? extends T>) Main.java   /Sorting/src/com/kash/test  line 11

You are passing T[] where List<T> is expected and Comparator<? extends T> where Comparator<? super T> is expected.
Why do you think it should not give error?


text:
Q: radio button value to the controller from vf page  <apex:selectRadio  id="Frequency" layout="pageDirection" value="{!frequency}"
                                      onChange="show(this.value)">
                        <apex:selectOption itemValue="Daily" itemLabel="Daily"></apex:selectOption>
                        <apex:selectOption itemValue="Weekly" itemLabel="Weekly"></apex:selectOption>
                        <apex:selectOption itemValue="Monthly" itemLabel="Monthly"></apex:selectOption>
                        <apex:selectOption itemValue="Yearly" itemLabel="Yearly"></apex:selectOption>
                    </apex:selectRadio>

here is the controller code
     public String frequency { get; set; }

     System.debug(frequency);

how can I get the value of frequency as selected on the list and whenever the selection is changed then frequency variable also updates in the controller?
thanks a lot for the help

A: Try actionfunction or actionSupport
VF:
<apex:actionFunction action="{!MyMethod}" name="myFunction" />

<apex:selectRadio id="Frequency" layout="pageDirection" value="{!frequency}"
    onChange="myFunction()">

Or:
    <apex:actionSupport event="onchange" action="{!MyMethod}" />
</apex:selectRadio>

Apex:
public void MyMethod(){
    System.debug(frequency);
}


text:
Q: Как запустить gradle task в отдельном .gradle файле Как запустить gradle task в отдельном .gradle файле до assembleDebug
Т.е. у меня в build.gradle (Project: gradle)
buildscript {
    //something
}

allprojects{
    //something
}

tasks.whenTaskAdded { task ->
    if (task.name == 'assembleDebug') {
        task.dependsOn mytask
    }
}

И есть файл mytask.gradle в котором
task mytask << {
    println "mytask run!"
}

Не выполняется.
Есть вот такая ошибка: Could not get unknown property 'mytask' for root project 'gradle' of type org.gradle.api.Project.
Как запустить gradle task в отдельном .gradle файле до выполнения assembleDebug?

A: Нужно добавить

apply from: 'gradle/mytask.gradle'

https://stackoverflow.com/questions/54593836/run-a-file-mytask-gradle-before-executing-assembledebug


text:
Q: Append values to div as array - jquery i have a menu. These menu includes some artists and when admin clicks checkboxes, the artists is inserted to DB.
first of all,
function AddDataImdb(par, par2, par3) {

    var artistIds = [];
    $("input[name='" + par + "']:checked").each(function () {
        artistIds.push($(this).val());
    });

    $.post('/json/management/AddDataImdbAjax', {
        "artistIds": artistIds
    }, function (response) {
        if (response == 'error') {

            alert("Sanatçı bulunamadı, yönlendiriliyorsunuz");
            window.location.replace("myurl");

        } else {
            alert("succesfully added");
            $("#" + par2 + "").append(('
<input type="checkbox" name =' + par + ' value=' + response + ' />' + par3 + '
'));
        }
    });

}

With above code, i can add my div the new added artists.
The problem is that when admin insert 2 or more artist, it shows the last one as added
$("#"+par2+"").append(('
<input type="checkbox" name ='+par+' value='+response+' />'+par3+'
'));

Above code add the div. How can i  add these as array ? What can i do ?

A: can you state more? what is the content of the response?
if your response is a list then you may do this:
$.each(reponse, function () {
    //append as div
}):


text:
Q: Jmeter : How to get first userID from first request and transfer to second request same userId? I have a script include two HTTP request
1 The first request is User Authentication。include userId.....
2: the second request also includes userId.
The two parameters are consistent。
How to get the first userID from the first request and transfer to second request same userId?
I want to get userID from the first request, not from the response, response body does not include userId, transfer the same userId to the second request.
Here is the first request body:
[

   {"productId":"5551",
   "userId":"${__RandomString(32,44e00d674dee4ff7a2d4f0081991b6d40Bs9Hc)}",
   "service":"200008",
   "app_system":"7.1.1",
   "equipmentId":"866935038314977",
   "app_devicetype":"vivo X20A",
   "app_platform":"Android",
   "app_version":"3.1.3",
   "market":"icash_main"}
]

A: Use Extractors for the co-relating your requests and responses.
First, you need to extract the userID from the response of your 1st requests.
To do this, choose an extractor (Use JSON Extractor if your requests return the JSON response) and add to your 1st request.
Second, After getting the value of userId through a variable using the extractor, you can use it in your subsequent requests.
Edit:
As you want to use the same userId in both requests, use User Defined Variables in your test plan and add a variable userID in it like this:

In your request body use the variable of userId like this:
{"productId":"5551",
   "userId":"${userId}",
   "service":"200008",
   "app_system":"7.1.1",
   "equipmentId":"866935038314977",
   "app_devicetype":"vivo X20A",
   "app_platform":"Android",
   "app_version":"3.1.3",
   "market":"icash_main"}

Here is the requests body of the two requests which are using the same userId
Body of the Request 1:

Body of the Request 2:


text:
Q: Find a List of strings in a txt file in Python What is the fastest way to search a list of strings in a txt file in python?
I am loading the txt file, then splitting it's content by white spaces.
   It  produces a list and then I am using :
   for eachString in StringList:
     if eachString in File:
      //do this

A: Assuming you want to know the location:

str.find(sub[, start[, end]])
Return the lowest index in the string where substring sub is found, such that sub is contained in the slice s[start:end]. Optional

arguments start and end are interpreted as in slice notation. Return
  -1 if sub is not found.

If you don't care to know where the substring is located in the haystack string, just
substr in haystack

will return True or False, and that's all you want to know
Since you're already loading the entire file into memory, this seems like the best way to go. If it turns out that the file is larger than will fit in memory, or is actually a stream, then some other approach will be required. (but I don't want to get into that unless it's needed)


text:
Q: Dangers/Guarantees for using ByteArrayInputStream to have "Correct" mark/reset behaviour The question may be generic but I am trying to understand the major implications here.
I am trying to do some byte code engineering using BCEL library and part of the workflow requires me to read the same byte code file multiple times (from the beginning). The flow is the following
// 1. Get Input Stream

// 2. Do some work

// 3. Finish

// 4. Do some other work.

At step 4, I will need to reset the mark or get the stream as though it's from beginning. I know of the following choices.
1) Wrap the stream using BufferedInputStream - chance of getting "Resetting to invalid mark" IOException
2) Wrap it using ByteArrayInputStream - it always works even though some online research suggests that it's erroneous?
3) Simply call getInputStream() if I need to read from the stream again.
I am trying to understand which option would be better for me. I don't want to use BufferedInputStream because I have no clue where the last mark is called, so calling reset for a higher mark position will cause IOException. I would prefer using ByteArrayInputStream since it requires the minimum code change for me, but could anyone suggest whether option#2 or option#3 will be better?
I  know that implementations for mark() and reset() are different for ByteArrayInputStream and BufferedInputStream in JDK.
Regards

A: The problem of mark/reset is not only that you have to know in advance the maximum amount of data being read between these calls, you also have to know whether the code you're delegating to will use that feature for itself internally, rendering your mark obsolete. It's impossible for code using mark/reset to remember and restore a previous mark for the caller.
So while it would be possible to fix the maximum issue by specifying the total file size as maximum readlimit, you can never rely on a working mark when passing the InputStream to an arbitrary library function that does not explicitly document to never use the mark/reset feature internally.
Also, a BufferedInputStream getting a readlimit matching the total file size would not be more efficient than a ByteArrayInputStream wrapping an array holding the entire file, as both end up maintaining a buffer of the same size.

The best solution would be to read the entire class file into an array once and directly use the array, e.g. for code under your control or when you have a choice regarding the library (ASM's ClassReader supports using a byte array instead of an InputStream, for example).
If you have to feed an InputStream to a library function insisting on it, like BCEL, then wrap the byte array into a ByteArrayInputStream when needed, but create a new ByteArrayInputStream each time you have to re-parse the class file. Constructing the new ByteArrayInputStream costs nothing, as it is a lightweight wrapper and is reliable, as it does not depend on the state of an older input stream in any way. You could even have multiple ByteArrayInputStream instances reading the same array at the same time.
Calling getInputStream() again would be an option, if you have to deal with really large files for which buffering the entire contents is not an option, however, this is not the case for class files.


text:
Q: VB.Net - Deleting multiple selected rows in a Datagridview I cannot find a way to delete the selected rows not only on the datagridview, but also on the SQL Server Database. How should I do that in VB.Net?

A: Delete the selected items from the database using something like delete from table where x = @x. Then delete the same selected items from the DataGridView.


text:
Q: Post photo from phone gallary to Api using retroft Android i have project and i need to post photo that chose from user to Api , and in another activity i have to get the photo , my question is how i can post the photo?? and what the column type in api should be ??? i using retroft and all the project and i need to post photo in retroft ?
this how i get the photo from user and i need to post it !
       buttonLoadImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(i, RESULT_LOAD_IMAGE);
        }
    });
    if (shouldAskPermission() == true)
    {
        String[] perms = {"android.permission.READ_EXTERNAL_STORAGE"};
        int permsRequestCode = 200;
        requestPermissions(perms, permsRequestCode);
    }
    s = (Button) findViewById(R.id.button);
    s.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Save();
        }
    });
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
         picturePath = cursor.getString(columnIndex);
        cursor.close();
        ImageView imageView = (ImageView) findViewById(R.id.imgView);
        imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
        Log.d("image",picturePath+"");

    }
}
private boolean shouldAskPermission(){
    return(Build.VERSION.SDK_INT> Build.VERSION_CODES.LOLLIPOP_MR1);
}


text:
Q: Can the Python module gekko handle complex numbers? I'm faced with an Hessenberg index-2 DAE, I'm trying to solve it using the python module gekko.
After a few days of trial and error, I think I'm not too far from a code that works. But I've just realized that maybe gekko is not able to handle complex numbers?
Here is a minimal working example:
import numpy as np
from gekko import GEKKO

# Define the simulation and its parameters
g = GEKKO()
g.options.IMODE = 7
g.options.NODES = 1

# define the time array
n_steps = 100
Time = np.linspace(0, 2 * np.pi, n_steps)
g.time = Time

# Initialise the variables
x = g.Var(0.0)

# Write the model's equations
g.Equation(x.dt() == 1.0j * x)

# solve the equations
g.solve(disp = False)

print(x.value)

If I try to run this code, I expect to find the standard complex exponential.
But instead, I get the following error:
File "gekko.py", line 2185, in solve
    raise Exception(response)
Exception:  @error: Model Expression
 *** Error in syntax of function string: Missing operator

Position: 9
 $v1-(((1j)*(v1)))

Could you confirm that gekko cannot handle complex numbers? And maybe suggest another python DAE solver that does?
Thank you so much!

A: Gekko does not natively handle complex numbers. The automatic differentiation and gradient-based solvers haven't been programmed with that in mind. As you discussed in the comments, there are workarounds to solve complex number problems by splitting the variable. There are additional suggestions at Application of complex numbers in Linear Programming?


text:
Q: Automatically export all properties as named exports I'm wanting to create a simple mechanism whereby I can switch out the underlying provider that I'm using to get blog entries (among other things).
You'll notice that I'm explicitly exporting getBlogBySlug at the end of the file. This is fine with just a few named exports, but I may end up with a whole load of these.
Is there any way to export all the properties of the providerImplementation as individual named exports without defining them all individually as named exports?
All of the provider implementations (blog system A and B in the code) will adhere to the same interface.
import * as blogSystemA from './providers/blog-system-a'
import * as blogSystemB from './providers/blog-system-b'
import { BlogProvider } from './types'

let providerImplementation: BlogProvider

if (provider === Provider.BLOG_SYSTEM_A) {
  providerImplementation = blogSystemB
} else if (provider === Provider.BLOG_SYSTEM_B) {
  providerImplementation = blogSystemB
}

export const getBlogBySlug = providerImplementation.getBlogBySlug


text:
Q: How to read all files in Android/media directory including folders with a .nomedia file programmatically in Android 11 I want read files in Android/media/x.com/.dir without using All file access permission in android 11.
x.com is not the my app's package name, .dir is a another app's media directory. Also it contains .nomedia file. So is it possible to read files in .dir directory. I know that we can do it with MANAGE_EXTERNAL_STORAGE permission. But it is difficult to publish app with this permission in PlayStore and also my app only need to access files in media directory. The problem is that folder which I want read contains a .nomedia file. Is there any way to do that without MANAGE_EXTERNAL_STORAGE permission.


text:
Q: Can Azure storage account (files) be mounted on multiple servers? I am using storage accounts (files) as a mount point on a Linux server. It's being used to storage media files.
Can the same volume be mounted on another Linux server? Will this cause issues?
The goal is to have multiple servers sharing the media files, for read and write purposes.

A: If you're referring specifically to Azure File Storage, which is an SMB 3.0 share that sits atop Azure Storage, then yes - you may mount this file storage to multiple VMs. Since you mentioned Linux: There's currently a limitation where the VM must be in the same region as the file share (see this article for more details).
If you're referring to Azure blobs directly (specifically, a vhd mounted as a disk), then no - a vhd may only be mounted to a single VM (and there's a blob lease preventing any other VM's from also mounting that vhd as a disk).


text:
Q: Code Signing Error with fastlane I am getting error while building my application through fastlane. It gives me error that

Code Signing Error: No profile for team '4TM2DK894Y' matching 'match
  Development bundle-id' found:  Xcode couldn't find any provisioning
  profiles matching '4TM2DK894Y/match Development bundle-id'.

I was able to do that but I ran the command mistakenly fastlane match --readonly and it installed new profiles and certificates I guess. After that I am continuously getting this error.
While I am able to archive and export the build manually through Xcode.
Anyone has clue how to fix this issue?


text:
Q: Why this always save data even if those fields are empty? I have this model http://pastebin.com/tSaTvLxW and this is my Controller http://pastebin.com/iWeyvF71 and this is the associated view add.ctp http://pastebin.com/YWqwMtqx but when I add a new Information record and even if Education, Experience are empty always records are created in the respective tables and I don't know what cause that behaviour, can any help me to find this?

A: When I run this, I see the following in the $this->request->data :
Array
(
    [Information] => Array
        (
            [name] => Test
            [lastname] => Name
            [email] => test@example.com
            [mobile_phone] => 1561561566
            [home_phone] => 1521521522
            [address] => 123 Any Street
            [other_information] => Other information
            [picture] => Array
                (
                    [name] => avatar.png
                    [type] => image/png
                    [tmp_name] => /tmp/php2Jvveh
                    [error] => 0
                    [size] => 89486
                )

        )

    [Education] => Array
        (
            [0] => Array
                (
                    [education_content] =>
                )

        )

    [Experience] => Array
        (
            [0] => Array
                (
                    [experience_content] =>
                )
        )
)

You will notice that the Education array and the Experience array, while empty, still exist in the $this->request->data. Because you are using the $this->Information->saveAll($this->request->data), it will save an empty set of data to the table. If you do not want to save empty data, check the array to see if it is empty. If it is, unset it before you saveAll. The way you have your form setup, it would be something like this:
if (empty($this->request->data['Experience'][0]['experience_content'])) {
    unset($this->request->data['Experience']);
}
if (empty($this->request->data['Education'][0]['education_content'])) {
    unset($this->request->data['Education']);
}
$this->Information->create();
    if ($this->Information->saveAll($this->request->data)) {
    ...snip...


text:
Q: Using SimpleDateFormat as a String for filenames I'm currently creating an app that saves data into the disk. I want the file name of the files to be the current date. I tried using SimpleDateFormat for this purpose, but I don't know how I could convert it to a string. Its toString() method isn't being overrided from Object, therefore I don't get a valid result back.
This is the code:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
...
ImageIO.write(capture, "png", new File(sdf.toString() + ".png"));

How do I represent that date/time format as a string?
Complete code:
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.imageio.ImageIO;

public class Screenshot {

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

    public static void fullScreenshot() {
        Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());

        try {
            BufferedImage capture = new Robot().createScreenCapture(screenRect);
            ImageIO.write(capture, "png", new File(sdf.format(new Date()) + ".png"));
        } catch (IOException e) {
            System.err.println("Thrown exception at IO file save");
        } catch (AWTException e) {
            System.err.println("Insufficient permissions or explosion while screenshoting");
        }
    }
}

A: you should do
sdf.format( new Date() );

This will work!

A: You're looking for sdf.format(new Date()). A DateFormat is not initialized with any date, you have to pass the date to its format method (or a string to its parse one).

A: only pass the date on format method
sdf.format(new Date().getTime())

A: You can do :
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
sdf.format(new Date().getTime());

or
String fName = String.valueOf(new Timestamp(new Date().getTime())); // it ll give you current timestamp

ImageIO.write(capture, "png", new File(fName + ".png"));

or
ImageIO.write(capture, "png", new File("Name" + fName + ".png"));

in both case Date() from java.sql package.


text:
Q: Populating data to individual columns in pandas dataframe I am trying to get the data from the list (list_addresses) and populate it to different columns of the dataframe (dfloc). I use the below code, not sure where I am going wrong.
Values are present in list_addresses but not getting populated to the dataframe.
Any help would be appreciated.
for index in range(len(list_addresses)):
 location = geolocator.reverse([list_addresses[index][0],list_addresses[index][1]])
 dfloc.loc[dfloc.Latitude] = list_addresses[index][0]
 dfloc.loc[dfloc.Longitude] = list_addresses[index][1]
 dfloc.loc[dfloc.Address] = location.address

A: So it looks like you have a list of lists or tuples with form of [(Lat1,Lon1),(Lat2,Lon2), etc...].  I like to make a list for each column, then assign the entire column at once:
lat_list = [x[0] for x in list_addresses]
lon_list = [x[1] for x in list_addresses]
address_list = []

for index in range(len(list_addresses)):
    location = geolocator.reverse([list_addresses[index][0],list_addresses[index][1]])
    address_list.append(location.address)

dfloc['Latitude'] = lat_list
dfloc['Longitude'] = lon_list
dfloc['Address'] = address_list


text:
Q: Iterate over cells contained in range contained in array I'm trying to iterate over every cell in a range. In the past, I have been able to do this by using the following:
Function iterateOverEverything(someRange) As Integer
    Dim cell As range
    For Each cell In someRange
        doSomething(cell)
    Next
    iterateOverEverything = 3
End Function

The above code works.
The issue is that I am trying to create a function that is given multiple ranges, and iterates over them separately - I do not want to union the ranges, and it is imperative that I be able to compare multiple ranges. My current strategy is to use an array of ranges, then for each every cell in the range. Consider the following code:
Function iterateOverMultipleRanges(rangeZero, rangeOne) As Integer
    Dim ranges(1) As range
    ranges(0) = rangeZero
    ranges(1) = rangeOne
    Dim cell As range

    For i = 0 To UBound(ranges) - 1
        For Each cell In ranges(i)
            doSomething(cell)
        Next
    Next
    iterateOverMultipleRanges = 3
End Function

The above code does not work.
I believe I've determined the issue: the for each is unable to iterate over the contents of the array, for some reason. To run into this issue, attempt to run the following code:
Function iterateOverMultipleRanges(rangeZero, rangeOne) As Integer
    Dim ranges(1) As range
    ranges(0) = rangeZero
    ranges(1) = rangeOne
    Dim cell As range
    For Each cell In ranges(1)
            doSomething(cell)
    Next
    iterateOverMultipleRanges = 3
End Function

The above will throw an error.
How am I supposed to iterate over multiple ranges? What am I missing?
Note that I was unable to find any identical questions, but due to my lack of familiarity with the issue it is completely possible this is closely related to a different question.
Thanks!
EDIT: For additional information regarding answer, see mwolfe02's answer: https://stackoverflow.com/a/5042718/8133062

Property Set is for objects (e.g., class instances),
Property Let is for "normal" datatypes (e.g., string, boolean, long, etc.)

A: You need to use Set when assigning objects:
Function iterateOverMultipleRanges(rangeZero As Range, _
                                   rangeOne As Range) As Integer
    Dim ranges(1) As range
    Set ranges(0) = rangeZero
    Set ranges(1) = rangeOne
    Dim cell As range

    For i = 0 To UBound(ranges) - 1
        For Each cell In ranges(i)
            doSomething(cell)
        Next
    Next
    iterateOverMultipleRanges = 3
End Function


text:
Q: Simple Injector is missing one of the open generic types after it is registered - what might be happening? I'm having some difficulty with registering some open generic types with simple injector.
In startup I am registering in the following way..
 var assemblies = LoadAssemblies("MyProjectName");
 _container.Register(typeof(IMessageProcessor<>), assemblies, Lifestyle.Singleton);

When I try to get an instance one of them is missing. If I try to explicitly register the instance I get an error that it is already registered so i'm a bit lost as to what is happening.
I have checked the classes and they all look the same and exist in the same assembly.
The interfaces look like...
public interface IBaseMessageProcessor
{
    Task Process<T>(T message);
}

public interface IMessageProcessor<T> : IBaseMessageProcessor where T : BaseMessage
{
    Task Process(T message);
}

There are multiple examples that implement these interfaces that look like..
public interface IAssignToMultipleMessageProcessor : IMessageProcessor<AssignToMultipleMessage> { }

public interface IReturnBenefitMessageProcessor : IMessageProcessor<ReturnBenefitMessage> { }

public interface IAssignWelcomeBenefitsMessageProcessor : IMessageProcessor<AssignWelcomeBenefitsMessage> { }

In total there are six like IMessageProcessor<> where the Messages all inherit from BaseMessage
The concerete example of the above three look like this..
public class AssignToMultipleMessageProcessor : IAssignToMultipleMessageProcessor
{
    public async Task Process(AssignToMultipleMessage message)
    {
        await Task.CompletedTask;
    }

    public async Task Process<T>(T message)
    {
        if (message is AssignToMultipleMessage assignToMultipleMessage)
        {
            await Process(assignToMultipleMessage);
        }
    }
}

public class ReturnBenefitMessageProcessor : IReturnBenefitMessageProcessor
{
    public async Task Process(ReturnBenefitMessage message)
    {
        await Task.CompletedTask;
    }

    public async Task Process<T>(T message)
    {
        if (message is ReturnBenefitMessage assignToMultipleMessage)
        {
            await Process(assignToMultipleMessage);
        }
    }
}

public class AssignWelcomeBenefitMessageProcessor : IAssignWelcomeBenefitsMessageProcessor
{
    public async Task Process(AssignWelcomeBenefitsMessage message)
    {
        await Task.CompletedTask;
    }

    public async Task Process<T>(T message)
    {
        if (message is AssignWelcomeBenefitsMessage assignWelcomeBenefitsMessage)
        {
            await Process(assignWelcomeBenefitsMessage);
        }
    }
}

When I debug the startup the container shows all six instances are in the LifeStyleRegistrationCache of the container as Singletons.
Later when trying to get the instance...
var instance = scope.GetInstance<IAssignWelcomeBenefitsMessageProcessor>();

All six are still present in the LifeStyleResistrationCache as Singletons  but the error is thrown
No registration for type IAssignWelcomeBenefitsMessageProcessor could be found.
In the LifeStyleRegistrationCache it shows {[{Name = AssignWelcomeBenefitMessageProcessor FullName = MyAppName.MessageProcessing.AssignWelcomeBenefitMessageProcessor}, {System.WeakReference}]}
The SerializationStackTraceString says...
at SimpleInjector.Container.ThrowMissingInstanceProducerException(Type type)\r\n   at SimpleInjector.Container.GetInstanceFromProducer(InstanceProducer instanceProducer, Type serviceType)\r\n   at SimpleInjector.Container.GetInstanceForRootType(Type serviceType)\r\n   at SimpleInjector.Container.GetInstance(Type serviceType)\r\n   at SimpleInjector.Scope.GetInstance(Type serviceType)\r\n   at SimpleInjector.Scope.GetInstance[TService]()\r\n
All the other five instances can be successfully resolved in the same way but this one is failing. Would really appreciate some help on this if anyone can point me in the right direction.
Cheers :)