问:
Angular UI router permissions / access control
I am having a lot of trouble determining how to add permissions / access-control to our Angular app. Right now we have this:

```<code>    app.config(['$stateProvider', function ($stateProvider) {

      $stateProvider

      .state('default', {
        url: '',
        templateUrl: 'pages/home/view/home.html',
        controller: 'HomeCtrl'
      })

      .state('home', {
        url: '/home',
        templateUrl: 'pages/home/view/home.html',
        controller: 'HomeCtrl',

        permissions: {                    // ?
          only: ['Admin','Moderator']
        },

        access: {                         // ?
         roles: ['*']
        },

        resolve: {                        // ?
          authenticate: function($state, $q, $timeout){

          },

        }

      })

}]);
</code>```

I having trouble determining which methodology to use to create access control to each page.

Right now, the logged in user is stored in an Angular value:

```<code>app.value('USER', JSON.parse('{{{user}}}'));
</code>```

The USER value contains the information about which roles / permissions the user has.

But I cannot inject USER into app.config() callback, it says "unknown provider".

How can I do access-control based of the USER parameters?

答: You might want to check out ngAA, I use it alongside ui-router.</p>

Body:
I am having a lot of trouble determining how to add permissions / access-control to our Angular app. Right now we have this:

    app.config(['$stateProvider', function ($stateProvider) {

      $stateProvider

      .state('default', {
        url: '',
        templateUrl: 'pages/home/view/home.html',
        controller: 'HomeCtrl'
      })

      .state('home', {
        url: '/home',
        templateUrl: 'pages/home/view/home.html',
        controller: 'HomeCtrl',

        permissions: {                    // ?
          only: ['Admin','Moderator']
        },

        access: {                         // ?
         roles: ['*']
        },

        resolve: {                        // ?
          authenticate: function($state, $q, $timeout){

          },

        }

      })

}]);

I having trouble determining which methodology to use to create access control to each page.

Right now, the logged in user is stored in an Angular value:

app.value('USER', JSON.parse('{{{user}}}'));

The USER value contains the information about which roles / permissions the user has.

But I cannot inject USER into app.config() callback, it says "unknown provider".

How can I do access-control based of the USER parameters?


来源: stackexchange

问:
external table with partitions in hive
I have a bunch of tsv files in HDFS in a directory structure that follows the partition convention where an event_dt is the partition.

```<code>some_path/event_dt=2017-04-30
some_path/event_dt=2017-05-01
</code>```

and so on.

The issue is that event_dt is also one of the columns. The second one in particular.  But I cannot specify so since event_dt cannot appear in the table schema and in the PARTITIONED BY statement. That triggers:

```<code> Column repeated in partitioning columns
</code>```

Is there a way around this other than using different names. It is, after all, the same information.

答:
3 options if you dont want to rename the column.

If your event_dt is the last column in your csv, you create the table excluding this column.

During the ingestion process exclude this information of your data, transforming the data from one place to another where the target table is partitioned by even_dt (not the most efficient way)

create a view on top of your table excluding one of the columns, anyway the original table will need the rename .

ContentLicense: CC BY-SA 3.0

Title: external table with partitions in hive

Body:
I have a bunch of tsv files in HDFS in a directory structure that follows the partition convention where an event_dt is the partition.

some_path/event_dt=2017-04-30
some_path/event_dt=2017-05-01

and so on.

The issue is that event_dt is also one of the columns. The second one in particular.  But I cannot specify so since event_dt cannot appear in the table schema and in the PARTITIONED BY statement. That triggers:

 Column repeated in partitioning columns

Is there a way around this other than using different names. It is, after all, the same information.


问:
How to solve this issue: actual and formal argument lists differ in length
I´m trying to put setResult in adapter class, but I get the following error:

Error:(79, 59) error: constructor ActivityAdapter in class
  ActivityAdapter cannot be applied to given types;

required: MainActivity,Context,ArrayList<Adicional>

found: Context,ArrayList<Adicional>

reason: actual and formal argument lists
  differ in length.

I include some parameters in viewholder and after this occurred errors. Sorry about my English.

```<code>My Activity
public class MainActivity extends AppCompatActivity {
    RecyclerView rvAdicional;
    String idComidaad, addic;
    final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity);

        rvAdicional = (RecyclerView) findViewById(R.id.t1_1_1_1recyclerview);
        rvAdicional.setHasFixedSize(true);

        LinearLayoutManager manager = new LinearLayoutManager(this);

        rvAdicional.setLayoutManager(manager);

        Intent intent = getIntent();
        if(intent != null) {
            Bundle params = intent.getExtras();
            if (params != null) {
                idComidaad = getIntent().getExtras().getString("CMD");

                String addd = params.getString("A1_1_1QTD");
                TextView addtv = (TextView) findViewById(R.id.textViewttt);

                addtv.setText(addd);

       /* if (getIntent().getSerializableExtra("RESTAURANTE_INTENTI") != null) {*/

                // Comida selectedRestaurante = (Comida) getIntent().getSerializableExtra("RESTAURANTE");
                //Comida selectedRestaurante = (Comida) intent.getSerializableExtra("RESTAURANTE");
                String url3 = "http://192.168.1.38:8085/apeti/adicional.php?id=" + idComidaad;
                StringRequest stringRequest = new StringRequest(Request.Method.GET,
                        url3,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                Log.d(TAG, response);

                                ArrayList<Adicional> adicionalList = new JsonConverter<Adicional>()
                                        .toArrayList(response, Adicional.class);

                                 Adapter adapter = new  Adapter(getApplicationContext(), adicionalList);

                                rvAdicional.setAdapter(adapter);

                            }
                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                if (error != null) {
                                    Log.d(TAG, error.toString());
                                    Toast.makeText(getApplicationContext(), "Alguma coisa deu errado com a sua requisição.", Toast.LENGTH_LONG).show();
                                }
                            }
                        }
                );
                MySingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
            }
        }
        }
    @Override
    protected  void onPause() {
        super.onPause();
        finish();
    }
}
</code>```

Adapter:

```<code>public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> {
    private Context context;
    private ArrayList<Adicional> itemList;

    private MainActivity mActivity;

    public Adapter(MainActivity mActivity, Context context, ArrayList<Adicional> itemList){
        this.context = context;
        this.itemList = itemList;

        this.mActivity= mActivity;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View view = inflater.from(parent.getContext())
                .inflate(R.layout.card, parent, false);

        MyViewHolder itemViewHolder = new MyViewHolder(view,mActivity);
        return itemViewHolder;
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, int position) {
      final Adicional adicional = itemList.get(position);

        holder.tvAdicional.setText(adicional.adicional);
        holder.tvPreco.setText((String.format("R$ %.2f",adicional.valorad)).toString().replace(".",","));
        holder.idCmd.setText(adicional.idrestaurante);

        holder.current_number = 0;

        holder.tvQtdcd.setText("" + holder.current_number);

      holder.addItemcd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (holder.current_number < 10) {
                    holder.current_number++;
                }
                holder.tvQtdcd.setText("" + holder.current_number);
            }
        });

        holder.removeItemcd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (holder.current_number > 0) {
                    holder.current_number--;
                }
                holder.tvQtdcd.setText("" + holder.current_number);
            }
        });

        holder.btnadd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(holder.current_number == 0){
                    Toast.makeText(context,"Selecione a quantidade para o adicional desejado",Toast.LENGTH_LONG).show();}
                else{

                    Intent intent = new Intent();
                    intent.putExtra("msg", "Aceitou");

                    mActivity.setResult(1, intent);
                    mActivity.finish();
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        if(itemList != null){
            return itemList.size();
        }
        return 0;
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder{
        public CardView cvItem;
        public TextView tvAdicional; public TextView tvPreco; public TextView idCmd; public TextView addItemcd; public TextView removeItemcd; public TextView tvQtdcd;
        public Button btnadd;

        int current_number;

        private MainActivity mActivity;
        public MyViewHolder(View itemView, MainActivity mActivity) {
            super(itemView);
            cvItem = (CardView)itemView.findViewById(R.id.t1_1_1_1card_view);
            tvAdicional = (TextView)itemView.findViewById(R.id.t1_1_1_1addcard);
            tvPreco = (TextView)itemView.findViewById(R.id.t1_1_1_1precocard);
            addItemcd =(TextView) itemView.findViewById(R.id.add_itemcard);
            removeItemcd  =(TextView) itemView.findViewById(R.id.remove_itemcard);
            tvQtdcd = (TextView) itemView.findViewById(R.id.iteam_amountcard);
            idCmd = (TextView) itemView.findViewById(R.id.tvidcmdd);
            btnadd = (Button) itemView.findViewById(R.id.t1_1_1_1btnadd);

            this.mActivity=mActivity;
        }
    }
}
</code>```

答:
You given wrong parameter in your adapter class constructer.

Change Below line in your MainActivity Class:

```<code>Adapter adapter = new  Adapter(MainActivity,getApplicationContext(), adicionalList);
</code>```

Body:
I´m trying to put setResult in adapter class, but I get the following error:

Error:(79, 59) error: constructor ActivityAdapter in class
  ActivityAdapter cannot be applied to given types;

required: MainActivity,Context,ArrayList<Adicional>

found: Context,ArrayList<Adicional>

reason: actual and formal argument lists
  differ in length.

I include some parameters in viewholder and after this occurred errors. Sorry about my English.

My Activity
public class MainActivity extends AppCompatActivity {
    RecyclerView rvAdicional;
    String idComidaad, addic;
    final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity);

        rvAdicional = (RecyclerView) findViewById(R.id.t1_1_1_1recyclerview);
        rvAdicional.setHasFixedSize(true);

        LinearLayoutManager manager = new LinearLayoutManager(this);

        rvAdicional.setLayoutManager(manager);

        Intent intent = getIntent();
        if(intent != null) {
            Bundle params = intent.getExtras();
            if (params != null) {
                idComidaad = getIntent().getExtras().getString("CMD");

                String addd = params.getString("A1_1_1QTD");
                TextView addtv = (TextView) findViewById(R.id.textViewttt);

                addtv.setText(addd);

       /* if (getIntent().getSerializableExtra("RESTAURANTE_INTENTI") != null) {*/

                // Comida selectedRestaurante = (Comida) getIntent().getSerializableExtra("RESTAURANTE");
                //Comida selectedRestaurante = (Comida) intent.getSerializableExtra("RESTAURANTE");
                String url3 = "http://192.168.1.38:8085/apeti/adicional.php?id=" + idComidaad;
                StringRequest stringRequest = new StringRequest(Request.Method.GET,
                        url3,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                Log.d(TAG, response);

                                ArrayList<Adicional> adicionalList = new JsonConverter<Adicional>()
                                        .toArrayList(response, Adicional.class);

                                 Adapter adapter = new  Adapter(getApplicationContext(), adicionalList);

                                rvAdicional.setAdapter(adapter);

                            }
                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                if (error != null) {
                                    Log.d(TAG, error.toString());
                                    Toast.makeText(getApplicationContext(), "Alguma coisa deu errado com a sua requisição.", Toast.LENGTH_LONG).show();
                                }
                            }
                        }
                );
                MySingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
            }
        }
        }
    @Override
    protected  void onPause() {
        super.onPause();
        finish();
    }
}

