问:
ionic 2 serve ignores changes in html
I am starting an ionic2 project, and running into trouble with seeing changes in code reflect to the browser.

Description of the phenomenon:

At some point I  see all of what I expect to see in the browser. For example, a single page whose .html is

```<code>{{text}}
</code>```

and text field in the .ts contains "hola".

The output is obviously hola.

Then, I either can change the .html to

```<code>Hello World!
</code>```

Or the text field in the .ts to "mundo"

Since ionic serve is running in the background, I see the browser update itself after I save the change in the code.

However, it always updates to the same old hola.

Doesn't matter how many times I refresh, save, change. I can even delete all contents of both .html and .ts files, and still the browser would show the old state.

things I tried that don't work:

clearing cache from chrome

restarting ionic serve

saving any and all files again

refreshing browser.

It is very frustrating to work like this, as this problem comes and goes, and I have no clear method to even bypass it.

Any suggestions?

I run windows 10, and this happens both in chrome and firefox.

my package.json:

```<code>{
  "name": "saperli",
  "version": "0.0.1",
  "author": "Ionic Framework",
  "homepage": "http://ionicframework.com/",
  "private": true,
  "scripts": {
    "clean": "ionic-app-scripts clean",
    "build": "ionic-app-scripts build",
    "lint": "ionic-app-scripts lint",
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/common": "4.1.2",
    "@angular/compiler": "4.1.2",
    "@angular/compiler-cli": "4.1.2",
    "@angular/core": "4.1.2",
    "@angular/forms": "4.1.2",
    "@angular/http": "4.1.2",
    "@angular/platform-browser": "4.1.2",
    "@angular/platform-browser-dynamic": "4.1.2",
    "@ionic-native/core": "3.10.2",
    "@ionic-native/splash-screen": "3.10.2",
    "@ionic-native/status-bar": "3.10.2",
    "@ionic/storage": "2.0.1",
    "ionic-angular": "3.3.0",
    "ionicons": "3.0.0",
    "rxjs": "5.1.1",
    "sw-toolbox": "3.6.0",
    "zone.js": "0.8.11"
  },
  "devDependencies": {
    "@ionic/app-scripts": "1.3.7",
    "@ionic/cli-plugin-ionic-angular": "1.3.0",
    "typescript": "2.3.3"
  },
  "description": "An Ionic project"
}
</code>```

答: First run in your project folder npm run clean to do a clean then npm run build to rebuild before serving again.

Title: ionic 2 serve ignores changes in html

Body:
I am starting an ionic2 project, and running into trouble with seeing changes in code reflect to the browser.

Description of the phenomenon:

At some point I  see all of what I expect to see in the browser. For example, a single page whose .html is

{{text}}

and text field in the .ts contains "hola".

The output is obviously hola.

Then, I either can change the .html to

Hello World!

Or the text field in the .ts to "mundo"

Since ionic serve is running in the background, I see the browser update itself after I save the change in the code.

However, it always updates to the same old hola.

Doesn't matter how many times I refresh, save, change. I can even delete all contents of both .html and .ts files, and still the browser would show the old state.

things I tried that don't work:

clearing cache from chrome

restarting ionic serve

saving any and all files again

refreshing browser.

It is very frustrating to work like this, as this problem comes and goes, and I have no clear method to even bypass it.

Any suggestions?

I run windows 10, and this happens both in chrome and firefox.

my package.json:

{
  "name": "saperli",
  "version": "0.0.1",
  "author": "Ionic Framework",
  "homepage": "http://ionicframework.com/",
  "private": true,
  "scripts": {
    "clean": "ionic-app-scripts clean",
    "build": "ionic-app-scripts build",
    "lint": "ionic-app-scripts lint",
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/common": "4.1.2",
    "@angular/compiler": "4.1.2",
    "@angular/compiler-cli": "4.1.2",
    "@angular/core": "4.1.2",
    "@angular/forms": "4.1.2",
    "@angular/http": "4.1.2",
    "@angular/platform-browser": "4.1.2",
    "@angular/platform-browser-dynamic": "4.1.2",
    "@ionic-native/core": "3.10.2",
    "@ionic-native/splash-screen": "3.10.2",
    "@ionic-native/status-bar": "3.10.2",
    "@ionic/storage": "2.0.1",
    "ionic-angular": "3.3.0",
    "ionicons": "3.0.0",
    "rxjs": "5.1.1",
    "sw-toolbox": "3.6.0",
    "zone.js": "0.8.11"
  },
  "devDependencies": {
    "@ionic/app-scripts": "1.3.7",
    "@ionic/cli-plugin-ionic-angular": "1.3.0",
    "typescript": "2.3.3"
  },
  "description": "An Ionic project"
}


来源: stackexchange

问:
How to mock uuid generation in a test case?
I have a test case in which in the setUp, I create an object for which I want to mock the function uuid4 in the module uuid.

```<code>TEST_UUIDS = ['uuid_{}'.format(i) for i in range(10000)]
UUID_POOL = iter(TEST_UUIDS)

def generate_uuid() -> str:
    return next(UUID_POOL)

class MyTestCase(TestCase):

    def setUp(self, **kwargs):
        self._create_my_object

    @patch.object(uuid, 'uuid4', generate_uuid)
    def _create_my_object(self):
        # Create an object using a uuid
</code>```

My problem now is that when I run write two test cases, the second time the object is created, it gets other uuids as the first time. Therefore, the result is dependent on the number of test cases in my test class and the order they are run in, something I don't want.

Is this the best way to mock a uuid generator?

How do I reset or recreate the iterator at every call of setUp (or tearDown)?

答:
The answer was easier than I thought: just don't use iterators! Instead, set the list of uuids as side_effect of the mock.

```<code>TEST_UUIDS = ['uuid_{}'.format(i) for i in range(10000)]

class MyTestCase(TestCase):

    def setUp(self, **kwargs):
        self._create_my_object

    @patch.object(uuid, 'uuid4', side_effect=TEST_UUIDS)
    def _create_my_object(self):
        # Create an object using a uuid
</code>```

EDIT

I found an even nicer way to write this as a context manager, which allows for prefixing uuids based on the context.

```<code>TEST_UUIDS = ['uuid_{}'.format(i) for i in range(10000)]

def uuid_prefix(prefix: str):
    return patch.object(uuid, 'uuid4', side_effect=['{}_{}'.format(prefix, x) for x in TEST_UUIDS])

class MyTestCase(TestCase):

    def setUp(self, **kwargs):
        self._create_my_object

    def _create_my_object(self):
        with uuid_prefix('obj_a'):
            # Create an object A using a uuid
        with uuid_prefix('obj_b'):
            # Create an object B using a uuid
</code>```

Explanation: I am mocking the function uuid.uuid4 using patch.object(uuid, 'uuid4'). In it, I define a side effect as a list. If your side effect is a list, it can be seen as a list of return values of that function on subsequent calls, so the first time the function uuid4() is called, it returns the first element of that list, the second time the second element, etc. If in the with-context I am generating 10 objects A, the UUIDs will be 'obj_a_uuid_0' up to 'obj_a_uuid_9'.

ContentLicense: CC BY-SA 3.0

Body:
I have a test case in which in the setUp, I create an object for which I want to mock the function uuid4 in the module uuid.

TEST_UUIDS = ['uuid_{}'.format(i) for i in range(10000)]
UUID_POOL = iter(TEST_UUIDS)

def generate_uuid() -> str:
    return next(UUID_POOL)

class MyTestCase(TestCase):

    def setUp(self, **kwargs):
        self._create_my_object

    @patch.object(uuid, 'uuid4', generate_uuid)
    def _create_my_object(self):
        # Create an object using a uuid

My problem now is that when I run write two test cases, the second time the object is created, it gets other uuids as the first time. Therefore, the result is dependent on the number of test cases in my test class and the order they are run in, something I don't want.

Is this the best way to mock a uuid generator?

How do I reset or recreate the iterator at every call of setUp (or tearDown)?

Body:
The answer was easier than I thought: just don't use iterators! Instead, set the list of uuids as side_effect of the mock.

TEST_UUIDS = ['uuid_{}'.format(i) for i in range(10000)]

class MyTestCase(TestCase):

    def setUp(self, **kwargs):
        self._create_my_object

    @patch.object(uuid, 'uuid4', side_effect=TEST_UUIDS)
    def _create_my_object(self):
        # Create an object using a uuid

EDIT

I found an even nicer way to write this as a context manager, which allows for prefixing uuids based on the context.

TEST_UUIDS = ['uuid_{}'.format(i) for i in range(10000)]

def uuid_prefix(prefix: str):
    return patch.object(uuid, 'uuid4', side_effect=['{}_{}'.format(prefix, x) for x in TEST_UUIDS])

class MyTestCase(TestCase):

    def setUp(self, **kwargs):
        self._create_my_object

    def _create_my_object(self):
        with uuid_prefix('obj_a'):
            # Create an object A using a uuid
        with uuid_prefix('obj_b'):
            # Create an object B using a uuid

Explanation: I am mocking the function uuid.uuid4 using patch.object(uuid, 'uuid4'). In it, I define a side effect as a list. If your side effect is a list, it can be seen as a list of return values of that function on subsequent calls, so the first time the function uuid4() is called, it returns the first element of that list, the second time the second element, etc. If in the with-context I am generating 10 objects A, the UUIDs will be 'obj_a_uuid_0' up to 'obj_a_uuid_9'.

ContentLicense: CC BY-SA 4.0


问:
Type detection: using variadic arguments to properly implement a function that calculates the mean
I am trying to understand how to properly implement a function to calculate the mathematical sample mean, with two initial required characteristics:

1) using variadic arguments.

2) not using two functions to do the job, that is, not using a caller function and then a second function that actually does the calculation.

3) function should be as generic as possible

I am very aware that a pretty similar question has been already asked: Calculate the average of several values using a variadic-template function However, while the accepted answer to that question seems to have taught the OP how to do the small part he didn't know, it presents a code that is actually wrong and does not compile.

So, my own first attempt was along these lines:

```<code>template <class... Args>
double mean(const Args & ... args)
{
    auto total = 0;
    for (auto value : { ...args })
    {
        total += value;
    }
    return (double)total / sizeof...(args);
}
</code>```

The problem here is that in the line auto total = 0; the compile naturally can't automatically identify the type that object total should have.

Then, my second attempt:

```<code>template <class T, class... Args>
T mean(const T &t, const Args & ... args)
{
    T total = 0;
    for (auto value : { args... })
    {
        total += value;
    }
    return (T)(total / sizeof...(args));
}
</code>```

That version the following problem. It does not work if the caller calls the function with arguments of mixed type, like in mean(1, 2.5), where the first arguments is automatically detected as an int and the second is detected as a double.

I was able to solve that by doing the following:

```<code>template <class T, class... Args>
T mean(const T &t, const Args & ... args)
{
    size_t argsSize = sizeof...(args);
    T total = t;
    T arg_array[] = { args... };
    for (size_t i = 0; i< argsSize; i++)
    {
        total += (T)arg_array[i];
    }
    return (T)(total / argsSize) ;
}
</code>```

This one works even when passed arguments are of different types (of course, provided that such types can be converted to T). The problem now, however, is that the function only works with a minimum of two arguments. If it is called like in mean(3.14), while it should return 3.14, it actually raises an error because T arg_array[] = { args... } can't be compiled because it is impossible to have a static array be created with size 0. Sure, I could substitute it for a dynamic array, but that would make me have to do one memory allocation and one memory deallocation every time that the function is called - which is an unacceptable waste.

So, what would be the correct way to implement such a function that avoids the mentioned problems and that follows my two initial conditions?

答:
Use std::common_type_t:

```<code>template<class... Args> constexpr auto mean(Args... args) {
    std::common_type_t<Args...> total(0);
    for(auto value : {std::common_type_t<Args...>(args)...}) total += value;
    return total/sizeof...(args);
}
</code>```

