问:
Basic math calculation issue with Arduino
I am doing a basic operation in Arduino and for some reason (this is why I need you) it gives me a totally inappropriate result. Below is the code:

```<code>long init_H_top; //I am declaring it a long to make sure I got enough bytes
init_H_top=251*255/360; //gives me -4 and it should be 178
</code>```

Any idea why it does that?
I am very confused... Thanks!

答:
Your variable may be a long but your constants (251, 255, and 360) are not.

They are int types so will calculate giving an int result which will then be put into the long variable, after any overflow has already done the damage.

Since Arduino has a 16-bit int type, 251 * 255 (64005) will exceed the maximum integer of 32767 and result in behaviour like you're seeing. The value 64005 is -1531 in 16-bit two's complement and, when you divide that by 360, you get about -4.25 which truncates to -4.

You should be using long constants to avoid this:

```<code>init_H_top = 251L * 255L / 360L;
</code>```

Body:
I am doing a basic operation in Arduino and for some reason (this is why I need you) it gives me a totally inappropriate result. Below is the code:

long init_H_top; //I am declaring it a long to make sure I got enough bytes
init_H_top=251*255/360; //gives me -4 and it should be 178

Any idea why it does that?
I am very confused... Thanks!

Body:
Your variable may be a long but your constants (251, 255, and 360) are not.

They are int types so will calculate giving an int result which will then be put into the long variable, after any overflow has already done the damage.

Since Arduino has a 16-bit int type, 251 * 255 (64005) will exceed the maximum integer of 32767 and result in behaviour like you're seeing. The value 64005 is -1531 in 16-bit two's complement and, when you divide that by 360, you get about -4.25 which truncates to -4.

You should be using long constants to avoid this:

init_H_top = 251L * 255L / 360L;


来源: stackexchange

问:
Python2.6+ code parser
Is there a parser that:

is able to parse Python2.6+ code, and

can be run in Python2.5 (python-only, no C extensions allowed)?

NOTE: This is somewhat related to my previous quostion about class decorators.

答: Yes, lib2to3 can, all you need to do is to provide it with the right Grammar file (get the source code for the Python you want and copy Grammar/Grammar).

ContentLicense: CC BY-SA 2.5

Title: Python2.6+ code parser


问:
How can I align these elements side by side?
I'm having difficulties in aligning these elements side by side, anyway this—

—is how it looks so far, but I want it look like this:

.reviewprofile {
  background-color: transparent;
  border: none;
  margin-top: 5em;
}

.reviewentry {
  display: inline-block;
  font-family: 'Abhaya Libre', Times, Serif;
  font-size: 0.8em;
  font-weight: 400;
  color: #5e5e5e;
  text-align: left;
  padding-left: 3.5em;
  margin: 0;
}

.commbutton button {
  float: left;
}