Adapter:

public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> {
    private Context context;
    private ArrayList<Adicional> itemList;

    private MainActivity mActivity;

    public Adapter(MainActivity mActivity, Context context, ArrayList<Adicional> itemList){
        this.context = context;
        this.itemList = itemList;

        this.mActivity= mActivity;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View view = inflater.from(parent.getContext())
                .inflate(R.layout.card, parent, false);

        MyViewHolder itemViewHolder = new MyViewHolder(view,mActivity);
        return itemViewHolder;
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, int position) {
      final Adicional adicional = itemList.get(position);

        holder.tvAdicional.setText(adicional.adicional);
        holder.tvPreco.setText((String.format("R$ %.2f",adicional.valorad)).toString().replace(".",","));
        holder.idCmd.setText(adicional.idrestaurante);

        holder.current_number = 0;

        holder.tvQtdcd.setText("" + holder.current_number);

      holder.addItemcd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (holder.current_number < 10) {
                    holder.current_number++;
                }
                holder.tvQtdcd.setText("" + holder.current_number);
            }
        });

        holder.removeItemcd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (holder.current_number > 0) {
                    holder.current_number--;
                }
                holder.tvQtdcd.setText("" + holder.current_number);
            }
        });

        holder.btnadd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(holder.current_number == 0){
                    Toast.makeText(context,"Selecione a quantidade para o adicional desejado",Toast.LENGTH_LONG).show();}
                else{

                    Intent intent = new Intent();
                    intent.putExtra("msg", "Aceitou");

                    mActivity.setResult(1, intent);
                    mActivity.finish();
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        if(itemList != null){
            return itemList.size();
        }
        return 0;
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder{
        public CardView cvItem;
        public TextView tvAdicional; public TextView tvPreco; public TextView idCmd; public TextView addItemcd; public TextView removeItemcd; public TextView tvQtdcd;
        public Button btnadd;

        int current_number;

        private MainActivity mActivity;
        public MyViewHolder(View itemView, MainActivity mActivity) {
            super(itemView);
            cvItem = (CardView)itemView.findViewById(R.id.t1_1_1_1card_view);
            tvAdicional = (TextView)itemView.findViewById(R.id.t1_1_1_1addcard);
            tvPreco = (TextView)itemView.findViewById(R.id.t1_1_1_1precocard);
            addItemcd =(TextView) itemView.findViewById(R.id.add_itemcard);
            removeItemcd  =(TextView) itemView.findViewById(R.id.remove_itemcard);
            tvQtdcd = (TextView) itemView.findViewById(R.id.iteam_amountcard);
            idCmd = (TextView) itemView.findViewById(R.id.tvidcmdd);
            btnadd = (Button) itemView.findViewById(R.id.t1_1_1_1btnadd);

            this.mActivity=mActivity;
        }
    }
}

Body:
You given wrong parameter in your adapter class constructer.

Change Below line in your MainActivity Class:

Adapter adapter = new  Adapter(MainActivity,getApplicationContext(), adicionalList);


问:
What broke my getResourceAsStream?
I'm taking over a project and have to assume that the tests worked at some point the way I find them (boiled down to what should not be null):

```<code>@Test
public void testCoding() {
   assertNotNull(getClass().getResourceAsStream("/myfile.json"));
   //assertNotNull(MyTest.class.getResourceAsStream("/myfile.json"));
   //assertNotNull(MyTest.class.getClassLoader().getResourceAsStream("myfile.json"));
   //...
}
</code>```

with myfile.json in src/test/resources/ and the test in src/test/java/some/package/.

I tried putting myfile.json into the same folder as the test, in the src/java folder, I tried with and without leading / and with /resources and all the tips I found on SO.

The gradle file is:

```<code>    apply plugin: 'java'

    repositories {
        mavenCentral()
    }

    dependencies {
        testCompile "junit:junit:$junitVersion"
    }
</code>```

What am I missing?

Update:

I realized that the source code is in the open source part of our project and that it does fail in AS, only.

Here is the line that fails if I right-click the lt-api/src/test/java/ folder and select "Run All Tests". The Gradle console prints out this line:

```<code>    Executing tasks: [:lt-api:compileJava, :lt-api:testClasses, :mbwlib:compileJava, :mbwlib:testClasses, :bitlib:compileJava, :bitlib:testClasses]
</code>```

Running
        ./gradlew clean :lt-api:compileJava :lt-api:testClasses :mbwlib:compileJava :mbwlib:testClasses :bitlib:compileJava :bitlib:testClasses

does not trigger the error but neither does it run tests. (How can I know what exactly AS is doing there? I thought AS was doing gradle all the way now?)

Running

```<code>    ./gradlew clean :lt-api:test
</code>```

I get the tests to run (adding a typo results in failing tests) but it doesn't trigger the issue I originally had and that I'd like to understand.

Where should the file be?

```<code>$ sudo updatedb
$ locate test-classes
$ locate ungargasse.json
/path/to/project/lt-api/build/resources/test/ungargasse.json
/path/to/project/lt-api/src/test/resources/ungargasse.json
</code>```

答:
Be Sure that myfile.json is in the test-classe after you complied the codes.

(By default,the files in src/test/resources/ will automatically move into test-classes after compling)

You can use getResourceAsStream without leading "/" in two cases:

Test.java is in src/test/java/some/package  and myfile.json is in /test/resource

```<code>src/test/java/some/package/Test.java
src/test/resource/myfile.json
</code>```

Test.java and myfile.json are in the same package

```<code>src/test/java/some/package/Test.java
src/test/java/some/package/myfile.json
</code>```

For example

```<code>@org.junit.Test
    public void testCoding() {
        InputStream resourceAsStream = getClass().getResourceAsStream("myfile.json");
        System.out.println(resourceAsStream);

    }
</code>```

Title: What broke my getResourceAsStream?

Body:
I'm taking over a project and have to assume that the tests worked at some point the way I find them (boiled down to what should not be null):

@Test
public void testCoding() {
   assertNotNull(getClass().getResourceAsStream("/myfile.json"));
   //assertNotNull(MyTest.class.getResourceAsStream("/myfile.json"));
   //assertNotNull(MyTest.class.getClassLoader().getResourceAsStream("myfile.json"));
   //...
}

with myfile.json in src/test/resources/ and the test in src/test/java/some/package/.

I tried putting myfile.json into the same folder as the test, in the src/java folder, I tried with and without leading / and with /resources and all the tips I found on SO.

The gradle file is:

    apply plugin: 'java'

    repositories {
        mavenCentral()
    }

    dependencies {
        testCompile "junit:junit:$junitVersion"
    }

What am I missing?

Update:

I realized that the source code is in the open source part of our project and that it does fail in AS, only.

Here is the line that fails if I right-click the lt-api/src/test/java/ folder and select "Run All Tests". The Gradle console prints out this line:

    Executing tasks: [:lt-api:compileJava, :lt-api:testClasses, :mbwlib:compileJava, :mbwlib:testClasses, :bitlib:compileJava, :bitlib:testClasses]

Running
        ./gradlew clean :lt-api:compileJava :lt-api:testClasses :mbwlib:compileJava :mbwlib:testClasses :bitlib:compileJava :bitlib:testClasses

does not trigger the error but neither does it run tests. (How can I know what exactly AS is doing there? I thought AS was doing gradle all the way now?)

Running

    ./gradlew clean :lt-api:test

I get the tests to run (adding a typo results in failing tests) but it doesn't trigger the issue I originally had and that I'd like to understand.

Where should the file be?

$ sudo updatedb
$ locate test-classes
$ locate ungargasse.json
/path/to/project/lt-api/build/resources/test/ungargasse.json
/path/to/project/lt-api/src/test/resources/ungargasse.json

Body:
Be Sure that myfile.json is in the test-classe after you complied the codes.

(By default,the files in src/test/resources/ will automatically move into test-classes after compling)

You can use getResourceAsStream without leading "/" in two cases:

Test.java is in src/test/java/some/package  and myfile.json is in /test/resource

src/test/java/some/package/Test.java
src/test/resource/myfile.json

Test.java and myfile.json are in the same package

src/test/java/some/package/Test.java
src/test/java/some/package/myfile.json

For example

@org.junit.Test
    public void testCoding() {
        InputStream resourceAsStream = getClass().getResourceAsStream("myfile.json");
        System.out.println(resourceAsStream);

    }


问:
Checking out of bound condition if 0(\0) is inserted in a char array (at an out of range index)
I'm just learning C++ from the basics and in arrays learnt that in C++, there is no bound checking on arrays (Ex: int data[10], accessing data[12] compiler doesn't produce any error and give value in runtime if memory can be accessed)

I noticed the following difference when practicing int and char arrays:

```<code>char char_data[10];//char array case
char_data[1] = 'h';
char_data[15] = 'v';//line 1
char_data[11] = '\0';//line 2

int int_data[10];//int array case
int_data[1] = 10;
int_data[15] = 150;//line 3
int_data[11] = 0;//line 4
</code>```

When I run the above code in main with MSVC++ 14.0 , the code is compiled fine (as no bound checking in C++) but in char array case, the code is crashing/breaking at line 2 where I equate the element to '\0' (Its not considering the index but the value('\0') when the index is out of range) and the assembly produced is as follows:

```<code>    10:     data[15] = 'v'; //(no bound check here)
00CF1FE5 B8 01 00 00 00       mov         eax,1
00CF1FEA 6B C8 0F             imul        ecx,eax,0Fh
00CF1FED C6 44 0D EC 76       mov         byte ptr data[ecx],76h

11:     data[11] = '\0';//line 2 (bound check here)
00AF1FFA 89 8D F0 FE FF FF    mov         dword ptr [ebp-110h],ecx
00AF2000 83 BD F0 FE FF FF 0A cmp         dword ptr [ebp-110h],0Ah
00AF2007 73 02                jae         main+5Bh (0AF200Bh)
00AF2009 EB 05                jmp         main+60h (0AF2010h)
00AF200B E8 6C F1 FF FF       call        ___report_rangecheckfailure        (0AF117Ch)
00AF2010 8B 95 F0 FE FF FF    mov         edx,dword ptr [ebp-110h]
00AF2016 C6 44 15 EC 00       mov         byte ptr data[edx],0
</code>```

