Q: Python: last item position So I have a huge string and I process it element by element. I want to know how much is left so I try to take the current position word minus the last position word to see how many are left. I tried something like this:
with codecs.open("C:\\dna_chain.txt",'r', "utf-8") as file:
    for line in file:
        temp_buffer = line.split()
        for i,word in enumerate(temp_buffer):
            print(enumerate(temp_buffer[i]))
            print(enumerate(temp_buffer[-1]))

I get positions in memory and they are the same.

A: enumerate() returns a generator object; you only printed the representation of the object, then discard it again. The second line then reused the same memory location for a now object.
You can just refer directly to the temp_buffer object without enumerate() here:
for i, word in enumerate(temp_buffer):
    print(temp_buffer[i])
    print(temp_buffer[-1])

but temp_buffer[i] is the same thing as word in that loop. temp_buffer[-1] is the last word in your list.
If you wanted to know how many more words there are to process, use len(temp_buffer) - i, the length of the temp_buffer list, subtracting the current position.

A: You should count the number of items beforehand:
words = len(temp_buffer)

in your code this would look like
import codecs

with codecs.open("C:\\dna_chain.txt",'r', "utf-8") as file:
    for line in file:
        temp_buffer = line.split()
        words = len(temp_buffer)
        for i,word in enumerate(temp_buffer):
            print(i, word, words-i-1)

this will print the index i, the word word and the number of remaining items in this row words-i-1.


Q: Comparing two text files is not working in Powershell I am trying to compare the contents of two text files and have only the differences be outputted to the console.
The first text file is based on the file names in a folder.
$AsyFolder = Get-ChildItem -Path .\asy-data -Name
I then remove the prefix of the file name that is set up by the user and is the same for every file and is separated from the relevant info with a dash.
$AsyFolder| ForEach-Object{$_.Split("-").Replace("$Prefix", "")} | Where-Object {$_}|Set-Content -Path .\templog.txt
The output looks like $Asyfolder Output
bpm.art
gbr.pdf
asy.pdf
fab.pdf
as1.art
odb.tgz
ccam.cad
read_me_asy.txt

There is another file that is the reference and contains the suffixes of files that should be there.
It looks like this Reference File
tpm.art
bpm.art
gbr.pdf
asy.pdf
fab.pdf
as1.art
as2.art
odb.tgz
xyp.txt
ccam.cad

And its contents are received with $AsyTemplate = Get-Content -Path C:\Users\asy_files.txt
The logic is as follows
$AsyTemplate |
    ForEach-Object{
        If(Select-String -Path .\templog.txt -Pattern $_  -NotMatch -Quiet){
           Write-Host "$($_)"
        }

    }

I have tried various ways of setting up the templog.txt with -InputObject: using Get-Content, Get-Content -Raw, a variable, writing an array manually. I have also tried removing -NotMatch and using -eq $False for the output of select string.
Everytime though the output is just the contents of asy_files.txt (Reference File). It doesn't seem to care what is in templog.txt ($AsyFolder Output).
I have tried using compare-object/where-object method as well and it just says that both files are completely different.

A: Thank you @Lee_Dailey for your help in figuring out how to properly ask a question...
It ended up being additional whitespace (3 tabs) after the characters in the reference file asy_files.txt.
It was an artifact from where I copied from, and powershell was seeing "as2.art" and "as2.art               " I am not 100% as to why that matters, but I found that sorting for any whitespace with /S that appears after a word character /W and removing it made the comparison logic work. The Compare-Object|Where-Object worked as well after removing the whitespace.


Q: How do I configure logback to use xz compression for my logs automatically? How do I configure logback to use xz compression for my logs automatically?
Is xz even supported or only gz and zip?

A: No, logback doesn't support xz. You can see it in source for RollingPolicyBase.java and source for Comressor.java


Q: how to generate a UI for a ListView Adapter for FaceBook like Feed how to creat a Arraylist adapter which will change the view based on a flag in the LISTVIEW, Flag can be IMAGE , IMAGETEXT, VIDEO , VIDEOTEXT, TEXT
e.g like in facebook post , 1.   if a friend posts a text, list row will only contain a text with his Name
2. if a friend posts a Image , list row will only contain a image with his Name
3. if a friend poasts a Video , list row will only contain a Video with his Name , and only Video onClick() ,
 Playing  that Video in a external Player

*

*Flag = text. view to be attached is text.xml

*Flag = Video, View to be attached is video.xml

*Flag = Image ,View to be attached is image.xml
ANY HELP ON THIS.
Thanks in Advance...

