问:
App crashing by pressing buttons in activity bar
I'm new in Android Studio. The problem is that, when I start the app and press a button in the activity bar, it crashes.

This is my main activity:

```<code>package com.example.tirir_000.iavq;

import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.app.FragmentManager;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, AdmisionFragment.OnFragmentInteractionListener {
        NavigationView navigationView = null;
        Toolbar toolbar = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            InicioFragment fragment = new InicioFragment();
            android.support.v4.app.FragmentTransaction fragmentTransaction =
                    getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.fragment_container, fragment);
            fragmentTransaction.commit();

        } else if (id == R.id.nav_gallery) {
            AdmisionFragment fragment = new AdmisionFragment();
            android.support.v4.app.FragmentTransaction fragmentTransaction =
                    getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.fragment_container, fragment);
            fragmentTransaction.commit();

        } else if (id == R.id.nav_slideshow) {
            CarrerasFragment fragment = new CarrerasFragment();
            android.support.v4.app.FragmentTransaction fragmentTransaction =
                    getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.fragment_container, fragment);
            fragmentTransaction.commit();

        } else if (id == R.id.nav_manage) {
            ComunidadFragment fragment = new ComunidadFragment();
            android.support.v4.app.FragmentTransaction fragmentTransaction =
                    getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.fragment_container, fragment);
            fragmentTransaction.commit();

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {
            SgaFragment fragment = new SgaFragment();
            android.support.v4.app.FragmentTransaction fragmentTransaction =
                    getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.fragment_container, fragment);
            fragmentTransaction.commit();

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onFragmentInteraction(Uri uri) {
    }
</code>```

My logcat says this:

```<code> Process: com.example.tirir_000.iavq, PID: 31097
     java.lang.RuntimeException: com.example.tirir_000.iavq.MainActivity@659c204 must implement OnFragmentInteractionListener
            at com.example.tirir_000.iavq.InicioFragment.onAttach(InicioFragment.java:83)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1231)
            at android.support.v4.app.FragmentTransition.addToFirstInLastOut(FragmentTransition.java:1085)
            at android.support.v4.app.FragmentTransition.calculateFragments(FragmentTransition.java:976)
            at android.support.v4.app.FragmentTransition.startTransitions(FragmentTransition.java:95)
            at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2146)
            at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2013)
            at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
            at android.os.Handler.handleCallback(Handler.java:815)
            at android.os.Handler.dispatchMessage(Handler.java:104)
            at android.os.Looper.loop(Looper.java:207)
            at android.app.ActivityThread.main(ActivityThread.java:5763)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
</code>```

How can I fix it?

答:
Hey you did not in last you use onFragmentInteraction but you didn't implememt onFragmentInteraction in you Java class

Like this you have to do

Public class xyz extends AppcompactActivity implent onFragmnetInteraction

Do this

Body:
I'm new in Android Studio. The problem is that, when I start the app and press a button in the activity bar, it crashes.

This is my main activity:

package com.example.tirir_000.iavq;

import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.app.FragmentManager;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, AdmisionFragment.OnFragmentInteractionListener {
        NavigationView navigationView = null;
        Toolbar toolbar = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            InicioFragment fragment = new InicioFragment();
            android.support.v4.app.FragmentTransaction fragmentTransaction =
                    getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.fragment_container, fragment);
            fragmentTransaction.commit();

        } else if (id == R.id.nav_gallery) {
            AdmisionFragment fragment = new AdmisionFragment();
            android.support.v4.app.FragmentTransaction fragmentTransaction =
                    getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.fragment_container, fragment);
            fragmentTransaction.commit();

        } else if (id == R.id.nav_slideshow) {
            CarrerasFragment fragment = new CarrerasFragment();
            android.support.v4.app.FragmentTransaction fragmentTransaction =
                    getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.fragment_container, fragment);
            fragmentTransaction.commit();

        } else if (id == R.id.nav_manage) {
            ComunidadFragment fragment = new ComunidadFragment();
            android.support.v4.app.FragmentTransaction fragmentTransaction =
                    getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.fragment_container, fragment);
            fragmentTransaction.commit();

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {
            SgaFragment fragment = new SgaFragment();
            android.support.v4.app.FragmentTransaction fragmentTransaction =
                    getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.fragment_container, fragment);
            fragmentTransaction.commit();

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onFragmentInteraction(Uri uri) {
    }

My logcat says this:

 Process: com.example.tirir_000.iavq, PID: 31097
     java.lang.RuntimeException: com.example.tirir_000.iavq.MainActivity@659c204 must implement OnFragmentInteractionListener
            at com.example.tirir_000.iavq.InicioFragment.onAttach(InicioFragment.java:83)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1231)
            at android.support.v4.app.FragmentTransition.addToFirstInLastOut(FragmentTransition.java:1085)
            at android.support.v4.app.FragmentTransition.calculateFragments(FragmentTransition.java:976)
            at android.support.v4.app.FragmentTransition.startTransitions(FragmentTransition.java:95)
            at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2146)
            at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2013)
            at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
            at android.os.Handler.handleCallback(Handler.java:815)
            at android.os.Handler.dispatchMessage(Handler.java:104)
            at android.os.Looper.loop(Looper.java:207)
            at android.app.ActivityThread.main(ActivityThread.java:5763)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)

How can I fix it?


来源: stackexchange

问:
Stuff terminal command error into Robot Framework report
Still new to Robot Framework - Quick Question:
The command that is executed via Robot Framework generates an error dump on the terminal.  I would like to pick up the error and stuff it into the log.html#s1-t1 in the Robot Framework report.

Here is my Python Code:

```<code>from test.testing import testcase
from testers import *

def run_testcase():
        main(module=testcase, action='simulate')
</code>```

Here is my Robot Framework code:

```<code>*** Settings ***
Library                testing_testcase.py

*** Test Cases ***
Testing the testcase - (TC462)
  Run testcase
</code>```

All I want is some help on how to capture the error generated by the command in the terminal and stuff it into the Robot Framework report.

These are the dumps, I'd like to capture in the report.  This command was run manually:

```<code>Johns-MacBook-Pro:~ john.doe$ ~/models/.venv/bin/python /Users/john.doe/models/cores/mumimo/pycores/mumimo/testing_testcase.py simulate
Traceback (most recent call last):
  File "/Users/john.doe/models/cores/mumimo/pycores/mumimo/testing_testcase.py", line 138, in <module>
    main3()
  File "/Users/john.doe/models/src/mymytask/mymytask.py", line 529, in main3
    env = environment()
  File "/Users/john.doe/models/.venv/src/mytask/mytask/_block.py", line 125, in __call__
    self.srcline, *args, **kwargs)
  File "/Users/john.doe/models/.venv/src/mytask/mytask/_block.py", line 158, in __init__
    self.subs = _flatten(func(*args, **kwargs))
  File "/Users/john.doe/models/src/mymytask/mymytask.py", line 527, in environment
    tb = args.testbench(ports, params)
  File "/Users/john.doe/models/.venv/src/mytask/mytask/_block.py", line 125, in __call__
    self.srcline, *args, **kwargs)
  File "/Users/john.doe/models/.venv/src/mytask/mytask/_block.py", line 158, in __init__
    self.subs = _flatten(func(*args, **kwargs))
</code>```

答:
If by an error generated on the terminal you mean the keyword fails and you see it in the conosle during the run, then use the keyword Run Keyword And Ignore Error - it returns 2 variables, the status of the embedded keyword, and either its output on success, or the error/exception on failure (your desired case).

So the body of your test case would be:

```<code>Testing the testcase - (TC462)
    ${rc}  ${msg}    Run Keyword And Ignore Error    Run testcase
    Run Keyword If    '${rc}' == 'FAIL'    Log    The error is: ${msg}
               ...    ELSE    Log the keyword did not fail, its output is: ${msg}

    Run Keyword If    '${rc}' == 'FAIL'    Fail    Failing the case, the keyword failed
</code>```

Looking at the updated question, it seems to me you want to log not only the particular exception - which would happen with the above code, but also the full stack trace.

If that is so, there is a change in the python code that should be done - you have to get and return it as part of the function.

There is a python module just for that - traceback, and more specifically its format_exec. Here's a sample how it could be done, shape it a bit according to your needs:

```<code>import traceback
from test.testing import testcase
from testers import *

def run_testcase():
    try:
        main(module=testcase, action='simulate')
    except Exception as e:
        tb = traceback.format_exc()
        raise Exception(tb)
</code>```

So any exception is caught (that's a wide net, you might want to change it to something more specific), the stack trace is stored as a string in tb, and then reraised - so RF catches it, marks the keyword as failed, and the code in the first part logs it.

ContentLicense: CC BY-SA 3.0

Body:
Still new to Robot Framework - Quick Question:
The command that is executed via Robot Framework generates an error dump on the terminal.  I would like to pick up the error and stuff it into the log.html#s1-t1 in the Robot Framework report.

Here is my Python Code:

from test.testing import testcase
from testers import *

def run_testcase():
        main(module=testcase, action='simulate')

Here is my Robot Framework code:

*** Settings ***
Library                testing_testcase.py

*** Test Cases ***
Testing the testcase - (TC462)
  Run testcase

All I want is some help on how to capture the error generated by the command in the terminal and stuff it into the Robot Framework report.

These are the dumps, I'd like to capture in the report.  This command was run manually:

Johns-MacBook-Pro:~ john.doe$ ~/models/.venv/bin/python /Users/john.doe/models/cores/mumimo/pycores/mumimo/testing_testcase.py simulate
Traceback (most recent call last):
  File "/Users/john.doe/models/cores/mumimo/pycores/mumimo/testing_testcase.py", line 138, in <module>
    main3()
  File "/Users/john.doe/models/src/mymytask/mymytask.py", line 529, in main3
    env = environment()
  File "/Users/john.doe/models/.venv/src/mytask/mytask/_block.py", line 125, in __call__
    self.srcline, *args, **kwargs)
  File "/Users/john.doe/models/.venv/src/mytask/mytask/_block.py", line 158, in __init__
    self.subs = _flatten(func(*args, **kwargs))
  File "/Users/john.doe/models/src/mymytask/mymytask.py", line 527, in environment
    tb = args.testbench(ports, params)
  File "/Users/john.doe/models/.venv/src/mytask/mytask/_block.py", line 125, in __call__
    self.srcline, *args, **kwargs)
  File "/Users/john.doe/models/.venv/src/mytask/mytask/_block.py", line 158, in __init__
    self.subs = _flatten(func(*args, **kwargs))