.starsrev {
  padding-left: 2.8em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="commsec">
  <div class="commbutton">
    <button class="reviewprofile"><img src="img/reviewprofile.png">  </button>
  </div>

  <div class="commentry">
    <p class="reviewentry">Cras ultricies dolor ac justo scelerisque, sit amet imperdiet<br> purus placerat.</p>
    <img class="starsrev" src="img/stars.png" alt="stars" />
  </div>
</div></code>```

答:
flex on the parent will create this layout with your existing markup. Here's a visual guide for help with syntax/options https://css-tricks.com/snippets/css/a-guide-to-flexbox/

.reviewprofile {
  background-color: transparent;
  border: none;
}

.reviewentry {
  font-family: 'Abhaya Libre', Times, Serif;
  font-size: 0.8em;
  font-weight: 400;
  color: #5e5e5e;
  text-align: left;
  margin: 0;
}

.commsec {
  display: flex;
  align-items: center; /* this will affect vertical alignment */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="commsec">
  <div class="commbutton">
    <button class="reviewprofile"><img src="http://cdn.quilt.janrain.com/2.1.2/profile_default.png">  </button>
  </div>

  <div class="commentry">
    <p class="reviewentry">Cras ultricies dolor ac justo scelerisque, sit amet imperdiet<br> purus placerat.</p>
    <img style="max-width: 100px" class="starsrev" src="http://www.moviesmacktalk.com/news/wp-content/uploads/2013/11/2.5-Stars.jpg" alt="stars" />
  </div>
</div></code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm having difficulties in aligning these elements side by side, anyway this—

—is how it looks so far, but I want it look like this:

.reviewprofile {
  background-color: transparent;
  border: none;
  margin-top: 5em;
}

.reviewentry {
  display: inline-block;
  font-family: 'Abhaya Libre', Times, Serif;
  font-size: 0.8em;
  font-weight: 400;
  color: #5e5e5e;
  text-align: left;
  padding-left: 3.5em;
  margin: 0;
}

.commbutton button {
  float: left;
}

.starsrev {
  padding-left: 2.8em;
}

    <button class="reviewprofile">  </button>

Cras ultricies dolor ac justo scelerisque, sit amet imperdiet
 purus placerat.

Body:
flex on the parent will create this layout with your existing markup. Here's a visual guide for help with syntax/options https://css-tricks.com/snippets/css/a-guide-to-flexbox/

.reviewprofile {
  background-color: transparent;
  border: none;
}

.reviewentry {
  font-family: 'Abhaya Libre', Times, Serif;
  font-size: 0.8em;
  font-weight: 400;
  color: #5e5e5e;
  text-align: left;
  margin: 0;
}

.commsec {
  display: flex;
  align-items: center; /* this will affect vertical alignment */
}

<div class="commsec">
  <div class="commbutton">
    <button class="reviewprofile"><img src="http://cdn.quilt.janrain.com/2.1.2/profile_default.png">  </button>
  </div>

  <div class="commentry">
    <p class="reviewentry">Cras ultricies dolor ac justo scelerisque, sit amet imperdiet<br> purus placerat.</p>
    <img style="max-width: 100px" class="starsrev" src="http://www.moviesmacktalk.com/news/wp-content/uploads/2013/11/2.5-Stars.jpg" alt="stars" />
  </div>
</div>

ContentLicense: CC BY-SA 3.0


问:
How can I find the first occurrence in a string that is not numeric in java
I'm working on my own method in Java that will be able to calculate math equations given a string. Basically my calculator gets something like "698+33-47*2".
I want to split the parts (using substring and finding the characters '+', '-', '*', '/') but I'm not sure how to find the first non numeric character. My method is like this so far:</p>

```<code>public void DoEquation() {
  String s = storedData.getText() + data.getText();
  s = s.replaceAll(" ", "");

  ArrayList<String> list = new ArrayList<>();
  boolean checking = true;
  while (checking) {
    if (!s.contains("+") && !s.contains("-") && !s.contains("*") && !s.contains("/") {
      checking = false;
      break;
    }
    // Logic for extracting the numbers into the list
    // Then extract the mathamatical sign and place into list
  }
  System.out.println(list); // For testing
}
</code>```

答:
You can use regex like

String arr1[]=temp.split("[^0-9]+");

String arr2[]=temp.split("[0-9]+");

The first one will return all numbers in array as String, while second will return all operation symbols with the first element of array as null

```<code>eg: Input :-"698+33-47*2"
Output :- arr1=["698","33","47","2"]
arr2=[,"+","-","*"]
</code>```

Body:
I'm working on my own method in Java that will be able to calculate math equations given a string. Basically my calculator gets something like "698+33-47*2".
I want to split the parts (using substring and finding the characters '+', '-', '*', '/') but I'm not sure how to find the first non numeric character. My method is like this so far:

public void DoEquation() {
  String s = storedData.getText() + data.getText();
  s = s.replaceAll(" ", "");

  ArrayList<String> list = new ArrayList<>();
  boolean checking = true;
  while (checking) {
    if (!s.contains("+") && !s.contains("-") && !s.contains("*") && !s.contains("/") {
      checking = false;
      break;
    }
    // Logic for extracting the numbers into the list
    // Then extract the mathamatical sign and place into list
  }
  System.out.println(list); // For testing
}

Body:
You can use regex like

String arr1[]=temp.split("[^0-9]+");

String arr2[]=temp.split("[0-9]+");

The first one will return all numbers in array as String, while second will return all operation symbols with the first element of array as null

eg: Input :-"698+33-47*2"
Output :- arr1=["698","33","47","2"]
arr2=[,"+","-","*"]


问:
how to create an array of list of pair in C++
I want to use an array of list of pairs to represent a directed weighted graph using adjacent list

```<code>class Graph{
int n_v;
list<pair<int, int> > *adj;
public:
Graph(int _n_v){
    n_v = _n_v;
    adj = new list<pair<int, int> >[n_v];
}
</code>```

but the compiler raised an error:

```<code>class list<pair<int, int>> is not compatible with list<int, int>>
</code>```

how to solve with this problem?

答:
try this, so simple and easy:</p>

```<code>std::pair <int, int> pair_array[MAX_NUMBER];

for(int i=0; i<MAX_NUMBER; ++i)
{
  //...
  func(i,a,b);
}

void func(int i, int a, int b)
{
  pair_array[i] = std::make_pair(a,b);
}
</code>```

Body:
I want to use an array of list of pairs to represent a directed weighted graph using adjacent list

class Graph{
int n_v;
list<pair<int, int> > *adj;
public:
Graph(int _n_v){
    n_v = _n_v;
    adj = new list<pair<int, int> >[n_v];
}

but the compiler raised an error:

class list<pair<int, int>> is not compatible with list<int, int>>

how to solve with this problem?

Body:
try this, so simple and easy:

std::pair <int, int> pair_array[MAX_NUMBER];

for(int i=0; i<MAX_NUMBER; ++i)
{
  //...
  func(i,a,b);
}

void func(int i, int a, int b)
{
  pair_array[i] = std::make_pair(a,b);
}


问:
Suppress only the actual make command and final print statement
I have a program that outputs things--numbers--to stdout.

The program runs with make run input.txt 0.87 > output_file in an auto-grader (this is for an assignment). The program must run this way (even though it is not really supposed to be possible for a make file).

However, I got it working with the help of a SO question on here. Here is my makefile:

```<code>pr.exe : main.cpp
    g++ -std=c++11 $^ -o $@

run:
    @./pr.exe $(filter-out $@,$(MAKECMDGOALS))

%:
    @:

compile : pr.exe
.PHONY : compile
</code>```

There is just one problem: the command make run input.txt 0.87 outputs, in addition to the program output, the final line:

```<code>make: 'input.txt' is up to date.
</code>```

How do I suppress this line in my make file such that only the program output is redirected into the file?

It must run properly with only the following command (no make arguments, nada):

```<code>make run input.txt 0.87 > some_output_file.txt
</code>```

答:
The printing of message is disabled by -s option of make:

https://github.com/mturk/gnumake/blob/9c3fecf4dd76a8c802055d9bd3689d0c6c5d6167/remake.c#L229

```<code>  if (!rebuilding_makefiles
  /* If the update_status is zero, we updated successfully
     or not at all.  G->changed will have been set above if
     any commands were actually started for this goal.  */
  && file->update_status == 0 && !g->changed
  /* Never give a message under -s or -q.  */
  && !silent_flag && !question_flag)
    message (1, ((file->phony || file->cmds == 0)
             ? _("Nothing to be done for '%s'.")
             : _("'%s' is up to date.")),
         file->name);
</code>```

The silent_flag is set by -s command line option of make:

https://github.com/mturk/gnumake/blob/9c3fecf4dd76a8c802055d9bd3689d0c6c5d6167/main.c#L412

```<code>/* Nonzero means do not print commands to be executed (-s).  */

int silent_flag;
{ 's', flag, &silent_flag, 1, 1, 0, 0, 0, "silent" },
</code>```

And also it is set in https://github.com/mturk/gnumake/blob/9c3fecf4dd76a8c802055d9bd3689d0c6c5d6167/file.c#L752

```<code>  f = lookup_file (".SILENT");
  if (f != 0 && f->is_target)
    {
      if (f->deps == 0)
        silent_flag = 1;
      else
        for (d = f->deps; d != 0; d = d->next)
          for (f2 = d->file; f2 != 0; f2 = f2->prev)
            f2->command_flags |= COMMANDS_SILENT;
    }
</code>```

This is parsing of .SILENT special target documented in https://www.gnu.org/software/make/manual/html_node/Special-Targets.html

.SILENT

If you specify prerequisites for .SILENT, then make will not print the
  recipe used to remake those particular files before executing them.
  The recipe for .SILENT is ignored.

If mentioned as a target with no prerequisites, .SILENT says not to
  print any recipes before executing them. This usage of ‘.SILENT’ is
  supported only for historical compatibility. We recommend you use the
  more selective ways to silence specific recipes. See Recipe Echoing.
  If you want to silence all recipes for a particular run of make, use
  the ‘-s’ or ‘--silent’ option (see Options Summary).

So, try to add .SILENT special target to your Makefile without any additional prerequisites. (Solution is not tested by me.)

```<code>.SILENT:
</code>```

Body:
I have a program that outputs things--numbers--to stdout.

The program runs with make run input.txt 0.87 > output_file in an auto-grader (this is for an assignment). The program must run this way (even though it is not really supposed to be possible for a make file).

However, I got it working with the help of a SO question on here. Here is my makefile:

pr.exe : main.cpp
    g++ -std=c++11 $^ -o $@

run:
    @./pr.exe $(filter-out $@,$(MAKECMDGOALS))

%:
    @:

compile : pr.exe
.PHONY : compile

There is just one problem: the command make run input.txt 0.87 outputs, in addition to the program output, the final line:

make: 'input.txt' is up to date.

How do I suppress this line in my make file such that only the program output is redirected into the file?

It must run properly with only the following command (no make arguments, nada):

make run input.txt 0.87 > some_output_file.txt

Body:
The printing of message is disabled by -s option of make:

https://github.com/mturk/gnumake/blob/9c3fecf4dd76a8c802055d9bd3689d0c6c5d6167/remake.c#L229

  if (!rebuilding_makefiles
  /* If the update_status is zero, we updated successfully
     or not at all.  G->changed will have been set above if
     any commands were actually started for this goal.  */
  && file->update_status == 0 && !g->changed
  /* Never give a message under -s or -q.  */
  && !silent_flag && !question_flag)
    message (1, ((file->phony || file->cmds == 0)
             ? _("Nothing to be done for '%s'.")
             : _("'%s' is up to date.")),
         file->name);

The silent_flag is set by -s command line option of make:

https://github.com/mturk/gnumake/blob/9c3fecf4dd76a8c802055d9bd3689d0c6c5d6167/main.c#L412

/* Nonzero means do not print commands to be executed (-s).  */

int silent_flag;
{ 's', flag, &silent_flag, 1, 1, 0, 0, 0, "silent" },

And also it is set in https://github.com/mturk/gnumake/blob/9c3fecf4dd76a8c802055d9bd3689d0c6c5d6167/file.c#L752

  f = lookup_file (".SILENT");
  if (f != 0 && f->is_target)
    {
      if (f->deps == 0)
        silent_flag = 1;
      else
        for (d = f->deps; d != 0; d = d->next)
          for (f2 = d->file; f2 != 0; f2 = f2->prev)
            f2->command_flags |= COMMANDS_SILENT;
    }

This is parsing of .SILENT special target documented in https://www.gnu.org/software/make/manual/html_node/Special-Targets.html

.SILENT

If you specify prerequisites for .SILENT, then make will not print the
  recipe used to remake those particular files before executing them.
  The recipe for .SILENT is ignored.

If mentioned as a target with no prerequisites, .SILENT says not to
  print any recipes before executing them. This usage of ‘.SILENT’ is
  supported only for historical compatibility. We recommend you use the
  more selective ways to silence specific recipes. See Recipe Echoing.
  If you want to silence all recipes for a particular run of make, use
  the ‘-s’ or ‘--silent’ option (see Options Summary).

So, try to add .SILENT special target to your Makefile without any additional prerequisites. (Solution is not tested by me.)

.SILENT:


问:
How to wait until thread is completed in android
I have this method updatePosts() that needs to run inside of a thread. it looks like this

```<code>public void updatePosts(){
    new Thread(){
        public void run(){
            posts.addAll(pholder.fetchPosts());
            System.out.println("size of posts is " + posts.size());

            // UI elements should be accessed only in
            // the primary thread, so we must use the
            // handler here.

        }
    }.start();
}
</code>```

It is literally updating the List called "posts". I have this in my onCreate. The problem is, since it is running in a separate thread, it does not complete before my ImageAdapter needs to use the "posts" List.

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

    GridView gridview = (GridView) findViewById(R.id.gridview);
    gridview.setAdapter(new ImageAdapter(this, posts));

    gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v,
                                int position, long id) {
            Toast.makeText(MainActivity.this, "" + position,
                    Toast.LENGTH_SHORT).show();
        }
    });

}
</code>```

What options do I have to ensure that the updatePosts can finish before the ImageAdapter get created?

答:
You should use an AsyncTask or any other mechanism that lets you offload a task to a background thread with a callback to the UI on completion.

```<code>private class BackgroundTask extends AsyncTask<Void, Void, List<Post>> {

    @Override
    protected List<Post> doInBackground(Void... params) {
        // TODO
        return posts;
    }

    @Override
    protected void onPostExecute(List<Post> posts) {
        // TODO: update UI
    }
}
</code>```

Another option is to use RxJava,

```<code>        Observable
                .fromCallable(new Callable<List<Post>>() {
                    @Override
                    public List<Post> call() throws Exception {
                        // TODO: get posts
                        return posts;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(posts -> {
                    // TODO: update UI
                }, throwable -> {
                    // TODO
                })
</code>```

Body:
I have this method updatePosts() that needs to run inside of a thread. it looks like this

public void updatePosts(){
    new Thread(){
        public void run(){
            posts.addAll(pholder.fetchPosts());
            System.out.println("size of posts is " + posts.size());

            // UI elements should be accessed only in
            // the primary thread, so we must use the
            // handler here.

        }
    }.start();
}

It is literally updating the List called "posts". I have this in my onCreate. The problem is, since it is running in a separate thread, it does not complete before my ImageAdapter needs to use the "posts" List.

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

    GridView gridview = (GridView) findViewById(R.id.gridview);
    gridview.setAdapter(new ImageAdapter(this, posts));

    gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v,
                                int position, long id) {
            Toast.makeText(MainActivity.this, "" + position,
                    Toast.LENGTH_SHORT).show();
        }
    });

}

What options do I have to ensure that the updatePosts can finish before the ImageAdapter get created?

Body:
You should use an AsyncTask or any other mechanism that lets you offload a task to a background thread with a callback to the UI on completion.

private class BackgroundTask extends AsyncTask<Void, Void, List<Post>> {

    @Override
    protected List<Post> doInBackground(Void... params) {
        // TODO
        return posts;
    }

    @Override
    protected void onPostExecute(List<Post> posts) {
        // TODO: update UI
    }
}