Body:
I am trying to understand how to properly implement a function to calculate the mathematical sample mean, with two initial required characteristics:

1) using variadic arguments.

2) not using two functions to do the job, that is, not using a caller function and then a second function that actually does the calculation.

3) function should be as generic as possible

I am very aware that a pretty similar question has been already asked: Calculate the average of several values using a variadic-template function However, while the accepted answer to that question seems to have taught the OP how to do the small part he didn't know, it presents a code that is actually wrong and does not compile.

So, my own first attempt was along these lines:

template <class... Args>
double mean(const Args & ... args)
{
    auto total = 0;
    for (auto value : { ...args })
    {
        total += value;
    }
    return (double)total / sizeof...(args);
}

The problem here is that in the line auto total = 0; the compile naturally can't automatically identify the type that object total should have.

Then, my second attempt:

template <class T, class... Args>
T mean(const T &t, const Args & ... args)
{
    T total = 0;
    for (auto value : { args... })
    {
        total += value;
    }
    return (T)(total / sizeof...(args));
}

That version the following problem. It does not work if the caller calls the function with arguments of mixed type, like in mean(1, 2.5), where the first arguments is automatically detected as an int and the second is detected as a double.

I was able to solve that by doing the following:

template <class T, class... Args>
T mean(const T &t, const Args & ... args)
{
    size_t argsSize = sizeof...(args);
    T total = t;
    T arg_array[] = { args... };
    for (size_t i = 0; i< argsSize; i++)
    {
        total += (T)arg_array[i];
    }
    return (T)(total / argsSize) ;
}

This one works even when passed arguments are of different types (of course, provided that such types can be converted to T). The problem now, however, is that the function only works with a minimum of two arguments. If it is called like in mean(3.14), while it should return 3.14, it actually raises an error because T arg_array[] = { args... } can't be compiled because it is impossible to have a static array be created with size 0. Sure, I could substitute it for a dynamic array, but that would make me have to do one memory allocation and one memory deallocation every time that the function is called - which is an unacceptable waste.

So, what would be the correct way to implement such a function that avoids the mentioned problems and that follows my two initial conditions?

Body:
Use std::common_type_t:

template<class... Args> constexpr auto mean(Args... args) {
    std::common_type_t<Args...> total(0);
    for(auto value : {std::common_type_t<Args...>(args)...}) total += value;
    return total/sizeof...(args);
}


问:
Running .NET .exe in Azure Data Factory
I have an .exe (console application) file written in C# , which I want to run using Azure Data Factory.

What are the steps I need to do to achieve this?

I know that for .dll files we have options to run them in azure, but what about .exe files?

答:
As Paul Andrew has pointed out, you need to use the custom activities SPI as described at https://learn.microsoft.com/en-us/azure/data-factory/data-factory-use-custom-activities. You have three options:

Change your project into a class library

If you need the executable for some other purpose, refactor your solution into three separate projects: a class library containing the common logic, an executable project, and a data factory custom activity

If you cannot change the code for some reason, you can create an activity that calls the .exe directly. A sample is provided at
https://github.com/Azure/Azure-DataFactory/blob/master/Samples/RunRScriptUsingADFSample/InvokeRScript.cs

Title: Running .NET .exe in Azure Data Factory


问:
Create a dataset for multi-labelled classification
I have a dataset of the following form:

```<code>Id  Class

1   a
2   b
2   c
3   c
3   d
3   a
3   e
3   f
4   g
</code>```

And I need to prep this data to perform a multi-label classification
so I use:

```<code>df.groupby("Id").Class.apply(','.join).reset_index()
</code>```

to get:

```<code>Id  Class

1   a
2   b,c
3   c,d,e,f
4   g
</code>```

Now the MultiLabelBinarizer is unable to process this in its current form because df.Class is represented as

("a", "b,c", "c,d,e,f", "g")

however, it is supposed to be in the form

[["a"], ["b","c"], ["c","d","e","f"],["g"]]

How should I go about it?

答:
You need apply list:

```<code>print (df.groupby("Id").Class.apply(list))
Id
1                [a]
2             [b, c]
3    [c, d, a, e, f]
4                [g]
Name: Class, dtype: object
</code>```

Body:
I have a dataset of the following form:

Id  Class

1   a
2   b
2   c
3   c
3   d
3   a
3   e
3   f
4   g

And I need to prep this data to perform a multi-label classification
so I use:

df.groupby("Id").Class.apply(','.join).reset_index()

to get:

Id  Class

1   a
2   b,c
3   c,d,e,f
4   g

Now the MultiLabelBinarizer is unable to process this in its current form because df.Class is represented as

("a", "b,c", "c,d,e,f", "g")

however, it is supposed to be in the form

[["a"], ["b","c"], ["c","d","e","f"],["g"]]

How should I go about it?

Body:
You need apply list:

print (df.groupby("Id").Class.apply(list))
Id
1                [a]
2             [b, c]
3    [c, d, a, e, f]
4                [g]
Name: Class, dtype: object


问:
How can I set custom length for integer field by using Blueprint class in Laravel

I am trying to set custom length for integer type field from user
  input.
  By using Blueprint class I can set custom length for varchar field
  like $table->string('varchar_field',50);. But I didn't find any way
  to set custom length for integer field, It takes default length always.

Ex :

```<code>Varchar :
$table->string('varchar_field',50);

Integer :
$table->integer('interger_field');
</code>```

答:
Also you can create column with specific length (not tested, but should work): </p>

```<code>$table->addColumn('integer', 'column_name', ['length' => 50]);
</code>```

Body:
I am trying to set custom length for integer type field from user
  input.
  By using Blueprint class I can set custom length for varchar field
  like $table->string('varchar_field',50);. But I didn't find any way
  to set custom length for integer field, It takes default length always.

Ex :

Varchar :
$table->string('varchar_field',50);

Integer :
$table->integer('interger_field');

Body:
Also you can create column with specific length (not tested, but should work):

$table->addColumn('integer', 'column_name', ['length' => 50]);


问:
How to remove actionbar shadow on Android version 21
I can't remove the shadow below the actionbar, I already tried to use android:windowContentOverlay @null but it doesn't change a thing, I'm using API 21, how can I remove that shadow?

```<code><style name="AppTheme" parent="Theme.AppCompat.Light">
    <!-- Customize your theme here. -->
    <item name="android:actionBarStyle">@style/MyActionBar</item>
    <item name="actionBarStyle">@style/MyActionBar</item>

</style>

<style name="Transparent" parent="@style/Widget.AppCompat.Light.ActionBar">
    <item name="android:background">@android:color/transparent</item>
    <item name="background">@android:color/transparent</item>
</style>

<style name="MyActionBar"
    parent="AppTheme">
    <item name="android:actionBarStyle">@style/Transparent</item>
    <item name="actionBarStyle">@style/Transparent</item>
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:backgroundDimEnabled">false</item>
    <item name="android:windowActionBarOverlay">true</item>
    <item name="windowActionBarOverlay">true</item>

</style>
</code>```

I also tried that:

```<code>getSupportActionBar().setElevation(0);
</code>```

NavigationDrawer:

```<code>public class NavigationMain extends ActionBarActivity implements Animation.AnimationListener {

    public int lastPosition = 0;
    private ListView listDrawer;
    private int counterItemDownloads;
    private DrawerLayout layoutDrawer;
    private LinearLayout linearDrawer;
    private RelativeLayout userDrawer;
    private ActionBarDrawerToggleCompat drawerToggle;
    private final int GALLERY_ACTIVITY_CODE = 200;
    private final int RESULT_CROP = 400;
    private NavigationAdapter navigationAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.navigation_main);

        getSupportActionBar().setCustomView(R.layout.custombar);
        getSupportActionBar().setDisplayOptions(DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_HOME_AS_UP);
        getSupportActionBar().setElevation(0);

        listDrawer = (ListView) findViewById(R.id.listDrawer);
        linearDrawer = (LinearLayout) findViewById(R.id.linearDrawer);
        layoutDrawer = (DrawerLayout) findViewById(R.id.layoutDrawer);

        userDrawer = (RelativeLayout) findViewById(R.id.userDrawer);
        userDrawer.setOnClickListener(userOnClick);

        if (listDrawer != null) {
            navigationAdapter = NavigationList.getNavigationAdapter(this);
        }

        listDrawer.setAdapter(navigationAdapter);
        listDrawer.setOnItemClickListener(new DrawerItemClickListener());

        drawerToggle = new ActionBarDrawerToggleCompat(this, layoutDrawer);
        layoutDrawer.setDrawerListener(drawerToggle);

        if (savedInstanceState != null) {
            setLastPosition(savedInstanceState.getInt(Constant.LAST_POSITION));

            navigationAdapter.resetarCheck();
            navigationAdapter.setChecked(lastPosition, true);

        } else {
            setLastPosition(lastPosition);
            setFragmentList(lastPosition);
        }

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(Constant.LAST_POSITION, lastPosition);
    }

    private static final int REFRESH = 1;

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (drawerToggle.onOptionsItemSelected(item)) {
            return true;
        }

        switch (item.getItemId()) {
            case Menus.HOME:
                if (layoutDrawer.isDrawerOpen(linearDrawer)) {
                    layoutDrawer.closeDrawer(linearDrawer);
                } else {
                    layoutDrawer.openDrawer(linearDrawer);
                }

            case REFRESH:
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return super.onCreateOptionsMenu(menu);

    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        drawerToggle.syncState();
    }

    public void setTitleActionBar(CharSequence informacao) {
        getSupportActionBar().setTitle(informacao);
    }

    public void setSubtitleActionBar(CharSequence informacao) {
        getSupportActionBar().setSubtitle(informacao);
    }

    public void setIconActionBar(int icon) {
        getSupportActionBar().setIcon(icon);
    }

    public void setLastPosition(int posicao) {
        this.lastPosition = posicao;
    }

    @Override
    public void onAnimationStart(Animation animation) {

    }

    @Override
    public void onAnimationEnd(Animation animation) {

    }

    @Override
    public void onAnimationRepeat(Animation animation) {

    }

    private class ActionBarDrawerToggleCompat extends ActionBarDrawerToggle {

        public ActionBarDrawerToggleCompat(Activity mActivity, DrawerLayout mDrawerLayout) {
            super(
                    mActivity,
                    mDrawerLayout,
                    R.drawable.ic_menu,
                    R.string.drawer_open,
                    R.string.drawer_close);
        }

        @Override
        public void onDrawerClosed(View view) {
            supportInvalidateOptionsMenu();
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            navigationAdapter.notifyDataSetChanged();
            supportInvalidateOptionsMenu();
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        drawerToggle.onConfigurationChanged(newConfig);
    }

    private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int posicao, long id) {
            layoutDrawer.closeDrawer(linearDrawer);
            setLastPosition(posicao);
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    setFragmentList(lastPosition);
                }
            }, 350);
        }
    }

    private OnClickListener userOnClick = new OnClickListener() {
        @Override
        public void onClick(View v) {
            layoutDrawer.closeDrawer(linearDrawer);
        }
    };

    public void setFragmentList(int posicao) {

        android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
        android.support.v4.app.Fragment fragment = new InstituicoesActivity();

        switch (posicao) {

            case 0:
                fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commitAllowingStateLoss();
                break;
//            case 1:
//                fragment = new MensagensFragment();
//                break;
//            case 2:
//                fragment = new EscolasFragment();
//                break;
//            case 3:
//                fragment = new AutorizadasFragment();
//                break;
//            case 4:
//                fragment = new CadastroFragment();
//                break;
            default:
                break;

        }
            // update selected item and title, then close the drawer
            navigationAdapter.resetarCheck();
            navigationAdapter.setChecked(posicao, true);
            layoutDrawer.closeDrawer(linearDrawer);

    }

    public int getCounterItemDownloads() {
        return counterItemDownloads;
    }

    public void setCounterItemDownloads(int value) {
        this.counterItemDownloads = value;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

}
</code>```

