问:
RxTextView and other widgets not found while using latest com.jakewharton.rxbinding3:rxbinding:3.0.0-alpha2 library
I wanna use RxJava binding APIs for Android UI widgets in my project.

Therefore following the guidance as per this site  'https://github.com/JakeWharton/RxBinding'

But I am unable to import any Android UI widgets in my Kotlin File.
Where as its working fine if I am consuming these widgets in Java File.
Hence, not been to find the actual of this issue.

For reference following are the gradle file and class files(both kotlin and java) using in same project

build.gradle

```<code>dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.0.0-beta01'
    implementation 'androidx.core:core-ktx:1.2.0-alpha01'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.0-alpha4'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha4'
    implementation 'io.reactivex.rxjava2:rxjava:2.2.8'
    implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
    //RxBinding
    implementation 'com.jakewharton.rxbinding3:rxbinding:3.0.0-alpha2'
}
</code>```

BindingExample.java class

RxBindingExample.kt class

Have tried exploring this issue on S.O. but questions or solutions are available for previous version of lib 'com.jakewharton.rxbinding2:rxbinding'

答:
Check this reference:
https://github.com/JakeWharton/RxBinding/blob/master/rxbinding/src/main/java/com/jakewharton/rxbinding3/widget/TextViewTextChangeEventObservable.kt

There are different ways to use depending on the language, note the @file:JvmName("RxTextView") at the start. If you're using java the class RxTextView is visible, in kotlin you should use the extension functions provided by the lib, textChangeEvents() is an example of it.

like that, this will aquire the observable e.g.:

```<code>val someTextView = TextView(context)
someTextView.textChangeEvents()
</code>```

Edit:

Seems that the old class that I've referenced was deleted, here is another one:
https://github.com/JakeWharton/RxBinding/blob/master/rxbinding/src/main/java/com/jakewharton/rxbinding4/widget/TextViewAfterTextChangeEventObservable.kt

Body:
I wanna use RxJava binding APIs for Android UI widgets in my project.

Therefore following the guidance as per this site  'https://github.com/JakeWharton/RxBinding'

But I am unable to import any Android UI widgets in my Kotlin File.
Where as its working fine if I am consuming these widgets in Java File.
Hence, not been to find the actual of this issue.

For reference following are the gradle file and class files(both kotlin and java) using in same project

build.gradle

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.0.0-beta01'
    implementation 'androidx.core:core-ktx:1.2.0-alpha01'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.0-alpha4'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha4'
    implementation 'io.reactivex.rxjava2:rxjava:2.2.8'
    implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
    //RxBinding
    implementation 'com.jakewharton.rxbinding3:rxbinding:3.0.0-alpha2'
}

BindingExample.java class

RxBindingExample.kt class

Have tried exploring this issue on S.O. but questions or solutions are available for previous version of lib 'com.jakewharton.rxbinding2:rxbinding'

Body:
Check this reference:
https://github.com/JakeWharton/RxBinding/blob/master/rxbinding/src/main/java/com/jakewharton/rxbinding3/widget/TextViewTextChangeEventObservable.kt

There are different ways to use depending on the language, note the @file:JvmName("RxTextView") at the start. If you're using java the class RxTextView is visible, in kotlin you should use the extension functions provided by the lib, textChangeEvents() is an example of it.

like that, this will aquire the observable e.g.:

val someTextView = TextView(context)
someTextView.textChangeEvents()

Edit:

Seems that the old class that I've referenced was deleted, here is another one:
https://github.com/JakeWharton/RxBinding/blob/master/rxbinding/src/main/java/com/jakewharton/rxbinding4/widget/TextViewAfterTextChangeEventObservable.kt


来源: stackexchange

问:
How to save a sound to Download folder of Internal Memory
I have a soundboard with a number of sounds contained in the Raw folder. Each button corresponds to a sound being played when clicked.

I'd like to long click on a sound and save that .mp3 file to the Download folder of the phone's storage. My phone does not have SD Card capability, so it would be to the Internal Memory only.

I have some code for now, which I have experimented with to try and save a sound to the app's location, but I am not aware of how to change that to relate to Downloads instead.

Is anybody able to help out please? I have attached some of my code below in case it is needed. Many thanks.

```<code>@Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            setContentView(R.layout.activity_second);

            Button a;

            a = findViewById(R.id.button11);

           final String path = Environment.getExternalStorageDirectory().getPath()
                    + "/media/audio/";

            a.setOnLongClickListener(new View.OnLongClickListener() {
                public boolean onLongClick(View arg0) {

                    try {
                        copyRAWtoPhone(R.raw.addressmeassir, path);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    return true;
                }

                private void copyRAWtoPhone(int id, String path) throws IOException {

                    InputStream in = getResources().openRawResource(id);
                    FileOutputStream out = new FileOutputStream(path);
                    byte[] buff = new byte[1024];
                    int read = 0;
                    try {
                        while ((read = in.read(buff)) > 0) {
                            out.write(buff, 0, read);
                        }
                    } finally {
                        in.close();
                        out.close();
                    }

                }
            });
</code>```

答:
Saving to Download folder:

```<code> val file = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), name)
  if (writeToFile_1(Objects.requireNonNull<ResponseBody>(response.body()), file)) {
   Toast.makeText(context.applicationContext, "File was downloaded.", Toast.LENGTH_SHORT).show()
   } else {
   Toast.makeText(context.applicationContext, "Error.", Toast.LENGTH_SHORT).show()
}
</code>```

and file creating:

```<code>private fun writeToFile_1(body: ResponseBody, file: File): Boolean {
        var inputStream: InputStream? = null
        var outputStream: OutputStream? = null
        try {
            inputStream = body.byteStream()
            outputStream = FileOutputStream(file)

            val buffer = ByteArray(4096)
            while (true) {
                val read = inputStream.read(buffer)
                if (read < 0) break
                outputStream.write(buffer, 0, read)
            }
            outputStream.close()
            return true
        } catch (e: IOException) {
            e.printStackTrace()
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }

            }
            if (outputStream != null) {
                try {
                    outputStream.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }

            }
        }
        return false
    }
</code>```

I use this method for saving files from server, but you can write some another byte[] I hope that you will got the main idea of my method. You have to get byte[] of your sound and then write to file via my method. Good luck :)

ContentLicense: CC BY-SA 4.0

Body:
I have a soundboard with a number of sounds contained in the Raw folder. Each button corresponds to a sound being played when clicked.

I'd like to long click on a sound and save that .mp3 file to the Download folder of the phone's storage. My phone does not have SD Card capability, so it would be to the Internal Memory only.

I have some code for now, which I have experimented with to try and save a sound to the app's location, but I am not aware of how to change that to relate to Downloads instead.

Is anybody able to help out please? I have attached some of my code below in case it is needed. Many thanks.

@Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            setContentView(R.layout.activity_second);

            Button a;

            a = findViewById(R.id.button11);

           final String path = Environment.getExternalStorageDirectory().getPath()
                    + "/media/audio/";

            a.setOnLongClickListener(new View.OnLongClickListener() {
                public boolean onLongClick(View arg0) {

                    try {
                        copyRAWtoPhone(R.raw.addressmeassir, path);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    return true;
                }

                private void copyRAWtoPhone(int id, String path) throws IOException {

                    InputStream in = getResources().openRawResource(id);
                    FileOutputStream out = new FileOutputStream(path);
                    byte[] buff = new byte[1024];
                    int read = 0;
                    try {
                        while ((read = in.read(buff)) > 0) {
                            out.write(buff, 0, read);
                        }
                    } finally {
                        in.close();
                        out.close();
                    }

                }
            });

Body:
Saving to Download folder:

 val file = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), name)
  if (writeToFile_1(Objects.requireNonNull<ResponseBody>(response.body()), file)) {
   Toast.makeText(context.applicationContext, "File was downloaded.", Toast.LENGTH_SHORT).show()
   } else {
   Toast.makeText(context.applicationContext, "Error.", Toast.LENGTH_SHORT).show()
}

and file creating:

private fun writeToFile_1(body: ResponseBody, file: File): Boolean {
        var inputStream: InputStream? = null
        var outputStream: OutputStream? = null
        try {
            inputStream = body.byteStream()
            outputStream = FileOutputStream(file)

            val buffer = ByteArray(4096)
            while (true) {
                val read = inputStream.read(buffer)
                if (read < 0) break
                outputStream.write(buffer, 0, read)
            }
            outputStream.close()
            return true
        } catch (e: IOException) {
            e.printStackTrace()
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }

            }
            if (outputStream != null) {
                try {
                    outputStream.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }

            }
        }
        return false
    }

I use this method for saving files from server, but you can write some another byte[] I hope that you will got the main idea of my method. You have to get byte[] of your sound and then write to file via my method. Good luck :)


问:
Pass Range Cells for Copy-Paste: Excel VBA
I have to pass 2 cells (reference or value) from one sub to another sub so that the value in the first cell is copied and pasted to the other cell.
Since it is required for multiple cell combinations, I want to get it done by passing the cell (reference or value) from one subroutine to other.

I've tried the following code and combination with Byref and ByVal options. But unable to get the desired results.
Essentially, in the below code, whatever value is present in cell E1792 should be copy-pasted to C1799 as Value and Number formatted.

```<code>Private Sub Copy_Val(ByRef CopyFrom As Range, ByRef PasteTo As Range)
Application.ScreenUpdating = False

    Range(CopyFrom).Select
    Selection.Copy
    Range(PasteTo).Select

    Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
        xlNone, SkipBlanks:=False, Transpose:=False

End Sub

Sub Apply_Filter()
    Dim CpFrm As Range
    Dim PstTo As Range
    Set CpFrm = Range("E1792")
    Set PstTo = Range("C1799")
    Call Copy_Val(CpFrm, PstTo)
End Sub
</code>```

Sometimes I get Type Mismatch error, and sometimes "400" error.
Expected output is that the cell value present in cell E1792 should be copy-pasted to C1799 as Value and Number formatted.

Any help in fixing this will be appreciated.

答:
You could try:</p>

```<code>Option Explicit

Public Sub Copy_Val(ByVal CopyFrom As Range, ByVal PasteTo As Range)

    Application.ScreenUpdating = False

        CopyFrom.Copy
        PasteTo.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
            xlNone, SkipBlanks:=False, Transpose:=False

    Application.ScreenUpdating = True

End Sub

Sub Apply_Filter()

    With ThisWorkbook.Sheets("Sheet1")

        Call Copy_Val(.Range("E1792"), .Range("C1799"))

    End With

End Sub
</code>```

Body:
I have to pass 2 cells (reference or value) from one sub to another sub so that the value in the first cell is copied and pasted to the other cell.
Since it is required for multiple cell combinations, I want to get it done by passing the cell (reference or value) from one subroutine to other.

I've tried the following code and combination with Byref and ByVal options. But unable to get the desired results.
Essentially, in the below code, whatever value is present in cell E1792 should be copy-pasted to C1799 as Value and Number formatted.

Private Sub Copy_Val(ByRef CopyFrom As Range, ByRef PasteTo As Range)
Application.ScreenUpdating = False

    Range(CopyFrom).Select
    Selection.Copy
    Range(PasteTo).Select

    Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
        xlNone, SkipBlanks:=False, Transpose:=False

End Sub

Sub Apply_Filter()
    Dim CpFrm As Range
    Dim PstTo As Range
    Set CpFrm = Range("E1792")
    Set PstTo = Range("C1799")
    Call Copy_Val(CpFrm, PstTo)
