text:
Q: Configuring existing Citrix XenApp farm to also works as a Windows RDS farm We're looking into providing a Citrix XenApp 6.5 farm and Windows Server 2008 R2 RDS farm for the users using the same server resources. Please notice that, why/why not, isn't really the question here.

*

*Would it be possible to host both Citrix farm and RDS farm functionality on the same servers.

Just reading about it I'm not aware of any problems, but that's almost the case with all things technical, it's not until you actually implement it that the issues starting to arrive. Has anyone actually done this?
Today the infrastructure consists of:

*

*2 servers holding the Citrix Web Interface and Citrix Secure Gateway roles

*2 servers holding the Citrix Licensing/RD Licensing

*2 servers holding the Citrix Data Collector role

*20 servers holding the Citrix Host-Mode role

The idea is to add the Windows RDS roles onto the existing Citrix XenApp servers:

*

*2 servers holding the Citrix Data Collector and RD Connection Broker roles

*20 servers holding the Citrix Host-Mode and RD Session Host roles

The RDS farm should not be available from outside the company network, towards the RDS farm end users would only connect to the desktop from the thin client. The thin client will have the RDP client preconfigured for the RDS farm if they should use that. In all other scenarios the Citrix solution would be configured for the end user.
Probably some scenarios (and hundreds more) to think about:

*

*How would the two different solutions load balance users between servers as they probably not aware of each other

*Will Citrix have issues with licenses as users can, in theory, connect both through the Citrix and the RDS

*Will RDS have issues with licenses due to the scenario above

Appreciate any input/experience on the subject of the matter. Will edit the post to add more details if needed/down the road.

A: This is implemented and tested for Windows Server 2008 R2, it's however not extensively tested. There are major licensing issues with this setup.
It's possible to have Citrix farm and RDS farm functionality on the same servers. This implementation is done with DNS round robin, connection broker load balancing, redirection with ip address. Maintenance on servers require to logon with mstsc /v:IP /admin to get the correct server, or remotely manage with admin tools. At the moment the RD Connection Broker is a s.p.o.f.

*

*Licenses

Issues has been seen that if there are no Citrix licenses available, this also affects the RDS farm and user can not logon there either, this could probably however just be an configuration issue (not been investigated). The RDS servers are "per user". Regarding Citrix this is configured for concurrent.
This means that each RDP session towards a server also running the Citrix application will also take a Citrix license. There are therefor no purpose off trying to run CTX and RDS on same server and use RDS for saving licenses for those users that don't need CTX functionality

*

*Sessions

Citrix uses ICA protocol, RDS uses RDP protocol. You'll need to configure for both if you for example don't want new users to connect to the server due to maintenance.
They won't be aware of each other regarding sessions, meaning, a user (the same) connecting to the Citrix farm and then to the RDS farm will get two separated sessions.
They won't be aware of each other regarding load balancing, but Citrix will however be aware of the server load based on the configuration, take that in account.
RDS is also somewhat, ineffective, then load balancing based on the Connection Broker service.

*

*Applications

RDS farm (2008 R2) cannot be selective with what applications and such is available per server, therefore only add those servers that are exactly the same as the Citrix servers. For example only servers that delivers a whole desktop and all have the same applications.

*

*Certificates

For the RDS farm you'll need to handle the certificates (a certificate containing both the farm name and each server within the farm) if you don't reconfigure RDP for RDP Security Layer.
Extending this answer/Corrections to this answer is encouraged.


text:
Q: How to write a specific MySQL query to perform a relational division/ intersect? Id est, what query do I write? I'm having trouble understanding how to write a specific MySQL query to perform a relational division/ intersect. I have looked at the following links/ SO questions, but I'm still confused :
MySQL equivalent of IN() clause doing Logical AND ; Relational Algebra : Division ; Divided we Stand ; Advanced SQL : Intersect ; Doing INTERSECT and MINUS in MySQL and Alternative to INTERSECT in MySQL
I attempted to adapt the SQL query shown in "Alternative to INTERSECT in MySQL", but got lost in the implementation.
Pseudocode :
Want : package.* from package WHERE package.pkid equalto package_products.pkid AND package_products.pid is_all_of (
    WANT : option_products.pid FROM option_products
    WHERE option_products.oid = [optionID]
), // returning packages that have all of the product IDs (pids) and not just one of them.
[OptionID] = $option

MySQL (inside db_query() :
"SELECT package.* FROM package WHERE package.pkid = package_products.pkid && package_products.pid is_allof(".
    // What do I use in place of 'is_all_of'? How do I do an intersection/ relational division with INNER JOIN and/ or USING(pid)?
"    SELECT options_products.pid FROM options_products WHERE options_products.oid = :option
)", array(":option" => $option )

A: Maybe I am missing something here, but I'd say that
db_query("SELECT package.* FROM package
WHERE package.pkid = package_products.pkid
&& package_products.pid IN
(SELECT options_products.pid FROM options_products
WHERE options_products.oid = %d)", $option));

should work for you.
I have rewritten your syntax to meet Drupal 6 db_query requirements (http://api.drupal.org/api/drupal/includes!database.mysql-common.inc/function/db_query/6).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Gradle, iterating over the downloaded dependency Jar's and extract a specific file using Gradle Task Once Gradle has downloaded the dependencies I'm trying to iterate over each jar file, extract a specific file, swagger yml, into a folder. However, when I execute the task it returns NO-SOURCE.
The task to extract the file into a folder:
task unzip(type: Copy) {
    configurations.artifact.asFileTree.each {
        from zipTree(it).matching { include "OpenApi-*.yml" }
        into 'swaggerExtract/'
    }
}

build.gradle
repositories {
    mavenLocal()
}
configurations {
    artifact
}

dependencies {
    artifact 'com.example.android:accounts-service:0.0.2-SNAPSHOT'
    artifact 'com.example.android:my-service:0.0.4.RELEASE'
}

apply plugin: 'java'


text:
Q: how to copy certain type files from remote server to local with id and password? I am a greenhand in bash so please be patient with me. Thank you.
I am writing a bash script. There are three arguments: server, login id, and password. I want to copy all of the files in the id's home directory on the server with .c extension as well as encryption executable: encryptor to my current directory.
I tried to using scp and expect, but I have other code that need to run under #!/bin/bash, so that using expect won't work. Please suggest how could I implement this. Thank you very much!!
Difference from scp or sftp copy multiple files with single command:

*

*The id and password are command line argument when run the script so
that I do not need to type in password after the script starts. For
example, it works as "./example.sh server id password".

*I don't know the structure of the home directory on the remote server. Is there any way to select certain file and copy them to local using command in one bash script? will grep work? How to combine it with scp?

A: You may need to use public key authentication with ssh in order to accomplish this without expect. Generate an RSA key pair and place it in the authorized_keys file in the remote host.
Here are the steps:
https://sureshvv.wordpress.com/2009/04/07/how-to-setup-ssh-so-that-manual-password-entry-is-not-needed/
Here is the full background:
https://www.digitalocean.com/community/tutorials/how-to-configure-ssh-key-based-authentication-on-a-linux-server


text: Q: Does Logic Pro X require GarageBand's instrument library? I've formerly have GarageBand and its instrument library installed, but since then I have "upgraded" to Logic Pro X and uninstalled GarageBand. Recently I've been running low on storage and found a bunch of music creation files labelled under "GarageBand". I'm wondering whether these files are used by Logic Pro X, or are they just leftover GarageBand files that didn't get deleted? Is it safe to remove them without messing up Logic Pro X?


text:
Q: How to create Custom form I am new to magento.
I want to create a new forms in my magento website. Some form have to add in the cms pages.
I got reference from This Question
I tried to create pages same like it. but it is not displaying anything.May b its beacause I am using Luxury theme. Help me placing files.
This is my theme path app\design\frontend\mgstheme\luxury
I tried placing file here app\design\frontend\mgstheme\luxury\templateeasylife_customform/form.phtml as Marius told in that answer
What i am doing wrong?
Thankyou

A: You need to verify this things,
Your frontend layout file is put in proper theme or not.
In above case you put file here.
app/design/frontend/mgstheme/luxury/layout/easylife_customform.xml

Do magento caching and reindexing.
Now try to access with URL.

A: if you want your form show in yourfile.phtml then paste it's code..
if you want to show this form as separate CMS page then create CMS page from CMS menu > Pages & place the below code in it
{{block type="formbuilder/frontend_form" name="frontend_form" form_id="1" template="formbuilder/form.phtml"}}

(replace form_id with your form_id, see form_id from Admin panel > Form Builder menu > Manage Forms)


text:
Q: C - Passing dynamic allocated 3D Matrix to function In my main function i create a dynamic 3D array and succesfull alocate it.
    int ***board = (int ***)malloc(counter * sizeof(int **));
    for(int i = 0; i < counter; i++){

        board[i] = (int **) malloc(dimension[i] * dimension[i] * sizeof(int));
    }

Then i wan to pass it to a function defined as:
void readPuzzle(int board[][MAX][MAX], int *dimension, int counter,const char *);

I pass it like this:
readPuzzle(board, dimension, counter, argv[1]);

But i keep getting this error, i searched for it but never could fix it!
main.c: In function 'main':
main.c:22:13: warning: passing argument 1 of 'readPuzzle' from       incompatible pointer type [-Wincompatible-pointer-types]
readPuzzle(board, dimension, counter, argv[1]);
         ^~~~~
In file included from main.c:4:0:
headers.h:7:6: note: expected 'int (*)[100][100]' but argument is of type     'int ***'
void readPuzzle(int board[][MAX][MAX], int *dimension, int counter, const char *);

A: If your 2D arrays have variable dimensions, you need int ***, but this prototype
void readPuzzle(int board[][MAX][MAX], int *dimension, int counter, const char *);

isn't compatible with board passed as int *** because it required an array of 2D arrays, not a triple pointer.
So fix it like that:
void readPuzzle(int ***board, int *dimension, int counter, const char *);

but you still need to keep track of the dimensions for each "slice".
The alternative, if the 2D arrays have fixed dimensions MAX*MAX is to allocate an array of 2D arrays like this:
int (*board)[MAX][MAX] = malloc(counter*sizeof(*board));

now you can pass board as int board[][MAX][MAX]. Of course, if not all data is used, you still need to keep track of max dimensions somewhere.


text: Q: Can the identity permutation be expressed as a product of disjoint transpositions? I can only think of expressing it as the product of zero disjoint transpositions, but I don't know if the product of zero transpositions is even defined, or if it equals identity.


text:
Q: what values of $j$ makes this congruence solvable? For what values of $j$ is this congruence solvable?
$$0 \equiv xp^{a+s-b}j + yp^t\pmod{p^b} $$ where $p$ is an odd prime and $x,y$ are not divisible by $p.$ and $s,a$ are any integers.
Since the given congruence above is equivalent to $xp^{a+s−b}j + yp^t = k p^b $ for some $k$; and then I have to divide both sides by $p^m$ where $m= \operatorname{min} \{a+s−b,t,b\}$, then how can I know the values of $j$ that makes this congruence solvable (what stuck me is that the value of $m$ is not clearly specified)? could you please help me in answering this question?
EDIT:
I assumed that $a \geq b.$

A: Since you do not know which of the quantities is minimal you can split the problem up into different cases. I presume we can assume that $a+s-b\ge 0$.
If $m=b$
Then the equation is satisfied for all $j$.
If $m\ne b, a+s-b=m$
Then $xj + yp^{t-m} = k p^{b-m}$ and the equation can be solved if and only if $j$ is a multiple of $p^n$, where $n$ is the minimum of $t-m$ and $b-m$.
If $m\ne b, a+s-b\ne m$
Then $xjp^{a+s-b-m} + y = k p^{b-m}$ and since $p$ is not a factor of $y$ there are no solutions.


text: Q: How to open WhatsApp using angular and android I have an angular app and converted to android app using android studio. In my app there is button called message on WhatsApp on click of that WhatsApp should open but in my case its not working. Getting error like webpage not available.


text:
Q: Showing a parametrized curve is orthogonal
Let $\alpha : \mathbb{I}\to \mathbb{R}^3$ be a parametrized curve,
  with $\alpha'(t) \ne 0$ for all $t\in I$. Show that $|\alpha(t)|$ is a
  nonzero constant if and only if $\alpha(t)$ is orthogonal to
  $\alpha'(t)$ for all $t\in \mathbb{I}$.

I became really rusty with vector calculus because of a long break (I should have never done that).
So far I got:
Let,
$\alpha(t) = (x(t), y(t),z(t)),\text{then}$
$\alpha'(t) = (x'(t), y'(t),z'(t))\ne0 $
$|\alpha(t)|= D= \sqrt{x^2+y^2+z^2},\ D'=\frac{xx'+yy'+zz'}{\sqrt{x^2+y^2+z^2}} $
If $\alpha(t)\dot\ \alpha'(t)=0$ then $xx'+yy'+zz'=0$.