Here, if the value is other than '\0', there is no assembly generated for rangecheck failure. But if I consider the case of int, its not checking the range when the value for an out of range indexis 0('\0' is nothing but 0). I couldn't understand this behavior.

Is this a compiler dependent or this behavior (bound check if value is \0) is same across all the compilers?

Please help!!!

答:
So, you want bounds-checking on your arrays?  There is a solution to this, and that is to use std::array which is part of the standard library since C++11 via the header <array>.  If you define your array as:

```<code>std::array<int, 10> data;
</code>```

Then all the usual array access can be achieved with operator[] as usual, but you also get the at function (documentation here), which will do a range-test and throw std::out_of_range on failure.

```<code>data.at(9) = 0;     // OK
data.at(10) = 0;    // will throw
data.at(5678) = 0;  // will throw
</code>```

And you are welcome to catch the exception in a try-block if you like.  If you don't catch, then you will get a nice program crash at the exact point where you caused the error.  And that's nicer than undefined behavior.

Of course, you really shouldn't have to use exception-throwing bounds-checking in ordinary cases.  Particularly on an array.  You know its size, so don't do silly stuff like accessing values outside its valid range.

Body:
I'm just learning C++ from the basics and in arrays learnt that in C++, there is no bound checking on arrays (Ex: int data[10], accessing data[12] compiler doesn't produce any error and give value in runtime if memory can be accessed)

I noticed the following difference when practicing int and char arrays:

char char_data[10];//char array case
char_data[1] = 'h';
char_data[15] = 'v';//line 1
char_data[11] = '\0';//line 2

int int_data[10];//int array case
int_data[1] = 10;
int_data[15] = 150;//line 3
int_data[11] = 0;//line 4

When I run the above code in main with MSVC++ 14.0 , the code is compiled fine (as no bound checking in C++) but in char array case, the code is crashing/breaking at line 2 where I equate the element to '\0' (Its not considering the index but the value('\0') when the index is out of range) and the assembly produced is as follows:

    10:     data[15] = 'v'; //(no bound check here)
00CF1FE5 B8 01 00 00 00       mov         eax,1
00CF1FEA 6B C8 0F             imul        ecx,eax,0Fh
00CF1FED C6 44 0D EC 76       mov         byte ptr data[ecx],76h

11:     data[11] = '\0';//line 2 (bound check here)
00AF1FFA 89 8D F0 FE FF FF    mov         dword ptr [ebp-110h],ecx
00AF2000 83 BD F0 FE FF FF 0A cmp         dword ptr [ebp-110h],0Ah
00AF2007 73 02                jae         main+5Bh (0AF200Bh)
00AF2009 EB 05                jmp         main+60h (0AF2010h)
00AF200B E8 6C F1 FF FF       call        ___report_rangecheckfailure        (0AF117Ch)
00AF2010 8B 95 F0 FE FF FF    mov         edx,dword ptr [ebp-110h]
00AF2016 C6 44 15 EC 00       mov         byte ptr data[edx],0

Here, if the value is other than '\0', there is no assembly generated for rangecheck failure. But if I consider the case of int, its not checking the range when the value for an out of range indexis 0('\0' is nothing but 0). I couldn't understand this behavior.

Is this a compiler dependent or this behavior (bound check if value is \0) is same across all the compilers?

Please help!!!

Body:
So, you want bounds-checking on your arrays?  There is a solution to this, and that is to use std::array which is part of the standard library since C++11 via the header <array>.  If you define your array as:

std::array<int, 10> data;

Then all the usual array access can be achieved with operator[] as usual, but you also get the at function (documentation here), which will do a range-test and throw std::out_of_range on failure.

data.at(9) = 0;     // OK
data.at(10) = 0;    // will throw
data.at(5678) = 0;  // will throw

And you are welcome to catch the exception in a try-block if you like.  If you don't catch, then you will get a nice program crash at the exact point where you caused the error.  And that's nicer than undefined behavior.

Of course, you really shouldn't have to use exception-throwing bounds-checking in ordinary cases.  Particularly on an array.  You know its size, so don't do silly stuff like accessing values outside its valid range.


问:
MS Access 2016 - Retaining default text
I'm building a report generator in ms-access using exported transactions from Xero accounting.

It includes emailing reports to users.  I have a default Body Text for the email, but would like it to be editable by the user (rather than code change).

I can hard-code this using vba but I would like the user to be able to edit and save it ,so it's available the next time ms-access is opened.

How can Access save this information from one session to the next?

答: Create a table with a memo field.  Use that as the source for the "body text".</p>

Title: MS Access 2016 - Retaining default text


问:
Windows bat: files without extension (dot in name issue)
At first: it's not a repeated question (I hope). I've searched a lot and found How to find files with no file extension in directory tree with a batch file? and Find and rename files with no extension?, among others, but I have a "small" additional problem.

I'm trying to rename multiple (thousands) of jpg files on Windows 10. The name format is "Name (ABC).jpg" or "Multiple Names (ABC).jpg". I need "Some Name.jpg".

What have you tried? So many things, none of them a real solution, until this:

```<code>for /f "tokens=1-3 delims=)(" %%a in ('dir /b *.jpg') do @rename "%%a(%%b)%%c" "%%a"
for /R %%x in (*.) do ren "%%x" *.png
</code>```

It works fine for most of the files, except when there's a dot in the name. If the name is something like "A Name.Supercool (ABC).jpg", it will be only "A Name.Supercool", with no extension.

I know the problem is on (*.), just don't know how to solve...

答:
Magoo's answer is closer to what I asked, but there is a problem with special characters in file names. TessellatingHeckler posted the best approach as a comment, so here it goes. Batch file:

```<code>powershell -command "gci *.jpg | ren -newname { ($_.basename -replace '\s+\(.*\)') + '.jpg'};gci *.png | ren -newname { ($_.basename -replace '\s+\(.*\)') + '.png'}"
</code>```

With this I can handle .jpg and .png at once, flawlessly. Thank you all.

Body:
At first: it's not a repeated question (I hope). I've searched a lot and found How to find files with no file extension in directory tree with a batch file? and Find and rename files with no extension?, among others, but I have a "small" additional problem.

I'm trying to rename multiple (thousands) of jpg files on Windows 10. The name format is "Name (ABC).jpg" or "Multiple Names (ABC).jpg". I need "Some Name.jpg".

What have you tried? So many things, none of them a real solution, until this:

for /f "tokens=1-3 delims=)(" %%a in ('dir /b *.jpg') do @rename "%%a(%%b)%%c" "%%a"
for /R %%x in (*.) do ren "%%x" *.png

It works fine for most of the files, except when there's a dot in the name. If the name is something like "A Name.Supercool (ABC).jpg", it will be only "A Name.Supercool", with no extension.

I know the problem is on (*.), just don't know how to solve...

Body:
Magoo's answer is closer to what I asked, but there is a problem with special characters in file names. TessellatingHeckler posted the best approach as a comment, so here it goes. Batch file:

powershell -command "gci *.jpg | ren -newname { ($_.basename -replace '\s+\(.*\)') + '.jpg'};gci *.png | ren -newname { ($_.basename -replace '\s+\(.*\)') + '.png'}"

With this I can handle .jpg and .png at once, flawlessly. Thank you all.


问:
Drools with Rule Flow Group
I am new to Drools and started with basic example. I have very simple rule as below and it works fine.

```<code>rule "One"
    when
        m : Message( status == Message.HELLO, myMessage : message )
    then
        System.out.println( myMessage );
        m.setMessage( "Goodbye cruel world" );
        m.setStatus( Message.GOODBYE );
        update( m );
end

rule "Two"
    when
        Message( status == Message.GOODBYE, myMessage : message )
    then
        System.out.println( myMessage );
end

KieServices ks = KieServices.Factory.get();
KieContainer kContainer = ks.getKieClasspathContainer();
KieSession kSession = kContainer.newKieSession("ksession-rules");

Message message = new Message();
message.setMessage("Hello World");
message.setStatus(Message.HELLO);
kSession.insert(message);
int rulesFired = kSession.fireAllRules();
</code>```

But when I added ruleflow-group, rule is not getting executed.

```<code>rule "One"
  ruleflow-group "dog"
    when
        m : Message( status == Message.HELLO, myMessage : message )
    then
        System.out.println( myMessage );
        m.setMessage( "Goodbye cruel world" );
        m.setStatus( Message.GOODBYE );
        update( m );
end

rule "Two"
  ruleflow-group "dog"
    when
        Message( status == Message.GOODBYE, myMessage : message )
    then
        System.out.println( myMessage );
end
</code>```

with the rule flow group name added, with the same code rule is not getting fired.

答:
When you use ruleflowGroup/agendaGroup we have to set focus on custom ruleflowgroup. In your code add below line:

kSession.getAgenda().getAgendaGroup("dog").setFocus();

Try with this approach..!!

ContentLicense: CC BY-SA 4.0

Title: Drools with Rule Flow Group

Body:
I am new to Drools and started with basic example. I have very simple rule as below and it works fine.

rule "One"
    when
        m : Message( status == Message.HELLO, myMessage : message )
    then
        System.out.println( myMessage );
        m.setMessage( "Goodbye cruel world" );
        m.setStatus( Message.GOODBYE );
        update( m );
end

rule "Two"
    when
        Message( status == Message.GOODBYE, myMessage : message )
    then
        System.out.println( myMessage );
end

KieServices ks = KieServices.Factory.get();
KieContainer kContainer = ks.getKieClasspathContainer();
KieSession kSession = kContainer.newKieSession("ksession-rules");

Message message = new Message();
message.setMessage("Hello World");
message.setStatus(Message.HELLO);
kSession.insert(message);
int rulesFired = kSession.fireAllRules();

But when I added ruleflow-group, rule is not getting executed.

rule "One"
  ruleflow-group "dog"
    when
        m : Message( status == Message.HELLO, myMessage : message )
    then
        System.out.println( myMessage );
        m.setMessage( "Goodbye cruel world" );
        m.setStatus( Message.GOODBYE );
        update( m );
end

rule "Two"
  ruleflow-group "dog"
    when
        Message( status == Message.GOODBYE, myMessage : message )
    then
        System.out.println( myMessage );
end

with the rule flow group name added, with the same code rule is not getting fired.


问:
Integrate CKEditor in ADF12c Popup
Am trying to integrate CKEditor in a ADF popup which is in a page fragment using JSP Tag Libraries.
Am using JDeveloper 12.13 version.
Here is the code am using in a popup which is in a subform.

