问:
How to perform basic Multiple Sequence Alignments in R?
(I've tried asking this on BioStars, but for the slight chance that someone from text mining would think there is a better solution, I am also reposting this here)

The task I'm trying to achieve is to align several sequences.

I don't have a basic pattern to match to.  All that I know is that the "True" pattern should be of length "30" and that the sequences I have had missing values introduced to them at random points.

Here is an example of such sequences, were on the left we see what is the real location of the missing values, and on the right we see the sequence that we will be able to observe.

My goal is to reconstruct the left column using only the sequences I've got on the right column (based on the fact that many of the letters in each position are the same)

```<code>                     Real_sequence           The_sequence_we_see
1   CGCAATACTAAC-AGCTGACTTACGCACCG CGCAATACTAACAGCTGACTTACGCACCG
2   CGCAATACTAGC-AGGTGACTTCC-CT-CG   CGCAATACTAGCAGGTGACTTCCCTCG
3   CGCAATGATCAC--GGTGGCTCCCGGTGCG  CGCAATGATCACGGTGGCTCCCGGTGCG
4   CGCAATACTAACCA-CTAACT--CGCTGCG   CGCAATACTAACCACTAACTCGCTGCG
5   CGCACGGGTAAGAACGTGA-TTACGCTCAG CGCACGGGTAAGAACGTGATTACGCTCAG
6   CGCTATACTAACAA-GTG-CTTAGGC-CTG   CGCTATACTAACAAGTGCTTAGGCCTG
7   CCCA-C-CTAA-ACGGTGACTTACGCTCCG   CCCACCTAAACGGTGACTTACGCTCCG
</code>```

Here is an example code to reproduce the above example:

```<code>ATCG <- c("A","T","C","G")
set.seed(40)
original.seq <- sample(ATCG, 30, T)
seqS <- matrix(original.seq,200,30, T)
change.letters <- function(x, number.of.changes = 15, letters.to.change.with = ATCG)
{
    number.of.changes <- sample(seq_len(number.of.changes), 1)
    new.letters <- sample(letters.to.change.with , number.of.changes, T)
    where.to.change.the.letters <- sample(seq_along(x) , number.of.changes, F)
    x[where.to.change.the.letters] <- new.letters
    return(x)
}
change.letters(original.seq)
insert.missing.values <- function(x) change.letters(x, 3, "-")
insert.missing.values(original.seq)

seqS2 <- t(apply(seqS, 1, change.letters))
seqS3 <- t(apply(seqS2, 1, insert.missing.values))

seqS4 <- apply(seqS3,1, function(x) {paste(x, collapse = "")})
require(stringr)
# library(help=stringr)
all.seqS <- str_replace(seqS4,"-" , "")

# how do we allign this?
data.frame(Real_sequence = seqS4, The_sequence_we_see = all.seqS)
</code>```

I understand that if all I had was a string and a pattern I would be able to use

```<code>library(Biostrings)
pairwiseAlignment(...)
</code>```

But in the case I present we are dealing with many sequences to align to one another (instead of aligning them to one pattern).

Is there a known method for doing this in R?

答:
Writing an alignment algorithm in R looks like a bad idea to me, but there is an R interface to the MUSCLE algorithm in the bio3d package (function seqaln()). Be aware of the fact that you have to install this algorithm first.

Alternatively, you can use any of the available algorithms (eg ClustalW, MAFFT, T-COFFEE) and import the multiple sequence alignemts in R using bioconductor functionality. See eg here..

ContentLicense: CC BY-SA 4.0

Body:
(I've tried asking this on BioStars, but for the slight chance that someone from text mining would think there is a better solution, I am also reposting this here)

The task I'm trying to achieve is to align several sequences.

I don't have a basic pattern to match to.  All that I know is that the "True" pattern should be of length "30" and that the sequences I have had missing values introduced to them at random points.

Here is an example of such sequences, were on the left we see what is the real location of the missing values, and on the right we see the sequence that we will be able to observe.

My goal is to reconstruct the left column using only the sequences I've got on the right column (based on the fact that many of the letters in each position are the same)

                     Real_sequence           The_sequence_we_see
1   CGCAATACTAAC-AGCTGACTTACGCACCG CGCAATACTAACAGCTGACTTACGCACCG
2   CGCAATACTAGC-AGGTGACTTCC-CT-CG   CGCAATACTAGCAGGTGACTTCCCTCG
3   CGCAATGATCAC--GGTGGCTCCCGGTGCG  CGCAATGATCACGGTGGCTCCCGGTGCG
4   CGCAATACTAACCA-CTAACT--CGCTGCG   CGCAATACTAACCACTAACTCGCTGCG
5   CGCACGGGTAAGAACGTGA-TTACGCTCAG CGCACGGGTAAGAACGTGATTACGCTCAG
6   CGCTATACTAACAA-GTG-CTTAGGC-CTG   CGCTATACTAACAAGTGCTTAGGCCTG
7   CCCA-C-CTAA-ACGGTGACTTACGCTCCG   CCCACCTAAACGGTGACTTACGCTCCG

Here is an example code to reproduce the above example:

ATCG <- c("A","T","C","G")
set.seed(40)
original.seq <- sample(ATCG, 30, T)
seqS <- matrix(original.seq,200,30, T)
change.letters <- function(x, number.of.changes = 15, letters.to.change.with = ATCG)
{
    number.of.changes <- sample(seq_len(number.of.changes), 1)
    new.letters <- sample(letters.to.change.with , number.of.changes, T)
    where.to.change.the.letters <- sample(seq_along(x) , number.of.changes, F)
    x[where.to.change.the.letters] <- new.letters
    return(x)
}
change.letters(original.seq)
insert.missing.values <- function(x) change.letters(x, 3, "-")
insert.missing.values(original.seq)

seqS2 <- t(apply(seqS, 1, change.letters))
seqS3 <- t(apply(seqS2, 1, insert.missing.values))

seqS4 <- apply(seqS3,1, function(x) {paste(x, collapse = "")})
require(stringr)
# library(help=stringr)
all.seqS <- str_replace(seqS4,"-" , "")

# how do we allign this?
data.frame(Real_sequence = seqS4, The_sequence_we_see = all.seqS)

I understand that if all I had was a string and a pattern I would be able to use

library(Biostrings)
pairwiseAlignment(...)

But in the case I present we are dealing with many sequences to align to one another (instead of aligning them to one pattern).

Is there a known method for doing this in R?


来源: stackexchange

问:
git push not send changes to remote git repository
I am making changes to some file in my local git repository and then want to send the changes to the remote git repository from which the local was cloned via ssh.

After run "git commit -a" on my local side, to send the changes to the remote, I run

```<code>$ git push
Everything up-to-date
</code>```

However I checked the remote files and they are not changed!
Any idea?

Thanks and regards!

答:
I found that the issue was that I had not added the files to the update as well as a message. I fixed this by using the following commands:

```<code>git add .
</code>```

and then

```<code>git commit -m "updates done by..."
</code>```

and then

```<code>git push origin <repo_name>
</code>```

Hope this helps someone ;)

ContentLicense: CC BY-SA 2.5

Body:
I am making changes to some file in my local git repository and then want to send the changes to the remote git repository from which the local was cloned via ssh.

After run "git commit -a" on my local side, to send the changes to the remote, I run

$ git push
Everything up-to-date

However I checked the remote files and they are not changed!
Any idea?

Thanks and regards!

Body:
I found that the issue was that I had not added the files to the update as well as a message. I fixed this by using the following commands:

git add .

and then

git commit -m "updates done by..."

and then

git push origin <repo_name>

Hope this helps someone ;)

ContentLicense: CC BY-SA 3.0


问:
PostgreSQL + Node Integration
Need some advice regarding the following situation:
There is an existing PostgreSQL database that I would like to draw information from (with full authorization of course). How can I query the entries in that database using NodeJS? I know sequelize can offer what I'm looking for, but I'm a bit confused as to how to approach this. I've heard that I would have to migrate the data first in order to then query it. What's the best way to go about doing this? Thanks.

For reference, I've taken a look at this link (https://github.com/sequelize/sequelize/issues/3791) but haven't gotten what I'd hoped out of it.

答: You can query without migration for existing database, this package should help https://www.npmjs.com/package/pg</p>

Title: PostgreSQL + Node Integration


问:
Accessing and editing multiple addresses in memory
I want to access and edit multiple addresses in memory.
In case it's vague, the question is: If I used memory scanner and the results were a list of addresses, how would I be able to access and edit them all?
I've already been told to try putting all the addresses in an array, how do I do this?

Here's the code so far:

```<code>//

#include "stdafx.h"
#include "iostream"
#include "Windows.h"
#include <cstdint>
#include <stdint.h>

using namespace std;
int main()
{
    int newValue = 0;
    int* p;
    p = (int*)0x4F6DCFE3DC; // now p points to address 0x220202

    HWND hwnd = FindWindowA(NULL, "Call of Duty®: Modern Warfare® 3 Multiplayer");// Finds Window
    if (hwnd == NULL) {// Tests for success
        cout << "The window is not open" << endl;
        Sleep(3000);
        exit(-1);
    }
    else {
        cout << "It's open boss!";
    }
    else {// If Successful Begins the following
        DWORD procID;
        GetWindowThreadProcessId(hwnd, &procID);
        HANDLE handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, procID);//Gets handle on process
        if (procID == NULL) {
            cout << "Cannot obtain process." << endl;
            Sleep(3000);
            exit(-1);
        }
        else {//Begins writing to memory
            while (newValue == 0) {
                 /*This Writes*/WriteProcessMemory(handle, (LPVOID)0x04F6DCFE3DC, &newValue, sizeof(newValue), 0);
                 cout << p;
                 Sleep(3000);

            }
        }
    }
}
</code>```

答:
It's fairly easy. Just use a std::vector<std::pair<int*,int>> to contain all these addresses you want to modify along with the value they should achieve:

```<code>std::vector<std::pair<int*,int>> changeMap = {
    { (int*)0x4F6DCFE3DC , 0 }
    // more address value pairs ...
};
</code>```

Then you can process them in a loop:

```<code>for(auto it = std::begin(changeMap); it != std::end(changeMap); ++it)
{
    WriteProcessMemory(handle, (LPVOID)it->first, &(it->second),
                       sizeof(it->second), 0);
}
</code>```

Whatever you want to achieve with that1.

I've already been told to try putting all the addresses in an array, how do I do this?

If you want to set all the address contents to 0 you may use a simpler construct:

```<code>int newValue = 0;
std::vector<int*> changeAddrList = {
    (int*)0x4F6DCFE3DC ,
    // more addresses to change ...
};

// ...

for(auto addr : changeAddrList)
{
    WriteProcessMemory(handle, (LPVOID)addr , &newValue ,
                       sizeof(newValue), 0);
}
</code>```

1Fiddling around in another processes memory is error prone and might lead to all kinds of unexpected behavior!

Your code may fail miserably at a newer version of that program, where you're trying to apply your cheat codez.

Body:
I want to access and edit multiple addresses in memory.
In case it's vague, the question is: If I used memory scanner and the results were a list of addresses, how would I be able to access and edit them all?
I've already been told to try putting all the addresses in an array, how do I do this?