A: We have $\vert \alpha(t) \vert^2 = \alpha(t) \cdot \alpha(t) = c$, $c$ a constant.  Then
$\frac{d}{dt}(\alpha(t) \cdot \alpha(t)) = 0$,
but
$\frac{d}{dt}(\alpha(t) \cdot \alpha(t)) = \dot{\alpha}(t) \cdot \alpha(t) + \alpha(t) \cdot \dot{\alpha}(t) = 2 \alpha(t) \cdot \dot{\alpha}(t) = 0$,
whence
$\alpha(t) \cdot \dot{\alpha}(t) = 0$.
Sorry about switching up the notation from $\alpha'(t)$ to $\dot{\alpha}(t)$; old dawgs, new tricks; you know how it is! ;)

A: Try this.
Proof
Suppose $|\alpha (t)| \neq 0$, then so does $|\alpha(t)|^2 = \alpha(t) \cdot \alpha(t)$. Differentiating both sides yield $2\alpha'(t)\cdot\alpha(t) = 0 \implies \alpha'(t)\cdot\alpha(t) = 0 $
On the other hand, suppose we have $\alpha'(t)\cdot\alpha(t) = 0$ instead. Consider $|\alpha(t)|^2 = \alpha(t) \cdot \alpha(t)$  again. This time around we have $(|\alpha (t) |^2)' = 2\alpha'(t)\cdot\alpha(t) = 0$ where the RHS of the equation comes from our orthogonal assumption.
This means that $(|\alpha (t) |^2)' = 0 \implies |\alpha (t) |^2 = c$ for some positive constant $c$. Taking the square root gives the desired result.


text:
Q: Ruby 2.6.0 installation fails on MacOS with rbenv I have a Mac on Mojave, and it's failing to install some of the basic stuff required for development:
$ rbenv install 2.6.0

Downloading openssl-1.1.1d.tar.gz...
-> https://dqw8nmjcqpjn7.cloudfront.net/1e3a91bc1f9dfce01af26026f856e064eab4c8ee0a8f457b5ae30b40b8b711f2
Installing openssl-1.1.1d...

BUILD FAILED (OS X 10.14.6 using ruby-build 20191223)

Inspect or clean up the working tree at /var/folders/l_/xgbzwc3j0xn_cb74550m71vr0000gn/T/ruby-build.20191225225406.18503.lq8QNM
Results logged to /var/folders/l_/xgbzwc3j0xn_cb74550m71vr0000gn/T/ruby-build.20191225225406.18503.log

Last 10 log lines:
      _s_server_main in s_server.o
  "_verify_stateless_cookie_callback", referenced from:
      _s_server_main in s_server.o
  "_wait_for_async", referenced from:
      _s_client_main in s_client.o
      _sv_body in s_server.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[1]: *** [apps/openssl] Error 1
make: *** [all] Error 2

I found several blogposts talking about how the Mojave release has broken a few things for developers, but none of the articles provide a solution. Has anyone else faced the issue described above?

A: Reposting my response from this other thread - I was facing a similar issue and can recommend the approach below that's related to binutils needing to be uninstalled first. What worked for me:
brew uninstall binutils
# Uninstalling /usr/local/Cellar/binutils/2.33.1... (134 files, 167.6MB)

rbenv install 2.6.5 && rbenv local 2.6.5 ;
# Downloading openssl-1.1.1d.tar.gz...
# -> https://dqw8nmjcqpjn7.cloudfront.net/1e3a91bc1f9dfce01af26026f856e064eab4c8ee0a8f457b5ae30b40b8b711f2
# Installing openssl-1.1.1d...
# Installed openssl-1.1.1d to /Users/auser/.rbenv/versions/2.6.5

# Downloading ruby-2.6.5.tar.bz2...
# -> https://cache.ruby-lang.org/pub/ruby/2.6/ruby-2.6.5.tar.bz2
# Installing ruby-2.6.5...
# ruby-build: using readline from homebrew
# Installed ruby-2.6.5 to /Users/auser/.rbenv/versions/2.6.5

Prior to this the I was also getting a number of varying messages in ruby-build.log - with the last being:
# ld: symbol(s) not found for architecture x86_64

A number of other steps that I took as part of my homebrew setup (prior to uninstall) included:
brew install perl ruby rbenv
# // UPDATE PATHs with suggestions made by brew during install
which awk perl
# /usr/local/bin/awk
# /usr/local/bin/perl
# ^^^ IN SHORT ALL PATHs should be with /usr/local/opt OR /usr/local/bin

You can re-install binutils again after as needed and remember to repeat the uninstallation with any future rbenv install version(s) that you're likely to re-execute (note to self).
PS - tested on macOS Catalina 10.15.3 (19D76) successfully installing both 2.4.0 & 2.6.5


text:
Q: How to get max and min of mysql column from another related table in Laravel this is my database tables

*

*Lists

*Requests

*products

Every request has one product and every list has many requests
now i want to get the min and max price/size for the products in list X , how can i achieve this with Laravel Elequent  ?
Lists table
+----+----------+
| id | user_id  |
+====+==========+
| 1  | 1        |
+----+----------+
| 2  | 1        |
+----+----------+
| 3  | 2        |
+----+----------+

Requests table
+----+-------------+----------+
| id | product_id  | list_id  |
+====+=============+==========+
| 1  | 1           | 1        |
+----+-------------+----------+
| 2  | 1           | 1        |
+----+-------------+----------+
| 3  | 2           | 2        |
+----+-------------+----------+

Products table
+----+-------+------+-------+
| id | price | size | other |
+====+=======+======+=======+
| 1  | 110   | 10   | test  |
+----+-------+------+-------+
| 2  | 130   | 12   | test  |
+----+-------+------+-------+
| 3  | 100   | 24   | test  |
+----+-------+------+-------+
| 4  | 200   | 16   | test  |
+----+-------+------+-------+

A:
I want to get the min and max price/size for the products in list X

$maxSize = Product::whereHas('request.list', function($q) use($listId) {
    $q->where('list.id', $listId);
})
->max('size');

$minSize = Product::whereHas('request.list', function($q) use($listId) {
    $q->where('list.id', $listId);
})
->min('size');

Do the same for the min and max price.


text:
Q: I want to implement javamelody in livyServer, Please let me how can i do this Hi I need to implement the javamelody so that i can know how much time is consuming by which call. SO please help me to implement this.

A: Just add below code in LivyServer.scala and javamelody and jrobin dependency in pom.xml
import net.bull.javamelody._
// JavaMelody Filter
val melodyHolder = new FilterHolder(new MonitoringFilter())
melodyHolder.setInitParameter(Parameter.AUTHORIZED_USERS.getCode(), "username:password")
melodyHolder.setInitParameter(Parameter.STORAGE_DIRECTORY.getCode(), "/tmp/javamelody")
server.context.addFilter(melodyHolder, "/*", EnumSet.allOf(classOf[DispatcherType]))


text:
Q: Replacing characters from string one to string two I need to create a function that takes the parameters (character, stringOne, stringTwo). The function returns a new word  which contain the same data as stringTwo + whatever characters in stringOne in the same position.
Example:

*

*stringOne = "apple"

*stringTwo = "12345"

*character = "p"

*Should Return "1pp45"

I am lost on how I should proceed.
def replace(char, word1, word2):
newWord = ""
for s in range(len(word1)):
    if word1[s] == char:
return

A: Continuing what you have done, using simple for-loop and ternary operation, this is how it can be done:
def replace(char, word1, word2):
    newWord = ""
    for s in range(len(word1)):
        newWord += char if word1[s] == char else word2[s]
    return newWord

Which is equivalent to:
def replace(char, word1, word2):
    newWord = ""
    for s in range(len(word1)):
        if word1[s] == char:
            newWord += char
        else:
            newWord += word2[s]
    return newWord

Just in case you are not familiar with ternary operation.

A: Here's how to modify your existing code so that it does what you want. I've changed newWord to new_word to conform with the standard Python style convention.
def replace(char, word1, word2):
    new_word = ""
    for i in range(len(word2)):
        if word1[i] == char:
            new_word += char
        else:
            new_word += word2[i]
    return new_word

# Test
print(replace("p", "apple", "12345"))

output
1pp45

Note that this code will raise an IndexError: string index out of range exception if word1 is shorter than word2.
There are various better ways to implement this function. Firstly, we can use the zip function to iterate over the characters of both strings in parallel. This is a bit cleaner than your indirect iteration using the indices of the strings to access the characters.
def replace(char, word1, word2):
    new_word = ""
    for c1, c2 in zip(word1, word2):
        if c1 == char:
            new_word += char
        else:
            new_word += c2
    return new_word

Note that if the strings aren't the same length then zip will stop gracefully when the shorter string finishes.
We can make that code more compact by replacing the if... else block with a conditional expression.
def replace(char, word1, word2):
    new_word = ""
    for c1, c2 in zip(word1, word2):
        new_word += char if c1 == char else c2
    return new_word

A more advanced version uses a list comprehension to build a list of the desired characters and the string .join method to convert that list into a string.
def replace(char, word1, word2):
    return ''.join([char if c1 == char else c2
        for c1, c2 in zip(word1, word2)])

It's also possible to do this using a generator expression.
''.join(char if c1 == char else c2 for c1, c2 in zip(word1, word2))

However that's less efficient than using a list comprehension, due to the way that .join works. .join has to scan its argument twice: the first scan is used to calculate the total size of the output string, the second scan does the actual joining. But you can't scan a generator twice, so if you pass .join a generator it has to build a temporary list from the generator.