Another option is to use RxJava,

        Observable
                .fromCallable(new Callable<List<Post>>() {
                    @Override
                    public List<Post> call() throws Exception {
                        // TODO: get posts
                        return posts;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(posts -> {
                    // TODO: update UI
                }, throwable -> {
                    // TODO
                })


问:
Rails 4 throws pending migrations error even if there are no pending migrations
I recently upgraded my app from Rails 3.2.15 to Rails 4.0.4 and rake test fails throwing:

```<code>You have 161 pending migrations:
  20111126090934 DeviseCreateUsers
  20111126195631 AddUsernameToUsers
  20111128012039 CreateLocations
  20111129051416 AddConfirmableToDevise
...
Run `rake db:migrate` to update your database then try again.
</code>```

I am sure, I don't have any pending migrations and the schema_migrations table is up-to date with all the migration version numbers. Also,

```<code>[2] pry(main)> ActiveRecord::Migration.check_pending!
  ActiveRecord::SchemaMigration Load (0.4ms)  SELECT `schema_migrations`.* FROM `schema_migrations`
=> nil
[3] pry(main)>
</code>```

Since, this is development environment I've also tried to reset db with:

```<code>$> rake db:migrate:reset
</code>```

I am in the process of moving my app from Rails 3.2.15 to Rails 4.0.4. I am at a loss here, not understanding what is happening.

```<code>$> rake db:migrate:status

Status   Migration ID    Migration Name
--------------------------------------------------
   up     20111126090934  ********** NO FILE **********
   up     20111126195631  ********** NO FILE **********
   up     20111128012039  ********** NO FILE **********
   up     20111129051416  ********** NO FILE **********
...
</code>```

答:
To add to Syed's answer:

Instead of removing the subfolders in db/migrate/, you can also rename them to start with a '.'. This worked for me with activerecord 3.2.

Ex: rename db/migrate/archive/ to db/migrate/.archive/

Body:
I recently upgraded my app from Rails 3.2.15 to Rails 4.0.4 and rake test fails throwing:

You have 161 pending migrations:
  20111126090934 DeviseCreateUsers
  20111126195631 AddUsernameToUsers
  20111128012039 CreateLocations
  20111129051416 AddConfirmableToDevise
...
Run `rake db:migrate` to update your database then try again.

I am sure, I don't have any pending migrations and the schema_migrations table is up-to date with all the migration version numbers. Also,

[2] pry(main)> ActiveRecord::Migration.check_pending!
  ActiveRecord::SchemaMigration Load (0.4ms)  SELECT `schema_migrations`.* FROM `schema_migrations`
=> nil
[3] pry(main)>

Since, this is development environment I've also tried to reset db with:

$> rake db:migrate:reset

I am in the process of moving my app from Rails 3.2.15 to Rails 4.0.4. I am at a loss here, not understanding what is happening.

$> rake db:migrate:status

Status   Migration ID    Migration Name
--------------------------------------------------
   up     20111126090934  ********** NO FILE **********
   up     20111126195631  ********** NO FILE **********
   up     20111128012039  ********** NO FILE **********
   up     20111129051416  ********** NO FILE **********
...


问:
Bootstrap navbar moves when I change to another section
I made my first Wordpress for learning purposes. I have downloaded Themekraft, and I added my own customized bootstrap header navbar, because I want to customize as much as I can.

I have some sections (only "inicio" and "articulos" are working), but when there is an article with photo (sometimes without photo happens the same), I have realised that blue navbar moves.

I tried to fix it in many different ways (adding a max width for the body
and navbar, deleting a lot of margins and/or paddings...), but I have only discovered that it is a problem of paddings... I think.

I mean, when I add, for example, a padding-top:10px for the body, everything seems to be ok... until I have an article or two. When it happens, it seems i have to add more padding-top on the body in order to "fix" the problem.

I have searched on SO suggestions, looking for some clues, but I found nothing.

Bootstrap navbar moves right on scroll

Bootstrap navbar covers top of section when linked

What could I do? I have uploaded the site to a server so you can check it.

http://pruebaint.esy.es/

答:
As far as I can see it the issue is not any of your padding. Its the scroll bar that is causing the problem as the content moves somewhat to the left. If your page has lesser content without vertical scrolls you will not see the nav moving.

Is there any other problem that you see apart from horizontal movement?


问:
I am getting UnboundLocalError because I have the same variable inside functions and in main code
I am having a nightmare, I have created a code in Python to simulate a virtual queue.

The code is simplistic but should work, except for the reoccurring 'UnboundLocalError' I keep getting.

I think the issue is having 'aList' as a parameter for functions and having the variable in the main code as well as within def functions.

The code isn't that long and can be found on this link.

Please can somebody help? I've tried adding 'global aList' but it didn't solve it.

Thanks very much for any assistance.

Snapshot of code below :

```<code>def aRemove(aList):
    newlist = []
    for i in range(1,len(aList)):
        newlist.append(aList[i])
    aList = newlist
    return (aList)

user_request()
aList = ["mark","jon","peter"]
aList = (aRemove(aList))
print(aList)
</code>```

答:
The error you're seeing isn't caused by the code snippet you've posted, but rather the user_request function (from your pastebin code). In it, you're trying to reference the global aList variable, but you're also reassigning a local variable called aList.

To attempt to paraphrase what's happening, python assumes aRemove(aList) is referring to the local aList variable, which doesn't exist yet.

You can fix this in two ways:

add global aList within your function to tell python that your local aList is the same as the global aList:

```<code>def user_request():
    global aList
    order = input("What would you like to do P | A | N | L | M | Q \n")
    while True:
        if order == 'P':
            aPrint()
        elif order == 'A':
            useradd = input("what would you like to add to the queue?")
            aAdd(useradd)
        elif order == 'N':
            aList = (aRemove(aList))
        elif order == 'L':
            aList = (aLeave(aList,input("What would you like to remove from the queue?")))
        elif order == 'M':
            aLocation()
        elif order == 'Q':
            aQuit()
</code>```

Or, rename your local aList variable so that it no longer collides with the global variable:

```<code>def user_request():
    order = input("What would you like to do P | A | N | L | M | Q \n")
    while True:
        if order == 'P':
            aPrint()
        elif order == 'A':
            useradd = input("what would you like to add to the queue?")
            aAdd(useradd)
        elif order == 'N':
            bList = (aRemove(aList))
        elif order == 'L':
            bList = (aLeave(aList,input("What would you like to remove from the queue?")))
        elif order == 'M':
            aLocation()
        elif order == 'Q':
            aQuit()
</code>```

Body:
I am having a nightmare, I have created a code in Python to simulate a virtual queue.

The code is simplistic but should work, except for the reoccurring 'UnboundLocalError' I keep getting.

I think the issue is having 'aList' as a parameter for functions and having the variable in the main code as well as within def functions.

The code isn't that long and can be found on this link.

Please can somebody help? I've tried adding 'global aList' but it didn't solve it.

Thanks very much for any assistance.

Snapshot of code below :

def aRemove(aList):
    newlist = []
    for i in range(1,len(aList)):
        newlist.append(aList[i])
    aList = newlist
    return (aList)

user_request()
aList = ["mark","jon","peter"]
aList = (aRemove(aList))
print(aList)

Body:
The error you're seeing isn't caused by the code snippet you've posted, but rather the user_request function (from your pastebin code). In it, you're trying to reference the global aList variable, but you're also reassigning a local variable called aList.

To attempt to paraphrase what's happening, python assumes aRemove(aList) is referring to the local aList variable, which doesn't exist yet.

You can fix this in two ways:

add global aList within your function to tell python that your local aList is the same as the global aList:

def user_request():
    global aList
    order = input("What would you like to do P | A | N | L | M | Q \n")
    while True:
        if order == 'P':
            aPrint()
        elif order == 'A':
            useradd = input("what would you like to add to the queue?")
            aAdd(useradd)
        elif order == 'N':
            aList = (aRemove(aList))
        elif order == 'L':
            aList = (aLeave(aList,input("What would you like to remove from the queue?")))
        elif order == 'M':
            aLocation()
        elif order == 'Q':
            aQuit()

Or, rename your local aList variable so that it no longer collides with the global variable:

def user_request():
    order = input("What would you like to do P | A | N | L | M | Q \n")
    while True:
        if order == 'P':
            aPrint()
        elif order == 'A':
            useradd = input("what would you like to add to the queue?")
            aAdd(useradd)
        elif order == 'N':
            bList = (aRemove(aList))
        elif order == 'L':
            bList = (aLeave(aList,input("What would you like to remove from the queue?")))
        elif order == 'M':
            aLocation()
        elif order == 'Q':
            aQuit()


问:
Deleting Blobs from azure storage mvc
When trying to delete, or copy a blob from my Azure storage, after successfully uploading it, I get the following 404 error. I cannot see why it is not finding the blob from my storage system, due to successfull upload and successfull downloading. Here is my code to delete that does not work;
I tried setting the "            CloudBlockBlob blob = container.GetBlockBlobReference(path);
" to a file I knew was there "2020Resume.pdf" and it still didnt work

```<code>// GET: DocumentUps/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            DocumentUps documentUps = db.DocumentUps.Find(id);
            Distributee distributees = db.Distributees.Find(id);
            if (documentUps == null)
            {
                return HttpNotFound();
            }
            return View(documentUps);
        }

        // POST: DocumentUps/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        DocumentUps documentUps = db.DocumentUps.Find(id);
        Distributee distributees = db.Distributees.Find(id);

        string attachmnt = documentUps.Attachment.ToString();
        if (attachmnt.Contains('.'))
            attachmnt = attachmnt.Substring(0, attachmnt.LastIndexOf('.'));

        var fileName = documentUps.DocumentId.ToString() + documentUps.RevisionId.ToString() + attachmnt;

        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("filestorageideagen_AzureStorageConnectionString"));
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
        CloudBlobContainer container = blobClient.GetContainerReference("documentuploader");
        CloudBlockBlob blob = container.GetBlockBlobReference(fileName);
        blob.Delete();

        if (distributees != null)
        {
            db.Distributees.Remove(distributees);
        }
        db.DocumentUps.Remove(documentUps);
        db.SaveChanges();

        return RedirectToAction("Index");
    }
</code>```

The error

```<code>Server Error in '/' Application.

The remote server returned an error: (404) Not Found.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Net.WebException: The remote server returned an error: (404) Not Found.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[WebException: The remote server returned an error: (404) Not Found.]
   System.Net.HttpWebRequest.GetResponse() +1399
   Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync(RESTCommand`1 cmd, IRetryPolicy policy, OperationContext operationContext) +1150

[StorageException: The remote server returned an error: (404) Not Found.]
   Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync(RESTCommand`1 cmd, IRetryPolicy policy, OperationContext operationContext) +4559
   Microsoft.WindowsAzure.Storage.Blob.CloudBlob.Delete(DeleteSnapshotsOption deleteSnapshotsOption, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) +62
   Integrated_Project.Controllers.MyDocumentUpsController.DeleteConfirmed(Int32 id) +336
   lambda_method(Closure , ControllerBase , Object[] ) +97
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +157
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
   System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22
   System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
   System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +50
   System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +225
   System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +26
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36
   System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9765121
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
</code>```

答:
The parameters of GetBlockBlobReference is blob name. So please try to use blob name instead of path.

CloudBlockBlob blob = container.GetBlockBlobReference(fileName);

Title: Deleting Blobs from azure storage mvc

Body:
When trying to delete, or copy a blob from my Azure storage, after successfully uploading it, I get the following 404 error. I cannot see why it is not finding the blob from my storage system, due to successfull upload and successfull downloading. Here is my code to delete that does not work;
I tried setting the "            CloudBlockBlob blob = container.GetBlockBlobReference(path);
" to a file I knew was there "2020Resume.pdf" and it still didnt work

// GET: DocumentUps/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            DocumentUps documentUps = db.DocumentUps.Find(id);
            Distributee distributees = db.Distributees.Find(id);
            if (documentUps == null)
            {
                return HttpNotFound();
            }
            return View(documentUps);
        }

        // POST: DocumentUps/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        DocumentUps documentUps = db.DocumentUps.Find(id);
        Distributee distributees = db.Distributees.Find(id);

        string attachmnt = documentUps.Attachment.ToString();
        if (attachmnt.Contains('.'))
            attachmnt = attachmnt.Substring(0, attachmnt.LastIndexOf('.'));

        var fileName = documentUps.DocumentId.ToString() + documentUps.RevisionId.ToString() + attachmnt;

        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("filestorageideagen_AzureStorageConnectionString"));
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
        CloudBlobContainer container = blobClient.GetContainerReference("documentuploader");
        CloudBlockBlob blob = container.GetBlockBlobReference(fileName);
        blob.Delete();

        if (distributees != null)
        {
            db.Distributees.Remove(distributees);
        }
        db.DocumentUps.Remove(documentUps);
        db.SaveChanges();

        return RedirectToAction("Index");
    }