End Sub

Sometimes I get Type Mismatch error, and sometimes "400" error.
Expected output is that the cell value present in cell E1792 should be copy-pasted to C1799 as Value and Number formatted.

Any help in fixing this will be appreciated.

Body:
You could try:

Option Explicit

Public Sub Copy_Val(ByVal CopyFrom As Range, ByVal PasteTo As Range)

    Application.ScreenUpdating = False

        CopyFrom.Copy
        PasteTo.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
            xlNone, SkipBlanks:=False, Transpose:=False

    Application.ScreenUpdating = True

End Sub

Sub Apply_Filter()

    With ThisWorkbook.Sheets("Sheet1")

        Call Copy_Val(.Range("E1792"), .Range("C1799"))

    End With

End Sub


问:
What does XmlReader.Parse() do?
edit: The project is an old project and the below code is one class in there that handles the xml.

There is a question to get the xsd from an old legacy application, but all it seems to be doing is: xmlReader.ParseXml(fileName,outputFile); in the ProcessXml() method.

```<code>using System;
using System.IO;
using System.Configuration;
using Utilities;
namespace JobProcessor
{

public class XmlJob : Job
{
    #region variables
    private string      ftpServer;
    private string      ftpUserName;
    private string      ftpPassWord;
    private string      ftpDestination;
    ///<summary>The xml reader used to get validation information from the xmp parsing</summary>
    protected XmlReader xmlReader   = new XmlReader();

    private string      outputFile;

    public XmlJob(string fileName, string type) : base(fileName, type){
        ftpServer       = ConfigurationManager.AppSettings[type + "-ftp"];
        ftpUserName     = ConfigurationManager.AppSettings[type + "-ftpUser"];
        ftpPassWord     = ConfigurationManager.AppSettings[type + "-ftpPass"];
        ftpDestination  = ConfigurationManager.AppSettings[type + "-ftpDest"];
    }

    protected bool ConfigureXmlReader(){
        int    recType    = 0;

        try{
            //set up the record types (i.e. the elements that trigger a new record in the output
            while(ConfigurationManager.AppSettings[type + "-RecordType" + recType.ToString("00")] != null){
                xmlReader.AddRecordType(ConfigurationManager.AppSettings[type + "-RecordType" + recType.ToString("00")],recType.ToString("00"));
                recType++;
            }
            //store the number of types
            xmlReader.SetNoRecordTypes(recType);
        }catch(Exception e){
            HandleError("Error loading record types\r\n" + e.ToString() + "\r\n" + e.StackTrace + "\r\n");
            return(false);
        }

        try{
            //set up the fields which make up each record type
            for(int i=0;i<recType;i++){
                xmlReader.AddFieldsList(i,ConfigurationManager.AppSettings[type + "-" + i.ToString("00") + "Fields"]);
            }
        }catch(Exception e){
            HandleError("Error loading field list\r\n" + e.ToString() + "\r\n" + e.StackTrace + "\r\n");
            return(false);
        }
        return(true);
    }

    public override void RunJob(){
        outputFile = Path.Combine(destinationDirectory, Path.GetFileNameWithoutExtension(fileName) + ".flat");

        if(!ConfigureXmlReader()){
            return;
        }

        if(!CheckInputFile()){
            return;
        }

        if(!ProcessXml()){
            return;
        }

        if(!Validate()){
            return;
        }

        if(ftpServer!=null && ftpUserName!=null && ftpPassWord!=null && ftpDestination!=null){
            if(!FtpFile()){
                return;
            }
        }

        MoveOriginalFile();
    }

    protected virtual bool Validate(){
        return(true);
    }

    protected bool ProcessXml(){
        /*
         * Process the xml file into a delimited format
         */

        try{
            xmlReader.ParseXml(fileName,outputFile);
        }catch(Exception e){
            HandleError("Error parsing XML file\r\n" + e.ToString() + "\r\n" + e.StackTrace + "\r\n");
            return(false);
        }
        return(true);
    }
    protected bool FtpFile(){
        try{
            FtpMethods.UploadFile(ftpServer,ftpUserName,ftpPassWord,outputFile,ftpDestination);
        }catch(Exception e){
            HandleError("Error FTPing file\r\n" + e.ToString() + "\r\n" + e.StackTrace + "\r\n");
            return(false);
        }
        return(true);
    }

    #endregion
}
</code>```

}

What exactly does this command do? F1 doesn't find anything and searching google gets me to a lot of xmlTextReaders.

答: The XmlReader class you are using is a custom class, most likely it is Utilities.XmlReader. We can't say anything about it, because it is a class written by you or a co worker.

ContentLicense: CC BY-SA 3.0

Title: What does XmlReader.Parse() do?

Body:
edit: The project is an old project and the below code is one class in there that handles the xml.

There is a question to get the xsd from an old legacy application, but all it seems to be doing is: xmlReader.ParseXml(fileName,outputFile); in the ProcessXml() method.

using System;
using System.IO;
using System.Configuration;
using Utilities;
namespace JobProcessor
{

public class XmlJob : Job
{
    #region variables
    private string      ftpServer;
    private string      ftpUserName;
    private string      ftpPassWord;
    private string      ftpDestination;
    ///The xml reader used to get validation information from the xmp parsing
    protected XmlReader xmlReader   = new XmlReader();

    private string      outputFile;

    public XmlJob(string fileName, string type) : base(fileName, type){
        ftpServer       = ConfigurationManager.AppSettings[type + "-ftp"];
        ftpUserName     = ConfigurationManager.AppSettings[type + "-ftpUser"];
        ftpPassWord     = ConfigurationManager.AppSettings[type + "-ftpPass"];
        ftpDestination  = ConfigurationManager.AppSettings[type + "-ftpDest"];
    }

    protected bool ConfigureXmlReader(){
        int    recType    = 0;

        try{
            //set up the record types (i.e. the elements that trigger a new record in the output
            while(ConfigurationManager.AppSettings[type + "-RecordType" + recType.ToString("00")] != null){
                xmlReader.AddRecordType(ConfigurationManager.AppSettings[type + "-RecordType" + recType.ToString("00")],recType.ToString("00"));
                recType++;
            }
            //store the number of types
            xmlReader.SetNoRecordTypes(recType);
        }catch(Exception e){
            HandleError("Error loading record types\r\n" + e.ToString() + "\r\n" + e.StackTrace + "\r\n");
            return(false);
        }

        try{
            //set up the fields which make up each record type
            for(int i=0;i<recType;i++){
                xmlReader.AddFieldsList(i,ConfigurationManager.AppSettings[type + "-" + i.ToString("00") + "Fields"]);
            }
        }catch(Exception e){
            HandleError("Error loading field list\r\n" + e.ToString() + "\r\n" + e.StackTrace + "\r\n");
            return(false);
        }
        return(true);
    }

    public override void RunJob(){
        outputFile = Path.Combine(destinationDirectory, Path.GetFileNameWithoutExtension(fileName) + ".flat");

        if(!ConfigureXmlReader()){
            return;
        }

        if(!CheckInputFile()){
            return;
        }

        if(!ProcessXml()){
            return;
        }

        if(!Validate()){
            return;
        }

        if(ftpServer!=null && ftpUserName!=null && ftpPassWord!=null && ftpDestination!=null){
            if(!FtpFile()){
                return;
            }
        }

        MoveOriginalFile();
    }

    protected virtual bool Validate(){
        return(true);
    }

    protected bool ProcessXml(){
        /*
         * Process the xml file into a delimited format
         */

        try{
            xmlReader.ParseXml(fileName,outputFile);
        }catch(Exception e){
            HandleError("Error parsing XML file\r\n" + e.ToString() + "\r\n" + e.StackTrace + "\r\n");
            return(false);
        }
        return(true);
    }
    protected bool FtpFile(){
        try{
            FtpMethods.UploadFile(ftpServer,ftpUserName,ftpPassWord,outputFile,ftpDestination);
        }catch(Exception e){
            HandleError("Error FTPing file\r\n" + e.ToString() + "\r\n" + e.StackTrace + "\r\n");
            return(false);
        }
        return(true);
    }

    #endregion
}

}

What exactly does this command do? F1 doesn't find anything and searching google gets me to a lot of xmlTextReaders.


问:
How to modify a CSS display property from JavaScript?
I'm trying to change the display CSS property of a
 tag when the user changes the value of a <select>.

Here is my HTML code :

```<code><select type="text" name="category" onblur="display_hidden_fields();">
    <option><!-- Content --></option>
    <option><!-- Content --></option>
</select>

<div id="hidden" style="display:none;">
    <label for="test">Label</font></label>
    <select type="text" name="test">
        <option value="1">Default</option>
        <option value="2">Value1</option>
        <option value="3">Value2</option>
    </select>
</div>
</code>```

(note that's a simplified version of my code. Actually, every  and <select> are in . I think it doesn't matter)

Now, my JS code :

```<code>function display_hidden_fields()
{
    alert("JS Function");
    document.getElementById("hidden").style.display = "block";
}
</code>```

Well. When I select a new <option> in the first <select> named "category", I get the alert "JS Function". So my display_hidden_fields() function is correctly executed.

But the second line of this function does... nothing ! My
 named "hidden" is not displayed :(

It seems to me there is nothing wrong in my code. Moreover, I tried many variants.

 - Like specifying style="display:block" in the
 properties, and changing it to "none" in the JS.

 - Or trying to use other properties like "inline", "inline-block", ...

 - Or using "visibility" instead of "display"

 - Or not specifying any property at all in the HTML.

Does anyone can help me ? :)

Thanks.

[EDIT] Important observation

I think I found something interesting. It seems that a
 with display:none; mixed with
 and  is completely nonfunctional. Here is my real code :

```<code><tr>
    <div id="hidden" style="display:none;">
        <td class="depot_table_left">
            <label for="sexe">Sexe</label>
        </td>
        <td>
            <select type="text" name="sexe">
                <option value="1">Sexe</option>
                <option value="2">Joueur</option>
                <option value="3">Joueuse</option>
            </select>
        </td>
    </div>
</tr>
</code>```

The content of the
 is still displayed. And I can try to change it in any way in JS, it doesn't work.
I also tried to remove the
,
 and  tags, and it works fine. But I need this table...

答:
CSS properties should be set by cssText property or setAttribute method.

```<code>// Set multiple styles in a single statement
elt.style.cssText = "color: blue; border: 1px solid black";
// Or
elt.setAttribute("style", "color:red; border: 1px solid blue;");
</code>```

Styles should not be set by assigning a string directly to the style property (as in elt.style = "color: blue;"), since it is considered read-only, as the style attribute returns a CSSStyleDeclaration object which is also read-only.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to change the display CSS property of a
 tag when the user changes the value of a <select>.

Here is my HTML code :

<select type="text" name="category" onblur="display_hidden_fields();">
    <option></option>
    <option></option>
</select>

    Label
    <select type="text" name="test">
        <option value="1">Default</option>
        <option value="2">Value1</option>
        <option value="3">Value2</option>
    </select>

(note that's a simplified version of my code. Actually, every  and <select> are in . I think it doesn't matter)

Now, my JS code :

function display_hidden_fields()
{
    alert("JS Function");
    document.getElementById("hidden").style.display = "block";
}

Well. When I select a new <option> in the first <select> named "category", I get the alert "JS Function". So my display_hidden_fields() function is correctly executed.

