问:
Cobol: cannot find entry point of a text file
Hi i am learning cobol from tutorialpoints and every program from there works as i've tested them in OpenCobolIDE(some needed a little editing). Then i came across the File Handling chapter and in there the program had a lot of errors. I did manage to rewrite the program until it didn't show me any errors but it doesn't do anything.

Here's my code:

```<code>IDENTIFICATION DIVISION.
       PROGRAM-ID. HELLO.

       ENVIRONMENT DIVISION.
           INPUT-OUTPUT SECTION.
           FILE-CONTROL.
               SELECT STUDENT ASSIGN TO
               'C:\Cobol\FIle Handling\input.txt'
               ORGANIZATION IS INDEXED
               ACCESS IS RANDOM
               RECORD KEY IS STUDENT-ID
               FILE STATUS IS FS.

       DATA DIVISION.
           FILE SECTION.
           FD STUDENT.
               01 STUDENT-FILE.
               05 STUDENT-ID PIC 9(5).
               05 NAME PIC A(25).

           WORKING-STORAGE SECTION.
               01 WS-STUDENT-FILE.
               05 WS-STUDENT-ID PIC 9(5).
               05 WS-NAME PIC A(25).
               01 FS PIC 9(02).

       PROCEDURE DIVISION.
           OPEN I-O STUDENT.
               MOVE 20005 TO STUDENT-ID.
           READ STUDENT RECORD INTO WS-STUDENT-FILE
                   KEY IS STUDENT-ID
                   INVALID KEY DISPLAY 'Invalid Key'
                   NOT INVALID KEY DISPLAY WS-STUDENT-FILE
           END-READ.

           CLOSE STUDENT.
       STOP RUN.
</code>```

This is the text file:

```<code>20003 Mohtashim M.
20004 Nishant Malik
20005 Amitabh Bachhan
</code>```

The result should be the text:

```<code>20005 Amitabh Bachhan
</code>```

答:
It's doing something: It's reading the file.  But that's all; you didn't ask for it to display or do anything else beyond reading the record into memory.  You might want to look at using the DISPLAY statement or maybe create another file to write the output to.

Might I make a couple of suggestions?

In modern COBOL, stylistically, you don't put a period after everything in the procedure division -- you only put it in where it is necessary.  For example:

```<code>   PROCEDURE DIVISION.
       OPEN I-O STUDENT
       MOVE 20005 TO STUDENT-ID
       READ STUDENT RECORD INTO WS-STUDENT-FILE
          KEY IS STUDENT-ID
          INVALID KEY DISPLAY 'Invalid Key'
          NOT INVALID KEY DISPLAY WS-STUDENT-FILE
       END-READ

       CLOSE STUDENT
       STOP RUN
       .
</code>```

Although the compiler doesn't care about spaces and returns, if I were you, I'd try to indent my code a bit better (I like how I indented the above :-) ). It's up to you and a lot of people like to do it differently, but if you are consistent you can spot problems that might sneak through your code.

Edit: I didn't notice that you were reading with a key from a text file.  So, either you need to:

read from a pre-built indexed file, or

read the file sequentially and search for what you want by comparing what you read for the student id you wanted.

Body:
Hi i am learning cobol from tutorialpoints and every program from there works as i've tested them in OpenCobolIDE(some needed a little editing). Then i came across the File Handling chapter and in there the program had a lot of errors. I did manage to rewrite the program until it didn't show me any errors but it doesn't do anything.

Here's my code:

IDENTIFICATION DIVISION.
       PROGRAM-ID. HELLO.

       ENVIRONMENT DIVISION.
           INPUT-OUTPUT SECTION.
           FILE-CONTROL.
               SELECT STUDENT ASSIGN TO
               'C:\Cobol\FIle Handling\input.txt'
               ORGANIZATION IS INDEXED
               ACCESS IS RANDOM
               RECORD KEY IS STUDENT-ID
               FILE STATUS IS FS.

       DATA DIVISION.
           FILE SECTION.
           FD STUDENT.
               01 STUDENT-FILE.
               05 STUDENT-ID PIC 9(5).
               05 NAME PIC A(25).

           WORKING-STORAGE SECTION.
               01 WS-STUDENT-FILE.
               05 WS-STUDENT-ID PIC 9(5).
               05 WS-NAME PIC A(25).
               01 FS PIC 9(02).

       PROCEDURE DIVISION.
           OPEN I-O STUDENT.
               MOVE 20005 TO STUDENT-ID.
           READ STUDENT RECORD INTO WS-STUDENT-FILE
                   KEY IS STUDENT-ID
                   INVALID KEY DISPLAY 'Invalid Key'
                   NOT INVALID KEY DISPLAY WS-STUDENT-FILE
           END-READ.

           CLOSE STUDENT.
       STOP RUN.

This is the text file:

20003 Mohtashim M.
20004 Nishant Malik
20005 Amitabh Bachhan

The result should be the text:

20005 Amitabh Bachhan

Body:
It's doing something: It's reading the file.  But that's all; you didn't ask for it to display or do anything else beyond reading the record into memory.  You might want to look at using the DISPLAY statement or maybe create another file to write the output to.

Might I make a couple of suggestions?

In modern COBOL, stylistically, you don't put a period after everything in the procedure division -- you only put it in where it is necessary.  For example:

   PROCEDURE DIVISION.
       OPEN I-O STUDENT
       MOVE 20005 TO STUDENT-ID
       READ STUDENT RECORD INTO WS-STUDENT-FILE
          KEY IS STUDENT-ID
          INVALID KEY DISPLAY 'Invalid Key'
          NOT INVALID KEY DISPLAY WS-STUDENT-FILE
       END-READ

       CLOSE STUDENT
       STOP RUN
       .

Although the compiler doesn't care about spaces and returns, if I were you, I'd try to indent my code a bit better (I like how I indented the above :-) ). It's up to you and a lot of people like to do it differently, but if you are consistent you can spot problems that might sneak through your code.

Edit: I didn't notice that you were reading with a key from a text file.  So, either you need to:

read from a pre-built indexed file, or

read the file sequentially and search for what you want by comparing what you read for the student id you wanted.


来源: stackexchange

问:
How to play ringtone/alarm sound in Android
I have been looking everywhere how to play a ringtone/alarm sound in Android.

I press a button and I want to play a ringtone/alarm sound. I could not find an easy, straightforward sample. Yes, I already looked at Alarm clock source code... but it is not straightforward and I cannot compile it.

I cannot make this work:

```<code>Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(this, alert);
final AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);

if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
    player.setAudioStreamType(AudioManager.STREAM_ALARM);
    player.setLooping(true);
    player.prepare();
    player.start();
}
</code>```

I get this error:

```<code>04-11 17:15:27.638: ERROR/MediaPlayerService(30): Couldn't open fd for
content://settings/system/ringtone
</code>```

So.. please if somebody knows how to play a default ringtone/alarm let me know.

I prefer not to upload any file. Just play a default ringtone.

答:
For the future googlers: use RingtoneManager.getActualDefaultRingtoneUri() instead of RingtoneManager.getDefaultUri(). According to its name, it would return the actual uri, so you can freely use it. From documentation of getActualDefaultRingtoneUri():

Gets the current default sound's Uri. This will give the actual sound
  Uri, instead of using this, most clients can use DEFAULT_RINGTONE_URI.

Meanwhile getDefaultUri() says this:

Returns the Uri for the default ringtone of a particular type. Rather than returning the actual ringtone's sound Uri, this will return the symbolic Uri which will resolved to the actual sound when played.

ContentLicense: CC BY-SA 3.0

Body:
I have been looking everywhere how to play a ringtone/alarm sound in Android.

I press a button and I want to play a ringtone/alarm sound. I could not find an easy, straightforward sample. Yes, I already looked at Alarm clock source code... but it is not straightforward and I cannot compile it.

I cannot make this work:

Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(this, alert);
final AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);

if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
    player.setAudioStreamType(AudioManager.STREAM_ALARM);
    player.setLooping(true);
    player.prepare();
    player.start();
}

I get this error:

04-11 17:15:27.638: ERROR/MediaPlayerService(30): Couldn't open fd for
content://settings/system/ringtone

So.. please if somebody knows how to play a default ringtone/alarm let me know.

I prefer not to upload any file. Just play a default ringtone.


问:
Polymorphism inside monads
I'm trying to pull a value out of a monad, but keep the value, which doesn't depend on the monad, polymorphic. Specifically:

```<code>foo :: (Monad mon, Ring a) => mon a
foo = return 3

main :: IO ()
main = do
  x <- foo
  print (x :: Double)
  print (x :: Int)
</code>```

The point is that the monadic portion of the computation is expensive to compute, so I only want to do it once, while keeping the value in the monad polymorphic. All of my attempts so far:

giving x the signature forall a. (Ring a) => a)

giving foo :: (Monad mon) => mon (forall a . (Ring a) => a)

enabling -XNoMonomorphismRestriction and NoMonoLocalBins

have either not worked or given errors about impredicative polymorphism, which I'm not willing to use. Is there some way to pull a polymorphic value out of a monad without impredicative polymorphism (or alternatively: is there a safe way to use impredicative polymorphism in GHC)?

答:
I found another interesting solution, which came from this paper on typed, tagless, final interpreters (section 2.3).

The idea is to use a "duplicator":

```<code>data Dup a b = Dup a b

duplicate :: Dup a b -> (a,b)
duplicate (Dup a b) = (a,b)

instance (Num a, Num b) => Num (Dup a b) where
  fromInteger x = Dup (fromInteger x) (fromInteger x)
  ...

foo :: (Monad mon, Num a) => mon a
foo = return 3

main :: IO ()
main = do
 x <- foo
 let (y,z) = duplicate x
 print (y :: Double)
 print (z :: Int)
</code>```

This solution isn't as general as Li-yao Xia's (it only works when the monadic value is an instance of a type class), but it is interesting because you don't need higher-rank polymorphism.

Title: Polymorphism inside monads

Body:
I'm trying to pull a value out of a monad, but keep the value, which doesn't depend on the monad, polymorphic. Specifically:

foo :: (Monad mon, Ring a) => mon a
foo = return 3

main :: IO ()
main = do
  x <- foo
  print (x :: Double)
  print (x :: Int)

The point is that the monadic portion of the computation is expensive to compute, so I only want to do it once, while keeping the value in the monad polymorphic. All of my attempts so far:

giving x the signature forall a. (Ring a) => a)

giving foo :: (Monad mon) => mon (forall a . (Ring a) => a)

enabling -XNoMonomorphismRestriction and NoMonoLocalBins

