text:
Q: Is possible to process queue without calling join method? I've 3 workers waiting to stuffs come to queue but these workers just start their work when i call join() method.
I'm working with this example;
https://docs.python.org/3/library/asyncio-queue.html#examples
Is possible to enqueue something and process right away without calling join? if so, how?

A: You can sometimes process a queue without calling the join, but it is really advised that you wait.
.join() ensures that each item in your queue has been "gotten" and processed, and if you continue before join is finished, you may end up with an incomplete or fragemented queue structure.
To answer your question, theoretically yes, but it is highly recommended to use .join()
An example of not using .join(), but still mimicking its capability, can be found here.
https://docs.python.org/2/library/queue.html


text:
Q: Use Django+Redis+Socket.io to build chat room, where to start? I've heard of these three giant technologies would allow developers to build pub/sub paradigm which result in rapid server push experience.
I've got background on Django, but non of the other two. So just wondering, where can I kick off?
I currently use Gunicorn as django server, uses Nginx as a proxy to serve static files, uses Haproxy as a front-end load balancer. After I adopt new technology stack, can I keep them still?

A: You will probably encounter issues using Socket.io (which will try to use websocket) with Nginx. Nginx 1.0 does not support proxying of HTTP/1.1. You can use tcp_proxy to work around it. You might be able to find some forks for Nginx 1.1 that have websocket support though.
Check out this and this.

A: Start here:

*

*http://gevent-socketio.readthedocs.org
and here:

*

*https://github.com/abourget/gevent-socketio
There are some Django examples as to how to get started.  Your tech. stack should allow you to run this without much problems.

redpajama_set_name: RedPajamaStackExchange


text:
Q: LaTeX for Mac (lion) 2011 - how to add cls file?
Possible Duplicate:
How do I add a .sty file to my TeXShop installation?

I'm trying to get into LaTeX and have to use a publisher provided cls file (and some tex and bst files) and try to use them with my LaTeX installation. I have the latest version of LaTeX and use texmaker as editor.
I tried to google for advise how to do that but its either confusing or it seems that things changed in lion/2011.


text:
Q: Unable to evaluate expressions with a reflexive transitive closure The following expressions are almost identical:
value "(1,5) ∈ trancl {(1::nat,2::nat),(2,5)}"
value "(1,5) ∈ rtrancl {(1::nat,2::nat),(2,5)}"

However the first one is evaluated fine, and for the second one I get the following error:
Wellsortedness error:
Type nat not of sort {enum,equal}
No type arity nat :: enum

It seems that the error is caused by the identity relation:
value "(1::nat,5::nat) ∈ Id"

However the following code lemma doesn't help:
lemma Id_code [code]: "(a, b) ∈ Id ⟷ a = b" by simp

Could you please suggest how to fix it? Why it doesn't work from the scratch? Is it just an incompleteness of code lemmas or there are more fundamental reasons?

A: The problem becomes apparent when you look at the code equations for rtrancl with code_thms rtrancl:
rtrancl r ≡ trancl r ∪ Id