But the second line of this function does... nothing ! My
 named "hidden" is not displayed :(

It seems to me there is nothing wrong in my code. Moreover, I tried many variants.

 - Like specifying style="display:block" in the
 properties, and changing it to "none" in the JS.

 - Or trying to use other properties like "inline", "inline-block", ...

 - Or using "visibility" instead of "display"

 - Or not specifying any property at all in the HTML.

Does anyone can help me ? :)

Thanks.

[EDIT] Important observation

I think I found something interesting. It seems that a
 with display:none; mixed with
 and  is completely nonfunctional. Here is my real code :

            Sexe

            <select type="text" name="sexe">
                <option value="1">Sexe</option>
                <option value="2">Joueur</option>
                <option value="3">Joueuse</option>
            </select>

The content of the
 is still displayed. And I can try to change it in any way in JS, it doesn't work.
I also tried to remove the
,
 and  tags, and it works fine. But I need this table...

Body:
CSS properties should be set by cssText property or setAttribute method.

// Set multiple styles in a single statement
elt.style.cssText = "color: blue; border: 1px solid black";
// Or
elt.setAttribute("style", "color:red; border: 1px solid blue;");

Styles should not be set by assigning a string directly to the style property (as in elt.style = "color: blue;"), since it is considered read-only, as the style attribute returns a CSSStyleDeclaration object which is also read-only.


问:
is there a way to examine if an angle is a right angle programmatically?
i plot an angle in python

here is the code

```<code>x = [0,0.5,1]
y = [0,0.5,0]
plt.scatter(x,y)
plt.plot(x,y)
plt.show()
</code>```

is there a way to examine if the angle is a right angle programmatically?

答:
The other answers do not really care about possible inaccuracies and truncation errors, nor efficiency.

Rather than an exact comparison to 90° (or 0° in case of dot product), it is wiser to check for a small angle difference to 90° (resp. 0°).

Also wise to avoid divisions, square roots and trigonometric functions. The cross-product method is among the most attractive.

Compute the cross-product of the sides of the angle and their squared lengths, and compare
with a precomputed tolerance:

```<code>(ABx . BCy - ABy . BCx)² ≥ α.(ABx² + ABy²).(BCx² + BCy²)
</code>```

with α = cos²δ where δ is the angle tolerance.

Body:
i plot an angle in python

here is the code

x = [0,0.5,1]
y = [0,0.5,0]
plt.scatter(x,y)
plt.plot(x,y)
plt.show()

is there a way to examine if the angle is a right angle programmatically?

Body:
The other answers do not really care about possible inaccuracies and truncation errors, nor efficiency.

Rather than an exact comparison to 90° (or 0° in case of dot product), it is wiser to check for a small angle difference to 90° (resp. 0°).

Also wise to avoid divisions, square roots and trigonometric functions. The cross-product method is among the most attractive.

Compute the cross-product of the sides of the angle and their squared lengths, and compare
with a precomputed tolerance:

(ABx . BCy - ABy . BCx)² ≥ α.(ABx² + ABy²).(BCx² + BCy²)

with α = cos²δ where δ is the angle tolerance.


问:
How to fix dynamic variable assignment conflict in Python
How do I fix the variable assignment in this Python code? So, I have this python code:

```<code>with open('save.data') as fp:
    save_data = [line.split(' = ') for line in fp.read().splitlines()]
with open('brute.txt') as fp:
    brute = fp.read().splitlines()
for username, password in save_data:
    if username in brute:
        break
else:
    print("didn't find the username")
</code>```

Okay so, a quick explanation; thesave.data is a file that contains variables of Batch-file game (such as username, hp etc...) and brute.txt is a file that contains "random" strings (like what seen in wordlists used for brute-force).

save.data:

```<code>username1 = PlayerName
password1 = PlayerPass
hp = 100
</code>```

As I said before, it's a Batch-file game so, no need to quote strings.

brute.txt:

```<code>username
username1
password
password1
health
hp
</code>```

So, when the Python code is executed, it loads the two files contents and save them into a list and then iterate through the username and password "brute" them until they match with what on brute.txt, and they assign themselves automatically. But, the problem is with the assignment, when i try to print them (the variables) this happens:

```<code>## We did all the previous code
...
>>> print(save_data)

[['username', 'PlayerName'], ['password', 'PlayerPass'], ['health', '100']]
>>> print("Your username is: " + username)

username
>> print("Your password is: " + password)

PlayerName
>> print("Your health is: " + hp)

NameError: name 'hp' is not defined
</code>```

So, any idea on how to fix the assignment conflict? If you didn't understand something, kindly comment it and I will clear it up.

答:
and they assign themselves automatically

This isn't a thing.  I suppose you're imagining that the pseudo-variables pseudo-defined in save.data will become Python variables in your program.  They won't.

Instead, parse them into a data structure and retrieve the values from the data structure.

For example,

```<code>with open('save.data') as fp:
    save_data = dict([line.split(' = ') for line in fp.read().splitlines()])

...

print(save_data["hp"])
</code>```

Body:
How do I fix the variable assignment in this Python code? So, I have this python code:

with open('save.data') as fp:
    save_data = [line.split(' = ') for line in fp.read().splitlines()]
with open('brute.txt') as fp:
    brute = fp.read().splitlines()
for username, password in save_data:
    if username in brute:
        break
else:
    print("didn't find the username")

Okay so, a quick explanation; thesave.data is a file that contains variables of Batch-file game (such as username, hp etc...) and brute.txt is a file that contains "random" strings (like what seen in wordlists used for brute-force).

save.data:

username1 = PlayerName
password1 = PlayerPass
hp = 100

As I said before, it's a Batch-file game so, no need to quote strings.

brute.txt:

username
username1
password
password1
health
hp

So, when the Python code is executed, it loads the two files contents and save them into a list and then iterate through the username and password "brute" them until they match with what on brute.txt, and they assign themselves automatically. But, the problem is with the assignment, when i try to print them (the variables) this happens:

## We did all the previous code
...
>>> print(save_data)

[['username', 'PlayerName'], ['password', 'PlayerPass'], ['health', '100']]
>>> print("Your username is: " + username)

username
>> print("Your password is: " + password)

PlayerName
>> print("Your health is: " + hp)

NameError: name 'hp' is not defined

So, any idea on how to fix the assignment conflict? If you didn't understand something, kindly comment it and I will clear it up.

Body:
and they assign themselves automatically

This isn't a thing.  I suppose you're imagining that the pseudo-variables pseudo-defined in save.data will become Python variables in your program.  They won't.

Instead, parse them into a data structure and retrieve the values from the data structure.

For example,

with open('save.data') as fp:
    save_data = dict([line.split(' = ') for line in fp.read().splitlines()])

...

print(save_data["hp"])


问:
Start a process in Powershell v2 with user credentials and a hidden window
How to do this in Powershell v2.0 ?

```<code>Start-Process cmd.exe -Credential $MyCred -WindowStyle Hidden;
</code>```

i.e. start a process while giving user credentials and hiding the window.

When i execute each one separately it just works fine.

答:
You may try something like this:</p>

```<code>$cred=Get-Credential
Start-Process cmd.exe -Credential $cred -WindowStyle Hidden
</code>```

Body:
How to do this in Powershell v2.0 ?

Start-Process cmd.exe -Credential $MyCred -WindowStyle Hidden;

i.e. start a process while giving user credentials and hiding the window.

When i execute each one separately it just works fine.

Body:
You may try something like this:

$cred=Get-Credential
Start-Process cmd.exe -Credential $cred -WindowStyle Hidden


问:
Is that possible to make button click if it is from Directive
Why this hi() is not calling?

InnerHTML button click is not working?

this code is inside Directive

```<code>@HostListener('mouseenter') onMouseEnter() {
 this.el.nativeElement.innerHTML ="<button (click)=hi()>dasdsad</button>";
  this.el.nativeElement.style.backgroundColor = this.hc;
}
</code>```

hi() mehod is from app.component and in app.component.html

```<code><p appMillahint="pink" dc="yellow" text="name" ml="#9c27b0" me="red" mo="blue">
  Start editing to see some magic happen :) {{name}}
</p>
</code>```

full code

```<code>import { Directive } from '@angular/core';
import { ElementRef ,HostListener,Input } from '@angular/core';
import {MatTooltipModule} from '@angular/material/tooltip';
import { OverlayModule } from '@angular/cdk/overlay';

@Directive({
  selector: '[appMillahint]'
})
export class MillahintDirective {
@Input('appMillahint') hc: string;
@Input() dc: string;
@Input() mo: string;
@Input() callback2:Function;
@Input() me: string;
@Input() ml: string;
@Input() text: string;
@Input() rt:String;
  constructor(   private el:ElementRef) {
    el.nativeElement.style.backgroundColor = this.dc;
    this.text="milla";

  }

      ngOnInit() {
       this.    el.nativeElement.innerHTML ='<style>'+this.ribbonstyle+'</style><h1 class="ribbon">  <strong class="ribbon-content">'+this.rt+'</strong></h1>';
    }
  @HostListener('onmouseover') onmouseover(){
  this.    el.nativeElement.style.backgroundColor =this.mo;
}@HostListener('mouseenter') onMouseEnter() {
 this.    el.nativeElement.innerHTML ='<style>'+this.ribbonstyle+'</style><h1 class="ribbon">  <strong class="ribbon-content">'+this.rt+'</strong></h1>';

  //this.    el.nativeElement.style.backgroundColor = this.hc;

}table=' <style> table {  font-family: arial, sans-serif;   border-collapse: collapse;  width: 100%;}  td, th { border: 1px solid #dddddd; text-align: left; padding: 8px;}  tr:nth-child(even) { background-color: #dddddd; } </style><table>  <tr>   <th>Company</th>  <th>Contact</th>  <th>Country</th>  </tr>  <tr>  <td>Alfreds Futterkiste</td>  <td>Maria Anders</td>  <td>Germany</td>  </tr> <tr>  <td>Centro comercial Moctezuma</td>   <td>Francisco Chang</td>  <td>Mexico</td>  </tr> <tr>   <td>Ernst Handel</td>  <td>Roland Mendel</td>   <td>Austria</td>  </tr> <tr>  <td>Island Trading</td>  <td>Helen Bennett</td>  <td>UK</td>  </tr>  <tr>  <td>Laughing Bacchus Winecellars</td>   <td>Yoshi Tannamuri</td>  <td>Canada</td> </tr> <tr>  <td>Giovanni Rovelli</td>   </tr> </table>';
  ribbonstyle='.ribbon { font-size: 16px !important;  width: 50%; position: relative; background: #ba89b6; color: #fff; text-align: center; padding: 1em 2em; /* Adjust to suit */ margin: 2em auto 3em;   } .ribbon:before, .ribbon:after { content: ""; position: absolute; display: block; bottom: -1em; border: 1.5em solid #986794; z-index: -1; } .ribbon:before { left: -2em; border-right-width: 1.5em; border-left-color: transparent; } .ribbon:after { right: -2em; border-left-width: 1.5em; border-right-color: transparent; } .ribbon .ribbon-content:before, .ribbon .ribbon-content:after { content: ""; position: absolute; display: block; border-style: solid; border-color: #804f7c transparent transparent transparent; bottom: -1em; } .ribbon .ribbon-content:before { left: 0; border-width: 1em 0 0 1em; } .ribbon .ribbon-content:after { right: 0; border-width: 1em 1em 0 0; }';

 @HostListener('mouseleave') onMouseLeave() {

    this.    el.nativeElement.innerText="i am milla";
   //  this.    el.nativeElement.style.backgroundColor = this.ml;
  }
</code>```

}