答:
Accepted answer didn't work for me.

To remove shadow in AppBarLayout use

app:elevation="0" in AppBarLayout xml or

use mAppBarLayout.setTargetElevation(0) in java.

I tried and it worked for me.

Body:
I can't remove the shadow below the actionbar, I already tried to use android:windowContentOverlay @null but it doesn't change a thing, I'm using API 21, how can I remove that shadow?

I also tried that:

getSupportActionBar().setElevation(0);

NavigationDrawer:

public class NavigationMain extends ActionBarActivity implements Animation.AnimationListener {

    public int lastPosition = 0;
    private ListView listDrawer;
    private int counterItemDownloads;
    private DrawerLayout layoutDrawer;
    private LinearLayout linearDrawer;
    private RelativeLayout userDrawer;
    private ActionBarDrawerToggleCompat drawerToggle;
    private final int GALLERY_ACTIVITY_CODE = 200;
    private final int RESULT_CROP = 400;
    private NavigationAdapter navigationAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.navigation_main);

        getSupportActionBar().setCustomView(R.layout.custombar);
        getSupportActionBar().setDisplayOptions(DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_HOME_AS_UP);
        getSupportActionBar().setElevation(0);

        listDrawer = (ListView) findViewById(R.id.listDrawer);
        linearDrawer = (LinearLayout) findViewById(R.id.linearDrawer);
        layoutDrawer = (DrawerLayout) findViewById(R.id.layoutDrawer);

        userDrawer = (RelativeLayout) findViewById(R.id.userDrawer);
        userDrawer.setOnClickListener(userOnClick);

        if (listDrawer != null) {
            navigationAdapter = NavigationList.getNavigationAdapter(this);
        }

        listDrawer.setAdapter(navigationAdapter);
        listDrawer.setOnItemClickListener(new DrawerItemClickListener());

        drawerToggle = new ActionBarDrawerToggleCompat(this, layoutDrawer);
        layoutDrawer.setDrawerListener(drawerToggle);

        if (savedInstanceState != null) {
            setLastPosition(savedInstanceState.getInt(Constant.LAST_POSITION));

            navigationAdapter.resetarCheck();
            navigationAdapter.setChecked(lastPosition, true);

        } else {
            setLastPosition(lastPosition);
            setFragmentList(lastPosition);
        }

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(Constant.LAST_POSITION, lastPosition);
    }

    private static final int REFRESH = 1;

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (drawerToggle.onOptionsItemSelected(item)) {
            return true;
        }

        switch (item.getItemId()) {
            case Menus.HOME:
                if (layoutDrawer.isDrawerOpen(linearDrawer)) {
                    layoutDrawer.closeDrawer(linearDrawer);
                } else {
                    layoutDrawer.openDrawer(linearDrawer);
                }

            case REFRESH:
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return super.onCreateOptionsMenu(menu);

    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        drawerToggle.syncState();
    }

    public void setTitleActionBar(CharSequence informacao) {
        getSupportActionBar().setTitle(informacao);
    }

    public void setSubtitleActionBar(CharSequence informacao) {
        getSupportActionBar().setSubtitle(informacao);
    }

    public void setIconActionBar(int icon) {
        getSupportActionBar().setIcon(icon);
    }

    public void setLastPosition(int posicao) {
        this.lastPosition = posicao;
    }

    @Override
    public void onAnimationStart(Animation animation) {

    }

    @Override
    public void onAnimationEnd(Animation animation) {

    }

    @Override
    public void onAnimationRepeat(Animation animation) {

    }

    private class ActionBarDrawerToggleCompat extends ActionBarDrawerToggle {

        public ActionBarDrawerToggleCompat(Activity mActivity, DrawerLayout mDrawerLayout) {
            super(
                    mActivity,
                    mDrawerLayout,
                    R.drawable.ic_menu,
                    R.string.drawer_open,
                    R.string.drawer_close);
        }

        @Override
        public void onDrawerClosed(View view) {
            supportInvalidateOptionsMenu();
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            navigationAdapter.notifyDataSetChanged();
            supportInvalidateOptionsMenu();
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        drawerToggle.onConfigurationChanged(newConfig);
    }

    private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int posicao, long id) {
            layoutDrawer.closeDrawer(linearDrawer);
            setLastPosition(posicao);
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    setFragmentList(lastPosition);
                }
            }, 350);
        }
    }

    private OnClickListener userOnClick = new OnClickListener() {
        @Override
        public void onClick(View v) {
            layoutDrawer.closeDrawer(linearDrawer);
        }
    };

    public void setFragmentList(int posicao) {

        android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
        android.support.v4.app.Fragment fragment = new InstituicoesActivity();

        switch (posicao) {

            case 0:
                fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commitAllowingStateLoss();
                break;
//            case 1:
//                fragment = new MensagensFragment();
//                break;
//            case 2:
//                fragment = new EscolasFragment();
//                break;
//            case 3:
//                fragment = new AutorizadasFragment();
//                break;
//            case 4:
//                fragment = new CadastroFragment();
//                break;
            default:
                break;

        }
            // update selected item and title, then close the drawer
            navigationAdapter.resetarCheck();
            navigationAdapter.setChecked(posicao, true);
            layoutDrawer.closeDrawer(linearDrawer);

    }

    public int getCounterItemDownloads() {
        return counterItemDownloads;
    }

    public void setCounterItemDownloads(int value) {
        this.counterItemDownloads = value;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

}


问:
Warning treated as error - no 'object' file generated
I am trying to build my first COM Example, I created a VS 2012 project. I got the errors in the library, which I solved by changing the _WIN32_WINNT to 0x0601 for Windows 7 and apparently changed _WIN32_IE to 0x0800 in StdAfx.h. Also I changed the _WIN32_WINNT in Settings -> C/C++ -> Preprocessor and now I am getting the errors as below

```<code>1>------ Build started: Project: COM, Configuration: Debug x64 ------
1>  COMIntro.cpp
1>COMIntro.cpp(21): error C2220: warning treated as error - no 'object' file generated
1>COMIntro.cpp(21): warning C4100: 'envp' : unreferenced formal parameter
1>COMIntro.cpp(21): warning C4100: 'argv' : unreferenced formal parameter
1>COMIntro.cpp(21): warning C4100: 'argc' : unreferenced formal parameter
1>  StdAfx.cpp
1>  Generating Code...
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
</code>```

Is it due to my windows SDK version which is 7.1 or some compatibility issue ?

答:
I should have done some searching first. I got tangled up between COM and few other new concepts that I missed the conventional C++ dos and dont's

I just used cast. the unused variables were causing this problem

```<code>(void)argc;
(void)argv;
(void)envp;
</code>```

Correct solution
Use of UNREFERENCED_PARAMETER works for me.

Body:
I am trying to build my first COM Example, I created a VS 2012 project. I got the errors in the library, which I solved by changing the _WIN32_WINNT to 0x0601 for Windows 7 and apparently changed _WIN32_IE to 0x0800 in StdAfx.h. Also I changed the _WIN32_WINNT in Settings -> C/C++ -> Preprocessor and now I am getting the errors as below

1>------ Build started: Project: COM, Configuration: Debug x64 ------
1>  COMIntro.cpp
1>COMIntro.cpp(21): error C2220: warning treated as error - no 'object' file generated
1>COMIntro.cpp(21): warning C4100: 'envp' : unreferenced formal parameter
1>COMIntro.cpp(21): warning C4100: 'argv' : unreferenced formal parameter
1>COMIntro.cpp(21): warning C4100: 'argc' : unreferenced formal parameter
1>  StdAfx.cpp
1>  Generating Code...
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Is it due to my windows SDK version which is 7.1 or some compatibility issue ?

Body:
I should have done some searching first. I got tangled up between COM and few other new concepts that I missed the conventional C++ dos and dont's

I just used cast. the unused variables were causing this problem

(void)argc;
(void)argv;
(void)envp;

Correct solution
Use of UNREFERENCED_PARAMETER works for me.


问:
Scotchbox: Document root missing / desynced with Vagrant
I'm using Scotchbox (box.scotch.io) for Vagrant. Since their last update I get a document root missing error (AH00112: Warning: DocumentRoot [/var/www/mypage] does not exist) when i try and set up my some domain configs in Apache. I can't really determine whether its a change in settings since Scotch 2.0 or if Vagrant for some reason has descyned these folders. My setup as follows,

Vagrant file pathway

```<code>config.vm.synced_folder ".", "/var/www", :mount_options => ["dmode=777", "fmode=666"]
</code>```

Apache domain config pathway

```<code><VirtualHost *:80>
        ServerAdmin webmaster@localhost
        ServerName mypage.dev
        ServerAlias www.mypage.dev
        DocumentRoot /var/www/mypage
</VirtualHost>
</code>```

The 000-default and scotchbox config files both point to /var/www/public. My default dev folder is located at ~username/Development, in that folder is my Vagrant file.

Any ideas?
Let me know if I need to provide other details.

Update: Switching to Docker. Tired of this.

答:
I've just cloned Scotchbox and my Vagrant file also contains:

```<code>config.vm.synced_folder ".", "/var/www", :mount_options => ["dmode=777", "fmode=666"]
</code>```

My apache config (/etc/apache2/sites-enabled/000-default.conf) looks:

```<code><VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/public
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
</code>```

And I have public directory in my root dir on the host machine, ls -1 prints:

```<code>README.md
Vagrantfile
public
</code>```

And it works for me!

In your case, you need update apache config, and have:

```<code>DocumentRoot /var/www/public
</code>```

And pay attention that you have public directory near Vagrantfile.

If you have directory mypage - then run mv mypage public

Body:
I'm using Scotchbox (box.scotch.io) for Vagrant. Since their last update I get a document root missing error (AH00112: Warning: DocumentRoot [/var/www/mypage] does not exist) when i try and set up my some domain configs in Apache. I can't really determine whether its a change in settings since Scotch 2.0 or if Vagrant for some reason has descyned these folders. My setup as follows,

Vagrant file pathway

config.vm.synced_folder ".", "/var/www", :mount_options => ["dmode=777", "fmode=666"]

Apache domain config pathway

<VirtualHost *:80>
        ServerAdmin webmaster@localhost
        ServerName mypage.dev
        ServerAlias www.mypage.dev
        DocumentRoot /var/www/mypage
</VirtualHost>

The 000-default and scotchbox config files both point to /var/www/public. My default dev folder is located at ~username/Development, in that folder is my Vagrant file.

Any ideas?
Let me know if I need to provide other details.

Update: Switching to Docker. Tired of this.

Body:
I've just cloned Scotchbox and my Vagrant file also contains:

config.vm.synced_folder ".", "/var/www", :mount_options => ["dmode=777", "fmode=666"]

My apache config (/etc/apache2/sites-enabled/000-default.conf) looks:

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/public
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

And I have public directory in my root dir on the host machine, ls -1 prints:

README.md
Vagrantfile
public

And it works for me!

In your case, you need update apache config, and have:

DocumentRoot /var/www/public

And pay attention that you have public directory near Vagrantfile.

If you have directory mypage - then run mv mypage public


问:
Price field validation using javascript either jquery?
I have a price field in my form i should allow decimal or floating point numbers only , not characters and any other special and white spaces in my price field.

How could i get that?

This is my code :

```<code>    $("#foo").blur(function() {
    var price = $("#foo").value;
    var validatePrice = function(price) {
   return /^(\d*([.,](?=\d{3}))?\d+)+((?!\2)[.,]\d\d)?$/.test(price);
}
    alert(validatePrice(price)); // False
});
</code>```

Fiddle

答:
For https://stackoverflow.com/a/21494842/1885344, the correct regex would be

```<code>var regex = /^\d*(\.\d{2})?$/;
regex.test(price);   //Boolean
</code>```

As it is now, it would permits all character as the decimal separator where as it should be only dot (.) character.