Body:
If by an error generated on the terminal you mean the keyword fails and you see it in the conosle during the run, then use the keyword Run Keyword And Ignore Error - it returns 2 variables, the status of the embedded keyword, and either its output on success, or the error/exception on failure (your desired case).

So the body of your test case would be:

Testing the testcase - (TC462)
    ${rc}  ${msg}    Run Keyword And Ignore Error    Run testcase
    Run Keyword If    '${rc}' == 'FAIL'    Log    The error is: ${msg}
               ...    ELSE    Log the keyword did not fail, its output is: ${msg}

    Run Keyword If    '${rc}' == 'FAIL'    Fail    Failing the case, the keyword failed

Looking at the updated question, it seems to me you want to log not only the particular exception - which would happen with the above code, but also the full stack trace.

If that is so, there is a change in the python code that should be done - you have to get and return it as part of the function.

There is a python module just for that - traceback, and more specifically its format_exec. Here's a sample how it could be done, shape it a bit according to your needs:

import traceback
from test.testing import testcase
from testers import *

def run_testcase():
    try:
        main(module=testcase, action='simulate')
    except Exception as e:
        tb = traceback.format_exc()
        raise Exception(tb)

So any exception is caught (that's a wide net, you might want to change it to something more specific), the stack trace is stored as a string in tb, and then reraised - so RF catches it, marks the keyword as failed, and the code in the first part logs it.


问:
Expand/reshape dimension of column of Pandas Series
I want to expand a pandas series from one to three dimension. Below print(np.array(xs).shape) gives me an output of (2,) and I would like the shape of np.array(xs) to be (2,3,3), what should I do?

```<code>import pandas as pd
x = []
x.append(np.ones((3,3)))
x.append(np.zeros((3,3)))

xs = pd.Series(x)
print(np.array(xs).shape)
</code>```

Any reply is appreciated!

note: I know np.array(x) would give me the desired output and shape, however I am given xs in the first place. The expected output should be print(np.array(x)) whose shape is (2,3,3).

```<code>array([[[ 1.,  1.,  1.],
        [ 1.,  1.,  1.],
        [ 1.,  1.,  1.]],

      [[ 0.,  0.,  0.],
       [ 0.,  0.,  0.],
       [ 0.,  0.,  0.]]])
</code>```

答:
You can convert the Series to dataframes and then concat and convert to numpy array. Finally reshape it to the shape you need.</p>

```<code>pd.concat(xs.apply(pd.DataFrame).tolist()).values.reshape(2,3,3)
Out[1081]:
array([[[ 1.,  1.,  1.],
        [ 1.,  1.,  1.],
        [ 1.,  1.,  1.]],

       [[ 0.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.]]])
</code>```

Body:
I want to expand a pandas series from one to three dimension. Below print(np.array(xs).shape) gives me an output of (2,) and I would like the shape of np.array(xs) to be (2,3,3), what should I do?

import pandas as pd
x = []
x.append(np.ones((3,3)))
x.append(np.zeros((3,3)))

xs = pd.Series(x)
print(np.array(xs).shape)

Any reply is appreciated!

note: I know np.array(x) would give me the desired output and shape, however I am given xs in the first place. The expected output should be print(np.array(x)) whose shape is (2,3,3).

array([[[ 1.,  1.,  1.],
        [ 1.,  1.,  1.],
        [ 1.,  1.,  1.]],

      [[ 0.,  0.,  0.],
       [ 0.,  0.,  0.],
       [ 0.,  0.,  0.]]])

Body:
You can convert the Series to dataframes and then concat and convert to numpy array. Finally reshape it to the shape you need.

pd.concat(xs.apply(pd.DataFrame).tolist()).values.reshape(2,3,3)
Out[1081]:
array([[[ 1.,  1.,  1.],
        [ 1.,  1.,  1.],
        [ 1.,  1.,  1.]],

       [[ 0.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.]]])


问:
How can I append a string to a line when certain conditions are met?
I'm handling large .txt files and we are trying to identify which ones do not comply with the correct amount of characters in a line (80 characters top).

For the sake of this example let's say that we need 10 characters for every line, I need to append "(+Number of extra characters)" and "(-Number of missing characters)" for each line that does not have exactly 10 characters.

Here is what I have so far:

```<code>while IFS='' read -r line || [[ -n "$line" ]]; do
  if [[ "${#line}" -gt 10 ]]; then
    echo "Mo dan 10 D: ${#line}"
  elif [[ "${#line}" -lt 10 ]]; then
    echo "Less dan 10 D: ${#line}"
  fi

done < "$1"
</code>```

I'm stuck in finding a way to append those two strings I'm echoing in the corresponding line so we can identify them.

I researched about awk and sed but haven't been able to properly loop through the entire .txt file, count the amount of characters in every line and append a string with the appropriate message.

Would appreciate some assistance in either shell scripting or as an awk or sed solution.
Thank You.

Edit: This is an example input file (note white spaces also count as characters)

```<code>Line 1****
Line 2*****
Line 3*
Line 4****
Line 5****
Line 6**
Line 7****
Line 8********
Line 9****
</code>```

This is the desired output

```<code>Line 1****
Line 2*****(+1)
Line 3*(-3)
Line 4****
Line 5****
Line 6**(-2)
Line 7****
Line 8********(+4)
Line 9****
</code>```

答:
I based my answer on your original script

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

while IFS='' read -r line || [[ -n "$line" ]]; do
  nchars=${#line}
  target=10
  if [[ $nchars -gt $target ]]; then
          echo "$line+($((nchars-target)))"
  elif [[ $nchars -lt $target ]]; then
          echo "$line-($((target-nchars)))"
  else
      echo "$line"
  fi

done < "$1"
</code>```

simply use it like this bash evalscript inputfile > outputfile

Body:
I'm handling large .txt files and we are trying to identify which ones do not comply with the correct amount of characters in a line (80 characters top).

For the sake of this example let's say that we need 10 characters for every line, I need to append "(+Number of extra characters)" and "(-Number of missing characters)" for each line that does not have exactly 10 characters.

Here is what I have so far:

while IFS='' read -r line || [[ -n "$line" ]]; do
  if [[ "${#line}" -gt 10 ]]; then
    echo "Mo dan 10 D: ${#line}"
  elif [[ "${#line}" -lt 10 ]]; then
    echo "Less dan 10 D: ${#line}"
  fi

done < "$1"

I'm stuck in finding a way to append those two strings I'm echoing in the corresponding line so we can identify them.

I researched about awk and sed but haven't been able to properly loop through the entire .txt file, count the amount of characters in every line and append a string with the appropriate message.

Would appreciate some assistance in either shell scripting or as an awk or sed solution.
Thank You.

Edit: This is an example input file (note white spaces also count as characters)

Line 1****
Line 2*****
Line 3*
Line 4****
Line 5****
Line 6**
Line 7****
Line 8********
Line 9****

This is the desired output

Line 1****
Line 2*****(+1)
Line 3*(-3)
Line 4****
Line 5****
Line 6**(-2)
Line 7****
Line 8********(+4)
Line 9****

Body:
I based my answer on your original script

#!/bin/bash

while IFS='' read -r line || [[ -n "$line" ]]; do
  nchars=${#line}
  target=10
  if [[ $nchars -gt $target ]]; then
          echo "$line+($((nchars-target)))"
  elif [[ $nchars -lt $target ]]; then
          echo "$line-($((target-nchars)))"
  else
      echo "$line"
  fi

done < "$1"

simply use it like this bash evalscript inputfile > outputfile


问:
(Porting to Android) In the Android NDK, how can I get the OpenGL context in my current thread?
I'm porting some code to Android from iOS.

In iOS, you can make an OpenGL context current in the current thread like so:

```<code>[EAGLContext *aContext=[viewController getContext];
[EAGLContext setCurrentContext:aContext];
</code>```

And now suddenly you can use OpenGL in this thread without a problem.

What is the equivalent way to do this in Android, using the NDK?

答:
eglMakeCurrent():

eglMakeCurrent binds context to the current rendering thread and to the draw and read surfaces.

Body:
I'm porting some code to Android from iOS.

In iOS, you can make an OpenGL context current in the current thread like so:

[EAGLContext *aContext=[viewController getContext];
[EAGLContext setCurrentContext:aContext];

And now suddenly you can use OpenGL in this thread without a problem.

What is the equivalent way to do this in Android, using the NDK?


问:
C# Is it possible to replace my dictionary class with the contents of a text file?
For example, in a file of my project I have Dictionaries.cs containing:

```<code> public DictionaryInit() {

        public Dictionary<int, DictionaryCheckup> H = new Dictionary<int, DictionaryCheckup>()
        {
            {180000, new DictionaryCheckup {theGrouping="H"}},
            {180001, new DictionaryCheckup {theGrouping="H"}},
            {180303, new DictionaryCheckup {theGrouping="H"}},
        };

     public Dictionary<int, DictionaryCheckup> C = new Dictionary<int, DictionaryCheckup>()
        {
            {180700, new DictionaryCheckup {theGrouping="C"}},
            {180201, new DictionaryCheckup {theGrouping="C"}},
            {180503, new DictionaryCheckup {theGrouping="C"}},
        };

      Etc.
     }
</code>```

(DictionaryCheckup is a class that get;set; the string theGrouping)

The idea is that I wanted to allow my end user to hot swap a criteria, which is the dictionary class in question. Should he need to add a Dictionary U, he will simply need to copy the structure in the text file, replace the Key or Value where necessary, and then select it from the program. This loads it and replaces my dictionary class at runtime. Is this possible?

After some research, I found that Json and serialization is a method of doing this, but I'm not so  familiar with it, or if there's any difference from reading a text file. Here is a thread I found: How do I read and write a C# string Dictionary to a file?.

In these examples, i'm not sure how they differentiate a key from a value. Furthermore, I don't think I will be able to access my DictionaryCheckup class through this, which is the criteria the Key is valued to.

So, my question is whether I can, for simplicity, write my dictionary class, perhaps as-is, to a text file of some sort, and then load it up at runtime? Or would I have to create a var dictionary, and then add keys and values to it based on the external file? I'll probably look into the Json method anyway of seralization, I'm just worried about implementing a web function when my program has nothing to do with it.

答:
You can use JSON.Net to serialize your dictionaries to JSON, which can then be read and written to the file.

JSON is simply a way to format .Net objects in a manner that can be stored (e.g. in a file). It is based on JavaScript's syntax, but has nothing to do with the web directly.

Something like this should work:

```<code>// Default dictionary
Dictionary<int, DictionaryCheckup> H = new Dictionary<int, DictionaryCheckup>()
{
    {180000, new DictionaryCheckup {theGrouping = "H"}},
    {180001, new DictionaryCheckup {theGrouping = "H"}},
    {180303, new DictionaryCheckup {theGrouping = "H"}},
};

// Then when we plan on loading our dictionary...

// Write our our default JSON if no config file exists
if (!File.Exists("H.json"))
{
    using (var stream = new StreamWriter(File.Create("H.json")))
    {
        // Convert our "H" dictionary into JSON
        var json = JsonConvert.SerializeObject(H, Formatting.Indented);

        // Write the JSON to the file
        stream.Write(json);
        stream.Flush();
    }
}
// Read the JSON that our user has configured
else
{
    using (var stream = new StreamReader(File.OpenRead("H.json")))
    {
        // Read our JSON from the file
        var json = stream.ReadToEnd();

        // Convert it back to a Dictionary<int, DictionaryCheckup> object and store
        // it in our "H" variable
        H = JsonConvert.DeserializeObject<Dictionary<int, DictionaryCheckup>>(json);
    }
}
</code>```

The above code reads/writes files that look like this:

```<code>{
  "180000": {
    "theGrouping": "H"
  },
  "180001": {
    "theGrouping": "H"
  },
  "180303": {
    "theGrouping": "H"
  }
}
</code>```

Note that the above example is just for writing and loading a single dictionary. If you wanted, you could change the code to store an array of dictionaries (or even dictionaries of dictionaries) which would then allow adding or removing dictionaries via copy-paste.

Body:
For example, in a file of my project I have Dictionaries.cs containing:

 public DictionaryInit() {

        public Dictionary<int, DictionaryCheckup> H = new Dictionary<int, DictionaryCheckup>()
        {
            {180000, new DictionaryCheckup {theGrouping="H"}},
            {180001, new DictionaryCheckup {theGrouping="H"}},
            {180303, new DictionaryCheckup {theGrouping="H"}},
        };

     public Dictionary<int, DictionaryCheckup> C = new Dictionary<int, DictionaryCheckup>()
        {
            {180700, new DictionaryCheckup {theGrouping="C"}},
            {180201, new DictionaryCheckup {theGrouping="C"}},
            {180503, new DictionaryCheckup {theGrouping="C"}},
        };

      Etc.
     }

(DictionaryCheckup is a class that get;set; the string theGrouping)

The idea is that I wanted to allow my end user to hot swap a criteria, which is the dictionary class in question. Should he need to add a Dictionary U, he will simply need to copy the structure in the text file, replace the Key or Value where necessary, and then select it from the program. This loads it and replaces my dictionary class at runtime. Is this possible?

After some research, I found that Json and serialization is a method of doing this, but I'm not so  familiar with it, or if there's any difference from reading a text file. Here is a thread I found: How do I read and write a C# string Dictionary to a file?.

In these examples, i'm not sure how they differentiate a key from a value. Furthermore, I don't think I will be able to access my DictionaryCheckup class through this, which is the criteria the Key is valued to.

So, my question is whether I can, for simplicity, write my dictionary class, perhaps as-is, to a text file of some sort, and then load it up at runtime? Or would I have to create a var dictionary, and then add keys and values to it based on the external file? I'll probably look into the Json method anyway of seralization, I'm just worried about implementing a web function when my program has nothing to do with it.

Body:
You can use JSON.Net to serialize your dictionaries to JSON, which can then be read and written to the file.

JSON is simply a way to format .Net objects in a manner that can be stored (e.g. in a file). It is based on JavaScript's syntax, but has nothing to do with the web directly.

Something like this should work:

// Default dictionary
Dictionary<int, DictionaryCheckup> H = new Dictionary<int, DictionaryCheckup>()
{
    {180000, new DictionaryCheckup {theGrouping = "H"}},
    {180001, new DictionaryCheckup {theGrouping = "H"}},
    {180303, new DictionaryCheckup {theGrouping = "H"}},
};

// Then when we plan on loading our dictionary...

// Write our our default JSON if no config file exists
if (!File.Exists("H.json"))
{
    using (var stream = new StreamWriter(File.Create("H.json")))
    {
        // Convert our "H" dictionary into JSON
        var json = JsonConvert.SerializeObject(H, Formatting.Indented);

        // Write the JSON to the file
        stream.Write(json);
        stream.Flush();
    }
}
// Read the JSON that our user has configured
else
{
    using (var stream = new StreamReader(File.OpenRead("H.json")))
    {
        // Read our JSON from the file
        var json = stream.ReadToEnd();

        // Convert it back to a Dictionary<int, DictionaryCheckup> object and store
        // it in our "H" variable
        H = JsonConvert.DeserializeObject<Dictionary<int, DictionaryCheckup>>(json);
    }
}

The above code reads/writes files that look like this:

{
  "180000": {
    "theGrouping": "H"
  },
  "180001": {
    "theGrouping": "H"
  },
  "180303": {
    "theGrouping": "H"
  }
}

Note that the above example is just for writing and loading a single dictionary. If you wanted, you could change the code to store an array of dictionaries (or even dictionaries of dictionaries) which would then allow adding or removing dictionaries via copy-paste.


问:
small image link as a button at the bottom right of the image it is selling
Im trying to put a link button to amazon on a picture but not only is it not working its making my website all wonky

.review-page-lander > img {
  width: 100%;
  max-width: 1169px;
  margin: 0 auto;
}
img.buy-from-button{
  height: 35px;
  width: 150px;
  top: 35px;
  float:left;
  position: relative;
  z-index: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="lander-image">

    <img class="buy-from-button" src="http://oathtohealth.com/wp-content/uploads/2016/05/Amazon.png" alt="buy at amazon">

  <img src="amazon-item.jpg">
</div>   </code>```

答:
I would suggest to keep your product image above your buy button and make buy button float right relatively with bottom: 40px;

.lander-image>img {
  width: 100%;
  max-width: 1169px;
  margin: 0 auto;
}

img.buy-from-button {
  height: 35px;
  width: 150px;
  float: right;
  position: relative;
  z-index: 1;
  bottom: 40px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="lander-image">
  <img src="http://placehold.it/250x300">

    <img class="buy-from-button" src="http://oathtohealth.com/wp-content/uploads/2016/05/Amazon.png" alt="buy at amazon">

</div></code>```

Body:
I would suggest to keep your product image above your buy button and make buy button float right relatively with bottom: 40px;

.lander-image>img {
  width: 100%;
  max-width: 1169px;
  margin: 0 auto;
}

img.buy-from-button {
  height: 35px;
  width: 150px;
  float: right;
  position: relative;
  z-index: 1;
  bottom: 40px;
}

<div class="lander-image">
  <img src="http://placehold.it/250x300">
  <a href="#">
    <img class="buy-from-button" src="http://oathtohealth.com/wp-content/uploads/2016/05/Amazon.png" alt="buy at amazon">
  </a>
</div>


问:
How to post process bound data in angularjs
Is it possible to post process data bound with angularjs?

I am writing simple search page and i have generated results with code:

```<code>...
<div class="row" ng-repeat="document in sc.searchResult.content">
    <blockquote>
        {{document.content}}
    </blockquote>
</div>
...
</code>```

The problem is that I need to bold specific words in every result (the words from query box - like in google below)

How to reach that effect?

答:
controller.js

```<code>$scope.document.content = someSearchContent.replace(/<searchTerm>/g, '<strong>' + <searchTerm> + '</strong>')
</code>```

searchTerm is the string that you need to modify. You can use RegExp() to create a regular expresion.

template

```<code><blockquote ng-bind-html="document.content"></blockquote>
</code>```

Body:
Is it possible to post process data bound with angularjs?

I am writing simple search page and i have generated results with code:

...

        {{document.content}}

...

The problem is that I need to bold specific words in every result (the words from query box - like in google below)

How to reach that effect?

Body:
controller.js

$scope.document.content = someSearchContent.replace(/<searchTerm>/g, '<strong>' + <searchTerm> + '</strong>')

searchTerm is the string that you need to modify. You can use RegExp() to create a regular expresion.

template

<blockquote ng-bind-html="document.content"></blockquote>


问:
Extracting a selected item in a ListBox c#
I have a list box that displays members of a List<Student> where Student is a class that has some properties like name etc.. I also have a list box that displays members of a 'ListwherePaperis similar toStudent`.

How do I get the selected Student and Paper and add them to a dict {Paper.Name:Student.Name} when a button is clicked ?

I have tried
Form2

selectedStudent_Form2 = studentListBox_Form2.SelectedItem;

But I get an error saying

Cannot implicitly convert type 'object' to 'TestProjectForProject5.Student'.

答:
Assuming that you added names of the students to the listBox, then you can search through your data structure for the selected name (nameToSearch).</p>

```<code>string nameToSearch = studentListBox_Form2.SelectedItem.ToString();

foreach (Student s in students) { //or use a for loop
    if (s.Name == nameToSearch) {
        //code
    }
}
</code>```

Body:
Assuming that you added names of the students to the listBox, then you can search through your data structure for the selected name (nameToSearch).

string nameToSearch = studentListBox_Form2.SelectedItem.ToString();

foreach (Student s in students) { //or use a for loop
    if (s.Name == nameToSearch) {
        //code
    }
}


问:
NullPointerException for my States in my DFA?
I can't figure out why I am getting a NullPointerException in my code.
I am trying to write simulator for a DFA and I have made my a Node type class that holds my states as seen below,

```<code>import java.util.Map;

class State{
        //fields
        Map<String,State> nextStates;

        public State passChar(String putIn){
            if(!nextStates.containsKey(putIn)){
                return null;
            }
            return nextStates.get(putIn);
        }

        /**
         * Add a state that this state connects to.
         * @param sta the state that this state connects to when
         * a letter in the alphabet is passed to it.
         * @param pass the letter that is passed to it.
         */
        public void addNextState(String pass,State sta){
            nextStates.put(pass,sta);
        }
    }
</code>```

I have tried I the main is in my driving class
and is as such,

```<code>//Setting up my Q
        State q1 = new State();
        State q2 = new State();
        q1.addNextState("1", q1); //this is where my exception is thrown.
        q1.addNextState("0", q2);

Exception in thread "main" java.lang.NullPointerException
    at State.addNextState(State.java:25)
    at DFA.main(DFA.java:100)
</code>```

答:
You got to initialize the Map:

```<code>Map<String,State> nextStates;
</code>```

Where are you doing it ? Something like this:

```<code>Map<String,State> nextStates = new HasMap <>();
</code>```

That's the reason for NullPointerException.

Body:
I can't figure out why I am getting a NullPointerException in my code.
I am trying to write simulator for a DFA and I have made my a Node type class that holds my states as seen below,

import java.util.Map;

class State{
        //fields
        Map<String,State> nextStates;

        public State passChar(String putIn){
            if(!nextStates.containsKey(putIn)){
                return null;
            }
            return nextStates.get(putIn);
        }

        /**
         * Add a state that this state connects to.
         * @param sta the state that this state connects to when
         * a letter in the alphabet is passed to it.
         * @param pass the letter that is passed to it.
         */
        public void addNextState(String pass,State sta){
            nextStates.put(pass,sta);
        }
    }

I have tried I the main is in my driving class
and is as such,

//Setting up my Q
        State q1 = new State();
        State q2 = new State();
        q1.addNextState("1", q1); //this is where my exception is thrown.
        q1.addNextState("0", q2);

Exception in thread "main" java.lang.NullPointerException
    at State.addNextState(State.java:25)
    at DFA.main(DFA.java:100)

Body:
You got to initialize the Map:

Map<String,State> nextStates;

Where are you doing it ? Something like this:

Map<String,State> nextStates = new HasMap <>();

That's the reason for NullPointerException.


问:
Permissions error when connecting to EC2 via SSH on Mac OSx
I am new to EC2. I created my security credentials from this site:

http://paulstamatiou.com/how-to-getting-started-with-amazon-ec2

It worked great, I rebooted and now when I try to connect I get a login/password prompt. (Which I never set up.) After several attempts I get this error:

Permission denied (publickey,gssapi-with-mic).

What am I doing wrong?

答:
I had met this problem too.And I found  that happend beacuse I forgot to add the user-name before the host name:
like this:

```<code>ssh -i test.pem ec2-32-122-42-91.us-west-2.compute.amazonaws.com
</code>```

and I add the user name:

```<code>ssh -i test.pem ec2-user@ec2-32-122-42-91.us-west-2.compute.amazonaws.com
</code>```

it works!

Body:
I had met this problem too.And I found  that happend beacuse I forgot to add the user-name before the host name:
like this:

ssh -i test.pem ec2-32-122-42-91.us-west-2.compute.amazonaws.com

and I add the user name:

ssh -i test.pem ec2-user@ec2-32-122-42-91.us-west-2.compute.amazonaws.com

it works!


问:
Pivot or Transforming JavaScript object
I have the following JavaScript object. I need to generate a new object from the given object. What is the approach I should take in JavaScript?

```<code>[
 {"name": "Dan",  "city" : "Columbus", "ZIP":"47201"},
 {"name": "Jen",  "city" : "Columbus", "ZIP":"47201"},
 {"name": "Mark", "city" : "Tampa",  "ZIP":"33602"},
]
</code>```

How can I transform or pivot to generate the following object?

```<code>[
 { "47201": [
              {"name": "Dan", "city": "Columbus"},
              {"name": "Jen", "city": "Columbus"},
             ],
    "count": "2"
  },
  { "33602": [
              {"name": "Mark", "city": "Tampa"}
             ],
    "count": "1"
  }
 ]
</code>```

答:
I don't know why you want the .count property, when that can be accessed via the array's .length property, but anyway:

const input = [
  {"name": "Dan",  "city" : "Columbus", "ZIP":"47201"},
  {"name": "Jen",  "city" : "Columbus", "ZIP":"47201"},
  {"name": "Mark", "city" : "Tampa",  "ZIP":"33602"},
]

const working = input.reduce((acc, {ZIP, name, city}) => {
  (acc[ZIP] || (acc[ZIP] = [])).push({name, city})
  return acc
}, {})

const output = Object.keys(working)
  .map(k => ({[k]: working[k], count: working[k].length}))

console.log(output)```

Further reading:

Array .reduce()

Array .map()

Object.keys()

Unpacking fields from objects passed as function parameters

Computed property names

Title: Pivot or Transforming JavaScript object

Body:
I have the following JavaScript object. I need to generate a new object from the given object. What is the approach I should take in JavaScript?

[
 {"name": "Dan",  "city" : "Columbus", "ZIP":"47201"},
 {"name": "Jen",  "city" : "Columbus", "ZIP":"47201"},
 {"name": "Mark", "city" : "Tampa",  "ZIP":"33602"},
]

How can I transform or pivot to generate the following object?

[
 { "47201": [
              {"name": "Dan", "city": "Columbus"},
              {"name": "Jen", "city": "Columbus"},
             ],
    "count": "2"
  },
  { "33602": [
              {"name": "Mark", "city": "Tampa"}
             ],
    "count": "1"
  }
 ]

Body:
I don't know why you want the .count property, when that can be accessed via the array's .length property, but anyway:

const input = [
  {"name": "Dan",  "city" : "Columbus", "ZIP":"47201"},
  {"name": "Jen",  "city" : "Columbus", "ZIP":"47201"},
  {"name": "Mark", "city" : "Tampa",  "ZIP":"33602"},
]

const working = input.reduce((acc, {ZIP, name, city}) => {
  (acc[ZIP] || (acc[ZIP] = [])).push({name, city})
  return acc
}, {})

const output = Object.keys(working)
  .map(k => ({[k]: working[k], count: working[k].length}))

console.log(output)

Further reading:

Array .reduce()

Array .map()

Object.keys()

Unpacking fields from objects passed as function parameters

Computed property names


问:
Python : How to use random sample when we don't need duplicates random sample
My Code

```<code>import random

MyList = [[1,2,3,4,5,6,7,8],[a,s,d,f,g,h,h],[q,w,e,r,t,y]]
MyListRandom = []
random_number = 5
i=0
while True:
     random_list = randint(0,len(MyList))
     element_random = random.sample(MyList[random_list], 1)
     if element_random[0] not in MyListRandom:
     i = i+1
     MyListRandom.append(element_random[0])
else:
    continue
if(i>=random_number):
    break
</code>```

if I don't want to use this code to check it

```<code> if element_random[0] not in MyListRandom:
     MyListRandom.append(element_random[0])
</code>```

Is there a better way more than this if i don't want a duplicates sample?

答:
From the documentation random.sample(MyList) will give you unique answers from the list's items already. For duplicates in MyList you sample from, you can just make it a set.

Also you don't need the loop for every sample, you can just give it a k argument and it will return k many random samples. So the whole code can be written as:

```<code># I have flatten the whole list into one list
element_random = random.sample(set([item for sublist in MyList for item in sublist]), 5)
</code>```

Body:
My Code

import random

MyList = [[1,2,3,4,5,6,7,8],[a,s,d,f,g,h,h],[q,w,e,r,t,y]]
MyListRandom = []
random_number = 5
i=0
while True:
     random_list = randint(0,len(MyList))
     element_random = random.sample(MyList[random_list], 1)
     if element_random[0] not in MyListRandom:
     i = i+1
     MyListRandom.append(element_random[0])
else:
    continue
if(i>=random_number):
    break

if I don't want to use this code to check it

 if element_random[0] not in MyListRandom:
     MyListRandom.append(element_random[0])

Is there a better way more than this if i don't want a duplicates sample?

Body:
From the documentation random.sample(MyList) will give you unique answers from the list's items already. For duplicates in MyList you sample from, you can just make it a set.

Also you don't need the loop for every sample, you can just give it a k argument and it will return k many random samples. So the whole code can be written as:

# I have flatten the whole list into one list
element_random = random.sample(set([item for sublist in MyList for item in sublist]), 5)


问:
Zend Framework: How do I remove the decorators on a Zend Form Hidden Element?
I'm trying to remove the default decorators on a hidden form element. By default, the hidden element is displayed like this:

```<code><dt>Hidden Element Label (if I had set one)</dt>
<dd><input type="hidden" name="foobar" value="1" id="foobar"></dd>
</code>```

I don't want my hidden element to take up space on my page. I want to remove all the default decorators so all I'm left with is the input tag.

```<code><input type="hidden" name="foobar" value="1" id="foobar">
</code>```

How can I achieve this?

答:
Using only a single "ViewHelper" decorator will generate invalid markup if you're still using the
 wrapper. Another approach is outlined in ZF-2718. This adds hidden fields to a subform that is wrapped in a
.

OwnerDisplayName: Andrew

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to remove the default decorators on a hidden form element. By default, the hidden element is displayed like this:

Hidden Element Label (if I had set one)

<input type="hidden" name="foobar" value="1" id="foobar">

I don't want my hidden element to take up space on my page. I want to remove all the default decorators so all I'm left with is the input tag.

<input type="hidden" name="foobar" value="1" id="foobar">

How can I achieve this?

LastEditorDisplayName: Andrew

Body: Using only a single "ViewHelper" decorator will generate invalid markup if you're still using the <dl> wrapper. Another approach is outlined in ZF-2718. This adds hidden fields to a subform that is wrapped in a <dd>.


问:
How to sum up a particular amount of numbers from a list
I would like to sum up a particular amount of numbers from a list.

```<code>openBids = df_1['openBid']
mean = np.mean(openBids)
std = np.std(openBids)
rets = np.log(openBids / openBids.shift(1))
rets.dropna()
round(sum(rets.dropna()), 4) # here i only want to add together the first ten numbers from the list for example
</code>```

Can someone tell me how to do it?

Kind regards

Marcel

答:
You can use python's list slicing (assuming rets.dropna() returns a list). rets.dropna()[:10] will be the first ten from the list.

```<code>round(sum(rets.dropna()[:10]), 4)
</code>```

See more examples of this syntax in the python docs tutorial.

Body:
I would like to sum up a particular amount of numbers from a list.

openBids = df_1['openBid']
mean = np.mean(openBids)
std = np.std(openBids)
rets = np.log(openBids / openBids.shift(1))
rets.dropna()
round(sum(rets.dropna()), 4) # here i only want to add together the first ten numbers from the list for example

Can someone tell me how to do it?

Kind regards

Marcel

Body:
You can use python's list slicing (assuming rets.dropna() returns a list). rets.dropna()[:10] will be the first ten from the list.

round(sum(rets.dropna()[:10]), 4)

See more examples of this syntax in the python docs tutorial.


问:
OnLocationChanged callback is never called
I am trying to get the users current location using the LocationManager.  I have done a lot of research and can't seem to find anyone with the same problem.  The OnLocationChanged callback never seems to be called. Below is my various code and the logcat.

```<code>protected LocationListener locationListener;
protected LocationManager locationManager;
protected Context context;
</code>```

My OnCreate() method

```<code>@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.v(TAG, "IN ON CREATE");

    this.context = getActivity();

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

My registerLocationUpdates method

```<code>void registerLocationUpdates() {
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_LOW);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);

    locationManager = (LocationManager)getActivity().getSystemService(LOCATION_SERVICE);

    provider = locationManager.getBestProvider(criteria, true);

    // Cant get a hold of provider
    if (provider == null) {
        Log.v(TAG, "Provider is null");
        showNoProvider();
        return;
    } else {
        Log.v(TAG, "Provider: " + provider);
    }

    locationListener = new MyLocationListener();

    locationManager.requestLocationUpdates(provider, 1L, 1f, locationListener);

    // connect to the GPS location service
    Location oldLocation = locationManager.getLastKnownLocation(provider);

    if (oldLocation != null)  {
        Log.v(TAG, "Got Old location");
        latitude = Double.toString(oldLocation.getLatitude());
        longitude = Double.toString(oldLocation.getLongitude());
        waitingForLocationUpdate = false;
        getNearbyStores();
    } else {
        Log.v(TAG, "NO Last Location found");
    }
}
</code>```

My LocationListener

```<code>private class MyLocationListener implements LocationListener {

    public void onLocationChanged(Location location) {
        latitude = Double.toString(location.getLatitude());
        longitude = Double.toString(location.getLongitude());

        Log.v(TAG, "IN ON LOCATION CHANGE");

        if (waitingForLocationUpdate) {
            getNearbyStores();
            waitingForLocationUpdate = false;
        }

        locationManager.removeUpdates(this);
    }

    public void onStatusChanged(String s, int i, Bundle bundle) {
        Log.v(TAG, "Status changed: " + s);
    }

    public void onProviderEnabled(String s) {
        Log.e(TAG, "PROVIDER DISABLED: " + s);
    }

    public void onProviderDisabled(String s) {
        Log.e(TAG, "PROVIDER DISABLED: " + s);
    }
}
</code>```

My permissions in the AndroidManifest

```<code><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
</code>```

And finally the logcat after I run my app

```<code>01-25 09:43:10.963: VERBOSE/NearbyListFragment(3060): IN ON CREATE
01-25 09:43:10.963: VERBOSE/LocationManagerService(1329): getProviders
01-25 09:43:10.963: VERBOSE/LocationManagerService(1329): getProviders
01-25 09:43:10.973: VERBOSE/LocationManagerService(1329): getProviders
01-25 09:43:10.983: VERBOSE/NearbyListFragment(3060): Provider: gps
01-25 09:43:10.983: DEBUG/LocationManager(3060): requestLocationUpdates: provider = gps, listener = co.fusionweb.dealsplus.app.NearbyItems$NearbyListFragment$MyLocationListener@46ef4680
01-25 09:43:10.983: DEBUG/GpsLocationProvider(1329): setMinTime 1
01-25 09:43:10.983: VERBOSE/NearbyListFragment(3060): NO Last Location found
01-25 09:43:10.983: VERBOSE/LocationManagerService(1329): _requestLocationUpdates: listener = Receiver{47421e68 Listener android.os.BinderProxy@47421a68}
01-25 09:43:11.003: VERBOSE/countingFragment(3060): IN ON CREATE VIEW
01-25 09:43:11.003: WARN/GpsLocationProvider(1329): Duplicate add listener for co.fusionweb.dealsplus
01-25 09:43:11.013: VERBOSE/ScrollListener(3060): In Constructor
01-25 09:43:11.013: VERBOSE/ScrollListener(3060): Scrolling
01-25 09:43:11.033: DEBUG/GpsLocationProvider(1329): startNavigating
01-25 09:43:11.043: DEBUG/lib_locapi(1329): loc_eng_set_qos_time_out(standalone = 60, agps = 89)
01-25 09:43:11.043: DEBUG/lib_locapi(1329): loc_eng_set_qos_accuracy(accuracy = 50)
01-25 09:43:11.043: VERBOSE/lib_locapi(1329): persist.radio.agps.mode: []
01-25 09:43:11.043: DEBUG/lib_locapi(1329): loc_eng_set_position mode, client = 1, interval = 1, mode = 1
01-25 09:43:11.043: VERBOSE/lib_locapi(1329): loc_eng_ioctl called: client = 1, ioctl_type = 2
01-25 09:43:11.043: VERBOSE/locapi_rpc_glue(1329): loc_ioctl
01-25 09:43:11.043: DEBUG/RPC(1329): written RPC packet size: [96]
01-25 09:43:11.043: DEBUG/RPC(1329): read RPC packet
01-25 09:43:11.043: DEBUG/RPC(1329): read RPC packet size: [28]
01-25 09:43:11.043: VERBOSE/locapi_rpc_glue(1329): loc_api_sync_ioctl: select_id = 0, loc_ioctl returned 0
01-25 09:43:11.043: DEBUG/RPC(1329): read RPC packet
01-25 09:43:11.043: DEBUG/RPC(1329): read RPC packet size: [80]
01-25 09:43:11.043: VERBOSE/locapi_rpc_glue(1329): Callback received: 80 (cb_id=0x5310000 handle=1)
01-25 09:43:11.043: DEBUG/RPC(1329): written RPC packet size: [28]
01-25 09:43:11.043: VERBOSE/lib_locapi(1329): loc_eng_ioctl result: client = 1, ioctl_type = 2, SUCCESS
01-25 09:43:11.043: DEBUG/lib_locapi(1329): loc_eng_start
01-25 09:43:11.043: DEBUG/locapi_rpc_glue(1329): loc_start_fix
01-25 09:43:11.043: DEBUG/RPC(1329): written RPC packet size: [44]
01-25 09:43:11.043: DEBUG/RPC(1329): read RPC packet
01-25 09:43:11.053: DEBUG/RPC(1329): read RPC packet size: [28]
01-25 09:43:11.103: DEBUG/RPC(1329): read RPC packet
01-25 09:43:11.103: DEBUG/RPC(1329): read RPC packet size: [80]
01-25 09:43:11.113: VERBOSE/locapi_rpc_glue(1329): Callback received: 100 (cb_id=0x5310000 handle=1)
01-25 09:43:11.113: VERBOSE/lib_locapi(1329): process_deferred_action: pthread_cond_wait returned
01-25 09:43:11.113: DEBUG/lib_locapi(1329): loc_eng_report_status: GPS_STATUS_SESSION_BEGIN
01-25 09:43:11.113: DEBUG/lib_locapi(1329): loc_eng_report_status: update status
01-25 09:43:11.113: VERBOSE/GpsLocationProvider(1329): reportStatus status: 1
01-25 09:43:11.113: DEBUG/GpsLocationProvider(1329): Acquiring wakelock
01-25 09:43:11.123: DEBUG/RPC(1329): written RPC packet size: [28]
01-25 09:43:11.183: DEBUG/PowerManagerService(1329): New lightsensor value:40, lcdValue:77
01-25 09:43:11.273: DEBUG/RPC(1329): read RPC packet
01-25 09:43:11.273: DEBUG/RPC(1329): read RPC packet size: [80]
01-25 09:43:11.273: VERBOSE/locapi_rpc_glue(1329): Callback received: 100 (cb_id=0x5310000 handle=1)
01-25 09:43:11.273: VERBOSE/lib_locapi(1329): process_deferred_action: pthread_cond_wait returned
01-25 09:43:11.273: DEBUG/lib_locapi(1329): loc_eng_report_status: GPS_STATUS_ENGINE_ON
01-25 09:43:11.273: DEBUG/lib_locapi(1329): loc_eng_report_status: update status
01-25 09:43:11.273: VERBOSE/GpsLocationProvider(1329): reportStatus status: 3
</code>```

And the android SDK location parts of the logcat keep repeating them selves.  I have tried everything that i can think of and have seen on google and stackoverflow.  Als just as a side note i have been able to get it to work on a 2.3 device using the requestSingleUpdate which is available in API 9 and by following the guide  A Deep Dive into Location  but i need it to work on 2.1 or 2.2 and higher using the old SDK. SO if you have any hints or would like to know more please let me know.

答:
If you are trying with NETWORK_PROVIDER, it is really difficult to test:

on Emulator: never work

on Real Device: only getLastKnownLocation() works, to receive onLocationChanged(), you have to use mobile data and go outside with the risk of losing phone from robber :P

I guess the reason is that it just the location of network provider only not your device itself, and the network provider never move, so the onLocationChanged() never call. It might happen only when switching between mobile data and wifi and vice versa. Please correct me if I am wrong.

So I suggest to use GPS_PROVIDER to experiment before considering performance and battery usage. It works nicely on both emulators and real devices. For the best practice: https://developer.android.com/guide/topics/location/strategies.html

It took me several hours to test with NETWORK_PROVIDER without any results, so hopefully my suggestion helpful.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to get the users current location using the LocationManager.  I have done a lot of research and can't seem to find anyone with the same problem.  The OnLocationChanged callback never seems to be called. Below is my various code and the logcat.

protected LocationListener locationListener;
protected LocationManager locationManager;
protected Context context;

My OnCreate() method

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.v(TAG, "IN ON CREATE");

    this.context = getActivity();

    registerLocationUpdates();
}

My registerLocationUpdates method

void registerLocationUpdates() {
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_LOW);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);

    locationManager = (LocationManager)getActivity().getSystemService(LOCATION_SERVICE);

    provider = locationManager.getBestProvider(criteria, true);

    // Cant get a hold of provider
    if (provider == null) {
        Log.v(TAG, "Provider is null");
        showNoProvider();
        return;
    } else {
        Log.v(TAG, "Provider: " + provider);
    }

    locationListener = new MyLocationListener();

    locationManager.requestLocationUpdates(provider, 1L, 1f, locationListener);

    // connect to the GPS location service
    Location oldLocation = locationManager.getLastKnownLocation(provider);

    if (oldLocation != null)  {
        Log.v(TAG, "Got Old location");
        latitude = Double.toString(oldLocation.getLatitude());
        longitude = Double.toString(oldLocation.getLongitude());
        waitingForLocationUpdate = false;
        getNearbyStores();
    } else {
        Log.v(TAG, "NO Last Location found");
    }
}

My LocationListener

private class MyLocationListener implements LocationListener {

    public void onLocationChanged(Location location) {
        latitude = Double.toString(location.getLatitude());
        longitude = Double.toString(location.getLongitude());

        Log.v(TAG, "IN ON LOCATION CHANGE");

        if (waitingForLocationUpdate) {
            getNearbyStores();
            waitingForLocationUpdate = false;
        }

        locationManager.removeUpdates(this);
    }

    public void onStatusChanged(String s, int i, Bundle bundle) {
        Log.v(TAG, "Status changed: " + s);
    }

    public void onProviderEnabled(String s) {
        Log.e(TAG, "PROVIDER DISABLED: " + s);
    }

    public void onProviderDisabled(String s) {
        Log.e(TAG, "PROVIDER DISABLED: " + s);
    }
}

My permissions in the AndroidManifest

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

And finally the logcat after I run my app

01-25 09:43:10.963: VERBOSE/NearbyListFragment(3060): IN ON CREATE
01-25 09:43:10.963: VERBOSE/LocationManagerService(1329): getProviders
01-25 09:43:10.963: VERBOSE/LocationManagerService(1329): getProviders
01-25 09:43:10.973: VERBOSE/LocationManagerService(1329): getProviders
01-25 09:43:10.983: VERBOSE/NearbyListFragment(3060): Provider: gps
01-25 09:43:10.983: DEBUG/LocationManager(3060): requestLocationUpdates: provider = gps, listener = co.fusionweb.dealsplus.app.NearbyItems$NearbyListFragment$MyLocationListener@46ef4680
01-25 09:43:10.983: DEBUG/GpsLocationProvider(1329): setMinTime 1
01-25 09:43:10.983: VERBOSE/NearbyListFragment(3060): NO Last Location found
01-25 09:43:10.983: VERBOSE/LocationManagerService(1329): _requestLocationUpdates: listener = Receiver{47421e68 Listener android.os.BinderProxy@47421a68}
01-25 09:43:11.003: VERBOSE/countingFragment(3060): IN ON CREATE VIEW
01-25 09:43:11.003: WARN/GpsLocationProvider(1329): Duplicate add listener for co.fusionweb.dealsplus
01-25 09:43:11.013: VERBOSE/ScrollListener(3060): In Constructor
01-25 09:43:11.013: VERBOSE/ScrollListener(3060): Scrolling
01-25 09:43:11.033: DEBUG/GpsLocationProvider(1329): startNavigating
01-25 09:43:11.043: DEBUG/lib_locapi(1329): loc_eng_set_qos_time_out(standalone = 60, agps = 89)
01-25 09:43:11.043: DEBUG/lib_locapi(1329): loc_eng_set_qos_accuracy(accuracy = 50)
01-25 09:43:11.043: VERBOSE/lib_locapi(1329): persist.radio.agps.mode: []
01-25 09:43:11.043: DEBUG/lib_locapi(1329): loc_eng_set_position mode, client = 1, interval = 1, mode = 1
01-25 09:43:11.043: VERBOSE/lib_locapi(1329): loc_eng_ioctl called: client = 1, ioctl_type = 2
01-25 09:43:11.043: VERBOSE/locapi_rpc_glue(1329): loc_ioctl
01-25 09:43:11.043: DEBUG/RPC(1329): written RPC packet size: [96]
01-25 09:43:11.043: DEBUG/RPC(1329): read RPC packet
01-25 09:43:11.043: DEBUG/RPC(1329): read RPC packet size: [28]
01-25 09:43:11.043: VERBOSE/locapi_rpc_glue(1329): loc_api_sync_ioctl: select_id = 0, loc_ioctl returned 0
01-25 09:43:11.043: DEBUG/RPC(1329): read RPC packet
01-25 09:43:11.043: DEBUG/RPC(1329): read RPC packet size: [80]
01-25 09:43:11.043: VERBOSE/locapi_rpc_glue(1329): Callback received: 80 (cb_id=0x5310000 handle=1)
01-25 09:43:11.043: DEBUG/RPC(1329): written RPC packet size: [28]
01-25 09:43:11.043: VERBOSE/lib_locapi(1329): loc_eng_ioctl result: client = 1, ioctl_type = 2, SUCCESS
01-25 09:43:11.043: DEBUG/lib_locapi(1329): loc_eng_start
01-25 09:43:11.043: DEBUG/locapi_rpc_glue(1329): loc_start_fix
01-25 09:43:11.043: DEBUG/RPC(1329): written RPC packet size: [44]
01-25 09:43:11.043: DEBUG/RPC(1329): read RPC packet
01-25 09:43:11.053: DEBUG/RPC(1329): read RPC packet size: [28]
01-25 09:43:11.103: DEBUG/RPC(1329): read RPC packet
01-25 09:43:11.103: DEBUG/RPC(1329): read RPC packet size: [80]
01-25 09:43:11.113: VERBOSE/locapi_rpc_glue(1329): Callback received: 100 (cb_id=0x5310000 handle=1)
01-25 09:43:11.113: VERBOSE/lib_locapi(1329): process_deferred_action: pthread_cond_wait returned
01-25 09:43:11.113: DEBUG/lib_locapi(1329): loc_eng_report_status: GPS_STATUS_SESSION_BEGIN
01-25 09:43:11.113: DEBUG/lib_locapi(1329): loc_eng_report_status: update status
01-25 09:43:11.113: VERBOSE/GpsLocationProvider(1329): reportStatus status: 1
01-25 09:43:11.113: DEBUG/GpsLocationProvider(1329): Acquiring wakelock
01-25 09:43:11.123: DEBUG/RPC(1329): written RPC packet size: [28]
01-25 09:43:11.183: DEBUG/PowerManagerService(1329): New lightsensor value:40, lcdValue:77
01-25 09:43:11.273: DEBUG/RPC(1329): read RPC packet
01-25 09:43:11.273: DEBUG/RPC(1329): read RPC packet size: [80]
01-25 09:43:11.273: VERBOSE/locapi_rpc_glue(1329): Callback received: 100 (cb_id=0x5310000 handle=1)
01-25 09:43:11.273: VERBOSE/lib_locapi(1329): process_deferred_action: pthread_cond_wait returned
01-25 09:43:11.273: DEBUG/lib_locapi(1329): loc_eng_report_status: GPS_STATUS_ENGINE_ON
01-25 09:43:11.273: DEBUG/lib_locapi(1329): loc_eng_report_status: update status
01-25 09:43:11.273: VERBOSE/GpsLocationProvider(1329): reportStatus status: 3

And the android SDK location parts of the logcat keep repeating them selves.  I have tried everything that i can think of and have seen on google and stackoverflow.  Als just as a side note i have been able to get it to work on a 2.3 device using the requestSingleUpdate which is available in API 9 and by following the guide  A Deep Dive into Location  but i need it to work on 2.1 or 2.2 and higher using the old SDK. SO if you have any hints or would like to know more please let me know.


问:
Lowercase Dictionary Keys in Swift
I need to convert a Dictionary with mixed case keys in the same exact Dictionary but with only lowercase keys.

Here is my attempt (It works but I found this implementation extremely rough)

```<code>extension Dictionary {
    func lowercaseKeys()->Dictionary<String, AnyObject>{
        var newDictionary = Dictionary<String,AnyObject>()

        for k in keys{
            if let k_string = k as? String{
                newDictionary[k_string.lowercaseString] = self[k] as? AnyObject
            }
        }
        return newDictionary
    }
}
</code>```

Can you suggest a more elegant way to solve this problem?

答:
Arbitur's answer, updated for Swift 3:</p>

```<code>extension Dictionary where Key: ExpressibleByStringLiteral {
    public mutating func lowercaseKeys() {
        for key in self.keys {
            self[String(describing: key).lowercased() as! Key] = self.removeValue(forKey: key)
        }
    }
}
</code>```

Title: Lowercase Dictionary Keys in Swift

Body:
I need to convert a Dictionary with mixed case keys in the same exact Dictionary but with only lowercase keys.

Here is my attempt (It works but I found this implementation extremely rough)

extension Dictionary {
    func lowercaseKeys()->Dictionary<String, AnyObject>{
        var newDictionary = Dictionary<String,AnyObject>()

        for k in keys{
            if let k_string = k as? String{
                newDictionary[k_string.lowercaseString] = self[k] as? AnyObject
            }
        }
        return newDictionary
    }
}

Can you suggest a more elegant way to solve this problem?

Body:
Arbitur's answer, updated for Swift 3:

extension Dictionary where Key: ExpressibleByStringLiteral {
    public mutating func lowercaseKeys() {
        for key in self.keys {
            self[String(describing: key).lowercased() as! Key] = self.removeValue(forKey: key)
        }
    }
}


问:
Why has netty of unspecified version shaded into jar?
The netty version is declared in pom file.

```<code><netty.version>4.0.36.Final</netty.version>
</code>```

The shade plugin of maven is also declared as following:

```<code> <plugin>
    <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-shade-plugin</artifactId>
            <version>2.3</version>
            <configuration>
                <createDependencyReducedPom>false</createDependencyReducedPom>
                <filters>
                    <filter>
                        <artifact>client</artifact>
                        <includes>
                            <include>**/*.class</include>
                        </includes>
                    </filter>
                    <filter>
                        <artifact>*:*</artifact>
                        <excludes>
                            <exclude>META-INF/*.SF</exclude>
                            <exclude>META-INF/*.DSA</exclude>
                            <exclude>META-INF/*.RSA</exclude>
                        </excludes>
                    </filter>
                </filters>
            </configuration>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                    <configuration>
                        <transformers>
                            <transformer
                                    implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                <mainClass>io.Client</mainClass>
                            </transformer>
                        </transformers>
                    </configuration>
                </execution>
            </executions>
  </plugin>
</code>```

But, i found another version of netty was included from compiled log. I can not understand this situation.

```<code>[INFO] --- maven-shade-plugin:2.3:shade (default) @ client ---
[INFO] Including io.netty:netty-all:jar:4.0.36.Final in the shaded jar.
[INFO] Including io.netty:netty:jar:3.7.0.Final in the shaded jar.
[INFO] Including com.fasterxml.jackson.core:jackson-core:jar:2.5.1 in the shaded jar.
[INFO] Including com.fasterxml.jackson.core:jackson-databind:jar:2.5.1 in the shaded jar.
[INFO] Including com.fasterxml.jackson.core:jackson-annotations:jar:2.5.0 in the shaded jar.
</code>```

答:
You can analyze your project's dependency tree to get to know the source of io.netty:netty artifact using -

```<code>mvn dependency:tree
</code>```

Just to reproduce using the specified version and artifact as in your logs -

Including io.netty:netty-all:jar:4.0.36.Final

The following dependency

```<code><dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>4.0.36.Final</version>
</dependency>
</code>```

results into a sample log as follows for me -

```<code>[INFO] --- maven-shade-plugin:2.3:shade (default) @ netty-sample ---
[INFO] Including io.netty:netty-all:jar:4.0.36.Final in the shaded jar.

[INFO] No artifact matching filter client
</code>```

Note: There is no io.netty:netty:jar:3.7.0.Final in the logs.

Body:
The netty version is declared in pom file.

<netty.version>4.0.36.Final</netty.version>

The shade plugin of maven is also declared as following:

 <plugin>
    <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-shade-plugin</artifactId>
            <version>2.3</version>
            <configuration>
                <createDependencyReducedPom>false</createDependencyReducedPom>
                <filters>
                    <filter>
                        <artifact>client</artifact>
                        <includes>
                            <include>**/*.class</include>
                        </includes>
                    </filter>
                    <filter>
                        <artifact>*:*</artifact>
                        <excludes>
                            <exclude>META-INF/*.SF</exclude>
                            <exclude>META-INF/*.DSA</exclude>
                            <exclude>META-INF/*.RSA</exclude>
                        </excludes>
                    </filter>
                </filters>
            </configuration>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                    <configuration>
                        <transformers>
                            <transformer
                                    implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                <mainClass>io.Client</mainClass>
                            </transformer>
                        </transformers>
                    </configuration>
                </execution>
            </executions>
  </plugin>

But, i found another version of netty was included from compiled log. I can not understand this situation.

[INFO] --- maven-shade-plugin:2.3:shade (default) @ client ---
[INFO] Including io.netty:netty-all:jar:4.0.36.Final in the shaded jar.
[INFO] Including io.netty:netty:jar:3.7.0.Final in the shaded jar.
[INFO] Including com.fasterxml.jackson.core:jackson-core:jar:2.5.1 in the shaded jar.
[INFO] Including com.fasterxml.jackson.core:jackson-databind:jar:2.5.1 in the shaded jar.
[INFO] Including com.fasterxml.jackson.core:jackson-annotations:jar:2.5.0 in the shaded jar.

Body:
You can analyze your project's dependency tree to get to know the source of io.netty:netty artifact using -

mvn dependency:tree

Just to reproduce using the specified version and artifact as in your logs -

Including io.netty:netty-all:jar:4.0.36.Final

The following dependency

<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>4.0.36.Final</version>
</dependency>

results into a sample log as follows for me -

[INFO] --- maven-shade-plugin:2.3:shade (default) @ netty-sample ---
[INFO] Including io.netty:netty-all:jar:4.0.36.Final in the shaded jar.

[INFO] No artifact matching filter client

Note: There is no io.netty:netty:jar:3.7.0.Final in the logs.


问:
Using a member variable declared in the constructor in another function in the same class in Javascript
I instantiate this class in a different file by saying RunConfigurationController controller = new RunConfigurationController().

In the constructor, I make a new RunConfigurationView and then set the onclick functionality. Then when I run the program, and execute the cancel button click, I get an error saying that I cannot access Uncaught TypeError: Cannot read property 'getRunConfigurationModal' of undefined.

How can I access the "this" variable which I created in the constructor from another method inside the same class.

```<code>'use babel';

import RunConfigurationView from './run-configuration-view'

export default class RunConfigurationController {

  constructor() {
    this.runConfigurationView = new RunConfigurationView();
    this.runConfigurationView.getUpdateButton().onclick = this.updateButtonClick;
    this.runConfigurationView.getCancelButton().onclick = this.cancelButtonClick;

  }

  updateButtonClick() {

  }

  cancelButtonClick() {
    this.runConfigurationView.getRunConfigurationModal().remove();
  }

  getRunConfigurationView() {
    return this.runConfigurationView;
  }

}
</code>```

答:
It's your binding...adjust these two lines in your constructor

```<code>this.runConfigurationView.getUpdateButton().onclick = this.updateButtonClick.bind(this);
this.runConfigurationView.getCancelButton().onclick = this.cancelButtonClick.bind(this);
</code>```

See here or here for more info

Body:
I instantiate this class in a different file by saying RunConfigurationController controller = new RunConfigurationController().

In the constructor, I make a new RunConfigurationView and then set the onclick functionality. Then when I run the program, and execute the cancel button click, I get an error saying that I cannot access Uncaught TypeError: Cannot read property 'getRunConfigurationModal' of undefined.

How can I access the "this" variable which I created in the constructor from another method inside the same class.

'use babel';

import RunConfigurationView from './run-configuration-view'

export default class RunConfigurationController {

  constructor() {
    this.runConfigurationView = new RunConfigurationView();
    this.runConfigurationView.getUpdateButton().onclick = this.updateButtonClick;
    this.runConfigurationView.getCancelButton().onclick = this.cancelButtonClick;

  }

  updateButtonClick() {

  }

  cancelButtonClick() {
    this.runConfigurationView.getRunConfigurationModal().remove();
  }

  getRunConfigurationView() {
    return this.runConfigurationView;
  }

}

Body:
It's your binding...adjust these two lines in your constructor

this.runConfigurationView.getUpdateButton().onclick = this.updateButtonClick.bind(this);
this.runConfigurationView.getCancelButton().onclick = this.cancelButtonClick.bind(this);

See here or here for more info


问:
Cannot rollback in if block transaction sql
When I executed this stored procedure, I cannot rollback in IF block even the IF statement was right. If the IF statement was right, script still running in the end and there is no rollback at all.

The message: The account id has already used successful register

Msg 3902, Level 16, State 1, Procedure PROC_DANGKY, Line 23

  The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION.

Code:

```<code>CREATE PROCEDURE PROC_REGISTER
    @name nvarchar(30),
    @birth datetime,
    @passport nvarchar(9),
    @address nvarchar(50),
    @phone nvarchar(11),
    @email nvarchar(20),
    @account nvarchar(30),
    @password nvarchar(20)
AS
BEGIN TRAN
    BEGIN TRY
        IF (EXISTS(SELECT * FROM CUSTOMER WHERE ACCOUNT = @account))
        BEGIN
            PRINT N'The account id has already been used'
            ROLLBACK TRAN
        END

        INSERT INTO KHACHHANG
        VALUES (@name, @birth, @passport, @address, @phone, @email, @account, @password)
        PRINT N'Successfully registered'
    END TRY
    BEGIN CATCH
        DECLARE @ErrorMsg VARCHAR(2000)
        SELECT @ErrorMsg = N'Error: ' + ERROR_MESSAGE()
        RAISERROR(@ErrorMsg, 16,1)

        ROLLBACK TRAN

        RETURN
    END CATCH
COMMIT TRAN
</code>```

答:
You can check @@TRANCOUNT before rollback to ckeck if transaction exists:</p>

```<code>CREATE PROC PROC_REGISTER
    @name nvarchar(30),
    @birth datetime,
    @passport nvarchar(9),
    @address nvarchar(50),
    @phone nvarchar(11),
    @email nvarchar(20),
    @account nvarchar(30),
    @password nvarchar(20)

AS
BEGIN TRAN
    BEGIN TRY
        IF (EXISTS(SELECT * FROM CUSTOMER WHERE ACCOUNT = @account))
            BEGIN
                PRINT N'The account id has already used'
                IF (@@TRANCOUNT > 0)
                BEGIN
                    ROLLBACK TRAN
                END
            END
        INSERT INTO KHACHHANG VALUES (@name, @birth, @passport, @address, @phone, @email, @account, @password)
        PRINT N'Successul register'
    END TRY
    BEGIN CATCH
        DECLARE @ErrorMsg VARCHAR(2000)
        SELECT @ErrorMsg = N'Error: ' + ERROR_MESSAGE()
        RAISERROR(@ErrorMsg, 16,1)
        IF (@@TRANCOUNT > 0)
        BEGIN
            ROLLBACK TRAN
        END
        RETURN
    END CATCH
COMMIT TRAN
</code>```

Body:
When I executed this stored procedure, I cannot rollback in IF block even the IF statement was right. If the IF statement was right, script still running in the end and there is no rollback at all.

The message: The account id has already used successful register

Msg 3902, Level 16, State 1, Procedure PROC_DANGKY, Line 23

  The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION.

Code:

CREATE PROCEDURE PROC_REGISTER
    @name nvarchar(30),
    @birth datetime,
    @passport nvarchar(9),
    @address nvarchar(50),
    @phone nvarchar(11),
    @email nvarchar(20),
    @account nvarchar(30),
    @password nvarchar(20)
AS
BEGIN TRAN
    BEGIN TRY
        IF (EXISTS(SELECT * FROM CUSTOMER WHERE ACCOUNT = @account))
        BEGIN
            PRINT N'The account id has already been used'
            ROLLBACK TRAN
        END

        INSERT INTO KHACHHANG
        VALUES (@name, @birth, @passport, @address, @phone, @email, @account, @password)
        PRINT N'Successfully registered'
    END TRY
    BEGIN CATCH
        DECLARE @ErrorMsg VARCHAR(2000)
        SELECT @ErrorMsg = N'Error: ' + ERROR_MESSAGE()
        RAISERROR(@ErrorMsg, 16,1)

        ROLLBACK TRAN

        RETURN
    END CATCH
COMMIT TRAN

Body:
You can check @@TRANCOUNT before rollback to ckeck if transaction exists:

CREATE PROC PROC_REGISTER
    @name nvarchar(30),
    @birth datetime,
    @passport nvarchar(9),
    @address nvarchar(50),
    @phone nvarchar(11),
    @email nvarchar(20),
    @account nvarchar(30),
    @password nvarchar(20)

AS
BEGIN TRAN
    BEGIN TRY
        IF (EXISTS(SELECT * FROM CUSTOMER WHERE ACCOUNT = @account))
            BEGIN
                PRINT N'The account id has already used'
                IF (@@TRANCOUNT > 0)
                BEGIN
                    ROLLBACK TRAN
                END
            END
        INSERT INTO KHACHHANG VALUES (@name, @birth, @passport, @address, @phone, @email, @account, @password)
        PRINT N'Successul register'
    END TRY
    BEGIN CATCH
        DECLARE @ErrorMsg VARCHAR(2000)
        SELECT @ErrorMsg = N'Error: ' + ERROR_MESSAGE()
        RAISERROR(@ErrorMsg, 16,1)
        IF (@@TRANCOUNT > 0)
        BEGIN
            ROLLBACK TRAN
        END
        RETURN
    END CATCH
COMMIT TRAN


问:
Help with a MySQL query
I have the following query:

```<code>SELECT u.uid, pf.title, pv.value FROM users AS u INNER JOIN
profile_values AS pv ON pv.uid = u.uid
INNER JOIN
profile_fields AS pf ON pf.fid = pv.fid
ORDER BY u.uid
</code>```

Which results in:

```<code>uid     title   value
1   First name  Jared
1   Last name   Boo
1   Organization    Acme
1   Website http://acme.com
1   Country Canada
6   First name  Nathan
6   Last name   Foo
</code>```

I am attempting to use this result to create another result set which looks like this:

```<code>uid  First name  Last name  Organization  Website  Country
1    Jared       Boo        Acme          http...  Canada
6    Nathan      Foo
</code>```

Am I going about this correctly?

Thanks in advance

EDIT

Tables:

```<code>CREATE TABLE `users` (
  `uid` int(10) unsigned NOT NULL auto_increment,
  `name` varchar(60) NOT NULL default '',
  `pass` varchar(32) NOT NULL default '',
  `mail` varchar(64) default '',
  `created` int(11) NOT NULL default '0',
  `access` int(11) NOT NULL default '0',
  PRIMARY KEY  (`uid`),
  UNIQUE KEY `name` (`name`),
  KEY `access` (`access`),
  KEY `created` (`created`),
  KEY `mail` (`mail`)
);

CREATE TABLE `profile_fields` (
  `fid` int(11) NOT NULL auto_increment,
  `title` varchar(255) default NULL,
  `name` varchar(128) NOT NULL default '',
  `explanation` text,
  `category` varchar(255) default NULL,
  PRIMARY KEY  (`fid`),
  UNIQUE KEY `name` (`name`),
  KEY `category` (`category`)
);

CREATE TABLE `profile_values` (
  `fid` int(10) unsigned NOT NULL default '0',
  `uid` int(10) unsigned NOT NULL default '0',
  `value` text,
  PRIMARY KEY  (`uid`,`fid`),
  KEY `fid` (`fid`)
);
</code>```

答:
```<code>SELECT u.uid, pf.title, pv.value
FROM users AS u, profile_values AS pv, profile_fields AS pf
WHERE pv.id = u.uid, pf.fid = pv.fid
ORDER BY u.uid
</code>```

Is something like this what your looking for? What do the tables look like in terms of foreign keys? You may want to throw a DISTINCT in right after SELECT.

Title: Help with a MySQL query

Body:
I have the following query:

SELECT u.uid, pf.title, pv.value FROM users AS u INNER JOIN
profile_values AS pv ON pv.uid = u.uid
INNER JOIN
profile_fields AS pf ON pf.fid = pv.fid
ORDER BY u.uid

Which results in:

uid     title   value
1   First name  Jared
1   Last name   Boo
1   Organization    Acme
1   Website http://acme.com
1   Country Canada
6   First name  Nathan
6   Last name   Foo

I am attempting to use this result to create another result set which looks like this:

uid  First name  Last name  Organization  Website  Country
1    Jared       Boo        Acme          http...  Canada
6    Nathan      Foo

Am I going about this correctly?

Thanks in advance

EDIT

Tables:

CREATE TABLE `users` (
  `uid` int(10) unsigned NOT NULL auto_increment,
  `name` varchar(60) NOT NULL default '',
  `pass` varchar(32) NOT NULL default '',
  `mail` varchar(64) default '',
  `created` int(11) NOT NULL default '0',
  `access` int(11) NOT NULL default '0',
  PRIMARY KEY  (`uid`),
  UNIQUE KEY `name` (`name`),
  KEY `access` (`access`),
  KEY `created` (`created`),
  KEY `mail` (`mail`)
);

CREATE TABLE `profile_fields` (
  `fid` int(11) NOT NULL auto_increment,
  `title` varchar(255) default NULL,
  `name` varchar(128) NOT NULL default '',
  `explanation` text,
  `category` varchar(255) default NULL,
  PRIMARY KEY  (`fid`),
  UNIQUE KEY `name` (`name`),
  KEY `category` (`category`)
);

CREATE TABLE `profile_values` (
  `fid` int(10) unsigned NOT NULL default '0',
  `uid` int(10) unsigned NOT NULL default '0',
  `value` text,
  PRIMARY KEY  (`uid`,`fid`),
  KEY `fid` (`fid`)
);

Body:
SELECT u.uid, pf.title, pv.value
FROM users AS u, profile_values AS pv, profile_fields AS pf
WHERE pv.id = u.uid, pf.fid = pv.fid
ORDER BY u.uid

Is something like this what your looking for? What do the tables look like in terms of foreign keys? You may want to throw a DISTINCT in right after SELECT.


问:
What is Ruby's double-colon `::`?
What is this double-colon ::? E.g. Foo::Bar.

I found a definition:

The :: is a unary operator that allows: constants, instance methods and class methods defined within a class or module, to be accessed from anywhere outside the class or module.

What good is scope (private, protected) if you can just use :: to expose anything?

答:
Adding to previous answers, it is valid Ruby to use :: to access instance methods. All the following are valid:

```<code>MyClass::new::instance_method
MyClass::new.instance_method
MyClass.new::instance_method
MyClass.new.instance_method
</code>```

As per best practices I believe only the last one is recommended.

Title: What is Ruby's double-colon `::`?

Body:
Adding to previous answers, it is valid Ruby to use :: to access instance methods. All the following are valid:

MyClass::new::instance_method
MyClass::new.instance_method
MyClass.new::instance_method
MyClass.new.instance_method

As per best practices I believe only the last one is recommended.


问:
echo 'the character - (dash) in the unix command line
This is an extremely simple question that had absolutely nothing related on the internet no matter what.
How do I print a single dash with the echo command? I tried escaping it with '\', '/', '-', '%' and even '#', but it seemed it refused to print a simple, single dash character nonetheless. I tried it with a single quote, double quote or no quote at all, but it seems that this simply isn't possible with echo. Nothing on the man page nor anywhere else, for that matter, can someone please tell me how to do this?
To make things absolutely clear: I want to use echo '-' (or anything like this ) and get a single dash - as output</p>

答:
Try this on zsh:</p>

```<code>[asatsi@stevevai]~% echo - -
-
</code>```

Body:
Try this on zsh:

[asatsi@stevevai]~% echo - -
-