问:
Maven: build Docker images of children projects
My project has the following structure:

```<code>pom.xml
  |
  x----child1
  |      |
  |      x----pom.xml
  |
  x----child2
         |
         x----pom.xml
</code>```

There is a pom father and two children poms. The build of the children uses the Spotify Plugin to generate the Docker images of the projects. My question is, how can I invoke both the build from the root directory? I basically need to invoke the spotify plugin build on the children modules.
I tried to use

```<code>mvn clean install
</code>```

but the children are built with maven-compiler-plugin, and not with the docker-maven-plugin.

This is the build I use in the children:

```<code><build>
    <plugins>
        <plugin>
            <groupId>com.spotify</groupId>
            <artifactId>docker-maven-plugin</artifactId>
            <version>${spotify.plugin.version}</version>
            <configuration>
                <imageName>childImage</imageName>
                <dockerDirectory>${project.build.directory}/../src/docker</dockerDirectory>
                <resources>
                    <resource>
                        <targetPath>/</targetPath>
                        <directory>${project.build.directory}</directory>
                        <include>${project.build.finalName}.jar</include>
                    </resource>
                </resources>
            </configuration>
        </plugin>
    </plugins>
</build>
</code>```

In the pom father I already defined the modules like this.

```<code>   <modules>
        <module>child1</module>
        <module>child2</module>
   </modules>
</code>```

Thanks in advice!

答:
You have couple of options to tackle this issue:

Configure the plugin in the parent pom's  section but default the plugin configuration to skip the docker build, and override that in the child module to not skip

Configure it only in the child module and bind the build goal to the package phase.

I have been using [2] with following in child pom.xml:

```<code><build>
  <plugins>
    ...
    <plugin>
      <groupId>com.spotify</groupId>
      <artifactId>docker-maven-plugin</artifactId>
      <version>0.4.13</version>
      <executions>
        <execution>
          <goals>
            <goal>build</goal>
          </goals>
          <phase>package</phase>
        </execution>
      </executions>
      <configuration>
        <imageName>example</imageName>
        <baseImage>example</baseImage>
        <resources>
          <resource>
            <targetPath>/</targetPath>
            <directory>target</directory>
            <include>example.war</include>
          </resource>
        </resources>
      </configuration>
    </plugin>
  ...
  </plugins>
</build>
</code>```

Body:
My project has the following structure:

pom.xml
  |
  x----child1
  |      |
  |      x----pom.xml
  |
  x----child2
         |
         x----pom.xml

There is a pom father and two children poms. The build of the children uses the Spotify Plugin to generate the Docker images of the projects. My question is, how can I invoke both the build from the root directory? I basically need to invoke the spotify plugin build on the children modules.
I tried to use

mvn clean install

but the children are built with maven-compiler-plugin, and not with the docker-maven-plugin.

This is the build I use in the children:

<build>
    <plugins>
        <plugin>
            <groupId>com.spotify</groupId>
            <artifactId>docker-maven-plugin</artifactId>
            <version>${spotify.plugin.version}</version>
            <configuration>
                <imageName>childImage</imageName>
                <dockerDirectory>${project.build.directory}/../src/docker</dockerDirectory>
                <resources>
                    <resource>
                        <targetPath>/</targetPath>
                        <directory>${project.build.directory}</directory>
                        <include>${project.build.finalName}.jar</include>
                    </resource>
                </resources>
            </configuration>
        </plugin>
    </plugins>
</build>

In the pom father I already defined the modules like this.

   <modules>
        <module>child1</module>
        <module>child2</module>
   </modules>

Thanks in advice!

Body:
You have couple of options to tackle this issue:

Configure the plugin in the parent pom's  section but default the plugin configuration to skip the docker build, and override that in the child module to not skip

Configure it only in the child module and bind the build goal to the package phase.

I have been using [2] with following in child pom.xml:

<build>
  <plugins>
    ...
    <plugin>
      <groupId>com.spotify</groupId>
      <artifactId>docker-maven-plugin</artifactId>
      <version>0.4.13</version>
      <executions>
        <execution>
          <goals>
            <goal>build</goal>
          </goals>
          <phase>package</phase>
        </execution>
      </executions>
      <configuration>
        <imageName>example</imageName>
        <baseImage>example</baseImage>
        <resources>
          <resource>
            <targetPath>/</targetPath>
            <directory>target</directory>
            <include>example.war</include>
          </resource>
        </resources>
      </configuration>
    </plugin>
  ...
  </plugins>
</build>


来源: stackexchange

问:
Microsoft Office Communicator 2007 when client not on NT Domain
I'm trying to run Microsoft Office Communicator 2007 on client which is not part of an NT Domain, but which has VPN access to my corporate network.  When trying to authenticate, however, MOC just hangs forever.  Is there some way to configure MOC so that it connects, even if the client machine is not a member of the NT Domain?

I have verified that a corporate machine can connect from the same remote location, so it's not a networking issue.

答: I figured this out: you need to have the domain's certificate installed as a Trusted Root on the client machine. So, it's doable: you just need to really really trust the server if it's a self-signed certificate.</p>

ContentLicense: CC BY-SA 2.5


问:
Summing columns with same names in the row and show it in new sheet run with date
In my Excel worksheet Cell F5, F7, F8 has a name of XXX and F6,F9,F10 has name of YYY and hours for those names is mentioned in Column  K. There are two types of hours and that will be mentioned in Column H.

Each row will be entered on different dates and dates will be on Column A.

What I need is, if I enter from date and to date on Command box it must sum up the hours on that particular name with type of hours worked within those dates and show it in new tab.

答:
You can use SUMIFS formula:

Formula for B5 in Sheet2:

```<code>=SUMIFS(Sheet1!$H:$H,Sheet1!$A:$A,">="&Sheet2!$B$1,Sheet1!$A:$A,"<="&Sheet2!$B$2,Sheet1!$F:$F,Sheet2!A5)
</code>```

Formula for B6 in Sheet2:

```<code>=SUMIFS(Sheet1!$H:$H,Sheet1!$A:$A,">="&Sheet2!$B$1,Sheet1!$A:$A,"<="&Sheet2!$B$2,Sheet1!$F:$F,Sheet2!A6)
</code>```

Formula for C5 in Sheet2:

```<code>=SUMIFS(Sheet1!$K:$K,Sheet1!$A:$A,">="&Sheet2!$B$1,Sheet1!$A:$A,"<="&Sheet2!$B$2,Sheet1!$F:$F,Sheet2!A5)
</code>```

Formula for C6 in Sheet2:

```<code>=SUMIFS(Sheet1!$K:$K,Sheet1!$A:$A,">="&Sheet2!$B$1,Sheet1!$A:$A,"<="&Sheet2!$B$2,Sheet1!$F:$F,Sheet2!A6)
</code>```

Sheet1:

Sheet2:

ContentLicense: CC BY-SA 3.0

Body:
You can use SUMIFS formula:

Formula for B5 in Sheet2:

=SUMIFS(Sheet1!$H:$H,Sheet1!$A:$A,">="&Sheet2!$B$1,Sheet1!$A:$A,"<="&Sheet2!$B$2,Sheet1!$F:$F,Sheet2!A5)

Formula for B6 in Sheet2:

=SUMIFS(Sheet1!$H:$H,Sheet1!$A:$A,">="&Sheet2!$B$1,Sheet1!$A:$A,"<="&Sheet2!$B$2,Sheet1!$F:$F,Sheet2!A6)

Formula for C5 in Sheet2:

=SUMIFS(Sheet1!$K:$K,Sheet1!$A:$A,">="&Sheet2!$B$1,Sheet1!$A:$A,"<="&Sheet2!$B$2,Sheet1!$F:$F,Sheet2!A5)

Formula for C6 in Sheet2:

=SUMIFS(Sheet1!$K:$K,Sheet1!$A:$A,">="&Sheet2!$B$1,Sheet1!$A:$A,"<="&Sheet2!$B$2,Sheet1!$F:$F,Sheet2!A6)

Sheet1:

Sheet2:


问:
How to share data between two presenters in MVP architecture in Android?
Here's an example scenario:

I have an activity (view) and a presenter for that view. The presenter fetches a list of users from a network API and holds it in memory using a List object. The activity contains different types of fragments to display the content about the users based on User.type. The two fragments (UserType1Fragment and UserType2Fragment) have their own respective presenters too.

The activity's presenter decides what type (I or II) of fragment is shown next based. The fragments' presenters decide how the user object is displayed and handle a button click event called killUser(). This should update the List object in the activity's presenter.

This is where the problem lies:

How do the fragment presents have a reference to the data in activity presenter? The presenters shouldn't directly communicate with each other. Maybe I should abstract out the List into a repository/interactor? How would the List be shared among presenters?