Here, Id is the identity relation, i.e. the set of all (x, x). If your type is infinite, both Id and its complement will also be infinite, and there is no way to represent that in a set with the Isabelle code generator's default set representation (which is as lists of either all the elements that are in the set or all the elements that are not in the set).
The code equation for Id reflects this as well:
Id = (λx. (x, x)) ` set enum_class.enum

Here, enum_class.enum comes from the enum type class and is a list of all values of a type. This is where the enum constraint comes from when you try to evaluate rtrancl.
I don't think it's possible to evaluate rtrancl without modifying the representation of sets in the code generator setup (and even then, printing the result in a readable form would be challenging). However, getting the code generator to evaluate things like (1, 5) ∈ rtrancl … is relatively easy: you can simply register a code unfold rule like this:
lemma in_rtrancl_code [code_unfold]: "z ∈ rtrancl A ⟷ fst z = snd z ∨ z ∈ trancl A"
  by (metis prod.exhaust_sel rtrancl_eq_or_trancl)

Then your value command works fine.


text:
Q: Find at least $5$ integers $n$ such that $\varphi(n)=16$
Let $\varphi(n)$ denote Euler's totient function. Find all integers such that $\varphi(n)=16$.

Answers given were $17,32,34,40,48.$
I am thinking a generalisation of this problem: is there a way to find all positive integers $n$ such that $\varphi(n)=k$ for a specific $k$? Is there a way to do it other than trial and error? (which is what I did BTW)

A: Here is a very good page on this problem.
It has a calculator that finds all solutions to inverting the Euler totient $\phi$. I put in $16$ and it found that there are exactly six solutions: $$34, 60, 40, 48, 32, 17.$$
It also gives links describing the algorithm used to them (which involves traversing some tree) and the complexity of the problem.

A: If $$n= p_1^{a_1}p_2^{a_2}...p_k^{a_k}$$  where $a_i\geq 1$ and $p_1<p_2<...<p_k$ then we have $$\phi(n) = p_1^{a_1-1}p_2^{a_2-1}...p_k^{a_k-1} (p_1-1)...(p_k-1)$$
$$16= p_1^{a_1-1}p_2^{a_2-1}...p_k^{a_k-1} (p_1-1)...(p_k-1)$$

If $p_1=2$ and $k>1$ $$2^4= 2^{a_1-1}p_2^{a_2-1}...p_k^{a_k-1} (p_2-1)...(p_k-1)$$
then $a_i=1$ for all $i>1$, so we have $$2^4= 2^{a_1-1} (p_2-1)...(p_k-1)$$
Now if $a_1 = 1$ then $k\leq 5$  so $$ 2^4= (p_2-1)...(p_k-1)$$
and thus $p_k\leq 17$.
We see that $k=2$ and $p_2 = 17$ does works, so $\boxed{ n_1=34}$
and it is the only one if $a_1=1$
If $a_1 = 2$ then $k\leq 4$  so $$ 2^3= (p_2-1)...(p_k-1)$$
and thus $p_k\leq 7$. We see that $p_2 =3$ and $p_3=5$ works, so $\boxed{ n_2 = 60}$
If $a_1 = 3$ then $k\leq 3$  so $$ 2^2= (p_2-1)...(p_k-1)$$
and thus $p_k\leq 5$. We see that $p_2 =5$ works, so $\boxed{ n_3 = 40}$
If $a_1 = 4$ then $k=2$  so $$ 2= p_2-1$$
so $p_2 =3$ works, so $\boxed{n_4 = 48}$
If $a_1 =5$ then o $\boxed{n_5 = 32}$  and we have 5 numbers

If $p_1 >2$ then ...


text:
Q: Render Many Images with dbc.Carousel in Dash app I have a large file of images I will like to display and eventually filter on (with callback) using dbc.Carousel. Currently, I cannot get the images to display on the local test server (127.0.0.1) - I either get a no image sliding thumbnail placeholder or nothing.
So I have:
# local path
imagePath = r"C:\Users\asdean\Documents\TagOCR\assets\\"

# string list of file names... 1-image.jpg, 2-image.jpg, etc
list_of_images = [os.path.basename(x) for x in glob.glob('{}*.jpg'.format(imagePath))]

# encoded list of bytes of images... used this before in Dash, will explain more
encodedList = [base64.b64encode(open(imagePath + i, 'rb').read()) for i in list_of_images]

Now to render the images on the dbc.Carousel I have tried several different things...
First, a direct copy on what they suggest on https://dash-bootstrap-components.opensource.faculty.ai/docs/components/carousel/
dbc.Carousel(
    id="carousel",
    items = [
            {'key': "2", "src": r"C:\Users\asdean\Documents\TagOCR\assets\1-1spot-cam-ptz.jpg"}
            ],
    controls=True,
    indicators=True,
    interval=None,
),

Yields 'no image thumbnail'
But really following the docs directly does me no good as I am pulling from a file with large (and growing) number of images. List/Dict comprehensions I suspect will likely have to be used.
So, I tried something like:
dbc.Carousel(
        id="carousel",
        items = [
            {'key': i, 'src'} for i in list_of_images
            ],
        controls=True,
        indicators=True,
        interval=None,
    ),

Which gave me the blank thumbnail, BUT I could rotate through to other blank thumbnails. From there, I remembered using an encode and decode combo to rending a single image in the past. So, I am things like (but not limited to)...
dbc.Carousel(
        id="carousel",
        items = [
            {'key': x} x.decode('utf-8') for x in encodedList
            ],
        controls=True,
        indicators=True,
        interval=None,
    ),

Which had yielded nothing. What am I missing here? How can I display many images from a file of images to a dbc.Carousel?
Note: I have no built any callbacks for this yet. I am planning on building one that filters images by start text (pseudo code: if imageName.startswith("1-") filter on 1) Not as concerned about this right now, mainly want to know how I can display many images from a file, but if you have it, go for it.
Thanks

A: This ended up being what worked
    dbc.Carousel(
        id="carousel",
        items = [
            {'src':'data:image/jpg;base64,{}'.format(x.decode())} for x in encodedList
            ],
        controls=True,
        indicators=True,
        interval=None,
    ),


text:
Q: How to process incoming email sent to a catchall address (and a few valid email addresses) I need to build a web application where people can send an email to custom email addresses (like - 1week@example.com, or 2days@example.com) and the email address '1week' and '2days' is used to perform certain actions on that email.
I looked at this Postfix - How to process inbound emails?, particularly, the response - https://serverfault.com/a/247279/94544 and that is indeed a solution that will work for me.
Questions:

*

*In the above mentioned solution, can I have actual inboxes, for example service@example.com which would be a real email address hosted with Google Apps? How do I specify the others to be redirected to the 'catch-all' address? Note that the email addresses - 1day, 1 week are NOT defined beforehand - there can be an email address - 9999weeks, for instance.

*Can the script access the email address '1week', the subject line, date/time sent, and the body?

*Is perl the best language for processing these emails, assuming that we scale up to handle 100s and 1000s of emails a day (or an hour)? It will need to process these emails and store them in a database.
I'm reading that the other options are of using Postfix, procmail, but I'm unsure about which would be the best, most scalable option.

A: *

*You can't mix Google Apps addresses with local postfix addresses. Your MX either points to G Apps or to local server.
Maybe if G Apps allows catch-all address/alias, then that would be forwarded to usermail@subdomain.example.com, and subdomain.example.com would point to your postfix server. (where postfix alias would forward the mail's to a script).

*Yes

*Perl is a good language for processing these mails. 100/1000 mails per hour/day would depend obviously on what the script is doing. And server resources. But should be possible.

A: Google Apps (for Business) allows you to reroute "unknown" (and known) email addresses elsewhere.
When you are in Gmail click "Settings", "Manage This Domain" then go to "Google Apps", "Gmail", "Default Routing" you then have the ability to setup multiple rules
e.g. if you wished to send all email sent to person1@example.com to person1@example.org you can add the following rules:-

*

*Specify Envelope Recipients to Match:; Single recipient;  person1@example.com

*Route; Envelope Receipient; / Change Envelope Receipient; Replace Receipient : person1@example.org

However it's much more powerful than that - you can add pattern matches* - e.g. [0-9]weeks@example.com could be forwarded to myautomaticprocessor@example.com or myautomaticprocessor@example.org where it would be able to see the recipient, you could also strip attachments and bypass the spam filter if you wish.

*

*I'm rubbish with regexs - you'd need one that says allow characters 0-9 one or more times where the first digit is 1-9 followed by weeks@example.com

Assuming it's just days, weeks, months, and years that's not too much of a faff to setup the four rules required.


text:
Q: Compile errors when importing ArduDroid to Android Studio Im importing this old ArduDroid project (https://github.com/xgxzatx/ArduDroid) into Android Studio 1.5.1.  At first I got an unrecoverable error due to the ActionBarSherlock library and Android Studio wouldn't even import the project.  I followed a post that suggested commenting out the call in project.properties for that library and then importing, so I did and the project imported successfully into Android Studio.  Then I downloaded the ActionBarSherlock folder and put that into my project folder so it is recognized, which it is.
Now I've gotten quite a few errors asking for a different SDK and build tools.  So far I've tried SDK 19 and the default 22 which I guess installed with Android Studio.  The problem seems to be that the ActionBarSherlock seems to be set for SDK 19 but the project seems to be set at a different SDK.  I also believe it has something to do with ActionBarSherlock only compiling as far up as SDK 19.
Currently these are my settings:
Ive installed SDK's:
22
19
15

AndroidProject
AndroidManifest.xml>>>min:15, target:15
build.gradle>>>>>>>>>>compile:15, buildTools:22.0.1, min:15, target:15

ActionBarSherlock
AndroidManifest.xml>>>min:15, target:15
build.gradle>>>>>>>>>>compile:19, buildTools:19.1.0
project.properties>>>>target=android-15

Now I'm getting:
Error retrieving parent for item: No resource found that matches the given name 'Theme.Sherlock'

A: Ok, I removed the entire project folder from my workspace and started over again:

*

*Commented out this line in the project.properties using TextEdit:
android.library.reference.1=../../JakeWharton-ActionBarSherlock-e5c2d1c/library

*Imported the project into Android Studio.

*Noticed I have a Project build.gradle, Module build.gradle.

*Did not paste the ActionBarSherlock folder into the project in Android Studio this time.

*Added these lines to the Module build.gradle:
dependencies {
compile 'com.actionbarsherlock:actionbarsherlock:4.4.0@aar'
compile 'com.android.support:support-v4:18.0.0'

}

*Left Module build.gradle as:
compileSdkVersion 15
buildToolsVersion "22.0.1"
defaultConfig {
    applicationId "com.xgxzatx.ardudroid"
    minSdkVersion 8
    targetSdkVersion 15
}

*Left AndroidManifest.xml with min=8 and target=15
However when I run the app on my phone I just get a blank screen with a Configuration tab and a Monitoring tab, but ArduDroid is supposed to have lots of buttons and sliders and a few text fields at the bottom, like this:

but what I get is like this:

So Im guessing this might have been a work in progress that the author never finished?  Can anyone else run the project and confirm?


text:
Q: Setup with Swagger UI and Swagger Editor using yaml split across mutliple files I would like to use swagger for our project, which is rather big. Documenting the whole REST-API in one single yaml file would be too much, so I would like to split it into several yaml files.
First I tried to use Swagger UI simply by downloading it an opening its index.html. That works until the point that I split the yaml into multiple files, as I got CORS errors then. To circumvent them, I simply deployed the Swagger-UI Folder, with my projects yaml files inside it as artifact to my tomcat.
The folder structure of the artifact looked like this:
swagger_ui
├── index.html
└── api
    ├── root.yaml
    ├── paths
    │   ├── path1.yaml
    │   ├── path2.yaml
    │   └── ...
    └── schemas
        ├── schema1.yaml
        ├── schema2.yaml
        └── ...

Now all CORS errors were gone, as my references are now all within the same origin (eg. "http://localhost:8080/swagger_ui")
So far, so good.
Now I wanted to have a simple way of editing the files using Swagger Editor.
In Swagger Editor, I click on File --> Import URL and import my root.yaml file. Now I get a bunch of errors saying the URLs to "paths" and "schemas" can not be resolved... Which makes sense, as I only imported root.yaml and the path and schema files are stored on a completely different server.
So my current approach is to deploy Swagger Editor alongside Swagger UI in my tomcat.
The current folder structure looks like this:
swagger_ui
└── index.html
swagger_editor
└── index.html
api
├── root.yaml
├── paths
│   ├── path1.yaml
│   ├── path2.yaml
│   └── ...
└── schemas
    ├── schema1.yaml
    ├── schema2.yaml
    └── ...

I thougt I can use eg. "$ref: '../api/paths/path1.yaml'" to reference the the path1.yaml file from BOTH Swagger UI and Swagger Editor, but I get the Error:

Could not resolve reference: Tried to resolve a relative URL, without having a basePath. path: '../api/paths/path1.yaml' basePath: 'undefined'".

Aside from this error... Using ".." to go up one directory does not seem right in itself...
So the question is:
Which is the right way to set up a Swagger API Definition that has the following properties:

*

*It is spread over multiple yaml files

*It can be edited in Swagger Editor

*It can also simply be visualized in Swagger UI

If my current approach is totaly wrong and there is a completely different approach, please tell me. It is no requirement to use tomcat or anything else I stated above. I just wanted to know if my approach makes any sense at all.


text:
Q: R check if NA is found in any of the column and perform the function I have an dataset in csv and it contains 10 thousand rows. I will show you the top 6 rows including the headers.
I have listed down the requirements below.

*

*I want to perform checking for ever columns header, Name, Sex, Age
and Birth on how many NA values are there.

*If there is NA values, I will create a dataframe and load the column values to the dataframe
including the NA values.

*If there is no NA values, I will create a dataframe and load the column values to the dataframe
without the NULL values.

*I need to create 4 dataframe to store each columns as there are 4 columns.

Here is how the data look like
Name    Sex    Age    Birth
James   M      20     Africa
Lim     F      NA     London
NA      M      25     Australia
Alice   NA     27     Britain
Brown   F      29     USA

I have listed down the R code below.
headers <- colenames(data) #Print the headers of the dataframe to the header array
for (i in headers) #Loop through the headers array
{
    print(sum(is.na(data$i))) #Perform checking the sum of NA values under the specific columns
    if (sum(is.na(data$i)) > 0) #If sum of na is more than 0 meaning there are NA found

        table <- table(data[i], useNA = "always") #load the data to the dataframe
    else
        table <- table(data[i]) #load the data to the dataframe
}

A: I think you need useNA = "ifany" (see ?table for the available options) instead of a conditional, and you can simplify your code into one expression:
lapply(dat, table, useNA = "ifany")
# $Name
# Alice Brown James   Lim  <NA>
#     1     1     1     1     1
# $Sex
#    F    M <NA>
#    2    2    1
# $Age
#   20   25   27   29 <NA>
#    1    1    1    1    1
# $Birth
#    Africa Australia   Britain    London       USA
#         1         1         1         1         1

Data
dat <- structure(list(Name = c("James", "Lim", NA, "Alice", "Brown"), Sex = c("M", "F", "M", NA, "F"), Age = c(20L, NA, 25L, 27L, 29L), Birth = c("Africa", "London", "Australia", "Britain", "USA")), class = "data.frame", row.names = c(NA, -5L))


text:
Q: Not valid for more testcase. why? question-https://www.codechef.com/submit/FRUITS
Read problems statements in Mandarin Chinese, Russian and Vietnamese as well.
Today is Chef's birthday. His mom has surprised him with truly fruity gifts: 2 fruit baskets. The first basket contains N apples, and the second one contains M oranges. Chef likes apples and oranges very much but he likes them equally, and therefore, wants to have the minimum possible difference between the number of apples and oranges he has. To do so, he can purchase 1 apple or 1 orange by paying exactly 1 gold coin (that's some expensive fruit, eh?). Chef can purchase fruits at most K times (as he has only K gold coins in his pocket) to make the difference the minimum possible.
Our little Chef is busy in celebrating his birthday to the fullest, and therefore, he has handed this job to his best friend — you. Can you help him by finding the minimum possible difference he can achieve between the number of apples and orange he owns?
Input
The first line of input contains a single integer T denoting the number of test cases. The first and only line of each test case contains 3 space separated integers — N, M and K — denoting the number of apples, number of oranges, and number of gold coins our little Chef has.
Output
For each test case, output the minimum possible difference between the number of apples and oranges that Chef can achieve.
Constraints
1 ≤ T ≤ 100
1 ≤ N, M, K ≤ 100
Sample Input 1
3
3 4 1
5 2 1
3 4 3
Sample Output 1
0
2
0
Explanation
Test 1: Chef will buy 1 apple by paying 1 gold coin and will have equal number of apples and oranges.
Test 2: Chef will buy 1 orange by paying 1 gold coin and will have 5 apples and 3 oranges.
my code
l=list()
def avb(N,M,K):

    if N<M:
        for i in range(1,K+1):
            N+=1
            if N==M:
                absolute=N-M
                return l.append(absolute)
                break
        absolute=-1*(N-M)
        return l.append(absolute)
    else:
        N,M=M,N
        for i in range(1,K+1):
            N+=1
            if N==M:
                absolute=N-M
                return l.append(absolute)
                break
        absolute=-1*(N-M)
        return l.append(absolute)

t=int(input())
for i in range(t):
    apple,mango,gold=map(int,input().split())
    avb(apple,mango,gold)

for absolute in l:
    print(absolute)


text:
Q: sqlachemy: filter by relationship (like django orm)? In django ORM you can directly filter by relationship attributes. Eg, given the tables
class Product(models.Model):
    product_id = models.IntegerField(primary_key=True)
    color = models.TextField()

class Sale(models.Model):
    sale_id = models.IntegerField(primary_key=True)
    timestamp = models.DateTimeField()
    product = models.ForeignKey(Product, on_delete=models.CASCADE)

You can do
Sale.objects.filter(product__color__in=['red', 'blue'])

Or even the other way around
Product.objects.filter(sale__timestamp__gt=datetime.now())

What is the proper way of doing this in sqlalchemy, without explicit JOINs??

A: You can use any() and has() to filter based on non-scalar and scalar relationships. They produce EXISTS subquery expressions:
session.query(Product).filter(Product.sales.any(Sale.timestamp > datetime.now()))

and
session.query(Sale).filter(Sale.product.has(Product.color.in_(['red', 'blue'])))

Unfortunately on some DBMS the EXISTS subquery expressions may perform poorly, compared to using explicit joins.


text:
Q: JavaScript + index Of returns false when should be true I do not know what I am doing wrong when checking if a piece of text exists within a string.
When the text I look for is present, my check seems to not see it and sends the code to the else part of the statement.
the code in question:
if (response.data.indexOf("Panelists sucessfully added Meeting ID") > 0) { < this check
    $scope.IsColor = true;
    $scope.Messages = response.data;
    angular.element("#msg").focus()
    return true;
}
else {
    $scope.IsColor = false;
    $scope.Messages = response.data;
    angular.element("#msg").focus()
    return false;
}

The contents of response.data
response.data[0]: "Panelists sucessfully added Meeting ID: 94395753143 on 07/31/2020 at 01:53:17 PM"

Screenshot:

Is it because indexOf cannot be used to check if a value exists within a string in an array?
Any insight is appreciated.
Thank you,
Erasmo

A:

const response = 'Panelists sucessfully added Meeting ID: 94395753143 on 07/31/2020 at 01:53:17 PM';

if (response.indexOf('Panelists sucessfully added Meeting ID') !== -1) {
    console.log(true);
} else {
    console.log(false);
}


text:
Q: DNS Spoofing with PowerDNS I want to modify the DNS query answer that PowerDNS returns by replacing the IP of the domain with the IP of a static page. I know the place to do this modification is in the startDoResolve function in pdns_recursor.cc. However I am having trouble figuring out where exactly the IP gets inserted into the response packet. Anyone having experience working with PowerDNS who can help me out with this?

A: It seems, you are using PowerDNS Recursor.
The standard way of doing this is via the lua extensions.
Depending on the criteria, when you want to spoof, you probably want to use one of the query interceptor function specified in the lua scripting documentation
You may also be interested in the spoofing capabilities mentioned in the dnsdist Packet Policies documentation. For example: addAction(domain, SpoofAction({IP[,…]}))


text:
Q: PHP Script Connecting to MySQL Docker Container :: What Am I Doing Wrong? I have a MySQL Docker container running, and I need a PHP script to connect to the container to do database stuff.  My script isn't working, and I can't tell if its a script thing or a container thing.
First, my system.  I'm developing on an Ubuntu 16.04.7 machine, running Docker 20.10.7, should be the latest.  My MySQL Container was pulled from Docker Hub (docker pull mysql pulled down Image ID 667ee8fb158e).  I spun up the container with this command:
docker run --detach --name=myMYSQL -p 52000:3306  --env="MYSQL_ROOT_PASSWORD=password123" 667ee8fb158e

Note the port mapping here.  For reasons too numerous for this post, this mapping is required.  It may be what is causing my script errors later, I dunno.
Before I discuss my script, I manually connected to the database and did some admin work:
mysql>
mysql> CREATE USER 'user01'@'localhost';
Query OK, 0 rows affected (0.02 sec)

mysql> SET PASSWORD FOR 'user01'@'localhost' = 'password123';
Query OK, 0 rows affected (0.01 sec)

mysql> create database myDB;
Query OK, 1 row affected (0.05 sec)

mysql> GRANT ALL PRIVILEGES ON myDB.* TO 'user01'@'localhost';
Query OK, 0 rows affected, 1 warning (0.03 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.01 sec)

mysql> show grants for 'user01'@'localhost';
+-------------------------------------------------------------------------+
| Grants for user01@localhost                                             |
+-------------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON `myDB`.* TO `user01`@`localhost`                |
+-------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql>

Okay, now for the PHP script.  After doing an apt-get install for mysql-client-core-5.7 and php-mysql, I used the below script:
<?php
$servername = "127.0.0.1";
$username = "user01";
$password = "password123";
$database = "myDB";
$mysqlPort = "52000"
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database, $mysqlPort, null);
// Check connection
if (!$conn) {
    die("OH NO!!!  Connection has failed, dude: " . mysqli_connect_error());
}
echo "Excellent, connected successfully!!!";
mysqli_close($conn);
?>

(Note how I'm using mysqli_connect() here.  According to this post, if I'm using "127.0.0.1" as the $servername, I'm forcing a TCP connection and I don't need to supply a $socket.  That's fine with me, as I need a TCP connection here.)
Fowever, the script fails.  Here's the command line output:
me@myUbuntu:~$
me@myUbuntu:~$ php phpMySQL.php
PHP Warning:  mysqli_connect(): (HY000/1045): Access denied for user 'user01'@'10.10.10.10' (using password: YES) in /home/me/phpMySQL.php on line 8
OH NO!!!  Connection has failed, dude: Access denied for user 'user01'@'10.10.10.10' (using password: YES)me@myUbuntu:~$

Arrgh.  A number of Google searches imply that my script is successfully connecting to the MySQL container, but being denied?  Maybe.  Sadly, I can't enable the MySQL error logs to confirm.  But I can't help wonder if my port-mapping are coming back to bite me and the script is never successfully reaching the container?  I wish I knew.  Does anyone have any advice?  Thank you.

A: I think your grant should be at 10.10.10.10.
GRANT ALL PRIVILEGES ON `myDB`.* TO `user01`@`10.10.10.10`

Make sure that the user is also @10.10.10.10


text:
Q: How do I call 2 functions with a onClick event in NextJS? I already have 2 constants that in my NextJs app => "toggleMenu" and "changeLanguage". When someone clicks on the language changer inside the menu I need it to call these two functions.
I have tried this, but it doesn´t seem to work in my code, it gets stuck on one of the functions saying it is not defined. If I try just running that function alone it does work as intended, so the problem must be this code:
onClick={() => { changeLanguage(); toggleMenu() }}

I found this online but it also does not work because of the syntax I believe:
onclick="f1();f2()"

Can anyone suggest anything else? Thanks
EDIT:
Here are the 2 functions I am trying to call but get an error on the "changelanguage" function, specifically on => undefined when reading "e.target.value".
const Navbar = (props) => {

  const [isOpen, setOpen] = useState(false);
  const toggleMenu = () => setOpen(!isOpen);

  useEffect(() =>{
    document.body.style.overflowY = isOpen ? 'hidden' : 'auto';
  }, [isOpen])

  const router = useRouter();
  const { locale } = router
  const t = locale === 'en' ? en : es;

  const changeLanguage = (e) => {
    router.push(router.pathname, router.pathname,{
        locale: e.target.value,
    })
  }

  return (

            {/* Logos on the left */}

            {/* Hamburger menu icon */}

              <button aria-label="menu" onClick={toggleMenu} className="flex text-white hover:text-gray-500">
              </button>

            {/* nav links and language changer*/}

              <Link href="servicios">
                {t.navbar.serviciosLink}
              </Link>

              <select defaultValue={ router.locale } onChange={changeLanguage} className='bg-black text-white'>
                <option className=' font-light' value='es'>ES</option>
                <option className=' font-light' value='en'>EN</option>
              </select>

        {isOpen && (

              {/*Left logo*/}

              {/* close icon*/}

                <button aria-label="close-menu" onClick={toggleMenu} className="text-black hover:text-gray-500">
                </button>

            {/* navigation links */}

            {/* social links and language changer */}

                  <button onClick={ changeLanguage } className='cursor-pointer font-light' value='es'>ES</button>
                  <button onClick={ changeLanguage } className='cursor-pointer font-light' value='en'>EN</button>

        )}

  );
};

export default Navbar

A: You can call two functions in one click event

export default function Somepage() {

  const functionOne = event =>{
    console.log("function one");

  }

  const functionTwo = event =>{
    console.log("function two");

  }

  const mainFunction = event => {
    functionOne(event)
    functionTwo(event)
  }

  return (
    <>
    <button onClick={mainFunction}>click to change</button>
    </>
  )
}

A: You cannot use e.target.value on the onClick event of a button. What I would do is create another function, handleSelectChange that would keep the state of the selected option.
.....
const [selectValue, setSelectValue] = useState("defaultValue");
.....
const handleSelectChange = (event) => {
  setSelectValue(event.target.value);
}
.....
<select defaultValue={ router.locale } onChange={handleSelectChange} className='bg-black text-white'>

Then for your button call your changeLanguage function which is now implemented to use the state variable
  const changeLanguage = (e) => {
    router.push(router.pathname, router.pathname,{
        locale: selectValue,
    })
  }

To be honest we don't really understand where the actual problem is. Is it the undefined event or the fact you can't call two functions.


text:
Q: Spaces with unique endomorphism monoids If $(X,\tau)$ is a topological space, let $\text{End}(X)$ denote the collection of all continuous maps $f: X\to X$. With composition, this becomes the endomorphism monoid $(\text{End}(X), \circ)$.
We say that the space $X$ has a unique endomorphism monoid if $\text{End}(X) \cong \text{End}(Y)$ as monoids, for some space $Y$, then the spaces $X$ and $Y$ are homeomorphic.
Question. Is there for every infinite cardinality $\kappa$ a space $(X,\tau)$ with unique endomorphism monoid, and $|X| = \kappa$?

A: While the OP question ultimately is specific (as it should), it really offers an entire topic:
TOPIC:  What are topological spaces
$\ (X\ T)\ $ which are topologically uniquely characterized by monoid $\ \text{End}(X\ T)\,?$
In other words, given an abstract monoid $\ M,\ $ can
we recover topological space $\ (X\ T)\ $ uniquely (if at all) so that $\ M\ $ and $\ \text{End}(X\ T)\ $ are isomorphic (as abstract algebraic monoids).
In this answer, let me provide some tools.
Let $\ \mathbf M:=(M\ \circ\ J)\ $ be an arbitrary monoid.  Let
$$ C\ :=\ \{c\in M:\ \forall_{f\in M}\ c\circ f=c\} $$
If $\ \mathbf M\ $ were isomorphic to $\ \text{End}(X\ T)\ $
then $\ C\ $ and $\ X\ $ would be in a canonical 1-1 correspondence as mentioned by @YCor in a comment to Dominic's
real-question. This is the basic starting tool.
Next, let's discuss the next tool, the idempotents
$\ i\in\mathcal I\subseteq M,\ $ where
$$ \mathcal I\ :=\ \{i\in M:\ i\circ i=i\} $$
For instance, the unit $\ J\in M\ $ and constants
$\ c\in C\ $ are all idempotents.
Definition
$$ \forall_{i\ j\,\in\mathcal I}\quad
    (\,i\subseteq j\ \Leftarrow:\Rightarrow\
      j\circ i=i\,) $$
It follows that:

*

*$\ \forall_{i\in\mathcal I}\quad i\subseteq i;$

*$\ \forall_{i\ j\ k\in\mathcal I}\quad(
    (i\subseteq j\ \text{and}\ j\subseteq k)\ \Rightarrow
      i\subseteq k) $

*$\ \forall_{i\in\mathcal I}\,
      \forall_{j\in C}\quad
       (\ i\subseteq j\ \Rightarrow\ j=i\ ) $
Topological idempotents $\ i:X\to X\ $ are closely related to Karol Borsuk's retractions; such idempotent
$\ i\ $ retract $\ X\ $ retracts $\ X\ $ onto
$\ i(X)\subseteq X. $
By Bourbaki theorem, $\ (X\ T)\ $ is Hausdorff
$\ \Leftrightarrow\ \Delta_X:=\{(x\ x):x\in X\ $ is closed in $\ X\times X.$ It follows that for Hausdorff spaces the said retract $\ i(X)\ $ is closed in $\ X.\ $ Indeed,
$$ i(X)\ :=\ \{x:\ i(x)=x\}\ =
   \ (i\triangle \text{Id}_X)^{-1}(\Delta_X) $$
for diagonal product function
$\ i\triangle \text{Id}_X : X\to X\times X.$
Great!. (This is obviously useful for Hausdorff spaces).
Let $\ \pi:\mathcal I\to 2^C\ $ be defined by
$$ \forall_{i\in\mathcal I}\quad \pi(i)\ :=
         \ \{c\in C:\ i\circ c = c\} $$
This is how idempotents of $\ \mathbf M\ $ point to the respective subsets of $\ X;\ $ or to closed subsets in the Hausdorff case -- I mean pointing to $\ \pi(i).$
Theorem

*

*$\ \forall_{i\ j\in\mathcal I}\quad(\,i\subseteq j
    \ \Rightarrow \pi(i)\subseteq\pi(j)\, ) $

*$\ \forall_{i\ j\in\mathcal I}\quad(\,(i\subseteq j
      \ \text{and}\ j\subseteq i)
    \ \Rightarrow\ \pi(i)=\pi(j)\, ) $

*$\ \forall_{i\in\mathcal I}\quad (\, i\in C
    \ \Leftrightarrow\ \pi(i)=\{i\} $
Another tool, the uc-morphisms and nuc-morphims, was mentioned in my answer to Dominic's-real-question. In topological language, if $\ i\ $ is a topological idempotent then $\ I(X)\ $ has or has not fpp when $\ i\ $ is an uc-morphism or nuc-morphism respectively.
These tools may serve as a starting point to a discussion of specific topological spaces or their classes.

A: $\DeclareMathOperator\End{End}$As shown in Todd Trimble's comment, the set of constant maps $X\to X$ is definable in $\End(X,\tau)$, as it consists of exactly the left-absorbing endomorphisms (i.e., $\phi\in\End(X,\tau)$ such that $\phi\circ\psi=\phi$ for all $\psi\in\End(X,\tau)$). Thus, an isomorphism $F\colon\End(X,\tau)\to\End(Y,\sigma)$ induces a bijection $f\colon X\to Y$ such that $F(c_x)=c_{f(x)}$ for all $x\in X$, where $c_x\colon X\to X$ is the constant-$x$ map. But then $F$ is completely determined by $f$ by
$$F(\phi)(f(x))=f(\phi(x))$$
for all $\phi\in\End(X,\tau)$: indeed, we have
$$c_{f(\phi(x))}=F(c_{\phi(x)})=F(\phi\circ c_x)=F(\phi)\circ F(c_x)=F(\phi)\circ c_{f(x)}=c_{F(\phi)(f(x))}.$$
Since we may as well assume that $X=Y$ and $f$ is the identity, it follows that:

Lemma 1. $(X,\tau)$ has a unique endomorphism monoid iff it is homeomorphic to all spaces of the form $(X,\sigma)$ such that $\End(X,\tau)$ and $\End(X,\sigma)$ are literally equal (i.e., a map $X\to X$ is an endomorphism of $(X,\tau)$ iff it is an endomorphism of $(X,\sigma)$.)

This implies

Proposition 2. If $(X,\le)$ is a total order which is isomorphic to its opposite order, then the Alexandrov space $(X,\tau)$ of upper sets of $(X,\le)$ has a unique endomorphism monoid. In particular, there exist such spaces of arbitrary cardinality.

Indeed, let $\sigma$ be a topology on $X$ such that $\End(X,\sigma)$ consists of the order-preserving maps. We may assume $|X|\ge2$. Then $\sigma$ cannot be indiscrete, hence we can fix $V\in\sigma$ and $a$ and $b$ such that $a\notin V$, $b\in V$. Assume first $a<b$. Then $\tau\subseteq\sigma$: consider an upper set $U\in\tau$. The map
$$\phi_{a,b,U}(x)=\begin{cases}b&x\in U,\\a&x\notin U\end{cases}$$
is order-preserving, hence $\phi_{a,b,U}\in\End(X,\sigma)$, and $\phi_{a,b,U}^{-1}[V]=U$, thus $U\in\sigma$. In fact, $\sigma=\tau$: if we assume for contradiction that $W\in\sigma$ is not an upper set, then the argument above shows that $\sigma$ also includes all lower sets, thus for any upper set $U$, $\phi_{b,a,U}\in\End(X,\sigma)$, but $\phi_{b,a,U}$ is not order-preserving if $U\notin\{\varnothing,X\}$.
Dually, if $a>b$, we obtain that $\sigma$ consists of all lower subsets of $X$, hence it is the Alexandrov topology corresponding to the opposite of $\le$, but this is homeomorphic to $(X,\tau)$ by our assumption on $\le$.

One can generalize the argument to a complete characterization for Alexandrov spaces. (Note that in particular, all finite spaces are Alexandrov.)  First, a lemma. If $(X,\tau)$ is a topological space, let $x\le_\tau y$ denote the specialization preorder $x\in\overline{\{y\}}$, and $x\sim_\tau y$ the indistinguishability equivalence $x\le_\tau y\land y\le_\tau x$.

Lemma 3. If $\End(X,\tau)=\End(X,\sigma)$, then ${\sim_\tau}={\sim_\sigma}$ unless one space is discrete and the other indiscrete.

Proof: If, say, $a\sim_\tau b$ but $a\nsim_\sigma b$, then all mappings $X\to\{a,b\}$ are in $\End(X,\tau)$, hence in $\End(X,\sigma)$, hence $(X,\sigma)$ is discrete, hence all mappings $X\to X$ are in $\End(X,\tau)$, hence $(X,\tau)$ is indiscrete lest $a\nsim_\tau b$. QED

Proposition 4. If $(X,\tau)$ is an Alexandrov space, then $\End(X,\tau)\simeq\End(Y,\sigma)$ if and only if

*

*$(Y,\sigma)$ is homeomorphic to $(X,\tau)$, or

*$(Y,\sigma)$ is homeomorphic to the opposite of $(X,\tau)$ (i.e., the Alexandrov space corresponding to $\ge_\tau$), or

*the two spaces are the discrete and indiscrete topologies on sets of the same cardinality.
Consequently, $(X,\tau)$ has a unique endomorphism monoid iff $(X,\le_\tau)\simeq(X,\ge_\tau)$, and $\tau$ is neither discrete nor indiscrete unless $|X|\le1$.

Proof: The right-to-left implication is clear. For the left-to-right implication, we may assume $X=Y$ and $\End(X,\tau)=\End(X,\sigma)$ as above.
Assume first that $\le_\tau$ is an equivalence (i.e., ${\le_\tau}={\sim_\tau}$). By Lemma 3, we may assume that ${\sim_\tau}={\sim_\sigma}$ and $\tau$ is not indiscrete. (If $\tau$ is indiscrete, then either $\sigma$ is discrete and we are done, or ${\sim}_\sigma={\sim}_\tau$, hence $\sigma$ is indiscrete, i.e., $\sigma=\tau$, and we are also done.) Since $\tau$ is the finest topology with indistinguishability relation $\sim_\tau$, this implies $\sigma\subseteq\tau$; on the other hand, if we fix $a\nsim_\tau b$, and w.l.o.g. $a\lnsim_\sigma b$, then $\phi_{a,b,U}$ is in $\End(X,\sigma)$ for all $U\in\tau$, hence $U\in\sigma$, i.e., $\sigma=\tau$.
If $\le_\tau$ is not an equivalence, let us fix $a\lnsim_\tau b$. This also implies we can fix $V\in\tau$ whose complement is not in $\tau$. Then $\phi_{a,b,V}\in\End(X,\tau)$ and $\phi_{b,a,V}\notin\End(X,\tau)$, hence $a\lnsim_\sigma b$ or $b\lnsim_\sigma a$. W.lo.g., we assume the former (the other choice leads to the opposite order). Then for each $U\in\tau$, $\phi_{a,b,U}\in\End(X,\tau)$ implies $U\in\sigma$, i.e., $\tau\subseteq\sigma$. Since $\tau$ is the finest topology with specialization preorder $\le_\tau$, if $\tau\subsetneq\sigma$, then (in view of ${\sim_\tau}={\sim_\sigma}$) there are $x,y$ such that $x\lnsim_\tau y$ and $x\nleq_\sigma y\nleq_\sigma x$. But as above, this contradicts $\phi_{x,y,V}\notin\End(X,\sigma)$ for suitable $V\in\tau$. Thus, $\tau=\sigma$. QED

The characterization can be easily extended to all non-$R_0$ spaces. Recall that $(X,\tau)$ is $R_0$ if $\le_\tau$ is symmetric (i.e., ${\le_\tau}={\sim_\tau}$).

Proposition 5. If $(X,\tau)$ is a non-Alexandrov non-$R_0$ space, then $(X,\tau)$ has a unique endomorphism monoid.

Proof: Assume that $\End(X,\tau)=\End(X,\sigma)$. Let us fix $a\lnsim_\tau b$. There exists $V\in\tau$ whose complement is not in $\tau$ (e.g., any open set separating $b$ from $a$); then $\phi_{a,b,V}\in\End(X,\tau)$ and $\phi_{b,a,V}\notin\End(X,\tau)$, hence (1) $a\lnsim_\sigma b$ or (2) $b\lnsim_\sigma a$. (In particular, $(X,\sigma)$ is not $R_0$.) If (1) holds, then for every $U\in\tau$, $\phi_{a,b,U}\in\End(X,\tau)$ implies $U=\phi_{a,b,U}^{-1}[b]\in\sigma$, i.e., $\tau\subseteq\sigma$. If (2) holds, then the same argument gives $\{X\smallsetminus U:U\in\tau\}\subseteq\sigma$.
Since $(X,\sigma)$ is not $R_0$ either, a symmetric argument implies that (1') $\sigma\subseteq\tau$, or (2') $\{X\smallsetminus U:U\in\sigma\}\subseteq\tau$. It is impossible that (1) and (2') hold together: this would imply that $\tau$ is closed under complement, whence it is $R_0$. Likewise, (2) and (1') are incompatible. Thus, the only two possibilities are that either (1) and (2) hold, in which case $\tau=\sigma$, or (1') and (2') hold, in which case $\tau$ and $\sigma$ are mutually opposite Alexandrov spaces. QED
Notice that $(X,\tau)$ is $R_0$ iff the Kolmogorov quotient $X/{\sim_\tau}$ is $T_1$. It is easy to see that:

Lemma 6. If $(X,\tau)$ and $(X,\sigma)$ are spaces such that ${\sim_\tau}={\sim_\sigma}$, then $\End(X,\tau)=\End(X,\sigma)$ iff $\End((X,\tau)/{\sim_\tau})=\End((X,\sigma)/{\sim_\sigma})$.

In view of Lemma 3, this gives a reduction of the remaining classification to $T_1$ spaces. Observe that an $R_0$ space $(X,\tau)$ is Alexandrov iff $(X,\tau)/{\sim_\tau}$ is discrete.

Corollary 7. If $(X,\tau)$ is an $R_0$ non-Alexandrov space, then $(X,\tau)$ has a unique mononorphism monoid iff the $T_1$ space $(X,\tau)/{\sim_\tau}$ has a unique monomorphism monoid.

A: NOTATION
$$ S_X\ :=\ \{\emptyset\ X\} $$
$$ D_X\ :=\ 2^X\ =\ \{A:\ A\subseteq X\} $$
Given an arbitrary set $\ X,\ $ topology $\ S_X\ $ is the smallest (the weakest) topology in $\ X;\ $ and the discrete topology $\ D_X\ $ is the largest (the strongest) topology in $\ X.$
--------------------
Here is a logically initial modest positive result:
Theorem   Let set $\ X\ $ be finite. Then for every non-discrete topological space $\ (Y\ T)\ $ (i.e. $\ T\ne D_Y),\ $ if monoids $\ \text{End}(X\ S_X)\ $ and
$\ \text{End}(Y\ T)\ $ are isomorphic then topological spaces $\ (X\ S_X)\,$ and $\,(Y\ T)\ $ are homeomorphic, i.e. $\,\ |Y|=|X|\ $ and $\ T=S_Y.$
Proof   If two monoids are isomorphic than they have the same number (cardinality) of constants (of the left-absorbing elements). Furthermore, the number of points of an arbitrary topological space is equal to the number the constants of its monoid of continuous self-maps.
Let's assume that monoids $\ \text{End}(X\ S_X)\ $ and
$\ \text{End}(Y\ T)\ $ are isomorphic. Then
$$ |X|\ =\ |Y| $$
Also,
$$ |\text{End}(X\ S_X)|\ =\ |\text{End}(Y\ T)|\ $$
hence
$$ |\text{End}(Y\ T)|\ =\ |\text{End}(X\ S_X)|
                \ =\ |X^X| $$
so that
$$ |\text{End}(Y\ T)|\ =\ |Y^Y| $$
This means that $\ T=S_Y\ $ or $\ T=D_Y\ $ hence,
by theorem's assumption, $\ T=S_Y\ $ --
otherwise $\ T\ $ would be not discrete nor the
smallest, i.e. there exists $\ G\ \in\ T\setminus S_Y\ $ and non-isolated $\ p\in Y\ $ (i.e. such that
$\ \{p\}\not\in T)$. Then consider $\ f:Y\to Y\ $ such that $ f(p)\in G\ $ and
$\ f(Y\setminus\{p\})\subseteq Y\setminus G.\ $ Such
$\ f\ $ is not continuous in $\ (Y\ T),\ $ hence
$$ |\text{End}(Y\ T)|\ <\ |Y^Y| $$
-- a contradiction.   End of PROOF
----------------
Remark For every set $\ X,\ $ monoids
$$ \text{End}(X\ S_X)\quad \text{and}\quad
        \text{End}(X\ D_X)\ $$
are isomorphic while the respective topological spaces $\ (X\ S_X)\ $ and $\ (X\ D_X)\ $ are not homeomorphic whenever $\ |X|>1.$


text:
Q: AJAX - No Refresh , loading auto refresh to another page My only problem is the page does not load auto refresh, tho it is loading when i refresh the page.. P.S Im loading the page to another page
here is my html and ajax code with its database.

My Trigger Button

    <?php
        $data = mysqli_query($con,"SELECT * FROM announcement");
        $count = mysqli_num_rows($data);
        if ($count != 0) {
            while($row = mysqli_fetch_array($data)) {
                echo '
                    <button class="btn btn-danger nav-link delannouncement" id="delannouncement">Resume System</button>';
                $dataid = $row['id'];
            }
        }else{
            echo '<button class="btn btn-primary nav-link announcement" id="announcement">Passenger Announcement</button>';
        }
    ?>

Fetching the Data in Database

Here is where I call the data in mysql from ajax to here.
$data = mysqli_query($con,"SELECT * FROM announcement");
    $count = mysqli_num_rows($data);
    if ($count != 0) {
      while($row = mysqli_fetch_array($data)) {
          echo '

Announcement

'.$row['additional_info'].'

Please click refresh button to resume after the announcement

';
                  $dataid = $row['id'];
          }
      }

        ?>


text:
Q: Statistical test should be used for comparing population means of skewed data I am trying to find out if the population means of 2 sets of data is significantly different at the 10% level. The 2 sets of data is the same size (25 sample points each), and is taken from the same sample but at different times. I plotted the data of each set and found that both sets of data is highly skewed towards the left, meaning that I cannot use T-test to compare the means. Does anyone have any suggestions on what test I could use to find if the 2 sets of data are significantly different or not.

A: When you say "from the same sample" it's not 100% clear whether you mean that you have two observations on each subject (paired data) or not. You should clarify.
There are several possibilities, of which I'll list some:

*

*If the variable is one for which you have a suitable distributional model, you may be able to derive a suitable test (e.g. a test based on the likelihood ratio, or one that's asymptotically equivalent to it). Taking account of a suitable model if you have one may lead to more powerful tests than other approaches.
If you want to add a little safety on significance level you could combine this (as a way to choose a statistic) with a permutation test; this has the advantage of offering good power if your model is close to correct while still keeping the significance level close to correct if your model is not as accurate.

*A test based on resampling, either a permutation test or a bootstrap test. At these sample sizes I'd be looking at a permutation test; if the distribution is continuous and the other assumptions hold (sufficient to have exchangeability under the null) this will guarantee your significance level is almost exactly correct (though power may not be all that great if the distribution is quite far from normal).

*If you're prepared to make some additional assumptions, including about the form of the alternative (assumptions that would make it correspond to a test of means), you may be able to use a suitable rank-based test, like a signed rank test (for paired data) or a Wilcoxon-Mann-Whitney (for unpaired data).

*If your distribution is not so strongly skew or heavy tailed you may get pretty close to the desired significance level with a t-test (presumably paired). As with item 2, even if the significance level is fine, there may be an issue with power.
If I was faced with this situation and didn't know much about the likely population distribution, I'd probably lean toward a straight permutation test. If your data are paired, this would presumably involve a one-sample permutation test on pair-differences.

A: Try bootstrapping. Here's one approach. Lump all samples into one bag of 50 observations. Run $k$ simulations as follows. Sample 25 observations $x_{ki}$ with replacement from the bag, and another 25 observations $z_{ki}$ with replacement. Calculate the differences $\Delta_k=\bar x_k-\bar z_k$ for your $k$ simulations, where $\bar x_k,\bar z_k$ are the averages (sample means) of the two samples. Now you can estimate the distribution of $\Delta_k$ and compare to the differences of sample means of original two sample, and run tests of significance. For instance if the original difference of means was $\Delta_o=\hat\mu_1-\hat\mu_2$, then you could compare it to standard deviation of the distribution of $\Delta_k$ or a percentile, under null hypothesis that $\Delta_o=0$


text:
Q: How to update user role totals I am working on a new site but I am using the users from an old site.
I created all my user roles, which match the user roles on the other site. I deleted the user and usermeta table from the new site and imported these tables from the old site.
I can now see all the users and I can login with the users. The issue I have is that the users, other than the primary admin, have no roles assigned.
When I check the database, I do see the proper role assigned to them.
'2039843', '308', 'wp_capabilities', 'a:1:{s:10:"subscriber";b:1;}'

When I am in the Users section of WordPress, I can see all the users but they have no roles "assigned" to them (even though it clearly is defined in the dataabase).
I am importing over 40,000 users so the database option seems the most fitting for my needs. Is there a snippet of code I can do to update this total perhaps? Where are these totals stored? I can tell, it's not scanning the usermeta table for these values so it has to be in the options table.
I already added the option for wp_user_roles and assigned it the same value as the old site, still no luck. No roles have totals and no users are assigned to the roles.
What is the best method to update the user role totals so WordPress will recognize the users are assigned properly to the roles?

A: You'll also need to export the old site's options table which is usually called wp_options and import it to new one. Cause in the options table aka wp_options table there is a row field called wp_user_roles and it holds the role values of the site.

A: Ok, this is something I didn't know...
The usermeta meta_key wp_capabilities is unique to your database prefix. Since I used a different prefix than wp_ this key is also prefixed with the same prefix.
Since I imported the data from a table that used the default prefix: wp_ The data I imported used the prefix from the other database. So all I had to do to fix this was to do an update to replace wp_capabilities with the PREFIX_capabilities and now it works as expected.
This was interesting to identify as I wouldn't think that an option key would be prefixed with the database prefix. This is a little bit of a concern because now I am not sure what uses the prefix vs what doesn't... Bad design IMHO


text:
Q: Android: extract link from String value I would like to have link from the share intent. When I receive a link via chrome its properly formatted, but sometimes other apps add text too.
Example:
Chrome: "www.recode.net/2016/7/21/12243560/google-machine-learning-comics-play"
Twitter: "Guys check out this link it's so cool https://www.recode.net/2016/7/21/12243560/google-machine-learning-comics-play"
So in case of twitter I would like to get rid of all the context and have only the link remaining,ie, www.recode.net/2016/7/21/12243560/google-machine-learning-comics-play
Note: Link may be of any format https://.. (or) www. .. (or) recode.net/... (without the www at the beginning).
Any regex to sort this out?
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_shareintent);

    // Get intent, action and MIME type
    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();

    if (Intent.ACTION_SEND.equals(action) && type != null)
    {
        if ("text/plain".equals(type))
        {
            // Handle text being sent
            handleSendText(intent);
        }
    }
}

void handleSendText(Intent intent)
{
    String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
    if (sharedText != null)
    {
        // Update UI to reflect text being shared
        TextView tvShare = (TextView) findViewById(R.id.tvShare);
        tvShare.setText(sharedText);
    }
}

A: The following method does the trick:
//Pull all links from the body for easy retrieval
public ArrayList<String> pullLinks(String text)
{
    ArrayList<String> links = new ArrayList<String>();

    //String regex = "\\(?\\b(http://|www[.])[-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|]";
    String regex = "\\(?\\b(https?://|www[.]|ftp://)[-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|]";

    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(text);

    while(m.find())
    {
        String urlStr = m.group();

        if (urlStr.startsWith("(") && urlStr.endsWith(")"))
        {
            urlStr = urlStr.substring(1, urlStr.length() - 1);
        }

            links.add(urlStr);
    }

        return links;
}

A: You could recognize and extract a particular pattern from the String.
// Pattern for recognizing a URL, based off RFC 3986
private static final Pattern urlPattern = Pattern.compile(
        "(?:^|[\\W])((ht|f)tp(s?):\\/\\/|www\\.)"
                + "(([\\w\\-]+\\.){1,}?([\\w\\-.~]+\\/?)*"
                + "[\\p{Alnum}.,%_=?&#\\-+()\\[\\]\\*$~@!:/{};']*)",
        Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);

Example :
Matcher matcher = urlPattern.matcher("foo bar http://example.com baz");
while (matcher.find()) {
    int matchStart = matcher.start(1);
    int matchEnd = matcher.end();
    // now you have the offsets of a URL match
}

reference: may be other answers there will be useful to you as well

A: You can just extract the Url from a string using the Matcher Class.following code will extract all the links included in the string to an array of Urls.
 Matcher webMatcher = Patterns.WEB_URL.matcher(stringWhichContainsUrl);
        ArrayList<String> hyperLinks = new ArrayList<>();

        while (webMatcher.find()) {
            String res = webMatcher.group();
            hyperLinks.add(res);
        }

        Log.e("links", hyperLinks.toString());


text:
Q: inserting into a XML file by Javascript, Jquery or Ajax Is there any way to insert some data into XML file??
For example, if there is a XML code like this
<charlist>
<list>
<title>gb</title>
<chr>Goodbye</chr>
`</list>
<list>
<title>ttyl</title>
<chr>talk to you later</chr>
</list>
</charlist>
How can i insert more data like "" into XML file.
I used "append" to add more data into a XML file, but it did not work.
Do I need to use Ajax or the others???