Body:
I have a price field in my form i should allow decimal or floating point numbers only , not characters and any other special and white spaces in my price field.

How could i get that?

This is my code :

    $("#foo").blur(function() {
    var price = $("#foo").value;
    var validatePrice = function(price) {
   return /^(\d*([.,](?=\d{3}))?\d+)+((?!\2)[.,]\d\d)?$/.test(price);
}
    alert(validatePrice(price)); // False
});

Fiddle

Body:
For https://stackoverflow.com/a/21494842/1885344, the correct regex would be

var regex = /^\d*(\.\d{2})?$/;
regex.test(price);   //Boolean

As it is now, it would permits all character as the decimal separator where as it should be only dot (.) character.


问:
How to add two kind of values from the same columns in a table
I have a table called Expenses in MySQL data store. The table structure and data are given below:

```<code>   ---------------
   |YEAR|Expenses|
   |----|--------|
   |2015|503K    |
   |----|--------|
   |2015|406K    |
   |----|--------|
   |2015|1.2M    |
   |----|--------|
   |2016|700K    |
   |----|--------|
   |2016|900K    |
   |----|--------|
   |2016|3.2M    |
   |----|--------|
   |2016|4.7M    |
   ---------------
</code>```

I need to take the sum of all values ending with 'K', group the result by year and multiply the result with 1000. Likewise, I need to take the sum of all the values ending with 'M', group the result by year and multiply the result with 1000000. Finally, I need to add the results of both K values and M values and obtain the total expenses for every year. My final table should look like this in two different formats:

```<code>   ---------------
   |YEAR|Expenses|
   |----|--------|
   |2015|2109000 |
   |----|--------|
   |2016|9500000 |
   |----|--------|
</code>```

or

```<code>   ---------------
   |YEAR|Expenses|
   |----|--------|
   |2015|2.1M    |
   |----|--------|
   |2016|9.5M    |
   |----|--------|
</code>```

Any suggestions or guidelines?

答:
You can use the following:

```<code>SELECT
    year,
    sum(
        CASE
            WHEN expenses like '%K' then expenses*1000
            WHEN expenses like '%M' then expenses*1000000
        END) AS expenses
FROM
    table_name
GROUP BY
    year
ORDER BY
    year;
</code>```

Hope it helps. Interesting that mysql lets you add values ending with non-numeric characters. Didn't know that one.

Body:
I have a table called Expenses in MySQL data store. The table structure and data are given below:

   ---------------
   |YEAR|Expenses|
   |----|--------|
   |2015|503K    |
   |----|--------|
   |2015|406K    |
   |----|--------|
   |2015|1.2M    |
   |----|--------|
   |2016|700K    |
   |----|--------|
   |2016|900K    |
   |----|--------|
   |2016|3.2M    |
   |----|--------|
   |2016|4.7M    |
   ---------------

I need to take the sum of all values ending with 'K', group the result by year and multiply the result with 1000. Likewise, I need to take the sum of all the values ending with 'M', group the result by year and multiply the result with 1000000. Finally, I need to add the results of both K values and M values and obtain the total expenses for every year. My final table should look like this in two different formats:

   ---------------
   |YEAR|Expenses|
   |----|--------|
   |2015|2109000 |
   |----|--------|
   |2016|9500000 |
   |----|--------|

or

   ---------------
   |YEAR|Expenses|
   |----|--------|
   |2015|2.1M    |
   |----|--------|
   |2016|9.5M    |
   |----|--------|

Any suggestions or guidelines?

Body:
You can use the following:

SELECT
    year,
    sum(
        CASE
            WHEN expenses like '%K' then expenses*1000
            WHEN expenses like '%M' then expenses*1000000
        END) AS expenses
FROM
    table_name
GROUP BY
    year
ORDER BY
    year;

Hope it helps. Interesting that mysql lets you add values ending with non-numeric characters. Didn't know that one.


问:
JDBC Connection close conecpt
I have created connection's object and stored in the hashMap. While executing query on the connection object I retrieve the object from the hashMap. In finally block I close the connection.
However, when we come for the second time I again retrieve the connection's object from the hashMap. This time while executing the query I get closed connection exception.
If I remove conn.close() from finally, it works.
what is the reason behind this? Moreover, when i print the connection's object I get the object.</p>

答:
I think you need to move to some implementation of the connection pool.

P.S. It would be helpful to see your code

Title: JDBC Connection close conecpt


问:
how to changes the background time in html canvas AI
enter image description here this is a picture of AI gaming project.

My problem is this.in this project has two times.one is daytime and night time.

this project works successfully.but I need instead of changes color of daytime and night time change a picture. I have day time and night time picture how will I insert those I tried many ways but I couldn't please help someone to do this

```<code>window.onload = init();
    function init()
    {
    cs = document.getElementById("canvas3");
    ctx = cs.getContext("2d"); // set context as 2D
    ctx.rect(10,50,900,700);
    ctx.fill();
    // Coordinates and speed of player
    var x1 = 580;
    var y1 = 200;
    var SPEED = 5;
    // initialize visibility duration count
    var count = 0;
    //initialize time of day
    timeofday = "Day Time";
    hourcount = 0;
    // initialize enemy state
    EnemyCanSee = false;
    enemyCOLOR = "green";
    // Handle keyboard controls
    var keysDown = {};
    addEventListener("keydown", function (e){
        keysDown[e.keyCode] = true;
    }, false);
    addEventListener("keyup", function (e) {
        delete keysDown[e.keyCode];
    }, false);
    //create a player to control
    function player(x1, y1)
    {
        //ctx.fillStyle = "green";
        //ctx.fillRect(x1, y1, 40, 40);
        var demoImage = new Image();   // make image object
        demoImage.src = "player.jpg";  // set image path
        ctx.drawImage(demoImage, x1, y1, 40, 40);
    }
    function drawObstacle()
    {
    var demoImage = new Image();   // make image object
    demoImage.src = "wall.jpg";  // set image path
    ctx.drawImage(demoImage, 500, 150, 50, 200);
    }
    function drawEnemy()
    {
      ctx.beginPath();
      ctx.arc(100,230,50,0,2*Math.PI,false);
      ctx.fillStyle= enemyCOLOR;
      ctx.fill();
    }
    function drawDungeonDoor()
    {
    var demoImage = new Image();   // make image object
    demoImage.src = "door.jpg";  // set image path
    ctx.drawImage(demoImage, 300, 250, 50, 60);
    }
    function clear()
    {
      ctx.fillStyle = "rgb(255, 255, 255)";
      ctx.beginPath();
      ctx.rect(0, 0, 800, 500);
      ctx.closePath();
      ctx.fill();
    }
    function drawStuff()
    {
    if (timeofday == "Night Time")
    {
      ctx.fillStyle = "black";
      ctx.rect(10,50,900,700);
      ctx.fill();
     }
    player(x1,y1);
    drawObstacle();
    drawDungeonDoor();
    drawEnemy();
    ctx.fillStyle = "red";
    ctx.font = "20px Arial";
    ctx.fillText(timeofday, 100, 70);
    }
    function checkVisibility()
    {
      if ((y1<150)|| (y1>350)||(x1<500))
         EnemyCanSee = true;
         else
         EnemyCanSee = false;
    }
    function shootPlayer()
    {
    ctx.lineWidth = 5;
    ctx.strokeStyle = 'yellow';
    ctx.moveTo(100,230);
    ctx.lineTo(x1,y1);
    ctx.stroke();
    var demoImage = new Image();   // make image object
    demoImage.src = "explode.jpg";  // set image path
    ctx.drawImage(demoImage, x1-50, y1-50, 160, 160);
    }
    function updateStuff()
    {
           if (hourcount>240) //12 hours scaled up to 1200
               timeofday = "Night Time";
            if (hourcount>480) //12 hours scaled up to 1200
               {
                 timeofday = "Day Time";
                 hourcount = 0;
               }
        checkVisibility();
        // control the ninja using arrow keys
        if (38 in keysDown && y1>0)
        {
            y1 = y1-SPEED;
        }
        if (40 in keysDown && y1<460)
        {
            y1 = y1+SPEED;
        }
            if (37 in keysDown && x1>0)
        {
            x1 = x1-SPEED;
        }
           if (39 in keysDown && x1<600)
        {
            x1 = x1+SPEED;
        }
    if (EnemyCanSee == true && timeofday == "Day Time")
               {
                 enemyCOLOR = "red";
                 count = count + 1;
            }
            else
               {
                 enemyCOLOR = "green";
             count = 0;
               }
            if (count > 60)  //player was visible for few seconds
              {
                shootPlayer();
              }

    }

    function GameLoop()
    {   clear();
        updateStuff();
        drawStuff();
            hourcount = hourcount+1;
        setTimeout(GameLoop, 1000 / 50);
    }
    GameLoop();
    }
</code>```

答:
```<code>if (timeofday == "Night Time")
{
  ctx.fillStyle = "black";
  ctx.rect(10,50,900,700);
  ctx.fill();
 }
</code>```

there is no else condition for day time

you can also use image with condition using

```<code>var background = new Image();
background.src = "http://i.imgur.com/yf6d9SX.jpg";

background.onload = function(){
    ctx.drawImage(background,0,0);
}
</code>```

Body:
enter image description here this is a picture of AI gaming project.

My problem is this.in this project has two times.one is daytime and night time.

this project works successfully.but I need instead of changes color of daytime and night time change a picture. I have day time and night time picture how will I insert those I tried many ways but I couldn't please help someone to do this

window.onload = init();
    function init()
    {
    cs = document.getElementById("canvas3");
    ctx = cs.getContext("2d"); // set context as 2D
    ctx.rect(10,50,900,700);
    ctx.fill();
    // Coordinates and speed of player
    var x1 = 580;
    var y1 = 200;
    var SPEED = 5;
    // initialize visibility duration count
    var count = 0;
    //initialize time of day
    timeofday = "Day Time";
    hourcount = 0;
    // initialize enemy state
    EnemyCanSee = false;
    enemyCOLOR = "green";
    // Handle keyboard controls
    var keysDown = {};
    addEventListener("keydown", function (e){
        keysDown[e.keyCode] = true;
    }, false);
    addEventListener("keyup", function (e) {
        delete keysDown[e.keyCode];
    }, false);
    //create a player to control
    function player(x1, y1)
    {
        //ctx.fillStyle = "green";
        //ctx.fillRect(x1, y1, 40, 40);
        var demoImage = new Image();   // make image object
        demoImage.src = "player.jpg";  // set image path
        ctx.drawImage(demoImage, x1, y1, 40, 40);
    }
    function drawObstacle()
    {
    var demoImage = new Image();   // make image object
    demoImage.src = "wall.jpg";  // set image path
    ctx.drawImage(demoImage, 500, 150, 50, 200);
    }
    function drawEnemy()
    {
      ctx.beginPath();
      ctx.arc(100,230,50,0,2*Math.PI,false);
      ctx.fillStyle= enemyCOLOR;
      ctx.fill();
    }
    function drawDungeonDoor()
    {
    var demoImage = new Image();   // make image object
    demoImage.src = "door.jpg";  // set image path
    ctx.drawImage(demoImage, 300, 250, 50, 60);
    }
    function clear()
    {
      ctx.fillStyle = "rgb(255, 255, 255)";
      ctx.beginPath();
      ctx.rect(0, 0, 800, 500);
      ctx.closePath();
      ctx.fill();
    }
    function drawStuff()
    {
    if (timeofday == "Night Time")
    {
      ctx.fillStyle = "black";
      ctx.rect(10,50,900,700);
      ctx.fill();
     }
    player(x1,y1);
    drawObstacle();
    drawDungeonDoor();
    drawEnemy();
    ctx.fillStyle = "red";
    ctx.font = "20px Arial";
    ctx.fillText(timeofday, 100, 70);
    }
    function checkVisibility()
    {
      if ((y1<150)|| (y1>350)||(x1<500))
         EnemyCanSee = true;
         else
         EnemyCanSee = false;
    }
    function shootPlayer()
    {
    ctx.lineWidth = 5;
    ctx.strokeStyle = 'yellow';
    ctx.moveTo(100,230);
    ctx.lineTo(x1,y1);
    ctx.stroke();
    var demoImage = new Image();   // make image object
    demoImage.src = "explode.jpg";  // set image path
    ctx.drawImage(demoImage, x1-50, y1-50, 160, 160);
    }
    function updateStuff()
    {
           if (hourcount>240) //12 hours scaled up to 1200
               timeofday = "Night Time";
            if (hourcount>480) //12 hours scaled up to 1200
               {
                 timeofday = "Day Time";
                 hourcount = 0;
               }
        checkVisibility();
        // control the ninja using arrow keys
        if (38 in keysDown && y1>0)
        {
            y1 = y1-SPEED;
        }
        if (40 in keysDown && y1<460)
        {
            y1 = y1+SPEED;
        }
            if (37 in keysDown && x1>0)
        {
            x1 = x1-SPEED;
        }
           if (39 in keysDown && x1<600)
        {
            x1 = x1+SPEED;
        }
    if (EnemyCanSee == true && timeofday == "Day Time")
               {
                 enemyCOLOR = "red";
                 count = count + 1;
            }
            else
               {
                 enemyCOLOR = "green";
             count = 0;
               }
            if (count > 60)  //player was visible for few seconds
              {
                shootPlayer();
              }

    }

    function GameLoop()
    {   clear();
        updateStuff();
        drawStuff();
            hourcount = hourcount+1;
        setTimeout(GameLoop, 1000 / 50);
    }
    GameLoop();
    }