答:
So I ended up implementing something like what @Jahnold recommended. (I'll post the diagram in the link provided for an idea stackoverflow.com/a/41966497/568898 )

Hannes Dorfmann (the guy who created/manages the famous Mosby MVP library : Github link ) also pointed me in this direction.

Implementation

I have a presenter for the main activity and multiple fragments that can be used in that activity. Each fragment has its own presenter. Then I use a repository (search for repository pattern) which is basically stores the models and the business logic. For my use case, I keep this repository as a singleton. The repository provides data in three forms, from an online api, an sqllite database, or a cache stored in memory (basically an arraylist of items). I also have some currentitem int indexes and stuff in this repository, that get updated based on the current state.

Hence the data, the state and the business logic are stored in this shared repository. The presenters and the views are pretty dumb. I don't have much business logic (application specific logic) in presenters. They simply have the logic associated with how the data has to be displayed (view specific logic) and preprocessing in logic them.

Example

Whenever the fragment and activity need to talk to each other (via presenters) when the user clicks a button in a child fragment, the fragment asks its presenter to handleClick, the presenters updates the repository's currentItemSelected data (or something else) and asks the fragment to fire an event (say onbuttonclick) to an interface listener which the activity implements. When the activity gets the event, it asks it's own presenter to handle it and in turn the activity presenter looks for an update in the repository to get the new currentItemSelected.

Extra Info (advanced version):

You can also follow Clean architecture which is sort of a more advanced version of MVP architecture. MVP just deals with the architecture of the views, where as Clean architecture also deals with business logic and data architecture, MVP is just a small part of clean arch which is used to handle the views. Using this, you can break down the mega repo in my case into even further use-cases (or interactors) that handle a specific business logic use-case, and the repository just provides data. So the logic flow is now view-->presenter-->interactor-->repo and back.


问:
Change event on Select without triggering Click event
I've got this code:

```<code>var $d_docSelect = $("<select>").appendTo($registerExamBox).click(function(){
    while($d_docSelect[0].firstChild) $d_docSelect[0].removeChild($d_docSelect[0].firstChild);
    $.ajax({
        url: 'test.php',
        type: 'POST',
        data: {
            func: 87,
        }
    }).done(function($msg){
        try{
            $docs = JSON.parse($msg);
        }catch($e){
            console.log($e.message);
            return false;
        }
        $docs.forEach(function($row){
            $("<option>", {"doc" : $row[0]}).text($row[1] + ' ' + $row[2] + ' ' + $row[3]).appendTo($d_docSelect);
        })
        $("<option>").text("Dodaj").appendTo($d_docSelect);
    });
}).change(function(){
    if($d_docSelect[0].selectedIndex == $d_docSelect[0].length - 1){
        addDoc($d_docSelect);
    }
});
</code>```

Everytime i change option i select, not only "change" event triggers, but "click" too.
I don't want to trigger "click" when changing option, and I don't know how. I didn't find answer here and on Google.

答:
Well.

I think i guess what you want to do, but i'm not sure you're on the right way.

Loading options on click of the select, means that you'll load these options each time the click event happens.
Why are you not trying to load these options when your page is ready (maybe the most common way, but you could have a good reason I don't know)?

Then, you'll only got your change event and no conflict.

Nowthere if someone knows and could show an example of how to cancel click when the change event occurs (I already know that change occurs before click)

Body:
I've got this code:

var $d_docSelect = $("<select>").appendTo($registerExamBox).click(function(){
    while($d_docSelect[0].firstChild) $d_docSelect[0].removeChild($d_docSelect[0].firstChild);
    $.ajax({
        url: 'test.php',
        type: 'POST',
        data: {
            func: 87,
        }
    }).done(function($msg){
        try{
            $docs = JSON.parse($msg);
        }catch($e){
            console.log($e.message);
            return false;
        }
        $docs.forEach(function($row){
            $("<option>", {"doc" : $row[0]}).text($row[1] + ' ' + $row[2] + ' ' + $row[3]).appendTo($d_docSelect);
        })
        $("<option>").text("Dodaj").appendTo($d_docSelect);
    });
}).change(function(){
    if($d_docSelect[0].selectedIndex == $d_docSelect[0].length - 1){
        addDoc($d_docSelect);
    }
});

Everytime i change option i select, not only "change" event triggers, but "click" too.
I don't want to trigger "click" when changing option, and I don't know how. I didn't find answer here and on Google.


问:
RecyclerView not refreshing after inserting item using Alertdialog
I have an RecycleView. i take an ArrayList for Fetch all my Category that i inserted in mySqliteDatabase. and finally i set this ArrayList into RecycleView using its Adapter.

Problem:

(1) First Open CategoryActivity. (no categories)
(2) Add First Category, Second, Third  no one is Refreshing.
(3) but after Adding First if i go back. and come again in that Activity. and if now i am insert Second categories then all [next items] are getting refresh.

My Problem is whenever i insert 1st Category. it insert successfully but it is not shown in my RecycleView or an ArrayList [means Recycleview not refreshing].

but my Main Problem is my RecycleView is not Refreshing only FirstCategory on My ArrayList.. After adding First item my next all Arraylist item is getting Refreshed.

Below is my All Code.

CategoryAdapter

```<code>public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.MyViewHolder> implements Filterable {

        private ArrayList<CategoryModel> dataList;

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView tvCategoryItem;

            MyViewHolder(View view) {
                super(view);
                tvCategoryItem = (TextView) view.findViewById(R.id.tvCategoryName);
            }
        }

        CategoryAdapter(ArrayList<CategoryModel> dataSet) {
            this.dataList = dataSet;
            this.filterList = dataSet;
        }

        // I used this method too. but same problem.
        void refreshAdapter(ArrayList<CategoryModel> dataSet) {
            dataList.clear();
            dataList.addAll(dataSet);
            notifyDataSetChanged();
        }

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

            return new MyViewHolder(itemView);
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            CategoryModel categoryModel = dataList.get(position);
            holder.tvCategoryItem.setText(categoryModel.getCategoryName());
        }

        @Override
        public int getItemCount() {
            return dataList.size();
        }
    }
</code>```

CategoryListActivity

```<code>MyDatabase myDb;
            CategoryModel categoryModel;
            RecyclerView recyclerCategory;
            RecyclerView.LayoutManager layoutManager;
            CategoryAdapter adapter;
            ArrayList<CategoryModel> allCategory;
            int CategoryType;

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

    myDb = new MyDatabase(this);
    recyclerCategory = (RecyclerView) findViewById(R.id.recyclerCategory);

    CategoryType = CaseActivity.CategoryType;
    Log.d(GlobalConstant.KEY_CATEGORY_TYPE, "" + CategoryType);

    allCategory = myDb.getCategoryByType(CategoryType);

    if (allCategory.size() == 0) {
        Toast.makeText(this, "No Category", Toast.LENGTH_SHORT).show();
    }

    adapter = new CategoryAdapter(allCategory);
    recyclerCategory.setAdapter(adapter);
    layoutManager = new LinearLayoutManager(this);
    recyclerCategory.setLayoutManager(layoutManager);
    recyclerCategory.setItemAnimator(new DefaultItemAnimator());
    recyclerCategory.setHasFixedSize(true);

    recyclerCategory.addOnItemTouchListener(new RecyclerItemClickListener(this, recyclerCategory,
            new RecyclerItemClickListener.OnItemTouchListener() {
                @Override
                public void onItemClick(View view, int position) {
                    TextView tvCategoryItem = (TextView) view.findViewById(R.id.tvCategoryName);
                    String CategoryName = tvCategoryItem.getText().toString();

                    Intent intent = new Intent();
                    CategoryId = allCategory.get(+position).getCategoryId();
                    intent.putExtra("CategoryId", String.valueOf(CategoryId));

                    Log.e("Clicked Cat Id is ", "" + CategoryId);
                    intent.putExtra("CategoryName", CategoryName);
                    setResult(Activity.RESULT_OK, intent);
                    finish();
                }

                @Override
                public void onLongItemClick(View view, int position) {

                }
            }
    ));
}

private void openAlert() {
    final EditText etCategoryName = new EditText(this);

    CustomAlertDialog dialog1 = new CustomAlertDialog(this);
    dialog1.setTitle("Add Category");
    dialog1.setView(etCategoryName);
    dialog1.setCancelable(true);

    dialog1.setPositiveButton("Add", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            final String CategoryName = etCategoryName.getText().toString().trim();
            final String storedCategoryName = myDb.ExistCategory(CategoryName);

            if (CategoryName.equals("") && CategoryName.length() == 0) {
                Builder builder1 = GlobalConstant.createAlert(CategoryListActivity.this, "Warning", "Enter Category Name");
                builder1.setPositiveButton("Back", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                });
            } else {
                if (CategoryName.equals(storedCategoryName)) {
                    Builder builder1 = GlobalConstant.createAlert(CategoryListActivity.this, "Warning", "Category Already Exists");
                    builder1.setPositiveButton("Back", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                        }
                    });
                } else {
                    dialogInterface.dismiss();

                    categoryModel = new CategoryModel(CategoryName, String.valueOf(CategoryType));

                    myDb.createCategory(categoryModel);

                    Toast.makeText(CategoryListActivity.this, "CategoryName " + CategoryName
                            + "\nCategoryType " + CategoryType, Toast.LENGTH_SHORT).show();

                    allCategory.clear();

                    allCategory = myDb.getCategoryByType(CategoryType);

                    adapter.notifyDataSetChanged();

                }
            }
        }
    });
    dialog1.show();
}

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
                case R.id.action_add:
                    openAlert();
                default:
                    return super.onOptionsItemSelected(item);
            }
        }
    }
</code>```

my createCategory() method.

```<code>public long createCategory(CategoryModel categoryModel) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();

        values.put(CATEGORY_NAME, categoryModel.getCategoryName());
        values.put(CATEGORY_TYPE, categoryModel.getCategoryType());

        long CategoryId = db.insert(TABLE_CATEGORY, null, values);
        db.close();
        return CategoryId;
    }
</code>```

and Finally my getCategoryByType() method on My Database.

```<code>public ArrayList<CategoryModel> getCategoryByType(int CategoryType) {
        ArrayList<CategoryModel> Categories = new ArrayList<>();
        // String selectQuery = "SELECT " + CATEGORY_NAME + " FROM " + TABLE_CATEGORY + " WHERE " + CATEGORY_TYPE + " = " + CategoryType;
        String selectQuery = "SELECT * FROM " + TABLE_CATEGORY + " WHERE " + CATEGORY_TYPE + " = " + CategoryType + " ORDER BY CategoryId DESC";
        Log.e(DB_LOG, selectQuery);
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.rawQuery(selectQuery, null);
        if (cursor != null && cursor.getCount() > 0) {
            if (cursor.moveToFirst()) {
                do {
                    CategoryModel categoryModel = new CategoryModel();

                    categoryModel.setCategoryId(cursor.getInt(cursor.getColumnIndex(CATEGORY_ID)));
                    categoryModel.setCategoryName(cursor.getString(cursor.getColumnIndex(CATEGORY_NAME)));
                    categoryModel.setCategoryType(cursor.getString(cursor.getColumnIndex(CATEGORY_TYPE)));

                    Categories.add(categoryModel);
                } while (cursor.moveToNext());
            }
            cursor.close();
        }
        return Categories;
    }
</code>```

Any Type of Help, Suggestion is much Appreciated.....Thanks in advance

Below is Screenshot after adding First Item.

First Item Inserted but not shown in RecycleView

My LogCat Screenshot is below.

Logcat Screenshot

答:
Change your Activity onCreate:

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

        myDb = new MyDatabase(this);
        recyclerCategory = (RecyclerView) findViewById(R.id.recyclerCategory);

        CategoryType = CaseActivity.CategoryType;
        Log.d(GlobalConstant.KEY_CATEGORY_TYPE, "" + CategoryType);
        allCategory = new ArrayList<>();
        adapter = new CategoryAdapter(allCategory);
        layoutManager = new LinearLayoutManager(this);
        recyclerCategory.setLayoutManager(layoutManager);
        recyclerCategory.setItemAnimator(new DefaultItemAnimator());
        recyclerCategory.setHasFixedSize(true);
        recyclerCategory.setAdapter(adapter);

        allCategory = myDb.getCategoryByType(CategoryType);
        adapter.notifyDataSetChange();

        if (allCategory.size() == 0) {

            Toast.makeText(this, "No Category", Toast.LENGTH_SHORT).show();
        }
    }
</code>```

and inside setPositiveButton, replace

```<code>adapter = new CategoryAdapter(allCategory);
recyclerCategory.setAdapter(adapter);

adapter.notifyDataSetChanged();
</code>```

with

```<code>adapter.notifyDataSetChanged();
</code>```

Also replace

```<code>allCategory = myDb.getCategoryByType(CategoryType);
</code>```

with

```<code>allCategory.addAll(myDb.getCategoryByType(CategoryType));
</code>```

And try to run your program again.

Body:
I have an RecycleView. i take an ArrayList for Fetch all my Category that i inserted in mySqliteDatabase. and finally i set this ArrayList into RecycleView using its Adapter.

Problem:

(1) First Open CategoryActivity. (no categories)
(2) Add First Category, Second, Third  no one is Refreshing.
(3) but after Adding First if i go back. and come again in that Activity. and if now i am insert Second categories then all [next items] are getting refresh.

My Problem is whenever i insert 1st Category. it insert successfully but it is not shown in my RecycleView or an ArrayList [means Recycleview not refreshing].

but my Main Problem is my RecycleView is not Refreshing only FirstCategory on My ArrayList.. After adding First item my next all Arraylist item is getting Refreshed.

Below is my All Code.

CategoryAdapter

public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.MyViewHolder> implements Filterable {

        private ArrayList<CategoryModel> dataList;

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView tvCategoryItem;

            MyViewHolder(View view) {
                super(view);
                tvCategoryItem = (TextView) view.findViewById(R.id.tvCategoryName);
            }
        }

        CategoryAdapter(ArrayList<CategoryModel> dataSet) {
            this.dataList = dataSet;
            this.filterList = dataSet;
        }

        // I used this method too. but same problem.
        void refreshAdapter(ArrayList<CategoryModel> dataSet) {
            dataList.clear();
            dataList.addAll(dataSet);
            notifyDataSetChanged();
        }

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

            return new MyViewHolder(itemView);
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            CategoryModel categoryModel = dataList.get(position);
            holder.tvCategoryItem.setText(categoryModel.getCategoryName());
        }

        @Override
        public int getItemCount() {
            return dataList.size();
        }
    }

CategoryListActivity

MyDatabase myDb;
            CategoryModel categoryModel;
            RecyclerView recyclerCategory;
            RecyclerView.LayoutManager layoutManager;
            CategoryAdapter adapter;
            ArrayList<CategoryModel> allCategory;
            int CategoryType;

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

    myDb = new MyDatabase(this);
    recyclerCategory = (RecyclerView) findViewById(R.id.recyclerCategory);

    CategoryType = CaseActivity.CategoryType;
    Log.d(GlobalConstant.KEY_CATEGORY_TYPE, "" + CategoryType);

    allCategory = myDb.getCategoryByType(CategoryType);

    if (allCategory.size() == 0) {
        Toast.makeText(this, "No Category", Toast.LENGTH_SHORT).show();
    }

    adapter = new CategoryAdapter(allCategory);
    recyclerCategory.setAdapter(adapter);
    layoutManager = new LinearLayoutManager(this);
    recyclerCategory.setLayoutManager(layoutManager);
    recyclerCategory.setItemAnimator(new DefaultItemAnimator());
    recyclerCategory.setHasFixedSize(true);

    recyclerCategory.addOnItemTouchListener(new RecyclerItemClickListener(this, recyclerCategory,
            new RecyclerItemClickListener.OnItemTouchListener() {
                @Override
                public void onItemClick(View view, int position) {
                    TextView tvCategoryItem = (TextView) view.findViewById(R.id.tvCategoryName);
                    String CategoryName = tvCategoryItem.getText().toString();

                    Intent intent = new Intent();
                    CategoryId = allCategory.get(+position).getCategoryId();
                    intent.putExtra("CategoryId", String.valueOf(CategoryId));

                    Log.e("Clicked Cat Id is ", "" + CategoryId);
                    intent.putExtra("CategoryName", CategoryName);
                    setResult(Activity.RESULT_OK, intent);
                    finish();
                }

                @Override
                public void onLongItemClick(View view, int position) {

                }
            }
    ));
}

private void openAlert() {
    final EditText etCategoryName = new EditText(this);

    CustomAlertDialog dialog1 = new CustomAlertDialog(this);
    dialog1.setTitle("Add Category");
    dialog1.setView(etCategoryName);
    dialog1.setCancelable(true);

    dialog1.setPositiveButton("Add", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            final String CategoryName = etCategoryName.getText().toString().trim();
            final String storedCategoryName = myDb.ExistCategory(CategoryName);

            if (CategoryName.equals("") && CategoryName.length() == 0) {
                Builder builder1 = GlobalConstant.createAlert(CategoryListActivity.this, "Warning", "Enter Category Name");
                builder1.setPositiveButton("Back", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                });
            } else {
                if (CategoryName.equals(storedCategoryName)) {
                    Builder builder1 = GlobalConstant.createAlert(CategoryListActivity.this, "Warning", "Category Already Exists");
                    builder1.setPositiveButton("Back", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                        }
                    });
                } else {
                    dialogInterface.dismiss();

                    categoryModel = new CategoryModel(CategoryName, String.valueOf(CategoryType));

                    myDb.createCategory(categoryModel);

                    Toast.makeText(CategoryListActivity.this, "CategoryName " + CategoryName
                            + "\nCategoryType " + CategoryType, Toast.LENGTH_SHORT).show();

                    allCategory.clear();

                    allCategory = myDb.getCategoryByType(CategoryType);

                    adapter.notifyDataSetChanged();

                }
            }
        }
    });
    dialog1.show();
}

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
                case R.id.action_add:
                    openAlert();
                default:
                    return super.onOptionsItemSelected(item);
            }
        }
    }

my createCategory() method.

public long createCategory(CategoryModel categoryModel) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();

        values.put(CATEGORY_NAME, categoryModel.getCategoryName());
        values.put(CATEGORY_TYPE, categoryModel.getCategoryType());

        long CategoryId = db.insert(TABLE_CATEGORY, null, values);
        db.close();
        return CategoryId;
    }

and Finally my getCategoryByType() method on My Database.

public ArrayList<CategoryModel> getCategoryByType(int CategoryType) {
        ArrayList<CategoryModel> Categories = new ArrayList<>();
        // String selectQuery = "SELECT " + CATEGORY_NAME + " FROM " + TABLE_CATEGORY + " WHERE " + CATEGORY_TYPE + " = " + CategoryType;
        String selectQuery = "SELECT * FROM " + TABLE_CATEGORY + " WHERE " + CATEGORY_TYPE + " = " + CategoryType + " ORDER BY CategoryId DESC";
        Log.e(DB_LOG, selectQuery);
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.rawQuery(selectQuery, null);
        if (cursor != null && cursor.getCount() > 0) {
            if (cursor.moveToFirst()) {
                do {
                    CategoryModel categoryModel = new CategoryModel();

                    categoryModel.setCategoryId(cursor.getInt(cursor.getColumnIndex(CATEGORY_ID)));
                    categoryModel.setCategoryName(cursor.getString(cursor.getColumnIndex(CATEGORY_NAME)));
                    categoryModel.setCategoryType(cursor.getString(cursor.getColumnIndex(CATEGORY_TYPE)));

                    Categories.add(categoryModel);
                } while (cursor.moveToNext());
            }
            cursor.close();
        }
        return Categories;
    }

Any Type of Help, Suggestion is much Appreciated.....Thanks in advance

Below is Screenshot after adding First Item.

First Item Inserted but not shown in RecycleView

My LogCat Screenshot is below.

Logcat Screenshot

Body:
Change your Activity onCreate:

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

        myDb = new MyDatabase(this);
        recyclerCategory = (RecyclerView) findViewById(R.id.recyclerCategory);

        CategoryType = CaseActivity.CategoryType;
        Log.d(GlobalConstant.KEY_CATEGORY_TYPE, "" + CategoryType);
        allCategory = new ArrayList<>();
        adapter = new CategoryAdapter(allCategory);
        layoutManager = new LinearLayoutManager(this);
        recyclerCategory.setLayoutManager(layoutManager);
        recyclerCategory.setItemAnimator(new DefaultItemAnimator());
        recyclerCategory.setHasFixedSize(true);
        recyclerCategory.setAdapter(adapter);

        allCategory = myDb.getCategoryByType(CategoryType);
        adapter.notifyDataSetChange();

        if (allCategory.size() == 0) {

            Toast.makeText(this, "No Category", Toast.LENGTH_SHORT).show();
        }
    }

and inside setPositiveButton, replace

adapter = new CategoryAdapter(allCategory);
recyclerCategory.setAdapter(adapter);

adapter.notifyDataSetChanged();

with

adapter.notifyDataSetChanged();

Also replace

allCategory = myDb.getCategoryByType(CategoryType);

with

allCategory.addAll(myDb.getCategoryByType(CategoryType));

And try to run your program again.


问:
DbContext Dispose is extremely slow after any Update
I've updated my code to properly dispose of all my EF6 DbContext objects after use, via a using statement (according to almost everyone in the online community). So now I can see exactly how long it takes to call dispose.

What I've discovered is that the DBContext goes away in milliseconds, unless the DbContext has had piece of content modified, and a SaveChanges command executed against it. When that happens (on any piece of content), then the disposal takes about 13 seconds.

Obviously, I can't see what the Dispose command is actually doing behind the scenes, but it's ridiculously slow and I am not sure how to proceed. Suggestions?

答:
We had the same problem with a Azure SQL Database. We configurate your EntityFramework based on the msdn Documentation over Handling of Transaction Commit Failures

After we detect this problem we remove this line of code, to turn this feature off again:

```<code>public class MyConfiguration : DbConfiguration
{
  public MyConfiguration()
  {
    // SetTransactionHandler(SqlProviderServices.ProviderInvariantName, () => new CommitFailureHandler());
    SetExecutionStrategy(SqlProviderServices.ProviderInvariantName, () => new SqlAzureExecutionStrategy());
  }
}
</code>```

Based of the codeplex Documentation Handling of Transaction Commit Failures you can add this code at application start to clean up the __TransactionHistory table.

```<code>var commitFailureHandler = CommitFailureHandler.FromContext(context);
if (commitFailureHandler != null)
{
    commitFailureHandler.ClearTransactionHistory();
}
</code>```

Body:
We had the same problem with a Azure SQL Database. We configurate your EntityFramework based on the msdn Documentation over Handling of Transaction Commit Failures

After we detect this problem we remove this line of code, to turn this feature off again:

public class MyConfiguration : DbConfiguration
{
  public MyConfiguration()
  {
    // SetTransactionHandler(SqlProviderServices.ProviderInvariantName, () => new CommitFailureHandler());
    SetExecutionStrategy(SqlProviderServices.ProviderInvariantName, () => new SqlAzureExecutionStrategy());
  }
}

Based of the codeplex Documentation Handling of Transaction Commit Failures you can add this code at application start to clean up the __TransactionHistory table.

var commitFailureHandler = CommitFailureHandler.FromContext(context);
if (commitFailureHandler != null)
{
    commitFailureHandler.ClearTransactionHistory();
}


问:
Pass arguments with white spaces to batch file
I am so sure answer is as simple as passing "" to the arguments in batch file. But this fails. Here is what I am trying to do.

```<code>Test.bat env "Some cmd"
</code>```

This "Some cmd" is another command that needs to run in environment set by env.

Test.bat:

```<code>Something like  set Env with %1%

set cmd=%2%

%cmd%
</code>```

The above fails with '"Some cmd"' is not recognized as a cmd.

Only way I can get this to work is if I use "%cmd%" in batch file. Is this right?

答: I think you need to specify path where   "Some cmd" is present.  </p>

Body:
I am so sure answer is as simple as passing "" to the arguments in batch file. But this fails. Here is what I am trying to do.

Test.bat env "Some cmd"

This "Some cmd" is another command that needs to run in environment set by env.

Test.bat:

Something like  set Env with %1%

set cmd=%2%

%cmd%

The above fails with '"Some cmd"' is not recognized as a cmd.

Only way I can get this to work is if I use "%cmd%" in batch file. Is this right?


问:
ASP MVC Layout Page does not run custom JavaScript
I am working on a new project and therefore used a boilerplate (this one)
For some reason the custom javascript I add in my _Layout page does not run.

This is what I have on the bottom of my body tag :

```<code>@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/jqueryvalunobtrusive")
@Scripts.Render("~/bundles/tether")
@Scripts.Render("~/bundles/bootstrap")
@Scripts.Render("~/bundles/site")
@Scripts.Render("~/Scripts/search.js") ==> Works aswell
<script type="text/javascript"> ==> Does not work
    alert("loading");
</script>
@RenderSection("JavaScript", false)
</code>```

Everything works from external files except the alert. If I inspect my website I see that the code is added :

All of the JavaScript in my other views that I place inside a section does not work aswell :

```<code>@section JavaScript
{
    <script type="text/javascript">
        alert("test");
        $().ready(function () {
            console.log("view");
            alert("test");
       });
    </script>
}
</code>```

I have no idea whats wrong. Never had this before. Any help is much appreciated.

Thx!

答:
Answer by the maker of the boilerplate :

"You need to read about Content Security Policy (CSP). Inline scripts are blocked by default as a security feature."

Body:
I am working on a new project and therefore used a boilerplate (this one)
For some reason the custom javascript I add in my _Layout page does not run.

This is what I have on the bottom of my body tag :

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/jqueryvalunobtrusive")
@Scripts.Render("~/bundles/tether")
@Scripts.Render("~/bundles/bootstrap")
@Scripts.Render("~/bundles/site")
@Scripts.Render("~/Scripts/search.js") ==> Works aswell

@RenderSection("JavaScript", false)

Everything works from external files except the alert. If I inspect my website I see that the code is added :

All of the JavaScript in my other views that I place inside a section does not work aswell :

@section JavaScript
{

}

I have no idea whats wrong. Never had this before. Any help is much appreciated.

Thx!


问:
XSLT transform Dictionary<string,string>
I have the following class:

```<code>public class HelloWorldDictionary
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Dictionary<string, string> Items { get; set; }
}
</code>```

And an XSLT like so:

```<code><xsl:template match="/HelloWorldDictionary">
  <html xmlns="http://www.w3.org/1999/xhtml">
  <br/>
  <a>
    Hi there <xsl:value-of select="FirstName" /> <xsl:value-of select="LastName" />!
  </a>
  <br/>
  <br/>
  <xsl:for-each select="Items/*">
    <xsl:value-of select="Key?" />
    <span> : </span>
    <xsl:value-of select="Value?" />
    <br/>
  </xsl:for-each>