The error

Server Error in '/' Application.

The remote server returned an error: (404) Not Found.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Net.WebException: The remote server returned an error: (404) Not Found.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[WebException: The remote server returned an error: (404) Not Found.]
   System.Net.HttpWebRequest.GetResponse() +1399
   Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync(RESTCommand`1 cmd, IRetryPolicy policy, OperationContext operationContext) +1150

[StorageException: The remote server returned an error: (404) Not Found.]
   Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync(RESTCommand`1 cmd, IRetryPolicy policy, OperationContext operationContext) +4559
   Microsoft.WindowsAzure.Storage.Blob.CloudBlob.Delete(DeleteSnapshotsOption deleteSnapshotsOption, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) +62
   Integrated_Project.Controllers.MyDocumentUpsController.DeleteConfirmed(Int32 id) +336
   lambda_method(Closure , ControllerBase , Object[] ) +97
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +157
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
   System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22
   System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
   System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +50
   System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +225
   System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +26
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36
   System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9765121
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155


问:
SQL Query Java Net Beans
Basically I have a table name java_db.Customer with the columns CustomerID,
Name, Address and FinanceOK.

Basically I want to write a simple query that says if FinanceOK = true JOptionPane.ShowMessage "Finance Accepted"

Otherwise FinanceOK = False JOptionPane.ShowMessage "Finance Declined".

What is the the best way to go about writing this query?

答:
Now, there's a lot of information in your post that is missing but down and dirty here is how you might accomplish the task:

```<code>long customerID_Variable = 232;   // .... whatever you have to provide customer ID number ....
String customerName = "John Doe"; // .... whatever you have to provide customer name ....
boolean financeOK = false;   // default financing approval flag
String message = "Finance Declined!"; //default message

// Catch SQLException if any...
try {
    // Use whatever your connection string might be
    // to connect to your particular Database....
    Connection conn = DriverManager.getConnection("jdbc:derby:c:/databases/salesdb jdbc:derby:salesdb");
    conn.setAutoCommit(false);

    // The SQL query string...
    String sql = "SELECT FinanceOK FROM Customer WHERE CustomerID = " + customerID_Variable + ";";
    // Although it is best to use the Customer ID  to reference a
    // particular Customer you may prefer to to use the Customer
    // name and if so then use the query string below instead...
    // String sql = "SELECT FinanceOK FROM Customer WHERE Name = '" + customerName + "';";

    // Execute the SQL query...
    PreparedStatement stmt = conn.prepareStatement(sql);
    ResultSet rs = stmt.executeQuery();

    //Retrieve the data from the query result set...
    while (rs.next()) {
        financeOK = rs.getBoolean("FinanceOK");
    }

    //Close everything...
    rs.close();
    stmt.close();
    conn.close();
}
catch (SQLException ex) { ex.printStackTrace(); }
int msgIcon = JOptionPane.ERROR_MESSAGE;
if (financeOK) {
    message = "Finance Accepted!";
    msgIcon = JOptionPane.INFORMATION_MESSAGE;
}
JOptionPane.showMessageDialog(null, message, "Financing Approval...", msgIcon);
</code>```

Title: SQL Query Java Net Beans

Body:
Now, there's a lot of information in your post that is missing but down and dirty here is how you might accomplish the task:

long customerID_Variable = 232;   // .... whatever you have to provide customer ID number ....
String customerName = "John Doe"; // .... whatever you have to provide customer name ....
boolean financeOK = false;   // default financing approval flag
String message = "Finance Declined!"; //default message

// Catch SQLException if any...
try {
    // Use whatever your connection string might be
    // to connect to your particular Database....
    Connection conn = DriverManager.getConnection("jdbc:derby:c:/databases/salesdb jdbc:derby:salesdb");
    conn.setAutoCommit(false);

    // The SQL query string...
    String sql = "SELECT FinanceOK FROM Customer WHERE CustomerID = " + customerID_Variable + ";";
    // Although it is best to use the Customer ID  to reference a
    // particular Customer you may prefer to to use the Customer
    // name and if so then use the query string below instead...
    // String sql = "SELECT FinanceOK FROM Customer WHERE Name = '" + customerName + "';";

    // Execute the SQL query...
    PreparedStatement stmt = conn.prepareStatement(sql);
    ResultSet rs = stmt.executeQuery();

    //Retrieve the data from the query result set...
    while (rs.next()) {
        financeOK = rs.getBoolean("FinanceOK");
    }

    //Close everything...
    rs.close();
    stmt.close();
    conn.close();
}
catch (SQLException ex) { ex.printStackTrace(); }
int msgIcon = JOptionPane.ERROR_MESSAGE;
if (financeOK) {
    message = "Finance Accepted!";
    msgIcon = JOptionPane.INFORMATION_MESSAGE;
}
JOptionPane.showMessageDialog(null, message, "Financing Approval...", msgIcon);


问:
Crystal reports Command for date Range in Visual Studio 2012
I am editing an application that is made in Visual Studio 2012. I am trying to create a Crystal Report where the user selects a date range. I added a command for my simple SQL Server Query, which runs fine in the SQL Management Studio.

```<code>Select customerID, orderID, orderDate
From tblOrders
Where orderDate BETWEEN CONVERT(DATETIME, '01/01/2015 00:00:00', 102)
                    AND CONVERT(DATETIME, '01/01/2016 11:59:59', 102)
</code>```

I then created the parameters From and To as dates and substituted my dates:

```<code>Select customerID, orderID, orderDate
From tblOrders
Where orderDate BETWEEN CONVERT(DATETIME, '{?From} 00:00:00', 102)
                        AND
                        CONVERT(DATETIME, '{?To} 11:59:59', 102)
</code>```

I get the following error using the same dates:

```<code>Failed to retrieve data from the database.
Details: ADO Error Code 0x80040e14
Source Microsoft OLE DB Provider for SQL Server Description: Incorrect syntax near '2015'.
SQL State: 42000
Native Error: 102 [Database Vendor Code 102]
</code>```

I tried the query without the Convert function, but get the same result.

答:
This is not a correct code:

```<code>'{?From} 00:00:00'
</code>```

it can be:

```<code>{?From}  & " " & '00:00:00' in formula
</code>```

And i am wondering why you want to do like that a Parameter with static time?

This is the convertion running as tested.

```<code>CONVERT(DATETIME,convert(datetime, CONVERT(varchar,dt,101) + ' 00:00:00',102), 102)
</code>```

you can change the dt to {?From} in your crystal report

Body:
I am editing an application that is made in Visual Studio 2012. I am trying to create a Crystal Report where the user selects a date range. I added a command for my simple SQL Server Query, which runs fine in the SQL Management Studio.

Select customerID, orderID, orderDate
From tblOrders
Where orderDate BETWEEN CONVERT(DATETIME, '01/01/2015 00:00:00', 102)
                    AND CONVERT(DATETIME, '01/01/2016 11:59:59', 102)

I then created the parameters From and To as dates and substituted my dates:

Select customerID, orderID, orderDate
From tblOrders
Where orderDate BETWEEN CONVERT(DATETIME, '{?From} 00:00:00', 102)
                        AND
                        CONVERT(DATETIME, '{?To} 11:59:59', 102)

I get the following error using the same dates:

Failed to retrieve data from the database.
Details: ADO Error Code 0x80040e14
Source Microsoft OLE DB Provider for SQL Server Description: Incorrect syntax near '2015'.
SQL State: 42000
Native Error: 102 [Database Vendor Code 102]

I tried the query without the Convert function, but get the same result.