Body:
if (timeofday == "Night Time")
{
  ctx.fillStyle = "black";
  ctx.rect(10,50,900,700);
  ctx.fill();
 }

there is no else condition for day time

you can also use image with condition using

var background = new Image();
background.src = "http://i.imgur.com/yf6d9SX.jpg";

background.onload = function(){
    ctx.drawImage(background,0,0);
}


问:
SELECT record in object
I am looking similar like Select record in dataset

```<code>foreach (DataRow r in Histryds.Tables[0].Select("Cust_ID='" + custid + "'"))
</code>```

Below is for object, how to use .Select?

```<code>foreach (History hr in rows)
</code>```

答:
you need a where. Not Select</p>

```<code>foreach (DataRow r in Histryds.Tables[0].AsEnumerable().Where(t=>t["Cust_ID"]==customerId))
{
   //do the needfull
}
</code>```

Title: SELECT record in object

Body:
I am looking similar like Select record in dataset

foreach (DataRow r in Histryds.Tables[0].Select("Cust_ID='" + custid + "'"))

Below is for object, how to use .Select?

foreach (History hr in rows)

Body:
you need a where. Not Select

foreach (DataRow r in Histryds.Tables[0].AsEnumerable().Where(t=>t["Cust_ID"]==customerId))
{
   //do the needfull
}


问:
Create new variables in multiple data
I have a dataset with 30 Data and I had written a loop to read all of them into the enviroment. (Thats works good).

All of them have the same 6 variables and I want to write a loop, to get a new variable in all of them. This Variable should consist of a substraction of two other Variables. Both are numeric. So thats my code.

```<code>list <- c("Data1", "Data2", "Data3", "Data4")

for (i in list){

i[,7] <- i[,5] - i[,2]

}

Get this:
Error in i[, 5] : incorrect number of dimensions
</code>```

R can't indentify the i as the variable in list. But I don't know why, because in the loop before (to read all the Datas to the Enviroment) it works perfect! I also try to write i$Variable7 <- i$Variable5 - i$Variable2 but doesnt work, too.

答:
We can get the datasets in a list, loop through the list with lapply, update the 7th column with the difference of 5th and 2nd columns

```<code>lst <- lapply(mget(list), function(x) {x[,7] <- x[,5] - x[,2]; x})
</code>```

If we really wanted to update the original dataset objects,

```<code>list2env(lst, envir = .GlobalEnv)
</code>```

The reason why the OP's code didn't work was because it was looping through the string and not getting the values of the dataset object

Title: Create new variables in multiple data

Body:
I have a dataset with 30 Data and I had written a loop to read all of them into the enviroment. (Thats works good).

All of them have the same 6 variables and I want to write a loop, to get a new variable in all of them. This Variable should consist of a substraction of two other Variables. Both are numeric. So thats my code.

list <- c("Data1", "Data2", "Data3", "Data4")

for (i in list){

i[,7] <- i[,5] - i[,2]

}

Get this:
Error in i[, 5] : incorrect number of dimensions

R can't indentify the i as the variable in list. But I don't know why, because in the loop before (to read all the Datas to the Enviroment) it works perfect! I also try to write i$Variable7 <- i$Variable5 - i$Variable2 but doesnt work, too.

Body:
We can get the datasets in a list, loop through the list with lapply, update the 7th column with the difference of 5th and 2nd columns

lst <- lapply(mget(list), function(x) {x[,7] <- x[,5] - x[,2]; x})

If we really wanted to update the original dataset objects,

list2env(lst, envir = .GlobalEnv)

The reason why the OP's code didn't work was because it was looping through the string and not getting the values of the dataset object


问:
How to send Google's original message on JavaMail?
```<code>   public static boolean sendEmail() throws Exception {
   ServerSettings server;
   String receiver="someone@example.org";
   File mail = new File("file.eml");
   String subject = "subject";
        try {
            Properties props = System.getProperties();
            Session session = Session.getInstance(props, null);
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress("someoneelse@example.org"));;
            msg.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(receiver, false));
            InputStream is = new FileInputStream(mail.getAbsoluteFile());
            MimeMessage message = new MimeMessage(session, is);
            msg.setSubject(subject);
            msg.setContent(message.getContent(), message.getEncoding());
            msg.setHeader("X-Mailer", "Email program");
            msg.setSentDate(new Date());
            SMTPTransport t = null;
            props.put("mail.smtp.host", "smtp.outlook.com");
            t = (SMTPTransport) session.getTransport("smtp");
            t.setStartTLS(true);
            t.connect("smtp.outlook.com", 587, "someone@example.org", "1234");
            t.sendMessage(msg, msg.getAllRecipients());
            System.out.println("Response: " + t.getLastServerResponse());
            return true;
        } catch (Exception e) {
            System.out.println("Not sent error: ");
            e.printStackTrace();
            throw e;
            return false;
        }
        return false;
    }
</code>```

Error:

If I save an EML file using Thunderbird,  I the message is sent normally.
However if using Google's show original message, I get the following error

```<code>javax.mail.internet.ParseException: Expected '/', got null
    at javax.mail.internet.ContentType.<init>(ContentType.java:102)
    at javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:1331)
    at javax.mail.internet.MimeMessage.updateHeaders(MimeMessage.java:2107)
    at javax.mail.internet.MimeMessage.saveChanges(MimeMessage.java:2075)
    at javax.mail.Transport.send(Transport.java:145)
</code>```

Example:

Thunderbird EML:

```<code>Delivered-To: <redacted>@gmail.com Received: by 10.12.175.177 with SMTP id s46csp2076396qvc;
        Tue, 6 Jun 2017 10:00:00 -0700 (PDT) X-Received: by 10.28.194.198 with SMTP id s189mr4723102wmf.123.1496768400250;
        Tue, 06 Jun 2017 10:00:00 -0700 (PDT) ARC-Seal: i=1; a=rsa-sha256; t=1496768400; cv=none;
        d=google.com; s=arc-20160816;
        b=muU9j+79SMnr5A+zG3srmyV566l+sGO2uNkXKiSBXv6bmGZrrnkKshbWmYuG/glSA0
         zdKK3kxIdqvXq2lgpf5xLUmd2kHLfnmFLRAP44VsX4cWE222XLceCVWB6Kz7FYrvQyOb
         eZsR5TxeNGYNMGYRsA22ojYA5hDapa7N2vA6Uq5DNt3Jh7iMFFfaRemao0IBPdChmP0k
         +1kfS06vuUm8JptpNQUzAR6UI1VHvkilWwLZADwjhTLHxyDXU/dA+m8Tl0kEBALfx5Ey
         sOa5V2yC6jaHXjrFh/YEm3lsOA4DBdUkVXCl+nsm2+ldzypjh6dl7Fjowr/Bh4pqVoM6
         +uPQ== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816;
        h=content-transfer-encoding:mime-version:subject:message-id:to:from
         :date:arc-authentication-results;
        bh=mez4y5GUUS/twpn+ODAQpRYd5LFrkFHDFwrnRROrKQw=;
        b=CnLDxOneD7gp0ycGUjuOU+HBiVR9pgiVhIi+81yEZ+q48bC/fyhPikIJxsE3gnZZN9
         RDsEcTq3HEii6jBNRNRT6P0lG07HEsVG4kCMUPezmE1SYJj1KKZ1o9XhU33dY5yNz1TZ
         LzbUCQdA0QHNccR5JW7QMzGVBmEMMr9Dn+9jFe4ms4YDwaA8+bas9zfQdVqR+R41p+LA
         WP6+MGAnhjCBTjdqzeM9mAO2i/gpqJhuv/+H5BPJQ8r6Wk0ItXRAVv74rDkMUUMbfAg8
         st8WwRKN5nU+5ZKFON+JTw4+l0hsddtjO8qV2op/Q9VNBKrLcJANhdCXADW4lzTKeP+j
         fklw== ARC-Authentication-Results: i=1; mx.google.com;
       spf=pass (google.com: best guess record for domain of <redacted>@t-online.de designates 194.25.134.84 as permitted sender) smtp.mailfrom=<redacted>@t-online.de Return-Path: <<redacted>@t-online.de> Received: from mailout09.t-online.de (mailout09.t-online.de. [194.25.134.84])
        by mx.google.com with ESMTPS id 91si12402140wrf.105.2017.06.06.10.00.00
        for <<redacted>@gmail.com>
        (version=TLS1_2 cipher=ECDHE-RSA-AES128-GCM-SHA256 bits=128/128);
        Tue, 06 Jun 2017 10:00:00 -0700 (PDT) Received-SPF: pass (google.com: best guess record for domain of <redacted>@t-online.de designates 194.25.134.84 as permitted sender) client-ip=194.25.134.84; Authentication-Results: mx.google.com;
       spf=pass (google.com: best guess record for domain of <redacted>@t-online.de designates 194.25.134.84 as permitted sender) smtp.mailfrom=<redacted>@t-online.de Received: from fwd34.aul.t-online.de (fwd34.aul.t-online.de [172.20.26.145])     by mailout09.t-online.de (Postfix) with SMTP id BD7BB427CD24    for <<redacted>@gmail.com>; Tue,  6 Jun 2017 18:59:59 +0200 (CEST) Received: from 192.168.10.106 (Gh+1Z-ZrYh+NeNL9ZgFe5BnHV3ELdJQ--fuZLhOzcsrLBbkHL3uoBI7jVcElEdow8J@[179.228.100.105]) by fwd34.t-online.de    with (TLSv1:ECDHE-RSA-AES128-SHA encrypted)     esmtp id 1dIHph-14uvui0; Tue, 6 Jun 2017 18:59:53 +0200
Date: Tue, 6 Jun 2017 13:59:47 -0300 (BRT)
From: <redacted>@t-online.de To: <redacted>@gmail.com
Message-ID: <1310540333.0.1496768392987.JavaMail.Mansueli@Mansueli-Computer>
Subject: japanese encoding issue
MIME-Version: 1.0
Content-Type: text/html; charset=UTF-8; Content-Transfer-Encoding=7bit
Content-Transfer-Encoding: base64
X-Mailer: Rodrigo's program
X-ID: Gh+1Z-ZrYh+NeNL9ZgFe5BnHV3ELdJQ--fuZLhOzcsrLBbkHL3uoBI7jVcElEdow8J
X-TOI-MSGID: 21dc56c3-b5f6-4c7d-88d0-93c4171a46c4

PGh0bWw+PGJvZHk+PHA+0JLRiyDQv9C+0LvRg9GH0LjQu9C4INGN0YLQviDQv9C40YHRjNC80L4g 0LjQty3Qt9CwINC/0L7Qv9GL0YLQutC4INCy0YXQvtC00LAg0YEg0LrQvtC80L/RjNGO0YLQtdGA PC9oMT48L2JvZHk+PC9odG1sPg==
</code>```

