问:
Error when running "bundle install" on mac - therubyracer failing to install
I am trying to install rails for the first time on my new macbook pro running OS X 10.9 (Mavericks) and I am running into an issue installing therubyracer. When I do "bundle install" I get this error:

An error occurred while installing therubyracer (0.10.2), and Bundler cannot
  continue.
  Make sure that gem install therubyracer -v '0.10.2' succeeds before bundling.

Then I follow their instructions and run

gem install therubyracer -v '0.10.2'

Then I get this error message:

Building native extensions.  This could take a while...
  ERROR:  Error installing therubyracer:
      ERROR: Failed to build gem native extension.

/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/ruby extconf.rb

checking for main() in -lobjc... yes
  creating Makefile

make "DESTDIR="
  compiling rr.cpp
  clang: warning: argument unused during compilation: '-rdynamic'
  rr.cpp:48:1: warning: control reaches end of non-void function [-Wreturn-type]
  }
  ^
  1 warning generated.
  compiling v8.cpp
  clang: warning: argument unused during compilation: '-rdynamic'
  compiling v8_array.cpp
  clang: warning: argument unused during compilation: '-rdynamic'
  compiling v8_callbacks.cpp
  clang: warning: argument unused during compilation: '-rdynamic'
  compiling v8_context.cpp
  clang: warning: argument unused during compilation: '-rdynamic'
  compiling v8_date.cpp
  clang: warning: argument unused during compilation: '-rdynamic'
  compiling v8_debug.cpp
  clang: warning: argument unused during compilation: '-rdynamic'
  compiling v8_exception.cpp
  clang: warning: argument unused during compilation: '-rdynamic'
  v8_exception.cpp:10:16: warning: unused variable 'stack' [-Wunused-variable]
    static void* stack[20];
                 ^
  1 warning generated.
  compiling v8_external.cpp
  clang: warning: argument unused during compilation: '-rdynamic'
  v8_external.cpp:10:9: warning: unused variable 'references' [-Wunused-variable]
    VALUE references;
          ^
  1 warning generated.
  compiling v8_function.cpp
  clang: warning: argument unused during compilation: '-rdynamic'
  compiling v8_handle.cpp
  clang: warning: argument unused during compilation: '-rdynamic'
  compiling v8_locker.cpp
  clang: warning: argument unused during compilation: '-rdynamic'
  v8_locker.cpp:45:5: warning: control reaches end of non-void function [-Wreturn-type]
      }
      ^
  v8_locker.cpp:85:5: warning: control reaches end of non-void function [-Wreturn-type]
      }
      ^
  2 warnings generated.
  compiling v8_message.cpp
  clang: warning: argument unused during compilation: '-rdynamic'
  compiling v8_object.cpp
  clang: warning: argument unused during compilation: '-rdynamic'
  v8_object.cpp:77:19: warning: unused variable 'proto' [-Wunused-variable]
      Handle proto(rr_rb2v8(prototype));
                    ^
  1 warning generated.
  compiling v8_script.cpp
  clang: warning: argument unused during compilation: '-rdynamic'
  compiling v8_string.cpp
  clang: warning: argument unused during compilation: '-rdynamic'
  compiling v8_template.cpp
  clang: warning: argument unused during compilation: '-rdynamic'
  compiling v8_try_catch.cpp
  clang: warning: argument unused during compilation: '-rdynamic'
  v8_try_catch.cpp:15:14: warning: initialization of pointer of type 'v8::TryCatch *' to null from a constant boolean expression [-Wbool-conversion]
        return false;
               ^~~~~
  1 warning generated.
  compiling v8_v8.cpp
  clang: warning: argument unused during compilation: '-rdynamic'
  compiling v8_value.cpp
  clang: warning: argument unused during compilation: '-rdynamic'
  v8_value.cpp:100:9: warning: unused function 'ToInt32' [-Wunused-function]
    VALUE ToInt32(VALUE self) {
          ^
  1 warning generated.
  compiling v8_weakref.cpp
  clang: warning: argument unused during compilation: '-rdynamic'
  linking shared-object v8.bundle
  clang: error: no such file or directory: '/Library/Ruby/Gems/2.0.0/gems/libv8-3.3.10.4/lib/libv8/build/v8/libv8.a'
  make: * [v8.bundle] Error 1

Gem files will remain installed in /Library/Ruby/Gems/2.0.0/gems/therubyracer-0.10.2 for inspection.
  Results logged to /Library/Ruby/Gems/2.0.0/gems/therubyracer-0.10.2/ext/v8/gem_make.out

I'm not really sure what this means or how to fix this.

All I really want to do is run my rails projects.

Anyone know what the issue is?

答:
I had the same issue when I upgraded from OS X Mountain Lion to OS X Mavericks.

I followed these steps:

brew install v8

gem install libv8 -v '3.16.14.3' -- --with-system-v8

gem install therubyracer -v '0.12.3' --source 'https://rubygems.org/' this may produce an error, don't worry if it does

bundle config build.therubyracer --with-v8-dir=$(brew --prefix v8@3.15)

'bundle install' - in my case this was not needed, but it may be in your case


来源: stackexchange

答:
You can do conditional aggregation:

```<code>select id, label,
       count(distinct case when action = 'A' then action end) as action_a,
       count(distinct case when action = 'B' then action end) as action_b
from t
group by id, label;
</code>```

OR You can just use max() :

```<code>select id, label,
       max(case when action = 'A' then 1 else 0 end) as action_a,
       max(case when action = 'B' then 1 else 0 end) as action_b
from t
group by id, label;
</code>```

ContentLicense: CC BY-SA 4.0

Title: Calculate distinct value_1 when value_2, value_3 is equal to certain value

Body:
The output table looks like this let's say:

table : people
+-------+-----------+-----------+
|   id  |  label    |   action  |
+-------+-----------+-----------+
|   1   |  aaaaa    |       B   |
|   1   |  aaaaa    |       B   |
|   1   |  aaaaa    |       A   |
|   2   |  aaaaa    |       B   |
|   2   |  aaaaa    |       B   |
+-------+-----------+-----------+

What I would like to do is to count unique ids this way:

table : people
+-------+-----------+-------------+-------------+
|   id  |  label    |   action_A  |   action_B  |
+-------+-----------+-------------+-------------+
|   1   |  aaaaa    |       1     |       1     |
|   2   |  aaaaa    |       0     |       1     |
+-------+-----------+-------------+-------------+

Body:
You can do conditional aggregation:

select id, label,
       count(distinct case when action = 'A' then action end) as action_a,
       count(distinct case when action = 'B' then action end) as action_b
from t
group by id, label;

OR You can just use max() :

select id, label,
       max(case when action = 'A' then 1 else 0 end) as action_a,
       max(case when action = 'B' then 1 else 0 end) as action_b
from t
group by id, label;


问:
Prevent Recyclerview from losing focus
I am developping this android TV app which has one activity containing some buttons. After clicking a button, a RecyclerView (in the same activity) gets populated and automatically focused.

The problem is when navigating with DPAD toward the direction of the buttons, the RecyclerView loses focus to the buttons. I want to prevent this behavior, i.e. prevent the RecyclerView from losing focus to anything else on the activity. Later, the only way to select another button is by clicking the back button, this I can do, no problem.

Here is what I have tried, and did not work:

```<code><androidx.recyclerview.widget.RecyclerView
        android:id="@+id/categories_rv"
        android:layout_width="@dimen/categories_list_width"
        android:layout_height="wrap_content"
        android:focusable="true"
        android:nextFocusForward="@id/categories_rv"
        android:nextFocusUp="@id/categories_rv"
        android:nextFocusRight="@id/categories_rv"
        android:nextFocusLeft="@id/categories_rv"
        android:nextFocusDown="@id/categories_rv"
        android:focusableInTouchMode="true" />
</code>```

And this:

```<code> binding.categoriesRv.setOnFocusChangeListener { v, hasFocus ->
     if (!hasFocus)
        v.requestFocus()
  }
</code>```

In the second way, the FocusChangeListener never gets called unless I use android:descendantFocusability="blocksDescendants" in the RecyclerView, but this prevents the items of the RecyclerView of being focused.

答:
You can achieve this by implementing key listeners on your controls and recyclerview and manage this thing manually. </p>

<p>Add the below method in your adapter class and define each step which you want to perform on every click. It is working in my app I hope it helps you too. </p>

```<code>@Override
public void onAttachedToRecyclerView(final RecyclerView recyclerView) {
    super.onAttachedToRecyclerView(recyclerView);
    recyclerView.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            LinearLayoutManager lm = ((LinearLayoutManager) recyclerView.getLayoutManager());

            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
                    //return false or true; // whatever your case is
                } else if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
                  return false;

                } else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {

                } else if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {

                } else if (keyCode == KeyEvent.KEYCODE_ENTER) {

                } else if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
                }
            }
            return false;
        }
    });

    recyclerView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {

            } else if (!hasFocus) {

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

Title: Prevent Recyclerview from losing focus

Body:
I am developping this android TV app which has one activity containing some buttons. After clicking a button, a RecyclerView (in the same activity) gets populated and automatically focused.

The problem is when navigating with DPAD toward the direction of the buttons, the RecyclerView loses focus to the buttons. I want to prevent this behavior, i.e. prevent the RecyclerView from losing focus to anything else on the activity. Later, the only way to select another button is by clicking the back button, this I can do, no problem.

Here is what I have tried, and did not work:

<androidx.recyclerview.widget.RecyclerView
        android:id="@+id/categories_rv"
        android:layout_width="@dimen/categories_list_width"
        android:layout_height="wrap_content"
        android:focusable="true"
        android:nextFocusForward="@id/categories_rv"
        android:nextFocusUp="@id/categories_rv"
        android:nextFocusRight="@id/categories_rv"
        android:nextFocusLeft="@id/categories_rv"
        android:nextFocusDown="@id/categories_rv"
        android:focusableInTouchMode="true" />

And this:

 binding.categoriesRv.setOnFocusChangeListener { v, hasFocus ->
     if (!hasFocus)
        v.requestFocus()
  }

In the second way, the FocusChangeListener never gets called unless I use android:descendantFocusability="blocksDescendants" in the RecyclerView, but this prevents the items of the RecyclerView of being focused.

Body:
You can achieve this by implementing key listeners on your controls and recyclerview and manage this thing manually.

Add the below method in your adapter class and define each step which you want to perform on every click. It is working in my app I hope it helps you too.

@Override
public void onAttachedToRecyclerView(final RecyclerView recyclerView) {
    super.onAttachedToRecyclerView(recyclerView);
    recyclerView.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            LinearLayoutManager lm = ((LinearLayoutManager) recyclerView.getLayoutManager());

            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
                    //return false or true; // whatever your case is
                } else if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
                  return false;

                } else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {

                } else if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {

                } else if (keyCode == KeyEvent.KEYCODE_ENTER) {

                } else if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
                }
            }
            return false;
        }
    });

    recyclerView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {

            } else if (!hasFocus) {

            }
        }
    });
}


问:
Elegant way for space efficient unpacking of a vector of pairs in two vectors
I have a big vector of std::pair<std::string,size_t> elements and I want to unpack it in two vectors using small extra memory overhead (I don't want the memory space occupation doubled, i.e. erasing the vector of pairs after the unpacking) and possibly as fast as possible. The following solution is unacceptably slow:

```<code>std::vector<std::pair<std::string, size_t>> string_weight;
get_from_file("mybigfile.txt", string_weight); //it just fills the string_weight vector
//... do stuff...
std::vector<std::string> strings;
std::vector<size_t> weights;
for (auto it = string_weight.begin(); it != string_weight.end() ; it = string_weight.erase(it)) {
     strings.push_back(std::move(it->first));
     weights.push_back(std::move(it->second));
}
</code>```

Therefore I tried to modify the previous solution just changing the for loop in the following way:

```<code>for (auto it = string_weight.begin(), it2 = it; it != string_weight.end() ; it = string_weight.erase(it, it2)) {
        size_t delta = 100000;
        for ( it2 = it ; it2 != string_weight.end() && it2 != it+delta; it2++ ) {
            strings.push_back(std::move(it2->first));
            weights.push_back(std::move(it2->second));
        }
    }
</code>```

This is faster but the completion time is proportional to the value I choose for delta and I don't like it. Can you help me giving a solution or pointing out some useful technique?

Thank you in advance.

答:
If it weren't for all the levels of abstraction in C++, you could do this in-place.

None of this is possible for the memory owned by a std::vector in C++, of course.  And even in assembly, you'd need a way to tell your memory allocator that your one big allocation is now two smaller allocations.  If you wanted to be able to do this in C++, you'd maybe use a union of arrays or something, or placement new to repurpose raw memory you got from an allocator.

I post this just as an illustration of how much it sucks to have levels of abstraction that make efficient code impossible.  (e.g. C++ new/delete doesn't even have a try_realloc that could let vector attempt to grow or shrink in-place; all the mainstream C++ implementations have a std::vector that always just allocates and copies without even trying to see if there is free address space contiguous with the existing allocation when growing.)  IDK why ISO C++ still hasn't added anything which could allow efficient memory management (besides std::malloc / std::realloc which aren't compatible with new/delete).

If you want to grow a std::vector without writing the new elements (because you want to read() into that memory or something), you need a vector using a custom allocator to not construct the elements.

std::string can be std::moveed, which just boils down to copying the object representation.  And size_t is trivially copyable.

Given the size ratios of the pair of objects, calculate the byte offset of the end of the first output array.  e.g. assuming a 32-byte std::string (3 pointers plus extra space for inline small strings, like libstdc++ on x86-64 uses), and an 8-byte size_t, the ratio is 4:1.  Assuming alignment doesn't require extra padding in each pair, that means the source vector has 40-byte elements.

So for a 10M element source array (400M bytes), the string array will be 10 M elements, 320M bytes, and the size_t array will be 80M bytes.

When we're done, the string array will be the first 320MB of the pair array, and the size_t array will be the next 80MB.  We can calculate ahead of time a pointer to that destination.  The location is also the start of a pair that needs to be read before we overwrite that memory

I'll first explain a 1:1 size ratio of objects in a pair.

load 2 pairs, one from the start of the whole, and from the offset where the 2nd array will start.  (i.e. tmp0 = vec[pos0]; tmp1 = vec[pos1])

store the first member of each tmp pair into the space where the first pair was.

store the second member of each tmp pair into the space where the second was.

Repeat until done, incrementing positions.  Allocating or touching any new memory for this is a total waste of CPU cycles, and will cause unnecessary memory pressure.  On CPUs with SIMD, these loads and shuffles can be nicely vectorized and hopefully run at near-memcpy speed, and fully benefit from the destination being hot in cache vs. copying to new cold memory.

For pairs of uneven sizes, you need to load e.g. 4 pairs from the start for every 1 pair from the middle.  4x 40 = 5x 32, so again we can put the new data back without overwriting anything we haven't read yet.  And in the high part, 1x 40B = 5x 8B.

In C++ you could use a local tmp array and a compiler could still plausibly optimize this into registers for small array sizes.

Alternatively, don't create a huge vector of pairs in the first place.  Read from the file in medium-sized chunks (like 8kiB is a good size that fits comfortably into L1d cache) and parse lines into 2 vectors.

ContentLicense: CC BY-SA 3.0

Body:
I have a big vector of std::pair<std::string,size_t> elements and I want to unpack it in two vectors using small extra memory overhead (I don't want the memory space occupation doubled, i.e. erasing the vector of pairs after the unpacking) and possibly as fast as possible. The following solution is unacceptably slow:

std::vector<std::pair<std::string, size_t>> string_weight;
get_from_file("mybigfile.txt", string_weight); //it just fills the string_weight vector
//... do stuff...
std::vector<std::string> strings;
std::vector<size_t> weights;
for (auto it = string_weight.begin(); it != string_weight.end() ; it = string_weight.erase(it)) {
     strings.push_back(std::move(it->first));
     weights.push_back(std::move(it->second));
}

Therefore I tried to modify the previous solution just changing the for loop in the following way:

for (auto it = string_weight.begin(), it2 = it; it != string_weight.end() ; it = string_weight.erase(it, it2)) {
        size_t delta = 100000;
        for ( it2 = it ; it2 != string_weight.end() && it2 != it+delta; it2++ ) {
            strings.push_back(std::move(it2->first));
            weights.push_back(std::move(it2->second));
        }
    }

This is faster but the completion time is proportional to the value I choose for delta and I don't like it. Can you help me giving a solution or pointing out some useful technique?

Thank you in advance.


问:
Why does python3.7 pass argv elements alongside 'garbage'
I had this script working for me, before I decided I'm gonna rewrite everything and make it portable.
Without delving too much into the details, there's a central Bash script, which calls 5 other Bash scripts in their own respective folders. I have no intention of porting to Windows anytime soon, as of current this is just for Linux.

The execution path of the central Bash script is:

```<code>dos.1/1-init.sh dos.1/

dos.2/1-trace-to-file.sh dos.2/ dos.1/

dos.3/1-recognize-categories.sh dos.3/

dos.4/1-ping-in-groups.sh dos.4/ dos.3/

dos.5/init.sh dos.5/ dos.4/
</code>```

I run with ./init.sh

Before the script was 'portable' I was using explicit file paths inside each respective script. All was well and good. The program itself is a combination of Bash and Python, and writes to files in one directory, so that they can be manipulated in various ways, before being read back into different parts of the program.

I understand that the fastest way to do this would be to write a monolithic Python script, using subprocess calls for the Bash side of things... However, I am doing it this way to ease maintenance, and (before I started making it 'portable') it was lightning fast.

My issue now is this: each time I have to read text into Python (either from SQL or from file) there's always this added garbage. Up until this point, I have been using sed, awk and Python's .rstrip() function to manage this... Which is all well and good, but this one damn function will not play nice... And I feel there must be a better way.

In bash I call it with:

```<code>$prog_dir=$1
$data_dir=$2
$prog_dir/2fast-ping.py $data_dir/group0.txt > $prog_dir/group0_averages.txt
$prog_dir/2fast-ping.py $data_dir/group1.txt > $prog_dir/group1_averages.txt
...
</code>```

Now I know that I could write to file from within Python, but in this instance I have other reasons not to.

The issue, is that when the 2fast-ping.py script is ran, it reads the text file in with commas and a newline char. I have vigorously checked and I can confirm that the group#.txt files 100% do not contain commas. Here's the Python:

```<code>import sys
import subprocess
import select
from concurrent.futures import ThreadPoolExecutor

filename = sys.argv[1]

f = open(filename, "r")
ips = [elem.rstrip('\n') for elem in f]
print(ips)
f.close()
</code>```

The script goes on to do some work on the IPs afterwards, but this is the painful part. If I call the script direct from CLI:  ./2fast-ping.py ../dos.3/group0.txt, the text is processed PROPERLY and the superseding instructions actually function. But, when called from the first init script, the program basically sh*ts itself because each line is read in with commas. It works until the point where it starts to use the processed info, then:

```<code><actual IP would be here>
ping: ('##.###.###.###',): Name or service not known
</code>```

Of course, the issue is the ('',)  But, Python is adding that in, and I don't know how to stop it :(

Any ideas?

答: Python code was okay, just passing an additional / with the argument :(</p>

Body:
I had this script working for me, before I decided I'm gonna rewrite everything and make it portable.
Without delving too much into the details, there's a central Bash script, which calls 5 other Bash scripts in their own respective folders. I have no intention of porting to Windows anytime soon, as of current this is just for Linux.

The execution path of the central Bash script is:

dos.1/1-init.sh dos.1/

dos.2/1-trace-to-file.sh dos.2/ dos.1/

dos.3/1-recognize-categories.sh dos.3/

dos.4/1-ping-in-groups.sh dos.4/ dos.3/

dos.5/init.sh dos.5/ dos.4/

I run with ./init.sh

Before the script was 'portable' I was using explicit file paths inside each respective script. All was well and good. The program itself is a combination of Bash and Python, and writes to files in one directory, so that they can be manipulated in various ways, before being read back into different parts of the program.

I understand that the fastest way to do this would be to write a monolithic Python script, using subprocess calls for the Bash side of things... However, I am doing it this way to ease maintenance, and (before I started making it 'portable') it was lightning fast.

My issue now is this: each time I have to read text into Python (either from SQL or from file) there's always this added garbage. Up until this point, I have been using sed, awk and Python's .rstrip() function to manage this... Which is all well and good, but this one damn function will not play nice... And I feel there must be a better way.

In bash I call it with:

$prog_dir=$1
$data_dir=$2
$prog_dir/2fast-ping.py $data_dir/group0.txt > $prog_dir/group0_averages.txt
$prog_dir/2fast-ping.py $data_dir/group1.txt > $prog_dir/group1_averages.txt
...

Now I know that I could write to file from within Python, but in this instance I have other reasons not to.

The issue, is that when the 2fast-ping.py script is ran, it reads the text file in with commas and a newline char. I have vigorously checked and I can confirm that the group#.txt files 100% do not contain commas. Here's the Python:

import sys
import subprocess
import select
from concurrent.futures import ThreadPoolExecutor

filename = sys.argv[1]

f = open(filename, "r")
ips = [elem.rstrip('\n') for elem in f]
print(ips)
f.close()

The script goes on to do some work on the IPs afterwards, but this is the painful part. If I call the script direct from CLI:  ./2fast-ping.py ../dos.3/group0.txt, the text is processed PROPERLY and the superseding instructions actually function. But, when called from the first init script, the program basically sh*ts itself because each line is read in with commas. It works until the point where it starts to use the processed info, then:

<actual IP would be here>
ping: ('##.###.###.###',): Name or service not known

Of course, the issue is the ('',)  But, Python is adding that in, and I don't know how to stop it :(

Any ideas?


问:
Search into pandas dataframe column for which input value is smaller than the next index column value
I want to search a dataframe to find a value correspond to index row and column value. However, I am struggling because the column header values are the upper bound of a range where the previous column header value is the lower bound ( but the uppper bound of its other neightbor column value).

I cannot find a way to match my input with the column corresponding to the lower bound of the range.

with an example it is very easy to see:

```<code>data_frame_test = pd.DataFrame({'location' : [1, 2, 'S'],
                                '200' : [342, 690, 103],
                                '1000' : [322, 120, 193],
                                '2000' : [249, 990, 403]})

data_frame_test = data_frame_test.set_index('location')
</code>```

and what I want to do is this

```<code>location = 1
weight = 500

output = data_frame_test.iloc[1][??] #must be equal to 342
</code>```

see, the column where weight must look into is 200, because it is in the range between ]200;1000[. I don't know what else to try to translate that into python code. Any help would be greatly appreciated.

答:
I can think of cansting the columns to int, and indexing the dataframe using Series.searchsorted, and boolean indexing on the index:

```<code>location = 1
weight = 500

data_frame_test.iloc[data_frame_test.index==location,
                     data_frame_test.columns.astype('int').searchsorted(weight)-1]

location
1    342
Name: 200, dtype: int64
</code>```

Body:
I want to search a dataframe to find a value correspond to index row and column value. However, I am struggling because the column header values are the upper bound of a range where the previous column header value is the lower bound ( but the uppper bound of its other neightbor column value).

I cannot find a way to match my input with the column corresponding to the lower bound of the range.

with an example it is very easy to see:

data_frame_test = pd.DataFrame({'location' : [1, 2, 'S'],
                                '200' : [342, 690, 103],
                                '1000' : [322, 120, 193],
                                '2000' : [249, 990, 403]})

data_frame_test = data_frame_test.set_index('location')

and what I want to do is this

location = 1
weight = 500

output = data_frame_test.iloc[1][??] #must be equal to 342

see, the column where weight must look into is 200, because it is in the range between ]200;1000[. I don't know what else to try to translate that into python code. Any help would be greatly appreciated.

Body:
I can think of cansting the columns to int, and indexing the dataframe using Series.searchsorted, and boolean indexing on the index:

location = 1
weight = 500

data_frame_test.iloc[data_frame_test.index==location,
                     data_frame_test.columns.astype('int').searchsorted(weight)-1]

location
1    342
Name: 200, dtype: int64


问:
Not able to load Kibana on port 5601
I have installed Elasticsearch, Logstash, Kibana and Nginx following this guide,

https://www.digitalocean.com/community/tutorials/how-to-install-elasticsearch-logstash-and-kibana-elk-stack-on-ubuntu-14-04

Elasticsearch is running on 9200

But running

```<code>curl http://localhost:5601
</code>```

returns this:

```<code>curl: (7) Failed to connect to localhost port 5601: Connection refused
</code>```

In kibana.yml file I configured

```<code>server.port: 5601

server.host: "127.0.0.1"
</code>```

Here I also checked with localhost and aws private ip address.

And while checking the port running this:

```<code>netstat -anp | grep 5601
</code>```

I am getting:

```<code>(No info could be read for "-p": geteuid()=1000 but you should be root.)
</code>```

I can start kibana running:

```<code>sudo service kibana start
</code>```

But while checking status using:

```<code>sudo service kibana status
</code>```

I get:

```<code>kibana is not running
</code>```

I haven't setup firewall and running

```<code>sudo ufw status
</code>```

Returns:

```<code>Status : Inactive
</code>```

I am confused, why is  the kibana port not listening?

答:
For me helped solution from
https://discuss.elastic.co/t/kibana-5601-connection-refused/103641/2</p>

```<code> /opt/kibana/bin/kibana & disown
</code>```

Title: Not able to load Kibana on port 5601

Body:
I have installed Elasticsearch, Logstash, Kibana and Nginx following this guide,

https://www.digitalocean.com/community/tutorials/how-to-install-elasticsearch-logstash-and-kibana-elk-stack-on-ubuntu-14-04

Elasticsearch is running on 9200

But running

curl http://localhost:5601

returns this:

curl: (7) Failed to connect to localhost port 5601: Connection refused

In kibana.yml file I configured

server.port: 5601

server.host: "127.0.0.1"

Here I also checked with localhost and aws private ip address.

And while checking the port running this:

netstat -anp | grep 5601

I am getting:

(No info could be read for "-p": geteuid()=1000 but you should be root.)

I can start kibana running:

sudo service kibana start

But while checking status using:

sudo service kibana status

I get:

kibana is not running

I haven't setup firewall and running

sudo ufw status

Returns:

Status : Inactive

I am confused, why is  the kibana port not listening?

Body:
For me helped solution from
https://discuss.elastic.co/t/kibana-5601-connection-refused/103641/2

 /opt/kibana/bin/kibana & disown


问:
How to parse an Xml having two tags with same name
I am using SAX parser to get a data from XML. unfortunately i am having two tags with same name example <tags> <sametag>Abc</sametag> <sametag>Def</sametag ></tags>. so whenever i am parsing the file i only getting ABC the same tag which contains different data will never parse. if anyone having idea for to parse same name tags pls guide me to solve.

答:
Simple XML Framework:

```<code>@Root(name = "tags")
class Tags {
    @ElementList(entry = "sametag", inline = "true")
    public ArrayList<String> sameTags;
}
</code>```

I have totally not tested that code but you get the gist as to how easy it is to use. To see how to use it in Android take a look at my blog post.

Body:
Simple XML Framework:

@Root(name = "tags")
class Tags {
    @ElementList(entry = "sametag", inline = "true")
    public ArrayList<String> sameTags;
}

I have totally not tested that code but you get the gist as to how easy it is to use. To see how to use it in Android take a look at my blog post.


问:
C# ASP.NET WebApi (2/Core 3.1) Problem with Json serialization of big numbers
I have an issue with big numbers (Int64/UInt64) being rounded by ASP.NET Json serialization.
This happens in ASP.NET WebApi2 (.NET 4.5.2) as well as in ASP.NET Core WebApi (Core 3.1).

This my DTO-class:

```<code>public class TestDTO
{
    public IEnumerable<long> BigNumbers { get; set; }
}
</code>```

This is my controller method:

```<code>[HttpGet]
public IHttpActionResult GetNumberTest()
{
    TestDTO dto = new TestDTO
    {
        BigNumbers = new long[]
        {
            121720000000004554,
            21720000000004554,
            1720000000004554,
            720000000004554,
        }
    };

    return Ok(dto);
}
</code>```

And this is the result:

```<code>{
  "bigNumbers": [
    121720000000004560,
    21720000000004550,
    1720000000004554,
    720000000004554
  ]
}
</code>```

As you can see the first two numbers are rounded (first one being rounded up, second one down), the last two are not rounded. This, of course, can be fatal behaviour. How can I disable this behaviour?

The strange thing is... when I serialize the DTO manually via Newtonsoft.Json (JsonConvert.SerializeObject), then the result is correct.

I know it works when I serialize the numbers as strings, but that´s not a real solution to the problem in my opinion. I should be able to rely on a correct serialization of my DTO.

Can anyone help me please?

答: As it turns out, the serialized raw data is correct. It´s just the visualization of SwaggerUi / Firefox through JavaScript which causes the issue.</p>

Body:
I have an issue with big numbers (Int64/UInt64) being rounded by ASP.NET Json serialization.
This happens in ASP.NET WebApi2 (.NET 4.5.2) as well as in ASP.NET Core WebApi (Core 3.1).

This my DTO-class:

public class TestDTO
{
    public IEnumerable<long> BigNumbers { get; set; }
}

This is my controller method:

[HttpGet]
public IHttpActionResult GetNumberTest()
{
    TestDTO dto = new TestDTO
    {
        BigNumbers = new long[]
        {
            121720000000004554,
            21720000000004554,
            1720000000004554,
            720000000004554,
        }
    };

    return Ok(dto);
}

And this is the result:

{
  "bigNumbers": [
    121720000000004560,
    21720000000004550,
    1720000000004554,
    720000000004554
  ]
}

As you can see the first two numbers are rounded (first one being rounded up, second one down), the last two are not rounded. This, of course, can be fatal behaviour. How can I disable this behaviour?

The strange thing is... when I serialize the DTO manually via Newtonsoft.Json (JsonConvert.SerializeObject), then the result is correct.

I know it works when I serialize the numbers as strings, but that´s not a real solution to the problem in my opinion. I should be able to rely on a correct serialization of my DTO.

Can anyone help me please?


问:
Changing getter value using state value in Vuex
I have this getter that get the value of one item in the state:

```<code>boxdata: state => {
      return state.boxchart.data
    },
</code>```

Now I have another item in state that I use to change the value of getter

Currently I do this when component is mounted but it seems that the data sometimes loads but sometimes does not:

```<code>computed: {
      ...mapGetters(["boxdata"]),
      ...mapState(['reference_fc'])
    },

mounted() {
 this.boxdata[0].chartOptions.series[0].data[0]=this.reference_fc.NSR.values
}
</code>```

So I wonder how can I ensure that the boxdata getter is already updated on the first time that the component loads?

答:
Vue cannot detect array element assignments. This is explained in Caveats.

Try this instead:

```<code>this.$set(this.boxdata[0].chartOptions.series[0].data, 0, this.reference_fc.NSR.values)
</code>```

Body:
I have this getter that get the value of one item in the state:

boxdata: state => {
      return state.boxchart.data
    },

Now I have another item in state that I use to change the value of getter

Currently I do this when component is mounted but it seems that the data sometimes loads but sometimes does not:

computed: {
      ...mapGetters(["boxdata"]),
      ...mapState(['reference_fc'])
    },

mounted() {
 this.boxdata[0].chartOptions.series[0].data[0]=this.reference_fc.NSR.values
}

So I wonder how can I ensure that the boxdata getter is already updated on the first time that the component loads?

Body:
Vue cannot detect array element assignments. This is explained in Caveats.

Try this instead:

this.$set(this.boxdata[0].chartOptions.series[0].data, 0, this.reference_fc.NSR.values)


问:
ERROR Unexpected function expression when "firebase deploy"
I am using React-Native and Expo.
I am doing Push Notification for my application.
When the user receives a new task, it will show a notification by expo.

This is the code for Firebase index.js

```<code>const functions = require('firebase-functions');
var fetch = require('node-fetch')

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

//send the push notification
exports.sendPushNotification =
functions.database.ref('Task/').onCreate(event => {

const root = event.data.ref.root
var messages = []

//return the main promise
return root.child('/users').once('value').then(function (snapshot) {
    snapshot.forEach(function (childSnapshot) {

        var expoToken = childSnapshot.val().expoToken;

        messages.push({
            "to": expoToken,
            "sound": "default",
            "body": "New Task Added"
        });
    });
    //firebase.database then() respved a single promise that resolves
    //once all the messages have been resolved
    return Promise.all(messages)

})
    .then(messages => {
        // console.log(messages)
        fetch('https://exp.host/--/api/v2/push/send', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(messages)

        });
    })
    .catch(reason => {
        console.log(reason)
    })

});
</code>```

I got the following error when I do "firebase deploy"

Can someone please kindly assist me, thank you.

答:
from this

```<code> facts = queryRecords().then(function(result) {
    return result.data
}).catch(function(error) {
    facts = error
});
</code>```

to this

```<code> facts = queryRecords().then(result => {
    return result.data
}).catch(error => {
    facts = error
});
</code>```

Body:
I am using React-Native and Expo.
I am doing Push Notification for my application.
When the user receives a new task, it will show a notification by expo.

This is the code for Firebase index.js

const functions = require('firebase-functions');
var fetch = require('node-fetch')

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

//send the push notification
exports.sendPushNotification =
functions.database.ref('Task/').onCreate(event => {

const root = event.data.ref.root
var messages = []

//return the main promise
return root.child('/users').once('value').then(function (snapshot) {
    snapshot.forEach(function (childSnapshot) {

        var expoToken = childSnapshot.val().expoToken;

        messages.push({
            "to": expoToken,
            "sound": "default",
            "body": "New Task Added"
        });
    });
    //firebase.database then() respved a single promise that resolves
    //once all the messages have been resolved
    return Promise.all(messages)

})
    .then(messages => {
        // console.log(messages)
        fetch('https://exp.host/--/api/v2/push/send', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(messages)

        });
    })
    .catch(reason => {
        console.log(reason)
    })

});

I got the following error when I do "firebase deploy"

Can someone please kindly assist me, thank you.

Body:
from this

 facts = queryRecords().then(function(result) {
    return result.data
}).catch(function(error) {
    facts = error
});

to this

 facts = queryRecords().then(result => {
    return result.data
}).catch(error => {
    facts = error
});


问:
Angular Schematics: How to reach filesToCreate record set coming from previous operation in a chain?
I've made a chained schematics and in the first part I generate a module using:

externalSchematic('@schematics/angular', 'module', moduleOptions).

In the second part/element of the chain I call a schematic I've written and I want to edit one of the files added during above module creation. However tree.visit() iterates on whole project tree, which is highly unnecessary.

When I log tree/host I see it has a private _record and in term that one has a _filesToCreate set containing only files created in previous step.

Is there a helper function or property/method of tree I'm missing that helps?

Update

Adding tree.getDir(path) before calling .visit(), path being specific folder of added files, makes things faster of course.

I just want to know if there is a way to read in my second step of chain, get list of files created/modified in the previous step, since they are kept in host object, I just can't find a way to read that set/list.

答:
When I check the source code I see they are protected members and there seems no public getters or methods exists to expose them for the time being.

♀


问:
Slice an array with spaces in bash
I want to use a key-value storage in bash, and then access the elements and work with them. I have the following code so far, which finds the key in the storage, but can't extract the values from the array without interpreting the spaces.

A straight forward solution to this (since I know there will be three values for each key) is to access those directly, but surely there must be a way to slice the array properly.

```<code># the array is a key: value storage, the keys do not contain spaces, but the values might
# there are always three values for each key, but the number of words in them is unknown
services=("key1" "some values" "another_value" "a lot of values"
          "key2" "other values" "simple_value2" "a lot of values here"
          "key3" "something else here" "another_value3" "whatever")