答:
In Angular you can't add templates like this. Do the following changes.

Inject ViewContainerRef and ElementRef in directive constructor

```<code>constructor(private vc: ViewContainerRef, private tl: TemplateRef, private El: ElementRef<any>) {
 this.vc.createEmbeddedView(this.tl);
 this.el.nativeElement.style.backgroundColor = this.hc;
}

</code>```

use the directive inside the ng-template

```<code><ng-template appMillahint="pink">
   <p dc="yellow" text="name" ml="#9c27b0" me="red" mo="blue">
     Start editing to see some magic happen :) {{name}}
   <button (click)=hi()>dasdsad</button>
   </p>
</ng-template>

</code>```

Body:
Why this hi() is not calling?

InnerHTML button click is not working?

this code is inside Directive

@HostListener('mouseenter') onMouseEnter() {
 this.el.nativeElement.innerHTML ="<button (click)=hi()>dasdsad</button>";
  this.el.nativeElement.style.backgroundColor = this.hc;
}

hi() mehod is from app.component and in app.component.html

  Start editing to see some magic happen :) {{name}}

full code

import { Directive } from '@angular/core';
import { ElementRef ,HostListener,Input } from '@angular/core';
import {MatTooltipModule} from '@angular/material/tooltip';
import { OverlayModule } from '@angular/cdk/overlay';

@Directive({
  selector: '[appMillahint]'
})
export class MillahintDirective {
@Input('appMillahint') hc: string;
@Input() dc: string;
@Input() mo: string;
@Input() callback2:Function;
@Input() me: string;
@Input() ml: string;
@Input() text: string;
@Input() rt:String;
  constructor(   private el:ElementRef) {
    el.nativeElement.style.backgroundColor = this.dc;
    this.text="milla";

  }

      ngOnInit() {
       this.    el.nativeElement.innerHTML ='
  '+this.rt+'
';
    }
  @HostListener('onmouseover') onmouseover(){
  this.    el.nativeElement.style.backgroundColor =this.mo;
}@HostListener('mouseenter') onMouseEnter() {
 this.    el.nativeElement.innerHTML ='
  '+this.rt+'
';

  //this.    el.nativeElement.style.backgroundColor = this.hc;

}table='

   Company	  Contact	  Country

  Alfreds Futterkiste	  Maria Anders	  Germany

  Centro comercial Moctezuma	   Francisco Chang	  Mexico

   Ernst Handel	  Roland Mendel	   Austria

  Island Trading	  Helen Bennett	  UK

  Laughing Bacchus Winecellars	   Yoshi Tannamuri	  Canada

  Giovanni Rovelli

';
  ribbonstyle='.ribbon { font-size: 16px !important;  width: 50%; position: relative; background: #ba89b6; color: #fff; text-align: center; padding: 1em 2em; /* Adjust to suit */ margin: 2em auto 3em;   } .ribbon:before, .ribbon:after { content: ""; position: absolute; display: block; bottom: -1em; border: 1.5em solid #986794; z-index: -1; } .ribbon:before { left: -2em; border-right-width: 1.5em; border-left-color: transparent; } .ribbon:after { right: -2em; border-left-width: 1.5em; border-right-color: transparent; } .ribbon .ribbon-content:before, .ribbon .ribbon-content:after { content: ""; position: absolute; display: block; border-style: solid; border-color: #804f7c transparent transparent transparent; bottom: -1em; } .ribbon .ribbon-content:before { left: 0; border-width: 1em 0 0 1em; } .ribbon .ribbon-content:after { right: 0; border-width: 1em 1em 0 0; }';

 @HostListener('mouseleave') onMouseLeave() {

    this.    el.nativeElement.innerText="i am milla";
   //  this.    el.nativeElement.style.backgroundColor = this.ml;
  }

}

Body:
In Angular you can't add templates like this. Do the following changes.

Inject ViewContainerRef and ElementRef in directive constructor

constructor(private vc: ViewContainerRef, private tl: TemplateRef, private El: ElementRef<any>) {
 this.vc.createEmbeddedView(this.tl);
 this.el.nativeElement.style.backgroundColor = this.hc;
}

use the directive inside the ng-template

<ng-template appMillahint="pink">
   <p dc="yellow" text="name" ml="#9c27b0" me="red" mo="blue">
     Start editing to see some magic happen :) {{name}}
   <button (click)=hi()>dasdsad</button>
   </p>
</ng-template>


问:
Get SSL Certificate 'Issued to'
I want to know how can I get Local Computer SSL certificates Issued to field values. I used this command to show all SSL certificates informations but it did not show me Issued To field

GET-CHILDITEM -Path 'Cert:\LocalMachine\' –RECURSE | FORMAT-LIST –PROPERTY *

答:
Does this answer your question?

```<code>gci Cert:\LocalMachine\my| select -expandp dnsnamelist
</code>```

Enjoy -tom

Title: Get SSL Certificate 'Issued to'

Body:
Does this answer your question?

gci Cert:\LocalMachine\my| select -expandp dnsnamelist

Enjoy -tom


问:
MapStruct not autowring with Spring-boot testing Gradle Junit5
I am trying to use mapstruct with Gradle, but I am having limited success. When I'm using it in the application everything seems to be working fine, but when I tried to write some tests Spring can't autowire MapStruct properly (it just returns NullPointer exceptions). I am using Gradle 5.4.1, Junit5 and IntelliJ 2019.1.2.

This is the build folder and there is no mapper generated for test classes.

Repository with the code is here:
https://github.com/MirkoManojlovic/mapstruct-example

Mapper:

@Mapper(unmappedTargetPolicy = ReportingPolicy.WARN,
        componentModel = "spring",
        injectionStrategy = InjectionStrategy.CONSTRUCTOR)
public interface ItemMapper {
    ItemDto toDto(Item item);
    Item toItem(ItemDto itemDto);
}

```
<h3>Repository:</h3>
<pre class="lang-java prettyprint-override"><code>public class ItemRepository {
    public ItemDto getItemDto() {
        return new ItemDto("item 1");
    }

    public Item getItem() {
        return new Item(1, "item 1", 20);
    }
}
</code>```

Service:

@Service
@RequiredArgsConstructor
@Log4j2
public class ItemService {
    private final ItemRepository itemRepository;
    private final ItemMapper itemMapper;

    public ItemDto getItemDto() {
        Item item = itemRepository.getItem();
        ItemDto itemDto = itemMapper.toDto(item);
        log.info(itemDto);
        return itemDto;
    }

    public Item getItem() {
        ItemDto itemDto = itemRepository.getItemDto();
        Item item = itemMapper.toItem(itemDto);
        log.info(item);
        return item;
    }
}
```
<h3>Test:</h3>
<pre class="lang-java prettyprint-override"><code>@ExtendWith(MockitoExtension.class)
public class ItemServiceTest {

    @Mock
    private ItemRepository itemRepository;

    @InjectMocks
    private ItemService itemService;

    @Spy
    private ItemMapper itemMapper;

    @Test
    void shouldReturnItemDto() {
        Item mockItem = new Item(1, "mockItem", 10);
        given(itemRepository.getItem()).willReturn(mockItem);
        ItemDto itemDto = itemService.getItemDto();
        assertThat(mockItem.getName()).isEqualTo(itemDto.getName());
    }

}
</code>```

build.gradle:

```<code>plugins {
    id 'org.springframework.boot' version '2.1.5.RELEASE'
    id 'java'
}

apply plugin: 'io.spring.dependency-management'

group = 'com.mapstruct.spring.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

test {
    useJUnitPlatform {
    }
}

dependencies {
    // Mapstruct
    implementation 'org.mapstruct:mapstruct:1.3.0.Final'
    annotationProcessor 'org.mapstruct:mapstruct-processor:1.3.0.Final'
    testAnnotationProcessor 'org.mapstruct:mapstruct-processor:1.3.0.Final'

    implementation 'org.springframework.boot:spring-boot-starter-web'
    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'

    testImplementation('org.springframework.boot:spring-boot-starter-test')

    // JUnit5
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.3.2'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.3.2'
    testImplementation 'org.junit.jupiter:junit-jupiter-params:5.3.2'

    // Mockito
    testImplementation 'org.mockito:mockito-core:2.23.4'
    testImplementation 'org.mockito:mockito-junit-jupiter:2.23.4'
}

</code>```

答:
@Spy annotation on

```<code>@Spy
private ItemMapper itemMapper;
</code>```

will not perform dependency injection of the generated ItemMapperImpl class file. The solution would be to set

```<code> @Spy
 private ItemMapper itemMapper = Mappers.getMapper(ItemMapper.class);
</code>```

Or alternativly to enable spring dependency injection via @SpringBootTest(classes = {ItemMapperImpl.class}).

Body:
I am trying to use mapstruct with Gradle, but I am having limited success. When I'm using it in the application everything seems to be working fine, but when I tried to write some tests Spring can't autowire MapStruct properly (it just returns NullPointer exceptions). I am using Gradle 5.4.1, Junit5 and IntelliJ 2019.1.2.

This is the build folder and there is no mapper generated for test classes.

Repository with the code is here:
https://github.com/MirkoManojlovic/mapstruct-example

Mapper:

@Mapper(unmappedTargetPolicy = ReportingPolicy.WARN,
        componentModel = "spring",
        injectionStrategy = InjectionStrategy.CONSTRUCTOR)
public interface ItemMapper {
    ItemDto toDto(Item item);
    Item toItem(ItemDto itemDto);
}

Repository:

public class ItemRepository {
    public ItemDto getItemDto() {
        return new ItemDto("item 1");
    }

    public Item getItem() {
        return new Item(1, "item 1", 20);
    }
}

Service:

@Service
@RequiredArgsConstructor
@Log4j2
public class ItemService {
    private final ItemRepository itemRepository;
    private final ItemMapper itemMapper;

    public ItemDto getItemDto() {
        Item item = itemRepository.getItem();
        ItemDto itemDto = itemMapper.toDto(item);
        log.info(itemDto);
        return itemDto;
    }

    public Item getItem() {
        ItemDto itemDto = itemRepository.getItemDto();
        Item item = itemMapper.toItem(itemDto);
        log.info(item);
        return item;
    }
}

Test:

@ExtendWith(MockitoExtension.class)
public class ItemServiceTest {

    @Mock
    private ItemRepository itemRepository;

    @InjectMocks
    private ItemService itemService;

    @Spy
    private ItemMapper itemMapper;

    @Test
    void shouldReturnItemDto() {
        Item mockItem = new Item(1, "mockItem", 10);
        given(itemRepository.getItem()).willReturn(mockItem);
        ItemDto itemDto = itemService.getItemDto();
        assertThat(mockItem.getName()).isEqualTo(itemDto.getName());
    }

}

build.gradle:

plugins {
    id 'org.springframework.boot' version '2.1.5.RELEASE'
    id 'java'
}

apply plugin: 'io.spring.dependency-management'

group = 'com.mapstruct.spring.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

test {
    useJUnitPlatform {
    }
}

