问:
Maven:Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:2.7:resources
I am building my project using Maven. My maven version is apache-maven-3.0.4. I am using Eclipse Luna. When I try to build my project I get the following error

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:2.7:resources (default-resources) on project OrionCommunity: Mark invalid -> [Help 1].

Following is the stack trace when I run mvn clean install -X:

```<code>[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1:53.295s
[INFO] Finished at: Thu Oct 09 20:00:26 IST 2014
[INFO] Final Memory: 9M/25M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:2.7:resources (default-resources) on project OrionCommunity: Mark invalid -> [Hel
p 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:2.7:resources (default-resources)
 on project OrionCommunity: Mark invalid
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:217)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
        at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
        at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
        at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
        at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
        at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)
        at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
        at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
        at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
        at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
        at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
        at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
        at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
Caused by: org.apache.maven.plugin.MojoExecutionException: Mark invalid
        at org.apache.maven.plugin.resources.ResourcesMojo.execute(ResourcesMojo.java:306)
        at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
        ... 19 more
Caused by: org.apache.maven.shared.filtering.MavenFilteringException: Mark invalid
        at org.apache.maven.shared.filtering.DefaultMavenFileFilter.copyFile(DefaultMavenFileFilter.java:129)
        at org.apache.maven.shared.filtering.DefaultMavenResourcesFiltering.filterResources(DefaultMavenResourcesFiltering.java:264)
        at org.apache.maven.plugin.resources.ResourcesMojo.execute(ResourcesMojo.java:300)
        ... 21 more
Caused by: java.io.IOException: Mark invalid
        at java.io.BufferedReader.reset(BufferedReader.java:485)
        at org.apache.maven.shared.filtering.MultiDelimiterInterpolatorFilterReaderLineEnding.read(MultiDelimiterInterpolatorFilterReaderLineEnding.java:416)
        at org.apache.maven.shared.filtering.MultiDelimiterInterpolatorFilterReaderLineEnding.read(MultiDelimiterInterpolatorFilterReaderLineEnding.java:205)
        at java.io.Reader.read(Reader.java:123)
        at org.apache.maven.shared.utils.io.IOUtil.copy(IOUtil.java:181)
        at org.apache.maven.shared.utils.io.IOUtil.copy(IOUtil.java:168)
        at org.apache.maven.shared.utils.io.FileUtils.copyFile(FileUtils.java:1856)
        at org.apache.maven.shared.utils.io.FileUtils.copyFile(FileUtils.java:1804)
        at org.apache.maven.shared.filtering.DefaultMavenFileFilter.copyFile(DefaultMavenFileFilter.java:114)
        ... 23 more
</code>```

My maven repository is under D:/mavenrepo. I have completely deleted all the jars present in the repo and did a clean install. But I still get this error.

答:
I had the same error because of character '@' in my resources/application.properties. All I did was replacing the '@' for its unicode value:
eureka.client.serviceUrl.defaultZone=http://discUser:discPassword\u0040localhost:8082/eureka/ and it worked like charm. I know the '@' is a perfectly valid character in .properties files and the file was in UTF-8 encoding and it makes me question my career till today but it's worth a shot if you delete content of your resource files to see if you can get pass this error.

Body:
I am building my project using Maven. My maven version is apache-maven-3.0.4. I am using Eclipse Luna. When I try to build my project I get the following error

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:2.7:resources (default-resources) on project OrionCommunity: Mark invalid -> [Help 1].

Following is the stack trace when I run mvn clean install -X:

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1:53.295s
[INFO] Finished at: Thu Oct 09 20:00:26 IST 2014
[INFO] Final Memory: 9M/25M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:2.7:resources (default-resources) on project OrionCommunity: Mark invalid -> [Hel
p 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:2.7:resources (default-resources)
 on project OrionCommunity: Mark invalid
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:217)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
        at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
        at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
        at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
        at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
        at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)
        at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
        at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
        at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
        at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
        at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
        at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
        at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
Caused by: org.apache.maven.plugin.MojoExecutionException: Mark invalid
        at org.apache.maven.plugin.resources.ResourcesMojo.execute(ResourcesMojo.java:306)
        at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
        ... 19 more
Caused by: org.apache.maven.shared.filtering.MavenFilteringException: Mark invalid
        at org.apache.maven.shared.filtering.DefaultMavenFileFilter.copyFile(DefaultMavenFileFilter.java:129)
        at org.apache.maven.shared.filtering.DefaultMavenResourcesFiltering.filterResources(DefaultMavenResourcesFiltering.java:264)
        at org.apache.maven.plugin.resources.ResourcesMojo.execute(ResourcesMojo.java:300)
        ... 21 more
Caused by: java.io.IOException: Mark invalid
        at java.io.BufferedReader.reset(BufferedReader.java:485)
        at org.apache.maven.shared.filtering.MultiDelimiterInterpolatorFilterReaderLineEnding.read(MultiDelimiterInterpolatorFilterReaderLineEnding.java:416)
        at org.apache.maven.shared.filtering.MultiDelimiterInterpolatorFilterReaderLineEnding.read(MultiDelimiterInterpolatorFilterReaderLineEnding.java:205)
        at java.io.Reader.read(Reader.java:123)
        at org.apache.maven.shared.utils.io.IOUtil.copy(IOUtil.java:181)
        at org.apache.maven.shared.utils.io.IOUtil.copy(IOUtil.java:168)
        at org.apache.maven.shared.utils.io.FileUtils.copyFile(FileUtils.java:1856)
        at org.apache.maven.shared.utils.io.FileUtils.copyFile(FileUtils.java:1804)
        at org.apache.maven.shared.filtering.DefaultMavenFileFilter.copyFile(DefaultMavenFileFilter.java:114)
        ... 23 more

My maven repository is under D:/mavenrepo. I have completely deleted all the jars present in the repo and did a clean install. But I still get this error.


来源: stackexchange

问:
How to display text depending on the number in UILabel
I work on the app with some calculate function. I have a UITextField where user enter a number and UILabel where is result. How can I display some text in second UILabel depending on the number in the first UILabel?

Example:

```<code>If number in *firstLabel less than 20, then display in *secondLabel: small

If number in *firstLabel from 20 to 30, then display in *secondLabel: normal

If number in *firstLabel greater than 40, then display in *secondLabel: big
</code>```

I hope you understood what i mean. Thank you! Sorry for my english.

答:
```<code>if([firstLabel.text intValue] <20)
{
    secondLabel .text=@"small";
}
else if(([firstLabel.text intValue] >=20) && ([firstLabel.text intValue] <=30) )
{
    secondLabel .text=@"normal";
}
else if([firstLabel.text intValue] >30)
{
    secondLabel .text=@"big";
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I work on the app with some calculate function. I have a UITextField where user enter a number and UILabel where is result. How can I display some text in second UILabel depending on the number in the first UILabel?

Example:

If number in *firstLabel less than 20, then display in *secondLabel: small

If number in *firstLabel from 20 to 30, then display in *secondLabel: normal

If number in *firstLabel greater than 40, then display in *secondLabel: big

I hope you understood what i mean. Thank you! Sorry for my english.


问:
Replacing  with <math> change minus to question mark
I want to replace  with a MathML(image01.xml) like below:

```<code><math>
  <semantics>
    <mrow>
      <mfrac>
        <mrow>
          <mo stretchy="false">(</mo>
          <mi>n</mi>
          <mo>−</mo>
          <mn>1</mn>
          <mo stretchy="false">)</mo>
          <mo>×</mo>
          <mi>n</mi>
        </mrow>
        <mn>2</mn>
      </mfrac>
    </mrow>
  </semantics>
</math>
</code>```

Using below code to replace (changed the code based on Rufus L's suggestion):

```<code>string newStr = File.ReadAllText(path to image01.xml);
span.InnerHtml = newStr;
</code>```

After replacing, the embeded MathML is different- <mo>−</mo> changes to <mo>?</mo>

```<code><math>
  <semantics>
    <mrow>
      <mfrac>
        <mrow>
          <mo stretchy="false">(</mo>
          <mi>n</mi>
          <mo>?</mo>
          <mn>1</mn>
          <mo stretchy="false">)</mo>
          <mo>×</mo>
          <mi>n</mi>
        </mrow>
        <mn>2</mn>
      </mfrac>
    </mrow>
  </semantics>