</html>
</code>```

As you can expect, the above for-each won't work...

The resulting XML is as follows:

```<code><HelloWorldDictionary xmlns="http://schemas.datacontract.org/2004/07/CommunicationTests.XsltEmail" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<FirstName>Foo</FirstName>
<Items xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
    <a:KeyValueOfstringstring>
        <a:Key>Key1</a:Key>
        <a:Value>12345678912</a:Value>
    </a:KeyValueOfstringstring>
    <a:KeyValueOfstringstring>
        <a:Key>Key2</a:Key>
        <a:Value>ABC1234</a:Value>
    </a:KeyValueOfstringstring>
    <a:KeyValueOfstringstring>
        <a:Key>Key3</a:Key>
        <a:Value>Test</a:Value>
    </a:KeyValueOfstringstring>
</Items>
<LastName>Bar</LastName>
</code>```

What is the correct XSLT syntax for me to grab each key value pair from the Items dictionary?

答:
With the xml in the question, namespaces are the awkward bit; you'd need to  observe the namespaces throughout. Let's assume that you have:

```<code>xmlns:dc="http://schemas.datacontract.org/2004/07/CommunicationTests.XsltEmail"
xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays"
</code>```

at the top of your xslt; then we have (untested) something like:

```<code><xsl:template match="/dc:HelloWorldDictionary">
  <html xmlns="http://www.w3.org/1999/xhtml">
  <br/>
  <a>
    Hi there <xsl:value-of select="dc:FirstName" /> <xsl:value-of select="dc:LastName" />!
  </a>
  <br/>
  <br/>
  <xsl:for-each select="dc:Items/*">
    <xsl:value-of select="a:Key" />
    <span> : </span>
    <xsl:value-of select="a:Value" />
    <br/>
  </xsl:for-each>