dependencies {
    // Mapstruct
    implementation 'org.mapstruct:mapstruct:1.3.0.Final'
    annotationProcessor 'org.mapstruct:mapstruct-processor:1.3.0.Final'
    testAnnotationProcessor 'org.mapstruct:mapstruct-processor:1.3.0.Final'

    implementation 'org.springframework.boot:spring-boot-starter-web'
    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'

    testImplementation('org.springframework.boot:spring-boot-starter-test')

    // JUnit5
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.3.2'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.3.2'
    testImplementation 'org.junit.jupiter:junit-jupiter-params:5.3.2'

    // Mockito
    testImplementation 'org.mockito:mockito-core:2.23.4'
    testImplementation 'org.mockito:mockito-junit-jupiter:2.23.4'
}

Body:
@Spy annotation on

@Spy
private ItemMapper itemMapper;

will not perform dependency injection of the generated ItemMapperImpl class file. The solution would be to set

 @Spy
 private ItemMapper itemMapper = Mappers.getMapper(ItemMapper.class);

Or alternativly to enable spring dependency injection via @SpringBootTest(classes = {ItemMapperImpl.class}).


问:
MJML how to set compile output directory same as the found input file directory?
I am trying to compile a folder with subfolders that will each have a .mjml file. This command works: mjml ./views/**/*.mjml.html.erb -o, however I can't seem to set the output to be in the same directory as the initial file, all of the files from each of the subfolders will be piled up in the root directory, and if I set any directory it will pile up there obviously.

I tried using ** and such but to no avail. I think it is possible to run a separate command for each of the subfolders but it will eat up a lot of resources and time, so it is not viable.

答:
Sorry, I did something wrong before, iteration through every folder is quick enough.

I just used glob to map out all of the files I need to compile and ran the mjml compiler on each one individually. It was surprisingly fast (10-50ms per file).


问:
How to use <template> with dynamic IDs?
Given a HTML-template like this:

```<code><template id="paragraph-template">
<p>Hi, I am a paragraph</p>
</template>
</code>```

I load and append this template via JS, like so:

```<code>let templateInstance = document.getElementById("paragraph-template");
myContainer.appendChild(templateInstance)
</code>```

Now I'd like to add the template multiple times (i.e. in a for-loop) and I want the
-elements to each have a unique id, so the result would look like e.g.:

```<code><div>
<p id="p1">Hi, I am a paragraph</p>
<p id="p2">Hi, I am a paragraph</p>
<p id="p3">Hi, I am a paragraph</p>
<div>
</code>```

How can I achieve this with HTML-templates?

EDIT:
The example I provide here is minified – In the real world I have a template with many elements, which should all get a unique ID.

答:
I suggest you : </p>

```<code>    let templateInstance = document.getElementById("paragraph-template");
    for(var i=1;i<4;i++){
        let clone = document.importNode(templateInstance .content, true);
        clone.querySelector('p').id = "p"+i;
        myContainer.appendChild(clone);
    }
</code>```

Title: How to use <template> with dynamic IDs?

Body:
Given a HTML-template like this:

<template id="paragraph-template">

Hi, I am a paragraph

</template>

I load and append this template via JS, like so:

let templateInstance = document.getElementById("paragraph-template");
myContainer.appendChild(templateInstance)

Now I'd like to add the template multiple times (i.e. in a for-loop) and I want the
-elements to each have a unique id, so the result would look like e.g.:

Hi, I am a paragraph

Hi, I am a paragraph

Hi, I am a paragraph

How can I achieve this with HTML-templates?

EDIT:
The example I provide here is minified – In the real world I have a template with many elements, which should all get a unique ID.

Body:
I suggest you :

    let templateInstance = document.getElementById("paragraph-template");
    for(var i=1;i<4;i++){
        let clone = document.importNode(templateInstance .content, true);
        clone.querySelector('p').id = "p"+i;
        myContainer.appendChild(clone);
    }


问:
Coinmarketcap api blocked by Adblock
I have made a react app few months ago. It's a simple app that utilizes Coinmarketcap api to list prices for different cryptocurrencies. When I tried to check on it later, I found out that adblock block the api URL.
How do I make sure this doesn't happen on the user client, and why is this happing in the first place?</p>

答: I believe the only way would be to set up a custom API that acts as a proxy (you could use Firebase functions/ AWS Lambda/ Stdlib), unless Coinmarketcap has a secondary API which isn't blocked.</p>

Title: Coinmarketcap api blocked by Adblock


问:
Custom filters in laravel-ffmpeg/ php-ffmpeg?
I wanna create custom command using php-ffmpeg/laravel-ffmpeg?

$customFilter = ['-stream_loop 3'];
$customFilter1 = ['-c copy'];
\FFMpeg::fromDisk($this->data['input_disk'])
    ->open($this->data['input'])
    ->addFilter(function ($filters) {
            $filters->custom($customFilter);
            $filters->custom($customFilter1);
     })
    ->export()
    ->toDisk($this->data['output_disk'])
    ->inFormat(new \FFMpeg\Format\Video\X264('libmp3lame', 'libx264'))
    ->save($this->data['output']);
```

local.ERROR: Encoding failed {"exception":"[object] (FFMpeg\Exception\RuntimeException(code: 0):

答:
Please try if this could help to you. As per the fix given here...use string start/end with space instead of array.

https://github.com/PHP-FFMpeg/PHP-FFMpeg/issues/381#issuecomment-314150217

```<code>$customFilter = ' -stream_loop 3 ';
$customFilter1 = ' -c copy ';
\FFMpeg::fromDisk($this->data['input_disk'])
    ->open($this->data['input'])
    ->addFilter(function ($filters) {
            $filters->custom($customFilter);
            $filters->custom($customFilter1);
     })
    ->export()
    ->toDisk($this->data['output_disk'])
    ->inFormat(new \FFMpeg\Format\Video\X264('libmp3lame', 'libx264'))
    ->save($this->data['output']);
</code>```

Body:
I wanna create custom command using php-ffmpeg/laravel-ffmpeg?

$customFilter = ['-stream_loop 3'];
$customFilter1 = ['-c copy'];
\FFMpeg::fromDisk($this->data['input_disk'])
    ->open($this->data['input'])
    ->addFilter(function ($filters) {
            $filters->custom($customFilter);
            $filters->custom($customFilter1);
     })
    ->export()
    ->toDisk($this->data['output_disk'])
    ->inFormat(new \FFMpeg\Format\Video\X264('libmp3lame', 'libx264'))
    ->save($this->data['output']);

local.ERROR: Encoding failed {"exception":"[object] (FFMpeg\Exception\RuntimeException(code: 0):

Body:
Please try if this could help to you. As per the fix given here...use string start/end with space instead of array.

https://github.com/PHP-FFMpeg/PHP-FFMpeg/issues/381#issuecomment-314150217

$customFilter = ' -stream_loop 3 ';
$customFilter1 = ' -c copy ';
\FFMpeg::fromDisk($this->data['input_disk'])
    ->open($this->data['input'])
    ->addFilter(function ($filters) {
            $filters->custom($customFilter);
            $filters->custom($customFilter1);
     })
    ->export()
    ->toDisk($this->data['output_disk'])
    ->inFormat(new \FFMpeg\Format\Video\X264('libmp3lame', 'libx264'))
    ->save($this->data['output']);


问:
CSS background properties
I have this img set as background to a div. But is too big for my liking. Is there a way I could resize it in css ? </p>

```<code>.portfolio {
    width: 100%;
    height: 100vh;
    background-image: url('img/img2.jpg');
    background-position: center;
    background-size: cover;
}
</code>```

答:
Surely you can do this with two methods.
First is by giving background-size: auto;
Second is by giving custome size like  background-size: 500px 200px;

This will solve your problem. :)

Title: CSS background properties

Body:
I have this img set as background to a div. But is too big for my liking. Is there a way I could resize it in css ?

.portfolio {
    width: 100%;
    height: 100vh;
    background-image: url('img/img2.jpg');
    background-position: center;
    background-size: cover;
}


问:
Why is my function not printing anything in the CLI?
At the moment I am just trying to get the function to print what it has found in
the database, however I am not getting anything in the CLI when submitting
eywords via a form which has this functions URL as an action.

import os
from flask import Flask, render_template, redirect, request, url_for
from flask_pymongo import PyMongo
from bson.objectid import ObjectId

app = Flask(__name__)

app.config["MONGO_DBNAME"] = 'recipe_site'
app.config["MONGO_URI"] = os.getenv("MONGO_URI")

mongo = PyMongo(app)

#function for search bar.

@app.route('/search', methods=['GET', 'POST'])
def search():
    mongo.db.recipes.create_index( { "name": "text" } )
    if request.method == "POST":
        q = request.form['search']
    else:
        q = ""
    query = ( { "$text": { "$search": q } } )
    results = mongo.db.recipes.find(query)

    return render_template('searchresults.html', recipes = results)
```
<p>The form that calls search function and captures key search word:</p>
<pre class="lang-html prettyprint-override"><code><form action="{{ url_for('search', text=text) }}" method="POST">
    <div>
        <div class="input-field">
            <input id="search" name="search" type="text" class="validate">
            <span class="helper-text" data-error="Try again" data-success="Done"></span>
        </div>
    </div>
    <button type="submit">Submit </button>
</form>
</code>```

Error code

Debugger PIN: 272-267-243
10.240.1.220 - - [25/May/2019 19:24:14] "POST /search/ HTTP/1.1" 404 -

As the code stands now all I expect is that it should print any collections in my database which have the keyword searched using the form.

答: Thank you for your attempts to support but I have now rectified the issue. The reason why nothing was printing in the cli was due the there being an issue with the create_index line. There was an existing index within that collection i was unaware of which was preventing this line from running.</p>

Body:
At the moment I am just trying to get the function to print what it has found in
the database, however I am not getting anything in the CLI when submitting
eywords via a form which has this functions URL as an action.

import os
from flask import Flask, render_template, redirect, request, url_for
from flask_pymongo import PyMongo
from bson.objectid import ObjectId

app = Flask(__name__)

app.config["MONGO_DBNAME"] = 'recipe_site'
app.config["MONGO_URI"] = os.getenv("MONGO_URI")

mongo = PyMongo(app)

#function for search bar.

@app.route('/search', methods=['GET', 'POST'])
def search():
    mongo.db.recipes.create_index( { "name": "text" } )
    if request.method == "POST":
        q = request.form['search']
    else:
        q = ""
    query = ( { "$text": { "$search": q } } )
    results = mongo.db.recipes.find(query)

    return render_template('searchresults.html', recipes = results)

The form that calls search function and captures key search word:

<form action="{{ url_for('search', text=text) }}" method="POST">

            <input id="search" name="search" type="text" class="validate">

    <button type="submit">Submit </button>
</form>

Error code

Debugger PIN: 272-267-243
10.240.1.220 - - [25/May/2019 19:24:14] "POST /search/ HTTP/1.1" 404 -

As the code stands now all I expect is that it should print any collections in my database which have the keyword searched using the form.


问:
Moving array via ajax from PHP to JS with valid JSON format
I started with an array from php, which when called via ajax looked like this:

```<code>Array
(
    [0] => {id:"12",from:"09:00:00",to:"15:00:00"}
    [1] => {id:"13",from:"08:00:00",to:"10:00:00"}
    [2] => {id:"12",from:"15:00:00",to:"17:00:00"}
)
</code>```

PHP code

```<code>public static function getBookedTime($date) {

    $query = "SELECT * FROM booking WHERE cid = ".$_SESSION["cid"]." AND doc_date='".strftime("%Y-%m-%d",strtotime($date))."'";
    $result = self::qry($query);

    while ($line = mysqli_fetch_array($result, MYSQLI_ASSOC)) {

        $obj = "{";
        $obj.= 'id:'.'"'.$line["person_id"].'",';
        $obj.= 'from:'.'"'.$line["from_time"].'",';
        $obj.= 'to:'.'"'.$line["to_time"].'"';
        $obj.= "}";

        $time_array[] = $obj;

    }

    print_r( json_encode($time_array) );

}
</code>```

So I added json_encode($myarray) to the PHP and also added  JSON.parse(response) to the javascript.  Now in my page, after being called via ajax, it looks like this:

```<code>var booking1 = {id:"12",from:"09:00:00",to:"15:00:00"},{id:"13",from:"08:00:00",to:"10:00:00"},{id:"12",from:"15:00:00",to:"17:00:00"};
</code>```

The trouble is, I still cannot access any of the values. This is not a valid format in js.

Using either JS or php, how can I get booking1 to look like booking2 (or any valid format)?  I tried array.push and about a thousand things but it just won't budge.

```<code>var booking2 = [
    {id:"12",from:"09:00:00",to:"15:00:00"},
    {id:"13",from:"08:00:00",to:"10:00:00"},
    {id:"12",from:"15:00:00",to:"17:00:00"}
  ];
