Q: Contentful with Gatsby: rendering RichText field by accessing json not possible (raw instead) I am following a documentation on how to implement Contentful's RichText field type with Gatsby.
My GraphQL query only returns a field raw on my RichText field called synopsis:
query MyQuery {
  allContentfulCountry {
    edges {
      node {
        id
        synopsis {
          raw
        }
      }
    }
  }
}

It returns:
{
  "data": {
    "allContentfulCountry": {
      "edges": [
        {
          "node": {
            "id": "fa07b3db-6acb-5b9a-7c4b-c42ef3c191b0",
            "synopsis": {
              "raw": "{\"data\":{},\"content\":[{\"data\":{},\"content\":[{\"data\":{},\"marks\":[],\"value\":\"The actual rich text...\",\"nodeType\":\"text\"}],\"nodeType\":\"paragraph\"}],\"nodeType\":\"document\"}"
            },
            "slug": "france"
          }
        }
      ]
    }
  }
}

The documentation assumes documentToReactComponents(node.bodyRichText.json, options) but I can't access json and need to do this: JSON.parse(country.synopsis.raw)
Am I missing something?
"@contentful/rich-text-react-renderer": "^14.1.2",
"@contentful/rich-text-types": "^14.1.2",

System:
  OS: macOS 11.0.1
  CPU: (8) x64 Intel(R) Core(TM) i7-7820HQ CPU @ 2.90GHz
  Shell: 5.8 - /bin/zsh
Binaries:
  Node: 12.13.0 - ~/.nvm/versions/node/v12.13.0/bin/node
  npm: 6.14.9 - ~/.nvm/versions/node/v12.13.0/bin/npm
Languages:
  Python: 2.7.16 - /usr/bin/python
Browsers:
  Firefox: 82.0.3
npmPackages:
  gatsby: ^2.26.1 => 2.26.1
  gatsby-image: ^2.6.0 => 2.6.0
  gatsby-plugin-intl: ^0.3.3 => 0.3.3
  gatsby-plugin-newrelic: ^1.0.5 => 1.0.5
  gatsby-plugin-react-helmet: ^3.3.5 => 3.3.5
  gatsby-plugin-sharp: ^2.9.0 => 2.9.0
  gatsby-source-contentful: ^4.1.0 => 4.1.0
  gatsby-transformer-remark: ^2.11.0 => 2.11.0
  gatsby-transformer-sharp: ^2.5.6 => 2.5.6
npmGlobalPackages:
  gatsby-cli: 2.14.0

A: Contentful DevRel here.
There has been a breaking change in the gatsby-source-contentful in v4. It's now recommended to use raw. You can find more information in the changelog.
A recommended Gatsby query from the changelog:
export const pageQuery = graphql`
  query pageQuery($id: String!) {
    contentfulPage(id: { eq: $id }) {
      title
      slug
      description {
        raw
        references {
          ... on ContentfulPage {
            # contentful_id is required to resolve the references
            contentful_id
            title
            slug
          }
          ... on ContentfulAsset {
            # contentful_id is required to resolve the references
            contentful_id
            fluid(maxWidth: 600) {
              ...GatsbyContentfulFluid_withWebp
            }
          }
        }
      }
    }
  }
`


Q: Extension SNMP Agent C# I am a complete newbie to SNMP. Recently, I am trying to write a simple program that is supposed to monitor and modify a data file in a remote machine. The file itself could just be a plain-text file or whatsoever. I was introduced to the SNMP, and tried to figure out a way to make SNMP do the job in Windows OS. The prefered language is C# or any .net. I have been googling for a few days, however, did not find a good how-to instruction to do so.
Really need help on this to get my job done.
Thank you very much,
Terry

A: Here's one SnmpSharpNet. More can be found here.

A: I use SharpSnmpLib. It works very well for SNMPv2 and is pretty easy to understand


Q: Possible exception(s) thrown by CloudBlockBlob.UploadFromFile(...) Which exception(s) can be raised by
Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob.UploadFromFile(...)?
The C# metadata and online documentation page lists no exceptions for this method. Several examples on StackOverflow and elsewhere catch the base Exception class. Presumably only specific exceptions can be thrown. Quick-Starts and Tutorials on learn.microsoft.com don't include error handling.
Could it be just Microsoft.Azure.Storage.StorageException?

A: The method can throw lots of exceptions like ArgumentException, NotSupportedException, or etc. However, if your inputs are correct, the most possible exceptions are StorageException for communications against Azure Storage service and IOException for reading the file from local disk.


Q: getting data using Importxml into a spread sheet I tried to import xml data from a website to a spreadsheet, but most of the xpaths work except this one, it keeps throwing errors
This is my full syntax:
=IMPORTXML("http://egypt.souq.com/eg-en/2724304505488/s/","//*[@id="content-body"]/header/div[2]/div[1]/div[1]/div/h1")

Is this a problem with Google spread sheet or what ?

A: You've used double quotes inside your XPath query. Switching these for single quotes allows sheets to parse the formula correctly:
=IMPORTXML("http://egypt.souq.com/eg-en/2724304505488/s/","//*[@id='content-body']/header/div[2]/div[1]/div[1]/div/h1")

But this still results in an error:
Error
Imported XML content cannot be parsed.

You haven't been very specific but you can get the H1 content from the page in your code with this:
=IMPORTXML("http://egypt.souq.com/eg-en/2724304505488/s/","//h1")

This may well break for other pages, though.


Q: How to create a nested list from an object? I have an tags object from treetagger's python wrapper that apparently is list:
In:
print type (tags)
Out:
<type 'list'>

When I print the content of tags as follows, I get the following lists:
In:

def postag_directory(input_directory, output_directory):
    import codecs, treetaggerwrapper, glob, os
    for filename in sorted(glob.glob(os.path.join(input_directory, '*.txt'))):
        with codecs.open(filename, encoding='utf-8') as f:
            lines = [f.read()]
            #print 'lines:\n',lines
            tagger = treetaggerwrapper.TreeTagger(TAGLANG = 'en')
            tags = tagger.TagText(lines)

            print '\n\n**** labels:****\n\n',tags

Out:

[[u'I\tPP\tI', u'am\tVBP\tbe', u'an\tDT\tan', u'amateur\tJJ\tamateur']]

[[u'This\tDT\tthis', u'my\tPP$\tmy']]

[[u'was\tVBD\tbe', u'to\tTO\tto', u'be\tVB\tbe', u'my\tPP$\tmy', u'camera\tNN\tcamera', u'for\tIN\tfor', u'long-distance\tJJ\tlong-distance', u'backpacking\tNN\tbackpacking', u'trips\tNNS\ttrip', u'.\tSENT\t.', u'It\tPP\tit']]

However, I would like to get just one single nested list like this:
[[u'I\tPP\tI', u'am\tVBP\tbe', u'an\tDT\tan', u'amateur\tJJ\tamateur'],[u'This\tDT\tthis', u'my\tPP$\tmy'],[u'was\tVBD\tbe', u'to\tTO\tto', u'be\tVB\tbe', u'my\tPP$\tmy', u'camera\tNN\tcamera', u'for\tIN\tfor', u'long-distance\tJJ\tlong-distance', u'backpacking\tNN\tbackpacking', u'trips\tNNS\ttrip', u'.\tSENT\t.', u'It\tPP\tit']]

I all ready tried with list(), append(), [] and also with:
        for sublist in [item]:
            new_list = []
            new_list.append(sublist)
            print new_list

Any idea of how can I nest each list from tags?.

A: This is a list of one element (another list).
[[u'I\tPP\tI', u'am\tVBP\tbe', u'an\tDT\tan', u'amateur\tJJ\tamateur']]

So if item is a list of lists, each with one element, then you can do
new_list = [sublist[0] for sublist in item]

If you had more than one element in each sublist, then you'll need another nested loop in that.

Though, in reality, you shouldn't use lines = [f.read()]. The documentation uses a single string when you use tag_text, so start with this
# Initialize one tagger
tagger = treetaggerwrapper.TreeTagger(TAGLANG='en')
# Loop over the files
all_tags = []
for filename in sorted(glob.glob(os.path.join(input_directory, '*.txt'))):
    with codecs.open(filename, encoding='utf-8') as f:
        # Read the file
        content = f.read()
        # Tag it
        tags = tagger.tag_text(content)
        # add those tags to the master tag list
        all_tags.append(tags)

print(all_tags)


Q: Searching for one-word string occupying a line of a text with Python 2.7 I have (very) long document (in .txt) that has this format:
 Title
 text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text

 Whatever
 text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text

I would like to collect a column of all the titles before each text. For now I have a problem identifying them and printing them out.
I focus on the fact that there is an \n character before and after the 'title' of each text. I am not sure how to tell to python to select that 'title' that lies between the \n characters regardless of its length.
I used the code from here
text = "\n" + "" + "\n"
searchfile = open("MyTEXT.txt", "r")
for line in searchfile:
    if str(text) in line: print line
searchfile.close()

There are two problems with the code above that I do not know how to solve:
1) The first \n is in a different line (the line above), so the code above finds nothing.
2) The 'Title' string that I would like to collect are in varying lengths, some are 4 characters, but some are more (not more than 10).
Any suggestions will be very helpful,
thank you in advance!

A: Is this what you were looking for?
with open("MyTEXT.txt", "r") as myfile:
    wordlist = [line.rstrip('\n').split() for line in myfile]

titlelist = [i[0] for i in wordlist if len(i) == 1 and i[0] != "unwanted"]

For example, if MyTEXT.txt contained:
unwanted
12345 2124

abcd
efghi jkl mn

o
pqr 123

unwanted
stu v

wq
y z

unwanted
567 890

The output would be:
>>> titlelist
['abcd', 'o', 'wq']


Q: Convergence of sum with binomial coefficient I found this exercise in a book and I don't know how to start:

With the help of probabilistic methods, prove that
$$
\lim_{n\rightarrow\infty} \frac{1}{4^n} \sum_{k=0}^n  \binom{2n}{k} = 1/2
$$

One cannot use the binomial theorem because the sum just goes to $n$ and not to $2n$ and besides that, am I supposed to use one of the limit theorems in stochastics? If so, which one and how can I approach this exercise.

A: Let $(\xi_j)_{j\geqslant 1}$ be an i.i.d. sequence of random variables such that $\mathbb P(\xi_1=1)=\mathbb P(\xi_1=0)=1/2$. Then $\sum_{j=1}^{2n}\xi_j$ has a binomial distribution with parameters $(2n,1/2)$ hence
$$
\frac{1}{4^n} \sum_{k=0}^n  \binom{2n}{k}=\mathbb P\left(\sum_{j=1}^{2n}\xi_j\leqslant n\right).
$$
The central limit theorem will give the answer.