A: override  getItemViewType(int position) and getViewTypeCount() method in your adapter and
inflate you view according to it from getView(). In you case write methods like
 @Override
public int getItemViewType(int position) {
        if(list.get(position).flag == text)
            return 0;
         else if(list.get(position).flag == image)
            return 1;
         else
            return 2;
}

@Override
public int getViewTypeCount() {
    return 3;
}

A: I am not pretty much sure but it's my concept that firstly create a layout for row that can hold every thing that you want show(image, video, text etc ). And make this layout such a way if one thing is not present then it automatically wrapped(means if video is not present then video space will not be there).
Now make json of every list row and pass it to Adapter of list. Then override getView() method of the
adapter and parse json there and display according to your layout.

A: i implemented similar Custom Adapter for ListView which is used in this link , also used ViewHolders
check this link
http://www.androidhive.info/2014/06/android-facebook-like-custom-listview-feed-using-volley/


Q: Getting an Array from Return statement, deduce a string from that I have a 'Case' conditional code snippet wherein I am returning two objects.
The psuedocode is -
case name
when 'a'
object1 = - SQL Logic -
when 'b'
object1 = - SQL Logic -
when 'c'
object2 = - SQL Logic -
when 'd'
object2 = - SQL Logic -
end
return object1, object2

As evident, I am returning two objects. However, in my Controller I need one object at a time. The object are returned in form of Array like ['value', 'nil']. One of them is always nil.
In my controller I am passing one of these objects as -
Model.find_by_sql ["select * from #{object}"]  #either object1 or object2

Is there any way that I can break off this array and return the object that is required at that place as String?
Thanks.

A: While you can use compact to eliminate the nil values from your array, I'm not sure why you need this in the first place.
Doing
case name
  when 'a'
    return "SQL statement"
  when 'b'
    return "SQL statement"
  when 'c'
    return "SQL statement"
  when 'd'
    return "SQL statement"
end

is way more intuitive.

A: return [object1, object2].compact
you can use compact method to remove nil value of array.

A: You could write:
return (['a', 'b'].include?(name) && - SQL Logic 1 -) ||
         (['c', 'd'].include?(name) && - SQL Logic 2 -)

If it's the last line of a method, you don't need return.
Let's see what's happening.
If ['a', 'b'].include?(name) #=> true, - SQL Logic 1 -, which is truthy, will be returned.
If ['a', 'b'].include?(name) #=> false, the first && clause is false (- SQL Logic 1 - is not executed), so we consider the other || clause. ['c', 'd'].include?(name) must be true, so we return - SQL Logic 2 -.


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: 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: 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: 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: 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: 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: 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: 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: 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: 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: Three.js particles vs particle system and picking I have an app that uses a Three.js ParticleSystem to render on the order of 50,000 points.  I have spent a lot of time searching for efficient ways to do picking (ray-casting) so as to be able to interact with individual points but have not found a good solution.  I am considering changing to just using an array of Particles instead of ParticleSystems.
My questions are:

*

*Am I missing something; is there a good way to do picking with the ParticleSystem?

*Will I suffer a performance hit using an array of Particles instead of the ParticleSystem, especially since I am taking advantage of the ability to pass several arrays of attributes into the shader.

Thanks for any insight anyone can provide!

A: You're checking 50,000 points every time. That's a bit too much.
You may want to split those points into different ParticleSystems... Like 10 objects with 5000 particles each.
Ideally each object would compose a different "quadrant" so the Raycaster can check the boundingSphere first and ignore all those points if not intersecting.


Q: findViewById returns null for EditText passing values from one class to another class Here is my code.
public void HandleSearchButtonValue(int START_INDEX,int places,String featurea)
    {
        try
        {
            EditText locationEdit=(EditText)findViewById(places);
            InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(locationEdit.getWindowToken(), 0);
            String locationAddress =locationEdit.getText().toString();
        /*try {
            Geocoder geocoder;
            List<Address> addresses;
            geocoder = new Geocoder(this, Locale.getDefault());
            addresses = geocoder.getFromLocation(lat, longt, 1);
            addressline = addresses.get(0).getAddressLine(0);

        } catch (IOException e) {
            return;
        }
        String locationAddress =addressline;*/

            if (locationAddress.equals("")){
                removePoint(START_INDEX);
                map.invalidate();
                return;
            }
            Toast.makeText(this, "Searching:\n"+locationAddress, Toast.LENGTH_LONG).show();
            AutoCompleteOnPreferences.storePreference(this, locationAddress, SHARED_PREFS_APPKEY, PREF_LOCATIONS_KEY);
            new GeocodingTask().execute(locationAddress, START_INDEX);
            String feature = featurea;

            mPoiMarkers = new RadiusMarkerClusterer(this);
            Drawable clusterIconD = getResources().getDrawable(R.drawable.marker_atm);
            Bitmap clusterIcon = ((BitmapDrawable) clusterIconD).getBitmap();
            mPoiMarkers.setIcon(clusterIcon);
            mPoiMarkers.mAnchorV = Marker.ANCHOR_BOTTOM;
            mPoiMarkers.mTextAnchorU = 0.70f;
            mPoiMarkers.mTextAnchorV = 0.27f;
            mPoiMarkers.getTextPaint().setTextSize(12.0f);
            map.getOverlays().add(mPoiMarkers);
            updateUIWithPOI(mPOIs, "");

            if (!feature.equals(""))
                Toast.makeText(this, "Searching:\n" + feature, Toast.LENGTH_LONG).show();
            getPOIAsync(feature);
        }
        catch (Exception e) {
          e.getMessage();
        }
    }


