text:
Q: Ocra generated exe doesn't accepts arguments am building .exe using ocra like this ocra testing.rb -- sample
here am passing ''sample'' as argument to the below code and building an exe
require "selenium-webdriver"

$var = ARGV[0]

driver = Selenium::WebDriver.for :chrome
wait = Selenium::WebDriver::Wait.new(:timeout => 20)

puts $var

driver.navigate.to "https://accounts.google.com/ServiceLogin?service=mail&passive=true&rm=false&continue=https://mail.google.com/mail/&ss=1&scc=1&ltmpl=default&ltmplcache=2&emr=1&osid=1#identifier"
sleep 5
input = driver.find_element(:id, "Email")
input.send_keys($var)
button = driver.find_element(:id, "next")
button.click
sleep 5

the issue here is ,after building the .exe and when i tried to run exe by passing a different argument (value) it always takes the same value as "sample" to the argument as it was hard code .
C:\Users\shivaj\Downloads>testing.exe -- test1
it puts as sample
Please help me out with this ,i just made a sample program with issue but the actual program has more to do with it . Any help is appreciated . Thank you for the help !

A: I suppose this is because you assign the parameter to a variable and while building the exe you provide a parameter.
I use some scripts that use parameters and that are converted to exe using ocra.
What I do is the following
ARGV.each do|arg|
  # do whatever with arg
end

And then, when you build the exe you don't provide a parameter, the code will run fine because ARGV will be there but empty.

A: Currently is not supported by Ocra: https://github.com/larsch/ocra/issues/48


text:
Q: How to get ContentReference Name I have attached some image in my custom field 'Rich Text Area'. Than i just want name of uploaded or attached image from Field.
Thanks In Adv.

A: I'm afraid that rich text area simply doesn't care about file name. Also I can see only one advantage of using this field - it's can display image at your page layout.
If I'm right, you can store your files in attachments and display them in your rich text.
In the following example trigger for attachment checks if its our sObject type and then updates custom fields with file name and file link:
trigger attachmentTrigger on Attachment (after update, after insert) {
string placeholder = '';
list<contact> contactToUpdate = new list<Contact>();

for (Attachment att :trigger.new) {
    if (att.ParentId.getSobjectType() == Schema.Contact.SObjectType){

        List<String> fillers = new String[]{att.name,string.valueOf(att.id)};
        contactToUpdate.add(new Contact(id = att.ParentId,
                                        pname__c = att.name,
                                        picture__c = String.format(placeholder, fillers)));
    }
}
update contactToUpdate;
}

You will see the latest image in you rich text. You can change it to readonly mode.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ordering x-axis when combining plot types I'm combining a boxplot and a dot plot using ggplot and would like to order the x-axis so that the boxplots are next to each other.
Reordering the factors to the desired order does not work as ggplot calls fortify on the data and removes the unused factors when I pass data to geom_boxplot or geom_point.
Here's an example.
set.seed(100)
x<-factor(rep(LETTERS[1:3],5))
y<-runif(15,0,10)

data<-data.frame(x=x,y=y)

data$x <- factor(data$x,levels=c("A","C","B"))

library(ggplot2)
ggplot(data,aes(x,y))+
        geom_boxplot(data=data[data$x %in% c("A","C"),])+
        geom_point(data=data[data$x=="B",])

The desired output would be the A and C boxplots next to each other, followed by the B dot plot.

A: You need scale_x_discrete():
library(ggplot2)
ggplot(data,aes(x,y))+
  geom_boxplot(data=data[data$x %in% c("A","C"),])+
  geom_point(data=data[data$x=="B",]) +
  scale_x_discrete(limit = c("A", "C", "B"))


text:
Q: Array not looping correctly - Java I have an array with 60 values, and when I click the next button, it will cycle through all of the values of my array in ascending order until the number 60, then it starts at number one again.
I also have a previous button, so I can go down values instead of going up. When I hit the previous button on the first array value [0], my app crashes and I am not sure why.
Here is my code:
public String nextFact() {
    i++;
    if(i >= facts.length) {
        i = 0;
    }
    return facts[i];
}

public String previousFact() {
    i--;
    if(i < 0) {
        i = facts.length;
    }
    return facts[i];
}

A: You are getting an ArrayIndexOutOfBoundsException when you change i to facts.length, because valid array indexes range from 0 through facts.length - 1.  Set i to facts.length - 1.
if(i < 0) {
    i = facts.length - 1;
}

Your wrapping-around code for greater than or equal to the length should be working fine.

A: Your array is of size array.length. So the last index will be array.length-1. In your previous function, you assign array.length to i. This is larger index than max index for array and therefore it crashes down. You must be getting am indexoutofbound error too.
You should replace that line with this:
i = facts.length - 1;


text:
Q: is this txt file actually an image? I found this GitHub rep about image classification (Male and female images) using an artificial neural network, the training data are 2 directories "./male", and "./female", each one contains a list of txt files.
these text files contain rows of numbers, each row of 16 numbers.
a preview
37 40 48 49 49 45 41 34 34 34 33 34 33 33 33 33
32 31 31 31 30 30 29 29 28 27 28 27 27 26 26 26
25 25 24 24 24 23 23 22 22 21 21 20 20 19 19 19
18 19 20 21 25 25 24 22 16 17 15 22 21 20 21 20
20 20 19 19 19 16 20 21 23 23 23 23 23 23 23 24
24 24 25 24 24 25 26 25 25 26 26 25 26 26 26 26
27 27 27 28 28 29 29 29 29 30 29 29 29 29 29 29
29 30 29 29 30 30 30 30 30 30 29 29 29 29 28 29
...

I don't understand! ARE THESE SUPPOSED TO BE IMAGES (matrices of pixels values)?
the rep link:
https://github.com/Kurispy/neuralnet

A: By investigating the source code of Main.java we see that files are intended to be painted https://github.com/Kurispy/neuralnet/blob/master/Main.java#L90
public static void painter(FileInputStream fin) {
double[] store = new double[120 * 128];
    byte[] buffer = new byte[(15360 + 1) * 8];
    ByteBuffer b = ByteBuffer.wrap(buffer);
    DoubleBuffer db = b.asDoubleBuffer();

    try {
        while(fin.available() > 0) {
            fin.read(buffer, 0, (15360 + 1) * 8);

            db.get();
            db.get(store);
            db.rewind();
            paint(store);
        }
    }
    catch (java.io.IOException e) {
        System.err.println(e.getMessage());
    }

}

and we see that each file is interpreted as 120 x 128 grayscale image, by loading first file and trying to plot it like this we see it is a picture of a face.

A: Yes the files contain grayscale images. It is obvious when you look at the actual code.


text:
Q: Process hangs before termination with ubuntu 18.04 When using ABAQUS 6.14 (but also ABAQUS 2018) on ubuntu 18.04 everything seems to work fine except the termination of the standard process (the process started when performing an implicit analysis -- if you are not familiar with this it doesn't matter).
The analysis indeed works as one can also see in a log file (the .sta file, for those who are familiar with abaqus) the message THE ANALYSIS HAS COMPLETED SUCCESSFULLY. The output database contains the analysis results. However, after the analysis has been completed, the process standard remains in a sleeping status using 0% CPU and keeping the same amount of RAM as when it was running.
From strace I get:
[pid 23191] close(8)                    = 0
[pid 23185] <... select resumed> )      = 0 (Timeout)
[pid 23185] select(0, NULL, NULL, NULL, {tv_sec=0, tv_usec=50000} <unfinished ...>
[pid 23193] <... select resumed> )      = 0 (Timeout)
[pid 23193] futex(0x7f3acd917db0, FUTEX_WAKE_PRIVATE, 1 <unfinished ...>
[pid 23191] futex(0x7f3acd917db0, FUTEX_WAIT_PRIVATE, 2, NULL <unfinished ...>
[pid 23193] <... futex resumed> )       = 0
[pid 23191] <... futex resumed> )       = -1 EAGAIN (Resource temporarily unavailable)
[pid 23191] futex(0x7f3acd917db0, FUTEX_WAKE_PRIVATE, 1) = 0
[pid 23193] select(7, [4 5 6], NULL, NULL, {tv_sec=0, tv_usec=20000} <unfinished ...>
[pid 23191] munmap(0x7f3ab130b000, 327680) = 0
[pid 23191] munmap(0x7f3ab136b000, 1114112) = 0
[pid 23191] munmap(0x7f3ab16db000, 1114112) = 0
[pid 23191] munmap(0x7f3ab0fbb000, 1114112) = 0
[pid 23191] munmap(0x7f3ab0ddb000, 1114112) = 0
[pid 23191] munmap(0x7f3ab0a0b000, 1114112) = 0
[pid 23191] munmap(0x7f3ab03fb000, 1114112) = 0
[pid 23191] munmap(0x7f3ab050b000, 1114112) = 0
[pid 23191] munmap(0x7f3ab00cb000, 1114112) = 0
[pid 23191] munmap(0x7f3ab02eb000, 1114112) = 0
[pid 23191] munmap(0x7f3ab14eb000, 1114112) = 0
[pid 23191] futex(0x7f3ab8a5dd44, FUTEX_WAIT_PRIVATE, 8, NULL) = -1 EAGAIN (Resource temporarily unavailable)
[pid 23191] futex(0x7f3ab8a5dd44, FUTEX_WAIT_PRIVATE, 12, NULL <unfinished ...>
[pid 23193] <... select resumed> )      = 0 (Timeout)
[pid 23193] select(7, [4 5 6], NULL, NULL, {tv_sec=0, tv_usec=20000}) = 0 (Timeout)
[pid 23193] select(7, [4 5 6], NULL, NULL, {tv_sec=0, tv_usec=20000} <unfinished ...>
[pid 23185] <... select resumed> )      = 0 (Timeout)
[pid 23185] select(10, [5 6 8 9], NULL, NULL, {tv_sec=0, tv_usec=20000} <unfinished ...>
[pid 23193] <... select resumed> )      = 0 (Timeout)
[pid 23193] select(7, [4 5 6], NULL, NULL, {tv_sec=0, tv_usec=20000} <unfinished ...>
[pid 23185] <... select resumed> )      = 0 (Timeout)
[pid 23185] select(0, NULL, NULL, NULL, {tv_sec=0, tv_usec=50000} <unfinished ...>
[pid 23193] <... select resumed> )      = 0 (Timeout)
[pid 23193] select(7, [4 5 6], NULL, NULL, {tv_sec=0, tv_usec=20000}) = 0 (Timeout)
[pid 23193] select(7, [4 5 6], NULL, NULL, {tv_sec=0, tv_usec=20000} <unfinished ...>
[pid 23185] <... select resumed> )      = 0 (Timeout)
[pid 23185] select(10, [5 6 8 9], NULL, NULL, {tv_sec=0, tv_usec=20000} <unfinished ...>
[pid 23193] <... select resumed> )      = 0 (Timeout)
[pid 23193] select(7, [4 5 6], NULL, NULL, {tv_sec=0, tv_usec=20000} <unfinished ...>
[pid 23185] <... select resumed> )      = 0 (Timeout)
[pid 23185] select(0, NULL, NULL, NULL, {tv_sec=0, tv_usec=50000} <unfinished ...>
[pid 23193] <... select resumed> )      = 0 (Timeout)
[pid 23193] select(7, [4 5 6], NULL, NULL, {tv_sec=0, tv_usec=20000}) = 0 (Timeout)
[pid 23193] select(7, [4 5 6], NULL, NULL, {tv_sec=0, tv_usec=20000}) = 0 (Timeout)
[pid 23193] select(7, [4 5 6], NULL, NULL, {tv_sec=0, tv_usec=20000} <unfinished ...>

Like if the two processes were in a deadlock state. Moreover, the commands
pid -p 7002

and
pid -p 7010

do give an empty output. The dirs /proc/7002 and /proc/7010 do not exist.
The only abaqus-related processes executing are
david  6995  0.0  0.1 295428 51388 pts/0    S    17:00   0:00 /opt/abaqus/6.14-1/code/bin/python /opt/abaqus/6.14-1
david  6998  0.0  0.2 368744 97948 pts/0    S    17:00   0:00 /opt/abaqus/6.14-1/code/bin/python std_inst.com
david  7001  0.1  0.0 122076 20096 pts/0    Sl   17:00   0:03 /opt/abaqus/6.14-1/code/bin/eliT_DriverLM -job std_in
david  7008  0.4  0.5 735812 185364 pts/0   Sl   17:00   0:07 /opt/abaqus/6.14-1/code/bin/standard -standard -acade

On ubuntu 16.04 the exact same version works like a charm. Here the same strace on ubuntu 16.04 (with the same kernel version as my 18.04, i.e. 4.15.0-29):
3890  close(8)                          = 0
3892  <... select resumed> )            = 0 (Timeout)
3892  futex(0x7f29e43e1db0, FUTEX_WAIT_PRIVATE, 2, NULL <unfinished ...>
3890  futex(0x7f29e43e1db0, FUTEX_WAKE_PRIVATE, 1) = 0
3892  <... futex resumed> )             = -1 EAGAIN (Resource temporarily unavailable)
3892  futex(0x7f29e43e1db0, FUTEX_WAIT_PRIVATE, 2, NULL <unfinished ...>
3890  futex(0x7f29e43e1db0, FUTEX_WAKE_PRIVATE, 1) = 0
3892  <... futex resumed> )             = -1 EAGAIN (Resource temporarily unavailable)
3892  futex(0x7f29e43e1db0, FUTEX_WAKE_PRIVATE, 1 <unfinished ...>
3890  futex(0x7f29e43e1db0, FUTEX_WAIT_PRIVATE, 2, NULL <unfinished ...>
3892  <... futex resumed> )             = 0
3890  <... futex resumed> )             = -1 EAGAIN (Resource temporarily unavailable)
3890  futex(0x7f29e43e1db0, FUTEX_WAKE_PRIVATE, 1) = 0
3892  select(7, [4 5 6], NULL, NULL, {0, 20000} <unfinished ...>
3890  munmap(0x7f29c7adb000, 327680)    = 0
3890  munmap(0x7f29c7b3b000, 1114112)   = 0
3890  munmap(0x7f29c7eab000, 1114112)   = 0
3890  munmap(0x7f29c778b000, 1114112)   = 0
3890  munmap(0x7f29c75ab000, 1114112)   = 0
3890  munmap(0x7f29c71db000, 1114112)   = 0
3890  munmap(0x7f29c6bcb000, 1114112)   = 0
3890  munmap(0x7f29c6cdb000, 1114112)   = 0
3890  munmap(0x7f29c689b000, 1114112)   = 0
3890  munmap(0x7f29c6abb000, 1114112)   = 0
3890  munmap(0x7f29c7cbb000, 1114112)   = 0
3890  exit_group(0)                     = ?
3891  +++ exited with 0 +++
3893  +++ exited with 0 +++
3892  +++ exited with 0 +++
3890  +++ exited with 0 +++
3880  <... wait4 resumed> [{WIFEXITED(s) && WEXITSTATUS(s) == 0}], 0, NULL) = 3890
3880  --- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=3890, si_uid=1000, si_status=0, si_utime=107, si_stime=7} ---