have either not worked or given errors about impredicative polymorphism, which I'm not willing to use. Is there some way to pull a polymorphic value out of a monad without impredicative polymorphism (or alternatively: is there a safe way to use impredicative polymorphism in GHC)?

Body:
I found another interesting solution, which came from this paper on typed, tagless, final interpreters (section 2.3).

The idea is to use a "duplicator":

data Dup a b = Dup a b

duplicate :: Dup a b -> (a,b)
duplicate (Dup a b) = (a,b)

instance (Num a, Num b) => Num (Dup a b) where
  fromInteger x = Dup (fromInteger x) (fromInteger x)
  ...

foo :: (Monad mon, Num a) => mon a
foo = return 3

main :: IO ()
main = do
 x <- foo
 let (y,z) = duplicate x
 print (y :: Double)
 print (z :: Int)

This solution isn't as general as Li-yao Xia's (it only works when the monadic value is an instance of a type class), but it is interesting because you don't need higher-rank polymorphism.


问:
Avoid sending full table with MongoDB and Pymongo
I'm trying to get the min and max value from some fields inside a collection. I'm not sure if this:

```<code>result = collection.find(date_filter, expected_projection).sort({'attribute': -1}).limit(1)
</code>```

is equivalent to this:

```<code>result_a = collection.find(date_filter, expected_projection)
result_b = result_a.sort({'attribute': -1}).limit(1)
</code>```

I don't want the server to query all the data in result_a from the database. Is the first line of code actually fetching every document in my collection and THEN sorting it, or just fetching the max element in the attribute field?

答:
The first line of code tells MongoDB to return only the document with the lowest value for "attribute". If "attribute" is indexed, then MongoDB can directly access only that one document, and not even consider the rest of the collection.

Do this once:

```<code>collection.create_index([('attribute', 1)])
</code>```

Having that index in place means you can find the highest-sorting or lowest-sorting document practically instantly.

Body:
I'm trying to get the min and max value from some fields inside a collection. I'm not sure if this:

result = collection.find(date_filter, expected_projection).sort({'attribute': -1}).limit(1)

is equivalent to this:

result_a = collection.find(date_filter, expected_projection)
result_b = result_a.sort({'attribute': -1}).limit(1)

I don't want the server to query all the data in result_a from the database. Is the first line of code actually fetching every document in my collection and THEN sorting it, or just fetching the max element in the attribute field?

Body:
The first line of code tells MongoDB to return only the document with the lowest value for "attribute". If "attribute" is indexed, then MongoDB can directly access only that one document, and not even consider the rest of the collection.

Do this once:

collection.create_index([('attribute', 1)])

Having that index in place means you can find the highest-sorting or lowest-sorting document practically instantly.


问:
How to insert and update two form same data into single table but different rows using php
I have to insert and update two form data on single submit click to mysql table. Please help me how can I do this. Just provide me a hint.

Thank you...

答:
As Per PHP w3Schools article about mysqli_multi_query :

The mysqli_multi_query() function performs one or more queries against
  the database. The queries are separated with a semicolon.

```<code>mysqli_multi_query(connection,query);
</code>```

Body:
As Per PHP w3Schools article about mysqli_multi_query :

The mysqli_multi_query() function performs one or more queries against
  the database. The queries are separated with a semicolon.

mysqli_multi_query(connection,query);


问:
Is it possible to set properties on blob storage via AZ Copy
We have an Azure CDN pointed at blob storage container. We upload on a regular basis new files via AZ Copy.

I can set it in many ways such as https://learn.microsoft.com/nb-no/azure/cdn/cdn-manage-expiration-of-blob-content but not in bulk.

Is it possible to set the Cache-Control property/meta data via AzCopy?

答:
Looking at the AzCopy parameters documentation, it does not appear you can set the Cache-Control property.

However, the Azure Data Movement Library exposes a SetAttributesCallback which would allow you to set properties.


问:
Sort DataAdapter Alphabetically - VB.Net
This should be a fairly simple one. I am creating a dataset which will contain a description field which I would like to sort by. The reason I want to sort the dataadapter and not in my SQL is that I am already ordering by the results that have a particular value.

My SQL looks like this:

```<code>SELECT pif_desc, pif_fund, psf_end, (CASE WHEN SUM(pmi_units) IS Null THEN 0 ELSE SUM(pmi_units) END) As fundunits
    FROM tbl_mem INNER JOIN tbl_sfunds
    ON pm_scheme = psf_scheme
    INNER JOIN tbl_invfun
    ON tbl_fund = tbl_fund
    LEFT JOIN pe_minv
    ON pmi_fund = pif_fund AND pm_member = pmi_member
    WHERE pm_member = @pm_member
    GROUP BY pif_desc, pif_fund, psf_end
    ORDER BY fundunits DESC
</code>```

My VB looks like this:

```<code>Dim cmd As New SqlCommand("getMembersFundsDCGENST", conn)
        cmd.CommandType = CommandType.StoredProcedure

        Dim p_pm_member As New SqlParameter("@pm_member", SqlDbType.Int)
        p_pm_member.Value = pm_member
        cmd.Parameters.Add(p_pm_member)

        Dim p_period_closing_date As New SqlParameter("@closingdate", SqlDbType.DateTime)
        p_period_closing_date.Value = period_closing_date
        cmd.Parameters.Add(p_closing_date)

        Dim da As New SqlDataAdapter(cmd)
        da.Fill(ds)
</code>```

I want to sort the datarows is ds.tables(0) by pif_desc but still have the rows with fundunits > 0 listed first.

I am also open to other suggestions on how I can achieve the correct ordering.

答:
Is the output you're looking for more like this?

```<code>pif_desc    fundunits
ABCDEF      6
CBCDEG      2
DEFGHI      4
ADFKHG      0
BFJSKL      0
XDFDKF      0
</code>```

If so, try this SQL query:

```<code>SELECT  pif_desc,
        pif_fund,
        psf_end,
        (CASE WHEN fundunits IS Null THEN 0
        ELSE fundunits END) As fundunits,
        (CASE WHEN fundunits IS Null THEN 0
        ELSE 1 END) As pif_order
FROM    (
            SELECT  pif_desc,
                    pif_fund,
                    psf_end,
                    SUM(pmi_units) As fundunits
            FROM    tbl_mem
            INNER   JOIN tbl_sfunds
                    ON pm_scheme = psf_scheme
            INNER   JOIN tbl_invfun
                    ON tbl_fund = tbl_fund
            LEFT    JOIN pe_minv
                    ON pmi_fund = pif_fund AND pm_member = pmi_member
            WHERE   pm_member = @pm_member
            GROUP   BY pif_desc, pif_fund, psf_end
        ) pifs
ORDER   BY pif_order,pif_desc
</code>```

ContentLicense: CC BY-SA 2.5

Body:
This should be a fairly simple one. I am creating a dataset which will contain a description field which I would like to sort by. The reason I want to sort the dataadapter and not in my SQL is that I am already ordering by the results that have a particular value.

My SQL looks like this:

SELECT pif_desc, pif_fund, psf_end, (CASE WHEN SUM(pmi_units) IS Null THEN 0 ELSE SUM(pmi_units) END) As fundunits
    FROM tbl_mem INNER JOIN tbl_sfunds
    ON pm_scheme = psf_scheme
    INNER JOIN tbl_invfun
    ON tbl_fund = tbl_fund
    LEFT JOIN pe_minv
    ON pmi_fund = pif_fund AND pm_member = pmi_member
    WHERE pm_member = @pm_member
    GROUP BY pif_desc, pif_fund, psf_end
    ORDER BY fundunits DESC

My VB looks like this:

Dim cmd As New SqlCommand("getMembersFundsDCGENST", conn)
        cmd.CommandType = CommandType.StoredProcedure

        Dim p_pm_member As New SqlParameter("@pm_member", SqlDbType.Int)
        p_pm_member.Value = pm_member
        cmd.Parameters.Add(p_pm_member)

        Dim p_period_closing_date As New SqlParameter("@closingdate", SqlDbType.DateTime)
        p_period_closing_date.Value = period_closing_date
        cmd.Parameters.Add(p_closing_date)

        Dim da As New SqlDataAdapter(cmd)
        da.Fill(ds)

I want to sort the datarows is ds.tables(0) by pif_desc but still have the rows with fundunits > 0 listed first.

I am also open to other suggestions on how I can achieve the correct ordering.

Body:
Is the output you're looking for more like this?

pif_desc    fundunits
ABCDEF      6
CBCDEG      2
DEFGHI      4
ADFKHG      0
BFJSKL      0
XDFDKF      0

If so, try this SQL query:

SELECT  pif_desc,
        pif_fund,
        psf_end,
        (CASE WHEN fundunits IS Null THEN 0
        ELSE fundunits END) As fundunits,
        (CASE WHEN fundunits IS Null THEN 0
        ELSE 1 END) As pif_order
FROM    (
            SELECT  pif_desc,
                    pif_fund,
                    psf_end,
                    SUM(pmi_units) As fundunits
            FROM    tbl_mem
            INNER   JOIN tbl_sfunds
                    ON pm_scheme = psf_scheme
            INNER   JOIN tbl_invfun
                    ON tbl_fund = tbl_fund
            LEFT    JOIN pe_minv
                    ON pmi_fund = pif_fund AND pm_member = pmi_member
            WHERE   pm_member = @pm_member
            GROUP   BY pif_desc, pif_fund, psf_end
        ) pifs
ORDER   BY pif_order,pif_desc


问:
8 meassurements (cube) in 3D space - interpolate between the values by one 3D position
I measured data in a 3d space. lets say temperature in a room for example. the 8 measurement points are arranged like the edges of a cube. I have room coordinates and temperature data for each point.

Now I track a moving person within the same space. Based on the person's actual position I want to interpolate between the 8 values to assume the temperature at that point in space.

答: I think weighted average based on measurement points' distances to the person will give the value you're after.</p>


问:
how can i show data of listview in other activity using database query?
I have a listview which take the value form two edittext. First sqlite database saves the value of these edittextand then convert it in listviews.What I want is that when the user click on list item it will show the values of that item in next activity using database queries. Can anyone tell me how can I do that. Please answer me in detail because I am new in android</p>