A: We obtain
\begin{align*}
\color{blue}{\sum_{k=0}^n\binom{2n}{k}}&=\frac{1}{2}\sum_{k=0}^{n-1}\binom{2n}{k}+\binom{2n}{n}+\frac{1}{2}\sum_{k=n+1}^{2n}\binom{2n}{k}\tag{1}\\
&=\frac{1}{2}\sum_{k=0}^{2n}\binom{2n}{k}+\frac{1}{2}\binom{2n}{n}\\
&\,\,\color{blue}{=\frac{1}{2}2^{2n}+\frac{1}{2}\binom{2n}{n}}\tag{2}
\end{align*}
In (1) we use the symmetry $\binom{2n}{k}=\binom{2n}{2n-k}$. We use Stirling's approximation formula
\begin{align*}
n!\sim \left(\frac{n}{e}\right)^n\sqrt{2\pi n}
\end{align*}
and get
\begin{align*}
\color{blue}{\binom{2n}{n}}=\frac{(2n)!}{n!n!}
&\sim\left(\frac{2n}{e}\right)^{2n}\sqrt{4\pi n}\left(\frac{e}{n}\right)^{2n}\frac{1}{2\pi n}\\
&\,\,\color{blue}{\sim 4^n\frac{1}{\sqrt{\pi n}}}\tag{3}
\end{align*}

We conclude from (2) and (3)
\begin{align*}
\color{blue}{\frac{1}{4^n}}\color{blue}{\sum_{k=0}^n\binom{2n}{k}}
&=\frac{1}{4^n}\left(\frac{1}{2}2^{2n}+\frac{1}{2}\binom{2n}{n}\right)\\
&=\frac{1}{2}+\frac{1}{2}\,\frac{1}{4^n}\binom{2n}{n}\\
&\sim\frac{1}{2}+\frac{1}{2}\frac{1}{\sqrt{\pi n}}\color{blue}{\underset{n\to\infty }{\longrightarrow} \frac{1}{2}}
\end{align*}
and the claim follows.


Q: android gradle monkeyTalk build issue I'm using monkeyTalk in order to get write test by this demo. I`m using AndroidAnnotations 2.7.1 and i faced an issue like this.
 Note: Generating source file:com.activity.SaveFileDialogActivity_
Note: Time measurements: [Whole Processing = 517 ms], [Generate Sources = 185 ms], [Extract Manifest = 102 ms], [Extract Annotations = 96 ms], [Validate Annotations = 68 ms], [Process Annotations = 54 ms], [Find R Classes = 11 ms],
Note: Time measurements: [Whole Processing = 0 ms],
warning: The following options were not recognized by any processor: '[androidManifestFile, resourcePackageName]'
        189 errors
                               2 warnings
     :app:compileMonkeytalkJava FAILED

 FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileMonkeytalkJava'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --info or --debug option to get more log output.

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:compileMonkeytalkJava'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:64)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:42)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.AbstractTask.executeWithoutThrowingTaskFailure(AbstractTask.java:305)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.executeTask(AbstractTaskPlanExecutor.java:79)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:63)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:51)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:23)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:88)
    at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:29)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62)
    at org.gradle.execution.DefaultBuildExecuter.access$200(DefaultBuildExecuter.java:23)
    at org.gradle.execution.DefaultBuildExecuter$2.proceed(DefaultBuildExecuter.java:68)
    at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:55)
    at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:149)
    at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:106)
    at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:86)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:80)
    at org.gradle.launcher.cli.ExecuteBuildAction.run(ExecuteBuildAction.java:33)
    at org.gradle.launcher.cli.ExecuteBuildAction.run(ExecuteBuildAction.java:24)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:36)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)
    at org.gradle.launcher.cli.RunBuildAction.run(RunBuildAction.java:51)
    at org.gradle.internal.Actions$RunnableActionAdapter.execute(Actions.java:171)
    at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:237)
    at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:210)
    at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:35)
    at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:24)
    at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:206)
    at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:169)
    at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:33)
    at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:22)
    at org.gradle.launcher.Main.doAction(Main.java:33)
    at org.gradle.launcher.bootstrap.EntryPoint.run(EntryPoint.java:45)
    at org.gradle.launcher.bootstrap.ProcessBootstrap.runNoExit(ProcessBootstrap.java:54)
    at org.gradle.launcher.bootstrap.ProcessBootstrap.run(ProcessBootstrap.java:35)
    at org.gradle.launcher.GradleMain.main(GradleMain.java:23)
    at org.gradle.wrapper.BootstrapMainStarter.start(BootstrapMainStarter.java:33)
    at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:130)
    at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:48)
Caused by: org.gradle.api.internal.tasks.compile.CompilationFailedException: Compilation failed; see the compiler error output for details.
    at org.gradle.api.internal.tasks.compile.JdkJavaCompiler.execute(JdkJavaCompiler.java:44)
    at org.gradle.api.internal.tasks.compile.JdkJavaCompiler.execute(JdkJavaCompiler.java:35)
    at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.delegateAndHandleErrors(NormalizingJavaCompiler.java:97)
    at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.execute(NormalizingJavaCompiler.java:50)
    at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.execute(NormalizingJavaCompiler.java:36)
    at org.gradle.api.internal.tasks.compile.CleaningJavaCompilerSupport.execute(CleaningJavaCompilerSupport.java:34)
    at org.gradle.api.internal.tasks.compile.CleaningJavaCompilerSupport.execute(CleaningJavaCompilerSupport.java:25)
    at org.gradle.api.tasks.compile.JavaCompile.performCompilation(JavaCompile.java:158)
    at org.gradle.api.tasks.compile.JavaCompile.compile(JavaCompile.java:138)
    at org.gradle.api.tasks.compile.JavaCompile.compile(JavaCompile.java:92)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:63)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$IncrementalTaskAction.doExecute(AnnotationProcessingTaskFactory.java:235)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:211)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$IncrementalTaskAction.execute(AnnotationProcessingTaskFactory.java:222)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:200)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:80)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:61)
    ... 47 more

BUILD FAILED


Q: Datascroller issue - When dataTable and dataScroller is nested inside loop DataScroller pagination issue - The requested page #2 isn't found in the model containing 1 pages. Paging is reset to page #1
I have used a4j:repeat to iterate rich:dataTable and rich:datascroller. The problem with rich:datascroller is that pagination is not working properly.
I have also tried JSTL c:foreach also. But, still I am getting the following error in console.

(UIDatascroller.java:471) - Datascroller indexId:j_id129:j_id139: The requested page #2 isn't found in the model containing 1 pages. Paging is reset to page #1

In the PageBean.java
private List parentList;
public List getParentList() {
    return parentList;
}
public void setParentList(List parentList) {
    this.parentList = parentList;
}
public String openPage(){
    for(int i=0;i<10;i++){
        List<BeanDto> dtoList = ...;
        if(dtoList!=null){
            if(parentList==null){
                parentList = new ArrayList<List<BeanDto>>();
            }
            parentList.add(dtoList);
        }
    }
    return "page"
}

In the page.xhtml
<a4j:repeat value="#{pageBean.parentList}" var="item">
    <rich:dataTable id="table" rows="2" var="childDto" value="#{item}">
        <f:facet name="header">
            <rich:columnGroup>
                <rich:column>
                    <h:outputText value="Name" />
                </rich:column>
                <rich:column>
                    <h:outputText value="Age" />
                </rich:column>
            </rich:columnGroup>
        </f:facet>
            <rich:column>
                <h:outputText value="#{childDto.name}"/>
            </rich:column>
            <rich:column>
                <h:outputText value="#{childDto.age}"/>
            </rich:column>
    </rich:dataTable>

    <rich:datascroller for="table" maxPages="10">
    </rich:datascroller>
</a4j:repeat>

Tables were displayed in the screen, but pagination is not working.
I have also tried to give index to the <rich:dataTable>'s id; That is also not woeking properly. Could you help me on this.


Q: Apache Detects files as directories I have a file 'result.txt' in my documentroot, now when I access:
http://localhost/result/first

It's accessing this instead:
http://localhost/result.txt/first

What could have I incorrectly misconfigured in my apache config?
EDIT: My rewrite rules are as follow:
<IfModule mod_rewrite.c>
    Options +FollowSymLinks
    RewriteEngine On
</IfModule>
<IfModule mod_rewrite.c>
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

A: Where did he get ".txt"? Not from the rewrite rules as I see.
Search for "txt" string in your apache config files (entirely) and disable rewrite rules.


Q: simple while loop excercise im learning java and currently im stuck on one exercise in which i cannot comprehend why is code behaving this way. Im tracing my steps on paper, but i would expect different answer than program actually does. If anyone could please explain why it does what it does
CODE:
System.out.print("Enter an integer: ");
int numb = in.nextInt();

   while (in.hasNextInt())
   {
      System.out.println(numb);
      System.out.print("Enter an integer: ");
      numb = in.nextInt();
   }

TESTER is just entering numbers, so output should look like this:
Enter an integer: 5
- 5
- Enter an integer: 10
- 10
- Enter an integer: 8
- 8
- Enter an integer: k
...

But it looks like this:
Enter an integer: 5
- 10
- 5
- Enter an integer: -4
- 10
- Enter an integer: 8
- -4
- Enter an integer: -6
- 8
- Enter an integer: 11
- -6
- Enter an integer: -1

A: This is because you use in.hasNextInt() too soon (or too late, depending on how you look at it): the Scanner cannot tell you if it sees an integer or not until after the end user has entered a value.
If you prompt for a number and then check for hasNextInt, your code should not skip the second prompt:
System.out.print("Enter an integer: ");
while (in.hasNextInt()) {
    int numb = in.nextInt();
    System.out.println(numb);
    System.out.print("Enter an integer: ");
}

This would also prevent an exception in situations when the very first entry is not a number.


Q: Nothing is being returned? Can I not assign a two-dimensional array all the values of a pre-existing one? I am trying to return an array of points by looping through an existing two-dimensional point array. findMatches(b) contains an array of arrays of points from a board. If I could just access and alter these points directly so as to return them all to the point array I am returning, that would be great, but I don't suppose it is that easy.
Here is my code:
public static Point[] findPossibleSwaps(Board b)
    {
        Point[][] nums = new Point[findMatches(b).length][];
        nums = findMatches(b);
        Point[] foundSwaps = new Point[3];
        int xH = 0;
        int yV = 0;
        int index = 0;
        int x = 0;
        int y = 0;

        for(int a = 0; a<nums.length; a++)
        {
            Point [] lop  = nums[a];
            for(int h = 0; h<lop.length; h++)
            {
                Point qo = new Point(x,y);
                qo = lop[h];
                if(qo.x!=0)
                {
                    xH = qo.x-1;
                    foundSwaps [index] = new Point(xH,qo.y);
                    index++;
                }

                if(qo.y!=0)
                {
                    yV = qo.y-1;
                    foundSwaps [index] = new Point(qo.x,yV);
                    index++;
                }

            }

        }
        return foundSwaps;
    }

Thanks everyone


Q: How to change Label in Manipulate? I would like to have the Label called beta being shown with the Greek letter, without renaming the variable beta. This is my try so far, which is not what I want because Greek beta (β) is not substituting beta.
Manipulate[
 Plot[beta x , {x, 0, 1}],
 {{beta, "β="}, 0, 1, Appearance -> "Labeled"}]