```<code><cke:editor basePath="/PLS/js/" editor="editor1"  value="Type Here"/>
</code>```

Am getting below error
java.lang.IllegalStateException: Could not find component to stream
        at oracle.adfinternal.view.faces.streaming.StreamingDataManager.submit(StreamingDataManager.java:519)
        at oracle.adfinternal.view.faces.renderkit.rich.DocumentRenderer._encodeStreamingResponse(DocumentRenderer.java:4047)

Getting this exception with different Content Delivery modes(immediate, lazy)  for popup. I have also tried declared ADF RichText Editor and replacing it with CKEDitor replace tag.

Does anyone has idea why CKEDitor is not working in ADF Popup.

答:
Does your var rt1 and rt2 return any values or are they undefined? To search for components in ADF page , you should use javascript as defined in links here and here .

You can also refer the oracle documentation here for using ADF client side Architecture.

Title: Integrate CKEditor in ADF12c Popup

Body:
Am trying to integrate CKEditor in a ADF popup which is in a page fragment using JSP Tag Libraries.
Am using JDeveloper 12.13 version.
Here is the code am using in a popup which is in a subform.

<cke:editor basePath="/PLS/js/" editor="editor1"  value="Type Here"/>

Am getting below error
java.lang.IllegalStateException: Could not find component to stream
        at oracle.adfinternal.view.faces.streaming.StreamingDataManager.submit(StreamingDataManager.java:519)
        at oracle.adfinternal.view.faces.renderkit.rich.DocumentRenderer._encodeStreamingResponse(DocumentRenderer.java:4047)

Getting this exception with different Content Delivery modes(immediate, lazy)  for popup. I have also tried declared ADF RichText Editor and replacing it with CKEDitor replace tag.

Does anyone has idea why CKEDitor is not working in ADF Popup.


问:
How to make the java wait for x seconds and then execute
I making an app and I would run in to a problem that I can't fix.
I am using Android Studio and I need to make a Button that I have already made. Do more then it already does. I want it to after display a text also close the app. Do you know how I should program that. It would be very helpful. Thanks in advance.

Here is the Java code:

```<code>package test.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void buttonOnClick(View v) {
    Button button=(Button) v;
    ((Button) v).setText("Correct");
}

public void buttonAnClick(View q) {
    Button button=(Button) q;
    ((Button) q).setText("Niet goed");
}
</code>```

}

So I have already made the button in XML and told it:

android:onClick="buttonOnClick"

Hope you can help me out!

答:
Try this. </p>

```<code>public void buttonOnClick(View v) {
     Button button=(Button) v;
     ((Button) v).setText("Correct");
     new android.os.Handler().postDelayed(new Runnable() {
         @Override
         public void run() {
             finish();
         }
     },1000); // milliseconds: 1 seg.
}
</code>```

Body:
I making an app and I would run in to a problem that I can't fix.
I am using Android Studio and I need to make a Button that I have already made. Do more then it already does. I want it to after display a text also close the app. Do you know how I should program that. It would be very helpful. Thanks in advance.

Here is the Java code:

package test.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void buttonOnClick(View v) {
    Button button=(Button) v;
    ((Button) v).setText("Correct");
}

public void buttonAnClick(View q) {
    Button button=(Button) q;
    ((Button) q).setText("Niet goed");
}

}

So I have already made the button in XML and told it:

android:onClick="buttonOnClick"

Hope you can help me out!

Body:
Try this.

public void buttonOnClick(View v) {
     Button button=(Button) v;
     ((Button) v).setText("Correct");
     new android.os.Handler().postDelayed(new Runnable() {
         @Override
         public void run() {
             finish();
         }
     },1000); // milliseconds: 1 seg.
}


问:
msbuild proj file creator/tool for msbuild proj file
Is there any tool that will create .proj file. Its very cumbersome to create it by hand for big & complex project structure. </p>

答:
According to this article, there is a way to generate msbuild .proj file from Visual Studio solution.

You just have to run Visual Studio command prompt and set a special environment variable:

```<code>set MSBuildEmitSolution=1
</code>```

Then cd to your project directory and run msbuild <<your project>>.sln.

This will generate a .sln.metaproj which in fact is an msbuild project file.

ContentLicense: CC BY-SA 2.5

Body:
According to this article, there is a way to generate msbuild .proj file from Visual Studio solution.

You just have to run Visual Studio command prompt and set a special environment variable:

set MSBuildEmitSolution=1

Then cd to your project directory and run msbuild <<your project>>.sln.

This will generate a .sln.metaproj which in fact is an msbuild project file.


问:
Angular2 : The pipe 'SomePipe' could not be found
I have custom pipe which I m using to search a string in the table data and I get the error message "The pipe 'FilterPipe' could not be found" . I referred the below question but the solution given there didn't work me.

The pipe ' ' could not be found angular2 custom pipe

Actual.pipe.ts

```<code>import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'FilterPipe',
})
export class FilterPipe implements PipeTransform {
    transform(value: any, input: string) {
        if (input) {
            input = input.toLowerCase();
            return value.filter(function (el: any) {
                return el.Name.toLowerCase().indexOf(input) > -1;
            })
        }
        return value;
    }
}
</code>```

main-ipe.module.ts

```<code>import { NgModule } from '@angular/core';
import {CommonModule} from "@angular/common";

import {FilterPipe} from "./Actual.pipe";

@NgModule({
declarations:[FilterPipe],
imports:[CommonModule],
exports:[FilterPipe]
})

export class MainPipe{}
</code>```

app.module.ts

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { FileSelectDirective, FileDropDirective } from 'ng2-file-upload';
import { Ng2DragDropModule } from 'ng2-drag-drop';
import {DndModule} from 'ng2-dnd';

import { AppComponent } from './app.component';
import { routing } from './app.routing';
import { AppConfig } from './app.config';
import {MainPipe} from './main-pipe.module';

import { AlertComponent } from './_directives/index';
import { AuthGuard } from './_guards/index';
import { AlertService, AuthenticationService, UserService, SchemaService, TemplateService } from './_services/index';
import { HomeComponent } from './home/index';
import { LoginComponent } from './login/index';
import { RegisterComponent } from './register/index';
import { UploadComponent } from './upload/index';
import { ReadComponent } from './read/index';
import { DragComponent } from './drag/index';

@NgModule({
    imports: [
        BrowserModule,
        DndModule.forRoot(),
        FormsModule,
        HttpModule,
        routing,
        Ng2DragDropModule,
        MainPipe
    ],
    declarations: [
        AppComponent,
        AlertComponent,
        HomeComponent,
        LoginComponent,
        RegisterComponent,
        FileSelectDirective,
        UploadComponent,
        ReadComponent,
        DragComponent
    ],
    providers: [
        AppConfig,
        AuthGuard,
        AlertService,
        AuthenticationService,
        UserService,
        SchemaService,
        TemplateService

    ],
    bootstrap: [AppComponent]
})

export class AppModule { }
</code>```

my html code where am using the pipe:

```<code> <div class="table-responsive">
            <table class="table">
                 <thead>
                 <tr>
                      <th>Template Name</th>
                      <th>Created On</th>
                      <th>Last Modified</th>
                      <th>Actions</th>
                      </tr>
               </thead>
   <tbody *ngFor="let template of templates | FilterPipe: queryString">
           <tr>
               <td>{{template.Name}}</td>
               <td>{{template.Created_Date}}</td>
               <td>{{template.Modified_Date}}</td>
               <td>
               <button type="button" class="btn btn-default"><span class="glyphicon glyphicon-pencil"></span> Edit</button>
               <button type="button" class="btn btn-default"><span class="glyphicon glyphicon-trash"></span> Delete</button>
               </td>
            </tr>
     </tbody>
   </table>
</code>```

I tried referring to other similar questions as well, but even those didn't yeld any result. Am new to Angular2 , please help with this. Thanks for reading !

答:
You should import your pipe into declarations not under imports,

try this,

```<code>declarations: [
        AppComponent,
        AlertComponent,
        MainPipe,
        HomeComponent,
        LoginComponent,
        RegisterComponent,
        FileSelectDirective,
        UploadComponent,
        ReadComponent,
        DragComponent
    ],
</code>```

Body:
I have custom pipe which I m using to search a string in the table data and I get the error message "The pipe 'FilterPipe' could not be found" . I referred the below question but the solution given there didn't work me.

The pipe ' ' could not be found angular2 custom pipe

Actual.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'FilterPipe',
})
export class FilterPipe implements PipeTransform {
    transform(value: any, input: string) {
        if (input) {
            input = input.toLowerCase();
            return value.filter(function (el: any) {
                return el.Name.toLowerCase().indexOf(input) > -1;
            })
        }
        return value;
    }
}

main-ipe.module.ts

import { NgModule } from '@angular/core';
import {CommonModule} from "@angular/common";

import {FilterPipe} from "./Actual.pipe";

@NgModule({
declarations:[FilterPipe],
imports:[CommonModule],
exports:[FilterPipe]
})

export class MainPipe{}

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { FileSelectDirective, FileDropDirective } from 'ng2-file-upload';
import { Ng2DragDropModule } from 'ng2-drag-drop';
import {DndModule} from 'ng2-dnd';

import { AppComponent } from './app.component';
import { routing } from './app.routing';
import { AppConfig } from './app.config';
import {MainPipe} from './main-pipe.module';

import { AlertComponent } from './_directives/index';
import { AuthGuard } from './_guards/index';
import { AlertService, AuthenticationService, UserService, SchemaService, TemplateService } from './_services/index';
import { HomeComponent } from './home/index';
import { LoginComponent } from './login/index';
import { RegisterComponent } from './register/index';
import { UploadComponent } from './upload/index';
import { ReadComponent } from './read/index';
import { DragComponent } from './drag/index';

@NgModule({
    imports: [
        BrowserModule,
        DndModule.forRoot(),
        FormsModule,
        HttpModule,
        routing,
        Ng2DragDropModule,
        MainPipe
    ],
    declarations: [
        AppComponent,
        AlertComponent,
        HomeComponent,
        LoginComponent,
        RegisterComponent,
        FileSelectDirective,
        UploadComponent,
        ReadComponent,
        DragComponent
    ],
    providers: [
        AppConfig,
        AuthGuard,
        AlertService,
        AuthenticationService,
        UserService,
        SchemaService,
        TemplateService

    ],
    bootstrap: [AppComponent]
})

export class AppModule { }

my html code where am using the pipe:

                      Template Name
                      Created On
                      Last Modified
                      Actions

               {{template.Name}}
               {{template.Created_Date}}
               {{template.Modified_Date}}

               <button type="button" class="btn btn-default"> Edit</button>
               <button type="button" class="btn btn-default"> Delete</button>

I tried referring to other similar questions as well, but even those didn't yeld any result. Am new to Angular2 , please help with this. Thanks for reading !

Body:
You should import your pipe into declarations not under imports,

try this,

declarations: [
        AppComponent,
        AlertComponent,
        MainPipe,
        HomeComponent,
        LoginComponent,
        RegisterComponent,
        FileSelectDirective,
        UploadComponent,
        ReadComponent,
        DragComponent
    ],


问:
Get a querystring from URL and pass as querystring to new URL using javascript
I need to Get a querystring from URL1 then redirect to URL2 - with the querystring from URL1 appended.

The querystring has 2 values:

```<code>http://URL1.com/hi/j?a=123&b=666
</code>```

I want this to redirect to:

```<code>http://URL2.com/hi/b?a=123&b=666
</code>```

I can't find anything on doing this on Google. I found this but it only works with 1 value and seems to have got criticism - and it only takes the querystring and doesn't add it: How can I get query string values in JavaScript?

Thanks.

答:
try this pattern \?(.*) . Match the regex pattern after ? .Then paste with newly created url extenstion

Add your code as like this

```<code>var a =window.location.href;
var after =/\?(.*)/g.exec(a)[0]
window.location.href='http://URL2.com/hi/b'+after
</code>```

Working example

var a ='http://URL1.com/hi/j?a=123&b=666';
var after =/\?(.*)/g.exec(a);
console.log(after[1].split('&'))//try with your wish from array(selectquery)
console.log('http://URL2.com/hi/b'+after[0])//for whole query```