答:
```<code>            **Check this full code   MainActivity**
            package com.example.developer.database;
            import android.content.DialogInterface;
            import android.content.Intent;
            import android.database.Cursor;
            import android.database.sqlite.SQLiteDatabase;
            import android.os.Bundle;
            import android.os.Environment;
            import android.support.v7.app.AlertDialog;
            import android.support.v7.app.AppCompatActivity;
            import android.text.InputType;
            import android.util.Patterns;
            import android.view.View;
            import android.widget.Button;
            import android.widget.ListView;
            import android.widget.TextView;

            import com.example.developer.database.helper.DBhelper;
            import com.example.developer.database.model.Contact;
            import com.example.developer.database.model.MyListAdapter;

            import java.io.BufferedWriter;
            import java.io.File;
            import java.io.FileWriter;
            import java.util.ArrayList;

            public class MainActivity extends AppCompatActivity implements View.OnClickListener {
                DBhelper dBhelper;
                private Button SUBMIT;
                SQLiteDatabase sqldb;
                TextView infotext;
                private Button edit;
                private String[] arrText =
                        new String[]{"First Name","useremail", "password"
                                ,"city","phone no"};
                private String[]arrcity=new String[]{"INDIA","PAKISTAN","CHINA"};
                //    private String[] arrTemp;
                ArrayList<Contact> arrlst = new ArrayList<>();
                private MyListAdapter myListAdapter;

                private String adap1="adap1";

                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_main);
                    edit=(Button)findViewById(R.id.next);
                    infotext=(TextView) findViewById(R.id.infotext);

                    edit.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent i=new Intent(MainActivity.this,Show.class);
                            startActivity(i);
                        }
                    });

                    dBhelper=new DBhelper(this);
                    //arrTemp = new String[arrText.length];

                    for (int i = 0; i < arrText.length; i++) {
                        Contact reg =new Contact();
                        reg.setFieldName(arrText[i]);
                        // reg.setValue("");

                        switch (i){
                            case 5:
                                reg.setInput_type(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                                break;
                            case 6:
                                reg.setInput_type(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                                break;
                        }

                        arrlst.add(reg);
                    }

                    myListAdapter = new MyListAdapter(MainActivity.this,arrlst,adap1);

                    ListView listView = (ListView) findViewById(R.id.listViewMain);
                    listView.setAdapter(myListAdapter);

                    setupViews();

                }
                public void setupViews() {
                    SUBMIT = (Button) findViewById(R.id.submit);

                    SUBMIT.setOnClickListener(MainActivity.this);

                }

                @Override
                public void onClick(View v) {

                    if (v.getId() == R.id.submit) {
                        String NAME=arrlst.get(0).getValue();
                        String Email=arrlst.get(1).getValue();
                        String Password=arrlst.get(2).getValue();
                        String City=AppData.city;
                        String PhoneNo=arrlst.get(4).getValue();

                        arrlst.get(0).setError("");
                        arrlst.get(1).setError("");
                        arrlst.get(2).setError("");
                        arrlst.get(3).setError("");
                        arrlst.get(4).setError("");

                        if(NAME.length()<1) {

            //                alert();
                            arrlst.get(0).setError("Not a valid Name");
                            myListAdapter.notifyDataSetChanged();

                        }
                        else if(NAME.length()<1)
                        {
                            alert();
                        }
                        else if(Password.length()<1){
                            alert();
                        }
                        else if (City.isEmpty()){
                            alert();
                        }
                        else if(!isValidEmail(Email) ){
                            // Toast.makeText(getBaseContext(), "please give proper email", Toast.LENGTH_SHORT).show();
                            arrlst.get(1).setError("Not a valid email");
                            myListAdapter.notifyDataSetChanged();
                        }
                        else {
                            dBhelper.inserRecord(NAME,Email,Password,City,PhoneNo,AppData.city_pos);
                            Toast.makeText(MainActivity.this, "inserted.", Toast.LENGTH_LONG).show();
                            Intent i=new Intent(MainActivity.this,Show.class);
                            startActivity(i);
                        }

                    }
                }
                public void alert(){
                    AlertDialog.Builder adb=new AlertDialog.Builder(MainActivity.this);
                    adb.setTitle("UnSucessful");
                    adb.setMessage("You're not Successfully Registered!");
                    adb.setPositiveButton("OK",new DialogInterface.OnClickListener(){
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();

                        }
                    });
                    AlertDialog AD=adb.create();
                    AD.show();
                }
                private boolean isValidEmail(String EMAIL) {

                    return Patterns.EMAIL_ADDRESS.matcher(EMAIL).matches();
                }

            }

            **Adapter for MainActivity**
        package com.example.developer.database.adapter;

        import android.app.Activity;
        import android.content.Context;
        import android.text.Editable;
        import android.text.TextWatcher;
        import android.view.LayoutInflater;
        import android.view.View;
        import android.view.ViewGroup;
        import android.widget.AdapterView;
        import android.widget.ArrayAdapter;
        import android.widget.BaseAdapter;
        import android.widget.EditText;
        import android.widget.Spinner;
        import android.widget.TextView;

        import com.example.developer.database.AppData;
        import com.example.developer.database.MainActivity;
        import com.example.developer.database.R;
        import com.example.developer.database.helper.DBhelper;
        import com.example.developer.database.model.Contact;

        import java.util.ArrayList;

        /**
         * Created by sanjeev on 31/3/17.
         */
        public class MyListAdapter extends BaseAdapter {

            Context context;

            ArrayList<Contact> arrlst;
            LayoutInflater inflater;
            ArrayList<String> citylist=new ArrayList<>();

            String dec = "";
            String adap1 = "";
            String ada2 = "";
            private Contact contact ;

            public MyListAdapter(Activity activity, ArrayList<Contact> arrlst,Contact contact,String ada2) {
                this.context = activity;
                this.arrlst = arrlst;
                inflater = activity.getLayoutInflater();
                this.contact = contact;
                this.ada2 = ada2;
                dec = ada2;
                citylist.add("Kolkata");
                citylist.add("burdwan");
                citylist.add("bankura");citylist.add("mednipur");citylist.add("birbhum");
                citylist.add("malda");
                citylist.add("Coachbihar");
            }

            public MyListAdapter(MainActivity mainActivity, ArrayList<Contact> arrlst, String adap1) {
                this.context = mainActivity;
                this.arrlst = arrlst;
                inflater = mainActivity.getLayoutInflater();
                this.adap1 = adap1;
                dec = adap1;

                citylist.add("Kolkata");
                citylist.add("burdwan");
                citylist.add("bankura");citylist.add("mednipur");citylist.add("birbhum");
                citylist.add("malda");
                citylist.add("Coachbihar");
            }

            @Override
            public int getCount() {

                Log.d("ppp",""+arrlst.size());
                return arrlst.size();
            }

            @Override
            public Object getItem(int position) {
                return arrlst.get(position);
            }

            @Override
            public long getItemId(int position) {
                return position;
            }

            private class ViewHolder {
                TextView textView1;
                EditText editText1;
                public Spinner spinner;

                public ViewHolder(View item) {
                    editText1 = (EditText) item.findViewById(R.id.editText1);
                }

            }

            @Override
            public View getView(final int position, View convertView, ViewGroup parent) {
                final int pos = position;

                final ViewHolder holder;
                if (pos == 3) {
                    convertView = inflater.inflate(R.layout.spinner, null, false);

                } else {
                    convertView = inflater.inflate(R.layout.layout, null, false);
                }

                    holder = new ViewHolder(convertView);
                    convertView.setTag(holder);

                if(pos==3){
                    holder.spinner = (Spinner) convertView.findViewById(R.id.sp);
                    holder.textView1 = (TextView) convertView.findViewById(R.id.textView1);

                }
                else{
                    holder.textView1 = (TextView) convertView.findViewById(R.id.textView1);
                    holder.editText1 = (EditText) convertView.findViewById(R.id.editText1);

                    holder.textView1.setText(arrlst.get(pos).getFieldName());
                }

                if (pos == 3) {

                    holder.textView1.setText(arrlst.get(3).getFieldName());
                    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>
                            (context, android.R.layout.simple_spinner_item,citylist);

                    dataAdapter.setDropDownViewResource
                            (android.R.layout.simple_spinner_dropdown_item);

                    holder.spinner.setAdapter(dataAdapter);

                    if(contact!=null) {

                        holder.spinner.setSelection(contact.getCITYPOSITION());
                    }

                    holder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                            AppData.city = holder.spinner.getSelectedItem().toString();
                            AppData.city_pos= holder.spinner.getSelectedItemPosition();
                        }
                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {

                        }
                    });

                }else{
                    holder.editText1.setTag(pos);
                    holder.editText1.setHint(arrlst.get(pos).getFieldName());
                    holder.editText1.setText(arrlst.get(pos).getValue());
                    holder.editText1.setInputType(arrlst.get(pos).getInput_type());
                }

                if (pos == 3) {

                }else {

                if(!arrlst.get(pos).getError().equalsIgnoreCase("")){
                    holder.editText1.setError(arrlst.get(pos).getError());
                    holder.editText1.requestFocus();
                }

                holder.editText1.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                    }

                    @Override
                    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                    }

                    @Override
                    public void afterTextChanged(Editable editable) {
                        Log.d("POS", "" + pos + " VAL" + editable.toString());
                        int pos = (int) holder.editText1.getTag();

                        arrlst.get(pos).setValue(editable.toString());

                    }
                });
                }
                return convertView;
            }

        }
        **Database code**

            package com.example.developer.database.helper;

        import android.content.ContentValues;
        import android.content.Context;
        import android.database.Cursor;
        import android.database.sqlite.SQLiteDatabase;
        import android.database.sqlite.SQLiteOpenHelper;
        import android.util.Log;

        import com.example.developer.database.model.Contact;

        import java.util.ArrayList;

        public class DBhelper extends SQLiteOpenHelper {

            private static String CREATE_TABLE1;

            //    Database name
            static String DATABASE_NAME = "EmployeeRecords";

            //    Talble name
            public static final String TABLE1_NAME = "employee";

            //      Fields for table
            public static final String ID = "id";
            public static final String NAME = "name";
            public static final String EMAIL = "email";
            public static final String PASSWORD = "password";
            public static final String CITY = "city";
            public static final String PHONE = "phone";
            public  static final String CITYPOS= "city_pos";

            //      Required resorces to manage database
            private ContentValues cValues;
            private SQLiteDatabase dataBase = null;
            private Cursor cursor;

            public DBhelper(Context context) {
                super(context, context.getExternalFilesDir(null).getAbsolutePath()
                        + "/" + DATABASE_NAME, null, 1);
            }
            @Override
            public void onCreate(SQLiteDatabase db) {
                CREATE_TABLE1 = "CREATE TABLE " + TABLE1_NAME +"("
                        + ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "
                        + NAME + " TEXT NOT NULL, "
                        + EMAIL + " TEXT NOT NULL, "
                        + PASSWORD + " TEXT NOT NULL, "+ CITY + " TEXT NOT NULL, "+ PHONE + " TEXT NOT NULL, "+ CITYPOS + " INTEGER) ";

                db.execSQL(CREATE_TABLE1);

            }

            @Override
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

                db.execSQL("DROP TABLE IF EXISTS " + TABLE1_NAME);

                onCreate(db);
            }

            public void inserRecord(String name, String email , String password , String city, String phone, int city_pos) {

                dataBase = getWritableDatabase();
                cValues = new ContentValues();

                cValues.put(NAME, name);
                cValues.put(EMAIL, email);
                cValues.put(PASSWORD, password);
                cValues.put(CITY, city);
                cValues.put(PHONE, phone);
                cValues.put(CITYPOS, city_pos);

                // insert data into database
                dataBase.insert(TABLE1_NAME, null, cValues);

                dataBase.close();
            }
            public void updateRecord(String name, String email ,String password , String city , String phone,int city_pos) {

                dataBase = getWritableDatabase();

                cValues = new ContentValues();

                if(name!=null) {

                    cValues.put(NAME, name);
                }
                if(email!=null) {
                    cValues.put(EMAIL, email);
                } if(password!=null) {
                    cValues.put(PASSWORD, password);
                } if(city!=null) {
                    cValues.put(CITY, city);
                } if(phone!=null) {
                    cValues.put(PHONE, phone);
                }
                    cValues.put(CITYPOS, city_pos);

        //    Update data from database table
                dataBase.update(DBhelper.TABLE1_NAME, cValues,
                        null, null);

                dataBase.close();
            }

            public ArrayList<Contact> getValues() {
                ArrayList<Contact> values = new ArrayList<Contact>();
                String selectQuery = "SELECT  * FROM " + TABLE1_NAME;
                SQLiteDatabase db = this.getReadableDatabase();
                Cursor cursor = db.rawQuery(selectQuery, null);
                if(cursor.moveToFirst()) {
                    do {
                        Contact contact = new Contact();
                        contact.setID(cursor.getString(0));
                        contact.setNAME(cursor.getString(1));
                        contact.setEMAIL(cursor.getString(2));
                        contact.setPASSWORD(cursor.getString(3));
                        contact.setCITY(cursor.getString(4));
                        contact.setPHONE(cursor.getString(5));
                        contact.setCITYPOSITION(cursor.getInt(6));
                        Log.d("jjj","ghh"+cursor);
        // Adding contact to list
                        values.add(contact);
                     //
        //  values.add(cursor.getString(cursor.getColumnInde"value")));
                    }while(cursor.moveToNext());
                }
                cursor.close();
                db.close();
                return values;
            }

            public void deleteUser(String id)
            {
                SQLiteDatabase db = this.getWritableDatabase();
                try
                {
                    db.delete(TABLE1_NAME, "ID = ?", new String[] { id });
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }
                finally
                {
                    db.close();
                }
            }

            public Contact getContact(String id) {
                SQLiteDatabase db = this.getReadableDatabase();
                Cursor cursor = db.query(TABLE1_NAME, new String[] { ID,
                                NAME, EMAIL, PASSWORD, CITY, PHONE, CITYPOS}, ID + "=?",
                        new String[] { String.valueOf(id) }, null, null, null, null);
                if (cursor != null)
                    cursor.moveToFirst();

                Contact contact = new Contact(cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getInt(6));
                Log.d("aaa","ggg"+contact);
        // return contact
                return contact;
            }

        }
        **ShowListActivityAdapter code here**

           package com.example.developer.database.adapter;

    import com.example.developer.database.model.Contact;

    import java.util.ArrayList;

    public class UserAdapter extends BaseAdapter {
        ArrayList<Contact> arrayList;
        Activity activity;
        LayoutInflater infl;
        public UserAdapter(Activity activity, ArrayList<Contact> arrayList) {
            //getting values from MainActivity
            infl = activity.getLayoutInflater();
            this.arrayList = arrayList;
            this.activity = activity;

        }
        @Override
        public int getCount() {
            Log.d("aaa", "" + arrayList.size());
            return arrayList.size();
        }

        @Override
        public Object getItem(int position) {
            return arrayList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }
        static class ViewHolder {
            TextView name;
            TextView email;
            TextView password;
            TextView city;
            TextView phone;

            public ViewHolder(View item) {
                //we have to find the id of listview to avoid viewlost
                name= (TextView)item.findViewById(R.id.name);
                email=(TextView)item.findViewById(R.id.email);
                password=(TextView)item.findViewById(R.id.password);
                city=(TextView)item.findViewById(R.id.city);
                phone=(TextView)item.findViewById(R.id.phone);

            }
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            final int pos = position;
            View view = convertView;
            final  ViewHolder holder ;
    //      view will be null for the first time only
            if (view == null) {
                view = infl.inflate(R.layout.layout1, parent, false);
                holder = new ViewHolder(view);
                view.setTag(holder);

            } else {
                holder = (ViewHolder) view.getTag();
            }
            holder.name.setText(arrayList.get(pos).getNAME());
            holder.email.setText(arrayList.get(pos).getEMAIL());
            holder.password.setText(arrayList.get(pos).getPASSWORD());
            holder.city.setText(arrayList.get(pos).getCITY());
            holder.phone.setText(arrayList.get(pos).getPHONE());

            return view;
        }
    }

    package com.example.developer.database.model;

/**
 * Created by sanjeev on 31/3/17.
 */
public class Contact {
    String fieldName, value;
    int input_type = -1;
    String city;
    String error = "";
    String NAME,EMAIL,PASSWORD,CITY,PHONE,ID;
    int CITYPOSITION;

    public Contact(String string, String string1, String string2, String string3, String string4, int pos) {
        this.NAME = string;
        this.EMAIL = string1;
        this.PASSWORD = string2;
        this.CITY = string3;
        this.PHONE = string4;
        this.CITYPOSITION = pos;
    }

    public Contact() {

    }

    public String getFieldName() {
        return fieldName;
    }

    public void setFieldName(String fieldName) {
        this.fieldName = fieldName;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public int getInput_type() {
        return input_type;
    }

    public void setInput_type(int input_type) {
        this.input_type = input_type;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getID() {
        return ID;
    }

    public void setID(String ID) {
        this.ID = ID;
    }

    public String getNAME() {
        return NAME;
    }

    public void setNAME(String NAME) {
        this.NAME = NAME;
    }

    public String getEMAIL() {
        return EMAIL;
    }

    public void setEMAIL(String EMAIL) {
        this.EMAIL = EMAIL;
    }

    public String getPASSWORD() {
        return PASSWORD;
    }

    public void setPASSWORD(String PASSWORD) {
        this.PASSWORD = PASSWORD;
    }

    public String getCITY() {
        return CITY;
    }

    public void setCITY(String CITY) {
        this.CITY = CITY;
    }

    public String getPHONE() {
        return PHONE;
    }

    public void setPHONE(String PHONE) {
        this.PHONE = PHONE;
    }

    public int getCITYPOSITION() {
        return CITYPOSITION;
    }

    public void setCITYPOSITION(int CITYPOSITION) {
        this.CITYPOSITION = CITYPOSITION;
    }

    public String getError() {
        return error;
    }

    public void setError(String error) {
        this.error = error;
    }
}
</code>```