Google txt:

```<code>Delivered-To: <redacted>@gmail.com Received: by 10.12.175.177 with SMTP id s46csp2076396qvc;
        Tue, 6 Jun 2017 10:00:00 -0700 (PDT) X-Received: by 10.28.194.198 with SMTP id s189mr4723102wmf.123.1496768400250;
        Tue, 06 Jun 2017 10:00:00 -0700 (PDT) ARC-Seal: i=1; a=rsa-sha256; t=1496768400; cv=none;
        d=google.com; s=arc-20160816;
        b=muU9j+79SMnr5A+zG3srmyV566l+sGO2uNkXKiSBXv6bmGZrrnkKshbWmYuG/glSA0
         zdKK3kxIdqvXq2lgpf5xLUmd2kHLfnmFLRAP44VsX4cWE222XLceCVWB6Kz7FYrvQyOb
         eZsR5TxeNGYNMGYRsA22ojYA5hDapa7N2vA6Uq5DNt3Jh7iMFFfaRemao0IBPdChmP0k
         +1kfS06vuUm8JptpNQUzAR6UI1VHvkilWwLZADwjhTLHxyDXU/dA+m8Tl0kEBALfx5Ey
         sOa5V2yC6jaHXjrFh/YEm3lsOA4DBdUkVXCl+nsm2+ldzypjh6dl7Fjowr/Bh4pqVoM6
         +uPQ== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816;
        h=content-transfer-encoding:mime-version:subject:message-id:to:from
         :date:arc-authentication-results;
        bh=mez4y5GUUS/twpn+ODAQpRYd5LFrkFHDFwrnRROrKQw=;
        b=CnLDxOneD7gp0ycGUjuOU+HBiVR9pgiVhIi+81yEZ+q48bC/fyhPikIJxsE3gnZZN9
         RDsEcTq3HEii6jBNRNRT6P0lG07HEsVG4kCMUPezmE1SYJj1KKZ1o9XhU33dY5yNz1TZ
         LzbUCQdA0QHNccR5JW7QMzGVBmEMMr9Dn+9jFe4ms4YDwaA8+bas9zfQdVqR+R41p+LA
         WP6+MGAnhjCBTjdqzeM9mAO2i/gpqJhuv/+H5BPJQ8r6Wk0ItXRAVv74rDkMUUMbfAg8
         st8WwRKN5nU+5ZKFON+JTw4+l0hsddtjO8qV2op/Q9VNBKrLcJANhdCXADW4lzTKeP+j
         fklw== ARC-Authentication-Results: i=1; mx.google.com;
       spf=pass (google.com: best guess record for domain of <redacted>@t-online.de designates 194.25.134.84 as permitted sender) smtp.mailfrom=<redacted>@t-online.de Return-Path: <<redacted>@t-online.de> Received: from mailout09.t-online.de (mailout09.t-online.de. [194.25.134.84])
        by mx.google.com with ESMTPS id 91si12402140wrf.105.2017.06.06.10.00.00
        for <<redacted>@gmail.com>
        (version=TLS1_2 cipher=ECDHE-RSA-AES128-GCM-SHA256 bits=128/128);
        Tue, 06 Jun 2017 10:00:00 -0700 (PDT)
Received-SPF: pass (google.com: best guess record for domain of <redacted>@t-online.de designates 194.25.134.84 as permitted sender) client-ip=194.25.134.84; Authentication-Results: mx.google.com;
       spf=pass (google.com: best guess record for domain of <redacted>@t-online.de designates 194.25.134.84 as permitted sender) smtp.mailfrom=<redacted>@t-online.de
Received: from fwd34.aul.t-online.de (fwd34.aul.t-online.de [172.20.26.145])    by mailout09.t-online.de (Postfix) with SMTP id BD7BB427CD24    for <<redacted>@gmail.com>; Tue,  6 Jun 2017 18:59:59 +0200 (CEST)
Received: from 192.168.10.106 (Gh+1Z-ZrYh+NeNL9ZgFe5BnHV3ELdJQ--fuZLhOzcsrLBbkHL3uoBI7jVcElEdow8J@[179.228.100.105]) by fwd34.t-online.de   with (TLSv1:ECDHE-RSA-AES128-SHA encrypted)     esmtp id 1dIHph-14uvui0; Tue, 6 Jun 2017 18:59:53 +0200
Date: Tue, 6 Jun 2017 13:59:47 -0300 (BRT)
From:<redacted>@t-online.de
To: <redacted>@gmail.com
Message-ID: <1310540333.0.1496768392987.JavaMail.Mansueli@Mansueli-Computer>
Subject: japanese encoding issue
MIME-Version: 1.0
Content-Type: text/html; charset=UTF-8; Content-Transfer-Encoding=7bit
Content-Transfer-Encoding: base64
X-Mailer: Rodrigo's program
X-ID: Gh+1Z-ZrYh+NeNL9ZgFe5BnHV3ELdJQ--fuZLhOzcsrLBbkHL3uoBI7jVcElEdow8J
X-TOI-MSGID: 21dc56c3-b5f6-4c7d-88d0-93c4171a46c4

PGh0bWw+PGJvZHk+PHA+0JLRiyDQv9C+0LvRg9GH0LjQu9C4INGN0YLQviDQv9C40YHRjNC80L4g 0LjQty3Qt9CwINC/0L7Qv9GL0YLQutC4INCy0YXQvtC00LAg0YEg0LrQvtC80L/RjNGO0YLQtdGA PC9oMT48L2JvZHk+PC9odG1sPg==
</code>```

Is Google's show original message not a valid EML?  How to make it compliant with JavaMail EML parser?

答:
You're copying the content from the original message to a new message and you're using the encoding as the MIME type, which it is not, which is why you're getting the exception.  (Google vs. Thunderbird shouldn't make a difference here.)

Try this simpler version instead:

```<code>        Properties props = System.getProperties();
        props.put("mail.smtp.host", "smtp.outlook.com");
        props.put("mail.smtp.starttls.enable", "true");
        Session session = Session.getInstance(props, null);
        InputStream is = new FileInputStream(mail.getAbsoluteFile());
        MimeMessage msg = new MimeMessage(session, is);
        msg.setFrom(new InternetAddress("someoneelse@example.org"));;
        msg.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse(receiver, false));
        msg.setSubject(subject);
        msg.setHeader("X-Mailer", "Email program");
        msg.setSentDate(new Date());
        Transport.send(msg, "someone@example.org", "1234");
</code>```

Body:
   public static boolean sendEmail() throws Exception {
   ServerSettings server;
   String receiver="someone@example.org";
   File mail = new File("file.eml");
   String subject = "subject";
        try {
            Properties props = System.getProperties();
            Session session = Session.getInstance(props, null);
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress("someoneelse@example.org"));;
            msg.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(receiver, false));
            InputStream is = new FileInputStream(mail.getAbsoluteFile());
            MimeMessage message = new MimeMessage(session, is);
            msg.setSubject(subject);
            msg.setContent(message.getContent(), message.getEncoding());
            msg.setHeader("X-Mailer", "Email program");
            msg.setSentDate(new Date());
            SMTPTransport t = null;
            props.put("mail.smtp.host", "smtp.outlook.com");
            t = (SMTPTransport) session.getTransport("smtp");
            t.setStartTLS(true);
            t.connect("smtp.outlook.com", 587, "someone@example.org", "1234");
            t.sendMessage(msg, msg.getAllRecipients());
            System.out.println("Response: " + t.getLastServerResponse());
            return true;
        } catch (Exception e) {
            System.out.println("Not sent error: ");
            e.printStackTrace();
            throw e;
            return false;
        }
        return false;
    }

Error:

If I save an EML file using Thunderbird,  I the message is sent normally.
However if using Google's show original message, I get the following error

javax.mail.internet.ParseException: Expected '/', got null
    at javax.mail.internet.ContentType.<init>(ContentType.java:102)
    at javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:1331)
    at javax.mail.internet.MimeMessage.updateHeaders(MimeMessage.java:2107)
    at javax.mail.internet.MimeMessage.saveChanges(MimeMessage.java:2075)
    at javax.mail.Transport.send(Transport.java:145)

Example:

Thunderbird EML:

Delivered-To: <redacted>@gmail.com Received: by 10.12.175.177 with SMTP id s46csp2076396qvc;
        Tue, 6 Jun 2017 10:00:00 -0700 (PDT) X-Received: by 10.28.194.198 with SMTP id s189mr4723102wmf.123.1496768400250;
        Tue, 06 Jun 2017 10:00:00 -0700 (PDT) ARC-Seal: i=1; a=rsa-sha256; t=1496768400; cv=none;
        d=google.com; s=arc-20160816;
        b=muU9j+79SMnr5A+zG3srmyV566l+sGO2uNkXKiSBXv6bmGZrrnkKshbWmYuG/glSA0
         zdKK3kxIdqvXq2lgpf5xLUmd2kHLfnmFLRAP44VsX4cWE222XLceCVWB6Kz7FYrvQyOb
         eZsR5TxeNGYNMGYRsA22ojYA5hDapa7N2vA6Uq5DNt3Jh7iMFFfaRemao0IBPdChmP0k
         +1kfS06vuUm8JptpNQUzAR6UI1VHvkilWwLZADwjhTLHxyDXU/dA+m8Tl0kEBALfx5Ey
         sOa5V2yC6jaHXjrFh/YEm3lsOA4DBdUkVXCl+nsm2+ldzypjh6dl7Fjowr/Bh4pqVoM6
         +uPQ== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816;
        h=content-transfer-encoding:mime-version:subject:message-id:to:from
         :date:arc-authentication-results;
        bh=mez4y5GUUS/twpn+ODAQpRYd5LFrkFHDFwrnRROrKQw=;
        b=CnLDxOneD7gp0ycGUjuOU+HBiVR9pgiVhIi+81yEZ+q48bC/fyhPikIJxsE3gnZZN9
         RDsEcTq3HEii6jBNRNRT6P0lG07HEsVG4kCMUPezmE1SYJj1KKZ1o9XhU33dY5yNz1TZ
         LzbUCQdA0QHNccR5JW7QMzGVBmEMMr9Dn+9jFe4ms4YDwaA8+bas9zfQdVqR+R41p+LA
         WP6+MGAnhjCBTjdqzeM9mAO2i/gpqJhuv/+H5BPJQ8r6Wk0ItXRAVv74rDkMUUMbfAg8
         st8WwRKN5nU+5ZKFON+JTw4+l0hsddtjO8qV2op/Q9VNBKrLcJANhdCXADW4lzTKeP+j
         fklw== ARC-Authentication-Results: i=1; mx.google.com;
       spf=pass (google.com: best guess record for domain of <redacted>@t-online.de designates 194.25.134.84 as permitted sender) smtp.mailfrom=<redacted>@t-online.de Return-Path: <<redacted>@t-online.de> Received: from mailout09.t-online.de (mailout09.t-online.de. [194.25.134.84])
        by mx.google.com with ESMTPS id 91si12402140wrf.105.2017.06.06.10.00.00
        for <<redacted>@gmail.com>
        (version=TLS1_2 cipher=ECDHE-RSA-AES128-GCM-SHA256 bits=128/128);
        Tue, 06 Jun 2017 10:00:00 -0700 (PDT) Received-SPF: pass (google.com: best guess record for domain of <redacted>@t-online.de designates 194.25.134.84 as permitted sender) client-ip=194.25.134.84; Authentication-Results: mx.google.com;
       spf=pass (google.com: best guess record for domain of <redacted>@t-online.de designates 194.25.134.84 as permitted sender) smtp.mailfrom=<redacted>@t-online.de Received: from fwd34.aul.t-online.de (fwd34.aul.t-online.de [172.20.26.145])     by mailout09.t-online.de (Postfix) with SMTP id BD7BB427CD24    for <<redacted>@gmail.com>; Tue,  6 Jun 2017 18:59:59 +0200 (CEST) Received: from 192.168.10.106 (Gh+1Z-ZrYh+NeNL9ZgFe5BnHV3ELdJQ--fuZLhOzcsrLBbkHL3uoBI7jVcElEdow8J@[179.228.100.105]) by fwd34.t-online.de    with (TLSv1:ECDHE-RSA-AES128-SHA encrypted)     esmtp id 1dIHph-14uvui0; Tue, 6 Jun 2017 18:59:53 +0200