A: You can also use a list comprehension, iterate and replace.
>>> x, y, c = 'apple', '12345', 'p'
>>> ''.join([c if x[i] == c else s for i, s in enumerate(y)])
'1pp45'

A: Pythonic way:
>>> stringOne = "apple"
>>> stringTwo = "12345"
>>> my_char = "p"
>>> "".join([x[1] if my_char!=x[0] else x[0] for x in zip(stringOne, stringTwo)])
'1pp45'

A: def replace(char, word1, word2):
    newWord= list(word2)
    for counter in range(min(len(word1), len(word2))):
            if word1[counter]== char:
                    newWord[counter]= char
    return "".join(newWord)

A: The simplest solution would be to iterate through characters of word1 and if a character match is found with the character that we are interested in finding, then we replace the character at that index in word2.
def replace(char, word1, word2):
    newWord = ""
    word2List = list(word2)
    # Check is character is present in word1
    # and if length of word1 and word2 are equal
    if char not in word1 or len(word1) != len(word2):
        return False
    else:
        for i,c in enumerate(word1):
            if c == char:
                word2List[i] = c

    # Converting list back to string
    return ''.join(word2List)

print(replace('p','apple','12345'))

Output:
1pp45


text:
Q: AttributeError: 'tuple' object has no attribute 'encode' Arduino and MySQL I need to read some numbers sent by an Arduino via the serial port and then insert these numbers into a MySQL table.
This is my code:
import mysql.connector, serial

ser = serial.Serial(port='/dev/ttyACM3', baudrate='9600')
ser.isOpen()
read_port = ser.readline()
print (read_port)
mysql_connection = mysql.connector.connect(host="localhost", user="optim_admin", passwd="marcopolo", database="optimbit_acces")
cursor = mysql_connection.cursor()
sql1 = "insert into check_in (card, checkin) values (%s, Now()); ", (read_port)
cursor.execute(sql1)
mysql_connection.close()

This is my error:
 Traceback (most recent call last):
  File "/home/admin1/Documents/OptimAcces/db_service_connect.py", line 10, in <module>
    cursor.execute(sql1, (str(read_port.decode('unicode_escape').encode('ascii', 'utf-8')), ))
  File "/usr/local/lib/python2.7/dist-packages/mysql/connector/cursor.py", line 492, in execute
    stmt = operation.encode(self._connection.python_charset)
AttributeError: 'tuple' object has no attribute 'encode'

Process finished with exit code 1

How can I fix this error?

A: You are entering wrong parameters syntax from your code. Try this:
 from time import gmtime, strftime

 date_time = strftime("%Y-%m-%d %H:%M:%S", gmtime())
 sql1 = "insert into check_in (card, checkin) values (%s, %s)"
 args = read_port, date_time
 cursor.execute(sql1, args)

The Error message that you are facing is because your query has wrong number of parameters and has more brackets not correct closed.
See below the signature for cursor.execute:
Definition: cursor.execute(self, query, args=None)
     query -- string, query to execute on server
     args -- optional sequence or mapping, parameters to use with query

Hope it helps!

A: Thanks to all. I solved the problem by switching the database to MariaDb from MySql. Now it works fine.
Thank you for your help.


text:
Q: Выбор точки появления в Unity3d Пытаюсь сделать переключение места появления(transform) в одном моём проекте. Выглядеть это должно так: в главном меню игры игрок выбирает точку появления (при помощи toggle), после чего скрипт сохраняет через PlayerPrefs.SetInt число, которое обозначает номер transforma для того, чтобы получить этот инт в другой сцене. И тут у меня возникает проблема: не знаю, как сделать, чтобы в другой сцене скрипт, "принимающий" это число спавнил игрока на выбранной точке. Пробовал сделать через if, но получил ошибку, т.к. это переменная int, а не bool.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class CarLoad : MonoBehaviour
{
[SerializeField] private Transform _carPos1;
[SerializeField] private Transform _carPos2;
public GameObject _car1;

void Start()
{
    PlayerPrefs.GetInt("LocNum");
}

void Update()
{
    if (PlayerPrefs.GetInt("LocNum", 1))
    {
        Instantiate(_car1, _carPos1.position, _carPos1.rotation);
    }
}
}

Или есть какой-нибудь другой вариант?
Подскажите, как можно решить эту проблему?

A:  if (PlayerPrefs.GetInt("LocNum", 1) == 1)

А еще лучше
int locNum = PlayerPrefs.GetInt("LocNum", 1)
switch (locNum)
      {
      case 1:
          Instantiate(_car1, _carPos1.position, _carPos1.rotation);
          break;
      case 2:
          Instantiate(_car1, _carPos2.position, _carPos2.rotation);
          break;
      default:
          //Действие при невалидных данных
          Instantiate(_car1, _carPos1.position, _carPos1.rotation);
          break;
  }

И конечно Instantiate надо сделать один раз, например, в Start.


text:
Q: Conditional Expectation Property on two sub-sigma fields with no further assumptions on the fields I was looking on some old notes on probability theory and I found the following
"Let $\left(\Omega, \Sigma, P\right)$ be some probability space, $\Sigma_1, \Sigma_2 \subseteq \Sigma$ be two sigma algebras and $X$ be some random variable. Prove or disprove the following:
$ \textrm E\left[ \textrm E\left[ X | \Sigma_1\right] | \Sigma_2 \right]
= \textrm E\left[ \textrm E\left[ X | \Sigma_2\right] | \Sigma_1 \right]
= \textrm E\left[ X | \Sigma_1 \cap \Sigma_2 \right]
$"
I think this is not in general true, unless if we add the
$\Sigma_1 \cap \Sigma_2$-measurability for both $\textrm E\left[ \textrm E\left[ X | \Sigma_1\right] | \Sigma_2 \right]
$ and $ \textrm E\left[ \textrm E\left[ X | \Sigma_2\right] | \Sigma_1 \right] $ (which tranfsorms the question to a standard property of the conditional expectation).
In the case $\Sigma_1 \cap \Sigma_2 = \left\{ \emptyset, \Omega \right\}$ then $ \textrm E\left[ X | \Sigma_1 \cap \Sigma_2 \right] $ should be constant, which is not necessarily the case with the other two conditional expectations.
Counterexample: When $\left(\Omega= [0,1) , \Sigma = \mathcal M_\lambda, P = \lambda\right)$ ($\lambda$ being the Lebesgue measure) define $ X : \Omega = [0,1) \longmapsto \mathbb R : t \longmapsto X(t) = \pi \sin(3\pi t)$, and $\Sigma_1 = \left\{ \emptyset, \Omega, \left[0, 1/3\right), \left[1/3, 1\right) \right\} $, $\Sigma_2 = \left\{ \emptyset, \Omega, \left[0, 2/3\right), \left[2/3, 1\right) \right\} $
Is this correct?

A: Yes, you are correct.  The quoted statement is false, and your counterexample is valid.


text:
Q: How do i read a special type of mail in a network share The mail item selected from a folder of a network share has a strange looking icon, different from the regular type (attached image). It may have something to do with reporting read/unread status of a received mail. Maybe a different class altogether.
How do I read this type of mail in VBA?

Dim oSel As Outlook.Selection

Set oSel = Outlook.Application.ActiveExplorer.Selection

Dim oEmail As Outlook.mailitem

Set oEmail = oSel.Item(1)    ' getting a 13 compile error in this line

A: You have a ReportItem object, not MailItem. Declare oEmail as a generic object, and either use the TypeName() function to figure out the actual object type or read the Class property (all Outlook objects expose it) - for MailItem objects it will be 43 (olMail).


text:
Q: Writing video with cv2.VideoWriter First off, I know this question has been asked before but nothing I've found has worked.
I just want to make a video out of a series of matrices, and I thought i had written it all correctly, but it isn't working. Here is the code snippet I am using to try and debug it:
import cv2
import numpy as np

print(cv2.__version__)
print(np.__version__)
gout = cv2.VideoWriter('temp.mp4', cv2.VideoWriter_fourcc(*'mp4v'), 100.0, (100, 100))
for i in range(100):
    mat = np.uint8(np.random.rand(100,100)*256)
    gout.write(mat)
gout.release()

The version of cv2 is 4.1.2 and the version of numpy is 1.17.4
I have tried different fourcc codes, and nothing is working. The video gets created, and it shows that it has data (it isn't 0kb in file explorer), but when I go to open it with VLC, the program spazzes out. The title bar flashes extrememly quickly back and forth from "temp.mp4 - VLC media player" to "VLC media player". (Other video players, like the windows Photos app don't work either)
It seems like somehow the video I am writing is corrupted, but I am really not sure how that's possible. It seems to me like this code snippet is about the simplest possible use case for cv2.VideoWriter and I can't see what part I could debug at this point.

A: Thanks to Dan Masek, I realized I was writing grayscale images into a color video.
gout = cv2.VideoWriter('temp.mp4', cv2.VideoWriter_fourcc(*'mp4v'), 100.0, (100, 100), False)

worked for me


text:
Q: Counting in different bases If you want to count over 8 bits, in base 2, the result is like this:
0 0 0 0 0 0 0 0;
0 0 0 0 0 0 0 1;
0 0 0 0 0 0 1 0;
.....
1 1 1 1 1 1 1 1;

But how can you make an algorithm that counts - for each bit - based on a different bases, ex:
If the least significant bit is counted according to base 5 and the most significant one is on base 2, the result should look like:
0 0 0 0 0 0 0 0;
0 0 0 0 0 0 0 1;
0 0 0 0 0 0 0 2;
0 0 0 0 0 0 0 3;
0 0 0 0 0 0 0 4;
1 0 0 0 0 0 0 0;
1 0 0 0 0 0 0 1;
1 0 0 0 0 0 0 2;
...
1 0 0 0 0 0 0 4;

Can you please give me the algorithm that generates these vectors?

A: One algorithm for this problem is the kind of "ripple-carry" addition most students typically learn in kindergarten, except slightly modified. When you add two numbers, you do so digit-by-digit: first the ones place, then the tens place, then the hundreds place, etc. If you would ever had to write down a number larger than 10 (e.g. 7+8=15), then you write it down minus-10 and "carry" the 10 over to the next place, where you add it (it becomes a 1); this might "ripple" over many places (e.g. 999+1=1000). By repeatedly adding one using this algorithm, we can count up one-by-one.
It is important to clarify what we're after: what does it mean for different places to have different bases. If you allow places to have arbitrary number ranges, and stand for arbitrary numbers, then some bad things can happen: a number can be written in more than one way, and/or some decimal numbers cannot be written. Therefore we will limit ourselves to a "sane" scheme where if a place i has a base bi, that means the valid digits are 0,1,2,...,bi-1 (as usual, just like in decimal), and that digits in that place represents bi times the product of all bases on the right (bi-1 x bi-2 x ...). For example, if our bases were [10,10,10], the values of the digits would be [1000,100,10,1]; if our bases were [5,10,5], the values of the digits would be [250,50,5,1]
How to add 1 to a number:
Increment the least-significant digit (LSD)
Perform ripple-carry as follows:
    Set the current place to the LSD
    Repeat as long as the current place exceeds its allowed max digit:
        Set the digit at the current place to 0
        Advance the current place one to the left
        Increment the number at the new place (now on the left)