问:
Binding a TextBlock property inside Footer control with another property inside DB window user control, but both in the same MainWindow
I have a WPF form displaying a DB data in a DataGrid. The form is simple – MainWindow with two user controls. The first user control contains the DataGrid, and the second one is a footer control, where I have a TextBlock displaying the items count. I can apply different filters to the DataGrid, so the items count will be changed at run time.

The question is how to attach Items Count from the DBview control to the Text property of TextBlock inside the Footer control?

Below is a short version of how I load the data into the DataGrid and also count the items:

```<code>private int itemsCount;

public string ItemsCount
{
    get { return itemsCount.ToString(); }
    set { itemsCount = Convert.ToInt32(value); }
}

private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
    context = new MDBEntities();

    mapInfoViewSource = ((CollectionViewSource)(this.FindResource("mapInfoViewSource")));
    IQueryable<MapInfo> mapQuery = GetMapsQuery(context);
    mapInfoViewSource.Source = mapQuery.ToList();

    itemsCount = mapInfoDataGrid.Items.Count;
}
</code>```

Below is the XAML code in the Footer control:

```<code><TextBlock x:Name="DisplayedNum" x:FieldModifier="public" Foreground="#FF569CD6" Margin="10,3,3,0"
               Text="{Binding RelativeSource={RelativeSource AncestorType={x:Type local:DBviewer}}, Path=ItemsCount}"  />
</code>```

Also, I don’t use MVVM, just a code behind. I have tried several different bindings but the TextBox stays empty. Could you please suggest a solution? Thanks.

答:
Also, I don’t use MVVM, just a code behind.

That's your main issue. There is a reason why MVVM is the recommended design pattern for XAML based UI applications and this is one of them.

If both your UserControls share the same view model, you could easily bind the TextBlock to the Count property of the source collection that is bound to the DataGrid in the other control.

You cannot bind to a property of the other control using a RelativeSource nor ElementName binding because they reside in different naming scopes.

So you will either have to re-design your application (learn and use MVVM!) or you will have to get a reference to the other control programmatically in the code-behind of the footer Control using a visual tree helper method.

Body:
I have a WPF form displaying a DB data in a DataGrid. The form is simple – MainWindow with two user controls. The first user control contains the DataGrid, and the second one is a footer control, where I have a TextBlock displaying the items count. I can apply different filters to the DataGrid, so the items count will be changed at run time.

The question is how to attach Items Count from the DBview control to the Text property of TextBlock inside the Footer control?

Below is a short version of how I load the data into the DataGrid and also count the items:

private int itemsCount;

public string ItemsCount
{
    get { return itemsCount.ToString(); }
    set { itemsCount = Convert.ToInt32(value); }
}

private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
    context = new MDBEntities();

    mapInfoViewSource = ((CollectionViewSource)(this.FindResource("mapInfoViewSource")));
    IQueryable<MapInfo> mapQuery = GetMapsQuery(context);
    mapInfoViewSource.Source = mapQuery.ToList();

    itemsCount = mapInfoDataGrid.Items.Count;
}

Below is the XAML code in the Footer control:

<TextBlock x:Name="DisplayedNum" x:FieldModifier="public" Foreground="#FF569CD6" Margin="10,3,3,0"
               Text="{Binding RelativeSource={RelativeSource AncestorType={x:Type local:DBviewer}}, Path=ItemsCount}"  />

Also, I don’t use MVVM, just a code behind. I have tried several different bindings but the TextBox stays empty. Could you please suggest a solution? Thanks.