Date: Tue, 6 Jun 2017 13:59:47 -0300 (BRT)
From: <redacted>@t-online.de To: <redacted>@gmail.com
Message-ID: <1310540333.0.1496768392987.JavaMail.Mansueli@Mansueli-Computer>
Subject: japanese encoding issue
MIME-Version: 1.0
Content-Type: text/html; charset=UTF-8; Content-Transfer-Encoding=7bit
Content-Transfer-Encoding: base64
X-Mailer: Rodrigo's program
X-ID: Gh+1Z-ZrYh+NeNL9ZgFe5BnHV3ELdJQ--fuZLhOzcsrLBbkHL3uoBI7jVcElEdow8J
X-TOI-MSGID: 21dc56c3-b5f6-4c7d-88d0-93c4171a46c4

PGh0bWw+PGJvZHk+PHA+0JLRiyDQv9C+0LvRg9GH0LjQu9C4INGN0YLQviDQv9C40YHRjNC80L4g 0LjQty3Qt9CwINC/0L7Qv9GL0YLQutC4INCy0YXQvtC00LAg0YEg0LrQvtC80L/RjNGO0YLQtdGA PC9oMT48L2JvZHk+PC9odG1sPg==

Google txt:

Delivered-To: <redacted>@gmail.com Received: by 10.12.175.177 with SMTP id s46csp2076396qvc;
        Tue, 6 Jun 2017 10:00:00 -0700 (PDT) X-Received: by 10.28.194.198 with SMTP id s189mr4723102wmf.123.1496768400250;
        Tue, 06 Jun 2017 10:00:00 -0700 (PDT) ARC-Seal: i=1; a=rsa-sha256; t=1496768400; cv=none;
        d=google.com; s=arc-20160816;
        b=muU9j+79SMnr5A+zG3srmyV566l+sGO2uNkXKiSBXv6bmGZrrnkKshbWmYuG/glSA0
         zdKK3kxIdqvXq2lgpf5xLUmd2kHLfnmFLRAP44VsX4cWE222XLceCVWB6Kz7FYrvQyOb
         eZsR5TxeNGYNMGYRsA22ojYA5hDapa7N2vA6Uq5DNt3Jh7iMFFfaRemao0IBPdChmP0k
         +1kfS06vuUm8JptpNQUzAR6UI1VHvkilWwLZADwjhTLHxyDXU/dA+m8Tl0kEBALfx5Ey
         sOa5V2yC6jaHXjrFh/YEm3lsOA4DBdUkVXCl+nsm2+ldzypjh6dl7Fjowr/Bh4pqVoM6
         +uPQ== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816;
        h=content-transfer-encoding:mime-version:subject:message-id:to:from
         :date:arc-authentication-results;
        bh=mez4y5GUUS/twpn+ODAQpRYd5LFrkFHDFwrnRROrKQw=;
        b=CnLDxOneD7gp0ycGUjuOU+HBiVR9pgiVhIi+81yEZ+q48bC/fyhPikIJxsE3gnZZN9
         RDsEcTq3HEii6jBNRNRT6P0lG07HEsVG4kCMUPezmE1SYJj1KKZ1o9XhU33dY5yNz1TZ
         LzbUCQdA0QHNccR5JW7QMzGVBmEMMr9Dn+9jFe4ms4YDwaA8+bas9zfQdVqR+R41p+LA
         WP6+MGAnhjCBTjdqzeM9mAO2i/gpqJhuv/+H5BPJQ8r6Wk0ItXRAVv74rDkMUUMbfAg8
         st8WwRKN5nU+5ZKFON+JTw4+l0hsddtjO8qV2op/Q9VNBKrLcJANhdCXADW4lzTKeP+j
         fklw== ARC-Authentication-Results: i=1; mx.google.com;
       spf=pass (google.com: best guess record for domain of <redacted>@t-online.de designates 194.25.134.84 as permitted sender) smtp.mailfrom=<redacted>@t-online.de Return-Path: <<redacted>@t-online.de> Received: from mailout09.t-online.de (mailout09.t-online.de. [194.25.134.84])
        by mx.google.com with ESMTPS id 91si12402140wrf.105.2017.06.06.10.00.00
        for <<redacted>@gmail.com>
        (version=TLS1_2 cipher=ECDHE-RSA-AES128-GCM-SHA256 bits=128/128);
        Tue, 06 Jun 2017 10:00:00 -0700 (PDT)
Received-SPF: pass (google.com: best guess record for domain of <redacted>@t-online.de designates 194.25.134.84 as permitted sender) client-ip=194.25.134.84; Authentication-Results: mx.google.com;
       spf=pass (google.com: best guess record for domain of <redacted>@t-online.de designates 194.25.134.84 as permitted sender) smtp.mailfrom=<redacted>@t-online.de
Received: from fwd34.aul.t-online.de (fwd34.aul.t-online.de [172.20.26.145])    by mailout09.t-online.de (Postfix) with SMTP id BD7BB427CD24    for <<redacted>@gmail.com>; Tue,  6 Jun 2017 18:59:59 +0200 (CEST)
Received: from 192.168.10.106 (Gh+1Z-ZrYh+NeNL9ZgFe5BnHV3ELdJQ--fuZLhOzcsrLBbkHL3uoBI7jVcElEdow8J@[179.228.100.105]) by fwd34.t-online.de   with (TLSv1:ECDHE-RSA-AES128-SHA encrypted)     esmtp id 1dIHph-14uvui0; Tue, 6 Jun 2017 18:59:53 +0200
Date: Tue, 6 Jun 2017 13:59:47 -0300 (BRT)
From:<redacted>@t-online.de
To: <redacted>@gmail.com
Message-ID: <1310540333.0.1496768392987.JavaMail.Mansueli@Mansueli-Computer>
Subject: japanese encoding issue
MIME-Version: 1.0
Content-Type: text/html; charset=UTF-8; Content-Transfer-Encoding=7bit
Content-Transfer-Encoding: base64
X-Mailer: Rodrigo's program
X-ID: Gh+1Z-ZrYh+NeNL9ZgFe5BnHV3ELdJQ--fuZLhOzcsrLBbkHL3uoBI7jVcElEdow8J
X-TOI-MSGID: 21dc56c3-b5f6-4c7d-88d0-93c4171a46c4

PGh0bWw+PGJvZHk+PHA+0JLRiyDQv9C+0LvRg9GH0LjQu9C4INGN0YLQviDQv9C40YHRjNC80L4g 0LjQty3Qt9CwINC/0L7Qv9GL0YLQutC4INCy0YXQvtC00LAg0YEg0LrQvtC80L/RjNGO0YLQtdGA PC9oMT48L2JvZHk+PC9odG1sPg==

Is Google's show original message not a valid EML?  How to make it compliant with JavaMail EML parser?

Body:
You're copying the content from the original message to a new message and you're using the encoding as the MIME type, which it is not, which is why you're getting the exception.  (Google vs. Thunderbird shouldn't make a difference here.)

Try this simpler version instead:

        Properties props = System.getProperties();
        props.put("mail.smtp.host", "smtp.outlook.com");
        props.put("mail.smtp.starttls.enable", "true");
        Session session = Session.getInstance(props, null);
        InputStream is = new FileInputStream(mail.getAbsoluteFile());
        MimeMessage msg = new MimeMessage(session, is);
        msg.setFrom(new InternetAddress("someoneelse@example.org"));;
        msg.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse(receiver, false));
        msg.setSubject(subject);
        msg.setHeader("X-Mailer", "Email program");
        msg.setSentDate(new Date());
        Transport.send(msg, "someone@example.org", "1234");


问:
Delete shares excluding C$ D$ ADMIN$… etc
Have a script in .bat for deliting shares on win7 (without admins shares like ADMIN$ etc.)

```<code>@echo off
(wmic path Win32_OperatingSystem get /value|find "ProductType=1" > nul) || (echo [e] Server OS & goto :eof)
setlocal EnableDelayedExpansion

for /f "delims=" %%a in ('wmic share get name /value ^| findstr /r /v "^$"') do (
        for /f "tokens=2 delims==" %%b in ("%%a") do (
        set VarAdminAllowed=NotAllowed
        for %%c in (ADMIN$ IPC$ print$ fax$ A$ B$ C$ D$ E$ F$ G$ H$ I$ J$ K$ L$ M$ N$ O$ P$ Q$ R$ S$ T$ U$ V$ W$ X$ Y$ Z$) do (
          if %%b == %%c set VarAdminAllowed=Allowed
          )
        if !VarAdminAllowed! == NotAllowed net share /delete "%%b" /yes
    )
)
</code>```

May be another way to delete shares exist ?
P. S. Domain users over 3000+

答:
@echo off
    setlocal enableextensions disabledelayedexpansion

    rem Win32_OperatingSystem class
    rem https://msdn.microsoft.com/en-us/library/aa394239%28v=vs.85%29.aspx
    ( wmic OS where "ProductType=1" | find "Boot" ) >nul 2>nul || (
        echo [e] Server OS
        goto :eof
    )

    rem Win32_Share class
    rem https://msdn.microsoft.com/en-us/library/aa394435%28v=vs.85%29.aspx
    wmic share where "Type < 2147483648" call Delete
```

Just use the methods exposed by the wmi class.

Body:
Have a script in .bat for deliting shares on win7 (without admins shares like ADMIN$ etc.)

@echo off
(wmic path Win32_OperatingSystem get /value|find "ProductType=1" > nul) || (echo [e] Server OS & goto :eof)
setlocal EnableDelayedExpansion

for /f "delims=" %%a in ('wmic share get name /value ^| findstr /r /v "^$"') do (
        for /f "tokens=2 delims==" %%b in ("%%a") do (
        set VarAdminAllowed=NotAllowed
        for %%c in (ADMIN$ IPC$ print$ fax$ A$ B$ C$ D$ E$ F$ G$ H$ I$ J$ K$ L$ M$ N$ O$ P$ Q$ R$ S$ T$ U$ V$ W$ X$ Y$ Z$) do (
          if %%b == %%c set VarAdminAllowed=Allowed
          )
        if !VarAdminAllowed! == NotAllowed net share /delete "%%b" /yes
    )
)

May be another way to delete shares exist ?
P. S. Domain users over 3000+

Body:
@echo off
    setlocal enableextensions disabledelayedexpansion

    rem Win32_OperatingSystem class
    rem https://msdn.microsoft.com/en-us/library/aa394239%28v=vs.85%29.aspx
    ( wmic OS where "ProductType=1" | find "Boot" ) >nul 2>nul || (
        echo [e] Server OS
        goto :eof
    )

    rem Win32_Share class
    rem https://msdn.microsoft.com/en-us/library/aa394435%28v=vs.85%29.aspx
    wmic share where "Type < 2147483648" call Delete

Just use the methods exposed by the wmi class.


问:
Optimized mysql queries in mysql database
I want to fetch 3 rows data from class table who is belongs to class 5,6 and 7 last row only.

Right now I'm using 3 sql queries to fetch data:

```<code> 1. SELECT * from class where class_name = '5';

 2. SELECT * from class where class_name = '6';

 3. SELECT * from class where class_name = '7';