Has someone a good idea how to solve this? Or in which direction should I investigate further.

A: I found a solution that circumvents the deadlock by using a singularity container as proposed by Will Furnass here: http://learningpatterns.me/posts-output/2018-01-30-abaqus-singularity/
Although a bit complicated in the first place, it works like a charm when setup properly. I modified my aliases for abaqus on my host system (Manjaro/Arch linux) such that they point to the install in the singularity container and execute the command in the containers environment. However, since I need Intel Fortran Compiler, I generated a basic centos 7 container and modified it afterwards to install compilers and abaqus (v2019 in this case) rather than using the .def script as proposed by Will Furnass.
It takes some time to setup but now I have a container image I can work with on any system that runs singularity, which is quite nice :)
EDIT: I also tested copying a working install to a more recent linux system (and avoiding a fresh install of abaqus), I can confirm that this didn't work in my case (CentOS 7 install copied to Manajaro system).

A: I would like to present my work around for this issue. I've made a python wrapper for the abq2018 solver which checks the .sta file for completeness. Once the .sta file is complete, any process named standard will be killed. I've found that the solver exits gracefully when standard is killed and the analysis is complete.
This work around is not a perfect solution. Current issues with this work around:

*

*can't replace the abq2018 solver call directly

*will not work from GUI, must be run from the shell

*only parses job= argument

*you can only run one analysis at at time since all standard processes are killed

*abq will hang forever if .sta file is not created or modified

How to use this workaround:

*

*Create Python file named abq. Code for abq is detailed below. If you are using a solver other than abq2018, replace the line cmd = 'abq20xx.. with the solver that you are using.

*Make abq executable and available in your path. I placed abq in the Abaqus commands folder, then ran chmod +x abq

*Run an Abaqus standard job by executing abq job=Job-1. This will execute Job-1.inp, then this will kill the standard solver once Job-1.sta is completed.

Code for abq is below
#!/usr/bin/python
import subprocess
import sys
import time
arguments = sys.argv
jobname = arguments[1].split('job=')[-1]
cmd = 'abq2018 cpus=4 ask_delete=OFF background job=' + jobname
p = subprocess.call(cmd, shell=True)

complete = False
termination_criteria = [' THE ANALYSIS HAS COMPLETED SUCCESSFULLY\n',
                        ' THE ANALYSIS HAS NOT BEEN COMPLETED\n']

while complete is False:
    # wait every 5 seconds
    time.sleep(5)
    try:
        with open(jobname + '.sta', 'r') as f:
            last = f.readlines()[-1]
            if last in termination_criteria:
                # this will kill any process named standard
                subprocess.call('pgrep standard | xargs kill', shell=True)
                complete = True
    except IOError:
        # model.sta has been deleted or doesn't exist
        # try again in 5 seconds
        time.sleep(5)

A: Dassaults System published a bug-fix this month:
You need to update to Abaqus 2018 to Abaqus 2018-HF16 from https://software.3ds.com/ more details can be found at https://github.com/willfurnass/abaqus-2017-centos-7-singularity/issues/5#issue-713025844
I tried it with updating Abaqus 2020 to Abaqus 2020-HF5 and it worked for Ubuntu 20.04 as well as Fedora 32.

A: I met this problem with Linux mint 19 too.
Abaqus 6.14-5 installed in Linux Mint 19.
It cannot be terminated automatically but seen form .sta file, the analysis is completed.
I think this problem is related to the kernel.
By the way, do you find any solutions now?


text:
Q: Help with logical equivalences and proving tautology I've been wracking my brain trying to figure this out, but I don't know what to do after a certain point.  I'm trying to prove whether or not this is a tautology:
$$
[(p\wedge r)\wedge (p\rightarrow q)]\rightarrow q
$$
So this is what I did (~ is a negation, couldn't figure out how to do a different symbol):
$$
\sim [(p\wedge r)\wedge (p\rightarrow q)]\vee  q
$$
$$
[\sim(p\wedge r)\vee \sim(p\rightarrow q)]\vee  q
$$
$$
[(\sim p\vee \sim r) \vee \sim(p\rightarrow q)]\vee  q
$$
$$
[(\sim p\vee \sim r) \vee \sim(\sim p\vee q)]\vee  q
$$
$$
[(\sim p\vee \sim r) \vee \sim(\sim p\vee q)]\vee  q
$$
$$
[(\sim p\vee \sim r) \vee p\vee \sim q)]\vee  q
$$
I just don't know what to do now, or if I'm even going in the right direction.

A: $\begin{array}{ll}
\text{You were doing okay, up to here:}&[(\neg p\vee \neg r)\vee\neg (\neg p\vee q)]\vee q
\\[1ex] \text{Associate and Commute:}&[(\neg p\vee q)\vee \neg (\neg p\vee q)]\vee \neg r
\\[1ex] \text{Complement:} & \top\vee \neg r
\\[1ex] \text{Annihilate:}&\top
\end{array}$
And you are done.

Via Natural Deduction:
$$\boxed{\begin{array}{l|l:l}
1 & (p\wedge r)\wedge (p\to q) & \textsf{Assume}
\\2 & (p\wedge r) &1, \wedge\mathsf E
\\ 3 & p\to q & 1, \wedge\mathsf E
\\ 4 & p & 2, \wedge\mathsf E
\\ 5 & q & 3,4, \to\mathsf E(MP)
\\ \hline \Box & (p\wedge r) \wedge (p\to q) ~\to~ q & 1, 5, \to\mathsf I(MP)
\end{array}}$$

A: This should do it (a bit sloppy):
\begin{align*}
 & \left(\left(p\wedge r\right)\wedge\left(p\rightarrow q\right)\right)\rightarrow q\\
= & \neg\left(\left(p\wedge r\right)\wedge\left(\neg p\vee q\right)\right)\vee q\\
= & \left(\neg\left(p\wedge r\right)\vee\neg\left(\neg p\vee q\right)\right)\vee q\\
= & \left(\neg p\vee\neg r\vee\left(p\wedge q\right)\right)\vee q\\
= & \left(\neg p\vee\neg r\vee p\right)\vee q\\
= & 1\vee q
\end{align*}
Alternatively, there's always the brute force approach:

A: We wish to show that
$$
[(p\wedge r)\wedge (p\rightarrow q)]\rightarrow q
\, \, \bf(1)$$
First we use "simplification" to infer that
$$\textbf{(1)} \implies p \land (p \rightarrow q)$$
Now this is known as "Modus Ponens."
Well, $$p \implies q \iff \neg p \lor q$$
Then we have $$p \land ( \neg p \lor q)$$
if $\neg q$, we have a contradiction.
As an aside, you could use simplification and then use brute force.


text:
Q: Trigger/run earlier interaction in Selenium WebDriver I want to achieve the following process. The scripts are written in Katalon, but it does not matter. Selenium approach is enough.
I test an appearance of two elements in a dialog window. If a text message appears, the second element will not come and the dialog window is closed. If the first element (message) is not displayed, a button that displays after a certain amount of time is clicked.
I would like to continue and avoid using wait until element is visible/invisible. I do not know how to do it, but any action is triggered first it will go through it.
The problem is that the test waits for the message for the certain time and if it not displayed in (let say 30 sec), it clicks on the button. I want to avoid to wait until it is visible, and instead of waiting just to click immediately on the button. So the aim is to track two parallel actions (not selenium actions) and which one is fired first. Is there any approach? Maybe using tasks?
Here is the code:
TestObject dialogWinEl = findTestObject("Object Repository/FinacDocAndPayments/dialogWindow/div_dialogWin")
WebUI.waitForElementVisible(dialogWinEl, GlobalVariable.TIMEOUT_ELEMENT, FailureHandling.OPTIONAL)