A: Manipulate[
 Plot[beta x, {x, 0, 1}, PlotRange -> {0, 1}]
 , {{beta, 0, "β="}, 0, 1, Appearance -> "Labeled"}
 ]


Q: Bounty after Serial voting..? Say someone gets a Mortarboard due to serial up-voting. I know that badges can't be reversed. But, votes can. This case is somewhat interesting and I'm curious. Today (over Physics.SE), this user got a load of up-votes. In fact, we were discussing about the upvoter & the reversing scheme (see the whole transcript). Within a few minutes, the guy cleverly used this 200 rep. to offer a bounty over this question
What I'm wondering is: The engine has recorded the pattern of votes. It will definitely do the reversing. Now, this guy only has 25 rep. The minimum rep. score that a SE user can have is 1. So, the score can't go negative (neither zero).
So to be clear, what would happen tomorrow? Can the system be cheated this way?

To future viewers: The problem has been resolved and the bounty has been revoked. See his profile.  I think the rule has been implemented that Bounty shouldn't be awarded if one experiences serial upvoting

A: When a deletion or a reversal event causes a bounty to make a user's rep go negative, a "rep change" event is added to the user's history to "give" the user enough rep to place the bounty.
So barring moderator intervention, the upvotes will be reversed and a "rep change" event will be registered to give the user enough rep to leave him with 1 rep after the bounty.
In such a case, yes the rep used for the bounty is essentially free.


Q: Check if function will result in error before executing I have this discord bot I have been playing around with. Since I constantly am trying things, I decided to do a command-command, which I would call by doing !cmd (message.channel or whatever). However, due me being bad at typing and forgetting to do things like declare variables, the commands often result in (obvious) errors. Is there a way to check if the function will result in an error? My current code is this:
if(splitMessage[0] === '!cmd'){
//splitMessage is the variable that splits !cmd from the rest (no problems with it yet)
        var c = message.content.split(/ (.+)/)[1];
        eval(c);
}

My eventual goal is something like
if(splitMessage[0] === '!cmd'){
    var c = message.content.split(/ (.+)/)[1];
    if(eval(c) == error){
        eval(c);
    }
}

A: if(splitMessage[0] === '!cmd'){
    var c = message.content.split(/ (.+)/)[1];
    try {
        eval(c);
    } catch (err) {
        console.log('There is an error!')
    }
}

Modifying a code in runtime is so bad though.


Q: How to store Array of objects into redis cache using php I Have an array of objects that I need to store into redis cache and use it later.
$obj = array(
                'request_id' => $request_id,
                'request_start_dttm' => $start_time,
                'client_id' => $clientId,
            );

            $redis = Redis::connection();
            $name = "API".bin2hex(random_bytes(3));
            $redis->rpush($name,$obj);
            print_r($redis->lrange($name,0,-1));

But I get the output as following:
array (
    0 => '1732478',
    1 => '2021-10-18 12:55:39.000000',
    2 => '3'
)

What should I do to preserve the key value pair using redis php?


Q: Pandas DataFrame Replace every value by 1 except 0 I'm having a pandas DataFrame like following.
3,0,1,0,0
11,0,0,0,0
1,0,0,0,0
0,0,0,0,4
13,1,1,5,0

I need to replace every other value to '1' except '0'. So my expected output.
1,0,1,0,0
1,0,0,0,0
1,0,0,0,0
0,0,0,0,1
1,1,1,1,0

A: Just use something like df[df != 0] to get at the nonzero parts of your dataframe:
import pandas as pd
import numpy as np
np.random.seed(123)

df = pd.DataFrame(np.random.randint(0, 10, (5, 5)), columns=list('abcde'))
df
Out[11]:
   a  b  c  d  e
0  2  2  6  1  3
1  9  6  1  0  1
2  9  0  0  9  3
3  4  0  0  4  1
4  7  3  2  4  7

df[df != 0] = 1
df
Out[13]:
   a  b  c  d  e
0  1  1  1  1  1
1  1  1  1  0  1
2  1  0  0  1  1
3  1  0  0  1  1
4  1  1  1  1  1

A: As an unorthodox alternative, consider
%timeit (df/df == 1).astype(int)
1000 loops, best of 3: 449 µs per loop
%timeit df[df != 0] = 1
1000 loops, best of 3: 801 µs per loop

As a hint what's happening here: df/df gives you 1 for any value not 0, those will be Inf. Checking ==1 gives you the correct matrix, but in binary form - hence the transformation at the end.
However, as dataframe size increases, the advantage of not having to select but simply operate on all elements becomes irrelevant - eventually you it becomes less efficient.

A: Thanks Marius. Also works on just one column when you want to replace all values except 1. Just be careful, this does it inplace
create column 280 from 279 for class {1:Normal,0:Arrhythmia}
df[280] = df[279]
df[280][df[280]!=1] = 0


Q: Magento 1 : Adminhtml block not called in my custom module I created a module to show the customer inquiries on product in admin grid.
From controller it is not directed to my block.Below is my code.
Config.xml
<config>
.....
<global>
    <blocks>
        <eight25media_requestquote>
            <class>Eight25media_Requestquote_Block</class>
        </eight25media_requestquote>
    </blocks>
..................
<admin>
    <routers>
        <adminhtml>
            <args>
                <modules>
                    <requestquote>Eight25media_Requestquote_Adminhtml</requestquote>
                </modules>
            </args>
        </adminhtml>
    </routers>
</admin>
..........
</config>

adminhtml.xml
<config>
<menu>
    <requestquote translate="title" module="requestquote">
        <title>Quotes</title>
        <sort_order>71</sort_order>
        <children>
            <quotemenus translate="title" module="requestquote">
                <sort_order>0</sort_order>
                <title>Manage Quotes</title>
                <action>adminhtml/quotes/</action>
            </quotemenus>
        </children>
    </requestquote>
</menu>
<acl>
    <resources>
        <admin>
            <children>
                <requestquote>
                    <title>Quotes</title>
                    <sort_order>60</sort_order>
                    <children>
                        <quotemenus translate="title">
                            <title>Manage Quotes</title>
                        </quotemenus>
                    </children>
                </requestquote>
            </children>
        </admin>
    </resources>
</acl>

QuotesController.php
class Eight25media_Requestquote_Adminhtml_QuotesController extends Mage_Adminhtml_Controller_action
{

    protected function _initAction()
    {
       $this->loadLayout();

       return $this;

     }

     public function indexAction() {

        $this->_title($this->__('Quotes'))->_title($this->__('Manage Quotes'));
        $this->loadLayout();
        $this->_setActiveMenu('requestquote/quotemenus');
        $this->_addContent($this->getLayout()->createBlock('requestquote/adminhtml_quotes'));
        $this->renderLayout();
     }

Block File : Quotes.php
<?php
class Eight25media_Requestquote_Block_Adminhtml_Quotes extends Mage_Adminhtml_Block_Widget_Grid_Container
{
public function __construct(){

    $this->_blockGroup = 'requestquote';
    $this->_controller = 'adminhtml_quotes';
    $this->_headerText = Mage::helper('requestquote')->__('Product Quote Collection');

    parent::__construct();
}
}

If i echo some thing in my block file nothing show and i am unable to access to my block file.What is the mistake i am doing here.

A: Based on your config.xml you have to change
->createBlock('requestquote/adminhtml_quotes')

to
->createBlock('eight25media_requestquote/adminhtml_quotes')

Or you change the definition of global/blocks to requestquote instead of eight25media_requestquote.


Q: Android - Python communication using zeroMQ With zeroMQ, is it possible to send ('Hello' message) from an Android app I created to a commandline running .recv() in python?
I made an android app with a button, once pressed it sends "hello" to the tcp://machine2:5555.
An extract of the button listener:
settingsButton.setOnClickListener(new OnClickListener(){
public void onClick(final View v) {
Toast toast = Toast.makeText(getApplicationContext(), "Playing video", Toast.LENGTH_SHORT);
toast.show();
            // insert SSH command for ffmpeg here
            ZMQ.Context ctx = ZMQ.context(1);
            Socket soc = ctx.socket(ZMQ.REQ);
            soc.connect("tcp://192.168.0.16:5555");

            //System.out.print("established");

            String msg = "hi";

            soc.send(msg.getBytes(),0);
        }
    });

The python receiver running in the terminal will display the message received.
import zmq
import time
import subprocess

port = "5555"

#first create a context for zeroMQ to begin communication
context = zmq.Context()

#pair communication
socket = context.socket(zmq.REP)

#bind ip address and port opened for communication
socket.bind("tcp://*:%s" % port)
print "tcp://192.168.0.16"
while True:
    msg = socket.recv()
    if msg is not None:
    print msg
    #run_command(msg)[0]
    #subprocess.call(["mplayer","/home/kevo/capture003.dv"])
    subprocess.call(["time", "mplayer","/home/kevo/Desktop/small.mp4"])
time.sleep(1)

But nothing shows on my terminal so far.


Q: Can I fire event only when user finishes modifying Text widget? I have an SWT Text control. I am trying to figure out how to listen for when the user is finished modifying the control, ie it is modified and then tabbed out of. I don't want my listener to be called every time a character changes in the textbox, and I don't want it to be called when the user traverses through the fields on the page. I only want it when the user modifies and then leaves the control.
I've looked at the various listeners available for the Text control, but unless I'm missing something, I don't see anything like this. Did I miss it?

A: It sounds like you are looking for a FocusListener.  The Text control inherits addFocusListener() etc. from Control, so check the inherited methods section of its API docs.

A: *

*Save the text content to a variable on focus gain, then on focus lost compare it with the latest text - if different then text is modified else not.

*This listener will not be called on each and every character change.

*If you simply traverse the controls(with TAB key) then also you can detect whether text is changed or not.
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class Snippet19 {
    private static String temp = "";

    public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new GridLayout());
    final Text text = new Text(shell, SWT.BORDER);
    text.setLayoutData(new GridData());
    text.addFocusListener(new FocusListener() {

        @Override
        public void focusLost(FocusEvent e) {
            if (temp.equals(text.getText())) {
                System.out.println("Text not modified");
            } else {
                System.out.println("Text conent modified");
            }

        }

        @Override
        public void focusGained(FocusEvent e) {
            temp = text.getText();

        }
    });
    final Text text1 = new Text(shell, SWT.BORDER);
    text1.setText("chandrayya");
    text1.setLayoutData(new GridData());
    final Text text2 = new Text(shell, SWT.BORDER);
    text2.setText("chandrayya");
    text2.setLayoutData(new GridData());
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
    }
}


Q: How to fit Cos function to a list of integers without shrinking the X or Y axis in Python? I have a list of numbers called img which has 400 numbers in it. Once I plot it, I can clearly see the cos pattern in it. Once I try to fit using optimize.curve_fit, the function is not able to fit correctly, unless I divide img by a large number and also shrink the X axis range. For example in the below code, rangeY and rangeX are the factors I use to shrink the list in both Y and X dimensions respectively.
In the first example you can see the fitting works perfectly:
import numpy as np
from scipy import optimize
import matplotlib.pyplot as plt