A: Short answer is you can't without using a server side language - you can append it in memory, but you'd have to use something else to store it forever ;)
note You could use HTML5 LocalStorage(), but this probably isn't what you are looking for :(


text:
Q: How to bring up an okay / cancel dialog box in Javascript? When I click on "delete post" on StackOverflow it brings up a window on the screen asking if I want to go ahead or if I want to cancel.
How can I do that in Javascript so that it will work in both a computer and on an IPad?

A: You can achieve it by using confirm, use the code as below:
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
confirm("Press a button!");
}
</script>

The above example is very basic, if you some designed confirm box then please check craftpip's jquery-confirm Hope you like it.

A: You can use confirm for this. It will return true or false depending on the user's action. Example:
var result = confirm("Please confirm this action!")
if(result)
    //The user confirmed the action
else
    //The user declined the action

A: As stated by others, use the confirm method.
You can get the callback from confirm like this:
confirm("Are you sure you want to do this?", function(result) {
if(result)
    doSomethingPositive();
else
    doSomethingNegative();
});


text:
Q: BASH CURL SCRIPT / Automatic Web Form Login I need to login automatically to a Wi-fi network with a shell script (terminal / OS X).
The web form submit is controlled through a Javascript:
function submitAction(){
      var link = document.location.href;
      var searchString = "redirect=";
      var equalIndex = link.indexOf(searchString);
      var redirectUrl = "";
      var urlStr = "";
      if(equalIndex > 0) {
            equalIndex += searchString.length;
            redirectUrl = link.substring(equalIndex);
            if(redirectUrl.length > 0){
        if(redirectUrl.length > 255)
            redirectUrl = redirectUrl.substring(0,255);         document.forms[0].redirect_url.value = redirectUrl;
        }
      }
      document.forms[0].buttonClicked.value = 4;
      document.forms[0].submit(); }