TestObject statusMsgFilesDownloadEl = findTestObject("Object Repository/InvoiceDetailPage/div_dialogWin/span_noDocFoundStatus")
boolean noDownloadFiles = WebUI.waitForElementVisible(statusMsgFilesDownloadEl, GlobalVariable.DOWNLOAD_BTN, FailureHandling.OPTIONAL)

        if(noDownloadFiles){
            KeywordUtil.markPassed("No files found to download. Closing dialog")
        }
        else{
            KeywordUtil.markPassed("Files found. Click on Download files")
            TestObject btnEl = findTestObject('Object Repository/InvoicesAndPayments_Global/btn_generic', [('btn_text'):btnName])
            WebUI.waitForElementClickable(btnEl, GlobalVariable.TIMEOUT_ELEMENT)
            WebUI.click(btnEl)
            KeywordUtil.markPassed("File downloaded. Closing dialog window")
        }

TestObject xBtn = findTestObject('Object Repository/InvoicesAndPayments_Global/confDialog/div_closeBtn')
WebUI.waitForElementClickable(xBtn, GlobalVariable.TIMEOUT_ELEMENT)
WebUI.click(xBtn)
KeywordUtil.markPassed("Dialog window has been closed")

Basically the variable noDownloadFiles is equal to the status of the particular element (visible or not) and it waits for the time that is in the var GlobalVariable.DOWNLOAD_BTN = 20sec. The problem here is if this variable is false it means that it waited for the specific amount of time and then it continues in the else branch. The point is if the button appears earlier it does not have to wait to see if statusMsgFilesDownloadEl is visible or not.
I simply want to use this:
WebUI.waitForElementVisible(statusMsgFilesDownloadEl, GlobalVariable.DOWNLOAD_BTN, FailureHandling.OPTIONAL)

and
WebUI.waitForElementClickable(btnEl, GlobalVariable.TIMEOUT_ELEMENT)

and once the first or second is evaluated it continues. There is no reason to wait for one and then for the other.


text:
Q: Google Sheets API v4 Basics I am trying to get data from google sheets. For example, let's say I have a sheet "test" and I want to get cell a2 from "test", and so I save the contents of cell a2 as a string.
I believe Google Sheets Api v4 (https://developers.google.com/api-client-library/dotnet/apis/sheets/v4) is what I need to use, but I am not sure how to use it.
I have also found similar question posts on stack overflow, but they all seem outdated.
Finally, I have tried this tutorial (https://developers.google.com/sheets/api/quickstart/dotnet#step_2_prepare_the_project) with my c# visual studio, but I get error messages (which I can include if it is helpful).
So, my question is, how do extract data from a google sheet, using the API or some other tool. Thanks for the help, and please notify me if my question needs editing to better fit this community.
edit: So, following the tutorial, I have this code:
using System;
using System.Windows.Forms;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Sheets.v4;
using Google.Apis.Sheets.v4.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;

using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace GoogleSheetsTest1

{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
        class Program
        {
            static string[] Scopes = { SheetsService.Scope.SpreadsheetsReadonly };
            static string ApplicationName = "Google Sheets API .NET Quickstart";

            static void Main(string[] args)
            {
                UserCredential credential;

                using (var stream =
                    new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
                {
                    string credPath = System.Environment.GetFolderPath(
                        System.Environment.SpecialFolder.Personal);
                    credPath = Path.Combine(credPath, ".credentials/sheets.googleapis.com-dotnet-quickstart.json");

                    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        Scopes,
                        "user",
                        CancellationToken.None,
                        new FileDataStore(credPath, true)).Result;
                    Console.WriteLine("Credential file saved to: " + credPath);
                }

                // Create Google Sheets API service.
                var service = new SheetsService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = ApplicationName,
                });

                // Define request parameters.
                String spreadsheetId = "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms";
                String range = "Class Data!A2:E";
                SpreadsheetsResource.ValuesResource.GetRequest request =
                        service.Spreadsheets.Values.Get(spreadsheetId, range);

                // Prints the names and majors of students in a sample spreadsheet:
                // https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
                ValueRange response = request.Execute();
                IList<IList<Object>> values = response.Values;
                if (values != null && values.Count > 0)
                {
                    Console.WriteLine("Name, Major");
                    foreach (var row in values)
                    {
                        // Print columns A and E, which correspond to indices 0 and 4.
                        Console.WriteLine("{0}, {1}", row[0], row[4]);
                    }
                }
                else
                {
                    Console.WriteLine("No data found.");
                }
                Console.Read();

            }

        }
    }
    }

The error message I am getting is:
Error  CS0017  Program has more than one entry point defined. Compile with /main to specify the type that contains the entry point.
I realize this is probably a really stupid question and I hate to be asking for help here, but I am not sure how to use the google api code, so any help/explanation (so I can understand what the fix is) would be really appreciated. Thanks


text:
Q: SegFaults in C/MySQL through Structured Con Well, i've been working on this little project for a week or so now as a learning experience as I take C courses.  I've worked it almost error free until now, I was instructed to make *con a struct because I was getting a huge stack dump at the end (which was caused by a pointer problem)
My program works fine, everything.  However upon closing the mysql connection I am getting a segfault.
Code:
#include <my_global.h>
#include <mysql.h>
#include <string.h>
#include <stdlib.h>
struct sql {

    MYSQL *con;

};

int try(char getInput[100]) {

   struct sql grab;
   MYSQL_RES *res;
   MYSQL_ROW row;
   char *server = "localhost";
   char *user = "root";
   char *password = "iluvgeordi";
   char *database = "test";

    if( strcmp( getInput, "version" ) == 0 )
        printf( "\n->Mysql Version: %s\n", mysql_get_client_info() );
    else if( strcmp( getInput, "get" ) == 0 ) {

        grab.con = mysql_init(NULL);

        if( !mysql_real_connect(grab.con, server, user, password, database, 0, NULL, 0) ) {

            fprintf(stderr, "%s\n", mysql_error(grab.con));
            exit(1);

        }

        if( mysql_query(grab.con, "show tables") ) {

            fprintf(stderr, "%s\n", mysql_error(grab.con));
            exit(1);

        }

        res = mysql_use_result(grab.con);
        if( res != NULL ) {

            while( ( row = mysql_fetch_row(res) ) != NULL )
                printf( "%s \n", row[0] );

        }
        mysql_free_result(res);

    }

    mysql_close(grab.con);

}

Even though I know its the mysql_close, here the GDB Stack Dump/Back Trace

Program received signal SIGSEGV, Segmentation fault. 0xf7cca37e in
mysql_close () from /usr/lib/i386-linux-gnu/libmysqlclient.so.18 (gdb)
where
0  0xf7cca37e in mysql_close () from /usr/lib/i386-linux-gnu/libmysqlclient.so.18
1  0x08048afa in try (getInput=0xffffd37c "version") at m-try.c:61
2  0x0804894b in main (argc=1, argv=0xffffd494) at main.c:37 (gdb) bt
0  0xf7cca37e in mysql_close () from /usr/lib/i386-linux-gnu/libmysqlclient.so.18
1  0x08048afa in try (getInput=0xffffd37c "version") at m-try.c:61
2  0x0804894b in main (argc=1, argv=0xffffd494) at main.c:37 (gdb) quit

I know there is 1000's of mysql C questions, however none of them are relavent to what I need otherwise I surely would have found it by now.

A: It seems that error is caused by a call of try( "version" );:
1 0x08048afa in try (getInput=0xffffd37c "version") at m-try.c:61

and indeed, you only all mysql_init() and assign a value to grab.con if you call try( "get" ) but you always call mysql_close( grab.con );
You should just put that call into the "get" branch;
....
else if( strcmp( getInput, "get" ) == 0 ) {
    ...
    mysql_close( grab.con );
}