Repeat the above algorithm until you have all numbers you desire.
Python:
from itertools import *

def multibaseCount(baseFunction):
    currentDigits = [0]
    while True:
        yield currentDigits[::-1]

        # add 1
        currentDigits[0] += 1

        # ripple-carry:
        for place,digit in enumerate(currentDigits):
            if currentDigits[place]>=baseFunction(place):    # if exceeds max digit
                currentDigits[place] = 0         # mod current digit by 10
                if place==len(currentDigits)-1:  # add new digit if doesn't exist
                    currentDigits += [0]
                currentDigits[place+1] += 1      # add 1 to next digit
            else:    # doesn't exceed max digit; don't need to carry any more
                break

Demo, where place n has base n+1:
>>> for digits in islice(multibaseCount(lambda n:n+1),30):
...     print( ''.join(map(str,digits)).zfill(5) )
...
00000
00010
00100
00110
00200
00210
01000
01010
01100
01110
01200
01210
02000
02010
02100
02110
02200
02210
03000
03010
03100
03110
03200
03210
10000
10010
10100
10110
10200
10210

A: If you're really only interested in eight-digit "numbers" of this format, here's some pseudo-code that will get you started:
for (a=0; a<2: a++)
  for (b=0; b<5; b++)
    for (c=0; c<2; c++)
      for (d=0; d<2; d++)
        for (e=0; e<2; e++)
          for (f=0; f<2; f++)
            for (g=0; g<2; g++)
              for (h=0; h<2; h++)
                printf("%d%d%d%d%d%d%d%d\n", a, b, c, d, e, f, g, h);

In this case, it'll be base 2, 5, 2, 2, 2, 2, 2, 2. Change the indices as you wish.

A: too late, but here is a solution in C.
#include <stdio.h>
#include <assert.h>

void
odo(int base, int len)
{
    int stack[len+1];
    int pos=0;
    #define DIGIT (stack[pos])
    #define LOOP(code) for(int i=0; i<len; i++) code
    #define PRINT LOOP(printf("%d", stack[i]));printf("\n");
    LOOP(stack[i]=-1);
    while(pos>=0)
    {
        if (pos<len-1)
        {
            if (DIGIT<base)
            {
                DIGIT++;
                pos++;
                assert(DIGIT==-1);
            }
            else
            {
                DIGIT=-1;
                pos--;
                continue;
            }
        }
        else
        {
            assert(pos==len-1);
            if (DIGIT<base)
            {
                DIGIT++;
                PRINT;
            }
            else
            {
                DIGIT=-1;
                pos--;
            }
        }
    }
}

int
main(void)
{
    odo(4,6);
}


text:
Q: Swift: array variable stored property is not mutable In my app, i'm declaring an array stored property as a variable. when i want to check if it contains and object, Xcode doesn't autocomplete. If i complete it manually it shows an error saying that it doesn't contain this method. I think it the array is not being mutable although it's declared as a var. Here is my code:
class someClass{
   var someArray = AnyObject[]()

   func someFunction{
     if someArray.containsObject("object") <--- error here
   }
}

A: Your code contains a bunch of syntax errors:

*

*There shouldn't be parentheses after class someClass

*There should be parentheses after func someFunction
But the error you noticed is that there is no method containsObject on Array. You can do:
contains(someArray, "object")

or you can cast it to an NSArray:
(someArray as NSArray).containsObject("object")

Edit
As Rob Napier correctly points out, the first option will (of course) only work on String[], not on AnyObject[]. Swift really discourages mixed arrays.

A: Array doesn't have a method containsObject. That's a method of NSArray.
You can use the filter method for the find() function.
You could also cast the Array to NSArray then call the containsObject.


text:
Q: plot nonlinear regression conf intervals in R Please help.
I have managed to fit a fairly decent nonlinear regression curve to my data using:
model2 <- nls(urine~a*(1-exp(-c*water)), data = eagle, start = list(a=550, c=0.00385))

and then I generate my plot using:
av <- seq(0,1200, 0.5)
bv <- predict (model2, data=eagle, list(water=av))
plot (urine~water, data = eagle)
lines (av,bv)

I want to draw on some dotted lines for upper and lower 95% confidence intervals.  I have managed to write code for my linear regression analyses but I am struggling with the current nonlinear regression.  The following code:
a <- predict (model2, newdata=data.frame(water=av), interval="confidence")

for linear regressions this gives me a dataframe with three columns for fit, lwr and upr.  With my nonlinear regression it just gives me a list of numbers which I cant do anything with.  Any suggestions?  Is there a simple way to get upper and confidence lines for a nonlinear regression?

A: se.fit isnt operating apparently.  Found lots of forums discussing the difficulties of fitting confidence intervals to non linear regressions in R.  After a whole day of searching and banging my head against the internet I finally found a very helpful formula.  Im not 100% sure how it works but it works so here it is for anyone else who needs to do this...
http://www.r-bloggers.com/predictnls-part-1-monte-carlo-simulation-confidence-intervals-for-nls-models/
Once you have produced your table of statistics for your predicted values based on a sequence of x values, you can access the lwr and upr CI value data in columns 6 and 7 of the output and plot that way.


text:
Q: What is the "substantial" role played by mutants in DC Comics? From http://en.wikipedia.org/wiki/Mutant_%28fictional%29#DC_Comics

Mutants play a smaller, but still substantial role in DC Comics

However, that particular Wiki article only mentions very few mutants (Captain Comet, and a couple of Batman adversaries), neither of whom strike me as important enough to warrant "substantial" role.
Was that expression inaccurate? Or are there really mutants who play genuinely substantial role in DC universe?

A: The issue at hand is the DC Universe's definition of mutant. Finishing off your quote:

DC Comics does not make a semantic or an abstract distinction between humans (or superheroes/villains) born with mutations making them different from humans mutated by outside sources.

This is to say by DC standards, Spider-man is a mutant, not a mutate. This opens up our definition and the number of applicable characters.

Also characters who were transformed through radiation or a mutagenic gas are sometimes identified as mutants instead of Marvel's term, 'mutates'.
All humans with powers are simply referred to, and treated as, one group collectively known as metahumans. The term mutant does still exist for humans born with actual powers instead of attaining them.

Here is a handy picture for DC supers:

And for Marvel:

So anyone who's been 'mutated' by an external force would be considered a mutant in their lexicon. For instance, The Flash might be considered a mutant, as the chemicals he was exposed to mutated him. Because of the huge overlap with metahumans though, and being the more general case, they're often just called meta humans.

A: DC steers away from the Marvel version of mutant, perhaps because it plays such a major role at the House of Ideas or simply because they feel no need. There are mutants within the DC Universe and have been for some time; the first I can recall is Captain Comet who, if memory serves, left the Earth because he was a mutant and different from other humans.
Others include Jade and Obsidian, the children of the Golden Age Green Lantern and Nuklon or Atom Smasher as he is now called - all of whom were founding members of Infinity Inc., the legacy group of the JSA.
Metahumans seems to be the operative word of choice at DC and encompasses (pretty much) all heroes and villains with powers.


text:
Q: Why does my table tr td:hover only work for the th header row?, not for any other rows? I have this code in jsfiddle and I would like the rows to highlight when I hover over them. I have tried the usual technique that works for me, but on this one, it only highlights the th header row, and not the table rows.
View the code in JSFiddle.
Basically, I've tried the usual:
table tr:hover{background-color: yellow;}

But this only highlights the table tr th Row only, and not the rows of the table, I have no idea why it's doing this.
Check out the code in JSFiddle.

A: I'm not sure either why it doesn't work as it is, but removing td in #main_content table tr td seems to do the job. So change
#main_content table tr td
{
    color: #666;
    border-right: 1px solid #eee;
    background-color: #fafafa;
}

to
#main_content table tr
{
    color: #666;
    border-right: 1px solid #eee;
    background-color: #fafafa;
}

A: You need to modify the CSS code, as so:
#main_content table tr:hover td
{

        color: #666;
        border-right: 1px solid #eee;
        background-color: #ffcc11;
}

the :hover is the main thing.
Hope this helps

A: That's because your td's background color is overriding the tr's background color. So, you need to change the following
#main_content table tr td
{
    color: #666;
    border-right: 1px solid #eee;
    background-color: #fafafa;
}

to

#main_content table tr td
{
    color: #666;
    border-right: 1px solid #eee;
}

#main_content table tr           // apply the color to the tr instead of the td this way it can get overridden
{
    background-color: #fafafa;
}

A: In CSS, change
#main_content table tr td
{
        color: #666;
        border-right: 1px solid #eee;
        background-color: #fafafa;
}

to
#main_content table tr
{
        color: #666;
        border-right: 1px solid #eee;
        background-color: #fafafa;
}

as seen in http://jsfiddle.net/jhuntdog/NPrSU/12/embedded/result/


text:
Q: C# problem for getting how much kg I should gain I have a computer of MMI (body mass index), according to the formula weight (kg) / Pow(height (m), 2). I tried to go further and write a code that recommends how many kg to lose weight or to gain weight depending on the optimal bmi.
For weight loss works well, the problem is fattening, does not reach the same optimal bmi.
Example.
If I have 100kg and 1.84m then you have to get to 29.5 you have to get to 24 pm to somewhere 87kg. So far so good
But if I have 30kg and 1.84 then you have to get to 8.8 you have to get to 24 and here's the problem that the formula recommends 64kg, which for 1.84, 64 kg is under the optimal bmi.
using System;