Here's the code so far:

//

#include "stdafx.h"
#include "iostream"
#include "Windows.h"
#include <cstdint>
#include <stdint.h>

using namespace std;
int main()
{
    int newValue = 0;
    int* p;
    p = (int*)0x4F6DCFE3DC; // now p points to address 0x220202

    HWND hwnd = FindWindowA(NULL, "Call of Duty®: Modern Warfare® 3 Multiplayer");// Finds Window
    if (hwnd == NULL) {// Tests for success
        cout << "The window is not open" << endl;
        Sleep(3000);
        exit(-1);
    }
    else {
        cout << "It's open boss!";
    }
    else {// If Successful Begins the following
        DWORD procID;
        GetWindowThreadProcessId(hwnd, &procID);
        HANDLE handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, procID);//Gets handle on process
        if (procID == NULL) {
            cout << "Cannot obtain process." << endl;
            Sleep(3000);
            exit(-1);
        }
        else {//Begins writing to memory
            while (newValue == 0) {
                 /*This Writes*/WriteProcessMemory(handle, (LPVOID)0x04F6DCFE3DC, &newValue, sizeof(newValue), 0);
                 cout << p;
                 Sleep(3000);

            }
        }
    }
}

Body:
It's fairly easy. Just use a std::vector<std::pair<int*,int>> to contain all these addresses you want to modify along with the value they should achieve:

std::vector<std::pair<int*,int>> changeMap = {
    { (int*)0x4F6DCFE3DC , 0 }
    // more address value pairs ...
};

Then you can process them in a loop:

for(auto it = std::begin(changeMap); it != std::end(changeMap); ++it)
{
    WriteProcessMemory(handle, (LPVOID)it->first, &(it->second),
                       sizeof(it->second), 0);
}

Whatever you want to achieve with that1.

I've already been told to try putting all the addresses in an array, how do I do this?

If you want to set all the address contents to 0 you may use a simpler construct:

int newValue = 0;
std::vector<int*> changeAddrList = {
    (int*)0x4F6DCFE3DC ,
    // more addresses to change ...
};

// ...

for(auto addr : changeAddrList)
{
    WriteProcessMemory(handle, (LPVOID)addr , &newValue ,
                       sizeof(newValue), 0);
}

1Fiddling around in another processes memory is error prone and might lead to all kinds of unexpected behavior!

Your code may fail miserably at a newer version of that program, where you're trying to apply your cheat codez.


问:
wirte on external sd card does not work
My app doesn't seem to have writing permissions on my external sd card. I can read from it, but writing does only work on the internal one (sdcard0).
When i try

```<code>File f = new File("/storacge/sdcard1/Test/file.mp3");
boolean b = f.delete();
</code>```

then b is false and the file still exists. But i can play it with MediaPlayer.

I have <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> in my Manifest

What am i doing wrong?

答:
1)You need to ask for runtime permissions

2)Don't assume that the path is /storage/sdcard1.  That varies between devices.  Request the name via getExternalFilesDirs

Title: wirte on external sd card does not work

Body:
My app doesn't seem to have writing permissions on my external sd card. I can read from it, but writing does only work on the internal one (sdcard0).
When i try

File f = new File("/storacge/sdcard1/Test/file.mp3");
boolean b = f.delete();

then b is false and the file still exists. But i can play it with MediaPlayer.

I have <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> in my Manifest

What am i doing wrong?


问:
How to calculate form fields values to update hidden field value?
I want to know how to calculate the input values of the following fields

```<code><input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
</code>```

And update the span text and the hidden field value

```<code>TOTAL <span id="amountTotal">0 </span>
<input id="total" type="hidden" name="total" value="">
</code>```

Thanks in advance

答:
Please try this one.

$('.auto-sum').on('change',function(){
var totalvalue=0;
$('.auto-sum').each(function(a,b){
totalvalue=totalvalue+parseInt(($(b).val()=='' || isNaN($(b).val()))?0:$(b).val());
});

$('#amountTotal').text(totalvalue);
$('#total').val(totalvalue);
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">

TOTAL  <span id="amountTotal">0</span>
<input id="total" type="hidden" name="total" value=""></code>```

Body:
I want to know how to calculate the input values of the following fields

<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">

And update the span text and the hidden field value

TOTAL 0
<input id="total" type="hidden" name="total" value="">

Thanks in advance

Body:
Please try this one.

$('.auto-sum').on('change',function(){
var totalvalue=0;
$('.auto-sum').each(function(a,b){
totalvalue=totalvalue+parseInt(($(b).val()=='' || isNaN($(b).val()))?0:$(b).val());
});

$('#amountTotal').text(totalvalue);
$('#total').val(totalvalue);
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">

TOTAL  <span id="amountTotal">0</span>
<input id="total" type="hidden" name="total" value="">


问:
Exception in property when setting a binary value
I have the following method which gives me a stackoverflow exception on setting a value. I can't step into it and debug it application just crashes few seconds later. Here is the code

```<code>public byte[] ImageTIFF
{
    get
    {
        try
        {
            string filePath = ImageTIFFDir + ImageId + ".TIFF";

            if (File.Exists(filePath))
            {
                return File.ReadAllBytes(ImageTIFFDir + ImageCollectionId + ".TIFF");
            }
            else
            {
                return null;
            }
        }
        catch (Exception e)
        {
            Logger.log("Can't read TIFF image from file.", e);
            throw;
        }
    }
    set
    {
        try
        {
            ImageTIFF = value;
        }
        catch (Exception e)
        {
            Logger.log("Can't set image TIFF.", e);
            throw;
        }

    }
}
</code>```

This gets called during an export and it fails on a first call:

```<code>someImage.ImageTIFF = File.ReadAllBytes(imageName);
</code>```

答:
You're setting the value of Property within setting the value of the property...recursion, my friend:

```<code>ImageTIFF = value;
</code>```

You'll need to create another variable to hole value. Properties are no variables, they're just wrappers.

Body:
I have the following method which gives me a stackoverflow exception on setting a value. I can't step into it and debug it application just crashes few seconds later. Here is the code

public byte[] ImageTIFF
{
    get
    {
        try
        {
            string filePath = ImageTIFFDir + ImageId + ".TIFF";

            if (File.Exists(filePath))
            {
                return File.ReadAllBytes(ImageTIFFDir + ImageCollectionId + ".TIFF");
            }
            else
            {
                return null;
            }
        }
        catch (Exception e)
        {
            Logger.log("Can't read TIFF image from file.", e);
            throw;
        }
    }
    set
    {
        try
        {
            ImageTIFF = value;
        }
        catch (Exception e)
        {
            Logger.log("Can't set image TIFF.", e);
            throw;
        }

    }
}

This gets called during an export and it fails on a first call:

someImage.ImageTIFF = File.ReadAllBytes(imageName);

Body:
You're setting the value of Property within setting the value of the property...recursion, my friend:

ImageTIFF = value;

You'll need to create another variable to hole value. Properties are no variables, they're just wrappers.


问:
Is there !< and !> in JavaScript?
Someone told me that there's !< and !> in JavaScript. I tried it but it didn't work. Is there something like this in JavaScript? If not in JavaScript, is it there in any other language?</p>

答: No !< and !> are not there in javascript and in most of the other  programming languages too. You can try > instead of !< and < instead of !>

Title: Is there !< and !> in JavaScript?


问:
How to create a dynamic LOV at runtime
How to create a dynamic attribute in lov at runtime?
Suppose I have a employee lov, where only two attributes are currently present like employee id and employee name.

It user want to add a few more column at run time like employee age and employee salary.
Without changing the LOV logic. The user has one master table where IT user can handle how many attribute should be displayed to business user. They can add a new parameter in table which can be displayed.

Can anybody suggest me some approach to handle this type of scenario?

答: If I got you right, I'd use backingBean with method that returns List, that implemented as ArrayList<SelectItem>. Then populate from any source(like VO, or whatever mixed) label and value according to your current user request.

Title: How to create a dynamic LOV at runtime


问:
HTML link to local file in WebView with target API 24
How can one use HTML links to navigate to local files (HTML pages) in WebView if targeting API 24 or higher?

This has been discussed before and solutions use the file:// URI scheme.
What worked so far was using

```<code><a href="file:///android_asset/my_page.html">Go to local page</a>
</code>```

in an HTML file that is displayed in a WebView and clicking the link would load the local page app/src/main/assets/my_page.html.

However, starting from API 24, a FileUriExposedException is raised when clicking such a link. From logcat:

```<code>mypackage.myapp W/System.err: android.os.FileUriExposedException: file:///android_asset/my_page.html exposed beyond app through Intent.getData()
...
mypackage.myapp W/System.err:     at org.chromium.android_webview.ResourcesContextWrapperFactory$WebViewContextWrapper.startActivity(ResourcesContextWrapperFactory.java:121)
mypackage.myapp W/System.err:     at org.chromium.android_webview.AwContentsClient.sendBrowsingIntent(AwContentsClient.java:203)
</code>```

According to the documentation, this is thrown when "an application exposes a file:// Uri to another app.". I wonder why this is the case, because according to the log everything seems to happen inside mypackage.myapp.

The documentation suggests using the content:// URI scheme instead, but this does not work in HTML files.

答:
I never link in the HTML that way if you need to load an other page:

```<code><a href="file:///android_asset/my_page.html">Go to local page</a>
</code>```

I link this way because my map struture look like this:

```<code><a href="my_page.html">Go to local page</a>
</code>```

You just need that methode in your MainActivity.java and that will work:

```<code>private class MyBrowser extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url.startsWith("tel:") || url.startsWith("sms:") || url.startsWith("smsto:") || url.startsWith("mailto:") || url.startsWith("mms:") || url.startsWith("mmsto:") || url.startsWith("market:")) {
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
            return true;
        }
        else {
            view.loadUrl(url);
            return true;
        }
    }
}
</code>```

If you have any questions or It still don't work let me know

Body:
How can one use HTML links to navigate to local files (HTML pages) in WebView if targeting API 24 or higher?

This has been discussed before and solutions use the file:// URI scheme.
What worked so far was using

Go to local page

in an HTML file that is displayed in a WebView and clicking the link would load the local page app/src/main/assets/my_page.html.

However, starting from API 24, a FileUriExposedException is raised when clicking such a link. From logcat:

mypackage.myapp W/System.err: android.os.FileUriExposedException: file:///android_asset/my_page.html exposed beyond app through Intent.getData()
...
mypackage.myapp W/System.err:     at org.chromium.android_webview.ResourcesContextWrapperFactory$WebViewContextWrapper.startActivity(ResourcesContextWrapperFactory.java:121)
mypackage.myapp W/System.err:     at org.chromium.android_webview.AwContentsClient.sendBrowsingIntent(AwContentsClient.java:203)

According to the documentation, this is thrown when "an application exposes a file:// Uri to another app.". I wonder why this is the case, because according to the log everything seems to happen inside mypackage.myapp.

The documentation suggests using the content:// URI scheme instead, but this does not work in HTML files.

Body:
I never link in the HTML that way if you need to load an other page:

<a href="file:///android_asset/my_page.html">Go to local page</a>

I link this way because my map struture look like this:

<a href="my_page.html">Go to local page</a>

You just need that methode in your MainActivity.java and that will work:

private class MyBrowser extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url.startsWith("tel:") || url.startsWith("sms:") || url.startsWith("smsto:") || url.startsWith("mailto:") || url.startsWith("mms:") || url.startsWith("mmsto:") || url.startsWith("market:")) {
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
            return true;
        }
        else {
            view.loadUrl(url);
            return true;
        }
    }
}

If you have any questions or It still don't work let me know


问:
where is the Source code of adadelta in Tensorflow？
recently I have some confusion about adadelta in TensorFlow，I want to modify it rules of learning-rate ，but i not know how to do it.
i think i have to modify the source code :
because the rules is encapsulated in train.AdadeltaOpertimizer，and the class not
return learning-rate,it only has a initially learning-rate:

def init(self, learning_rate=0.001, rho=0.95, epsilon=1e-8,
               use_locking=False, name="Adadelta"):

where is the source code of adadelta in Tensorflow？

答:
I have not understood what exactly you want to modify, so I will just show how to find the source code for everything.

Each function in TF has information about the source-code of this function in the documentation. It points you to the python file.

For example AdaDelta optimizer has this in the docs:

Defined in tensorflow/python/training/adadelta.py.


问:
Selected Item of Autocomplete Textview Show as simple Textview?
I am using an Autocomplete Textview which shows some names from database.I want to show a name in a textview which I selected from autocomplete textview.Here is my code:

```<code>ArrayList<String> s1 = new ArrayList<String>();

      for (StudentInfo cn : studentInfo) {
            s1.add(cn.getName());
        }
        ArrayAdapter<String> adapter =  new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line,s1);
       a1.setThreshold(1);
        a1.setAdapter(adapter);