text:
Q: IIF ISNOTHING Expression I'm launching a sub-report to a separate window in reporting services by a JavaScript function as seen below,
=iif(Fields!PERIOD.Value <= Cint(right(Parameters!YEARPERIOD.Value, 2)),
"javascript:void(window.open('"
     & Globals!ReportServerURL
     & "?"
     & Left(Globals!ReportFolder, InStr(Globals!ReportFolder, "/Standard Reports"))
     & "Sub Reports/Trend Breakdown"
     & "&ServerName="
     & REPLACE(Parameters!ServerName.value,"\","\\")
     & "&CATALOG="
     & Parameters!CATALOG.Value
     & "&NOMINAL="
     & Fields!NOMINAL.Value
     & "&COMPANYCODE="
     & JOIN(Parameters!COMPANYCODE.Value, ",")
     & "&YEARCODE="
     & LEFT(Parameters!YEARPERIOD.Value, 7)
     & "&LOCATION="
     & Fields!LOCATION.Value
     & "&KEYLISTGROUPING="
     & Fields!KEYLISTGROUPING.Value
     & "&ANALYSISCODE="
     & Fields!ANALYSISCODE.Value
     & "&BUDGET="
     & Fields!BUDGET.Value
     & "&PERIOD="
     & Fields!PERIOD.Value
     & "&ParentReport=3
     &ADD_PERIODS="
     & JOIN(Parameters!ADD_PERIODS.Value, ",")
     & "','_blank','width=950,height=460,top=300'))", "")

Now i'm trying to change the & Globals!ReportServerURL to the following
& IIF(IsNothing(Parameters!GetExternal.Value), "Globals!ReportServerUrl", Parameters!GetExternal.Value)
Essentially replace the ReportServerURL in the sub-report link if there is a value in the GetExternal parameter.
But it isn't updating the report server url in the sub-report correctly, but instead appending the value from the parameter to the following part of the sub-report link, see the red box,

Question i have is how can i make it append the parameter value to the following part of the link? See the red highlighted section,


text:
Q: If, Elif, Greater than, Less than Logic I have multiple conditions for this game if a user reaches a certain amount of money, then the more money they steal if the other user is at their level.
I'm having an issue trying to figure out the logic. I've added comments asking questions but I just don't know if there's an easier way to approach this type of thing.
Do I start from a lower value when I start my if statements or should I start with my large values?
# do I need to put a check and money(message.author) < 500000 here?
if money(message.author) >= 20000 and money(user) < 20000:
    do_thing1()
# do I need to put a check and money(user) < 500000 here?
elif money(message.author) < 20000 and money(user) >= 20000:
    do_thing1()
# do I need to put a check money(message.author) and money(user) < 500000 here?
elif money(message.author) >= 20000 and money(user) >= 20000:
    do_thing2()
# do I need to put a check and money(user) >= 20000 here?
elif money(message.author) >= 500000 and money(user) < 500000:
    do_thing2()
# do I need to put a check and money(message.author) >= 20000 here?
elif money(message.author) < 500000 and money(user) >= 500000:
    do_thing2()
elif money(message.author) >= 500000 and money (user) >= 500000:
    do_thing3()

A: Note that you don't show what happens if both have less than 20000, or if both have more than 20000 but less than 500000. I will show where those are handled below.
if money(message.author) < 20000 and money(user) < 20000:
    do_thing0()  # both have < 20000. You didn't show this case.
elif money(message.author) < 20000 or money(user) < 20000:
    do_thing1()  # only one of them has < 20000
elif money(message.author) < 500000 and money(user) < 500000:
    do_thingX()  # both have >= 20000 but < 500000. You didn't show this case.
elif money(message.author) < 500000 or money(user) < 500000:
    do_thing2()  # both have >= 20000, only one of them has < 5000000
else:
    do_thing3()  # both have >= 500000

If you don't care about the cases where both have < 20000 or both have >= 20000 and < 500000, then you can shorten this with exclusive ors:
elif money(message.author) < 20000 ^ money(user) < 20000:
    do_thing1()  # only one of them has < 20000
elif money(message.author) < 500000 ^ money(user) < 500000:
    do_thing2()  # both have >= 20000, only one of them has < 5000000
elif money(message.author) >= 500000 and money(user) >= 50000
    do_thing3()  # both have >= 500000

Note in the last case we need to be explicit, otherwise we'll catch anything that wasn't caught by our first two cases, and here I'm assuming you don't want to catch the case where both have less than 20000, for example.
Your code executes sequentially, so if you make it past one of the checks, that tells you something about the range you are in and you can adjust your logic accordingly.
For example, once you've made it to the elif money(message.author) < 500000 and ... check, you know that both money(message.author) >= 20000 and money(user) >= 20000 because you wouldn't have made it this far if that wasn't true.

A:
# Do I need to put a check and money(message.author) < 500000 here?

Yes, you do, otherwise some of your cases will include others, e.g., if money(message.author) == 500001 and money(user) == 1, you probably want dothing2 to happen, but instead it will trigger dothing1.
You could use comparison chaining for those, e.g. instead of
if money(message.author) >= 20000 and money(message.author) < 500000 and money(user) < 20000:
    dothing1

you could use the much shorter
if 20000 <= money(message.author) < 500000 and money(user) < 20000:
    dothing1

Also, defining two temporary variables ma = money(message.author) and mu = money(user) might greatly help readability. Given the large number of if and elif statements, you might even define ma1 = ma < 20000, ma2 = 20000 <= ma < 500000, etc., but this might be overkill. You could also define variables low = 20000 and high = 500000, preventing typos (is that four zeros or five?) and making it easier to change that in future.
if low <= ma < high and mu < low:
    do_thing1()
elif ma < low and low <= mu < high:
    do_thing1()
elif low <= ma and low <= mu:
    do_thing2()
elif high <= ma and mu < high:
    do_thing2()
elif ma < high and high <= mu:
    do_thing2()
elif high <= ma and high <= mu:
    do_thing3()


text:
Q: Regexp constraint rejecting apparently valid data in Postgresql Using Postgres 10.3 with pgAdmin 4 v3.0
I have a constraint for GB national grid references on a column gridref of a table my_table:
ALTER TABLE my_table
ADD CONSTRAINT my_table_gridref_check
CHECK (gridref::text
~~ '[A-Z][A-Z][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'::text);

I have a grid reference which appears to match that format (AB12345678 - ie 2 alpha, 8 numeric - not a real grid reference, but a valid pattern), but on trying to insert a record with that value, the insert fails on that constraint, with this error
ERROR: new row for relation "my_table" violates check constraint "my_table_gridref_check"

However, if I do
SELECT select regexp_matches('AB12345678',
'[A-Z][A-Z][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]')

then I get as a result the single-item set containing that grid ref.
All of which seems to indicate that the grid ref should be accepted (which is what I expected), so I don't understand why the constraint is triggering.
Any ideas what I'm doing wrong? Are there restrictions or gotchas on the use of regular expressions as constraints in Postgres?

A: I had to look this up in the documentation:

The operator ~~ is equivalent to LIKE, and ~~* corresponds to ILIKE.

Postgres does not support character ranges in LIKE.
You want ~ (or regexp_match()):
CHECK (gridref::text ~ '[A-Z][A-Z][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'::text);

I'm guessing you really want:
CHECK (gridref::text ~ '^[A-Z][A-Z][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]$'::text);

Note the anchors so this matches the entire string.
Or more simply:
CHECK (gridref::text ~ '^[A-Z]{2}[0-9]{8}$'::text);


text:
Q: Installing OpenCV in Ubuntu without internet connection I had a question about installing OpenCV on a linux machine.
I downloaded OpenCV 2.4.11 (from here) on a Ubuntu linux machine that doesn't have internet. It's on its own stand alone network and won't be connected to the internet at all. I was wondering, how do I install OpenCV (for python) given the current conditions? Any documentation online points to using sudo apt-get or other methods that use the internet to install.
Right now I have installed Anaconda on the machine that gave me most of the dependencies that are required, but if I need to install any other dependencies, I can easily download the source code (and run like setup.py to install it), burn it on a disk and install it.

A: If you have already downloaded the OpenCV source code, building OpenCV is fairly straightforward.  You will only need the internet if you have any unmet dependencies (which it sounds like you're able to take care of).
cd opencv-source-code
mkdir build
cd build
cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local ..
make
sudo make install

This may take a while so have patience.  The full instructions along with all the required dependencies can be found here: Linux installation.

A: I agree with casper (but cannot comment). It is possible that even when building the code yourself you'll need internet connection to download ippicv (which happens automatically when running cmake). The instructions how to circumvent it are here.


text:
Q: How to create pdf using php i want to create PDF file for my PHP  web page it must be some button like create PDF
then user click button PDF file must automatically generate
my  web page  dynamic page it contain MySQL tables how i do it and there are any open source software for it ...

A: You can make PDFs with fpdf: http://fpdf.org/
<?php
require('fpdf.php');

$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

A: Generate the PHP as you usually would but add the header
header("Content-Type: application/pdf");
header('Content-Disposition:inline; filename="testing.pdf"'); //view in browser

Or
 header("Content-Type: application/pdf");
 header('Content-Disposition:attachment; filename="testing.pdf"'); //force download


text:
Q: Extract data from MDX query string I have hundreds of MDX queries captured from SQL Analysis Services (Extended Events).
They look like this :
SELECT {[Measures].[ Count - Sales],[Measures].[ Count - Customers],[Measures].[Revenue]} DIMENSION PROPERTIES PARENT_UNIQUE_NAME,HIERARCHY_UNIQUE_NAME ON COLUMNS , NON EMPTY Hierarchize(DrilldownMember({{DrilldownMember({{DrilldownLevel({[DimDate].[Calendar Date].[All]},,,INCLUDE_CALC_MEMBERS)}}, {[DimDate].[Calendar Date].[Calendar Year].&[2014],[DimDate].[Calendar Date].[Calendar Year].&[2015],[DimDate].[Calendar Date].[Calendar Year].&[2016],[DimDate].[Calendar Date].[Calendar Year].&[2017],[DimDate].[Calendar Date].[Calendar Year].&[2018],[DimDate].[Calendar Date].[Calendar Year].&[2013]},,,INCLUDE_CALC_MEMBERS)}},

I need to write a bit of c# to extract data as :
[Measures].[ Count - Sales]
[Measures].[ Count - Customers]
[Measures].[Revenue]
[DimDate].[Calendar Date].[All]
[DimDate].[Calendar Date].[Calendar Year]

etc..
I don't mind if I get repeating members.
I can rely ranges being :
[Measures] to second ]
[Dim to second or third ]
I'm leaning towards using Regex to extract data :
Any ideas on the regex to capture above elements?

A: This should work:
\[[^\]]+\]\.\[[^\]]+\](\.\[[^\]]+\])?