</code>```

(jQuery answers are ok!)

答:
Don't create your own json string use json_encode instead, it will do all the hard work for you in a much more precise way.

```<code>public static function getBookedTime($date) {

    $query = "SELECT * FROM booking WHERE cid = ".$_SESSION["cid"]." AND doc_date='".strftime("%Y-%m-%d",strtotime($date))."'";
    $result = self::qry($query);

    while ($line = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
        $time_array[] = ["id" =>$line["person_id"], "from" => $line["from_time"], "to" =>$line["to_time"]];
    }
    $json = json_encode($time_array);
}
</code>```

$json is now a correctly formatted json string that you can pass on to JavaScript.

Body:
I started with an array from php, which when called via ajax looked like this:

Array
(
    [0] => {id:"12",from:"09:00:00",to:"15:00:00"}
    [1] => {id:"13",from:"08:00:00",to:"10:00:00"}
    [2] => {id:"12",from:"15:00:00",to:"17:00:00"}
)

PHP code

public static function getBookedTime($date) {

    $query = "SELECT * FROM booking WHERE cid = ".$_SESSION["cid"]." AND doc_date='".strftime("%Y-%m-%d",strtotime($date))."'";
    $result = self::qry($query);

    while ($line = mysqli_fetch_array($result, MYSQLI_ASSOC)) {

        $obj = "{";
        $obj.= 'id:'.'"'.$line["person_id"].'",';
        $obj.= 'from:'.'"'.$line["from_time"].'",';
        $obj.= 'to:'.'"'.$line["to_time"].'"';
        $obj.= "}";

        $time_array[] = $obj;

    }

    print_r( json_encode($time_array) );

}

So I added json_encode($myarray) to the PHP and also added  JSON.parse(response) to the javascript.  Now in my page, after being called via ajax, it looks like this:

var booking1 = {id:"12",from:"09:00:00",to:"15:00:00"},{id:"13",from:"08:00:00",to:"10:00:00"},{id:"12",from:"15:00:00",to:"17:00:00"};

The trouble is, I still cannot access any of the values. This is not a valid format in js.

Using either JS or php, how can I get booking1 to look like booking2 (or any valid format)?  I tried array.push and about a thousand things but it just won't budge.

var booking2 = [
    {id:"12",from:"09:00:00",to:"15:00:00"},
    {id:"13",from:"08:00:00",to:"10:00:00"},
    {id:"12",from:"15:00:00",to:"17:00:00"}
  ];

(jQuery answers are ok!)

Body:
Don't create your own json string use json_encode instead, it will do all the hard work for you in a much more precise way.

public static function getBookedTime($date) {

    $query = "SELECT * FROM booking WHERE cid = ".$_SESSION["cid"]." AND doc_date='".strftime("%Y-%m-%d",strtotime($date))."'";
    $result = self::qry($query);

    while ($line = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
        $time_array[] = ["id" =>$line["person_id"], "from" => $line["from_time"], "to" =>$line["to_time"]];
    }
    $json = json_encode($time_array);
}

$json is now a correctly formatted json string that you can pass on to JavaScript.


问:
UITableViewController doesn't select a cell on initialization
I have the following subclass of UITableViewController:

```<code>final public class ILoveAppleSelectorTableViewController: UITableViewController {
    public weak var delegate: ILoveAppleSelectorTableViewControllerDelegate?
    public var data = [ILoveAppleGroupModel]()

    convenience init() {
        self.init(style: .plain)
    }

    convenience init(data: [ILoveAppleGroupModel]) {
        self.init(style: .plain)
        self.data = data
    }

    override public func viewDidLoad() {
        super.viewDidLoad()
        title = "Select APple Product"
        tableView.registerCellClass(CheckmarkTableViewCell.self)
        tableView.allowsSelection = true
        tableView.allowsMultipleSelection = false
    }

    // MARK: - Selection

    public func selectItem(at indexPath: IndexPath) {
        tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
    }

    // MARK: - Table view data source

    override public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }

    override public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: CheckmarkTableViewCell = tableView.dequeueCell(for: indexPath)
        let item = data[indexPath.row]
        cell.textLabel?.text = item.material_group_name
        return cell
    }

    override public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let selectedappleProduct = data[indexPath.row]
        delegate?.ILoveAppleSelector(controller: self, didSelect: selectedappleProduct)
    }
}
</code>```

I create an instance of it and call selectItem method:

```<code>let data = Array(appleProducts)
let selector = AppleProductSelector(data: data)
selector.selectItem(at: IndexPath(indexes: [0, 0]))
navigationController?.pushViewController(selector, animated: true)
</code>```

I check in the debugger that selectItem method gets successfully called, however nothing gets selected.

If I select an item on viewWillAppear instead, everything works as expected and the item is being shown as selected:

```<code>public override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    selectItem(at: selectedIndexPath)
}
</code>```

答:
By default, a table view controller will clear the selection when the table view is shown.

You are instantiating your class, then "selecting" a row, then pushing the VC onto the stack. When it appears, it then clears the selection.

In IB / Storyboard, it's controlled by a checkbox:

(un-check the box to prevent selection clearing)

In code, you can add this in your init func (or perhaps in viewDidLoad()):

```<code>self.clearsSelectionOnViewWillAppear = false
</code>```

Body:
I have the following subclass of UITableViewController:

final public class ILoveAppleSelectorTableViewController: UITableViewController {
    public weak var delegate: ILoveAppleSelectorTableViewControllerDelegate?
    public var data = [ILoveAppleGroupModel]()

    convenience init() {
        self.init(style: .plain)
    }

    convenience init(data: [ILoveAppleGroupModel]) {
        self.init(style: .plain)
        self.data = data
    }

    override public func viewDidLoad() {
        super.viewDidLoad()
        title = "Select APple Product"
        tableView.registerCellClass(CheckmarkTableViewCell.self)
        tableView.allowsSelection = true
        tableView.allowsMultipleSelection = false
    }

    // MARK: - Selection

    public func selectItem(at indexPath: IndexPath) {
        tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
    }

    // MARK: - Table view data source

    override public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }

    override public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: CheckmarkTableViewCell = tableView.dequeueCell(for: indexPath)
        let item = data[indexPath.row]
        cell.textLabel?.text = item.material_group_name
        return cell
    }

    override public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let selectedappleProduct = data[indexPath.row]
        delegate?.ILoveAppleSelector(controller: self, didSelect: selectedappleProduct)
    }
}

I create an instance of it and call selectItem method:

let data = Array(appleProducts)
let selector = AppleProductSelector(data: data)
selector.selectItem(at: IndexPath(indexes: [0, 0]))
navigationController?.pushViewController(selector, animated: true)

I check in the debugger that selectItem method gets successfully called, however nothing gets selected.

If I select an item on viewWillAppear instead, everything works as expected and the item is being shown as selected:

public override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    selectItem(at: selectedIndexPath)
}

Body:
By default, a table view controller will clear the selection when the table view is shown.

You are instantiating your class, then "selecting" a row, then pushing the VC onto the stack. When it appears, it then clears the selection.

In IB / Storyboard, it's controlled by a checkbox:

(un-check the box to prevent selection clearing)

In code, you can add this in your init func (or perhaps in viewDidLoad()):

self.clearsSelectionOnViewWillAppear = false


问:
Pass Range Cells for Copy-Paste: Excel VBA
I have to pass 2 cells (reference or value) from one sub to another sub so that the value in the first cell is copied and pasted to the other cell.
Since it is required for multiple cell combinations, I want to get it done by passing the cell (reference or value) from one subroutine to other.

I've tried the following code and combination with Byref and ByVal options. But unable to get the desired results.
Essentially, in the below code, whatever value is present in cell E1792 should be copy-pasted to C1799 as Value and Number formatted.

```<code>Private Sub Copy_Val(ByRef CopyFrom As Range, ByRef PasteTo As Range)
Application.ScreenUpdating = False

    Range(CopyFrom).Select
    Selection.Copy
    Range(PasteTo).Select

    Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
        xlNone, SkipBlanks:=False, Transpose:=False

End Sub

Sub Apply_Filter()
    Dim CpFrm As Range
    Dim PstTo As Range
    Set CpFrm = Range("E1792")
    Set PstTo = Range("C1799")
    Call Copy_Val(CpFrm, PstTo)
End Sub
</code>```

Sometimes I get Type Mismatch error, and sometimes "400" error.
Expected output is that the cell value present in cell E1792 should be copy-pasted to C1799 as Value and Number formatted.

Any help in fixing this will be appreciated.

答:
Since CopyFrom and PasteTo are Range objects, you don't need to use Range(). You can also eliminate the Select part and simplify your function considerably:

```<code>Private Sub Copy_Val(ByRef CopyFrom As Range, ByRef PasteTo As Range)
Application.ScreenUpdating = False

    CopyFrom.Copy
    PasteTo.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
        xlNone, SkipBlanks:=False, Transpose:=False