namespace BMI_Calculator
{
    class Program
    {
        static void Main(string[] args)
        {
            // define variables
            double weight;
            double height;
            double optimalBmiMin = 18.5;
            double optimalBmiMax = 24;
            double bmiPointKg = 2.3;

            /*
            Console.WriteLine("BMI Calculator");
            Console.WriteLine("");
            Console.WriteLine("developer: dannybest");
            System.Threading.Thread.Sleep(5000);
            Console.Clear();
            */

            Console.WriteLine("Write your weight in kg:");
            weight = Convert.ToDouble(Console.ReadLine());
            Console.Clear();

            Console.WriteLine("Write your height in m:");
            height = Convert.ToDouble(Console.ReadLine());
            Console.Clear();

            // bmi formula rounded to two decimals
            double bmi = weight / Math.Pow(height, 2);

            // calculates the difference in kg;
            double weightDiffLose = (bmi - optimalBmiMax) * bmiPointKg;
            double weightDiffGain = (optimalBmiMax - bmi) * bmiPointKg;

            // calculates the recomanded kg for your height based on bmi score;
            double recLoseKg = weight - weightDiffLose;
            double recGainKg = weight + weightDiffGain;

            // if is under optimal BMI score, calculate how much you should gain
            if (bmi < optimalBmiMin)
            {
                if (bmi < 15)
                {
                    Console.WriteLine("Your BMI is: " + bmi);
                    Console.WriteLine("Health: Very serious underweight");

                }
                else if (bmi > 15.0 && bmi < 16.0)
                {
                    Console.WriteLine("Your BMI is: " + bmi);
                    Console.WriteLine("Health: Severely underweight");
                }
                else if (bmi > 16.0 && bmi < 18.5)
                {
                    Console.WriteLine("Your BMI is: " + bmi);
                    Console.WriteLine("Health: Underweight");
                }

                Console.WriteLine();
                Console.WriteLine("You should gain: " + weightDiffGain + " kg");
                Console.WriteLine("Recomanded kg for your height: " + recGainKg + " kg / " + height + " m");
            }
            // else if above optimal BMI score, calculate how much you should lose
            else if (bmi > optimalBmiMax)
            {
                if (bmi > 25 && bmi < 30)
                {
                    Console.WriteLine("Your BMI score is: " + bmi);
                    Console.WriteLine("Health status: Overweight");
                }
                else if (bmi > 30 && bmi < 35)
                {
                    Console.WriteLine("Your BMI is: " + bmi);
                    Console.WriteLine("Health: Obese Class I (moderately obese)");
                }
                else if (bmi > 35 && bmi < 40)
                {
                    Console.WriteLine("Your BMI is: " + bmi);
                    Console.WriteLine("Health: Obese Class II (strictly obese)");
                }
                else if (bmi > 40)
                {
                    Console.WriteLine("Your BMI is: " + bmi);
                    Console.WriteLine("Health: Obese Class III (very seriously obese)");
                }

                Console.WriteLine();
                Console.WriteLine("You should lose: " + weightDiffLose + " kg");
                Console.WriteLine("Recomanded kg for your height: " + recLoseKg + " kg / " + height + " m");
            }
            // else normal BMI score
            else
            {
                Console.WriteLine("Your BMI score is: " + bmi);
                Console.WriteLine("Health status: Normal (healthy weight)");
            }
        }
    }
}

A: divine formula
            // Ideal Body Weight
            double heightInch = height / 0.0254;
            double ibwKg = 50 + 2.3 * (heightInch - 60);

            // calculates the diff
            double diffKg = ibwKg - weight;

using System;

namespace BMI_Calculator
{
    class Program
    {
        static void Main(string[] args)
        {
            // define variables
            double weight;
            double height;

            /*
            Console.WriteLine("BMI Calculator");
            Console.WriteLine("");
            Console.WriteLine("developer: dannybest");
            System.Threading.Thread.Sleep(5000);
            Console.Clear();
            */

            Console.WriteLine("Write your weight in kg:");
            weight = Convert.ToDouble(Console.ReadLine());
            Console.Clear();

            Console.WriteLine("Write your height in m:");
            height = Convert.ToDouble(Console.ReadLine());
            Console.Clear();

            // bmi formula
            double bmi = weight / Math.Pow(height, 2);

            // Ideal Body Weight
            double heightInch = height / 0.0254;
            double ibwKg = 50 + 2.3 * (heightInch - 60);

            // calculates the diff
            double diffKg = ibwKg - weight;

            // if is under optimal BMI score, calculate how much you should gain
            if (bmi < 18.5)
            {
                if (bmi < 15)
                {
                    Console.WriteLine("Your BMI is: " + bmi);
                    Console.WriteLine("Health: Very serious underweight");

                }
                else if (bmi > 15.0 && bmi < 16.0)
                {
                    Console.WriteLine("Your BMI is: " + bmi);
                    Console.WriteLine("Health: Severely underweight");
                }
                else if (bmi > 16.0 && bmi < 18.5)
                {
                    Console.WriteLine("Your BMI is: " + bmi);
                    Console.WriteLine("Health: Underweight");
                }

                Console.WriteLine();
                Console.WriteLine("You should gain: " + diffKg + " kg");
                Console.WriteLine("Recomanded kg for your height: " + ibwKg + " kg / " + height + " m");
            }
            // else if above optimal BMI score, calculate how much you should lose
            else if (bmi > 25)
            {
                if (bmi > 25 && bmi < 30)
                {
                    Console.WriteLine("Your BMI score is: " + bmi);
                    Console.WriteLine("Health status: Overweight");
                }
                else if (bmi > 30 && bmi < 35)
                {
                    Console.WriteLine("Your BMI is: " + bmi);
                    Console.WriteLine("Health: Obese Class I (moderately obese)");
                }
                else if (bmi > 35 && bmi < 40)
                {
                    Console.WriteLine("Your BMI is: " + bmi);
                    Console.WriteLine("Health: Obese Class II (strictly obese)");
                }
                else if (bmi > 40)
                {
                    Console.WriteLine("Your BMI is: " + bmi);
                    Console.WriteLine("Health: Obese Class III (very seriously obese)");
                }

                Console.WriteLine();
                Console.WriteLine("You should lose: " + diffKg + " kg");
                Console.WriteLine("Recomanded kg for your height: " + ibwKg + " kg / " + height + " m");
            }
            // else normal BMI score
            else
            {
                Console.WriteLine("Your BMI score is: " + bmi);
                Console.WriteLine("Health status: Normal (healthy weight)");
            }
        }
    }
}


text:
Q: typescript cannot infer subset of keys of object from usage I'm working on algebraic data types in ts and stuck with typing the match function. Simplified version of the problem is demonstrated below:
let rec = { a: 'a', b: 1 };

// just captures type of 'rec' and then reuses the type for eval
const makeEval = <Record>(rec: Record) => <
  Res,
  K extends keyof Record = keyof Record
>(
  val: Record,
  cases:
    | Cases<Record, Res>
    | (Cases<Record, Res, K> & { else: (r: Record) => Res })
): Res => (undefined as any) as Res;

export type Cases<Record, Res, K extends keyof Record = keyof Record> = {
  [T in K]: (value: Record[T]) => Res
};

const evalMyRecord = makeEval(rec);

// this is fine
const a = evalMyRecord(rec, { a: s => s, b: n => n.toString() });

// err
const b = evalMyRecord(rec, { a: s => s, else: _ => 'why err?' });
// Property 'b' is missing in type '{ a: (s: string) => string; else: (_: { a: string; b: number; }) => string; }'.

// requires explicit subset
const b_ = evalMyRecord<string, 'a'>(rec, {
  a: s => s,
  else: _ => 'but explicit a is fine'
});

// full set is fine
const c = evalMyRecord(rec, {
  a: s => s,
  b: n => 'n',
  else: _ => 'fine too'
});

So I want to express a type that is either has all keys of Record or any subset of it + {else} case.
I know that there is a solution with Partial:
type EvalCases<Record, Res> =
  | Cases<Record, Res>
  | (Partial<Cases<Record, Res>> & { else: (r: Record) => Res });

const b = evalMyRecord(rec, { a: s => s, else: _ => 'works' });

const b2 = evalMyRecord(rec, {
  a: s => s,
  b: undefined,
  else: _ => 'also works but weird'
});

But having: {b: undefined} looks a bit off. I want a compiler error if any case is not a proper function (if possible).
Any suggestions on typescript magic?
NOTE: conceptually close (but no the same) to Typescript cannot infer correct argument types for an object of functions.

A: The following solution allows you to have either Cases<Record, Res> or any subset of Cases<Record, Res> plus the else property.
type EnforcingPartial<T> = {
    [key in keyof T]: { [subKey in key]: T[key]; }
}[keyof T];

type EvalCases<Record, Res> = Cases<Record, Res> |
    (EnforcingPartial<Cases<Record, Res>> & { else: (r: Record) => Res });

const b = evalMyRecord(rec, { a: s => s, else: _ => 'works' });

const b2 = evalMyRecord(rec, {
    a: s => s,
    b: undefined, // ERROR HERE, b is incompatible
    else: _ => 'also works but weird'
});


text:
Q: Trigger a click on a HTML element (in dart) I'm trying to trigger a click on html element (in dart).
In other words, how can I execute the function that is normally executed when the element is clicked ?
Here is an example:
import 'dart:html';
import 'dart:math';

main() {
  querySelector("#first").onClick.listen((e) {
    r() => new Random().nextInt(256);
    querySelector("#first").style.color =
      "rgb(${r()},${r()},${r()})";
  });

  querySelector("#second").onClick.listen((e) {
    // pretend the first paragraph is clicked
  });
}

see also: https://dartpad.dartlang.org/456f1ec945536caf310c

A: This should work to produce a mouse event
querySelector("#second").dispatchEvent(new MouseEvent(...))


text:
Q: DOM event attributeModified/attributeRemoved/characterDataModified... are not triggered After
chrome.debugger.sendCommand({tabId:tabId}, "DOM.enable"), I found only event DOM.documentUpdated can be triggered, but others:
    DOM.attributeModified
    DOM.attributeRemoved
    DOM.characterDataModified
    DOM.childNodeCountUpdated
    DOM.childNodeInserted
    DOM.childNodeRemoved

can not be triggered. I think I should miss some calls to set something like MutationObserver options:
{
  boolean childList = false;
  boolean attributes;
  boolean characterData;
  boolean subtree = false;
  boolean attributeOldValue;
  boolean characterDataOldValue;
  sequence<DOMString> attributeFilter;
}

Any other chrome.debugger command I need to call for this?
Thanks.


text:
Q: c# lists not storing values after using int.TryParse I have the following code below that reads in text file and searches it for integers. I am using 'int.TryParse' to do this but it is not storing the integer values in the lists after it has run, just wondering if you could tell me what is wrong with this code. Thanks.
 namespace AccessErrorFile
  {
    class Program
    {
        static void Main(string[] args)
        {
            List<int> plans = new List<int>();
            List<int> events = new List<int>();

            using (var reader = new StreamReader(@"D:\Temp\AccessEmail.txt"))

                try
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        //split the line
                        string[] parts = line.Split(new[] { "Event" },      StringSplitOptions.None);

                        //get valid integers
                        plans.Add(GetInt(parts[0].Split(' ', '\'')));
                        events.Add(GetInt(parts[1].Split(' ', '\'')));
                   }
                }
                catch (System.Exception ex)
                {
                    Console.WriteLine("Error" + ex.Message);
                }

               //print the elements in the lists
               foreach (int x in plans)
               {
                   Console.WriteLine(x);
               }

               foreach (int y in events)
               {
                   Console.WriteLine(y);
               }

               //print the number of elements in the lists
               Console.WriteLine(plans.Count);
               Console.WriteLine(events.Count);
               Console.ReadLine();
        }
        public static int GetInt(string[] a)
        {
            int i = 0;
            foreach (string s in a)
            int.TryParse(s, out i);
            return i;
        }
    }
}

A: your problem is
  public static int GetInt(string[] a)
    {
        int i = 0;
        foreach (string s in a) //HERE
            int.TryParse(s, out i); //AND HERE

        return i;
    }

you are parsing in the loop, so the return i statement returns basically the last s of iteration, which, most probably is not a number, so i=0.
If you want to add all numbers from the string to array of ints, you can do something like:
IEnumerable<int> GetNumbersFromList(string[] s) {

    foreach(var str in s) {
        int val;
        if(int.TryParse(str, out val))
            yield return val;
    }
}

and after
  plans.AddRange(GetNumbersFromList(parts));

Just a basic idea, naturally, you have to fit it to your needs.