Explanation:
\[[^\]]+\] - open bracket, anything until close bracket, close bracket (let's call it BRACKETED).
It's followed by dot, and another BRACKETED. Last section of dot and BRACKETED is optional.


text:
Q: Split a Subversion Repository Project to Two Git Repositories I have a Subversion server with a few different projects in the standard layout like so:
ProjectA/
    trunk/
    branches/
    tags/
ProjectB/
    trunk/
        FolderOfBinaries/
        SourceFolderA/
        SourceFolderB/
        SourceFolderC/
    branches/
    tags/
        v1.0/
        v1.1/
        v2.0/
ProjectC/
    trunk/
    branches/
    tags/

ProjectB is going to be be migrated to Git, but not with a standard clone. I want to split the project into two Git repositories - one for the folder full of large binaries that change relatively often and another repository for everything else. I did a clone of the repository in full and it's a few GBs, but the binaries folder is probably 90% of that, and running git gc takes a long time. I'd rather have a small fast repository and then add the binaries folder as a submodule if the developer requires it.
I've found two potential options so far. First, I could use git branch-filter to try and remove the folder of binaries from the history as shown in the Git Book. Second, I could use svndumpfilter to split the current Subversion repository into two and then git svn clone each separately.
My question is though, what will happen to all the history, and particularly the branches and tags? I'd still like to know what the folder of binaries looked like at every tag in the project, even though the binaries may not have changed between two tags. is that possible?
Edit: The folder of binaries is not full of build artefacts (*.class, *.o, *.dll etc) so I can't just strip it out and make them external. It's full of binaries that are output from a third-party program that need to be versioned (think OpenOffice documents, Photoshop files etc.).

A: I would recommend svndumpfilter to first split ProjectB into two repositories. Afterwards you can use git svn clone to convert the new SVN repositories into GIT repositories.
When the --include patterns of svndumpfilter consider the trunk, branches, and tags folders, the full history of the split repositories will be preserved. So you can take a look at all the history of FolderOfBinaries in the new binaries repository.
When you create the GIT repositories using git svn clone, the content of the branches folder will be converted to GIT branches and the content of the tags folder will be converted into GIT tags.

A: Take a look at svndumpfilter. It's pretty simple to use. You do a Subversion repository dump, and then use the filter to either say what you want or what you don't want.
Do a dump of your current repository, then run svndumpfilter twice -- once for each Git repository. You can chain them. Just run it twice for each Git repository.
$ svndumpfilter include ProjectB < svn_repo_dump | svndumpfilter exclude ProjectB/trunk/folderofbinaries > svn_repos_no_binaries

I do want to mention one thing: Don't store built binary objects in your repository. In Subversion, they're impossible to remove without a dump and filter, and even in version control systems with the ability to obliterate revisions, doing so takes a lot of time and effort. It's a big maintenance headache.
And for what? Storing binaries in a version control system doesn't really help. You can't diff binaries, the history doesn't help, and they are hard for non-developers to access.
Instead, use a release repository, and store your binaries there. You can use a Maven repository like Artifactory or Nexus even if you don't use Maven or even use Java.

A: Well, I've managed to do this, but it wasn't all that straightforward. There may be a better way but not one that I could work out. I did the following:

*

*Create a dump of the current repository: svnadmin dump /opt/repo > full_dump

*Filter the dump to remove the binaries folder: svndumpfilter exclude *folderofbinaries* --pattern --renumber-revs --drop-empty-revs < full_dump > filtered_dump. I needed to make folderofbinaries a pattern because way back in the past someone had actually checked a binary directly into a tag (!) so the next step was failing due to a missing folder.

*Create a local SVN repository with the filtered dump:
mkdir repo-filtered;
svnadmin create repo-filtered;
svnadmin load repo-filtered < filtered_dump

*Clone both the full and filtered repo into different folders (I used svn2git). The filtered repo will not contain any of the binaries. If, in the full repo, only the binaries folder changed between tags A and B, in the new filtered Git repo the two tags will point to the same commit, which is exactly what I wanted.

*In the full Git repo, use Git to strip out everything except the binaries folder.
The reason that I had to use Git to isolate the binaries folder was because I couldn't work out how to maintain the tags just using svndumpfilter (especially given I had a binary committed directly into a tag). After the conversion I get the same behaviour as in the filtered repo - if no binaries changed between two tags then they both point to the same commit.
The commands for the final step were:
git checkout master
git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter folderofbinaries -- --all
git reset --hard
git for-each-ref --format="%(refname)" refs/original/ | xargs -n 1 git update-ref -d
git reflog expire --expire=now --all
git gc --prune=now

which I got from this question.
Now I have an 80MB sources repository and a 1.5GB binaries repository from my original 4.4GB SVN dump file! I can recreate the exact state of the original SVN repo by adding the binaries folder as a Git submodule of the sources repo and checking out the same tag on each (which is why I needed to preserve all the tag info) whilst not having one mammoth Git repo that's slow to work with.


text:
Q: Add controls to recent form after submit Angular 6 I have input with phone number, if the phone number is valid then the form will open more 5 inputs to full.
this.contactUsForm = this.formBuilder.group({
     contact_number: ['', Validators.compose([Validators.required, Validators.pattern(this.globalService.pattern)]), {disabled: true}],
});

How can I add more contorls without affect on my contact_number value. I just want to add more controls like this:
this.contactUsForm = this.formBuilder.group({
       contact_number: ['', Validators.compose([Validators.required, Validators.pattern(this.globalService.pattern)]), {disabled: true}],
       verification_code: ['', Validators.required]
       firstname: ['', Validators.required]
       lastname: ['', Validators.required]
});

I tried to this after contact_number success:
this.contactUsForm.addControl('verification_code',  new FormControl('', Validators.required));

But I had an error ERROR TypeError: v is not a function
https://stackblitz.com/edit/angular-bf4q3q

A: Thank you all for comments. The error appeared because I was doing this
this.contactUsForm = this.formBuilder.group({
            contact_number: ['', Validators.compose([Validators.required, Validators.pattern(this.globalService.pattern)]), {disabled: true}],
        });

It worked after removing {disabled: true}


text:
Q: c# StringExtension with Method Space I try to create a string extension with the method Space(int) in it. If I have an instance of a string, then its no problem. But without I have no Idea.
The call should be: string.Space(2) or String.Space(2)
Not "".Space(2)!!!
In this example, the method should return 2 space characters ("  ").
Anybody to help?

A: Thank you Sweeper:
namespace Exp.Util.Extension
{
    public static class IntegerExtension
    {
        public static string ToSpaces(this int aData)
        {
            return new string(' ', aData);
        }
    }
}

A: An extension method is supposed to act on an object instance, that's how and why it has the syntax it got.
But in your case, your method does not act on a string instance, so what's the point of trying to define it as a string extension method? Just keep it an old boring static method. There's nothing wrong with ye'ole static methods...

A: For this concrete example I think you can simply work with the string constructor:
var spaces = new string(' ', 2);


text:
Q: Odd results with parsing a Datetime c# I have the following code:
IFormatProvider culture = new System.Globalization.CultureInfo("es-ES", true);
date = DateTime.ParseExact(_date, "yyyy-MM-dd hh:mm", culture);

for _date = "2012-11-17 15:00"
it throws an exception
but for _date = "2012-11-17 10:00" works
Anyone can tell me what I'm doing wrong?

A: use HH instead of hh
date = DateTime.ParseExact(_date, "yyyy-MM-dd HH:mm", culture);

HH is for 24-hr
hh is for 12-hr


text:
Q: Finding derivative of a split function using the definition of derivative I have this function:
$
f(x) =
\begin{cases}
\frac{sin^2(3x)}{x},  & \text{if $x\ne0$} \\
0, & \text{if $x=0$}
\end{cases}
$
How would I find the derivative of it using the definition of the derivative?
I found using wolfram alpha that the derivative is:
$\frac{6sin(3x)cos(3x)}{x}-\frac{sin^2(3x)}{x^2}$
So I started with:
$\lim_{h\to 0}\frac{sin^2(3x+3h)-sin^2(3x)}{xh}$
I've no idea whatsoever to continue from here, can anyone help me or explain me what I should do?
Thanks.

A: You can find the limit of the derivative (without $h$!), but that uses a relatively sophisticated theorem, or go back to the definition: if it exists,
$$ f'(0)=\lim_{h\to 0}\frac{\cfrac{\sin^2 3h}{h} -0}{h} =\lim_{h\to 0}\Bigl(\frac{\sin 3h}{h}\Bigr)^2=3^2. $$


text:
Q: Kile crashing on typing in a file After start of Kile, I type a letter in the editor (last edited file opened), and the application crashed immediately. If instead of typing a letter, I open a new file and start typing in it, Kile is OK, but when I come back to the older file, again, after typing a letter it crashes.
It happened to me before and I managed to solve it, but I do not remember exact steps what helped. I think once I invoked the PDFLaTeX or LaTeX compilation as the first step, and after they had finished, the editing worked. Another time, that solution did not help, but running sudo kile or kile from CLI removed the problem. I do not understand why, but it helped.
I run KDE upon Ubuntu 14.04.
Does anyone know more about it? Any similar experience?


text:
Q: How to retrieve element's coordinates relative to an svg viewbox? In my index.html I have an svg viewbox:
<svg viewBox = "0 0 2000 2000" version = "1.1">
</svg>

I wish to animate an svg ellipse I have created such that when the ellipse is clicked it moves vertically to a certain y point we'll call TOP, and if clicked again moves back to its original position called BOTTOM. Currently I am using the following code which works to an extent.
var testFlag = 0;
d3.select("#ellipseTest").on("click", function(){
if (testFlag == 0){
  d3.select(this)
      .attr("transform", "translate(0,0)")
      .transition()
        .duration(450)
        .ease("in-out")
        .attr("transform", "translate(0,-650)")
    testFlag = 1;
}else{
 d3.select(this)
      .attr("transform", "translate(0,-650)")
      .transition()
        .duration(450)
        .ease("in-out")
        .attr("transform", "translate(0,0)")
testFlag = 0;
}
});

The issue however, is that I have also made the ellipse drag-able up to the point TOP and down to the point BOTTOM. So if I drag the ellipse halfway in between TOP and BOTTOM, then click the ellipse, it animates vertically above TOP, instead of stopping when it reaches TOP (and like wise for BOTTOM when animating down). This seems to be a result of how the transform translate method works.
I believe I can resolve this if I create a function that dynamically returns the amount the ellipse should translate relative to where the mouse clicks (or better yet, to where the ellipse is currently position) . The problem is that I can't figure out how to get the current y position of the element relative to the viewbox, rather I can only get the position with respect to the entire page.
Here is the faulty code I am using to get the position of my click:
var svg2 = document.getElementsByTagName('svg')[0];
var pt = svg2.createSVGPoint();
document.documentElement.addEventListener('click',function(evt){
    pt.x = evt.clientX;
    pt.y = evt.clientY;
    console.log('Position is.... ' + pt.y);
},false);

Here is my working code to make the ellipse draggable:
//These points are all relative to the viewbox
var lx1 = -500;
var ly1 = 1450;
var lx2 = -500;
var ly2 = 800;
function restrict(mouse){ //Y position of the mouse
    var x;
    if ( (mouse < ly1) && (mouse > ly2) ) {
        x = mouse;
    }else if (mouse > ly1){
        x = ly1;
    }else if (mouse < ly2) {
        x = ly2;
    }
    return x;
}

var drag = d3.behavior.drag()
    .on("drag", function(d) {
      var mx = d3.mouse(this)[0];
      var my = d3.mouse(this)[1];

      d3.select("#ellipseTest")
        .attr({
          cx: lx2,
          cy: restrict(d3.mouse(this)[1])
        });
    })

A: Animate cy instead of the transformation...
var testFlag = 0;
d3.select("#ellipseTest").on("click", function(){
if (testFlag == 0){
  d3.select(this)
      .transition()
        .duration(450)
        .ease("in-out")
        .attr("cy", 0)
    testFlag = 1;
}else{
 d3.select(this)
      .transition()
        .duration(450)
        .ease("in-out")
        .attr("cy", 650)
testFlag = 0;
}
});


text:
Q: Jquery append dropdown won't show values [Laravel 5] Fellow coders,
I'm running against a small wall here. I am currently realising a project for my internship company, what I have to do is make an hour registration app in the CRM they have here.
My question is: How can I Use the value I received in PHP to dropdown in the Jquery dropdown field. (the reason why I want this is because the user has to fill in the title of the project and the task: project - taskname kinda deal. The 2 values are being shown in my PHP. But when I try to use it in my Jquery yo append the dropdown it doesn't show any values besides an empty dropdown box
   $("#addField").click(function (){
      var user_id = $('#user_id').val();
      project_id = $('#project_id').val();
      note = $('#note').val();
      date = $('#date').val();
      hours = $('#hours').val();
      var markup = "
{{  $user_id->first_name }}		"
      + user_id +
      "  <select class='project_id' value='{!! \App\Project::getCompanyName($hoursregistration->project_id) !!} - {!! \App\Subproject::getTaskTitle($hoursregistration->subproject_id)!!}'>	"
      + project_id +
      "<input type='text' value='{{ $hoursregistration->note }}' name='note' class='note'>		"
      + note +
      "<input type='date' class='date' value='{!! \App\Helpers::dateFormat($hoursregistration->date) !!}'>	"
      + date +
      "<input type='hours' class='hours' value='{{ $hoursregistration->hours }}'>		"
      + hours +
      "<button id='btn-save' name='btn-save' class='btn btn-default btn-xd btn-save save-hoursregistration' value='' rel='addRow-"+addRows+"'>Save</button>"
      $("table tbody").append(markup);

This is the Jquery function I wrote that appends a new row to the time table.

                @foreach ($hoursregistrations as $hoursregistration)

                   {{  $user_id->first_name }}
                   {!! App\Project::getCompanyName($hoursregistration->project_id) !!} - {!! \App\Subproject::getTaskTitle($hoursregistration->subproject_id)!!}
                   {!! $hoursregistration->note !!}
                   {!! \App\Helpers::dateFormat($hoursregistration->date) !!}
                   {!! $hoursregistration->hours !!}

                    <button id="btn-edit" name="btn-edit" class="btn btn-warning btn-xs btn-detail open-modal" value="{{$hoursregistration->id}}">Edit</button>
                    <button id="btn-delete" name="btn-delete" class="btn btn-danger btn-xs btn-delete delete-hoursregistration" value="{{ $hoursregistration->id }}">Delete</button>
                    <button id="btn-save" name="btn-save" class="btn btn-default btn-xd btn-save save-hoursregistration" value="">Save</button>

This is the piece of code I wrote to show the values in the view table of my application.
addRows++;

      $(".btn-save").click(function(){

        rowId = $(this).attr('rel');

        var url = '/hoursregistrations/create';
        var data = {
            user_id: {{  $user_id->id }},
            project_id: $("tr#addRow-"+rowId + " .project_id").val(),
            note: $("tr#addRow-"+rowId + "  .note").val(),
            hours: $("tr#addRow-"+rowId + " .hours").val(),
            date: $("tr#addRow-"+rowId +  " .date").val(),
        };

        $.ajax({
            headers:{ 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
            type: 'post',
            url: url,
            dataType: 'json',
            data: data,
            success: function(data) {
                console.log(data);
                $("table tbody").append(markup);
        //redirect
        if(type=="exit")
            window.location = "create.blade.php";
    }
});

And this is my Ajax function that redirects to the blade file. And executes the store function within my controller.
public function store(Request $request)
{
    //$hoursregistration= new Hoursregistration($request->except(''));

    $input = Input::all();
   //dd($input);
    $hoursregistration = new Hoursregistration();

    $hoursregistration->user_id = Sentinel::getUser()->id;
    $hoursregistration->project_id = $input['project_id'];
    $hoursregistration->subproject_id = $input['subproject_id'];
    $hoursregistration->date = $input['date'];
    $hoursregistration->note = $input['note'];
    $hoursregistration->hours = $input['hours'];
    $hoursregistration->save();
    return redirect('hoursregistrations')->with('success', Lang::get('message.success.create'));
}

This is my controller file.
In conclusion: How can I add {!! App\Project::getCompanyName($hoursregistration->project_id) !!} - {!! \App\Subproject::getTaskTitle($hoursregistration->subproject_id)!!}
inside my Javascript append function so I can use AJAX to post the selected dropdown value into the database.
Apologies in advance for my inability to explain things.
EDIT:
{!! App\Project::getCompanyName($hoursregistration->project_id) !!} - {!! \App\Subproject::getTaskTitle($hoursregistration->subproject_id)!!}

This line of code in my loop that displays the rows from the table does not work in the dropdown of my javascript.
  <select class='project_id' value='{!! \App\Project::getCompanyName($hoursregistration->project_id) !!} - {!! \App\Subproject::getTaskTitle($hoursregistration->subproject_id)!!}'>	"
  + project_id +

A: I forgot the option tag within the select tag. A.k.a I feel really REALLY stupid rn


text:
Q: I want a custom JQL function to create subqueries for nfeed fields in Jira (via adaptavist scriptrunner). Any Ideas? I want to create a custom JQL function that allows a subquery in nfeed fields. I am working with adaptavist scriptrunner.
In Jira it should work like this: issueFunction in nFeedSubquery (nFeed_fieldname, subquery)
for example:
project = xEpic and issuetype = Epic and issueFunction in nFeedSubquery("Related
                         Product/s", issuetype = product and status = registered)

This JQL query should then search for Epics related to registered products.
Is this possible to do?
Any kind of ideas or help would be appreciated.


text:
Q: When App in Background and receiving push notification tap App goes crash I am working on Push Notification with Azure Notification Hub.
I want to start my app from AppDelegate where the Notification is Tap.
Here is the Scenario, How I can open my App.
AppDelegate.cs file
public class AppDelegate : UIApplicationDelegate
    {
        // class-level declarations
        private SBNotificationHub Hub { get; set; }

        public bool appIsStarting = false;

        public SlideoutNavigationController Menu { get; private set; }

        public override UIWindow Window
        {
            get;
            set;
        }

        public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
        {
            if (launchOptions != null)
            {
                // check for a remote notification
                if (launchOptions.ContainsKey(UIApplication.LaunchOptionsRemoteNotificationKey))
                {

                    NSDictionary remoteNotification = launchOptions[UIApplication.LaunchOptionsRemoteNotificationKey] as NSDictionary;
                    if (remoteNotification != null)
                    {
                        Window = new UIWindow(UIScreen.MainScreen.Bounds);
                        Menu = new SlideoutNavigationController();

                        var storyboard = UIStoryboard.FromName("Main", null);
                        var webController = storyboard.InstantiateViewController("DashBoardViewController") as DashBoardViewController;

                        Menu.MainViewController = new MainNavigationController(webController, Menu);
                        Menu.MenuViewController = new MenuNavigationController(new DummyControllerLeft(), Menu) { NavigationBarHidden = false };

                        Window.RootViewController = Menu;
                        Window.MakeKeyAndVisible();
                    }
                }
                ReceivedRemoteNotification(application, launchOptions);

            }
            else
            {

                UIApplication.SharedApplication.SetStatusBarStyle(UIStatusBarStyle.LightContent, false);
                UIApplication.SharedApplication.ApplicationIconBadgeNumber = 0;
            }

            UNUserNotificationCenter.Current.Delegate = new UserNotificationCenterDelegate();

            return true;
        }
}

UserNotificationCenterDelegate.cs file
class UserNotificationCenterDelegate : UNUserNotificationCenterDelegate
    {

        public SlideoutNavigationController Menu { get; private set; }

        #region Constructors
        public UserNotificationCenterDelegate()
        {
        }
        #endregion

        #region Override Methods
        public override void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler)
        {
            // Do something with the notification
            Console.WriteLine("Active Notification: {0}", notification);

            // Tell system to display the notification anyway or use
            // `None` to say we have handled the display locally.
            completionHandler(UNNotificationPresentationOptions.Alert);
        }

        public override void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response, Action completionHandler)
        {
            base.DidReceiveNotificationResponse(center, response, completionHandler);
        }

        #endregion
    }

I have tried all possible scenario which i found on google and So and other site but nothing is working for me.
I spent 4 days on this but not get success.
Any Help Will be Appreciated.

A: Have you checked in DeviceLogs Window->Devices->View Device Logs? There must be crash logged.


text:
Q: is there a site as SourceForge for Android? I Want to gain a little experience in developing Android apps in the upcoming semester where I'll have a workshop course in developing for Android.
So, is there a site as SourceForge for Android?
Thank you.

A: To learn android check following sites:

*

*how can i learn android

*how can i learn android

*Android developer's guide
For sample code visit following sites:

*

*Android samples

*Code Sample in Android
Hope this helps.

A: You can refer to the following website where a lot of open source projects can be downloaded
http://code.google.com/p/apps-for-android/


text:
Q: How can I send auto mail with thunderbird with bash scripting and xdotool? What I want to do is, if a condition is met, such as like if x=5, I want it to send a mail to me, automatically. With thunderbird, you can partially do this, but can't click send obviously...
This thunderbird command alone, works in that regard:
thunderbird -compose "subject='test',to='someaddress@mail.com',body='this and that'"

Also this xdotool command work:
xdotool mousemove 570 179 click 1

this 570 179 is where the SEND button is. But, if I combine these like this. This wont work(changing && s to ; don't work either):
thunderbird -compose "subject='test',to='someaddress@mail.com',body='this and that'" && sleep 2 && xdotool mousemove 576 218 click 1

However, when I only do thunderbird command, then in another terminal if I apply this xdotool mouse click, it works only then.
I was researching on this subject, they said this might be about x server, so they advised something like this:
thunderbird -compose "subject='something',to='someaddress@mail.com',body='
something'" && sleep 5; xdotool windowactivate $(xdotool getactivewindow) sleep 5 && xdotool mousemove 576 218 click 1


text:
Q: Executors.newSingleThreadExecutor I am trying to make a trivial example of Executors and Threads.
When I call newSingleThreadExecutor(new CustomThreadFactory) it goes well, but when I call newSingleThreadExecutor(null) with null parameter it gives me "AWT-EventQueue-0" java.lang.NullPointerException.
Why?
private Executor creador = Executors.newSingleThreadExecutor(null); //at this point fails, and with no parameters everything goes well
private QRExplorer explorer; // this class implements Runnable
//...
public MainView()
{
   //...
   explorer = new QRExplorer();
}
private void pCamaraMouseClicked(java.awt.event.MouseEvent evt)
{
      creador.execute(explorer);
}

A: Here
Executors.newSingleThreadExecutor(null);

you're trying to invoke the newSingleThreadExecutor overload that accepts a ThreadFactory argument. You're passing the value null as that single argument.
The javadoc of that method states

Throws:

*

*NullPointerException - if threadFactory is null

Since you're passing null, the invocation will throw NullPointerException.


text:
Q: Eclipse-Ivy-Selenium configuration when Ivy.xml and selenium jar kept on server We were trying to automate the test scripts using Selenium-Eclipse-Ivy.
The selenium jar files has to be called through ivy.xml and ivysettings.xml kept on server.
We are not allowed to download the Jar files nor the XML files.
We are not able to understand how we can use those XML files to call the jar.
Also, we are not allowed to modify these files.
Please help us as we are not able to take single step with this issue.
Thanks in advance.

A: Unlike the settings task, the ivy resolve task does not support a "url" argument. This means the "ivy.xml" will have to exist locally, whereas the "ivysettings.xml" could quite happily live on the server.
If you really can't support a local ivy.xml file, the only option I can think of is a cachepath task, listing the dependencies from within your build file.
<ivy:cachepath pathid="compile.path">
    <dependency org="org.seleniumhq.selenium" name="selenium" rev="2.0rc2"/>
</ivy:cachepath>

Finally, I don't really understand what you mean by not being allowed to download jar files.


text:
Q: VB.NET Import CSV file with multiple delimiters I'm being presented with a CSV file that i would like to import to a datatable. The challenge I have is that the file has 2 different delimters. The first few columns are delimited with a "tab" and the rest with a";". I can handle the one easily but not sure how to handle both. The code that I have so far but struggling to find a way to expand this to import it the single step:
Public Function LoadFileToDatatable(ByVal FullFilePath As String)
    'Load the Testfile into an datatable
    Dim folder As String = System.IO.Path.GetDirectoryName(FullFilePath)
    Dim filename As String = System.IO.Path.GetFileName(FullFilePath)
    Dim con = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & folder & ";Extended Properties=""text;HDR=No;FMT=Delimited"";"
    Dim dt As New DataTable

    Using Adp As New OleDbDataAdapter("Select * From " & filename, con)
        Adp.Fill(dt)

        'Remove the first row as it contains the header data
        Dim theRow As DataRow = dt.Rows(0)
        dt.Rows.Remove(theRow)
    End Using
    Return dt
End Function


text:
Q: Why is Java crashing on even the simplest Swing program? For seemingly no reason, Java has started crashing whenever I try to run anything with Swing. If I run the HelloWorld program, for example, just to test things, it'll run perfectly fine. But if I try to run a program with a JFrame, no matter how simple (I even tried the JFrame demo example on Java's website just so I could get a bare-bones JFrame program), I always get the "Java SE Platform Binary has stopped working" error.
Could this be related to a graphics driver update? I'd think not but you never know.
This is the demo I tried:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class FrameTest {
    public static void main(String[] args) {
        JFrame frame = new JFrame("FrameDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            JLabel emptyLabel = new JLabel("");
            emptyLabel.setPreferredSize(new Dimension(175, 100));
            frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);

            frame.pack();
            frame.setVisible(true);
    }
}

A: You should always use SwingUtilities.invokeLater() when dealing with Swing from main() or from any thread that isn't EDT.
https://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html
SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        createAndShowGUI();
    }
});

A: Still I am not allowed to post a comment. That is why I answer even for simple things.

*

*Go to Environment variables.

*Under the System Variables, click on new.

*In the variable name, enter _JAVA_OPTIONS

*In the Variable Value, enter -Xmx256M

*Press OK and Check if it works now.


text:
Q: Intuitive explanation to why superconductivity breaks at high temperatures I was recently caught up in a situation where I tried to explain to someone with only vary basic knowledge of physics (notion of atoms and electrons, etc.) what causes superconductivity. One thing I was unable to explain though was why superconductors work only at low temperatures.
Superconductivity is caused by electrons interacting with the phonons in such a way that the effective interaction between electrons becomes attractive (for electrons near the Fermi surface). The electrons with attractive interactions between them then form bosonic pairs and condense to the ground state which leaves a gap in the energy spectrum of the remaining electrons. The temperatures at which this no longer is possible is found by searching for a solution to the gap equation with gap parameter set to zero.
Without going through the mathematics and the gap equation, how would you explain to a layman or an undergrad or maybe even a physicist working on a different field why superconductivity ceases to exist at sufficiently high temperatures?

A: Since we haven't had any definitive answers I'll have a a go, but I expect comments from the big guns in the site! :-)
In the superconducting state you have electrons bound into pairs by an attractive force (due to lattice interactions). But there isn't just one electron pair, there are a huge number of them and they are all entangled. So you can't raise the energy of a single electron: you would have to raise the energy of the whole population of pairs and there are around Avagadro's number of them.
When you attempt to put energy in nothing happens until the energy breaks up a pair of electrons, and the isolated electrons now have a continuum of energies. So the smallest amount of energy you can put in is the binding energy of the Cooper pairs. This is why there is an energy gap.
It just remains to explain why the binding energy of the Cooper pairs falls with increasing temperature, and this is simply because the increased lattice vibrations interfere with and eventually destroy the long distance correlations required to form the pairs.
There is an interesting article on the history of superconductivity here, and it gives a popular science description of the processes inolved.

A: The simplest explanation is to consider a tray with a bunch of small depressions in it and a bunch of marbles on it.  When the tray is stationary, the marbles fall in to the depressions and stay there.  When you shake the tray very slowly, the marbles stay in their depressions.  But if you shake the tray vigorously, the marbles pop out of the depressions and go all over the place.  As long as you keep shaking vigourously, the marbles move around the tray almost as if the depressions weren't even there.  And as soon as you slow your shaking enough, the marble fall back in to the depressions and cannot move beyond their local depression.
"Temperature" is a measure of how vigorously the elements of something are moving around randomly.  A gas which is 4X as hot has its molecules moving, on average, 2 times as fast (square that to get 4 times the energy).  The depressions represent the fact that many molecules have a slighly lower energy when they are at a "sweet spot" distance from each other which is actually pretty close together, but that energy is not very much lower.  It is easy to see how the marbles in the depression is analogous to a solid, where the molecules are arrayed in fixed locations in a regular lattice.
But it is not much of a stretch to see how the marbles in the depression are also aanalagous to the liquid situation.  In liquid, the molecules want to stay near each other, but they can "roll around over each other" pretty freely as long as they don't get too far apart from any other molecules.
And so we have described "phase transitions," how a weak attractive force (shallow depressions) only impose their order when the temperature (amount of random motion energy) is low enough.
Superconducting Phase Transition
In a metal which is potentially superconducting, at high temperatures its conduction electrons zip around pretty freely and energetically throughout the extent of the metal.  It is so much like a gas of electrons that the very useful model is called the free electron model and at higher temperatures the electrons are referred to as a gas.
But it turns out that in some metals, (lead, tin, niobium, among others) there is a very weak attractive force between electrons.  This is so week that at room temperature it is completely unnoticeable.  Indeed, none of the gas electrons get "stuck" in the tiny "depressions" associated with such a weak force until the temperature is around one one-hundredth of normal room temperature, around 4 Kelvins for lead, whereas normal room temperature is about 290 Kelvins and liquid nitrogen is still 77 Kelvins.
The superconducting state is more like a liquid than a solid.  So the electrons have some "correlation" with each other, which is broken when they are jostled out of their "depression" by thermal bumping from other electrons.
Now what this model tells you is a way to describe falling in to a more correlated state from a "gas" state, which applies to gases condensing to liquids, then solids, it also applies to gasses of electrons condensing into a superconducting fluid-like state.  What it does NOT describe is WHY that state carries current with absolutely positively no voltage drop required.  That is a different (and probably harder) post!

A: I am very much confused about the answers presented so far and I believe they miss the main point. At any finite temperature it is not the normal (internal) energy E which is important but the free energy F = E - T S
At zero temperature the system is in a superconducting state because the pairing up the energy lowers the total energy of the system by the condensation energy (which is essentially the binding energy of the Cooper pairs). However the superconducting state is an ordered state: all the Cooper pairs are in a single macroscopic quantum state which can be described with a few degrees of freedom. Because of this the superconducting state has a much lower entropy than the corresponding normal state.
When going to any finite temperature it is not the state with the lowest energy which is realized but the one with the lowest free energy. Because of the difference in entropy it is clear that at some point the normal state will be favored.
Two points (which will maybe resolve some confusion):
1) for the superconducting state to exist and to be stable, it is not important that the single particle excitations are gapped. This is a red herring. In fact the single particle excitations in the high temperature superconductors (d-wave) are not gapped. The importance of gap stems from the fact that it is the order parameter which is a measure of the condensation energy.
2) the transition between a superconducting and a normal state driven by temperature is just the same as the transition between an (ordered) ferromagnet at low temperature (with low entropy) and the paramagnetic state  at high temperature (with high entropy). In both cases, it is not the internal energy which drives the transition as at any temperature the ferromagnetic state enjoys the lower energy