</html>
</code>```

However, IMO you'd be better off sticking to the default (empty) namespace in most cases; sadly, DataContractSerializer disagrees...

Body:
I have the following class:

public class HelloWorldDictionary
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Dictionary<string, string> Items { get; set; }
}

And an XSLT like so:

<xsl:template match="/HelloWorldDictionary">

    Hi there <xsl:value-of select="FirstName" /> <xsl:value-of select="LastName" />!

  <xsl:for-each select="Items/*">
    <xsl:value-of select="Key?" />
     :
    <xsl:value-of select="Value?" />

  </xsl:for-each>

As you can expect, the above for-each won't work...

The resulting XML is as follows:

<HelloWorldDictionary xmlns="http://schemas.datacontract.org/2004/07/CommunicationTests.XsltEmail" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<FirstName>Foo</FirstName>
<Items xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">

        Key1
        12345678912

        Key2
        ABC1234

        Key3
        Test

</Items>
<LastName>Bar</LastName>

What is the correct XSLT syntax for me to grab each key value pair from the Items dictionary?

Body:
With the xml in the question, namespaces are the awkward bit; you'd need to  observe the namespaces throughout. Let's assume that you have:

xmlns:dc="http://schemas.datacontract.org/2004/07/CommunicationTests.XsltEmail"
xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays"

at the top of your xslt; then we have (untested) something like:

<xsl:template match="/dc:HelloWorldDictionary">
  <html xmlns="http://www.w3.org/1999/xhtml">
  <br/>
  <a>
    Hi there <xsl:value-of select="dc:FirstName" /> <xsl:value-of select="dc:LastName" />!
  </a>
  <br/>
  <br/>
  <xsl:for-each select="dc:Items/*">
    <xsl:value-of select="a:Key" />
    <span> : </span>
    <xsl:value-of select="a:Value" />
    <br/>
  </xsl:for-each>
</html>

However, IMO you'd be better off sticking to the default (empty) namespace in most cases; sadly, DataContractSerializer disagrees...


问:
Python - checking for an ip address (and nothing after it)
I'm trying to create a Python (2.7) function that will take a string and return true if its input is an ip address, possibly with a slash in the end, but false otherwise.
It needs to return a false value if the string is not just an ip address, but an ip address followed by some sort of path.
It doesn't matter if the address is a valid IP or not (999.999.999.999 can be considered an ip address for that matter).

eg:
"124.131.141.248" - true
"124.131.141.248/" - true
"124.131.141.248/bla" - false
"hello world" - false

I've tried searching for a solution but most solutions include just checking for a valid IP address, disregarding my other needs.

Any help would be appreciated.

Thanks,

答:
That seems to be working:</p>

```<code>import re
def valid_ip(ip):
    if re.match(r'(\d+\.?){4}\\?$', ip):
        return True
    else:
        return False
</code>```

Body:
That seems to be working:

import re
def valid_ip(ip):
    if re.match(r'(\d+\.?){4}\\?$', ip):
        return True
    else:
        return False


问:
C# Linq XML InvalidOperationException
I am trying to create an XML file based on a .csv file. I figured I could use my old method for reading the .csv file and just replace some parts. However I get an exception saying:

InvalidOperationException

Here is my code:

```<code>    public void LoadFile() {
        XDocument outputDocument = new XDocument();
        outputDocument.Add(new XElement("Inventory"));

        using (var fstream = File.OpenRead(FilePathProducts))
        using (var fileReader = new StreamReader(fstream)) {
            while (!fileReader.EndOfStream) {
                var readLine = fileReader.ReadLine();
                var words = readLine.Split(';');

                outputDocument.Add(
                    new XElement("Item",
                        new XElement("Name", words[1]),
                        new XElement("Count", words[3]),
                        new XElement("Price", words[4]),
                        new XElement("Comment", "<Missing Value>"),
                        new XElement("Artist", "<Missing Value>"),
                        new XElement("Publisher", "Nintendo"),
                        new XElement("Genre", "<Missing Value>"),
                        new XElement("Year", words[0]),
                        new XElement("ProductID", words[2])
                    )
                );
            }
        }

        outputDocument.Save(FilePathResult);
    }
</code>```

It says something about "a wrongfully structured document is created" (roughly translated.)

When I tried removing the loop, the output file only displayed a self-closing Inventory-tag. I expected it to be an open and close -tag. So I'm guessing something is wrong with line 3 of the code above.

答:
You are trying to append your Item elements directly to the XML document and XML documents are not allowed to have more than one root element. That is why you are getting an error.

I presume you actually want to add them to the Inventory element, in which case you should do this:

```<code>public void LoadFile() {
    var outputDocument = new XDocument();
    var inventory = new XElement("Inventory");
    outputDocument.Add(inventory);

    using (var fstream = File.OpenRead(FilePathProducts))
    using (var fileReader = new StreamReader(fstream)) {
        while (!fileReader.EndOfStream) {
            var readLine = fileReader.ReadLine();
            var words = readLine.Split(';');

            inventory.Add(
                new XElement("Item",
                    new XElement("Name", words[1]),
                    new XElement("Count", words[3]),
                    new XElement("Price", words[4]),
                    new XElement("Comment", "<Missing Value>"),
                    new XElement("Artist", "<Missing Value>"),
                    new XElement("Publisher", "Nintendo"),
                    new XElement("Genre", "<Missing Value>"),
                    new XElement("Year", words[0]),
                    new XElement("ProductID", words[2])
                )
            );
        }
    }

    outputDocument.Save(FilePathResult);
}
</code>```

Title: C# Linq XML InvalidOperationException

Body:
I am trying to create an XML file based on a .csv file. I figured I could use my old method for reading the .csv file and just replace some parts. However I get an exception saying:

InvalidOperationException

Here is my code:

    public void LoadFile() {
        XDocument outputDocument = new XDocument();
        outputDocument.Add(new XElement("Inventory"));

        using (var fstream = File.OpenRead(FilePathProducts))
        using (var fileReader = new StreamReader(fstream)) {
            while (!fileReader.EndOfStream) {
                var readLine = fileReader.ReadLine();
                var words = readLine.Split(';');

                outputDocument.Add(
                    new XElement("Item",
                        new XElement("Name", words[1]),
                        new XElement("Count", words[3]),
                        new XElement("Price", words[4]),
                        new XElement("Comment", "<Missing Value>"),
                        new XElement("Artist", "<Missing Value>"),
                        new XElement("Publisher", "Nintendo"),
                        new XElement("Genre", "<Missing Value>"),
                        new XElement("Year", words[0]),
                        new XElement("ProductID", words[2])
                    )
                );
            }
        }

        outputDocument.Save(FilePathResult);
    }

It says something about "a wrongfully structured document is created" (roughly translated.)

When I tried removing the loop, the output file only displayed a self-closing Inventory-tag. I expected it to be an open and close -tag. So I'm guessing something is wrong with line 3 of the code above.

Body:
You are trying to append your Item elements directly to the XML document and XML documents are not allowed to have more than one root element. That is why you are getting an error.

I presume you actually want to add them to the Inventory element, in which case you should do this:

public void LoadFile() {
    var outputDocument = new XDocument();
    var inventory = new XElement("Inventory");
    outputDocument.Add(inventory);

    using (var fstream = File.OpenRead(FilePathProducts))
    using (var fileReader = new StreamReader(fstream)) {
        while (!fileReader.EndOfStream) {
            var readLine = fileReader.ReadLine();
            var words = readLine.Split(';');

            inventory.Add(
                new XElement("Item",
                    new XElement("Name", words[1]),
                    new XElement("Count", words[3]),
                    new XElement("Price", words[4]),
                    new XElement("Comment", "<Missing Value>"),
                    new XElement("Artist", "<Missing Value>"),
                    new XElement("Publisher", "Nintendo"),
                    new XElement("Genre", "<Missing Value>"),
                    new XElement("Year", words[0]),
                    new XElement("ProductID", words[2])
                )
            );
        }
    }

    outputDocument.Save(FilePathResult);
}


问:
Want to display 12 months name from sql server
I want to display 12 months name from sql server. i though to accomplish insert month name into temp table and then fire select statement on that table. so i had to write 12 insert table to insert 12 months name. so i search google to find better solution and i got it.

here is the sql statement

```<code>WITH R(N) AS
(
    SELECT 0
    UNION ALL
    SELECT N+1
    FROM R
    WHERE N < 12
)