Two fields are used (password & username) and the form is method="post".
Question:
Is it possible to do this through a shell script in OS X? How do I proceed when the submit is triggered this way with Javascript?
Many thanks!

A: I don't know much about OS X but I think it can be helpful for you anyway.
This is what I did:

*

*Take FF + Firebug

*Go to Network tab in the Firebug and set persistent data.

*Do whatever you need to authenticate yourself via wifi router's
webpage.

*Find request the browser sent with the credentials.

*Click it with right mouse button and choose Copy as cURL

*Past it to the script file.

*If it's self signed SSL cert than append -k for CURL

*Enjoy


text:
Q: Квартал в DateTimePicker Как добавить квартал в  DateTimePicker?
DateTimePicker.ShowUpDown = true;

Хочу место календаря названия кварталов. Например: 1 квартал 2018 г. => (после нажатия up button) => 2 квартал 2018 г. => 3 квартал 2018 г. => 4 квартал 2018 г. => 1 квартал 2019 г. и т.д.
Может создать новый класс? Но как? Я не эксперт по с#


text:
Q: Twitter Bootstrap - Can't get form to display properly I have a form that I'm making in bootstrap but no matter what I do, I cant seem to get it to look how it looks in the tutorials. The label goes above the text box when it should be beside it, and the whole thing looks like it lacks any css formatting. Thanks for your help.
Here is the site that I'm working on and you can view the source code there:
aerofied.snbw.co/registration.php