</code>```

```<code>a1.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
    }
        });
</code>```

答:
Use parent position is '0'</p>

```<code>  txt_search.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View arg1, int position, long id) {
            Object item = parent.getItemAtPosition(0);
            if (item instanceof MYData{
                MYData data=(MYData) item;
                String dd = data.getName();
            }
        }
    });
</code>```

Body:
I am using an Autocomplete Textview which shows some names from database.I want to show a name in a textview which I selected from autocomplete textview.Here is my code:

ArrayList<String> s1 = new ArrayList<String>();

      for (StudentInfo cn : studentInfo) {
            s1.add(cn.getName());
        }
        ArrayAdapter<String> adapter =  new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line,s1);
       a1.setThreshold(1);
        a1.setAdapter(adapter);

a1.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
    }
        });

Body:
Use parent position is '0'

  txt_search.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View arg1, int position, long id) {
            Object item = parent.getItemAtPosition(0);
            if (item instanceof MYData{
                MYData data=(MYData) item;
                String dd = data.getName();
            }
        }
    });


问:
APK not install when run the App after updation on Existing App
I have already Published App in Play Store. Now I add few things and want to upload it with new color and options but when I click on Run in Android Studio the "error message shown" as attached in img url here. I update my previous VersionCode from '1' to '2' and VersionName from '2.0' to '3.0'. But still not install apk in my Debug Device to check before published.
Where I missing and what exactly this error msg tell. Please help to solve this error. No Coding error in Android Studio found.

http://imgur.com/iPbU19Q

答: just delete the existing app manually and run the debugger</p>


问:
System Setting > Android SDK is missing
may I know why my "Android SDK" menu is missing? How do I enable it back?

答:
```<code> Go to Menu bar click ->View button and Select -> Toolbar
</code>```

Title: System Setting > Android SDK is missing


问:
Output three colums from my mysql database php
I'm a beginner in php and i'd like to output 3 fields from my database to my website which included a bloc image,text and name. using a foreach i can only get 2 out of the three.

```<code><table border="2px">
    <tr>
        <th> Brand</th>
        <th> Images</th>
        <th> Details</th>
    </tr>

    <?php
    $tex   = [];
    $query = mysqli_query($conn, "SELECT * FROM upload");
    while ($row = mysqli_fetch_assoc($query)) {
        $images[] = $row['image'];
        $br[]     = $row['name'];
        $det[]    = $row['text'];
    }
    foreach (array_combine($det, $images) as $text => $image) {
        echo "<tr><td>";
        echo $name;
        echo "</td>";
        echo "<td>";
        echo '<img src="data:image/jpeg;base64,'.base64_encode($image).'"/>';
        echo "<td>";
        echo $text;
        echo "</td>";
        echo "</td></tr>";
    }
    ?>
</table>
</code>```

that is a snippet of my code where images and text is outputted on the screen and receive and undefined variable in error in line 39 which would be echo $name;. what should i put in the foreach statement to get it to output all three?

```<code>$images[] = $row['image'];
$br[]     = $row['name'];
$det[]    = $row['text'];
</code>```

can someone explain these to me as i have an idea what it is doing but i want to be 100.

答:
There's no point using a separate foreach loop like that. You should simply change your while loop like this:

```<code>while($row = mysqli_fetch_assoc($query)){
    echo"<tr><td>";
    echo $row['name'];
    echo "</td>";
    echo "<td>";
    echo '<img src="data:image/jpeg;base64,'. base64_encode($row['image']) .'"/>';
    echo"<td>";
    echo $row['text'];
    echo "</td>";
    echo"</td></tr>";
}
</code>```

Body:
I'm a beginner in php and i'd like to output 3 fields from my database to my website which included a bloc image,text and name. using a foreach i can only get 2 out of the three.

         Brand
         Images
         Details

    <?php
    $tex   = [];
    $query = mysqli_query($conn, "SELECT * FROM upload");
    while ($row = mysqli_fetch_assoc($query)) {
        $images[] = $row['image'];
        $br[]     = $row['name'];
        $det[]    = $row['text'];
    }
    foreach (array_combine($det, $images) as $text => $image) {
        echo "
";
        echo $name;
        echo "	";
        echo "";
        echo '';
        echo "";
        echo $text;
        echo "	";
        echo "
";
    }
    ?>

that is a snippet of my code where images and text is outputted on the screen and receive and undefined variable in error in line 39 which would be echo $name;. what should i put in the foreach statement to get it to output all three?

$images[] = $row['image'];
$br[]     = $row['name'];
$det[]    = $row['text'];

can someone explain these to me as i have an idea what it is doing but i want to be 100.

Body:
There's no point using a separate foreach loop like that. You should simply change your while loop like this:

while($row = mysqli_fetch_assoc($query)){
    echo"<tr><td>";
    echo $row['name'];
    echo "</td>";
    echo "<td>";
    echo '<img src="data:image/jpeg;base64,'. base64_encode($row['image']) .'"/>';
    echo"<td>";
    echo $row['text'];
    echo "</td>";
    echo"</td></tr>";
}


问:
How i can add my contact in my channel with telethon API python
this is info my channel :

```<code>dialogs, entities = client.get_dialogs(1)
entity = entities[0]
print(entity)
(channel (ID: 0xa14dca52) = (creator=True, kicked=None, left=None, editor=None, moderator=None, broadcast=True, verified=None, megagroup=None, restricted=None, democracy=None, signatures=None, min=None, id=1135498252, access_hash=-6282984409346664480, title=channel_test, username=None, photo=(chatPhotoEmpty (ID: 0x37c1011c) = ()), date=2017-07-04 06:11:05, version=0, restriction_reason=None))
</code>```

and i have 3 contacts :

```<code>contacts = client.invoke(GetContactsRequest(""))
for u in contacts.contacts:
     print (u)
(contact (ID: 0xf911c994) = (user_id=231735496, mutual=False))
(contact (ID: 0xf911c994) = (user_id=408708469, mutual=False))
(contact (ID: 0xf911c994) = (user_id=442246143, mutual=False))
</code>```

I dont know how i can use this code:

```<code>from telethon.tl.functions.messages import AddChatUserRequest

client.invoke(AddChatUserRequest(
   chat_id,
   user_to_add,
   fwd_limit=10  # allow the user to see the 10 last messages
))
</code>```

what is chat_id ? and user_to_add ?

when i use this code

```<code>client.invoke(AddChatUserRequest(
   1135498252,
   231735496,
   fwd_limit=10  # allow the user to see the 10 last messages
))
</code>```

i see this error

```<code>Traceback (most recent call last):
 File "<pyshell#102>", line 4, in <module>
   fwd_limit=10  # allow the user to see the 10 last messages
  File "C:\Python34\lib\site-packages\telethon\telegram_client.py", line 247, in invoke
   request, timeout=timeout, updates=updates)
   File "C:\Python34\lib\site-packages\telethon\telegram_bare_client.py",    line 188, in invoke
    self.sender.send(request)
  File "C:\Python34\lib\site-packages\telethon\network\mtproto_sender.py",    line 57, in send
   request.on_send(writer)
  File "C:\Python34\lib\site-packages\telethon\tl\functions\messages    \add_chat_user.py", line 39, in on_send
   self.user_id.on_send(writer)
    AttributeError: 'int' object has no attribute 'on_send'
</code>```

答:
As I said on the issue I presume you opened too, you need to use the contact.users, not contacts.contacts. If you want to add the first user, first retrieve it, and then use it on the request:

```<code>contacts = client(GetContactsRequest(''))
user = contacts.users[0]  # For instance
client(AddChatUserRequest(
    chad_id=1135498252,
    user_id=user,  # Yes, the name is misleading
    fwd_limit=10
))
</code>```

As always, the documentation is your friend, and the documentation for AddChatUserRequest clearly says that user_id is of type InputUser (but you can pass it an User too).

Body:
this is info my channel :

dialogs, entities = client.get_dialogs(1)
entity = entities[0]
print(entity)
(channel (ID: 0xa14dca52) = (creator=True, kicked=None, left=None, editor=None, moderator=None, broadcast=True, verified=None, megagroup=None, restricted=None, democracy=None, signatures=None, min=None, id=1135498252, access_hash=-6282984409346664480, title=channel_test, username=None, photo=(chatPhotoEmpty (ID: 0x37c1011c) = ()), date=2017-07-04 06:11:05, version=0, restriction_reason=None))

and i have 3 contacts :

contacts = client.invoke(GetContactsRequest(""))
for u in contacts.contacts:
     print (u)
(contact (ID: 0xf911c994) = (user_id=231735496, mutual=False))
(contact (ID: 0xf911c994) = (user_id=408708469, mutual=False))
(contact (ID: 0xf911c994) = (user_id=442246143, mutual=False))

I dont know how i can use this code:

from telethon.tl.functions.messages import AddChatUserRequest

client.invoke(AddChatUserRequest(
   chat_id,
   user_to_add,
   fwd_limit=10  # allow the user to see the 10 last messages
))

what is chat_id ? and user_to_add ?

when i use this code

client.invoke(AddChatUserRequest(
   1135498252,
   231735496,
   fwd_limit=10  # allow the user to see the 10 last messages
))

i see this error

Traceback (most recent call last):
 File "<pyshell#102>", line 4, in <module>
   fwd_limit=10  # allow the user to see the 10 last messages
  File "C:\Python34\lib\site-packages\telethon\telegram_client.py", line 247, in invoke
   request, timeout=timeout, updates=updates)
   File "C:\Python34\lib\site-packages\telethon\telegram_bare_client.py",    line 188, in invoke
    self.sender.send(request)
  File "C:\Python34\lib\site-packages\telethon\network\mtproto_sender.py",    line 57, in send
   request.on_send(writer)
  File "C:\Python34\lib\site-packages\telethon\tl\functions\messages    \add_chat_user.py", line 39, in on_send
   self.user_id.on_send(writer)
    AttributeError: 'int' object has no attribute 'on_send'

Body:
As I said on the issue I presume you opened too, you need to use the contact.users, not contacts.contacts. If you want to add the first user, first retrieve it, and then use it on the request:

contacts = client(GetContactsRequest(''))
user = contacts.users[0]  # For instance
client(AddChatUserRequest(
    chad_id=1135498252,
    user_id=user,  # Yes, the name is misleading
    fwd_limit=10
))

As always, the documentation is your friend, and the documentation for AddChatUserRequest clearly says that user_id is of type InputUser (but you can pass it an User too).


问:
android.widget.LinearLayout cannot be cast to android.widget.TextView
I add a ListView on runtime like this:

```<code>     MainMenue =  getResources().getStringArray(R.array.Unit);
    // remove all controls
    LinearLayout formLayout = (LinearLayout)findViewById(R.id.submenue);
    formLayout.removeAllViews();
    menueview = new ListView(getApplicationContext());
    menueview.setVisibility(ListView.VISIBLE);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
               LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
    params.gravity = Gravity.RIGHT;
    menueview.setLayoutParams(params);
    menueview.setAdapter(new submenueadapter(menueview.getContext(), MainMenue));
    // Set the on Item
    SetMenueOnClick() ;
    formLayout.addView(menueview);