SELECT LEFT(DATENAME(MONTH,DATEADD(MONTH,-N,GETDATE())),3) AS [month]
FROM R
</code>```

the above script works perfectly but my problem is i just do not understand how it works. i never work with CTE.

so tell me what is the meaning of  WITH R(N) AS

and see this sql

```<code>SELECT LEFT(DATENAME(MONTH,DATEADD(MONTH,-N,GETDATE())),3) AS [month] FROM R
when above sql execute how it is getting value for -N ??
because here i have not set anything for -N ??
</code>```

so please anyone help me to understand how whole thing works. thaks

My Second Phase of Question

just have look a and tell me

```<code>;WITH months(MonthNumber) AS
(
    SELECT 0
    UNION ALL
    SELECT MonthNumber+1
    FROM months
    WHERE MonthNumber < 12
)
</code>```

onething is not clear to me that why only first time the below part execute

```<code>SELECT 0
UNION ALL
SELECT MonthNumber+1
FROM months
WHERE MonthNumber < 12
</code>```

and from the 2nd time only this below part execute

```<code>SELECT MonthNumber+1
FROM months
WHERE MonthNumber < 12
</code>```

whenever we write two sql statement using Union and execute then always it return data from two sql state but specially in this case from the 2nd time why only this below part
execute

```<code>SELECT MonthNumber+1
FROM months
WHERE MonthNumber < 12
</code>```

basically i not familiar with CTE with recursion technique and that is why things is not getting clear to me. if possible please discuss how CTE recursion works.

```<code>DECLARE @TotaDays SMALLINT
DECLARE @Month VARCHAR(15)
DECLARE @Year SMALLINT
DECLARE @date DATETIME
SET @Month = 'January'
SET @Year = 2015
SET @date = '01 ' + @Month + ' ' + CONVERT(VARCHAR(4),@Year)
SET @TotaDays = 0
SELECT @TotaDays = DATEDIFF(DAY, @date, DATEADD(MONTH, 1, @date))

;WITH months(MonthNumber) AS
(
    SELECT 1
    UNION ALL
    SELECT MonthNumber+1
    FROM months
    WHERE MonthNumber < @TotaDays
)

select * from months;
</code>```

答:
This query is to obtain all month names and month no's</p>

```<code>SELECT DATENAME(MONTH, DATEADD(MM, s.number, CONVERT(DATETIME, 0))) AS [MonthName],
MONTH(DATEADD(MM, s.number, CONVERT(DATETIME, 0))) AS [MonthNumber]
FROM master.dbo.spt_values s
WHERE [type] = 'P' AND s.number BETWEEN 0 AND 11
ORDER BY 2
</code>```

Body:
I want to display 12 months name from sql server. i though to accomplish insert month name into temp table and then fire select statement on that table. so i had to write 12 insert table to insert 12 months name. so i search google to find better solution and i got it.

here is the sql statement

WITH R(N) AS
(
    SELECT 0
    UNION ALL
    SELECT N+1
    FROM R
    WHERE N < 12
)

SELECT LEFT(DATENAME(MONTH,DATEADD(MONTH,-N,GETDATE())),3) AS [month]
FROM R

the above script works perfectly but my problem is i just do not understand how it works. i never work with CTE.

so tell me what is the meaning of  WITH R(N) AS

and see this sql

SELECT LEFT(DATENAME(MONTH,DATEADD(MONTH,-N,GETDATE())),3) AS [month] FROM R
when above sql execute how it is getting value for -N ??
because here i have not set anything for -N ??

so please anyone help me to understand how whole thing works. thaks

My Second Phase of Question

just have look a and tell me

;WITH months(MonthNumber) AS
(
    SELECT 0
    UNION ALL
    SELECT MonthNumber+1
    FROM months
    WHERE MonthNumber < 12
)

onething is not clear to me that why only first time the below part execute

SELECT 0
UNION ALL
SELECT MonthNumber+1
FROM months
WHERE MonthNumber < 12

and from the 2nd time only this below part execute

SELECT MonthNumber+1
FROM months
WHERE MonthNumber < 12

whenever we write two sql statement using Union and execute then always it return data from two sql state but specially in this case from the 2nd time why only this below part
execute

SELECT MonthNumber+1
FROM months
WHERE MonthNumber < 12

basically i not familiar with CTE with recursion technique and that is why things is not getting clear to me. if possible please discuss how CTE recursion works.

DECLARE @TotaDays SMALLINT
DECLARE @Month VARCHAR(15)
DECLARE @Year SMALLINT
DECLARE @date DATETIME
SET @Month = 'January'
SET @Year = 2015
SET @date = '01 ' + @Month + ' ' + CONVERT(VARCHAR(4),@Year)
SET @TotaDays = 0
SELECT @TotaDays = DATEDIFF(DAY, @date, DATEADD(MONTH, 1, @date))

;WITH months(MonthNumber) AS
(
    SELECT 1
    UNION ALL
    SELECT MonthNumber+1
    FROM months
    WHERE MonthNumber < @TotaDays
)

select * from months;

Body:
This query is to obtain all month names and month no's

SELECT DATENAME(MONTH, DATEADD(MM, s.number, CONVERT(DATETIME, 0))) AS [MonthName],
MONTH(DATEADD(MM, s.number, CONVERT(DATETIME, 0))) AS [MonthNumber]
FROM master.dbo.spt_values s
WHERE [type] = 'P' AND s.number BETWEEN 0 AND 11
ORDER BY 2


问:
IDEA IllegalStateException: Service is dying when running JUnit test with Kotlin
Yesterday I was working on my codebase and I was running my unit tests against my code when suddenly I saw this in the IDEA log:

Error:Kotlin: [Internal Error] java.lang.IllegalStateException:
  Service is dying
      at org.jetbrains.kotlin.daemon.common.CompileService$CallResult$Dying.get(CompileService.kt:60)
      at org.jetbrains.kotlin.daemon.common.CompileService$CallResult$Dying.get(CompileService.kt:59)
      at org.jetbrains.kotlin.compilerRunner.JpsKotlinCompilerRunner.compileWithDaemon(JpsKotlinCompilerRunner.kt:127)
      at org.jetbrains.kotlin.compilerRunner.JpsKotlinCompilerRunner.compileWithDaemonOrFallback(JpsKotlinCompilerRunner.kt:100)
      at org.jetbrains.kotlin.compilerRunner.JpsKotlinCompilerRunner.compileWithDaemonOrFallback(JpsKotlinCompilerRunner.kt:35)
      at org.jetbrains.kotlin.compilerRunner.KotlinCompilerRunner.runCompiler(KotlinCompilerRunner.kt:115)
      at org.jetbrains.kotlin.compilerRunner.JpsKotlinCompilerRunner.runK2JvmCompiler(JpsKotlinCompilerRunner.kt:65)
      at org.jetbrains.kotlin.jps.build.KotlinBuilder.compileToJvm(KotlinBuilder.kt:740)
      at org.jetbrains.kotlin.jps.build.KotlinBuilder.doCompileModuleChunk(KotlinBuilder.kt:458)
      at org.jetbrains.kotlin.jps.build.KotlinBuilder.doBuild(KotlinBuilder.kt:264)
      at org.jetbrains.kotlin.jps.build.KotlinBuilder.build(KotlinBuilder.kt:181)
      at org.jetbrains.jps.incremental.IncProjectBuilder.runModuleLevelBuilders(IncProjectBuilder.java:1282)
      at org.jetbrains.jps.incremental.IncProjectBuilder.runBuildersForChunk(IncProjectBuilder.java:956)
      at org.jetbrains.jps.incremental.IncProjectBuilder.buildTargetsChunk(IncProjectBuilder.java:1028)
      at org.jetbrains.jps.incremental.IncProjectBuilder.buildChunkIfAffected(IncProjectBuilder.java:915)
      at org.jetbrains.jps.incremental.IncProjectBuilder.buildChunks(IncProjectBuilder.java:741)
      at org.jetbrains.jps.incremental.IncProjectBuilder.runBuild(IncProjectBuilder.java:387)
      at org.jetbrains.jps.incremental.IncProjectBuilder.build(IncProjectBuilder.java:195)
      at org.jetbrains.jps.cmdline.BuildRunner.runBuild(BuildRunner.java:138)
      at org.jetbrains.jps.cmdline.BuildSession.runBuild(BuildSession.java:295)
      at org.jetbrains.jps.cmdline.BuildSession.run(BuildSession.java:125)
      at org.jetbrains.jps.cmdline.BuildMain$MyMessageHandler$1.run(BuildMain.java:238)
      at org.jetbrains.jps.service.impl.SharedThreadPoolImpl$1.run(SharedThreadPoolImpl.java:44)
      at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
      at java.util.concurrent.FutureTask.run(FutureTask.java:266)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
      at java.lang.Thread.run(Thread.java:745)

Was this an April's fool's joke from JetBrains?

I've never seen this before. killall java and an IDEA restart solved the problem and I was not able to reproduce this. Is this something which is documented (I did not found any hits on google) or just a one-off glitch in IDEA when compiling Kotlin code? What does this error mean?

Note that the unit test I ran was a simple exploratory test and I think it is irrelevant here:

```<code>internal fun fetchAsListWithSiblings(): List<Message<T>> {
    val first = this
    var currentMsg = first
    val result = mutableListOf(currentMsg)
    while(currentMsg.next.isPresent) {
        val next = currentMsg.next.get()
        currentMsg = next
        result.add(next)
    }
    return result
}