A: The simplest explanation is that the thermal energy present in a system at low temperatures is not enough to break the paired state of the electrons.
The pairing of the electrons and the condensation of the pairs is what makes a superconductor. If you want a dead-simple lay persons explanation, consider two spheres glued together as the electron pair, and you trying to pull the spheres apart as the thermal energy. Only if you are strong enough will you be able to pull apart the spheres, and break down the pairing states.  Now, if you have a million friends, all of whom have their own set of glued spheres and are as strong as you are, once you all have broken the glued sphere pairs, the spheres in your hands are free to move around willy-nilly, and bang into each other, giving rise to resistance.
This post gives me a reason to provide a link this video, which has its difficulties, but is visually appealing as a model : http://www.youtube.com/watch?v=O6sukIs0ozk


text:
Q: How do I set the eclipse.ini -vm option? I installed the Maven plugin for Eclipse, and then I got an error like below:

please make sure the -vm option in eclipse.ini is pointing to a JDK

How do I use the -vm option to point to my JDK in eclipse.ini?

A: I am not sure if something has changed, but I just tried the other answers regarding entries in "eclipse.ini" for Eclipse Galileo SR2 (Windows XP SR3) and none worked. Java is jdk1.6.0_18 and is the default Windows install. Things improved when I dropped "\javaw.exe" from the path.
Also, I can't thank enough the mention that -vm needs to be first line in the ini file. I believe that really helped me out.
Thus my eclipse.ini file starts with:
-vm
C:\Program Files\Java\jdk1.6.0_18\bin