</math>
</code>```

What's wrong with my code? I will fell very appreciated for any help.

```<code>==============================================================
</code>```

Update:
the newStr is (from Debug, the minus is still there):

```<code>"<math>\r\n  <semantics>\r\n    <mrow>\r\n      <mfrac>\r\n        <mrow>\r\n          <mo stretchy=\"false\">(</mo>\r\n          <mi>n</mi>\r\n          <mo>−</mo>\r\n          <mn>1</mn>\r\n          <mo stretchy=\"false\">)</mo>\r\n          <mo>×</mo>\r\n          <mi>n</mi>\r\n        </mrow>\r\n        <mn>2</mn>\r\n      </mfrac>\r\n    </mrow>\r\n  </semantics>\r\n</math>"
</code>```

The code for retrieving span is:

```<code>var spans = doc.DocumentNode.SelectNodes("//span[img]");
foreach (HtmlNode span in spans)
{
    // handle span here
}
</code>```

答:
What about handling the span as:

```<code>var mo = span.SelectNode("//mo")
if (mo.innerText=="-") { mo.innerText = "?"; }
</code>```

(untested...)

ContentLicense: CC BY-SA 4.0

Title: Replacing <img> with <math> change minus to question mark

Body:
I want to replace  with a MathML(image01.xml) like below:

<math>
  <semantics>
    <mrow>
      <mfrac>
        <mrow>
          <mo stretchy="false">(</mo>
          <mi>n</mi>
          <mo>−</mo>
          <mn>1</mn>
          <mo stretchy="false">)</mo>
          <mo>×</mo>
          <mi>n</mi>
        </mrow>
        <mn>2</mn>
      </mfrac>
    </mrow>
  </semantics>
</math>

Using below code to replace (changed the code based on Rufus L's suggestion):

string newStr = File.ReadAllText(path to image01.xml);
span.InnerHtml = newStr;

After replacing, the embeded MathML is different- <mo>−</mo> changes to <mo>?</mo>

<math>
  <semantics>
    <mrow>
      <mfrac>
        <mrow>
          <mo stretchy="false">(</mo>
          <mi>n</mi>
          <mo>?</mo>
          <mn>1</mn>
          <mo stretchy="false">)</mo>
          <mo>×</mo>
          <mi>n</mi>
        </mrow>
        <mn>2</mn>
      </mfrac>
    </mrow>
  </semantics>
</math>

What's wrong with my code? I will fell very appreciated for any help.

==============================================================

Update:
the newStr is (from Debug, the minus is still there):

"<math>\r\n  <semantics>\r\n    <mrow>\r\n      <mfrac>\r\n        <mrow>\r\n          <mo stretchy=\"false\">(</mo>\r\n          <mi>n</mi>\r\n          <mo>−</mo>\r\n          <mn>1</mn>\r\n          <mo stretchy=\"false\">)</mo>\r\n          <mo>×</mo>\r\n          <mi>n</mi>\r\n        </mrow>\r\n        <mn>2</mn>\r\n      </mfrac>\r\n    </mrow>\r\n  </semantics>\r\n</math>"

The code for retrieving span is:

var spans = doc.DocumentNode.SelectNodes("//span[img]");
foreach (HtmlNode span in spans)
{
    // handle span here
}

Body:
What about handling the span as:

var mo = span.SelectNode("//mo")
if (mo.innerText=="-") { mo.innerText = "?"; }

(untested...)


问:
Pseudo-localization on Android not working
I have enabled English [XA] on my phone placed it on top of English and added this code to my build.gradle

```<code>buildTypes {
        debug {
            pseudoLocalesEnabled true
        }
    }
</code>```

When I run my app I don't see my app being pseudo localized and I don't get why. I see some of the system alert dialogs being pseudo-localized and some of the settings but not everything. Am I missing something? Already looked at multiple resources (resource_1 & resource_2) about it and it seems that it's pretty straight forward to enable it and have it running but it's not.

答:
Figured it out and no documentation mentions (even the one from google tsk tsk) that you need to add "en_XA" to resConfigs

```<code>android {
  ...
  defaultConfig {
    ...
    resConfigs "en", "en_XA"
    ...
  }
}
</code>```

In case the pseudolocalized strings don't show check if the strings for "en_XA" were created by decompiling the apk and check if "values-en-rXA" folder was created. If it's created you can open strings.xml and see all the strings pseudlocalized.

Body:
I have enabled English [XA] on my phone placed it on top of English and added this code to my build.gradle

buildTypes {
        debug {
            pseudoLocalesEnabled true
        }
    }

When I run my app I don't see my app being pseudo localized and I don't get why. I see some of the system alert dialogs being pseudo-localized and some of the settings but not everything. Am I missing something? Already looked at multiple resources (resource_1 & resource_2) about it and it seems that it's pretty straight forward to enable it and have it running but it's not.

Body:
Figured it out and no documentation mentions (even the one from google tsk tsk) that you need to add "en_XA" to resConfigs

android {
  ...
  defaultConfig {
    ...
    resConfigs "en", "en_XA"
    ...
  }
}

In case the pseudolocalized strings don't show check if the strings for "en_XA" were created by decompiling the apk and check if "values-en-rXA" folder was created. If it's created you can open strings.xml and see all the strings pseudlocalized.


问:
Soundcloud embedded player on mobile
Here is how a SoundCloud embedded player on a HTML page looks like on mobile device:

It's rather annoying, because the user has to click "Listen in browser", and then, often, it doesn't start like it should, and so the user has to click "Pause" button and "Play" again.

How to have the normal look, even on mobile devices? :

Here is example of embedding code:

```<code><iframe width="100%" height="166" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/271188615&color=ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false"></iframe>
</code>```

答: Use show_teaser=false as parameter to hide the overlay.</p>

Title: Soundcloud embedded player on mobile


问:
How can I use Python to refactor nested function calls into lines of code?
I'm looking for some way to do this with Python itself, not using an IDE.

Example:

```<code>def upper(string):
    return string.upper()

def reverse_string(string):
    return string[::-1]

string = 'abc'
reverse_upper = reverse_string(upper(string))
</code>```

Converts to:

```<code>string = 'abc'
reverse_upper = string.upper()[::-1]
</code>```

I'm considering making a solution that works recursively with inspect.getsourcelines. Is there any other function or library that will get me further along?

答:
This comment from @kaya3 got me here.

There are two repos that do this that I can use as starting points: inliner and atinline. Neither are maintained, but I can use them for reference.

Body:
I'm looking for some way to do this with Python itself, not using an IDE.

Example:

def upper(string):
    return string.upper()

def reverse_string(string):
    return string[::-1]

string = 'abc'
reverse_upper = reverse_string(upper(string))

Converts to:

string = 'abc'
reverse_upper = string.upper()[::-1]

I'm considering making a solution that works recursively with inspect.getsourcelines. Is there any other function or library that will get me further along?


问:
Whoosh locked statement while writing index
I a trying to build an index of parliamentary transcripts that I have already split by page number and converted in txt.
I am using the last version of whoosh to build it up but it gives me lock error.
This is the code:

```<code>import os
from whoosh import index
from whoosh.index import create_in
from whoosh.fields import Schema, TEXT, ID
import sys

def createSearchableData(root):

    '''
    Schema definition: title(name of file), path(as ID), content(indexed
    but not stored),textdata (stored text content)
    '''
    schema = Schema(title=TEXT(stored=True),path=ID(stored=True),\
              content=TEXT,textdata=TEXT(stored=True))
    if not os.path.exists("indexdir"):
        os.mkdir("indexdir")

    # Creating a index writer to add document as per schema
    ix = index.create_in("indexdir",schema)
    writer = ix.writer()

    filepaths = [os.path.join(root,i) for i in os.listdir(root)]
    for path in filepaths:
        fp = open(path,'rb')
        print(path)
        text = fp.read()
        writer.add_document(title=path.split("\\")[1], path=path,\
          content=text,textdata=text)
        fp.close()
    writer.commit()

root = "C:\\Users\\vitop\\OneDrive\\Desktop\\Final Project\\Test\\Splitted\\Txt"
createSearchableData(root)
</code>```

This is the error noted:

```<code>LockError                                 Traceback (most recent call last)
<ipython-input-4-e8b4a33a2859> in <module>
     31
     32 root = "C:\\Users\\vitop\\OneDrive\\Desktop\\Final Project\\Test\\Splitted\\Txt"
---> 33 createSearchableData(root)

<ipython-input-4-e8b4a33a2859> in createSearchableData(root)
     18     # Creating a index writer to add document as per schema
     19     ix = index.create_in("indexdir",schema)
---> 20     writer = ix.writer()
     21
     22     filepaths = [os.path.join(root,i) for i in os.listdir(root)]

~\Anaconda3\lib\site-packages\whoosh\index.py in writer(self, procs, **kwargs)
    462         else:
    463             from whoosh.writing import SegmentWriter
--> 464             return SegmentWriter(self, **kwargs)
    465
    466     def lock(self, name):

~\Anaconda3\lib\site-packages\whoosh\writing.py in __init__(self, ix, poolclass, timeout, delay, _lk, limitmb, docbase, codec, compound, **kwargs)
    513             if not try_for(self.writelock.acquire, timeout=timeout,
    514                            delay=delay):
--> 515                 raise LockError
    516
    517         if codec is None:

LockError:
</code>```

The code created the folder and set up the index file. I tried to use the workaround suggest with Whoosh documentation but it does not work.

答:
Fixed with getting rid of binary option and encoding "utf-8" the txt file.</p>

```<code>for path in filepaths:
    fp = open(path,'r', encoding = "utf-8")
    print(path)
    text = fp.read()
    writer.add_document(title=path.split("\\")[1], path=path,
    content=text,textdata=text)
    fp.close()