Q: Aggregate root references another aggregate root by ID, how to maintain integrity using RavenDB? Say I have X as an aggregate root, and Y as another aggregate root.
Using a NoSql document database, X holds a reference to Y by Y's Id. If Y is deleted (independently outside of X's context), then X holds a reference to a Y that does not exist.
What is a proposed solution to eliminate or solve this problem in DDD?

A: A delete operation should have a business meaning. For example, just because someone deleted a product from the inventory collection, does not mean it should be deleted from users invoices.
If there is a real need for a delete. You can always define an index in RavenDB and update the entities containing that aggregate root ID.

A: I do not know if DDD speaks to your problem directly but the proposed "solution" may lie in Domain Events / Messaging.  If the related aggregate is in the same bounded context a domain event may suffice else you may need messaging infrastructure to communicate with another bounded context.
What happens when you receive the 'deleted' event is another story and possibly your domain experts can help.  As alluded to by @Dmitry S. you may need to denormalize the related aggregate data into a value object so that you have enough information to keep the main aggregate consistent.  When processing the 'deleted' event then you may want to set some indicator on your main aggregate or update the data somehow to reflect the deletion.

A: Why would you ever delete an aggregate? You might want to Expire() it or Suspend(). Deactivate(), Disable(), Ban(), Cancel(), Finish() or Archive(). But what benefit would you get from loosing your data with Delete()?
If you really need that (possibly due to legal purposes) maybe some EvaporaitonService should be created and it would find all related aggregates and whipe all references.


Q: How can a Java application be informed on receipt of a [FIN,ACK] on a TCP connection? I have 2 connections established from a JMeter instance to an Apache Server, and from the Apache server to a Java application deployed in Jonas.
When I kill the JMeter process, the connection to Apache is closed with a [RST]. Then Apache sends a [FIN, ACK] to Jonas. Jonas has not sent all data, so it keeps sending data. Jonas closes the connection later with a [FIN,ACK].
This behaviour is described in TCP RFC.
So, the problem is Apache receives all data from Jonas, even if Apache can not send it to JMeter.
My question is: Can my Java application be triggered on receipt of the FIN,ACK send from Apache ?

A: Not directly, eventually java may throw a IOException from the InputStream or OutputStream but this is platform dependent.
there was talk of a "raw sockets" java implementation prior to the release of JDK 7 but somehow I don't think it ever got off the ground.

A:
Can my Java application be triggered on receipt of the FIN,ACK send from Apache ?

Yes, but you would have to be reading from the connection. You will get end of stream in one of its various forms, depending on which read method you call. See the Javadoc.


Q: Java JVM Default Garbage Collector: is it configured the same across different applications? Simply as specified in the title.
I ran a test and recorded its memory heap usage pattern over time using JMX. Then I reran my jar file later and studied its memory behavior again. The result was a slightly different memory pattern. In both cases I didn't preconfigure my garbage collector. So I want to know now if two default garbage collectors have the same configurations on the same machine.
If not, how can I ensure that my garbage collector is the same without specifying many parameters? Also what could contribute to my result if not the GC config?

A: If you run the same application on the same machine, with the same JVM, the heap and GC parameters will be the same.
Ergonomics was a feature introduced way back in JDK 5.0 to try and take some of the guesswork out of GC tuning.  A server-class machine (2 or more cores and 2 or more Gb of memory) will use 1/4 of physical memory (up to 1Gb) for both the initial and maximum heap sizes (see https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/ergonomics.html).  So different machines may have different configurations by default.
To find out exactly what flags you have set, use:
java -XX:+PrintFlagsFinal -version
The difference in memory usage pattern is simply the non-deterministic behaviour of your application.  Even with the exact same set of inputs, I doubt you'd see exactly the same memory behaviour just down to so many other OS and hardware effects (cache, core affinity, etc.)