text:
Q: CommandParameter of event trigger using InvokeDelegateCommandAction I am using the class InvokeDelegateCommandAction from AlexeyZakharov's weblog on the basis of some advice from guys that this is the best way to send back a parameter from a View to a ViewModel from an EventTrigger.
Here's what I have.
In the View (a DataGrid to be specific):
<i:Interaction.Triggers>
    <i:EventTrigger EventName="SelectionChanged" >
        <cmnwin:InvokeDelegateCommandAction
                Command="{Binding SelectedExcludedItemChangedCommand}"
                CommandParameter="{Binding RelativeSource={RelativeSource self}, Path=SelectedItems}" />
    </i:EventTrigger>
</i:Interaction.Triggers>

In the ViewModel:
public DelegateCommandWithParameter SelectedActiveItemChangedCommand
{
    get
    {
        return selectedActiveItemChangedCommand ??
            (selectedActiveItemChangedCommand = new DelegateCommandWithParameter(DoSelectedActiveItemsChanged, CanDoSelectedActiveItemsChanged));
    }
}

public bool CanDoSelectedActiveItemsChanged(object param)
{
    return true;
}

public void DoSelectedActiveItemsChanged(object param)
{
    if (param != null && param is List<Object>)
    {
        var List = param as List<Object>;
        MyLocalField = List;
    }
}

The new kind of DelegateCommand that allows me to pass objects as args:
public class DelegateCommandWithParameter : ICommand
{
    #region Private Fields
    private Func<object, bool> canExecute;
    private Action<object> executeAction;
    private bool canExecuteCache;
    #endregion

    #region Constructor
    public DelegateCommandWithParameter(Action<object> executeAction, Func<object, bool> canExecute)
    {
        this.executeAction = executeAction;
        this.canExecute = canExecute;
    }
    #endregion

    #region ICommand Members
    public bool CanExecute(object parameter)
    {
        bool temp = canExecute(parameter);
        if (canExecuteCache != temp)
        {
            canExecuteCache = temp;
            if (CanExecuteChanged != null)
            {
                CanExecuteChanged(this, new EventArgs());
            }
        }
        return canExecuteCache;
    }

    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
        executeAction(parameter);
    }
    #endregion
}

Whenever my code gets to the DoSelectedActiveItemsChanged, the arg is always NULL.... am I being a complete doofus here? Where does the CommandParamter get linked to the command args? AKA, why does the View pass nothing back to the command? Please help.

A: I did it with a ListBox instead, but I got the same thing. The following is fine, as it passes CommandParameter instead of the invoke parameter. So why is CommandParameter null?
protected override void Invoke( object parameter ) {
    this.InvokeParameter = parameter;

    if ( this.AssociatedObject != null ) {
        ICommand command = this.ResolveCommand();
        if ( ( command != null ) && command.CanExecute( this.CommandParameter ) ) {
            command.Execute( this.CommandParameter );
        }
    }
}

CommandParameter doesn't seem to be working appropriately because your binding is setting it to null. {RelativeSource Self} resolves to an InvokeDelegateCommandAction, and that doesn't have a SelectedItems property. Instead, use this binding:
CommandParameter="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListBox}}, Path=SelectedItems}"

Then CommandParameter will pass in a SelectedItemCollection from the ListBox.
There is one other issue that you'll quickly discover. DoSelectedActiveItemsChanged()'s param will be an instance of SelectedItemCollection, not List<Object>.

A: I have solved the problem with the aid of Joel's observations... For those that may be interested, here's how. Although obviously I have credited Joel rightfully with the correct answer, it seems right to put this info as a answer rather than an edit to the question.
I discovered the generic DelegateCommand, so got rid of the DelegateCommandWithParameter
public ICommand SelectedObjectsChangedCommand
{
    get
    {
        return selectedObjectsChangedCommand ??
            (selectedObjectsChangedCommand = new DelegateCommand<MyType>(DoSelectedObjectsChangedCommand , CanDoSelectedObjectsChangedCommand ));
    }
}

The 'Do' (Execute method) now with the return of the SelectionChangedEventArgs...
public void DoSelectedObjectsChangedCommand(object param)
{
    if (param != null && param is SelectionChangedEventArgs)
    {
        foreach (MyType object in ((SelectionChangedEventArgs)param).AddedItems.Cast<MyType>().ToList())
        {
            selectedObjects.Add(object);
        }
        foreach (MyType object in ((SelectionChangedEventArgs)param).RemovedItems.Cast<MyType>().ToList())
        {
            selectedObjects.Remove(object);
        }
        UpdateAllCanDos();
    }
}

Along with the rest of my business logic it makes for a very smooth and intuitive UX. Many thanks to all the answer-ers. I have been doing WPF and MVVM with NHibernate not for only a month and I can't help but acknowledge that the SO community are getting me over the learning curves in the best and most enriching ways possible.


text:
Q: Simulating Keys In Video Games I want to code a bot that walks for me in a game called Minecraft To Explore All Of The Biomes. I've tried this code:
import pyautogui
import time

pyautogui.keydown("w")

time.sleep(8888)

pyautogui.keyUp("w")
print("Exploration Finished")

But it doesn't even move how can I fix it?

A: This is because you have inserted a time.sleep() code which will wait for 8888 seconds and then finish your code, resulting nothing. So instead, I put a for loop to fix your error:
from pyautogui import *

for i in range(8888):
    keyDown("w")

keyUp("w")
print("Exploration Finished")

You can use the time.sleep() function to go to your game, start the game etc...
Please tell if this worked for you


text:
Q: [Beginner]How to tackle mathematical proofs? So I recently joined university for a BSc in mathematics. I have never been exposed proofs but I have knowledge of algebra, trigonometry, and some differentiation/integration. Now I'm struggling with proofs. I'm having trouble figuring out the best way to write the proofs, since everything seems so random. I don't know where to begin.
After some Googling, I came across some tutorials but they do not help much. I think I lack the basics of proof solving and I think I lack the mathematical language to express what I need. Would anyone experienced have any suggestions for me on where to start and gradually be able to tackle most proofs(contradiction, induction) and I would really appreciate it if you could suggest some great introductory proof-based books which will give me a head start and gradually move to advanced stuff.
Thanks.

A: Induction is actually pretty easy to teach. You'll get a lot of practice with it in Number Theory, Graph Theory, and Computer Science. Here is a good link for learning how to write a proof by induction: http://www.dreamincode.net/forums/topic/280815-introduction-to-proofs-induction-and-big-o/
As for learning, I'd look at propositional calculus, first order predicate logic, and set theory first. These are the basic tools you'll need to learn math. Linear Algebra and Number Theory are pretty common courses to teach proof writing, if you haven't already had a mathematical fluency type course. With Linear Algebra, make sure to look at materials that talk about vector spaces. A lot of introductory material is more about teaching you how to crunch problems than think about abstract concepts and write proofs.
Number Theory is great for inductive and combinatorial arguments. The material is also familiar and beautiful. You'll see it pop up when you get into Abstract Algebra.


text:
Q: UIView shows perfect on iPhone but not on iPad I am pretty new to iOS development and I am able to create views and controllers. I have been testing using my iPhone and other sizes of iPhone and they look great. I tried once on an iPad but it was a border around the screen like in this image.
I constrained to margins and I did not give any height or width constraints so it could stretch properly. It also looks good on the storyboard viewing so what could I be doing wrong? Can't seem to find any resource online to help.

A: This is default behaviour when you run iphone app in ipad
This happened  because your app is supported iphone only .
Tap on your project and select universal if you want to  add support for both iphone and ipad.
Other option is you can check requires full screen check box but it will still show black bar
Note: However you are developing iPhone Only app but it is compulsory to check that everything works fine in ipad because apple review team will also check that in ipad and your app may be rejected if something is not proper

A: May be you have made an iPhone app. Try to change the setting to Universal app in the xcode settings. Normally iPhone app shows scaled on iPad, which is same as in your case.
Select Projet in xcode -> General Setting