</code>```

and then I add a item click listener like this:

```<code> public void SetMenueOnClick() {
     menueview.setOnItemClickListener(new OnItemClickListener() {
          public void onItemClick(AdapterView<?> parent, View view,
                  int position, long id) {
              final String text = (String) ((TextView)view).getText();
          }
     });
 }
</code>```

But then I have an error:

```<code>06-03 10:59:25.862: E/AndroidRuntime(14732):    at android.view.ViewRoot.handleMessage(ViewRoot.java:2109)
android.widget.LinearLayout cannot be cast to android.widget.TextView
</code>```

at this line:

```<code>final String text = (String) ((TextView)view).getText();
</code>```

Any idea how to get the text in this issue? the adapter looks like this:

```<code>public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View rowView = inflater.inflate(R.layout.shortmenue, parent, false);
    TextView textView = (TextView) rowView.findViewById(R.id.contents);

    textView.setText(values[position]);

    // Change icon based on name
    String s = values[position];

    System.out.println(s);

    rowView.setBackgroundResource(R.drawable.alternate_list_color);
    return rowView;
}
</code>```

and R.layout.shortmenue is simple, only a TextView like below:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

                <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/contents"
                android:textSize="34dp"

                />

</LinearLayout>
</code>```

答:
You can resolve this by replacing

```<code>final String text = (String) ((TextView)view).getText();
</code>```

with

```<code>TextView temp= (TextView) view.findViewById(R.id.textView);
</code>```

This works for me.

Body:
I add a ListView on runtime like this:

     MainMenue =  getResources().getStringArray(R.array.Unit);
    // remove all controls
    LinearLayout formLayout = (LinearLayout)findViewById(R.id.submenue);
    formLayout.removeAllViews();
    menueview = new ListView(getApplicationContext());
    menueview.setVisibility(ListView.VISIBLE);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
               LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
    params.gravity = Gravity.RIGHT;
    menueview.setLayoutParams(params);
    menueview.setAdapter(new submenueadapter(menueview.getContext(), MainMenue));
    // Set the on Item
    SetMenueOnClick() ;
    formLayout.addView(menueview);

and then I add a item click listener like this:

 public void SetMenueOnClick() {
     menueview.setOnItemClickListener(new OnItemClickListener() {
          public void onItemClick(AdapterView<?> parent, View view,
                  int position, long id) {
              final String text = (String) ((TextView)view).getText();
          }
     });
 }

But then I have an error:

06-03 10:59:25.862: E/AndroidRuntime(14732):    at android.view.ViewRoot.handleMessage(ViewRoot.java:2109)
android.widget.LinearLayout cannot be cast to android.widget.TextView

at this line:

final String text = (String) ((TextView)view).getText();

Any idea how to get the text in this issue? the adapter looks like this:

public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View rowView = inflater.inflate(R.layout.shortmenue, parent, false);
    TextView textView = (TextView) rowView.findViewById(R.id.contents);

    textView.setText(values[position]);

    // Change icon based on name
    String s = values[position];

    System.out.println(s);

    rowView.setBackgroundResource(R.drawable.alternate_list_color);
    return rowView;
}

and R.layout.shortmenue is simple, only a TextView like below:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

                <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/contents"
                android:textSize="34dp"

                />

</LinearLayout>

Body:
You can resolve this by replacing

final String text = (String) ((TextView)view).getText();

with

TextView temp= (TextView) view.findViewById(R.id.textView);

This works for me.


问:
To get a average % of two columns
I have the columns as mentioned below

```
1)OldOrderQty
2)NewOrderQty
3)OLdunitRate
4)NewUnitRate```

My issue is i need to get % of savings
if there is any savings for the new unit rate

Please help me out with this
thanks a lot for any answers

答:
```<code>3 * 1 = x
4 * 2 = y
</code>```

y / x = would be the savings I presume

Title: To get a average % of two columns

Body:
I have the columns as mentioned below

1)OldOrderQty
2)NewOrderQty
3)OLdunitRate
4)NewUnitRate

My issue is i need to get % of savings
if there is any savings for the new unit rate

Please help me out with this
thanks a lot for any answers

Body:
3 * 1 = x
4 * 2 = y

y / x = would be the savings I presume


问:
Retrofit 2 error URL query string must not have replace block
I am trying to call a legacy API using Retrofit 2, this is the URL "/api/0.3/v3/?endpoint=/admin/customers/6728382/addresses.json" and this is the interface method

```<code>@GET("/api/0.3/v3/?endpoint=/admin/customers/{customerId}/addresses.json")
Single<GetCustomerAddressesResponse> getUserAddresses(@Path("customerId") String customerId);
</code>```

However I am getting this error,

"URL query string
  "endpoint=//admin/customers/{customerId}/addresses.json" must not have
  replace block. For dynamic query parameters use @Query."

How can I fix this?

答: I think id has to be int type. Try to change String to int.

Body:
I am trying to call a legacy API using Retrofit 2, this is the URL "/api/0.3/v3/?endpoint=/admin/customers/6728382/addresses.json" and this is the interface method

@GET("/api/0.3/v3/?endpoint=/admin/customers/{customerId}/addresses.json")
Single<GetCustomerAddressesResponse> getUserAddresses(@Path("customerId") String customerId);

However I am getting this error,

"URL query string
  "endpoint=//admin/customers/{customerId}/addresses.json" must not have
  replace block. For dynamic query parameters use @Query."

How can I fix this?


问:
ienumerable , looping in mvc
I'm creating a page with multiple file uploader in MVC.

What I want to achieve is when I submit values the images uploaded should be named as guid and an incrementing i value, like guid0 , guid1, guid2. I tried for loop but its saving only one image until loop ends . i++ isn't working though.

My controller looks like this:

```<code>public ActionResult Home(SomeClass someclass, IEnumerable<HttpPostedFileBase> files)
    {
        var guid = Guid.NewGuid().ToString();
        someclass.filename = guid;
        int i = 0;
        foreach (var file in files)
        {
            if (file.ContentLength > 0)
             {
                var fileName = guid + "" + i + ".jpg";
                var path = Path.Combine(Server.MapPath("~/Content/admin/Upload"), fileName);
                file.SaveAs(path);
                i++;
             }
         }
         db.someclasses.Add(someclass);
         db.SaveChanges();
         return RedirectToAction("Preview");
      }
</code>```

And my view looks like this

```<code><input type="file" name="files" id=1>
<input type="file" name="files" id=2>
</code>```

Update : I'm receiving 11 files at the if loop but once they go through the loop there is only single image in the images folder named fdea36c3-545a-4e08-8af4-7fa6bd88bc6b0 . what i'm trying to achieve is all 11 images named as fdea36c3-545a-4e08-8af4-7fa6bd88bc6b0, fdea36c3-545a-4e08-8af4-7fa6bd88bc6b1,fdea36c3-545a-4e08-8af4-7fa6bd88bc6b2.....so on .

答:
try this way if you have multiple file controls on view.
you can even have Guid initialized  for each file and can ignore appending i to the name.

```<code>public class MultipleFilesForm
{
    public HttpPostedFileBase file1 {get;set;}

    public HttpPostedFileBase file2 {get;set;}
}
</code>```

action method as

```<code>public ActionResult Home(MultipleFilesForm form)
{
        var guid = Guid.NewGuid().ToString();
        someclass.filename = guid;
        int i = 0;

    if(form.file1 != null)
    {
             var file = form.file1;
             if (file.ContentLength > 0)
             {
                var fileName = guid + i.ToString() + Path.GetExtension(file.FileName));
                var path = Path.Combine(Server.MapPath("~/Content/admin/Upload"), fileName);
                file.SaveAs(path);
                i++;
             }
    }
    if(form.file2 != null)
    {
        //handle file
    }

    ...
}
</code>```

[UPDATE]
try this way

try this as well.

```<code>for (int i = 0; i < Request.Files.Count; i++)
        {
            var file = Request.Files[i];

            if (file != null && file.ContentLength > 0)
            {
     var fileName = guid + i.ToString() + Path.GetExtension(file.FileName));

var path = Path.Combine(Server.MapPath("~/Content/admin/Upload"), fileName);

 file.SaveAs(path);

i++;
            }
         }
</code>```

Title: ienumerable , looping in mvc

Body:
I'm creating a page with multiple file uploader in MVC.

What I want to achieve is when I submit values the images uploaded should be named as guid and an incrementing i value, like guid0 , guid1, guid2. I tried for loop but its saving only one image until loop ends . i++ isn't working though.

My controller looks like this:

public ActionResult Home(SomeClass someclass, IEnumerable<HttpPostedFileBase> files)
    {
        var guid = Guid.NewGuid().ToString();
        someclass.filename = guid;
        int i = 0;
        foreach (var file in files)
        {
            if (file.ContentLength > 0)
             {
                var fileName = guid + "" + i + ".jpg";
                var path = Path.Combine(Server.MapPath("~/Content/admin/Upload"), fileName);
                file.SaveAs(path);
                i++;
             }
         }
         db.someclasses.Add(someclass);
         db.SaveChanges();
         return RedirectToAction("Preview");
      }

And my view looks like this

<input type="file" name="files" id=1>
<input type="file" name="files" id=2>

Update : I'm receiving 11 files at the if loop but once they go through the loop there is only single image in the images folder named fdea36c3-545a-4e08-8af4-7fa6bd88bc6b0 . what i'm trying to achieve is all 11 images named as fdea36c3-545a-4e08-8af4-7fa6bd88bc6b0, fdea36c3-545a-4e08-8af4-7fa6bd88bc6b1,fdea36c3-545a-4e08-8af4-7fa6bd88bc6b2.....so on .