Body:
I need to Get a querystring from URL1 then redirect to URL2 - with the querystring from URL1 appended.

The querystring has 2 values:

http://URL1.com/hi/j?a=123&b=666

I want this to redirect to:

http://URL2.com/hi/b?a=123&b=666

I can't find anything on doing this on Google. I found this but it only works with 1 value and seems to have got criticism - and it only takes the querystring and doesn't add it: How can I get query string values in JavaScript?

Thanks.

Body:
try this pattern \?(.*) . Match the regex pattern after ? .Then paste with newly created url extenstion

Add your code as like this

var a =window.location.href;
var after =/\?(.*)/g.exec(a)[0]
window.location.href='http://URL2.com/hi/b'+after

Working example

var a ='http://URL1.com/hi/j?a=123&b=666';
var after =/\?(.*)/g.exec(a);
console.log(after[1].split('&'))//try with your wish from array(selectquery)
console.log('http://URL2.com/hi/b'+after[0])//for whole query


问:
PHP - Filtering data in table
I need help on how to filter data in a database. I want a filter like in the excel spreadsheet.

For example, I have this sample code on how to get data from w3school on how to select data from database. Here is my sample code:

```<code> <?php
$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("TableTest", $con);

$result = mysql_query("SELECT * FROM Colors ");

echo "<table border='1'>
<tr>
<th>Colors</th>
<th>Type</th>
</tr>";

while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['colors'] . "</td>";
  echo "<td>" . $row['type'] . "</td>";
  echo "</tr>";
  }
echo "</table>";

mysql_close($con);
?>
</code>```

I also found this sample too in w3school, but I dont want to filter the database with a drop down.

I'd like to make it like an excel filter. When I select the column 'Colors' to filter on 'Red', it will display only the color red. So i was wondering if anyone could help me on how to start.

Thanks all

答:
I am pretty sure you're looking for "this". You need JavaScript for that to work.

There are basically 3 steps:

Make an HTML table to display contents.

Use CSS to style that table.

Use JavaScript for searching and filtering the table.

See more on the link provided.

https://www.w3schools.com/howto/howto_js_filter_table.asp

Title: PHP - Filtering data in table

Body:
I need help on how to filter data in a database. I want a filter like in the excel spreadsheet.

For example, I have this sample code on how to get data from w3school on how to select data from database. Here is my sample code:

 <?php
$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("TableTest", $con);

$result = mysql_query("SELECT * FROM Colors ");

echo "

Colors
Type

";

while($row = mysql_fetch_array($result))
  {
  echo "
";
  echo "" . $row['colors'] . "	";
  echo "" . $row['type'] . "	";
  echo "
";
  }
echo "
";

mysql_close($con);
?>

I also found this sample too in w3school, but I dont want to filter the database with a drop down.

I'd like to make it like an excel filter. When I select the column 'Colors' to filter on 'Red', it will display only the color red. So i was wondering if anyone could help me on how to start.

Thanks all


问:
Can not share variables in angular controllers
I am new to angular js. I have two ng-controller in two Html  page. I want to share data from one controller into another controller.
Here is the service i have created:

```<code>app.service('sharedProperties', function() {
    var stringValue = 'test string value';
    var objectValue = {
        data: 'test object value'
    };

    return {
        getString: function() {
            return stringValue;
        },
        setString: function(value) {
            stringValue = value;
        },
        getObject: function() {
            return objectValue;
        }
    }
});
</code>```

Here is controller1:

```<code> app.controller('FirstCtrl',function($scope,sharedProperties){
         sharedProperties.setString("Hi");
  });
</code>```

Here is controller2:

```<code>app.controller('SeccondCtrl',function($scope,sharedProperties){
               window.alert(sharedProperties.getString());

});
</code>```

Instead of getting alert containing string 'Hi' i am getting 'test string value'.

NB. i am using FirstCtrl and SeccondCtrl in two HTML file.  And after setting string from FristCtrl i redirect to the second HTML file .

答:
Service have this reference you write your service method as per below

```<code>app.service('sharedProperties', function() {
        var stringValue = 'test string value';
        var objectValue = {
            data: 'test object value'
        };

       this.getString: function() {
                return stringValue;
            }
       this.setString: function(value) {
                stringValue = value;
            }
        this.getObject: function() {
                return objectValue;
            }

    });
</code>```

Body:
I am new to angular js. I have two ng-controller in two Html  page. I want to share data from one controller into another controller.
Here is the service i have created:

app.service('sharedProperties', function() {
    var stringValue = 'test string value';
    var objectValue = {
        data: 'test object value'
    };

    return {
        getString: function() {
            return stringValue;
        },
        setString: function(value) {
            stringValue = value;
        },
        getObject: function() {
            return objectValue;
        }
    }
});

Here is controller1:

 app.controller('FirstCtrl',function($scope,sharedProperties){
         sharedProperties.setString("Hi");
  });

Here is controller2:

app.controller('SeccondCtrl',function($scope,sharedProperties){
               window.alert(sharedProperties.getString());

});

Instead of getting alert containing string 'Hi' i am getting 'test string value'.

NB. i am using FirstCtrl and SeccondCtrl in two HTML file.  And after setting string from FristCtrl i redirect to the second HTML file .

Body:
Service have this reference you write your service method as per below

app.service('sharedProperties', function() {
        var stringValue = 'test string value';
        var objectValue = {
            data: 'test object value'
        };

       this.getString: function() {
                return stringValue;
            }
       this.setString: function(value) {
                stringValue = value;
            }
        this.getObject: function() {
                return objectValue;
            }

    });


问:
Override bootstrap !important
I just want to get rid of outline in my dropdown list when focus state. See this image

I tried to override bootstrap using !important but not working at all. Just check the dev tools and suddenly see this.

Bootstrap is also using !important tag. So I couldn't override it. I can use id to button and set focus outline to 0 but I have so many dropdowns in my website. Any fix for this kind of situation?

```<code>.bootstrap-select .dropdown-toggle:focus{
   outline: none!important;
}
</code>```

答: Your style.css file loads before your Bootstrap css file. However, you have to load your style.css after the bootstrap-select.min.css file in order to override the Bootstrap styles.

Title: Override bootstrap !important

Body:
I just want to get rid of outline in my dropdown list when focus state. See this image

I tried to override bootstrap using !important but not working at all. Just check the dev tools and suddenly see this.

Bootstrap is also using !important tag. So I couldn't override it. I can use id to button and set focus outline to 0 but I have so many dropdowns in my website. Any fix for this kind of situation?

.bootstrap-select .dropdown-toggle:focus{
   outline: none!important;
}


问:
htaccess rewrite based on IP or domain
I'm using Codeigniter, now the rewrite is working fine for accessing using domain name, here is the default Codeigniter htaccess:

```<code>RewriteRule ^(.*)$ index.php?/$1 [L]
</code>```

But I want to make it able to access using IP address as well and I host my website in a shared hosting with cPanel, so the IP address will be something like this: http://11.11.11.11/~username. But it just not working when I access using IP, I had tried adding a RewriteBase and also something like:

```<code>RewriteRule ^(.*)$ ~username/index.php?/$1 [L]
</code>```

and

```<code>RewriteRule ^~username/(.*)$ index.php?/$1 [L]
</code>```

but non of them work. Anyone please help? Thank you.

答:
Ok I just found the solution, I should check the host so that RewriteBase only will work properly:</p>

```<code>RewriteCond %{HTTP_HOST} ^www\.domain\.com [NC]
RewriteRule ^(.*)$ index.php?/$1 [L]

RewriteBase /~username/
RewriteCond %{HTTP_HOST} ^11\.11\.11\.11 [NC]
RewriteRule ^(.*)$ index.php?/$1 [L]
</code>```

Title: htaccess rewrite based on IP or domain

Body:
I'm using Codeigniter, now the rewrite is working fine for accessing using domain name, here is the default Codeigniter htaccess:

RewriteRule ^(.*)$ index.php?/$1 [L]

But I want to make it able to access using IP address as well and I host my website in a shared hosting with cPanel, so the IP address will be something like this: http://11.11.11.11/~username. But it just not working when I access using IP, I had tried adding a RewriteBase and also something like:

RewriteRule ^(.*)$ ~username/index.php?/$1 [L]

and

RewriteRule ^~username/(.*)$ index.php?/$1 [L]

but non of them work. Anyone please help? Thank you.

Body:
Ok I just found the solution, I should check the host so that RewriteBase only will work properly:

RewriteCond %{HTTP_HOST} ^www\.domain\.com [NC]
RewriteRule ^(.*)$ index.php?/$1 [L]

RewriteBase /~username/
RewriteCond %{HTTP_HOST} ^11\.11\.11\.11 [NC]
RewriteRule ^(.*)$ index.php?/$1 [L]


答:
Ping,

Unfortunately, you can not use IP as host while you'r on shared hosting. Share hosting shared single IP for multiple websites.

You need dedicated hosting or VPS for your purpose.

Title: htaccess rewrite based on IP or domain


问:
How to access custom array in custom list view class
So I have a List of type "Item_Array_Class" on My homescreen