rangeY = 8000
rangeX = 3

def test_func(x, a, b, c, d):
    return a + b * np.cos(c * x + d)

def fitCurve (img):
    x_data = np.linspace(0,rangeX,num=400)
    y_data = []
    for i in range(0,len(img)):
        y_data += [img[i] / rangeY]
    y_data = np.array(y_data)

    param_bounds = ([-np.inf, 0, 0, -np.inf], [np.inf, np.inf, np.inf, np.inf])
    params, params_covariance = optimize.curve_fit(test_func, x_data, y_data,      bounds=param_bounds,maxfev=100000)
    y_curve = test_func(x_data, params[0], params[1], params[2], params[3])
    MSE = round(np.square(np.subtract(y_data, y_curve)).mean(), 5)
    return (params,y_curve,MSE,x_data,y_data)

img = [8452, 8421, 8498, 8521, 8427, 8523, 8667, 8196, 8515, 8110, 8551, 8732, 8189, 8429, 8539, 8360, 8622, 8726, 8529, 8412, 8465, 8497, 8724, 8201, 8804, 8990, 8732, 8985, 8671, 8675, 8450, 8959, 8865, 8665, 8776, 8822, 9230, 8749, 8758, 8849, 8753, 9108, 9100, 8964, 8808, 9352, 8786, 9070, 9359, 8895, 9131, 9117, 8994, 9087, 9352, 9163, 9073, 9190, 9277, 9073, 9276, 9413, 9395, 9223, 9353, 9420, 9462, 9512, 9512, 9571, 9580, 9595, 9593, 9639, 9622, 9647, 9710, 9710, 9725, 9758, 9785, 9814, 9831, 9862, 9889, 9902, 9921, 9941, 9964, 9992, 10050, 10091, 10131, 10131, 10133, 10179, 10177, 10164, 10241, 10291, 10332, 10332, 10316, 10332, 10332, 10333, 10340, 10333, 10333, 10368, 10385, 10391, 10391, 10403, 10439, 10454, 10428, 10407, 10428, 10459, 10480, 10523, 10530, 10539, 10556, 10562, 10586, 10606, 10592, 10612, 10621, 10621, 10587, 10587, 10574, 10574, 10574, 10574, 10587, 10594, 10584, 10597, 10598, 10599, 10606, 10677, 10620, 10620, 10677, 10677, 10633, 10633, 10620, 10633, 10619, 10619, 10619, 10619, 10599, 10599, 10599, 10621, 10616, 10621, 10621, 10616, 10593, 10635, 10582, 10521, 10514, 10484, 10474, 10468, 10456, 10475, 10481, 10481, 10426, 10413, 10386, 10380, 10370, 10370, 10365, 10363, 10336, 10336, 10322, 10318, 10275, 10299, 10275, 10299, 10299, 10275, 10275, 10272, 10264, 10250, 10201, 10184, 10182, 10178, 10176, 10176, 10136, 10178, 10163, 10163, 10170, 10170, 10111, 10147, 10081, 10081, 10074, 10055, 10055, 10063, 10063, 10055, 10030, 10013, 10013, 9958, 9905, 9872, 9864, 9855, 9855, 9864, 9896, 9899, 9899, 9900, 9901, 9923, 9901, 9843, 9836, 9830, 9830, 9810, 9802, 9801, 9783, 9760, 9761, 9739, 9760, 9739, 9712, 9771, 9771, 9734, 9722, 9675, 9632, 9632, 9610, 9624, 9610, 9579, 9597, 9570, 9579, 9555, 9519, 9519, 9517, 9517, 9516, 9516, 9495, 9480, 9428, 9426, 9408, 9408, 9379, 9379, 9391, 9379, 9358, 9327, 9319, 9304, 9297, 9280, 9280, 9288, 9271, 9288, 9297, 9295, 9246, 9246, 9240, 9267, 9246, 9222, 9187, 9169, 9154, 9139, 9100, 9074, 9101, 9101, 9100, 9076, 9074, 9101, 9104, 9116, 9140, 9143, 9133, 9106, 9081, 9090, 9081, 9077, 9067, 9079, 9093, 9093, 9082, 9082, 9079, 9076, 9025, 9017, 9006, 9006, 8991, 9015, 9015, 9006, 9039, 9063, 9096, 9106, 9120, 9120, 9120, 9096, 9113, 9078, 9071, 9078, 9102, 9102, 9117, 9117, 9117, 9117, 9125, 9126, 9145, 9164, 9170, 9178, 9190, 9237, 9265, 9265, 9245, 9251, 9245, 9245, 9251, 9239, 9260, 9267, 9267, 9267, 9259, 9277, 9277, 9261, 9261, 9261, 9286, 9272, 9266, 9266, 9313, 9329, 9313, 9313, 9331, 9328, 9335, 9335, 9385, 9406, 9406, 9403]

params, y_curve, MSE, x_data, y_data = fitCurve(img)
plt.figure(figsize=(6, 4))
plt.scatter(x_data, y_data, label='Data')
plt.plot(x_data, y_curve, color="red", label='Fitted function')
plt.legend(loc='best')
plt.show()

Now if I change rangeY to a smaller number such as 100, fitting does not work properly, so for the same code:
rangeY = 100
rangeX = 3

Or if I don't shrink the X axis (rangeX=400) it still doesn't fit properly:
rangeY = 8000
rangeX = 400

Now my question is: Is there any way to correctly fit the red curve on the blue dots without shrinking the Y and X axis range, or at least without shrinking the X axis?
If not, how should I find the right values for rangeX and rangeY?
Thanks

A: After digging into the manual of optimize.curve_fit, I figured out this needs a boundary limit for "c" in func. Because this parameter depends on the T of the curve so it definitely needs a limit. So here we are with the new set of limits and the nice fitting curve, kudos to myself :-)
rangeX = 400
rangeY = 8000
param_bounds = ([-np.inf, 0, 0, -np.inf], [np.inf, np.inf, 0.02, np.inf])


Q: Is there a way to search a field name in the design view of Table or Query? I heave a table with about 100 fields, when I want to edit a field I found a difficulty to visual search among such No. of fields.
The work around is copying one field to Excel then search on Excel for the specific field name, but if the layout view is not as design sort it is not helpful.
For queries I'm copying SQL code to Notepad or ms-word and do searches.
Is there a direct way to search a field name in the design view of a Table or a Query?

A: There is no built-in way for searching, but I use a free addon Access Dependency Checker. It has many useful features, shows table/query structure, highlights a found field position and allows to open objects in design mode.


Q: Authenticating guest/anonymous users using JWT I'm building an SPA that a user can upload some files. The front-end is written in AngularJS while the back-end is using an API in Laravel 5.7. The authentication is implemented using the jwt-auth library.
So far I have implemented this for registered users where each user has a personal directory on the server where he/she uploads the files. The difference between the registered and the anonymous users is that the files of the anonymous will be deleted after a while.
Now, I want to do the same for anonymous/guest users (if the press the button continue as a guest). So what I tried first in the authContrroller.php side is to use something like this:
public function authentication(Request $rrequest) {

    $credentials = $request->only('email', 'password');

    // Guest authentication
    if( $credentials['email'] === 'guest' && $credentials['password'] === 'guest' )
    {
        $payload = auth()->factory()->claims(['sub' => $this->createRandomDir()])->make();
        $token = auth()->manager()->encode($payload);

        // OR

        $factory = JWTFactory::customClaims([
            'sub'   => $this->createRandomDir(),
        ]);

        $payload = $factory->make();

        $token = JWTAuth::encode($payload);

    }
    // Registered user authentication authentication
    else
    {
        if (! $token = auth()->setTTL(60)->attempt($credentials))
            return response()->json(['error' => 'invalid_credentials'], 400);
    }

    return response()->json(compact('token'));
}

The idea was to create a random directory and enclose it inside the payload and use it on the next requests.
But in the case of the guest, the server returns as a token an empty object. Possibly because there wasn't a user in the DB.
Another idea that I'm thinking of is to create a random user (add it to the DB) and assign to it a random directory each time a user needs to use the app as guest/anonymous. The only thing that I'm afraid on that approach is that if there are thousands of guests then thousands random users should be created on the DB.
So what do you think? Is there any other and more efficient way to handle this?
Any idea is welcomed.


Q: Bounding the norm of matrix powers Given two square matrices $A$ and $C \in \mathbb{R}^{n \times n}$ and $\Vert A - C \Vert_2  \leq \beta$ $ \forall \beta \geq 0$, can we say anything about the upper bound of $\Vert A^ {k} - C^{k} \Vert_2$ interms of $\beta$ where $k \in \mathbb{Z^+}$.  Also what is the condition for $\rho(C) < 1$, given that $\rho(A) < 1$, where $\rho$ represents the absolute maximum eigen value (spetral radius)?

A: You can write
$$
A^k- C^k = (A-C)A^{k-1} + C(A-C)A^{k-2} + \dots = \sum_{j=0}^k C^j(A-C)A^{k-j-1}.
$$
Hence
$$
\|A^k-C^k\|_2 \le \|A-C\|_2 \sum_{j=0}^k \|C^j\|_2\|A^{k-j-1}\|_2.
$$


Q: Assigning to an array which is a member of struct This question may be a duplicate. But I am asking it again because the solution provided there dint help me compile the code error free.
I have a following code snippet
    #include<stdlib.h>

    using namespace std;

    void initgrid();

    struct gridblock
    {
        bool occ;
        double col[3];
        double trans[3];
    }grid[10][19];

    void initgrid()
    {
        grid[0][0].occ=false;
        grid[0][0].trans={-23.0,0.0,-24.0};
        ....
    }

    int main(int argc, char **argv)
    {
        initgrid();
        return 0;
    }

when I compile the above snippet with g++ <filename>.cpp -o test
I have been shown the following warning followed by an error

I am looking for a solution to overcome this. I have tried initializer_list and memcpy but that dint work. The line number 17 is grid[0][0].trans={-23.0,0.0,-24.0}

A: Ok, so firstly your initialisation is completely wrong! Secondly where is your declaration for your struct instance? Thirdly you are missing several semi-colons to close off statements, next you are accessing your arrays wrong, please look at my code ad work from that.
struct gridblock
{
    bool occ;
    double col[3];
    double trans[3];
}grid[10][19];

void initgrid(gridblock& grid[10][19])
{
    grid[0][0].trans[0] = 3.3;
    grid[0][0].trans[1] = 5.1;
    grid[0][0].trans[2] = 7.0;
    grid[0][0].occ = false;
    ....
}

int main(int argc, char **argv)
{
    gridblock grid;

    initgrid(grid);
    return 0;
}

I would also recommend going through a beginner C++ book to learn these fundamental concepts, I get the feeling you have jumped ahead to structs way to fast!

