问:
How to grab inout from user and modify file using echo or sed
I am using the below code to get input from user and modify my backup.php file:

```<code>#!/bin/bash
read -p "Enter hostname: " hostname
read -p "Enter cPanel username: " user
read -p "Enter password: " pass

echo "\$source_server_ip = \"$hostname\";" >> "backup.php"
echo "\$cpanel_account = \"$user\"; "      >> "backup.php"
echo "\$cpanel_password = \"$pass\"; "     >> "backup.php"
</code>```

This works perfectly; however, I want to insert the user-provided details in backup.php at line numbers 4, 5 and 6, respectively.

backup.php contents:

```<code>Line no. 1: php
Line no. 2: include xmlapi.php
Line no. 3: (blank)
Line no. 4: $source_server_ip = "   ";
Line no. 5: $cpanel_account = "   ";
Line no. 6: $cpanel_password = "   ";
Line no 7 L code continue..
</code>```

I want to keep reset of the code as it is and want to make changes in line no 4,5.6 online.

How can I do this?  Do I need to use sed?

答:
If I understand correctly, you need to replace/update your 4th, 5th and 6th line with some new lines. You can use sed's substitution command for this:

```<code>host_line="\$source_server_ip = \"$hostname\""
user_line="\$cpanel_account = \"$user\""
pass_line="\$cpanel_password = \"$pass\""

sed -i "4s/.*/$host_line/; 5s/.*/$user_line/; 6s/.*/$pass_line/" backup.php

#different notation:
sed -i -e "4s/.*/$host_line/" -e "5s/.*/$user_line/" -e "6s/.*/$pass_line/" backup.php
</code>```

4s determines on which line the substitution command should take place (in this case 4th line)

.* matches the entire line and substitutes it with your user input

-i is in-place editing. It will edit your file instead of sending the result to stdin

Warning: using sed's s command is really straightforward but it can have some surprising and dangerous results if your variables contain unescaped special characters to sed, for example: &, /, newline, ...

Or make use of the sed's  c command:

```<code>sed -i "4c \
$host_line
5c \
$user_line
6c \
$pass_line
" backup.php

#different notatiton:
sed -i -e "4c $host_line" -e "5c $user_line" -e "6c $pass_line" backup.php
</code>```

Warning: you can manage to break this as well, with unescaped newline for example:

```<code>pass='mypass
2c oops'
</code>```

You will either have to escape those special characters to sed or use what I consider the safest solution, awk:

```<code>awk -i inplace -v hl="$host_line" -v ul="$user_line" -v pl="$pass_line" '
   NR==4 { $0=hl }
   NR==5 { $0=ul }
   NR==6 { $0=pl }
   { print }'  backup.php
</code>```

Do not forget to use -r option with read or it will treat backslashes specially.

Also, note that even backslashes in your variables will later get interpreted! You can add extra backslashes with parameter expansion if you want to prevent this:

```<code>host_line="\$source_server_ip = \"${hostname//\\/\\\\}\""
user_line="\$cpanel_account = \"${user//\\/\\\\}\""
pass_line="\$cpanel_password = \"${pass//\\/\\\\}\""
</code>```

EDIT: If you just want to insert the 3 lines after the 3th line, use this simple sed:

```<code>sed -i "4i $host_line\n$user_line\n$pass_line" backup.php
</code>```

Body:
I am using the below code to get input from user and modify my backup.php file:

#!/bin/bash
read -p "Enter hostname: " hostname
read -p "Enter cPanel username: " user
read -p "Enter password: " pass

echo "\$source_server_ip = \"$hostname\";" >> "backup.php"
echo "\$cpanel_account = \"$user\"; "      >> "backup.php"
echo "\$cpanel_password = \"$pass\"; "     >> "backup.php"

This works perfectly; however, I want to insert the user-provided details in backup.php at line numbers 4, 5 and 6, respectively.

backup.php contents:

Line no. 1: php
Line no. 2: include xmlapi.php
Line no. 3: (blank)
Line no. 4: $source_server_ip = "   ";
Line no. 5: $cpanel_account = "   ";
Line no. 6: $cpanel_password = "   ";
Line no 7 L code continue..

I want to keep reset of the code as it is and want to make changes in line no 4,5.6 online.

How can I do this?  Do I need to use sed?

Body:
If I understand correctly, you need to replace/update your 4th, 5th and 6th line with some new lines. You can use sed's substitution command for this:

host_line="\$source_server_ip = \"$hostname\""
user_line="\$cpanel_account = \"$user\""
pass_line="\$cpanel_password = \"$pass\""

sed -i "4s/.*/$host_line/; 5s/.*/$user_line/; 6s/.*/$pass_line/" backup.php

#different notation:
sed -i -e "4s/.*/$host_line/" -e "5s/.*/$user_line/" -e "6s/.*/$pass_line/" backup.php

4s determines on which line the substitution command should take place (in this case 4th line)

.* matches the entire line and substitutes it with your user input

-i is in-place editing. It will edit your file instead of sending the result to stdin

Warning: using sed's s command is really straightforward but it can have some surprising and dangerous results if your variables contain unescaped special characters to sed, for example: &, /, newline, ...

Or make use of the sed's  c command:

sed -i "4c \
$host_line
5c \
$user_line
6c \
$pass_line
" backup.php

#different notatiton:
sed -i -e "4c $host_line" -e "5c $user_line" -e "6c $pass_line" backup.php

Warning: you can manage to break this as well, with unescaped newline for example:

pass='mypass
2c oops'

You will either have to escape those special characters to sed or use what I consider the safest solution, awk:

awk -i inplace -v hl="$host_line" -v ul="$user_line" -v pl="$pass_line" '
   NR==4 { $0=hl }
   NR==5 { $0=ul }
   NR==6 { $0=pl }
   { print }'  backup.php

Do not forget to use -r option with read or it will treat backslashes specially.

Also, note that even backslashes in your variables will later get interpreted! You can add extra backslashes with parameter expansion if you want to prevent this:

host_line="\$source_server_ip = \"${hostname//\\/\\\\}\""
user_line="\$cpanel_account = \"${user//\\/\\\\}\""
pass_line="\$cpanel_password = \"${pass//\\/\\\\}\""

EDIT: If you just want to insert the 3 lines after the 3th line, use this simple sed:

sed -i "4i $host_line\n$user_line\n$pass_line" backup.php


来源: stackexchange

问:
How do I programmatically access data about my database?
I'd like to access the list of tables and for each table report number of rows, disk space used, etc. It would be nice to get these details at the database level, too.

How do I do this programmatically?

答:
Jason's answer above is good, but more generally. you're looking at Information Schema. Also Wikipedia's entry:

http://en.wikipedia.org/wiki/Information_schema

ContentLicense: CC BY-SA 2.5


问:
MyBatis and SQL, best performance query
I would know that is the best way to do a query linke the following. I need to optimize performances and to avoid useless operation in the DB (postgresql).

User will input a series of filters, which are a couple of values ("id_meta" and "value"), which will reduce the numbers of rows I exctract from "meta" table. Those fields are not PK.

Here is an example, the table has more column, but those are the interested ones.

```<code>| id_meta | value      | id_ud |
| ------- |:----------:| -----:|
| 1       | pippo      | 45    |
| 2       | 10         | 45    |
| 3       | 21/05/2010 | 45    |
| 1       | pluto      | 35    |
| 2       | 14         | 35    |
| 3       | 22/05/2010 | 35    |
</code>```

and so on... if users inputs the couple (1:pippo) and (2:14) the query will return 0 rows, because there is not a (2:14) for the id_ud returned by the first filter (45).

it can't give different values for the same id_meta at the same time, things like (1:pippo) AND (1:pluto) are not possible

So basically every couple of filters is a nested subqueries, which reduce the numbers of the first result set. If user will give 3 filters, I would do 3 subqueries

```<code>select id_ud
from meta
where id_meta = 12
      and value = '45'
      and id_ud in (select id_ud
                    from meta
                    where id_meta = 10
                    and value = 1000
                    and id_ud in (select id_ud
                                  from meta
                                  where id_meta = 6
                                  and value = 'll'
                                 )
                   )
</code>```

I need to count the number of the returned rows AND I have another condition

```<code>select count(id_ud)
from meta
where id_ud in (select ID_UD
                from documento
                where stato = 'ACHIVIATO'
                and id_cat_doc = 2)
and value= '2010'
and id_meta = 12 and id_ud in (select id_ud
                               from meta
                               where id_meta = 10
                               and value = 1000
                               and id_ud in (select id_ud
                                             from meta
                                             where id_meta = 6
                                             and value = 'll'
                                             )
                              );
</code>```

So basically I have to dinamically create a nested subqueries with MyBatis and count the returned values, as the last example above. Is there a way to avoid all that subqueries, pheraps using ANY, ALL, UNION or other SQL constructs ?

Thanks, please feel free to add more detail, I'm not sure i explained clearly my problem...

UPDATE

I'm trying to build this query with mybatis

```<code>    select
        count (id_ud)
    from
        documento
    where
        stato = 'ARCHIVIATO'
        and id_categoria_documentale = #{param2, jdbcType=BIGINT}
        <foreach item="value" index="key" collection="param1.entrySet()" open=" and id_ud in ("
            separator=" and id_ud in (" close="))">
            select
                id_ud
            from
                meta
            where
                id_meta = #{key, jdbcType=INTEGER}
                and value = #{value, jdbcType=VARCHAR}
        </foreach>
</code>```

Where param1 is the map object containing all the user filters. I have problems adding the correct numbers of closing )... Any Ideas ?

答:
try this

```<code>select count(id_ud)
from meta mt1
join (select ID_UD from documento where stato = 'ACHIVIATO' and id_cat_doc = 2) doc on (doc.ID_UD = mt1.id_ud)
join (select id_ud from meta where id_meta = 10 and value = 1000 ) mt2 on (mt2.id_ud = mt1.id_ud)
join (select id_ud from meta where id_meta = 6 and value = 'll' )  mt3 on (mt3.id_ud = mt2.id_ud)
where value= '2010' and id_meta = 12
</code>```

this should be faster..

EDIT:
another way:

```<code>select count(id_ud)
from meta mt1
join (select ID_UD from documento where stato = 'ACHIVIATO' and id_cat_doc = 2) doc on (doc.ID_UD = mt1.id_ud)
where (1=1) --always true
or (value= '2010' and id_meta = 12) and (id_meta = 6 and value = 'll') and (id_meta = 10 and value = 1000) --user conditions
</code>```

and you can build dynamic query in your script/program

ContentLicense: CC BY-SA 3.0

Title: MyBatis and SQL, best performance query

Body:
I would know that is the best way to do a query linke the following. I need to optimize performances and to avoid useless operation in the DB (postgresql).

User will input a series of filters, which are a couple of values ("id_meta" and "value"), which will reduce the numbers of rows I exctract from "meta" table. Those fields are not PK.

Here is an example, the table has more column, but those are the interested ones.