Body:
try this way if you have multiple file controls on view.
you can even have Guid initialized  for each file and can ignore appending i to the name.

public class MultipleFilesForm
{
    public HttpPostedFileBase file1 {get;set;}

    public HttpPostedFileBase file2 {get;set;}
}

action method as

public ActionResult Home(MultipleFilesForm form)
{
        var guid = Guid.NewGuid().ToString();
        someclass.filename = guid;
        int i = 0;

    if(form.file1 != null)
    {
             var file = form.file1;
             if (file.ContentLength > 0)
             {
                var fileName = guid + i.ToString() + Path.GetExtension(file.FileName));
                var path = Path.Combine(Server.MapPath("~/Content/admin/Upload"), fileName);
                file.SaveAs(path);
                i++;
             }
    }
    if(form.file2 != null)
    {
        //handle file
    }

    ...
}

[UPDATE]
try this way

try this as well.

for (int i = 0; i < Request.Files.Count; i++)
        {
            var file = Request.Files[i];

            if (file != null && file.ContentLength > 0)
            {
     var fileName = guid + i.ToString() + Path.GetExtension(file.FileName));

var path = Path.Combine(Server.MapPath("~/Content/admin/Upload"), fileName);

 file.SaveAs(path);

i++;
            }
         }


问:
Echoing a Product of Two Variables in PHP
I have the following code:

```<code>    $sel_referrals1="SELECT SUM(amount) as da_sum FROM topup WHERE user_id IN(SELECT t1.referree
FROM referrals AS t1
LEFT JOIN referrals AS t2 ON t2.referrer = t1.referree
LEFT JOIN referrals AS t3 ON t3.referrer = t2.referree
LEFT JOIN referrals AS t4 ON t4.referrer = t3.referree
LEFT JOIN referrals AS t5 ON t5.referrer = t4.referree
LEFT JOIN referrals AS t6 ON t6.referrer = t5.referree
LEFT JOIN referrals AS t7 ON t7.referrer = t6.referree
LEFT JOIN referrals AS t8 ON t8.referrer = t7.referree
LEFT JOIN referrals AS t9 ON t9.referrer = t8.referree
LEFT JOIN referrals AS t10 ON t10.referrer = t9.referree
LEFT JOIN referrals AS t11 ON t11.referrer = t10.referree
WHERE t1.referrer = '{$_SESSION['user']}')
AND YEAR(date_time) = YEAR(CURRENT_DATE())
AND MONTH(date_time) = MONTH(CURRENT_DATE())";

    $selected1=mysqli_query($conn,$sel_referrals1);
    $sel_level1_array=mysqli_fetch_row($selected1);
    $level1=number_format($sel_level1_array[0],2);
</code>```

$level1 evaluates as 1260.00.I have another variable $rate1 which is set as follows: $rate1=0.02.I need to multiply $level1 with $rate1. But, when code executes the   multiplication of $level1 * $rate1, the result yields 0.02.

My expected result is 25.20. What am I doing wrong?

答:
The problem stems from this statement in the OP's updated code:

```<code>$level1 = number_format( $sel_level1_array[0], 2 );
</code>```

By itself, the statement is fine.  The difficulty is that next $level1 is multiplied by $rate1, producing a seemingly bizarre result of 0.02. It does make sense once you understand the way PHP's parser behaves.

By default, when number_format() bears only two parameters, it returns a numeric string which includes a comma as a thousands-separator.  So, the value assigned to $level1 is actually "1,260.00", which the world beyond PHPland recognizes as essentially the same as 1260.00. The parser, however, disagrees as you may observe in the following example replicating this issue:

```<code><?php

$rate1 = 0.02;
$level1 = number_format(1260,2);

var_dump($rate1 * $level1);  // 0.02
</code>```

See demo

If you set error_reporting() on, shockingly, the code doesn't even emit a notice with respect to the last statement -- unless one is using PHP 7.1+ (see here) in which case it raises this error message:

Notice: A non well formed numeric value encountered ...

The reason for this message owes to the comma that number_format() inserted into the numeric string.  Once the parser encounters that non-numeric character, after handling the first digit "1", it ceases to further process the string, causing it to prematurely evaluate as the integer one. Thus, to ensure an accurate and expected result, numeric strings should not contain a comma when serving as operands.

You may avoid this PHP "gotcha" by initially specifing that number_format() should exclude a thousands-separator, as follows:

```<code><?php

$level1 = number_format(1260,2,'.','');
</code>```

Subsequently, $rate1 multiplied by $level1 produces the expected result of 25.20; see here.

Alternatively, one may simplify the code and only apply number_format() to the final result; see demo

Body:
I have the following code:

    $sel_referrals1="SELECT SUM(amount) as da_sum FROM topup WHERE user_id IN(SELECT t1.referree
FROM referrals AS t1
LEFT JOIN referrals AS t2 ON t2.referrer = t1.referree
LEFT JOIN referrals AS t3 ON t3.referrer = t2.referree
LEFT JOIN referrals AS t4 ON t4.referrer = t3.referree
LEFT JOIN referrals AS t5 ON t5.referrer = t4.referree
LEFT JOIN referrals AS t6 ON t6.referrer = t5.referree
LEFT JOIN referrals AS t7 ON t7.referrer = t6.referree
LEFT JOIN referrals AS t8 ON t8.referrer = t7.referree
LEFT JOIN referrals AS t9 ON t9.referrer = t8.referree
LEFT JOIN referrals AS t10 ON t10.referrer = t9.referree
LEFT JOIN referrals AS t11 ON t11.referrer = t10.referree
WHERE t1.referrer = '{$_SESSION['user']}')
AND YEAR(date_time) = YEAR(CURRENT_DATE())
AND MONTH(date_time) = MONTH(CURRENT_DATE())";

    $selected1=mysqli_query($conn,$sel_referrals1);
    $sel_level1_array=mysqli_fetch_row($selected1);
    $level1=number_format($sel_level1_array[0],2);

$level1 evaluates as 1260.00.I have another variable $rate1 which is set as follows: $rate1=0.02.I need to multiply $level1 with $rate1. But, when code executes the   multiplication of $level1 * $rate1, the result yields 0.02.

My expected result is 25.20. What am I doing wrong?

Body:
The problem stems from this statement in the OP's updated code:

$level1 = number_format( $sel_level1_array[0], 2 );

By itself, the statement is fine.  The difficulty is that next $level1 is multiplied by $rate1, producing a seemingly bizarre result of 0.02. It does make sense once you understand the way PHP's parser behaves.

By default, when number_format() bears only two parameters, it returns a numeric string which includes a comma as a thousands-separator.  So, the value assigned to $level1 is actually "1,260.00", which the world beyond PHPland recognizes as essentially the same as 1260.00. The parser, however, disagrees as you may observe in the following example replicating this issue:

<?php

$rate1 = 0.02;
$level1 = number_format(1260,2);

var_dump($rate1 * $level1);  // 0.02

See demo

If you set error_reporting() on, shockingly, the code doesn't even emit a notice with respect to the last statement -- unless one is using PHP 7.1+ (see here) in which case it raises this error message:

Notice: A non well formed numeric value encountered ...

The reason for this message owes to the comma that number_format() inserted into the numeric string.  Once the parser encounters that non-numeric character, after handling the first digit "1", it ceases to further process the string, causing it to prematurely evaluate as the integer one. Thus, to ensure an accurate and expected result, numeric strings should not contain a comma when serving as operands.

You may avoid this PHP "gotcha" by initially specifing that number_format() should exclude a thousands-separator, as follows:

<?php

$level1 = number_format(1260,2,'.','');

Subsequently, $rate1 multiplied by $level1 produces the expected result of 25.20; see here.

Alternatively, one may simplify the code and only apply number_format() to the final result; see demo


问:
Adding a script to a game object dynamically and assigning values to its properties
I want to add a script/component to a game object and populate values in that script. The values for input come from the parent object as 'LineManagerProperty'. In the example below I want to add the 'LineManager' class to the 'Line' game object and assign the properties in 'LineManager'. If you look at the 'Line' class I add 'LineManagerProperty' so that it can appear in the unity inspector as values to pass into 'LineManager'. Is there a better way to do this?

```<code>public class Line : MonoBehaviour
{
    //This is added here so that values can appear in inspector
    //These values will be passed into 'LineManager' when its created and added to 'Line' game object
    public LineManagerProperty LineManagerProperty;

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            //Add the 'LineManager' script and assign its properties
            gameObject.AddComponent<LineManager>().LineManagerProperty = new LineManagerProperty()
            {
                CollisionTag = LineManagerProperty.CollisionTag,
                MaxTimeDuration = LineManagerProperty.MaxTimeDuration,
                NumberOfHits = LineManagerProperty.NumberOfHits,
                Health = LineManagerProperty.Health
            };
        }
    }
}

public class LineManager : MonoBehaviour
{
    public LineManagerProperty LineManagerProperty;

    //...
}

[Serializable]
public class LineManagerProperty
{
    public string CollisionTag;
    public float MaxTimeDuration;
    public float NumberOfHits;
}
</code>```

答:
I don't understand what you want, do you wanna see LineManager in inspector or not, or what, but i will try to help.  I guess you are creating some editor and you don't want to save LineManager in prefab.

Maybe it will give some idea for you, idk.

```<code>#define EDIT_MODE // if you delete this, code in EDIT_MODE fields will ignored and never compiled
using UnityEngine;
public class Line : MonoBehaviour {
    public LineManagerProperty lineManagerProperty;
#if EDIT_MODE
    LineManager lineManager;
#endif
    void Start() {
#if EDIT_MODE
        lineManager = new LineManager(lineManagerProperty);
#endif
    }

    void Update() {
#if EDIT_MODE
        lineManager.Update();// if you want to call something
#endif
    }
}

public class LineManager  {
   public LineManager(LineManagerProperty lmp) {
       LineManagerProperty = lmp;
   }

   public LineManagerProperty LineManagerProperty;

   public void Update() { // if you want to call something
   }
}
</code>```

Body:
I want to add a script/component to a game object and populate values in that script. The values for input come from the parent object as 'LineManagerProperty'. In the example below I want to add the 'LineManager' class to the 'Line' game object and assign the properties in 'LineManager'. If you look at the 'Line' class I add 'LineManagerProperty' so that it can appear in the unity inspector as values to pass into 'LineManager'. Is there a better way to do this?

public class Line : MonoBehaviour
{
    //This is added here so that values can appear in inspector
    //These values will be passed into 'LineManager' when its created and added to 'Line' game object
    public LineManagerProperty LineManagerProperty;

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            //Add the 'LineManager' script and assign its properties
            gameObject.AddComponent<LineManager>().LineManagerProperty = new LineManagerProperty()
            {
                CollisionTag = LineManagerProperty.CollisionTag,
                MaxTimeDuration = LineManagerProperty.MaxTimeDuration,
                NumberOfHits = LineManagerProperty.NumberOfHits,
                Health = LineManagerProperty.Health
            };
        }
    }
}

public class LineManager : MonoBehaviour
{
    public LineManagerProperty LineManagerProperty;