End Sub
</code>```

Body:
I have to pass 2 cells (reference or value) from one sub to another sub so that the value in the first cell is copied and pasted to the other cell.
Since it is required for multiple cell combinations, I want to get it done by passing the cell (reference or value) from one subroutine to other.

I've tried the following code and combination with Byref and ByVal options. But unable to get the desired results.
Essentially, in the below code, whatever value is present in cell E1792 should be copy-pasted to C1799 as Value and Number formatted.

Private Sub Copy_Val(ByRef CopyFrom As Range, ByRef PasteTo As Range)
Application.ScreenUpdating = False

    Range(CopyFrom).Select
    Selection.Copy
    Range(PasteTo).Select

    Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
        xlNone, SkipBlanks:=False, Transpose:=False

End Sub

Sub Apply_Filter()
    Dim CpFrm As Range
    Dim PstTo As Range
    Set CpFrm = Range("E1792")
    Set PstTo = Range("C1799")
    Call Copy_Val(CpFrm, PstTo)
End Sub

Sometimes I get Type Mismatch error, and sometimes "400" error.
Expected output is that the cell value present in cell E1792 should be copy-pasted to C1799 as Value and Number formatted.

Any help in fixing this will be appreciated.

Body:
Since CopyFrom and PasteTo are Range objects, you don't need to use Range(). You can also eliminate the Select part and simplify your function considerably:

Private Sub Copy_Val(ByRef CopyFrom As Range, ByRef PasteTo As Range)
Application.ScreenUpdating = False

    CopyFrom.Copy
    PasteTo.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
        xlNone, SkipBlanks:=False, Transpose:=False

End Sub


问:
Manage the parallel degree of sql execution
I have a process that sends a lot of commands to be executed with parallel.

exmaple of command:

```<code>Insert /*+ parallel(16) */ ...
</code>```

The problem is that if the requested parallel is higher than the available servers, the command gets downgraded in the parallel degree,
and because I send several commands togather they "steal" parallel servers from each others.

I have one specific query, that’s more important and needs to run with the requested parallel, while the other queries are less important.

Is there a way to enforce the optimizer to decrease the other statements parallel degree and increase the parallel of the important query?

Is there a way to change the parallel degree of statement after it started running?

I'm using oracle 11g.

答:
Yes, you can use the Resource Manager.

The 11gr2 docs even have an example scenario basically up your alley...some jobs are more important than others, how to limit parallel processes to free up resources for the important ones

https://docs.oracle.com/cd/E11882_01/server.112/e25494/dbrm.htm#ADMIN13471

Oracle-Base of course also covers this feature. -- which as you can see has been around for a long time.

Note, you'll need an Enterprise Edition licensed copy of Oracle Database to use this feature...but if you're using that much CPU to begin with, I imagine you already have that?

Body:
I have a process that sends a lot of commands to be executed with parallel.

exmaple of command:

Insert /*+ parallel(16) */ ...

The problem is that if the requested parallel is higher than the available servers, the command gets downgraded in the parallel degree,
and because I send several commands togather they "steal" parallel servers from each others.

I have one specific query, that’s more important and needs to run with the requested parallel, while the other queries are less important.

Is there a way to enforce the optimizer to decrease the other statements parallel degree and increase the parallel of the important query?

Is there a way to change the parallel degree of statement after it started running?

I'm using oracle 11g.


问:
VS2010 - How can two or more people edit a use-case file at the same time?
I have a solution written in VS2010. I have a modeling project in this solution about use case. What I want is to allow two or more people to be able to edit the file at the same time. Also, I don't want people to overwrite each other. Instead, I'd like VS2010 to merge their changes. Is this possible in VS2010?</p>

答: Live editing, like you'd get on Google Docs, isn't possible. If you just want to merge changes once a day I'd recommend a version control system, such as Subversion.</p>


问:
StreamReader reads deleted file
I am trying to search a directory for some filenames and want to output every file found. The filenames are listed in "files.txt".

The strange thing is, that I deleted the file with Windows Explorer from the disk, but it still outputs the content of the old file.

```<code>using (StreamReader reader = new StreamReader(new FileStream(@"C:\Program Files (x86)\Test\files.txt", FileMode.Open)))
{
    while (!reader.EndOfStream)
    {
        var line = reader.ReadLine();
        Console.WriteLine($"ReadLine: \"{line}\"");
        if (!string.IsNullOrWhiteSpace(line))
        {
            Directory.GetFiles(folder, line, SearchOption.AllDirectories).ToList()
            .ForEach(s =>
            {
                Console.WriteLine($"FileFound: {s}");
             });
        }
    }
}
</code>```

I have no idea why this is happening or what the cause of this is.

答:
I solved it myself now and just write this if someone has a similiar problem.

The file was deleted and the above code still worked.
The problem was Windows VirtualStore. There was a copy from an older version of the file.

It was working because the data from the VirtualStore is treated with priority. In the moment I deleted the file from there it was working as expected.

Title: StreamReader reads deleted file

Body:
I am trying to search a directory for some filenames and want to output every file found. The filenames are listed in "files.txt".

The strange thing is, that I deleted the file with Windows Explorer from the disk, but it still outputs the content of the old file.

using (StreamReader reader = new StreamReader(new FileStream(@"C:\Program Files (x86)\Test\files.txt", FileMode.Open)))
{
    while (!reader.EndOfStream)
    {
        var line = reader.ReadLine();
        Console.WriteLine($"ReadLine: \"{line}\"");
        if (!string.IsNullOrWhiteSpace(line))
        {
            Directory.GetFiles(folder, line, SearchOption.AllDirectories).ToList()
            .ForEach(s =>
            {
                Console.WriteLine($"FileFound: {s}");
             });
        }
    }
}

I have no idea why this is happening or what the cause of this is.


问:
Count all persons who has ticket filed in last 12 months Grouped per month
I have these sample tables:

```<code>CREATE TABLE #tmp_persons (
    PersonID int primary key identity
    , FirstName varchar(max)
    , LastName varchar(max)
)

CREATE TABLE #tmp_tickets (
    TicketNum int primary key identity
    , Title varchar(max)
    , Descr varchar(max)
    , DateFiled datetime
    , SubmittedBy int FOREIGN KEY REFERENCES #tmp_persons(PersonID)
)

CREATE TABLE #tmp_assigned_lead (
    AssignmentID int primary key identity
    , PersonID int FOREIGN KEY REFERENCES #tmp_persons(PersonID) -- ID of the Lead
    , AssignedPersonID int FOREIGN KEY REFERENCES #tmp_persons(PersonID) -- ID of the person assigned
)

-- DATA DUMP
INSERT INTO #tmp_persons
VALUES
(1, 'John', 'Doe'), (2, 'Jane', 'Doe'),
(3, 'Carl', 'Smith'), (4, 'Jenny', 'Smith'),
(5, 'John', 'Wick'), (6, 'Stephanie', 'Mathews')

INSERT INTO #tmp_assigned_lead (PersonID, AssignedPersonID)
VALUES
(1, 2), (1, 3), (1, 4), (1, 5), (1, 6)

INSERT INTO #tmp_tickets (Title, Descr, DateFiled, SubmittedBy)
VALUES
('Ticket 1', 'blah', '01-01-2019', 2),
('Ticket 2', 'blah', '01-02-2019', 2),
('Ticket 3', 'blah', '05-01-2019', 4),
('Ticket 4', 'blah', '05-01-2019', 2),
('Ticket 5', 'blah', '06-01-2019', 5),
('Ticket 6', 'blah', '07-01-2019', 6),--
('Ticket 7', 'blah', '4-17-2018', 6),
('Ticket 8', 'blah', '12-30-2018', 6),
('Ticket 9', 'blah', '1-28-2019', 3),
('Ticket 10', 'blah', '3-16-2019', 3),
('Ticket 11', 'blah', '3-30-2018', 5),
('Ticket 12', 'blah', '2-4-2018', 4),
('Ticket 13', 'blah', '1-11-2019', 6),
('Ticket 14', 'blah', '9-5-2018', 6)
</code>```

So here are the points:

Each person in #tmp_persons can have a "lead" and this is stored in
a relational table #tmp_assigned_lead.

A person can file a ticket
which is stored in #tmp_tickets

A person is called a Contributor when he filed a ticket but goes back as a normal member when he doesnt file another ticket within 12 months.

Now my requirement is, I want to count all persons under a lead which have transitioned into Contributor per month. This will be a monthly record.

Sample Scenarios:

Person1 was registered Jan 01, 2018 and has never filed a ticket ever since until just Jan 01, 2019 when he filed his first ticket. This will consider Person1 as Contributor only for the month of January 2019 but he is a normal member from Jan 2018 up to Dec 2018.

Person1 filed another ticket in Feb 2019. Although he filed a new ticket, he is still not counted in Feb 2019 records of members who became Contributor since he is already a Contributor in Jan 2019

Person2 is registered in Feb 23, 2019 and immediately filed a ticket. This makes him/her a Contributor and is included in the count for "members who became contributors" in the month of Feb 2019.

This query I have come up so far groups the tickets per person and month:

```<code>SELECT
    SubmittedBy
    , MaxDate = MAX(DateFiled)
    , PeriodMonth = MONTH(DateFiled)
    , PeriodYear = YEAR(DateFiled)
FROM #tmp_tickets
GROUP BY
    SubmittedBy
    , MONTH(DateFiled)
    , YEAR(DateFiled)
</code>```

This is where I am at a roadblock. I can't come up with a query will return number of members under a lead, who became Contributors.

This is what I have so far. I used the above query as a CTE:

```<code>;with cte as (
    SELECT
        SubmittedBy
        , MaxDate = MAX(DateFiled)
        , PeriodMonth = MONTH(DateFiled)
        , PeriodYear = YEAR(DateFiled)
    FROM #tmp_tickets
    GROUP BY
        SubmittedBy
        , MONTH(DateFiled)
        , YEAR(DateFiled)
)
SELECT
    lead.PersonID
    , ContributorsCnt = COUNT(1)
    , PeriodMonth
    , PeriodYear
FROM #tmp_assigned_lead lead
INNER JOIN cte
    ON lead.AssignedPersonID = cte.SubmittedBy
-- WHERE??
-- check if member has no tickets in the past 12 months
GROUP BY
    lead.PersonID
    , PeriodMonth
    , PeriodYear