A: bootstrap.min.js returns a 404 error and I believe this is the reason.
This is the URL that returns the error: http://aerofied.snbw.co/js/bootstrap.min.js
You should also read the Bootstrap documentation. You must use some specific classes for your forms.


text:
Q: If 8 (indistinguishable) blackboards are to be divided among 4 schools, how many divisions are possible if each school must receive 2 blackboards? I attempted to come up with a solution. Please verify that it is correct or explain if there is anything wrong with it.
Solution: Since each school must receive exactly 2 blackboards, we draw the stars and bars diagram as ..|..|..|..
Here, N=8 and r=3. We use (N-1 choose r-1) since no school can receive zero chalkboards. Thus, there are (7 choose 2) = 21 different possible divisions.

A: Your use of stars and bars is off. First of all, with $4$ schools, you have $r=4$, and thus $r-1=3$, rather than $2$.
But, more pressingly, the updated formula $7 \choose 3$ would give you the number of ways to divvy up the $8$ boards among the $4$ schools where each school gets at least one.  But, the constraint is that each school must receive exactly two. Your formula, for example, would count 'solutions' where two schools get $3$ boards, and the other two schools get $1$ board each, but that violates the constraint that each should get $2$. In short, the formula just does not apply.
Indeed, just using common sense the anwer must of course be $1$: there is exactly one way to give $8$ (indistinguishable) boards to $4$ schools, each receiving exactly $2$


