问:
iOS Notification on battery level
I'm developing an iOS app, and I'm looking for a way to make a notification appear when a specific battery level is reached. So my app has to do that while in background.

I found a tutorial with local notification, but the only way to make it appear is to set up a precise date and time.
If you have informations about it, it'll be very sweet.

Thanks for your help !

答:
There is no easy solution for this. You have to run time to time your app in order to achieve this and check if desired battery charge level has reached then post an immediate notification if it's the case.

As a working case you can use background fetch mode to wake app at specific time intervals and do the required battery level check. Be aware that background fetch doesn't provide a consistent time period, you can't wake up app each 15 minutes or 30 minutes, the time is calculated by the system and it's variable, this can make app to "miss" the target level.

You can use also, silent remote notifications which wake your app when delivered, you do the check and present the local notification if needed. This is more reliable than the first case but of course you need to setup a push notification server or use a service which implements this.

Honestly being you won't find a 100% reliable way to do this, so if this is a primary feature of your app think twice before implementing it.

Title: iOS Notification on battery level


来源: stackexchange

问:
Java-syntax for explicitly specifying generic arguments in method calls
What is the syntax for explicitly giving the type parameters for a generic Java method?</p>

答:
The following is not the syntax

```<code><ArgType>genericMethod()
</code>```

It seems the type arguments must come after a dot as in

```<code>SomeClass.<ArgType>genericMethod()
this.<ArgType>genericMethod()
p.<ArgType>genericMethod()
super.<ArgType>genericMethod()
SomeClass.super.<ArgType>genericMethod()
SomeClass.this.<ArgType>genericMethod()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The following is not the syntax

<ArgType>genericMethod()

It seems the type arguments must come after a dot as in

SomeClass.<ArgType>genericMethod()
this.<ArgType>genericMethod()
p.<ArgType>genericMethod()
super.<ArgType>genericMethod()
SomeClass.super.<ArgType>genericMethod()
SomeClass.this.<ArgType>genericMethod()


问:
Scroll window to top of Iframe from iFrame with different domain than parent
Context:

PARENT PAGE loads an IFRAME that contains an app/plugin

PARENT PAGE has different domain than the IFRAME

PARENT PAGE and IFRAME both have installed the iframeResizer plugin -> the iframe has no scroll bar (all content is shown on parent page) - IFRAME is always resized based on its document height

PARENT PAGE html/js cannot be changed, only the IFRAME

Problem:

If the user is at the bottom of the IFRAME, and performs an action, how do you scroll him at the TOP OF THE IFRAME?

Solutions that DO NOT work:

window.scrollTo(0,0); // from iframe

anything with window.parent from iframe (cannot access)

use an anchor at top of iframe body and rewrite window.location

Solutions that do work?

will post one as an answer (it works, but it's weird...and not good for IE)

答:
You can try using document.body.scrollIntoView().

It should work on IE8+ and the other browsers (I only tested it in Chrome, FF and IE11)

See codepen demo here.

```<code>document.body.scrollIntoView();
</code>```

Body:
You can try using document.body.scrollIntoView().

It should work on IE8+ and the other browsers (I only tested it in Chrome, FF and IE11)

See codepen demo here.

document.body.scrollIntoView();


问:
XML formatting for later parsing in c#
I'm using XML to hold some settings, so let's go with the following example:

```<code><PermissionLevels>
    <Permission Name="MyPermission 1" Bases="XXX" />
    <Permission Name="MyPermission 2" Bases="XXX" />