Body:
This is not a correct code:

'{?From} 00:00:00'

it can be:

{?From}  & " " & '00:00:00' in formula

And i am wondering why you want to do like that a Parameter with static time?

This is the convertion running as tested.

CONVERT(DATETIME,convert(datetime, CONVERT(varchar,dt,101) + ' 00:00:00',102), 102)

you can change the dt to {?From} in your crystal report


问:
What causes "resource temporarily unavailable" in v4l2
I have compiled adv7180 driver available here.

I am unloading the ov5642 cameradriver(which in my case is built-in) and loading the adv7180_tvin module and after I am loading mxcv4l2_capture module which creates video0 in /dev/.
(dmesg command says: "mxc camera on IPU2_CSI1 registered as video0")

But when I try to access video0 with v4l2-ctl I got a message "resource temporarily unavailable" or when I am using gstreamer I got message "Can not open /dev/video0" (but the device is really created).

Is that a problem in device tree settings or it can be caused by something else? Which tools should I use to find out what causes this issue?

My device tree settings look like below:

```<code>&i2c3{
adv7180: adv7180@20{
compatible = "adv,adv7180";
reg = <0x20>;
clocks = <&clks IMX6QDL_CLK_CKO2>;
clock-names = "csi_mclk";
pwn-gpios = <&gpio3 10 GPIO_ACTIVE_LOW>;
ipu_id = <1>;
csi_id = <1>;
mclk = <24000000>;
mclk_source = <0>;
pinctrl-names = "default";
pinctrl-0 = <&pinctrl_hummingboard2_parallel>;

cvbs = <1>;

};
};
</code>```

I need to add that before adv7180 I was using above settings for ov5642 camera (excluding cvbs setting) and everything worked properly.

EDIT:

Ok I got one clue.

When I load modules in dmesg message "mxc_v4l2_master_attach: ipu(0:1)/csi(1:1)/mipi(0:0) doesn't match" shows.
But it only happens when ipu_id=<1> in v4l2_cap device tree settings and in adv7180 settings. When i change ipu_id to ipu_id=<0> in v4l2 settings and adv7180 dmesg now shows "parallel attach to IPU1 CSI1 and I can access the /dev/video0 succesfully with v4l2-ctl tool.

But In my case there is only one possibility to use IPU2_CSI1.

Why can't I set IPU2 to adv7180 when I was using it successfully to ov5642 ?

答:
As per my knowledge i.MX6 having two IPUs. I think by default IPU1 parallel interface is not enabled in the board file. So you need to check the IOMUXC_GPR1 register setting (bit 19 and 20) for IPU/CSI1 and pass the csi_id in your camera driver.

As you are using the parallel interface so check your pin muxing setting as well in your device tree. (which is not required for serial interface.)

Edit:
There are two ways which you can follow to update the register setting from the kernel space (boardfile or camera driver) itself:

1. From the board file:

```<code>struct regmap *gpr
gpr = syscon_regmap_lookup_by_compatible("fsl,imx6q-iomuxc-gpr");
regmap_update_bits(gpr, IOMUXC_GPR1, 1 << 20, 1 << 20);
</code>```

2. From the boardfile or camera driver

```<code>void __iomem *va_ipu2_address;
u32 reg_val;
va_ipu2_address = ioremap(0x20e0004,0xe0004);
reg_val = readl(va_ipu2_address);
/* Enable parallel interface to IPU2 CSI1.  */
writel(reg_val | 1 << 20, va_ipu2_address);
</code>```

Body:
I have compiled adv7180 driver available here.

I am unloading the ov5642 cameradriver(which in my case is built-in) and loading the adv7180_tvin module and after I am loading mxcv4l2_capture module which creates video0 in /dev/.
(dmesg command says: "mxc camera on IPU2_CSI1 registered as video0")

But when I try to access video0 with v4l2-ctl I got a message "resource temporarily unavailable" or when I am using gstreamer I got message "Can not open /dev/video0" (but the device is really created).

Is that a problem in device tree settings or it can be caused by something else? Which tools should I use to find out what causes this issue?

My device tree settings look like below:

&i2c3{
adv7180: adv7180@20{
compatible = "adv,adv7180";
reg = <0x20>;
clocks = <&clks IMX6QDL_CLK_CKO2>;
clock-names = "csi_mclk";
pwn-gpios = <&gpio3 10 GPIO_ACTIVE_LOW>;
ipu_id = <1>;
csi_id = <1>;
mclk = <24000000>;
mclk_source = <0>;
pinctrl-names = "default";
pinctrl-0 = <&pinctrl_hummingboard2_parallel>;

cvbs = <1>;

};
};

I need to add that before adv7180 I was using above settings for ov5642 camera (excluding cvbs setting) and everything worked properly.

EDIT:

Ok I got one clue.

When I load modules in dmesg message "mxc_v4l2_master_attach: ipu(0:1)/csi(1:1)/mipi(0:0) doesn't match" shows.
But it only happens when ipu_id=<1> in v4l2_cap device tree settings and in adv7180 settings. When i change ipu_id to ipu_id=<0> in v4l2 settings and adv7180 dmesg now shows "parallel attach to IPU1 CSI1 and I can access the /dev/video0 succesfully with v4l2-ctl tool.

But In my case there is only one possibility to use IPU2_CSI1.

Why can't I set IPU2 to adv7180 when I was using it successfully to ov5642 ?

Body:
As per my knowledge i.MX6 having two IPUs. I think by default IPU1 parallel interface is not enabled in the board file. So you need to check the IOMUXC_GPR1 register setting (bit 19 and 20) for IPU/CSI1 and pass the csi_id in your camera driver.

As you are using the parallel interface so check your pin muxing setting as well in your device tree. (which is not required for serial interface.)

Edit:
There are two ways which you can follow to update the register setting from the kernel space (boardfile or camera driver) itself:

1. From the board file:

struct regmap *gpr
gpr = syscon_regmap_lookup_by_compatible("fsl,imx6q-iomuxc-gpr");
regmap_update_bits(gpr, IOMUXC_GPR1, 1 << 20, 1 << 20);

2. From the boardfile or camera driver

void __iomem *va_ipu2_address;
u32 reg_val;
va_ipu2_address = ioremap(0x20e0004,0xe0004);
reg_val = readl(va_ipu2_address);
/* Enable parallel interface to IPU2 CSI1.  */
writel(reg_val | 1 << 20, va_ipu2_address);


问:
How to compare all values in one vector to all values in another? (In minimal time)
I have the following r code:

```<code>list1 <- c(5, 6, 8, 10, 15, 26, 75)
list2 <- c(3, 6, 8, 10, 100, 42)

total <- length(list1)*length(list2)
  for(x in 1:length(list1)) {
    for(y in 1:length(list2)) {
      print(total - (x*y))
      if(list1[x]>list2[y]) {
        l1Bigger <- l1Bigger + 1
      } else if(list1[x]<list2[y]) {
        l2Bigger <- l2Bigger + 1
      } else {
        tie <- tie + 1
      }
    }
  }
  percents <- c(l1Bigger/total, l2Bigger/total, tie/total)
  return(percents)
</code>```

Basically, what I want my code to do is iterate through list1 and list2 and compare the values to figure out how often the values in list1 are greater than the values in list 2. My current method takes a lot of time, is there any way to reduce the amount of time this process takes?

Thank you!

答:
You can convert what you've got into Rcpp which should speed up the process on long vectors

```<code>library(Rcpp)

set.seed(1)
v1 <- rnorm(10000)
v2 <- rnorm(10000)

cppFunction('NumericVector compareVectors(NumericVector v1, NumericVector v2){

            NumericVector out(3);

            for(int i = 0; i < v1.size(); i++){
               for(int j = 0; j < v2.size(); j++){
                  if(v1[i] == v2[j]){
                     out[0]++;
                  }else if(v1[i] < v2[j]){
                     out[1]++;
                  }else{
                     out[2]++;
                  }
               }
            }
            return out;
        }')

compareVectors(v1, v2)
[1]          0 5008309906 4991690094
</code>```

which shows favourable results when benchmarked

```<code>library(microbenchmark)

set.seed(1)
v1 <- rnorm(1000)
v2 <- rnorm(1000)

microbenchmark(

    rcpp = {
        compareVectors(v1, v2)
    },
    exg = {
        g <- expand.grid(v1, v2)
        x.bigger <- sum(g$Var1 > g$Var2)
        y.bigge <- sum(g$Var1 < g$Var2)
    }
)

# Unit: milliseconds
# expr       min        lq      mean    median        uq        max neval
# rcpp  5.600956  5.788145  6.036816  5.927468  6.183143   8.385282   100
#  exg 28.529272 35.246216 41.328205 36.000421 37.653801 540.850561   100
</code>```

Body:
I have the following r code:

list1 <- c(5, 6, 8, 10, 15, 26, 75)
list2 <- c(3, 6, 8, 10, 100, 42)

total <- length(list1)*length(list2)
  for(x in 1:length(list1)) {
    for(y in 1:length(list2)) {
      print(total - (x*y))
      if(list1[x]>list2[y]) {
        l1Bigger <- l1Bigger + 1
      } else if(list1[x]<list2[y]) {
        l2Bigger <- l2Bigger + 1
      } else {
        tie <- tie + 1
      }
    }
  }
  percents <- c(l1Bigger/total, l2Bigger/total, tie/total)
  return(percents)

Basically, what I want my code to do is iterate through list1 and list2 and compare the values to figure out how often the values in list1 are greater than the values in list 2. My current method takes a lot of time, is there any way to reduce the amount of time this process takes?

Thank you!

Body:
You can convert what you've got into Rcpp which should speed up the process on long vectors

library(Rcpp)

set.seed(1)
v1 <- rnorm(10000)
v2 <- rnorm(10000)