@Test
fun shouldFetchSiblingsWhenFetchSiblingsIsCalledWithMultipleSiblings() {
    val expected = listOf("foo", "bar", "baz")
    val messages = Message.createMultiple(expected)

    assertThat(messages.fetchAsListWithSiblings().map { it.payload }).isEqualTo(expected)
}
</code>```

答: It is the known problem - race condition on the parallel compilation start. Usually repeating the build solves it. Here is the relevant issue KT-15562 in the YouTrack. The problem is supposed to be finally fixed in Kotlin 1.1.2 release.</p>

Body:
Yesterday I was working on my codebase and I was running my unit tests against my code when suddenly I saw this in the IDEA log:

Error:Kotlin: [Internal Error] java.lang.IllegalStateException:
  Service is dying
      at org.jetbrains.kotlin.daemon.common.CompileService$CallResult$Dying.get(CompileService.kt:60)
      at org.jetbrains.kotlin.daemon.common.CompileService$CallResult$Dying.get(CompileService.kt:59)
      at org.jetbrains.kotlin.compilerRunner.JpsKotlinCompilerRunner.compileWithDaemon(JpsKotlinCompilerRunner.kt:127)
      at org.jetbrains.kotlin.compilerRunner.JpsKotlinCompilerRunner.compileWithDaemonOrFallback(JpsKotlinCompilerRunner.kt:100)
      at org.jetbrains.kotlin.compilerRunner.JpsKotlinCompilerRunner.compileWithDaemonOrFallback(JpsKotlinCompilerRunner.kt:35)
      at org.jetbrains.kotlin.compilerRunner.KotlinCompilerRunner.runCompiler(KotlinCompilerRunner.kt:115)
      at org.jetbrains.kotlin.compilerRunner.JpsKotlinCompilerRunner.runK2JvmCompiler(JpsKotlinCompilerRunner.kt:65)
      at org.jetbrains.kotlin.jps.build.KotlinBuilder.compileToJvm(KotlinBuilder.kt:740)
      at org.jetbrains.kotlin.jps.build.KotlinBuilder.doCompileModuleChunk(KotlinBuilder.kt:458)
      at org.jetbrains.kotlin.jps.build.KotlinBuilder.doBuild(KotlinBuilder.kt:264)
      at org.jetbrains.kotlin.jps.build.KotlinBuilder.build(KotlinBuilder.kt:181)
      at org.jetbrains.jps.incremental.IncProjectBuilder.runModuleLevelBuilders(IncProjectBuilder.java:1282)
      at org.jetbrains.jps.incremental.IncProjectBuilder.runBuildersForChunk(IncProjectBuilder.java:956)
      at org.jetbrains.jps.incremental.IncProjectBuilder.buildTargetsChunk(IncProjectBuilder.java:1028)
      at org.jetbrains.jps.incremental.IncProjectBuilder.buildChunkIfAffected(IncProjectBuilder.java:915)
      at org.jetbrains.jps.incremental.IncProjectBuilder.buildChunks(IncProjectBuilder.java:741)
      at org.jetbrains.jps.incremental.IncProjectBuilder.runBuild(IncProjectBuilder.java:387)
      at org.jetbrains.jps.incremental.IncProjectBuilder.build(IncProjectBuilder.java:195)
      at org.jetbrains.jps.cmdline.BuildRunner.runBuild(BuildRunner.java:138)
      at org.jetbrains.jps.cmdline.BuildSession.runBuild(BuildSession.java:295)
      at org.jetbrains.jps.cmdline.BuildSession.run(BuildSession.java:125)
      at org.jetbrains.jps.cmdline.BuildMain$MyMessageHandler$1.run(BuildMain.java:238)
      at org.jetbrains.jps.service.impl.SharedThreadPoolImpl$1.run(SharedThreadPoolImpl.java:44)
      at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
      at java.util.concurrent.FutureTask.run(FutureTask.java:266)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
      at java.lang.Thread.run(Thread.java:745)

Was this an April's fool's joke from JetBrains?

I've never seen this before. killall java and an IDEA restart solved the problem and I was not able to reproduce this. Is this something which is documented (I did not found any hits on google) or just a one-off glitch in IDEA when compiling Kotlin code? What does this error mean?

Note that the unit test I ran was a simple exploratory test and I think it is irrelevant here:

internal fun fetchAsListWithSiblings(): List<Message<T>> {
    val first = this
    var currentMsg = first
    val result = mutableListOf(currentMsg)
    while(currentMsg.next.isPresent) {
        val next = currentMsg.next.get()
        currentMsg = next
        result.add(next)
    }
    return result
}

@Test
fun shouldFetchSiblingsWhenFetchSiblingsIsCalledWithMultipleSiblings() {
    val expected = listOf("foo", "bar", "baz")
    val messages = Message.createMultiple(expected)

    assertThat(messages.fetchAsListWithSiblings().map { it.payload }).isEqualTo(expected)
}


问:
Fetch record if found match of one comma separated record with another comma separated records
I have 3 tables

user

service

userServices

User Table

```<code>Id  |  Name   | Status
------------------------
1   |  User1  | y
2   |  User2  | y
3   |  User3  | y
4   |  User4  | y
</code>```

Service Table

```<code>Id  |  ServiceName   | Status
------------------------
1   |  Service1      | y
2   |  Service2      | y
3   |  Service3      | y
4   |  Service4      | y
</code>```

User Service Table

```<code>Id  |  UserId   | ServiceId   | Status
-----------------------------------------
1   |  1        | 1           | y
2   |  1        | 3           | y
3   |  1        | 2           | y
4   |  1        | 4           | y
5   |  2        | 2           | y
6   |  2        | 3           | y
7   |  2        | 4           | y
8   |  3        | 1           | y
9   |  3        | 3           | y
10  |  3        | 4           | y
11  |  3        | 2           | y
</code>```

I will get service id as comma separated string like 1,2,3 as the input & I need to check that which user provide this all services.

For example;
User 1 provides services 1,3,2,4, and 1,2,3 is subset of 1,3,2,4 so this record should be returned.

User 2 provide services 2,3,4, so 1,2,3 is not subset of 2,3,4 then this record should not be returned.

I have tried using FIND_IN_SET with GROUP_CONCAT of user's id but it doesn't work.

答:
Can the User Service Table contain duplicates?

If not, you can try

```<code>SELECT UserId FROM userServices
WHERE serviceId IN (1,2,3)
GROUP BY UserId HAVING COUNT(*) >= 3
</code>```

( replace 1,2,3 with the input and 3 with number of groups in input, or you could even calculate it in the SQL itself)

Body:
I have 3 tables

user

service

userServices

User Table

Id  |  Name   | Status
------------------------
1   |  User1  | y
2   |  User2  | y
3   |  User3  | y
4   |  User4  | y

Service Table

Id  |  ServiceName   | Status
------------------------
1   |  Service1      | y
2   |  Service2      | y
3   |  Service3      | y
4   |  Service4      | y

User Service Table

Id  |  UserId   | ServiceId   | Status
-----------------------------------------
1   |  1        | 1           | y
2   |  1        | 3           | y
3   |  1        | 2           | y
4   |  1        | 4           | y
5   |  2        | 2           | y
6   |  2        | 3           | y
7   |  2        | 4           | y
8   |  3        | 1           | y
9   |  3        | 3           | y
10  |  3        | 4           | y
11  |  3        | 2           | y

I will get service id as comma separated string like 1,2,3 as the input & I need to check that which user provide this all services.

For example;
User 1 provides services 1,3,2,4, and 1,2,3 is subset of 1,3,2,4 so this record should be returned.

User 2 provide services 2,3,4, so 1,2,3 is not subset of 2,3,4 then this record should not be returned.

I have tried using FIND_IN_SET with GROUP_CONCAT of user's id but it doesn't work.

Body:
Can the User Service Table contain duplicates?

If not, you can try

SELECT UserId FROM userServices
WHERE serviceId IN (1,2,3)
GROUP BY UserId HAVING COUNT(*) >= 3

( replace 1,2,3 with the input and 3 with number of groups in input, or you could even calculate it in the SQL itself)


问:
Single Quotes Instead of Double Quotes?
Since both are acceptable by HTML as well as languages like ASP.NET and PHP when using attributes or strings, why is it that some people use single quotes and double quotes interchangeably?

It is my understanding that it is syntactically correct to use double quotes where possible, single when you need to embed a double quote for inline logic.

Is there something I am missing?

For examples:

HTML

```<code><a href='http://google.com'>Google</a>
</code>```

PHP

```<code><? echo 'Hello World!'; ?>
</code>```

ASP.NET

```<code><form id='myForm' runat='server'></form>
</code>```

答: Basically, the choice is yours. But for readability & maintainability, pick one form & stick with it.</p>

Title: Single Quotes Instead of Double Quotes?

Body:
Since both are acceptable by HTML as well as languages like ASP.NET and PHP when using attributes or strings, why is it that some people use single quotes and double quotes interchangeably?

It is my understanding that it is syntactically correct to use double quotes where possible, single when you need to embed a double quote for inline logic.

Is there something I am missing?

For examples:

HTML

Google

PHP

<? echo 'Hello World!'; ?>

ASP.NET

<form id='myForm' runat='server'></form>


问:
Two Forms on one page, With ajax submit functionality, _token is missing in Laravel
I've two different forms on one page. one accept the registration number to display user information with ajax.

The other one saves the information on another table with additional data. Now the problem is both forms have same _token value. So once the ajax form is submitted that _token is used so when I save other form I got _token error.

I'm using Form::open() and Form::close() for both forms.

What should I do?

Here is my jQuery Code:

```<code>$.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('[name="_token"]').val()
        }
});

$('#payment_schedule').change(function(event) {
    var planId = $(this).val();
    $.ajax({
        url: '{{ URL::to('/PlanInfo') }}',
        type: 'POST',
        dataType: 'JSON',
        data: {'paymentSchedule': planId},
        success: function(result){
            console.log("data = "+ result);
        },
        error: function(xhr, status,response){
            $('#data').html(xhr.responseText);
        }
    });

});
 var inputs = $('#data input, #data select').attr('disabled','disabled');