Here is that class:

```<code>public class Item_Array_Class {
    String vendor;
    String category;
    String price;
    Bitmap item_Image;
    int Index;

    public Item_Array_Class(String vendor, String category, String price, Bitmap item_Image, int Index) {
        this.vendor = vendor;
        this.category = category;
        this.price = price;
        this.item_Image = item_Image;
        this.Index = Index;
    }

    public String get_vendor() {
        return vendor;
    }

    public String get_category() {
        return category;
    }

    public String get_price() {
        return price;
    }

    public Bitmap get_Image() {
        return item_Image;
    }

    public int get_Index() { return Index; }
    }
</code>```

I want to access this List while making my custom listview so that I can pull out the Image and Vendor from the array and display them since the custom view is just an ImageView and a textView.

So here's the code I've got for my custom list view class:`

```<code>class custom_list_view extends ArrayAdapter
 {
 public custom_list_view(Context context, HomeScreen.Item_Array_Class[]
item_array)
{
    super(context, R.layout.custom_list_view, item_array);
}

@Override
public View getView(int position, View convertView, ViewGroup parent)
{
    LayoutInflater inflater = LayoutInflater.from(getContext());
    View customView_Var = inflater.inflate(R.layout.custom_list_view, parent, false);

    TextView item_title_TV = (TextView) customView_Var.findViewById(R.id.custom_list_title);
    ImageView item_image = (ImageView) customView_Var.findViewById(R.id.custom_list_image);

    //get the data from the array here <-------
    String vendor = item_array.get(position).get_Vendor(); //Cannot resolve symbol 'item_array'

    item_title_TV.setText();
    item_image.setImageBitmap();

    return customView_Var;
}
}
</code>```

What I was hoping to do was somehow go something like:

```<code>String vendor = item_array.get(position).get_Vendor();
</code>```

however, I can't seem to access the item_array I pass it in the constructor. I can just call getItem(position) but then I have no way to only get the Image and vendor. Any help would be greatly appreciated.

TL;DR: how can I access my HomeScreens custom List within the class for my custom list view to pull the Image and Vendor from each slot in the list to put on the Image View and Text view for each item in the ListView.

答:
I can just call getItem(position) but then I have no way to only get the Image and vendor.

Yes, you do have a way...

First, fix your class definition

```<code>extends ArrayAdapter<Item_Array_Class>
</code>```

Then

```<code>Item_Array_Class item = getItem(position);
String vendor = item.get_Vendor();
</code>```

Body:
So I have a List of type "Item_Array_Class" on My homescreen

Here is that class:

public class Item_Array_Class {
    String vendor;
    String category;
    String price;
    Bitmap item_Image;
    int Index;

    public Item_Array_Class(String vendor, String category, String price, Bitmap item_Image, int Index) {
        this.vendor = vendor;
        this.category = category;
        this.price = price;
        this.item_Image = item_Image;
        this.Index = Index;
    }

    public String get_vendor() {
        return vendor;
    }

    public String get_category() {
        return category;
    }

    public String get_price() {
        return price;
    }

    public Bitmap get_Image() {
        return item_Image;
    }

    public int get_Index() { return Index; }
    }

I want to access this List while making my custom listview so that I can pull out the Image and Vendor from the array and display them since the custom view is just an ImageView and a textView.

So here's the code I've got for my custom list view class:`

class custom_list_view extends ArrayAdapter
 {
 public custom_list_view(Context context, HomeScreen.Item_Array_Class[]
item_array)
{
    super(context, R.layout.custom_list_view, item_array);
}

@Override
public View getView(int position, View convertView, ViewGroup parent)
{
    LayoutInflater inflater = LayoutInflater.from(getContext());
    View customView_Var = inflater.inflate(R.layout.custom_list_view, parent, false);

    TextView item_title_TV = (TextView) customView_Var.findViewById(R.id.custom_list_title);
    ImageView item_image = (ImageView) customView_Var.findViewById(R.id.custom_list_image);

    //get the data from the array here <-------
    String vendor = item_array.get(position).get_Vendor(); //Cannot resolve symbol 'item_array'

    item_title_TV.setText();
    item_image.setImageBitmap();

    return customView_Var;
}
}

What I was hoping to do was somehow go something like:

String vendor = item_array.get(position).get_Vendor();

however, I can't seem to access the item_array I pass it in the constructor. I can just call getItem(position) but then I have no way to only get the Image and vendor. Any help would be greatly appreciated.

TL;DR: how can I access my HomeScreens custom List within the class for my custom list view to pull the Image and Vendor from each slot in the list to put on the Image View and Text view for each item in the ListView.

Body:
I can just call getItem(position) but then I have no way to only get the Image and vendor.

Yes, you do have a way...

First, fix your class definition

extends ArrayAdapter<Item_Array_Class>

Then

Item_Array_Class item = getItem(position);
String vendor = item.get_Vendor();


问:
How to check if an array doesn't contain a string and use it as condition
```<code>var name = document.getElementById("namebox").value;

if (array.includes(name) == false) {
   alert(name + " is not in record.")
}
</code>```

that didn't work and will always return false, how to express the check in other ways? please enlighten, thank you very much

答:
You may try</p>

```<code>if (array.indexOf(name) == -1) {
   alert(name + " is not in record.")
}
</code>```

Body:
var name = document.getElementById("namebox").value;

if (array.includes(name) == false) {
   alert(name + " is not in record.")
}

that didn't work and will always return false, how to express the check in other ways? please enlighten, thank you very much

Body:
You may try

if (array.indexOf(name) == -1) {
   alert(name + " is not in record.")
}


问:
Efficient SQL query for selecting records where a related record DOES NOT exist
I am trying to select a User where that User DOES NOT have an associated record with a certain value.

I have a User model, a User has_one Feed, a Feed has_many FeedTracks, a FeedTrack belongs_to a Track. I want to select Users only where they DO NOT have a FeedTrack with a certain TrackId.

I'm using rails but I would be open to strict SQL for this.

The best I've got is:

```<code> SELECT TOP 1000 *
 FROM Users u
 LEFT JOIN Feeds f ON f.user_id = u.id
 LEFT JOIN FeedTracks ft ON ft.feed_id = f.id
 ONLY IF ALL OF THOSE feedTracks' track_id !== <<track_id>>
</code>```

Obviously that last part statement is not real SQL and that's what my question is. How would I say, hey, get me the Users where this related record doesn't exist. But if that record does exist, don't return that User.

In other words, if that user has a feed, with a feed track with that track id, don't return that User. But if it doesn't, do return that User.

答:
Try</p>

```<code>User.joins(feed: :feed_tracks)
        .where('feed_tracks.track_id <> ?', unwanted_track_id)
        .order('id desc')
        .limit(1000)
        .to_sql
</code>```

Body:
I am trying to select a User where that User DOES NOT have an associated record with a certain value.

I have a User model, a User has_one Feed, a Feed has_many FeedTracks, a FeedTrack belongs_to a Track. I want to select Users only where they DO NOT have a FeedTrack with a certain TrackId.

I'm using rails but I would be open to strict SQL for this.

The best I've got is:

 SELECT TOP 1000 *
 FROM Users u
 LEFT JOIN Feeds f ON f.user_id = u.id
 LEFT JOIN FeedTracks ft ON ft.feed_id = f.id
 ONLY IF ALL OF THOSE feedTracks' track_id !== <<track_id>>

Obviously that last part statement is not real SQL and that's what my question is. How would I say, hey, get me the Users where this related record doesn't exist. But if that record does exist, don't return that User.

In other words, if that user has a feed, with a feed track with that track id, don't return that User. But if it doesn't, do return that User.

Body:
Try

User.joins(feed: :feed_tracks)
        .where('feed_tracks.track_id <> ?', unwanted_track_id)
        .order('id desc')
        .limit(1000)
        .to_sql


问:
meteor up - mup setup deploy error on digitalocean
Sorry for the question, but i didn't find any useful answer until now.

I am trying to follow a simple tutorial , and everything is going fine.

But when i type 'mup setup' on my local pc, I got this error:

```<code>Started TaskList: Setup Docker
[---.--.-.254] - Setup Docker
[---.--.-.254] x Setup Docker: FAILED

-----------------------------------STDERR-----------------------------------
bash: line 7: docker: command not found
rm: cannot remove ‘/var/cache/apt/archives/lock’: No such file or directory
W: Failed to fetch http://ubuntu.kurento.org/dists/xenial/InRelease  Unable to find expected entry 'km6/binary-amd64/Packages' in Release file (Wrong sources.list entry or malformed file)

E: Some index files failed to download. They have been ignored, or old ones used instead.
-----------------------------------STDOUT-----------------------------------
ce.com wily/main Translation-en [162 B]
Get:7 https://deb.nodesource.com wily/main Translation-en_US [162 B]
Get:8 https://deb.nodesource.com wily/main Translation-en [162 B]
Get:9 https://deb.nodesource.com wily/main Translation-en_US [162 B]
Hit http://downloads-distro.mongodb.org dist/10gen amd64 Packages
Get:10 https://deb.nodesource.com wily/main Translation-en [162 B]
Get:11 https://deb.nodesource.com wily/main Translation-en_US [162 B]
Hit http://downloads-distro.mongodb.org dist/10gen i386 Packages
Get:12 https://deb.nodesource.com wily/main Translation-en [162 B]
Get:13 https://deb.nodesource.com wily/main Translation-en_US [162 B]
Ign https://deb.nodesource.com wily/main Translation-en_US
Get:14 https://deb.nodesource.com wily/main Translation-en [162 B]
Ign https://deb.nodesource.com wily/main Translation-en
Ign http://downloads-distro.mongodb.org dist/10gen Translation-en_US
Ign http://downloads-distro.mongodb.org dist/10gen Translation-en
Fetched 12.8 kB in 3s (4,015 B/s)
----------------------------------------------------------------------------
</code>```

Note that login is succesful (I tried entering in mup.js a wrong password and process stops before all this).

Does anyone have an idea of why I'm getting this error and how to solve this? Do I have to install something on remote server?

答:
Have you tried to run sudo apt-get -f install on a remote server?

In my case this command has solved the issue.

Body:
Sorry for the question, but i didn't find any useful answer until now.

I am trying to follow a simple tutorial , and everything is going fine.

But when i type 'mup setup' on my local pc, I got this error:

Started TaskList: Setup Docker
[---.--.-.254] - Setup Docker
[---.--.-.254] x Setup Docker: FAILED

-----------------------------------STDERR-----------------------------------
bash: line 7: docker: command not found
rm: cannot remove ‘/var/cache/apt/archives/lock’: No such file or directory
W: Failed to fetch http://ubuntu.kurento.org/dists/xenial/InRelease  Unable to find expected entry 'km6/binary-amd64/Packages' in Release file (Wrong sources.list entry or malformed file)