A: The problem is that you have not enabled the C++11 compiler switch.  That capability is new.  The warning you is telling you to enable the switch.  Changing the code won't help.  You have to change the configuration of your compiler.


Q: Why my error in subscirbe(()=>{},err=>{here}) is different from the error in browser console This is loadSize() function and it calls a getTotalNumberCampaigns() function in my campaignsService class.
 loadSize() {
    this.campaignsService.getTotalNumberCampaigns().subscribe(value => {//async call
        this.campaignSize = value;
    }, (err: any) => { console.log(err.status); console.log(err);}

    );
}

this is my getTotalNumberCampaigns()
 getTotalNumberCampaigns(): Observable<number> {
    return this.http.get(`${this.apiUrl}/Count`, { headers: this.headers })
        .map<any>(res => res.json())
}

I start up the backend api everything works fine, now I stop the api and refresh my page. It will fire the console.log(err.status); console.log(err); since it's connection failed. but I actually got 200 status while in my browser console it says it is a 502 error.
anyone tell me why?

A: In fact, in the case of a connection failure, the response object you receive in your error callback is an error one since the value of its type attribute is 3 (ERROR). What is a bit strange is that it seems that the preflighted request is executed and received a response. Could you give us its details from the Network tab in dev tools (by clicking on "OPTIONS http://localhost:...")?
See this question for more details:

*

*Get error message from Angular 2 http


Q: Long-polling amazon sqs with android and ios sdk How would someone achieve this with not using http requests (rest). Is this possible with the native sdks?
On android I am running a "every-2-second" iteration of a intent service call:
scheduleTaskExecutor= Executors.newScheduledThreadPool(10);
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
        public void run() {
            Intent i = new Intent(MainActivity.this, AzureServiceBusHttpService.class);
            i.setAction(AzureServiceBusHttpService.START_LONG_POOL);
            startService(i);
        }
    }, 0, 2, TimeUnit.SECONDS);

And on the service side (xxx is sensible data):
AWSCredentials credentials = new BasicAWSCredentials("xxx", "xxx");
AmazonSQSClient sqsClient = new AmazonSQSClient(credentials);

ReceiveMessageRequest rmr = new ReceiveMessageRequest("https://xxx.amazonaws.com/xxx/xxx";
rmr.setMaxNumberOfMessages(10);
rmr.setVisibilityTimeout(30);

ReceiveMessageResult result = sqsClient.receiveMessage(rmr);

if (result.getMessages().size() > 0) {
    EventBus.getDefault().post(new MsgEvent(result.getMessages().get(0).getBody()));

    DeleteMessageRequest rreq = new DeleteMessageRequest("https://xxx.amazonaws.com/xxx/xxx", result.getMessages().get(0).getReceiptHandle());
    sqsClient.deleteMessage(rreq);
}

I am wondering if this can be improved (reduced calls with long polling)?

A: Long poll with setWaitTimeSeconds(waitTimeSeconds)? Or switch from pull (via SQS) to push (via SNS)?


Q: Regex error c#? How i can use "/show_name=(.?)&show_name_exact=true\">(.?)

    Match m = Regex.Match(input, "/show_name=(.*?)&show_name_exact=true\">(.*?)</i", RegexOptions.IgnoreCase);
   // Check Match instance
    if (m.Success)
    {
        // Get Group value
        string key = m.Groups[1].Value;
        Console.WriteLine(key);
        // alternate-1
    }

Error, Unterminated string literal(CS1039)]
Error, Newline in constant(CS1010)]
What I am doing wrong?

A: I think you're mixing up .NET's regex syntax with PHP's.  PHP requires you to use a regex delimiter in addition to the quotes that are required by the C# string literal.  For instance, if you want to match "foo" case-insensitively in PHP you would use something like this:
'/foo/i'

...but C# doesn't require the extra regex delimiters, which means it doesn't support the /i style for adding match modifiers (that would have been redundant anyway, since you're also using the RegexOptions.IgnoreCase flag).  I think this is what you're looking for:
@"show_name=(.*?)&show_name_exact=true"">(.*?)<"

Note also how I escaped the internal quotation mark using another quotation mark instead of a backslash.  You have to do it that way whether you use the old-fashioned string literal syntax or C#'s verbatim strings with the leading '@' (which is highly recommended for writing regexes).  That's why you were getting the unterminated string error.


Q: What does `pr -e` mean? From coreutils' manual about pr:

‘-e[in-tabchar[in-tabwidth]]’
‘--expand-tabs[=in-tabchar[in-tabwidth]]’

Expand tabs to spaces on input. Optional argument in-tabchar is the
  input tab character (default is the TAB character). Second optional
  argument in- tabwidth is the input tab character’s width (default is
  8).

Does -e[in-tabchar[in-tabwidth]] mean to replace each in-tabchar with in-tabwidth number of whitespaces?
In the following two examples, why are a, b and c separated by one whitespace, while 1 and 3 by three whitespaces in the first example, and two whitespaces in the second example? Thanks.
$ printf "a:b:c\n1::3\n" | pr -t -e:2
a b c
1   3

$ printf "a:b:c\n1::3\n" | pr -t -e:1
a b c
1  3

A: pr -e does the same job as the expand command. It expands tabs in a similar way as your terminal emulator typically would. TAB is a control character which terminals understand as moving the cursor to the next tab-stop, it is meant for tabular formatting and alignment.
On most terminals, tab stops by default are every 8 columns. So sending them a TAB will have the same effect as sending a number of spaces ranging from 1 to 8 depending on the current cursor position:
 $ printf '%b\n' 'a\tb' 'abcde\tg'
 a       b
 abcde   g

The first tab moved the cursor 7 columns to the right, the second 3 columns to the right.
pr -e would replace those \t with as many spaces as necessary to have the same effect:
$ printf 'abcde\tg\n' | sed l
abcde\tg$
abcde   g
$ printf 'abcde\tg\n' | pr -te | sed l
abcde   g$
abcde   g

Note that GNU pr suffers from the same limitation as GNU expand in that it  assumes all characters are made of one byte and take one column to display.


Q: Longest Common Subsequence of Three Sequences I've implemented my version of Longest Common Subsequence of Three Sequences and cannot find a mistake. But Coursera grader says that I fail last test case.
It means that the algorithm is almost corrects but outputs a wrong answer in a specific case. But what case is it?
Constraints: length of the list is not less than one and not bigger than 100. Numbers in the lists are integers from -10^9 to 10^9.
import sys

def lcs3(a, b, c):
    start_b = 0
    start_c = 0
    result = []
    for i in range(len(a)):
        for j in range(start_b, len(b)):
            if a[i] == b[j]:
                for k in range(start_c, len(c)):
                    if b[j] == c[k]:
                        start_b = j+1
                        start_c = k+1
                        result.append(a[i])
                        break
                if b[j] == c[k]:
                    break
    return len(result)

def lcs3_reversed(a,b, c):
    # check reversed sequence which can be with different order
    a_rev = a[::-1]
    b_rev = b[::-1]
    c_rev = c[::-1]
    result = lcs3(a, b, c)
    result_reversed = lcs3(a_rev, b_rev, c_rev)
    if result == result_reversed:
        return result
    else:
        return result_reversed

if __name__ == '__main__':
    input = sys.stdin.read()
    data = list(map(int, input.split()))
    an = data[0]
    data = data[1:]
    a = data[:an]
    data = data[an:]
    bn = data[0]
    data = data[1:]
    b = data[:bn]
    data = data[bn:]
    cn = data[0]
    data = data[1:]
    c = data[:cn]
    print(lcs3_reversed(a, b, c))

Update: added the function lcs3_reversed to solve the cases described by you. Anyway cannot pass the test case.
Output should contain the length of common subsequence. For example, for input:
3
1 2 3
3
2 1 3
3
1 3 5

output is 2 because the common part is (1, 3) for these 3 lists.
Runtime for failed case is 0.04 seconds and it looks like that the lists are rather long since most of my own tests worked much faster.
Thanks for your help!
Update2: I've tried another version. First we find the Longest Common Subsequence of 2 lists and then use it again on our result and the 3-rd list.
def lcs2(a, b):
    start_b = 0
    result = []
    for i in range(len(a)):
        for j in range(start_b, len(b)):
            if a[i] == b[j]:
                start_b = j+1
                result.append(a[i])
                break
    return result

def lcs2_reversed(a, b):
    # check reversed sequence which can be with different order
    a_rev = a[::-1]
    b_rev = b[::-1]
    result_reversed = lcs2(a_rev, b_rev)[::-1]
    return result_reversed

def lcs3_reversed(a, b, c):
    lcs2_str = lcs2(a, b)
    lcs2_rev = lcs2_reversed(a, b)
    lcs3_str_str = lcs2(lcs2_str, c)
    lcs3_rev_rev = lcs2_reversed(lcs2_rev, c)
    lenghts = [len(lcs3_str_str), len(lcs3_rev_rev)]
    return max(lenghts)

if __name__ == '__main__':
    an = input()
    a = input().split()
    bn = input()
    b = input().split()
    cn = input()
    c = input().split()
    print(max(lcs3_reversed(a, b, c), lcs3_reversed(a, c, b), lcs3_reversed(b, a, c),
              lcs3_reversed(b, c, a), lcs3_reversed(c, a, b), lcs3_reversed(c, b, a)))

Moreover, I tried all the combinations of orders but it did not help... Again I cannot pass this last test case.

A: Your example breaks with something like:
a = [1,2,7,3,7]
b = [2,1,2,3,7]
c = [1,2,3,1,7]

The sequence should be [1,2,3,7] (if I understand the exercise correctly), but the problem is that the last element of a gets matched to the last elements of b and c, which means that start_b and start_c are set to the last elements and therefore the loops are over.


Q: WPF DataGrid Last column not resizing properly I am using a DataGrid control to display some data and the last comun of the grid does not resize appropriately when the grid receives new data. When the grid loads is completely empty and data gets inserted after some user input. All other columns of the Grid behave as supposed to, any ideas of what I should do to make the last column resize?
My DataGrid XAML:
<DataGrid Grid.Row="4" Grid.Column="0" Margin="4,4,4,4" ItemsSource="{Binding Order.OrderItems}" CanUserReorderColumns="True"
              SelectedItem="{Binding OrderItem}" Height="200" AutoGenerateColumns="False" CanUserSortColumns="True"
              SelectionMode="Single" VerticalScrollBarVisibility="Auto" CanUserAddRows="False">
        <DataGrid.Columns>
            <DataGridTextColumn Header="SKU" Binding="{Binding SellerCode}"/>
            <DataGridTextColumn Header="Description" Width="*" Binding="{Binding Description}"/>
            <DataGridTextColumn Header="Quantity" Binding="{Binding Quantity}"/>
            <DataGridTextColumn Header="Net Cost" Binding="{Binding UnitCost, StringFormat='£ #,##0.00'}"/>
            <DataGridTextColumn Header="Total Cost" Binding="{Binding TotalCost, StringFormat='£ #,##0.00'}"/>
            <DataGridTextColumn Header="Gross" Binding="{Binding TotalCostWithVat, StringFormat='£ #,##0.00'}" Width="auto"/>
        </DataGrid.Columns>
    </DataGrid>