cppFunction('NumericVector compareVectors(NumericVector v1, NumericVector v2){

            NumericVector out(3);

            for(int i = 0; i < v1.size(); i++){
               for(int j = 0; j < v2.size(); j++){
                  if(v1[i] == v2[j]){
                     out[0]++;
                  }else if(v1[i] < v2[j]){
                     out[1]++;
                  }else{
                     out[2]++;
                  }
               }
            }
            return out;
        }')

compareVectors(v1, v2)
[1]          0 5008309906 4991690094

which shows favourable results when benchmarked

library(microbenchmark)

set.seed(1)
v1 <- rnorm(1000)
v2 <- rnorm(1000)

microbenchmark(

    rcpp = {
        compareVectors(v1, v2)
    },
    exg = {
        g <- expand.grid(v1, v2)
        x.bigger <- sum(g$Var1 > g$Var2)
        y.bigge <- sum(g$Var1 < g$Var2)
    }
)

# Unit: milliseconds
# expr       min        lq      mean    median        uq        max neval
# rcpp  5.600956  5.788145  6.036816  5.927468  6.183143   8.385282   100
#  exg 28.529272 35.246216 41.328205 36.000421 37.653801 540.850561   100


问:
How to make sense of DICT data in CFF font format

Problem

I'm trying to parse a OTF/CFF font and is struggling with top DICT part, more specifically the top DICT data part.

CFF File

The beginning of CFF table looks like this in hex editor:

The top DICT starts from the second line from offset 0xC2 with 00 01 "top DICT INDEX count", 01 "top DICT INDEX offsetsize", 01 77 "top DICT INDEX offsets".

The large yellow section is the data part for the DICT, but I simply cannot make sense of it. I referenced: https://typekit.files.wordpress.com/2013/05/5176.cff.pdf
http://wwwimages.adobe.com/content/dam/Adobe/en/devnet/font/pdfs/T1_SPEC.pdf

Things I tried

Since top DICT starts with version, Notice, Copyright which are SID, so I tried to look up the offsetted strings but they were way off the strings.

I tried to encode them using Table 3 in page 10 of the CFF reference pdf, essentially taking two bytes, b0, b1, and calculating the value, but the values seemed unrelated.

Further Information

It seems I'm having difficulty understanding Table 3 and Table 4. So the DICT data is supposed to be 1 or 2 byte operators and variable sized operands, and these are concatenated throughout the data? Some examples would be helpful.

答:
I misunderstood the encoding procedure. You need to start from the beginning, and based on the first byte, need to find which encoding it uses, integer encodings, real encoding, or instructions etc.
Btw, this font has CIDFont Operator Extensions eg  F8 1B F8 1C 8D 0C 1E meaning it is a CID font. So it doesn't have encoding offset, don't waste time like me trying to find one!


问:
Does pandas dataframe merge work with greater or less?
Now i need to merge two dataframe with the condition greater than(>=). But merge only support equal. Is there any way to deal with it? Thanks!</p>

答:
I don't know how to achieve the following with similar merge and join syntax in pandas,

```<code>SELECT *
FROM a
INNER JOIN b
ON a.column1 >= b.column1 AND a.column1 <= b.column2
</code>```

But the query above can also be written implicitly as;

```<code>SELECT *
FROM a, b
WHERE a.column1 >= b.column1 AND a.column1 <= b.column2
</code>```

Which is basically the old syntax and should do exactly same (performance wise). It takes the cartesian product of 2 tables (or cross join) and then select from that using the WHERE condition, which could be easily implemented in pandas. This could be a little heavy on memory, but should be fast.

First the FROM a, b clause (we temporarily assign a column with same values in all rows, so we can cross join over it);

```<code>df = pd.merge(a.assign(key=0), b.assign(key=0), on='key').drop('key', axis=1)
</code>```

and then use boolean indexing (our WHERE clause) to slice the frame;

```<code>df[(df["column1_x"] >= df["column1_y"]) & (df["column1_x"] <= df["column2_y"])]
</code>```

If you don't want the cartesian product and only want to compare the rows on same index of both tables, you can merge on index like this;

```<code>df = a.merge(b, left_index = True, right_index = True)
</code>```

or concat on axis 1 if they are same length;

```<code>df = pd.concat([a, b], axis=1)
</code>```

And use boolean indexing again to eliminate results;

```<code>df[(df["column1_x"] >= df["column1_y"]) & (df["column1_x"] <= df["column2_y"])]
</code>```

Body:
I don't know how to achieve the following with similar merge and join syntax in pandas,

SELECT *
FROM a
INNER JOIN b
ON a.column1 >= b.column1 AND a.column1 <= b.column2

But the query above can also be written implicitly as;

SELECT *
FROM a, b
WHERE a.column1 >= b.column1 AND a.column1 <= b.column2

Which is basically the old syntax and should do exactly same (performance wise). It takes the cartesian product of 2 tables (or cross join) and then select from that using the WHERE condition, which could be easily implemented in pandas. This could be a little heavy on memory, but should be fast.

First the FROM a, b clause (we temporarily assign a column with same values in all rows, so we can cross join over it);

df = pd.merge(a.assign(key=0), b.assign(key=0), on='key').drop('key', axis=1)

and then use boolean indexing (our WHERE clause) to slice the frame;

df[(df["column1_x"] >= df["column1_y"]) & (df["column1_x"] <= df["column2_y"])]

If you don't want the cartesian product and only want to compare the rows on same index of both tables, you can merge on index like this;

df = a.merge(b, left_index = True, right_index = True)

or concat on axis 1 if they are same length;

df = pd.concat([a, b], axis=1)

And use boolean indexing again to eliminate results;

df[(df["column1_x"] >= df["column1_y"]) & (df["column1_x"] <= df["column2_y"])]


问:
SmoothAppBarLayout collapsed toolbar height is bigger than intended
I recently changed my AppBarLayout with SmoothAppBarLayout

It is smoother and faster so i am happy with the result. But this changed my toolbar height somehow and i couldn't yet fix it.

Collapsed ToolBar's height should be 'actionBarSize' but it is bigger than that.

It is not about toolbar title, disabling or changing the padding of it doesnt work. But it is about the behaviour.

Setting a new behavior like below solves the problem but I want a proper solution.

```<code>    AppBarLayout.Behavior behavior = new AppBarLayout.Behavior();
    params.setBehavior(behavior);
</code>```

First image shows the intended size, second shows the actual size.