    //...
}

[Serializable]
public class LineManagerProperty
{
    public string CollisionTag;
    public float MaxTimeDuration;
    public float NumberOfHits;
}

Body:
I don't understand what you want, do you wanna see LineManager in inspector or not, or what, but i will try to help.  I guess you are creating some editor and you don't want to save LineManager in prefab.

Maybe it will give some idea for you, idk.

#define EDIT_MODE // if you delete this, code in EDIT_MODE fields will ignored and never compiled
using UnityEngine;
public class Line : MonoBehaviour {
    public LineManagerProperty lineManagerProperty;
#if EDIT_MODE
    LineManager lineManager;
#endif
    void Start() {
#if EDIT_MODE
        lineManager = new LineManager(lineManagerProperty);
#endif
    }

    void Update() {
#if EDIT_MODE
        lineManager.Update();// if you want to call something
#endif
    }
}

public class LineManager  {
   public LineManager(LineManagerProperty lmp) {
       LineManagerProperty = lmp;
   }

   public LineManagerProperty LineManagerProperty;

   public void Update() { // if you want to call something
   }
}


问:
Use ES6 'import' statement without transpilers
I have nodejs v8

```<code>$ node -v
v8.1.3
</code>```

and a script:

```<code>import cmd from "commander";
</code>```

There is an error "Unexpected token import" when I try to launch this script:

```<code>$ node script.js
/.../script.js:1
(function (exports, require, module, __filename, __dirname) { import cmd from "commander";
                                                              ^^^^^^

    SyntaxError: Unexpected token import
</code>```

Does any method exist to use ES6 modules ("import" statement) without transpiler?

答:
Without using transpiler, you have to use require:

```<code>const cmd = require('commander');
</code>```

Body:
I have nodejs v8

$ node -v
v8.1.3

and a script:

import cmd from "commander";

There is an error "Unexpected token import" when I try to launch this script:

$ node script.js
/.../script.js:1
(function (exports, require, module, __filename, __dirname) { import cmd from "commander";
                                                              ^^^^^^

    SyntaxError: Unexpected token import

Does any method exist to use ES6 modules ("import" statement) without transpiler?

Body:
Without using transpiler, you have to use require:

const cmd = require('commander');


问:
debugger for C/C++ and Java
I mainly use vim, but I really like the debuggers used in modern IDEs such as Netbeans, Visual C++, and Eclipse and I am wondering if there were any debuggers like those except in a standalone program? I tried using gdb, but it seems that debugging will take a lot longer using a command line. I also tried ddd, but it was a little frustrating to use since it would not display some complex structures with arrays. I really like how the debuggers in the modern IDEs allow me to just click on the down arrow to view what are in my arrays something which I do not know how to do in gdb or ddd.</p>

答:
You could have a look at:

http://code.google.com/p/jswat/

It's a standalone java debugger. I'm afraid it doesn't support C++ debugging.

Title: debugger for C/C++ and Java


问:
Print specific rows from dataframe using a condition
Be advised I'm doing this in a Function, and I've already referred a pretty good thread.

Here's the python function, the parameter passed is taken from user

```<code>def recommend(uid):
    ds = pd.read_csv("pred_matrix-full_ubcf.csv")
    records = ds.loc[ds['uid'] == uid]
    for recom in records:
        print recom
</code>```

Data Format:

```<code>uid iid     rat
344 1189    5
344 1500    5
344 814     5
736 217     3.3242361285
736 405     3.3238380154
736 866     3.323500531
331 1680    2
331 1665    2
331 36      1.999918585
</code>```

Referred:
this1,
this2

Unable to get where I'm going wrong, I'm following this1 thread and yet unable to get it.

答:
To iterate over your rows, use df.iterrows():

```<code>In [53]: records = df[df['uid'] == query]

In [54]: for index, row in records.iterrows():
    ...:     print(row['uid'], row['iid'], row['rat'])
    ...:
344.0 1189.0 5.0
344.0 1500.0 5.0
344.0 814.0 5.0
</code>```

There's two other possible ways to do select your data. You can use boolean indexing:

```<code>In [4]: query = 344

In [7]: df[df['uid'] == query]
Out[7]:
   uid   iid  rat
0  344  1189  5.0
1  344  1500  5.0
2  344   814  5.0
</code>```

You can also use DataFrame.query function:

```<code>In [8]: df.query('uid == %d' %query)
Out[8]:
   uid   iid  rat
0  344  1189  5.0
1  344  1500  5.0
2  344   814  5.0
</code>```

Body:
Be advised I'm doing this in a Function, and I've already referred a pretty good thread.

Here's the python function, the parameter passed is taken from user

def recommend(uid):
    ds = pd.read_csv("pred_matrix-full_ubcf.csv")
    records = ds.loc[ds['uid'] == uid]
    for recom in records:
        print recom

Data Format:

uid iid     rat
344 1189    5
344 1500    5
344 814     5
736 217     3.3242361285
736 405     3.3238380154
736 866     3.323500531
331 1680    2
331 1665    2
331 36      1.999918585

Referred:
this1,
this2

Unable to get where I'm going wrong, I'm following this1 thread and yet unable to get it.

Body:
To iterate over your rows, use df.iterrows():

In [53]: records = df[df['uid'] == query]

In [54]: for index, row in records.iterrows():
    ...:     print(row['uid'], row['iid'], row['rat'])
    ...:
344.0 1189.0 5.0
344.0 1500.0 5.0
344.0 814.0 5.0

There's two other possible ways to do select your data. You can use boolean indexing:

In [4]: query = 344

In [7]: df[df['uid'] == query]
Out[7]:
   uid   iid  rat
0  344  1189  5.0
1  344  1500  5.0
2  344   814  5.0

You can also use DataFrame.query function:

In [8]: df.query('uid == %d' %query)
Out[8]:
   uid   iid  rat
0  344  1189  5.0
1  344  1500  5.0
2  344   814  5.0


问:
How to calculate form fields values to update hidden field value?
I want to know how to calculate the input values of the following fields

```<code><input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
</code>```

And update the span text and the hidden field value

```<code>TOTAL <span id="amountTotal">0 </span>
<input id="total" type="hidden" name="total" value="">
</code>```

Thanks in advance

答:
```<code><input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
<input type="button" id="calculator" value="Caculate">

$("#calculator").on("click",function (){
var result=0;
var sum_fields=$(".auto-sum");
for(var i=0;i<sum_fields.length;i++){
if(!isNaN(sum_fields[i]) && sum_fields[i]>0){
result += sum_fields[i];
}
}
$("#amountTotal").text(result);
$("#total").val(result);
});
</code>```

Create array for the fields and loop through them
Check if it not a NaN and more than 0 add them to the result then after the loop attach the result to the hidden field and as a span text

Body:
I want to know how to calculate the input values of the following fields

<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">

And update the span text and the hidden field value

TOTAL 0
<input id="total" type="hidden" name="total" value="">

Thanks in advance

Body:
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
<input type="button" id="calculator" value="Caculate">

$("#calculator").on("click",function (){
var result=0;
var sum_fields=$(".auto-sum");
for(var i=0;i<sum_fields.length;i++){
if(!isNaN(sum_fields[i]) && sum_fields[i]>0){
result += sum_fields[i];
}
}
$("#amountTotal").text(result);
$("#total").val(result);
});

Create array for the fields and loop through them
Check if it not a NaN and more than 0 add them to the result then after the loop attach the result to the hidden field and as a span text


问:
sent_tokenize not working properly
I am new to NlTK and I used function sent_tokenize on two strings which is giving different output than expected

1) First string

```<code>sent_tokenize("An uncle is the female sibbling of one's parents. An aunt can also be the wife of an [[uncle]] who is the male sibbling of a parent")
</code>```

output:

["An uncle is the female sibbling of one's parents.",
   'An aunt can also be the wife of an [[uncle]] who is the male sibbling of a parent']

2) Second sting

```<code>sent_tokenize("An uncle is the female [[sibbling]] of one's [[parent]]s. An aunt can also be the wife of an [[uncle]] who is the male sibbling of a parent")
</code>```

output:

["An uncle is the female [[sibbling]] of one's [[parent]]s. An aunt can also be the wife of an [[uncle]] who is the male sibbling of a parent"]

here in second it's not giving two sentences as in first what might be the issue?

(we can use split and delimiter as "." and get the sentences but want to know what is the problem here)

答:
The sent_tokenize function uses  punkt tokenizer that only works on well formed English.

A full stop might not always mean the end of a sentence. For instance: "e.g. or i.e" .

Make sure your sentences are well formed in English before tokenizing them.

In your case, a simple space after 's' or replacing [[parent]]s by parents resolves the issue, but if this doesn't match your requirements, make sure to figure out a way to clean your text first.

You can read more about Punkt tokenizer here, this should help you.

Title: sent_tokenize not working properly

Body:
I am new to NlTK and I used function sent_tokenize on two strings which is giving different output than expected

1) First string

sent_tokenize("An uncle is the female sibbling of one's parents. An aunt can also be the wife of an [[uncle]] who is the male sibbling of a parent")

output:

["An uncle is the female sibbling of one's parents.",
   'An aunt can also be the wife of an [[uncle]] who is the male sibbling of a parent']

2) Second sting

sent_tokenize("An uncle is the female [[sibbling]] of one's [[parent]]s. An aunt can also be the wife of an [[uncle]] who is the male sibbling of a parent")

output:

["An uncle is the female [[sibbling]] of one's [[parent]]s. An aunt can also be the wife of an [[uncle]] who is the male sibbling of a parent"]

here in second it's not giving two sentences as in first what might be the issue?

(we can use split and delimiter as "." and get the sentences but want to know what is the problem here)


问:
How do I make msbuild find .Net assemblies when using a custom task (UsingTask)>
I've built a custom msbuild task based on the old CodePlex project:

http://sqlsrvintegrationsrv.codeplex.com/SourceControl/latest#main/SSISMSBuild/Project/Microsoft.SqlServer.IntegrationServices.Build.csproj

After finally getting this to build in VS 2015 (using the SQL Server 2016 SMSS assemblies) I can use the compiled project DLL to build SSIS projects.