</PermissionLevels>
</code>```

So the XXX is my problem. I will have several base permissions, e.g. "Read, Create, Delete", and I know C# has the .Split method, so I could probably try it with "," as a delimiter. I could also have child nodes to <Permission>.

Is there a correct way to do it? With correct I mean the following: I'm not sure whether I should use LINQ (XDocument) or the regular System.Xml variant (XmlDocument) and I am not sure if some different way might be better to handle.

With .Split I will have to take the node.Attributes["Base"].Value, split it and do a foreach for all elements in the array - maybe LINQ is smarter and can do something differently?

Sorry for my rambling, this is just not my domain. The question actually is: When I have multiple values for one attribute, do I concatenate them with e.g. a ",", or do I do it differently (e.g. with child nodes of the object)?

答:
I would prefer child nodes. Attributes are meant for scalar (single) values.

Also, this way your source code in C# with LINQ will be simple and that's good.

ContentLicense: CC BY-SA 2.5

Title: XML formatting for later parsing in c#

Body:
I'm using XML to hold some settings, so let's go with the following example:

<PermissionLevels>
    <Permission Name="MyPermission 1" Bases="XXX" />
    <Permission Name="MyPermission 2" Bases="XXX" />
</PermissionLevels>

So the XXX is my problem. I will have several base permissions, e.g. "Read, Create, Delete", and I know C# has the .Split method, so I could probably try it with "," as a delimiter. I could also have child nodes to <Permission>.

Is there a correct way to do it? With correct I mean the following: I'm not sure whether I should use LINQ (XDocument) or the regular System.Xml variant (XmlDocument) and I am not sure if some different way might be better to handle.

With .Split I will have to take the node.Attributes["Base"].Value, split it and do a foreach for all elements in the array - maybe LINQ is smarter and can do something differently?

Sorry for my rambling, this is just not my domain. The question actually is: When I have multiple values for one attribute, do I concatenate them with e.g. a ",", or do I do it differently (e.g. with child nodes of the object)?


问:
Equivalent function to stringr::word in stringi package
I went through the stringi package manual to find an equivalent to the function word() in the package stringr, but I could not find it. The reason I am looking for it is because I want to set collation options for my locale  and stringr doesn't give me all the options that stringi does. Is there a function in the stringi package that does the same as the word() function in the stringr package? See the example below, where I want the next three words after the word "José", that is written in different ways. In the stringi package, the function stri_opts_collatorallows to set the argument strength=1 for a permissive collation strength, so all forms of "José" would have been taken into consideration.

```<code>sentencas<-c("josé é um trabalhador responsável","José é um trabalhador
responsável","jose é um trabalhador responsável","Jose é um trabalhador
responsável")

sentencas %>% word(2,sep=coll("jose ",ignore_case=T)) %>% word(1,3)
</code>```

With stringi, I can extract all forms of "José":

```<code>stri_extract_first_coll(sentencas,"jose",strength=1).
</code>```

I would like to do something like this:

```<code>sentencas %>% word(2,sep=coll("jose ",strength=1)) %>% word(1,3)
</code>```

答:
Here another option. Please note, I have introduced some words before your marker word for extraction, i.e., "Josè", since I assume that you will not only have sentences starting with this word. The important functionality is the combination of using stri_locate for detecting the end of your marker word, adding one character position, and using this position with the last character position in your string to be passed to stri_sub. Please note, the function provided is not failsafe, e.g., for cases if there are zero matches, etc.

Please also check below benchmarks for the three solutions proposed so far.

```<code>library(stringi)
library(magrittr)

sentencas<- c("some words josé é um trabalhador responsável"
              ,"only one word José é um trabalhador responsável"
             ,"several words jose é um trabalhador responsável"
             ,"and again some words Jose é um trabalhador responsável")

stri_word <- function(marker, str, words_after_marker) {

  stri_sub(str,  cbind(stri_locate_first_coll(str, marker ,strength=1)[, "end"]+1, nchar(str)) ) %>%
  { gsub( "^\\s+|\\s+$", "", stri_extract_first_regex(., paste0("(\\s\\w+){", words_after_marker[1], ",", words_after_marker[2],"}"))) }

}

stri_word("jose", sentencas, c(1,3) )

#[1] "é um trabalhador" "é um trabalhador" "é um trabalhador" "é um trabalhador"

#Benchmarks
library(microbenchmark)
library(stringr)

stringi_positions <- function() {

  stri_word <- function(marker, str, words_after_marker) {

    stri_sub(str,  cbind(stri_locate_first_coll(str, marker ,strength=1)[, "end"]+1, nchar(str)) ) %>%
    { gsub( "^\\s+|\\s+$", "", stri_extract_first_regex(., paste0("(\\s\\w+){", words_after_marker[1], ",", words_after_marker[2],"}"))) }

  }

  stri_word("jose", sentencas, c(1,3) )

}

stringi_map <- function() {

  sentencas %>%
    map(stri_extract_all_words) %>%
    map(~{
      .x <- flatten_chr(.x)
      map(.x, stri_detect_coll, "jose", ignore.case=TRUE, strength=1L) %>%
        flatten_lgl() %>%
        which() -> pos
      .x[(pos+1):(pos+1+3)]
    })

}

semi_stringi <- function() {

  sentencas %>%
    stri_split_coll("jose ", strength=1, simplify = TRUE) %>%
    .[,2] %>%
    word(1,3)

}

microbenchmark(
  stringi_map(),
  semi_stringi(),
  stringi_positions()
)

# Unit: microseconds
#                        expr      min       lq      mean    median        uq       max neval
# stringi_map()       3498.667 3752.886 4059.0339 4038.0925 4214.3480  7365.635   100
# semi_stringi()      485.543  558.966  805.0216  593.9015  652.7195 15806.567   100
# stringi_positions()  288.958  325.669  456.9946  344.6180  384.4865 10719.428   100
</code>```

Body:
I went through the stringi package manual to find an equivalent to the function word() in the package stringr, but I could not find it. The reason I am looking for it is because I want to set collation options for my locale  and stringr doesn't give me all the options that stringi does. Is there a function in the stringi package that does the same as the word() function in the stringr package? See the example below, where I want the next three words after the word "José", that is written in different ways. In the stringi package, the function stri_opts_collatorallows to set the argument strength=1 for a permissive collation strength, so all forms of "José" would have been taken into consideration.

sentencas<-c("josé é um trabalhador responsável","José é um trabalhador
responsável","jose é um trabalhador responsável","Jose é um trabalhador
responsável")

sentencas %>% word(2,sep=coll("jose ",ignore_case=T)) %>% word(1,3)

With stringi, I can extract all forms of "José":

stri_extract_first_coll(sentencas,"jose",strength=1).

I would like to do something like this:

sentencas %>% word(2,sep=coll("jose ",strength=1)) %>% word(1,3)

Body:
Here another option. Please note, I have introduced some words before your marker word for extraction, i.e., "Josè", since I assume that you will not only have sentences starting with this word. The important functionality is the combination of using stri_locate for detecting the end of your marker word, adding one character position, and using this position with the last character position in your string to be passed to stri_sub. Please note, the function provided is not failsafe, e.g., for cases if there are zero matches, etc.

Please also check below benchmarks for the three solutions proposed so far.

library(stringi)
library(magrittr)

sentencas<- c("some words josé é um trabalhador responsável"
              ,"only one word José é um trabalhador responsável"
             ,"several words jose é um trabalhador responsável"
             ,"and again some words Jose é um trabalhador responsável")

stri_word <- function(marker, str, words_after_marker) {

  stri_sub(str,  cbind(stri_locate_first_coll(str, marker ,strength=1)[, "end"]+1, nchar(str)) ) %>%
  { gsub( "^\\s+|\\s+$", "", stri_extract_first_regex(., paste0("(\\s\\w+){", words_after_marker[1], ",", words_after_marker[2],"}"))) }

}

stri_word("jose", sentencas, c(1,3) )

#[1] "é um trabalhador" "é um trabalhador" "é um trabalhador" "é um trabalhador"

#Benchmarks
library(microbenchmark)
library(stringr)

stringi_positions <- function() {

  stri_word <- function(marker, str, words_after_marker) {

    stri_sub(str,  cbind(stri_locate_first_coll(str, marker ,strength=1)[, "end"]+1, nchar(str)) ) %>%
    { gsub( "^\\s+|\\s+$", "", stri_extract_first_regex(., paste0("(\\s\\w+){", words_after_marker[1], ",", words_after_marker[2],"}"))) }

  }

  stri_word("jose", sentencas, c(1,3) )

}

stringi_map <- function() {

  sentencas %>%
    map(stri_extract_all_words) %>%
    map(~{
      .x <- flatten_chr(.x)
      map(.x, stri_detect_coll, "jose", ignore.case=TRUE, strength=1L) %>%
        flatten_lgl() %>%
        which() -> pos
      .x[(pos+1):(pos+1+3)]
    })

}

semi_stringi <- function() {

  sentencas %>%
    stri_split_coll("jose ", strength=1, simplify = TRUE) %>%
    .[,2] %>%
    word(1,3)

}

microbenchmark(
  stringi_map(),
  semi_stringi(),
  stringi_positions()
)

# Unit: microseconds
#                        expr      min       lq      mean    median        uq       max neval
# stringi_map()       3498.667 3752.886 4059.0339 4038.0925 4214.3480  7365.635   100
# semi_stringi()      485.543  558.966  805.0216  593.9015  652.7195 15806.567   100
# stringi_positions()  288.958  325.669  456.9946  344.6180  384.4865 10719.428   100


问:
How do you create a list of Observables in RxJava?
I've a API which gives me a list of ids. I need to use these ids to make another network request to get their details of individual items. Once I get all the details I need to put them in a list.

So here is an example. Make a network request, get a list of ids say

1, 2, 3, 4, 5.

Now I need to make 5 separate requests for these 5 ids.

And then once I get the response of all, I need to create a list which is used to populate the RecyclerView.

Let me know if further information are needed. I'm new to Reactive programming.

答:
If you want to receive only 1 emission that contains a List: use Observable.just(1, 2, 3, 4, 5);

If you want to receive 5 emissions that contains a single number for each: use Observable.from(1, 2, 3, 4, 5);


问:
AutoComplete textview not showing the list
I am using an AutoCompleteTextView in which when the user types a character the words starting with that character will be shown up.But in my case the list is not showing up.

XML

```<code><?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:layout_width="match_parent"
            android:orientation="vertical"
            android:layout_height="match_parent">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:layout_marginRight="15dp"
                android:layout_marginLeft="15dp"
                android:layout_marginTop="50dp">

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/iv_image"
                    android:layout_gravity="center_horizontal"
                    android:adjustViewBounds="true" />

                <Button
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="30dp"
                    android:text="Choose File"
                    android:id="@+id/bt_choose_file"
                    android:layout_gravity="center_horizontal" />

                <EditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/et_Title"
                    android:layout_marginTop="30dp"
                    android:hint="File Name"
                    android:layout_gravity="center_horizontal"
                    style="@style/EditText" />

                <AutoCompleteTextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="30dp"
                    android:hint="Document Type"
                    android:imeOptions="actionDone"
                    style="@style/EditText"
                    android:id="@+id/ac_document_type"
                    android:layout_gravity="center_horizontal" />

            </LinearLayout>

            <LinearLayout
                android:orientation="horizontal"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="15dp"
                android:layout_marginRight="15dp"
                android:layout_marginTop="30dp">

                <Button
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Upload"
                    android:textColor="#fff"
                    android:textStyle="bold"
                    android:textSize="25sp"
                    android:id="@+id/bt_upload"
                    android:background="@drawable/button_1"
                    android:layout_marginRight="5dp"
                    android:layout_weight="1" />

                <Button
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Cancel"
                    android:textColor="#fff"
                    android:textStyle="bold"
                    android:textSize="25sp"
                    android:id="@+id/bt_cancel"
                    android:background="@drawable/button_1"
                    android:layout_marginLeft="5dp"
                    android:layout_weight="1" />
            </LinearLayout>
        </LinearLayout>
    </ScrollView>

</LinearLayout>
</code>```

Code

```<code>public class UploadDocument extends MasterFragment implements View.OnClickListener {

    private Button btChooseDoc, btUpload, btCancel;
    private EditText etTitle;
    private AutoCompleteTextView acDocumentType;
    private String[] chooseDocumentArray;
    private String userSelection = "";
    ImageView image;
    private Intent intent;
    Bitmap camera, galleryImage;
    Uri galleryUri;
    private String[] documentsArray;
    private ArrayAdapter<String> documentArrayAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.upload_docs_fragment, null, false);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initialize();
    }

    private void initialize() {

        btChooseDoc = (Button) getActivity().findViewById(R.id.bt_choose_file);
        acDocumentType = (AutoCompleteTextView) getActivity().findViewById(R.id.ac_document_type);
        btUpload = (Button) getActivity().findViewById(R.id.bt_upload);
        btCancel = (Button) getActivity().findViewById(R.id.bt_cancel);
        image = (ImageView) getActivity().findViewById(R.id.iv_image);
        etTitle = (EditText) getActivity().findViewById(R.id.et_Title);
        btChooseDoc.setOnClickListener(this);
        btUpload.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

        setUp();

        switch (view.getId()) {

            case R.id.bt_choose_file:

                displayPopup(getActivity(), "Choose File", chooseDocumentArray, btChooseDoc, false, new GetNamePosition() {
                    @Override
                    public void getName(String name) {
                        userSelection = name;
                        if (userSelection.equals("Gallery")) {
                            intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                            startActivityForResult(intent, 0);
                            btChooseDoc.setText("Choose File");
                        }

                        if (userSelection.equals("Camera")) {
                            intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            startActivityForResult(intent, 1);
                            btChooseDoc.setText("Choose File");
                        }

                        if (userSelection.equals("Other")) {
                            intent = new Intent(Intent.ACTION_GET_CONTENT);
                            intent.setType("file/*");
                            startActivityForResult(intent, 2);
                            btChooseDoc.setText("Choose File");
                        }
                    }

                    @Override
                    public void getPosition(int position) {

                    }
                });
                break;
            case R.id.bt_upload:

                if (isConnected(getActivity())) {

                } else {
                    Crouton.makeText(getActivity(), "Internet Connection not available", Style.ALERT).show();
                }

        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

//        Bitmap camera;
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();

        if (requestCode == 1 && resultCode == getActivity().RESULT_OK) {

            camera = (Bitmap) data.getExtras().get("data");
            camera.compress(Bitmap.CompressFormat.JPEG, 60, bytes);
            galleryImage = Bitmap.createScaledBitmap(galleryImage, 150, 150, false);
            image.setImageBitmap(camera);

        }

        if (requestCode == 0 && resultCode == getActivity().RESULT_OK) {

            galleryUri = data.getData();
            try {
                galleryImage = decodeUri(getActivity(), galleryUri);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            galleryImage.compress(Bitmap.CompressFormat.JPEG, 50, bytes);
            galleryImage = Bitmap.createScaledBitmap(galleryImage, 150, 150, false);
            image.setImageBitmap(galleryImage);

        }

    }

    private void setUp() {

        chooseDocumentArray = getResources().getStringArray(R.array.Choose_Document);

        // for documents

        documentsArray = getResources().getStringArray(R.array.Document);
        Arrays.sort(documentsArray);
        documentArrayAdapter = new ArrayAdapter<String>(getActivity(), R.layout.textview, documentsArray);
        acDocumentType.setAdapter(documentArrayAdapter);

    }

}
</code>```

I have set the arrayAdapter properly but still i am not getting the list

答:
Call autoTextView.setAdapter() once you get all data for array instead of calling adapter.notifyDataSetChanged()
If your array items is changed again, call autoTextView.setAdapter()

Body:
I am using an AutoCompleteTextView in which when the user types a character the words starting with that character will be shown up.But in my case the list is not showing up.

XML

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:layout_width="match_parent"
            android:orientation="vertical"
            android:layout_height="match_parent">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:layout_marginRight="15dp"
                android:layout_marginLeft="15dp"
                android:layout_marginTop="50dp">

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/iv_image"
                    android:layout_gravity="center_horizontal"
                    android:adjustViewBounds="true" />

                <Button
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="30dp"
                    android:text="Choose File"
                    android:id="@+id/bt_choose_file"
                    android:layout_gravity="center_horizontal" />

                <EditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/et_Title"
                    android:layout_marginTop="30dp"
                    android:hint="File Name"
                    android:layout_gravity="center_horizontal"
                    style="@style/EditText" />

                <AutoCompleteTextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="30dp"
                    android:hint="Document Type"
                    android:imeOptions="actionDone"
                    style="@style/EditText"
                    android:id="@+id/ac_document_type"
                    android:layout_gravity="center_horizontal" />

            </LinearLayout>

            <LinearLayout
                android:orientation="horizontal"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="15dp"
                android:layout_marginRight="15dp"
                android:layout_marginTop="30dp">

                <Button
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Upload"
                    android:textColor="#fff"
                    android:textStyle="bold"
                    android:textSize="25sp"
                    android:id="@+id/bt_upload"
                    android:background="@drawable/button_1"
                    android:layout_marginRight="5dp"
                    android:layout_weight="1" />

                <Button
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Cancel"
                    android:textColor="#fff"
                    android:textStyle="bold"
                    android:textSize="25sp"
                    android:id="@+id/bt_cancel"
                    android:background="@drawable/button_1"
                    android:layout_marginLeft="5dp"
                    android:layout_weight="1" />
            </LinearLayout>
        </LinearLayout>
    </ScrollView>

</LinearLayout>

Code

public class UploadDocument extends MasterFragment implements View.OnClickListener {

    private Button btChooseDoc, btUpload, btCancel;
    private EditText etTitle;
    private AutoCompleteTextView acDocumentType;
    private String[] chooseDocumentArray;
    private String userSelection = "";
    ImageView image;
    private Intent intent;
    Bitmap camera, galleryImage;
    Uri galleryUri;
    private String[] documentsArray;
    private ArrayAdapter<String> documentArrayAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.upload_docs_fragment, null, false);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initialize();
    }

    private void initialize() {

        btChooseDoc = (Button) getActivity().findViewById(R.id.bt_choose_file);
        acDocumentType = (AutoCompleteTextView) getActivity().findViewById(R.id.ac_document_type);
        btUpload = (Button) getActivity().findViewById(R.id.bt_upload);
        btCancel = (Button) getActivity().findViewById(R.id.bt_cancel);
        image = (ImageView) getActivity().findViewById(R.id.iv_image);
        etTitle = (EditText) getActivity().findViewById(R.id.et_Title);
        btChooseDoc.setOnClickListener(this);
        btUpload.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

        setUp();

        switch (view.getId()) {

            case R.id.bt_choose_file:

                displayPopup(getActivity(), "Choose File", chooseDocumentArray, btChooseDoc, false, new GetNamePosition() {
                    @Override
                    public void getName(String name) {
                        userSelection = name;
                        if (userSelection.equals("Gallery")) {
                            intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                            startActivityForResult(intent, 0);
                            btChooseDoc.setText("Choose File");
                        }

                        if (userSelection.equals("Camera")) {
                            intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            startActivityForResult(intent, 1);
                            btChooseDoc.setText("Choose File");
                        }

                        if (userSelection.equals("Other")) {
                            intent = new Intent(Intent.ACTION_GET_CONTENT);
                            intent.setType("file/*");
                            startActivityForResult(intent, 2);
                            btChooseDoc.setText("Choose File");
                        }
                    }

                    @Override
                    public void getPosition(int position) {

                    }
                });
                break;
            case R.id.bt_upload:

                if (isConnected(getActivity())) {

                } else {
                    Crouton.makeText(getActivity(), "Internet Connection not available", Style.ALERT).show();
                }

        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

//        Bitmap camera;
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();

        if (requestCode == 1 && resultCode == getActivity().RESULT_OK) {

            camera = (Bitmap) data.getExtras().get("data");
            camera.compress(Bitmap.CompressFormat.JPEG, 60, bytes);
            galleryImage = Bitmap.createScaledBitmap(galleryImage, 150, 150, false);
            image.setImageBitmap(camera);

        }

        if (requestCode == 0 && resultCode == getActivity().RESULT_OK) {

            galleryUri = data.getData();
            try {
                galleryImage = decodeUri(getActivity(), galleryUri);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            galleryImage.compress(Bitmap.CompressFormat.JPEG, 50, bytes);
            galleryImage = Bitmap.createScaledBitmap(galleryImage, 150, 150, false);
            image.setImageBitmap(galleryImage);

        }

    }

    private void setUp() {

        chooseDocumentArray = getResources().getStringArray(R.array.Choose_Document);

        // for documents

        documentsArray = getResources().getStringArray(R.array.Document);
        Arrays.sort(documentsArray);
        documentArrayAdapter = new ArrayAdapter<String>(getActivity(), R.layout.textview, documentsArray);
        acDocumentType.setAdapter(documentArrayAdapter);

    }

}

I have set the arrayAdapter properly but still i am not getting the list


问:
node.js returning only specific data from a http request
I'm attempting to use the Destiny 2 API in a discord chatbot I have been writing. Right now I just want it to return my player id by sending a request to the address designated in the API. I can successfully do this but it returns more information than I need. How do I just return the 'membershipId'?

The body of this request returns:

```<code>{
    "Response": [
        {
            "membershipType": 4,
            "membershipId": "4611686018470641209",
            "displayName": "LazyBrain#2918"
        }
    ],
    "ErrorCode": 1,
    "ThrottleSeconds": 0,
    "ErrorStatus": "Success",
    "Message": "Ok",
    "MessageData": {}
}
</code>```

Code:

```<code>    case 'stats':
    let options = {
        url: HOST + '/SearchDestinyPlayer/4/LazyBrain%232918/',
        headers: {
            'X-API-Key': config.key
        }
    };

    request(options, function (err, res, body) {
        let json = JSON.stringify(JSON.parse(body)['Response']);
        console.log(json);
    });
</code>```

But with the above code I have narrowed it down to:

```<code>[
    {
        "membershipType": 4,
        "membershipId": "4611686018470641209",
        "displayName": "LazyBrain#2918"
    }
]
</code>```

I'm not entirely sure if I'm going about this the right way though.

答:
Use body-parser and use dot notation to access membershipId.

For example:

```<code>req.body.membershipId
</code>```

I am unsure of the entirety of your code so the above is unlikely to work first try, you need the request object which should be given on a GET request.

Based on your question it looks like you have the membershipId inside an array, so use json[0].membershipId but do not use stringify on json beforehand, or use JSON.parse(body)["Response"][0].membershipId

Body:
I'm attempting to use the Destiny 2 API in a discord chatbot I have been writing. Right now I just want it to return my player id by sending a request to the address designated in the API. I can successfully do this but it returns more information than I need. How do I just return the 'membershipId'?

The body of this request returns:

{
    "Response": [
        {
            "membershipType": 4,
            "membershipId": "4611686018470641209",
            "displayName": "LazyBrain#2918"
        }
    ],
    "ErrorCode": 1,
    "ThrottleSeconds": 0,
    "ErrorStatus": "Success",
    "Message": "Ok",
    "MessageData": {}
}

Code:

    case 'stats':
    let options = {
        url: HOST + '/SearchDestinyPlayer/4/LazyBrain%232918/',
        headers: {
            'X-API-Key': config.key
        }
    };

    request(options, function (err, res, body) {
        let json = JSON.stringify(JSON.parse(body)['Response']);
        console.log(json);
    });

But with the above code I have narrowed it down to:

[
    {
        "membershipType": 4,
        "membershipId": "4611686018470641209",
        "displayName": "LazyBrain#2918"
    }
]

I'm not entirely sure if I'm going about this the right way though.

Body:
Use body-parser and use dot notation to access membershipId.

For example:

req.body.membershipId

I am unsure of the entirety of your code so the above is unlikely to work first try, you need the request object which should be given on a GET request.

Based on your question it looks like you have the membershipId inside an array, so use json[0].membershipId but do not use stringify on json beforehand, or use JSON.parse(body)["Response"][0].membershipId


问:
Java float vs double precision
```<code>public class MyClass {
    public static void main(String args[]) {
        float x=2.0f;
        float y=1.1f;

        System.out.println("Float = " + (x - y));

        double a=2.0d;
        double b=1.1d;

        System.out.println("Double = " + (a - b));
    }
}
</code>```

Answer:

```<code>Float = 0.9
Double = 0.8999999999999999
</code>```

I understand if I want better precision, I should have used BigDecimal, but why float (which is 32 bit with lesser precision compare to double) doesn't encounter the rounding issue?

答:
I modified the code to print the exact value of each result immediately after the rounded value:

```<code>Float = 0.9
0.89999997615814208984375
Double = 0.8999999999999999
0.899999999999999911182158029987476766109466552734375
</code>```

The double result is much, much closer to 0.9 than the float result. Those are the values that would have been used in any additional calculations.

The difference in the printout is a consequence of the Float and Double toString methods. Each aims to produce the shortest result that, on conversion back to the corresponding type, would produce the original value. 0.9 would convert to 0.89999997615814208984375 on float parsing. It would convert to 0.90000000000000002220446049250313080847263336181640625 on double parsing. It takes more digits to uniquely identify a double than a float.

Title: Java float vs double precision

Body:
public class MyClass {
    public static void main(String args[]) {
        float x=2.0f;
        float y=1.1f;

        System.out.println("Float = " + (x - y));

        double a=2.0d;
        double b=1.1d;

        System.out.println("Double = " + (a - b));
    }
}

Answer:

Float = 0.9
Double = 0.8999999999999999

I understand if I want better precision, I should have used BigDecimal, but why float (which is 32 bit with lesser precision compare to double) doesn't encounter the rounding issue?

Body:
I modified the code to print the exact value of each result immediately after the rounded value:

Float = 0.9
0.89999997615814208984375
Double = 0.8999999999999999
0.899999999999999911182158029987476766109466552734375

The double result is much, much closer to 0.9 than the float result. Those are the values that would have been used in any additional calculations.

The difference in the printout is a consequence of the Float and Double toString methods. Each aims to produce the shortest result that, on conversion back to the corresponding type, would produce the original value. 0.9 would convert to 0.89999997615814208984375 on float parsing. It would convert to 0.90000000000000002220446049250313080847263336181640625 on double parsing. It takes more digits to uniquely identify a double than a float.


问:
How to dispatch jobs to different queue providers in Laravel
In my api I am using Redis for caching dispatched jobs from my controllers: This is how my controller looks

```<code>class FormSubmissionsController extends Controller
{
    /**
     * @param StoreRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(StoreRequest $request, FormSubmission $formSubmission)
    {

        JobStore::dispatch($formSubmission, $request->get('tracking_code'), $request->get('form'));

        return response()->json([
            'id' => $formSubmission->id
        ]);
    }
}
</code>```

All is working, and the only change I did to use redis it was some config vars in dot env file. My question:

In another controller I want to use some of Amazon SQSservices for queued jobs, any idea how to config queue and how should I dispatch each job to particular queue handler ?

答:
You can pick a connection that should be used to dispatch a job with onConnection() method:

```<code>JobStore::dispatch()->onConnection('sqs');
</code>```

See https://laravel.com/docs/5.5/queues#dispatching-jobs for more details.

Body:
In my api I am using Redis for caching dispatched jobs from my controllers: This is how my controller looks

class FormSubmissionsController extends Controller
{
    /**
     * @param StoreRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(StoreRequest $request, FormSubmission $formSubmission)
    {

        JobStore::dispatch($formSubmission, $request->get('tracking_code'), $request->get('form'));

        return response()->json([
            'id' => $formSubmission->id
        ]);
    }
}

All is working, and the only change I did to use redis it was some config vars in dot env file. My question:

In another controller I want to use some of Amazon SQSservices for queued jobs, any idea how to config queue and how should I dispatch each job to particular queue handler ?

Body:
You can pick a connection that should be used to dispatch a job with onConnection() method:

JobStore::dispatch()->onConnection('sqs');

See https://laravel.com/docs/5.5/queues#dispatching-jobs for more details.


问:
Common solution for Xamarin.UWP and Xamarin.Mac
I have a quick question, it would be great if anyone can clear it out. I wanted to develop a cross-platform application for Window OS and Mac OS.

I search it out a lot and found that we can create Window app with UWP and Mac OS app with the help of Xamarin.Mac but in that case, we are having a different solution for both Windows and Mac platform. We need a common solution for both the platform.

I will really appreciate if anyone can clarify how we need to proceed with the Cross-Platform development of Windows and Mac.

答:
The idea with xamarin is to separate UI and non UI code. You can share the non UI code between the UWP and Xamarin.Mac

Another approach is to use Xamarin.Forms which abstracts the UI code to be cross platform. The Xamarin.Forms implementation for Xamarin.Mac is stil in preview though


问:
Sql query to add Zero between string with character and digits
What will be the generic sql query to update id by adding zeros in id. containing alphabets as well as numbers? In between the character and digits 00 needs to be padded e.g QTX23675  should turn into QTX0023675

```<code>UPDATE Table
    SET QID = 'QTX0023675'
    WHERE QID='QTX23675';
</code>```

There are many records to update and i found query with leading zeros.
Tried with spliting the string.

答:
In most databases, you could do something like this:

```<code>UPDATE Table
    SET QID = CONCAT(LEFT('QTX0023675', 3), '00', RIGHT('QTX0023675', 5))
    WHERE QID LIKE '________';
</code>```

In any given database, there might be somewhat simpler methods, but the idea is the same.

Body:
What will be the generic sql query to update id by adding zeros in id. containing alphabets as well as numbers? In between the character and digits 00 needs to be padded e.g QTX23675  should turn into QTX0023675

UPDATE Table
    SET QID = 'QTX0023675'
    WHERE QID='QTX23675';

There are many records to update and i found query with leading zeros.
Tried with spliting the string.

Body:
In most databases, you could do something like this:

UPDATE Table
    SET QID = CONCAT(LEFT('QTX0023675', 3), '00', RIGHT('QTX0023675', 5))
    WHERE QID LIKE '________';

In any given database, there might be somewhat simpler methods, but the idea is the same.


问:
Woocommerce Storefront theme customise product pages and category pages
I'm trying to create specific templates for both the category pages and individual product pages. It would be good to lay out various attributes on the pages according to where I would like them. However, beyond the endless 'hooks' that storefront uses... I can't find the places to modify actual code.

Does anyone know how to do this? I don't want to be modifying CSS specifically - I want to create new templates.

Thanks.

答:
If you want to create new templates, you should override multiple files from plugins/woocommerce/templates to themes/strefront_or_child/woocommerce, this is the documentation article, check loop/ and global/ folders too.

Hope this helps a little.


问:
Button is not redirecting me to the next "page"
I am currently making an app. I would like to redirect the user to the next page but it is mainly just pressing the button and you would be brought over to the next set of details. It should still remain on the same html link. However, when I press the button, nothing seems to be working.

```<code><div data-role="page" id="mainpage">
    <h1>
        <b>Converter App</b>
    </h1>
</div>
<div class="app">
    <a href="#convertingpage" class="ui-btn">Convert</a>
    <div data-role="page" id="convertingpage">
        <p> stuff on my second page</p>
    </div>
</div>
</code>```

I am sorry if this sounds rather complex or hard to comprehend.

答:
If you want to stay on the same html page, but be redirected to a different section of the page, as you appear to be trying to do in your example, you want to be using an anchor.

In your example,

```<code><div data-role="page" id="convertingpage">
    <p> stuff on my second page</p>
</div>
</code>```

you tried to do this with the id of you div, but to make an anchor you need to use an  tag.

Here's how I would do it, trying to stay as similar to your page a possible.

```<code><div data-role="page" id="mainpage">
    <h1>
        <b>Converter App</b>
    </h1>
</div>
<div class="app">
    <a href="#convertingpage" class="ui-btn">Convert</a>
    <div data-role="page">
    <a id="convertingpage"></a>
        <p> stuff on my second page</p>
    </div>
</div>
</code>```

Note the  anchor that the link redirects to. Also, I removed the id attribute from your second page div, so if you need it for styling, you should replace it.

Body:
I am currently making an app. I would like to redirect the user to the next page but it is mainly just pressing the button and you would be brought over to the next set of details. It should still remain on the same html link. However, when I press the button, nothing seems to be working.

        Converter App

    Convert

 stuff on my second page

I am sorry if this sounds rather complex or hard to comprehend.

Body:
If you want to stay on the same html page, but be redirected to a different section of the page, as you appear to be trying to do in your example, you want to be using an anchor.

In your example,

<div data-role="page" id="convertingpage">
    <p> stuff on my second page</p>
</div>

you tried to do this with the id of you div, but to make an anchor you need to use an <a> tag.

Here's how I would do it, trying to stay as similar to your page a possible.

<div data-role="page" id="mainpage">
    <h1>
        <b>Converter App</b>
    </h1>
</div>
<div class="app">
    <a href="#convertingpage" class="ui-btn">Convert</a>
    <div data-role="page">
    <a id="convertingpage"></a>
        <p> stuff on my second page</p>
    </div>
</div>

Note the <a id="convertingpage"></a> anchor that the link redirects to. Also, I removed the id attribute from your second page div, so if you need it for styling, you should replace it.


问:
Improve an if statement chain
```<code>if (firstPositionCpc && (firstPosition > 0 && firstPositionCpc <= maxCPC)) {
    var newCPC = firstPositionCpc;
} else if (topOfPageCpc && (topOfPageCpc > 0 && topOfPageCpc <= maxCPC)) {
    var newCPC = topOfPageCpc;
} else if (firstPageCpc && (firstPageCpc > 0 && firstPageCpc <= maxCPC )) {
    var newCPC = firstPageCpc;
} else {
    var newCPC = minCPC;
}
</code>```

Here is some wrong scenario

```<code>KeywordIdReport :197857118477
campaignName :BP 2015 QC (FR)
maxCPC : 3.00
OldCPC :0.46
firstPositionCpc : --
topOfPageCpc : 0.46
firstPageCpc : 0.05
NewCPC : --
</code>```

Here NewCPC needs to be a number. Hence, firstPositionCpc, topOfPageCpc and firstPageCpc need to exist and be a number.

```<code>KeywordIdReport :97483945
campaignName :BP 2015 QC (FR)
maxCPC: 3.00
OldCPC :1.96
firstPositionCpc : 4.28
topOfPageCpc : 1.68
firstPageCpc : 0.85
NewCPC : 4.28
</code>```

Here NewCPC needs to be lower or equal to maxCPC. Normally, the answer should be 1.68 instead of 4.28 for NewCPC.

How could I fix the chain of if statement so that it will fix the wrong scenarios?

UPDATE

Now after improvement, how could I say that the type of firstPositionCpc, topOfPageCpc and firstPageCpc exist and need to be a number?

答:
Hence, firstPositionCpc, topOfPageCpc and firstPageCpc need to exist and be a number.

The above doesn't really make sense given that you have 3 comparisons, so my answer will lean on the assumption that you want firstPosition > 0.

So I need to check if a value type is number and if that number is in some bound so taking your first if statement:

```<code>if (firstPositionCpc && (firstPosition > 0 && firstPositionCpc <= maxCPC)) {
    var newCPC = firstPositionCpc;
}
</code>```

I would change it to the following:

if(typeof(firstPositionCpc) == 'number' && firstPositionCpc <= maxCPC && firstPosition > 0){....}

typeof() reads the type of the parameter and returns a string indicating the value.

See here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

Title: Improve an if statement chain

Body:
if (firstPositionCpc && (firstPosition > 0 && firstPositionCpc <= maxCPC)) {
    var newCPC = firstPositionCpc;
} else if (topOfPageCpc && (topOfPageCpc > 0 && topOfPageCpc <= maxCPC)) {
    var newCPC = topOfPageCpc;
} else if (firstPageCpc && (firstPageCpc > 0 && firstPageCpc <= maxCPC )) {
    var newCPC = firstPageCpc;
} else {
    var newCPC = minCPC;
}

Here is some wrong scenario

KeywordIdReport :197857118477
campaignName :BP 2015 QC (FR)
maxCPC : 3.00
OldCPC :0.46
firstPositionCpc : --
topOfPageCpc : 0.46
firstPageCpc : 0.05
NewCPC : --

Here NewCPC needs to be a number. Hence, firstPositionCpc, topOfPageCpc and firstPageCpc need to exist and be a number.

KeywordIdReport :97483945
campaignName :BP 2015 QC (FR)
maxCPC: 3.00
OldCPC :1.96
firstPositionCpc : 4.28
topOfPageCpc : 1.68
firstPageCpc : 0.85
NewCPC : 4.28

Here NewCPC needs to be lower or equal to maxCPC. Normally, the answer should be 1.68 instead of 4.28 for NewCPC.

How could I fix the chain of if statement so that it will fix the wrong scenarios?

UPDATE

Now after improvement, how could I say that the type of firstPositionCpc, topOfPageCpc and firstPageCpc exist and need to be a number?

Body:
Hence, firstPositionCpc, topOfPageCpc and firstPageCpc need to exist and be a number.

The above doesn't really make sense given that you have 3 comparisons, so my answer will lean on the assumption that you want firstPosition > 0.

So I need to check if a value type is number and if that number is in some bound so taking your first if statement:

if (firstPositionCpc && (firstPosition > 0 && firstPositionCpc <= maxCPC)) {
    var newCPC = firstPositionCpc;
}

I would change it to the following:

if(typeof(firstPositionCpc) == 'number' && firstPositionCpc <= maxCPC && firstPosition > 0){....}

typeof() reads the type of the parameter and returns a string indicating the value.

See here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof


问:
Entity Framework, Code First, Layered application
I have 3 projects WinformApp, LogicProject, DataAccess. Where should I add entity framework NuGet package and what should be in App.config in every project? I want to have a connection to MSSQLserver on the same computer.

Simplified project:
https://github.com/McThrok/StackOverflowQuestion

答: You should reference Entity Framework in only your Data Access Layer, as it is data access specific. This means if you wish to change technology later down the road and not use EF anymore, your changes are restricted to only this layer and the rest of your code performs exactly the same. </p>


问:
FTP4j fails to use FTPES (TLS session of data connection has not resumed or the session does not match the control connection)
I am trying to use ftp4j lib to get list of files from FileZilla FTP servcer with TLS.

```<code>import it.sauronsoftware.ftp4j.FTPClient;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.Arrays;

public class FTP {

    public static void main(String args[]) throws Exception {
        System.setProperty("http.protocols", "TLSv1,TLSv1.1,TLSv1.2");
        //tried to avoid closing connection during the handshake

        //load and set certificate
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream("mykeystore.jks"), "root12".toCharArray());

        FTPClient client = new FTPClient();

        SSLContext sslContext = null;
        try {
            javax.net.ssl.TrustManagerFactory tmf = javax.net.ssl.TrustManagerFactory
                    .getInstance(javax.net.ssl.KeyManagerFactory
                            .getDefaultAlgorithm());
            tmf.init(keyStore);
            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, tmf.getTrustManagers(), new SecureRandom());
        } catch (Exception e) {
            e.printStackTrace();
        }

        SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

        client.setSSLSocketFactory(sslSocketFactory);
        client.setSecurity(FTPClient.SECURITY_FTPES);

        client.setCharset("UTF-8");
        client.setPassive(true);
        String[] arg = client.connect("localhost", 21);
        System.out.println(Arrays.toString(arg));

        client.login("admin", "pass"); //OK
        client.noop(); // aka Ping is OK
        String s = client.currentDirectory(); //OK
        client.changeDirectory("/"); //OK
        String[] files = client.listNames(); //Exception here
        System.out.println(Arrays.toString(files));
        client.disconnect(true);
    }
}
</code>```

I got an exception

Exception in thread "main" it.sauronsoftware.ftp4j.FTPException
  [code=450, message= TLS session of data connection has not resumed or
  the session does not match the control connection]    at
  it.sauronsoftware.ftp4j.FTPClient.listNames(FTPClient.java:2407)  at
  FTP.main(FTP.java:49)

I tried to use active mode, but it doesn't help also (failed after ping command)

Exception in thread "main" it.sauronsoftware.ftp4j.FTPException
  [code=421, message= Rejected command, requested IP address does not
  match control connection IP.]

Could you please answer me what I've done wrong or does ftp4j library actually support FTPES & TLS?

Screenshots with FileZilla server TLS configuration:

答: Try to remove this checkbox it helped me.

Body:
I am trying to use ftp4j lib to get list of files from FileZilla FTP servcer with TLS.

import it.sauronsoftware.ftp4j.FTPClient;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.Arrays;

public class FTP {

    public static void main(String args[]) throws Exception {
        System.setProperty("http.protocols", "TLSv1,TLSv1.1,TLSv1.2");
        //tried to avoid closing connection during the handshake

        //load and set certificate
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream("mykeystore.jks"), "root12".toCharArray());

        FTPClient client = new FTPClient();

        SSLContext sslContext = null;
        try {
            javax.net.ssl.TrustManagerFactory tmf = javax.net.ssl.TrustManagerFactory
                    .getInstance(javax.net.ssl.KeyManagerFactory
                            .getDefaultAlgorithm());
            tmf.init(keyStore);
            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, tmf.getTrustManagers(), new SecureRandom());
        } catch (Exception e) {
            e.printStackTrace();
        }

        SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

        client.setSSLSocketFactory(sslSocketFactory);
        client.setSecurity(FTPClient.SECURITY_FTPES);

        client.setCharset("UTF-8");
        client.setPassive(true);
        String[] arg = client.connect("localhost", 21);
        System.out.println(Arrays.toString(arg));

        client.login("admin", "pass"); //OK
        client.noop(); // aka Ping is OK
        String s = client.currentDirectory(); //OK
        client.changeDirectory("/"); //OK
        String[] files = client.listNames(); //Exception here
        System.out.println(Arrays.toString(files));
        client.disconnect(true);
    }
}

I got an exception

Exception in thread "main" it.sauronsoftware.ftp4j.FTPException
  [code=450, message= TLS session of data connection has not resumed or
  the session does not match the control connection]    at
  it.sauronsoftware.ftp4j.FTPClient.listNames(FTPClient.java:2407)  at
  FTP.main(FTP.java:49)

I tried to use active mode, but it doesn't help also (failed after ping command)

Exception in thread "main" it.sauronsoftware.ftp4j.FTPException
  [code=421, message= Rejected command, requested IP address does not
  match control connection IP.]

Could you please answer me what I've done wrong or does ftp4j library actually support FTPES & TLS?

Screenshots with FileZilla server TLS configuration:


问:
Apply drop caps to each word in a link
I'd like to recreate the menu effect seen at http://www.thedecoratorsource.co.uk using CSS fonts and drop caps.

I know that I can use

```<code>p.introduction:first-letter {
font-size : 300%;
}
</code>```

which will give me the first word with a larger first characerer but I want to apply it to each word. I'm guessing there isn't a way to do this with CSS(3). Would my best bet with javascript? I've already got Moo on the page so this would be my preferred method.

I don't want to add extra HTML to my links to achieve this.

Thanks

答:
you can use toUpperCase(); javascript function to make all the letters capitalize. Example:

```<code>var str="This is my 1st new tutorial 123";
var a1 = str.toUpperCase();
document.write(a1);
</code>```

so, in your case i would grab all the elements' contents that you wish to capitalize and apply the toUpperCase() function to the letters.

Mootools Version:
HTML:

```<code><ul id='mylist'>
    <li><a href='#'>test 1</a></li>
    <li><a href='#'>test 2</a></li>
    <li><a href='#'>test 1</a></li>
    <li><a href='#'>test 4</a></li>
    <li><a href='#'>test 5</a></li>
</ul>
</code>```

Mootools JS:

```<code>$$('#mylist li').each(function(el) {
    console.log(el.getElement('a').innerHTML.toUpperCase());
});
</code>```

Here is the jsfiddle

Title: Apply drop caps to each word in a link

Body:
I'd like to recreate the menu effect seen at http://www.thedecoratorsource.co.uk using CSS fonts and drop caps.

I know that I can use

p.introduction:first-letter {
font-size : 300%;
}

which will give me the first word with a larger first characerer but I want to apply it to each word. I'm guessing there isn't a way to do this with CSS(3). Would my best bet with javascript? I've already got Moo on the page so this would be my preferred method.

I don't want to add extra HTML to my links to achieve this.

Thanks

Body:
you can use toUpperCase(); javascript function to make all the letters capitalize. Example:

var str="This is my 1st new tutorial 123";
var a1 = str.toUpperCase();
document.write(a1);

so, in your case i would grab all the elements' contents that you wish to capitalize and apply the toUpperCase() function to the letters.

Mootools Version:
HTML:

<ul id='mylist'>
    <li><a href='#'>test 1</a></li>
    <li><a href='#'>test 2</a></li>
    <li><a href='#'>test 1</a></li>
    <li><a href='#'>test 4</a></li>
    <li><a href='#'>test 5</a></li>
</ul>

Mootools JS:

$$('#mylist li').each(function(el) {
    console.log(el.getElement('a').innerHTML.toUpperCase());
});

Here is the jsfiddle


问:
Gravity forms date based price calculation
I'm a WP newbie and am amazed so far by what it can do. I am currently using Gravity forms to charge my customers for a monthly subscription plan. However I give my users option to choose the months they want to enrol for and charge them for it as they enrol.

```<code>FromDate = Date entered by the user in From Date field  (in days)
ToDate = Date entered by the user in To date field  (in days)
</code>```

So my formula for price calculation is:

```<code>(ToDate - FromDate)* (cost per day of my subscription)
</code>```

However, I don't know how to implement this. Any help would deeply be appreciated.

答: The Gravity Forms Date Time Calculator plugin will allow you do to all sorts of date-based calculations. It's available by request to Gravity Perks users.</p>

Body:
I'm a WP newbie and am amazed so far by what it can do. I am currently using Gravity forms to charge my customers for a monthly subscription plan. However I give my users option to choose the months they want to enrol for and charge them for it as they enrol.

FromDate = Date entered by the user in From Date field  (in days)
ToDate = Date entered by the user in To date field  (in days)

So my formula for price calculation is:

(ToDate - FromDate)* (cost per day of my subscription)

However, I don't know how to implement this. Any help would deeply be appreciated.


问:
Compare null value for datetime
I am storing date as string in sql table. If date is not passed then it will be null. Now I want to check whether date is null from the design page of asp.net. I am getting error of type cast. Any one is having idea how to overcome this?

```<code><%# ((DateTime)Eval("Date")).ToString("yyy-MM-dd hh:mm tt") %>">
</code>```

Here data is getting as string input.

Thanks

答:
I am storing date as string in SQL table.

This is your first problem (here is a good explanation of why this is a problem).

I am getting error of type cast.

This is how your first problem (storing a date as a string) causes your second problem (type cast error). Although it is possible to fix this by parsing the date from a string using DateTime.Parse, DateTime.ParseExact, or DateTime.TryParse, I would strongly recommend against using any of these approaches.

The good news is that once you fix the first problem, the second problem goes away by itself!

Use this approach to change the type of the column without losing the data:

Add a new column of type date to your table

Run an update statement to populate the new date column from the old varchar column that contains string representations of dates

Drop the old varchar column

Title: Compare null value for datetime

Body:
I am storing date as string in sql table. If date is not passed then it will be null. Now I want to check whether date is null from the design page of asp.net. I am getting error of type cast. Any one is having idea how to overcome this?

<%# ((DateTime)Eval("Date")).ToString("yyy-MM-dd hh:mm tt") %>">

Here data is getting as string input.

Thanks


问:
Have Maven fail with a message if a certain profile is used
Let's say I have a profile "dostuff" defined in a pom.xml that uses a plugin to do some stuff when the user runs mvn -P dostuff:

```<code><profiles>
    <profile>
        <id>dostuff</id>
        <build>
            <plugins>
                <plugin>
                    ...
                </plugin>
            <plugins>
        </build>
    </profile>
<profiles>
</code>```

The task the profile performs have been replaced by a new non-maven command entirely.

Of course I can just remove the profile, but that has two problems:

It doesn't fail the build, it just produces a warning:

[WARNING] The requested profile "dostuff" could not be activated because
  it does not exist.

It doesn't give the user any information that they should use the new command instead.

So, I would like any use of the profile "dostuff" to produce an error with a message telling them to use the new non-maven command instead.

Is that even possible? It's a plus if the solution doesn't require a plugin.

答: The maven-enforcer-plugin has a built-in rule to require a profile is activated. Perhaps you could write your own rule to ban a profile, using that code as a starting point.

Body:
Let's say I have a profile "dostuff" defined in a pom.xml that uses a plugin to do some stuff when the user runs mvn -P dostuff:

<profiles>
    <profile>
        <id>dostuff</id>
        <build>
            <plugins>
                <plugin>
                    ...
                </plugin>
            <plugins>
        </build>
    </profile>
<profiles>

The task the profile performs have been replaced by a new non-maven command entirely.

Of course I can just remove the profile, but that has two problems:

It doesn't fail the build, it just produces a warning:

[WARNING] The requested profile "dostuff" could not be activated because
  it does not exist.

It doesn't give the user any information that they should use the new command instead.

So, I would like any use of the profile "dostuff" to produce an error with a message telling them to use the new non-maven command instead.

Is that even possible? It's a plus if the solution doesn't require a plugin.


问:
(Jquery-Rich Text Editor) How can be fixed bug in rich text editor - when press enter in firefox created 'br' tag but in IE created 'p' tag?
I working on website that use cleditor (Jquery-Rich Text Editor).
The editor have bug - when  press enter after letter in firefox created 'br' tag but in IE created 'p' tag.

Bug reproduction:
You can see this in their demo http://premiumsoftware.net/cleditor/ (enter some input end press enter (Firefox + IE ) -  see different space between lines because in IE generated 'p' tag vs firefox that genarated 'br' tag)

Update:

same question - better explanation then my: http://vanillaforums.org/discussion/13627/ie-uses-paragraph-tags-firefox-uses-br-tags/p1

please help me, what should i change for create 'br' tag also in IE instead 'p' tag.

Thanks,
Yosef

答:
It is not a bug. CLEditor uses standart browser api which can produce different result in different browsers and you cannot change IE behaviour but you can disable "br" generation in Mozilla by using execCommand

```<code>$("#input").cleditor()[0].doc.execCommand("insertBrOnReturn", false, false);
</code>```

But content should have at least one paragraph. Only in this case firefox will generate "p".

Body:
It is not a bug. CLEditor uses standart browser api which can produce different result in different browsers and you cannot change IE behaviour but you can disable "br" generation in Mozilla by using execCommand

$("#input").cleditor()[0].doc.execCommand("insertBrOnReturn", false, false);

But content should have at least one paragraph. Only in this case firefox will generate "p".


问:
Clause group by if two lines return the maximum
My query is:

```<code>SELECT ID,B,C,D, SUM(X), SUM(Y)
FROM TABLE
GROUP BY A,B,C,D
</code>```

But if the query returns 2 lines with the same id, I want take only one line which have the max of column D.

For example if the query returns:

```<code>+----+---+---+---+--------+--------+
| ID | B | C | D | SUM(X) | SUM(Y) |
+----+---+---+---+--------+--------+
| 2  | 1 | 1 | 1 | 70     | 100    |
| 2  | 1 | 1 | 3 | 100    | 150    |
+----+---+---+---+--------+--------+
</code>```

Then drop the line with D=1, and keep only the line with D=3

答:
You can use JOIN like this :

```<code>SELECT t1.ID, t1.B, t1.C, t1.D, SUM(t1.X), SUM(t1.Y)
FROM TABLE1 t1
join (select ID, max(D) D from TABLE1 group by ID) t2
on t1.ID=t2.ID and t1.D=t2.D
GROUP BY t1.ID, t1.B, t1.C, t1.D
</code>```

SQL HERE

Body:
My query is:

SELECT ID,B,C,D, SUM(X), SUM(Y)
FROM TABLE
GROUP BY A,B,C,D

But if the query returns 2 lines with the same id, I want take only one line which have the max of column D.

For example if the query returns:

+----+---+---+---+--------+--------+
| ID | B | C | D | SUM(X) | SUM(Y) |
+----+---+---+---+--------+--------+
| 2  | 1 | 1 | 1 | 70     | 100    |
| 2  | 1 | 1 | 3 | 100    | 150    |
+----+---+---+---+--------+--------+

Then drop the line with D=1, and keep only the line with D=3

Body:
You can use JOIN like this :

SELECT t1.ID, t1.B, t1.C, t1.D, SUM(t1.X), SUM(t1.Y)
FROM TABLE1 t1
join (select ID, max(D) D from TABLE1 group by ID) t2
on t1.ID=t2.ID and t1.D=t2.D
GROUP BY t1.ID, t1.B, t1.C, t1.D

SQL HERE


问:
Stuff Column Value handling select list exceeds the maximum allowed number of 4096 elements
SQL SERVER 2012

```<code>DECLARE @TABLE TABLE
    (
    BASENAME varchar(150),
    DESCRIPTIONS varchar(150)
    )

    insert @TABLE

    SELECT 'Accessory', 'Color' UNION ALL
    SELECT 'Accessory', 'Compatibility'UNION ALL
    SELECT 'Accessory', 'Finish'UNION ALL
    SELECT 'Accessory', 'Material'UNION ALL
    SELECT 'Accessory', 'Mount Type'UNION ALL
    SELECT 'Adapter',   'Adjustable'UNION ALL
    SELECT 'Adapter',   'Ampere'UNION ALL
    SELECT 'Adapter',   'Compatibility'UNION ALL
    SELECT 'Adapter',   'MountType'UNION ALL
    SELECT 'Adapter',   'Operation Type'UNION ALL
    SELECT 'Adapter',   'Vertical Lift'UNION ALL
    SELECT 'Adapter',   'Drawbar'UNION ALL
    SELECT 'Adapter',   'Switch'
</code>```

OUTPUT

```<code>BASENAME    DESC1   DESC2   DESC3   DESC4   DESC5   DESC6   DESC7   DESC8
Accessory   Color   Compatibility   Material    Mount Type  NULL    NULL    NULL    NULL
Adapter Adjustable  Ampere  Compatibility   MountType   Operation Type  Vertical Lift   Drawbar Switch
</code>```

The max number of DESC would be DESC 50 for one of the BASENAME.
STUFF not work in this scenario, as it is creating error as

Error: The number of elements in the select list exceeds the maximum allowed number of 4096 elements.

Code i tried:

```<code>DECLARE @Cols NVARCHAR(MAX);
DECLARE @SQL NVARCHAR(MAX);
DECLARE @Sel NVARCHAR(MAX);
DECLARE @GENERIC NVARCHAR(MAX)

SET @Cols = STUFF((SELECT distinct ',' + QUOTENAME([Description])
            FROM STAGING_TEMP
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'');
SET @Sel = STUFF((SELECT distinct ',' + QUOTENAME([Description]) +
' AS DESC'+CAST(row_number () over (partition by [Generic Name] order by [description]) as varchar(250))
            FROM STAGING_TEMP
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'');

SET @SQL = N'
SELECT DISTINCT [Generic Name], '+ @Sel+N'
FROM STAGING_TEMP
    pivot
    (
      MAX(Description) For Description IN ('+ @Cols + N')

    ) P';

EXECUTE( @SQL);
</code>```

is there any other way to achieve the desired output.

答:
Sounds like you are hitting a limit of SQL Server SELECT / INSERT statements as defined in the documentation though you haven't provided your STUFF() code snippet.

```<code>Columns per SELECT statement        4,096
Columns per INSERT statement        4,096
</code>```

Also note, the number of columns per a nonwide table is 1,024.

Body:
SQL SERVER 2012

DECLARE @TABLE TABLE
    (
    BASENAME varchar(150),
    DESCRIPTIONS varchar(150)
    )

    insert @TABLE

    SELECT 'Accessory', 'Color' UNION ALL
    SELECT 'Accessory', 'Compatibility'UNION ALL
    SELECT 'Accessory', 'Finish'UNION ALL
    SELECT 'Accessory', 'Material'UNION ALL
    SELECT 'Accessory', 'Mount Type'UNION ALL
    SELECT 'Adapter',   'Adjustable'UNION ALL
    SELECT 'Adapter',   'Ampere'UNION ALL
    SELECT 'Adapter',   'Compatibility'UNION ALL
    SELECT 'Adapter',   'MountType'UNION ALL
    SELECT 'Adapter',   'Operation Type'UNION ALL
    SELECT 'Adapter',   'Vertical Lift'UNION ALL
    SELECT 'Adapter',   'Drawbar'UNION ALL
    SELECT 'Adapter',   'Switch'

OUTPUT

BASENAME    DESC1   DESC2   DESC3   DESC4   DESC5   DESC6   DESC7   DESC8
Accessory   Color   Compatibility   Material    Mount Type  NULL    NULL    NULL    NULL
Adapter Adjustable  Ampere  Compatibility   MountType   Operation Type  Vertical Lift   Drawbar Switch

The max number of DESC would be DESC 50 for one of the BASENAME.
STUFF not work in this scenario, as it is creating error as

Error: The number of elements in the select list exceeds the maximum allowed number of 4096 elements.

Code i tried:

DECLARE @Cols NVARCHAR(MAX);
DECLARE @SQL NVARCHAR(MAX);
DECLARE @Sel NVARCHAR(MAX);
DECLARE @GENERIC NVARCHAR(MAX)

SET @Cols = STUFF((SELECT distinct ',' + QUOTENAME([Description])
            FROM STAGING_TEMP
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'');
SET @Sel = STUFF((SELECT distinct ',' + QUOTENAME([Description]) +
' AS DESC'+CAST(row_number () over (partition by [Generic Name] order by [description]) as varchar(250))
            FROM STAGING_TEMP
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'');

SET @SQL = N'
SELECT DISTINCT [Generic Name], '+ @Sel+N'
FROM STAGING_TEMP
    pivot
    (
      MAX(Description) For Description IN ('+ @Cols + N')

    ) P';

EXECUTE( @SQL);

is there any other way to achieve the desired output.

Body:
Sounds like you are hitting a limit of SQL Server SELECT / INSERT statements as defined in the documentation though you haven't provided your STUFF() code snippet.

Columns per SELECT statement        4,096
Columns per INSERT statement        4,096

Also note, the number of columns per a nonwide table is 1,024.


问:
Query in MySQL that get values from two tables and put them in a specific order
I want to get values from this two tables and put them in a GridView in a specific way.

First table is estimated income and the second is actual income.

This is the estimated income table:

and this is the actual income:

I want to get values from two tables and display them in a GridView to look like this table:

The code that i stuck in is:

```<code> select t as which , SUM(Amount_income_table) as Actual,
 SUM(estimated_amount) as Estimated
 from ((select MONTHNAME(Date_income_table) as T,
 select SUM(Amount_income_table) as Actual
 FROM bacci.income_table WHERE year(Date_income_table)='2017' GROUP BY
 monthname(date_income_table))
 )union all
 (SELECT SUM(estimated_amount) as Estimated
 FROM bacci.estimated_income_table WHERE estimated_year='2017' GROUP BY
 estimated_month) order by MONTHNAME(Date_income_table);
</code>```

答:
Assuming that bacci.estimated_income_table is guaranteed to contain rows for all twelve months we want to return, and assuming estimated_month column is integer value 1 thru 12, I'd do something like this:

EDIT

It appears that estimated_month is actually the month name January, February, ... so we derive the month number (1 thru 12) from that ...

```<code>SELECT d.y_                                  AS `year`
     , d.mn_                                 AS `month`
     , IFNULL(SUM(d.actual),0)               AS `actual`
     , IFNULL(SUM(d.estimated),0)            AS `estimated`
  FROM (
         SELECT YEAR(it.date_income_table)                      AS `y_`
              , MONTH(it.date_income_table)                     AS `m_`
              , MONTHNAME(it.date_income_table)                 AS `mn_`
              , SUM(it.amount_income_table)                     AS `actual`
              , NULL                                            AS `estimated`
           FROM bacci.income_table it
          WHERE it.date_income_table >= '2017-01-01'
            AND it.date_income_table  < '2017-01-01' + INTERVAL 1 YEAR
          GROUP
             BY YEAR(it.date_income_table)
              , MONTH(it.date_income_table)
              , MONTHNAME(it.date_income_table)

          UNION ALL

         SELECT ei.estimated_year                               AS `y_`
              , MONTH(STR_TO_DATE(ei.estimated_month,'%M'))     AS `m_`
              , ei.estimated_month                              AS `mn_`
              , NULL                                            AS `actual`
              , SUM(ei.estimated_amount)                        AS `estimated`
           FROM bacci.estimated_income_table ei
          WHERE ei.estimated_year = '2017'
          GROUP
             BY ei.estimated_year
              , MONTH(STR_TO_DATE(ei.estimated_month,'%M'))
              , ei.estimated_month
       ) d
 GROUP
    BY d.y_
     , d.m_
     , d.mn_
 ORDER
    BY d.y_
     , d.m_
</code>```

Body:
I want to get values from this two tables and put them in a GridView in a specific way.

First table is estimated income and the second is actual income.

This is the estimated income table:

and this is the actual income:

I want to get values from two tables and display them in a GridView to look like this table:

The code that i stuck in is:

 select t as which , SUM(Amount_income_table) as Actual,
 SUM(estimated_amount) as Estimated
 from ((select MONTHNAME(Date_income_table) as T,
 select SUM(Amount_income_table) as Actual
 FROM bacci.income_table WHERE year(Date_income_table)='2017' GROUP BY
 monthname(date_income_table))
 )union all
 (SELECT SUM(estimated_amount) as Estimated
 FROM bacci.estimated_income_table WHERE estimated_year='2017' GROUP BY
 estimated_month) order by MONTHNAME(Date_income_table);

Body:
Assuming that bacci.estimated_income_table is guaranteed to contain rows for all twelve months we want to return, and assuming estimated_month column is integer value 1 thru 12, I'd do something like this:

EDIT

It appears that estimated_month is actually the month name January, February, ... so we derive the month number (1 thru 12) from that ...

SELECT d.y_                                  AS `year`
     , d.mn_                                 AS `month`
     , IFNULL(SUM(d.actual),0)               AS `actual`
     , IFNULL(SUM(d.estimated),0)            AS `estimated`
  FROM (
         SELECT YEAR(it.date_income_table)                      AS `y_`
              , MONTH(it.date_income_table)                     AS `m_`
              , MONTHNAME(it.date_income_table)                 AS `mn_`
              , SUM(it.amount_income_table)                     AS `actual`
              , NULL                                            AS `estimated`
           FROM bacci.income_table it
          WHERE it.date_income_table >= '2017-01-01'
            AND it.date_income_table  < '2017-01-01' + INTERVAL 1 YEAR
          GROUP
             BY YEAR(it.date_income_table)
              , MONTH(it.date_income_table)
              , MONTHNAME(it.date_income_table)

          UNION ALL

         SELECT ei.estimated_year                               AS `y_`
              , MONTH(STR_TO_DATE(ei.estimated_month,'%M'))     AS `m_`
              , ei.estimated_month                              AS `mn_`
              , NULL                                            AS `actual`
              , SUM(ei.estimated_amount)                        AS `estimated`
           FROM bacci.estimated_income_table ei
          WHERE ei.estimated_year = '2017'
          GROUP
             BY ei.estimated_year
              , MONTH(STR_TO_DATE(ei.estimated_month,'%M'))
              , ei.estimated_month
       ) d
 GROUP
    BY d.y_
     , d.m_
     , d.mn_
 ORDER
    BY d.y_
     , d.m_


问:
Hand over variable from a function inside node.js + twit package
I am using the package twitinsite a node.js app to get some JSON data from Twitter.

I tried for hours to manage how I can hand over a variable from inside a function to the outside.

```<code>var tweets;
T.get('followers/ids', { screen_name: 'tolga_tezel' },  function (err, data, response) {
  tweets = data;
})
console.log(tweets); // -> undefiend

//data is the JSON I get from the Twitter Server. Console.log(data) shows it.
</code>```

I know its because of the asynchronous thing, but I dont know how to manage this.

I hope you can help me

答:
Put your console.log inside your callback function.
If you want to process further, please put that code inside your callback function.
There are other ways also to work with Asynchronous nature of javascript.
You can use async.js library, which is very easy to use.</p>

Body:
I am using the package twitinsite a node.js app to get some JSON data from Twitter.

I tried for hours to manage how I can hand over a variable from inside a function to the outside.

var tweets;
T.get('followers/ids', { screen_name: 'tolga_tezel' },  function (err, data, response) {
  tweets = data;
})
console.log(tweets); // -> undefiend

//data is the JSON I get from the Twitter Server. Console.log(data) shows it.

I know its because of the asynchronous thing, but I dont know how to manage this.

I hope you can help me


问:
Xcode: UIScrollView image gallery, having memory problems
I'm Trying to develop an UIScrollView Based Image gallery.

So let me explain what i'm trying to achieve here:

I want to a sliding presentation, that can show upto 140 image. ( You can swipe back and forth )
I've found information on the web, and i've been told the best way to do this is with a UIScrollview which has 3 UIImageViews which you create and remove from superview.

So i managed to create such a "sliding image gallery" with some help from a few tutorials :).
I've managed to upload the application to the ipad, start up the application and run it.

after i viewed about 50-70 slides the app crashes ( out of memory). My knowledge of Obj. C isn't that great .

You'll find the code below: it Prob. has something to do with releasing the images.
Improvements to the code would be really helpful

```<code>#import "ParatelPresentationViewController.h"

//Define the UIView ( we need 3 Image Views left, mid right);
@interface SlideShowView : UIView
{
 NSArray * mImages;

 UIImageView * mLeftImageView;
 UIImageView * mCurrentImageView;
 UIImageView * mRightImageView;

 NSUInteger mCurrentImage;

 BOOL mSwiping;
 CGFloat mSwipeStart;
}

- (id)initWithImages:(NSArray *)inImages;

@end // SlideShowView

#pragma mark -

@implementation SlideShowView

- (UIImageView *)createImageView:(NSUInteger)inImageIndex
{
 if (inImageIndex >= [mImages count])
 {
  return nil;
 }

 UIImageView * result = [[UIImageView alloc] initWithImage:[mImages objectAtIndex:inImageIndex]];
 result.opaque = YES;
 result.userInteractionEnabled = NO;
 result.backgroundColor = [UIColor blackColor];
 result.contentMode = UIViewContentModeScaleAspectFit;
 result.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight ;

 return result;
}

- (id)initWithImages:(NSArray *)inImages
{
 if (self = [super initWithFrame:CGRectZero])
 {
  mImages = [inImages retain];

  NSUInteger imageCount = [inImages count];
  NSLog(@"hoeveel foto's: %i");
  if (imageCount > 0)
  {
   mCurrentImageView = [self createImageView:0];
   [self addSubview:mCurrentImageView];

   if (imageCount > 1)
   {
    mRightImageView = [self createImageView:1];
    [self addSubview:mRightImageView];
   }

  }

  self.opaque = YES;
  self.backgroundColor = [UIColor blueColor];
  self.contentMode = UIViewContentModeScaleAspectFit;
  self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
 }

 return self;
}

- (void)dealloc
{
 [mImages release];
 [super dealloc];
}

- (void)layoutSubviews
{
 if (mSwiping)
  return;

 //CGSize contentSize = self.frame.size; // Enable when you use content.width/height
 //self.backgroundColor = [UIColor redColor];
 mLeftImageView.frame = CGRectMake(-1024, 0.0f, 1024, 748);//  (-1024, 0.0f, 1024, 748) can be replaced by  (-contentSize.width, 0.0f, contentSize.width, contentSize.height);
 mCurrentImageView.frame = CGRectMake(0.0f, 0.0f, 1024, 748);
 mRightImageView.frame = CGRectMake(1024, 0.0f,  1024, 748);
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
 if ([touches count] != 1)
  return;

 mSwipeStart = [[touches anyObject] locationInView:self].x;
 mSwiping = YES;

 mLeftImageView.hidden = NO;
 mCurrentImageView.hidden = NO;
 mRightImageView.hidden = NO;
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
 if (! mSwiping || [touches count] != 1)
  return;

 CGFloat swipeDistance = [[touches anyObject] locationInView:self].x - mSwipeStart;

 //CGSize contentSize = self.frame.size;

 mLeftImageView.frame = CGRectMake(swipeDistance - 1024, 0.0f, 1024, 748);
 mCurrentImageView.frame = CGRectMake(swipeDistance, 0.0f, 1024, 748);
 mRightImageView.frame = CGRectMake(swipeDistance + 1024, 0.0f, 1024, 748);
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
 if (! mSwiping)
  return;

 //CGSize contentSize = self.frame.size;

 NSUInteger count = [mImages count];

 CGFloat swipeDistance = [[touches anyObject] locationInView:self].x - mSwipeStart;
 if (mCurrentImage > 0 && swipeDistance > 50.0f)
 {
  mRightImageView.image = nil;
  //[mRightImageView.image release];
  [mRightImageView removeFromSuperview];
  [mRightImageView release];
  //mRightImageView = nil;
  //NSLog(@"Count of mRight : %i",[mRightImageView retainCount]);

  mRightImageView = mCurrentImageView;
  mCurrentImageView = mLeftImageView;

  mCurrentImage--;
  if (mCurrentImage > 0)
  {
   mLeftImageView = [self createImageView:mCurrentImage - 1];
   mLeftImageView.hidden = YES;

   [self addSubview:mLeftImageView];
  }
  else
  {
   mLeftImageView = nil;
  }
 }
 else if (mCurrentImage < count - 1 && swipeDistance < -50.0f)
 {
  mLeftImageView.image = nil;
  //[mLeftImageView.image release];
  [mLeftImageView removeFromSuperview];
  [mLeftImageView release];
  //mLeftImageView = nil;

  mLeftImageView = mCurrentImageView;
  mCurrentImageView = mRightImageView;

  mCurrentImage++;
  if (mCurrentImage < count - 1)
  {
   mRightImageView = [self createImageView:mCurrentImage + 1];
   mRightImageView.hidden = YES;

   [self addSubview:mRightImageView];
   NSLog(@"Count of mRight : %i",[mRightImageView.image retainCount]);
  }
  else
  {
   mRightImageView = nil;
  }
 }

 [UIView beginAnimations:@"swipe" context:NULL];
 [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
 [UIView setAnimationDuration:0.3f];

 mLeftImageView.frame = CGRectMake(-1024, 0.0f, 1024, 748);
 mCurrentImageView.frame = CGRectMake(0.0f, 0.0f, 1024, 748);
 mRightImageView.frame = CGRectMake(1024, 0.0f, 1024, 748);

 [UIView commitAnimations];

 mSwiping = NO;
}

@end // SlideShowView

#pragma mark -

@implementation ParatelPresentationViewController

- (id)init
{
 if (self = [super initWithNibName:nil bundle:nil])
 {

  NSMutableArray *Displayimages = [[NSMutableArray alloc]init];
  int i;
  for(i=0 ; i<139 ; i++) {

   NSString *tempString = [NSString stringWithFormat:@"Dia%d", i+1];
   NSLog(@"Dia%d.jpg", i+1);
   NSString *imageFile = [[NSBundle mainBundle] pathForResource:tempString ofType:@"JPG"];
   BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:imageFile];

   if (fileExists){
    [Displayimages addObject:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:tempString ofType:@"JPG"]]];
    NSLog(@"img");
   }else {
    break;
   }

  }

  //NSArray * images = [NSArray arrayWithObjects:[UIImage imageNamed:@"1.jpg"], [UIImage imageNamed:@"2.jpg"], [UIImage imageNamed:@"3.jpg"], [UIImage imageNamed:@"4.jpg"], [UIImage imageNamed:@"5.jpg"], nil];
  //NSLog(@"Objects Img = %@", images);
  NSLog(@"Images %@",Displayimages);
  self.view = [[[SlideShowView alloc] initWithImages:Displayimages] autorelease];
  [Displayimages release];
 }

 return self;
}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    //return YES;
 return UIInterfaceOrientationIsLandscape (interfaceOrientation);

}

@end
</code>```

If you would find a solution or tips, all are welcome !

Thanks in advance

kind regards Bart !

答:
You definitely have a memory leak in createImageView:. You will have to change

```<code>return result;
</code>```

to

```<code>return [result autorelease];
</code>```

There might be more leaks, but that's an obvious one.

Johannes

Body:
I'm Trying to develop an UIScrollView Based Image gallery.

So let me explain what i'm trying to achieve here:

I want to a sliding presentation, that can show upto 140 image. ( You can swipe back and forth )
I've found information on the web, and i've been told the best way to do this is with a UIScrollview which has 3 UIImageViews which you create and remove from superview.

So i managed to create such a "sliding image gallery" with some help from a few tutorials :).
I've managed to upload the application to the ipad, start up the application and run it.

after i viewed about 50-70 slides the app crashes ( out of memory). My knowledge of Obj. C isn't that great .

You'll find the code below: it Prob. has something to do with releasing the images.
Improvements to the code would be really helpful

#import "ParatelPresentationViewController.h"

//Define the UIView ( we need 3 Image Views left, mid right);
@interface SlideShowView : UIView
{
 NSArray * mImages;

 UIImageView * mLeftImageView;
 UIImageView * mCurrentImageView;
 UIImageView * mRightImageView;

 NSUInteger mCurrentImage;

 BOOL mSwiping;
 CGFloat mSwipeStart;
}

- (id)initWithImages:(NSArray *)inImages;

@end // SlideShowView

#pragma mark -

@implementation SlideShowView

- (UIImageView *)createImageView:(NSUInteger)inImageIndex
{
 if (inImageIndex >= [mImages count])
 {
  return nil;
 }

 UIImageView * result = [[UIImageView alloc] initWithImage:[mImages objectAtIndex:inImageIndex]];
 result.opaque = YES;
 result.userInteractionEnabled = NO;
 result.backgroundColor = [UIColor blackColor];
 result.contentMode = UIViewContentModeScaleAspectFit;
 result.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight ;

 return result;
}

- (id)initWithImages:(NSArray *)inImages
{
 if (self = [super initWithFrame:CGRectZero])
 {
  mImages = [inImages retain];

  NSUInteger imageCount = [inImages count];
  NSLog(@"hoeveel foto's: %i");
  if (imageCount > 0)
  {
   mCurrentImageView = [self createImageView:0];
   [self addSubview:mCurrentImageView];

   if (imageCount > 1)
   {
    mRightImageView = [self createImageView:1];
    [self addSubview:mRightImageView];
   }

  }

  self.opaque = YES;
  self.backgroundColor = [UIColor blueColor];
  self.contentMode = UIViewContentModeScaleAspectFit;
  self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
 }

 return self;
}

- (void)dealloc
{
 [mImages release];
 [super dealloc];
}

- (void)layoutSubviews
{
 if (mSwiping)
  return;

 //CGSize contentSize = self.frame.size; // Enable when you use content.width/height
 //self.backgroundColor = [UIColor redColor];
 mLeftImageView.frame = CGRectMake(-1024, 0.0f, 1024, 748);//  (-1024, 0.0f, 1024, 748) can be replaced by  (-contentSize.width, 0.0f, contentSize.width, contentSize.height);
 mCurrentImageView.frame = CGRectMake(0.0f, 0.0f, 1024, 748);
 mRightImageView.frame = CGRectMake(1024, 0.0f,  1024, 748);
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
 if ([touches count] != 1)
  return;

 mSwipeStart = [[touches anyObject] locationInView:self].x;
 mSwiping = YES;

 mLeftImageView.hidden = NO;
 mCurrentImageView.hidden = NO;
 mRightImageView.hidden = NO;
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
 if (! mSwiping || [touches count] != 1)
  return;

 CGFloat swipeDistance = [[touches anyObject] locationInView:self].x - mSwipeStart;

 //CGSize contentSize = self.frame.size;

 mLeftImageView.frame = CGRectMake(swipeDistance - 1024, 0.0f, 1024, 748);
 mCurrentImageView.frame = CGRectMake(swipeDistance, 0.0f, 1024, 748);
 mRightImageView.frame = CGRectMake(swipeDistance + 1024, 0.0f, 1024, 748);
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
 if (! mSwiping)
  return;

 //CGSize contentSize = self.frame.size;

 NSUInteger count = [mImages count];

 CGFloat swipeDistance = [[touches anyObject] locationInView:self].x - mSwipeStart;
 if (mCurrentImage > 0 && swipeDistance > 50.0f)
 {
  mRightImageView.image = nil;
  //[mRightImageView.image release];
  [mRightImageView removeFromSuperview];
  [mRightImageView release];
  //mRightImageView = nil;
  //NSLog(@"Count of mRight : %i",[mRightImageView retainCount]);

  mRightImageView = mCurrentImageView;
  mCurrentImageView = mLeftImageView;

  mCurrentImage--;
  if (mCurrentImage > 0)
  {
   mLeftImageView = [self createImageView:mCurrentImage - 1];
   mLeftImageView.hidden = YES;

   [self addSubview:mLeftImageView];
  }
  else
  {
   mLeftImageView = nil;
  }
 }
 else if (mCurrentImage < count - 1 && swipeDistance < -50.0f)
 {
  mLeftImageView.image = nil;
  //[mLeftImageView.image release];
  [mLeftImageView removeFromSuperview];
  [mLeftImageView release];
  //mLeftImageView = nil;

  mLeftImageView = mCurrentImageView;
  mCurrentImageView = mRightImageView;

  mCurrentImage++;
  if (mCurrentImage < count - 1)
  {
   mRightImageView = [self createImageView:mCurrentImage + 1];
   mRightImageView.hidden = YES;

   [self addSubview:mRightImageView];
   NSLog(@"Count of mRight : %i",[mRightImageView.image retainCount]);
  }
  else
  {
   mRightImageView = nil;
  }
 }

 [UIView beginAnimations:@"swipe" context:NULL];
 [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
 [UIView setAnimationDuration:0.3f];

 mLeftImageView.frame = CGRectMake(-1024, 0.0f, 1024, 748);
 mCurrentImageView.frame = CGRectMake(0.0f, 0.0f, 1024, 748);
 mRightImageView.frame = CGRectMake(1024, 0.0f, 1024, 748);

 [UIView commitAnimations];

 mSwiping = NO;
}

@end // SlideShowView

#pragma mark -

@implementation ParatelPresentationViewController

- (id)init
{
 if (self = [super initWithNibName:nil bundle:nil])
 {

  NSMutableArray *Displayimages = [[NSMutableArray alloc]init];
  int i;
  for(i=0 ; i<139 ; i++) {

   NSString *tempString = [NSString stringWithFormat:@"Dia%d", i+1];
   NSLog(@"Dia%d.jpg", i+1);
   NSString *imageFile = [[NSBundle mainBundle] pathForResource:tempString ofType:@"JPG"];
   BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:imageFile];

   if (fileExists){
    [Displayimages addObject:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:tempString ofType:@"JPG"]]];
    NSLog(@"img");
   }else {
    break;
   }

  }

  //NSArray * images = [NSArray arrayWithObjects:[UIImage imageNamed:@"1.jpg"], [UIImage imageNamed:@"2.jpg"], [UIImage imageNamed:@"3.jpg"], [UIImage imageNamed:@"4.jpg"], [UIImage imageNamed:@"5.jpg"], nil];
  //NSLog(@"Objects Img = %@", images);
  NSLog(@"Images %@",Displayimages);
  self.view = [[[SlideShowView alloc] initWithImages:Displayimages] autorelease];
  [Displayimages release];
 }

 return self;
}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    //return YES;
 return UIInterfaceOrientationIsLandscape (interfaceOrientation);

}

@end

If you would find a solution or tips, all are welcome !

Thanks in advance

kind regards Bart !

Body:
You definitely have a memory leak in createImageView:. You will have to change

return result;

to

return [result autorelease];

There might be more leaks, but that's an obvious one.

Johannes


问:
Get list of objects with unique combination of id/values
I have this collection:

```<code>{
  Id: 5,
  postalcodes: {2000, 3000, 4000}
},
{
 Id: 5,
 postalcodes: { 2000, 5000 }
},
{
 Id: 6,
 postalcodes: { 2000, 7000 }
}
</code>```

I would like to get a list of objects containing an ID and postalcode. The ID may occur multiple times, but the postalcode should be unique PER id.

So my result would be:

```<code>{
 id: 5,
 postalcode: 2000
}
{
 id: 5,
 postalcode: 3000
}
{
 id: 5,
 postalcode: 4000
}
{
 id: 5,
 postalcode: 5000
}
{
 id: 6,
 postalcode: 2000
}
{
 id: 6,
 postalcode: 7000
}
</code>```

This is my query:

```<code>collection.Select(x => new

                                                                 {
                                                                     x.id,
                                                                     x.postalcodes
                                                                 })
    .Distinct()
</code>```

I'm stuck in how to flatten the postalcodes so each postal code would create a seperate object.

Thanks!

答:
you can use SelectMany to flattern inner collections, i.e.:

```<code>collection
.SelectMany(i => i.postalcodes.Select(j=>new{i.id, postalcode = j}))
.Distinct()
</code>```

Body:
I have this collection:

{
  Id: 5,
  postalcodes: {2000, 3000, 4000}
},
{
 Id: 5,
 postalcodes: { 2000, 5000 }
},
{
 Id: 6,
 postalcodes: { 2000, 7000 }
}

I would like to get a list of objects containing an ID and postalcode. The ID may occur multiple times, but the postalcode should be unique PER id.

So my result would be:

{
 id: 5,
 postalcode: 2000
}
{
 id: 5,
 postalcode: 3000
}
{
 id: 5,
 postalcode: 4000
}
{
 id: 5,
 postalcode: 5000
}
{
 id: 6,
 postalcode: 2000
}
{
 id: 6,
 postalcode: 7000
}

This is my query:

collection.Select(x => new

                                                                 {
                                                                     x.id,
                                                                     x.postalcodes
                                                                 })
    .Distinct()

I'm stuck in how to flatten the postalcodes so each postal code would create a seperate object.

Thanks!

Body:
you can use SelectMany to flattern inner collections, i.e.:

collection
.SelectMany(i => i.postalcodes.Select(j=>new{i.id, postalcode = j}))
.Distinct()