text:
Q: How do I flash DIR-615 from the recovery console? I have installed dd-wrt on my DIR-615, but I now want to flash the stock firmware on it. However, while I can get into the recovery console (hold reset button and power on until power light flashes), I cannot upload the firmware. I am aware of the 100-continue as well as this question: remove DD-WRT from DIR-615, but I cannot manage to flash anything.
In essence, the problem is that the client (browser, curl, etc) sends a "Expect: 100-continue" but since the router recovery console only supports HTML 1.0, it never replies with a 100-continue status. So really what I am asking is how do I circumvent a "Expect 100-continue" request from the client side so that I can upload/flash the firmware.
I have tried numerous things such as using curl (which hangs). I also tried using Firefox portable (13_01) on Windows 7, but this results in a "No network access" message and I cannot subsequently connect to 192.168.0.1. The first thing I tried was modern Firefox on linux, but this does not work either (even changing it to HTML 1.0 does not work).
I am wondering if is an old linux browser that I can use (or how to resolve the "No network access" error on Windows. Or if there are simpler solutions to this problem.

A: I managed to solve this by disabling all DNS related services on the Windows 7 machine, and thereafter I could ping 192.168.0.1 and flash the firmware on there.


text:
Q: How do I grant a database role execute permissions on a schema? What am I doing wrong? I am using SQL Server 2008 Express edition.
I have created a Login , User, Role and Schema.
I have mapped the user to the login, and assigned the role to the user.
The schema contains a number of tables and stored procedures.
I would like the Role to have execute permissions on the entire schema.
I have tried granting execute permission through management studio and through entering the command in a query window.
GRANT EXEC ON SCHEMA::schema_name TO role_name

But When I connect to the database using SQL management studio (as the login I have created) firstly I cannot see the stored procedures, but more importantly I get a permission denied error when attempting to run them.
The stored procedure in question does nothing except select data from a table within the same schema.
I have tried creating the stored procedure with and without the line:
WITH EXECUTE AS OWNER

This doesn't make any difference.
I suspect that I have made an error when creating my schema, or there is an ownership issue somewhere, but I am really struggling to get something working.
The only way I have successfully managed to execute the stored procedures is by granting control permissions to the role as well as execute, but I don't believe this is the correct, secure way to proceed.
Any suggestions/comments would be really appreciated.
Thanks.

A: I have had good luck with the following technique below (using a schema named "myschema" for the example). It sounds like you have most of the pieces in place but the schema/role ownership might not be set correctly.
-- Create the role that will own the schema
CREATE ROLE [myschema_owner] AUTHORIZATION [dbo];

-- Create the role that will have execute permissions on the schema
CREATE ROLE [myschema_execute] AUTHORIZATION [dbo];

-- Create the schema owned by our role
CREATE SCHEMA [myschema] AUTHORIZATION [myschema_owner];

-- Assign execute permissions to execute role
GRANT SELECT, EXECUTE ON SCHEMA::[myschema] TO [myschema_execute];

A: I'm not sure how to limit this to a certain schema (though your syntax looks like it should work) but if it's acceptable to have execute rights on the entire database the following will do the trick, then add your login to the role like Ankur describes.
grant execute to <ROLE_NAME>

Also, granting VIEW DEFINITION to this role will aloow the logins in the role to see the stored procedures.

A:

Open SQL Server Management Studio using SA login or Windows Authentication
Go to Securities >> Logins
Right click on user and properties
Go to User Mappings
Select Database name
and assign permission
done


text:
Q: RegEx: Match a word with exactly one occurrence of a specified character at the beginning I want to detect words starting with $ but ignore words starting with $$ because I want to give the user a way to escape that character.
I have tried many things, but the nearer I got was this: [^\$]\$\w+
It matches occurrences like The side bar $$includes a| $Cheatsheet|, full with the white space at the beginning of the word $Cheatsheet included. It should match the word $Cheatsheet only, without the space.
How can I do it? Any ideas?

A: The regex you tried [^\$]\$\w+ will match not a dollar sign followed by a dollar sign and one or more times a word character. That would match for example a$Cheatsheet or $Cheatsheet with a leading space. Note that you don't have to escape the dollar sign in the character class.
If negative lookbehinds are supported, to match a word that does not start with a dollar sign you could use:
(?<!\$)\$\w+
Regex demo
Without a lookbehind you could match what you don't want and capture what you do want in a capturing group.
\${2}\w+|(\$\w+)
Regex demo
If the dollar sign can also not be in the middle of the word you could use:
\S(?:\$+\w+)+\$?|(\$\w+)
Regex demo

A: Since negative lookbehinds are NOT yet supported in all JavaScript engines (https://github.com/tc39/proposal-regexp-lookbehind), you can start with your regex and introduce a match group:
[^\$](\$\w+)

then, to exclude aaa$bbb, it is possible to use:
\s(\$\w+)

edit: and to match at the beginning or after punctuation:
(?:^|[^$\w])(\$\w+)

https://regex101.com/r/3cW5oY/2

A: You want to escape a $ with $. That means, you need
/(?:^|[^$])(?:\${2})*\B(\$\w+)/g

See the regex demo.
Details

*

*(?:^|[^$]) - start of string or any char but $

*(?:\${2})* - 0 or more repetitions of double dollar (this is required to avoid matching literal dollars)

*\B - requires start of string or non-word char before the next $

*(\$\w+) - Group 1: a $ and then 1+ word chars.

JS demo:

var s = "The $side bar $$includes a| $Cheatsheet|, $$$$full aaa$side";
var res = [], m;
var rx = /(?:^|[^$])(?:\${2})*\B(\$\w+)/g;
while(m=rx.exec(s)) {
  res.push(m[1]);
}
console.log(res);


text:
Q: Add commas between spaces in each line I have a file with 30,000 lines that look like such...
123456 123 firstname lastname

I am trying to make them all look like
123456,123,firstname,lastname

How would I do that to a large amount of lines in notepad++

A: Step 1: Open your text file

Step 2: Go to Search > Replace or use Ctrl+H

Step 3: Type (space) in Find what and (comma) in Replace with box with Search mode as normal. Then Replace All.

Step 4: Spaces are replaced with commas. Save the changes in your file

Note: Using \s with search mode regular expression will replace all tabs, spaces, and EOL (end of a line) with commas and your output will come in a single line.


text:
Q: Getting duplicate rows with row edit event in primefaces I am Using Prime faces 3.5.8,I am getting duplicate rows with row edit event.I am getting my row count as fine but one record is showing twice instead of other.This I am getting when call my clintList to load.When I close dialog and open it it is fine,Even I checked my list It is getting right data,Thanks in Advance..
    My BeanCode for edit,
    public void onClientEdit(RowEditEvent event) {
        try {
            Client edtClient = (Client) event.getObject();
            if (null == edtClient.getClientName()
                    || edtClient.getClientName() == "") {
                FacesContext.getCurrentInstance().addMessage(
                        null,
                        new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                CommonStringUtil.getUIString("clintNameEmpty"),
                                CommonStringUtil.getUIString("clintNameEmpty")));
                getAgencyClients();
                return;
            }
            HibernateUtil.beginTransaction();
            Agency tempAgency = agencyHome.findById(agency.getAgencyId());
            Hibernate.initialize(tempAgency.getClients());
            HibernateUtil.commitTransaction();
            for (Client cl : (Set<Client>) tempAgency.getClients()) {
                if (cl.getClientName().equalsIgnoreCase(
                        edtClient.getClientName().trim())) {
                    log.debug("Client Name Already exists");
                    FacesContext.getCurrentInstance().addMessage(
                            null,
                            new FacesMessage(FacesMessage.SEVERITY_WARN,

                                    CommonStringUtil
                                            .getUIString("clientNameExists"),

                                    CommonStringUtil
                                            .getUIString("clientNameExists")));
                    getAgencyClients();
                    return;
                }
            }
            HibernateUtil.beginTransaction();
            Client eClient = clientHome.findById(edtClient.getClientId());
            eClient.setClientName(edtClient.getClientName());
            clientHome.attachDirty(eClient);
            clientName = null;
            agencyHome.attachDirty(agency);
            HibernateUtil.commitTransaction();
            FacesContext.getCurrentInstance().addMessage(
                    null,
                    new FacesMessage(FacesMessage.SEVERITY_INFO, CommonStringUtil
                            .getUIString("clientNameEditSucc"), CommonStringUtil
                            .getUIString("clientNameEditSucc")));
            } catch (Exception e) {
            if (HibernateUtil.isTransactionActive())
                HibernateUtil.rollbackTransaction();
            log.error("Error Updating Client Name", e);
            FacesContext.getCurrentInstance().addMessage(
                    null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, CommonStringUtil
                            .getUIString("clientNameEditFail"), CommonStringUtil
                            .getUIString("clientNameEditFail")));
        }
    }

My View Part

<p:dialog widgetVar="clientDialogue" modal="true" id="clientdilogId"
        showHeader="false" style="padding:0;">
        <h:form id="clientDlgForm">
            <p:toolbar style="height:38px;">
                <p:toolbarGroup align="left">
                    <h:outputText
                        value="Edit Client Messages: #{adminAgencyBean.agencyName}"
                        styleClass="dialog-header-Text" style="line-height:38px"></h:outputText>
                </p:toolbarGroup>
                <p:toolbarGroup align="right" style="margin-left:50px;">
                    <p:inputText value="#{adminAgencyBean.clientName}" id="clientName"
                        maxlength="45" />
                    <p:spacer width="5"></p:spacer>
                    <p:commandButton action="#{adminAgencyBean.createClient}"
                        icon="ui-icon-custom-arrow" iconPos="right" value="Create"
                        style="margin-left:5px;margin-right:20px;" update="@form" />
                    <p:commandLink value="X" onclick="clientDialogue.hide()"
                        style="text-decoration:none;margin-right:10px;" process="@none"></p:commandLink>
                </p:toolbarGroup>
            </p:toolbar>

            <p:messages id="clientMsgs" />
            <p:scrollPanel style="width:980px;height:400px;width:100%;"
                mode="native">

                <p:dataTable value="#{adminAgencyBean.clientList}" var="client"
                    sortBy="#{client.clientName}" sortOrder="ascending" editable="true"
                    id="ClientTable">

                    <p:ajax event="rowEdit" listener="#{adminAgencyBean.onClientEdit}"
                        update=":clientDlgForm:clientMsgs"/>
                    <p:ajax event="rowEditCancel" />
                    <p:column headerText="Client Name" sortBy="#{client.clientName}"
                        style="white-space:pre-line;width:130px;">
                        <p:cellEditor>
                            <f:facet name="output">
                                <h:outputText value="#{client.clientName}" />
                            </f:facet>
                            <f:facet name="input">
                                <p:inputText id="editClientName" value="#{client.clientName}"
                                    maxlength="45"  style="width:90px"></p:inputText>

                            </f:facet>
                        </p:cellEditor>
                    </p:column>
                    <p:column headerText="Edit Client"
                        style="white-space:pre-line;width:80px;">
                        <p:rowEditor
                            rendered="#{adminAgencyBean.clientTransactionMap[client.clientId] lt 1}" />
                        <h:outputText value="#{commonmessages.NoEdit}"
                            rendered="#{adminAgencyBean.clientTransactionMap[client.clientId] ge 1}" />

                    </p:column>
                    <p:column headerText="Remove Client"
                        style="width:85px;white-space:pre-line">
                        <p:commandButton value="Remove"
                            rendered="#{adminAgencyBean.clientTransactionMap[client.clientId] lt 1}"
                            action="#{adminAgencyBean.deleteClient}" update="@form"
                            process="@none" styleClass="blue_button">
                            <f:setPropertyActionListener target="#{adminAgencyBean.clientId}"
                                value="#{client.clientId}"></f:setPropertyActionListener>
                        </p:commandButton>
                        <h:outputText value="#{commonmessages.nodelete}"
                            rendered="#{adminAgencyBean.clientTransactionMap[client.clientId] ge 1}" />
                    </p:column>

                </p:dataTable>
            </p:scrollPanel>
        </h:form>
    </p:dialog>


text:
Q: Affine transformation of a gaussian vector We know that (d is the dimension of the vector $X$):
$X$ has distribution $\mathcal{N}_{d}({\mu},{\Sigma})$
${Y=\Sigma^{-1/2}(X-\mu)=\Sigma^{-1/2}X-\Sigma^{-1/2}\mu}$
Since ${\Sigma}$ is a symmetric positive definite matrix, we know that ${\Sigma^{-1}}$ is also symmetric positive definite. Moreover, ${\Sigma^{-1/2}}$ is the positive square root of ${\Sigma^{-1}}$, that is, the one satisfying ${\Sigma^{-1/2}\Sigma^{-1/2}=\Sigma^{-1}}$. We remark that  ${Y}$ defines an affine transformation of ${X}$ in $\mathbb{R}^{d}$ so we can use a well know result of affine transformation of a Gaussian vector :
\begin{equation*}
    {Y}\sim\mathcal{N}_{d}({\Sigma^{-1/2}\mu -\Sigma^{-1/2}\mu,\Sigma^{-1/2}\Sigma\Sigma^{-1/2} })
\end{equation*}
and
\begin{equation*}
    \begin{aligned}
        &{\Sigma^{-1/2}\mu -\Sigma^{-1/2}\mu}=0_{d}\\
        &{\Sigma^{-1/2}\Sigma\Sigma^{-1/2}}= ?\quad\quad\quad                (1)
    \end{aligned}
\end{equation*}
and I'm getting trouble when it comes to compute $(1)$, I would like to use a commutative property but nothing allows me to do it in my knowledge
Edit : Roger answered the question !


text:
Q: Sort by columns and only keep the first line until next value in column 1 I have a file with roughly 10m lines. Each line is most likely unique, but I'm sorting the file by column 1 then 2 then 3.
Column 1 = CODE
Column 2 = DATE
Column 3 = AMOUNT

I only want to keep the first line until the next date and so on. Below is an example of what I have and what I need the output to be.
Original:
COL1   COL2         COL3
ABA    2019-01-01   100
ABA    2019-01-01   111
ABA    2019-01-02   140
ABA    2019-01-02   150
ABA    2019-01-03   200
ABA    2019-01-03   220

Ouptut needed:
COL1   COL2         COL3
ABA    2019-01-01   100
ABA    2019-01-02   140
ABA    2019-01-03   200

Anyone able to help me.  Have tried
a.drop_duplicates(subset[data.columns[0],data.columns[1],data.columns[2]], keep='first')