Here is the part of my XML: (Didn't put all of it since it is pretty long)

```<code>    <me.henrytao.smoothappbarlayout.SmoothAppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="210dp"
        android:minHeight="50dp"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:sabl_target_id="@id/nestedScrollView">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsingToolbarLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/transparent"
            android:fitsSystemWindows="true"
            android:minHeight="210dp"
            app:contentScrim="@color/dark_gray_actionbar"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="210dp"
                android:orientation="vertical"
                app:layout_collapseMode="parallax">

                <ImageView
                    android:id="@+id/serviceImage"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:contentDescription="Servis Fotoğrafı"
                    android:scaleType="centerCrop"
                    android:src="@drawable/gray_color_gradient"
                    app:layout_collapseMode="parallax" />
            </RelativeLayout>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?actionBarSize"
                android:layout_alignParentTop="true"
                android:layout_gravity="center_horizontal"
                app:layout_collapseMode="pin">

            </android.support.v7.widget.Toolbar>
        </android.support.design.widget.CollapsingToolbarLayout>
    </me.henrytao.smoothappbarlayout.SmoothAppBarLayout>

    <include
        layout="@layout/get_quote_layout"
        android:layout_width="match_parent"
        android:layout_height="64dp"
        app:layout_anchor="@id/nestedScrollView"
        app:layout_anchorGravity="bottom"
        app:layout_collapseMode="pin" />

</android.support.design.widget.CoordinatorLayout>
</code>```

答:
I think the issue comes from fitSystemWindows. You can simplify your layout as below: </p>

```<code>...
<me.henrytao.smoothappbarlayout.SmoothAppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:sabl_target_id="@id/nestedScrollView">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/collapsingToolbarLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/transparent"
        app:contentScrim="@color/dark_gray_actionbar"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="210dp"
            android:orientation="vertical"
            app:layout_collapseMode="parallax">

            <ImageView
                android:id="@+id/serviceImage"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:contentDescription="Servis Fotoğrafı"
                android:scaleType="centerCrop"
                android:src="@drawable/gray_color_gradient"
                app:layout_collapseMode="parallax" />
        </RelativeLayout>

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?actionBarSize"
            android:layout_alignParentTop="true"
            android:layout_gravity="center_horizontal"
            app:layout_collapseMode="pin">

        </android.support.v7.widget.Toolbar>
    </android.support.design.widget.CollapsingToolbarLayout>
</me.henrytao.smoothappbarlayout.SmoothAppBarLayout>
...
</code>```

Body:
I recently changed my AppBarLayout with SmoothAppBarLayout

It is smoother and faster so i am happy with the result. But this changed my toolbar height somehow and i couldn't yet fix it.

Collapsed ToolBar's height should be 'actionBarSize' but it is bigger than that.

It is not about toolbar title, disabling or changing the padding of it doesnt work. But it is about the behaviour.

Setting a new behavior like below solves the problem but I want a proper solution.

    AppBarLayout.Behavior behavior = new AppBarLayout.Behavior();
    params.setBehavior(behavior);

First image shows the intended size, second shows the actual size.

Here is the part of my XML: (Didn't put all of it since it is pretty long)

    <me.henrytao.smoothappbarlayout.SmoothAppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="210dp"
        android:minHeight="50dp"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:sabl_target_id="@id/nestedScrollView">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsingToolbarLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/transparent"
            android:fitsSystemWindows="true"
            android:minHeight="210dp"
            app:contentScrim="@color/dark_gray_actionbar"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="210dp"
                android:orientation="vertical"
                app:layout_collapseMode="parallax">

                <ImageView
                    android:id="@+id/serviceImage"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:contentDescription="Servis Fotoğrafı"
                    android:scaleType="centerCrop"
                    android:src="@drawable/gray_color_gradient"
                    app:layout_collapseMode="parallax" />
            </RelativeLayout>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?actionBarSize"
                android:layout_alignParentTop="true"
                android:layout_gravity="center_horizontal"
                app:layout_collapseMode="pin">

            </android.support.v7.widget.Toolbar>
        </android.support.design.widget.CollapsingToolbarLayout>
    </me.henrytao.smoothappbarlayout.SmoothAppBarLayout>

    <include
        layout="@layout/get_quote_layout"
        android:layout_width="match_parent"
        android:layout_height="64dp"
        app:layout_anchor="@id/nestedScrollView"
        app:layout_anchorGravity="bottom"
        app:layout_collapseMode="pin" />

</android.support.design.widget.CoordinatorLayout>

Body:
I think the issue comes from fitSystemWindows. You can simplify your layout as below:

...
<me.henrytao.smoothappbarlayout.SmoothAppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:sabl_target_id="@id/nestedScrollView">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/collapsingToolbarLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/transparent"
        app:contentScrim="@color/dark_gray_actionbar"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="210dp"
            android:orientation="vertical"
            app:layout_collapseMode="parallax">

            <ImageView
                android:id="@+id/serviceImage"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:contentDescription="Servis Fotoğrafı"
                android:scaleType="centerCrop"
                android:src="@drawable/gray_color_gradient"
                app:layout_collapseMode="parallax" />
        </RelativeLayout>

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?actionBarSize"
            android:layout_alignParentTop="true"
            android:layout_gravity="center_horizontal"
            app:layout_collapseMode="pin">

        </android.support.v7.widget.Toolbar>
    </android.support.design.widget.CollapsingToolbarLayout>
</me.henrytao.smoothappbarlayout.SmoothAppBarLayout>
...


问:
How do you quickly identify object structure in node?
Is there a way to quickly identify object structure in Node?  I have the following code below, which uses the spotify npm package

```<code>// *****************  Code for SPOTIFY  *************************

// Return Artist, Song Name, a preview link of the song from Spotify, and the albumn the song is from

//  Search for text variable on spotify.  Console log data

if (nodeArgs=="spotify-this-song") {

spotify.search({ type: 'track', query: text }, function(err, data) {
    if ( err ) {
        console.log('Error occurred: ' + err);
        return;
    }
    console.log(JSON.stringify(data, null, 2));
});

};
</code>```

This returns the data, but it's difficult for me (a new coder) to determine the object levels and to output the information I'm looking for (Artist, Song Name, a preview link of the song from Spotify, the albumn, etc)

Is there an easier way to graphically see the object structure?

Thanks in advance for your help!

答:
Try node's util library, available by default (You require it like a normal module), with the inspect function (which can have a configurable depth and some more options, like use colors). This link might help you: https://nodejs.org/api/util.html#util_util_inspect_object_options

The util.inspect() method returns a string representation of object that is primarily useful for debugging. Additional options may be passed that alter certain aspects of the formatted string.

Here's an example of usage:

```<code>var util = require("util"); // Require the util library, you have it by default.
var options = { depth: 3 }; // Set options to inspect with depth of 3.
// then with the object...
console.log(util.inspect(obj, options)); // options are optional.
</code>```

Body:
Is there a way to quickly identify object structure in Node?  I have the following code below, which uses the spotify npm package

// *****************  Code for SPOTIFY  *************************

// Return Artist, Song Name, a preview link of the song from Spotify, and the albumn the song is from

//  Search for text variable on spotify.  Console log data

if (nodeArgs=="spotify-this-song") {

spotify.search({ type: 'track', query: text }, function(err, data) {
    if ( err ) {
        console.log('Error occurred: ' + err);
        return;
    }
    console.log(JSON.stringify(data, null, 2));
});

};

This returns the data, but it's difficult for me (a new coder) to determine the object levels and to output the information I'm looking for (Artist, Song Name, a preview link of the song from Spotify, the albumn, etc)

Is there an easier way to graphically see the object structure?

Thanks in advance for your help!

Body:
Try node's util library, available by default (You require it like a normal module), with the inspect function (which can have a configurable depth and some more options, like use colors). This link might help you: https://nodejs.org/api/util.html#util_util_inspect_object_options

The util.inspect() method returns a string representation of object that is primarily useful for debugging. Additional options may be passed that alter certain aspects of the formatted string.

Here's an example of usage:

var util = require("util"); // Require the util library, you have it by default.
var options = { depth: 3 }; // Set options to inspect with depth of 3.
// then with the object...
console.log(util.inspect(obj, options)); // options are optional.


答: You could simply use writeClipboard( as.character(a$relative_importance) ) and paste it in Excel

Title: Is there anyway to delete rownames in R?

Body:
I made a table like this table name a.

   variable relative_importance scaled_importance percentage
1      x005        68046.078125          1.000000   0.195396
2      x004        63890.796875          0.938934   0.183464
3      x007        48253.820312          0.709134   0.138562
4      x012        43492.117188          0.639157   0.124889
5      x008        43132.035156          0.633865   0.123855
6      x013        32495.070312          0.477545   0.093310
7      x009        18466.910156          0.271388   0.053028
8      x015        10625.453125          0.156151   0.030511
9      x010         8893.750977          0.130702   0.025539
10     x014         4904.361816          0.072074   0.014083
11     x002         1812.269531          0.026633   0.005204
12     x001         1704.574585          0.025050   0.004895
13     x006         1438.692139          0.021143   0.004131
14     x011         1080.584106          0.015880   0.003103
15     x003           10.152302          0.000149   0.000029

and use this code to order that table.

setorder(a,variable)

and want to get only second column.

a[2]

   relative_importance
12            380.4296
11            645.4594
15             10.1440
4            8599.7715
2           10749.5752
13            263.7065
5            8434.3760
6            7443.8530
7            3602.8850
10            935.6713
14            256.7183
3            9160.4062
1           12071.1826
9            1173.0701
8            1698.0955

I want to copy "relative_importance" and paste in Excel.
But, I couldn't delete the rownames. (12,11,15...,9,8)
Is there any way to print only "relative_importance"? (print without rownames or hide rownames)

Thank you :)


问:
ZED SDK error while loading shared libraries: libGLEW.so.1.13: cannot open shared object file: No such file or directory
I'm trying to run the ZED Explorer application from ZED SDK. But when I do that, I get this error:

error while loading shared libraries: libGLEW.so.1.13: cannot open
  shared object file: No such file or directory

I tried to fix it using the other solutions mentioned on SO but didn't have any luck.

答:
It appears that your software needs the GLEW library, and you're missing the shared library libGLEW.so.1.13, so you have to install it.
Looking for it through aptitude or apt-cache:

```<code>sudo apt-cache search libGLEW
</code>```

shows that it belongs to the GLEW library.
So install the library through:

```<code>sudo apt-get install glew-utils
</code>```

Body:
It appears that your software needs the GLEW library, and you're missing the shared library libGLEW.so.1.13, so you have to install it.
Looking for it through aptitude or apt-cache:

sudo apt-cache search libGLEW

shows that it belongs to the GLEW library.
So install the library through:

sudo apt-get install glew-utils


问:
How can I align these elements side by side?
I'm having difficulties in aligning these elements side by side, anyway this—

—is how it looks so far, but I want it look like this:

.reviewprofile {
  background-color: transparent;
  border: none;
  margin-top: 5em;
}

.reviewentry {
  display: inline-block;
  font-family: 'Abhaya Libre', Times, Serif;
  font-size: 0.8em;
  font-weight: 400;
  color: #5e5e5e;
  text-align: left;
  padding-left: 3.5em;
  margin: 0;
}

.commbutton button {
  float: left;
}

.starsrev {
  padding-left: 2.8em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="commsec">
  <div class="commbutton">
    <button class="reviewprofile"><img src="img/reviewprofile.png">  </button>
  </div>

  <div class="commentry">
    <p class="reviewentry">Cras ultricies dolor ac justo scelerisque, sit amet imperdiet<br> purus placerat.</p>
    <img class="starsrev" src="img/stars.png" alt="stars" />
  </div>
</div></code>```

答: Apply float:left to the div which you want to show on the left and apply float: right for the one to be shown on the right. That's the starting point. Based on results you may have to change them to be inline too.

Body:
I'm having difficulties in aligning these elements side by side, anyway this—

—is how it looks so far, but I want it look like this:

.reviewprofile {
  background-color: transparent;
  border: none;
  margin-top: 5em;
}

.reviewentry {
  display: inline-block;
  font-family: 'Abhaya Libre', Times, Serif;
  font-size: 0.8em;
  font-weight: 400;
  color: #5e5e5e;
  text-align: left;
  padding-left: 3.5em;
  margin: 0;
}

.commbutton button {
  float: left;
}

.starsrev {
  padding-left: 2.8em;
}

    <button class="reviewprofile">  </button>

Cras ultricies dolor ac justo scelerisque, sit amet imperdiet
 purus placerat.


问:
Firebase Query Android
I am trying to query the last item in the news node with a particular newspaper_id. Basically i want to always get the last news of a particular newspaper using the id of the news as a query. The query is been done inside the FirebaseRecyclerAdpter populateViewHolder(), I am getting

java.lang.ArrayIndexOutOfBoundsException: length=0; index=-1
                                                                               at java.util.ArrayList.get(ArrayList.java:310)
                                                                               at com.simpumind.e_tech_news.adapter.VendorNewAdapter$1.onDataChange(VendorNewAdapter.java:100)

```<code> {
  "news": {
    "-HDRKDDGKSD56": {
          "caption" : "Hail Mary",
          "content" : "some  contents"
          "newspaper_id" : "-Kg9UvxyiuI4G3r6fCgU",
          thumbnail: "some base64 encoded image"
    },

 "newspaper": {
     "-Kg9UvxyiuI4G3r6fCgU" : {
            "content_provider" : 1,
            "cost" : "200",
            "logo" : "some base64 encoded image"
            "user": "The user"
    }
 }
</code>```

This is what i have attempted

```<code>@Override
protected void populateViewHolder(final NewsPaperHolder viewHolder, NewsPaper model, int position) {

    viewHolder.vendorName.setText(model.getPaper_name());

    mDatabaseRef = FirebaseDatabase.getInstance().getReference().child("news");

   String oneChildRef = getRef(position).getKey();

    mDatabaseRef.orderByChild("newspaper_id")
            .equalTo(oneChildRef)
            .addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

                List<News> newsList = new ArrayList();
                for (DataSnapshot d : dataSnapshot.getChildren()){
                    News n = d.getValue(News.class);
                    newsList.add(n);
                }

            newsList.toString();

                News news = newsList.get(newsList.size() -  1);
               updateUI(viewHolder, news);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    Picasso.with(context).load(model.getLogo()).into(viewHolder.vendorIcon);
}

public void updateUI(NewsPaperHolder holder, News news){

    holder.firstNewsTitle.setText(news.getCaption());
    Picasso.with(context).load(news.getThumbnail()).into(holder.firstNewsImage);

}
</code>```

News

```<code>public class News {

public String caption;
public String content;
public String newspaper_id;
public String thumbnail;
public String user;

public News(){

}

public News(String caption, String content, String newspaper_id, String thumbnail, String user) {
    this.caption = caption;
    this.content = content;
    this.newspaper_id = newspaper_id;
    this.thumbnail = thumbnail;
    this.user = user;
}

public String getCaption() {
    return caption;
}

public void setCaption(String caption) {
    this.caption = caption;
}

public String getContent() {
    return content;
}

public void setContent(String content) {
    this.content = content;
}

public String getNewspaper_id() {
    return newspaper_id;
}

public void setNewspaper_id(String newspaper_id) {
    this.newspaper_id = newspaper_id;
}

    public String getThumbnail() {
      return thumbnail;
    }

    public void setThumbnail(String thumbnail) {
       this.thumbnail = thumbnail;
    }
}
</code>```

答:
Probably you got that error when your database contains no child. Try evade it by this:

```<code>public void onDataChange(DataSnapshot dataSnapshot) {
    ...
    if (newsList.size() > 0) {
        News news = newsList.get(newsList.size() - 1);
        updateUI(viewHolder, news);
    }
}
</code>```

Hope this helps

Title: Firebase Query Android

Body:
I am trying to query the last item in the news node with a particular newspaper_id. Basically i want to always get the last news of a particular newspaper using the id of the news as a query. The query is been done inside the FirebaseRecyclerAdpter populateViewHolder(), I am getting

java.lang.ArrayIndexOutOfBoundsException: length=0; index=-1
                                                                               at java.util.ArrayList.get(ArrayList.java:310)
                                                                               at com.simpumind.e_tech_news.adapter.VendorNewAdapter$1.onDataChange(VendorNewAdapter.java:100)

 {
  "news": {
    "-HDRKDDGKSD56": {
          "caption" : "Hail Mary",
          "content" : "some  contents"
          "newspaper_id" : "-Kg9UvxyiuI4G3r6fCgU",
          thumbnail: "some base64 encoded image"
    },

 "newspaper": {
     "-Kg9UvxyiuI4G3r6fCgU" : {
            "content_provider" : 1,
            "cost" : "200",
            "logo" : "some base64 encoded image"
            "user": "The user"
    }
 }

This is what i have attempted

@Override
protected void populateViewHolder(final NewsPaperHolder viewHolder, NewsPaper model, int position) {

    viewHolder.vendorName.setText(model.getPaper_name());

    mDatabaseRef = FirebaseDatabase.getInstance().getReference().child("news");

   String oneChildRef = getRef(position).getKey();

    mDatabaseRef.orderByChild("newspaper_id")
            .equalTo(oneChildRef)
            .addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

                List<News> newsList = new ArrayList();
                for (DataSnapshot d : dataSnapshot.getChildren()){
                    News n = d.getValue(News.class);
                    newsList.add(n);
                }

            newsList.toString();

                News news = newsList.get(newsList.size() -  1);
               updateUI(viewHolder, news);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    Picasso.with(context).load(model.getLogo()).into(viewHolder.vendorIcon);
}

public void updateUI(NewsPaperHolder holder, News news){

    holder.firstNewsTitle.setText(news.getCaption());
    Picasso.with(context).load(news.getThumbnail()).into(holder.firstNewsImage);

}

News

public class News {

public String caption;
public String content;
public String newspaper_id;
public String thumbnail;
public String user;

public News(){

}

public News(String caption, String content, String newspaper_id, String thumbnail, String user) {
    this.caption = caption;
    this.content = content;
    this.newspaper_id = newspaper_id;
    this.thumbnail = thumbnail;
    this.user = user;
}

public String getCaption() {
    return caption;
}

public void setCaption(String caption) {
    this.caption = caption;
}

public String getContent() {
    return content;
}

public void setContent(String content) {
    this.content = content;
}

public String getNewspaper_id() {
    return newspaper_id;
}

public void setNewspaper_id(String newspaper_id) {
    this.newspaper_id = newspaper_id;
}

    public String getThumbnail() {
      return thumbnail;
    }

    public void setThumbnail(String thumbnail) {
       this.thumbnail = thumbnail;
    }
}

Body:
Probably you got that error when your database contains no child. Try evade it by this:

public void onDataChange(DataSnapshot dataSnapshot) {
    ...
    if (newsList.size() > 0) {
        News news = newsList.get(newsList.size() - 1);
        updateUI(viewHolder, news);
    }
}

Hope this helps


问:
ES6 Getter returning empty object
I have created a method that grabs the image data based on another method. As you can see the uploadAvatar() method stores the object back from Cloudinary into a constructor object this._userImage;. Then my getUserImage() method should return the user image data but instead it returns {} that when I log it to the console :P.

ImageUploader.js

```<code>'use strict';

const cloudinary = require('cloudinary');

class ImageUploader {

  constructor(imageObj) {
    this.imageObj = imageObj;
    this._apiKey = "key";
    this._apiSecret = "secret";
    this.config = cloudinary.config({
      cloud_name: 'name',
      api_key: this._apiKey,
      api_secret: this._apiSecret
    });
    this._userImage = {}; // where user image object should be stored
  }

  * uploadAvatar(path) {
    cloudinary.uploader.upload(path, (data) => {
      this._userImage = data; // where I overwrite the constructor obj
    });
  }
  getUserImage() {
    return this._userImage; // this returns `{}` when I log it in UsersController.js
  }

}

module.exports = ImageUploader;
</code>```

UsersController.js

```<code>'use strict'

const Validator = require("../Helpers/ValidatorHelper.js");
const ImageUploader = require("../Helpers/ImageUploader.js");

class UsersController {

  * registerView (request, response) {
    yield response.sendView('users.register');
  }

  * register (request, response) {
    const user = request.only('display_name', 'username', 'email', 'password', 'confirm_password', 'console');
    var avatar = request.file('avatar');

    let validator = new Validator(user, avatar);
    let imageUpload = new ImageUploader(avatar);

    let avatarStatus = yield validator.validateAvatar();
    var img;
    if (avatarStatus) { // is true
      yield imageUpload.uploadAvatar(avatar.file.path);
    } else { // is false
      // pick a random avatar
    }
    console.log(imageUpload.getUserImage());
    return response.status(200).json({
      user: user,
      avatar: imageUpload.getUserImage()
    });

  }

}

module.exports = UsersController
</code>```

答:
Not sure but here you could lost your this context.

```<code>cloudinary.uploader.upload(path, (data) => {
     this._userImage = data; // where I overwrite the constructor obj
});
</code>```

Check if 'this' there still links to your UsersController object

Title: ES6 Getter returning empty object

Body:
I have created a method that grabs the image data based on another method. As you can see the uploadAvatar() method stores the object back from Cloudinary into a constructor object this._userImage;. Then my getUserImage() method should return the user image data but instead it returns {} that when I log it to the console :P.

ImageUploader.js

'use strict';

const cloudinary = require('cloudinary');

class ImageUploader {

  constructor(imageObj) {
    this.imageObj = imageObj;
    this._apiKey = "key";
    this._apiSecret = "secret";
    this.config = cloudinary.config({
      cloud_name: 'name',
      api_key: this._apiKey,
      api_secret: this._apiSecret
    });
    this._userImage = {}; // where user image object should be stored
  }

  * uploadAvatar(path) {
    cloudinary.uploader.upload(path, (data) => {
      this._userImage = data; // where I overwrite the constructor obj
    });
  }
  getUserImage() {
    return this._userImage; // this returns `{}` when I log it in UsersController.js
  }

}

module.exports = ImageUploader;

UsersController.js

'use strict'

const Validator = require("../Helpers/ValidatorHelper.js");
const ImageUploader = require("../Helpers/ImageUploader.js");

class UsersController {

  * registerView (request, response) {
    yield response.sendView('users.register');
  }

  * register (request, response) {
    const user = request.only('display_name', 'username', 'email', 'password', 'confirm_password', 'console');
    var avatar = request.file('avatar');

    let validator = new Validator(user, avatar);
    let imageUpload = new ImageUploader(avatar);

    let avatarStatus = yield validator.validateAvatar();
    var img;
    if (avatarStatus) { // is true
      yield imageUpload.uploadAvatar(avatar.file.path);
    } else { // is false
      // pick a random avatar
    }
    console.log(imageUpload.getUserImage());
    return response.status(200).json({
      user: user,
      avatar: imageUpload.getUserImage()
    });

  }

}

module.exports = UsersController

Body:
Not sure but here you could lost your this context.

cloudinary.uploader.upload(path, (data) => {
     this._userImage = data; // where I overwrite the constructor obj
});

Check if 'this' there still links to your UsersController object