Q: Manage token life duration with SimpleCookie in Python Already got token working correctly, which is set this way:
session_cookie = SimpleCookie()
session_cookie['key'] = any_string_value
session_cookie['key']["Path"] = '/'

headers = []
headers.extend(("set-cookie", morsel.OutputString())
    for morsel
    in session_cookie.values())

start_response(status, headers)

I am also able to read the token and extract the information I need:
# Get cookies
cookies = request.get_cookies()
#     Get current token from cookies
token   = cookies['token'].value

Now, what would be the best approach to set an expiration to a cookie, I know there is 2 possible keys:

*

*session_cookie['key']['max-age'] = "time in secods"

*session_cookie['key']['expiration'] = "a date in the future"

How could I know if a token is expired or what could be the best way to manage expired tokens ?
Thanks a lot!

A: You can know if a token has expired if the token does not exist when you try to get it.
token   = cookies['token'].value #this will not exist

The browser deletes the cookie and everything related to that when the expiration date passes.
This way in many implementations you can even delete cookies or for example log-out a user just but setting the expiration date of the user_id cookie to something in the past( eg a negative number).
Now as I understand you need a policy to detect expired tokens server side and that can be accomplished by double validation. Eg try to store an unique identifier for each token and server side when you read the token try to check if it has expired. It's also possible for the user to manipulate his cookies so never blindly trust cookies to store significant data or make any user_id simple validation.
I hope I helped.
EDIT
From rfc2109

Max-Age=delta-seconds
Optional.  The Max-Age attribute defines the lifetime of the
cookie, in seconds.  The delta-seconds value is a decimal non-
negative integer.  After delta-seconds seconds elapse, the client
should discard the cookie.  A value of zero means the cookie
should be discarded immediately.

And from wiki http cookies

The Expires directive tells the browser when to delete the cookie.
Derived from the format used in RFC 1123, the date is specified in the
form of “Wdy, DD Mon YYYY HH:MM:SS GMT”,[29] indicating the exact
date/time this cookie will expire. As an alternative to setting cookie
expiration as an absolute date/time, RFC 6265 allows the use of the
Max-Age attribute to set the cookie’s expiration as an interval of
seconds in the future, relative to the time the browser received the
cookie.

I would recommend to use max-age because saves some trouble from setting dates etc. You just calculate an interval.
Reading a bit more I found that max-age is not supported by IE < 9 and that means that expires is preferred
Max-Age vs Expires
That should help ;-)


Q: Push a set of values to an array based on another unique value in the same array Question background
Hello, I have the following array of movie crew members:
array:7 [▼
  0 => array:6 [▼
    "credit_id" => "52fe49dd9251416c750d5e9d"
    "department" => "Directing"
    "id" => 139098
    "job" => "Director"
    "name" => "Derek Cianfrance"
    "profile_path" => "/zGhozVaRDCU5Tpu026X0al2lQN3.jpg"
  ]
  1 => array:6 [▼
    "credit_id" => "52fe49dd9251416c750d5ed7"
    "department" => "Writing"
    "id" => 139098
    "job" => "Story"
    "name" => "Derek Cianfrance"
    "profile_path" => "/zGhozVaRDCU5Tpu026X0al2lQN3.jpg"
  ]
  2 => array:6 [▼
    "credit_id" => "52fe49dd9251416c750d5edd"
    "department" => "Writing"
    "id" => 132973
    "job" => "Story"
    "name" => "Ben Coccio"
    "profile_path" => null
  ]
  3 => array:6 [▼
    "credit_id" => "52fe49dd9251416c750d5ee3"
    "department" => "Writing"
    "id" => 139098
    "job" => "Screenplay"
    "name" => "Derek Cianfrance"
    "profile_path" => "/zGhozVaRDCU5Tpu026X0al2lQN3.jpg"
  ]
  4 => array:6 [▼
    "credit_id" => "52fe49dd9251416c750d5ee9"
    "department" => "Writing"
    "id" => 132973
    "job" => "Screenplay"
    "name" => "Ben Coccio"
    "profile_path" => null
  ]
  5 => array:6 [▼
    "credit_id" => "52fe49dd9251416c750d5eef"
    "department" => "Writing"
    "id" => 1076793
    "job" => "Screenplay"
    "name" => "Darius Marder"
    "profile_path" => null
  ]
  11 => array:6 [▼
    "credit_id" => "52fe49de9251416c750d5f13"
    "department" => "Camera"
    "id" => 54926
    "job" => "Director of Photography"
    "name" => "Sean Bobbitt"
    "profile_path" => null
  ]
]