A: try groupby and then first:
a.groupby([data.columns[0],data.columns[1]], as_index=False).first()

A: Your solution is almost correct. This version is a modified version:
>> a.drop_duplicates(subset = [a.columns[0],a.columns[1]], keep='first')

That produces:
    COL1    COL2        COL3
0   ABA     2019-01-01  100
2   ABA     2019-01-02  140
4   ABA     2019-01-03  200

Explaining the modifications:

*

*subset is a named parameter, as you can see on the documentation of drop_duplicates;

*if column 3 can vary, it shouldn't be present on the subset parameter. The duplicate should consider the first 2 columns;

*the names you used in the code are not consistent, naming a and data for apparently the same object;


text:
Q: Relation between basis and Similar matrix I don't understand how it is true. In my book there is a lemma which says:
Characteristic polynomial , determinant and Trace of a linear transformation of finite dimensional vector space are independent of chosen basis.
I understand that similar matrices have same characteristics polynomial,determinant and Trace but i don't understand how is it independent of chosen basis?

A: The change of basis is a similarity transformation.
Take also a look here for more details:
Change of basis = similarity?


text:
Q: Why were the members of the DA so easily captured by the inquisitorial squad? In Harry Potter and the Order of the Phoenix, Harry attempts to use Umbridge's fire to contact Sirius after having his final vision during OWLs (Ordinary Wizarding Level exams; magical equivalent of high school diplomas I believe).  When he's yanked back out he finds that five members of the DA ('Dumbledore's Army', commonly refereed to as DA in the books) have been captured and restrained by an equal number of Inquisitorial Squad members.  It's made clear that the DA members have been roughed up, but no mention is made of any harm to the Inquisitorial Squad members.
I would concede that any duel could be won by circumstance and luck as much as skill.  Still, it seems terribly unlikely that five separate duels are all lost by students who have spent the entire year preparing specifically for this eventuality.  Further, so, that the winners should come out of it completely unscathed.  This builds on the oddness of the earlier scene when the Inquisitorial Squad captures DA members fleeing from their final meeting, without any mention made of resistance (not even a shield charm).
While Umbridge may have given a slight advantage to the Inquisitorial Squad, she has been shown time and again to be incompetent, both in terms of general magical knowledge and in practical magical abilities.  So it seems unlikely that she turned the tide so completely herself.  And the DA members were engaged in an illegal activity and specifically on guard against Inquisitorial Squad members and Umbridge, making surprise unlikely.  And it has been established that several members of the Inquisitorial Squad are not magically competent.
So how were the DA members so easily overpowered if, as the book claims earlier, they really were highly competent at defense against the dark arts?  What is really going on here, that the DA members continually lose with minimal resistance to fellow students?

A: Harry was in an extremely vulnerable position (head unhearing/seeing, butt in the air if I understand it correctly) and doing the most important work of the group. A fight there could potentially harm Harry while he's vulnerable as well as render him unable to get the information he needs. Mitigating factors also include the fact that they were ambushed, and that Dumbledore's Army had not yet engaged in open war with Umbridge and the Inquisitors, and to do so would cross a big red line.
So in the interest of getting the information, not using up their one chance to attack Umbridge when the DA was woefully unprepared, and keeping Harry safe, they surrender to reduce tensions.

A: They were taken by physical force and/or simply surprised.
If they had gotten involved in a physical fight while they were unprepared they would have probably lost.

There was silence in the office except for the fidgetings and scufflings resultant from the Slytherins' efforts to keep Ron and the others under control. Ron's lip was bleeding onto Umbridge's carpet as he struggled against Warrington's half nelson.- Harry Potter and the Order of the Phoenix, Chapter 32 (Out of the fire)

To me this quote shows that Ron was punched or elbowed or something of the like in the face, and then was subdued by Warrington I cant think of any spells that would give someone a cut on the lip, but they may be out there, also most of the Slytherins are larger (by far) than the D.A so it wouldn't have been much of a fight if they had been jumped. Since the slytherins were never mentioned having cuts or injuries it is more probable that the D.A were surprised.
Later they do fight with magic and the D.A wins.

"How did you get away?" asked Harry in amazement taking his wand from Ron.
"Couple of Stunners, a Disarming Charm, Neville brought off a really nice little Impediment Jinx," said Ron airily, now handing back Hermione's wand too. "But Ginny was best, she got Malfoy - Bat-Bogey Hex - it was superb, his whole face was covered in the great flapping things.- Harry Potter and the Order of the Phoneix, Chapter 33 (Fight and Flight)

So once it was a fair fight with Magic the D.A win, this leads me to believe if they were actually fighting with magic at first the Inquisitorial Squad had surprised the D.A and that's how they won.


text:
Q: Pandas : How to plot bar graph for each month over counts I have a dataframe df as below:
Student_id   Date_of_exam(d/m/y)  Student_Performance
1            1/4/2020              Excellent
1            30/12/2019            Poor
1            26/12/2019            Medium
2            3/1/2021              Medium
2            10/1/2021             Poor
3            4/5/2020              Poor
3            22/8/2020             Excellent

How can I get the bar-graph with x-axis as month-year(eg: y-ticks: Dec 2019, Jan 2020, Feb 2020) and on y-axis - the total number of students (count) whose Student_Performance == Poor.
Please, do give any ideas, Thanks in advance.

A: Hope the Below snippet is what you are looking for :
import seaborn as sns
import pandas as pd

df = pd.read_csv("student_data.csv") #assuming the data is in the csv file

# get only month and year from datetime column (date of exam)
df['date_col'] = df['Date_of_exam(d/m/y)'].dt.to_period('M')

# group by based on month and year after filtering poor graded students
data = df[df['Student_Performance']=='Poor'].groupby(['date_col']).size().reset_index(name
    = 'count')

ax = sns.barplot(x="date_col", y="count", data=data) #plot using seaborn

output :


text:
Q: How do i use Ninject 2 in an ASP.NET MVC 3 application? Ive searched everywhere, i can't seem to find a way to implement ninject in my project. Ive heard of deriving MvcApplication to the NinjectHttpApplication. But NinjectHttpApplication isnt found even if i add the lib to the reference. I can't find Ninject.Web.Mvc. Does anyone have a guide somewhere in order to make this work, all i want to do is be able to bind my interface from my domain to existing implementation.

A: http://weblogs.asp.net/shijuvarghese/archive/2010/04/30/dependency-injection-in-nerddinner-app-using-ninject.aspx
Looks like the bulk of it is done via
Global.asax.cs
public class MvcApplication : NinjectHttpApplication

Replace Application_Start with
protected override void OnApplicationStarted()
{
    AreaRegistration.RegisterAllAreas();
    RegisterRoutes(RouteTable.Routes);
    ViewEngines.Engines.Clear();
    ViewEngines.Engines.Add(new MobileCapableWebFormViewEngine());
    RegisterAllControllersIn(Assembly.GetExecutingAssembly());
}

Then create your Ninject modules and configure the kernel, all is explained in the blog post and source code is available here: http://nerddinneraddons.codeplex.com/
While the above is for MVC 2, it should still apply

A: See my blog post about the MVC3 extension here: http://www.planetgeek.ch/2010/11/13/official-ninject-mvc-extension-gets-support-for-mvc3/
The source code at github comes with a full featured sample application: https://github.com/ninject/ninject.web.mvc
The binaries can be found either at github: https://github.com/ninject/ninject.web.mvc/archives/master
Or on the build server: http://teamcity.codebetter.com/project.html?projectId=project3&tab=projectOverview


text:
Q: How to prevent Gunicorn from accepting connections from anything other than Nginx? How can I configure my Gunicorn server to accept requests only from my Nginx proxy, denying any direct requests to the Gunicorn port?

A: You don't.  Just don't bind your Gunicorn server to anything outside localhost.  Only other things on the machine will be able to talk to it.  This is the default, so you shouldn't have to do anything, or you can be explicit about it.
gunicorn -b localhost:8000 --workers 2 module:app

You could bind a Unix socket instead of a TCP socket.  A Unix socket can be file-like, so you can set normal file permissions so that only the Nginx user can read it.  This can be more performant than TCP sockets anyway, but is not really any more secure.


text:
Q: Find copies of folders? (Not files) I have a dozen of folders that are duplicates. Within them are a few dozen folders that are duplicates so i have a few thousand copies of the same files and folders. Many of them are exactly the same while others have changes in a few files.
What utility can i use to delete folders that are copies of others with no changes? if one or more files in that folder have been changed i dont want it deleted (and i'd like the subfolders to have a shortcuts to a copy but thats not required). Is there a utility to do this?

A: I duplicator tool will identify duplicated FILES.  I would then use the folder's they are in as input to a DIFF.  WinMerge is good for finding any difference in two folders.  n-way Folder Diff will compare multiple roots but has much less friendly output.

A: Don't know that there's going to be one tool to accomplish what you want.  But by combining, you may be pretty close.  Directory tools, comparison tools, duplicate file tools ...
Take a look at Altap Salamander (shareware) & in particular it's Compare Directories utility.  Compare can use various methods or combinations; size, date/time, attributes, contents, & subdirectories.
So if you have two similar trees that you are looking at, it can quickly filter out those sections of the tree that are identical (based on your comparison method) & then start comparing the different trees that are left.
Two top level dirs. R: & S:.  R: is kind of the Source, & S: is kind of the Backup.  Originally they were the same, purposely duplicated, but over time there were additions to R: & otherwise rearranged & cleaned up.
The highlighted (red) directores are not identical (per my comparison method), so deleting any of the S: directories that are not highlighted will only remove duplicate directory trees.
A#1, _from_USR, beat, bla, black ... all can safely be deleted.
Now, _from_C is different (highlighted in red).

So if I jump into the _from_C directory & run another Compare, again the difs are highlighted & those not can be deleted.  So again I can safely delete from S: _ecclectic, _Instrumental, 12 Girls Band ...  Now some directories are entirely new in R: & not in S: at all, like _flv & 10cc.  And again some directories are different.  So if I jumped into the corresponding _metal directories & Compared from there, I would come up with more diffs.  In some cases I may have added an m3u or a screenshot (jpg) that didn't exist before, causing the diffs.  So essentially the same, but a thing here or there that makes them not actually compare.  And once you got into the bottom level directory in a particular tree, what the differences are becomes clear (usually).  (With MP3, MS, WMP has a habit of messing with MP3 tags, which will both change the file date/time & contents, but not necessarily the size.  I never use WMP because of that.)

Anyhow throwing a tool like Salamander into the mix (of various tools) I feel can be worthwhile.  (Not to mention that Salamander is an excellent file manager too.)

A: WinMerge is not totally automated, but you can delete whole sets of duplicate folders at once by control-clicking on them.
You can limit your search to only folders by changing the Filter: field from "." to "*".
You can control-select all the duplicate folders and then delete the ones from the right or left side, or both.
In my case, it was a inherited PC where the previous user downloaded hundreds of zipped folders, extracted them in place (in the Users/***/Downloads folder) then either copied or re-extracted them into folders one level up.
It's was a rather tedious combinatorics exercise: I have to compare each of 20 or so folders against the other 19, but I can control-select the whole set and delete the unwanted ones.