However, I can only get the SSIS project to build (e.g. using a project file such as at https://speaksql.wordpress.com/2013/06/07/a-journey-to-db-deployment-automaton-ssis-build-using-msbuild/) when I copy the assemblies (the custom task DLL and the dependences from SMSS) into a copy of the msbuild bin directory.

Is there any way to direct Msbuild to look in a specific path? I'd rather not add assembles to the GAC if possible.

I've read any web articles and posts but they mostly refer to C# .csproj projects and they refer to setting AssemblySearchPaths and ReferencePath. As this isn't a C# project file I can't use these.

This issue is only occurring on one of my machines (Windows Server 2012). Thing seem to work fine on my Windows 10 machine :(

I can see other people have also seen this issue. E.g.:-
MsBuild does not look in the good directory for custom task's second-level dependencies

Any help would be greatly appreciated!

答:
The <UsingTask> directive's AssemblyFile attribute allows you to specify the full path to the assembly you want to load.

This is usually done relative to the location of the file that wants to use a particular task. e.g. if you build a NuGet package that contains a task, you would usually have a build/{packageId}.targets file and for example an tools/net46/sometasks.dll that contains the needed tasks. The .targets file would then use:

```<code><UsingTask TaskName="MyCustomTask" AssemblyFile="$(MSBuildThisFileDirectory)..\tools\net46\sometasks.dll" />
</code>```

If the task dll also references other assemblies, they need to be located in the same directory as the assembly in order to be discovered.

Body:
The <UsingTask> directive's AssemblyFile attribute allows you to specify the full path to the assembly you want to load.

This is usually done relative to the location of the file that wants to use a particular task. e.g. if you build a NuGet package that contains a task, you would usually have a build/{packageId}.targets file and for example an tools/net46/sometasks.dll that contains the needed tasks. The .targets file would then use:

<UsingTask TaskName="MyCustomTask" AssemblyFile="$(MSBuildThisFileDirectory)..\tools\net46\sometasks.dll" />

If the task dll also references other assemblies, they need to be located in the same directory as the assembly in order to be discovered.


问:
convert array_chunk from php to java
my php code is:</p>

```<code>$splitArray = array_chunk($theArray,ceil(count($theArray) / 2),true);
</code>```

答:
php's array_chunk function splits an array into chunks of the size you specify. You can do this in Java, by using Arrays.copyOfRange and passing in the start and end points. Here is some sample code:

```<code>/**
 * Chunks an array into size large chunks.
 * The last chunk may contain less than size elements.
 * @param <T>
 * @param arr The array to work on
 * @param size The size of each chunk
 * @return a list of arrays
 */
public static <T> List<T[]> chunk(T[] arr, int size) {

    if (size <= 0)
        throw new IllegalArgumentException("Size must be > 0 : " + size);

    List<T[]> result = new ArrayList<T[]>();

    int from = 0;
    int to = size >= arr.length ? arr.length : size;

    while (from < arr.length) {
        T[] subArray = Arrays.copyOfRange(arr, from, to);
        from = to;
        to += size;
        if (to > arr.length) {
            to = arr.length;
        }
        result.add(subArray);
    }
    return result;
}
</code>```

For example, to create chunks of size two:

```<code>String[] arr = {"a", "b", "c", "d", "e"} ;
List<String[]> chunks = chunk(arr,2);
</code>```

Which will return three arrays:

```<code>{a,b}
{c,d}
{e}
</code>```

Title: convert array_chunk from php to java

Body:
my php code is:

$splitArray = array_chunk($theArray,ceil(count($theArray) / 2),true);

Body:
php's array_chunk function splits an array into chunks of the size you specify. You can do this in Java, by using Arrays.copyOfRange and passing in the start and end points. Here is some sample code:

/**
 * Chunks an array into size large chunks.
 * The last chunk may contain less than size elements.
 * @param <T>
 * @param arr The array to work on
 * @param size The size of each chunk
 * @return a list of arrays
 */
public static <T> List<T[]> chunk(T[] arr, int size) {

    if (size <= 0)
        throw new IllegalArgumentException("Size must be > 0 : " + size);

    List<T[]> result = new ArrayList<T[]>();

    int from = 0;
    int to = size >= arr.length ? arr.length : size;

    while (from < arr.length) {
        T[] subArray = Arrays.copyOfRange(arr, from, to);
        from = to;
        to += size;
        if (to > arr.length) {
            to = arr.length;
        }
        result.add(subArray);
    }
    return result;
}

For example, to create chunks of size two:

String[] arr = {"a", "b", "c", "d", "e"} ;
List<String[]> chunks = chunk(arr,2);

Which will return three arrays:

{a,b}
{c,d}
{e}


问:
iOS CAMImagePickerCameraViewController crashes in iOS 10.3.1
My app started to crash after an update to ios 10.3.1 .The crash happens when I attempt to pick a video using the camera. The app works well on older ios versions (9.3.5 and 10.2.1).
The crash log shows that it is the CAMImagePickerCameraViewController that is crashing:

```<code>OS Version:          iPhone OS 10.3.1 (14E304)
Report Version:      104

Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Subtype: KERN_INVALID_ADDRESS at 0x00000019
Termination Signal: Segmentation fault: 11
Termination Reason: Namespace SIGNAL, Code 0xb
Terminating Process: exc handler [0]
Triggered by Thread:  0

Filtered syslog:
None found

Thread 0 name:  Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0   libobjc.A.dylib                 0x1b946f4e realizeClass(objc_class*) + 18
1   libobjc.A.dylib                 0x1b94704c realizeClass(objc_class*) + 272
2   libobjc.A.dylib                 0x1b94abc6 lookUpImpOrForward + 94
3   libobjc.A.dylib                 0x1b94ab64 _class_lookupMethodAndLoadCache3 + 26
4   libobjc.A.dylib                 0x1b9511ae _objc_msgSend_uncached + 14
5   CameraUI                        0x2f8d6896 -[CAMImagePickerCameraViewController _handleCapturedImagePickerVideoAtPath:withEditingMetadata:] + 166
6   CameraUI                        0x2f8d609a -[CAMImagePickerCameraViewController cropOverlayWasOKed:] + 478
7   UIKit                           0x2191e804 -[UIApplication sendAction:to:from:forEvent:] + 76
8   UIKit                           0x2191e798 -[UIControl sendAction:to:forEvent:] + 62
9   UIKit                           0x21908dc8 -[UIControl _sendActionsForEvents:withEvent:] + 478
10  UIKit                           0x2191e0d4 -[UIControl touchesEnded:withEvent:] + 604
11  UIKit                           0x2191dc1e -[UIWindow _sendTouchesForEvent:] + 2094
12  UIKit                           0x21918b5e -[UIWindow sendEvent:] + 2798
13  UIKit                           0x218ea702 -[UIApplication sendEvent:] + 308
14  UIKit                           0x2207dd36 __dispatchPreprocessedEventFromEventQueue + 2254
15  UIKit                           0x220786da __handleEventQueue + 4186
16  UIKit                           0x22078abc __handleHIDEventFetcherDrain + 144
17  CoreFoundation                  0x1c677fdc __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 12
18  CoreFoundation                  0x1c677b04 __CFRunLoopDoSources0 + 424
19  CoreFoundation                  0x1c675f50 __CFRunLoopRun + 1160
20  CoreFoundation                  0x1c5c90ee CFRunLoopRunSpecific + 470
21  CoreFoundation                  0x1c5c8f10 CFRunLoopRunInMode + 104
22  GraphicsServices                0x1dd73b40 GSEventRunModal + 80
23  UIKit                           0x2194de82 UIApplicationMain + 150
24  Stringr Dev                     0x00181604 0x82000 + 1046020
25  libdyld.dylib                   0x1bdb64ea start + 2
</code>```

A similar crash that I see in crashlytics is:

```<code>Crashed: com.apple.main-thread
EXC_BAD_ACCESS KERN_INVALID_ADDRESS 0x00000000c839e660

libobjc.A.dylib realizeClass(objc_class*) + 25

libobjc.A.dylib _objc_msgSend_uncached + 14

CameraUI    -[CAMImagePickerCameraViewController _handleCapturedImagePickerVideoAtPath:withEditingMetadata:]

CameraUI    -[CAMImagePickerCameraViewController cropOverlayWasOKed:]

UIKit   UIApplicationMain + 150
</code>```

Here is an excerpt from my code:

```<code>    /// Presents the video selection/capture dialog
    fileprivate func presentPickerController() {
        // Request authorization to access photo library if not yet granted
        PHPhotoLibrary.requestAuthorization { status in
            guard status == .authorized else {
                self.alert(.notPermittedToSelectVideos)
                return
            }

            // Create the custom asset picker (to get multiple at once)
            let assetsPickerController = DKImagePickerController()
            assetsPickerController.defaultAssetGroup = .smartAlbumVideos
            assetsPickerController.showsCancelButton = true
            assetsPickerController.assetType = .allVideos
            assetsPickerController.didSelectAssets = self.didSelectAssets
            assetsPickerController.didCancel = self.didCancel
            assetsPickerController.disableCaptureWhenSelected = true
            assetsPickerController.createCaptureController = self.createCaptureController

            self.assetsPickerController = assetsPickerController
            DispatchQueue.main.async {
                self.present(assetsPickerController, animated: true) {}
            }
        }
    }

fileprivate func createCaptureController() -> UIViewController? {
        let imagePickerController = UIImagePickerController()
        imagePickerController.sourceType = .camera
        imagePickerController.mediaTypes = [kUTTypeMovie as String]
        imagePickerController.videoQuality = .typeHigh
        imagePickerController.delegate = self
        guard canCaptureVideo() else {
            Logger.info?.message("Attempted to capture video when cannot capture video")
            alert(.cantCaptureVideo)
            return nil
        }

        guard permittedToCaptureVideo() else {
            Logger.info?.message("Attempted to capture video when cannot capture video")
            alert(.notPermittedToCaptureVideo)
            return nil
        }

        guard permittedToCaptureAudio() else {
            Logger.info?.message("Attempted to capture video when cannot capture audio")
            alert(.notPermittedToCaptureAudio)
            return nil
        }

        return imagePickerController
    }
</code>```

The controller that crashes is not part of my application and I cannot touch it. Does anyone have an idea how this problem can be fixed?
What is the purpose of CAMImagePickerCameraViewController? Why does it crash only on ios 10.3.1 and doesn't crash on previous versions?

答:
I have some similar issue here, and i found it's the delegate's problem.

My issue is viewController retain an object, and i set the object's weak delegate to viewController, when viewController dismissed and the object still try to use delegate to do something, crash occurred...

So i think the weak reference goes wrong...no idea why it happens, but you can fix this by add code blow to the viewController dealloc method

- (void)dealloc{
    self.assetsPickerController = nil
}

Body:
My app started to crash after an update to ios 10.3.1 .The crash happens when I attempt to pick a video using the camera. The app works well on older ios versions (9.3.5 and 10.2.1).
The crash log shows that it is the CAMImagePickerCameraViewController that is crashing:

OS Version:          iPhone OS 10.3.1 (14E304)
Report Version:      104

Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Subtype: KERN_INVALID_ADDRESS at 0x00000019
Termination Signal: Segmentation fault: 11
Termination Reason: Namespace SIGNAL, Code 0xb
Terminating Process: exc handler [0]
Triggered by Thread:  0

Filtered syslog:
None found

Thread 0 name:  Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0   libobjc.A.dylib                 0x1b946f4e realizeClass(objc_class*) + 18
1   libobjc.A.dylib                 0x1b94704c realizeClass(objc_class*) + 272
2   libobjc.A.dylib                 0x1b94abc6 lookUpImpOrForward + 94
3   libobjc.A.dylib                 0x1b94ab64 _class_lookupMethodAndLoadCache3 + 26
4   libobjc.A.dylib                 0x1b9511ae _objc_msgSend_uncached + 14
5   CameraUI                        0x2f8d6896 -[CAMImagePickerCameraViewController _handleCapturedImagePickerVideoAtPath:withEditingMetadata:] + 166
6   CameraUI                        0x2f8d609a -[CAMImagePickerCameraViewController cropOverlayWasOKed:] + 478
7   UIKit                           0x2191e804 -[UIApplication sendAction:to:from:forEvent:] + 76
8   UIKit                           0x2191e798 -[UIControl sendAction:to:forEvent:] + 62
9   UIKit                           0x21908dc8 -[UIControl _sendActionsForEvents:withEvent:] + 478
10  UIKit                           0x2191e0d4 -[UIControl touchesEnded:withEvent:] + 604
11  UIKit                           0x2191dc1e -[UIWindow _sendTouchesForEvent:] + 2094
12  UIKit                           0x21918b5e -[UIWindow sendEvent:] + 2798
13  UIKit                           0x218ea702 -[UIApplication sendEvent:] + 308
14  UIKit                           0x2207dd36 __dispatchPreprocessedEventFromEventQueue + 2254
15  UIKit                           0x220786da __handleEventQueue + 4186
16  UIKit                           0x22078abc __handleHIDEventFetcherDrain + 144
17  CoreFoundation                  0x1c677fdc __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 12
18  CoreFoundation                  0x1c677b04 __CFRunLoopDoSources0 + 424
19  CoreFoundation                  0x1c675f50 __CFRunLoopRun + 1160
20  CoreFoundation                  0x1c5c90ee CFRunLoopRunSpecific + 470
21  CoreFoundation                  0x1c5c8f10 CFRunLoopRunInMode + 104
22  GraphicsServices                0x1dd73b40 GSEventRunModal + 80
23  UIKit                           0x2194de82 UIApplicationMain + 150
24  Stringr Dev                     0x00181604 0x82000 + 1046020
25  libdyld.dylib                   0x1bdb64ea start + 2

A similar crash that I see in crashlytics is:

Crashed: com.apple.main-thread
EXC_BAD_ACCESS KERN_INVALID_ADDRESS 0x00000000c839e660

libobjc.A.dylib realizeClass(objc_class*) + 25

libobjc.A.dylib _objc_msgSend_uncached + 14

CameraUI    -[CAMImagePickerCameraViewController _handleCapturedImagePickerVideoAtPath:withEditingMetadata:]

CameraUI    -[CAMImagePickerCameraViewController cropOverlayWasOKed:]

UIKit   UIApplicationMain + 150

Here is an excerpt from my code:

    /// Presents the video selection/capture dialog
    fileprivate func presentPickerController() {
        // Request authorization to access photo library if not yet granted
        PHPhotoLibrary.requestAuthorization { status in
            guard status == .authorized else {
                self.alert(.notPermittedToSelectVideos)
                return
            }

            // Create the custom asset picker (to get multiple at once)
            let assetsPickerController = DKImagePickerController()
            assetsPickerController.defaultAssetGroup = .smartAlbumVideos
            assetsPickerController.showsCancelButton = true
            assetsPickerController.assetType = .allVideos
            assetsPickerController.didSelectAssets = self.didSelectAssets
            assetsPickerController.didCancel = self.didCancel
            assetsPickerController.disableCaptureWhenSelected = true
            assetsPickerController.createCaptureController = self.createCaptureController

            self.assetsPickerController = assetsPickerController
            DispatchQueue.main.async {
                self.present(assetsPickerController, animated: true) {}
            }
        }
    }

fileprivate func createCaptureController() -> UIViewController? {
        let imagePickerController = UIImagePickerController()
        imagePickerController.sourceType = .camera
        imagePickerController.mediaTypes = [kUTTypeMovie as String]
        imagePickerController.videoQuality = .typeHigh
        imagePickerController.delegate = self
        guard canCaptureVideo() else {
            Logger.info?.message("Attempted to capture video when cannot capture video")
            alert(.cantCaptureVideo)
            return nil
        }

        guard permittedToCaptureVideo() else {
            Logger.info?.message("Attempted to capture video when cannot capture video")
            alert(.notPermittedToCaptureVideo)
            return nil
        }

        guard permittedToCaptureAudio() else {
            Logger.info?.message("Attempted to capture video when cannot capture audio")
            alert(.notPermittedToCaptureAudio)
            return nil
        }

        return imagePickerController
    }

The controller that crashes is not part of my application and I cannot touch it. Does anyone have an idea how this problem can be fixed?
What is the purpose of CAMImagePickerCameraViewController? Why does it crash only on ios 10.3.1 and doesn't crash on previous versions?


问:
Why does "1" in awk print the current line?
In this answer,

```<code>awk '$2=="no"{$3="N/A"}1' file
</code>```

was accepted. Note the 1 at the end of the AWK script. In the comments, the author of the answer said

[1 is] a cryptic way to display the current line.

I'm puzzled. How does that work?

答:
The documentation says

In an awk rule, either the pattern or the action can be omitted, but not both. If the pattern is omitted, then the action is performed for every input line. If the action is omitted, the default action is to print all lines that match the pattern.

So, it treats 1 as pattern with no action. The default action is to print the line.

Even if you have a couple of rules, like in

```<code>awk '
    in_net {
        if (/^\s+bindIp:/) {
            print "  bindIp: 0.0.0.0"
            next
        } else if (/^\s*(#.*)?$/) {
            in_net = 0
        }
    }
    /^net:/ {
        in_net = 1
    }
    1
' /etc/mongod.conf
</code>```

You still need 1, since default action is triggered only when encountering rule with no action.

Body:
In this answer,

awk '$2=="no"{$3="N/A"}1' file

was accepted. Note the 1 at the end of the AWK script. In the comments, the author of the answer said

[1 is] a cryptic way to display the current line.

I'm puzzled. How does that work?

Body:
The documentation says

In an awk rule, either the pattern or the action can be omitted, but not both. If the pattern is omitted, then the action is performed for every input line. If the action is omitted, the default action is to print all lines that match the pattern.

So, it treats 1 as pattern with no action. The default action is to print the line.

Even if you have a couple of rules, like in

awk '
    in_net {
        if (/^\s+bindIp:/) {
            print "  bindIp: 0.0.0.0"
            next
        } else if (/^\s*(#.*)?$/) {
            in_net = 0
        }
    }
    /^net:/ {
        in_net = 1
    }
    1
' /etc/mongod.conf

You still need 1, since default action is triggered only when encountering rule with no action.


问:
How can I make my program have a consistent initial current working directory?
When I run the following script in IDLE

```<code>import os
print(os.getcwd())
</code>```

I get output as

```<code>D:\testtool
</code>```

but when I run from cmd prompt, I get

```<code>c:\Python33>python D:\testtool\current_dir.py
c:\Python33
</code>```

How do I get same result which I got using IDLE ?

答:
Using pathlib you can get the folder in which the current file is located. __file__ is the pathname of the file from which the module was loaded.
Ref: docs

```<code>import pathlib

current_dir = pathlib.Path(__file__).parent
current_file = pathlib.Path(__file__)
</code>```

Doc ref: link

Body:
When I run the following script in IDLE

import os
print(os.getcwd())

I get output as

D:\testtool

but when I run from cmd prompt, I get

c:\Python33>python D:\testtool\current_dir.py
c:\Python33

How do I get same result which I got using IDLE ?

Body:
Using pathlib you can get the folder in which the current file is located. __file__ is the pathname of the file from which the module was loaded.
Ref: docs

import pathlib

current_dir = pathlib.Path(__file__).parent
current_file = pathlib.Path(__file__)

Doc ref: link


问:
git: list of all changed files including those in submodules
I would like to get a list of all files, which have changed betweet two commits including those in submodules.

I know I can do this:

```<code>git diff --name-only --diff-filter=ACMR ${revision} HEAD
</code>```

It returns a list of files, including the submodule-path, but not the files within.

Example:
I've updated a submodule. I commited the super-project. Now I want to get a list of all files which have been modified.

Do you know a way to get this done?

答:
July 8,2017

Now to get a diff including that of a submodule, you can use the command -

```<code>git diff --submodule=diff
</code>```

Note - This has been introduced with Git 2.14.0

"git diff --submodule=diff" now recurses into nested submodules.

Body:
I would like to get a list of all files, which have changed betweet two commits including those in submodules.

I know I can do this:

git diff --name-only --diff-filter=ACMR ${revision} HEAD

It returns a list of files, including the submodule-path, but not the files within.

Example:
I've updated a submodule. I commited the super-project. Now I want to get a list of all files which have been modified.

Do you know a way to get this done?

Body:
July 8,2017

Now to get a diff including that of a submodule, you can use the command -

git diff --submodule=diff

Note - This has been introduced with Git 2.14.0

"git diff --submodule=diff" now recurses into nested submodules.


答:
"URL query string "endpoint=//admin/customers/{customerId}/addresses.json" must not have replace block. For dynamic query parameters use @Query."

As it suggests you should use @Query instead of @Path.

```<code>Single<GetCustomerAddressesResponse> getUserAddresses(@Query("customerId") String customerId);
</code>```

You may like to read this in details about @Query annotation https://square.github.io/retrofit/2.x/retrofit/index.html?retrofit2/http/Query.html

Title: Retrofit 2 error URL query string must not have replace block

Body:
I am trying to call a legacy API using Retrofit 2, this is the URL "/api/0.3/v3/?endpoint=/admin/customers/6728382/addresses.json" and this is the interface method

@GET("/api/0.3/v3/?endpoint=/admin/customers/{customerId}/addresses.json")
Single<GetCustomerAddressesResponse> getUserAddresses(@Path("customerId") String customerId);

However I am getting this error,

"URL query string
  "endpoint=//admin/customers/{customerId}/addresses.json" must not have
  replace block. For dynamic query parameters use @Query."

How can I fix this?

Body:
"URL query string "endpoint=//admin/customers/{customerId}/addresses.json" must not have replace block. For dynamic query parameters use @Query."

As it suggests you should use @Query instead of @Path.

Single<GetCustomerAddressesResponse> getUserAddresses(@Query("customerId") String customerId);

You may like to read this in details about @Query annotation https://square.github.io/retrofit/2.x/retrofit/index.html?retrofit2/http/Query.html


问:
print on dot matrix printer in .net
anyone can please tell me the code how to print documents on dot matrix printer in C# windows application.</p>

答:
You can print to dot matrix "graphically", which is built-in in Windows, albeit slower.

But if you only want to print pure text with simple formattings, you need to send escape commands to your dot matrix printer, which is faster than graphical printing.  Different printers has different escape commands.

Here are typical escape commands(for epson): http://www.printfil.com/manualen/c5.htm

This might help:  https://web.archive.org/web/20051212193242/http://sacpcug.org:80/archives/0306/prc0603.html

What I do in VB6 then was to print to Generic / Text Only printer, you open the PRN or LPT1 as a file handle, then print escape commands on the file handle, all escape commands will be redirected to whatever printer is attached to LPT1 or PRN.  You can do the same thing with C#, just open the PRN or LPT1 as a file, then print to it.

To add Generic / Text Only printer, Control Panel > Printers > Add Printer.  On manufacturer, select Generic, then on printers, select Generic / Text only.

You can do the same (printing on Generic / Text Only) for Zebra printers which have their own escape commands for printing bar codes, which is faster than letting Windows print to it graphically.

OwnerDisplayName: Vikram

LastEditorDisplayName: Gamecat

Title: print on dot matrix printer in .net

OwnerDisplayName: Michael Buen