FYI, my particular need to specify launching Eclipse with a JDK arose from my wanting to work with the m2eclipse plugin.

A: eclipse.ini file must have -vm on the first line and a path on the second line. Don't try to put everything into one line!
-vm
C:\Program Files\Java\jdk1.6.0_07\bin\javaw.exe

A: You have to edit the eclipse.ini file to have an entry similar to this:
C:\Java\JDK\1.5\bin\javaw.exe (your location of java executable)
-vmargs
-Xms64m   (based on you memory requirements)
-Xmx1028m

Also remember that in eclipse.ini, anything meant for Eclipse should be before the -vmargs line and anything for JVM should be after the -vmargs line.

A: Anything after the "vmargs" is taken to be vm arguments. Just make sure it's before that, which is the last piece in eclipse.ini.

A: The JDK you're pointing to in your eclipse.ini has to match the Eclipse installation.
If you are running a 32- or 64-bit Eclipse, use a 32 or 64-bit Java JDK, respectively.

A: I'd like to share this little hack:
A click on the Eclipse's icon indicated a problem with the JRE.
So, I put this command in the destination field of the icon's properties:
C:\...\eclipse.exe -vm c:\'Program Files'\Java\jdk1.7.0_51\jre\bin\javaw

Thinking that the "'" would solve the problem with the space in the path.
That did not function. Then, I tried this command:
C:\...\eclipse.exe -vm c:\Progra~1\Java\jdk1.7.0_51\jre\bin\javaw

with success

A: There is a wiki page here.
There are two ways the JVM can be started: by forking it in a separate process from the Eclipse launcher, or by loading it in-process using the JNI invocation API.
If you specify -vm with a path to the actual java(w).exe, then the JVM will be forked in a separate process. You can also specify -vm with a path to the jvm.dll so that the JVM is loaded in the same process:
-vm
D:/work/Java/jdk1.6.0_13/jre/bin/client/jvm.dll

You can also specify the path to the jre/bin folder itself.
Note also, the general format of the eclipse.ini is each argument on a separate line. It won't work if you put the "-vm" and the path on the same line.

A: I know that there exists a command line option, -vm, to specify the path to the executable of the Java runtime. This may be the same as in eclipse.ini.

A: Assuming you have a jre folder, which contains bin, lib, etc files copied from a Java Runtime distribution, in the same folder as eclipse.ini, you can set in your eclilpse.ini
-vm
jre\bin\javaw.exe

A:
-vm
C:\Program Files\Java\jdk1.5.0_06\bin\javaw.exe

Remember, no quotes, no matter if your path has spaces (as opposed to command line execution).
See here: Find the JRE for Eclipse

A: My solution for Ubuntu Linux:
-vm
/home/daniel/Downloads/jdk1.6.0_17/bin
-startup
plugins/org.eclipse.equinox.launcher_1.1.1.R36x_v20101122_1400.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.2.R36x_v20101019_1345
-product
org.eclipse.epp.package.jee.product
--launcher.defaultAction
openFile
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vmargs
-Dosgi.requiredJavaVersion=1.5
-XX:MaxPermSize=256m
-Xms40m
-Xmx512m

A: My solution is:
-vm
D:/work/Java/jdk1.6.0_13/bin/javaw.exe
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256M
-framework
plugins\org.eclipse.osgi_3.4.3.R34x_v20081215-1030.jar
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms40m
-Xmx512m

A: -startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20140415-2008.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.200.v20140603-1326
-product
org.eclipse.epp.package.jee.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
512M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
512m
--launcher.defaultAction
openFile
--launcher.appendVmargs
-vmargs
-Dosgi.requiredJavaVersion=1.6
-Xms2000m
-Xmx3512m


text:
Q: how to configure unit test in vscode for python unittest I am using Python 3.6 and latest version of vscode.
My folder structure:
/folder
    /src
        src.py
    /tests
        src_test.py

src.py:
class Addition:
  def __init__(self, a, b):
    self.a = a
    self.b = b
  def run(self):
    return self.a + self.b

src_test.py:
import unittest

from ..src.addition import Addition

class TestAddition(unittest.TestCase):
  def test_addition(self):
    inst = Addition(5, 10)
    res = inst.run()
    self.assertEqual(res, 16)

if( __name__ == "main"):
  unittest.main()

here is my project settings.json:
{
  "python.testing.unittestArgs": [
    "-v",
    "-s",
    ".",
    "-p",
    "*_test.py"
  ],
  "python.testing.pytestEnabled": false,
  "python.testing.nosetestsEnabled": false,
  "python.testing.unittestEnabled": true
}

Then under project root folder:

python3 -m unittest tests/src_test.py

 File "/usr/lib/python3.6/unittest/loader.py", line 153, in loadTestsFromName
    module = __import__(module_name)
ModuleNotFoundError: No module named 'tests.src_test'

A: You are missing an __init__.py file under the tests folder, and the import your module needs a tweak.
The __init__.py allows Python to go up in the folder structure and reach the src.py module (another __init__.py under src would be nice, but it is not necessary to make the vscode tests work).
This is a working folder structure:
.
├── src
│   └── src.py
└── tests
    ├── __init__.py
    └── src_test.py

Also, change the line in src.py:

*

*(OLD) from ..src.addition import Addition

*(NEW) from src.src import Addition


text:
Q: VSCode "Unable to open  Unable to read file" I'm using VSCode (1.52.1) for a while on my Fedora 33 machine.
I'm using Docker extension (v1.9.0) but for some reason, in the past few days when I'm trying to attach the VSCode to the Docker container, it failed to resolve the workspace folder.
I've tried to reinstall VSCode and the Docker extension but it did not help
I think this issue is related
Screenshot:

As you can see, the files explorer does not show any files, instead, it shows a hash-like string.

A: Accourding to this vs-code issue

You might have had that folder open before and it now no longer exists. Can you use File > Open Folder to open a different folder in the container?

All you need to do is go to
File --> Open Folder in the top menu
open the wanted folder and that it.

That worked for me