Thanks


Q: Defining dictionary inside a class in python I am creating an empty dictionary inside a class and then I am trying to give the variables inside the dictionary some value. As shown in the code below. In the end, I am trying to print the dictionary values in the console but I receiving errors
In the editor:
import numpy as np
class A:
    def __init__(self, variables = {}):
        self.variables = {}
        if ("leng") in variables:
            self.variables["leng"] = variables["leng"]
        else:
            self.variables["leng"] = np.array([10,])

        if ("width") in variables:
            self.variables["width"]= variables["width"]
        else:
            self.variables["width"] = np.array([10,])

In the Console:
variables.items()

>>>"leng" : 10
>>>"width" : 10

A: Just use an object to call class items.
m=A() and then m.variables


Q: Separate Socket.io into app.js I'm working on my Express project right, currently I have app.js, socket folder where are my sockets , but all my logic is in bin/www since Im using sockets in my routes like this:
 req.io.emit('dataUpdated', { id: client });

but I would like to seperate it into app.js how could I do that without breaking my app.
here is my www file:
var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var config = require('../config.json');
var appRoutes = require('./routes/Approutes');

var app = express();

app.use(express.static(path.join(__dirname, '../public')));

mongoose.Promise = global.Promise;
mongoose.connect('localhost/db_test');

app.set('views', path.join(__dirname, '../views'));
app.set('view engine', 'hjs');

app.set('appProperties', {
  secret: config.secret
});

var siofu = require("socketio-file-upload");
app.use(siofu.router);

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

var debug = require('debug')('express-seed:server');
var server = require('http').Server(app);

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
 * Set socket
 */

var socketioJwt = require('socketio-jwt');
var socketIo = require('socket.io');
var io = socketIo.listen(server);

io.use(socketioJwt.authorize({
   secret: config.secret,
   handshake: true
}));

app.io = io;
app.use(function(req, res, next) { 'use strict'; req.io = io; next(); });

app.use('/', appRoutes);

require('../sockets/user')(io);

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}

my app.js file is empty...
and my socket file
exports = module.exports = function (io) {
 io.sockets.on('connection', (socket) => {
   socket.on('clientGetList', (req) => {
// getting clientList
});
})
}

How can I move my logic from www file to app.js file without breaking the app?

A:
I would like to move my middleware, and socket connection to app.js and in www just to start server

You can separate the code like this and pass both app and server variables to your app.js module where it can run the rest of the initialization code (middleware, routes, socket.io setup, etc...):
// www
const express = require('express');
const app = express();

const server = require('http').Server(app);

const port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

// load app.js and let it do it's part of the initialization of app and server
require('./app.js')(app, server);

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}

And, then this would be an outline for app.js:
const bodyParser = require('body-parser');
const siofu = require("socketio-file-upload");
const config = require('../config.json');
const appRoutes = require('./routes/Approutes');
const socketioJwt = require('socketio-jwt');
const socketIo = require('socket.io');

// export one function that gets called once as the server is being initialized
module.exports = function(app, server) {
    app.set('views', path.join(__dirname, '../views'));
    app.set('view engine', 'hjs');

    app.set('appProperties', {
      secret: config.secret
    });

    app.use(siofu.router);

    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));

    var io = socketIo.listen(server);

    io.use(socketioJwt.authorize({
       secret: config.secret,
       handshake: true
    }));

    app.io = io;
    app.use(function(req, res, next) { 'use strict'; req.io = io; next(); });

    app.use('/', appRoutes);

    require('../sockets/user')(io);

}


Q: Como iniciar um array noutra classe - java Estou a tentar implementar o algoritmo depth first  para resolver um labirinto, como o abaixo, em que a posição inicial é S e a saída é E
_SW______\n
_WWW_W_WW\n
_____W__E\n

Na classe MazeReader eu leio o ficheiro .txt para o array Maze que depois deveria ter o seu conteudo importado para a classe Depth first
public class MazeReader extends JFrame  {
private static char[][] Maze;
private static ArrayList<String> mazeBuffer;
private static int startrow,startcol,finishcol,finishrow;
private final List<Integer> path = new ArrayList<Integer>();
private int pathIndex;

public MazeReader() {
    setTitle("Maze");
    setSize(640,480);
    setLocationRelativeTo(null);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    DepthFirst.searchPath(Maze, 0, 1, path);
    pathIndex = path.size() - 2;
}

public static void readTextFile(String filename) throws MazeFileWrongChar, MazeFileNumCols {
    startrow=startcol=finishcol=finishrow=-1;
    mazeBuffer=new ArrayList<String>();
    int numCols=0;
    try {
        Scanner file=new Scanner(new File(filename));
        while(file.hasNext()) {

            String nextLine=file.nextLine().replace("\\n", "");
            mazeBuffer.add(nextLine);
            if(nextLine.length()>numCols) {
                numCols=nextLine.length();
            }

        }
    }catch(Exception e) {
        System.out.println(filename + "there is a problem");
    }
    int numrows=mazeBuffer.size();
    System.out.println("number of rows: "+ numrows +  "\nnumber of columns: " + numCols);
    Maze=new char[numrows][numCols];
    for(int i=0;i<numrows;i++) {
        String row = mazeBuffer.get(i);
        for (int j = 0; j < numCols; j++) {

            try {
                    Maze[i][j] = row.charAt(j);

            } catch (Exception e) {
                throw new MazeFileNumCols(j);

            }

            if(Maze[i][j]!=('S') && Maze[i][j]!=('W') && Maze[i][j]!=('_') && Maze[i][j]!=('E') && Maze[i][j]!=(' ') ) {
                throw new MazeFileWrongChar(i,j);

            }

        }
    }

}

Em baixo o código da classe depth first
public class DepthFirst {
public static boolean searchPath(char[][] maze,int x,int y, List<Integer> path) {
    if(maze[y][x]=='E') {
        path.add(x);
        path.add(y);
        return true;
    }
    if(maze[y][x]=='_') {

        int dx=-1;
        int dy=0;
        if(searchPath(maze,x+dx,y+dy,path)) {
            path.add(x);
            path.add(y);
            return true;
        }

        dx = 1;
        dy = 0;
        if (searchPath(maze, x + dx, y + dy, path)) {
            path.add(x);
            path.add(y);
            return true;
        }

        dx = 0;
        dy = -1;
        if (searchPath(maze, x + dx, y + dy, path)) {
            path.add(x);
            path.add(y);
            return true;
        }

        dx = 0;
        dy = 1;
        if (searchPath(maze, x + dx, y + dy, path)) {
            path.add(x);
            path.add(y);
            return true;
        }
    }
    return false;
    }
    }

Aqui está a classe main
public class Main {
static MazeReader reader = new MazeReader();

public static void main(String[] args) throws MazeFileWrongChar,MazeFileNumCols {
    try {
        MazeReader.readTextFile("maze.txt");
        reader.printMaze();
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                MazeReader view = new MazeReader();
                view.setVisible(true);
            }
        });

    } catch (MazeFileWrongChar e ) {
        System.out.println(e.getMessage());
    } catch(MazeFileNumCols e) {
        System.out.println(e.getMessage());
    }
}
}

Estou a obter o seguinte erro:
Exception in thread "main" java.lang.ExceptionInInitializerError
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:264)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:123)
Caused by: java.lang.NullPointerException
    at DepthFirst.searchPath(DepthFirst.java:10)
    at MazeReader.<init>(MazeReader.java:23)

Mas estou a ter o erro NullPointerException porque supostamente o array Maze não está a ser inicializado corretamente, alguma forma de o conseguir fazer?


Q: do "search domain" in networkd configuration and LLMNR conflict? in networkd man page, the search domains are used to handle single-label names:
The domains without the prefix are called "search domains" and are first used as search suffixes for extending single-label host names (host names containing no dots) to become fully qualified domain names (FQDNs). If a single-label host name is resolved on this interface, each of the specified search domains are appended to it in turn, converting it into a fully qualified domain name, until one of them may be successfully resolved.
Both "search" and "routing-only" domains are used for routing of DNS queries: look-ups for host names ending in those domains (hence also single label names, if any "search domains" are listed), are routed to the DNS servers configured for this interface.
I wonder if a single-label name lookup request is handled by LLMNR or by the specified dns severs or both?

A: A single-label name is only handled by LLMNR, if solved.
If not solved, each of the list of words in Domains=:
Domains=domainA.example domainB.example ~example

is added at the end of the single-label and an attempt to resolve it is done. If it gets resolved at any trial, that is the end, if not resolved, try with the next word.
To resolve, different name resolution resources might be used: Avahi, resolved, LLMNR, or (usually at last) several DNS servers.


Q: How to get the same date result from Model.objects.create and Model.objects.get in Django? Given the following Django model:
from django.db import models

class SomeModel(models.Model):
    date = models.DateField()

When I create an object with following code, type of date field is unicode
obj = SomeModel.objects.create(date=u'2015-05-18')

But when I get the same object from database, type of date field will be datetime.date
obj = SomeModel.objects.get(pk=obj.pk)

I know Django will transform u'2015-05-18' to a datetime.date object automatically, but why it returns the original unicode string with Model.objects.create()? is there a way to always get datetime.date from Model.objects.create() and Model.objects.get()?

A: Simply pass an datetime  object to the create method:
from datetime import date
obj = SomeModel.objects.create(date=date(2015, 5, 18))

or
obj = SomeModel.objects.create(date=date.strftime('2015-05-18', '%y-%m-%d'))