$('#paymentForm').submit(function(event){
    event.preventDefault();
    var url = '{{ URL::to('/memberInfo') }}';
    var reg_no = $('#registration_no').val();
    $.ajax({
        url: url,
        type: 'POST',
        dataType: 'JSON',
        data: {'registration_no': reg_no},
        success: function(result){
            console.log('Ok'); //working fine
        },
        error: function(xhr, status, response){
            console.log(response);
        }
    });
});
</code>```

On Changing Payment Plan Receiving this error

答:
create another view called form2, and then in the first view create a section with @yield('form2') and call the form2 with @section('form2') and close it with @endsection, like this
put this in the first view

```<code><form>
token1{{ csrf_field() }}
bla bla bla
bla bla bla
</form>
@yield('form2')
</code>```

the in the second view put the other form like this

```<code>@section('form2')
<form>
token2{{ csrf_field() }}
blablabla
</form>
@endsection
</code>```

Body:
I've two different forms on one page. one accept the registration number to display user information with ajax.

The other one saves the information on another table with additional data. Now the problem is both forms have same _token value. So once the ajax form is submitted that _token is used so when I save other form I got _token error.

I'm using Form::open() and Form::close() for both forms.

What should I do?

Here is my jQuery Code:

$.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('[name="_token"]').val()
        }
});

$('#payment_schedule').change(function(event) {
    var planId = $(this).val();
    $.ajax({
        url: '{{ URL::to('/PlanInfo') }}',
        type: 'POST',
        dataType: 'JSON',
        data: {'paymentSchedule': planId},
        success: function(result){
            console.log("data = "+ result);
        },
        error: function(xhr, status,response){
            $('#data').html(xhr.responseText);
        }
    });

});
 var inputs = $('#data input, #data select').attr('disabled','disabled');
$('#paymentForm').submit(function(event){
    event.preventDefault();
    var url = '{{ URL::to('/memberInfo') }}';
    var reg_no = $('#registration_no').val();
    $.ajax({
        url: url,
        type: 'POST',
        dataType: 'JSON',
        data: {'registration_no': reg_no},
        success: function(result){
            console.log('Ok'); //working fine
        },
        error: function(xhr, status, response){
            console.log(response);
        }
    });
});

On Changing Payment Plan Receiving this error

Body:
create another view called form2, and then in the first view create a section with @yield('form2') and call the form2 with @section('form2') and close it with @endsection, like this
put this in the first view

<form>
token1{{ csrf_field() }}
bla bla bla
bla bla bla
</form>
@yield('form2')

the in the second view put the other form like this

@section('form2')
<form>
token2{{ csrf_field() }}
blablabla
</form>
@endsection


问:
Hide navigation when at the top
Hello how can i hide my navigation when not scrolling and show it when i scroll

i am using two menus at this link http://dev.thegabrielmethod.com/gabriel/

one on a white bg and the other on a blue bg

i would like to hide the navigation menu items on the white bg when not scrolling and then show them again when scrolling

This is what am trying which is not working

```<code><script type='text/javascript'>//<![CDATA[
$(document).ready(function() {
        var headerTop = $('#header').offset().top;
        var headerBottom = headerTop + 120; // Sub-menu should appear after this distance from top.
        $(window).scroll(function () {
            var scrollTop = $(window).scrollTop(); // Current vertical scroll position from the top
            if (scrollTop > headerBottom) { // Check to see if we have scrolled more than headerBottom
                if (($("#navigation-alongside").is(":visible") === false)) {
                    $('#navigation-alongside').fadeIn('slow');
                }
            } else {
                if ($("#navigation-alongside").is(":visible")) {
                    $('#navigation-alongside').hide();
                }
            }
        });
    });

</script>
</code>```

Please some one advice

答:
$(document).ready(function() {
  $(window).scroll(function() {
    $(".menu").css({
      'display': 'none'
    });
    clearTimeout($.data(this, 'scrollTimer'));
    $.data(this, 'scrollTimer', setTimeout(function() {
      $(".menu").css({
        'display': 'block'
      });
    }, 100));
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.menu {
  position: fixed;
  display: block;
  width: 100%;
  height: 150px;
  margin: 0px !important;
  box-shadow: 0 2mm 10px #aaa;
  text-align: center;
}

body {
  padding: 0px !important;
  height: 200vh;
}</code>```

Menu Box

```

Here!
It won't show the menu while scrolling.. and will show it again when when scrolling finished.

Please inform if I have misinterpreted your question.

Title: Hide navigation when at the top

Body:
Hello how can i hide my navigation when not scrolling and show it when i scroll

i am using two menus at this link http://dev.thegabrielmethod.com/gabriel/

one on a white bg and the other on a blue bg

i would like to hide the navigation menu items on the white bg when not scrolling and then show them again when scrolling

This is what am trying which is not working

Please some one advice

Body:
$(document).ready(function() {
  $(window).scroll(function() {
    $(".menu").css({
      'display': 'none'
    });
    clearTimeout($.data(this, 'scrollTimer'));
    $.data(this, 'scrollTimer', setTimeout(function() {
      $(".menu").css({
        'display': 'block'
      });
    }, 100));
  });
});

.menu {
  position: fixed;
  display: block;
  width: 100%;
  height: 150px;
  margin: 0px !important;
  box-shadow: 0 2mm 10px #aaa;
  text-align: center;
}

body {
  padding: 0px !important;
  height: 200vh;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <div class="menu"><br/>
    <h1>Menu Box</h1>
  </div>

</body>

Here!
It won't show the menu while scrolling.. and will show it again when when scrolling finished.

Please inform if I have misinterpreted your question.


问:
How to join same tables having same instances in MYSQL?
Suppose I have following tables in MYSQL

```<code>Sailors (sid,sname,rating,age) where sid-> Sailor's id,

Reserves (sid,bid,day) where bid-> boat's id
</code>```

My Query is :-

Find names of the sailors who have sailed two different boats on the same day ?

First of all, I tried to join the two copies of reserves table and adding a condition that bid's must be different.

```<code>SELECT * FROM reserves R1,reserves R2 WHERE R1.day = R2.day AND R1.bid <> R2.bid;
</code>```

I got output like this :-

Now, query wants the names of the sailors, hence for that I have to  join sailors table with this resultant table.

Now, how can I apply join (What are the conditions) operation to get the desired result ?

答:
You should add table Sailors to FROM clause and add condition: both columns sid of tables Sailors and R1 are equal.

Try this Query:

```<code>SELECT *
FROM Reserves R1
INNER JOIN Reserves R2 ON R1.sid=R2.sid AND R1.bid<R2.bid AND R1.date=R2.date
INNER JOIN Sailors S ON R1.sid=S.sid
</code>```

Also I have added necessary condition: R1.sid = R2.sid which you missed in your query

Body:
Suppose I have following tables in MYSQL

Sailors (sid,sname,rating,age) where sid-> Sailor's id,

Reserves (sid,bid,day) where bid-> boat's id

My Query is :-

Find names of the sailors who have sailed two different boats on the same day ?

First of all, I tried to join the two copies of reserves table and adding a condition that bid's must be different.

SELECT * FROM reserves R1,reserves R2 WHERE R1.day = R2.day AND R1.bid <> R2.bid;

I got output like this :-

Now, query wants the names of the sailors, hence for that I have to  join sailors table with this resultant table.

Now, how can I apply join (What are the conditions) operation to get the desired result ?

Body:
You should add table Sailors to FROM clause and add condition: both columns sid of tables Sailors and R1 are equal.

Try this Query:

SELECT *
FROM Reserves R1
INNER JOIN Reserves R2 ON R1.sid=R2.sid AND R1.bid<R2.bid AND R1.date=R2.date
INNER JOIN Sailors S ON R1.sid=S.sid

Also I have added necessary condition: R1.sid = R2.sid which you missed in your query


问:
connect to android via adb wifi without knowing device ip address
i know that we can connect device over WiFi. i need a batch script for windows to do it automatically. these three steps needed:

1. start the adb daemon listening on TCP on the specified port

```<code>adb tcpip <port>
</code>```

2. get ip address of android device. i know that with adb shell ifconfig wlan0 i can get information about wlan0 interface, some info like:

```<code>wlan0     Link encap:UNSPEC
          inet addr:192.168.1.101  Bcast:192.168.1.255  Mask:255.255.255.0
          inet6 addr: fe80::dee8:38ff:fe08:7322/64 Scope: Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:597 errors:0 dropped:1 overruns:0 frame:0
          TX packets:801 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:187557 TX bytes:106180
</code>```

but i need just ip address of wlan0.

3. if i know device_ip then i can do  adb connect device_ip

How to do this process automatically in just one batch script in windows?

Hoe to do it in linux?

答:
Finally i found the solution. just two commands:

In Windows:

```<code>adb tcpip 5555
for /f "tokens=3 delims=:, " %i  in ('adb shell ifconfig wlan0 ^| findstr /c:"inet addr"') do adb connect %i
</code>```

Body:
i know that we can connect device over WiFi. i need a batch script for windows to do it automatically. these three steps needed:

1. start the adb daemon listening on TCP on the specified port

adb tcpip <port>

2. get ip address of android device. i know that with adb shell ifconfig wlan0 i can get information about wlan0 interface, some info like:

wlan0     Link encap:UNSPEC
          inet addr:192.168.1.101  Bcast:192.168.1.255  Mask:255.255.255.0
          inet6 addr: fe80::dee8:38ff:fe08:7322/64 Scope: Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:597 errors:0 dropped:1 overruns:0 frame:0
          TX packets:801 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:187557 TX bytes:106180

but i need just ip address of wlan0.

3. if i know device_ip then i can do  adb connect device_ip

How to do this process automatically in just one batch script in windows?

Hoe to do it in linux?

Body:
Finally i found the solution. just two commands:

In Windows:

adb tcpip 5555
for /f "tokens=3 delims=:, " %i  in ('adb shell ifconfig wlan0 ^| findstr /c:"inet addr"') do adb connect %i


问:
Are unit tests and acceptance tests enough?
If I have unit tests for each class and/or member function and acceptance tests for every user story do I have enough tests to ensure the project functions as expected?

For instance if I have unit tests and acceptance tests for a feature do I still need integration tests or should the unit and acceptance tests cover the same ground? Is there overlap between test types?

I'm talking about automated tests here. I know manual testing is still needed for things like ease of use, etc.

答:
Probably not, unless your software is really, really simple and has only one component.

Unit tests are very specific, and you should cover everything thoroughly with them.  Go for high code-coverage here.  However, they only cover one piece of functionality at a time and not how things work together.  Acceptance tests should cover only what the customer really cares about at a high level, and while it will catch some bugs in how things work together, it won't catch everything as the person writing such tests will not know about the system in depth.

Most importantly, these tests may not be written by a tester.  Unit tests should be written by developers and run frequently (up to every couple minutes, depending on coding style) by the devs (and by the build system too, ideally).  Acceptance tests are often written by the customer or someone on behalf of the customer, thinking about what matters to the customer.  However, you also need tests written by a tester, thinking like a tester (and not like a dev or customer).

You should also consider the following sorts of tests, which are generally written by testers:

Functional tests, which will cover pieces of functionality.  This may include API testing and component-level testing.  You will generally want good code-coverage here as well.

Integration tests, which put two or more components together to make sure that they work together.  You don't want one component to put out the position in the array where the object is (0-based) when the other component expects the count of the object ("nth object", which is 1-based), for example.  Here, the focus is not on code coverage but on coverage of the interfaces (general interfaces, not code interfaces) between components.

System-level testing, where you put everything together and make sure it works end-to-end.

Testing for non-functional features, like performance, reliability, scalability, security, and user-friendliness (there are others; not all will relate to every project).


问:
Python built JSON with mixed types
Actually I build Json object starting from a python object.

My starting JSON is:

```<code>    responseMsgObject = {'Version': 1,
                         'Id': 'xc23',
                         'Local': "US"
                         'Type': "Test",
                         'Message' : "Message body" }

    responseMsgJson = json.dumps(responseMsgObject, sort_keys=False )