| id_meta | value      | id_ud |
| ------- |:----------:| -----:|
| 1       | pippo      | 45    |
| 2       | 10         | 45    |
| 3       | 21/05/2010 | 45    |
| 1       | pluto      | 35    |
| 2       | 14         | 35    |
| 3       | 22/05/2010 | 35    |

and so on... if users inputs the couple (1:pippo) and (2:14) the query will return 0 rows, because there is not a (2:14) for the id_ud returned by the first filter (45).

it can't give different values for the same id_meta at the same time, things like (1:pippo) AND (1:pluto) are not possible

So basically every couple of filters is a nested subqueries, which reduce the numbers of the first result set. If user will give 3 filters, I would do 3 subqueries

select id_ud
from meta
where id_meta = 12
      and value = '45'
      and id_ud in (select id_ud
                    from meta
                    where id_meta = 10
                    and value = 1000
                    and id_ud in (select id_ud
                                  from meta
                                  where id_meta = 6
                                  and value = 'll'
                                 )
                   )

I need to count the number of the returned rows AND I have another condition

select count(id_ud)
from meta
where id_ud in (select ID_UD
                from documento
                where stato = 'ACHIVIATO'
                and id_cat_doc = 2)
and value= '2010'
and id_meta = 12 and id_ud in (select id_ud
                               from meta
                               where id_meta = 10
                               and value = 1000
                               and id_ud in (select id_ud
                                             from meta
                                             where id_meta = 6
                                             and value = 'll'
                                             )
                              );

So basically I have to dinamically create a nested subqueries with MyBatis and count the returned values, as the last example above. Is there a way to avoid all that subqueries, pheraps using ANY, ALL, UNION or other SQL constructs ?

Thanks, please feel free to add more detail, I'm not sure i explained clearly my problem...

UPDATE

I'm trying to build this query with mybatis

    select
        count (id_ud)
    from
        documento
    where
        stato = 'ARCHIVIATO'
        and id_categoria_documentale = #{param2, jdbcType=BIGINT}
        <foreach item="value" index="key" collection="param1.entrySet()" open=" and id_ud in ("
            separator=" and id_ud in (" close="))">
            select
                id_ud
            from
                meta
            where
                id_meta = #{key, jdbcType=INTEGER}
                and value = #{value, jdbcType=VARCHAR}
        </foreach>

Where param1 is the map object containing all the user filters. I have problems adding the correct numbers of closing )... Any Ideas ?

Body:
try this

select count(id_ud)
from meta mt1
join (select ID_UD from documento where stato = 'ACHIVIATO' and id_cat_doc = 2) doc on (doc.ID_UD = mt1.id_ud)
join (select id_ud from meta where id_meta = 10 and value = 1000 ) mt2 on (mt2.id_ud = mt1.id_ud)
join (select id_ud from meta where id_meta = 6 and value = 'll' )  mt3 on (mt3.id_ud = mt2.id_ud)
where value= '2010' and id_meta = 12

this should be faster..

EDIT:
another way:

select count(id_ud)
from meta mt1
join (select ID_UD from documento where stato = 'ACHIVIATO' and id_cat_doc = 2) doc on (doc.ID_UD = mt1.id_ud)
where (1=1) --always true
or (value= '2010' and id_meta = 12) and (id_meta = 6 and value = 'll') and (id_meta = 10 and value = 1000) --user conditions

and you can build dynamic query in your script/program


问:
onCreateView() is never called in Fragment
i want to build the next UI:

TabLayout with 2 tabs and 2 different Fragments (Solved and Unsolved)
My onCreateView in Fragment is never called.

Here I inflate my viewPager:

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

    setContentView(R.layout.activity_main);

    mToolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(mToolbar);

    ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    mAdapter = new ViewPagerAdapter(getSupportFragmentManager());
    mAdapter.addFragment(new UnsolvedTasksFragment());
    mAdapter.addFragment(new SolvedTasksFragment());
    viewPager.setAdapter(mAdapter);

    mTabLayout = (TabLayout) findViewById(R.id.tabs);
    mTabLayout.setupWithViewPager(viewPager);

    mTabLayout.getTabAt(0).setText(getString(R.string.tablayout_unsolved));
    mTabLayout.getTabAt(1).setText(getString(R.string.tablayout_solved));

}
</code>```

My custom ViewPagerAdapter:

```<code> public class ViewPagerAdapter extends FragmentPagerAdapter {
 private final List<Fragment> mFragmentList = new ArrayList<>();

public ViewPagerAdapter(FragmentManager manager) {
    super(manager);
}

@Override
public Fragment getItem(int position) {
    if (!mFragmentList.isEmpty() && mFragmentList.size() > id)
        return mFragmentList.get(position);
    return new Fragment();
}

@Override
public int getCount() {
    return mFragmentList.size();
}

public void addFragment(Fragment fragment) {
    mFragmentList.add(fragment);
}

@Override
public CharSequence getPageTitle(int position) {
    return null;
}
}
</code>```

Here an example of my Fragment:

```<code> public class SolvedTasksFragment extends Fragment implements RecyclerViewClickListenerSolved {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
       //Some code here;
        return rootView;
    }

    @Override
    public void itemClick(View v, int position) {
       }
}
</code>```

Maybe somebody can tell what is wrong.

I don't need  the whole solution.

答:
First set the adapter and then add the fragments. Do it like this.
Change these statements

```<code>    mAdapter = new ViewPagerAdapter(getSupportFragmentManager());
    mAdapter.addFragment(new UnsolvedTasksFragment());
    mAdapter.addFragment(new SolvedTasksFragment());
    viewPager.setAdapter(mAdapter);
</code>```

to these

```<code>mAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
mAdapter.addFragment(new UnsolvedTasksFragment());
mAdapter.addFragment(new SolvedTasksFragment());
</code>```

Body:
i want to build the next UI:

TabLayout with 2 tabs and 2 different Fragments (Solved and Unsolved)
My onCreateView in Fragment is never called.

Here I inflate my viewPager:

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

    setContentView(R.layout.activity_main);

    mToolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(mToolbar);

    ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    mAdapter = new ViewPagerAdapter(getSupportFragmentManager());
    mAdapter.addFragment(new UnsolvedTasksFragment());
    mAdapter.addFragment(new SolvedTasksFragment());
    viewPager.setAdapter(mAdapter);

    mTabLayout = (TabLayout) findViewById(R.id.tabs);
    mTabLayout.setupWithViewPager(viewPager);

    mTabLayout.getTabAt(0).setText(getString(R.string.tablayout_unsolved));
    mTabLayout.getTabAt(1).setText(getString(R.string.tablayout_solved));

}

My custom ViewPagerAdapter:

 public class ViewPagerAdapter extends FragmentPagerAdapter {
 private final List<Fragment> mFragmentList = new ArrayList<>();

public ViewPagerAdapter(FragmentManager manager) {
    super(manager);
}

@Override
public Fragment getItem(int position) {
    if (!mFragmentList.isEmpty() && mFragmentList.size() > id)
        return mFragmentList.get(position);
    return new Fragment();
}

@Override
public int getCount() {
    return mFragmentList.size();
}

public void addFragment(Fragment fragment) {
    mFragmentList.add(fragment);
}

@Override
public CharSequence getPageTitle(int position) {
    return null;
}
}

Here an example of my Fragment:

 public class SolvedTasksFragment extends Fragment implements RecyclerViewClickListenerSolved {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
       //Some code here;
        return rootView;
    }

    @Override
    public void itemClick(View v, int position) {
       }
}

Maybe somebody can tell what is wrong.

I don't need  the whole solution.

Body:
First set the adapter and then add the fragments. Do it like this.
Change these statements

    mAdapter = new ViewPagerAdapter(getSupportFragmentManager());
    mAdapter.addFragment(new UnsolvedTasksFragment());
    mAdapter.addFragment(new SolvedTasksFragment());
    viewPager.setAdapter(mAdapter);

to these

mAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
mAdapter.addFragment(new UnsolvedTasksFragment());
mAdapter.addFragment(new SolvedTasksFragment());


问:
php time returns wrong timestamp
why my PHP time returns wrong timestamp I compare my server, value with three other servers seem all the three servers give same result expect my server how can I solve this problem? Also, I asked the support and show them the difference in time they said no problem in our server as he said "the time is right in the server now time in my server"

MON DEC 4 01:01:45 EST 2017

as I know the time function must be same on all servers every where in the world

finally this the comparison between my server time and the others

1512407620

and other server in same moment

1512382397

答:
You neet to set your timezone.

```<code>date_default_timezone_set('Europe/Copenhagen');
$date = date('Y-m-d H:i:s');
</code>```

Here is a list of all the support timezones: http://php.net/manual/en/timezones.php

Title: php time returns wrong timestamp

Body:
You neet to set your timezone.

date_default_timezone_set('Europe/Copenhagen');
$date = date('Y-m-d H:i:s');

Here is a list of all the support timezones: http://php.net/manual/en/timezones.php


问:
Form error mapping on collection
I have a form:

```<code>class ArticleType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('autor', AutorType::class)
            ->add('categories', CollectionType::class, array(
                'entry_type' => CategoryType::class,
                'error_bubbling' => false,
            ))
            ->add('submit', SubmitType::class)
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => Article::class,
        ));
    }
}
</code>```

This embeds to a custom form. my Article entity looks like this:

```<code>class Article
{
    /**
     * @Assert\Type(type="AppBundle\Model\Autor")
     * @Assert\Valid()
     */
    private $autor;

    /**
     *
     * @Assert\All({
     *     @Assert\Type(type="AppBundle\Model\Category")
     * })
     * @Assert\Valid()
     */
    private $categories;
}
</code>```

My problem is  a category field error (category name not blank for example); the error is never mapped to the field itself.

With 'error_bubbling' => true,the error is map with ArticleType form.

With 'error_bubbling' => false, the error is map to the collection
CollectionType but never to the CategoryType form or name filed of CategoryType.

I am on Symfony 3.3 and can not use cascade_validation, I use @Assert\Valid() but it don't seem to work as I expected.

Where did I do wrong?

Thanks for your help.

答:
Try using Valid() as form constraint instead of class one. (Be sure to remove class Valid constraint)

Just encountered same thing and after like 20 combinations it was the solution for me. I'm on symfony 3.2 though.

```<code>use Symfony\Component\Validator\Constraints\Valid;