A: There are two ways Django transforms the data in a model. The first, when saving the model the data is transformed to the correct data type and send to the backend. The data on the model itself is not changed. The second, when the data is loaded from the database, it is converted to the datatype that Django thinks is most appropriate.
This is by design: Django does not want to do any magic on the models itself. Models are just python class instances with attributes, so you are free to do whatever you want. This includes using the string u'2015-05-18' as a date or the string 'False' to store as True (yeah that's right).
The database cannot store dates as arbitrary data types, so in the database it is just the equivalent of a Python date object. The information that it used to be a string is lost, and when loading the data directly from the database with get(), the data is consistently converted to the most appropriate Python data type, a date.


Q: TestNG runner when using @DataProvider combined with apache poi does not execute tests sequentially EDIT: I have an ExcelUtility.java class to get cell data from it and pass it on to the tests methods in my test class.
I am reading from 1 excel file.
The excel file has 3 worksheets.
Every worksheet has 1 unique working table inside.
I have 1 Test class.
The test class has 3 test methods.
The test class contains 3 dataProviders.
All dataProviders differ in the worksheet name and working table name.
The tests in the test class are written in the following manner:
  @Test(priority = 0, dataProvider = "dp1")
    public void test01(String...strings){
 }
 @Test(priority = 1, dataProvider = "dp2")
    public void test02(String...strings){
 }
 @Test(priority = 2, dataProvider = "dp3")
    public void test03(String...strings){
}

I have the following java class to read from XLSX file using apache poi jars:
public class ExcelUtility {

        private static XSSFWorkbook ExcelWBook;
        private static XSSFSheet ExcelWSheet;

        /*
         * Set the File path, open Excel file
         * @params - Excel Path and Sheet Name
         */
        public static void setExcelFile(String path, String sheetName) throws Exception {
            try {
                // Open the Excel file
                FileInputStream ExcelFile = new FileInputStream(path);

                // Access the excel data sheet
                ExcelWBook = new XSSFWorkbook(ExcelFile);
                ExcelWSheet = ExcelWBook.getSheet(sheetName);
            } catch (Exception e) {
                throw (e);
            }
        }

        public static String[][] getTestData(String tableName) {
            String[][] testData = null;

            try {
                // Handle numbers and strings
                DataFormatter formatter = new DataFormatter();
                XSSFCell[] boundaryCells = findCells(tableName);
                XSSFCell startCell = boundaryCells[0];

                XSSFCell endCell = boundaryCells[1];

                int startRow = startCell.getRowIndex() + 1;
                int endRow = endCell.getRowIndex() - 1;
                int startCol = startCell.getColumnIndex() + 1;
                int endCol = endCell.getColumnIndex() - 1;

                testData = new String[endRow - startRow + 1][endCol - startCol + 1];

                for (int i=startRow; i<endRow+1; i++) {
                    for (int j=startCol; j<endCol+1; j++) {
                        // testData[i-startRow][j-startCol] = ExcelWSheet.getRow(i).getCell(j).getStringCellValue();
                        Cell cell = ExcelWSheet.getRow(i).getCell(j);
                        testData[i - startRow][j - startCol] = formatter.formatCellValue(cell);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return testData;
        }

        public static XSSFCell[] findCells(String tableName) {
            DataFormatter formatter = new DataFormatter();
            String pos = "begin";
            XSSFCell[] cells = new XSSFCell[2];

            for (Row row : ExcelWSheet) {
                for (Cell cell : row) {
                    // if (tableName.equals(cell.getStringCellValue())) {
                    if (tableName.equals(formatter.formatCellValue(cell))) {
                        if (pos.equalsIgnoreCase("begin")) {
                            cells[0] = (XSSFCell) cell;
                            pos = "end";
                        } else {
                            cells[1] = (XSSFCell) cell;
                        }
                    }
                }
            }
            return cells;
        }
    }

In order to read from the excel file I have organized the test methods in the following manner:
@DataProvider(name = "dp1")
    public Object[][] dp1() throws IOException {
        Object[][] testData = new Object[0][];
        try {
            ExcelUtility.setExcelFile(Constants.File_Path+Constants.File_Name, "Page1");
            testData = ExcelUtility.getTestData("P1");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return testData;
    }
    @DataProvider(name = "dp2")
    public Object[][] dp2() throws IOException {
        Object[][] testData = new Object[0][];
        try {
            ExcelUtility.setExcelFile(Constants.File_Path+Constants.File_Name, "Page2");
            testData = ExcelUtility.getTestData("P2");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return testData;
    }
    @DataProvider(name = "dp3")
    public Object[][] dp3() throws IOException {
        Object[][] testData = new Object[0][];
        try {
            ExcelUtility.setExcelFile(Constants.File_Path+Constants.File_Name, "Page3");
           testData = ExcelUtility.getTestData("P3");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return testData;
    }
    @Test(priority = 0, dataProvider = "dp1")
    public void test01(String...strings){
 //read data from excel and pass the value to the strings added as arguments in the method above
 }

 @Test(priority = 1, dataProvider = "dp2")
    public void test02(String...strings){

 }

 @Test(priority = 2, dataProvider = "dp3")
    public void test03(String...strings){

 }

What I would like to do is the following:

*

*Read first row data from sheet1, pass it to test1, continue to test2

*Read first row data from sheet2, pass it to test2, continue to test3

*Read first row data from sheet3, pass it to test3, continue to test1

*Read second row data from sheet 1, pass it to test1, continue to test2
And so on, depending of number of rows in the excel sheets.
What happens is:
The first test is executed, reads worksheet 1, row 1.
The first test is executed, reads worksheet 1, row 2.
The second test is executed, reads worksheet 2, row 1.
The second test is executed, reads worksheet 2, row 2.
All tests fail because they are dependable from each other, that is why I set execution priority.
Should I change something in the Test class, or something in the ExcelUtility.java class should be changed?
Thank you in advance!

A: TestNG allows you to specify ordering of tests with several approaches. However, you are doing something that does not align with unit testing methodology.
You should re-write your tests to perform a series of checks on the test data. What you call test1 and test2 are actually assertion1 and assertion2.
@Test(dataProvider = "dp1")
public void newTest1(String dp1) throws Exception {
  assertion1(dp1);
  assertion2(dp1);
}

@Test(dataProvider = "dp2")
public void newTest2(String dp2) throws Exception {
  assertion2(dp2);
  assertion3(dp2);
}

With this approach, the tests can be executed in any order. While you thought of the data being handled in a pipeline, that is not how unit testing frameworks operate.
You are also not constrained to have only a single assertion in a unit test. If there are religious zealots reviewing your code, then I would suggest composing those assertion methods into assertion1and2, etc, so that the test itself appears to make only one assertion.


Q: Remove top and bottom margins around listings When using the lstlisting environment, or similar ones from the listings package, there are paragraph-like margins above and below the actual text.  This makes sense in a paper, but gets in the way if you try to put code inside a Tikz node (e.g., for a Beamer presentation):
 \node[inner sep=1mm, text width=6cm, draw=green, line width=2pt, rounded corners]
  {%
    \lstinputlisting[basicstyle=\tiny\ttfamily, columns=fullflexible]{alt1.java}
  };

(Do ignore the question of why I put this jumbled code in a node...)
As you can see there are top and bottom margins that add extra redundant space to the node.
How can I remove these margins?  I suppose it is some lstset option, but I couldn't find it.

A: The space above and below the listing can be set using aboveskip and belowskip. The default value is \medskipamount.

\documentclass{article}

\usepackage{tikz}
\usepackage{listings}

\begin{document}
\tikz \node[inner sep=1mm, text width=6cm, draw=green, line width=2pt, rounded corners]
  {%
    \lstinputlisting[basicstyle=\tiny\ttfamily, columns=fullflexible, breaklines=true,aboveskip=0pt,belowskip=0pt]{data.txt}
  };
\end{document}


Q: Issue Initializing select2 dynamically Select2 initializes for the first item generated with on click and then on generating new div item with on click the select2 property is removed from the first item and initializes on the 2nd.
$(document).ready(function(){

$("#packages #add_package").on("click", function(){
  $(this).before(
    "
"+

        "
"+
          "
"+
            "Container Type"+
            "<select name='cntType' id='cntType' class='form-control select2' data-dropdown-css-class='select2' style='width: 100%;'>"+
              "<option value='0' selected='selected' disabled>Select Container Type</option>"+
              "<option>20 feet</option>"+
              "<option>40 feet</option>"+
            "</select>"+
        "
"+
      "
"+

  "
");
  $('.select2').select2();

  });
})

A: If you check your browser's devtools console, you will see a Javascript error thrown when you try to add the second select2:

Uncaught query function not defined for Select2 undefined

If you search for that error, you will find some other questions about this, for eg this one: "query function not defined for Select2 undefined error"
And if you read through the answers and comments, you will find several which describe what you are doing:

*

*This comment:

This problem usually happens if the select control has already been initialized by the .select2({}) method. A better solution would be calling the destroy method first. Ex: $("#mySelectControl").select2("destroy").select2({});

*

*This answer:

One of its other possible sources is that you're trying to call select2() method on already "select2ed" input.

*

*Also this answer:

I also had this problem make sure that you don't initialize the select2 twice.

... and possibly more.  These describe what you are doing - calling .select2() on elements which are already initialised as select2s.
The second time $('.select2').select2() runs, as well as trying to initialise your new select2, it is re-initialising the first select2 as a select2 again.
You have another problem in your code - every select has the same ID: id='cntType'.  IDs must be unique on the page, so this is invalid HTML.
We can solve both problems at once by keeping track of how many selects you have on the page, and giving each new one an ID including its number, like say cntType-1, cntType-2, etc.  Then we can target just the new ID to initialise it as a select2.
Here's a working example.

$(document).ready(function () {

    // Track how many selects are on the page
    let selectCount = 0;

    $("#packages").on("click", function () {

        // New select!  Increment our counter
        selectCount++;

        //. Add new HTML, using dynamically generated ID on the select
        $(this).before(
            "
" +
            "
" +
            "
" +
            "Container Type" +
            "<select name='cntType' id='cntType-" + selectCount + "' class='form-control select2' data-dropdown-css-class='select2' style='width: 100%;'>" +
            "<option value='0' selected='selected' disabled>Select Container Type</option>" +
            "<option>20 feet</option>" +
            "<option>40 feet</option>" +
            "</select>" +
            "
" +
            "
" +
            "
");

        // Initialise only our new select
        $('#cntType-' + selectCount).select2();
    });
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.0.0/select2.css" rel="stylesheet" />

<button id="packages">Add</button>


Q: Visual Studio / Properties / Debug / Working Directory want it permanent but don't want to check in the *.user file The project setting Debugging / Working Directory in Visual Studio 20015 will be saved by default in the *.user file wich I don't check in in to my repo because it's user specific. Still, I would like to have something other than $(ProjectDir) standing there when I do a clean checkout of my project. Is there an other place to store the Working Directory besides the *.user file?
Edit 1: The original idea is that I have a solution with multiple projects and all the binaries (dlls and exes) created end up in a folder called bin. If I want to debug it, I don't want to always edit the working directory again after a clean checkout.
Edit 2: In a post build step of every project within my solution, I copy the binaries in to the bin folder. If I start one of the executables from within VS, it starts them from the $(ProjectDir) folder, and of course not from the bin folder. This is why it does not find the dlls and why I want to set the working directory. I could change the output directory of my projects but then I get a lot of files ending up in the bin folder I don't want there. I will try it anyway; maybe I missed something. To be continued...
Edit 3: As expected, if I change the output directory to the bin folder, everything works fine except for some extra files that end up there and I don't want that (e.g. *.pbo, which would be okay, *.iobj, *.ipdb, etc.) Maybe that is the price I have to pay, but I don't like it.
So, the question remains: How can I have more control over which file ends up where after a build and still be able to run it from VS without changing the working dir?

A: The working directory should not have to be the directory that contains your DLLs. In fact, you definitely don't want that to be a requirement for running your application. Not only is it a hugely unexpected failure mode, but it could also be a potential security risk.
Put the required DLLs in the same directory as your application's executable. That's the first place that the loader will look. If necessary, use a post-build event in your library projects to copy them there.

A: Well since no body can help me I decided that I will change the output directory to the bin folder so VS will start my applications from the correct folder.
And how I can get rid of all the extra files that don't belong there I will find a way later.


Q: Retrieving the last record in each group - MongoDB There is a collection of items with the following fields:
id   item_id  quantity    last_update
-------------------------------------------
1    111         10        2020-02-10 09:00:00
2    222         10        2020-02-10 09:00:00
2    222         15        2020-02-10 10:00:00

I want to retrieve the last updated record , for each group by id and item_id .
The results should be:
id   item_id  quantity    last_update
-------------------------------------------
1    111         10        2020-02-10 09:00:00
2    222         15        2020-02-10 10:00:00

If it was SQL , then i would do something like:
SELECT a.* FROM items a JOIN
( SELECT id ,item_id , max(last_update) as max_last_update
FROM items ) as b ON a.id=b.id AND a.item_id=b.item_id AND a.last_update=b.max_last_update

(or using self join) .
I'm new to mongoDB  , I did the inner query like:
inner_query = db.items.aggregate({ $group : { _id: {id:"$id" , item_id:"$item_id"}, max_last_update: { $max : "$last_update" }}})

How can I use inner_query var to get the expected results?
What is the equivalent in Mongo to JOIN or subquery?
(i'm using mongodb 4.0.4)
Thanks!

A: Try this one:
db.collection.aggregate([
   { $sort: { id: 1, item_id: 1, last_update: -1 } },
   {
      $group: {
         _id: { id: "$id", item_id: "$item_id" },
         last_update: { $max: "$last_update" },
         quantity: { $first: "$quantity" },
      }
   },
   {
      $project: {
         last_update: 1,
         quantity: 1,
         id: "$_id.id",
         item_id: "$_id.item_id",
         _id: 0
      }
   }
])

Note, make proper $sort, otherwise $frist will return wrong value.


Q: Fastest and efficient way to update mysql data I have 2 db tables:
Tbl1:

*

*user_id

*item_id

*qty

*date_purchase

Tbl2 (summary of table 1):

*

*user_id

*item_id

*number_of_qty_purchased

*last_purchase

For now I have only a few thousands of Tbl1. My concern is the scalability of my current approach (retrieve and manually loop on program level, then update the Tbl2) What is the best way to update Tbl2?
Best regards.

A: You don't need table 2 at all.
You can determine what you're after from table 2 by querying table 1.

*

*Number purchased of any item:

Select sum(qty) from table_1 where item_id = [id of your item] and user_id = [id of your user];

*

*Last purchased date of given item for given user

select max(date_purchase) from table_1 where item_id = [id of your item] and user_id = [id of your user];
Also, remember to add indexes to table 1 so that your querying is as fast as possible.


Q: $ (dollar) sign in front of a class method name? In Mage_Sales_Model_Order_Payment::_void(), there is a $ sign placed like below.
$this->getMethodInstance()->setStore($order->getStoreId())->$gatewayCallback($this);

What is this doing?

A: https://github.com/LokeyCoding/magento-mirror/blob/magento-1.8/app/code/core/Mage/Sales/Model/Order/Payment.php#L1139-L1141
There is an argument $gatewayCallback passed to the _void method, this argument is a string.
So when you see something like this: $object->$variable();
and $variable = 'foo';
The following code is called: $object->foo();
In this case it calls the void method of the payment gateway by default (as you can see in the function definition).


Q: I am trying to get json data from bitbns.com but getting an error I am very new to javascript and I am trying to get json data from bitbns but getting error
  - "(Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘https://www.bitbns.com’)."
I searched a lot on internet but could not find any solution.
<script>

url="https://www.bitbns.com/order/getTicker";
var request = new Request(url);

fetch(request, {mode: "cors",
}).then(function(response) {
       return response.json();
    }).then(function(j) {
       console.log(JSON.stringify(j));
    }).catch(function(error) {
        console.log('Request failed', error)
    });
console.log(request.headers)
</script>

Can anyone help me with this at all?

A:

var proxyUrl = 'https://cors-anywhere.herokuapp.com/'
var url="https://www.bitbns.com/order/getTicker";
let x = proxyUrl + url
fetch(x, {mode: "cors",
}).then(function(response) {
       return response.json();
    }).then(function(j) {
       console.log(JSON.stringify(j));
    }).catch(function(error) {
        console.log('Request failed', error)
    });

This will get things rolling, but it is better not to use this for production due to lack of security.
https://cors-anywhere.herokuapp.com/ is a link that add cors header.

A: Here is what i found on https://www.sencha.com/forum/showthread.php?299915-How-to-make-an-ajax-request-cross-origin-CORS
$.ajax({
            url: 'http:ww.abc.com?callback=?',
            dataType: 'JSONP',
            jsonpCallback: 'callbackFnc',
            type: 'GET',
            async: false,
            crossDomain: true,
            success: function () { },
            failure: function () { },
            complete: function (data) {
                if (data.readyState == '4' && data.status == '200') {
                    errorLog.push({ IP: Host, Status: 'SUCCESS' })
                }
                else {
                    errorLog.push({ IP: Host, Status: 'FAIL' })
                }
            }
        });


Q: How to filter data using Linq in List I am calling stored procedure to get data from database using Linq. This stored procedure is using more than one table to return result using join :
public static List<classname> GetMediaTemp()
{
var medialist = (from m in Context.sp_Temp() select new classname
                                            {
                                               str_image = m.str_image,
                                                str_image_type = m.str_image_type,
                                                str_photodrawvideo = m.str_photodrawvideo,
                                            }).ToList();
if (medialist.Count > 0)
{
   return medialist
}
}

Everything working fine but now i have to filter data in this object list like on the calling end
List<classname> photoList = GetMediaTemp();//Here i want to filter list on the basis on str_photodrawvideo column.

Problem :
How i can perform this filter ?
Thanks in Advance. For more info please let me know.

A: you can do as below
var objList = Context.sp_Temp().ToList();
var photoList = objList.Where(o=>o._int_previous == 1).ToList();

Or
you can cast the object to Class which build the object list as below
var photoList =
   (from pht in objList
     let x=>(sp_TempResult)pht
     where x._int_previous == 1 select pht).ToList();


Q: IPhone SDK - How to serialize ABRecord? I'm new in iPhone development, can you advice me how to serialize AdressBook records?
I have read stackoverflow - How do I serialize a simple object in iPhone sdk, but I still have questions:
should I extend ABRecordRef? Is it possible? Or should I implement own class NSObject?
(similar question was on Mac forums and was left without answer)
Thank you!

A: ABRecord is an opaque C type. It is not an object in the sense of Objective-C. That means you can not extend it, you can not add a category on it, you can not message it. The only thing you can do is call functions described in ABRecord Reference with the ABRecord as a parameter.
You could do two things to be able to keep the information referenced by the ABRecord arround:

*

*Get the ABRecords id by ABRecordGetRecordID(). The ABRecordID is defined as int32_t so you can cast it to an NSInteger and store it wherever you like. You can later get the record back from ABAddressBookGetPersonWithRecordID () or ABAddressBookGetGroupWithRecordID(). But aware, the record could be changed or even deleted by the user or another app meanwhile.

*Copy all values inside the record to a standard NSObject subclass and use NSCoding or other techniques to store it. You will then of cause not benefit from changes or additions to the record the user could have made.
Of cause you can combine both approaches.


Q: Platform Migration: Error when compiling project A few weeks ago I started a Firebase course with flutter, and I was programming on a Windows computer, and now I've been using a Mac for a few days, to learn how to make firebase with iOS too. However, I have received these errors, and I do not know if I am missing a file, lines of code or if I have obsolete code. I tried some solutions I found on the internet, like deleting the files pubspec.lock, podfile, podfile.lock, reinstalling using pod init and pod install, but none of these solutions managed to solve the problem. I know very little about Swift / Objective-C, and this project is connected (android) on firebase.
/Users/mobileteam/Desktop/pasta_mary/aikoBot/aiko_bot/ios/Pods/FirebaseCrashlytics/Crashlytics/Shared/FIRCLSFABHost.m100:11: warning: 'UI_USER_INTERFACE_IDIOM' is deprecated: first deprecated in iOS 13.0 - Use -[UIDevice userInterfaceIdiom] directly. [-Wdeprecated-declarations]

  switch (UI_USER_INTERFACE_IDIOM()) {

          ^
In module 'UIKit' imported from /Users/mobileteam/Desktop/pasta_mary/aikoBot/aiko_bot/ios/Pods/FirebaseCrashlytics/Crashlytics/Shared/FIRCLSFABHost.m:20:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.1.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIDevice.h:97:36: note: 'UI_USER_INTERFACE_IDIOM' has been explicitly marked deprecated here

static inline UIUserInterfaceIdiom UI_USER_INTERFACE_IDIOM() API_DEPRECATED("Use -[UIDevice userInterfaceIdiom] directly.", ios(2.0, 13.0), tvos(9.0, 11.0)) {
                                   ^
1 warning generated.

/Users/mobileteam/Desktop/pasta_mary/aikoBot/aiko_bot/ios/Runner/AppDelegate.swift:14:18: error: cannot override with a stored property 'window'

    override var window: UIWindow?

                 ^

Flutter.FlutterAppDelegate:2:14: note: attempt to override property here

    open var window: UIWindow! { get set }

             ^

note: Using new build system

note: Building targets in parallel

note: Planning build

note: Constructing build description


Q: Entropy and tensor product I'm trying to understand the steps in a certain proof, where I think the following claim is used: $S( |i \rangle \langle i| \otimes \rho) = S(\rho)$, where $S()$ is the entropy, $|i \rangle$ is a state from some orthonormal basis, and $\rho$ is a density operator. Here's my attempt to see why this holds:
$$
\begin{align}
S( |i \rangle \langle i| \otimes \rho) &= -tr\left[\left(|i \rangle \langle i| \otimes \rho\right) \times \log \left(|i \rangle \langle i| \otimes \rho\right)\right]\\
&= -tr[(|i \rangle \langle i| \times \log |i \rangle \langle i|) \otimes \rho \log \rho]\\
&= -tr[(|i \rangle \langle i| \times \log |i \rangle \langle i|)] \times tr[\rho \log \rho]\\
&= 0 \times S(\rho)
\end{align}$$
so I am clearly making a mistake somewhere, that $0$ should not be there. The first equality comes from the definition of $S()$, the second because $(A \otimes B)(C \otimes D) = AC \otimes BD$, the third because $tr(A \otimes B) = tr(A) \times tr(B)$. Are any of these incorrect?

A: $$\log(A\otimes B)=\log A \otimes I + I\otimes \log B$$
You can show this by diagonalizing $A$ and $B$ and using the idea that the matrix log of a diagonal matrix is the log of the elements. In components,
$$\log(A\otimes B)_{ii',jj'}=\log(A_i B_{i'})I_{ij}I_{i'j'}=(\log A_i I_{ij})I_{i'j'}+I_{ij}(\log B_{i'}I_{i'j'})$$
Then if you use your correct rules for tensor product manipulation in your question you will prove the statement.