text:
Q: ASW SES not sending emails with no-reply@my.domain I have a verified domain configured in SES. When I send an email with no-reply@my.domain, SES is not sending the email. If I use a valid email address from that domain, SES delivers them.
Does anyone know why this is happening? If my memory doesn't fail me, this used to work just fine as I've had this setup for years. Did something change recently in the AWS SES service?
I have looked for any mention regarding this and all I found is that the domain needs to be verified which it is.
Any help/insight would be greatly appreciated.

A: According to AWS SES documentation, such emails are hight not recommended

Avoid using a no-reply address, such as no-reply@example.com, as your
"From" or "Reply-to" address. Using a no-reply@ email address sends
your recipients a clear message: that you aren't offering them a way
to contact you, and that you're not interested in their feedback.

https://docs.aws.amazon.com/ses/latest/DeveloperGuide/tips-and-best-practices.html

A: In addition to the domain being verified, the sender email address that you want to use should be verified too. AWS will send you a mail to this address to confirm that it exists. If it doesn't exist, you can create a email receiving rule that will save the email into S3. You can then dig the verification link from there.


text:
Q: array sort ascending order - bubble sort I'm trying to arrange my array in an asscending order but its giving me a different value:
#include <iostream>

int main ()
{
    const int size = 5;
                //    0  1  2  3  4
    int arr[size] = {50,20,54,12,23};

    for (int i=0; i<5; i++) //! bubble sort ascending order
    {
        for (int j=i; j<5; j++)
        {   //      50        20
            if (arr[j] > arr[j+1])
            {
                int temp = arr [j+1];
                arr [j+1] = arr [j];
                arr [j] = temp;
            }
        }
    }

    for (int i=0; i<5; i++)
    {
        std::cout<<arr[i]<<" ";
    }

    return 0;
}

The fact that it is not working, could it be of the empty array value (arr[6]) at the end of the loop that is messing up with the overall value? If so, it should be able to sort up till the last array size but its giving a different output instead
Output: 20 12 0 23 50

A: To prevent out of bound problems, change:

*

*i<5 to size-1

*j<5 to size-1-i

*j=i to j=0
Code:
int main ()
{
    const int size = 5;
                //    0  1  2  3  4
    int arr[size] = {50,20,54,12,23};

    for (int i=0; i<size-1; i++) //! bubble sort ascending order
    {
        for (int j=0; j<size-1-i; j++)
        {   //      50        20
            if (arr[j] > arr[j+1])
            {
                int temp = arr [j+1];
                arr [j+1] = arr [j];
                arr [j] = temp;
            }
        }
    }

    for (int i=0; i<5; i++)
    {
        std::cout<<arr[i]<<" ";
    }

    return 0;
}


text:
Q: code php on line when import on ftp When i import my php files to ftp all the code of each file stands on 1 line. Then when there is a commentary it puts in commentary all the code that comes after. How to do to import file and keep  the form ?

A: I found the answer, i just had to change the uploading format. Put binary instead of automatic.


text:
Q: How do I store image ID in query-string? I've used "ImageFlow" on my personal website, and what I want to do is that when you click on an image, another page opens with the ID of the image stored in a query-string like when you are using $_get in a form. For example:
http://www.mywebsite.com/details.php?id=001
Then I'm going to use some databases to print some information on the page like:
Place: Lake Otawa
Date: 1/1-2011

And so on...
Thanks in advance :)

A: Hard to answer without any additional code.
Where is the image id stored?
Guessing this would do:
<a href="http://domain.com/image.php?id=<?php echo $image_id;?>">


text:
Q: Updating count items with behaviorsubject cross side component communication I have a angular 8 application. and I have two components. one component where you can edit a item. And one component where you can see all the items. The items are divided in four categories. And for each category there is a counter that counts the items in each category. If I add a item the counter increase, so that works correct. But if I delete a item. The counter doest'n decrease.
So I have this service:
 _updateItemChanged = new BehaviorSubject<any>([]);
  constructor() {}
}

and this is the
component where you can delete a item child component:
 remove() {
    this.dossierItemService.deleteDossierItem(this.data.dossierId, this.data.item.id)
      .subscribe(() => {
        this.dialogRef.close(true);
        this.itemListService._updateItemChanged.next(this.data.item.title);
      }, (error) => {
        const processedErrors = this.errorProcessor.process(error);
        this.globalErrors = processedErrors.getGlobalValidationErrors();
    });
  }

and this is the parent component.html:
  <span i18n>Action steps</span>{{ dossierItemsCountString(itemTypes.ActionStep) }}

and this is parent.ts code
 ngOnInit(): void {
    this.itemlistService._updateItemChanged.subscribe(data => {
      this.dossierItems  = this.dossierItems.filter(d => d.title !== data);
    });
}

and the dossierItemsCountString function:
 dossierItemsCountBy(itemType: DossierItemTypeDto) {
    return this.typeSearchMatches[itemType.toString()] || { total: 0, matches: 0 };
  }

  dossierItemsCountString(itemType: DossierItemTypeDto) {
    const count = this.dossierItemsCountBy(itemType);

    if (this.hasSearchQuery) {
      return `(${count.matches}/${count.total})`;
    } else {
      return `(${count.total})`;
    }
  }

So what I have to change so that in the parent component also the counter decrease if you remove a item.
Thank you

A: After the discussion we found that the problem is in mixed pointers among components and the proper way to fix it is to manipulate the original array, instead of creating new one.
The solution:
    this.itemlistService._updateItemRemoved.subscribe(data => {
      const index = this.dossierItems.findIndex(a => a.id === data.id);
      if (index !== -1) {
        this.dossierItems.splice(index, 1);
      }
    });


text:
Q: Spring Junit test entity not saved to repository I'm trying to test a service method that lists all entities. The method looks like this:
@Test
public void listAllProfiles() {
  Profile sampleProfile = Profile.createWithDefaultValues();
  profileRepository.save(sampleProfile);

  ProfileService profileService = new ProfileService(profileRepository, new ModelMapper());
  List<ProfileDto> profiles = profileService.listAllProfiles();
  ProfileDto lastProfile = profiles.get(profiles.size() - 1);

  assertEquals(sampleProfile.getId(), lastProfile.getId());
}

The test fails cause IndexOutOfBoundsException: Index -1 out of bounds for length 0
I found out that the sampleProfile is not probably saved during the test. When I log profileRepository.findAll().size() the value is always 0.
What is worng with my test?

A: If you want to test your ProfileService you have to mock the profileRepository cause if you don't do that then you are actually doing an integration test.
Unit testing is all about testing small units if there are any dependencies on those units you have to mock them (either manually or with a framework, Mockito is the most common one in the Java world).
If your service is using the repository to fetch all the profiles you have to mock that call, something like this:
 List<Profile> profilesList = Arrays.asList(new Profile("Profile 1"), new Profile("Proiile 2"));
 given(profileRepository.findAll()).willAnswer((Answer<List>) invocation -> profilesList);

So you shouldn't save anything in the database (actually, you shouldn't interact with a database at all when you are unit testing), you just mock the repository you are using on your service. Here is a project I wrote some months ago where I actually solved the exact same issue.


text:
Q: Maintaining privacy on the web? I just read an article about the Importance of anonymity on the web.. Is it possible to maintain anonymity using services like Ubuntu One, and are there any native system tools within Ubuntu that will help me to maintain privacy and/or anonymity? I'm using Ubuntu 11.10 64bit.

A: The measures you take to protect your privacy depend on the concessions you are willing to make in order to make use of different services.  For example, if you decide to use Facebook, you will have filled out some info which is then visible to your contacts.  Any FB applications that you use will have had access to some of your info and could just as well have recorded and stored it in a database elsewhere. If you use a service like Google Docs or Dropbox, you are giving your files to a third party and trusting that they will not breach that trust.
A lot of your privacy measures will be up to you and the information you supply, I don't think tools can help you very much.  Sure, you could browse through a proxy but if you give information to a website, then that kind of defeats the point.
A few things you can attempt to do:

*

*When signing up to a website that you won't be visiting regularly, lie about your details.  But remember the lies in case you ever need them again.

*Browse with cookies turned off, although you may experience a somewhat crippled web experience with this

*Browse with JavaScript turned off: You can accomplish this with a browser extension called 'scriptblock' and whitelist the websites that you need/trust.  Again, it'll be a very different experience with scripts turned off.  Some websites simply won't work.

*Browse using a proxy service (you can even pay for proxy servers) so that your IP address isn't available to the party recording it

A: "Internet Privacy" is a very broad issue and some of the tools that can be used to track you are quite sophisticated, and some of the tracking tools do not have anything to do with your OS.
Here are some very broad suggestions
TOR
https://www.torproject.org/
Your ip address is only one piece of data that can be used to track you. I say this because a lot of people suggest TOR. Not that TOR does not have uses mind you, you should at least be aware of it's limitations as well.
If you are going to use tor with any reliability, you really need to read the documentation. Not just the installation guide, but all of the information, including the information of proxies and DNS leaks.
The tor project has very pertinent information on using tor, including this
https://www.torproject.org/download/download-easy.html.en#warning
In fact, the tor project advises you download the "tor bundle"
https://www.torproject.org/download/download-easy.html.en
Which includes tor, Vidalia , and patched applications.
Browser
Your choice of browser is also important. Some browsers (chrome) "phone home".
http://lifehacker.com/5763452/what-data-does-chrome-send-to-google-about-me
You should take the time to search the information your browser sends.
Browser settings
Your browser settings are important. Most browsers have a privacy mode, you should use it.
The issues here are cookies, flash cookies, html5 cookies.
It is possible for web sites to view your history and bookmarks ;)
Search engines
What search engine do you use ?
Take a look at this page:
https://www.ixquick.com/eng/protect-privacy.html
Passive OS Fingerprinting
Beware your IP address is not the only way you can be tracked.
See
https://panopticlick.eff.org/
technical details
http://www.ouah.org/incosfingerp.htm
If the above link is a little too technical, see
http://net.tutsplus.com/tutorials/other/http-headers-for-dummies/
The thing that "hurts" with these tools, the more you try to hide, the more you stand out. Try it, use a proxy server to filter the information your browser sends and you will be more and more unique.
Conclusions
It is extremely difficult to remain anonymous and requires education and diligence.
You can not be anonymous simply by installing an application, you have to change your behaviors as well (see the tor pages I linked).

A: Anonymity
For anonymity you can use Tor, which will make your real IP virtually impossible to detect. When you setup Tor you will use internet through a proxy, so all the information you send or receive (including Ubuntu One file transfers) will go through Tor and be made anonymous.
Security
For security, I believe there are some commercial antiviruses for Linux (though I don't really see a need for one, been using Ubuntu for years without antivirus and computer runs perfect).
You can also use a firewall, I believe Ubuntu runs UFW naturally. This will prevent people from breaking into your computer through ports.


text:
Q: Sorting string according to the ascending order of the last word I have a list of strings that is stored in:
List<String> unsorted = new ArrayList<String>();

Given my input strings are:
Mohammad Ali: salary is 24K, annual raise is 10% has balance of 317146.70
Steve Gates: salary is 36K, annual raise is 5% has balance of 474608.11
Michael Jordan: salary is 71K, annual raise is 7% has balance of 934461.89
Lora Star: salary is 104K, annual raise is 2% has balance of 1364777.40
Donald Kim: salary is 44K, annual raise is 1% has balance of 577470.66
Bill Jobs: salary is 54K, annual raise is 0% has balance of 706933.71

I want to print out the strings one by one based on ascending order of their balance i.e. the last value in the string.
Comparator<String> cmp = new Comparator<String>() {
      public int compare(String o1, String o2) {
        return (Integer.valueOf(o1.substring(o1.lastIndexOf(" ")+1)).compareTo(Integer.valueOf(o2.substring(o2.lastIndexOf(" ")+1))));
      }
    };

    Collections.sort(unsorted, cmp);

    for (int i = 0; i < unsorted.size(); i++){
      System.out.println(unsorted.get(i));
    }
  }