class ArticleType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('autor', AutorType::class)
            ->add('categories', CollectionType::class, array(
                'entry_type' => CategoryType::class,
                'error_bubbling' => false,
                'constraints' => [
                    new Valid(),
                ],
              ))
            ->add('submit', SubmitType::class)
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => Article::class,
        ));
    }
}
</code>```

Title: Form error mapping on collection

Body:
I have a form:

class ArticleType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('autor', AutorType::class)
            ->add('categories', CollectionType::class, array(
                'entry_type' => CategoryType::class,
                'error_bubbling' => false,
            ))
            ->add('submit', SubmitType::class)
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => Article::class,
        ));
    }
}

This embeds to a custom form. my Article entity looks like this:

class Article
{
    /**
     * @Assert\Type(type="AppBundle\Model\Autor")
     * @Assert\Valid()
     */
    private $autor;

    /**
     *
     * @Assert\All({
     *     @Assert\Type(type="AppBundle\Model\Category")
     * })
     * @Assert\Valid()
     */
    private $categories;
}

My problem is  a category field error (category name not blank for example); the error is never mapped to the field itself.

With 'error_bubbling' => true,the error is map with ArticleType form.

With 'error_bubbling' => false, the error is map to the collection
CollectionType but never to the CategoryType form or name filed of CategoryType.

I am on Symfony 3.3 and can not use cascade_validation, I use @Assert\Valid() but it don't seem to work as I expected.

Where did I do wrong?

Thanks for your help.

Body:
Try using Valid() as form constraint instead of class one. (Be sure to remove class Valid constraint)

Just encountered same thing and after like 20 combinations it was the solution for me. I'm on symfony 3.2 though.

use Symfony\Component\Validator\Constraints\Valid;

class ArticleType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('autor', AutorType::class)
            ->add('categories', CollectionType::class, array(
                'entry_type' => CategoryType::class,
                'error_bubbling' => false,
                'constraints' => [
                    new Valid(),
                ],
              ))
            ->add('submit', SubmitType::class)
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => Article::class,
        ));
    }
}


问:
duplicate record on sql left join
When I use this sql query, There is no duplicate shops.id:

```<code>SELECT *
FROM   shops
LEFT JOIN expiration
       ON shops.id = expiration.shopid
ORDER  BY shops.id
</code>```

But when I use this one (with where statement)  there are many duplicate shops.id:

```<code>SELECT *
FROM   shops
LEFT JOIN expiration
       ON shops.id = expiration.shopid
WHERE  shops.ref = 9
ORDER  BY shops.id
</code>```

Why left join returns duplicate rows and how adding where cause this?

答:
Looks like every one agree you already have duplicates on your first query but you just missed. Is easy to test</p>

```<code> SELECT 'shops', shops.id, COUNT(*)
 FROM shops
 GROUP BY shops.id
 HAVING COUNT(*) > 1

 UNION ALL

 SELECT 'expiration ', expiration.shopid , COUNT(*)
 FROM expiration
 GROUP BY expiration.shopid
 HAVING COUNT(*) > 1
</code>```

Title: duplicate record on sql left join

Body:
When I use this sql query, There is no duplicate shops.id:

SELECT *
FROM   shops
LEFT JOIN expiration
       ON shops.id = expiration.shopid
ORDER  BY shops.id

But when I use this one (with where statement)  there are many duplicate shops.id:

SELECT *
FROM   shops
LEFT JOIN expiration
       ON shops.id = expiration.shopid
WHERE  shops.ref = 9
ORDER  BY shops.id

Why left join returns duplicate rows and how adding where cause this?

Body:
Looks like every one agree you already have duplicates on your first query but you just missed. Is easy to test

 SELECT 'shops', shops.id, COUNT(*)
 FROM shops
 GROUP BY shops.id
 HAVING COUNT(*) > 1

 UNION ALL

 SELECT 'expiration ', expiration.shopid , COUNT(*)
 FROM expiration
 GROUP BY expiration.shopid
 HAVING COUNT(*) > 1


问:
Display output of command executed in bash as it is executing
I've got a line in my bash script like this:

```<code>echo "`some_command`"
</code>```

Now, some_command executes for around 1-2mins and it keeps printing alerts/messages in that interval.

Problem is when I execute my bash script, the script has no output for 1-2mins and then directly displays the output after complete execution of some_command.

How can I make my bash script output some_command as it is executing? Is there a way to do so?

答:
The command substitution is capturing everything your command writes to standard output, then displayed all at once by the echo command. Just run the command by itself. (And when you do want a command substitution, use $(...) instead of backticks.)

```<code>some_command  # not echo "$(some_command)"
</code>```

Body:
I've got a line in my bash script like this:

echo "`some_command`"

Now, some_command executes for around 1-2mins and it keeps printing alerts/messages in that interval.

Problem is when I execute my bash script, the script has no output for 1-2mins and then directly displays the output after complete execution of some_command.

How can I make my bash script output some_command as it is executing? Is there a way to do so?

Body:
The command substitution is capturing everything your command writes to standard output, then displayed all at once by the echo command. Just run the command by itself. (And when you do want a command substitution, use $(...) instead of backticks.)

some_command  # not echo "$(some_command)"


问:
jquery datatable : fetch next 25 rows from databse on next page button of jQuery datatable
I have huge number of data that I want to populate in jQuery datatable. I am using mysql database. Is it possible in angularJs to use jQuery datatable in such way that on first time only 25 records will be extracted and shown in datatable. On next or 2 button click next 25 records will be extracted and shown.

Below is my code for datatable in angular controller.

```<code>     $($scope.getDataPointDetails = function () {

         dataPointFactory.getDataPointDetails().then(
             function (response) {
                 for (var i = 0; i < response.data.length; i++)
                 {
                     dataPointData[i] = new Array(
                         '<i class="material-icons waves-effect" onclick="editDataPoint('+ i +');" data-toggle = "tooltip" data-placement = "left" title = "Edit">edit</i> \n\
                          <i class="material-icons waves-effect" onclick="DeleteDataPoint('+ i +');" data-toggle = "tooltip" data-placement = "left" title = "Delete">delete</i>',
                         response.data[i].companyName, //1
                         (response.data[i].addressLine1+', '+((response.data[i].addressLine1!==null)?response.data[i].addressLine1:'')+', '+response.data[i].city+'-'+response.data[i].pinCode), //2
                         response.data[i].state, //3
                         response.data[i].contactNos, //4
                         response.data[i].tollFreeNo, //5
                         response.data[i].compEmail, // 6
                         response.data[i].compWebsite, //7
                         response.data[i].level1, //8
                         response.data[i].level2, //9
                         response.data[i].level3, //10
                         response.data[i].remark1, //11
                         response.data[i].remark2, //12
                         response.data[i].remark3, //13
                         response.data[i].ptc1, //14
                         response.data[i].ptc2, //15
                         response.data[i].ptc3, //16
                         response.data[i].ptc4, //17
                         response.data[i].ptc5, //18
                         response.data[i].tallySrNo, //19
                         response.data[i].tallyProdType, //20
                         response.data[i].noOfUsers, //21
                         response.data[i].tallyDuration, //22
                         response.data[i].tallyStartDate, //23
                         response.data[i].tallyEndDate, //24
                         response.data[i].drn,//25
                         response.data[i].addressLine1,//26
                         response.data[i].addressLine2, //27
                         response.data[i].city, //28
                         response.data[i].pincode //29
                         );
                 }

                 $('#dataPointViewTable').dataTable({
                     "destroy": true,
                     "aaSorting": [],
                     "deferRender": true,
                     "responsive": true,
                     "aaData": dataPointData,
                     "bAutoWidth": false,
//                     "fixedColumns":   {
//                         leftColumns: 1,
//                         rightColumns: 1
//                     },
                     "processing": true,
                     "serverSide": true,
                     "aoColumns": [
                         {"sTitle": "Action", "sWidth": "5%"},
                         {"sTitle": "Company Name", "sWidth": "5%"},
                         {"sTitle": "Address", "sWidth": "15%"},
                         {"sTitle": "State", "sWidth": "8%"},
                         {"sTitle": "Contact Number", "sWidth": "10%"},
                         {"sTitle": "Toll Free Number", "sWidth": "10%"},
                         {"sTitle": "Email Address", "sWidth": "15%"},
                         {"sTitle": "Website", "sWidth": "15%"},
                         {"sTitle": "Level1", "sWidth": "15%"},
                         {"sTitle": "Level2", "sWidth": "15%"},
                         {"sTitle": "Level3", "sWidth": "15%"},
                         {"sTitle": "Remark1", "sWidth": "15%"},
                         {"sTitle": "Remark2", "sWidth": "15%"},
                         {"sTitle": "Remark3", "sWidth": "15%"},
                         {"sTitle": "Contact Person 1(Name, Designation, Email, Mobile No.)", "sWidth": "15%"},
                         {"sTitle": "Contact Person 2(Name, Designation, Email, Mobile No.)", "sWidth": "15%"},
                         {"sTitle": "Contact Person 3(Name, Designation, Email, Mobile No.)", "sWidth": "15%"},
                         {"sTitle": "Contact Person 4(Name, Designation, Email, Mobile No.)", "sWidth": "15%"},
                         {"sTitle": "Contact Person 5(Name, Designation, Email, Mobile No.)", "sWidth": "15%"},
                         {"sTitle": "Tally Serial No", "sWidth": "15%"},
                         {"sTitle": "Product Type", "sWidth": "15%"},
                         {"sTitle": "No of Users", "sWidth": "15%"},
                         {"sTitle": "Duration", "sWidth": "15%"},
                         {"sTitle": "TSS Purshase Date", "sWidth": "15%"},
                         {"sTitle": "TSS Expiry Date", "sWidth": "15%"}]
                 });

             });
     });