writer.commit()
</code>```

Body:
I a trying to build an index of parliamentary transcripts that I have already split by page number and converted in txt.
I am using the last version of whoosh to build it up but it gives me lock error.
This is the code:

import os
from whoosh import index
from whoosh.index import create_in
from whoosh.fields import Schema, TEXT, ID
import sys

def createSearchableData(root):

    '''
    Schema definition: title(name of file), path(as ID), content(indexed
    but not stored),textdata (stored text content)
    '''
    schema = Schema(title=TEXT(stored=True),path=ID(stored=True),\
              content=TEXT,textdata=TEXT(stored=True))
    if not os.path.exists("indexdir"):
        os.mkdir("indexdir")

    # Creating a index writer to add document as per schema
    ix = index.create_in("indexdir",schema)
    writer = ix.writer()

    filepaths = [os.path.join(root,i) for i in os.listdir(root)]
    for path in filepaths:
        fp = open(path,'rb')
        print(path)
        text = fp.read()
        writer.add_document(title=path.split("\\")[1], path=path,\
          content=text,textdata=text)
        fp.close()
    writer.commit()

root = "C:\\Users\\vitop\\OneDrive\\Desktop\\Final Project\\Test\\Splitted\\Txt"
createSearchableData(root)

This is the error noted:

LockError                                 Traceback (most recent call last)
<ipython-input-4-e8b4a33a2859> in <module>
     31
     32 root = "C:\\Users\\vitop\\OneDrive\\Desktop\\Final Project\\Test\\Splitted\\Txt"
---> 33 createSearchableData(root)

<ipython-input-4-e8b4a33a2859> in createSearchableData(root)
     18     # Creating a index writer to add document as per schema
     19     ix = index.create_in("indexdir",schema)
---> 20     writer = ix.writer()
     21
     22     filepaths = [os.path.join(root,i) for i in os.listdir(root)]

~\Anaconda3\lib\site-packages\whoosh\index.py in writer(self, procs, **kwargs)
    462         else:
    463             from whoosh.writing import SegmentWriter
--> 464             return SegmentWriter(self, **kwargs)
    465
    466     def lock(self, name):

~\Anaconda3\lib\site-packages\whoosh\writing.py in __init__(self, ix, poolclass, timeout, delay, _lk, limitmb, docbase, codec, compound, **kwargs)
    513             if not try_for(self.writelock.acquire, timeout=timeout,
    514                            delay=delay):
--> 515                 raise LockError
    516
    517         if codec is None:

LockError:

The code created the folder and set up the index file. I tried to use the workaround suggest with Whoosh documentation but it does not work.

Body:
Fixed with getting rid of binary option and encoding "utf-8" the txt file.

for path in filepaths:
    fp = open(path,'r', encoding = "utf-8")
    print(path)
    text = fp.read()
    writer.add_document(title=path.split("\\")[1], path=path,
    content=text,textdata=text)
    fp.close()
writer.commit()


问:
C# Console App - Streamwriter overwriting CSV file every time it writes new "Page" from API call, only leaving last API call results
So, I KNOW this is a simple thing but I typically work with ASP.NET web apps and SQL, so I'm having a problem with this console app.

I have a console app that pulls a "page" of data from a webclient API call. This pulls the data into a string (s) and writes that data to a CSV file. The method then loops, incrementing the "pagenum" by +1  until the API returns the string "No records found".

My problem is, instead of appending each new "page" of data to the existing CSV file, it overwrites the file with the previous "page" of data. So, I write page 1, then get page 2, and all the data in the CSV is replaced with Page 2 data, rinse and repeat.

My question: do I need to create a new "string" for each page of data (maybe incrementing the string variable name by 1 (s1, s2, s3) based on page number or do I simply need to change my loops to use some sort of other part of Streamwriter (like is there an add line command I need to call at the end of the loop?) If so, any ideas on how to do this based on my sample code below? (NOTE: I have some Console.WriteLines for debugging purposes so I can see the data while testing.)

```<code>while (!s.Contains("No records found")) //When API returns "No Records Found" we know we've reached the last page of data we need to get.
        {
            rpcURL = "https://api.WEBSITEcom/urlrpc?method=getPlacementReport&username=" + userName + "&password=" + passWord + "&class_code=" + classCode + "&from_date=" + startDate + "&to_date=" + endDate + "&page_num=" + page;
            Console.WriteLine(rpcURL);
            client.Headers.Add("user-agent", "Mozilla/4.0 (Compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
            using (var stream = client.OpenRead(rpcURL))
            using (var sr = new StreamReader(stream))
            {
                s = sr.ReadToEnd();

                Console.WriteLine(s);
                string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                string docPath = path + "\\" + "AleksReport.csv";

                if (!s.Contains("No records found"))
                {
                    using (StreamWriter writer = new StreamWriter(docPath))
                    {
                        writer.WriteLine(s);
                    }
                }
                else
                {
                    Console.WriteLine("End of records");
                }
            }
            page++;

        }
</code>```

答:
Use this constructor public StreamWriter (string path, bool append); with second param set to true. More info here.

append

true to append data to the file; false to overwrite the file. If the specified file does not exist, this parameter has no effect,
  and the constructor creates a new file.

Body:
So, I KNOW this is a simple thing but I typically work with ASP.NET web apps and SQL, so I'm having a problem with this console app.

I have a console app that pulls a "page" of data from a webclient API call. This pulls the data into a string (s) and writes that data to a CSV file. The method then loops, incrementing the "pagenum" by +1  until the API returns the string "No records found".

My problem is, instead of appending each new "page" of data to the existing CSV file, it overwrites the file with the previous "page" of data. So, I write page 1, then get page 2, and all the data in the CSV is replaced with Page 2 data, rinse and repeat.

My question: do I need to create a new "string" for each page of data (maybe incrementing the string variable name by 1 (s1, s2, s3) based on page number or do I simply need to change my loops to use some sort of other part of Streamwriter (like is there an add line command I need to call at the end of the loop?) If so, any ideas on how to do this based on my sample code below? (NOTE: I have some Console.WriteLines for debugging purposes so I can see the data while testing.)

while (!s.Contains("No records found")) //When API returns "No Records Found" we know we've reached the last page of data we need to get.
        {
            rpcURL = "https://api.WEBSITEcom/urlrpc?method=getPlacementReport&username=" + userName + "&password=" + passWord + "&class_code=" + classCode + "&from_date=" + startDate + "&to_date=" + endDate + "&page_num=" + page;
            Console.WriteLine(rpcURL);
            client.Headers.Add("user-agent", "Mozilla/4.0 (Compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
            using (var stream = client.OpenRead(rpcURL))
            using (var sr = new StreamReader(stream))
            {
                s = sr.ReadToEnd();

                Console.WriteLine(s);
                string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                string docPath = path + "\\" + "AleksReport.csv";

                if (!s.Contains("No records found"))
                {
                    using (StreamWriter writer = new StreamWriter(docPath))
                    {
                        writer.WriteLine(s);
                    }
                }
                else
                {
                    Console.WriteLine("End of records");
                }
            }
            page++;

        }


问:
Python convert an integer to fixed or varying size recoverable string
I want to get a string from an integer as:

convert(45)
 VHCDD65D2D5SS

This string should also be able to give back the integer.
What should be the proper way of doing this?

答:
Try to use a hash method. Hashlib or with Salt and hash a password in Python

To generate the token, I think you can add extra char in front of the ID

Example:
ID = 1

string_id = name_1

hashlib = xxxxxx


问:
Error in Moving sql database files
I want to copy my database mdf and ldf files programmatically and also change their names.
I tried File.Move() and "Alter database mydb modify file ..." and "use master exec sp_detach_db mydb" but i recieve this error "user doesnt have permission to do this action" or other errors like this.
note that i am an administrator user.
please help me</p>

答:
Try this it will work to rename the database

```<code>sp_rename 'Test','MyTest','DATABASE'
</code>```

Here Test is your old database name and MyTest is new database name.

And one thing i want to tell you is You can not change the name of your system database name.
and MYDB is system database.

Title: Error in Moving sql database files

Body:
Try this it will work to rename the database

sp_rename 'Test','MyTest','DATABASE'

Here Test is your old database name and MyTest is new database name.

And one thing i want to tell you is You can not change the name of your system database name.
and MYDB is system database.


问:
Remove a element from List of objects based on inner object list value in java
How can I remove the element from the list if some inner list attribute value fails to meet the condition.The trick here is that attribute is itself a list and comparison is based on some attribute of that inner list. Please refer the below sample and help out to fill the comment section in code:

Object :

```<code>Class product{
 private String productId;
 private String productName;
 private List<Attribute> attributeList;

    public static class Attribute{
        private Long attributeId;
    }
}
</code>```

Driver class :

```<code>Class Driver{
   List<product> productList = new ArrayList<product>();
   /*
   Remove the object from productList if attributeList doesn't contain attribute with attributeId = x;
*/
}
</code>```

答:
You can do a foreach loop and remove the unwanted elements. In "product" class you can insert a "FindInnerAtribute" function to search inside the Attributes list and return true if there is some.

```<code>List<product> productList = new ArrayList<product>();
for(product p : productList){
    if ( p.FindInnerAttribute(x) ){
        productList.remove(p);
    }
}
</code>```

How to remove from list

Body:
How can I remove the element from the list if some inner list attribute value fails to meet the condition.The trick here is that attribute is itself a list and comparison is based on some attribute of that inner list. Please refer the below sample and help out to fill the comment section in code:

Object :

Class product{
 private String productId;
 private String productName;
 private List<Attribute> attributeList;

    public static class Attribute{
        private Long attributeId;
    }
}

Driver class :

Class Driver{
   List<product> productList = new ArrayList<product>();
   /*
   Remove the object from productList if attributeList doesn't contain attribute with attributeId = x;
*/
}

Body:
You can do a foreach loop and remove the unwanted elements. In "product" class you can insert a "FindInnerAtribute" function to search inside the Attributes list and return true if there is some.

List<product> productList = new ArrayList<product>();
for(product p : productList){
    if ( p.FindInnerAttribute(x) ){
        productList.remove(p);
    }
}

How to remove from list


问:
vcrpy record cassettes doesn't record in a test using test_client.post
I'm implementing pytest and I want to record the answer of a request using vcrpy.

I'm using flask 1.0.2, pytest 4.5.0, pytest-flask 0.15.0 and vcrpy 2.0.1. I implemented a restful api using flask. I wrote a test but I would like to record the response of the request and vcr is not recording the response.

My endpoint is:

```<code>from flask import jsonify
from flask import Blueprint

class CompanyResource(Resource):

    def post(self):
        response = jsonify({
            "timestamp": datetime.utcnow()
        })
        response.status_code = 201
        return response

api_bp = Blueprint('dashboard', __name__)
api = Api(api_bp)
api.add_resource(CompanyResource, 'company', endpoint='company')
</code>```

The test is the following

```<code>import pytest
import vcr

from flask import url_for

base_vcr = vcr.VCR(
    cassette_library_dir='tests/dashboard/fixtures',
    record_mode='once'
)

def test_create_company(client, company_data, headers):
      with base_vcr.use_cassette('create_user.yaml'):
           response = client.post(url_for('dashboard.company'),
                                  json=company_data,
                                  headers=headers)
</code>```

I expect a file auto-generated on the directory specified. But when I run the test the cassette was not generated. The thing is that if I change client.post by requests.post the response is recorded for a get request, but if I try with a post an error is yield:

```<code>requests.exceptions.MissingSchema: Invalid URL '/api/dashboard/company': No schema supplied. Perhaps you meant http:///api/dashboard/company?

</code>```

Do you have any suggestions to test my post endpoint and record the answer?

答:
This is a little late but vcrpy has a list of libraries it records the HTTP requests for. requests is one of them, and the others are mentioned in https://vcrpy.readthedocs.io/en/latest/installation.html#compatibility.

aiohttp

boto

boto3

http.client

httplib2

requests (both 1.x and 2.x versions)

tornado.httpclient

urllib2

urllib3

Not sure what test client fixture you are using in your pytest, but if you use requests to call your endpoint successfully, it should record the response for you.

Body:
I'm implementing pytest and I want to record the answer of a request using vcrpy.

I'm using flask 1.0.2, pytest 4.5.0, pytest-flask 0.15.0 and vcrpy 2.0.1. I implemented a restful api using flask. I wrote a test but I would like to record the response of the request and vcr is not recording the response.

My endpoint is:

from flask import jsonify
from flask import Blueprint

class CompanyResource(Resource):

    def post(self):
        response = jsonify({
            "timestamp": datetime.utcnow()
        })
        response.status_code = 201
        return response

api_bp = Blueprint('dashboard', __name__)
api = Api(api_bp)
api.add_resource(CompanyResource, 'company', endpoint='company')

The test is the following

import pytest
import vcr

from flask import url_for

base_vcr = vcr.VCR(
    cassette_library_dir='tests/dashboard/fixtures',
    record_mode='once'
)

def test_create_company(client, company_data, headers):
      with base_vcr.use_cassette('create_user.yaml'):
           response = client.post(url_for('dashboard.company'),
                                  json=company_data,
                                  headers=headers)

I expect a file auto-generated on the directory specified. But when I run the test the cassette was not generated. The thing is that if I change client.post by requests.post the response is recorded for a get request, but if I try with a post an error is yield:

requests.exceptions.MissingSchema: Invalid URL '/api/dashboard/company': No schema supplied. Perhaps you meant http:///api/dashboard/company?

Do you have any suggestions to test my post endpoint and record the answer?


问:
Godot: How to get a variable from a non instanced scene
Godot: How to get a variable from a non instanced scene

I don't want to instance the scene.

答:
i am answering my own question because i figured it out.

you can use singletons:
http://docs.godotengine.org/en/stable/getting_started/step_by_step/singletons_autoload.html


问:
How can I initiate a new function, immediately after a function is successful in react native
I want to run a function, just after a function is completed, and also pass some data into the second function.
I have tested the two functions individually, they both work. But I want to initiate the second one immediately after the first is complete

This is my code below but the second function didn't run properly.

```<code>const ChargeCard = (dispatch) => ({
    cardNumber,
    expiryMonth,
    expiryYear,
    cvc,
    email,
    amountInKobo,
    id
}) => {

    try {
        RNPaystack.chargeCard({
            cardNumber: cardNumber,
            expiryMonth: expiryMonth,
            expiryYear: expiryYear,
            cvc: cvc,
            email: email,
            amountInKobo: amountInKobo * 100

        })
            .then(response => {

                if (response) {
                    setBasic({ id }) //the function to run if this is successful
                }
            })

    } catch {

        dispatch({
            type: "ADD_ERROR",
            payload:
                "Something went wrong during payment, please try again, don't worry you have not been charged."
        });
    }

};
</code>```

This function I want to run immediately that is successful;

```<code>const setBasic = () => async ({ id }) => {
    const Basic = 1
    const response = await appApi.put(`/usersub/${id}`, { Basic });
    if (response) {
        console.log(response.data)
    }
}
</code>```

答:
why mix async await with then() stick with one and be consistent with it.

```<code>const setBasic = async ({ id }) => {
    const Basic = 1
    const response = await appApi.put(`/usersub/${id}`, { Basic });
    if (response) {
        console.log(response.data)
    }
}

const ChargeCard = (dispatch) => async ({
    cardNumber,
    expiryMonth,
    expiryYear,
    cvc,
    email,
    amountInKobo,
    id
}) => {

    try {
        const response = await RNPaystack.chargeCard({
            cardNumber: cardNumber,
            expiryMonth: expiryMonth,
            expiryYear: expiryYear,
            cvc: cvc,
            email: email,
            amountInKobo: amountInKobo * 100

        })
        if(response) setBasic({ id }) //the function to run if this is successful

    } catch {

        dispatch({
            type: "ADD_ERROR",
            payload:
                "Something went wrong during payment, please try again, don't worry you have not been charged."
        });
    }

};
</code>```

This way your login is consistent. However, I just want to mention this; your first function looks like a shorthand way to write action creators using redux-thunk in case I am right, I think you are passing the dispatch wrongly in the first function. You should rewrite your function to this:

```<code>const ChargeCard = ({
    cardNumber,
    expiryMonth,
    expiryYear,
    cvc,
    email,
    amountInKobo,
    id
}) => async dispatch => {

    try {
        const response = await RNPaystack.chargeCard({
            cardNumber: cardNumber,
            expiryMonth: expiryMonth,
            expiryYear: expiryYear,
            cvc: cvc,
            email: email,
            amountInKobo: amountInKobo * 100

        })
        if(response) setBasic({ id }) //the function to run if this is successful

    } catch {

        dispatch({
            type: "ADD_ERROR",
            payload:
                "Something went wrong during payment, please try again, don't worry you have not been charged."
        });
    }

};
</code>```

Body:
I want to run a function, just after a function is completed, and also pass some data into the second function.
I have tested the two functions individually, they both work. But I want to initiate the second one immediately after the first is complete

This is my code below but the second function didn't run properly.

const ChargeCard = (dispatch) => ({
    cardNumber,
    expiryMonth,
    expiryYear,
    cvc,
    email,
    amountInKobo,
    id
}) => {

    try {
        RNPaystack.chargeCard({
            cardNumber: cardNumber,
            expiryMonth: expiryMonth,
            expiryYear: expiryYear,
            cvc: cvc,
            email: email,
            amountInKobo: amountInKobo * 100

        })
            .then(response => {

                if (response) {
                    setBasic({ id }) //the function to run if this is successful
                }
            })

    } catch {

        dispatch({
            type: "ADD_ERROR",
            payload:
                "Something went wrong during payment, please try again, don't worry you have not been charged."
        });
    }

};

This function I want to run immediately that is successful;

const setBasic = () => async ({ id }) => {
    const Basic = 1
    const response = await appApi.put(`/usersub/${id}`, { Basic });
    if (response) {
        console.log(response.data)
    }
}

Body:
why mix async await with then() stick with one and be consistent with it.

const setBasic = async ({ id }) => {
    const Basic = 1
    const response = await appApi.put(`/usersub/${id}`, { Basic });
    if (response) {
        console.log(response.data)
    }
}

const ChargeCard = (dispatch) => async ({
    cardNumber,
    expiryMonth,
    expiryYear,
    cvc,
    email,
    amountInKobo,
    id
}) => {

    try {
        const response = await RNPaystack.chargeCard({
            cardNumber: cardNumber,
            expiryMonth: expiryMonth,
            expiryYear: expiryYear,
            cvc: cvc,
            email: email,
            amountInKobo: amountInKobo * 100

        })
        if(response) setBasic({ id }) //the function to run if this is successful

    } catch {

        dispatch({
            type: "ADD_ERROR",
            payload:
                "Something went wrong during payment, please try again, don't worry you have not been charged."
        });
    }

};

This way your login is consistent. However, I just want to mention this; your first function looks like a shorthand way to write action creators using redux-thunk in case I am right, I think you are passing the dispatch wrongly in the first function. You should rewrite your function to this:

const ChargeCard = ({
    cardNumber,
    expiryMonth,
    expiryYear,
    cvc,
    email,
    amountInKobo,
    id
}) => async dispatch => {

    try {
        const response = await RNPaystack.chargeCard({
            cardNumber: cardNumber,
            expiryMonth: expiryMonth,
            expiryYear: expiryYear,
            cvc: cvc,
            email: email,
            amountInKobo: amountInKobo * 100

        })
        if(response) setBasic({ id }) //the function to run if this is successful

    } catch {

        dispatch({
            type: "ADD_ERROR",
            payload:
                "Something went wrong during payment, please try again, don't worry you have not been charged."
        });
    }

};


问:
How to send a message with login in Laravel?
I have this function for log but I have an error in the compact

```<code>public function redirectPath()
{
    if (Auth::user()){

        $msg_modal = 1;
        return '/', compact('msg_modal');
}
</code>```

to run this script which show me a modal

```<code>@if(!empty($msg_modal) && $msg_modal == 1)

<script>
$(function() {
$('#mostrarmodal').modal('show');
});
</script>

@endif
</code>```

This is the modal that I would like to see when I log

```<code><div class="modal fade" id="mostrarmodal" tabindex="-1" role="dialog" aria-labelledby="basicModal" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
       <div class="modal-header">
          <h3><center>System</center></h3>
       </div>
       <div class="modal-body">
          <h4><center>Message</center></h4>
          <center>You are connected!!!</center>
      </div>
       <div class="modal-footer">
      <a href="#" data-dismiss="modal" class="btn btn-info">Continuar</a>
       </div>
  </div>
</code>```

答:
In return '/' , compact($msg) you return string so you can not pass variable with compact

You should use view for this purpose like this:

```<code>return view('/',compact('msg_modal'));
</code>```

Body:
I have this function for log but I have an error in the compact

public function redirectPath()
{
    if (Auth::user()){

        $msg_modal = 1;
        return '/', compact('msg_modal');
}

to run this script which show me a modal

@if(!empty($msg_modal) && $msg_modal == 1)

@endif

This is the modal that I would like to see when I log

System

Message

          You are connected!!!

      Continuar

Body:
In return '/' , compact($msg) you return string so you can not pass variable with compact

You should use view for this purpose like this:

return view('/',compact('msg_modal'));


问:
How to create aab (bundle) via Fastlane?
I want to create aab (bundle) via Fastlane, but so far I was able to create only apk, here is my lane now, how to create aab?

```<code> lane :beta do
    store_password = prompt(text: "Signing Store Password: ", secure_text: true)
    key_password = prompt(text: "Alias Key Password: ", secure_text: true)
    releaseFilePath = File.join(Dir.pwd, "..", "my-release-key.keystore")
    gradle(task: 'clean')
    gradle(
      task: 'assemble',
      build_type: 'Release',
      print_command: false,
      properties: {
        "android.injected.signing.store.file" => releaseFilePath,
        "android.injected.signing.store.password" => store_password,
        "android.injected.signing.key.alias" => "my-key-alias",
        "android.injected.signing.key.password" => key_password,
      }
    )
    upload_to_play_store(
      track: 'internal'
    )
</code>```

答: Changing task from assemble to bundle, solved my issue!

Body:
I want to create aab (bundle) via Fastlane, but so far I was able to create only apk, here is my lane now, how to create aab?

 lane :beta do
    store_password = prompt(text: "Signing Store Password: ", secure_text: true)
    key_password = prompt(text: "Alias Key Password: ", secure_text: true)
    releaseFilePath = File.join(Dir.pwd, "..", "my-release-key.keystore")
    gradle(task: 'clean')
    gradle(
      task: 'assemble',
      build_type: 'Release',
      print_command: false,
      properties: {
        "android.injected.signing.store.file" => releaseFilePath,
        "android.injected.signing.store.password" => store_password,
        "android.injected.signing.key.alias" => "my-key-alias",
        "android.injected.signing.key.password" => key_password,
      }
    )
    upload_to_play_store(
      track: 'internal'
    )


问:
Says it cannot be used as constant
Visual studio 2019

```<code>const int inputs = 1, layers = 2, layerN = 3, output = 1;
const int how = inputs * layerN + pow(layerN,layers) + output * layerN;
float w[how];
</code>```

it says on w[how] that it must be "const" expression(but is is??)

I cannot run the program with this error.

hielp.

答:
Variable-length arrays (VLAs) are an optional feature of C, not C++. Visual Studio 2019 does not support them at all (neither in C nor C++ mode). However, some other compilers support VLAs even in C++ mode. These are compiler-specific extensions, though, and not part of the official C++ standard.

In cases where VLAs are not supported by the compiler, the expression how must be known at compile-time. The reason why the compiler cannot determine the value of how at compile-time is because the expression contains a function call to pow(). Replacing the expression pow( layerN, layers ) with 3*3 (which can be evaluated at compile-time) will make your code work.

In C++, functions declared as constexpr are guaranteed to be evaluated at compile-time. However, the C++ standard library function pow is not declared as constexpr.

Title: Says it cannot be used as constant

Body:
Visual studio 2019

const int inputs = 1, layers = 2, layerN = 3, output = 1;
const int how = inputs * layerN + pow(layerN,layers) + output * layerN;
float w[how];

it says on w[how] that it must be "const" expression(but is is??)

I cannot run the program with this error.

hielp.


问:
o:commandScript - update h:panelGroup after push
I want to use omnifaces push notification which is already working for me.
The only problem is that the container is not updating as soon I got a push notification. Only with a page refresh.

I would like tu update my bell icon:
Bell Icon

Here my code with the strucuture...
Code

Here my code JSF:

```<code>    <h:form id="notificationPushTopbarForm">
    <o:socket channel="notificationChannel"
        user="#{loginBean.currentEmployee.id}" scope="view"
        onmessage="someTestScript">
    </o:socket>

    <o:commandScript name="someTestScript"
        actionListener="#{numberOfUnreadNotificationByEmployeeNotLazyController.findNumberOfUnreadNotification()}"
        immediate="true" render="@parent:topbar_container, :notificationTopbarForm" />

</h:form>

    <h:panelGroup id="topbar_container" styleClass="topbar" layout="block">

    <ul class="topbar-menu">

        <li><p:commandLink id="notificationLink" global="true"
                update=":notificationTopbarForm" resetValues="true"
                oncomplete="PF('notificationSidebar').show()" ajax="true"
                process="@this">
                <i class="topbar-icon fa fa-fw fa-bell-o"></i>
                <h:outputText id="notificationTopbar"
                    value="#{numberOfUnreadNotificationByEmployeeNotLazyController.numberOf}"
                    rendered="#{numberOfUnreadNotificationByEmployeeNotLazyController.numberOf != 0}"
                    styleClass="topbar-badge animated FontBold rubberBand" />
                <h:outputText value="Benachrichtungen"
                    styleClass="topbar-item-name" />
            </p:commandLink> <p:tooltip for="notificationLink" value="Benachrichtungen"
                position="bottom" /></li>
</code>```

Any idea what I´m doing wrong

答:
Change the update attribute to the following:

render=":topbar_container :notificationTopbarForm"
```

Body:
I want to use omnifaces push notification which is already working for me.
The only problem is that the container is not updating as soon I got a push notification. Only with a page refresh.

I would like tu update my bell icon:
Bell Icon

Here my code with the strucuture...
Code

Here my code JSF:

    <h:form id="notificationPushTopbarForm">
    <o:socket channel="notificationChannel"
        user="#{loginBean.currentEmployee.id}" scope="view"
        onmessage="someTestScript">
    </o:socket>

    <o:commandScript name="someTestScript"
        actionListener="#{numberOfUnreadNotificationByEmployeeNotLazyController.findNumberOfUnreadNotification()}"
        immediate="true" render="@parent:topbar_container, :notificationTopbarForm" />

</h:form>

    <h:panelGroup id="topbar_container" styleClass="topbar" layout="block">

                <h:outputText id="notificationTopbar"
                    value="#{numberOfUnreadNotificationByEmployeeNotLazyController.numberOf}"
                    rendered="#{numberOfUnreadNotificationByEmployeeNotLazyController.numberOf != 0}"
                    styleClass="topbar-badge animated FontBold rubberBand" />
                <h:outputText value="Benachrichtungen"
                    styleClass="topbar-item-name" />

Any idea what I´m doing wrong


问:
Adding interface to get request
I am trying to add an interface to my code but am stuck with where and how to put it. Please see my code below.

Service.ts

```<code>getData() {
  return this.httpClient.get(Constants.API_ENDPOINT + 'data.json');
}
</code>```

Component.ts

```<code>ngOnInit() {
  this.apiService.getData().subscribe((res) => {
    console.log(res);
  });
}
</code>```

Interface.ts

```<code>export interface Items {
  name: string;
  description: string;
  url: string;
}
</code>```

How would I change the service.ts to use the interface?

答:
Define the return type on getData

Use the generic overload of HttpClient.get<T> to define the structure of the data being returned.

```<code>getData() : Observable<Items> {
   return this.httpClient.get<Items>(Constants.API_ENDPOINT + 'data.json');
}
</code>```

Title: Adding interface to get request

Body:
I am trying to add an interface to my code but am stuck with where and how to put it. Please see my code below.

Service.ts

getData() {
  return this.httpClient.get(Constants.API_ENDPOINT + 'data.json');
}

Component.ts

ngOnInit() {
  this.apiService.getData().subscribe((res) => {
    console.log(res);
  });
}

Interface.ts

export interface Items {
  name: string;
  description: string;
  url: string;
}

How would I change the service.ts to use the interface?

Body:
Define the return type on getData

Use the generic overload of HttpClient.get<T> to define the structure of the data being returned.

getData() : Observable<Items> {
   return this.httpClient.get<Items>(Constants.API_ENDPOINT + 'data.json');
}


问:
getting undefined in the console after entering either rock,paper or scissors in the prompt
```<code>        <script>

           console.log("enter \game()\ to start the game");

            function computerPlay(){
                let a = ['rock','paper','scissors'];
                let b = a[Math.floor(Math.random * a.length)];
                return b;
            }

            function humanPlay(){
                let c = prompt('rock,paper or scissors');
                return c;
          }

            function playRound ( computerSelection,humanSelection){
                if (computerSelection == humanSelection) {
                    console.log("Its a tie");

                }

               if (computerSelection == 'rock' && humanSelection.toLowerCase() == 'paper') {
                   return 'human wins';

               }

               else if (computerSelection == 'rock' && humanSelection.toLowerCase() == 'scissors') {
                   return 'computer wins';

               }

               else if ( computerSelection == 'paper' && humanSelection.toLowerCase() == 'rock') {
                   return 'computer wins';

               }

               else if (computerSelection == 'paper' && humanSelection.toLowerCase() == 'scissors') {
                   return 'human wins';

               }

               else if (computerSelection == 'scissors' && humanSelection.toLowerCase() == 'rock') {
                   return 'human wins';

               }

               else if (computerSelection == 'scissors' && humanSelection.toLowerCase() == 'paper') {
                   return 'computer wins'

               }

               else if (computerSelection == 'rock' && humanSelection.toLowerCase() == 'scissors') {
                   return 'computer wins';

               }

            }
            function game(){
                computerSelection = computerPlay();
                humanSelection = humanPlay();
                let results = playRound(computerSelection,humanSelection);
                console.log(results);

            }

        </script>
</code>```

I've been trying to code this simple game from the Odin project for 2 hours and i can't wrap my head around why isn't the code working. I have looked at a few student solutions and tried to write my code again and again but it just doesn't seem to work each time. what am i doing wrong in this script?

答:
I think your problem is in this line:

```<code>let b = a[Math.floor(Math.random * a.length)];
</code>```

It should be:

```<code>let b = a[Math.floor(Math.random() * a.length)];
</code>```

Also, you can test your code here: https://js.do/

Hope it helps!

Body:
I think your problem is in this line:

let b = a[Math.floor(Math.random * a.length)];

It should be:

let b = a[Math.floor(Math.random() * a.length)];

Also, you can test your code here: https://js.do/

Hope it helps!


问:
What files does the firebase client upload for firebase functions?
What does the firebase client need to upload the firebase functions? All I can identify is that it takes my files from my lib directory, does something to them, and then uploads everything. Does it take my dependencies also? How does this work?

The reason I'm asking is that I'm trying to use firebase functions with kotlin-js. Kotlin-js natively integrates with webpack, and can integrate with npm dependencies. I can give firebase a single file with all dependencies integrated, but it doesn't seem like firebase is uploading dependencies. It seems like maybe the package.json is being sent up or something.

If I compile to kotlin-js, what portions of my code/dependencies should I put in my lib folder to be uploaded?

答: The CLI uploads everything in the functions folder, except for node_modules.  That will be rebuilt on the server by running npm install. There's not really enough information here to understand what you ought to be doing, but everything that's needed at runtime needs to be in the functions folder.


答:
It doesn't word with const. The const keyword denotes a read-only variable but not necessary a compile-time constant,  is necessary to specify the size of your array.

In other words the only thing const guarantees is that the value of the variable will not change, but not necessarily that it is known before the program executes. To declare an array, the compiler needs to know the size when it compiles.

However C++ 11 introduced the constexpr keyword for this very purpose. constexpr tells the compiler that the value of the variable can be known at compile time.

This code uses constexpr.

```<code>constexpr int inputs = 1, layers = 2, layerN = 3, output = 1;
constexpr int how = inputs * layerN + pow(layerN,layers) + output * layerN;
float w[how];
</code>```

See it live here

This code will work provided that the pow function is declared as a constexpr function (a function declared as constexpr guarantees that it can compute its value at compile-time provided that its arguments are themselves known).

This seems to be the case in the GCC version I linked above but it is not guaranteed to work everywhere. If you want portable code, you can define your own version of the power function which will be constexpr.

EDIT : added detail about potentially non-constexpr pow

Title: Says it cannot be used as constant

Body:
It doesn't word with const. The const keyword denotes a read-only variable but not necessary a compile-time constant,  is necessary to specify the size of your array.

In other words the only thing const guarantees is that the value of the variable will not change, but not necessarily that it is known before the program executes. To declare an array, the compiler needs to know the size when it compiles.

However C++ 11 introduced the constexpr keyword for this very purpose. constexpr tells the compiler that the value of the variable can be known at compile time.

This code uses constexpr.

constexpr int inputs = 1, layers = 2, layerN = 3, output = 1;
constexpr int how = inputs * layerN + pow(layerN,layers) + output * layerN;
float w[how];

See it live here

This code will work provided that the pow function is declared as a constexpr function (a function declared as constexpr guarantees that it can compute its value at compile-time provided that its arguments are themselves known).

This seems to be the case in the GCC version I linked above but it is not guaranteed to work everywhere. If you want portable code, you can define your own version of the power function which will be constexpr.

EDIT : added detail about potentially non-constexpr pow


问:
How to handle returned object from function to avoid memory leaks?
Suppose I have a function

```<code>- (NSString *)fullNameCopy {
    return [[NSString alloc] initWithFormat:@"%@ %@", self.firstName, self.LastName];
}
</code>```

Can somebody tell me how to call this function, how to assign its value to a new object, and how then to release it, avoiding memory leaks, and bad access.

Would it be like

```<code>NSSting *abc = [object fullNameCopy];
</code>```

// Use it and release

```<code>[abc release];
</code>```

or I should alloc abc string too ?

Update:

The point here, Can I return non-autorelease objects from a function and then release them in the calling function. As per Obj-C function naming conventions, a function name containing alloc or copy should return object assuming that calling function has the ownership.

As in above case, my function "fullNameCopy" return a non-autoreleased abject, and I want to release them in the calling function.

答:
Refer this post

UPDATE:

```<code>- (NSString *)fullNameCopy {
    NSString *returnString  = [NSString stringWithFormat:@"%@ %@", self.firstName, self.LastName]; // Autorelease object.
    return returnString;
}

-(void) someFunction {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSString *fullName = [self fullNameCopy];

    [pool release]
}
</code>```

Body:
Suppose I have a function

- (NSString *)fullNameCopy {
    return [[NSString alloc] initWithFormat:@"%@ %@", self.firstName, self.LastName];
}

Can somebody tell me how to call this function, how to assign its value to a new object, and how then to release it, avoiding memory leaks, and bad access.

Would it be like

NSSting *abc = [object fullNameCopy];

// Use it and release

[abc release];

or I should alloc abc string too ?

Update:

The point here, Can I return non-autorelease objects from a function and then release them in the calling function. As per Obj-C function naming conventions, a function name containing alloc or copy should return object assuming that calling function has the ownership.

As in above case, my function "fullNameCopy" return a non-autoreleased abject, and I want to release them in the calling function.

Body:
Refer this post

UPDATE:

- (NSString *)fullNameCopy {
    NSString *returnString  = [NSString stringWithFormat:@"%@ %@", self.firstName, self.LastName]; // Autorelease object.
    return returnString;
}

-(void) someFunction {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSString *fullName = [self fullNameCopy];

    [pool release]
}


问:
Eclipse 4.12 - java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory
I am getting the error below while running my eclipse plugin.
Eclipse used 4.12 with java11. It used to work fine in eclipse 4.6.3 + java8.</p>
```<code>javax.xml.bind.JAXBException: Provider com.sun.xml.internal.bind.v2.ContextFactory not found
 - with linked exception:
[java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory cannot be found by com.my.cep.studio.cluster.topology_0.0.0]

!ENTRY com.my.cep.diagramming 4 0   at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:146)
    at javax.xml.bind.ContextFinder.find(ContextFinder.java:289)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:412)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:375)
    at com.my.cep.studio.cluster.topology.editors.ClusterTopologyDiagramManager.parseFile(ClusterTopologyDiagramManager.java:193)
    at com.my.cep.studio.cluster.topology.editors.ClusterTopologyDiagramManager.openModel(ClusterTopologyDiagramManager.java:175)
    at com.my.cep.diagramming.drawing.BaseDiagramManager.createDrawingCanvas(BaseDiagramManager.java:233)
    at com.my.cep.diagramming.drawing.DiagramManager$2.run(DiagramManager.java:259)
    at java.desktop/java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:313)
    at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:770)
    at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
    at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
    at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:740)
    at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
Caused by: java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory cannot be found by com.my.cep.studio.cluster.topology_0.0.0
    at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:512)
    at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:423)
    at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:415)
    at org.eclipse.osgi.internal.loader.ModuleClassLoader.loadClass(ModuleClassLoader.java:155)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    at javax.xml.bind.ContextFinder.safeLoadClass(ContextFinder.java:480)
    at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:112)
</code>```

答:
I've stumbled upon this question while migrating a big ancient Java application to Java 11. I think the following might come useful.

I had everything in place in my Maven POMs, javax bindings, JAXB's implementation, a few tests working fine. Yet, the original application's tests kept inexplicably complaining that com.sun.xml.internal.bind.v2.ContextFactory is not found.

Indeed, that class isn't in any 3rd-party implementations of JAXB (I'm using the Glassfish's one, but there are several others), and one has to replace the default factory that is instantiated inside  javax.xml.bind.JAXBContext.newInstance( <classes> ) with some new implementation (com.sun.xml.bind.v2.JAXBContextFactory in my case and, I guess, in other JAXB libs too).

And well, one of the ways to set that is via the jaxb.properties file, which must be visible to the classpath (so, in Maven, it's usually somewhere like src/main/resources/*). As it is explained here, this file has to contain:

javax.xml.bind.context.factory=com.sun.xml.bind.v2.JAXBContextFactory
```

In my case, it was containing the old now-disappeared factory. I guess, current JAXB libraries use a correct default factory if they don't meet that file, however it might be already present in your codebase and you might need a while before realising it. I hope that this answer will save you the time I wasted.

Body:
I am getting the error below while running my eclipse plugin.
Eclipse used 4.12 with java11. It used to work fine in eclipse 4.6.3 + java8.

javax.xml.bind.JAXBException: Provider com.sun.xml.internal.bind.v2.ContextFactory not found
 - with linked exception:
[java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory cannot be found by com.my.cep.studio.cluster.topology_0.0.0]

!ENTRY com.my.cep.diagramming 4 0   at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:146)
    at javax.xml.bind.ContextFinder.find(ContextFinder.java:289)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:412)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:375)
    at com.my.cep.studio.cluster.topology.editors.ClusterTopologyDiagramManager.parseFile(ClusterTopologyDiagramManager.java:193)
    at com.my.cep.studio.cluster.topology.editors.ClusterTopologyDiagramManager.openModel(ClusterTopologyDiagramManager.java:175)
    at com.my.cep.diagramming.drawing.BaseDiagramManager.createDrawingCanvas(BaseDiagramManager.java:233)
    at com.my.cep.diagramming.drawing.DiagramManager$2.run(DiagramManager.java:259)
    at java.desktop/java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:313)
    at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:770)
    at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
    at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
    at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:740)
    at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
Caused by: java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory cannot be found by com.my.cep.studio.cluster.topology_0.0.0
    at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:512)
    at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:423)
    at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:415)
    at org.eclipse.osgi.internal.loader.ModuleClassLoader.loadClass(ModuleClassLoader.java:155)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    at javax.xml.bind.ContextFinder.safeLoadClass(ContextFinder.java:480)
    at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:112)

Body:
I've stumbled upon this question while migrating a big ancient Java application to Java 11. I think the following might come useful.

I had everything in place in my Maven POMs, javax bindings, JAXB's implementation, a few tests working fine. Yet, the original application's tests kept inexplicably complaining that com.sun.xml.internal.bind.v2.ContextFactory is not found.

Indeed, that class isn't in any 3rd-party implementations of JAXB (I'm using the Glassfish's one, but there are several others), and one has to replace the default factory that is instantiated inside  javax.xml.bind.JAXBContext.newInstance( <classes> ) with some new implementation (com.sun.xml.bind.v2.JAXBContextFactory in my case and, I guess, in other JAXB libs too).

And well, one of the ways to set that is via the jaxb.properties file, which must be visible to the classpath (so, in Maven, it's usually somewhere like src/main/resources/*). As it is explained here, this file has to contain:

javax.xml.bind.context.factory=com.sun.xml.bind.v2.JAXBContextFactory

In my case, it was containing the old now-disappeared factory. I guess, current JAXB libraries use a correct default factory if they don't meet that file, however it might be already present in your codebase and you might need a while before realising it. I hope that this answer will save you the time I wasted.


问:
EmberJS: Computed property awareness of dependent keys
Let's suppose I have an object that has this structure:
{ filters: [{ params: { value: ["abc"] }] }.

How can I write a computed property that is aware of changes to the value property? For example, let's say we take one of the filters and do set(filter, 'params.value', ["abc", "123"]). I've been trying with computed('filters.@each.params.value.[]', ...) but it isn't working

答:
Alright, I guess I know how to help you. First of all it seems to be impossible to have a computed property with deeply nested keys after @each. That's why in order to make this work one has to split it. Something like this:

```<code>export default Component.extend({
  init() {
    this._super(...arguments);

    this.o = {filters: [{params: {value: ["abc"]}}]};
  },

  params: computed('o.filters.@each.params', function () {
    return this.o.filters.mapBy('params');
  }),

  paramsValue: computed('params.@each.value', function () {
    let aaa = this.params; // it seems like we need to reference the params anyhow
    return JSON.stringify(this.o);
  }),

  @action
  changeClassic() {
    let filter = this.o.filters[0];
    set(filter, 'params.value', ['abc', '123']);
  }

});
</code>```

I also tried to solve the same problem in case of a glimmer component with @tracked. There I had to use a separate class and make the value field tracked:

```<code>class ValueHandler {
  @tracked value;

  constructor(value) {
    this.value = value;
  }
}

export default class DeepObjectTestComponent extends Component {

  @tracked o = {filters: [{params: new ValueHandler('abc')}]};

  // so here I don't need an intermediate computed (hope this works for a more complicated  scenario
  get paramsValue() {
    let aaa = this.o.filters[0].params.value;
    return JSON.stringify(this.o);
  }

  @action
  changeGlimmer() {
    let filter = this.o.filters[0];
    // set(filter, 'params.value', ['abc', '123']);
    filter.params.value = ['abc', '123'];
  }
}

</code>```

Body:
Alright, I guess I know how to help you. First of all it seems to be impossible to have a computed property with deeply nested keys after @each. That's why in order to make this work one has to split it. Something like this:

export default Component.extend({
  init() {
    this._super(...arguments);

    this.o = {filters: [{params: {value: ["abc"]}}]};
  },

  params: computed('o.filters.@each.params', function () {
    return this.o.filters.mapBy('params');
  }),

  paramsValue: computed('params.@each.value', function () {
    let aaa = this.params; // it seems like we need to reference the params anyhow
    return JSON.stringify(this.o);
  }),

  @action
  changeClassic() {
    let filter = this.o.filters[0];
    set(filter, 'params.value', ['abc', '123']);
  }

});

I also tried to solve the same problem in case of a glimmer component with @tracked. There I had to use a separate class and make the value field tracked:

class ValueHandler {
  @tracked value;

  constructor(value) {
    this.value = value;
  }
}

export default class DeepObjectTestComponent extends Component {

  @tracked o = {filters: [{params: new ValueHandler('abc')}]};

  // so here I don't need an intermediate computed (hope this works for a more complicated  scenario
  get paramsValue() {
    let aaa = this.o.filters[0].params.value;
    return JSON.stringify(this.o);
  }

  @action
  changeGlimmer() {
    let filter = this.o.filters[0];
    // set(filter, 'params.value', ['abc', '123']);
    filter.params.value = ['abc', '123'];
  }
}


问:
How could I make my program play sounds according to a key.is_pressed statement?
Consider:

```<code>from playsound import playsound
import keyboard

notes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
while True:
    x = keyboard.is_pressed('')
    try:
        if x = (1):
            playsound('thingthing.wav')
    except ValueError:
        pass
</code>```

I'm trying to make a basic synthesizer that plays basic notes, but the problem is I don’t want to use if else statements way too much, so I decided on using a list. But how could I trigger events using lists?

I want to make a basic synthesizer that works on lists.

```<code>from playsound import playsound
import keyboard
notes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
while True:
    if keyboard.is_pressed('1'):
        playsound('a.wav')
    elif keyboard.is_pressed('2'):
        playsound('b.wav')
    elif keyboard.is_pressed('3'):
        playsound('c.wav')
    elif keyboard.is_pressed('4'):
        playsound('d.wav')
    elif keyboard.is_pressed('5'):
        playsound('e.wav')
    elif keyboard.is_pressed('6'):
        playsound('f.wav')
    elif keyboard.is_pressed('7'):
        playsound('g.wav')
    elif keyboard.is_pressed('8'):
        pass
    elif keyboard.is_pressed('9'):
        pass
    elif keyboard.is_pressed('0'):
        pass
    else:
        pass
    if keyboard.is_pressed('num_1'):
        break
    else:
        pass
</code>```

This is the final code, but I am not happy with it.

答:
```<code>import winsound
import keyboard
alias = winsound.SND_ASYNC | winsound.SND_NODEFAULT
while True:
    y = keyboard.read_key()
    d = "pykeyboardfeedback\\" + y + '.wav'
    winsound.PlaySound(d, alias)
</code>```

It turns out the problem I had was to concentrate way too much on catching an exception and implementing stuff that are both difficult and useless, like the dict there.

It adds y to the folder name and then adds a .wav at the end, so we use it there.

Body:
Consider:

from playsound import playsound
import keyboard

notes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
while True:
    x = keyboard.is_pressed('')
    try:
        if x = (1):
            playsound('thingthing.wav')
    except ValueError:
        pass

I'm trying to make a basic synthesizer that plays basic notes, but the problem is I don’t want to use if else statements way too much, so I decided on using a list. But how could I trigger events using lists?

I want to make a basic synthesizer that works on lists.

from playsound import playsound
import keyboard
notes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
while True:
    if keyboard.is_pressed('1'):
        playsound('a.wav')
    elif keyboard.is_pressed('2'):
        playsound('b.wav')
    elif keyboard.is_pressed('3'):
        playsound('c.wav')
    elif keyboard.is_pressed('4'):
        playsound('d.wav')
    elif keyboard.is_pressed('5'):
        playsound('e.wav')
    elif keyboard.is_pressed('6'):
        playsound('f.wav')
    elif keyboard.is_pressed('7'):
        playsound('g.wav')
    elif keyboard.is_pressed('8'):
        pass
    elif keyboard.is_pressed('9'):
        pass
    elif keyboard.is_pressed('0'):
        pass
    else:
        pass
    if keyboard.is_pressed('num_1'):
        break
    else:
        pass

This is the final code, but I am not happy with it.

Body:
import winsound
import keyboard
alias = winsound.SND_ASYNC | winsound.SND_NODEFAULT
while True:
    y = keyboard.read_key()
    d = "pykeyboardfeedback\\" + y + '.wav'
    winsound.PlaySound(d, alias)

It turns out the problem I had was to concentrate way too much on catching an exception and implementing stuff that are both difficult and useless, like the dict there.

It adds y to the folder name and then adds a .wav at the end, so we use it there.


问:
what better? Use the Provider of asp.net or not use?
what best practice?
If i will not use the provider I will need to make table of Session, roles, my tables and other....

if the provider better, how can I build custom register with connection to another tables(foreign keys)? how can i get the current user in registration(with sessionid?)

Thanks.

答:
Why reinvent he wheel? Best practice would be to use the provider model and if if you have any requirements out of the ordinary create your own custom membership provider (Akram has posted a link on how to do this).

If you are using windows forms there are a lot of examples out there of how to use the membership controls with the membership provider saving you a lot of time.


问:
How to make word triangle in c++ with for loop
how can I make this type of triangle:
where the size of triangle n = 5;

```<code>Five Four Three Two One
Five Four Three Two
Five Four Three
Five Four
Five
</code>```

Here's what I've tried:

```<code>int n;
cout<<"Enter Size of triangle: ";
cin>>n;

for(int i = n; i >= 1; i--){
    for(int j = n; j >= i; j--){
        cout<<j<<" ";
    }
    cout<<endl;
}
</code>```

答:
```<code>for(int i = n; i >= 1; i--){
    for(int j = n; j >= i; j--){
        switch(j) {
            case 0: cout <<"zero"<<; break;
            case 1: cout <<"one"<<; break;
            case 2: cout <<"two"<<; break;
            case 3: cout <<"three"<<; break;
        }
    }
    cout<<endl;
}
</code>```

Body:
how can I make this type of triangle:
where the size of triangle n = 5;

Five Four Three Two One
Five Four Three Two
Five Four Three
Five Four
Five

Here's what I've tried:

int n;
cout<<"Enter Size of triangle: ";
cin>>n;

for(int i = n; i >= 1; i--){
    for(int j = n; j >= i; j--){
        cout<<j<<" ";
    }
    cout<<endl;
}


问:
How to change WPF Material Design Palette at runtime?
I've recently "upgraded" a solution to a VS2017 and .NET Framework 4.6.1.

I've also updated all of the NuGet packages to their latest versions.

This question likely concerns one or more of the following packages (previous versions are in parenthesizes):

```<code>MahApps.Metro by Jan Karger et al. 1.6.5 (1.3.0-ALPHA016)

MaterialDesignColors by James Willock 1.1.3 (1.1.2)

MaterialDesignThemes by James Willock 2.5.0.1205 (1.1.0.234)

MaterialDesignThemes.MahApps by James Willock 0.0.12 (0.0.3)
</code>```

WPF related packages also being referenced include:

```<code>Extended.Wpf.Toolkit by Xceed 3.4.0 (2.6.0)

ControlzEx by Jan Karger et al. 3.0.2.4 (none, new dependency of MahApps.Metro)
</code>```

Prior to the updates, the following would change the UI color palette at runtime:

```<code>private void primaryPaletteComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
   paletteHelper.ReplacePrimaryColor(this.primaryPaletteComboBox.Text);
}

/* Where: */

var paletteHelper = new MaterialDesignThemes.Wpf.PaletteHelper();

this.primaryPaletteComboBox.Items.AddRange(new object[] {
    "Amber",
    "Blue",
    "BlueGrey",
    "Brown",
    "Cyan",
    "DeepOrange",
    "DeepPurple",
    "Green",
    "Grey",
    "Indigo",
    "LightBlue",
    "LightGreen",
    "Lime",
    "Orange",
    "Pink",
    "Purple",
    "Red",
    "Teal",
    "Yellow"});
</code>```

...Super simple, super easy.

After the updates, ReplacePrimaryColor throws the following exception:

System.InvalidOperationException: 'Unable to safely determine a single
  resource definition for SecondaryAccentBrush.'

Downgrading these packages to their previous versions cause other problems.

How can I change the color palette at runtime in the most recent version of these packages?

I would like to do this by simply using the color palette name that the user selects from a ComboBox.

Obviously SecondaryAccentBrush is a problem.

Does anyone know what changed in the last few years?

This should be easy, but Google doesn't give me anything useful. Maybe I'm not asking the right question.

PaletteHelper now provides a ReplacePalette(Palette palette) method that looks promising, perhaps there is a way to instantiate a Palette object by using the name of a predefined resource?

I would rather go to the dentist and proctologist at the same time, than to screw around with XAML resource definitions.

答:
You can achieve this using MDIX PaletteHelper.

For Dark/Light

Drop a ToggleButton on your Ui & bind its isChecked bool to the  isDark bool used below (Binding or Code behind, however you are wiring your ui up)

```<code>    private readonly PaletteHelper _paletteHelper = new PaletteHelper();
</code>```

```<code>    private void ToggleBaseColour(bool isDark)
    {
        ITheme theme = _paletteHelper.GetTheme();
        IBaseTheme baseTheme = isDark ? new MaterialDesignDarkTheme() : (IBaseTheme)new MaterialDesignLightTheme();
        theme.SetBaseTheme(baseTheme);
        _paletteHelper.SetTheme(theme);
    }
</code>```

For Primary & Accent colours

the MDIX GitHub demo apps PaletteSelector VM has well written & easy to read code here

Body:
I've recently "upgraded" a solution to a VS2017 and .NET Framework 4.6.1.

I've also updated all of the NuGet packages to their latest versions.

This question likely concerns one or more of the following packages (previous versions are in parenthesizes):

MahApps.Metro by Jan Karger et al. 1.6.5 (1.3.0-ALPHA016)

MaterialDesignColors by James Willock 1.1.3 (1.1.2)

MaterialDesignThemes by James Willock 2.5.0.1205 (1.1.0.234)

MaterialDesignThemes.MahApps by James Willock 0.0.12 (0.0.3)

WPF related packages also being referenced include:

Extended.Wpf.Toolkit by Xceed 3.4.0 (2.6.0)

ControlzEx by Jan Karger et al. 3.0.2.4 (none, new dependency of MahApps.Metro)

Prior to the updates, the following would change the UI color palette at runtime:

private void primaryPaletteComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
   paletteHelper.ReplacePrimaryColor(this.primaryPaletteComboBox.Text);
}

/* Where: */

var paletteHelper = new MaterialDesignThemes.Wpf.PaletteHelper();

this.primaryPaletteComboBox.Items.AddRange(new object[] {
    "Amber",
    "Blue",
    "BlueGrey",
    "Brown",
    "Cyan",
    "DeepOrange",
    "DeepPurple",
    "Green",
    "Grey",
    "Indigo",
    "LightBlue",
    "LightGreen",
    "Lime",
    "Orange",
    "Pink",
    "Purple",
    "Red",
    "Teal",
    "Yellow"});

...Super simple, super easy.

After the updates, ReplacePrimaryColor throws the following exception:

System.InvalidOperationException: 'Unable to safely determine a single
  resource definition for SecondaryAccentBrush.'

Downgrading these packages to their previous versions cause other problems.

How can I change the color palette at runtime in the most recent version of these packages?

I would like to do this by simply using the color palette name that the user selects from a ComboBox.

Obviously SecondaryAccentBrush is a problem.

Does anyone know what changed in the last few years?

This should be easy, but Google doesn't give me anything useful. Maybe I'm not asking the right question.

PaletteHelper now provides a ReplacePalette(Palette palette) method that looks promising, perhaps there is a way to instantiate a Palette object by using the name of a predefined resource?

I would rather go to the dentist and proctologist at the same time, than to screw around with XAML resource definitions.

Body:
You can achieve this using MDIX PaletteHelper.

For Dark/Light

Drop a ToggleButton on your Ui & bind its isChecked bool to the  isDark bool used below (Binding or Code behind, however you are wiring your ui up)

    private readonly PaletteHelper _paletteHelper = new PaletteHelper();

    private void ToggleBaseColour(bool isDark)
    {
        ITheme theme = _paletteHelper.GetTheme();
        IBaseTheme baseTheme = isDark ? new MaterialDesignDarkTheme() : (IBaseTheme)new MaterialDesignLightTheme();
        theme.SetBaseTheme(baseTheme);
        _paletteHelper.SetTheme(theme);
    }

For Primary & Accent colours

the MDIX GitHub demo apps PaletteSelector VM has well written & easy to read code here


问:
Windows 2019 and PHP 7.3: "session_start(): ps_files_cleanup_dir: opendir failed: No such file or directory (2)"
Having this problem. I know there is similar questions, but none of them provided a solution.

Windows Server 2019 server core

PHP 7.3.7 x64 under IIS.

Error message:

PHP Fatal error: Uncaught ErrorException: session_start():
  ps_files_cleanup_dir: opendir(D:\TempPHP) failed: No such file or
  directory (2).

The directory does exists and it is full of sessions files.

There is FULL permissions (I know, security risk, but I'm first trying to make it work) for the application pool user (IIS AppPool...), IUSR, IIS_IUSRS, LOCAL SERVICE, LOCAL NETWORK, SYSTEM and CREATE OWNER.

The error message seems to shows randomly.

Some relevant php.ini settings:

```<code>session.gc_probability = 1
error_log = "D:\TempPHP\PHP73x64_errors.log"
upload_tmp_dir = "D:\TempPHP\upload"
session.save_path = "D:\TempPHP"
sys_temp_dir = "D:\TempPHP"
</code>```

edit: "D:\" is a local partition. Not a mapped or a shared drive. Logs and sessions are being written successfully. It seems that php just can't remove those files.

答:
Ok, found out the problem.

Seems like that with windows the session.save_path cannot be in a different disk / partition from the PHP executable path. In my case PHP directory was c:\Program Files\PHP\v7.3, so I moved the TempPHP folder from D: to C: partition and changed the value of session.save_path from "D:\TempPHP" to "C:\TempPHP". Now the sess_xxxxx files are automatically cleaned up and there is no more error messages.

Don't know if this holds true for others php or windows versions.

Body:
Having this problem. I know there is similar questions, but none of them provided a solution.

Windows Server 2019 server core

PHP 7.3.7 x64 under IIS.

Error message:

PHP Fatal error: Uncaught ErrorException: session_start():
  ps_files_cleanup_dir: opendir(D:\TempPHP) failed: No such file or
  directory (2).

The directory does exists and it is full of sessions files.

There is FULL permissions (I know, security risk, but I'm first trying to make it work) for the application pool user (IIS AppPool...), IUSR, IIS_IUSRS, LOCAL SERVICE, LOCAL NETWORK, SYSTEM and CREATE OWNER.

The error message seems to shows randomly.

Some relevant php.ini settings:

session.gc_probability = 1
error_log = "D:\TempPHP\PHP73x64_errors.log"
upload_tmp_dir = "D:\TempPHP\upload"
session.save_path = "D:\TempPHP"
sys_temp_dir = "D:\TempPHP"

edit: "D:\" is a local partition. Not a mapped or a shared drive. Logs and sessions are being written successfully. It seems that php just can't remove those files.


问:
JavaScript - Math.random() - parameter
What changes adding the parameter in Math.random()?

For example:

```<code>Math.random() == Math.random(1234)
</code>```

答: It doesn't - Math.random() doesn't take any parameters... :)

Title: JavaScript - Math.random() - parameter

Body:
What changes adding the parameter in Math.random()?

For example:

Math.random() == Math.random(1234)