</code>```

How can I use single sql query to retrieve 3 row data instead of 3 sql queries ?

```<code>**class table structure:**

|id | class_name | student  |
|---| -----------| ---------|
|1  |      5     | Student A|
|2  |      6     | Student B|
|3  |      4     | Student C|
|4  |      6     | Student D|
|5  |      7     | Student E|
|6  |      5     | Student F|
|7  |      4     | Student G|
|8  |      6     | Student H|
|9  |      5     | Student I|
|10 |      6     | Student J|
|11 |      7     | Student K|
|12 |      6     | Student L|
|13 |      8     | Student M|
|14 |      6     | Student N|
|15 |      8     | Student O|
</code>```

Result required:
Student I,Student N and Student K

答:
```<code>SELECT * FROM class
WHERE id IN (
    SELECT MAX(ID)
    FROM dbo.class
    WHERE class_name IN (5,6,7)
    GROUP BY class_name )
</code>```

This should do the trick, tested and here's the result:

```<code>id          class_name student
----------- ---------- --------------------
1           5          A
2           6          B
3           4          C
4           6          D
5           7          E
6           5          F
7           4          G
8           6          H
9           5          I
10          6          J
11          7          K
12          6          L
13          8          M
14          6          N
15          8          O

(15 row(s) affected)

id          class_name student
----------- ---------- --------------------
9           5          I
11          7          K
14          6          N

(3 row(s) affected)
</code>```

Body:
I want to fetch 3 rows data from class table who is belongs to class 5,6 and 7 last row only.

Right now I'm using 3 sql queries to fetch data:

 1. SELECT * from class where class_name = '5';

 2. SELECT * from class where class_name = '6';

 3. SELECT * from class where class_name = '7';

How can I use single sql query to retrieve 3 row data instead of 3 sql queries ?

**class table structure:**

|id | class_name | student  |
|---| -----------| ---------|
|1  |      5     | Student A|
|2  |      6     | Student B|
|3  |      4     | Student C|
|4  |      6     | Student D|
|5  |      7     | Student E|
|6  |      5     | Student F|
|7  |      4     | Student G|
|8  |      6     | Student H|
|9  |      5     | Student I|
|10 |      6     | Student J|
|11 |      7     | Student K|
|12 |      6     | Student L|
|13 |      8     | Student M|
|14 |      6     | Student N|
|15 |      8     | Student O|

Result required:
Student I,Student N and Student K

Body:
SELECT * FROM class
WHERE id IN (
    SELECT MAX(ID)
    FROM dbo.class
    WHERE class_name IN (5,6,7)
    GROUP BY class_name )

This should do the trick, tested and here's the result:

id          class_name student
----------- ---------- --------------------
1           5          A
2           6          B
3           4          C
4           6          D
5           7          E
6           5          F
7           4          G
8           6          H
9           5          I
10          6          J
11          7          K
12          6          L
13          8          M
14          6          N
15          8          O

(15 row(s) affected)

id          class_name student
----------- ---------- --------------------
9           5          I
11          7          K
14          6          N

(3 row(s) affected)


问:
How do i save an C# float to an Mysql float?
I can't find any solution, how to save an float in c# to mysql. It save's only the integer.
If my float is for example 2.5 and i save it into my table, than there it's a 2.

I changed the type to double, but i got the same result.
Can somebody help me?

答:
This is my SQL Command:

```<code> using (MySqlConnection connection = new MySqlConnection(sqlConnString.GetConnectionString(true)))
        {
            connection.Open();

            string SQLString = @"INSERT INTO account_components
                                (accountID,shapeMother,shapeFather,skinMother,skinFather,shapeMix,skinMix,
                                eyeColor,eyeBrows,lipstick,lipstickColor,beard,beardColor,
                                hair,hairColor) VALUES
                                ('" + _acc.Id + "'," +
                                "'" + _acc.Character.ShapeMother + "'," +
                                "'" + _acc.Character.ShapeFather + "'," +
                                "'" + _acc.Character.SkinMother + "'," +
                                "'" + _acc.Character.SkinFather + "'," +
                                "'@ShapeMix'," +
                                "'@SkinMix'," +
                                "'" + _acc.Character.EyeColor + "'," +
                                "'" + _acc.Character.EyeBrows + "'," +
                                "'" + _acc.Character.Lipstick + "'," +
                                "'" + _acc.Character.LipstickColor + "'," +
                                "'" + _acc.Character.Beard + "'," +
                                "'" + _acc.Character.BeardColor + "'," +
                                "'" + _acc.Character.Hair + "'," +
                                "'" + _acc.Character.HairColor + "')";

            using (MySqlCommand cmd = new MySqlCommand(SQLString, connection))
            {
                cmd.Parameters.Add("ShapeMix", MySqlDbType.Float).Value = 0.5f; //_acc.Character.ShapeMix;
                cmd.Parameters.Add("SkinMix", MySqlDbType.Float).Value = 0.5f; //_acc.Character.SkinMix;
                cmd.ExecuteNonQuery();
            }

        } //connection closed and disposed here
    }
</code>```

And this is my database: Database Description

Body:
This is my SQL Command:

 using (MySqlConnection connection = new MySqlConnection(sqlConnString.GetConnectionString(true)))
        {
            connection.Open();

            string SQLString = @"INSERT INTO account_components
                                (accountID,shapeMother,shapeFather,skinMother,skinFather,shapeMix,skinMix,
                                eyeColor,eyeBrows,lipstick,lipstickColor,beard,beardColor,
                                hair,hairColor) VALUES
                                ('" + _acc.Id + "'," +
                                "'" + _acc.Character.ShapeMother + "'," +
                                "'" + _acc.Character.ShapeFather + "'," +
                                "'" + _acc.Character.SkinMother + "'," +
                                "'" + _acc.Character.SkinFather + "'," +
                                "'@ShapeMix'," +
                                "'@SkinMix'," +
                                "'" + _acc.Character.EyeColor + "'," +
                                "'" + _acc.Character.EyeBrows + "'," +
                                "'" + _acc.Character.Lipstick + "'," +
                                "'" + _acc.Character.LipstickColor + "'," +
                                "'" + _acc.Character.Beard + "'," +
                                "'" + _acc.Character.BeardColor + "'," +
                                "'" + _acc.Character.Hair + "'," +
                                "'" + _acc.Character.HairColor + "')";

            using (MySqlCommand cmd = new MySqlCommand(SQLString, connection))
            {
                cmd.Parameters.Add("ShapeMix", MySqlDbType.Float).Value = 0.5f; //_acc.Character.ShapeMix;
                cmd.Parameters.Add("SkinMix", MySqlDbType.Float).Value = 0.5f; //_acc.Character.SkinMix;
                cmd.ExecuteNonQuery();
            }

        } //connection closed and disposed here
    }

And this is my database: Database Description


问:
Printing last name + first name - but it shows error (Java)
So I have made a code for user to enter their first and last name; then exhanging the two position.

for example. Bulota Babi becomes Babi, Bulota

this is my code

```<code>public class trial {
    public static void main(String [] args) {
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();

        String fname = input.substring(0, input.indexOf(0));
        String lname = input.substring(1, input.indexOf(input.length()));

        System.out.println(lname +","+ fname);
    }

}
</code>```

im not sure whats wrong with it, this is the error message

```<code>Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.String.substring(String.java:1967)
    at trial.main(trial.java:11)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
</code>```

答:
Better to just use String.split

```<code>public static void main(String [] args) {
    Scanner sc = new Scanner(System.in);
    String input = sc.nextLine();

    String arr[] = input.split (" ");
    if (arr.length > 1)
        System.out.println(arr[1] +","+ arr[0]);
}
</code>```

With your solution, it is trying to find a char with the ascii value 0 which of course is returning -1 as it does not exist - hence your substring is failing

edit

To answer your comment below

```<code>         String in = "John Appleseed William";
         String arr[] = in.split (" ");
         if (arr.length == 2) {
             System.out.println(arr[1] + ", " + arr[0]);
         }
         if (arr.length == 3) {
             System.out.println(arr[2] + ", " + arr[0] + " " + arr[1]);
         }
</code>```

Body:
So I have made a code for user to enter their first and last name; then exhanging the two position.

for example. Bulota Babi becomes Babi, Bulota

this is my code

public class trial {
    public static void main(String [] args) {
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();

        String fname = input.substring(0, input.indexOf(0));
        String lname = input.substring(1, input.indexOf(input.length()));

        System.out.println(lname +","+ fname);
    }

}

im not sure whats wrong with it, this is the error message

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.String.substring(String.java:1967)
    at trial.main(trial.java:11)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

Body:
Better to just use String.split

public static void main(String [] args) {
    Scanner sc = new Scanner(System.in);
    String input = sc.nextLine();

    String arr[] = input.split (" ");
    if (arr.length > 1)
        System.out.println(arr[1] +","+ arr[0]);
}

With your solution, it is trying to find a char with the ascii value 0 which of course is returning -1 as it does not exist - hence your substring is failing

edit

To answer your comment below

         String in = "John Appleseed William";
         String arr[] = in.split (" ");
         if (arr.length == 2) {
             System.out.println(arr[1] + ", " + arr[0]);
         }
         if (arr.length == 3) {
             System.out.println(arr[2] + ", " + arr[0] + " " + arr[1]);
         }


问:
How to make pdf file password protected?
I want to make pdf file password protected. I just goolge it for the same and find a good solution given below. It's working fine But it wipe out all the data which is already there in my pdf after i secure pdf using below given code.

Used jar files for this code are:

itextpdf-5.2.1.jar

bcmail-jdk16-1.46.jar

bcprov-jdk16-1.46.jar

bctsp-jdk16-1.46.jar

Code to secure PDF :

```<code>import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Secure_file {
    private static String USER_PASSWORD = "password";
    private static String OWNER_PASSWORD = "secured";
    public static void main(String[] args) throws IOException {
        Document document = new Document();
        try {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("E:\\sample.pdf"));
            writer.setEncryption(USER_PASSWORD.getBytes(),OWNER_PASSWORD.getBytes(), PdfWriter.ALLOW_PRINTING,PdfWriter.ENCRYPTION_AES_128);
            document.open();
            document.add(new Paragraph("This is Password Protected PDF document."));
            document.close();
            writer.close();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}
</code>```

what changes i need to made in this program ?

答:
```<code>stamper.setEncryption(USER, OWNER,PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128);
</code>```

I've used this code to add password for the pdf. it will ask for the password while opening the pdf

Body:
I want to make pdf file password protected. I just goolge it for the same and find a good solution given below. It's working fine But it wipe out all the data which is already there in my pdf after i secure pdf using below given code.

Used jar files for this code are:

itextpdf-5.2.1.jar

bcmail-jdk16-1.46.jar

bcprov-jdk16-1.46.jar

bctsp-jdk16-1.46.jar

Code to secure PDF :

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Secure_file {
    private static String USER_PASSWORD = "password";
    private static String OWNER_PASSWORD = "secured";
    public static void main(String[] args) throws IOException {
        Document document = new Document();
        try {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("E:\\sample.pdf"));
            writer.setEncryption(USER_PASSWORD.getBytes(),OWNER_PASSWORD.getBytes(), PdfWriter.ALLOW_PRINTING,PdfWriter.ENCRYPTION_AES_128);
            document.open();
            document.add(new Paragraph("This is Password Protected PDF document."));
            document.close();
            writer.close();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

what changes i need to made in this program ?

Body:
stamper.setEncryption(USER, OWNER,PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128);

I've used this code to add password for the pdf. it will ask for the password while opening the pdf