However, when I try to run the program, I am met with the error:
java.lang.NumberFormatException: For input string: "474608.11"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.valueOf(Unknown Source)
    at Main$1.compare(Main.java:35)
    at Main$1.compare(Main.java:1)
    at java.util.TimSort.countRunAndMakeAscending(Unknown Source)
    at java.util.TimSort.sort(Unknown Source)
    at java.util.Arrays.sort(Unknown Source)
    at java.util.ArrayList.sort(Unknown Source)
    at java.util.Collections.sort(Unknown Source)
    at Main.main(Main.java:39)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:267)

May I know how to resolve this?


text:
Q: Using Amadeus flight search API, how does my users search for flight when they don't have location code I am using amadeus flight search API, built the endpoint with PHP and tested on postman, working perfectly now i am worried about how my users will use the frontend to search for flight, do they have to know the city codes to be able to search for flights? I want a situation whereby they just entered the names of the cities in the form from my frontend and they get to search for flights not entering city codes

A: All the airport and city codes are based on IATA standard.
Amadeus provides also another API to get this information : Airport and city search API. you can integrate this so that your user can type a keyword for your application to get the corresponding codes.

A: Thanks everyone for the contribution, i am really grateful, though i discovered getting list of JSON data of IATA codes, cities, and countries in my frontend application and then using javascript filter to search through responding to the onChange event handler from the user's form will solve the problem, once again i appreciate everyone contributions, i am really grateful


text:
Q: Update multiple rows in a table with one SQL statement with a computed value per row I have a scenario whereby I have a table of data I wish to import into my schema. The key field on the import t\ble AND my target table is a field called MEMBERNO
Before importing, I check if any of the rows in the import table have a MEMBERNO that currently exists within the target table. If so, I wish to amend the MEMBERNO on the import table to the next available value before starting the import (a simple INSERT INTO targetTable SELECT * FROM importTable)
The next available MEMBERNO is currently identified by adding 1 to SELECT MAX(MEMBERNO) FROM targetTable - can I apply this function to several rows in one SQL statement or will I have to create a cursor to loop through? Ideally, I would like to have one UPDATE statement where the value to set is "moving" but I'm not sure this is possible
So something like...
UPDATE importTable SET MEMBERNO = nextavailablenumber
   WHERE MEMBERNO IN (SELECT MEMBERNO FROM targetTable)

where nextAvailableNumber is computed for each UPDATE

A: You don't even need to do the update, you can do the check and alter the MemberNo all within the insert to the Target table
INSERT TargetTable (MemberNo, Column1, Column2, Column3)
SELECT  MemberNo = CASE WHEN t.MemberNoExists IS NULL THEN i.MemberNo
                        ELSE n.NextMemberNo + ROW_NUMBER() OVER(PARTITION BY t.MemberNoExists ORDER BY i.MemberNo)
                    END,
        i.Column1,
        i.Column2,
        i.Column3
FROM    ImportTable i
        OUTER APPLY
        (   SELECT  TOP 1 MemberNoExists = 1
            FROM    TargetTable t
            WHERE   t.MemberNo = i.MemberNo
        ) t
        CROSS JOIN
        (   SELECT  NextMemberNo = MAX(MemberNo)
            FROM    TargetTable
        ) n;

The subquery t simply generates 1 when the MemberNo already exists, and NULL when it doesn't. If it doesn't exist then the MemberNo from the import table is used.
The subquery n gets the maximum MemberNo in the target table. This is only used where the MemberNo from the import table already exists. Then, so that you don't need a loop it uses ROW_NUMBER to increment this maximum MemberNo by one for each new row to avoid duplicates.
Example on SQL Fiddle (Only with SELECT for demonstration purposes)
If you do still need to do the update you can use a similar query:
WITH Import AS
(   SELECT  NewMemberNo = n.NextMemberNo + ROW_NUMBER() OVER(ORDER BY i.MemberNo),
            i.MemberNo
    FROM    ImportTable i
            CROSS JOIN
            (   SELECT  NextMemberNo = MAX(MemberNo)
                FROM    TargetTable
            ) n
    WHERE   EXISTS
            (   SELECT  1
                FROM    TargetTable t
                WHERE   t.MemberNo = i.MemberNo
            )
)
UPDATE  Import
SET     MemberNo = NewMemberNo;

UPDATE example on SQL Fiddle


text:
Q: camera focus distance test I'm developing an Android app that requires 2.3 Gingerbread. There's a functionality to get the subject distance in the camera, but on my phone it returns 0.
http://developer.android.com/reference/android/hardware/Camera.Parameters.html#getFocusDistances(float[])
Can someone with Gingerbread test this app in the attachment? It launches the camera and when you press the middle button on your phone, it prints out the subject distances. On my phone I get [auto,0,0,0]. Can anyone pls post what they get on their phone?
For the source code please see this question
Camera focus distances
Here's the attachment
http://forum.xda-developers.com/attachment.php?attachmentid=645665&d=1309825196

A: The source-code you reference works, but this measuring technique seems to be very anaccurate.
I think the camera hardware in most smartphones is unsuitable for this task.


text:
Q: How to deal with multiple versions of dependencies? Hi I have a problem with a dependency hierarchy I am unsure how to solve:
alt text http://img525.imageshack.us/my.php?image=56330713it2.jpg
http://img525.imageshack.us/my.php?image=56330713it2.jpg
The problem is with how I should reference these dependencies from MyProject project. I have built BaseProject and the CommonUtil(version 1.0) it was built with into assemblies. Now in MyProject I am using classes from CommonUtil and I am unsure if I should reference the CommonUtil.v.1.0 or if I could/should reference the current version of CommonUtil (v 2.0).
Which CommonUtils assembly should I reference from my MyProject?
I cannot reference both assemblies as VS tells me it cannot determine which assembly to use as they both contain some of the same methods. If I only reference v.1.0 I would perhaps not have everything I need from v.2.0 and If I only reference v.2.0 I would perhaps not have all capabilities in v.1.0 (which BaseProject) needs.

A: If you are using the classes that BaseProject returns directly within MyProject, you need to stick with the same version (1.0). But if BaseProject only uses those classes internally and does not share with MyProject, you can safely use the new version (2.0).
Best practice: strongly name your assemblies so that the compiler can help you out.


text:
Q: Hung Processes in Apache? I'm running Apache 2.2.21 with the MPM prefork on a dedicated server.  More details:
Server Version: Apache/2.2.21 (Unix) mod_ssl/2.2.21 OpenSSL/1.0.0-fips DAV/2 SVN/1.7.0 mod_python/3.3.1 Python/2.6.5 mod_bwlimited/1.4 PHP/5.3.6

Traffic is usually somewhere between 10-30 requests/sec, there's 12GB of RAM, and we've tuned MaxClients fairly conservatively (250).  We do see spikes of usage for various reasons (on an older server, we hit our MaxClients of 100 several times during these spikes).
Anyways, this is a new server.  After running for a while, our Apache status starts to look something like this:
GGG_._._RC_.G..C.G_G.C_G..C_.CG_._._G__W____..R.WCR_.W..G_......

The G's ("Gracefully finishing") are getting stuck.  They only disappear if I restart Apache.  This will definitely cause us to hit our MaxClients limit without regular monitoring/fixing.  I read around on the internet and there seems to be a bug in Apache that is similar to this, but happens under different conditions.  It was also apparently fixed in version 2.2.14.
I'm included the stacktrace of a hung process for your inspection.
#0  0x000000350c6f119e in __lll_lock_wait_private () from /lib64/libc.so.6
#1  0x000000350c67c138 in _L_lock_9164 () from /lib64/libc.so.6
#2  0x000000350c679a32 in malloc () from /lib64/libc.so.6
#3  0x000000350c66fcfb in __libc_message () from /lib64/libc.so.6
#4  0x000000350c675676 in malloc_printerr () from /lib64/libc.so.6
#5  0x000000350c675aa1 in malloc_consolidate () from /lib64/libc.so.6
#6  0x000000350c677f38 in _int_free () from /lib64/libc.so.6
#7  0x0000003906c64cbb in my_once_free () at my_once.c:117
#8  0x0000003906c5d6ff in my_end (infoflag=0) at my_init.c:170
#9  0x0000003906c5c547 in mysql_server_end () at libmysql.c:209
#10 0x00007f34ac195be8 in zm_shutdown_mysqli (type=<value optimized out>, module_number=22)
    at /home/cpeasyapache/src/php-5.3.6/ext/mysqli/mysqli.c:834
#11 0x00007f34ac2b825f in module_destructor (module=0x1eafce0) at /home/cpeasyapache/src/php-5.3.6/Zend/zend_API.c:2098
#12 0x00007f34ac2be945 in zend_hash_apply_deleter (ht=0x7f34ac988aa0, p=0x1eafc80) at /home/cpeasyapache/src/php-5.3.6/Zend/zend_hash.c:614
#13 0x00007f34ac2bebd8 in zend_hash_graceful_reverse_destroy (ht=0x7f34ac988aa0) at /home/cpeasyapache/src/php-5.3.6/Zend/zend_hash.c:649
#14 0x00007f34ac2b3085 in zend_shutdown () at /home/cpeasyapache/src/php-5.3.6/Zend/zend.c:759
#15 0x00007f34ac26017a in php_module_shutdown () at /home/cpeasyapache/src/php-5.3.6/main/main.c:2146
#16 0x00007f34ac260229 in php_module_shutdown_wrapper (sapi_globals=<value optimized out>)
    at /home/cpeasyapache/src/php-5.3.6/main/main.c:2118
#17 0x00007f34ac33a461 in php_apache_child_shutdown (tmp=<value optimized out>)
    at /home/cpeasyapache/src/php-5.3.6/sapi/apache2handler/sapi_apache2.c:399
#18 0x00007f34ae59dea4 in run_cleanups () from /usr/local/apache/lib/libapr-1.so.0
#19 0x00007f34ae59cd72 in apr_pool_destroy () from /usr/local/apache/lib/libapr-1.so.0
#20 0x00000000004cc004 in clean_child_exit ()
#21 0x00000000004ccd00 in child_main ()
#22 0x00000000004cce62 in make_child ()
#23 0x00000000004cd107 in perform_idle_server_maintenance ()
#24 0x00000000004cd664 in ap_mpm_run ()
#25 0x000000000042e24f in main ()

It looks like the problem happens when our PHP script closes the mysqli connection.  There's a hang when attempting to free memory.  Anyone with a similar configuration - Apache 2.2.21, PHP 5.3.6, MySQL/mysqli (5.1.56) - having similar issues?
Anyone know what I can attempt to do to fix this? Upgrade MySQL/Apache/PHP?  I'm happy to provide more information if it helps.
Thanks!
UPDATE: Seems like MySQL isn't really involved in the problem.  Here's another stacktrace of a hanging process that only includes PHP:
#0  0x000000350c6f119e in __lll_lock_wait_private () from /lib64/libc.so.6
#1  0x000000350c67c138 in _L_lock_9164 () from /lib64/libc.so.6
#2  0x000000350c679a32 in malloc () from /lib64/libc.so.6
#3  0x000000350c66fcfb in __libc_message () from /lib64/libc.so.6
#4  0x000000350c675676 in malloc_printerr () from /lib64/libc.so.6
#5  0x000000350c675aa1 in malloc_consolidate () from /lib64/libc.so.6
#6  0x000000350c677f38 in _int_free () from /lib64/libc.so.6
#7  0x00007f532accb951 in zend_mm_shutdown (heap=0x2327aa0, full_shutdown=1, silent=<value optimized out>) at /home/cpeasyapache/src/php-5.3.6/Zend/zend_alloc.c:1648
#8  0x00007f532ac951af in php_module_shutdown () at /home/cpeasyapache/src/php-5.3.6/main/main.c:2159
#9  0x00007f532ac95229 in php_module_shutdown_wrapper (sapi_globals=<value optimized out>) at /home/cpeasyapache/src/php-5.3.6/main/main.c:2118
#10 0x00007f532ad6f461 in php_apache_child_shutdown (tmp=<value optimized out>) at /home/cpeasyapache/src/php-5.3.6/sapi/apache2handler/sapi_apache2.c:399
#11 0x00007f532cfd2ea4 in run_cleanups () from /usr/local/apache/lib/libapr-1.so.0
#12 0x00007f532cfd1d72 in apr_pool_destroy () from /usr/local/apache/lib/libapr-1.so.0
#13 0x00000000004cc004 in clean_child_exit ()
#14 0x00000000004ccd00 in child_main ()
#15 0x00000000004cce62 in make_child ()
#16 0x00000000004cd107 in perform_idle_server_maintenance ()
#17 0x00000000004cd664 in ap_mpm_run ()
#18 0x000000000042e24f in main ()