</code>```

I have added server side processing options to data table. I am getting response for $http which I am able to see in network but not in table and I am getting popup alert message for datatable as-
DataTables warning: table id=dataPointViewTable - Ajax error. For more information about this error, please see http://datatables.net/tn/7

答:
Enable server-side processing using serverSide option.

Write your own server-side script that will handle sorting, filtering and pagination on the server side. DataTables comes with ssp.class.php that helps with that if your language of choise is PHP.

Body:
I have huge number of data that I want to populate in jQuery datatable. I am using mysql database. Is it possible in angularJs to use jQuery datatable in such way that on first time only 25 records will be extracted and shown in datatable. On next or 2 button click next 25 records will be extracted and shown.

Below is my code for datatable in angular controller.

     $($scope.getDataPointDetails = function () {

         dataPointFactory.getDataPointDetails().then(
             function (response) {
                 for (var i = 0; i < response.data.length; i++)
                 {
                     dataPointData[i] = new Array(
                         'edit \n\
                          delete',
                         response.data[i].companyName, //1
                         (response.data[i].addressLine1+', '+((response.data[i].addressLine1!==null)?response.data[i].addressLine1:'')+', '+response.data[i].city+'-'+response.data[i].pinCode), //2
                         response.data[i].state, //3
                         response.data[i].contactNos, //4
                         response.data[i].tollFreeNo, //5
                         response.data[i].compEmail, // 6
                         response.data[i].compWebsite, //7
                         response.data[i].level1, //8
                         response.data[i].level2, //9
                         response.data[i].level3, //10
                         response.data[i].remark1, //11
                         response.data[i].remark2, //12
                         response.data[i].remark3, //13
                         response.data[i].ptc1, //14
                         response.data[i].ptc2, //15
                         response.data[i].ptc3, //16
                         response.data[i].ptc4, //17
                         response.data[i].ptc5, //18
                         response.data[i].tallySrNo, //19
                         response.data[i].tallyProdType, //20
                         response.data[i].noOfUsers, //21
                         response.data[i].tallyDuration, //22
                         response.data[i].tallyStartDate, //23
                         response.data[i].tallyEndDate, //24
                         response.data[i].drn,//25
                         response.data[i].addressLine1,//26
                         response.data[i].addressLine2, //27
                         response.data[i].city, //28
                         response.data[i].pincode //29
                         );
                 }

                 $('#dataPointViewTable').dataTable({
                     "destroy": true,
                     "aaSorting": [],
                     "deferRender": true,
                     "responsive": true,
                     "aaData": dataPointData,
                     "bAutoWidth": false,
//                     "fixedColumns":   {
//                         leftColumns: 1,
//                         rightColumns: 1
//                     },
                     "processing": true,
                     "serverSide": true,
                     "aoColumns": [
                         {"sTitle": "Action", "sWidth": "5%"},
                         {"sTitle": "Company Name", "sWidth": "5%"},
                         {"sTitle": "Address", "sWidth": "15%"},
                         {"sTitle": "State", "sWidth": "8%"},
                         {"sTitle": "Contact Number", "sWidth": "10%"},
                         {"sTitle": "Toll Free Number", "sWidth": "10%"},
                         {"sTitle": "Email Address", "sWidth": "15%"},
                         {"sTitle": "Website", "sWidth": "15%"},
                         {"sTitle": "Level1", "sWidth": "15%"},
                         {"sTitle": "Level2", "sWidth": "15%"},
                         {"sTitle": "Level3", "sWidth": "15%"},
                         {"sTitle": "Remark1", "sWidth": "15%"},
                         {"sTitle": "Remark2", "sWidth": "15%"},
                         {"sTitle": "Remark3", "sWidth": "15%"},
                         {"sTitle": "Contact Person 1(Name, Designation, Email, Mobile No.)", "sWidth": "15%"},
                         {"sTitle": "Contact Person 2(Name, Designation, Email, Mobile No.)", "sWidth": "15%"},
                         {"sTitle": "Contact Person 3(Name, Designation, Email, Mobile No.)", "sWidth": "15%"},
                         {"sTitle": "Contact Person 4(Name, Designation, Email, Mobile No.)", "sWidth": "15%"},
                         {"sTitle": "Contact Person 5(Name, Designation, Email, Mobile No.)", "sWidth": "15%"},
                         {"sTitle": "Tally Serial No", "sWidth": "15%"},
                         {"sTitle": "Product Type", "sWidth": "15%"},
                         {"sTitle": "No of Users", "sWidth": "15%"},
                         {"sTitle": "Duration", "sWidth": "15%"},
                         {"sTitle": "TSS Purshase Date", "sWidth": "15%"},
                         {"sTitle": "TSS Expiry Date", "sWidth": "15%"}]
                 });

             });
     });

I have added server side processing options to data table. I am getting response for $http which I am able to see in network but not in table and I am getting popup alert message for datatable as-
DataTables warning: table id=dataPointViewTable - Ajax error. For more information about this error, please see http://datatables.net/tn/7


问:
Dynamically Enable / Disable different adjacent element in HTML using CSS

In attached image. By default create button and password inputs will be in disabled state. once verified with email address create button got enabled. based on this button I need to enable those two inputs only using CSS.

This is third party login integration so they restricted JS and other technology. It should be achieved using CSS only.

```<code><div class="section1">
  <ul>
    <li>
      <label>Email Address</label>
      <input id="email">
      <button type="submit">Send verification code</button>
    </li>
    <li>
      <label>New Password</label>
      <input id="pwd" disabled>
    </li>
    <li>
      <label>Confirm Password</label>
      <input id="cnfpwd" disabled>
    </li>
  </ul>
</div>
<div class="section2">
  <button type="submit" **id="create"** disabled>create</button>
  <button type="submit">cancel</button>
</div>

<!-- CSS -->
label{
  width:100%;
  display:block;
}
input{
  display:block;
}
</code>```

Based on section2 button I need to enable section1 inputs using css

答:
based on this button I need to enable those two inputs only using CSS.

Absolutely impossible.

First of all, CSS can not select “upwards” in the DOM,

and secondly, CSS can not change the disabled state of an element to begin with.

Body:
In attached image. By default create button and password inputs will be in disabled state. once verified with email address create button got enabled. based on this button I need to enable those two inputs only using CSS.

This is third party login integration so they restricted JS and other technology. It should be achieved using CSS only.

      Email Address
      <input id="email">
      <button type="submit">Send verification code</button>

      New Password
      <input id="pwd" disabled>

      Confirm Password
      <input id="cnfpwd" disabled>

  <button type="submit" **id="create"** disabled>create</button>
  <button type="submit">cancel</button>

label{
  width:100%;
  display:block;
}
input{
  display:block;
}

Based on section2 button I need to enable section1 inputs using css


问:
How to slice different verb tenses word ending with -ed,-ing in a list?

So here is the sample list:

[work,worked,working,play,works,lotus]

I want to slice the -ed,-ing,-s form of work,the result should be like this:
 [work,play,lotus]

So,how can i achieve that with pure python code since the NLTK approach seemed to be inaccurate?

答:
In python, you can use filter to remove values which ends with ing or ed.

```<code>your_list = ['work', 'worked', 'working', 'play']
print filter(lambda i: not i.endswith(('ing', 'ed')), your_list)
</code>```

it returns a list.

```<code>['work', 'play']
</code>```

Body:
In python, you can use filter to remove values which ends with ing or ed.

your_list = ['work', 'worked', 'working', 'play']
print filter(lambda i: not i.endswith(('ing', 'ed')), your_list)

it returns a list.

['work', 'play']


问:
Improve speed execution of MySQL select query
I have 2 MySQL tables with several millions of rows and I'm trying to perform a query selection for get specific data column from both tables. Despite my first good expectations the execution of the query selection takes several seconds (around 5 seconds) also with an index applied on the WHERE condition.

Create statement for the 2 MySQL tables:

```<code>CREATE TABLE `T1` (
  `T1_id` int(15) NOT NULL AUTO_INCREMENT,
  `T1_val1` varchar(45) NOT NULL,
  `T1_val2` varchar(45) NOT NULL,
  `T1_val3` bigint(11) NOT NULL,
  `T1_val4` datetime NOT NULL,
  `T1_val5` varchar(100) NOT NULL,
  `T1_val6` float NOT NULL,
  `T1_val7` datetime NOT NULL,
  `T1_val8` varchar(100) NOT NULL,
  `T1_val9` varchar(100) NOT NULL,
  `T1_val10` varchar(100) NOT NULL,
  PRIMARY KEY (`T1_id`),
  KEY `T1_val4` (`T1_val4`)
) ENGINE=InnoDB AUTO_INCREMENT=53885653 DEFAULT CHARSET=latin1;