</code>```

Per data sample here, this is what the records look like in the cte above:

EDIT:

Added data dump and analysis points.

Points:

On 2018-02, PersonID 4 became a contributor. No one else filed a ticket except him. This will give us a row with:

LeadID: 1, PeriodYear: 2018, PeriodMonth: 2, Contributor: 1

On 2018-03, none other than PersonID 5 became a contributor. Again, this will give us another row:

LeadID: 1, PeriodYear: 2018, PeriodMonth: 3, Contributor: 1

On 2018-04, PersonID 6, became a contributor:

LeadID: 1, PeriodYear: 2018, PeriodMonth: 4, Contributor: 1

From 2018-05 to 2019-01, no one else became Contributor. PersonID 6 here is not counted because he is still a contributor.

On 2019-01, PersonID 2 and 3 became contributors. This is their first time filing ticket. Again, PersonID 6 is still a contributor. This will give us row:

LeadID: 1, PeriodYear: 2019, PeriodMonth: 1, Contributor: 2

On 2019-02, PersonID 4 is back to being a normal member, not a contributor, since it has been 12 months and he did not file any ticket since then. No row needed for this.

On 2019-03, PersonID 5 becomes a normal member (same logic in point #6). Person 3 filed a ticket but he is still a contributor. Overall, no row needed.

On 2019-05, Person 2 filed a ticket but he is still a contributor. Person 4 filed a ticket and he is already a regular member so he is now a Contributor:

LeadID: 1, PeriodYear: 2019, PeriodMonth: 5, Contributor: 1

On 2019-06, Person 5 becomes a contributor:

LeadID: 1, PeriodYear: 2018, PeriodMonth: 5 Contributor: 1

On 2019-07, Person 6 filed a ticket but he is still a contributor since his last ticket was filed on 2019-01. (What a busy man!)

Expected Data Set:

```<code>LeadID: 1, PeriodYear: 2018, PeriodMonth: 2, Contributor: 1
LeadID: 1, PeriodYear: 2018, PeriodMonth: 3, Contributor: 1
LeadID: 1, PeriodYear: 2018, PeriodMonth: 4, Contributor: 1
LeadID: 1, PeriodYear: 2019, PeriodMonth: 1, Contributor: 2
LeadID: 1, PeriodYear: 2019, PeriodMonth: 5, Contributor: 1
LeadID: 1, PeriodYear: 2018, PeriodMonth: 5 Contributor: 1
</code>```

I hope this helps clarify my question.

答:
you can use a where condition</p>

```<code>DATEDIFF(MONTH, DateFiled, GETDATE()) <=12
group by MONTH(DateFiled)
</code>```

Body:
I have these sample tables:

CREATE TABLE #tmp_persons (
    PersonID int primary key identity
    , FirstName varchar(max)
    , LastName varchar(max)
)

CREATE TABLE #tmp_tickets (
    TicketNum int primary key identity
    , Title varchar(max)
    , Descr varchar(max)
    , DateFiled datetime
    , SubmittedBy int FOREIGN KEY REFERENCES #tmp_persons(PersonID)
)

CREATE TABLE #tmp_assigned_lead (
    AssignmentID int primary key identity
    , PersonID int FOREIGN KEY REFERENCES #tmp_persons(PersonID) -- ID of the Lead
    , AssignedPersonID int FOREIGN KEY REFERENCES #tmp_persons(PersonID) -- ID of the person assigned
)

-- DATA DUMP
INSERT INTO #tmp_persons
VALUES
(1, 'John', 'Doe'), (2, 'Jane', 'Doe'),
(3, 'Carl', 'Smith'), (4, 'Jenny', 'Smith'),
(5, 'John', 'Wick'), (6, 'Stephanie', 'Mathews')

INSERT INTO #tmp_assigned_lead (PersonID, AssignedPersonID)
VALUES
(1, 2), (1, 3), (1, 4), (1, 5), (1, 6)

INSERT INTO #tmp_tickets (Title, Descr, DateFiled, SubmittedBy)
VALUES
('Ticket 1', 'blah', '01-01-2019', 2),
('Ticket 2', 'blah', '01-02-2019', 2),
('Ticket 3', 'blah', '05-01-2019', 4),
('Ticket 4', 'blah', '05-01-2019', 2),
('Ticket 5', 'blah', '06-01-2019', 5),
('Ticket 6', 'blah', '07-01-2019', 6),--
('Ticket 7', 'blah', '4-17-2018', 6),
('Ticket 8', 'blah', '12-30-2018', 6),
('Ticket 9', 'blah', '1-28-2019', 3),
('Ticket 10', 'blah', '3-16-2019', 3),
('Ticket 11', 'blah', '3-30-2018', 5),
('Ticket 12', 'blah', '2-4-2018', 4),
('Ticket 13', 'blah', '1-11-2019', 6),
('Ticket 14', 'blah', '9-5-2018', 6)

So here are the points:

Each person in #tmp_persons can have a "lead" and this is stored in
a relational table #tmp_assigned_lead.

A person can file a ticket
which is stored in #tmp_tickets

A person is called a Contributor when he filed a ticket but goes back as a normal member when he doesnt file another ticket within 12 months.

Now my requirement is, I want to count all persons under a lead which have transitioned into Contributor per month. This will be a monthly record.

Sample Scenarios:

Person1 was registered Jan 01, 2018 and has never filed a ticket ever since until just Jan 01, 2019 when he filed his first ticket. This will consider Person1 as Contributor only for the month of January 2019 but he is a normal member from Jan 2018 up to Dec 2018.

Person1 filed another ticket in Feb 2019. Although he filed a new ticket, he is still not counted in Feb 2019 records of members who became Contributor since he is already a Contributor in Jan 2019

Person2 is registered in Feb 23, 2019 and immediately filed a ticket. This makes him/her a Contributor and is included in the count for "members who became contributors" in the month of Feb 2019.

This query I have come up so far groups the tickets per person and month:

SELECT
    SubmittedBy
    , MaxDate = MAX(DateFiled)
    , PeriodMonth = MONTH(DateFiled)
    , PeriodYear = YEAR(DateFiled)
FROM #tmp_tickets
GROUP BY
    SubmittedBy
    , MONTH(DateFiled)
    , YEAR(DateFiled)

This is where I am at a roadblock. I can't come up with a query will return number of members under a lead, who became Contributors.

This is what I have so far. I used the above query as a CTE:

;with cte as (
    SELECT
        SubmittedBy
        , MaxDate = MAX(DateFiled)
        , PeriodMonth = MONTH(DateFiled)
        , PeriodYear = YEAR(DateFiled)
    FROM #tmp_tickets
    GROUP BY
        SubmittedBy
        , MONTH(DateFiled)
        , YEAR(DateFiled)
)
SELECT
    lead.PersonID
    , ContributorsCnt = COUNT(1)
    , PeriodMonth
    , PeriodYear
FROM #tmp_assigned_lead lead
INNER JOIN cte
    ON lead.AssignedPersonID = cte.SubmittedBy
-- WHERE??
-- check if member has no tickets in the past 12 months
GROUP BY
    lead.PersonID
    , PeriodMonth
    , PeriodYear

Per data sample here, this is what the records look like in the cte above:

EDIT:

Added data dump and analysis points.

Points:

On 2018-02, PersonID 4 became a contributor. No one else filed a ticket except him. This will give us a row with:

LeadID: 1, PeriodYear: 2018, PeriodMonth: 2, Contributor: 1

On 2018-03, none other than PersonID 5 became a contributor. Again, this will give us another row:

LeadID: 1, PeriodYear: 2018, PeriodMonth: 3, Contributor: 1

On 2018-04, PersonID 6, became a contributor:

LeadID: 1, PeriodYear: 2018, PeriodMonth: 4, Contributor: 1

From 2018-05 to 2019-01, no one else became Contributor. PersonID 6 here is not counted because he is still a contributor.

On 2019-01, PersonID 2 and 3 became contributors. This is their first time filing ticket. Again, PersonID 6 is still a contributor. This will give us row:

LeadID: 1, PeriodYear: 2019, PeriodMonth: 1, Contributor: 2

On 2019-02, PersonID 4 is back to being a normal member, not a contributor, since it has been 12 months and he did not file any ticket since then. No row needed for this.

On 2019-03, PersonID 5 becomes a normal member (same logic in point #6). Person 3 filed a ticket but he is still a contributor. Overall, no row needed.

On 2019-05, Person 2 filed a ticket but he is still a contributor. Person 4 filed a ticket and he is already a regular member so he is now a Contributor:

LeadID: 1, PeriodYear: 2019, PeriodMonth: 5, Contributor: 1

On 2019-06, Person 5 becomes a contributor:

LeadID: 1, PeriodYear: 2018, PeriodMonth: 5 Contributor: 1

On 2019-07, Person 6 filed a ticket but he is still a contributor since his last ticket was filed on 2019-01. (What a busy man!)

Expected Data Set:

LeadID: 1, PeriodYear: 2018, PeriodMonth: 2, Contributor: 1
LeadID: 1, PeriodYear: 2018, PeriodMonth: 3, Contributor: 1
LeadID: 1, PeriodYear: 2018, PeriodMonth: 4, Contributor: 1
LeadID: 1, PeriodYear: 2019, PeriodMonth: 1, Contributor: 2
LeadID: 1, PeriodYear: 2019, PeriodMonth: 5, Contributor: 1
LeadID: 1, PeriodYear: 2018, PeriodMonth: 5 Contributor: 1

I hope this helps clarify my question.

Body:
you can use a where condition

DATEDIFF(MONTH, DateFiled, GETDATE()) <=12
group by MONTH(DateFiled)


问:
How to solve "undefined local variable or method `article' for #<ArticlesController:0x9d00548>" in ruby on rails
I'm new in ruby on rails web development. Now I try to create simple form using ruby on rails.

But after submitting the form it shows following error,

```<code>NameError in ArticlesController#create

undefined local variable or method `article` for #<ArticlesController:0x9d00548> Did you mean? article_url

Request

Parameters:

{"utf8"=>"✓",
"authenticity_token"=>"vUOVlqSQTJMHGT11RhZKv4jfcKgEyxnHXCMiHSeaUI7ghsnoZ4vsjZ/QmM2d/MvLLV0YFJ1UIn61RTgJEcgVvA==",
"article"=>{"itle"=>"Text heading", "text"=>"Text subject"},
"commit"=>"Save Article"}

Response
Headers:

None
</code>```

My code part is,

new.html.erb

```<code><h1>New Article</h1>

<%= form_with scope: :article, url: articles_path, local: true do |form| %>
    <p>
        <%= form.label :itle %><br>
        <%= form.text_field :itle %>
    </p>
    <p>
        <%= form.label :text %><br>
        <%= form.text_field :text %>
    </p>

    <p>
        <%= form.submit %>
    </p>
<% end %>
</code>```

Article Controller

```<code>class ArticlesController < ApplicationController
    def new

    end

    def create
        @article = article.new(params[:article].inspect)

        @article.save
        redirect_to @article
    end
end
</code>```

route

```<code>Rails.application.routes.draw do
  get 'welcome/index'

  resources :articles
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
  root 'welcome#index'
end
</code>```

If I print the input value using this below line,

```<code>render plain: params[:article].inspect
</code>```

It shows following message,

```<code><ActionController::Parameters {"title"=>"First Article!", "text"=>"This is my first article."} permitted: false>
</code>```

But I use article.new(params[:article].inspect) this line is does not work.

I check my code but I have no idea how to fix this issue.

If anyone help me to find what mistake I done my coding

I implement my code by using this page https://guides.rubyonrails.org/getting_started.html

答:
Move from

```<code>@article = article.new(params[:article])
</code>```

to

```<code>@article = Article.new(params[:article])
</code>```

You need to use the class to create objects. Also, yes, article does not exist

Body:
I'm new in ruby on rails web development. Now I try to create simple form using ruby on rails.

But after submitting the form it shows following error,

NameError in ArticlesController#create

undefined local variable or method `article` for #<ArticlesController:0x9d00548> Did you mean? article_url

Request

Parameters:

{"utf8"=>"✓",
"authenticity_token"=>"vUOVlqSQTJMHGT11RhZKv4jfcKgEyxnHXCMiHSeaUI7ghsnoZ4vsjZ/QmM2d/MvLLV0YFJ1UIn61RTgJEcgVvA==",
"article"=>{"itle"=>"Text heading", "text"=>"Text subject"},
"commit"=>"Save Article"}

Response
Headers:

None

My code part is,

new.html.erb

New Article

<%= form_with scope: :article, url: articles_path, local: true do |form| %>

        <%= form.label :itle %>

        <%= form.text_field :itle %>

        <%= form.label :text %>

        <%= form.text_field :text %>

        <%= form.submit %>

<% end %>

Article Controller

class ArticlesController < ApplicationController
    def new

    end

    def create
        @article = article.new(params[:article].inspect)

        @article.save
        redirect_to @article
    end
end

route

Rails.application.routes.draw do
  get 'welcome/index'

  resources :articles
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
  root 'welcome#index'
end

If I print the input value using this below line,

render plain: params[:article].inspect

It shows following message,

<ActionController::Parameters {"title"=>"First Article!", "text"=>"This is my first article."} permitted: false>

But I use article.new(params[:article].inspect) this line is does not work.

I check my code but I have no idea how to fix this issue.

If anyone help me to find what mistake I done my coding

I implement my code by using this page https://guides.rubyonrails.org/getting_started.html

Body:
Move from

@article = article.new(params[:article])

to

@article = Article.new(params[:article])

You need to use the class to create objects. Also, yes, article does not exist