</code>```

Every things works but now I need to put the JSON below into "Message" field.

```<code>  {
  "DepID": "001",
  "Assets": [
    {
      "Type": "xyz",
      "Text": [
        "abc",
        "def"
      ],
      "Metadata": {
        "V": "1",
        "Req": true,
        "Other": "othervalue"
      },
      "Check": "refdw321"
    },
    {
      "Type": "jkl",
      "Text": [
        "ghi"
      ],
      "Metadata": {
        "V": "6"
      },
      "Check": "345ghsdan"
    }
  ]
}
</code>```

I built many other json (but simpler) but I'm in trouble with this json.

Thanks for the help.

答:
try to replace true with True works fine for me

```<code>import json
responseMsgObject = {
    'Version': 1,
    'Id': 'xc23',
    'Local': "US",
    'Type': "Test",
    'Message': {
        "DepID": "001",
        "Assets": [{
            "Type": "xyz",
            "Text": [
                "abc",
                "def"
            ],
            "Metadata": {
                "V": "1",
                "Req": True,
                "Other": "othervalue"
            },
            "Check": "refdw321"
        }, {
            "Type": "jkl",
            "Text": [
                "ghi"
            ],
            "Metadata": {
                "V": "6"
            },
            "Check": "345ghsdan4"
        }]
    }
}

responseMsgJson = json.dumps(responseMsgObject, sort_keys=False )
print("responseMsgJson", responseMsgJson)
</code>```

DEMO

Title: Python built JSON with mixed types

Body:
Actually I build Json object starting from a python object.

My starting JSON is:

    responseMsgObject = {'Version': 1,
                         'Id': 'xc23',
                         'Local': "US"
                         'Type': "Test",
                         'Message' : "Message body" }

    responseMsgJson = json.dumps(responseMsgObject, sort_keys=False )

Every things works but now I need to put the JSON below into "Message" field.

  {
  "DepID": "001",
  "Assets": [
    {
      "Type": "xyz",
      "Text": [
        "abc",
        "def"
      ],
      "Metadata": {
        "V": "1",
        "Req": true,
        "Other": "othervalue"
      },
      "Check": "refdw321"
    },
    {
      "Type": "jkl",
      "Text": [
        "ghi"
      ],
      "Metadata": {
        "V": "6"
      },
      "Check": "345ghsdan"
    }
  ]
}

I built many other json (but simpler) but I'm in trouble with this json.

Thanks for the help.

Body:
try to replace true with True works fine for me

import json
responseMsgObject = {
    'Version': 1,
    'Id': 'xc23',
    'Local': "US",
    'Type': "Test",
    'Message': {
        "DepID": "001",
        "Assets": [{
            "Type": "xyz",
            "Text": [
                "abc",
                "def"
            ],
            "Metadata": {
                "V": "1",
                "Req": True,
                "Other": "othervalue"
            },
            "Check": "refdw321"
        }, {
            "Type": "jkl",
            "Text": [
                "ghi"
            ],
            "Metadata": {
                "V": "6"
            },
            "Check": "345ghsdan4"
        }]
    }
}

responseMsgJson = json.dumps(responseMsgObject, sort_keys=False )
print("responseMsgJson", responseMsgJson)

DEMO


答:
I Observed your html as well. and found some issue. first is -
you have set the margin for blue nav bar - margin-top: 100px; that is not required.

and the execute the below code.

open that site, and open developer tool > in console execute the below code, then scroll the page, you will see its working as expected.

You just need to execute the below code on page load, and it will handle the margin issue as well in second line..

```<code>jQuery('.banner.include-nav').fadeOut();
jQuery('.nav-bar-below.op-page-header.cf').css({'margin':'0px'});
var h = jQuery('.nav-bar-below.op-page-header.cf').height();
jQuery(window).scroll(function () {
    if(jQuery(window).scrollTop() > h)
    {
        jQuery('.banner.include-nav').fadeIn();
    }
    else
    {
        jQuery('.banner.include-nav').fadeOut();
    }
})
</code>```

Before Scroll

When Scroll

Update

As per you comment I understood you, in white one you just wanted to hide the menu not the logo itself. try the below code. as told you above now.

```<code>jQuery('.banner.include-nav > .fixed-width.cf > .sixteen.columns').fadeOut();
//jQuery('.nav-bar-below.op-page-header.cf').css({'margin':'0px'});
var h = jQuery('.nav-bar-below.op-page-header.cf').height();
jQuery(window).scroll(function () {
    if(jQuery(window).scrollTop() > h)
    {
        jQuery('.banner.include-nav > .fixed-width.cf > .sixteen.columns').fadeIn();
    }
    else
    {
        jQuery('.banner.include-nav > .fixed-width.cf > .sixteen.columns').fadeOut();
    }
})
</code>```

Title: Hide navigation when at the top

Body:
I Observed your html as well. and found some issue. first is -
you have set the margin for blue nav bar - margin-top: 100px; that is not required.

and the execute the below code.

open that site, and open developer tool > in console execute the below code, then scroll the page, you will see its working as expected.

You just need to execute the below code on page load, and it will handle the margin issue as well in second line..

jQuery('.banner.include-nav').fadeOut();
jQuery('.nav-bar-below.op-page-header.cf').css({'margin':'0px'});
var h = jQuery('.nav-bar-below.op-page-header.cf').height();
jQuery(window).scroll(function () {
    if(jQuery(window).scrollTop() > h)
    {
        jQuery('.banner.include-nav').fadeIn();
    }
    else
    {
        jQuery('.banner.include-nav').fadeOut();
    }
})

Before Scroll

When Scroll

Update

As per you comment I understood you, in white one you just wanted to hide the menu not the logo itself. try the below code. as told you above now.

jQuery('.banner.include-nav > .fixed-width.cf > .sixteen.columns').fadeOut();
//jQuery('.nav-bar-below.op-page-header.cf').css({'margin':'0px'});
var h = jQuery('.nav-bar-below.op-page-header.cf').height();
jQuery(window).scroll(function () {
    if(jQuery(window).scrollTop() > h)
    {
        jQuery('.banner.include-nav > .fixed-width.cf > .sixteen.columns').fadeIn();
    }
    else
    {
        jQuery('.banner.include-nav > .fixed-width.cf > .sixteen.columns').fadeOut();
    }
})


问:
multiple plots in same figure with one axis via python matplotlib
I'm trying to plot one diagram of both cyclical components(gdp and hoursworked) using HP-filters and matplotlib in python. Currently only getting one figure to plot and other figure is flatline(HoursWorked is flatlined) (Image below). Any pointers on how to improve code.

```<code>import statsmodels.api as sm
import matplotlib.pyplot as plt
pandas_datareader import data
import datetime as dt

start, end = dt.datetime(1965, 1, 1), dt.datetime(2016,12, 31)

gdp = data.DataReader('GDPC1', 'fred', start, end)
HoursWorked = data.DataReader('PRSCQ', 'fred', start, end)

plt.figure(1)
plt.subplot(211)
plt.plot(gdp)

plt.title('RealGDP and Hours Worked')
cycle, trend = sm.tsa.filters.hpfilter(gdp, 1600)

plt.figure(1)
plt.subplot(211)
plt.plot(HoursWorked)
ax = plt.gca()
ax.set_xticklabels([])

plt.show()
</code>```

[2

答:
I think you would want to use a twin axes. I.e. you want two axes which sit on top ofeach other and share the same x scale, but have a different y scale. This can be done with the following code:

```<code>import matplotlib.pyplot as plt
import pandas_datareader.data
import datetime as dt

start, end = dt.datetime(1965, 1, 1), dt.datetime(2016,12, 31)

gdp = pandas_datareader.data.DataReader('GDPC1', 'fred', start, end)
HoursWorked = pandas_datareader.data.DataReader('PRSCQ', 'fred', start, end)

fig, ax = plt.subplots()
ax2 = ax.twinx()
ax.plot(gdp, label="GDP")
ax2.plot(HoursWorked, color="C2", label="HoursWorked")

ax.set_title('RealGDP and Hours Worked')

ax.legend(loc=2)
ax2.legend(loc=4)
plt.show()
</code>```

Body:
I'm trying to plot one diagram of both cyclical components(gdp and hoursworked) using HP-filters and matplotlib in python. Currently only getting one figure to plot and other figure is flatline(HoursWorked is flatlined) (Image below). Any pointers on how to improve code.

import statsmodels.api as sm
import matplotlib.pyplot as plt
pandas_datareader import data
import datetime as dt

start, end = dt.datetime(1965, 1, 1), dt.datetime(2016,12, 31)

gdp = data.DataReader('GDPC1', 'fred', start, end)
HoursWorked = data.DataReader('PRSCQ', 'fred', start, end)

plt.figure(1)
plt.subplot(211)
plt.plot(gdp)

plt.title('RealGDP and Hours Worked')
cycle, trend = sm.tsa.filters.hpfilter(gdp, 1600)

plt.figure(1)
plt.subplot(211)
plt.plot(HoursWorked)
ax = plt.gca()
ax.set_xticklabels([])

plt.show()

[2

Body:
I think you would want to use a twin axes. I.e. you want two axes which sit on top ofeach other and share the same x scale, but have a different y scale. This can be done with the following code:

import matplotlib.pyplot as plt
import pandas_datareader.data
import datetime as dt

start, end = dt.datetime(1965, 1, 1), dt.datetime(2016,12, 31)

gdp = pandas_datareader.data.DataReader('GDPC1', 'fred', start, end)
HoursWorked = pandas_datareader.data.DataReader('PRSCQ', 'fred', start, end)

fig, ax = plt.subplots()
ax2 = ax.twinx()
ax.plot(gdp, label="GDP")
ax2.plot(HoursWorked, color="C2", label="HoursWorked")

ax.set_title('RealGDP and Hours Worked')

ax.legend(loc=2)
ax2.legend(loc=4)
plt.show()


问:
How to call custom helper in laravel 5?
I wanna make my very own helper, and i put it in app/http/helpers.php.
This is my helper code:

```<code><?php

namespace App\Helpers;
use Auth;
class helper {

    public static function is_login() {
        if(Auth::check()){
           return True;
        }else{
           return False;
        }
    }

    public static function must_login(){
        if(Auth::check()){
           return True;
        }else{
           return Redirect::to('logout');;
        }
    }
}

?>
</code>```

and this is my app.php code:

```<code>  'aliases' => [
                'customhelper'=> App\Helpers\Helper::class
               ]
</code>```

when i use for my blade file customhelper::is_login() it work. But when i try to use in my controller customhelper::must_login() it doesn't work and i've got some error

Class 'App\Http\Controllers\customhelper' not found

答:
@Reynald Henryleo

First thing like you have mentioned 'app/http/helpers.php' your helper file path in that case your namespace should be 'namespace App\Http'.

for better understanding to make global helper function refer 'Custom Classes in Laravel 5, the Easy Way' section of Best practices for custom helpers on Laravel 5

Title: How to call custom helper in laravel 5?

Body:
I wanna make my very own helper, and i put it in app/http/helpers.php.
This is my helper code:

<?php

namespace App\Helpers;
use Auth;
class helper {

    public static function is_login() {
        if(Auth::check()){
           return True;
        }else{
           return False;
        }
    }

    public static function must_login(){
        if(Auth::check()){
           return True;
        }else{
           return Redirect::to('logout');;
        }
    }
}

?>

and this is my app.php code:

  'aliases' => [
                'customhelper'=> App\Helpers\Helper::class
               ]

when i use for my blade file customhelper::is_login() it work. But when i try to use in my controller customhelper::must_login() it doesn't work and i've got some error

Class 'App\Http\Controllers\customhelper' not found