As you can see this is a list of credits I'm getting via the TMDb API. The first step of building the above array was to filter out all jobs that I don't want to display, here's how I did that:
$jobs = [ 'Director', 'Director of Photography', 'Cinematography', 'Cinematographer', 'Story', 'Short Story', 'Screenplay', 'Writer' ];

$crew = array_filter($tmdbApi, function ($crew) use ($jobs) {
    return array_intersect($jobs, $crew);
});

My question
I'd like to figure out how to take the above result one step further and combine jobs where the id is the same, so as to end up with something like this, for example:
array:7 [▼
  0 => array:6 [▼
    "credit_id" => "52fe49dd9251416c750d5e9d"
    "department" => "Directing"
    "id" => 139098
    "job" => "Director, Story, Screenplay"
    "name" => "Derek Cianfrance"
    "profile_path" => "/zGhozVaRDCU5Tpu026X0al2lQN3.jpg"
  ]

I have also considered ditching doing this in my logic and instead doing it in my blade template, but I'm not sure how to achieve that.
How would you accomplish this?

A: Since you are trying to edit the array elements and its size, I believe array_map() or array_filter() won't be a solution to this.
This is what I could come up with...
$jobs = [
  'Director', 'Director of Photography', 'Cinematography',
  'Cinematographer', 'Story', 'Short Story', 'Screenplay', 'Writer'
];

$crew = [];

foreach($tmdbApi as $key => $member) {
  if($member['id'] == $id && in_array($member['job'], $jobs)) {
    if(!isset($crew[$key]))  {
      $crew[$key] = $member;
    } else {
      $crew_jobs = explode(', ', $crew[$key]['job']);
      if(!in_array($member['job'], $crew_jobs)) {
        $crew_jobs[] = $member['job'];
      }
      $crew[$key]['job'] = implode(', ', $crew_jobs);
    }
  }
}

Hope this answers your question :)

A: You could nicely use Laravel's Collection in such a situation, which has a great number of methods which will help you in this case.
First, turn this array (the one you already filtered on jobs) to a Collection:
$collection = collect($crew);

Second, group this Collection by it's ids:
$collectionById = $collection->groupBy('id');

Now, the results are grouped by the id and transformed to a Collection in which the keys correspond to the id, and the value an array of 'matching' results. More info about it here.
Finally, just a easy script that iterates through all the results for each id and combines the job field:
$combinedJobCollection = $collectionById->map(function($item) {
    // get the default object, in which all fields match
    // all the other fields with same ID, except for 'job'
    $transformedItem = $item->first();

    // set the 'job' field according all the (unique) job
    // values of this item, and implode with ', '
    $transformedItem['job'] = $item->unique('job')->implode('job', ', ');

    /* or, keep the jobs as an array, so blade can figure out how to output these
    $transformedItem['job'] = $item->unique('job')->pluck('job');
    */

    return $transformedItem;
})->values();
// values() makes sure keys are reordered (as groupBy sets the id
// as the key)

At this point, this Collection is returned:
Collection {#151 ▼
  #items: array:4 [▼
    0 => array:6 [▼
      "credit_id" => "52fe49dd9251416c750d5e9d"
      "department" => "Directing"
      "id" => 139098
      "job" => "Director, Story, Screenplay"
      "name" => "Derek Cianfrance"
      "profile_path" => "/zGhozVaRDCU5Tpu026X0al2lQN3.jpg"
    ]
    1 => array:6 [▼
      "credit_id" => "52fe49dd9251416c750d5edd"
      "department" => "Writing"
      "id" => 132973
      "job" => "Story, Screenplay"
      "name" => "Ben Coccio"
      "profile_path" => null
    ]
    2 => array:6 [▼
      "credit_id" => "52fe49dd9251416c750d5eef"
      "department" => "Writing"
      "id" => 1076793
      "job" => "Screenplay"
      "name" => "Darius Marder"
      "profile_path" => null
    ]
    3 => array:6 [▼
      "credit_id" => "52fe49de9251416c750d5f13"
      "department" => "Camera"
      "id" => 54926
      "job" => "Director of Photography"
      "name" => "Sean Bobbitt"
      "profile_path" => null
    ]
  ]
}

Note: to use this Collection as an array, use:
$crew = $combinedJobCollection->toArray();

There are multiple ways to achieve this, for example: search the array for overlapping id's, but I think this is the easiest way to achieve this.
Goodluck!