text:
Q: Firebase Console still show Crashlytics Implementation Dialog Implemented As Explained In Docs
https://firebase.google.com/docs/crashlytics/get-started?authuser=0
buildscript {

repositories {
    google()
    jcenter()
    maven { url 'https://maven.fabric.io/public' }
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.1.4'
    classpath 'com.google.gms:google-services:4.0.1'
    classpath 'io.fabric.tools:gradle:1.25.4'
    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}
allprojects {
    repositories {
        google()
        jcenter()
        maven {
            url 'https://maven.google.com/'
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Module:app
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

......
......
dependencies {
    ........
    ........

    implementation 'com.google.firebase:firebase-core:16.0.3'
    implementation 'com.google.firebase:firebase-messaging:17.3.2'
    implementation 'com.startapp:inapp-sdk:3.10.1'
    implementation 'com.crashlytics.sdk.android:crashlytics:2.9.5'
    implementation 'com.google.firebase:firebase-crash:11.8.0'
}
apply plugin: 'com.google.gms.google-services'

In Main Laucher Activity
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    /*StartAppSDK.init(this, getResources().getString(R.string.startApp_sdk), false);
    StartAppAd.disableSplash();*/

    setContentView(R.layout.activity_permission);

//Both Tried But Not get Any result

    Fabric.with(this, new Crashlytics());
   /*final Fabric fabric = new Fabric.Builder(this)
            .kits(new Crashlytics())
            .debuggable(true)  // Enables Crashlytics debugger
            .build();
    Fabric.with(fabric);*/
    FirebaseCrash.log("Activity created");
  }
}

I tried Manual Crashing
Crashlytics.getInstance().crash(); // Force a crash

My Problem Is Firebase Console still Showing Implementation Dialog

Why its already implemented since before 2 hours?
After crashing application logs looks like...for just testing Basb I removed my MainActivity from Manifest file. Error comes as expected but Firebase console is still showing implementation dialog. Why?
D/CrashlyticsCore: Crashlytics is handling uncaught exception "android.content.ActivityNotFoundException: Unable to find explicit activity class {com.gauravkhannamarketeer.navratriwallpaperapp/com.gauravkhannamarketeer.navratriwallpaperapp.activity.MainActivity}; have you declared this activity in your AndroidManifest.xml?" from thread main
D/Answers: Logged crash
D/SensorManager: sensorCTSV isCtsVerifier false
                 sensorCTSV isCtsVerifier false
                 sensorCTSV isCtsVerifier false
D/CrashlyticsCore: No log data to include with this event.
D/CrashlyticsCore: Closing open sessions.
                   Closing session: 5BAB3C570014-0001-7C73-036ED06B5023
                   Collecting session parts for ID 5BAB3C570014-0001-7C73-036ED06B5023
D/CrashlyticsCore: Session 5BAB3C570014-0001-7C73-036ED06B5023 has fatal exception: true
                   Session 5BAB3C570014-0001-7C73-036ED06B5023 has non-fatal exceptions: false
D/CrashlyticsCore: Collecting SessionStart data for session ID 5BAB3C570014-0001-7C73-036ED06B5023
D/CrashlyticsCore: Collecting SessionUser data for session ID 5BAB3C570014-0001-7C73-036ED06B5023
D/CrashlyticsCore: Collecting SessionApp data for session ID 5BAB3C570014-0001-7C73-036ED06B5023
D/CrashlyticsCore: Collecting SessionOS data for session ID 5BAB3C570014-0001-7C73-036ED06B5023
D/CrashlyticsCore: Collecting SessionDevice data for session ID 5BAB3C570014-0001-7C73-036ED06B5023
D/CrashlyticsCore: Removing session part files for ID 5BAB3C570014-0001-7C73-036ED06B5023
D/CrashlyticsCore: Opening a new session with ID 5BAB3C9403A8-0002-7C73-036ED06B5023
D/CrashlyticsCore: Crashlytics completed exception processing. Invoking default exception handler.

A: By the way the main question is still going on but i solve it by moving to fabric implementation using android studio fabric plugin
Fabric
Download 'Fabric for Android' via your IDE repositories.
Mac users: Select "Preferences…" from the Android Studio / IntelliJ Menu.
Windows and Linux users: Select "Settings" from the File Menu.
Select 'Plugins' on the left side of the Settings Dialog. Select 'Browse Repositories...'
Search for 'Fabric for Android' and install the plugin.
After the IDE restarts, click the Fabric toolbar button to start using Fabric!


text:
Q: Как изменить картинку кнопки через tkinter Допустим я  нажимаю на кнопку и она должна поменять картинку

A: Используйте PhotoImage чтобы загрузить картинку и параметр image у кнопки, чтобы установить ей картинку.
Пример загружает картинки в список и при клике на кнопку меняет ей иконку на следующую в списке:
import tkinter as tk

def _on_button_click(button):
    global PHOTO_COUNTER
    PHOTO_COUNTER += 1
    if len(photo_list) <= PHOTO_COUNTER:
        PHOTO_COUNTER = 0

    button.config(image=photo_list[PHOTO_COUNTER])

root = tk.Tk()
root.geometry('200x200')

PHOTO_COUNTER = 0

photo_list = [
    tk.PhotoImage(file="icons/ok.png"),
    tk.PhotoImage(file="icons/no.png"),
    tk.PhotoImage(file="icons/help.png"),
]

button = tk.Button(root, text="ClickMe!", image=photo_list[PHOTO_COUNTER])
button.config(command=lambda: _on_button_click(button))
button.pack()

root.mainloop()

Скриншот:

PS. вариант с PHOTO_COUNTER можно упростить за счет использования генератора:
import tkinter as tk

def _on_button_click(button):
    button.config(image=get_next_image())

def next_image_generator():
    photo_list = [
        tk.PhotoImage(file="icons/ok.png"),
        tk.PhotoImage(file="icons/no.png"),
        tk.PhotoImage(file="icons/help.png"),
    ]

    while True:
        yield from photo_list

NEXT_IMAGE = next_image_generator()

def get_next_image():
    return next(NEXT_IMAGE)

root = tk.Tk()
root.geometry('200x200')

button = tk.Button(root, text="ClickMe!", image=get_next_image())
button.config(command=lambda: _on_button_click(button))
button.pack()

root.mainloop()


text:
Q: Python code to extract all the methods from a JAVA file I have a file MainActivity.java

public class MainActivity
  extends Activity
{
  EditText etResponse;
  TextView tvIsConnected;

  public static String GET(String paramString)
  {
    try
    {
      InputStream localInputStream = new DefaultHttpClient().execute(new HttpGet(paramString)).getEntity().getContent();
      if (localInputStream != null) {
        return convertInputStreamToString(localInputStream);
      }
      return "Did not work!";
    }
    catch (Exception localException)
    {
      Log.d("InputStream", localException.getLocalizedMessage());
    }
    return "";
  }

  private static String convertInputStreamToString(InputStream paramInputStream)
    throws IOException
  {
    BufferedReader localBufferedReader = new BufferedReader(new InputStreamReader(paramInputStream));
    String str2;
    for (String str1 = "";; str1 = str1 + str2)
    {
      str2 = localBufferedReader.readLine();
      if (str2 == null)
      {
        paramInputStream.close();
        return str1;
      }
    }
  }

  public boolean isConnected()
  {
    NetworkInfo localNetworkInfo = ((ConnectivityManager)getSystemService("connectivity")).getActiveNetworkInfo();
    return (localNetworkInfo != null) && (localNetworkInfo.isConnected());
  }

  protected void onCreate(Bundle paramBundle)
  {
    super.onCreate(paramBundle);
    setContentView(2130903040);
    this.etResponse = ((EditText)findViewById(2131165185));
    this.tvIsConnected = ((TextView)findViewById(2131165184));
    if (isConnected())
    {
      this.tvIsConnected.setBackgroundColor(-16724992);
      this.tvIsConnected.setText("You are conncted");
    }
    for (;;)
    {
      new HttpAsyncTask(null).execute(new String[] { "http://www.google.com" });
      return;
      this.tvIsConnected.setText("You are NOT conncted");
    }
  }

and I want to search for all the methods used in this file such as onCreate(), execute(), setText(), DefaultHttpClient() etc using Python language.
I have tried using regular expressions but is not helping me much.


text:
Q: breadcrumbs are not added on cached views in my Layouts default.ctp I have
<!--nocache-->
  <?php echo $this->Html->getCrumbs(' / ', 'Home'); ?>
<!--/nocache-->

Inside a view called rules.cpt I have
<!--nocache--><?php $this->Html->addCrumb('Rules', '/rules'); ?><!--/nocache-->

When first opening the (uncached) view, the breadcrumbs are rendered as wished. With every additional (cached) rendering, only Home is being displayed.
When removing the caching from the Controller
// public $cacheAction = array('home' => 120, 'rules'  => 36000);

everything works.
Why isn't addCrumb() being called? I tested to add <?php echo time(); ?> to the same nocache-block which works (i.e. is called on every page rendering).

A: The issues source seems to be the order of the calls being made.
In my initial version <?php echo $this->Html->getCrumbs(' / ', 'Home'); ?> was called before <?php $this->Html->addCrumb('Rules', '/rules'); ?> what works fine as long as the views are not being cached.
As soon as they are cached in only works addCrumb is being called before getCrumbs.
This only partly answers my question. Because getCrumbs is used in my layouts .ctp it is not possible to change the order.
I posted this as answer and not as note on my question, so that nobody gets the bounty for something which I already wrote in the question ;) If you can provide a solution to the remaining problem or know if this is a bug in Cake, I am happy to provide you with the bounty.


text:
Q: react-native info not detecting Xcode 9 On my mac, to be able to develop react-native apps, I installed react-native-cli and create-react-native-app using npm.
When I run:
react-native info

I see the following output:
Environment:
  OS:  macOS Sierra 10.12.6
  Node:  6.11.4
  Yarn:  Not Found
  npm:  3.10.10
  Watchman:  4.9.0
  Xcode:  Not Found
  Android Studio:  Not Found

Packages: (wanted => installed)
  react: 16.0.0-alpha.12 => 16.0.0-alpha.12
  react-native: ^0.48.4 => 0.48.4

As you can see, Xcode is shown as "Not Found". I am running Xcode 9 on my system.
What should I be checking for / installing on my OS for react-native to work with Xcode 9?

A: I installed Expo XDE and tried to create and run a project from there. I saw this error in the XDE. Helped me solve the problem.

Simulator not installed. Please visit
  https://developer.apple.com/xcode/download/ to download Xcode and
  the iOS simulator. If you already have the latest version of Xcode
  installed, you may have to run the command
  sudo xcode-select -s /Applications/Xcode.app.


text:
Q: problem while display the data on server at time of login give error Undefined index: Gender in C:\xampp\htdocs\test\stud.php on line 67

FEMALE  Notice: Undefined index: Gender in C:\xampp\htdocs\test\stud.php on line 68
  MALE  Notice: Undefined index: Gender in C:\xampp\htdocs\test\stud.php on line 69
  OTHER

Gender:
<input type="radio" name="Gender" required value="FEMALE" <?php echo  isset($student) && $student ['Gender'] === 'FEMALE' ? 'checked' : ''?>>FEMALE
<input type="radio" name="Gender" required value="MALE" <?php echo  isset($student) && $student ['Gender'] === 'MALE' ? 'checked' : '' ?>>MALE
<input type="radio" name="Gender" required value="OTHER" <?php echo  isset($student) && $student ['Gender'] === 'OTHER' ? 'checked' : '' ?>>OTHER

Undefined index: Gender in C:\xampp\htdocs\test\stud.php on line 67

FEMALE  Notice: Undefined index: Gender in C:\xampp\htdocs\test\stud.php on line 68
  MALE  Notice: Undefined index: Gender in C:\xampp\htdocs\test\stud.php on line 69
  OTHER

A: My be Gender $student does not have index 'Gender', You can do it by below-
Gender:
<input type="radio" name="Gender" required value="FEMALE" <?php echo  isset($student ['Gender']) && $student ['Gender'] === 'FEMALE' ? 'checked' : ''?>>FEMALE
<input type="radio" name="Gender" required value="MALE" <?php echo  isset($student ['Gender']) && $student ['Gender'] === 'MALE' ? 'checked' : '' ?>>MALE
<input type="radio" name="Gender" required value="OTHER" <?php echo  isset($student ['Gender']) && $student ['Gender'] === 'OTHER' ? 'checked' : '' ?>>OTHER