E: Some index files failed to download. They have been ignored, or old ones used instead.
-----------------------------------STDOUT-----------------------------------
ce.com wily/main Translation-en [162 B]
Get:7 https://deb.nodesource.com wily/main Translation-en_US [162 B]
Get:8 https://deb.nodesource.com wily/main Translation-en [162 B]
Get:9 https://deb.nodesource.com wily/main Translation-en_US [162 B]
Hit http://downloads-distro.mongodb.org dist/10gen amd64 Packages
Get:10 https://deb.nodesource.com wily/main Translation-en [162 B]
Get:11 https://deb.nodesource.com wily/main Translation-en_US [162 B]
Hit http://downloads-distro.mongodb.org dist/10gen i386 Packages
Get:12 https://deb.nodesource.com wily/main Translation-en [162 B]
Get:13 https://deb.nodesource.com wily/main Translation-en_US [162 B]
Ign https://deb.nodesource.com wily/main Translation-en_US
Get:14 https://deb.nodesource.com wily/main Translation-en [162 B]
Ign https://deb.nodesource.com wily/main Translation-en
Ign http://downloads-distro.mongodb.org dist/10gen Translation-en_US
Ign http://downloads-distro.mongodb.org dist/10gen Translation-en
Fetched 12.8 kB in 3s (4,015 B/s)
----------------------------------------------------------------------------

Note that login is succesful (I tried entering in mup.js a wrong password and process stops before all this).

Does anyone have an idea of why I'm getting this error and how to solve this? Do I have to install something on remote server?


问:
Pick up lines from a file based on line numbers in another file
I have two files - one contains the addresses (line numbers) and the other one data, like this:

address file:

```<code>2
4
6
7
1
3
5
</code>```

data file

```<code>1.000451451
2.000589214
3.117892278
4.479511994
5.484514874
6.784499874
7.021239396
</code>```

I want to randomize the data file based on the numbers of address files
so I get:

```<code>2.000589214
4.479511994
6.784499874
7.021239396
1.000451451
3.117892278
5.484514874
</code>```

I want to do it either in python or in bash, but didn't yet find any solution.

答:
If you don't mind sed, we can use process substitution to achieve this easily:

```<code>sed -nf <(sed 's/$/p/' addr.txt) data.txt
</code>```

-n suppresses the default printing

-f makes sed read commands from the process substitution <(...)

<(sed 's/$/p/' addr.txt) creates sed print commands based on line numbers in addr.txt

Gives the output:

```<code>2.000589214
4.479511994
6.784499874
7.021239396
1.000451451
3.117892278
5.484514874
</code>```

Body:
I have two files - one contains the addresses (line numbers) and the other one data, like this:

address file:

2
4
6
7
1
3
5

data file

1.000451451
2.000589214
3.117892278
4.479511994
5.484514874
6.784499874
7.021239396

I want to randomize the data file based on the numbers of address files
so I get:

2.000589214
4.479511994
6.784499874
7.021239396
1.000451451
3.117892278
5.484514874

I want to do it either in python or in bash, but didn't yet find any solution.

Body:
If you don't mind sed, we can use process substitution to achieve this easily:

sed -nf <(sed 's/$/p/' addr.txt) data.txt

-n suppresses the default printing

-f makes sed read commands from the process substitution <(...)

<(sed 's/$/p/' addr.txt) creates sed print commands based on line numbers in addr.txt

Gives the output:

2.000589214
4.479511994
6.784499874
7.021239396
1.000451451
3.117892278
5.484514874


问:
doinbackground() method is not called in aync task
I am trying to upload post from my app to my database. To show the progress dialog when uploading is in progress I am using async task. The doinbackground() method is not executed. :

```<code>private ProgressDialog mProgress;
public void startPosting() {
//uploading posts
}

post.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Task task=new Task();
             if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.HONEYCOMB)
                task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            else
                task.execute();
        }
    });

}

class Task extends AsyncTask<Void,Void,Void>{

        @Override
        protected void onPreExecute() {
            mProgress = new ProgressDialog(PostActivity.this);

            mProgress.setMessage("Posting Alert");
            mProgress.show();
        }

        @Override
        protected Void doInBackground(Void... voids) {
            try {
                startPosting();
            }catch (Exception e){

            }

            return null;
        }

        @Override
        protected void onProgressUpdate(Void... values) {

        }

        @Override
        protected void onPostExecute(Void aVoid) {
            mProgress.dismiss();
            Toast.makeText(PostActivity.this, "Alert Posted", Toast.LENGTH_LONG).show();

        }
    }

}
</code>```

Any help is appreciated.
Thank you

答:
replace your async task class code with this code in your app.

```<code>//=====================================================================================
// Async Task Class
//=====================================================================================

public class LazyDataConnection extends AsyncTask<String, Void, String> {
    String method;

    public LazyDataConnection(String method) {
        this.method = method;
    }

    @Override
    protected String doInBackground(String... arg0) {
        method = arg0[0];
        return getData.callWebService_2(arg0[0], arg0[1]);
    }

    protected void onPostExecute(String xmlResponse) {

        if (xmlResponse.equals("")) {
            try {
                if (progDialog != null && progDialog.isShowing()) {
                    progDialog.dismiss();
                }
            } catch (Exception ex) {
            }
            Toast.makeText(getApplicationContext(), "No Internet Connection", Toast.LENGTH_LONG).show();
        } else if (method.equals("METHOD NAME")) { // method name
            try {
                if (progDialog != null && progDialog.isShowing()) {
                    progDialog.dismiss();
                }
            } catch (Exception ex) {
            }

            METHOD NAME(xmlResponse, "METHOD NAME");
            if (complaint_id != 0) {
                finish();
            }

            Toast.makeText(getApplicationContext(), alertmessage, Toast.LENGTH_LONG).show();

        }
    }
</code>```

`

if any query ask me.

Body:
I am trying to upload post from my app to my database. To show the progress dialog when uploading is in progress I am using async task. The doinbackground() method is not executed. :

private ProgressDialog mProgress;
public void startPosting() {
//uploading posts
}

post.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Task task=new Task();
             if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.HONEYCOMB)
                task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            else
                task.execute();
        }
    });

}

class Task extends AsyncTask<Void,Void,Void>{

        @Override
        protected void onPreExecute() {
            mProgress = new ProgressDialog(PostActivity.this);

            mProgress.setMessage("Posting Alert");
            mProgress.show();
        }

        @Override
        protected Void doInBackground(Void... voids) {
            try {
                startPosting();
            }catch (Exception e){

            }

            return null;
        }

        @Override
        protected void onProgressUpdate(Void... values) {

        }

        @Override
        protected void onPostExecute(Void aVoid) {
            mProgress.dismiss();
            Toast.makeText(PostActivity.this, "Alert Posted", Toast.LENGTH_LONG).show();

        }
    }

}

Any help is appreciated.
Thank you

Body:
replace your async task class code with this code in your app.

//=====================================================================================
// Async Task Class
//=====================================================================================

public class LazyDataConnection extends AsyncTask<String, Void, String> {
    String method;

    public LazyDataConnection(String method) {
        this.method = method;
    }

    @Override
    protected String doInBackground(String... arg0) {
        method = arg0[0];
        return getData.callWebService_2(arg0[0], arg0[1]);
    }

    protected void onPostExecute(String xmlResponse) {

        if (xmlResponse.equals("")) {
            try {
                if (progDialog != null && progDialog.isShowing()) {
                    progDialog.dismiss();
                }
            } catch (Exception ex) {
            }
            Toast.makeText(getApplicationContext(), "No Internet Connection", Toast.LENGTH_LONG).show();
        } else if (method.equals("METHOD NAME")) { // method name
            try {
                if (progDialog != null && progDialog.isShowing()) {
                    progDialog.dismiss();
                }
            } catch (Exception ex) {
            }

            METHOD NAME(xmlResponse, "METHOD NAME");
            if (complaint_id != 0) {
                finish();
            }

            Toast.makeText(getApplicationContext(), alertmessage, Toast.LENGTH_LONG).show();

        }
    }

`

if any query ask me.


问:
Error: ScalesList was built with an incompatible version of ggproto
I'm doing a presentation in slidfy, using the deckjs framework.
Everything was ok, but suddenly this chunk of code:

```<code>ggplot(cars, aes(x = speed, y = dist)) +  geom_point(color = 'red') + stat_smooth(method = "lm", formula = y ~ x, size = 0.5, se = F)
</code>```

stopped working and shows this error instead:

```<code>## Error: ScalesList was built with an incompatible version of ggproto.
## Please reinstall the package that provides this extension.
</code>```

The code works perfectly when executed from source or console... But it doesn't work anymore from the R markdown. The function that fails is the stat_smooth(). The rest visualizes ok if executed without the smooth.

Here and here a similar error is reported, and the solution offered is to reinstall ggplot and the packages from github, but I'm not sure which packages should I install, and, besides, the code only fails from Rmarkdown, and not when executed from console or source.

Thanks

答: I had similar problem with geom_tufteboxplot . I first updated ggplot2 & ggthemes package, then detached all ggplot related packages and reloaded them. It worked for me.

Body:
I'm doing a presentation in slidfy, using the deckjs framework.
Everything was ok, but suddenly this chunk of code:

ggplot(cars, aes(x = speed, y = dist)) +  geom_point(color = 'red') + stat_smooth(method = "lm", formula = y ~ x, size = 0.5, se = F)

stopped working and shows this error instead:

## Error: ScalesList was built with an incompatible version of ggproto.
## Please reinstall the package that provides this extension.

The code works perfectly when executed from source or console... But it doesn't work anymore from the R markdown. The function that fails is the stat_smooth(). The rest visualizes ok if executed without the smooth.

Here and here a similar error is reported, and the solution offered is to reinstall ggplot and the packages from github, but I'm not sure which packages should I install, and, besides, the code only fails from Rmarkdown, and not when executed from console or source.

Thanks


问:
UICollectionView ScrollTo Crashing
I am attempting to have my UICollectionView in my custom UIView, be able to scroll to a page when a button is pressed in the main VC. Unfortunately everytime I call the method to do it in the MainVC, it crashes, @ to scrollToItem .

here is my MainVC.

```<code>let mainView = MainViewsHome()
</code>```

In the ViewWillAppear:

```<code>/** Setting up the bottom half **/
        mainView.frame = CGRect(x:self.view.frame.width * 0, y:self.view.frame.height / 6.2, width:self.view.frame.width,height:self.view.frame.height / 1.1925)
        mainView.backgroundColor = UIColor.clear
        self.view.addSubview(mainView)
</code>```

