text:
Q: Capistrano Laravel 4.1.x deployment fails on artisan command So the background on this is I am deploying this to a shared hosting account.
I have had other deployments to different domains work without a problem but for some reason this one is giving me grief.
I can't seem to sort out what is causing artisan to fail.
I had to roll back my Laravel version as this host doesn't have support for PHP 5.4 so I don't know if this could have been an issues.  I went to the source for Laravel 4.1 and ensured that the files were the proper versions for artisan and a couple others.
The PHP version on this server is a fast CGI build apparently, but I have even tried updating the deployment commands from 'php' to 'php-cli' and get a failure but it isn't the one below with a 500 error, just no more information on the failure.
I have downloaded the composer.phar file, CHMOD 777 on it and stored it in the root of the account which is where the other one is for another account I have this working for.
* 2014-09-21 13:04:19 executing `deploy:migrate'
* executing "php /home/username/domaincom/releases/20140921170416/artisan migrate"
servers: ["domain.com"]
[domain.com] executing command
** [out :: domain.com] Status: 500 Internal Server Error
** [out :: domain.com] X-Powered-By: PHP/5.3.27
** [out :: domain.com] Content-type: text/html
** [out :: domain.com]
command finished in 381ms
*** [deploy:create_symlink] rolling back
*** no previous release to rollback to, rollback of symlink skipped
*** [deploy:update_code] rolling back
* executing "rm -rf /home/username/domain.com/releases/20140921170416; true"

I am at a loss on this and am reaching the point of frustration.  I would like to be able to utilize my shared reseller plan to be able to build and host Laravel sites but at this rate I am going to have to either purchase another reseller for these or an AWS micro per which I would rather not due as I have the resources already.
Any recommendations / suggestions are welcome.  I just need to sort this out.
EDIT:
Added full deployment script output.
triggering load callbacks
* 2014-09-21 13:04:10 executing `production'
triggering start callbacks for `deploy'
* 2014-09-21 13:04:10 executing `multistage:ensure'
* 2014-09-21 13:04:10 executing `deploy'
* 2014-09-21 13:04:10 executing `deploy:update'
** transaction: start
* 2014-09-21 13:04:10 executing `deploy:upload_config'
servers: ["domain.com"]
** sftp upload #<StringIO:0x00000001a33ff8> -> /home/username/domain.com/shared/config/database.php
[domain.com] /home/username/domain.com/shared/config/database.php
[domain.com] done
* sftp upload complete
servers: ["domain.com"]
** sftp upload #<StringIO:0x00000001f2a430> -> /home/username/domain.com/shared/config/app.php
[domain.com] /home/username/domain.com/shared/config/app.php
[domain.com] done
* sftp upload complete
servers: ["domain.com"]
** sftp upload #<StringIO:0x0000000227d038> -> /home/username/domain.com/shared/config/mail.php
[domain.com] /home/username/domain.com/shared/config/mail.php
[domain.com] done
* sftp upload complete
* 2014-09-21 13:04:11 executing `deploy:update_code'
updating the cached checkout on all servers
executing locally: "git ls-remote git@bitbucket.org:drmcnasty/domain.com.git laravel-downgrade"
command finished in 968ms
* executing "if [ -d /home/username/domain.com/shared/cached-copy ]; then cd /home/username/domain.com/shared/cached-copy && git fetch  origin && git fetch --tags  origin && git reset  --hard c4f8cb133da8e5097d6d0be7234b355f1befaa21 && git clean  -d -x -f; else git clone -b laravel-downgrade git@bitbucket.org:drmcnasty/domain.com.git /home/username/domain.com/shared/cached-copy && cd /home/username/domain.com/shared/cached-copy && git checkout -b deploy c4f8cb133da8e5097d6d0be7234b355f1befaa21; fi"
servers: ["domain.com"]
[domain.com] executing command
** [domain.com :: out] HEAD is now at c4f8cb1 updated to last laravel version
command finished in 3833ms
copying the cached version to /home/username/domain.com/releases/20140921170416
* executing "cp -RPp /home/username/domain.com/shared/cached-copy /home/username/domain.com/releases/20140921170416 && (echo c4f8cb133da8e5097d6d0be7234b355f1befaa21 > /home/username/domain.com/releases/20140921170416/REVISION)"
servers: ["domain.com"]
[domain.com] executing command
command finished in 347ms
* 2014-09-21 13:04:17 executing `deploy:finalize_update'
* executing "rm -rf -- /home/username/domain.com/releases/20140921170416/public/system && mkdir -p -- /home/username/domain.com/releases/20140921170416/public/ && ln -s -- /home/username/domain.com/shared/system /home/username/domain.com/releases/20140921170416/public/system && rm -rf -- /home/username/domain.com/releases/20140921170416/log && ln -s -- /home/username/domain.com/shared/log /home/username/domain.com/releases/20140921170416/log && rm -rf -- /home/username/domain.com/releases/20140921170416/tmp/pids && mkdir -p -- /home/username/domain.com/releases/20140921170416/tmp/ && ln -s -- /home/username/domain.com/shared/pids /home/username/domain.com/releases/20140921170416/tmp/pids"
servers: ["domain.com"]
[domain.com] executing command
command finished in 346ms
* executing "find /home/username/domain.com/releases/20140921170416/public/images /home/username/domain.com/releases/20140921170416/public/stylesheets /home/username/domain.com/releases/20140921170416/public/javascripts -exec touch -t 201409211704.17 -- {} ';'; true"
servers: ["domain.com"]
[domain.com] executing command
** [out :: domain.com] find: `/home/username/domain.com/releases/20140921170416/public/javascripts': No such file or directory
command finished in 367ms
* 2014-09-21 13:04:17 executing `deploy:fix_permissions'
* executing "ls -x /home/username/domain.com/releases"
servers: ["domain.com"]
[domain.com] executing command
command finished in 347ms
* executing "chmod -R a+w /home/username/domain.com/releases/20140921170416/app/storage"
servers: ["domain.com"]
[domain.com] executing command
command finished in 338ms
* 2014-09-21 13:04:18 executing `deploy:copy_config'
* executing "cp /home/username/domain.com/shared/config/* /home/username/domain.com/releases/20140921170416/app/config/"
servers: ["domain.com"]
[domain.com] executing command
command finished in 326ms
* 2014-09-21 13:04:18 executing `deploy:prepare_artisan'
* executing "chmod u+x /home/username/domain.com/releases/20140921170416/artisan"
servers: ["domain.com"]
[domain.com] executing command
command finished in 322ms
* 2014-09-21 13:04:19 executing `deploy:create_symlink'
* executing "rm -f /home/username/domain.com/current &&  ln -s /home/username/domain.com/releases/20140921170416 /home/username/domain.com/current"
servers: ["domain.com"]
[domain.com] executing command
command finished in 340ms
* 2014-09-21 13:04:19 executing `deploy:migrate'
* executing "php /home/username/domain.com/releases/20140921170416/artisan migrate"
servers: ["domain.com"]
[domain.com] executing command
** [out :: domain.com] Status: 500 Internal Server Error
** [out :: domain.com] X-Powered-By: PHP/5.3.27
** [out :: domain.com] Content-type: text/html
** [out :: domain.com]
command finished in 381ms
*** [deploy:create_symlink] rolling back
*** no previous release to rollback to, rollback of symlink skipped
*** [deploy:update_code] rolling back
* executing "rm -rf /home/username/domain.com/releases/20140921170416; true"
servers: ["domain.com"]
[domain.com] executing command
command finished in 341ms
failed: "sh -c 'php /home/username/domain.com/releases/20140921170416/artisan migrate'" on domain.com

A: So apparently you have to update your capistrano commands in the deploy file to user 'php-cli' instead of just 'php'.
Now this I read about before but what I didn't hear was the need to make this change in the scripts section of your composer.json file.


text:
Q: Using a JWT for more than authentication Should JWTs be used for more than just authenticating a user? I read that it's okay to store non sensitive stuff like a user ID in it. Would it be okay to store stuff like permission levels in the token? This way I get to avoid doing a database call.

A: JWT tokens can be used for authentication purposes, but nothing stops you from creating your own claims to store additional data, such as the user roles or a scope of access.
Some authentication providers add a scope of access to their tokens. Have a look at this answer.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Binary write to address Can someone help me out writing hex string to file hex address from textbox?
This is my current code:
private void button1_Click(object sender, EventArgs e)
{
    BinaryWriter wr = new BinaryWriter(File.OpenWrite(listBox1.SelectedItem.ToString()));
    for (int i = 0x83C410; i <= 0x83C417; i++)
    {
        wr.Write(textBox1.Text);
    }
    wr.Close();
}

But it doesn't work after i click button nothing happens to file, even it doesn't show any error which is kinda strange.
After few tweaks i got it working saving value into file binary but now it add one extra char idk how. This is code i use now:
 private void button1_Click(object sender, EventArgs e)
    {
        BinaryWriter wr = new BinaryWriter(File.OpenWrite(listBox1.SelectedItem.ToString()));
        wr.BaseStream.Position = 0x83C410;
        wr.Write(textBox1.Text);
        wr.Flush();
    }

Instead adding 8 bytes it adds 9 1 extra, and my textbox is limited to 8 chars.
Hex that adds: 08736574706F777265
Instead: 736574706F777265
ASCII that adds: .setpowre
Instead: setpowre

A: First of all, a few hints when using FileWriters:

*

*Always put them within using-statements when possible, so they get properly disposed of.

*I always recommend calling Flush() explicitly instead of Close(). The Dispose()-method will close it afterwards anyway, and Closing does not always Flush the writer. This might be the cause why your writes aren't being flushed to the file.

Another interesting point about your code is that you are using a for-loop with specific hexadecimal values, only to write the same value (textBox1.Text) to the file. Why is that?
Update - I saw your code at flushbin, and if you don't mind, I picked out this part where you commented out some other code:
private void button1_Click(object sender, EventArgs e)
        {
#region "New"
            //byte[] bytes = new byte[str.Length * sizeof(char)];
            //System.Buffer.BlockCopy(textBox1.Text.ToCharArray(), 0, bytes, 0, bytes.Length);
            //using (FileStream fs = File.OpenWrite(listBox1.SelectedItem.ToString()))
            //{
            //    fs.Seek(0x83C410, SeekOrigin.Begin);
            //    fs.Write(bytes, 0, 7);
            //}
#endregion

            BinaryWriter wr = new BinaryWriter(File.OpenWrite(listBox1.SelectedItem.ToString()));
            textBox8.Text = ConvertToHex(Encoding.UTF8.GetBytes(textBox8.Text));
            for (int i = 0x83C410; i <= 0x83C417; i++)
            {

               // wr.Write(textBox1.Text);
            }
            wr.Close();
        }

My point about using the using-statement and calling Flush() explicitly still stands, but now I see that when you are reading the file you are using the hexadecimal values of the for-loop to determine the stream-position of the bytes to read, so I guess you should not forget to use these numbers to explicitly set the stream-position when you are writing the bytes:
wr.BaseStream.Position = i;

Another difference is that you are reading byte for byte, whereas you are writing the entire string at once, so you either do not need the for-loop in your write-method, or you should change your code to writing byte for byte too.

A: Since Listbox.SelectedItem is an Object, the ToString() method will probably not return the value you want it it return. Try this instead;
string selected = listBox1.GetItemText(listBox1.SelectedValue);
BinaryWriter bw = new BinaryWriter(File.OpenWrite(selected));

A: private void button1_Click(object sender, EventArgs e)
        {
            BinaryWriter wr = new BinaryWriter(File.OpenWrite(listBox1.SelectedItem.ToString()));
            wr.BaseStream.Position = 0x83C410;
            wr.Write(System.Text.Encoding.UTF8.GetBytes(textBox1.Text));
            wr.Close();
        }

This is answer to my question.


text:
Q: Convert date format in springboot using java8 I receive the following date format
private String newDate = "Mon Apr 25 04:50:00 CET 2022"

How can I convert it into the following format in java 8
2022-04-25T04:50:00

A: You can use Java 8's date/time API, and more precisely the DateTimeFormatter.
There's no pre-defined formatter that matches your initial input. The closest is DateTimeFormatter.RFC_1123_DATE_TIME, but it requires a comma after the day of the week.
To solve that, you can write your own pattern:
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z yyyy", Locale.ROOT));
String input = "Mon Apr 25 04:50:00 CET 2022";
ZonedDateTime date = ZonedDateTime.parse(input, inputFormatter);

The best way to represent your initial date is a ZonedDateTime, since your date contains zone-related information.
For your output, you can use the DateTimeFormatter.ISO_LOCAL_DATE_TIME formatter. For example:
String output = DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(date);

A: Almost the same answer is already given.
The given input format looks like Date.toSTring(), especially as weekday and month seem to be English, but might be German too. Below with Locale.ENGLISH (as suggested by "CET") but Locale.GERMAN might be better.
    String newDate = "Mon Apr 25 04:50:00 CET 2022";
    DateTimeFormatter formatter =
        DateTimeFormatter.ofPattern("eee MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
    ZonedDateTime t = ZonedDateTime.parse(newDate, formatter);
    System.out.println(t);
    System.out.println(Date.from(t.toInstant()));
    System.out.println(t.format(DateTimeFormatter.ISO_DATE_TIME));
    System.out.println(t.toLocalDateTime().format(DateTimeFormatter.ISO_DATE_TIME));
    System.out.println(t.withZoneSameInstant(ZoneId.of("UTC")).toLocalDateTime()
        .format(DateTimeFormatter.ISO_DATE_TIME));

The output variants are:
Mon Apr 25 04:50:00 CEST 2022
2022-04-25T04:50+02:00[Europe/Paris]
2022-04-25T04:50:00+02:00[Europe/Paris]
2022-04-25T04:50:00
2022-04-25T02:50:00

It is indeed best to start with a ZonedDateTime.
If you get input all over Europe, it would be best to use Universal Time Coordinated, Greenwich time. (But it often depends on the existing database data.)


text:
Q: What does it mean when someone says they have sparse labels? I'm going through the Hands-On Machine Learning book with Scikit-Learn and TF by Aurelion Geron and I've come across the notion of choosing a specific loss function due to the data having sparse labels.
The specific quote is

This code requires some explanation. First, we use the
  "sparse_categorical_crossentropy" loss because we have sparse labels
  (i.e., for each instance, there is just a target class index, from 0
  to 9 in this case), and the classes are exclusive. If instead we had
  one target probability per class for each instance (such as one-hot
  vectors, e.g. [0., 0., 0., 1., 0., 0., 0., 0., 0., 0.] to represent
  class 3), then we would need to use the "categorical_crossentropy"
  loss instead.

The thing is this is different than my understanding of a sparse vector where most of the values are 0. So what are sparse labels?

A: imagen you have a target class with 10 target classes: class 0, class 2, ...., class 9
In the first example you will have only one target column called sparse labels, e.g.:
columnA columnB target
10      10       0
1       24       2
...

in the second exmaple you will have one target column for every class:
columnA columnB class 0 class 1 class 2 ....
10      10       1       0       0      ...
1       24       0       0       1      ...

A: My interpretation is that if you only have one label indicating which class the instance belong to, it is sparse in the sense that is limited to a single class assignment. The matrix version of this is the one-hot vectors representation which only has mostly zeros and only 1 ones on the correpsonding class (which is a sparse matrix). More generally you can use a matrix in which each element indicates the probability for the instance to belong to a specific class (which is not sparse matrix).


text:
Q: Taking photo from camera by C and win32 api I would to get a still image (in jpg format) from any type of cameras plugged to my computer (USB and Serial) and then save it on my hard disk, so what the code you recommend me to write while I use C programming language and Win32 api, finally I would to tell you that I work on Microsoft VC++ 2008 on Windows XP sp3 and I know that the solution of my problem related to WIA library or Microsoft STI library but I don't have any idea on how to use it or how to write code via them, so please I would a clear answer with clear codes cause I am beginner.

A: Stack Overflow really isn't a magic code generator or personal tutor but rather a place to which you can turn when you get stuck in your code.
That said, luck has it that Microsoft provides a tutorial on how to do this:
WIA Tutorial
It assumes you can follow C code, but if you can't already do that maybe you should start with something easier :)


text:
Q: Can i trust the value that is returned from ServerVariables["REMOTE_ADDR"] I have a IIS hosted ASP.NET WebAPI app and im using ServerVariables["REMOTE_ADDR"] to get the client address and identify the user: client logs in and i will generate a cookie that contains the client IP. In subsequent calls i will get the IP from the cookie, and validate that it is correct.
Can i trust the address, or is there a way that ServerVariables["REMOTE_ADDR"] returns e.g. 161.121.222.223 and the client is really somewhere else?

A:
Yes, it's safe. It is the source IP of the TCP connection and can't be substituted by changing an HTTP header.
One case you may want to be worry of is if you are behind a reverse proxy in which case the REMOTE_ADDR will always be the IP of the proxy server and the user IP will be provided in an HTTP header (such as X-Forwarded-For). But for the normal use case reading REMOTE_ADDR is fine.

Taken from: Is it safe to trust $_SERVER['REMOTE_ADDR']?

A: Yes, it's reliable. It can't be modified by the client, except by simply connecting from another IP. (Proxy)


text:
Q: Enterprise Application Display Name I am running a command to get the equivalent display name of an Azure Enterprise Application Object ID however it is not working. Below is the powershell script that I am using.
$caller.caller = (Get-AzADApplication -ObjectId $caller.caller).DisplayName
Thank you in advance for the help.
This is where I am getting the data to be converted to its display name

A: I tried to reproduce the same in my environment and it's working fine
Please use the below command to get enterprise application display name.
(Get-AzADServicePrincipal -ObjectId 279d67ab-fa63-461a-*********).DisplayName

Output:


text:
Q: Do I need to add CHAR(13) in put_line() statement in Oracle to use fflush()? I've read that to use fflush() function in oracle, every line in the output should end with a new line character. Will put_line() automatically introduce a new line character that needs fflush() to work ?
What is the new line character (\r\n or \n or depends on OS) that fflush() needs ? And what is the new line (\r\n or \n or depends on OS) character that put_line() introduces if at all it does ?

A: Yes, put_line() adds the required new line character(s). From the documentation for put_line():

This procedure writes the text string stored in the buffer parameter to the open file identified by the file handle. The file must be open for write operations. PUT_LINE terminates the line with the platform-specific line terminator character or characters.

That's really the difference between put() and put_line():

No line terminator is appended by PUT; use NEW_LINE to terminate the line or use PUT_LINE to write a complete line with a line terminator.

It's slightly confusing that the description of fflush() refers to just "a newline character" while put_line() refers to "line terminator character or characters", but they do mean the same thing - to flush the buffer must end with the operating-system line terminator character(s).
Note that it means the database server's operating system, not your client operating system, since utl_file (and all PL/SQL) is on the server and doesn't know anything about the client environment. It's generally safer to use put_line() or new_line() than to manually add \n or \r\n; even if you know the OS your database is running on now, it may move to a different OS one day.


text:
Q: return clean error message from server side function On my lightning component I have function that calls to server side function to create a case
Controller.apxc
public class CommunityCaseFormController {

    @AuraEnabled
    public static Id createCase(Case c) {
        try {
            insert c;
        } catch (Exception e) {
            String message = e.getMessage();
            AuraHandledException auraError = new AuraHandledException(message);
            auraError.setMessage(message);
            throw auraError;
        }

        return c.Id;
    }
}

I'm getting an error message because an admin created a validation rule for cases on creation. The response.getError()[0].message from calling the server function has the error message that is in the validation rule, but is has bunch of extra stuff that the user doesn't need to see, such as.

Insert failed. First exception on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION,
.: [Priority]

I could use JavaScript to manipulate the string, but in my opinion that shouldn't be required. How do I get my server-side function to return a cleaner error message?

A: I've seen the answer where you get the 0th message from the DmlException, but it does have the disadvantage that if there are multiple rows, it will only return errors about the first.
DmlException is relatively well handled by Aura, so I just rethrow it e.g.
    Savepoint savepoint = Database.setSavepoint();

    try {
        // Do my action
    } catch(DmlException e) {
        Database.rollback(savepoint);
        throw e;
    } catch(AnotherException e) {
        // Catch any other exceptions that could use special treatment
    } catch(Exception e) {
        Database.rollback(savepoint);
        throw new AuraHandledException(e.getMessage() + e.getStackTraceString());
    }

This actually results in an error object that you can deal with in Aura to give a nice user-readable message without having to chop up strings.

A: You can use DMLException first to handle these errors, and this class has getDmlMessage method to get the proper validation error message.
So in your case, to get the proper message you can write:
try {
    insert c;
} catch (DMLException e) {
    String message = e.getDmlMessage(0);
    //further code
} catch (Exception e) {
    //any other exception handling
}

in getDmlMessage(0) method, 0 is the row number, in your case there is just one object. You can check the reference-
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_exception_methods.htm


text:
Q: Create combinations of measurements concatenated using underscore I have a dataframe df1
ID <- c("A","B","C")
Measurement <- c("Length","Height","Breadth")
df1 <- data.frame(ID,Measurement)

I am trying to create combinations of measurements with an underscore between them and put it under the ID column "ALL"
Here is my desired output
   ID           Measurement
    A                Length
    B                Height
    C               Breadth
  ALL Length_Height_Breadth
  ALL Length_Breadth_Height
  ALL Breadth_Height_Length
  ALL Breadth_Length_Height
  ALL Height_Length_Breadth
  ALL Height_Breadth_Length

Also when there are similar measurements in the "measurement" column, I want to eliminate the underscore.
For example:
ID <- c("A","B")
Measurement <- c("Length","Length")
df2 <- data.frame(ID,Measurement)

Then I would want the desired output to be
   ID           Measurement
    A                Length
    B                Length
  ALL                Length

I am trying to do something like this which is totally wrong
df1$ID <- paste(df1$Measurement, df1$Measurement, sep="_")

Can someone point me in the right direction to achieving the above outputs?
I would like to see how it is done programmatically instead of using the actual measurement names. I am intending to apply the logic to a larger dataset that has several measurement names and so a general solution would be much appreciated.

A: We could use the permn function from the combinat package:
library(combinat)
sol_1 <- sapply(permn(unique(df1$Measurement)),
                FUN = function(x) paste(x, collapse = '_'))
rbind.data.frame(df1, data.frame('ID' = 'All', 'Measurement' = sol_1))

#    ID           Measurement
# 1   A                Length
# 2   B                Height
# 3   C               Breadth
# 4 All Length_Height_Breadth
# 5 All Length_Breadth_Height
# 6 All Breadth_Length_Height
# 7 All Breadth_Height_Length
# 8 All Height_Breadth_Length
# 9 All Height_Length_Breadth

sol_2 <- sapply(permn(unique(df2$Measurement)),
                FUN = function(x) paste(x, collapse = '_'))
rbind.data.frame(df2, data.frame('ID' = 'All', 'Measurement' = sol_2))

#    ID Measurement
# 1   A      Length
# 2   B      Length
# 3 All      Length

Giving credit where credit is due: Generating all distinct permutations of a list.
We could also use permutations from the gtools package (HT @joel.wilson):
library(gtools)
unique_meas <- as.character(unique(df1$Measurement))
apply(permutations(length(unique_meas), length(unique_meas), unique_meas),
      1, FUN = function(x) paste(x, collapse = '_'))

# "Breadth_Height_Length" "Breadth_Length_Height"
# "Height_Breadth_Length" "Height_Length_Breadth"
# "Length_Breadth_Height" "Length_Height_Breadth"


text:
Q: SceneWillConnect to session not called after adding SceneDelegate into an existing project - getting blank screen i have an existing project based on storyboard that works from iOS 12.
I am trying to implement the SceneDelegate class to make some things working on iOS 13 and above but when I launch the app I get a blank a screen.
I did the following:
In my info.plist file I added this code:
<key>UIApplicationSceneManifest</key>
<dict>
    <key>UIApplicationSupportsMultipleScenes</key>
    <false/>
    <key>UISceneConfigurations</key>
    <dict>
        <key>UIWindowSceneSessionRoleApplication</key>
        <array>
            <dict>
                <key>UISceneDelegateClassName</key>
                <string>$(PRODUCT_MODULE_NAME).SceneDelegate</string>
                <key>UISceneConfigurationName</key>
                <string>Default Configuration</string>
                <key>UISceneStoryboardFile</key>
                <string>Splash</string>
            </dict>
        </array>
    </dict>
</dict>

Since my project is storyboard based I added this to the SceneDelegate class

@available (iOS 13.0, *)
class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

        guard let windowScene = (scene as? UIWindowScene) else { return }
  }
    func sceneDidDisconnect(_ scene: UIScene) {
        // Called as the scene is being released by the system.
    }

    func sceneDidBecomeActive(_ scene: UIScene) {
        // Not called under iOS 12 - See AppDelegate applicationDidBecomeActive
    }

    func sceneWillResignActive(_ scene: UIScene) {
        // Not called under iOS 12 - See AppDelegate applicationWillResignActive
    }

    func sceneWillEnterForeground(_ scene: UIScene) {
        // Not called under iOS 12 - See AppDelegate applicationWillEnterForeground
    }

    func sceneDidEnterBackground(_ scene: UIScene) {
        // Not called under iOS 12 - See AppDelegate applicationDidEnterBackground
    }
}

Am I doing something wrong?
Bests


text:
Q: What is in vs What is there in I can't quite figure if there is a difference between:

*

*What is in the bag?

*What is there in the bag?

And this:

*

*Who is in the house?

*Who is there in the house?

A: In my opinion, the word there in both sentences is unnecessary. Or you replace bag or house with 'there'.
"What is in the bag?" good sentence
"What is there in the bag?" Or, "What is in there?"
"Who is in the house?" good sentence
"Who is there in the house?" Or, "Who is there?"


text:
Q: Formula for the diameter of an emerging beam I have the following problem:

A thin beam of white light with negligible radius is incident at $50.0^\circ$ on a $10.0 cm$ thick slab of clear plastic. The index of refraction for red light in this material is $1.51$ and for violet light it's $1.54$. Determine the approximate diameter, $D$ of the emerging beam. Express your answer in cm with two significant figures.

I realise that this is a physics problem, and asking physics questions is off-topic on math.stackexchange. However, my question does not pertain to the physics of the problem, but rather the geometry used to solve certain aspects of it.
This seems to be a variation (same problem, different numeric values) of problem 4.20 in Optics, 4th edition, by Hecht.
My solution proceeds as follows:
Snell's law can be used to find $\theta_{red}$ and $\theta_{violet}$:
$$\begin{align} \theta_{red} &= \arcsin \left[ \dfrac{n_1}{n_{red}} \sin(\theta_i) \right] \\ &= \arcsin \left[ \dfrac{1}{1.51} \sin(50^\circ) \right] \end{align}$$
$$\begin{align} \theta_{violet} = \arcsin \left[ \dfrac{1}{1.54} \sin(50^\circ) \right] \end{align}$$
Since $\tan(\theta) = opposite/adjacent$, we have that
$$\begin{align} h_{red} = 10 \tan(\theta_{red}) \end{align}$$
$$\begin{align} h_{violet} = 10 \tan(\theta_{violet}) \end{align}$$
Now, here is where I ran into trouble. I now need to find the diameter of the emerging beam. My instructor's solutions give the diameter of an emerging beam as $D = \cos(50^\circ)(h_{red} - h_{violet}$).
The following is an illustration of the problem in question:

However, when researching how to find the diameter of an emerging beam, I found conflicting answers. The solutions to the aforementioned Hecht textbook give the diameter of the emerging beam as $D = \dfrac{h_{red} - h_{violet}}{\cos(50^\circ)}$. However, I have also found some documents that use the same formula as my instructor. Furthermore, I found two YouTube videos that claim to derive the formula for the diameter of an emerging beam, but derive different answers!
After spending much time researching this, it seems that there is no clear consensus, at least, none that I can find, on what the formula for the diameter of an emerging beam actually is. And another problem is that, for a learner such as myself who wants to actually understand the formula (rather than blindly memorizing some formula that was handed to me), there are no sources that provide a clear, step-by-step derivation this formula. At this point, I am completely lost.
I am kindly requesting that someone knowledgeable on this subject please take the time to (1) provide the formula for the diameter of an emerging beam, and (2) provide a step-by-step, well explained proof/derivation of that formula.

A: Let's call $V$ the point where the violet beam exits the plastic, and $R$ where the red beam exits the plastic. Draw a perpendicular from $R$ to the outgoing violet beam, and call $P$ the point of intersection. In this right angle triangle, the hypotenuse is $h_{red}-h_{violet}$ and one of the sides is $D$. Notice that all outgoing beams will exit the plastic at the same angle with respect to the normal, so at $50^\circ$ with respect to the normal to the surface. Then the angle between the beam and the direction parallel to the surface is $40^\circ$. So in the $\triangle VRP$ you can write $$\sin 40^\circ=\frac{D}{h_{red}-h_{violet}}$$
Note that $\sin 40^\circ=\cos 50^\circ$, so $$D=(h_{red}-h_{violet})\cos50^\circ$$


text:
Q: Continuously calculating averages over past intervals w/ Pandas DataFrame I believe that my problem is really straightforward and there must be a really easy way to solve this issue, however as I am don't feel really confident on working with timestamps so I could not sort that problem by my own.
I made the following example, which represents a simple case of what I have been working on. There, you can see that I have made up a dataframe consisting of a speed signal (which is an input) over a period of one hour.
import pandas as pd
import numpy as np

start = pd.Timestamp('2019-11-15T16:00')
end = pd.Timestamp('2019-11-15T17:00')
t = np.linspace(start.value, end.value, 60*60+1)
data = pd.DataFrame([])
data['Timestamp'] = pd.to_datetime(t)

noise = np.random.normal(0,1,3601)
data['Speed'] = 10*abs(np.random.randn(3601))+noise

I am going to implement a controller, which will limit that speed signal, but that not on the scope of the question. So what I am looking for is a way in which I can loop through the column for i,val in enumerate(data['Speed'].values): and calculate the mean speed over the last 10 seconds for each loop. So the idea is for each new iteration, calculate the mean over the past 10 values.
Hope that I managed to be succinct and precise. I would really appreciate your help on this one! Suggestions of what to look up for are also welcome.

A: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.window.Rolling.mean.html#pandas.core.window.Rolling.mean
data['Speed_10s_mean'] = data['Speed'].rolling(10).mean()

result
    Timestamp           Speed       Speed_10s_mean
0   2019-11-15 16:00:00 6.467616    NaN
1   2019-11-15 16:00:01 1.233462    NaN
2   2019-11-15 16:00:02 9.136592    NaN
3   2019-11-15 16:00:03 18.617069   NaN
4   2019-11-15 16:00:04 7.628102    NaN
5   2019-11-15 16:00:05 11.840941   NaN
6   2019-11-15 16:00:06 7.788474    NaN
7   2019-11-15 16:00:07 13.069130   NaN
8   2019-11-15 16:00:08 5.549147    NaN
9   2019-11-15 16:00:09 0.596765    8.192730
10  2019-11-15 16:00:10 13.273170   8.873285
11  2019-11-15 16:00:11 19.339124   10.683851
12  2019-11-15 16:00:12 18.659298   11.636122
13  2019-11-15 16:00:13 4.094160    10.183831
14  2019-11-15 16:00:14 13.240686   10.745089
15  2019-11-15 16:00:15 17.535431   11.314539
16  2019-11-15 16:00:16 28.936041   13.429295
17  2019-11-15 16:00:17 6.081373    12.730520
18  2019-11-15 16:00:18 16.009562   13.776561
19  2019-11-15 16:00:19 1.101115    13.826996
...


text:
Q: ERROR: command errored out with exit status 1 when installing Kivy I am trying to install Kivy by using: pip3 install Kivy and I keep getting this error ERROR: command errored out with exit status 1
My pip is up to date and I tried installing the library via PyCharm and via the Terminal (I am using a mac). Thanks in advance
added the error below
Collecting Kivy
  Using cached Kivy-1.11.1.tar.gz (23.6 MB)

DEPRECATION: The -b/--build/--build-dir/--build-directory option is deprecated. pip 20.3 will remove support for this functionality. A possible replacement is use the TMPDIR/TEMP/TMP environment variable, possibly combined with --no-clean. You can find discussion regarding this at https://github.com/pypa/pip/issues/8333.
    ERROR: Command errored out with exit status 1:
     command: /Users/davidsokulin/PycharmProjects/FirsProject/venv/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/ch/_69bcffn79s9nxnc5mzrsm4r0000gn/T/pycharm-packaging/kivy/setup.py'"'"'; __file__='"'"'/private/var/folders/ch/_69bcffn79s9nxnc5mzrsm4r0000gn/T/pycharm-packaging/kivy/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/ch/_69bcffn79s9nxnc5mzrsm4r0000gn/T/pip-pip-egg-info-m9a_f9np
         cwd: /private/var/folders/ch/_69bcffn79s9nxnc5mzrsm4r0000gn/T/pycharm-packaging/kivy/
    Complete output (92 lines):
    Using setuptools
    User distribution detected, avoid portable command.
    Using this graphics system: OpenGL ES 2
    OSX framework used, force to x86_64 only
    OSX ARCHFLAGS are: -arch x86_64
    GStreamer framework not found, fallback on pkg-config
    WARNING: A problem occurred while running pkg-config --libs --cflags gstreamer-1.0 (code 127)

    b'/bin/sh: pkg-config: command not found\n'

    Missing framework /Library/Frameworks/SDL2.framework
    Missing framework /Library/Frameworks/SDL2_ttf.framework
    Missing framework /Library/Frameworks/SDL2_image.framework
    Missing framework /Library/Frameworks/SDL2_mixer.framework
    SDL2 frameworks not found, fallback on pkg-config
    WARNING: A problem occurred while running pkg-config --libs --cflags sdl2 SDL2_ttf SDL2_image SDL2_mixer (code 127)

    b'/bin/sh: pkg-config: command not found\n'

    Xcode detected at b'/Applications/Xcode.app/Contents/Developer', and using OS X10.15 sdk
    WARNING: A problem occurred while running pkg-config --libs --cflags pangoft2 (code 127)

    b'/bin/sh: pkg-config: command not found\n'

    ERROR: Dependency for context.pyx not resolved: config.pxi
    ERROR: Dependency for compiler.pyx not resolved: config.pxi
    ERROR: Dependency for context_instructions.pyx not resolved: config.pxi
    ERROR: Dependency for fbo.pyx not resolved: config.pxi
    ERROR: Dependency for gl_instructions.pyx not resolved: config.pxi
    ERROR: Dependency for instructions.pyx not resolved: config.pxi
    ERROR: Dependency for opengl.pyx not resolved: config.pxi
    ERROR: Dependency for opengl_utils.pyx not resolved: config.pxi
    ERROR: Dependency for shader.pyx not resolved: config.pxi
    ERROR: Dependency for stencil_instructions.pyx not resolved: config.pxi
    ERROR: Dependency for scissor_instructions.pyx not resolved: config.pxi
    ERROR: Dependency for texture.pyx not resolved: config.pxi
    ERROR: Dependency for vbo.pyx not resolved: config.pxi
    ERROR: Dependency for vertex.pyx not resolved: config.pxi
    ERROR: Dependency for vertex_instructions.pyx not resolved: config.pxi
    ERROR: Dependency for cgl.pyx not resolved: config.pxi
    ERROR: Dependency for cgl_mock.pyx not resolved: config.pxi
    ERROR: Dependency for cgl_gl.pyx not resolved: config.pxi
    ERROR: Dependency for cgl_glew.pyx not resolved: config.pxi
    ERROR: Dependency for cgl_sdl2.pyx not resolved: config.pxi
    ERROR: Dependency for svg.pyx not resolved: config.pxi
    fatal: not a git repository (or any of the parent directories): .git
     WARNING: The wheel package is not available.
    WARNING: Skipping page https://github.com/kivy-garden/garden/archive/master.zip because the HEAD request got Content-Type: application/zip.The only supported Content-Type is text/html
      ERROR: Command errored out with exit status 1:
       command: /Users/davidsokulin/PycharmProjects/FirsProject/venv/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/ch/_69bcffn79s9nxnc5mzrsm4r0000gn/T/pip-wheel-ijxakt66/cython/setup.py'"'"'; __file__='"'"'/private/var/folders/ch/_69bcffn79s9nxnc5mzrsm4r0000gn/T/pip-wheel-ijxakt66/cython/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /private/var/folders/ch/_69bcffn79s9nxnc5mzrsm4r0000gn/T/pip-wheel-oan20jxf
           cwd: /private/var/folders/ch/_69bcffn79s9nxnc5mzrsm4r0000gn/T/pip-wheel-ijxakt66/cython/
      Complete output (7 lines):
      Unable to find pgen, not compiling formal grammar.
      usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
         or: setup.py --help [cmd1 cmd2 ...]
         or: setup.py --help-commands
         or: setup.py cmd --help

      error: invalid command 'bdist_wheel'
      ----------------------------------------
      ERROR: Failed building wheel for cython
    ERROR: Failed to build one or more wheels
     Traceback (most recent call last):
       File "/Users/davidsokulin/PycharmProjects/FirsProject/venv/lib/python3.8/site-packages/setuptools/installer.py", line 126, in fetch_build_egg
         subprocess.check_call(cmd)
       File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/subprocess.py", line 364, in check_call
         raise CalledProcessError(retcode, cmd)
     subprocess.CalledProcessError: Command '['/Users/davidsokulin/PycharmProjects/FirsProject/venv/bin/python', '-m', 'pip', '--disable-pip-version-check', 'wheel', '--no-deps', '-w', '/var/folders/ch/_69bcffn79s9nxnc5mzrsm4r0000gn/T/tmp25x0n6e6', '--quiet', '--find-links', 'https://github.com/kivy-garden/garden/archive/master.zip', 'cython!=0.27,!=0.27.2,<=0.29.10,>=0.24']' returned non-zero exit status 1.

     The above exception was the direct cause of the following exception:

     Traceback (most recent call last):
       File "<string>", line 1, in <module>
       File "/private/var/folders/ch/_69bcffn79s9nxnc5mzrsm4r0000gn/T/pycharm-packaging/kivy/setup.py", line 1073, in <module>
         setup(
       File "/Users/davidsokulin/PycharmProjects/FirsProject/venv/lib/python3.8/site-packages/setuptools/__init__.py", line 152, in setup
         _install_setup_requires(attrs)
       File "/Users/davidsokulin/PycharmProjects/FirsProject/venv/lib/python3.8/site-packages/setuptools/__init__.py", line 147, in _install_setup_requires
         dist.fetch_build_eggs(dist.setup_requires)
       File "/Users/davidsokulin/PycharmProjects/FirsProject/venv/lib/python3.8/site-packages/setuptools/dist.py", line 673, in fetch_build_eggs
         resolved_dists = pkg_resources.working_set.resolve(
       File "/Users/davidsokulin/PycharmProjects/FirsProject/venv/lib/python3.8/site-packages/pkg_resources/__init__.py", line 764, in resolve
         dist = best[req.key] = env.best_match(
       File "/Users/davidsokulin/PycharmProjects/FirsProject/venv/lib/python3.8/site-packages/pkg_resources/__init__.py", line 1049, in best_match
         return self.obtain(req, installer)
       File "/Users/davidsokulin/PycharmProjects/FirsProject/venv/lib/python3.8/site-packages/pkg_resources/__init__.py", line 1061, in obtain
         return installer(requirement)
       File "/Users/davidsokulin/PycharmProjects/FirsProject/venv/lib/python3.8/site-packages/setuptools/dist.py", line 732, in fetch_build_egg
         return fetch_build_egg(self, req)
       File "/Users/davidsokulin/PycharmProjects/FirsProject/venv/lib/python3.8/site-packages/setuptools/installer.py", line 128, in fetch_build_egg
         raise DistutilsError(str(e)) from e
     distutils.errors.DistutilsError: Command '['/Users/davidsokulin/PycharmProjects/FirsProject/venv/bin/python', '-m', 'pip', '--disable-pip-version-check', 'wheel', '--no-deps', '-w', '/var/folders/ch/_69bcffn79s9nxnc5mzrsm4r0000gn/T/tmp25x0n6e6', '--quiet', '--find-links', 'https://github.com/kivy-garden/garden/archive/master.zip', 'cython!=0.27,!=0.27.2,<=0.29.10,>=0.24']' returned non-zero exit status 1.
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

A: It seems you miss pkg-config, try with
brew install pkg-config


text:
Q: C# вывод изображения. Здравствуйте. Возникла такая проблема. Вывести изображение получается только если оно имеется в папке с exe файлом. А мне необходимо написать программу, которая бы отрисовывала изображение на форме без его наличия, то есть был 1 exe файл без каких либо других файлов. Как это сделать? Где можно найти подробную информацию?
A: Сохраните изображение в ресурсах и загружайте оттуда.


text:
Q: is there a way to save multiple records with attachements at once without calling insert each time I have some files that I need to save to the database, and every file should be attached to a instance of an ActiveRecord like so:
pdf_files.each do |pdf_file|
 cipher_file = ...
 payslip = MyhraPayslips::Payslip.new(myhra_users_user_id: user_to_update.id, payslip_date:
          DateTime.parse(date).strftime("%Y-%m-%d"))
 payslip.payslip.attach(io: File.open(cipher_file), filename: File.basename(pdf_file),
         content_type: 'application/pdf')
 payslip.save
end

Since I have many files, I want to insert them into the database all at once, and, because I have to call attach method on each record, I can't just do it with bulk insert or use create instead of new.


text:
Q: PayPal Country state codes Can I find the states codes somewhere that have to be used for the PayPal address format?
For example: Which states codes have to be used for Turkey?
I already tried IST for Istanbul for example, but that doesn't work.

A: From the Classic API Developer Guide:
PayPal accepts the following State codes in the State field of an address.

*

*Canada

*Italy

*Netherlands

*United States

...
For Turkey you should not need to pass a state code as this field is optional. And the state codes on this page are the only valid codes.

A: I had the same problem. When the country is Mexico, PayPal complains if the state field is missing. I tried "AGU" and "MX-AGU", for Aguascalientes, then PayPal claimed the field was too long. Finally it accepted "AG", which I found here: http://en.wikipedia.org/wiki/Template:Mexico_State-Abbreviation_Codes
Looks like that developer guide page that PP_MSI_Aaron shared, might need updating.
For Turkey you could try http://en.wikipedia.org/wiki/Provinces_of_Turkey#Codes maybe?
However when I tried it with country=Turkey and no state/province, PayPal did not complain. But then I am using PayPal via SagePay via Magento, which only submits the state/province data for a select few countries (Turkey not among them), so I can't test what PayPal would say if I tried it with country=Turkey and province=IST.


text:
Q: Как сделать filter к SimpleAdapter в ListFragment? как правильно составить  фильтр чтоб находить нужные пункты списка с listView?
в моем коде вылетает на строчке sAdapter.notifyDataSetChanged();
public class FirstFragment extends ListFragment {

 final String ATTRIBUTE_NAME_TEXT = "text";
 final String ATTRIBUTE_NAME_LL = "ll";
 ListView lvSimple;
 SimpleAdapter sAdapter;
 EditText editsearch;
 Map<String, Object> m;
 ArrayList<Map<String, Object>> aData ;
 ArrayList<Map<String, Object>> mAllData;
 String product[] = new String[]{"one", "two", "three", "four", "five"};
 Integer degree[] = {99, 98, 97,96,96};

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_first, container, false);
    editsearch = (EditText) rootView.findViewById(R.id.inputSearch);
    return rootView;

} //End OnCreate()

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    aData = new ArrayList<Map<String, Object>>(product.length);
    mAllData= new ArrayList<>();

    for (int i = 0; i < product.length; i++) {
        m = new HashMap<String, Object>();
        m.put(ATTRIBUTE_NAME_TEXT, product[i]);

        m.put(ATTRIBUTE_NAME_LL, degree[i]);
        aData.add(m);
        //&
        mAllData.add(m); // for filter
    }

    String[] from = {ATTRIBUTE_NAME_TEXT, ATTRIBUTE_NAME_LL};
    int[] to = {R.id.tvLoad, R.id.llLoad};

    SimpleAdapter sAdapter = new SimpleAdapter(getActivity(), aData, R.layout.e_list_item,
            from, to);
    setListAdapter(sAdapter);

    lvSimple = (ListView) getActivity().findViewById(R.id.list_one);
    lvSimple.setAdapter(sAdapter);

    editsearch.addTextChangedListener(new TextWatcher() {
        @Override
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub
            String text = editsearch.getText().toString().toLowerCase(Locale.getDefault());

        }
        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1,
                                      int arg2, int arg3) {
            // TODO Auto-generated method stub
        }
        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                                  int arg3) {
            // TODO Auto-generated method stub
            String text = editsearch.getText().toString().toLowerCase(Locale.getDefault());
            filter(text);
        }
    });

} //End onActivityCreated()

public void filter(String charText) {
    charText = charText.toLowerCase(Locale.getDefault());
    aData.clear();
    if (charText.length() == 0) {

        aData.addAll(mAllData);
    } else {
        for (Map<String, Object> wp : mAllData) {

            if (wp.keySet().contains(charText)) {
                aData .add((Map<String, Object>) wp);
            }
        }
    }
    sAdapter.notifyDataSetChanged(); // вылетает на этой строчке
}

}

stack trace:
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.fts.sejo.foodadditive.FirstFragment.filter(FirstFragment.java:122)
at com.fts.sejo.foodadditive.FirstFragment$1.onTextChanged(FirstFragment.java:102)
at android.widget.TextView.sendOnTextChanged(TextView.java:7079)
at android.widget.TextView.handleTextChanged(TextView.java:7138)
at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:8732)
at android.text.SpannableStringBuilder.sendTextChanged(SpannableStringBuilder.java:962)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:496)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:435)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:30)
at android.text.method.QwertyKeyListener.onKeyDown(QwertyKeyListener.java:222)
at android.text.method.TextKeyListener.onKeyDown(TextKeyListener.java:136)
at android.widget.TextView.doKeyDown(TextView.java:5240)
at android.widget.TextView.onKeyDown(TextView.java:5059)
at android.view.KeyEvent.dispatch(KeyEvent.java:2609)
at android.view.View.dispatchKeyEvent(View.java:7086)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1358)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1358)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1358)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1358)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1358)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1358)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1358)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1358)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1358)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1358)
at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchKeyEvent(PhoneWindow.java:1892)
at com.android.internal.policy.impl.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1369)
at android.app.Activity.dispatchKeyEvent(Activity.java:2356)
at android.support.v7.app.AppCompatActivity.dispatchKeyEvent(AppCompatActivity.java:531)
at android.support.v7.view.WindowCallbackWrapper.dispatchKeyEvent(WindowCallbackWrapper.java:50)
at android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.dispatchKeyEvent(AppCompatDelegateImplBase.java:241)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1819)
at android.view.ViewRootImpl.deliverKeyEventPostIme(ViewRootImpl.java:3575)
at android.view.ViewRootImpl.handleImeFinishedEvent(ViewRootImpl.java:3545)
at android.view.ViewRootImpl$ViewRootHandler.handleMessage(ViewRootImpl.java:2795)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)


text:
Q: How can I show two attributes values in one column through relation in Yii 2 GridView i have Gridview in index i want to show width and height both in one column how can i do it
here is the view code
<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],

        'fld_id',
        'fld_name',
        [
            'label' => 'Material Name',
            'attribute' => 'fld_material_id',
            'value' => 'fldMaterial.fld_name',

        ],
        [
            'label' => 'Size',
            'attribute' => 'fld_size_id',
            'value' => 'fldSize.fld_width',
        ],
        // 'fld_size_id',
        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>

i have relation fldSize in model here it is just only displaying fld_width i want to show it in the format fld_width."x".fld_height how can i do it in Yii2

A: You should simply use value callback, e.g. :
[
    'label' => 'Size',
    'attribute' => 'fld_size_id',
    'value' => function ($model) {
        return $model->fldSize->fld_width . 'x' . $model->fldSize->fld_height;
    },
],

A: Sorry that after more than one year, but it works (not a dropdown but Select2).
Here is the code for the form
 <?= $form->field($model, 'ID_MACH')->widget(Select2::classname(), [
      'data'=> ArrayHelper::map(Maschines::find()->all(),'ID_MACH','fullname'),
     'language'=>'ru',
    'theme'=>'krajee',
    'options'=>['placeholders'=>'suda...',
        'prompt'=>'10-'],
    'pluginOptions'=>[
        'allowclear'=>true
    ],

Next is the Model for Mashines:
public function getFullName()
        {
                return $this->customer.','.$this->Manufacturer.','.$this->type.','.$this->serial;}


text:
Q: Why is the Matrix a collective? Why is the Matrix a collective?  That is, why are humans in the bioelectric harvesting fields part of a shared simulation?
Why is this better than having each subject jacked into his or her own simulation?  It is clear from one of the training constructs that the Nebuchadnezzar crew uses ("The Woman in Red") that people can be simulated, and so it seems that a simulation designed for an individual could be populated by virtual characters as the machines see fit.
Also, discussions in other questions on this site have made it clear that

 "redpills" are allowed to escape from the Matrix, so that their threat to the Matrix can be contained.

It seems that if subjects had their own individual Matrices, then this threat would be rendered moot and the machines would be able to mothball the One altogether.

A: Doing so would defeat the entire purpose of the simulation.  As stated by the Architect, they had tried making the simulation a Utopia, making the humans happy.  However, this failed.  The result being a new Matrix, designed to be life-like, and ultimately designed to produce The One.
From IMDB, the Architect has this to say on the subject.  Basically, the original Matrix failed because humans were not given a choice.

As I was saying, she stumbled upon a solution whereby
  nearly ninety-nine percent of the test subjects accepted the program
  provided they were given a choice - even if they were only aware of it
  at a near-unconscious level. While this solution worked, it was
  fundamentally flawed, creating the otherwise contradictory systemic
  anomaly, that, if left unchecked, might threaten the system itself.
  Ergo, those who refused the program, while a minority, would
  constitute an escalating probability of disaster.

So, they were given a choice.  Then, it was discovered that a small percentage would still reject the Matrix.  The solution was to wipe everything out and start over.

The function of the One is now to return to the source, allowing a
  temporary dissemination of the code you carry, reinserting the prime
  program. After which you will be required to select from the matrix 23
  individuals, 16 female, 7 male, to rebuild Zion. Failure to comply
  with this process will result in a cataclysmic system crash killing
  everyone connected to the matrix, which coupled with the extermination
  of Zion will ultimately result in the extinction of the entire human
  race.

If they made it so that the humans were not linked together, it would have been difficult for those in Zion to get into the Matrix and recruit The One.  Without The One, the machines would lose their power source.
I would argue that "red pills" are allowed to leave to facilitate the creation of The One, not to minimize the risk.

A: Same reason websites can be on shared servers: save resources.
Edit
cde's answer is much better than mine, but to clarify what I mean by saving resources I'll use a quote from him:

By networking the humans together, they provide their own interaction,
  greatly reducing the processing and programming requirements, and
  minimizing the number of sentient machines or programs needed for the
  matrix to exist.

If each person was in their own matrix, each matrix would require the same programs across them all.  If one program needed to be updated, deleted, etc that is each individual matrix that would need this work done. Even if this didn't necessarily take up more resources to run, the amount of resources needed to maintain this kind of system would be greater.

A: Take a few assumptions for granted, a matrix meant for a single human would require a ton of programs willing to be NPCs, with both reasonable and unreasonable responses scripted, and hope the PC does not reject it. For any PC that is in a city scenario, that means a bunch of unique looking background NPCs, and a significant number of interact able ones. At that point, if they are not AI, the PC could grow suspicious. If they are AI, the program would have to be willing to do it as we know many programs have free will and can even rebel against the machine source.
By networking the humans together, they provide their own interaction, greatly reducing the processing and programming requirements, and minimizing the number of sentient machines or programs needed for the matrix to exist.
Given that, the machines weren't purely evil in their intents. They wanted to placate the humans, as far as giving them a utopia. They understand that we are herd (or pack) animals and need socializing to thrive. Networking the humans was as much a means as an end.
That said I still think there are multiple matrices running concurrently, like a MMORPG does, but there is no evidence for that aside from Smiths "entire crops lost" statement. It implies that groups of humans physically nearby were lost at once, instead of the entire matrix collapsing.
As for the rebels having the training Sims, they were scripted. A bunch of people moving in one direction, no interaction. Nothing close to a realistic human conversation.

Mouse: The woman in the red dress? I designed her. She, uhm, well she doesn't talk very much, but, but if you'd like to meet her, I can arrange a much more personalized meeting.
Switch: Digital pimp, hard at work.

A: The only answers are:

*

*They tried it and it failed or was somehow less desirable than what we are presented with.

*They have not tried it yet because the current is working fine as-is or believed to be better.

*They have not thought to try it.

The third answer is a weak one and requires no explanation, so I will pass over it. The other two are similar in that the current implementation is at least possibly better.
My answer will expand on Dave Johnson's and cde's answers.
The only other Matrix we specifically know about is from The Architect, here is the quote again, emphasis my own (Edit 1: Everything before the [...] was added in this edit.) :

The first Matrix I designed was quite naturally perfect, it was a work of art - flawless, sublime. A triumph equaled only by its monumental failure. The inevitability of its doom is apparent to me now as a consequence of the imperfection inherent in every human being. Thus, I redesigned it based on your history to more accurately reflect the varying grotesqueries of your nature. However, I was again frustrated by failure. I have since come to understand that the answer eluded me because it required a lesser mind, or perhaps a mind less bound by the parameters of perfection. Thus the answer was stumbled upon by another - an intuitive program, initially created to investigate certain aspects of the human psyche. If I am the father of the matrix, she would undoubtedly be its mother.
[...]
As I was saying, she [The Oracle] stumbled upon a solution whereby nearly ninety-nine percent of the test subjects accepted the program provided they were given a choice - even if they were only aware of it at a near-unconscious level. While this solution worked, it was fundamentally flawed, creating the otherwise contradictory systemic anomaly, that, if left unchecked, might threaten the system itself. Ergo, those who refused the program, while a minority, would constitute an escalating probability of disaster.

(Edit 1: The striked through text is incorrect. The text before it and the was added in this edit.) The Architect describes various previous Matrices he created, specifically a "flawless" and "sublime", "naturally perfect" one and one "reflect[ing] the varying grotesqueries of [human] nature". These are both described as failures. This "solution" above is specifically referring to the paradise-like Matrix made by The Oracle that didn't work out. The idea is, as I understand, that something in the human mind understood that perfection (Edit 1: and horrible imperfection) was impossible and something was wrong.
My belief is that the machines/programs while able to closely resemble human behavior are not 100%, and that a Matrix where every other being was a program would trigger a similar response from too many people. (Edit 1: This is supported in part by The Architect's inability to create an adequate Matrix. Of course it begs the question that if The Oracle is able to do it then surely it's at least possible to resemble human behavior (the scene where the program says that love isn't a human emotion, it's a word that implies a connection for example), but as stated only 99% accepted the current program implying it's still not perfect. It's not a big leap to assume that more interaction with the machines and programs would increase this rate and it would become a bigger and bigger issue.)

A: I'm not terribly familiar with Matrix lore, but I know that human will can modify the Matrix. This leads me to believe that the humans' own brains are being used to at least partially handle the processing workload of simulating the entire world. It stands to reason that the resourceful machines use humans not just as energy sources, but also as parallel processors to create the world they're contained within. If that's true, then of course you want all of the human minds working on the same simulation in parallel. Not only does that reduce the cost of the entire simulation, but it also reduces each individual human's control over the entire simulation. If each human had their own simulation and their brain was used for the processing power behind it (e.g. as is likely the case on the Nebuchadnezzar's private simulations), then each person would have far more control over their simulation and would be far more likely to notice it change on accident.
In other words, all people in one simulation is more efficient and stable than individual simulations.
Check out this Rick and Morty episode to get an idea of what I mean.

A: If AI cannot become truly sentient, like humans, then a human in a simulation will figure out that they are the only true human.  Additionally, I've heard that in the original story the computers enslaved humans not for their energy, but for their unique capabilities that the AIs could not replicate.  Consequently, there is more benefit for the AIs by combining the humans and having them interact than by separating the humans.

A: I don't know of a canon answer to this, but I have this theory...
There is apparently a minimum number of processor cores (read: human minds) that must participate together to produce enough processing power to simulate an entire planet and have it be believable. The simulation system, for example, could only generate a small city while two people were within in it, and not the entire planet. It was much smaller in scale. A sole human mind couldn't run the entire Matrix simulation in their mind and have it remain 100% believable, or it would fry their brain completely from having to work at 100% capacity all the time.
If only one person were needed, the machines could just choose one person at random, jettison the entire human race, and start over each time the anomaly occurred, and yet just over 20 people were required by the system to seed the next generation. This is clearly less than the calculations for what we have predicted would be needed for genetic diversity for perpetuation of the human race, so it's reasonable to surmise that the machines know how to manipulate the gene pool, and therefore only need the power of those chosen minds to run the full simulation temporarily while they replenish their stock.
You also couldn't share the processing power if everyone were in their own personal grid. Also, humans are known to have psychotic breaks when placed in isolation for long periods of time. For most humans, this wouldn't matter, because they'd chatter on happily to that weird person at the bar that never speaks back, but that small percentage that are attuned to the fact that they are, indeed, inside a simulation, this would drive them crazy, possibly infecting other nodes or crashing the system faster. It's much safer to simply pool resources together and not take the chance.
It's not directly stated this way in the movies, but it's plausible. There's a short story about how an asteroid hit the Earth, and destroyed a tower containing 200,000 humans that were simulating London. London literally disappeared while the processing power rerouted data to get to simulating London again. That was mentioned on Why Did the Machines Even Bother With a Matrix?.

A: We do not know exactly how efficient the Matrix is as a power source, but we do know that the Machines are proud of its efficiency. Near the end of the second film, the Architect makes comments about this at are the closest we ever see any Machine (other than Smith) come to outright bragging.
We do not know exactly how much power the Matrix can get from a human, but we do know two things:

*

*It is not infinite. If the Machines could get infinite power from humanity, then they would not bother with the rigamarole of farming millions of humans. They could do it with only a couple thousand, only one of which would be needed to provide power at any given time (the rest would provide redundancy, replacements, and a sustainable gene pool).

*They can get more out of a human than is required to account for that human's presence in the Matrix. Otherwise, humans wouldn't be a worthwhile power source.

We don't know the specifics of the state of AI technology in the time period in which the Matrix takes place, but it's safe to assume that AI probably doesn't consume computing resources (including power) at a lower rate than our current attempts at it in the real world. And in the real world, our best AIs are quite expensive indeed.
Now, consider that humans, as a rule, crave social contact. They need to live in an environment where other people exist. If they don't, they break down: something which, in the world of the Matrix, might cause them to reject it. Needless to say, this would cause problems for the Machines.
Therefore, the Matrix must provide some kind of social contact for its inhabitants. Theoretically, the Machines might be able to simulate social contact, but that would require one AI Program per simulated person. An average human would need several hundred of these simulated people in order to feel comfortable. But if AI is expensive, then running this many Programs -perhaps 3-400 per human- is almost certainly far more taxing on power than the Machines would want to sustain. It might even require so much power that humans would no longer be viable as a power source
A more efficient approach is to use humans not just for power, but to provide each other's social contacts, at a rate of one simulated person per actual person. Then the Matrix gets the social functionality it needs "for free"; the humans themselves provide it, rather than the Machines. Since the Matrix does not have to run "social AIs", it has that much more power available for the Machines themselves.


text:
Q: how to block editing of the same text for a few users I need to prevent users from simultaneously editing the same text or article on tinymce.
How can I block other users from editing while one user is editing text in the admin panel?

A: Well many ways actually.. but just of the top of my head while I sit in the John is to

*

*When someone within your application begins the edit you then send a update query to the database top update the row "editing"

*Now if the next user tries to edit the same post redirect then to a error message.

*If the first user is done then send another query to update the row "editing". Now the second ist can edit what ever they want...
Something like this will work :
If($_POST['startedit'] ) {
     ............... // start your editing and then also send a query to a database

} else {
   If($_POST['finished']){
       .............// send the update query and send them some where like homepage
   }
}

Any questions please ask

Edit 1

Alright so you asked how would you get the editing time? Well there are plethora ways to get it simple you could just use the database in fact to do the time stamps for you and I'll show you have that is possible.
Step 1) create a table in a database consisting of all the fields you need, and then at the end of the table a time stamp field that is set to update when the row is updated. (this can be done easily use PHPmyadmin if you do not know any sql)
Step 2) when a user clicks on the "startedit" button
you would send a query like so :
$query = $pdo->prepare("UPDATE `yourtable` SET `editing` = '1' WHERE `text_id` = ':id'"); //Using PDO you prepare a update query to dynamically update any ID based on what form a user is using.

$query->bindParam(':ID', $form_id); // Bind your value of the form to the parameter being passed to the PDO query

$query->execute() // Run the PDO query.

now you can do a conditional if on $query to check if it executed, if it did it will return true... so we do it like this :
if($query) {
    Redirect(to the form that he / she wants to work on) // Redirect (obviously lol)
} else {
............ What ever? ...........
}

Now your asking yourself well crap how do I check if some one is currently editing this form?
Well then we need to run a query when along side of to see if the form is being edited.
so we do :
$query = $pdo->prepare("SELECT * from `yourtable` WHERE `editing` = `1` and `form_id` = :ID"); // Retrieve all forms that are being edited

$query->bindParam(':ID', $form_id); // Bind the parameter

 $query->execute();

 if ($query->rowCount() > 0 ) {
     die("OOOPS! Some one is editing this form!! - Sorry to late!")
 } else {
   echo "Have fun editing punk!";
 }

There you go, that is pretty much the gist of it. I will not code all of it for you. But this is a rudimentary way for you to get this done. Now of course you want to add if a time out has occurred kick the user from editing and what not. And if the user finishes then update editing to = 0. and so on.
This will help you build up your work.
I am also using PDO so if your not accustomed to it read this and this.

*

*Enjoy

A: Probably the most friendly solution is to let users edit articles simultaneously. In case of a conflict - say the article gets saved by different users in a given timespan - one could choose wich version of the article to use. This would require versioning though and is probably harder to implement then @Rixhers Ajazi solution.


text:
Q: jQuery - slideToggle, links continue to slide up and down I'm trying to have some menu items slide down when a user hovers on an image, then hide when they move the cursor away from the image and/or the menu items. The problem is, if the user isn't really, really accurate when they move the mouse to a menu item, the menu items will slide up, and down, and up... and down.
Is there a way to get this working so that once the menu items appear, they will remain in place until the user "mouses out" of either the main image, or the link items below the image?
Here's a JSFiddle. Any help is appreciated.

A: Stop the hover events from propagating when called on the .slideBucket children.  You'll need to also position the slideBucket up so that it overlaps the bucket and a mouseleave is not triggered.  And then manually do the slideUp on the slideBucket.  Adding a .stop(true, true) also helps clean up the animation:
http://jsfiddle.net/gilly3/yHMQV/9/
$(".bucket").hover(function() {
    $(this).children('.slideBucket').stop(true, true).slideToggle('400');
}).children('.slideBucket').hover(function(e) {
    e.stopPropagation();
}, function(e) {
    e.stopPropagation();
    $(this).slideUp(400);
});

A: Here's my version: jsfiddle
hover actually takes two functions :-)
$(document).ready(function(){
    $(".bucket").hover(
        function(){
            $(this).children('.slideBucket').slideDown('400');
        },
        function(){
            $(this).children('.slideBucket').slideUp('400');
        }
    );
});


text:
Q: Hyperledger Fabric peer, peer chaincode commands Hyperledger Fabric provides peer, peer chaincode commands: https://hyperledger-fabric.readthedocs.io/en/release-2.3/commands/peerchaincode.html
I have setup on different VMs. I am using commands like:
peer chaincode query on terminal on one vm
It should show the chaincode for the current value on a peer's ledger.
Instead I get command not found error. What am i missing?

A: That is because the terminal doesn't know where to find the peer command. You have to set the $PATH environment variable to indicate the location of the peer binary file. From the doc

You may want to add that to your PATH environment variable so that these can be picked up without fully qualifying the path to each binary. e.g.: export PATH=/bin:$PATH


text:
Q: Youtube thumbnail does not appear always I am showing a list of youtube videos on my client's site. All videos have thumbnail. I have used the following code:
<object style="display: block;" width="300" height="250" data="https://www.youtube.com/v/wK_JI0UxY3g?fs=1&hl=en_US" type="application/x-shockwave-flash">
<param name="data" value="https://www.youtube.com/v/wK_JI0UxY3g?fs=1&hl=en_US" />
<param name="src" value="https://www.youtube.com/v/wK_JI0UxY3g?fs=1&hl=en_US" />
</object>

I am displaying 5 videos on the page. Strangely, thumbnail appears on some videos (randomly).
Is there any attribute to specify that "thumbnail should appear compulsorily"? I've tried showlist=1 which does not solve the issue.

A: According to youtube's docs, this embed code is deprecation.

Deprecation Notice
  YouTube  embeds were deprecated on January 27, 2015. Please migrate your applications to use  embeds, which can intelligently use whichever embedded player – HTML (<video>) or Flash (<object>) – the client supports.

https://developers.google.com/youtube/player_parameters


text:
Q: Linux Mint: pastebin is in /usr/local/bin I'm running Linux Mint 17.
I found a pastebin python file in /usr/local/bin
In light of what people use pastebin for, was this a security risk?

Output from the stat command:
  File: 'pastebin'
  Size: 576         Blocks: 8          IO Block: 4096   regular file
Device: fc01h/64513d    Inode: 5768847     Links: 1
Access: (0755/-rwxr-xr-x)  Uid: (    0/    root)   Gid: (    0/    root)
Access: 2016-01-19 10:43:31.595833213 -0500
Modify: 2015-02-03 07:15:10.000000000 -0500
Change: 2016-01-19 10:43:30.575833252 -0500
 Birth: -

It is believed the pastebin was put there by the original distro. Related discussion here Distro invades '/usr/local'.

A: Whether it's in /usr/local/bin or /usr/bin is irrelevant.
It's just a python script that posts either its arguments or its STDIN to a web service:
#! /usr/bin/python

import sys, os, stat, subprocess

content = ""

mode = os.fstat(0).st_mode
if stat.S_ISFIFO(mode):
    content = sys.stdin.read()
elif stat.S_ISREG(mode):
    content = sys.stdin.read()
else:
    args = sys.argv[1:]
    if len(args) == 1 and os.path.exists(args[0]):
        with open(args[0], 'r') as infile:
            content = infile.read()
    else:
        str_args = ' '.join(args)
        content = str_args

if content != "":
    p = subprocess.Popen(["/bin/nc", "paste.linuxmint.com", "9999"], stdin = subprocess.PIPE)
    p.communicate(content)

If your users have Internet access, pastebin doesn't allow them to do anything more than what they already can do.
BTW, isn't it nice that bash allows you to compress the above ugly pythonese to just?:
/bin/nc paste.linuxmint.com 9999 <<< "${*:-`cat`}"

(It won't behave completely identically, but it shouldn't matter.)


text:
Q: Real World CNC Machining Geometry Problem I need to re-find center on a circle. In our tool room a tool maker milled an annulus with a 4 hole pattern. The holes were milled in a square, each equidistant from the center of the annulus. The part was removed from the machine and pins were installed into the holes. Then returned to the machine for more work.

In order to re-find the center the tool maker puts a dial indicator in the spindle and moves the spindle close to the center of the part and checks the pins with the indicator. The indicator will tell him the relative distance each pin is from the center of the spindle. in other words the indicator tip is some at some arbitrary radius from the center of the spindle and when it moves past a pin the dial shows how much closer the pin is to center than the neutral position of the tip.
Known:

*

*The radius of the annulus, pin pattern and pins

*The origin of the coordinate system is within the annulus

*The origin of the coordinate system is defined by the axis of the spindle/indicator.

*The difference, radially, between a radius of constant, but arbitrary length and the distance from the pins and the origin of the coordinate system.

Unknown

*

*The angle of the square hole pattern to the coordinate system

*Location of the center of the annulus relative to the coordinate system.

Assumptions:

*

*The parts are machined to perfect tolerances

Looking for:

*

*An equation that describes the center of the annulus

Update:
Please forgive the hand drawn diagram (if anyone has a recommendation for an easy way to draw pretty diagrams on the computer, please let me know).
Here is a drawing of how I visualize the problem.
R is the arbitrary, unknown radius of the indicator centered at the origin.
$\delta_A$ (etc.) is the measurement from the indicator. Therefor, point A (the closest point of the pin to the center) is at a distance of R-$\delta_A$ from the center, with an unknown angle $\theta_A$
Square ABCD is of known size but not known position, so I cannot simply find it's center. AB=BC=CD=AD, AC=BD; known: length AC
Looking for the position of center point c (sorry about any ambiguity around pin C and center point c)

A:
Let (known) common length $CA_k=\rho$.
Let $r$ be the length and $\theta$ the polar angle of $\vec{OC}$.
Let $\rho$ be the length and $\alpha$ the polar angle of $\vec{CA_4}$.
With the other notations of the figure, we can write 4 equations with 3 unknowns, each one being  the cosine law applied to one of the four triangles with "a" red, "a" blue and "the" green arrow :
$$OA_k^2=OC^2+CA_k^2-2 OC.CA_k \cos(...)$$
i.e.,
$$\color{blue}{\gamma_k}^2=\color{green}{r}^2+\color{red}{\rho}^2-2 r \rho \cos(\theta+\alpha+k \pi/2), \ \ \ \ k=1,2,3,4,$$
giving rise to a system of four equations with three unknowns $r,\theta$ and $R$:
$$\begin{cases}
k=1: \ \ &(R-\delta_1)^2=\gamma_1^2&=&r^2+\rho^2+2 r \rho \sin(\theta)\\
k=2: \ \ &(R-\delta_2)^2=\gamma_2^2&=&r^2+\rho^2+2 r \rho \cos(\theta)\\
k=3: \ \ &(R-\delta_3)^2=\gamma_3^2&=&r^2+\rho^2-2 r \rho \sin(\theta)\\
k=3: \ \ &(R-\delta_4)^2=\gamma_4^2&=&r^2+\rho^2-2 r \rho \cos(\theta)
\end{cases}$$
which looks tractable ; for example
$$\frac{Eq. 1-Eq. 3}{Eq. 2-Eq. 4} \iff \tan \theta = \frac{\gamma_1^2-\gamma_3^2}{\gamma_2^2-\gamma_4^2}$$
connecting in fact angle $\theta$ and radius $R$.
Anyway, there is a good hope that this system having less unknowns than equations is solvable...
I stop there and ask you if it is the kind of development you wanted or not, or not exactly...


text:
Q: Getting Parent Page name How to get the parent page name of the modal popup dialog? I have one page that is using in two or more pages by using modal popup. When the close button of the modal popup dialog window, it will redirect to the orgin. But where from we will get the parent page name by programmatically?

A: You can get a reference to the parent from javascripts window.opener object, if the current window was indeed opened in a popup/modal dialog.

A: As David says, you can use window.opener to get the page that opened a popup window.
However, if you're using a ModalPopupExtender from the AJAX Control Toolkit then you'll likely already be on that page, in which case you'd need to hook up something to the OnOkScript or OnCancelScript attributes of the extender to refresh the page.
If you could post some code it'll make it easier to offer a solution.


text:
Q: MySQL query optimization sum.. case Is there any way to optimize the query below?
SELECT
DATE_FORMAT(a.duedate,'%d-%b-%y') AS dte,
duedate,
SUM(CASE WHEN (typeofnotice='ddat' AND STATUS='open') THEN 1 ELSE 0 END) AS 'DDatOpen',
SUM(CASE WHEN (typeofnotice='ddat' AND STATUS='closed') THEN 1 ELSE 0 END) AS 'DDatClosed',
SUM(CASE WHEN (b.action='tagunchanged' AND STATUS='closed') THEN 1 ELSE 0 END) AS 'DDatUnchanged',
SUM(CASE WHEN (typeofnotice='rss' AND validindicator IS NULL AND STATUS='open') THEN 1 ELSE 0 END) AS 'RSSValidation',
SUM(CASE WHEN (typeofnotice='rss' AND validindicator=1 AND STATUS='open') THEN 1 ELSE 0 END) AS 'RSSValidOpen',
SUM(CASE WHEN (typeofnotice='rss' AND validindicator=1 AND STATUS='closed') THEN 1 ELSE 0 END) AS 'RSSValidClosed',
SUM(CASE WHEN (typeofnotice='rss' AND validindicator=0) THEN 1 ELSE 0 END) AS 'RSSInvalid',
SUM(CASE WHEN (typeofnotice='copernic' AND validindicator IS NULL AND STATUS='open') THEN 1 ELSE 0 END) AS 'CopernicValidation',
SUM(CASE WHEN (typeofnotice='copernic' AND isaward=1 AND validindicator=1 AND STATUS='open') THEN 1 ELSE 0 END) AS 'CopernicValidAwardOpen',
SUM(CASE WHEN (typeofnotice='copernic' AND isaward=1 AND validindicator=1 AND STATUS='closed') THEN 1 ELSE 0 END) AS 'CopernicValidAwardClosed',
SUM(CASE WHEN (typeofnotice='copernic' AND isaward=1 AND validindicator=0) THEN 1 ELSE 0 END) AS 'CopernicInvalidAward',
SUM(CASE WHEN (typeofnotice='copernic' AND isaward=0 AND validindicator=1 AND STATUS='open') THEN 1 ELSE 0 END) AS 'CopernicOpportunityValidOpen',
SUM(CASE WHEN (typeofnotice='copernic' AND isaward=0 AND validindicator=1 AND STATUS='closed') THEN 1 ELSE 0 END) AS 'CopernicOpportunityValidClosed',
SUM(CASE WHEN (typeofnotice='copernic' AND isaward=0 AND validindicator=0) THEN 1 ELSE 0 END) AS 'CopernicOpportunityInvalid',
SUM(CASE WHEN (typeofnotice='copernic' AND STATUS='limited') THEN 1 ELSE 0 END) AS 'CopernicLimitation',
SUM(CASE WHEN ((validindicator IS NULL OR validindicator = 1) AND STATUS='open') THEN 1 ELSE 0 END) AS 'TotalNotices',
SUM(CASE WHEN (validindicator=1 AND STATUS='closed') THEN 1 ELSE 0 END) AS 'TotalCompleted',
SUM(CASE WHEN (validindicator=0 AND (typeofnotice='wget' OR typeofnotice='copernic' OR typeofnotice='rss')) THEN 1 ELSE 0 END) AS 'TotalInvalid'
FROM tblNotices AS a LEFT JOIN tblTransactions AS b
ON a.id = b.noticeid WHERE b.noticeid IS NOT NULL
WHERE duedate >= '2011-04-04 00:00:00'  AND  a.duedate <= '2012-05-08 24:00:00'
GROUP BY dte
ORDER BY dueDate ASC;

tblTransactions has 1.5 million rows
tblNotices has 900k rows.
And the query runs for about 1 min. Is it normal? Is there any way to optimize this query?

I think the DATE_FORMAT function here really kills the performance.. Is there any tips here? It runs for about 58 seconds.

A: The query looks as simple as it could get ... aside from your SUM( IF()) instances.
Your query has a LEFT-JOIN to transactions, but then have where b.noticeID is not null.  The combination of the two results in a normal "JOIN" or "INNER JOIN" meaning required on both sides.
As for your Where clause, I would ensure you have a simple index on the due-date.  Your table shows a "MUL" (multiple key) index, I would ensure the due date is the first part of that key, or at least ONE index has duedate as the first field.
Next, your group by.  Since you are doing a group by the date formatting of the due date, I would just leave the group by based on the duedate (matching the table index) only.  The visual formatted string will follow along for the ride anyhow.  And since your Order By is also based on the duedate (and not the pretty formatted string version), it should be good to go.
As for the date range of the query itself... how many records are within the range provided.
REVISION
You MIGHT be able to take advantage of having a multipart index of the elements used in your query so the query doesn't have to actually go to the page data to look at the individual elements from the entire record.  Since the data would be part of the index key, the query could use that directly and not require going to the pages.
Try an index on
INDEX on ... ( DueDate, status, IsAward, TypeOfNotice, ValidIndicator )
Also, for clarification of alias.fields in your query.  Sometimes you explicitly reference the "a." alias and other times, have no alias.  For others working on the query after you, or others trying to offer help.  It makes it easier to explicitly reference all fields with proper alias to prevent ambiguity of which columns from what table.  Yes, you provided your table structure here, but future could make things easier than having to keep looking back at structures.

A: Well, that
FROM tblNotices AS a LEFT JOIN tblTransactions AS b
ON a.id = b.noticeid WHERE b.noticeid IS NOT NULL

is the same as
FROM tblNotices AS a INNER JOIN tblTransactions AS b
ON a.id = b.noticeid

The second one could be faster.
Why don't you group by duedate? Then you could omit the DATE_FORMAT(), but that's just peanuts, I guess. If you omit it, the ORDER BY is also not necessary, since it's implicated in the GROUP BY then.
Apart from that there's not much you can do.


text:
Q: Resolvent of the Laplacian as a pseudodifferential operator and its single layer potential In M.Taylor's book "Partial differential equations II" it is shown that the fundamental solution $E(x,y)$ of the Laplacian equation gives rise to an elliptic pseudodifferential operator $S$ on the boundary $\partial \Omega$ of a domain $\Omega$ (for simplicity, let $\Omega \subset \mathbb R^3$ and $\partial \Omega$ be smooth) by the formula:
$$
   Sf (x) = \int_{\partial \Omega} E(x,y)f(y) \, dS(y), \\
   E(x,y) = \frac{1}{4\pi|x-y|},
$$
where $dS(y)$ is the surface measure. The fact $S \in OPS^{-1}(\partial \Omega)$ follows from $E \in OPS^{-2}(\mathbb R^3)$ and from the representation formula
$$
  Sf(x) = \lim_{y \in \Omega, y\to x} \int_{\mathbb R^3} E(x,y)(f\delta_{\partial \Omega}) dy, \quad x \in \partial \Omega,
$$
where $\delta_{\partial \Omega}$ is the delta-function concentrated on $\partial \Omega$. Ellipticity follows from the explicit expression for the symbol of $S$ (the symbol of $E$ restricted to $\partial \Omega$ and integrated along conormal direction).
Here is my question. Consider, instead of $E$, the limit value of resolvent $R_+(\lambda)=R(\lambda+i0)$, $\lambda > 0$, for the operator $-\Delta$. Its integral kernel is
$$
  R_+(x,y,\lambda)  = \frac{e^{i\sqrt \lambda |x-y|}}{4\pi |x-y|}.
$$
In analogy with $S$ we can define
$$
  S_+(\lambda)f(x) = \int_{\partial \Omega} R_+(x,y,\lambda)f(y) \,dS(y).
$$
Is it true that $R_+(\lambda) \in OPS^{-2}(\mathbb R^3)$? If yes, what is its symbol? Is it true that $S_+(\lambda) \in OPS^{-1}(\partial \Omega)$ and is elliptic?

A: You can find a lot on this operator in the book
 Agranovich, Mikhail S. Sobolev spaces, their generalizations and elliptic problems in smooth and Lipschitz domains. Revised translation of the 2013 Russian original. Springer Monographs in Mathematics. Springer, Cham, 2015.


text:
Q: What is the difficulty/advantage to obfuscate a multi-thread program? According to my knowledge, several obfuscation strategies are widely used(or at least described in academic) like:

*

*complicating control flow

*

*inserting bogus control-flow

*control-flow flattening

*jump through branch functions

*opaque values from array aliasing

*Opaque Predicates

*

*opaque predicates from pointer aliasing

*dynamic obfuscation

*

*self-modifying state machine

*code as key material

From the examples they give when introducing these obfuscation ways, multi-thread program has not been talked.
So I am wondering whether these strategies are feasible(or even feasible, but not very practical) in multi-thread programs?

A: Why would they not be applicable?
Obfuscation basically tries to make analysis hard.   I'd imagine you could add a few more techniques based on multithreading, to leverage its already difficult to understand nature:
*  obfuscated synchronization, esp. conditional or multiple waits
*  bogus fork/joins
*  things that look like data races

In terms of difficulty: obfuscation is relatively easy once you know what you want to do, and you have good machinery to manipulate source code.  (The latter is the hard part, not the former).


text:
Q: How to implement SSO using ADFS bypassing the ADFS login page in iOS app I have an app where earlier there was only AD login which we directly authenticated the app via our own server API as a middleware. Now after implementing the ADFS on the server, we are getting the ADFS login page, which we would like to bypass in order to maintain the workflow.
Basically we want to connect to Office 365 data via our own server and feed it to our app.
Does anyone know if even it is feasible to bypass that login page? ADFS v3.0

A: ADFS has two flows; passive (browser) and active (WCF).
You can bypass the login screen on passive by setting up the browser to do IWA.
Active will give you the flow you want i.e. authentication via a service.


text:
Q: Re-writing mysql statement - select left join alias union join subtraction issue I am thinking of the best way to re-write this:
SELECT
debits.account_title, debits.total - credits.total AS net_reduction
FROM
    (
SELECT SUM(a) FROM
(
SELECT SUM(mainaccount_a_2017.amount) AS a FROM `mainaccount_a_2017`
LEFT JOIN chart_of_account ON (chart_of_account.joint_account_numbers = mainaccount_a_2017.joint_account_number)
LEFT JOIN asset_liability_income_expenditure_tbl ON (asset_liability_income_expenditure_tbl.a_l_code = chart_of_account.account_type)
WHERE mainaccount_a_2017.dr_cr_action = 'DR' AND asset_liability_income_expenditure_tbl.a_l_code = 'IN'

UNION ALL

SELECT SUM(mainaccount_b_2017.amount) AS a FROM `mainaccount_b_2017`
LEFT JOIN chart_of_account ON (chart_of_account.joint_account_numbers = mainaccount_b_2017.joint_account_number)
LEFT JOIN asset_liability_income_expenditure_tbl ON (asset_liability_income_expenditure_tbl.a_l_code = chart_of_account.account_type)
WHERE mainaccount_b_2017.dr_cr_action = 'DR' AND asset_liability_income_expenditure_tbl.a_l_code = 'IN'
)a
  )AS debits
JOIN
   (
SELECT SUM(a) FROM
(
SELECT SUM(mainaccount_a_2017.amount) AS a FROM `mainaccount_a_2017`
LEFT JOIN chart_of_account ON (chart_of_account.joint_account_numbers = mainaccount_a_2017.joint_account_number)
LEFT JOIN asset_liability_income_expenditure_tbl ON (asset_liability_income_expenditure_tbl.a_l_code = chart_of_account.account_type)
WHERE mainaccount_a_2017.dr_cr_action = 'CR' AND asset_liability_income_expenditure_tbl.a_l_code = 'IN'

UNION ALL

SELECT SUM(mainaccount_b_2017.amount) AS a FROM `mainaccount_b_2017`
LEFT JOIN chart_of_account ON (chart_of_account.joint_account_numbers = mainaccount_b_2017.joint_account_number)
LEFT JOIN asset_liability_income_expenditure_tbl ON (asset_liability_income_expenditure_tbl.a_l_code = chart_of_account.account_type)
WHERE mainaccount_b_2017.dr_cr_action = 'CR' AND asset_liability_income_expenditure_tbl.a_l_code = 'IN'
)a
   )AS credits
ON debits.account_title = credits.account_title

A: Try this:
SELECT B.account_title,
       SUM(CASE WHEN A.dr_cr_action = 'CR' THEN A.amount * -1 ELSE A.amount END) AS net_reduction
FROM (SELECT A.joint_account_number, A.dr_cr_action, A.amount
      FROM mainaccount_a_2017 A
     UNION ALL
      SELECT B.joint_account_number, B.dr_cr_action, B.amount
      FROM mainaccount_b_2017 B
     ) AS A
INNER JOIN chart_of_account B ON A.joint_account_number = B.joint_account_numbers
WHERE B.account_type = 'IN'
GROUP BY B.account_title;

Check the SQL FIDDLE DEMO:
::OUTPUT::
|           account_title | net_reduction |
|-------------------------|---------------|
| OTHER GRANTS AND GIFTS  |        301200 |


text:
Q: divisors and powers of line bundles Can anyone help me with the following question? Let $X$ be a smooth, projective algebraic variety over a field $k$ of characteristic zero. Let $D$ be an effective divisor on $X$ and $m \geq 2$ an integer.
Under which conditions there exists a line bundle $L$ such that $O_X(D)=L^m$?
There is of course the obvious one: $m$ should divide de degree of $D$. Is that sufficient?
Thanks

A: There is no standard way to deduce that a divisor $D$ on a projective variety $X$ is $m$-divisible in the Picard group, and even for $m=2$ this can be a difficult problem. Geometrically, this condition is equivalent to the existence of a simple cyclic cover $Y \to X$ of degree $m$ branched precisely on $D$.
The condition you give is not sufficient, and the following is a counterexample. Take a quartic surface $X \subset \mathbb{P}^3$ and assume that $X$ contains a conic $D$. Then the degree of $D$ with respect to the hyperplane section of $X$ is $2$. On the other hand, there is no divisor $L$ on $X$ such that $2L=D$. In fact, since $X$ is a $K3$ surface, by adjunction formula one finds $D \cdot D=-2$, that would imply $L \cdot L=-1/2$, a contradiction.
However, the condition is true for curves (see my comment below) and also in the following situation. Assume that $\textrm{Pic}(X)=\mathbb{Z}$, generated by an effective divisor $H$. If $\deg_H D = m \deg_H H$, then $D$ is linearly equivalent to $mH$. This happens for instance when $X=\mathbb{P}^n$, when $X \subset \mathbb{P}^3$ is a very general smooth surface of degree at least $4$ and when $X \subset \mathbb{P}^n$ is a smooth complete intersection of dimension at least $3$.


text:
Q: "all over" vs. "all across" Consider these two sentences.

people use smart phones all over the
  world
people use smart phones all across the
  world

per Oxford Dictionary, "all over" means "everywhere".
per Cambridge Dictionary, "across" means

in every part of a particular place or country

And then, "all across the world" means "everywhere in the world". Obviously both of them mean the same.
However, Google Ngram implies that the former is much more commonly used than the latter.

So, is it both grammatical and idiomatic to say "all across the world"?

update: thanks to @FumbleFingersReinstateMonica reminder, here is another one.


text:
Q: Cómo saber si un método o propiedad está siendo sobreescrita Tengo una clase que solamente define algunas propiedades públicas pero que tiene una larga cadena de herencia.
public class AgencyPaginatedQuery : SortedPaginatedQuery
{
    public string Code { get; set; }
    public string Name { get; set; }
    public string Initials { get; set; }
}

public class SortedPaginatedQuery : PaginatedQuery
{
    public string Sort { get; set; }
    public string Order { get; set; }
}

public class PaginatedQuery
{
    public int? Start { get; set; }
    public int? Size { get; set; }
}

La clase que estoy examinando es AgencyPaginatedQuery y estoy tratando de obtener los nombres de dichas propiedades usando LINQ y Reflection. Hasta ahora he sido capaz de obtener cuales de estas propiedades pertenecen a la clase en cuestión con una simple consulta
var type = typeof(AgencyPaginatedQuery);
var names = from prop in type.GetProperties()
            where prop.DeclaringType.Name == type.Name &&
                  prop.MemberType == System.Reflection.MemberTypes.Property
            select prop.Name;

Esto me retorna
[0] = "Code"
[1] = "Name"
[2] = "Initials"

Pero ahora me falta filtrar de esa lista las propiedades que son sobreescritas para en caso que yo escriba
public class AgencyPaginatedQuery : SortedPaginatedQuery
{
    public string Code { get; set; }
    public string Name { get; set; }
    public string Initials { get; set; }
    public override string Sort { get; set; }
}

esta última propiedad Sort no me aparezca en la lista.
¿Como puedo saber si la propiedad tiene un override usando mi consulta?
PD: Sé que debo marcar como virtual la propiedad en la clase base para que esto funcione.

A: Te paso una forma de checkearlo mediante GetBaseDefinition()
Usando el flag BindingFlags.DeclaredOnly ignoras los miembros heredados.
Type type = typeof(AgencyPaginatedQuery);

foreach ( var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) {
    var getMethod = property.GetGetMethod(false);
    if (getMethod.GetBaseDefinition() == getMethod) {
        Console.WriteLine(getMethod);
    }
}

si la propiedad está sobre-escrita el MethodInfo del getter será diferente al MethodInfo de GetBaseDefinition()
Podrías obtenerlo de esta manera:
var names = from prop
              in type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
             let getMethod = prop.GetGetMethod(false)
           where getMethod.GetBaseDefinition() == getMethod
          select prop.Name;

Como resultado obtengo:

Code
   Name
   Initials