UPDATE 2:  Turns out this is a known problem for some systems.
http://docs.cpanel.net/twiki/bin/view/EasyApache3/EA3KnownIssues#Bug:%20Apache%202.2%20Child%20Processes
I've noticed I'm also getting "C" status Apache processes hanging around for quite some time (>3000 seconds).  I've written a cron to kill processes hanging in either "G" or "C" status for a long time... but that's a band-aid.  I'd like to fix the problem.
One thing I noticed, and also changed, about my configuration was that I wasn't setting thie "GracefulShutdownTimeout" directive:
http://httpd.apache.org/docs/2.2/mod/mpm_common.html#gracefulshutdowntimeout
I added this and changed it to 30 seconds.  We'll see if that also helps.
More Info:  Here's the output of cat /proc/PROCESS_ID/status for one of the "G" processes:
Name:   httpd
State:  S (sleeping)
Tgid:   14867
Pid:    14867
PPid:   30017
TracerPid:      0
Uid:    99      99      99      99
Gid:    99      99      99      99
Utrace: 0
FDSize: 64
Groups: 99
VmPeak:   355752 kB
VmSize:   222996 kB
VmLck:         0 kB
VmHWM:    191120 kB
VmRSS:     77928 kB
VmData:    62300 kB
VmStk:        96 kB
VmExe:      1032 kB
VmLib:     24736 kB
VmPTE:       488 kB
VmSwap:        0 kB
Threads:        1
SigQ:   0/95107
SigPnd: 0000000000000000
ShdPnd: 0000000000000000
SigBlk: 0000000000000000
SigIgn: 0000000000001000
SigCgt: 000000018c0046eb
CapInh: 0000000000000000
CapPrm: 0000000000000000
CapEff: 0000000000000000
CapBnd: ffffffffffffffff
Cpus_allowed:   ffffff
Cpus_allowed_list:      0-23
Mems_allowed:   00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000003
Mems_allowed_list:      0-1
voluntary_ctxt_switches:        24708
nonvoluntary_ctxt_switches:     2651

Loaded Modules in Apache:
 core_module (static)
 authn_file_module (static)
 authn_default_module (static)
 authz_host_module (static)
 authz_groupfile_module (static)
 authz_user_module (static)
 authz_default_module (static)
 auth_basic_module (static)
 include_module (static)
 filter_module (static)
 log_config_module (static)
 logio_module (static)
 mime_magic_module (static)
 expires_module (static)
 setenvif_module (static)
 ssl_module (static)
 mpm_prefork_module (static)
 http_module (static)
 mime_module (static)
 dav_module (static)
 status_module (static)
 autoindex_module (static)
 info_module (static)
 suexec_module (static)
 cgi_module (static)
 dav_fs_module (static)
 dav_lock_module (static)
 negotiation_module (static)
 dir_module (static)
 actions_module (static)
 userdir_module (static)
 alias_module (static)
 rewrite_module (static)
 so_module (static)
 python_module (shared)
 dav_svn_module (shared)
 authz_svn_module (shared)
 bwlimited_module (shared)
 php5_module (shared)

Loaded Modules in PHP:
[PHP Modules]
bcmath
Core
ctype
curl
date
dom
eAccelerator
ereg
exif
filter
gd
gettext
hash
iconv
imap
json
libxml
mbstring
mcrypt
memcache
mysql
mysqli
openssl
pcre
PDO
pdo_mysql
pdo_sqlite
posix
Reflection
session
SimpleXML
sockets
SPL
SQLite
sqlite3
standard
tokenizer
xml
xmlreader
xmlwriter
zlib

[Zend Modules]
eAccelerator

A: Try setting Keepalive Off.  I tend to do this automatically, especially on IO-contended systems, like virtual machines.

A: Some general guidelines I work by, sorry if this is not immediately feasible for you:

*

*use the worker MPM

*avoid mod_<language>

*instead use the fcgi interfaces PHP, Python etc. provide

*use mod_fcgid
If you're not modifying HTTP headers or similar in your application, you might be able to make the switch to fcgi without any code changes.
What you gain by this is a much cleaner separation of the various elements that take play in this setup. The httpd will be a lot more robust against any bugs (performance-, but also security-wise) that third party modules inflict.


text:
Q: aggregate function error in case expression I have this query
SELECT mylearning.Employee_Id,
 case
        when max(case when not mylearning.CourseStatusTXT = 'Completed' then 1 else 0 end) = 0 then '2018 Complete'
        when max(case when mylearning.CourseStatusTXT in ('Started', 'Not Started') then 1 else 0 end) = 1 then '2018 Not Complete'
  end as Completion_Status
FROM  Analytics.myLearning_Completions as mylearning inner join Analytics.Workday WD on mylearning.Employee_ID = WD.Employee_ID

And I want to add a condition to the first when statement to make it like this
 when max(case when not mylearning.CourseStatusTXT = 'Completed' then 1 else 0 end) = 0
             and WD.Adjusted_Hire_Date like '2019% '
            and mylearning.CourseTimeCompletedH < cast (WD.Adjusted_Hire_Date as date format 'YYYY/MM/DD') +7
             then '2018 Complete'

but I keep getting this error
Executed as Single statement.  Failed [3504 : HY000] Selected non-aggregate values must be part of the associated group.
Elapsed time = 00:00:00.069

How can I fix it?

A: Like a couple others mentioned, you are trying to mix grouped data with non-aggregated data in your calculation, which is why you're getting the 3504 error.  You need to either include the referenced columns in your GROUP BY or include them inside an aggregate function (i.e. MAX).
I'm not 100% sure if this is what you're after, but hopefully it can help you along.
SELECT
  mylearning.Employee_Id,
  CASE
    WHEN
      MAX(CASE WHEN NOT mylearning.CourseStatusTXT = 'Completed' THEN 1 ELSE 0 END) = 0 AND
      WD.Adjusted_Hire_Date like '2019% ' AND
      -- Check if most recently completed course is before Hire (Date + 1 week)
      MAX(mylearning.CourseTimeCompletedH) <
      CAST(WD.Adjusted_Hire_Date AS DATE FORMAT 'YYYY/MM/DD') + 7
    THEN '2018 Complete' -- No incomplete learnings
    WHEN MAX(
      CASE WHEN mylearning.CourseStatusTXT IN ('Started', 'Not Started') THEN 1 ELSE 0 END
    ) = 1 THEN '2018 Not Complete' -- Started / Not Started learnings exist
  END AS Completion_Status
FROM Analytics.myLearning_Completions as mylearning  -- Get learning info
INNER JOIN Analytics.Workday WD on mylearning.Employee_ID = WD.Employee_ID -- Employee info
GROUP BY mylearning.Employee_Id, WD.Adjusted_Hire_Date

This will give you a summary per employee, with a couple assumptions:

*

*Assuming employee_ID value in Analytics.Workday is a unique value (one-to-one join), to use WD.Adjusted_Hire_Date in your comparisons, you just need to include it in the GROUP BY.

*Assuming you have multiple courses per employee_Id, in order to use mylearning.CourseTimeCompletedH in your comparisons, you'd need to wrap that in an aggregate like MAX.
The caveat here is that the query will check if the most recently completed course per employee is before the "hire_date" expression, so I'm not sure if that's what you're after.
Give it a try and let me know.

A: The issue here is that you are mixing detail row by row information in the same query as group or aggregated data.  Aggregated data will output a single value for all the rows unless you have a group by clause.  If you have a group by clause then it will output a single value for each group.  When you are grouping you can also include any values that are in the group by clause since they will be unique for the group.
if you want this data for each employee, then you could group by employee_id.  Any other data would need to also be an aggregate like Max(Adjusted_Hire_Date)

A: Maybe this is what you want?
SELECT
  mylearning.employee_id
  , case
    when CourseStatusTXT = 'Completed' and WD.Adjusted_Hire_Date like '2019%'
      and mylearning.CourseTimeCompletedH < cast (WD.Adjusted_Hire_Date as date format 'YYYY/MM/DD') +7
    then '2018 Complete'
    else '2018 Not Complete'
  end CompletionStatus
FROM  myLearning_Completions mylearning, Workday WD
WHERE mylearning.employee_id = WD.employee_id


text:
Q: Call delete on std::vector Do I have to call delete on the destructor of a class that uses std::vectors ?
If not, why?
For example:
Test.h:
class Test
{
private:
    // Signal buffer for RAW signal and Moving Average
    std::vector<double> BUFFER; // Sensor signal buffer
...

}

Test.cpp:
#include "Test.h"

Test::~Test()
{
    // no delete for std:vector as they use STD memory allocation ???
}

Test::Test()
{
    BUFFER.reserve(100); // Who is going to free this memory?
}

Thanks

A: No, you don't. You only use delete to match a use of new. Since (in this case) you used auto storage class, the vector will be deleted automatically when the Test that owns it is destroyed.

A: No you do not need to explicitly destroy or delete it.  The vector is held by value in your class, so will be destroyed automatically, and the data inside the vector will be deleted by the vector's own destructor.
The term for all this is RAII, and it works really well.


text:
Q: Using set-builder notation to express a function I would like to use set builder notation for the following text:
The functions maps a series of numbers (L) (assume all positive) to a list of sub-partitions (P). Each sub-partition contains some elements of the L. The union of all sub-partitions is L and there is no common element between two sub-partitions. Also each sub-partition has at least one element.
$f: L  \rightarrow P$
$P=\{p: |p_i| \geq 1,   \cup p_i=U,  \cap p_i= \phi\}$
$p_i=[L_{ab}], 1 \leq a,b  \leq m$ (where $m$ is the number of elements in L)
For example, if $L=\{2,4,5,10\}$, then $p_1=[2,4,5]$ (or $L_{13}$). Therefore $P=\{(2,4,5),(10)\}$. I would like to know if the notations are correct in the set-builder rules and reader understands that. If you think another representation is more meaningful, please let me know.


text:
Q: Auto Increment ID is skipping the values in SQL Server. How can i prevent it? Step 1: Create Table
CREATE TABLE [dbo].[AAA](
[id] [int] IDENTITY(1,1) NOT NULL,
[name] [nchar](10) NOT NULL,
[last] [nchar](10) NOT NULL)

Step 2: Insert Correct Value
insert into aaa values ('lkj', 'lkj')

This will Generate ID - 1
Step 3: Try to Insert Incorrect Value
insert into aaa values ('lkj', NULL)

This will error and no record will be inserted
Step 4:
insert into aaa values ('lkj', 'lkj')

This will insert again, But ID generated will be - 3 (Not 2)
Because ID 2 was generated at Step 3 but no record was inserted.
I want that when I next enter any record ID generated should be 2 and not 3.
I have searched and found solution for MySQL below, but I want it in SQL Server:
alter table tablename auto_increment =1

OR
alter table tablename auto_increment =#

Also there is another solution I found...
declare @max int;
select @max = max(key) from table;
dbcc checkident(table,reseed,@max)

This code is good and it works. But I have to execute this every time there is a skipped ID... Isn't there a permanent fix for this problem? I want something like "execute it once and then forget about it..." I am facing this problem on production server so I want a permanent solution. I am using entity framework for inserting data so i cant use this query every time.
Please let me know any way to fix it. Either in SQL Server 2012 or in Entity Framework 6.
Thanks in Advance.


text:
Q: "Did you check if […]" Is this a grammatically correct/formal way to ask the question of this type? Here is an example

Hey, did you check if the payment went through?

What's the better way to rephrase it?

A: I think yours works. This might sound nicer:

Hey, did you check whether the payment went through?

A: Please, make sure your payment went through before [whatever].

A: Consider:   Did you check "whether" the payment went through?  "If" not, you should check as soon as possible.  This demonstrates the use of "if" and "whether" in the context.