问:
Send data between two cells from different collection views embedded in the same viewController
I have two collectionViews embedded in the same viewController and inside each collectionView I added a UISlider that control the volume of an AVAudioplayer. What I need is that when I change the value of one of the two sliders the value of the other change, the two sliders control the same AVAudioPlayer.

Edit:

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    switch collectionView {
    case mainCollectionView:
        let cell = mainCollectionView.dequeueReusableCell(withReuseIdentifier: "mainCell", for: indexPath) as! MainCell
        if cell.isSelected {
            cell.backgroundColor = UIColor.magenta
            cell.audioPlayer = indexOfAudioPlayer[indexPath]
            cell.volumeSlider.isHidden = false
        } else {
            cell.backgroundColor = colorArray[indexPath.section]
            cell.volumeSlider.isHidden = true
        }
        return cell
    case soundVolumeCollectionView:
        let cell = soundVolumeCollectionView.dequeueReusableCell(withReuseIdentifier: "soundVolumeCell", for: indexPath) as! MainCell
        cell.audioPlayer = sortedAudioPlayers[indexPath.item]
        return cell
    default:
        let cell = menuCollectionView.dequeueReusableCell(withReuseIdentifier: "menuCell", for: indexPath) as! MenuCell
        cell.backgroundColor = colorArray[indexPath.item]
        return cell
    }
}
</code>```

Both mainCollectionView and soundVolumeCollectionView are responsible for controlling the AVAudioPlayers.

答:
You should use NotificationCenter.  This isn't meant to be final code, but it should get you in the right direction.  Your MenuCell class will need to implement similar observers and send similar notifications.

```<code>class ViewController: UIViewController, UICollectionViewDataSource {
    var volume: Float {
        didSet {
            player.volume = volume
            NotificationCenter.default.post(name: Notification.Name.playerVolumeChanged, object: self, userInfo: ["volume":volume]);
        }
    }

    var player: AVAudioPlayer

    override init() {
        super.init()
        NotificationCenter.default.addObserver(self, selector: #selector(volumeChanged(_:)), name: Notification.Name.sliderChangedVolume, object: nil)
    }

    func volumeChanged(_ notification:Notification) {
        if let userInfo = notification.userInfo, let newVolume = userInfo["volume"] as? Float {
            self.volume = newVolume
        }
    }
}

extension Notification.Name {
    static let playerVolumeChanged = Notification.Name("reverse.domain.name.playerVolumeChanged")
    static let sliderChangedVolume = Notification.Name("reverse.domain.name.sliderChangedVolume")
}

class MainCell: UICollectionViewCell {

    var slider = UISlider()

    required init(frame: CGRect) {
        super.init(frame: frame)
        NotificationCenter.default.addObserver(self, selector: #selector(volumeDidChange(_:)), name: Notification.Name.playerVolumeChanged, object: nil)
        slider.addTarget(self, action: #selector(sliderChanged(_:)), for: UIControlEvents.valueChanged);
    }

    func volumeDidChange(_ notification:Notification) {
        if let userInfo = notification.userInfo, let newVolume = userInfo["volume"] as? Float {
            self.slider.value = newVolume
        }
    }

    func sliderChanged(_ slider:UISlider) {
        NotificationCenter.default.post(name: Notification.Name.sliderChangedVolume, object: self, userInfo: ["volume": slider.value])
    }

    override func prepareForReuse() {
        super.prepareForReuse()
        NotificationCenter.default.removeObserver(self, name: Notification.Name.playerVolumeChanged, object: nil)
    }
}
</code>```

Body:
I have two collectionViews embedded in the same viewController and inside each collectionView I added a UISlider that control the volume of an AVAudioplayer. What I need is that when I change the value of one of the two sliders the value of the other change, the two sliders control the same AVAudioPlayer.

Edit:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    switch collectionView {
    case mainCollectionView:
        let cell = mainCollectionView.dequeueReusableCell(withReuseIdentifier: "mainCell", for: indexPath) as! MainCell
        if cell.isSelected {
            cell.backgroundColor = UIColor.magenta
            cell.audioPlayer = indexOfAudioPlayer[indexPath]
            cell.volumeSlider.isHidden = false
        } else {
            cell.backgroundColor = colorArray[indexPath.section]
            cell.volumeSlider.isHidden = true
        }
        return cell
    case soundVolumeCollectionView:
        let cell = soundVolumeCollectionView.dequeueReusableCell(withReuseIdentifier: "soundVolumeCell", for: indexPath) as! MainCell
        cell.audioPlayer = sortedAudioPlayers[indexPath.item]
        return cell
    default:
        let cell = menuCollectionView.dequeueReusableCell(withReuseIdentifier: "menuCell", for: indexPath) as! MenuCell
        cell.backgroundColor = colorArray[indexPath.item]
        return cell
    }
}

Both mainCollectionView and soundVolumeCollectionView are responsible for controlling the AVAudioPlayers.

Body:
You should use NotificationCenter.  This isn't meant to be final code, but it should get you in the right direction.  Your MenuCell class will need to implement similar observers and send similar notifications.

class ViewController: UIViewController, UICollectionViewDataSource {
    var volume: Float {
        didSet {
            player.volume = volume
            NotificationCenter.default.post(name: Notification.Name.playerVolumeChanged, object: self, userInfo: ["volume":volume]);
        }
    }

    var player: AVAudioPlayer

    override init() {
        super.init()
        NotificationCenter.default.addObserver(self, selector: #selector(volumeChanged(_:)), name: Notification.Name.sliderChangedVolume, object: nil)
    }

    func volumeChanged(_ notification:Notification) {
        if let userInfo = notification.userInfo, let newVolume = userInfo["volume"] as? Float {
            self.volume = newVolume
        }
    }
}

extension Notification.Name {
    static let playerVolumeChanged = Notification.Name("reverse.domain.name.playerVolumeChanged")
    static let sliderChangedVolume = Notification.Name("reverse.domain.name.sliderChangedVolume")
}

class MainCell: UICollectionViewCell {

    var slider = UISlider()

    required init(frame: CGRect) {
        super.init(frame: frame)
        NotificationCenter.default.addObserver(self, selector: #selector(volumeDidChange(_:)), name: Notification.Name.playerVolumeChanged, object: nil)
        slider.addTarget(self, action: #selector(sliderChanged(_:)), for: UIControlEvents.valueChanged);
    }

    func volumeDidChange(_ notification:Notification) {
        if let userInfo = notification.userInfo, let newVolume = userInfo["volume"] as? Float {
            self.slider.value = newVolume
        }
    }

    func sliderChanged(_ slider:UISlider) {
        NotificationCenter.default.post(name: Notification.Name.sliderChangedVolume, object: self, userInfo: ["volume": slider.value])
    }

    override func prepareForReuse() {
        super.prepareForReuse()
        NotificationCenter.default.removeObserver(self, name: Notification.Name.playerVolumeChanged, object: nil)
    }
}


问:
C# Multiple Indexers
Is it possible to have something like the following:

```<code>class C
{
    public Foo Foos[int i]
    {
        ...
    }

    public Bar Bars[int i]
    {
        ...
    }
}
</code>```

If not, then are what are some of the ways I can achieve this? I know I could make functions called getFoo(int i) and getBar(int i) but I was hoping to do this with properties.

答:
There IS a way..   if you define 2 new types to alow the compiler to distinguish the two different signatures...

```<code>  public struct EmployeeId
  {
      public int val;
      public EmployeeId(int employeeId) { val = employeeId; }
  }
  public struct HRId
  {
      public int val;
      public HRId(int hrId) { val = hrId; }
  }
  public class Employee
  {
      public int EmployeeId;
      public int HrId;
      // other stuff
  }
  public class Employees: Collection<Employee>
  {
      public Employee this[EmployeeId employeeId]
      {
          get
             {
                foreach (Employee emp in this)
                   if (emp.EmployeeId == employeeId.val)
                      return emp;
                return null;
             }
      }
      public Employee this[HRId hrId]
      {
          get
             {
                foreach (Employee emp in this)
                   if (emp.HRId == hrId.val)
                      return emp;
                return null;
             }
      }
      // (or using new C#6+ "expression-body" syntax)
      public Employee this[EmployeeId empId] =>
             this.FirstorDefault(e=>e.EmployeeId == empId .val;
      public Employee this[HRId hrId] =>
             this.FirstorDefault(e=>e.EmployeeId == hrId.val;

  }
</code>```

Then to call it you would have to write:

```<code>Employee Bob = MyEmployeeCollection[new EmployeeID(34)];
</code>```

And if you wrote an implicit conversion operator:

```<code>public static implicit operator EmployeeID(int x)
{ return new EmployeeID(x); }
</code>```

then you wouldn't even have to do that to use it, you could just write:

```<code>Employee Bob = MyEmployeeCollection[34];
</code>```

Same thing applies even if the two indexers return different types...

Title: C# Multiple Indexers

Body:
Is it possible to have something like the following:

class C
{
    public Foo Foos[int i]
    {
        ...
    }

    public Bar Bars[int i]
    {
        ...
    }
}

If not, then are what are some of the ways I can achieve this? I know I could make functions called getFoo(int i) and getBar(int i) but I was hoping to do this with properties.

Body:
There IS a way..   if you define 2 new types to alow the compiler to distinguish the two different signatures...

  public struct EmployeeId
  {
      public int val;
      public EmployeeId(int employeeId) { val = employeeId; }
  }
  public struct HRId
  {
      public int val;
      public HRId(int hrId) { val = hrId; }
  }
  public class Employee
  {
      public int EmployeeId;
      public int HrId;
      // other stuff
  }
  public class Employees: Collection<Employee>
  {
      public Employee this[EmployeeId employeeId]
      {
          get
             {
                foreach (Employee emp in this)
                   if (emp.EmployeeId == employeeId.val)
                      return emp;
                return null;
             }
      }
      public Employee this[HRId hrId]
      {
          get
             {
                foreach (Employee emp in this)
                   if (emp.HRId == hrId.val)
                      return emp;
                return null;
             }
      }
      // (or using new C#6+ "expression-body" syntax)
      public Employee this[EmployeeId empId] =>
             this.FirstorDefault(e=>e.EmployeeId == empId .val;
      public Employee this[HRId hrId] =>
             this.FirstorDefault(e=>e.EmployeeId == hrId.val;

  }

Then to call it you would have to write:

Employee Bob = MyEmployeeCollection[new EmployeeID(34)];

And if you wrote an implicit conversion operator:

public static implicit operator EmployeeID(int x)
{ return new EmployeeID(x); }

then you wouldn't even have to do that to use it, you could just write:

Employee Bob = MyEmployeeCollection[34];

Same thing applies even if the two indexers return different types...

OwnerDisplayName: Charles Bretana


问:
splitting a variable number of tokens with strtok_r
I'm receiving via a named pipe commands with this format:

```<code>GETIP <machine_name> \n
<process_id>

GETNAME<ip_address> \n
<process_id>

UDATA <machine_name> <ip_address>
<process_id>

DDATA <machine_name> \n
<process_id>
</code>```

So, sample strings read from the pipe are:

```<code>GETIP lolcatzmachine
1235

UDATA cheezburger 127.0.0.1
7564
</code>```

Truthfully, I don't know what the hell I'm doing here, I'm not familiar with c tokenizing. How can I alter my code to meet the requirements?

```<code>char *token;

char *commandName [10];
char machineName[200];
char ip[40];
char pid[30];

char * separator = "  ";
char *brkt; // reentrant pointer, as this tokenizing will be multithreaded

for ( ; ; ) {

 token=strtok_r(command_and_pid, separator, &brkt); //strtok_r is needed for multithreading

 commandName = strdup(token);

    //ip=strtok_r(NULL, separator, &brkt);

   //pid=strtok_r(NULL, separator, &brkt);

  if (token == NULL)
        break;
}
</code>```

答:
Check out this. Note : didnt tested & optimized</p>

```<code>    #include <stdio.h>
#include <string.h>
#include <malloc.h>

#include "strtok.h"

//char temp[100];

char *strTok(char *string, char *delimiter)
{
    static char *inputStr = NULL;
    char *temp = NULL;
    int i,count,j;

    if (string != NULL)
    {

        if( inputStr != NULL)
            free(inputStr);

        inputStr = (char*) malloc (sizeof(char) * strlen(string));
        strcpy(inputStr,string);

    }

    for( i = 0 ; i < strlen(inputStr) ; i++ )
    {
        if ( inputStr[i] == delimiter[0] )
        {
            count = 1;
            for( j = 1 ; j < strlen(delimiter) ; j++ )
            {
                if ( inputStr[i+j] == delimiter[j] )
                    count ++;
                else
                    break;
            }
        }

        if ( count == strlen(delimiter) )
        {

            if( temp != NULL)
                free(temp);

            temp = (char*) malloc (sizeof(char) * i);

            strncpy(temp,inputStr,i);
            strcpy(inputStr,inputStr+i+strlen(delimiter));

            return temp;

        }

    }

    return inputStr;
}

/*int main()
{
    char *str = strTok("title:4:int",":");
    printf("%s\n",str);

    str = strTok(NULL,":");
    printf("%s\n",str);

    str = strTok(NULL,":");
    printf("%s\n",str);

    str = strTok(NULL,":");
    printf("%s\n",str);
    str = strTok("director:int:sdjjsd",":");
    printf("%s\n",str);

    str = strTok(NULL,":");
    printf("%s\n",str);

}*/
</code>```

Body:
I'm receiving via a named pipe commands with this format:

GETIP <machine_name> \n
<process_id>

GETNAME<ip_address> \n
<process_id>

UDATA <machine_name> <ip_address>
<process_id>

DDATA <machine_name> \n
<process_id>

So, sample strings read from the pipe are:

GETIP lolcatzmachine
1235

UDATA cheezburger 127.0.0.1
7564

Truthfully, I don't know what the hell I'm doing here, I'm not familiar with c tokenizing. How can I alter my code to meet the requirements?

char *token;

char *commandName [10];
char machineName[200];
char ip[40];
char pid[30];

char * separator = "  ";
char *brkt; // reentrant pointer, as this tokenizing will be multithreaded

for ( ; ; ) {

 token=strtok_r(command_and_pid, separator, &brkt); //strtok_r is needed for multithreading

 commandName = strdup(token);

    //ip=strtok_r(NULL, separator, &brkt);

   //pid=strtok_r(NULL, separator, &brkt);

  if (token == NULL)
        break;
}

Body:
Check out this. Note : didnt tested & optimized

    #include <stdio.h>
#include <string.h>
#include <malloc.h>

#include "strtok.h"

//char temp[100];

char *strTok(char *string, char *delimiter)
{
    static char *inputStr = NULL;
    char *temp = NULL;
    int i,count,j;

    if (string != NULL)
    {

        if( inputStr != NULL)
            free(inputStr);

        inputStr = (char*) malloc (sizeof(char) * strlen(string));
        strcpy(inputStr,string);

    }

    for( i = 0 ; i < strlen(inputStr) ; i++ )
    {
        if ( inputStr[i] == delimiter[0] )
        {
            count = 1;
            for( j = 1 ; j < strlen(delimiter) ; j++ )
            {
                if ( inputStr[i+j] == delimiter[j] )
                    count ++;
                else
                    break;
            }
        }

        if ( count == strlen(delimiter) )
        {

            if( temp != NULL)
                free(temp);

            temp = (char*) malloc (sizeof(char) * i);

            strncpy(temp,inputStr,i);
            strcpy(inputStr,inputStr+i+strlen(delimiter));

            return temp;

        }

    }

    return inputStr;
}

/*int main()
{
    char *str = strTok("title:4:int",":");
    printf("%s\n",str);

    str = strTok(NULL,":");
    printf("%s\n",str);

    str = strTok(NULL,":");
    printf("%s\n",str);

    str = strTok(NULL,":");
    printf("%s\n",str);
    str = strTok("director:int:sdjjsd",":");
    printf("%s\n",str);

    str = strTok(NULL,":");
    printf("%s\n",str);

}*/


问:
XPath doesn't work as desired in C#
My code doesn't return the node

```<code>XmlDocument xml = new XmlDocument();
xml.InnerXml = text;

XmlNode node_ =  xml.SelectSingleNode(node);
return node_.InnerText; // node_ = null !
</code>```

I'm pretty sure my XML and Xpath are correct.

My Xpath : /ItemLookupResponse/OperationRequest/RequestId

My XML :

```<code><?xml version="1.0"?>
<ItemLookupResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2005-10-05">
  <OperationRequest>
    <RequestId>xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx</RequestId>
    <!-- the rest of the xml is irrelevant -->
  </OperationRequest>
</ItemLookupResponse>
</code>```

The node my XPath returns is always null for some reason. Can someone help?

答:
Sorry for the late reply but I had a similar problem just a moment ago.

if you REALLY want to ignore that namespace then just delete it from the string you use to initialise the XmlDocument

```<code>text=text.Replace(
"<ItemLookupResponse xmlns=\"http://webservices.amazon.com/AWSECommerceService/2005-10-05\">",
"<ItemLookupResponse>");

XmlDocument xml = new XmlDocument();
xml.InnerXml = text;

XmlNode node_ =  xml.SelectSingleNode(node);
return node_.InnerText;
</code>```

Title: XPath doesn't work as desired in C#

Body:
My code doesn't return the node

XmlDocument xml = new XmlDocument();
xml.InnerXml = text;

XmlNode node_ =  xml.SelectSingleNode(node);
return node_.InnerText; // node_ = null !

I'm pretty sure my XML and Xpath are correct.

My Xpath : /ItemLookupResponse/OperationRequest/RequestId

My XML :

<?xml version="1.0"?>
<ItemLookupResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2005-10-05">
  <OperationRequest>
    <RequestId>xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx</RequestId>

  </OperationRequest>
</ItemLookupResponse>

The node my XPath returns is always null for some reason. Can someone help?

Body:
Sorry for the late reply but I had a similar problem just a moment ago.

if you REALLY want to ignore that namespace then just delete it from the string you use to initialise the XmlDocument

text=text.Replace(
"<ItemLookupResponse xmlns=\"http://webservices.amazon.com/AWSECommerceService/2005-10-05\">",
"<ItemLookupResponse>");

XmlDocument xml = new XmlDocument();
xml.InnerXml = text;

XmlNode node_ =  xml.SelectSingleNode(node);
return node_.InnerText;


问:
Laravel - Email Attachment Undefined variable
I have three files a user can upload but the issue is if an image isn't attached it throws an Undefined variable error, because nothing is being passed through, the main issue is that attachments are defined via the url, so when I add a null value or a '' to it, it throws a timeout error.

is there a better way/approach to tackling this?

```<code>if ($request->file('img_1')) {
            $file = $request->file('img_1');
            $image_name1 = time()."-".$file->getClientOriginalName();

            if ($file->move('uploads/quote', $image_name1)) {
                $enquiry->img_1 = $image_name1;
                $enquiry->save();
            }
        }else{
            $image_name1 = '';
        }
</code>```

Here's the function I used after this

```<code>function ($message) use ($request, $image_name1, $image_name2, $image_name3) {

                $name_input = $request['name'];
                $company_name = 'Test';

                $message->to($sendto_email, '')->from('alerts@testing.com', 'Quote')->subject('New Quote from ' . $name_input )->attach('uploads/quote/' . $image_name1)->attach('uploads/quote/' . $image_name2)->attach('uploads/quote/' . $image_name3);
        });
</code>```

EDIT:
It's mainly the $message-to part, finding a way to not add the ->attach IF a specific image isn't selected/isn't set

答:
Well, you can use array-variable to put it in a use to avoid 'undefined error':</p>

```<code>$images = [$image_name1, $image_name2, $image_name3];

function ($message) use ($request, $images) {

    $name_input = $request['name'];
    $company_name = 'Test';

    $message->to($sendto_email, '')->from('alerts@testing.com', 'Quote')->subject('New Quote from ' . $name_input);

    foreach ($images as $image) {
        $message->attach('uploads/quote/' . $image);
    }
</code>```

Body:
I have three files a user can upload but the issue is if an image isn't attached it throws an Undefined variable error, because nothing is being passed through, the main issue is that attachments are defined via the url, so when I add a null value or a '' to it, it throws a timeout error.

is there a better way/approach to tackling this?

if ($request->file('img_1')) {
            $file = $request->file('img_1');
            $image_name1 = time()."-".$file->getClientOriginalName();

            if ($file->move('uploads/quote', $image_name1)) {
                $enquiry->img_1 = $image_name1;
                $enquiry->save();
            }
        }else{
            $image_name1 = '';
        }

Here's the function I used after this

function ($message) use ($request, $image_name1, $image_name2, $image_name3) {

                $name_input = $request['name'];
                $company_name = 'Test';

                $message->to($sendto_email, '')->from('alerts@testing.com', 'Quote')->subject('New Quote from ' . $name_input )->attach('uploads/quote/' . $image_name1)->attach('uploads/quote/' . $image_name2)->attach('uploads/quote/' . $image_name3);
        });

EDIT:
It's mainly the $message-to part, finding a way to not add the ->attach IF a specific image isn't selected/isn't set

Body:
Well, you can use array-variable to put it in a use to avoid 'undefined error':

$images = [$image_name1, $image_name2, $image_name3];

function ($message) use ($request, $images) {

    $name_input = $request['name'];
    $company_name = 'Test';

    $message->to($sendto_email, '')->from('alerts@testing.com', 'Quote')->subject('New Quote from ' . $name_input);

    foreach ($images as $image) {
        $message->attach('uploads/quote/' . $image);
    }


问:
What is the difference between an identifier and variable?
I'm a bit confused about identifiers.  In my textbook it says, "We use identifiers to name variables (and many other things) in Java."

I'm not really sure what this means. Is it like assigning a variable...to a variable? What?

So far, I'm getting this impression:

```<code>int a, b, c; a = 2; b = 99; c = a + b;
</code>```

Is c an identifier? When it says, "Using identifiers to name variables," are identifiers like int, double, boolean, things used to categorize variables?  Please provide some examples.

答:
Identifiers are names given to things in Java. This includes variables, methods, classes, etc. So, technically a variable is an identifier.
see: https://www.cs.umd.edu/~clin/MoreJava/Intro/var-ident.html

Regarding your confusion on "I'm not really sure what this means. Is it like assigning a variable...to a variable? What?" --> the correct way of saying is: Assigning a "name" to variable (what name would you like for a variable).

Body:
I'm a bit confused about identifiers.  In my textbook it says, "We use identifiers to name variables (and many other things) in Java."

I'm not really sure what this means. Is it like assigning a variable...to a variable? What?

So far, I'm getting this impression:

int a, b, c; a = 2; b = 99; c = a + b;

Is c an identifier? When it says, "Using identifiers to name variables," are identifiers like int, double, boolean, things used to categorize variables?  Please provide some examples.


问:
What is the first character in the sort order used by Windows Explorer?
For example, in a Windows folder, if we create some files and name them 1.html, 2.txt, 3.txt, photo.jpg, zen.png the order will be as is. But if we create another file with the name _file.doc it will be placed at the top. (considering we sort by name in descending order)

likewise, what would be the character that would be considered as the first, such that if i use that character, it would place the file on top of the hierarchy?

答:
If you google for sort order windows explorer you will find out that Windows Explorer (since Windows XP) obviously uses the function StrCmpLogicalW in the sort order "by name". I did not find information about the treatment of the underscore character. I was amused by the following note in the documentation:

Behavior of this function, and therefore the results it returns, can change from release to release. ...


问:
Values for Principal and SecretAlias ID in PGP encryption
While configuring PGP encryption what values we have to pass for principal and Secret Alias ID.

答:
In PGP encryption principal is nothing but the username in the key that is it is a combination of name and email ID you specified while generating the keys
ex: smith .
 and coming to Secret alias ID GPA tool does not provide this value.we have to provide some random value, deploy application and run your flow.Mule will throw an exception in the console you can also the list of keys that is Secret Alias ID that what we want.In console we can find suggested Secret Alias ID like this </p>


问:
Variable variables in PHP allow for illegal variable names?
I found what appears to be an abusable bug in the PHP language. When creating variable variables a seemingly illegal variable can be declared and then handled as long as you keep accessing it as a variable variable.
Example:

```<code>${'0'} = 1;         //I am an illegal variable called $0
${'0'}++;           //I can be accessed and manipulated.
var_dump(${'0'});   //Output: int(2)
</code>```

This behavior appears rather odd. It is briefly mentioned in the official documentation for SimpleXml as a way to create variable names that contain hyphens but my example shows it can be abused pretty badly nonetheless.

I would like to know how come this behavior is possible and is tolerated when the code is parsed?

答:
Internally PHP stores variables (zend_array* symbol_table) in a same data structure that is used for arrays. This allows you to have variable names with the same constraints as array keys.

Eg. Zend API function zend_set_local_var sets a value to symbol table using zend_hash_update, which is a function used to manipulate PHP array types as well.

We can't however allow every character in variable names in PHP source code. That's because lexical analysis must distinguish labels from other tokens. Variable variables offer a workaround for this.

It's not a bug nor a way to abuse anything. That being said, the documentation states that all labels, including variables, must have a regex form [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*, so i wouldn't rely on having arbitrary characters in variable names.

What ${'0'} = 1; actually does, it sets value 1 to the current scope's symbol table at key 0.
You can get that particular table with get_defined_vars function.
Looking at the source code, we'll see that the function just copies the current symbol table and returns it to caller.

PHP extract function (src) actually checks that keys have a valid label format (by calling php_valid_var_name), so you can't generate variables with funky names using that.

Anyway, even though it's possible to create variables of any name using variable variable syntax (even a variable with no name ${''}), i think it's bad practice. Even worse if a library expects or enforces you to do so. Saying it's a workaround might be a bit overstatement actually. Maybe it should be considered as an implementation detail and an undocumented feature.

Body:
I found what appears to be an abusable bug in the PHP language. When creating variable variables a seemingly illegal variable can be declared and then handled as long as you keep accessing it as a variable variable.
Example:

${'0'} = 1;         //I am an illegal variable called $0
${'0'}++;           //I can be accessed and manipulated.
var_dump(${'0'});   //Output: int(2)

This behavior appears rather odd. It is briefly mentioned in the official documentation for SimpleXml as a way to create variable names that contain hyphens but my example shows it can be abused pretty badly nonetheless.

I would like to know how come this behavior is possible and is tolerated when the code is parsed?


问:
Add a heavily nested dictioary to MongoDB preserving its format
I pulled some data from the Facebook GraphAPI using python and saved it to a variable. The API returns JSON which is saved as a nested dictionary in Python. This is what the data from the API looks like in the browser.

Python dict looks like this :

I want mongoDB to store the data in the sane JSON format as returned by the FB API. Is that possible ?

Code :

```<code>import facebook

graph = facebook.GraphAPI(access_token='my_token', version='2.7')

post = graph.get_object(id='me/friends', fields='feed{message,story,story_tags,created_time,id,message_tags},posts{message,story,story_tags,message_tags,created_time,id},name')
print(post)
</code>```

Any help please.

答:
Yes:

```<code>from pymongo import MongoClient
db = MongoClient().test
db.collection.insert_one(post)
</code>```

The PyMongo tutorial is a good way to learn Python and MongoDB.

Body:
I pulled some data from the Facebook GraphAPI using python and saved it to a variable. The API returns JSON which is saved as a nested dictionary in Python. This is what the data from the API looks like in the browser.

Python dict looks like this :

I want mongoDB to store the data in the sane JSON format as returned by the FB API. Is that possible ?

Code :

import facebook

graph = facebook.GraphAPI(access_token='my_token', version='2.7')

post = graph.get_object(id='me/friends', fields='feed{message,story,story_tags,created_time,id,message_tags},posts{message,story,story_tags,message_tags,created_time,id},name')
print(post)

Any help please.

Body:
Yes:

from pymongo import MongoClient
db = MongoClient().test
db.collection.insert_one(post)

The PyMongo tutorial is a good way to learn Python and MongoDB.


问:
How do you reload your environment while using script/console?
I think I have seen Ryan Bates do it one of his screencasts, but I can't find it.

I believe there is a command you can run while in script/console that lets you reload your models (if say you have made a change) so that you dont have to exit and then recall the console.

Any Ideas?

答:
If you are using rspec use </p>

```<code>load 'some_class.rb'
</code>```

Body:
If you are using rspec use

load 'some_class.rb'


问:
width and height of image are zero because of asynchronous image loading in objective c iOS
i am trying to get image width and height out of dispatch_async function but it gives zero result.

Below is my code

```<code>dispatch_async(dispatch_get_main_queue(), ^{
                NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://url%@",[[arrayEvents objectAtIndex:j] valueForKey:@"image"]]]];

                //NSData *imageData = [NSData dataWithContentsOfURL:url];
                UIImage *images = [[UIImage alloc]initWithData:imageData];
                CGFloat height = images.size.height;
                CGFloat width = images.size.width;
                ratio_2=scrrenwidth/width;
                scaledHeight_2=height*ratio_2;

                 img_vw2.image=[UIImage imageWithData:imageData];

 });

 NSLog(@"%f",scaledHeight_2);
</code>```

When I print Inside the dispatch_async I got correct Image height and width but when I print outside the dispatch_async it gives me 0 as a value.

Thanks in advance

答: if your NSLog call is immediately after the dispatch_async, then it will always show zero - just move that print to inside the completion handler

Body:
i am trying to get image width and height out of dispatch_async function but it gives zero result.

Below is my code

dispatch_async(dispatch_get_main_queue(), ^{
                NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://url%@",[[arrayEvents objectAtIndex:j] valueForKey:@"image"]]]];

                //NSData *imageData = [NSData dataWithContentsOfURL:url];
                UIImage *images = [[UIImage alloc]initWithData:imageData];
                CGFloat height = images.size.height;
                CGFloat width = images.size.width;
                ratio_2=scrrenwidth/width;
                scaledHeight_2=height*ratio_2;

                 img_vw2.image=[UIImage imageWithData:imageData];

 });

 NSLog(@"%f",scaledHeight_2);

When I print Inside the dispatch_async I got correct Image height and width but when I print outside the dispatch_async it gives me 0 as a value.

Thanks in advance


问:
How to prevent Vue.js from automatically merging CSS classes?
I recently started working with Vue.js and I really enjoy it but I have come across something that I just can't figure out how to do. I have searched and read the documentation but found no solution.

When you add a CSS class to any of your components Vue.js will automatically add or merge the CSS classes with the root element in your child component.

This is a nice feature but I need to deactivate this feature for a specific component since I want the classes to be added to a child element of the root element.

I made this fiddle to illustrate http://jsfiddle.net/rasmuswoelk/9m2j0a9s/3

```<code><div id="demo">
  <child-component class="some-class"></child-component>
</div>
</code>```

(The "some-class" is being added automatically and adds a green background color)

How can I prevent Vue.js from automatically merging CSS classes?

答:
Updated
I disagree that it is intuitive to have a class that is applied to a component be moved by that component to an inner element, so my recommendation is still: Pass it as a prop.

However, it is possible to do what you want to do, with some caveats. The component will have a list of classes that belong on the outer element. In mounted, it looks at $el.classList and finds the classes that are not among the known outer element classes. Those get applied to the inner element and removed from the outer element. Caveat: if one of the outer element classes is applied to the component, it will not be moved to the inner element. And any updates to the applied class will not be caught.

Vue.component('child-component', {
  template: `<div :class="outerClasses"><h1 :class="childClasses">Hello</h1></div>`,
  data() {
    return {
      outerClasses: ['child'],
      childClasses: []
    };
  },
  mounted() {
    this.childClasses = Array.from(this.$el.classList).filter((c) => !this.outerClasses.includes(c));
    for (const c of this.childClasses) this.$el.classList.remove(c);
  }
});

var demo = new Vue({
  el: '#demo'
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.child {
  border: 1px solid red;
  padding: 20px;
  text-align: center;
}

.some-class {
  background-color: green;
}</code>```

  <child-component class="some-class a b c"></child-component>

```

Body:
I recently started working with Vue.js and I really enjoy it but I have come across something that I just can't figure out how to do. I have searched and read the documentation but found no solution.

When you add a CSS class to any of your components Vue.js will automatically add or merge the CSS classes with the root element in your child component.

This is a nice feature but I need to deactivate this feature for a specific component since I want the classes to be added to a child element of the root element.

I made this fiddle to illustrate http://jsfiddle.net/rasmuswoelk/9m2j0a9s/3

  <child-component class="some-class"></child-component>

(The "some-class" is being added automatically and adds a green background color)

How can I prevent Vue.js from automatically merging CSS classes?

Body:
Updated
I disagree that it is intuitive to have a class that is applied to a component be moved by that component to an inner element, so my recommendation is still: Pass it as a prop.

However, it is possible to do what you want to do, with some caveats. The component will have a list of classes that belong on the outer element. In mounted, it looks at $el.classList and finds the classes that are not among the known outer element classes. Those get applied to the inner element and removed from the outer element. Caveat: if one of the outer element classes is applied to the component, it will not be moved to the inner element. And any updates to the applied class will not be caught.

Vue.component('child-component', {
  template: `<div :class="outerClasses"><h1 :class="childClasses">Hello</h1></div>`,
  data() {
    return {
      outerClasses: ['child'],
      childClasses: []
    };
  },
  mounted() {
    this.childClasses = Array.from(this.$el.classList).filter((c) => !this.outerClasses.includes(c));
    for (const c of this.childClasses) this.$el.classList.remove(c);
  }
});

var demo = new Vue({
  el: '#demo'
});

.child {
  border: 1px solid red;
  padding: 20px;
  text-align: center;
}

.some-class {
  background-color: green;
}

<script src="//vuejs.org/js/vue.min.js"></script>
<div id="demo">
  <child-component class="some-class a b c"></child-component>
</div>


问:
Piped input for `bc` division generates random numbers
I've got two files formatted in this way:

File1:

```<code>word token occurence
</code>```

File2:

```<code>token occurence
</code>```

What I want is a third file with this output:

```<code>word token occurrence1/occurence2
</code>```

This is my code:

```<code>while read token pos count
do
    #get pos counts
    poscount=$(grep "^$pos" $2 | cut -f 2)
    #calculate probability
    prob=$(echo "scale=5;$count / $poscount" | bc -l)
    #print token, pos-tag & probability
    echo -e "$token\t$pos\t$prob"
done < $1
</code>```

The problem is that my output is something like this:

```<code>-   :   .25000
:   :   .75000
'   ''  1.00000
0   CD  .00396
1000    CD  .00793
13  CD  .00793
13th    JJ  .00073
36
29
16  CD  .00396
17  CD  .00396
</code>```

There are lines with numbers that I don't know where they come from, they are not in the previous files.

Why do these numbers appear?  Is there a way to remove those lines?
Thanks in advance!

答:
Method using paste, cut, & dc:

```<code>echo "5 k $(paste file[12] | cut -f 3,5) / p" | dc | \
paste file1 - | cut --complement -f 3
</code>```

Method using bash, paste & dc:

```<code>paste <(join -1 2 file1 -2 1 file2 -o 1.1,1.2)  \
  <(echo "5 k $(join -1 2 file1 -2 1 file2 -o 1.3,2.2) / p" | dc)
</code>```

Body:
I've got two files formatted in this way:

File1:

word token occurence

File2:

token occurence

What I want is a third file with this output:

word token occurrence1/occurence2

This is my code:

while read token pos count
do
    #get pos counts
    poscount=$(grep "^$pos" $2 | cut -f 2)
    #calculate probability
    prob=$(echo "scale=5;$count / $poscount" | bc -l)
    #print token, pos-tag & probability
    echo -e "$token\t$pos\t$prob"
done < $1

The problem is that my output is something like this:

-   :   .25000
:   :   .75000
'   ''  1.00000
0   CD  .00396
1000    CD  .00793
13  CD  .00793
13th    JJ  .00073
36
29
16  CD  .00396
17  CD  .00396

There are lines with numbers that I don't know where they come from, they are not in the previous files.

Why do these numbers appear?  Is there a way to remove those lines?
Thanks in advance!

Body:
Method using paste, cut, & dc:

echo "5 k $(paste file[12] | cut -f 3,5) / p" | dc | \
paste file1 - | cut --complement -f 3

Method using bash, paste & dc:

paste <(join -1 2 file1 -2 1 file2 -o 1.1,1.2)  \
  <(echo "5 k $(join -1 2 file1 -2 1 file2 -o 1.3,2.2) / p" | dc)


问:
trigger a function when button clicked, through socket.io
I have the following node server and index.html file, when i open the index.html file in multiple tabs or windows in browser and when i click the button it shows button clicked in all the opened tabs and windows but the button colour does not change in all the tabs it only changes in tab in which the button was clicked.

app.js

```<code>const io = require('socket.io')(3000);
io.on('connection', function (socket) {
    console.log('a client has connected');
    socket.on('clicked', function() {
        io.emit('clicked');
    });

});

console.log('socket.io server started at port 3000');
</code>```

index.html

```<code><!doctype html>
  <html>
    <head>
      <title>Testing socket.io</title>
      </head>
    <body>
      <input type="button" id="button" style="width: 100px; padding: 10px; box-shaddow: 10px 6px 5px; #999999; -webkit-box-shadow: 6px 6px 5px #999999; -moz-box-shadow: 6px 6px 5px #999999; font-weight: bold; background: #16ed07; color: #000000; cursor: pointer; border-radius: 10px; border: 1px solid #D9D9D9; font-size: 150%;" value="Send!" onClick="onClickHandler(this)"/>
      <h2 id="alert"> waiting...</h2>

      <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.min.js"></script>
      <script>
        var socket = io("http://localhost:3000");
        socket.on('connect', function() {
          document.getElementById("button").addEventListener("click", function () {
              socket.emit("clicked");
          });

         });
        socket.on('clicked', function() {
          console.log('clicked');
          document.getElementById("alert").innerHTML = "send clicked";
        });

      </script>

       <script type="text/javascript">
function onClickHandler(elem) {
elem.style.background = 'red';
elem.style.color = 'black';
}
</script>

    </body>
  </html>
</code>```

答:
Add "onClickHandler" call to "clicked" event callback, like:</p>

```<code>socket.on('clicked', function() {
  var button = document.getElementById('button');

  console.log('clicked');
  document.getElementById("alert").innerHTML = "send clicked";

  onClickHandler(button);
});
</code>```

Body:
I have the following node server and index.html file, when i open the index.html file in multiple tabs or windows in browser and when i click the button it shows button clicked in all the opened tabs and windows but the button colour does not change in all the tabs it only changes in tab in which the button was clicked.

app.js

const io = require('socket.io')(3000);
io.on('connection', function (socket) {
    console.log('a client has connected');
    socket.on('clicked', function() {
        io.emit('clicked');
    });

});

console.log('socket.io server started at port 3000');

index.html

<!doctype html>

      <title>Testing socket.io</title>

      <input type="button" id="button" style="width: 100px; padding: 10px; box-shaddow: 10px 6px 5px; #999999; -webkit-box-shadow: 6px 6px 5px #999999; -moz-box-shadow: 6px 6px 5px #999999; font-weight: bold; background: #16ed07; color: #000000; cursor: pointer; border-radius: 10px; border: 1px solid #D9D9D9; font-size: 150%;" value="Send!" onClick="onClickHandler(this)"/>

 waiting...

Body:
Add "onClickHandler" call to "clicked" event callback, like:

socket.on('clicked', function() {
  var button = document.getElementById('button');

  console.log('clicked');
  document.getElementById("alert").innerHTML = "send clicked";

  onClickHandler(button);
});


问:
Hide separator line on one UITableViewCell
I'm customizing a UITableView. I want to hide the line separating on the last cell ... can i do this?

I know I can do tableView.separatorStyle = UITableViewCellStyle.None but that would affect all the cells of the tableView. I want it to only affect my last cell.

答:
Swift:

```<code>public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    ...

    // remove separator for last cell
    cell.separatorInset = indexPath.row < numberOfRowsInSection-1
        ? tableView.separatorInset
        : UIEdgeInsets(top: 0, left: tableView.bounds.size.width, bottom: 0, right: 0)

    return cell
}
</code>```

Objective-C:

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView
     cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    ...

    // remove separator for last cell
    cell.separatorInset = (indexPath.row < numberOfRowsInSection-1)
        ? tableView.separatorInset
        : UIEdgeInsetsMake(0.f, tableView.bounds.size.width, 0.f, 0.f);

    return cell;
}
</code>```

Body:
Swift:

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    ...

    // remove separator for last cell
    cell.separatorInset = indexPath.row < numberOfRowsInSection-1
        ? tableView.separatorInset
        : UIEdgeInsets(top: 0, left: tableView.bounds.size.width, bottom: 0, right: 0)

    return cell
}

Objective-C:

- (UITableViewCell *)tableView:(UITableView *)tableView
     cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    ...

    // remove separator for last cell
    cell.separatorInset = (indexPath.row < numberOfRowsInSection-1)
        ? tableView.separatorInset
        : UIEdgeInsetsMake(0.f, tableView.bounds.size.width, 0.f, 0.f);

    return cell;
}


问:
Does ArangoDB supports cross-building for ARMv5?
My target is an ARMv5 CPU, so I have to find out an nosql suits running it. The MongoDB stopped supports for ARMv5, so I come to ArangoDB.  Does it allow me cross-build and run on ARMv5?  Does anyone has some experience on this job?

Thanks in advance.
-woody

答:
Sorry, no arangodb doesn't scale down to this target. Its V8 dependency will require ARMV7 at least.

For the ARM7 target will compile, but is currently not working completely.

However you can access it via a simple HTTP client - so a Client/Server architecture may better suit your needs.

For Embedded targets of that size SQLite tends to be the best solution.