&& My custom UIView

```<code>class MainViewsHome: UIView, UIGestureRecognizerDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

    var cellId = "Cell"

    var collectionView : UICollectionView!

     override init(frame: CGRect) {

        super.init(frame: CGRect(x:0, y:0, width:UIScreen.main.bounds.width, height: UIScreen.main.bounds.height / 1.3))

        /**Creation of the View **/
        let flowLayout : UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        flowLayout.scrollDirection = .horizontal

        let collectionView = UICollectionView(frame: CGRect(x:self.frame.width * 0,y:self.frame.height * 0,width:self.frame.width,height: self.frame.height), collectionViewLayout: flowLayout)
        collectionView.register(uploadGenreSelectionCVC.self, forCellWithReuseIdentifier: cellId)
        collectionView.isPagingEnabled = true
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = UIColor.purple

        self.addSubview(collectionView)

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func moveToPage() {
     print("we are moving to page")

        self.collectionView.scrollToItem(at: 2 as IndexPath, at: UICollectionViewScrollPosition.right, animated: true)

    }
</code>```

&& Then in my MainVC I am calling: mainView.moveToPage() Where am I going wrong with my understanding?

答:
Problem is with 2 as IndexPath, IndexPath is not Integer so you need to make the object of IndexPath using its init init(item:section:). and after that scroll collectionView to specific item this way.

```<code>func moveToPage() {
    let indexPath = IndexPath(item: 2, section: 0) //Change section from 0 to other if you are having multiple sections
    self.collectionView.scrollToItem(at: indexPath, at: .right, animated: true)
}
</code>```

Note: CollectionView's items start at 0 index so if you want to scroll to 2nd item then make indexPath using IndexPath(item: 1, section: 0) because 2nd will scroll at 3rd cell of collectionView.

Title: UICollectionView ScrollTo Crashing

Body:
I am attempting to have my UICollectionView in my custom UIView, be able to scroll to a page when a button is pressed in the main VC. Unfortunately everytime I call the method to do it in the MainVC, it crashes, @ to scrollToItem .

here is my MainVC.

let mainView = MainViewsHome()

In the ViewWillAppear:

/** Setting up the bottom half **/
        mainView.frame = CGRect(x:self.view.frame.width * 0, y:self.view.frame.height / 6.2, width:self.view.frame.width,height:self.view.frame.height / 1.1925)
        mainView.backgroundColor = UIColor.clear
        self.view.addSubview(mainView)

&& My custom UIView

class MainViewsHome: UIView, UIGestureRecognizerDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

    var cellId = "Cell"

    var collectionView : UICollectionView!

     override init(frame: CGRect) {

        super.init(frame: CGRect(x:0, y:0, width:UIScreen.main.bounds.width, height: UIScreen.main.bounds.height / 1.3))

        /**Creation of the View **/
        let flowLayout : UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        flowLayout.scrollDirection = .horizontal

        let collectionView = UICollectionView(frame: CGRect(x:self.frame.width * 0,y:self.frame.height * 0,width:self.frame.width,height: self.frame.height), collectionViewLayout: flowLayout)
        collectionView.register(uploadGenreSelectionCVC.self, forCellWithReuseIdentifier: cellId)
        collectionView.isPagingEnabled = true
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = UIColor.purple

        self.addSubview(collectionView)

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func moveToPage() {
     print("we are moving to page")

        self.collectionView.scrollToItem(at: 2 as IndexPath, at: UICollectionViewScrollPosition.right, animated: true)

    }

&& Then in my MainVC I am calling: mainView.moveToPage() Where am I going wrong with my understanding?

Body:
Problem is with 2 as IndexPath, IndexPath is not Integer so you need to make the object of IndexPath using its init init(item:section:). and after that scroll collectionView to specific item this way.

func moveToPage() {
    let indexPath = IndexPath(item: 2, section: 0) //Change section from 0 to other if you are having multiple sections
    self.collectionView.scrollToItem(at: indexPath, at: .right, animated: true)
}

Note: CollectionView's items start at 0 index so if you want to scroll to 2nd item then make indexPath using IndexPath(item: 1, section: 0) because 2nd will scroll at 3rd cell of collectionView.


问:
Is mysql insertion possible without the field names
To save time and space is it possible to insert into a mysql db without the use of the field names as shown below:

With the fields

```<code>INSERT INTO `wp_realty_listingsdb` (`listingsdb_id`,`user_id`,`class_id)
values
    (1,1,1);
</code>```

Without the fields

```<code>INSERT INTO `wp_realty_listingsdb` values(1,1,1);
</code>```

答:
If you are adding values for all the columns of the table, you do not need to specify the column names in the SQL query. However, make sure the order of the values is in the same order as the columns in the table.

Otherwise, if you are inserting to specific columns of table then you must enter the column names.

Body:
To save time and space is it possible to insert into a mysql db without the use of the field names as shown below:

With the fields

INSERT INTO `wp_realty_listingsdb` (`listingsdb_id`,`user_id`,`class_id)
values
    (1,1,1);

Without the fields

INSERT INTO `wp_realty_listingsdb` values(1,1,1);


问:
Retrieve template parameters from CXXConstructExpr in Clang AST
Say I have a variable declaration like this:

```<code>std::vector<MyType> myVector(1);
</code>```

This is represented as a CXXConstructExpr in the Clang AST. I have a matcher that finds this CXXConstructExpr, but I'd like to extract the decl for MyType from it.

I've tried all sorts of things, but nothing seems to work:

```<code>const CXXConstructExpr* construct = Result.Nodes.getNodeAs<CXXConstructExpr>("expr");
construct->getConstructor()->getTemplateSpecializationArgs()  // Always nullptr
construct->getConstructor()->getParent()  // Seems to lose the template parameters
construct->getConstructor()->getDescribedTemplate()  // Always nullptr
</code>```

答:
Here's a matcher:

```<code>varDecl(
  has(
    cxxConstructExpr()
  )
 ,hasType(
    classTemplateSpecializationDecl().bind(sp_dcl_bd_name_)
  )
).bind(var_bd_name_);
</code>```

It starts with the VarDecl and traverses to the type, which is a ClassTemplateSpecializationDecl buried in vector's ClassTemplateDecl. In the callback, one can work from the ClassTemplateSpecializationDecl to the template argument list, and operate on the individual template arguments:

```<code>using CTSD = ClassTemplateSpecializationDecl;
CTSD * spec_decl =
    const_cast<CTSD *>(result.Nodes.getNodeAs<CTSD>(sp_dcl_bd_name_));
VarDecl * var_decl =
    const_cast<VarDecl *>(result.Nodes.getNodeAs<VarDecl>(var_bd_name_));
if(spec_decl && var_decl) {
  // get the template args
  TemplateArgumentList const &tal(spec_decl->getTemplateArgs());
  for(unsigned i = 0; i < tal.size(); ++i){
    TemplateArgument const &ta(tal[i]);
    // is this arg a type arg? If so, get that type
    TemplateArgument::ArgKind k(ta.getKind());
    std::string argName = "";
    if(k==TemplateArgument::ArgKind::Type){
      QualType t = ta.getAsType();
      argName = t.getAsString();
    }
    // Could do similar actions for integral args, etc...
    std::cout << "For variable declared at "
      << corct::sourceRangeAsString(var_decl->getSourceRange(),&sm) << ":"
      << spec_decl->getNameAsString()
      << ": template arg " << (i+1) << ": " << argName << std::endl;
  } // for template args
} // if
</code>```

For this code:

```<code>struct B{int b_;};
std::vector<B> vb(1);
</code>```

this produces:

```<code>For variable declared at <line:14:1, col:20>:vector: template arg 1: struct B
For variable declared at <col:1, col:20>:vector: template arg 2: class std::__1::allocator<struct B>
</code>```

The full example is in the Code Analysis and Refactoring with Clang Tools examples repo at github: https://github.com/lanl/CoARCT (see apps/TemplateType.cc)

Body:
Say I have a variable declaration like this:

std::vector<MyType> myVector(1);

This is represented as a CXXConstructExpr in the Clang AST. I have a matcher that finds this CXXConstructExpr, but I'd like to extract the decl for MyType from it.

I've tried all sorts of things, but nothing seems to work:

const CXXConstructExpr* construct = Result.Nodes.getNodeAs<CXXConstructExpr>("expr");
construct->getConstructor()->getTemplateSpecializationArgs()  // Always nullptr
construct->getConstructor()->getParent()  // Seems to lose the template parameters
construct->getConstructor()->getDescribedTemplate()  // Always nullptr

Body:
Here's a matcher:

varDecl(
  has(
    cxxConstructExpr()
  )
 ,hasType(
    classTemplateSpecializationDecl().bind(sp_dcl_bd_name_)
  )
).bind(var_bd_name_);

It starts with the VarDecl and traverses to the type, which is a ClassTemplateSpecializationDecl buried in vector's ClassTemplateDecl. In the callback, one can work from the ClassTemplateSpecializationDecl to the template argument list, and operate on the individual template arguments:

using CTSD = ClassTemplateSpecializationDecl;
CTSD * spec_decl =
    const_cast<CTSD *>(result.Nodes.getNodeAs<CTSD>(sp_dcl_bd_name_));
VarDecl * var_decl =
    const_cast<VarDecl *>(result.Nodes.getNodeAs<VarDecl>(var_bd_name_));
if(spec_decl && var_decl) {
  // get the template args
  TemplateArgumentList const &tal(spec_decl->getTemplateArgs());
  for(unsigned i = 0; i < tal.size(); ++i){
    TemplateArgument const &ta(tal[i]);
    // is this arg a type arg? If so, get that type
    TemplateArgument::ArgKind k(ta.getKind());
    std::string argName = "";
    if(k==TemplateArgument::ArgKind::Type){
      QualType t = ta.getAsType();
      argName = t.getAsString();
    }
    // Could do similar actions for integral args, etc...
    std::cout << "For variable declared at "
      << corct::sourceRangeAsString(var_decl->getSourceRange(),&sm) << ":"
      << spec_decl->getNameAsString()
      << ": template arg " << (i+1) << ": " << argName << std::endl;
  } // for template args
} // if

For this code:

struct B{int b_;};
std::vector<B> vb(1);

this produces:

For variable declared at <line:14:1, col:20>:vector: template arg 1: struct B
For variable declared at <col:1, col:20>:vector: template arg 2: class std::__1::allocator<struct B>

The full example is in the Code Analysis and Refactoring with Clang Tools examples repo at github: https://github.com/lanl/CoARCT (see apps/TemplateType.cc)