CREATE TABLE `T2` (
  `T2_id` int(11) NOT NULL,
  `T2_val1` float NOT NULL,
  `T2_val2` float NOT NULL,
  `T2_val3` varchar(45) NOT NULL,
  PRIMARY KEY (`T2_id`),
  KEY `T2_val3` (`T2_val3`),
  KEY `T2_val1_2` (`T2_val1`,`T2_val2`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
</code>```

As you can see both tables have an AI primary key and foreign key that matches as one-to-one relationship between them (T1_id and T2_id). And we have an index applied on T1 for T1_val4 that is in a datetime format.

The selection query

```<code>SELECT
      T1_val5,
      T2_val1,
      T2_val2,
      T2_val3,
      T1_val9,
      count(T2_val1) as cnt,
      T1_val4
   FROM
      T1 USE INDEX (T1_val4)
         INNER JOIN T2
            ON T1.T1_id = T2.T2_id
   WHERE
      T1_val4 BETWEEN '2016-02-18 15:00:00'
                  AND '2016-02-18 16:59:59'
   GROUP BY
      T2_val1,
      T2_val2,
      T2_val3,
      T1_val9,
      T1_val5
   order by
      T1_val4 ASC;
</code>```

As you can notice, I have specified a HINT for the index in order to tell to MySQL to use that specific index for the datetime column. Actually if I extend the datetime range in the WHERE condition to several hours well.. for example BETWEEN '2016-02-18 15:00:00' AND '2016-02-18 23:59:59' the execution time grows up till 50/100 seconds. Probably I'm missing something in the logic.

The EXPLAIN output

```<code>+-------+---------------+-----------+-----------+-------------------+-----------+---------------+-----------+-----------+------------------------------------------------------------+
|   ID  |   SELECT_TYPE |   TABLE   |   TYPE    |   POSSIBLE_KEYS   |   KEY     |   KEY_LEN     |   REF     |   ROWS    |       EXTRA                                                |
+-------+---------------+-----------+-----------+-------------------+-----------+---------------+-----------+-----------+------------------------------------------------------------+
|   1   |   SIMPLE      |   T1      |   range   |   T1_val4         |   T1_val4 |      5        |   NULL    |   10670   |   "Using index condition; Using temporary; Using filesort" |
+-------+---------------+-----------+-----------+-------------------+-----------+---------------+-----------+-----------+------------------------------------------------------------+
|   1   |   SIMPLE      |   T2      |   eq_ref  |   PRIMARY         |   PRIMARY |      4        |   T1_id   |   1       |     NULL                                                   |
+-------+---------------+-----------+-----------+-------------------+-----------+---------------+-----------+-----------+------------------------------------------------------------+
</code>```

The EXPLAIN output updated with compound index

(As suggested from @O. Jones)

```<code>+-------+---------------+-----------+-----------+------------------------------+-----------+---------------+-----------+-----------+---------------------------------------------------------------+
|   ID  |   SELECT_TYPE |   TABLE   |   TYPE    |   POSSIBLE_KEYS              |   KEY     |   KEY_LEN     |   REF     |   ROWS    |       EXTRA                                                   |
+-------+---------------+-----------+-----------+------------------------------+-----------+---------------+-----------+-----------+---------------------------------------------------------------+
|   1   |   SIMPLE      |   T1      |   range   |   "PRIMARY,ix_rlf"           |   ix_rlf  |      5        |   NULL    |   10906   |   "Using where; Using index; Using temporary; Using filesort" |
+-------+---------------+-----------+-----------+------------------------------+-----------+---------------+-----------+-----------+---------------------------------------------------------------+
|   1   |   SIMPLE      |   T2      |   eq_ref  |   "PRIMARY,ix_cc"            |   PRIMARY |      4        |   T1_id   |   1       |     NULL                                                      |
+-------+---------------+-----------+-----------+------------------------------+-----------+---------------+-----------+-----------+---------------------------------------------------------------+
</code>```

ix_rlf is the compound index of T1_val4, T1_val9, T1_val5and ix_cc is the compound index suggested from @Tom Shir for T2 made of T2_id, T2_val1, T2_val2, T2_val3.

Query execution plan visual schema

(considering 2 HOURS as interval, and in this case the result of the query it's around 6632 rows and 6/7 seconds as execution time)

答:
This is your query with table prefixes:

```<code>SELECT
        T1.T1_val5,
        T2.T2_val1,
        T2.T2_val2,
        T2.T2_val3,
        T1.T1_val9,
        COUNT(T2.T2_val1) AS cnt,
        T1.T1_val4
    FROM
        T1
    INNER JOIN
        T2.T2
            ON T1.T1_id = T2.T2_id
    WHERE
        T1.T1_val4 BETWEEN '2016-02-18 15:00:00' AND '2016-02-18 16:59:59'
    GROUP BY
        T2.T2_val1,
        T2.T2_val2,
        T2.T2_val3,
        T1.T1_val9,
        T1.T1_val5
    ORDER BY
        T1.T1_val4 ASC
</code>```

I believe you can improve its performance by using the correct indexes.
I ran your query through an SQL query optimizer I'm using for my own queries, which recommended to use these indexes:

```<code>ALTER TABLE `T1` ADD INDEX `T1_index_1` (`T1_id`, `T1_val4`);
ALTER TABLE `T2` ADD INDEX `T2_index_1` (`T2_id`, `T2_val1`, `T2_val2`, `T2_val3`);
</code>```

Also, please post the explain plan, as it can help better understand which indexes are currently used by MySQL.

Another recommendation - remove the hint you added. Usually, MySQL will know how to optimize the query better than we do.

Body:
I have 2 MySQL tables with several millions of rows and I'm trying to perform a query selection for get specific data column from both tables. Despite my first good expectations the execution of the query selection takes several seconds (around 5 seconds) also with an index applied on the WHERE condition.

Create statement for the 2 MySQL tables:

CREATE TABLE `T1` (
  `T1_id` int(15) NOT NULL AUTO_INCREMENT,
  `T1_val1` varchar(45) NOT NULL,
  `T1_val2` varchar(45) NOT NULL,
  `T1_val3` bigint(11) NOT NULL,
  `T1_val4` datetime NOT NULL,
  `T1_val5` varchar(100) NOT NULL,
  `T1_val6` float NOT NULL,
  `T1_val7` datetime NOT NULL,
  `T1_val8` varchar(100) NOT NULL,
  `T1_val9` varchar(100) NOT NULL,
  `T1_val10` varchar(100) NOT NULL,
  PRIMARY KEY (`T1_id`),
  KEY `T1_val4` (`T1_val4`)
) ENGINE=InnoDB AUTO_INCREMENT=53885653 DEFAULT CHARSET=latin1;

CREATE TABLE `T2` (
  `T2_id` int(11) NOT NULL,
  `T2_val1` float NOT NULL,
  `T2_val2` float NOT NULL,
  `T2_val3` varchar(45) NOT NULL,
  PRIMARY KEY (`T2_id`),
  KEY `T2_val3` (`T2_val3`),
  KEY `T2_val1_2` (`T2_val1`,`T2_val2`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

As you can see both tables have an AI primary key and foreign key that matches as one-to-one relationship between them (T1_id and T2_id). And we have an index applied on T1 for T1_val4 that is in a datetime format.

The selection query

SELECT
      T1_val5,
      T2_val1,
      T2_val2,
      T2_val3,
      T1_val9,
      count(T2_val1) as cnt,
      T1_val4
   FROM
      T1 USE INDEX (T1_val4)
         INNER JOIN T2
            ON T1.T1_id = T2.T2_id
   WHERE
      T1_val4 BETWEEN '2016-02-18 15:00:00'
                  AND '2016-02-18 16:59:59'
   GROUP BY
      T2_val1,
      T2_val2,
      T2_val3,
      T1_val9,
      T1_val5
   order by
      T1_val4 ASC;

As you can notice, I have specified a HINT for the index in order to tell to MySQL to use that specific index for the datetime column. Actually if I extend the datetime range in the WHERE condition to several hours well.. for example BETWEEN '2016-02-18 15:00:00' AND '2016-02-18 23:59:59' the execution time grows up till 50/100 seconds. Probably I'm missing something in the logic.

The EXPLAIN output

+-------+---------------+-----------+-----------+-------------------+-----------+---------------+-----------+-----------+------------------------------------------------------------+
|   ID  |   SELECT_TYPE |   TABLE   |   TYPE    |   POSSIBLE_KEYS   |   KEY     |   KEY_LEN     |   REF     |   ROWS    |       EXTRA                                                |
+-------+---------------+-----------+-----------+-------------------+-----------+---------------+-----------+-----------+------------------------------------------------------------+
|   1   |   SIMPLE      |   T1      |   range   |   T1_val4         |   T1_val4 |      5        |   NULL    |   10670   |   "Using index condition; Using temporary; Using filesort" |
+-------+---------------+-----------+-----------+-------------------+-----------+---------------+-----------+-----------+------------------------------------------------------------+
|   1   |   SIMPLE      |   T2      |   eq_ref  |   PRIMARY         |   PRIMARY |      4        |   T1_id   |   1       |     NULL                                                   |
+-------+---------------+-----------+-----------+-------------------+-----------+---------------+-----------+-----------+------------------------------------------------------------+

The EXPLAIN output updated with compound index

(As suggested from @O. Jones)

+-------+---------------+-----------+-----------+------------------------------+-----------+---------------+-----------+-----------+---------------------------------------------------------------+
|   ID  |   SELECT_TYPE |   TABLE   |   TYPE    |   POSSIBLE_KEYS              |   KEY     |   KEY_LEN     |   REF     |   ROWS    |       EXTRA                                                   |
+-------+---------------+-----------+-----------+------------------------------+-----------+---------------+-----------+-----------+---------------------------------------------------------------+
|   1   |   SIMPLE      |   T1      |   range   |   "PRIMARY,ix_rlf"           |   ix_rlf  |      5        |   NULL    |   10906   |   "Using where; Using index; Using temporary; Using filesort" |
+-------+---------------+-----------+-----------+------------------------------+-----------+---------------+-----------+-----------+---------------------------------------------------------------+
|   1   |   SIMPLE      |   T2      |   eq_ref  |   "PRIMARY,ix_cc"            |   PRIMARY |      4        |   T1_id   |   1       |     NULL                                                      |
+-------+---------------+-----------+-----------+------------------------------+-----------+---------------+-----------+-----------+---------------------------------------------------------------+

ix_rlf is the compound index of T1_val4, T1_val9, T1_val5and ix_cc is the compound index suggested from @Tom Shir for T2 made of T2_id, T2_val1, T2_val2, T2_val3.

Query execution plan visual schema

(considering 2 HOURS as interval, and in this case the result of the query it's around 6632 rows and 6/7 seconds as execution time)

Body:
This is your query with table prefixes:

SELECT
        T1.T1_val5,
        T2.T2_val1,
        T2.T2_val2,
        T2.T2_val3,
        T1.T1_val9,
        COUNT(T2.T2_val1) AS cnt,
        T1.T1_val4
    FROM
        T1
    INNER JOIN
        T2.T2
            ON T1.T1_id = T2.T2_id
    WHERE
        T1.T1_val4 BETWEEN '2016-02-18 15:00:00' AND '2016-02-18 16:59:59'
    GROUP BY
        T2.T2_val1,
        T2.T2_val2,
        T2.T2_val3,
        T1.T1_val9,
        T1.T1_val5
    ORDER BY
        T1.T1_val4 ASC

I believe you can improve its performance by using the correct indexes.
I ran your query through an SQL query optimizer I'm using for my own queries, which recommended to use these indexes:

ALTER TABLE `T1` ADD INDEX `T1_index_1` (`T1_id`, `T1_val4`);
ALTER TABLE `T2` ADD INDEX `T2_index_1` (`T2_id`, `T2_val1`, `T2_val2`, `T2_val3`);

Also, please post the explain plan, as it can help better understand which indexes are currently used by MySQL.

Another recommendation - remove the hint you added. Usually, MySQL will know how to optimize the query better than we do.


问:
Javascript document write
How do I get this javascript to populate the textarea?

```<code><body onload="form1.submit();"><div align="center">Loading...</div>
<script type="text/javascript" src="<%= g_page_site_actual %>/js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="<%= g_page_site_actual %>/js/jquery.wordstats.js"></script> <!-- core code -->
<script type="text/javascript" src="<%= g_page_site_actual %>/js/jquery.wordstats.en.js"></script> <!-- English stop words -->
<script type="text/javascript">
        $(function() {
            var count = 20;
            $.extend($.wordStats.stopWords, {'retrieved': true, '2007': true});
            $.wordStats.computeTopWords(count);
            var msgcounttext1 = '<%=completehtml%>'
            for(var i = 0, j = $.wordStats.topWords.length; i < j && i <= count; i++) {
               msg += $.wordStats.topWords[i].substring(1) + ', ';
            }
            {
            document.form1.textarea.value = document.write(msgcounttext);
            }
            $.wordStats.clear();
        });
        </script>
<div id="content" class="hidden"><%=completehtml%>
    <form id="form1" name="form1" method="post" action="test.asp">
        <textarea name="textarea" id="textarea" cols="45" rows="5"></textarea>
    </form>
  </div>
</body>
</code>```

Thanks

答:
Sample of a JQuery function to do that...</p>

```<code>$('a').click(function()
{
   $('#textarea').val('Insert this into the Text Area');
   //this puts the 'Insert this..' into the text area with the id 'textarea'
})
</code>```

Title: Javascript document write

Body:
How do I get this javascript to populate the textarea?

Loading...

<%=completehtml%>
    <form id="form1" name="form1" method="post" action="test.asp">
        <textarea name="textarea" id="textarea" cols="45" rows="5"></textarea>
    </form>

Thanks

Body:
Sample of a JQuery function to do that...

$('a').click(function()
{
   $('#textarea').val('Insert this into the Text Area');
   //this puts the 'Insert this..' into the text area with the id 'textarea'
})


问:
Save UIView to a transparent PNG
I have a UIView and I want it to be stored as a transparent PNG, i.e. without the UIVIew background color...

I am currently using this code and it's working OK but with the background color :(

```<code>UIGraphicsBeginImageContext(self.bounds.size);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage* image1 = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *imageData = UIImagePNGRepresentation(image1);
[imageData writeToFile:filePath atomically:YES];
</code>```

So does anyone have any idea about getting this image as a transparent one?

Thank you in advance..

答:
For Objective-c you have to set opaque = NO

```<code> + (UIImage *) imageWithView:(UIView *)view
    {
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, [[UIScreen mainScreen] scale]);
        [view.layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return img;
    }
</code>```

For Swift you have to set opaque = false

```<code>func imageWithView(inView: UIView) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(inView.bounds.size, false, 0.0)
        if let context = UIGraphicsGetCurrentContext() {
            inView.layer.render(in: context)
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return image
        }
        return nil
    }
</code>```

Title: Save UIView to a transparent PNG

Body:
I have a UIView and I want it to be stored as a transparent PNG, i.e. without the UIVIew background color...

I am currently using this code and it's working OK but with the background color :(

UIGraphicsBeginImageContext(self.bounds.size);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage* image1 = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *imageData = UIImagePNGRepresentation(image1);
[imageData writeToFile:filePath atomically:YES];

So does anyone have any idea about getting this image as a transparent one?

Thank you in advance..

Body:
For Objective-c you have to set opaque = NO

 + (UIImage *) imageWithView:(UIView *)view
    {
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, [[UIScreen mainScreen] scale]);
        [view.layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return img;
    }

For Swift you have to set opaque = false

func imageWithView(inView: UIView) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(inView.bounds.size, false, 0.0)
        if let context = UIGraphicsGetCurrentContext() {
            inView.layer.render(in: context)
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return image
        }
        return nil
    }


问:
AngularJS pass string to function by ng-click
I am trying to pass a string to a function through ng click, here's an example

HTML

 ng-click="test(STRING_TO_PASS)"

Controller

$scope.test = function(stringOne, stringTwo){
    valueOne = test(STRING_TO_PASS);
}

Edit -

Turns out I was thinking about this the wrong way... not really sure why I asked it, sorry guys!

答:
Correct HTML for ng-click to be used as an attribute is as

```<code><a class="btn" ng-click="test('STRING_TO_PASS')"> Click</a>
</code>```

Also, the test function would accept one parameter in your controller.

var app = angular.module("app", []).controller("ctrl", function($scope) {
$scope.test = function(stringOne) {
    valueOne = stringOne;
    console.log(valueOne);
  };
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app" ng-controller="ctrl">
   Click
</body></code>```

Body:
Correct HTML for ng-click to be used as an attribute is as

<a class="btn" ng-click="test('STRING_TO_PASS')"> Click</a>

Also, the test function would accept one parameter in your controller.

var app = angular.module("app", []).controller("ctrl", function($scope) {
$scope.test = function(stringOne) {
    valueOne = stringOne;
    console.log(valueOne);
  };
})

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app" ng-controller="ctrl">
  <a class="btn" ng-click="test('STRING_TO_PASS')"> Click</a>
</body>


问:
how to display pop up only 1 time in 1 day using javascript
i have a code like this. i want to showing that pop up only 1 time in 1 day.

```<code><script type="text/javascript">
    var popup = function() {
        window.open ("http://example.com", "Window","status=1,toolbar=1");
    }
</script>
<body onclick="popup()">    </body>
</code>```

that code will open pop up when i click anywhere on the page but it will always pop up a window everytime i click, so i want to make that pop up only showing 1 time in 1 day.

答: You could use localStorage or cookies to store the time when the popup was last shown. If the difference between the current time and the last time is greater than 24 hours, you will render the popup.</p>

Body:
i have a code like this. i want to showing that pop up only 1 time in 1 day.

that code will open pop up when i click anywhere on the page but it will always pop up a window everytime i click, so i want to make that pop up only showing 1 time in 1 day.


问:
Jenkins mergeDebugResources FAILED - no access to files
I would like to run espresso tests on jenkins. I did configuration like here
https://www.perfectomobile.com/solutions/devtunnel/espresso-in-continuous-integration

I got error like below

```<code>C:\Windows\System32\config\systemprofile\.gradle\caches\transforms-1\files-
1.1\design-26.1.0.aar\a1a21cd8aba52bd546711d26a970dfcb\res\drawable-
v21\avd_hide_password.xml: error: file not found.

Error: java.util.concurrent.ExecutionException:
com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
:app:mergeDebugResources FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:mergeDebugResources'.
> Error: java.util.concurrent.ExecutionException:
com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --
debug option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED in 9s
10 actionable tasks: 9 executed, 1 up-to-date
Build step 'Invoke Gradle script' changed build result to FAILURE
Build step 'Invoke Gradle script' marked build as failure
Finished: FAILURE
</code>```

Any sugestions what can be wrong?

答:
This is happening because AAPT2 still has issues with long paths on windows (only supports paths up to 145 characters or so for now, sadly). This file path is around 170, so it's over that limit.

The issue should be fixed soon, in the meantime you can move your cache directory closer to the C: root.

Body:
I would like to run espresso tests on jenkins. I did configuration like here
https://www.perfectomobile.com/solutions/devtunnel/espresso-in-continuous-integration

I got error like below

C:\Windows\System32\config\systemprofile\.gradle\caches\transforms-1\files-
1.1\design-26.1.0.aar\a1a21cd8aba52bd546711d26a970dfcb\res\drawable-
v21\avd_hide_password.xml: error: file not found.

Error: java.util.concurrent.ExecutionException:
com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
:app:mergeDebugResources FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:mergeDebugResources'.
> Error: java.util.concurrent.ExecutionException:
com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --
debug option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED in 9s
10 actionable tasks: 9 executed, 1 up-to-date
Build step 'Invoke Gradle script' changed build result to FAILURE
Build step 'Invoke Gradle script' marked build as failure
Finished: FAILURE

Any sugestions what can be wrong?


问:
how to show json data in jquery datatable
This is my jquery datatable ajax request... in success im getting the json data but in datatable its not showing ..its showing only loading..

```<code><script type="text/javascript">
function inituserdatatable() {

  alert("in");
  try {
    $('#userdetailDatatable').DataTable({

      "processing": true,
      "serverSide": true,

      "ajax": {
        "url": "ps/getUserDetails",
        "type": "post",
        "datatype": "json",
        "success": function(data) {

        },

      },

      "columns": [{
          'data': 'name'
        },
        {
          'data': 'email_id'
        },
        {
          'data': 'user_name'
        },
        {
          'data': 'password'
        }
      ],
      dom: 'Bfrtip',
    });
  } catch (exp) {
    alert(exp);
  }
}
</script>
</code>```

This is my json data from postgresql

```<code>{
  "data": [{
    "id": 12,
    "name": "",
    "email_id": "",
    "user_name": "",
    "password": ""
  }, {
    "id": 13,
    "name": "Ss",
    "email_id": "sd",
    "user_name": "g",
    "password": "g"
  }]
}
</code>```

答: Remove the following processing and serverSide options, they are not needed based on your data format.

Body:
This is my jquery datatable ajax request... in success im getting the json data but in datatable its not showing ..its showing only loading..

This is my json data from postgresql

{
  "data": [{
    "id": 12,
    "name": "",
    "email_id": "",
    "user_name": "",
    "password": ""
  }, {
    "id": 13,
    "name": "Ss",
    "email_id": "sd",
    "user_name": "g",
    "password": "g"
  }]
}


问:
TCP - How to play a java game between two players on localhost server
I have made a game named Two Dice Pig in java. The game has a simple GUI interface showing two dice faces as well as both players scores and names. The game starts with the simple dialog message asking for both players' name and the game starts. Both players interact with only one GUI interface and play as their turn come.  The game is completely coded. Now, what I want is to make a server (For now I want to try it on my local server) and both players should get their own GUI. And when a player A is playing, player B should not be able to do anything with the interface. I hope it clears. It's my networking project, but I don't have any idea how to do that. Any help would be greatly appreciated.

Note: I want to apply the same idea as this man applied. Just watch only for 15 seconds. Thanks!,

答:
You should start googling "Rest Services with Java" or something like this.

You need some central component, that manages the game state of your two android game sessions. For example you have a url like localhost://myService/Dice where you
 would POST a new dice throw. If somebody else makes a GET to that ressource, he would be able to retrieve the thrown dice you have posted during the game.
If you do not want the player to be able to interact, you could forbid a player to POST a new Dice when he is not able to do that and the GUI should reflect that somehow. Maybe disable buttons after you posted a Dice or something like that.

There is much more to it, but this should get you started somehow.

https://docs.oracle.com/javaee/6/tutorial/doc/gilik.html

the important code part from the url above would be the hello world like this:

```<code>package com.sun.jersey.samples.helloworld.resources;

import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.Path;

// The Java class will be hosted at the URI path "/helloworld"
@Path("/helloworld")
public class HelloWorldResource {

    // The Java method will process HTTP GET requests
    @GET
    // The Java method will produce content identified by the MIME Media
    // type "text/plain"
    @Produces("text/plain")
    public String getClichedMessage() {
        // Return some cliched textual content
        return "Hello World";
    }
}
</code>```

Body:
You should start googling "Rest Services with Java" or something like this.

You need some central component, that manages the game state of your two android game sessions. For example you have a url like localhost://myService/Dice where you
 would POST a new dice throw. If somebody else makes a GET to that ressource, he would be able to retrieve the thrown dice you have posted during the game.
If you do not want the player to be able to interact, you could forbid a player to POST a new Dice when he is not able to do that and the GUI should reflect that somehow. Maybe disable buttons after you posted a Dice or something like that.

There is much more to it, but this should get you started somehow.

https://docs.oracle.com/javaee/6/tutorial/doc/gilik.html

the important code part from the url above would be the hello world like this:

package com.sun.jersey.samples.helloworld.resources;

import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.Path;

// The Java class will be hosted at the URI path "/helloworld"
@Path("/helloworld")
public class HelloWorldResource {

    // The Java method will process HTTP GET requests
    @GET
    // The Java method will produce content identified by the MIME Media
    // type "text/plain"
    @Produces("text/plain")
    public String getClichedMessage() {
        // Return some cliched textual content
        return "Hello World";
    }
}


问:
Initial Token is cassandra is not working as expected
To understand the ring without vNodes, I tried initial token in Node 1 as 25 and Node 2 as 50 like below,

```<code>Address       Rack        Status State   Load            Owns                Token
                                                                             50
172.30.56.60  rack1       Up     Normal  82.08 KiB       100.00%             25
172.30.56.61  rack1       Up     Normal  82.09 KiB       100.00%             50
</code>```

I expect only the partition ranges between 0 to 50 should be added in database, But It is allowing any primary key / partition key value I provide as follows (user_id - primary / partition key).

```<code> user_id    | user_name | user_phone
------------+-----------+------------
  999933333 |       ram | 9003934069
        111 |       ram | 9003934069
          1 |       ram | 9003934069
  111333333 |       ram | 9003934069
 1113333333 |       ram | 9003934069
</code>```

where, user_id is the primary / partition key.

Does it mean that token provided in initial_token is the total number of tokens and not the partition range? If so how the partition range is calculated?

Thanks,
Harry

答:
The token number is a hash of the partition key. This decides where the data should be stored.

(ref: https://www.datastax.com/dev/blog/repair-in-cassandra):

In this picture N0 is assigned token 0, N1 token 10 and so on. By doing this we say N1 is responsible for token ranges 1-10. However if we use RF 3 then we say N1 is responsible for token ranges 81-10 instead. What you have done in your example is saying 60 owns 51-25. Since there is still a total of 2^127 tokens (depending on your partitioner) that means it now owns a huge amount of data compared to 61.

Body:
To understand the ring without vNodes, I tried initial token in Node 1 as 25 and Node 2 as 50 like below,

Address       Rack        Status State   Load            Owns                Token
                                                                             50
172.30.56.60  rack1       Up     Normal  82.08 KiB       100.00%             25
172.30.56.61  rack1       Up     Normal  82.09 KiB       100.00%             50

I expect only the partition ranges between 0 to 50 should be added in database, But It is allowing any primary key / partition key value I provide as follows (user_id - primary / partition key).

 user_id    | user_name | user_phone
------------+-----------+------------
  999933333 |       ram | 9003934069
        111 |       ram | 9003934069
          1 |       ram | 9003934069
  111333333 |       ram | 9003934069
 1113333333 |       ram | 9003934069

where, user_id is the primary / partition key.

Does it mean that token provided in initial_token is the total number of tokens and not the partition range? If so how the partition range is calculated?

Thanks,
Harry


问:
View is not getting updated (MVVM) but property associated is getting updated correctly
I am very new to WPF and working on MVVM, I have a scenario where my datagrid is not getting updated but the property to which it is bound is getting updated correctly, I am able to see new changes in the SlotFloorData property during PropertyChanged event.

below is XAML code (grid.row is bind to property SlotFloorData):

```<code><Page x:Class="CasinoCAD.V6.Views.DashboardView"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:vm="clr-namespace:CasinoCAD.V6.ViewModels"
      mc:Ignorable="d"
      d:DesignHeight="300" d:DesignWidth="300"
    Title="DashboardView">

    <Page.DataContext>
        <vm:CasinoCADDViewModel x:Name="viewModel"/>
    </Page.DataContext>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="200"/>
            <RowDefinition Height="200"/>
        </Grid.RowDefinitions>
        <TextBlock Grid.Row="0"  Text="Dashboard View" />

        <DataGrid Grid.Row="1" Name="grdDB" ItemsSource="{Binding Path=SlotFloorData}"  />

        <!--<DataGrid Grid.Row="2" ItemsSource="{Binding Path=Properties }" />-->
   </Grid>
</Page>
</code>```

I am implementing INotifyPropertyChanged in main model i.e. in CasinoCADDViewModel

and in DashboardView, I have only below (I tried INotifyPropertyChanged here too but it did not work):

Please let me know if I need to put any other information here

TIA!

答:
CollectionChanged

I assume that you change the contents of the SlotFloorData-enumeration and that you expect to see the changes (adding and removing items). Right? If yes, the enumeration must implement some change-notification system for collectons. Try using an ObservableCollection<T>. It has is such notification built in. You also can build your on by implementing INotifyCollectionChanged.

PropertyChanged

If you change the items itselfs and want to see the changes, your items must implement INotifyPropertyChanged or the properties of the items must be DependencyProperties.

ItemsSource Reference Changed

And last there is the case where you really change the ItemsSource. This may be that you have a collection without change-notification and you add or remove items. The you set the ItemsSource to null and then reset the ItemsSource to the ancient collection. This is not nice, but will work. However if you only set the ItemsSource to the same reference without setting it to null before, the contents will not be changed because the property system sees that it is the same reference and does nothing.

I hope, that one of the above statements will lead you to the solution.

Body:
I am very new to WPF and working on MVVM, I have a scenario where my datagrid is not getting updated but the property to which it is bound is getting updated correctly, I am able to see new changes in the SlotFloorData property during PropertyChanged event.

below is XAML code (grid.row is bind to property SlotFloorData):

<Page x:Class="CasinoCAD.V6.Views.DashboardView"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:vm="clr-namespace:CasinoCAD.V6.ViewModels"
      mc:Ignorable="d"
      d:DesignHeight="300" d:DesignWidth="300"
    Title="DashboardView">

    <Page.DataContext>
        <vm:CasinoCADDViewModel x:Name="viewModel"/>
    </Page.DataContext>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="200"/>
            <RowDefinition Height="200"/>
        </Grid.RowDefinitions>
        <TextBlock Grid.Row="0"  Text="Dashboard View" />

        <DataGrid Grid.Row="1" Name="grdDB" ItemsSource="{Binding Path=SlotFloorData}"  />

   </Grid>
</Page>

I am implementing INotifyPropertyChanged in main model i.e. in CasinoCADDViewModel

and in DashboardView, I have only below (I tried INotifyPropertyChanged here too but it did not work):

Please let me know if I need to put any other information here

TIA!


问:
Include attachment where the name matches recipient name
I have code in Excel which sends email to a list of recipients:

```<code>Sub SendEMail()
    Dim xEmail As String
    Dim xSubj As String
    Dim xMsg As String
    Dim xURL As String
    Dim i As Integer
    Dim k As Double
    Dim xCell As Range
    Dim xRg As Range
    Dim xTxt As String
    On Error Resume Next
    xTxt = ActiveWindow.RangeSelection.Address
    Set xRg = Application.InputBox("Please select the data range:", "Send emails to:", xTxt, , , , , 8)
    If xRg Is Nothing Then Exit Sub
    If xRg.Columns.Count <> 3 Then
        MsgBox "Incorrect number of columns: You have to choose Name, Email address, Account no.!"
        Exit Sub
    End If
    For i = 1 To xRg.Rows.Count
    '   Get the email address
        xEmail = xRg.Cells(i, 2)
    '   Message subject
        xSubj = "Your customer's account is on hold"
    '   Compose the message
        xMsg = ""
        xMsg = xMsg & "Dear client" & "," & vbCrLf & vbCrLf
        xMsg = xMsg & "We would like to inform you, that Your account has been put on hold - "
        xMsg = xMsg & xRg.Cells(i, 3).Text & "." & vbCrLf & vbCrLf
        xMsg = xMsg & "If you have any queries, please contact us on uk.ar@bodycote.com." & vbCrLf & vbCrLf
        xMsg = xMsg & "Kind regards," & vbCrLf
        xMsg = xMsg & "Jon and Martina"
    '   Replace spaces with %20 (hex)
        xSubj = Application.WorksheetFunction.Substitute(xSubj, " ", "%20")
        xMsg = Application.WorksheetFunction.Substitute(xMsg, " ", "%20")
    '   Replace carriage returns with %0D%0A (hex)
        xMsg = Application.WorksheetFunction.Substitute(xMsg, vbCrLf, "%0D%0A")
    '   Create the URL
        xURL = "mailto:" & xEmail & "?subject=" & xSubj & "&body=" & xMsg
    '   Execute the URL (start the email client)
        ShellExecute 0&, vbNullString, xURL, vbNullString, vbNullString, vbNormalFocus
    '   Wait two seconds before sending keystrokes
        Application.Wait (Now + TimeValue("0:00:02"))
        Application.SendKeys "%s"
    Next
End Sub
</code>```

I would like to add variable attachments. It will be a pdf file and its name will be the same as the name of customer (which is placed in column A). Basically it should look for "Name.pdf" in "S:\All Team\AX OTI\test\"

The source table looks like:

答:
Based on @Vityata advice, I've checked the question and based on that, I' ve changed the code. It is tested and works smoothly. The code is much easier, but the job is done.

```<code>Sub SendEmail()

Dim Mail_Object, OutApp As Variant

 With ActiveSheet
    lastrow = .Cells(.Rows.Count, "B").End(xlUp).Row 'list of recipients (email address) - it takes as many addresses as B column contains
    End With

For i = 2 To lastrow

Set Mail_Object = CreateObject("Outlook.Application")
Set OutApp = Mail_Object.CreateItem(0)

    With OutApp
    .Subject = "Your customer's account is on hold"
    .Body = "Dear client" & "," & vbCrLf & vbCrLf & "We would like to inform you, that Your account has been put on hold." & vbCrLf & vbCrLf & "If you have any queries, please contact us on uk.ar@bodycote.com." & vbCrLf & vbCrLf & "Kind regards," & vbCrLf & "Jon and Martina"
    .To = Cells(i, 2).Value
     strLocation = "S:\All team\AX OTI\test\" & Cells(i, 1) & ".pdf"
    .Attachments.Add (strLocation)
    .display
    '.send
    End With

Next i

debugs:
If Err.Description <> "" Then MsgBox Err.Description

End Sub
</code>```

Body:
I have code in Excel which sends email to a list of recipients:

Sub SendEMail()
    Dim xEmail As String
    Dim xSubj As String
    Dim xMsg As String
    Dim xURL As String
    Dim i As Integer
    Dim k As Double
    Dim xCell As Range
    Dim xRg As Range
    Dim xTxt As String
    On Error Resume Next
    xTxt = ActiveWindow.RangeSelection.Address
    Set xRg = Application.InputBox("Please select the data range:", "Send emails to:", xTxt, , , , , 8)
    If xRg Is Nothing Then Exit Sub
    If xRg.Columns.Count <> 3 Then
        MsgBox "Incorrect number of columns: You have to choose Name, Email address, Account no.!"
        Exit Sub
    End If
    For i = 1 To xRg.Rows.Count
    '   Get the email address
        xEmail = xRg.Cells(i, 2)
    '   Message subject
        xSubj = "Your customer's account is on hold"
    '   Compose the message
        xMsg = ""
        xMsg = xMsg & "Dear client" & "," & vbCrLf & vbCrLf
        xMsg = xMsg & "We would like to inform you, that Your account has been put on hold - "
        xMsg = xMsg & xRg.Cells(i, 3).Text & "." & vbCrLf & vbCrLf
        xMsg = xMsg & "If you have any queries, please contact us on uk.ar@bodycote.com." & vbCrLf & vbCrLf
        xMsg = xMsg & "Kind regards," & vbCrLf
        xMsg = xMsg & "Jon and Martina"
    '   Replace spaces with %20 (hex)
        xSubj = Application.WorksheetFunction.Substitute(xSubj, " ", "%20")
        xMsg = Application.WorksheetFunction.Substitute(xMsg, " ", "%20")
    '   Replace carriage returns with %0D%0A (hex)
        xMsg = Application.WorksheetFunction.Substitute(xMsg, vbCrLf, "%0D%0A")
    '   Create the URL
        xURL = "mailto:" & xEmail & "?subject=" & xSubj & "&body=" & xMsg
    '   Execute the URL (start the email client)
        ShellExecute 0&, vbNullString, xURL, vbNullString, vbNullString, vbNormalFocus
    '   Wait two seconds before sending keystrokes
        Application.Wait (Now + TimeValue("0:00:02"))
        Application.SendKeys "%s"
    Next
End Sub

I would like to add variable attachments. It will be a pdf file and its name will be the same as the name of customer (which is placed in column A). Basically it should look for "Name.pdf" in "S:\All Team\AX OTI\test\"

The source table looks like:

Body:
Based on @Vityata advice, I've checked the question and based on that, I' ve changed the code. It is tested and works smoothly. The code is much easier, but the job is done.

Sub SendEmail()

Dim Mail_Object, OutApp As Variant

 With ActiveSheet
    lastrow = .Cells(.Rows.Count, "B").End(xlUp).Row 'list of recipients (email address) - it takes as many addresses as B column contains
    End With

For i = 2 To lastrow

Set Mail_Object = CreateObject("Outlook.Application")
Set OutApp = Mail_Object.CreateItem(0)

    With OutApp
    .Subject = "Your customer's account is on hold"
    .Body = "Dear client" & "," & vbCrLf & vbCrLf & "We would like to inform you, that Your account has been put on hold." & vbCrLf & vbCrLf & "If you have any queries, please contact us on uk.ar@bodycote.com." & vbCrLf & vbCrLf & "Kind regards," & vbCrLf & "Jon and Martina"
    .To = Cells(i, 2).Value
     strLocation = "S:\All team\AX OTI\test\" & Cells(i, 1) & ".pdf"
    .Attachments.Add (strLocation)
    .display
    '.send
    End With

Next i

debugs:
If Err.Description <> "" Then MsgBox Err.Description

End Sub


问:
Auto-updating time for chatting
How can we get time?

For instance:

1 min ago

1 sec ago

today

yesterday

tuesday

before 7 days (1 week ago) it must show the date.

答:
If your'e saving the date, you can just use Period:

```<code>DateTime myDate = new DateTime(1978, 3, 26, 12, 35, 0, 0);
DateTime now = new DateTime();
Period period = new Period(myDate, now);

PeriodFormatter formatter = new PeriodFormatterBuilder()
    .appendSeconds().appendSuffix(" seconds ago\n")
    .appendMinutes().appendSuffix(" minutes ago\n")
    .appendHours().appendSuffix(" hours ago\n")
    .appendDays().appendSuffix(" days ago\n")
    .appendWeeks().appendSuffix(" weeks ago\n")
    .appendMonths().appendSuffix(" months ago\n")
    .appendYears().appendSuffix(" years ago\n")
    .printZeroNever()
    .toFormatter();

String elapsed = formatter.print(period);
System.out.println(elapsed);
</code>```

Prints:

```<code>3 seconds ago
51 minutes ago
7 hours ago
6 days ago
10 months ago
31 years ago
</code>```

From

Title: Auto-updating time for chatting

Body:
If your'e saving the date, you can just use Period:

DateTime myDate = new DateTime(1978, 3, 26, 12, 35, 0, 0);
DateTime now = new DateTime();
Period period = new Period(myDate, now);

PeriodFormatter formatter = new PeriodFormatterBuilder()
    .appendSeconds().appendSuffix(" seconds ago\n")
    .appendMinutes().appendSuffix(" minutes ago\n")
    .appendHours().appendSuffix(" hours ago\n")
    .appendDays().appendSuffix(" days ago\n")
    .appendWeeks().appendSuffix(" weeks ago\n")
    .appendMonths().appendSuffix(" months ago\n")
    .appendYears().appendSuffix(" years ago\n")
    .printZeroNever()
    .toFormatter();

String elapsed = formatter.print(period);
System.out.println(elapsed);

Prints:

3 seconds ago
51 minutes ago
7 hours ago
6 days ago
10 months ago
31 years ago

From


问:
Contributing to a GIT repository
The author of a repository on Github asked for contribution on his project by translating some language files. I tried to collaborate by doing the following steps:

Clone the repository and make a Pull

Create a branch "German_locale"

Made changes to language files

commit while adding a message

Push branch to origin (failed)

Intended final step: pull request on Github website

However, the 5. action fails. It asks for Username /Password and doesn't give me access if I'm providing my personal. I think, the system tries to verify me as the original author, which I am not.

The very basic questions are (sorry, I'm new):

What do I have to do in order to push a branch to a foreign repository? Do I have to ask for being a collaborator first? This doesn't seem right.

Would it be a better idea to create a fork in the first place? This doesn't seem right, either.

I'm using SmartGit as a client, so please describe the solution rather then providing command lines. I really want to understand how that works. I have seen other contributors translating other language files on this project successfully but have no idea how that works in general.

答: First, the owner of the repository should add you as a collaborator. Then you will be able to push changes to a remote Git repository.</p>

Title: Contributing to a GIT repository

ContentLicense: CC BY-SA 4.0


问: How to refresh the page

答: You can use location.reload() after successful submission of the form. If you just want to empty all fields you can use var anyField= "";

Title: How to refresh the page


问:
moving files between folders not working
i'm trying to move more than one million files from one folder to another using a script but i'm not getting any results i.e no files moved and i did not get any errors,the script checks if they are more than 20 records in a folder and it moves them in another specified folder,here is my script.

```<code>#!/bin/bash

cd "/home/admin/Lulu/Bo/"

check="ls | wc -l"
if [ $(check) -gt 1 ]
then
   find ./ -name " oAS1_201613*.tar.gz"|grep -v bak| xargs -t -I {} mv {} /RS/2011/
fi
</code>```

any suggestion on how this can be done?

答:
One possible reason for finding no files might be that the filename you've specified is incorrect. Do your files really start with a space character?

Is there a reason you're bothering to count the items? Wouldn't the existence of files matching your find criteria imply that $(check) -gt 1? If so, you can eliminate the check -- find will do nothing if it sees no files that match.

```<code>#!/bin/bash

src="/home/admin/Lulu/Bo/"

find "$src/" \
  -type f
  -name "oAS1_201613*.tar.gz" \
  -not -name "*bak*" \
  -print0 |
xargs -0 -t -I {} mv "{}" /RS/2011/
</code>```

Note the -print0 and xargs -0, which allow you to handle files with whitespace in their names.

Note that you could also run your mv as an option to find. Instead of -print0, you might use this:

```<code>find "$src/" ... -exec mv -v "{}" /RS/2011/ \;
</code>```

If you REALLY wanted to emulate the functionality of xargs -t, you could do that via multiple -exec commands.

One of the benefits of using xargs is sometimes the -P option, which lets you run things in parallel. At first glance, it would seem like a "big" job of moving a million files would be a candidate for this, but it's likely you'll be IO-bound anyway, so running your mv's in parallel might not be so helpful, in which case find .. -exec might be just as performant as the pipe to xargs.

Body:
i'm trying to move more than one million files from one folder to another using a script but i'm not getting any results i.e no files moved and i did not get any errors,the script checks if they are more than 20 records in a folder and it moves them in another specified folder,here is my script.

#!/bin/bash

cd "/home/admin/Lulu/Bo/"

check="ls | wc -l"
if [ $(check) -gt 1 ]
then
   find ./ -name " oAS1_201613*.tar.gz"|grep -v bak| xargs -t -I {} mv {} /RS/2011/
fi

any suggestion on how this can be done?

Body:
One possible reason for finding no files might be that the filename you've specified is incorrect. Do your files really start with a space character?

Is there a reason you're bothering to count the items? Wouldn't the existence of files matching your find criteria imply that $(check) -gt 1? If so, you can eliminate the check -- find will do nothing if it sees no files that match.

#!/bin/bash

src="/home/admin/Lulu/Bo/"

find "$src/" \
  -type f
  -name "oAS1_201613*.tar.gz" \
  -not -name "*bak*" \
  -print0 |
xargs -0 -t -I {} mv "{}" /RS/2011/

Note the -print0 and xargs -0, which allow you to handle files with whitespace in their names.

Note that you could also run your mv as an option to find. Instead of -print0, you might use this:

find "$src/" ... -exec mv -v "{}" /RS/2011/ \;

If you REALLY wanted to emulate the functionality of xargs -t, you could do that via multiple -exec commands.

One of the benefits of using xargs is sometimes the -P option, which lets you run things in parallel. At first glance, it would seem like a "big" job of moving a million files would be a candidate for this, but it's likely you'll be IO-bound anyway, so running your mv's in parallel might not be so helpful, in which case find .. -exec might be just as performant as the pipe to xargs.


问:
Reading/Writing/Storing extremely large sets of sequential data
I am interacting with large sequential sets of data in Java. Ideally, I'm searching for a library where I can store streaming data (think sequences of immutable objects) and then jump around through the saved data later. The data should ultimately be stored on the disk and shouldn't be stored in memory in it's entirety. The data would be states of mathematical systems -- so predominately numbers (of doubles, or even BigDecimals) as well as some strings.

At the moment this is for a desktop application, so there would only be one user and maybe a few concurrent connections at a time (several streams of objects/states). Later I may consider a distributed approach and support for multiple clients on the same database backend.

I've been looking at various NoSQL libraries but I am not sure what's right for my needs. Any thoughts?

答: If you have any means of calculating the offset for each object you want to access, a simple java.nio.MappedByteBuffer - the equivalent to mmap - might do the job.


问:
Java: Print a unique character in a string
I'm writing a program that will print the unique character in a string (entered through a scanner). I've created a method that tries to accomplish this but I keep getting characters that are not repeats, instead of a character (or characters) that is unique to the string. I want the unique letters only.

Here's my code:

```<code>import java.util.Scanner;
public class Sameness{
   public static void main (String[]args){
   Scanner kb = new Scanner (System.in);
     String word = "";

     System.out.println("Enter a word: ");
     word = kb.nextLine();

     uniqueCharacters(word);
}

    public static void uniqueCharacters(String test){
      String temp = "";
         for (int i = 0; i < test.length(); i++){
            if (temp.indexOf(test.charAt(i)) == - 1){
               temp = temp + test.charAt(i);
         }
      }

    System.out.println(temp + " ");

   }
}
</code>```

And here's sample output with the above code:

```<code>Enter a word:
nreena
nrea
</code>```

The expected output would be: ra

答:
If you don't want to use additional space:

```<code>    String abc="developer";

    System.out.println("The unique characters are-");

    for(int i=0;i<abc.length();i++)
    {
        for(int j=i+1;j<abc.length();j++)
        {
            if(abc.charAt(i)==abc.charAt(j))
                abc=abc.replace(String.valueOf(abc.charAt(j))," ");
        }
    }
    System.out.println(abc);
</code>```

Time complexity O(n^2) and no space.

Body:
I'm writing a program that will print the unique character in a string (entered through a scanner). I've created a method that tries to accomplish this but I keep getting characters that are not repeats, instead of a character (or characters) that is unique to the string. I want the unique letters only.

Here's my code:

import java.util.Scanner;
public class Sameness{
   public static void main (String[]args){
   Scanner kb = new Scanner (System.in);
     String word = "";

     System.out.println("Enter a word: ");
     word = kb.nextLine();

     uniqueCharacters(word);
}

    public static void uniqueCharacters(String test){
      String temp = "";
         for (int i = 0; i < test.length(); i++){
            if (temp.indexOf(test.charAt(i)) == - 1){
               temp = temp + test.charAt(i);
         }
      }

    System.out.println(temp + " ");

   }
}

And here's sample output with the above code:

Enter a word:
nreena
nrea

The expected output would be: ra

Body:
If you don't want to use additional space:

    String abc="developer";

    System.out.println("The unique characters are-");

    for(int i=0;i<abc.length();i++)
    {
        for(int j=i+1;j<abc.length();j++)
        {
            if(abc.charAt(i)==abc.charAt(j))
                abc=abc.replace(String.valueOf(abc.charAt(j))," ");
        }
    }
    System.out.println(abc);

Time complexity O(n^2) and no space.