# this should look for the given value in the array and return the key and respective values if its found
function find_key () {
    arr=("${@:2}")
    len=$(( ${#arr[@]} -1 ))
    for i in $(seq 0 4 "$len")
    do
    if [[ ${arr[$i]} == "$1" ]] ; then
        # this should get the i'th element and 4 following elements (the values), which works correctly
        result="${arr[*]:$i:4}"
        # at this point result is just a regular array and there is no way to separate the values again

        # this prints just one line with all words
        for x in "${result[@]}"; do
            echo "element: '$x'"
        done

        # I want to return the array ("key" "value 1" "value 2" "the third value") from here to work with it later
        echo "${result[@]}"
        return 0
    fi
    done
    return 1
}

key_and_values="$(find_key "key2" "${services[@]}")"
echo "${key_and_values[@]}"
</code>```

The output is:

```<code>element: 'key2 other values simple_value2 a lot of values here'
key2 other values simple_value2 a lot of values here
</code>```

And I am looking for:

```<code>element: 'key2'
element: 'other values'
element: 'simple_value2'
element: 'a lot of values here'
key2 other values simple_value2 a lot of values here
</code>```

答:
I use this tehniq in piu-piu

```<code>array=("abs 123 ---" "DEF 456 +++")
for items in "${array[@]}"; {
    sub=( $items )
    echo  ======
    for item in ${sub[@]}; {
        echo $item
    }
}
</code>```

output

```<code>======
abs
123
---
======
DEF
456
+++
</code>```

Also you can use an associative array and loop over indexes

```<code>declare -A items=( [item1]="123 abc" [item2]="dfe 234" )

for key in ${!items[@]}; {
    echo "key=$key"
    echo "val=${items[$key]}"
}
</code>```

output

```<code>key=item2
val=dfe 234
key=item1
val=123 abc
</code>```

But the question was about slicing right?), of course you can slice an array like this

```<code>array=("abs 123" "DEF 456" "ASA 789")

$ echo "${array[@]:1}"
DEF 456 ASA 789

$ echo "${array[@]::1}"
abs 123

$ echo "${array[@]:1:3}"
DEF 456 ASA 789

$ echo "${array[@]:1:1}"
DEF 456
</code>```

Title: Slice an array with spaces in bash

Body:
I want to use a key-value storage in bash, and then access the elements and work with them. I have the following code so far, which finds the key in the storage, but can't extract the values from the array without interpreting the spaces.

A straight forward solution to this (since I know there will be three values for each key) is to access those directly, but surely there must be a way to slice the array properly.

# the array is a key: value storage, the keys do not contain spaces, but the values might
# there are always three values for each key, but the number of words in them is unknown
services=("key1" "some values" "another_value" "a lot of values"
          "key2" "other values" "simple_value2" "a lot of values here"
          "key3" "something else here" "another_value3" "whatever")

# this should look for the given value in the array and return the key and respective values if its found
function find_key () {
    arr=("${@:2}")
    len=$(( ${#arr[@]} -1 ))
    for i in $(seq 0 4 "$len")
    do
    if [[ ${arr[$i]} == "$1" ]] ; then
        # this should get the i'th element and 4 following elements (the values), which works correctly
        result="${arr[*]:$i:4}"
        # at this point result is just a regular array and there is no way to separate the values again

        # this prints just one line with all words
        for x in "${result[@]}"; do
            echo "element: '$x'"
        done

        # I want to return the array ("key" "value 1" "value 2" "the third value") from here to work with it later
        echo "${result[@]}"
        return 0
    fi
    done
    return 1
}

key_and_values="$(find_key "key2" "${services[@]}")"
echo "${key_and_values[@]}"

The output is:

element: 'key2 other values simple_value2 a lot of values here'
key2 other values simple_value2 a lot of values here

And I am looking for:

element: 'key2'
element: 'other values'
element: 'simple_value2'
element: 'a lot of values here'
key2 other values simple_value2 a lot of values here

Body:
I use this tehniq in piu-piu

array=("abs 123 ---" "DEF 456 +++")
for items in "${array[@]}"; {
    sub=( $items )
    echo  ======
    for item in ${sub[@]}; {
        echo $item
    }
}

output

======
abs
123
---
======
DEF
456
+++

Also you can use an associative array and loop over indexes

declare -A items=( [item1]="123 abc" [item2]="dfe 234" )

for key in ${!items[@]}; {
    echo "key=$key"
    echo "val=${items[$key]}"
}

output

key=item2
val=dfe 234
key=item1
val=123 abc

But the question was about slicing right?), of course you can slice an array like this

array=("abs 123" "DEF 456" "ASA 789")

$ echo "${array[@]:1}"
DEF 456 ASA 789

$ echo "${array[@]::1}"
abs 123

$ echo "${array[@]:1:3}"
DEF 456 ASA 789

$ echo "${array[@]:1:1}"
DEF 456


问:
C# Compiler Warning 1685
So, (seemingly) out of the blue, my project starts getting compiler warning 1685:

The predefined type
  'System.Runtime.CompilerServices.ExtensionAttribute'
  is defined in multiple assemblies in
  the global alias; using definition
  from 'c:\Program Files\Reference
  Assemblies\Microsoft\Framework\v3.5\System.Core.dll'

Perplexed, I researched the MSDN article to figure out its cause. Here's the information I found:

Visual C# Reference: Errors and
  Warnings Compiler Warning (level 1)
  CS1685

Error Message The predefined type
  'System.type name' is defined in
  multiple assemblies in the global
  alias; using definition from 'File
  Name'

This error occurs when a predefined
  system type such as System.int32 is
  found in two assemblies. One way this
  can happen is if you are referencing
  mscorlib from two different places,
  such as trying to run the.Net
  Framework versions 1.0 and 1.1
  side-by-side.

The compiler will use the definition
  from only one of the assemblies. The
  compiler searches only global aliases,
  does not search libraries defined
  /reference. If you have specified
  /nostdlib, the compiler will search
  for Object, and in the future start
  all searches for predefined types in
  the file where it found Object.

Now I'm really scratching my head.

I'm not running two different
versions of the .NET Framework
(unless you count 2.0 and 3.5).

I'm not referencing any bizarre
assemblies that might make me
suspicious.

I don't recall making any changes to my application that would spur this change.

I've verified that all components target .NET Framework version v2.0.50727.

I'm open to suggestions, or ideas on how to correct this. I treat warnings as errors, and it's driving me crazy.

What really bugs me about it is that I don't know why it's occurring. Things that happen should have a discernable cause, and I should know why they happened. If I can't explain it, I can't accurately remedy it. Guesswork is never satisfactory.

The application is straightforward, consisting of a class library, and a windows forms application.

A C# class library DLL providing basic functionality encapsulating database access. This DLL references the following components:

System

System.Core

System.Core.Data

System.Data

System.Data.DataSetExtensions

System.Data.OracleClient

System.Drawing

System.Windows.Forms

System.Xml

System.Xml.Linq

A C# Windows Forms application providing the UI. This application references the following components:

CleanCode

CleanCodeControls (both of these provide syntax editor support, and are locally built against .NET 3.5).

LinqBridge

Roswell.Framework (the class library above)

System

System.Core

System.Data

System.Data.DataSetExtensions

System.Data.OracleClient

System.Deployment

System.Design

System.Drawing

System.Windows.Forms

System.Xml

System.Xml.Linq

Let me know if you need further information and I'll gladly provide it.

答:
Marc is almost certainly correct.  Here's a way to verify

Open Reflector.exe

Add all of Non-System assemblies

F3 and search for ExtensionAttribute

If it pops up anywhere besides System.Core then you know where it's coming from.

OwnerDisplayName: Mike Hofer

Title: C# Compiler Warning 1685

OwnerDisplayName: JaredPar

ContentLicense: CC BY-SA 2.5


问:
Subtotal for hidden rows in Excel Pivot table
I have a pivot table, and need to apply different filters. Is there any way I can keep the subtotal values such that it is not changed for every applied filter, so to include hidden rows as well.

For instance I have this table:

When I apply a filter I get:

But my desired output is (made manually))):

答:
If you manually hide rows, with no filters you get the desired output.

Let me know if this quick fix is not what you want. For something dynamic and applicable to many rows i would have to revise.


问:
Biometric Authentication evaluation with swiftUI
I've been able to get a rudimentary version of Face / Touch ID working inside my app. However, I want to add better fallbacks and error handling.

So I've been researching how to do it. There are fantastic resources like this:

Face ID evaluation process not working properly

However, I can't find anything that works inside a SwiftUI view. At the moment my project won't run with:

```<code>'unowned' may only be applied to class and class-bound protocol types, not 'AuthenticateView'
</code>```

and

```<code>Value of type 'AuthenticateView' has no member 'present'
</code>```

any help would be much appreciated. Thank you!

Here's my code inside AuthenticateView.swift

```<code>func Authenticate(completion: @escaping ((Bool) -> ())){

    //Create a context
    let authenticationContext = LAContext()
    var error:NSError?

    //Check if device have Biometric sensor
    let isValidSensor : Bool = authenticationContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error)

    if isValidSensor {
        //Device have BiometricSensor
        //It Supports TouchID

        authenticationContext.evaluatePolicy(
            .deviceOwnerAuthenticationWithBiometrics,
            localizedReason: "Touch / Face ID authentication",
            reply: { [unowned self] (success, error) -> Void in

                if(success) {
                    // Touch / Face ID recognized success here
                    completion(true)
                } else {
                    //If not recognized then
                    if let error = error {
                        let strMessage = self.errorMessage(errorCode: error._code)
                        if strMessage != ""{
                            self.showAlertWithTitle(title: "Error", message: strMessage)
                        }
                    }
                    completion(false)
                }
        })
    } else {

        let strMessage = self.errorMessage(errorCode: (error?._code)!)
        if strMessage != ""{
            self.showAlertWithTitle(title: "Error", message: strMessage)
        }
    }
}
</code>```

```<code>func errorMessage(errorCode:Int) -> String{

    var strMessage = ""

    switch errorCode {

    case LAError.Code.authenticationFailed.rawValue:
        strMessage = "Authentication Failed"

    case LAError.Code.userCancel.rawValue:
        strMessage = "User Cancel"

    case LAError.Code.systemCancel.rawValue:
        strMessage = "System Cancel"

    case LAError.Code.passcodeNotSet.rawValue:
        strMessage = "Please goto the Settings & Turn On Passcode"

    case LAError.Code.touchIDNotAvailable.rawValue:
        strMessage = "TouchI or FaceID DNot Available"

    case LAError.Code.touchIDNotEnrolled.rawValue:
        strMessage = "TouchID or FaceID Not Enrolled"

    case LAError.Code.touchIDLockout.rawValue:
        strMessage = "TouchID or FaceID Lockout Please goto the Settings & Turn On Passcode"

    case LAError.Code.appCancel.rawValue:
        strMessage = "App Cancel"

    case LAError.Code.invalidContext.rawValue:
        strMessage = "Invalid Context"

    default:
        strMessage = ""

    }
    return strMessage
}
</code>```

```<code>func showAlertWithTitle( title:String, message:String ) {
    let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)

    let actionOk = UIAlertAction(title: "OK", style: .default, handler: nil)
    alert.addAction(actionOk)
    self.present(alert, animated: true, completion: nil)
}
</code>```

答:
Explanation:

'unowned' may only be applied to class and class-bound protocol types, not 'AuthenticateView'

First of all, you have AuthenticateView which is a struct. You can't do it class because whole Apple's SwiftUI idea is about structures. And because Struct is value type and not a Reference type, so no pointer as such. So you may not include code parts containing unowned self and weak self modifiers into struct AuthenticateView: View {}

Value of type 'AuthenticateView' has no member 'present'

present is a UIViewController's method. Here in SwiftUI you have no access to it. The alerts are being presented using the next style:

struct ContentView: View {
    @State private var show = false
    var body: some View {
        Button(action: { self.show = true }) { Text("Click") }
        .alert(isPresented: $showingAlert) {
            Alert(title: Text("Title"),
                message: Text("Message"),
          dismissButton: .default(Text("Close")))
        }
    }
}
```

<p>Solution:
For your case, I would create a <code>class</code> Handler subclass of <code>ObservableObject</code> for your logic and use the power of <code>@ObservedObject</code>, <code>@Published</code> and <code>@State</code>.</p>

<p>Rough example for understanding the concept:</p>

<pre class="lang-swift prettyprint-override"><code>import SwiftUI

struct ContentView: View {
    @ObservedObject var handler = Handler()
    var body: some View {
        Button(action: { self.handler.toggleShowAlert() }) { Text("Click") }
            .alert(isPresented: $handler.shouldShowAlert) {
                Alert(title: Text(handler.someTitle),
                    message: Text(handler.someMessage),
              dismissButton: .default(Text("Close")))
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

class Handler: ObservableObject {
    @Published var shouldShowAlert: Bool = false
    @Published var someTitle = ""
    @Published var someMessage = ""

    func toggleShowAlert() {
        shouldShowAlert.toggle()
        someTitle = "ErrorTitle"
        someMessage = "ErrorMessage"
    }
}
</code>```

Body:
I've been able to get a rudimentary version of Face / Touch ID working inside my app. However, I want to add better fallbacks and error handling.

So I've been researching how to do it. There are fantastic resources like this:

Face ID evaluation process not working properly

However, I can't find anything that works inside a SwiftUI view. At the moment my project won't run with:

'unowned' may only be applied to class and class-bound protocol types, not 'AuthenticateView'

and

Value of type 'AuthenticateView' has no member 'present'

any help would be much appreciated. Thank you!

Here's my code inside AuthenticateView.swift

func Authenticate(completion: @escaping ((Bool) -> ())){

    //Create a context
    let authenticationContext = LAContext()
    var error:NSError?

    //Check if device have Biometric sensor
    let isValidSensor : Bool = authenticationContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error)

    if isValidSensor {
        //Device have BiometricSensor
        //It Supports TouchID

        authenticationContext.evaluatePolicy(
            .deviceOwnerAuthenticationWithBiometrics,
            localizedReason: "Touch / Face ID authentication",
            reply: { [unowned self] (success, error) -> Void in

                if(success) {
                    // Touch / Face ID recognized success here
                    completion(true)
                } else {
                    //If not recognized then
                    if let error = error {
                        let strMessage = self.errorMessage(errorCode: error._code)
                        if strMessage != ""{
                            self.showAlertWithTitle(title: "Error", message: strMessage)
                        }
                    }
                    completion(false)
                }
        })
    } else {

        let strMessage = self.errorMessage(errorCode: (error?._code)!)
        if strMessage != ""{
            self.showAlertWithTitle(title: "Error", message: strMessage)
        }
    }
}

func errorMessage(errorCode:Int) -> String{

    var strMessage = ""

    switch errorCode {

    case LAError.Code.authenticationFailed.rawValue:
        strMessage = "Authentication Failed"

    case LAError.Code.userCancel.rawValue:
        strMessage = "User Cancel"

    case LAError.Code.systemCancel.rawValue:
        strMessage = "System Cancel"

    case LAError.Code.passcodeNotSet.rawValue:
        strMessage = "Please goto the Settings & Turn On Passcode"

    case LAError.Code.touchIDNotAvailable.rawValue:
        strMessage = "TouchI or FaceID DNot Available"

    case LAError.Code.touchIDNotEnrolled.rawValue:
        strMessage = "TouchID or FaceID Not Enrolled"

    case LAError.Code.touchIDLockout.rawValue:
        strMessage = "TouchID or FaceID Lockout Please goto the Settings & Turn On Passcode"

    case LAError.Code.appCancel.rawValue:
        strMessage = "App Cancel"

    case LAError.Code.invalidContext.rawValue:
        strMessage = "Invalid Context"

    default:
        strMessage = ""

    }
    return strMessage
}

func showAlertWithTitle( title:String, message:String ) {
    let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)

    let actionOk = UIAlertAction(title: "OK", style: .default, handler: nil)
    alert.addAction(actionOk)
    self.present(alert, animated: true, completion: nil)
}

Body:
Explanation:

'unowned' may only be applied to class and class-bound protocol types, not 'AuthenticateView'

First of all, you have AuthenticateView which is a struct. You can't do it class because whole Apple's SwiftUI idea is about structures. And because Struct is value type and not a Reference type, so no pointer as such. So you may not include code parts containing unowned self and weak self modifiers into struct AuthenticateView: View {}

Value of type 'AuthenticateView' has no member 'present'

present is a UIViewController's method. Here in SwiftUI you have no access to it. The alerts are being presented using the next style:

struct ContentView: View {
    @State private var show = false
    var body: some View {
        Button(action: { self.show = true }) { Text("Click") }
        .alert(isPresented: $showingAlert) {
            Alert(title: Text("Title"),
                message: Text("Message"),
          dismissButton: .default(Text("Close")))
        }
    }
}

Solution:
For your case, I would create a class Handler subclass of ObservableObject for your logic and use the power of @ObservedObject, @Published and @State.

Rough example for understanding the concept:

import SwiftUI

struct ContentView: View {
    @ObservedObject var handler = Handler()
    var body: some View {
        Button(action: { self.handler.toggleShowAlert() }) { Text("Click") }
            .alert(isPresented: $handler.shouldShowAlert) {
                Alert(title: Text(handler.someTitle),
                    message: Text(handler.someMessage),
              dismissButton: .default(Text("Close")))
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

class Handler: ObservableObject {
    @Published var shouldShowAlert: Bool = false
    @Published var someTitle = ""
    @Published var someMessage = ""

    func toggleShowAlert() {
        shouldShowAlert.toggle()
        someTitle = "ErrorTitle"
        someMessage = "ErrorMessage"
    }
}


问:
Python Concatenation and Sort 3 Dataframes
I am doing concat on three dataframes, doing code like this:

```<code>df_bigram = pd.concat([bigramFreqTable, skipgram, df2],axis=1)
df_bigram
</code>```

And the output of df_bigram is

```<code>                      bigramf   freq           Skipgram   Freq                         bigram          PMI
0  (Asam, deoksiribonukleat,)      1      (unting, DNA)    22                        (12, Å.)    11.487338
1 (deoksiribonukleat,, lebih)      1      (DNA, unting)    22                        (22, Å,)    11.487338
2            (lebih, dikenal)      1        (DNA, yang)    20                     (220, juta)    11.487338
3           (dikenal, dengan)      2        (yang, DNA)    20                 (34, ÅngströmÅ)    11.487338
4         (dengan, singkatan)      1       (DNA, dalam)    13                (A-DNA,, B-DNA,)    11.487338
5            (singkatan, DNA)      1       (dalam, DNA)    13   (Akibatnya,, protein-protein)    11.487338
6                    (DNA, ,)      2   (pasangan, basa)    11                (Alec, Jeffreys)    11.487338
7                 (,, adalah)      1   (basa, pasangan)    11        (Alfred, HersheyHershey)    11.487338
8           (adalah, sejenis)      1    (terdiri, dari)    10      (Asam, deoksiribonukleat,)    11.487338
9       (sejenis, biomolekul)      1    (dari, terdiri)    10            (Bacillus, subtilis)    11.487338
10         (biomolekul, yang)      1        (pada, DNA)    10            (Banyak, yurisdiksi)    11.487338
...            ...                ...          ...         ...               ...                  ...
</code>```

The problem is I want to sort 'freq' by descending value. I just confused why the other column name like 'Freq' and 'PMI', they have been sorted by descending value, meanwhile 'freq' haven't been. So, I am coding this for sorting:

```<code>x = df_bigram.sort_values(by='freq', ascending=False)
x
</code>```

And the output be like this:

```<code>                bigramf   freq             Skipgram   Freq                      bigram          PMI
72        (unting, DNA)    17    (hidrogen, ikatan)     5     (ditranskripsikan., Para)    11.487338
212         (DNA, yang)    15          (satu, pada)     3           (Temperatur, lebur)    10.487338
136    (pasangan, basa)    10          (dalam, ===)     4              (myeloid, akut.)    11.487338
83      (yang, disebut)     9      (rantai, Proses)     5             (gen., Sedangkan)    11.487338
432  (disebut, sebagai)     9     (unting, disebut)     2           (sama., Karenanya,)     9.902375
58      (terdiri, dari)     9       (DNA, memiliki)     6             (darah,, sperma,)    11.487338
525          (Hal, ini)     8       (disebut, satu)     2          (resisten, terhadap)     9.487338
888     (heliks, ganda)     7    (tergulung, lebih)     2         (banyak, kemungkinan)     7.902375
657       (rantai, DNA)     7      (Diplonema, dan)     2                (sebuah, cara)     8.902375
...          ...           ...            ...          ...                 ...                ...
</code>```

while actually I want to sort all of the column name like 'freq', 'Freq', 'PMI' by descending value. What am I doing wrong?

答:
I think this can be corrected by reindexing with the original dataframe columns as follows:

df_bigram = df_bigram.reindex_axis(bigramFreqTable.columns, axis=1)

If you want to sort by single column then what you have implemented above is correct. But if you want to sort by multiple columns then you may try:

x = df_bigram.sort_values(by=['freq','Freq','PMI'], ascending=False)

x

Note:- when sorting by multiple columns, pandas sort_value() uses the first variable first and second variable next.

Body:
I am doing concat on three dataframes, doing code like this:

df_bigram = pd.concat([bigramFreqTable, skipgram, df2],axis=1)
df_bigram

And the output of df_bigram is

                      bigramf   freq           Skipgram   Freq                         bigram          PMI
0  (Asam, deoksiribonukleat,)      1      (unting, DNA)    22                        (12, Å.)    11.487338
1 (deoksiribonukleat,, lebih)      1      (DNA, unting)    22                        (22, Å,)    11.487338
2            (lebih, dikenal)      1        (DNA, yang)    20                     (220, juta)    11.487338
3           (dikenal, dengan)      2        (yang, DNA)    20                 (34, ÅngströmÅ)    11.487338
4         (dengan, singkatan)      1       (DNA, dalam)    13                (A-DNA,, B-DNA,)    11.487338
5            (singkatan, DNA)      1       (dalam, DNA)    13   (Akibatnya,, protein-protein)    11.487338
6                    (DNA, ,)      2   (pasangan, basa)    11                (Alec, Jeffreys)    11.487338
7                 (,, adalah)      1   (basa, pasangan)    11        (Alfred, HersheyHershey)    11.487338
8           (adalah, sejenis)      1    (terdiri, dari)    10      (Asam, deoksiribonukleat,)    11.487338
9       (sejenis, biomolekul)      1    (dari, terdiri)    10            (Bacillus, subtilis)    11.487338
10         (biomolekul, yang)      1        (pada, DNA)    10            (Banyak, yurisdiksi)    11.487338
...            ...                ...          ...         ...               ...                  ...

The problem is I want to sort 'freq' by descending value. I just confused why the other column name like 'Freq' and 'PMI', they have been sorted by descending value, meanwhile 'freq' haven't been. So, I am coding this for sorting:

x = df_bigram.sort_values(by='freq', ascending=False)
x

And the output be like this:

                bigramf   freq             Skipgram   Freq                      bigram          PMI
72        (unting, DNA)    17    (hidrogen, ikatan)     5     (ditranskripsikan., Para)    11.487338
212         (DNA, yang)    15          (satu, pada)     3           (Temperatur, lebur)    10.487338
136    (pasangan, basa)    10          (dalam, ===)     4              (myeloid, akut.)    11.487338
83      (yang, disebut)     9      (rantai, Proses)     5             (gen., Sedangkan)    11.487338
432  (disebut, sebagai)     9     (unting, disebut)     2           (sama., Karenanya,)     9.902375
58      (terdiri, dari)     9       (DNA, memiliki)     6             (darah,, sperma,)    11.487338
525          (Hal, ini)     8       (disebut, satu)     2          (resisten, terhadap)     9.487338
888     (heliks, ganda)     7    (tergulung, lebih)     2         (banyak, kemungkinan)     7.902375
657       (rantai, DNA)     7      (Diplonema, dan)     2                (sebuah, cara)     8.902375
...          ...           ...            ...          ...                 ...                ...

while actually I want to sort all of the column name like 'freq', 'Freq', 'PMI' by descending value. What am I doing wrong?


问:
vue-meta => How to change the header information
I have a nuxtjs project with a page opening on a url like server\posts\id. On this page I have added head information to influence the meta tags. However, some tags are post specific and need to be filled dynamically. This only seems possible after you have data loaded in mounted. How can I add the meta maniplulation to mounted?

答:
Right way to get meta from api is: using fetch method

```<code>  async fetch({ store, params }) {
    await store.dispatch('modules/item/get_item', params.article)
  },
</code>```

Use Computed :

```<code>  computed: {
    ...mapState('modules/item', {
      Item: (state) => state.data
    })
  },
</code>```

and use nuxt head (vue-meta)

```<code>head() {
    return {
      title:
        this.$store.state.modules.general.info.name + ' / ' + this.Item.title,
      meta: [
        {
          hid: 'description',
          name: 'description',
          content:
            this.$store.state.modules.general.info.name +
            ' / ' +
            this.Item.seo_description
        },
  }
</code>```

Body:
Right way to get meta from api is: using fetch method

  async fetch({ store, params }) {
    await store.dispatch('modules/item/get_item', params.article)
  },

Use Computed :

  computed: {
    ...mapState('modules/item', {
      Item: (state) => state.data
    })
  },

and use nuxt head (vue-meta)

head() {
    return {
      title:
        this.$store.state.modules.general.info.name + ' / ' + this.Item.title,
      meta: [
        {
          hid: 'description',
          name: 'description',
          content:
            this.$store.state.modules.general.info.name +
            ' / ' +
            this.Item.seo_description
        },
  }


问:
How to specify the size of a shared Docker volume?
If I would like to create a data volume of let´s say 15GB that would be of type ext4, how would I do that?

docker volume create --name vol just creates an empty volume.

docker volume create --opt type=ext4 --name vol creates an ext4 volume but I cannot specify the size of it since ext4 does not support it according to the mount options of ext4.

答:
Leaning on the answer of Rao, there are now some udpated docs and example on their docs.docker page:

Create a volume and pass the size option with the opt flag

This example volume creation is taken from this page:

```<code>$ docker volume create --driver local \
--opt type=tmpfs \
--opt device=tmpfs \
--opt o=size=100m,uid=1000 \
foo
</code>```

Body:
Leaning on the answer of Rao, there are now some udpated docs and example on their docs.docker page:

Create a volume and pass the size option with the opt flag

This example volume creation is taken from this page:

$ docker volume create --driver local \
--opt type=tmpfs \
--opt device=tmpfs \
--opt o=size=100m,uid=1000 \
foo


问:
Create a generic data factory with multiple linked services
Use Case: To create a generic data factory which can read data from different azure blob containers which has flat files into Azure SQL. I have created a data pipeline which uses stored procedures to populate the Azure SQL tables.

Issue: The trouble that I have is that I want to execute this data factory from my code and change the database and blob container on the fly and execute the same data factory with this new parameters. The Table names will remain the same on the Azure SQL side and the File name will also remain same in the blob storage. The change will the the Container or the folder name inside the Container which will be know before hand.

Please help me out or point me in the direction as to what could help me achieve this and if this can be at all be achieved or not.

答:
You would need to use the parameterized datasets and linked services. Define parameters on your data factory pipeline (which you want to pass from your code e.g. container name or the folder name, connection string for SQL azure and connection string for blob storage). Once this is defined - you would need to pass these values downstream all the way till the linked service

i.e. something like this
Pipeline Parameters > Dataset Parameters > Linked Service Parameters


问:
Using Index annotation on superclass with Hibernate
I have an abstract superclass which every Entity on my domain is a subclass of it.

Using DB schema generation, I want to create an Index for each Entity, on a field on the superclass, and without using the Table annotation on every subclass.

My superclass

    @MappedSuperclass
    public abstract class BaseEntity {

        @Id
        @GeneratedValue(strategy = SEQUENCE)
        private Long surrogateId;

        @Index(name="id_index") // Every subclass should inherit this index, with its own name
        @Column(unique = true, updatable = false, nullable = false)
        private UUID id = UUID.randomUUID();
```

<p>An example of subclass</p>

<pre class="lang-java prettyprint-override"><code>    @Entity
    public class Customer extends BaseEntity {
        ...
    }
</code>```

I tried so far:

use the Table annotation with @Index on the superclass, but Hibernate
doesn't seem to use that annotation if it is not marked with @Entity.
For example
@Table(indexes = {@Index(name="index_id", columnList = "id")})
No SQL statements are generated.

use the deprecated @Index annotation with a name "id_index", but only one index
is created on startup (the db raises an error that this index already
exists for other entities). Some generated SQL statements:

```<code>    Hibernate: create index id_index on "customer" ("id")

    Hibernate: create index id_index on "user" ("id")

    2020-02-15 17:47:26,620 WARN  o.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl    - GenerationTarget encountered exception accepting command : Error executing DDL "create index id_index on "customer" ("id")" via JDBC Statement
    org.postgresql.util.PSQLException: ERROR: relation "id_index" already exists
</code>```

Any ideas on how to do this without too much code duplication?

Thanks

答:
Alan Hay answer may work but it seems a bit of overengineering... So I decided to not use schema generation and use Liquibase instead, so I can have more control over the database.

Anyway, If anyone is having the same problem with schema generation, I tried with @Index (using eclipselink) and it worked, so this issue is only in Hibernate.

Body:
I have an abstract superclass which every Entity on my domain is a subclass of it.

Using DB schema generation, I want to create an Index for each Entity, on a field on the superclass, and without using the Table annotation on every subclass.

My superclass

    @MappedSuperclass
    public abstract class BaseEntity {

        @Id
        @GeneratedValue(strategy = SEQUENCE)
        private Long surrogateId;

        @Index(name="id_index") // Every subclass should inherit this index, with its own name
        @Column(unique = true, updatable = false, nullable = false)
        private UUID id = UUID.randomUUID();

An example of subclass

    @Entity
    public class Customer extends BaseEntity {
        ...
    }

I tried so far:

use the Table annotation with @Index on the superclass, but Hibernate
doesn't seem to use that annotation if it is not marked with @Entity.
For example
@Table(indexes = {@Index(name="index_id", columnList = "id")})
No SQL statements are generated.

use the deprecated @Index annotation with a name "id_index", but only one index
is created on startup (the db raises an error that this index already
exists for other entities). Some generated SQL statements:

    Hibernate: create index id_index on "customer" ("id")

    Hibernate: create index id_index on "user" ("id")

    2020-02-15 17:47:26,620 WARN  o.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl    - GenerationTarget encountered exception accepting command : Error executing DDL "create index id_index on "customer" ("id")" via JDBC Statement
    org.postgresql.util.PSQLException: ERROR: relation "id_index" already exists

Any ideas on how to do this without too much code duplication?

Thanks


问:
Set a variable equal to null if it is not included in an array?
If I have something like,

```<code>const {
  someProperty,
  anotherProperty,
  thirdProperty
} = someObject;

const includeProperties = ['someProperty', 'thirdProperty']
</code>```

Is it possible to make anotherProperty = null?

答:
You may nullify all the not needed properties within source object shallow copy and destructure that:

const srcObj = {a:1, b:2, c:3},
      neededKeys = ['a','b'],
      objCopy = (obj =>
        (Object.keys(obj).forEach(key =>
          !neededKeys.includes(key) && (obj[key]=null)), obj)
      )({...srcObj}),
      {a,b,c} = objCopy

console.log(a,b,c)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper{min-height:100%;}</code>```

Body:
If I have something like,

const {
  someProperty,
  anotherProperty,
  thirdProperty
} = someObject;

const includeProperties = ['someProperty', 'thirdProperty']

Is it possible to make anotherProperty = null?

Body:
You may nullify all the not needed properties within source object shallow copy and destructure that:

const srcObj = {a:1, b:2, c:3},
      neededKeys = ['a','b'],
      objCopy = (obj =>
        (Object.keys(obj).forEach(key =>
          !neededKeys.includes(key) && (obj[key]=null)), obj)
      )({...srcObj}),
      {a,b,c} = objCopy

console.log(a,b,c)

.as-console-wrapper{min-height:100%;}


问:
SQL adding new column
I would be happy to ask my first question on StackOverflow.

I have two tables (employees and salaries) within my database (employees).

Employees table looks like this:

```<code>+------------+---------------+------+-----+---------+-------+
| Field      | Type          | Null | Key | Default | Extra |
+------------+---------------+------+-----+---------+-------+
| emp_no     | int           | NO   | PRI | NULL    |       |
| first_name | varchar(14)   | NO   |     | NULL    |       |
| last_name  | varchar(16)   | NO   |     | NULL    |       |
+------------+---------------+------+-----+---------+-------+
</code>```

Salaries table looks like this:

```<code>+-----------+------+------+-----+---------+-------+
| Field     | Type | Null | Key | Default | Extra |
+-----------+------+------+-----+---------+-------+
| emp_no    | int  | NO   | PRI | NULL    |       |
| salary    | int  | NO   |     | NULL    |       |
| from_date | date | NO   | PRI | NULL    |       |
| to_date   | date | NO   |     | NULL    |       |
+-----------+------+------+-----+---------+-------+
</code>```

I want to return values for a specific date interval. For instance, I want to know what salary an employee had for an interval in a dynamic view, for the 1990-1991 years for 1991-1992 years, etc.

I wrote the following query:

```<code>SELECT
    e.emp_no,
    e.first_name,
    e.last_name,
    s.salary AS Salary_for_1990
FROM
    employees e
        JOIN
    salaries s ON e.emp_no = s.emp_no
WHERE
    from_date BETWEEN '1990-01-01' AND '1990-12-31'
GROUP BY e.emp_no
ORDER BY e.emp_no ASC
LIMIT 10;
</code>```

I got the following result:

```<code>+--------+------------+-----------+-----------------+
| emp_no | first_name | last_name | Salary_for_1990 |
+--------+------------+-----------+-----------------+
|  10001 | Georgi     | Facello   |           66961 |
|  10004 | Christian  | Koblick   |           48271 |
|  10005 | Kyoichi    | Maliniak  |           82621 |
|  10006 | Anneke     | Preusig   |           40000 |
|  10007 | Tzvetan    | Zielinski |           60740 |
|  10009 | Sumant     | Peace     |           70889 |
|  10011 | Mary       | Sluis     |           42365 |
|  10013 | Eberhardt  | Terkki    |           46305 |
|  10018 | Kazuhide   | Peha      |           61648 |
|  10021 | Ramzi      | Erde      |           59700 |
+--------+------------+-----------+-----------------+
</code>```

So it works for a single value '1990-1991' years, however, I seek for a possibility to add in the query additional column for '1991-1992', '1992-1993' years, etc to be able to see the dynamic growth of employee's salaries.

I thought about variables, however, I don't have an idea how to query it within the context.

Look forward to your answers.
 Thank you in advance.

答:
If you want to make this 'scaleable' then you should use conditional aggregation and prepared statements for example

```<code>drop table if exists t;
create table t(emp int,dt date,salary int);

insert into t values
(1,'2015-06-30',7),
(1,'2015-12-31',10),
(1,'2016-12-31',05),
(1,'2017-12-31',10),
(2,'2015-12-31',20),
(2,'2016-12-31',25),
(2,'2017-12-31',30);

set @sql =
        (select group_concat(concat('max(case when year(dt) = ',dt ,' then salary else 0 end) as ', 'yr',dt))
        from
        (
        select distinct year(dt) dt from t
        ) s
        )
;
set @sql = (select concat('Select emp,',@sql,' from t group by emp'));

prepare sqlstmt from @sql;
execute sqlstmt;
deallocate prepare sqlstmt;

+------+--------+--------+--------+
| emp  | yr2015 | yr2016 | yr2017 |
+------+--------+--------+--------+
|    1 |     10 |      5 |     10 |
|    2 |     20 |     25 |     30 |
+------+--------+--------+--------+
2 rows in set (0.00 sec)
</code>```

Note this will return the MAX salary in any given year.

Title: SQL adding new column

Body:
I would be happy to ask my first question on StackOverflow.

I have two tables (employees and salaries) within my database (employees).

Employees table looks like this:

+------------+---------------+------+-----+---------+-------+
| Field      | Type          | Null | Key | Default | Extra |
+------------+---------------+------+-----+---------+-------+
| emp_no     | int           | NO   | PRI | NULL    |       |
| first_name | varchar(14)   | NO   |     | NULL    |       |
| last_name  | varchar(16)   | NO   |     | NULL    |       |
+------------+---------------+------+-----+---------+-------+

Salaries table looks like this:

+-----------+------+------+-----+---------+-------+
| Field     | Type | Null | Key | Default | Extra |
+-----------+------+------+-----+---------+-------+
| emp_no    | int  | NO   | PRI | NULL    |       |
| salary    | int  | NO   |     | NULL    |       |
| from_date | date | NO   | PRI | NULL    |       |
| to_date   | date | NO   |     | NULL    |       |
+-----------+------+------+-----+---------+-------+

I want to return values for a specific date interval. For instance, I want to know what salary an employee had for an interval in a dynamic view, for the 1990-1991 years for 1991-1992 years, etc.

I wrote the following query:

SELECT
    e.emp_no,
    e.first_name,
    e.last_name,
    s.salary AS Salary_for_1990
FROM
    employees e
        JOIN
    salaries s ON e.emp_no = s.emp_no
WHERE
    from_date BETWEEN '1990-01-01' AND '1990-12-31'
GROUP BY e.emp_no
ORDER BY e.emp_no ASC
LIMIT 10;

I got the following result:

+--------+------------+-----------+-----------------+
| emp_no | first_name | last_name | Salary_for_1990 |
+--------+------------+-----------+-----------------+
|  10001 | Georgi     | Facello   |           66961 |
|  10004 | Christian  | Koblick   |           48271 |
|  10005 | Kyoichi    | Maliniak  |           82621 |
|  10006 | Anneke     | Preusig   |           40000 |
|  10007 | Tzvetan    | Zielinski |           60740 |
|  10009 | Sumant     | Peace     |           70889 |
|  10011 | Mary       | Sluis     |           42365 |
|  10013 | Eberhardt  | Terkki    |           46305 |
|  10018 | Kazuhide   | Peha      |           61648 |
|  10021 | Ramzi      | Erde      |           59700 |
+--------+------------+-----------+-----------------+

So it works for a single value '1990-1991' years, however, I seek for a possibility to add in the query additional column for '1991-1992', '1992-1993' years, etc to be able to see the dynamic growth of employee's salaries.

I thought about variables, however, I don't have an idea how to query it within the context.

Look forward to your answers.
 Thank you in advance.

Body:
If you want to make this 'scaleable' then you should use conditional aggregation and prepared statements for example

drop table if exists t;
create table t(emp int,dt date,salary int);

insert into t values
(1,'2015-06-30',7),
(1,'2015-12-31',10),
(1,'2016-12-31',05),
(1,'2017-12-31',10),
(2,'2015-12-31',20),
(2,'2016-12-31',25),
(2,'2017-12-31',30);

set @sql =
        (select group_concat(concat('max(case when year(dt) = ',dt ,' then salary else 0 end) as ', 'yr',dt))
        from
        (
        select distinct year(dt) dt from t
        ) s
        )
;
set @sql = (select concat('Select emp,',@sql,' from t group by emp'));

prepare sqlstmt from @sql;
execute sqlstmt;
deallocate prepare sqlstmt;

+------+--------+--------+--------+
| emp  | yr2015 | yr2016 | yr2017 |
+------+--------+--------+--------+
|    1 |     10 |      5 |     10 |
|    2 |     20 |     25 |     30 |
+------+--------+--------+--------+
2 rows in set (0.00 sec)

Note this will return the MAX salary in any given year.


问:
Check the Keys of an external JSON File in Java
as the Title states i would like to check the Keys of an external Json File in Java.

What i tried:

```<code>JSONObject json = new JSONObject("src/com/json/inventory.json");
System.out.println(json.keys());
</code>```

Issue: Doesn't do anything.

What are other posibilities?

Thank you in advance!

EDIT
Error

答:
Get JSON file from Assets Folder

Print all keys from JSON

-

```<code>private String getJSonFromAssets(){
    String json = null;
    try {
        InputStream is = getAssets().open("colorAndValue.json");
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException e) {
        e.printStackTrace();
    }
    return json;
}

---

try {
        JSONObject jsonObject = new JSONObject(getJSonFromAssets());
        Iterator<String> keys = jsonObject.keys();
        while(keys.hasNext()) {
            String key = keys.next();
            System.out.println(key);
            Log.d("innerKey", "key " + key);
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
</code>```

And your output will be like
 1. key color0
 2. key color1
 3. key color2
 4. key color3
 5. key color4
 6. key color5

Body:
as the Title states i would like to check the Keys of an external Json File in Java.

What i tried:

JSONObject json = new JSONObject("src/com/json/inventory.json");
System.out.println(json.keys());

Issue: Doesn't do anything.

What are other posibilities?

Thank you in advance!

EDIT
Error

Body:
Get JSON file from Assets Folder

Print all keys from JSON

-

private String getJSonFromAssets(){
    String json = null;
    try {
        InputStream is = getAssets().open("colorAndValue.json");
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException e) {
        e.printStackTrace();
    }
    return json;
}

---

try {
        JSONObject jsonObject = new JSONObject(getJSonFromAssets());
        Iterator<String> keys = jsonObject.keys();
        while(keys.hasNext()) {
            String key = keys.next();
            System.out.println(key);
            Log.d("innerKey", "key " + key);
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

And your output will be like
 1. key color0
 2. key color1
 3. key color2
 4. key color3
 5. key color4
 6. key color5


问:
How to format cell with datetime object of the form 'yyyy-mm-dd hh:mm:ss' in Excel using openpyxl
So, given:

```<code>dttm = datetime.datetime.strptime("2014-06-23 13:56:30", "%Y-%m-%d %H:%M:%S")
ws['A1'] = dttm
</code>```

The result in excel is that the correct date-time is written to the cell (you can see it where you'd input formulas). BUT, the cell display format is only MM/DD/YYYY.

I need the cell to display like "6/23/2014 13:56" instead of just "6/23/2014".

How can I explicitly format the cell to accomplish this?

Thanks!

Edit

@alecxe This solution works and is exactly what I asked for. I would like to be able to save styles like the solution by @Woodham. Unfortunately it raises a typeError (see comment). Any suggestions?

答:
I found that this worked. Although number_format is used it seems to recognise the date format specified when put into the excel wb.  </p>

```<code>import datetime
date = datetime.date(2020, 2, 24) # python datetime format is yyyy mm dd
ws.cell(row=[row_ref], column=[col_ref], value=date)
ws.cell(row=[row_ref], column=[col_ref]).number_format = 'dd/mm/yy'
</code>```

Body:
So, given:

dttm = datetime.datetime.strptime("2014-06-23 13:56:30", "%Y-%m-%d %H:%M:%S")
ws['A1'] = dttm

The result in excel is that the correct date-time is written to the cell (you can see it where you'd input formulas). BUT, the cell display format is only MM/DD/YYYY.

I need the cell to display like "6/23/2014 13:56" instead of just "6/23/2014".

How can I explicitly format the cell to accomplish this?

Thanks!

Edit

@alecxe This solution works and is exactly what I asked for. I would like to be able to save styles like the solution by @Woodham. Unfortunately it raises a typeError (see comment). Any suggestions?

Body:
I found that this worked. Although number_format is used it seems to recognise the date format specified when put into the excel wb.

import datetime
date = datetime.date(2020, 2, 24) # python datetime format is yyyy mm dd
ws.cell(row=[row_ref], column=[col_ref], value=date)
ws.cell(row=[row_ref], column=[col_ref]).number_format = 'dd/mm/yy'


问:
How can I limit the area of chip items (the wrap area) to 2 lines max inside the ChipGroup?
I am trying to implement a ChipGroup with some chip items inside it. Which works fine so far. But My requirement is to show these items inside the ChipGroup with certain number of rows. As example: I have 20 items as chip inside my group, And only 6/7 items fits in between the 2 lines. So, I want to show the chips which fit into the ChipGroup between 2 lines only.

Currently I am getting this (sample) output:

And my expectation is like below:

Additional queries:

Is it possible to get the current row count of chip items from the

ChipGroup? If yes how?

Can I set the maximum visible rows for the    ChipGroup
programatically?

答:
I use customer view to make this feature.

```<code>public class AppChipGroup extends ChipGroup {

    private static final int[] MAX_HEIGHT_ATTRS = {android.R.attr.maxHeight};

    private int mMaxHeight = Integer.MAX_VALUE;

    public AppChipGroup(Context context) {
        super(context);
    }

    public AppChipGroup(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AppChipGroup(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, MAX_HEIGHT_ATTRS);
        mMaxHeight = typedArray.getDimensionPixelSize(0, Integer.MAX_VALUE);
        typedArray.recycle();
    }

    @SuppressLint("RestrictedApi")
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int height = Math.min(getMeasuredHeight(), mMaxHeight);
        setMeasuredDimension(getMeasuredWidth(), height);
    }

}
</code>```

then when use ChipGroup, set the maxHeight value.

```<code><packagename.chip.AppChipGroup
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    style="@style/Widget.MaterialComponents.ChipGroup"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:maxHeight="@dimen/search_input_history_max_height"
    app:chipSpacing="@dimen/search_input_history_chip_space" />
</code>```

Or you can get the chip height and calculate the max_height in onMeasure method and set the measure dimension.

Body:
I use customer view to make this feature.

public class AppChipGroup extends ChipGroup {

    private static final int[] MAX_HEIGHT_ATTRS = {android.R.attr.maxHeight};

    private int mMaxHeight = Integer.MAX_VALUE;

    public AppChipGroup(Context context) {
        super(context);
    }

    public AppChipGroup(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AppChipGroup(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, MAX_HEIGHT_ATTRS);
        mMaxHeight = typedArray.getDimensionPixelSize(0, Integer.MAX_VALUE);
        typedArray.recycle();
    }

    @SuppressLint("RestrictedApi")
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int height = Math.min(getMeasuredHeight(), mMaxHeight);
        setMeasuredDimension(getMeasuredWidth(), height);
    }

}

then when use ChipGroup, set the maxHeight value.

<packagename.chip.AppChipGroup
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    style="@style/Widget.MaterialComponents.ChipGroup"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:maxHeight="@dimen/search_input_history_max_height"
    app:chipSpacing="@dimen/search_input_history_chip_space" />

Or you can get the chip height and calculate the max_height in onMeasure method and set the measure dimension.


问:
Swift dyld: Library not loaded: @rpath/Charts.framework/Charts
I've a IOS swift application which uses 2 externs packages, 1) SwiftKeychainWrapper and 2) Charts. Both these packages have been installed using 'pod' and my Podfile is as follows,

```<code># Uncomment the next line to define a global platform for your project
platform :ios, '9.0'
use_frameworks!

target 'MyApp' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  pod 'SwiftKeychainWrapper', '~> 3.0'
  pod 'Charts'

  # Pods for MyApp

  target 'MyAppTests' do
    inherit! :search_paths
    # Pods for testing
  end
</code>```

target 'MyAppUITests' do
    inherit! :search_paths
    # Pods for testing
  end
end

I'm using Xcode version 9.2

Directory structure looks like this,

```<code>MyApp
...
...
Pods
    Podfile
    Frameworks
        iOS
            Foundation.framework
     Pods
         Charts
             Core
             Support Files
         SwiftkeychainWrapper
    Products
    Target Support Files
</code>```

Under MyApp settings, I see following two interesting tabs,

```<code> - General
      Embedded Binaries
         —
      Linked Frameworks and Libraries
         Name
         Pods_MyApp.framework
</code>```

Both SwiftKeychainWrapper and Charts is installed using 'pod install'.

I also added "Charts.framework" under Linked Frameworks and Libraries but I got above error. I tried adding 'Charts.framework" under 'Embeddd section' but still got same error.

If I follow current instructions from https://github.com/danielgindi/Charts which says following,

```<code>Drag the Charts.xcodeproj to your project
Go to your target's settings, hit the "+" under the "Embedded Binaries" section, and select the Charts.framework
@import Charts
</code>```

Which says to add this under 'Embedded binaries'. If I do that then the build fails for 'SwiftKeychainWrapper'.

BTW, this error happens when I tried to run it on my physical iphone6 device. It works ok on simulator. I really don't know how to proceed. Any help is appreciated.

答:
Check Chart Framework add in General-> Embedded Binaries + --> ChartFramework.

if added change Embed column with 'Embed & sign'

and run.

It's work for me.

Body:
I've a IOS swift application which uses 2 externs packages, 1) SwiftKeychainWrapper and 2) Charts. Both these packages have been installed using 'pod' and my Podfile is as follows,

# Uncomment the next line to define a global platform for your project
platform :ios, '9.0'
use_frameworks!

target 'MyApp' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  pod 'SwiftKeychainWrapper', '~> 3.0'
  pod 'Charts'

  # Pods for MyApp

  target 'MyAppTests' do
    inherit! :search_paths
    # Pods for testing
  end

target 'MyAppUITests' do
    inherit! :search_paths
    # Pods for testing
  end
end

I'm using Xcode version 9.2

Directory structure looks like this,

MyApp
...
...
Pods
    Podfile
    Frameworks
        iOS
            Foundation.framework
     Pods
         Charts
             Core
             Support Files
         SwiftkeychainWrapper
    Products
    Target Support Files

Under MyApp settings, I see following two interesting tabs,

 - General
      Embedded Binaries
         —
      Linked Frameworks and Libraries
         Name
         Pods_MyApp.framework

Both SwiftKeychainWrapper and Charts is installed using 'pod install'.

I also added "Charts.framework" under Linked Frameworks and Libraries but I got above error. I tried adding 'Charts.framework" under 'Embeddd section' but still got same error.

If I follow current instructions from https://github.com/danielgindi/Charts which says following,

Drag the Charts.xcodeproj to your project
Go to your target's settings, hit the "+" under the "Embedded Binaries" section, and select the Charts.framework
@import Charts

Which says to add this under 'Embedded binaries'. If I do that then the build fails for 'SwiftKeychainWrapper'.

BTW, this error happens when I tried to run it on my physical iphone6 device. It works ok on simulator. I really don't know how to proceed. Any help is appreciated.