问:
Default query params not getting passed in axios request
I'm using axios.create() to pass in a baseURL and some default query params like this

```<code>axios.create({
    baseURL: 'http://somebigurlhere',
    params: {
        part: 'part',
        maxResults: 5,
        key: 'key'
   }
});
</code>```

When I use

```<code>axios.get('/search', {
    params: {
        q: 'word'
    }
});
</code>```

the default params do not get merged in the GET call.

What I get is
http://somebigurlhere/search?q=word

instead of
http://somebigurlhere/search?part=part&maxResults=5&key=key&q=asd

I tried putting the configuration in many other ways but it still doesn't work.
Am i doing something wrong here ?

I tried the same in other projects and it is working there. Just created a new react app with create-react-app and this doesn't seem to work anymore.

答:
Use should return a custom object like this

```<code>const custom = axios.create({
    baseURL: 'http://somebigurlhere',
    params: {
        part: 'part',
        maxResults: 5,
        key: 'key'
   }
});
</code>```

Then use the custom object to make request

```<code>custom.get('/search', {
    params: {
        q: 'word'
    }
});
</code>```

Please try similar example in this codepen

Then you will see in the console, the query parameters are merged together in the request (blue line) as following image

Body:
I'm using axios.create() to pass in a baseURL and some default query params like this

axios.create({
    baseURL: 'http://somebigurlhere',
    params: {
        part: 'part',
        maxResults: 5,
        key: 'key'
   }
});

When I use

axios.get('/search', {
    params: {
        q: 'word'
    }
});

the default params do not get merged in the GET call.

What I get is
http://somebigurlhere/search?q=word

instead of
http://somebigurlhere/search?part=part&maxResults=5&key=key&q=asd

I tried putting the configuration in many other ways but it still doesn't work.
Am i doing something wrong here ?

I tried the same in other projects and it is working there. Just created a new react app with create-react-app and this doesn't seem to work anymore.

Body:
Use should return a custom object like this

const custom = axios.create({
    baseURL: 'http://somebigurlhere',
    params: {
        part: 'part',
        maxResults: 5,
        key: 'key'
   }
});

Then use the custom object to make request

custom.get('/search', {
    params: {
        q: 'word'
    }
});

Please try similar example in this codepen

Then you will see in the console, the query parameters are merged together in the request (blue line) as following image


来源: stackexchange

问:
Problem with propagation (choosing right) in declarative transaction in Spring
I have a question about propagation in @Transactional annotation. I need to make two operations in one method and every should be in own transaction after which is making commit.

```<code>@Service
@Transactional
public class FakturaServiceImpl implements FakturaService {

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Integer przyjmijZaliczkeNaPodstPlatnosci(Integer platnoscId) {

      Platnosc plat = Optional.ofNullable(platDao.findOne(platnoscId))
             .orElseThrow(() -> new RecordNotExistsException("Platnosc", platnoscId));

      // here should be beginning of transaction
      Integer faktId = utworzFaktureZaliczkowaNaPodstPlatnosci(plat);
      // commit
      // start new transaction
      rachotwMgr.dodajRachotwDlaZaliczekNaFakturze(faktId);
      // commit

      // ...
      return faktId;
    }

    @Override
    public Integer utworzFaktureZaliczkowaNaPodstPlatnosci(Platnosc plat) {
    // Here not starting new transaction, it's still Propagation.NOT_SUPPORTED
    rachotwMgr.naliczRachotwDlaRezerwacji(rezId, true); // this line is in new transaction
    // Continue in Propagation.NOT_SUPPORTED
    }
}

@Service
@Transactional
public class RachotwServiceImpl implements RachotwService {
    @Override
    @Transactional
    public List<Rachotw> dodajRachotwDlaZaliczekNaFakturze(@NotNull Integer fakturaId) {
    // Here starts new transaction..
    }
}
</code>```

Is my idea with one method with Propagation.NOT_SUPPORTED and two methods inside with Propagation.REQUIRED right (after utworzFaktureZaliczkowaNaPodstPlatnosci() and dodajRachotwDlaZaliczekNaFakturze() should be commit)?

Why does utworzFaktureZaliczkowaNaPodstPlatnosci() which has Propagation.REQUIRED (by default) is not starting new transaction and dodajRachotwDlaZaliczekNaFakturze() and naliczRachotwDlaRezerwacji() starts new transaction. How to make utworzFaktureZaliczkowaNaPodstPlatnosci() to start a new transaction?

答:
This is pretty straight forward.
By 'FakturaServiceImpl' class declaration the method utworzFaktureZaliczkowaNaPodstPlatnosci does support transaction but only if it will be called via bean declaration somewhere else:

```<code>@Inject
FakturaService service;

public void someMethod() {
   // Transaction will be here
   service.utworzFaktureZaliczkowaNaPodstPlatnosci(new Platnosc());
}
</code>```

But you are doing just a simple call to the method there is not transaction configuration involved.

```<code>@Override
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public Integer przyjmijZaliczkeNaPodstPlatnosci(Integer platnoscId) {
  .....

  // Simple method call
  Integer faktId = utworzFaktureZaliczkowaNaPodstPlatnosci(plat);

  // ...
  return faktId;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a question about propagation in @Transactional annotation. I need to make two operations in one method and every should be in own transaction after which is making commit.

@Service
@Transactional
public class FakturaServiceImpl implements FakturaService {

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Integer przyjmijZaliczkeNaPodstPlatnosci(Integer platnoscId) {

      Platnosc plat = Optional.ofNullable(platDao.findOne(platnoscId))
             .orElseThrow(() -> new RecordNotExistsException("Platnosc", platnoscId));

      // here should be beginning of transaction
      Integer faktId = utworzFaktureZaliczkowaNaPodstPlatnosci(plat);
      // commit
      // start new transaction
      rachotwMgr.dodajRachotwDlaZaliczekNaFakturze(faktId);
      // commit

      // ...
      return faktId;
    }

    @Override
    public Integer utworzFaktureZaliczkowaNaPodstPlatnosci(Platnosc plat) {
    // Here not starting new transaction, it's still Propagation.NOT_SUPPORTED
    rachotwMgr.naliczRachotwDlaRezerwacji(rezId, true); // this line is in new transaction
    // Continue in Propagation.NOT_SUPPORTED
    }
}

@Service
@Transactional
public class RachotwServiceImpl implements RachotwService {
    @Override
    @Transactional
    public List<Rachotw> dodajRachotwDlaZaliczekNaFakturze(@NotNull Integer fakturaId) {
    // Here starts new transaction..
    }
}

Is my idea with one method with Propagation.NOT_SUPPORTED and two methods inside with Propagation.REQUIRED right (after utworzFaktureZaliczkowaNaPodstPlatnosci() and dodajRachotwDlaZaliczekNaFakturze() should be commit)?

Why does utworzFaktureZaliczkowaNaPodstPlatnosci() which has Propagation.REQUIRED (by default) is not starting new transaction and dodajRachotwDlaZaliczekNaFakturze() and naliczRachotwDlaRezerwacji() starts new transaction. How to make utworzFaktureZaliczkowaNaPodstPlatnosci() to start a new transaction?

Body:
This is pretty straight forward.
By 'FakturaServiceImpl' class declaration the method utworzFaktureZaliczkowaNaPodstPlatnosci does support transaction but only if it will be called via bean declaration somewhere else:

@Inject
FakturaService service;

public void someMethod() {
   // Transaction will be here
   service.utworzFaktureZaliczkowaNaPodstPlatnosci(new Platnosc());
}

But you are doing just a simple call to the method there is not transaction configuration involved.

@Override
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public Integer przyjmijZaliczkeNaPodstPlatnosci(Integer platnoscId) {
  .....

  // Simple method call
  Integer faktId = utworzFaktureZaliczkowaNaPodstPlatnosci(plat);

  // ...
  return faktId;
}


问:
LexikJwtAuthBundle unable to generate key
I'm trying to install lexikJwtauthbundle, when I try to generate key :

```<code>$ openssl genrsa -out app/config/jwt/private.pem -aes256 4096

Generating RSA private key, 4096 bit long modulus

..........................................................++

........++
</code>```

The command seems to never finish, I must do a CTRL-C to exit. The file is created but empty.
The next command to generate the public key return:

```<code>unable to load Private Key
12568:error:0906D06C:PEM routines:PEM_read_bio:no start line:pem_lib.c:707:Expecting: ANY PRIVATE KEY
</code>```

What is the problem ?

I want use it for an Api rest i'm building on symfony 3.4, with FosRestBundle.
Windows10.

答:
Try :

$ openssl genrsa -out config/jwt/private.pem 4096

without using the option -aes256

Body:
I'm trying to install lexikJwtauthbundle, when I try to generate key :

$ openssl genrsa -out app/config/jwt/private.pem -aes256 4096

Generating RSA private key, 4096 bit long modulus

..........................................................++

........++

The command seems to never finish, I must do a CTRL-C to exit. The file is created but empty.
The next command to generate the public key return:

unable to load Private Key
12568:error:0906D06C:PEM routines:PEM_read_bio:no start line:pem_lib.c:707:Expecting: ANY PRIVATE KEY

What is the problem ?

I want use it for an Api rest i'm building on symfony 3.4, with FosRestBundle.
Windows10.


问:
How to Implement Method Chaining
Is there a way to chain the following methods from Cache class

cache = cache.getKey(key) || cache.setKey(key).get(key);
// cache = cache.getKey(key) || cache.setKey(key).getKey(key);

I know we have native methods Map.prototype.set() and Map.prototype.get() but I want to implement it this way. Let me know if you have any suggestions.

```<code>function isObject(arg) {
  const typeOfObj = typeof arg;
  return (typeOfObj === 'object' || typeOfObj === 'function') && arg !== null;
}

class Cache {
  constructor() {
    this.map = new Map();
    this.weakmap = new WeakMap();
  }

  setKey(key) {
    const map = this[isObject(key) ? 'weakmap' : 'map'];
    return map.set(key, new Cache());
  }

  getKey(key) {
    const map = this[isObject(key) ? 'weakmap' : 'map'];
    return map.get(key);
  }
}

function getCache(args, cache) {
  for (const key of args) {
    cache = cache.getKey(key) || cache.setKey(key).get(key);
    // cache = cache.getKey(key) || cache.setKey(key).getKey(key);
  }
  return cache;
}

function memoize(fn) {
  const cache = new Cache();
  return (...args) => {
    const item = getCache(args, cache);

    if (Reflect.has(item, 'value')) {
      return item.value;
    }

    return (item.value = fn(args));
  };
}

let counter = 1;
function foo() {
  counter += 1;
  return counter;
}

const id1 = Symbol('id');
const id2 = Symbol('id');

const memoizedFoo = memoize(foo);
console.log(memoizedFoo(id1)); // 2
console.log(memoizedFoo(id1)); // 2
console.log(memoizedFoo(id2)); // 3
console.log(memoizedFoo(id2)); // 3
</code>```

Any help is greatly appreciated.

答:
Unfortunately, if you're trying to "GET" a key, you cannot return the map, as you're asking for the key, so it must return the key. So you can't chain that method. But any method that shouldn't return something by default (IE would be void), we can do this:

cache = cache.getKey(key) || cache.setKey(key).get(key);

This will return a boolean, as the || symbol means return true if either is true.

But if you'd like to do the sort of chaining that JQuery does, that's easily achievable! What you want to do is return this or the object in every method.

Like so:

```<code>function isObject(arg) {
  const typeOfObj = typeof arg;
  return (typeOfObj === 'object' || typeOfObj === 'function') && arg !== null;
}

class Cache {
  constructor() {
    this.map = new Map();
    this.weakmap = new WeakMap();
  }

  setKey(key) {
    const map = this[isObject(key) ? 'weakmap' : 'map'];
    map.set(key, new Cache());
    return this; // HERE'S THE IMPORTANT PART
  }
}

let counter = 1;
function foo() {
  counter += 1;
  return counter;
}

const id1 = Symbol('id');
const id2 = Symbol('id');

const memoizedFoo = memoize(foo);
console.log(memoizedFoo(id1)); // 2
console.log(memoizedFoo(id1)); // 2
console.log(memoizedFoo(id2)); // 3
console.log(memoizedFoo(id2)); // 3
</code>```

Title: How to Implement Method Chaining

Body:
Is there a way to chain the following methods from Cache class

cache = cache.getKey(key) || cache.setKey(key).get(key);
// cache = cache.getKey(key) || cache.setKey(key).getKey(key);

I know we have native methods Map.prototype.set() and Map.prototype.get() but I want to implement it this way. Let me know if you have any suggestions.

function isObject(arg) {
  const typeOfObj = typeof arg;
  return (typeOfObj === 'object' || typeOfObj === 'function') && arg !== null;
}

class Cache {
  constructor() {
    this.map = new Map();
    this.weakmap = new WeakMap();
  }

  setKey(key) {
    const map = this[isObject(key) ? 'weakmap' : 'map'];
    return map.set(key, new Cache());
  }

  getKey(key) {
    const map = this[isObject(key) ? 'weakmap' : 'map'];
    return map.get(key);
  }
}

function getCache(args, cache) {
  for (const key of args) {
    cache = cache.getKey(key) || cache.setKey(key).get(key);
    // cache = cache.getKey(key) || cache.setKey(key).getKey(key);
  }
  return cache;
}

function memoize(fn) {
  const cache = new Cache();
  return (...args) => {
    const item = getCache(args, cache);

    if (Reflect.has(item, 'value')) {
      return item.value;
    }

    return (item.value = fn(args));
  };
}

let counter = 1;
function foo() {
  counter += 1;
  return counter;
}

const id1 = Symbol('id');
const id2 = Symbol('id');

const memoizedFoo = memoize(foo);
console.log(memoizedFoo(id1)); // 2
console.log(memoizedFoo(id1)); // 2
console.log(memoizedFoo(id2)); // 3
console.log(memoizedFoo(id2)); // 3

Any help is greatly appreciated.

Body:
Unfortunately, if you're trying to "GET" a key, you cannot return the map, as you're asking for the key, so it must return the key. So you can't chain that method. But any method that shouldn't return something by default (IE would be void), we can do this:

cache = cache.getKey(key) || cache.setKey(key).get(key);

This will return a boolean, as the || symbol means return true if either is true.

But if you'd like to do the sort of chaining that JQuery does, that's easily achievable! What you want to do is return this or the object in every method.

Like so:

function isObject(arg) {
  const typeOfObj = typeof arg;
  return (typeOfObj === 'object' || typeOfObj === 'function') && arg !== null;
}

class Cache {
  constructor() {
    this.map = new Map();
    this.weakmap = new WeakMap();
  }

  setKey(key) {
    const map = this[isObject(key) ? 'weakmap' : 'map'];
    map.set(key, new Cache());
    return this; // HERE'S THE IMPORTANT PART
  }
}

let counter = 1;
function foo() {
  counter += 1;
  return counter;
}

const id1 = Symbol('id');
const id2 = Symbol('id');

const memoizedFoo = memoize(foo);
console.log(memoizedFoo(id1)); // 2
console.log(memoizedFoo(id1)); // 2
console.log(memoizedFoo(id2)); // 3
console.log(memoizedFoo(id2)); // 3


问:
Codeigniter: cannot upload files from subdirectory to main directory
I'm having 2 codeigniter applications one of them in the root and the other is in a sub directory. I'm trying to upload files from the application in the sub sirectory the the images/artists folder in the root (in the main application) but I get

```<code>ERROR  404 Page Not Found: Images/artists
The upload destination folder does not appear to be writable.
</code>```

I run this code in the controller which is used to upload in the sub directory application

```<code>if (file_exists('../images/artists')) {
     echo 'directory exists - ';
        if (!is_dir('../images/artists')) {
            echo 'not a dir';
         }
         else{
            echo 'it is a dir';
         }
}
</code>```

And I get "directory exists - it is a dir" and then run the upload code

```<code>$gallery_path = realpath(APPPATH . '../images/artists/');
$config['upload_path'] = $gallery_path;
$config['allowed_types'] = 'jpg|png|jpeg';
$config['max_size'] = '20000';
$config['file_name'] = round(microtime(true) * 1000).'.jpg';
$this->load->library('upload', $config);
if ($this->upload->do_upload('img')) {
    $phot_data = $this->upload->data();
    $photo_name = $phot_data['file_name'];
    $this->resizeImage($photo_name);
     $artist_data['image'] = $config['file_name'];
}
</code>```

//not used here but dows it override and trigger the error?

```<code>function do_upload() {
    if ($_FILES['photos']['name'][0] != '') {
        $name_array = array();
        foreach ($_FILES as $key => $value)
            $_FILES['userfile']['name'] = $value['name'];
            $_FILES['userfile']['type'] = $value['type'];
            $_FILES['userfile']['tmp_name'] = $value['tmp_name'];
            $_FILES['userfile']['error'] = $value['error'];
            $_FILES['userfile']['size'] = $value['size'];

            $config['upload_path'] = realpath(APPPATH . 'images/artists/');

            $config['allowed_types'] = 'gif|jpg|png|jpeg';
            $config['max_size'] = '2000';
            $this->load->library('upload');
            $this->upload->initialize($config);
            $this->upload->do_upload();
            $data = $this->upload->data();
            $name_array[] = $data['file_name'];

    }
    redirect('admin/gallery');
}
</code>```

I checked images and artists permissions and they are set to 777 Where's the issue then?

答:
The first snippet only checks if the directory exists, but you want to confirm that it is writable (i.e. that you can put new files into it).

Check is_writable for more details.  To fix the problem you'll need to run chmod 600 /path/to/images/artists on the server.

Body:
I'm having 2 codeigniter applications one of them in the root and the other is in a sub directory. I'm trying to upload files from the application in the sub sirectory the the images/artists folder in the root (in the main application) but I get

ERROR  404 Page Not Found: Images/artists
The upload destination folder does not appear to be writable.

I run this code in the controller which is used to upload in the sub directory application

if (file_exists('../images/artists')) {
     echo 'directory exists - ';
        if (!is_dir('../images/artists')) {
            echo 'not a dir';
         }
         else{
            echo 'it is a dir';
         }
}

And I get "directory exists - it is a dir" and then run the upload code

$gallery_path = realpath(APPPATH . '../images/artists/');
$config['upload_path'] = $gallery_path;
$config['allowed_types'] = 'jpg|png|jpeg';
$config['max_size'] = '20000';
$config['file_name'] = round(microtime(true) * 1000).'.jpg';
$this->load->library('upload', $config);
if ($this->upload->do_upload('img')) {
    $phot_data = $this->upload->data();
    $photo_name = $phot_data['file_name'];
    $this->resizeImage($photo_name);
     $artist_data['image'] = $config['file_name'];
}

//not used here but dows it override and trigger the error?

function do_upload() {
    if ($_FILES['photos']['name'][0] != '') {
        $name_array = array();
        foreach ($_FILES as $key => $value)
            $_FILES['userfile']['name'] = $value['name'];
            $_FILES['userfile']['type'] = $value['type'];
            $_FILES['userfile']['tmp_name'] = $value['tmp_name'];
            $_FILES['userfile']['error'] = $value['error'];
            $_FILES['userfile']['size'] = $value['size'];

            $config['upload_path'] = realpath(APPPATH . 'images/artists/');

            $config['allowed_types'] = 'gif|jpg|png|jpeg';
            $config['max_size'] = '2000';
            $this->load->library('upload');
            $this->upload->initialize($config);
            $this->upload->do_upload();
            $data = $this->upload->data();
            $name_array[] = $data['file_name'];

    }
    redirect('admin/gallery');
}

I checked images and artists permissions and they are set to 777 Where's the issue then?


问:
Accessing Dataframe columns using bracket vs dot notation in Julia
Which is the recommended way to access Dataframe columns in Julia: Using df[:col] or df.col? For example, in Pandas Dataframe, the recommended way is using the bracket notation for performance as well as other reasons as discussed here: Speed difference between bracket notation and dot notation for accessing columns in pandas.

So, is there a similar recommendation for using bracket notation over the dot notation for Dataframes in Julia, either for performance or otherwise? Or are both equally good?

答:
They are equally good, and normally df.col is used. There are two cases when you need to use the other style:

when column name is not a valid identifier, e.g. df[Symbol("Some column name with spaces")]

soon broadcasting for data frames will be implemented and then if col does not exist in df the syntax df.col .= 1 will not work while df[:col] .= 1 will create a new column.

Note that df.col notation is handy as if you write df. and press <tab> in REPL or Jupyter Notebook you will get a list of column names.


问:
UNION ALL vs OR condition in sql server query
I have to select some rows based on a not exists condition on a table. If I use a union all as below, it gets executed in less than 1 second.

```<code>SELECT 1 FROM dummyTable
WHERE NOT EXISTS
(

SELECT 1 FROM TABLE t
WHERE Data1 = t.Col1 AND Data2=t.Col2

UNION ALL

SELECT 1 FROM TABLE t
WHERE Data1 = t.Col2 AND Data2=t.Col1

)
</code>```

but if I use an OR condition, it takes close to a minute as SQL server is doing a table lazy pool. Can someone explain it?

```<code>SELECT 1 FROM dummyTable
WHERE NOT EXISTS
(

SELECT 1 FROM TABLE t
WHERE ( (Data1 = t.Col1 AND Data2=t.Col2) OR (Data1 = t.Col2 AND Data2=t.Col1))
)
</code>```

答: The usage of the OR is probably causing the query optimizer to no longer use an index in the second query.  Look at the explain for each query and that will tell you the answer.

ContentLicense: CC BY-SA 3.0

Body:
I have to select some rows based on a not exists condition on a table. If I use a union all as below, it gets executed in less than 1 second.

SELECT 1 FROM dummyTable
WHERE NOT EXISTS
(

SELECT 1 FROM TABLE t
WHERE Data1 = t.Col1 AND Data2=t.Col2

UNION ALL

SELECT 1 FROM TABLE t
WHERE Data1 = t.Col2 AND Data2=t.Col1

)

but if I use an OR condition, it takes close to a minute as SQL server is doing a table lazy pool. Can someone explain it?

SELECT 1 FROM dummyTable
WHERE NOT EXISTS
(

SELECT 1 FROM TABLE t
WHERE ( (Data1 = t.Col1 AND Data2=t.Col2) OR (Data1 = t.Col2 AND Data2=t.Col1))
)


问:
Will const instance remain in memory after a Stateful widget gets disposed in Flutter?
A const variable will only be created once. When I try to create the same variable, the old variable will be returned. Thus, no new memory allocation occurs.

For example, if I create const Icon(Icons.add) and later try to use const Icon(Icons.add) in another class, the old one will be returned.

But my question is: if I use const Icon(Icons.add) in a stateful widget, will this memory allocation be present forever even after the stateful widget is disposed?

答:
Yes, an instance created using const will never be garbage collected.

The instance is in fact created at the compilation and present in the binary.


问:
compare two lists to get non matching elements
I checked this comparing lists, Only one answer is relative to what I am trying to do. I have to lists with some similiar elements, I want to get the non -matching elements.

```<code>len(h) = 1973182  #h[0] = 'B00006J8F4F2', y[0] = 'B0075Y2X2GO6'
len(y) = 656890
</code>```

I am doing

new_list = [i for i in h if i not in y],however this takes about 13 minutes to do, Is there a faster way of doing this?

In refer to "duplicate" question, Finding elements not in a list, I use the same code, What I am looking for is a faster way of doing it.

答:
using programmatically and keep order and handle duplicate in list1

```<code>def function(list1, list2):
    dic2={}
    for i in list2:
        try:
            if i in dic2.keys():
                pass
        except KeyError:
            dic2[i]=1

    result =[]
    for i in list1:
        try:
            if i in dic2.keys():
                pass
        except:
            result.append(i)
    return result

list1=[1,2,2,3]
list2=[3,4,5]

solution = function(list1,list2)
print(solution)
</code>```

output

```<code>[1, 2, 2]
</code>```

using @yatu h,y list, here is time result

```<code>%timeit function(h,y)
2.75 ms ± 22.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
</code>```

Body:
I checked this comparing lists, Only one answer is relative to what I am trying to do. I have to lists with some similiar elements, I want to get the non -matching elements.

len(h) = 1973182  #h[0] = 'B00006J8F4F2', y[0] = 'B0075Y2X2GO6'
len(y) = 656890

I am doing

new_list = [i for i in h if i not in y],however this takes about 13 minutes to do, Is there a faster way of doing this?

In refer to "duplicate" question, Finding elements not in a list, I use the same code, What I am looking for is a faster way of doing it.

Body:
using programmatically and keep order and handle duplicate in list1

def function(list1, list2):
    dic2={}
    for i in list2:
        try:
            if i in dic2.keys():
                pass
        except KeyError:
            dic2[i]=1

    result =[]
    for i in list1:
        try:
            if i in dic2.keys():
                pass
        except:
            result.append(i)
    return result

list1=[1,2,2,3]
list2=[3,4,5]

solution = function(list1,list2)
print(solution)

output

[1, 2, 2]

using @yatu h,y list, here is time result

%timeit function(h,y)
2.75 ms ± 22.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)


问:
Build .NET solution using GitLab CI Pipeline
I have a solution with several .NET projects in it. I use GitLab, not self-hosted, for version control and would like to start using their CI tools as well. I have added the following .gitlab-ci.yml file to my root:

```<code>stages:
  - build
  - test

build_job:
  stage: build
  script:
  - 'echo building...'
  - 'msbuild.exe Bizio.sln'
  except:
  - tags

test_job:
  stage: test
  script:
  - 'echo: testing...'
  - 'msbuild.exe Bizio.sln'
  - 'dir /s /b *.Tests.dll | findstr /r Tests\\bin\\ > tests_list.txt'
  - 'for /f %%f in (tests_list.txt) do mstest.exe /testcontainer: "%%f"'
  except:
  - tags
</code>```

The build stage always fails because it doesn't know what msbuild is. The exact error is:

/bin/bash: line 61: msbuild.exe: command not found

After some investigating, I've figured out that I'm using a shared runner. Here is the entire output from the job run:

```<code>Running with gitlab-runner 10.6.0-rc1 (0a9d5de9)
  on docker-auto-scale 72989761
Using Docker executor with image ruby:2.5 ...
Pulling docker image ruby:2.5 ...
Using docker image sha256:bae0455cb2b9010f134a2da3a1fba9d217506beec2d41950d151e12a3112c418 for ruby:2.5 ...
Running on runner-72989761-project-1239128-concurrent-0 via runner-72989761-srm-1520985217-1a689f37...
Cloning repository...
Cloning into '/builds/hyjynx-studios/bizio'...
Checking out bc8085a4 as master...
Skipping Git submodules setup
$ echo building...
building...
$ C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe Bizio.sln
/bin/bash: line 61: msbuild.exe: command not found
ERROR: Job failed: exit code 1
</code>```

It looks like the shared runner I have is using a Docker image for Ruby, which seems wrong. I don't know how I can change that or select a different one that can be used for .NET. After some further investigating I'm getting worried that I'll have to jump through a lot of hoops to get what I want, like using an Azure VM to host a GitLab Runner that can build .NET apps.

What do I need to do to use GitLab's CI pipelines to build my .NET solution using a non-self-hosted GitLab instance?

答:
Or multi stage builds:</p>

```<code>stages:
  - build-dotnet
  - test-dotnet
  - build-mono
  - test-mono

build-dotnet:
  stage: build-dotnet
  image: microsoft/dotnet:latest
  before_script:
    - "cd source"
    - "dotnet restore"
    - "cd .."
    - "cd samples"
    - "dotnet restore"
    - "cd .."
  script:
      - "cd source"
      - "dotnet build"
      - "cd .."
      - "cd samples"
      - "dotnet build"
      - "cd .."

build-mono:
  stage: build-mono
  image: mono:latest
  before_script:
  script:
    - nuget restore ./source/Source.sln
    - msbuild
        /p:Configuration="Release"
        /p:Platform="Any CPU"
        "./source/Source.sln"

</code>```

Body:
I have a solution with several .NET projects in it. I use GitLab, not self-hosted, for version control and would like to start using their CI tools as well. I have added the following .gitlab-ci.yml file to my root:

stages:
  - build
  - test

build_job:
  stage: build
  script:
  - 'echo building...'
  - 'msbuild.exe Bizio.sln'
  except:
  - tags

test_job:
  stage: test
  script:
  - 'echo: testing...'
  - 'msbuild.exe Bizio.sln'
  - 'dir /s /b *.Tests.dll | findstr /r Tests\\bin\\ > tests_list.txt'
  - 'for /f %%f in (tests_list.txt) do mstest.exe /testcontainer: "%%f"'
  except:
  - tags

The build stage always fails because it doesn't know what msbuild is. The exact error is:

/bin/bash: line 61: msbuild.exe: command not found

After some investigating, I've figured out that I'm using a shared runner. Here is the entire output from the job run:

Running with gitlab-runner 10.6.0-rc1 (0a9d5de9)
  on docker-auto-scale 72989761
Using Docker executor with image ruby:2.5 ...
Pulling docker image ruby:2.5 ...
Using docker image sha256:bae0455cb2b9010f134a2da3a1fba9d217506beec2d41950d151e12a3112c418 for ruby:2.5 ...
Running on runner-72989761-project-1239128-concurrent-0 via runner-72989761-srm-1520985217-1a689f37...
Cloning repository...
Cloning into '/builds/hyjynx-studios/bizio'...
Checking out bc8085a4 as master...
Skipping Git submodules setup
$ echo building...
building...
$ C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe Bizio.sln
/bin/bash: line 61: msbuild.exe: command not found
ERROR: Job failed: exit code 1

It looks like the shared runner I have is using a Docker image for Ruby, which seems wrong. I don't know how I can change that or select a different one that can be used for .NET. After some further investigating I'm getting worried that I'll have to jump through a lot of hoops to get what I want, like using an Azure VM to host a GitLab Runner that can build .NET apps.

What do I need to do to use GitLab's CI pipelines to build my .NET solution using a non-self-hosted GitLab instance?

Body:
Or multi stage builds:

stages:
  - build-dotnet
  - test-dotnet
  - build-mono
  - test-mono

build-dotnet:
  stage: build-dotnet
  image: microsoft/dotnet:latest
  before_script:
    - "cd source"
    - "dotnet restore"
    - "cd .."
    - "cd samples"
    - "dotnet restore"
    - "cd .."
  script:
      - "cd source"
      - "dotnet build"
      - "cd .."
      - "cd samples"
      - "dotnet build"
      - "cd .."

build-mono:
  stage: build-mono
  image: mono:latest
  before_script:
  script:
    - nuget restore ./source/Source.sln
    - msbuild
        /p:Configuration="Release"
        /p:Platform="Any CPU"
        "./source/Source.sln"


问:
how to get the respective array key value if it meets the if condition in for loop
I have any array with keys and values , I want to get the value of the key ,if key is equal to certain string.

When I use this code I am getting the last key value of array. I have the flexibility to change the array structure also if we want.

```<code>$grouparray =[ "red" => "4" , "blue" =>"5" , "green" => "6"];

foreach($grouparray   as $x=>$x_value){
          if($x=blue){
              $group_id=$x_value;

          }

      }

print_r($group_id);
</code>```

I want to expect $group_id = 5;

答:
your are missing quotes on blue.</p>

```<code>$grouparray =[ "red" => "4" , "blue" =>"5" , "green" => "6"];

    foreach($grouparray as $x=>$x_value){
              if($x=="blue"){
                  $group_id=$x_value;

              }

          }

    print_r($group_id);
</code>```

Body:
I have any array with keys and values , I want to get the value of the key ,if key is equal to certain string.

When I use this code I am getting the last key value of array. I have the flexibility to change the array structure also if we want.

$grouparray =[ "red" => "4" , "blue" =>"5" , "green" => "6"];

foreach($grouparray   as $x=>$x_value){
          if($x=blue){
              $group_id=$x_value;

          }

      }

print_r($group_id);

I want to expect $group_id = 5;

Body:
your are missing quotes on blue.

$grouparray =[ "red" => "4" , "blue" =>"5" , "green" => "6"];

    foreach($grouparray as $x=>$x_value){
              if($x=="blue"){
                  $group_id=$x_value;

              }

          }

    print_r($group_id);


问:
UI5: change the style of list items after clicking on a button
I want to dynamically change the style of a sap.m.CustomListItem of my list when I click on a button.

I used addStyleClass and it works only in the onInit method but not in the press` function, the style has been added but the view doesn't change.

Controller

pressbutton: function(oEvent) {
  var o = oEvent.getParameter("value");
  MessageToast.show(o.toString());
  var listitem = this.getView().byId("IDCustomerListItem");
  if (listitem.hasStyleClass("myListItemClass")) {
    this.getView().byId("IDCustomerListItem").removeStyleClass("myListItemClass");
    this.getView().byId("IDCustomerListItem").addStyleClass("myListItemClasso");
  } else {
    this.getView().byId("IDCustomerListItem").addStyleClass("myListItemClass");
  }
}
```

<h1>CSS</h1>

<pre class="lang-css prettyprint-override"><code>.myListItemClass {
  width: 50% !important;
  float: left;
}

.myListItemClasso {
  width: 100% !important;
}
</code>```

答:
Here is a working example: https://embed.plnkr.co/LAv1qfsUjX0Anu7S/.

Why it didn't work

The reason why it worked only in onInit but not in the press handler is because the style was being applied to the template control. You probably have something like this in your view:

<List xmlns="sap.m" items="{/myCollection}">
  <CustomListItem id="IDCustomerListItem">

  </CustomListItem>
</List>
```
</blockquote>

<ol>
<li><p>In <code>onInit</code>, the template control (<code>"IDCustomerListItem"</code>) applies the custom style, and then the framework <strong>clones</strong> the template control for each collection item before rendering.</p></li>
<li><p>In the press handler, however, applying the style to the template control doesn't have any effects any longer since the list items have been already cloned and rendered. It won't trigger cloning again. </p></li>
</ol>

<p>The sample solution I provided above applies the style to the list. When the user triggers an action (via Switch for example), the render manager adds a custom data attribute to the corresponding HTML element by which the CSS can be applied accordingly.</p>

<pre class="lang-css prettyprint-override"><code>.myApp .sapMList.myList[data-awesomestyle] .sapMLIB {
  /* my custom style */
}
</code>```

See Binding in Control with "class" Attribute

Body:
I want to dynamically change the style of a sap.m.CustomListItem of my list when I click on a button.

I used addStyleClass and it works only in the onInit method but not in the press` function, the style has been added but the view doesn't change.

Controller

pressbutton: function(oEvent) {
  var o = oEvent.getParameter("value");
  MessageToast.show(o.toString());
  var listitem = this.getView().byId("IDCustomerListItem");
  if (listitem.hasStyleClass("myListItemClass")) {
    this.getView().byId("IDCustomerListItem").removeStyleClass("myListItemClass");
    this.getView().byId("IDCustomerListItem").addStyleClass("myListItemClasso");
  } else {
    this.getView().byId("IDCustomerListItem").addStyleClass("myListItemClass");
  }
}

CSS

.myListItemClass {
  width: 50% !important;
  float: left;
}

.myListItemClasso {
  width: 100% !important;
}

Body:
Here is a working example: https://embed.plnkr.co/LAv1qfsUjX0Anu7S/.

Why it didn't work

The reason why it worked only in onInit but not in the press handler is because the style was being applied to the template control. You probably have something like this in your view:

<List xmlns="sap.m" items="{/myCollection}">
  <CustomListItem id="IDCustomerListItem"> <!-- template control -->
    <!-- ... -->
  </CustomListItem>
</List>

In onInit, the template control ("IDCustomerListItem") applies the custom style, and then the framework clones the template control for each collection item before rendering.

In the press handler, however, applying the style to the template control doesn't have any effects any longer since the list items have been already cloned and rendered. It won't trigger cloning again.

The sample solution I provided above applies the style to the list. When the user triggers an action (via Switch for example), the render manager adds a custom data attribute to the corresponding HTML element by which the CSS can be applied accordingly.

.myApp .sapMList.myList[data-awesomestyle] .sapMLIB {
  /* my custom style */
}

See Binding in Control with "class" Attribute


问:
C# MVC Razor or Master/Content performance
I'm starting a new project with MVC and I've never used the Razor engine.  Will there be any performance gains or hits as compared to using the standard Content/Master pages?  I know that Razor looks better and seems easier to program for, but what is the cost?

Thanks

答:
Razor, according to these tests, is slightly slower:

ASP.NET MVC 3 Razor performance


问:
How to indicate that date is null in sql
With the following code I was hoping to retrieve the records that have a null value for the ClosedDateTimeT field, but it only shows the records that have a value. Am I doing something wrong here:</p>

```<code>SELECT DISTINCT
    t.ticketid,
    t.Sub,
    i.status,
    i.OwnedByTeam,
    i.OwnedByTeamT,
    i.TypeOptions,
    i.ClosedDateTimeT,
    i.CompletedDateTime,
    i.TitleT
FROM
    ticket AS t
INNER JOIN
    Incident AS i ON t.TicketID = i.IncidentID
WHERE
    CAST(t.Sub AS DATE) >= '01-01-2019'
    AND CAST(t.Sub AS DATE ) <= '05-30-2019'
    AND i.Subcategory = 'Content Request'
    AND (i.TypeOptions = 'New/Initial Submission' OR
         i.TypeOptions = 'Am/Re')
    AND ((i.OwnedByTeamT LIKE '%C - CA%'
          AND i.TitleT LIKE '%B Build%'
          AND i.ClosedDateTimeT IS NOT NULL) OR
         (i.OwnedByTeamT LIKE '%C - CA%'
          AND i.TitleT LIKE '%B Build%'
          AND i.ClosedDateTimeT IS NULL) OR
         (i.OwnedByTeamT LIKE '%E - Cl%'
          AND i.TitleT LIKE '%OP B V%'))
</code>```

答:
By your comments I would remove just remove that date field from your where clause. I also removed a piece that repeated i.OwnedByTeamT like '%C - CA%' AND i.TitleT LIKE '%B Build%' </p>

```<code>Select distinct t.ticketid,
 t.Sub,
 i.status,
 i.OwnedByTeam,
 i.OwnedByTeamT,
 i.TypeOptions,
 i.ClosedDateTimeT,
 i.CompletedDateTime,
 i.TitleT

From ticket as t inner join Incident as i on
t.TicketID=i.IncidentID

where
CAST(t.Sub AS DATE) >= '01-01-2019'
AND CAST(t.Sub AS DATE ) <= '05-30-2019'
AND i.Subcategory = 'Content Request'
AND (i.TypeOptions='New/Initial Submission' OR
 i.TypeOptions='Am/Re')
AND (
(i.OwnedByTeamT like '%C - CA%' AND i.TitleT LIKE '%B Build%'
)
OR (
i.OwnedByTeamT like '%E - Cl%' AND i.TitleT LIKE '%OP B V%')
)
</code>```

Body:
With the following code I was hoping to retrieve the records that have a null value for the ClosedDateTimeT field, but it only shows the records that have a value. Am I doing something wrong here:

SELECT DISTINCT
    t.ticketid,
    t.Sub,
    i.status,
    i.OwnedByTeam,
    i.OwnedByTeamT,
    i.TypeOptions,
    i.ClosedDateTimeT,
    i.CompletedDateTime,
    i.TitleT
FROM
    ticket AS t
INNER JOIN
    Incident AS i ON t.TicketID = i.IncidentID
WHERE
    CAST(t.Sub AS DATE) >= '01-01-2019'
    AND CAST(t.Sub AS DATE ) <= '05-30-2019'
    AND i.Subcategory = 'Content Request'
    AND (i.TypeOptions = 'New/Initial Submission' OR
         i.TypeOptions = 'Am/Re')
    AND ((i.OwnedByTeamT LIKE '%C - CA%'
          AND i.TitleT LIKE '%B Build%'
          AND i.ClosedDateTimeT IS NOT NULL) OR
         (i.OwnedByTeamT LIKE '%C - CA%'
          AND i.TitleT LIKE '%B Build%'
          AND i.ClosedDateTimeT IS NULL) OR
         (i.OwnedByTeamT LIKE '%E - Cl%'
          AND i.TitleT LIKE '%OP B V%'))

Body:
By your comments I would remove just remove that date field from your where clause. I also removed a piece that repeated i.OwnedByTeamT like '%C - CA%' AND i.TitleT LIKE '%B Build%'

Select distinct t.ticketid,
 t.Sub,
 i.status,
 i.OwnedByTeam,
 i.OwnedByTeamT,
 i.TypeOptions,
 i.ClosedDateTimeT,
 i.CompletedDateTime,
 i.TitleT

From ticket as t inner join Incident as i on
t.TicketID=i.IncidentID

where
CAST(t.Sub AS DATE) >= '01-01-2019'
AND CAST(t.Sub AS DATE ) <= '05-30-2019'
AND i.Subcategory = 'Content Request'
AND (i.TypeOptions='New/Initial Submission' OR
 i.TypeOptions='Am/Re')
AND (
(i.OwnedByTeamT like '%C - CA%' AND i.TitleT LIKE '%B Build%'
)
OR (
i.OwnedByTeamT like '%E - Cl%' AND i.TitleT LIKE '%OP B V%')
)


问:
How do I randomly set an integer to a class name based on array length?
I'm trying to randomly set some css rules to different section tags, but I don't know how many section tags I will end up with. If there are 10 section tags, each section should have a random class name between section0 to section9. It needs to be randomized and not in order.

I read about document.getElementByTagName and I'm able to assign class names with an integer by using a for loop, but I'm not sure where and how to implement Math.floor(Math.random() * myArray.length) and return it correctly.

```<code>   function myFunction(){
    var randomize = document.getElementsByTagName("section");
    for (i = 0; i <= randomize.length; i++) {
        randomize[i].className = "section" + i;
        }
    }
</code>```

I've tried i = Math.floor(Math.random() * randomize.length);

and return randomize[i].className = "section" + i;

but that does not seem to work. I'm trying to incorporate two things I've been reading about but I'm not sure how to correctly do so.

答:
This version of a solution randomly generates a number dependent upon how many sections there are.  It keeps track of the numbers already used in an array.  So long as a number is already used, it will keep trying.

var sections = document.querySelectorAll('section');
var usedValues = [];

[...sections].forEach(function(section){
  var classAssigned = false;

  while (!classAssigned) {
    let randomNumber = Math.floor(Math.random() * 100 * sections.length) % sections.length;

    if (classAssigned = !usedValues.includes(randomNumber)) {
      section.classList.add('section'+ randomNumber);
      usedValues.push(randomNumber);
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section>A</section>
<section>B</section>
<section>C</section>
<section>D</section>
<section>E</section>
<section>F</section>
<section>G</section>
<section>H</section>
<section>I</section>
<section>J</section>
<section>K</section>
<section>L</section>
<section>M</section>
<section>N</section></code>```

Body:
I'm trying to randomly set some css rules to different section tags, but I don't know how many section tags I will end up with. If there are 10 section tags, each section should have a random class name between section0 to section9. It needs to be randomized and not in order.

I read about document.getElementByTagName and I'm able to assign class names with an integer by using a for loop, but I'm not sure where and how to implement Math.floor(Math.random() * myArray.length) and return it correctly.

   function myFunction(){
    var randomize = document.getElementsByTagName("section");
    for (i = 0; i <= randomize.length; i++) {
        randomize[i].className = "section" + i;
        }
    }

I've tried i = Math.floor(Math.random() * randomize.length);

and return randomize[i].className = "section" + i;

but that does not seem to work. I'm trying to incorporate two things I've been reading about but I'm not sure how to correctly do so.

Body:
This version of a solution randomly generates a number dependent upon how many sections there are.  It keeps track of the numbers already used in an array.  So long as a number is already used, it will keep trying.

var sections = document.querySelectorAll('section');
var usedValues = [];

[...sections].forEach(function(section){
  var classAssigned = false;

  while (!classAssigned) {
    let randomNumber = Math.floor(Math.random() * 100 * sections.length) % sections.length;

    if (classAssigned = !usedValues.includes(randomNumber)) {
      section.classList.add('section'+ randomNumber);
      usedValues.push(randomNumber);
    }
  }
});

<section>A</section>
<section>B</section>
<section>C</section>
<section>D</section>
<section>E</section>
<section>F</section>
<section>G</section>
<section>H</section>
<section>I</section>
<section>J</section>
<section>K</section>
<section>L</section>
<section>M</section>
<section>N</section>


问:
How to fetch all from table1 and attach count of rows from table2 in a single query by laravel eloquent
I'm using Laravel 5.8, and I have 2 tables in a (one-to-many) relationship as below:

Contacts DB

id

name

number

Send DB

id

user_id

text

to

time

what I want to achieve is a list of all (Contacts) along with how many (send) they've made that related to that (contact) by matching Contacts.id with Send.user_id,

here is the result of the query that I'm looking for:

Query result:

id

name

number

count of Sends

Thank you :)

答:
You need to setup your model relationship

Add the following to your Contact Model:

```<code>public function sends()
{
    return $this->hasMany('App\Send', 'user_id'); //Assuming Send Model is directly in app folder
}
</code>```

Then simply get your information:

```<code>$contact = Contact::withCount('sends')->get();
</code>```

Body:
You need to setup your model relationship

Add the following to your Contact Model:

public function sends()
{
    return $this->hasMany('App\Send', 'user_id'); //Assuming Send Model is directly in app folder
}

Then simply get your information:

$contact = Contact::withCount('sends')->get();


问:
Ionic 4: this.platform.is('desktop') returns wrong value when installed apk in android 4.4.4
I have created an app using Ionic 4 and built android app with below code .

```<code>alert('desktop ' + this.platform.is('desktop'));
</code>```

When I installed an app in android 4.4.4 version device and emulator, it is showing the alert value as true whereas In other higher OS version device it is showing as false.

I have used platform condition at so many places in my code. Because of the above issue code is breaking in android 4.4.4 devices.

I am not able to understand why it is showing desktop platform as true in android kitkat device?

ionic info :

```<code>Ionic:

   ionic (Ionic CLI)             : 4.12.0 (C:\Users\user1\AppData\Roaming\npm\node_modules\ionic)
   Ionic Framework               : @ionic/angular 4.4.2
   @angular-devkit/build-angular : 0.13.9
   @angular-devkit/schematics    : 7.3.9
   @angular/cli                  : 7.3.9
   @ionic/angular-toolkit        : 1.5.1

Cordova:

   cordova (Cordova CLI) : 9.0.0 (cordova-lib@9.0.1)
   Cordova Platforms     : android 8.0.0
   Cordova Plugins       : cordova-plugin-ionic-keyboard 2.1.3, cordova-plugin-ionic-webview 4.0.1, (and 4 other plugins)

System:

   Android SDK Tools : 26.1.1 (C:\Users\user1\AppData\Local\Android\sdk)
   NodeJS            : v10.14.2 (C:\Program Files\nodejs\node.exe)
   npm               : 6.4.1
   OS                : Windows 10
</code>```

Can anyone please provide any solution to this issue?

答: Ionic 4 properly works minimum android 5.0 lolipop.</p>

Body:
I have created an app using Ionic 4 and built android app with below code .

alert('desktop ' + this.platform.is('desktop'));

When I installed an app in android 4.4.4 version device and emulator, it is showing the alert value as true whereas In other higher OS version device it is showing as false.

I have used platform condition at so many places in my code. Because of the above issue code is breaking in android 4.4.4 devices.

I am not able to understand why it is showing desktop platform as true in android kitkat device?

ionic info :

Ionic:

   ionic (Ionic CLI)             : 4.12.0 (C:\Users\user1\AppData\Roaming\npm\node_modules\ionic)
   Ionic Framework               : @ionic/angular 4.4.2
   @angular-devkit/build-angular : 0.13.9
   @angular-devkit/schematics    : 7.3.9
   @angular/cli                  : 7.3.9
   @ionic/angular-toolkit        : 1.5.1

Cordova:

   cordova (Cordova CLI) : 9.0.0 (cordova-lib@9.0.1)
   Cordova Platforms     : android 8.0.0
   Cordova Plugins       : cordova-plugin-ionic-keyboard 2.1.3, cordova-plugin-ionic-webview 4.0.1, (and 4 other plugins)

System:

   Android SDK Tools : 26.1.1 (C:\Users\user1\AppData\Local\Android\sdk)
   NodeJS            : v10.14.2 (C:\Program Files\nodejs\node.exe)
   npm               : 6.4.1
   OS                : Windows 10

Can anyone please provide any solution to this issue?


问:
Run Powershell Command from Oracle Procedure
I need to print pdf documents to my network printer from my android studio application. I want to print the pdf as is with all images and formatting, however, the solutions I have found only allow for the extraction and printing of text from the pdf.

I have also seen solutions mentioning tools like Ghostscript etc which are supposed to convert the pdf to a postscript file, but these tools do not work with Android Studio or at-least I haven't figured out how to integrate them into my application. I cannot pay for tools like jPDFPrint which does exactly what I need.

I started thinking about a work around and came upon the idea of sending my pdf as a blob to my oracle database and invoke a power shell command from a procedure to print it to a specific printer.

I've created and tested the below command to print to my network printer from my PC which works great.

```<code>    Start-Process -FilePath “c:\test.pdf” –Verb PrintTo '\\PrintServer\PrinterName' -PassThru | %{sleep 10;$_} | kill
</code>```

Now I need help with the oracle part. Is it possible to invoke or run a powershell command from within oracle 12c and pass it the pdf blob as well as the printer name?

答: You can use the PL/SQL package DBMS_SCHEDULER procedure create_program, using the program_type=>'EXECUTABLE' to do what you want.  Then you would have your process that sends the data to oracle create a job to invoke that program.  The DBMS_SCHEDULER package is pretty complex so you'll probably need to hunt around for tutorials/tips; you may want to search https://asktom.oracle.com for starters.</p>

Body:
I need to print pdf documents to my network printer from my android studio application. I want to print the pdf as is with all images and formatting, however, the solutions I have found only allow for the extraction and printing of text from the pdf.

I have also seen solutions mentioning tools like Ghostscript etc which are supposed to convert the pdf to a postscript file, but these tools do not work with Android Studio or at-least I haven't figured out how to integrate them into my application. I cannot pay for tools like jPDFPrint which does exactly what I need.

I started thinking about a work around and came upon the idea of sending my pdf as a blob to my oracle database and invoke a power shell command from a procedure to print it to a specific printer.

I've created and tested the below command to print to my network printer from my PC which works great.

    Start-Process -FilePath “c:\test.pdf” –Verb PrintTo '\\PrintServer\PrinterName' -PassThru | %{sleep 10;$_} | kill

Now I need help with the oracle part. Is it possible to invoke or run a powershell command from within oracle 12c and pass it the pdf blob as well as the printer name?


问:
In Android Studio, app is running on emulator but not in physical device
I am using Android studio 3.4.1, In which my projects are not running in real device. but not having any problem in emulator.

After connecting the usb and i have run the app. then getting this error. after that device is not even listed in the available devices.

error got in logs:

```<code>Installation did not succeed.

The application could not be installed.

Installation failed due to: 'device '711KPMZ0603459' not found'

Retry
</code>```

Retry also not working.

I also tried in Android studio Beta 1 and Beta 3. same problem happening.

can any one help me in this?

FYKI:
1. USB debugging enabled.

Tried USB option for File Transfer, USB tethering, No data transfer.

Tried with different cable as well.

Problem identified only after updating 3.4.1 android studio. Also facing in 3.5 Beta 1 and Beta 3.

Same kind of problem already added in Issue Tracker. https://issuetracker.google.com/issues/122892907

答:
Well the mark of your phone is important because in my case i use LG G5 and i could not see my device even after turning on developer mode and enabling debugger options.
I don't know the type of phone you use but you can try my solution.
After turning on USB debugging, go to tethering under the networks sections and turn on USB tethering then try again.

Hope It helps!

Body:
I am using Android studio 3.4.1, In which my projects are not running in real device. but not having any problem in emulator.

After connecting the usb and i have run the app. then getting this error. after that device is not even listed in the available devices.

error got in logs:

Installation did not succeed.

The application could not be installed.

Installation failed due to: 'device '711KPMZ0603459' not found'

Retry

Retry also not working.

I also tried in Android studio Beta 1 and Beta 3. same problem happening.

can any one help me in this?

FYKI:
1. USB debugging enabled.

Tried USB option for File Transfer, USB tethering, No data transfer.

Tried with different cable as well.

Problem identified only after updating 3.4.1 android studio. Also facing in 3.5 Beta 1 and Beta 3.

Same kind of problem already added in Issue Tracker. https://issuetracker.google.com/issues/122892907


问:
Python: How to write to read and write to a global variable
Trying to read and write to a global variable from inside an if/else statement but getting an error

SyntaxError: name 'PREV_HASH' is assigned to before global declaration

I have tried using the global syntax but I can't get it to work. Not used to the global v local variables in python

PREV_HASH = ''
LOGFILE_DIRECTORY = 'c:\\securelog\\securelog_logs\\'
ARCHIVE_FOLDER = 'c:\\securelog\\securelog_archive\\'
WORKFILES_FOLDER = 'c:\\securelog\\securelog_workfiles\\'
TMP_FOLDER = 'c:\\securelog\\processed\\'
COMPLETED_FOLDER = 'c:\\securelog\\completed\\'

CHAIN_FILE = WORKFILES_FOLDER + 'chain_info.txt'

#check if this is the first run, if it is hardcode the block & previous hash and pass the hash
if chain_list[0] == 1:
    fileHandle = open (CHAIN_FILE, 'r+')
    fileHandle.write('1,0,' + hasher.hexdigest())
    fileHandle.close()
    global PREV_HASH
    PREV_HASH = hasher.hexdigest()
    #print("1 previous hash is: " + str(PREV_HASH))
else:
    #update list with hash of current and previous block
    ###del (chain_list[1:])
    global PREV_HASH
    chain_list.insert (1,PREV_HASH)
    print("2 previous hash is: " + str(PREV_HASH))
    chain_list.insert (2,hasher.hexdigest())
    fileHandle = open (CHAIN_FILE, 'a')
    print('2 what is the chain list at this point:' + str(chain_list))

    #Write the contents of the list to the chain file on a new line and separate with a comma
    fileHandle.write(',' + str(chain_list[2]))
    fileHandle.close()

    PREV_HASH = hasher.hexdigest()
```

<p>I expect on the first run of the script, a new file to be created and contain one line with 1, 0 and a hash key that was generated in a previous step ("hasher.hexdigest()")
That hash will then be saved in a global variable PREV_HASH</p>

<p>Then on the second run the file will be updated with a new line from a list. It will contain an incremented number, previous hash and current hash</p>

<blockquote>
  <p>2,previous #,current #</p>
</blockquote>

<p>When removing the global PREV_HASH i get the following output</p>

```>file does not exist
>-----------------
>24
>1--2019-05-31-archive.zip
>what is the chain list at this point:[1, 0, 0]
>1 previous hash is:

>C:\Python>"SL Proof of Concept.py"
>-----------------
>17
>2--2019-05-31-archive.zip
>what is the chain list at this point:[2, '0', '01d056902f77f5a247f639d363b67827d762d72f9738498989d417563c504a3f82f7b44d7e827cd35843545d33856c85']
>2 previous hash before insert is:
>2 what is the chain list at this point:[2, '', '93fcc831b99a8de59063924a994bf81d09dc677b635e32fc133747ca564bfa843fa6bf60274feeb372a5eeb6f406a120', '0', '01d056902f77f5a247f639d363b67827d762d72f9738
498989d417563c504a3f82f7b44d7e827cd35843545d33856c85']
```

答:
If this code is at the top level of a file, just remove these global statements.

If this code is within something, you need to put global before the first assignment, on the first line. (PREV_HASH = '')

Body:
Trying to read and write to a global variable from inside an if/else statement but getting an error

SyntaxError: name 'PREV_HASH' is assigned to before global declaration

I have tried using the global syntax but I can't get it to work. Not used to the global v local variables in python

PREV_HASH = ''
LOGFILE_DIRECTORY = 'c:\\securelog\\securelog_logs\\'
ARCHIVE_FOLDER = 'c:\\securelog\\securelog_archive\\'
WORKFILES_FOLDER = 'c:\\securelog\\securelog_workfiles\\'
TMP_FOLDER = 'c:\\securelog\\processed\\'
COMPLETED_FOLDER = 'c:\\securelog\\completed\\'

CHAIN_FILE = WORKFILES_FOLDER + 'chain_info.txt'

#check if this is the first run, if it is hardcode the block & previous hash and pass the hash
if chain_list[0] == 1:
    fileHandle = open (CHAIN_FILE, 'r+')
    fileHandle.write('1,0,' + hasher.hexdigest())
    fileHandle.close()
    global PREV_HASH
    PREV_HASH = hasher.hexdigest()
    #print("1 previous hash is: " + str(PREV_HASH))
else:
    #update list with hash of current and previous block
    ###del (chain_list[1:])
    global PREV_HASH
    chain_list.insert (1,PREV_HASH)
    print("2 previous hash is: " + str(PREV_HASH))
    chain_list.insert (2,hasher.hexdigest())
    fileHandle = open (CHAIN_FILE, 'a')
    print('2 what is the chain list at this point:' + str(chain_list))

    #Write the contents of the list to the chain file on a new line and separate with a comma
    fileHandle.write(',' + str(chain_list[2]))
    fileHandle.close()

    PREV_HASH = hasher.hexdigest()

I expect on the first run of the script, a new file to be created and contain one line with 1, 0 and a hash key that was generated in a previous step ("hasher.hexdigest()")
That hash will then be saved in a global variable PREV_HASH

Then on the second run the file will be updated with a new line from a list. It will contain an incremented number, previous hash and current hash

2,previous #,current #

When removing the global PREV_HASH i get the following output

>file does not exist
>-----------------
>24
>1--2019-05-31-archive.zip
>what is the chain list at this point:[1, 0, 0]
>1 previous hash is:

>C:\Python>"SL Proof of Concept.py"
>-----------------
>17
>2--2019-05-31-archive.zip
>what is the chain list at this point:[2, '0', '01d056902f77f5a247f639d363b67827d762d72f9738498989d417563c504a3f82f7b44d7e827cd35843545d33856c85']
>2 previous hash before insert is:
>2 what is the chain list at this point:[2, '', '93fcc831b99a8de59063924a994bf81d09dc677b635e32fc133747ca564bfa843fa6bf60274feeb372a5eeb6f406a120', '0', '01d056902f77f5a247f639d363b67827d762d72f9738
498989d417563c504a3f82f7b44d7e827cd35843545d33856c85']


问:
tabulator is not a function
I am following quick start guide in tabulator(v4.2+) - http://tabulator.info/docs/4.2/quickstart which worked as expected, when I included a button click function inside my html script I get .tabulator is not a function error and the table variable seems to be printing undefined in the browser console,

When i try to print in the browser console it returns table object but not console.log from the code

var tabledata = [{
  id: 1,
  name: "Oli Bob",
  age: "12",
  col: "red",
  dob: ""
}, {
  id: 2,
  name: "Mary May",
  age: "1",
  col: "blue",
  dob: "14/05/1982"
}, {
  id: 3,
  name: "Christine Lobowski",
  age: "42",
  col: "green",
  dob: "22/05/1982"
}, {
  id: 4,
  name: "Brendon Philips",
  age: "125",
  col: "orange",
  dob: "01/08/1980"
}, {
  id: 5,
  name: "Margret Marmajuke",
  age: "16",
  col: "yellow",
  dob: "31/01/1999"
}, ];

table = new Tabulator("#example-table", {
  height: 200,
  data: tabledata,
  layout: "fitColumns",
  columns: [{
    title: "Name",
    field: "name",
    width: 150
  }, {
    title: "Age",
    field: "age",
    align: "left",
    formatter: "progress"
  }, {
    title: "Favourite Color",
    field: "col"
  }, {
    title: "Date Of Birth",
    field: "dob",
    sorter: "date",
    align: "center"
  }, ],
  rowClick: function(e, row) {
    alert("Row " + row.getData().id + " Clicked!!!!");
  },
});
console.log(table);

$("#savebtn").click(function(e) {
  e.preventDefault()
  console.log(table)
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://unpkg.com/tabulator-tables@4.2.7/dist/css/tabulator.min.css" rel="stylesheet">
<script type="text/javascript" src="https://unpkg.com/tabulator-tables@4.2.7/dist/js/tabulator.min.js"></script>

<div class="form-group">
  <label for="comment2"></label>
  <div id="example-table"></div>
</div>

<input type="submit" value="Save" id="savebtn" /></code>```

The error is coming in this part of the code when the button click happens, table object is printing as undefined ?

```<code>$("#savebtn").click(function(e) {
  e.preventDefault()
  console.log(table)
});
</code>```

答:
Use var keyword

```<code>var table = new Tabulator(
</code>```

const tabledata = [{
  id: 1,
  name: "Oli Bob",
  age: "12",
  col: "red",
  dob: ""
}, {
  id: 2,
  name: "Mary May",
  age: "1",
  col: "blue",
  dob: "14/05/1982"
}, {
  id: 3,
  name: "Christine Lobowski",
  age: "42",
  col: "green",
  dob: "22/05/1982"
}, {
  id: 4,
  name: "Brendon Philips",
  age: "125",
  col: "orange",
  dob: "01/08/1980"
}, {
  id: 5,
  name: "Margret Marmajuke",
  age: "16",
  col: "yellow",
  dob: "31/01/1999"
}, ];

const table = new Tabulator("#example-table", {
  height: 200,
  data: tabledata,
  layout: "fitColumns",
  columns: [{
    title: "Name",
    field: "name",
    width: 150
  }, {
    title: "Age",
    field: "age",
    align: "left",
    formatter: "progress"
  }, {
    title: "Favourite Color",
    field: "col"
  }, {
    title: "Date Of Birth",
    field: "dob",
    sorter: "date",
    align: "center"
  }, ],
  rowClick: function(e, row) {
    alert("Row " + row.getData().id + " Clicked!!!!");
  },
});
console.log(table.getData());

$("#savebtn").click(function(e) {
 // e.preventDefault()
 // console.log(table.getData());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <link href="https://unpkg.com/tabulator-tables@4.2.7/dist/css/tabulator.min.css" rel="stylesheet">
  <script type="text/javascript" src="https://unpkg.com/tabulator-tables@4.2.7/dist/js/tabulator.min.js"></script>
</head>

<body>
  <div class="form-group">
    <label for="comment2"></label>
    <div id="example-table"></div>
  </div>

  <input type="submit" value="Save" id="savebtn" />
</body>

</html></code>```

Title: tabulator is not a function

Body:
I am following quick start guide in tabulator(v4.2+) - http://tabulator.info/docs/4.2/quickstart which worked as expected, when I included a button click function inside my html script I get .tabulator is not a function error and the table variable seems to be printing undefined in the browser console,

When i try to print in the browser console it returns table object but not console.log from the code

var tabledata = [{
  id: 1,
  name: "Oli Bob",
  age: "12",
  col: "red",
  dob: ""
}, {
  id: 2,
  name: "Mary May",
  age: "1",
  col: "blue",
  dob: "14/05/1982"
}, {
  id: 3,
  name: "Christine Lobowski",
  age: "42",
  col: "green",
  dob: "22/05/1982"
}, {
  id: 4,
  name: "Brendon Philips",
  age: "125",
  col: "orange",
  dob: "01/08/1980"
}, {
  id: 5,
  name: "Margret Marmajuke",
  age: "16",
  col: "yellow",
  dob: "31/01/1999"
}, ];

table = new Tabulator("#example-table", {
  height: 200,
  data: tabledata,
  layout: "fitColumns",
  columns: [{
    title: "Name",
    field: "name",
    width: 150
  }, {
    title: "Age",
    field: "age",
    align: "left",
    formatter: "progress"
  }, {
    title: "Favourite Color",
    field: "col"
  }, {
    title: "Date Of Birth",
    field: "dob",
    sorter: "date",
    align: "center"
  }, ],
  rowClick: function(e, row) {
    alert("Row " + row.getData().id + " Clicked!!!!");
  },
});
console.log(table);

$("#savebtn").click(function(e) {
  e.preventDefault()
  console.log(table)
});

<link href="https://unpkg.com/tabulator-tables@4.2.7/dist/css/tabulator.min.css" rel="stylesheet">

<input type="submit" value="Save" id="savebtn" />

The error is coming in this part of the code when the button click happens, table object is printing as undefined ?

$("#savebtn").click(function(e) {
  e.preventDefault()
  console.log(table)
});

Body:
Use var keyword

var table = new Tabulator(

const tabledata = [{
  id: 1,
  name: "Oli Bob",
  age: "12",
  col: "red",
  dob: ""
}, {
  id: 2,
  name: "Mary May",
  age: "1",
  col: "blue",
  dob: "14/05/1982"
}, {
  id: 3,
  name: "Christine Lobowski",
  age: "42",
  col: "green",
  dob: "22/05/1982"
}, {
  id: 4,
  name: "Brendon Philips",
  age: "125",
  col: "orange",
  dob: "01/08/1980"
}, {
  id: 5,
  name: "Margret Marmajuke",
  age: "16",
  col: "yellow",
  dob: "31/01/1999"
}, ];

const table = new Tabulator("#example-table", {
  height: 200,
  data: tabledata,
  layout: "fitColumns",
  columns: [{
    title: "Name",
    field: "name",
    width: 150
  }, {
    title: "Age",
    field: "age",
    align: "left",
    formatter: "progress"
  }, {
    title: "Favourite Color",
    field: "col"
  }, {
    title: "Date Of Birth",
    field: "dob",
    sorter: "date",
    align: "center"
  }, ],
  rowClick: function(e, row) {
    alert("Row " + row.getData().id + " Clicked!!!!");
  },
});
console.log(table.getData());

$("#savebtn").click(function(e) {
 // e.preventDefault()
 // console.log(table.getData());
});

<html>

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <link href="https://unpkg.com/tabulator-tables@4.2.7/dist/css/tabulator.min.css" rel="stylesheet">
  <script type="text/javascript" src="https://unpkg.com/tabulator-tables@4.2.7/dist/js/tabulator.min.js"></script>
</head>

<body>
  <div class="form-group">
    <label for="comment2"></label>
    <div id="example-table"></div>
  </div>

  <input type="submit" value="Save" id="savebtn" />
</body>

</html>


问:
Nginx rewrite : how to remove everything after extension of a file
There are a lot of bad request of images and files on my site... but with names close from the real name. basically, if i have a file called example.gif, there is a call to example.gifzerzer. What i want is to rewrite to keep the name and the extension, but nothing after it.

I did create a map file with rewrite (it's working for example the tmp.php to index.php rewrite below except the rule for removing everything after extension).

Here is what i've done so far :

```<code>/(.+\.(bmp|gif|ico|jpeg|jpg|png|svg)).+ /$1;
</code>```

this is not working neither

```<code>/(.+\.(bmp|gif|ico|jpeg|jpg|png|svg)).+? /$1;
</code>```

my map :

```<code>map $request_uri $redirect_uri {
  default "";
  /(.+\.(bmp|gif|ico|jpeg|jpg|png|svg)).+ /$1;
  /tmp.php /index.php;
}
</code>```

i was under Apache before migrating to Nginx and this was working :

```<code>RewriteRule ^([a-z0-9\-/_]*\.(bmp|gif|ico|jpeg|jpg|png|svg)).+ /$1 [R=301,L]
</code>```

答:
I did that rewrite that is working, when put in the server section, but then it is not included in the map.

```<code>location ~ (.+\.(bmp|gif|ico|jpeg|jpg|png|svg)).+$ {
    return 301 /$1;
}
</code>```

if someone has an idea why, or can confirm that i'm doing it right ?

Body:
There are a lot of bad request of images and files on my site... but with names close from the real name. basically, if i have a file called example.gif, there is a call to example.gifzerzer. What i want is to rewrite to keep the name and the extension, but nothing after it.

I did create a map file with rewrite (it's working for example the tmp.php to index.php rewrite below except the rule for removing everything after extension).

Here is what i've done so far :

/(.+\.(bmp|gif|ico|jpeg|jpg|png|svg)).+ /$1;

this is not working neither

/(.+\.(bmp|gif|ico|jpeg|jpg|png|svg)).+? /$1;

my map :

map $request_uri $redirect_uri {
  default "";
  /(.+\.(bmp|gif|ico|jpeg|jpg|png|svg)).+ /$1;
  /tmp.php /index.php;
}

i was under Apache before migrating to Nginx and this was working :

RewriteRule ^([a-z0-9\-/_]*\.(bmp|gif|ico|jpeg|jpg|png|svg)).+ /$1 [R=301,L]

Body:
I did that rewrite that is working, when put in the server section, but then it is not included in the map.

location ~ (.+\.(bmp|gif|ico|jpeg|jpg|png|svg)).+$ {
    return 301 /$1;
}

if someone has an idea why, or can confirm that i'm doing it right ?


问:
xDocument Remove Element base on sub-element value
I'm trying to remove an element from an xml file based on it's sub-element value.

my xml is formated like this:

I want to remove the CB element if it's sub-element CBA has the value of AXIS.

This is what I'm trying, the compiler isn't giving me any errors, but it's also not doing removing the element.

```<code>string portXML = @"C:\Users\User\Desktop\port.xml";
XDocument _port = XDocument.Load(portXML);
_port.Descendants().Where(e => e.Name("CBA").Value == "AXIS").Remove();
_port.Save(portXML);
</code>```

I'm not familiar with how attributes/elements and xDoc, so I apologies if this is a stupid question.

答:
Try the following:</p>

```<code>string portXML = @"C:\Users\User\Desktop\port.xml";
            XDocument _port = XDocument.Load(portXML);
             _port.Descendants("CB").Where(e => e.Element("CBA").Value == "AXIS").Remove();
            _port.Save(portXML);
</code>```

Body:
I'm trying to remove an element from an xml file based on it's sub-element value.

my xml is formated like this:

I want to remove the CB element if it's sub-element CBA has the value of AXIS.

This is what I'm trying, the compiler isn't giving me any errors, but it's also not doing removing the element.

string portXML = @"C:\Users\User\Desktop\port.xml";
XDocument _port = XDocument.Load(portXML);
_port.Descendants().Where(e => e.Name("CBA").Value == "AXIS").Remove();
_port.Save(portXML);

I'm not familiar with how attributes/elements and xDoc, so I apologies if this is a stupid question.

Body:
Try the following:

string portXML = @"C:\Users\User\Desktop\port.xml";
            XDocument _port = XDocument.Load(portXML);
             _port.Descendants("CB").Where(e => e.Element("CBA").Value == "AXIS").Remove();
            _port.Save(portXML);


答:
You have 2 problems in your if statement :

Replace if ($x=blue) { by if ($x == "blue") {

Blue is a string so you need some quote

= is to assign value, == or === are for comparaison.

But you shouldn't do a foreach loop to get your answer. If you just do $group_id = $grouparray['blue']; you will get what you want, not sure why you need a loop ?

Title: how to get the respective array key value if it meets the if condition in for loop

Body:
I have any array with keys and values , I want to get the value of the key ,if key is equal to certain string.

When I use this code I am getting the last key value of array. I have the flexibility to change the array structure also if we want.

$grouparray =[ "red" => "4" , "blue" =>"5" , "green" => "6"];

foreach($grouparray   as $x=>$x_value){
          if($x=blue){
              $group_id=$x_value;

          }

      }

print_r($group_id);

I want to expect $group_id = 5;


问:
Python combo chart add the percentage on the bar but wrong
I tried to add the percentage on the bar in combo chart, line and column graphs.

However, all the values displayed are messy.

I provide the data here, this is also my previous post and the answer is provided by Quang Hoang.

```<code>Group   yq        Value1    Value2
G       2014Q1     0.07        1.1
G       2014Q2     0.06        1.09
G       2014Q3     0.09        1.11
G       2014Q4     0.04        1.13
I       2014Q1     0.10        1.2
I       2014Q2     0.13        1.25
I       2014Q3     0.15        1.23
I       2014Q4     0.18        1.4
</code>```

I provided the code I tried:

```<code>fig, ax1 = plt.subplots(figsize=(7,5))
ax2=ax1.twinx()
sns.lineplot(x='yq',y='Value2', data=dataset, hue='Group', ax=ax1, legend = None)
ax1.set_xticklabels(ax1.get_xticks(), rotation=45)
ax1.set_ylabel("")
ax1.set_ylim((min(dataset['Value2']) - 0.05, max(dataset['Value2']) + 0.05))
sns.barplot(x='yq', y='Value1', data=dataset, hue='Group',ax=ax2)
ax2.set_yticklabels(['{:.1f}%'.format(a*100) for a in ax2.get_yticks()])
ax2.set_ylabel("")
for index, row in dataset.iterrows():
    ax2.text(row.name,row['Value1'], '{:.1f}%'.format(round(row['Value1'],2)), color='black')
plt.show()
</code>```

The percentages showing on the plot are messy and do not place properly on each bar and group.

I searched on here and here but I cannot solve it.

Any solution?

I provide my result:

I also provide the correct resulting image created by R's package ggplot2.

There are two packages similar to ggplot2 in Python, plotnine and ggplot. However, I cannot use it in my Python.

I provide my R code as your reference if it helps:

```<code>library(data.table)
library(ggplot2)
library(zoo)
dataset <- fread("Group   yq        Value1    Value2
G       2014/1/1     0.07        1.1
G       2014/4/1     0.06        1.09
G       2014/7/1     0.09        1.11
G       2014/10/1     0.04        1.13
I       2014/1/1     0.10        1.2
I       2014/4/1     0.13        1.25
I       2014/7/1     0.15        1.23
I       2014/10/1     0.18        1.4", header = T)
dataset$yq <- as.Date(dataset$yq)
dataset[, yq := as.yearqtr(dataset$yq, format = "%Y-%m-%d")]

ggplot(data = dataset, aes(x = yq, colour = Group, fill = Group,
                           label = scales::percent(Value1, accuracy = 0.1))) +
  geom_col(aes(y = sec_axis_mult * Value1), position = position_dodge2(width = 0)) +
  geom_line(aes(y = Value2)) +
  scale_colour_manual(values = c("red", "darkblue"), labels = c("G", "I")) +
  scale_fill_manual(values = c("red", "darkblue"), labels = NULL, breaks = NULL) +
  scale_x_yearqtr(format = "%YQ%q", breaks = unique(dataset$yq)) +
  scale_y_continuous(name = "Value2",
                     sec.axis = sec_axis(~./sec_axis_mult, name = "Value1",
                                         labels = scales::percent)) +
  theme_bw() +
  theme(axis.title.x = element_blank(),
        axis.title.y = element_blank(),
        axis.title.y.right = element_blank(),
        axis.ticks.x=element_blank(),
        axis.ticks.y=element_blank(),
        axis.text.x=element_text(angle = 45, size = 12, vjust = 0.5, face = "bold"),
        axis.text.y=element_blank(),
        axis.line = element_line(colour = "white"),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.border = element_blank(),
        panel.background = element_blank(),
        plot.background=element_blank(),
        legend.position="left",
        legend.title=element_blank(),
        legend.text = element_text(size = 16, face = "bold"),
        legend.key = element_blank(),
        legend.box.background =  element_blank()) +
  guides(colour = guide_legend(override.aes = list(shape = 15, size = 10))) +
  geom_text(data = dataset, aes(y = sec_axis_mult * Value1, colour = Group),
            position = position_dodge(width = 0.25),
            vjust = -0.3, size = 4)
</code>```

答:
What I'm doing is dynamically labeling the bar graphs based on the coordinates for each patch that's drawn by the bar function.

```<code>fig, ax1 = plt.subplots(figsize=(7,5))
ax2=ax1.twinx()
sns.lineplot(x='yq',y='Value2', data=dataset, hue='Group', ax=ax1, legend = None)
ax1.set_xticklabels(ax1.get_xticks(), rotation=45)
ax1.set_ylabel("")
ax1.set_ylim((min(dataset['Value2']) - 0.05, max(dataset['Value2']) + 0.05))
sns.barplot(x='yq', y='Value1', data=dataset, hue='Group',ax=ax2)
ax2.set_yticklabels(['{:.1f}%'.format(a*100) for a in ax2.get_yticks()])
ax2.set_ylabel("")
#iterate through each group of bars
for group in ax2.containers:
    for bar in group:
        #label the bar graphs based on the coordinates of the bar patches
        ax2.text(
            bar.get_xy()[0]+bar.get_width()/2,
            bar.get_height(),
            '{:.1f}%'.format(round(100*bar.get_height(),2)),
            color='black',
            horizontalalignment='center'
        )
</code>```

Output:

I've adjusted the code to more closely match the desired output that's been added to the original question.

```<code>fig, ax1 = plt.subplots(figsize=(7,5))
ax2=ax1.twiny().twinx()
sns.lineplot(x='yq',y='Value2', data=dataset, hue='Group', ax=ax1, legend = None)
ax1.set_xticklabels(dataset['yq'], rotation=45)
ax1.set_ylabel("")
ax1.set_ylim((0, max(dataset['Value2']) + 0.05))
ax2.set_ylim(0, max(dataset['Value2']) + 0.05)
sns.barplot(x='yq', y='Value1', data=dataset, hue='Group',ax=ax2)

#iterate through each group of bars
for group in ax2.containers:
    for bar in group:
        #label the bar graphs based on the coordinates of the bar patches
        ax2.text(
            bar.get_xy()[0]+bar.get_width()/2,
            bar.get_height(),
            '{:.1f}%'.format(100*bar.get_height()),
            color='black',
            horizontalalignment='center'
        )

ax1.yaxis.set_visible(False)
ax2.yaxis.set_visible(False)
ax2.xaxis.set_visible(False)
</code>```

Outputs:

Body:
I tried to add the percentage on the bar in combo chart, line and column graphs.

However, all the values displayed are messy.

I provide the data here, this is also my previous post and the answer is provided by Quang Hoang.

Group   yq        Value1    Value2
G       2014Q1     0.07        1.1
G       2014Q2     0.06        1.09
G       2014Q3     0.09        1.11
G       2014Q4     0.04        1.13
I       2014Q1     0.10        1.2
I       2014Q2     0.13        1.25
I       2014Q3     0.15        1.23
I       2014Q4     0.18        1.4

I provided the code I tried:

fig, ax1 = plt.subplots(figsize=(7,5))
ax2=ax1.twinx()
sns.lineplot(x='yq',y='Value2', data=dataset, hue='Group', ax=ax1, legend = None)
ax1.set_xticklabels(ax1.get_xticks(), rotation=45)
ax1.set_ylabel("")
ax1.set_ylim((min(dataset['Value2']) - 0.05, max(dataset['Value2']) + 0.05))
sns.barplot(x='yq', y='Value1', data=dataset, hue='Group',ax=ax2)
ax2.set_yticklabels(['{:.1f}%'.format(a*100) for a in ax2.get_yticks()])
ax2.set_ylabel("")
for index, row in dataset.iterrows():
    ax2.text(row.name,row['Value1'], '{:.1f}%'.format(round(row['Value1'],2)), color='black')
plt.show()

The percentages showing on the plot are messy and do not place properly on each bar and group.

I searched on here and here but I cannot solve it.

Any solution?

I provide my result:

I also provide the correct resulting image created by R's package ggplot2.

There are two packages similar to ggplot2 in Python, plotnine and ggplot. However, I cannot use it in my Python.

I provide my R code as your reference if it helps:

library(data.table)
library(ggplot2)
library(zoo)
dataset <- fread("Group   yq        Value1    Value2
G       2014/1/1     0.07        1.1
G       2014/4/1     0.06        1.09
G       2014/7/1     0.09        1.11
G       2014/10/1     0.04        1.13
I       2014/1/1     0.10        1.2
I       2014/4/1     0.13        1.25
I       2014/7/1     0.15        1.23
I       2014/10/1     0.18        1.4", header = T)
dataset$yq <- as.Date(dataset$yq)
dataset[, yq := as.yearqtr(dataset$yq, format = "%Y-%m-%d")]

ggplot(data = dataset, aes(x = yq, colour = Group, fill = Group,
                           label = scales::percent(Value1, accuracy = 0.1))) +
  geom_col(aes(y = sec_axis_mult * Value1), position = position_dodge2(width = 0)) +
  geom_line(aes(y = Value2)) +
  scale_colour_manual(values = c("red", "darkblue"), labels = c("G", "I")) +
  scale_fill_manual(values = c("red", "darkblue"), labels = NULL, breaks = NULL) +
  scale_x_yearqtr(format = "%YQ%q", breaks = unique(dataset$yq)) +
  scale_y_continuous(name = "Value2",
                     sec.axis = sec_axis(~./sec_axis_mult, name = "Value1",
                                         labels = scales::percent)) +
  theme_bw() +
  theme(axis.title.x = element_blank(),
        axis.title.y = element_blank(),
        axis.title.y.right = element_blank(),
        axis.ticks.x=element_blank(),
        axis.ticks.y=element_blank(),
        axis.text.x=element_text(angle = 45, size = 12, vjust = 0.5, face = "bold"),
        axis.text.y=element_blank(),
        axis.line = element_line(colour = "white"),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.border = element_blank(),
        panel.background = element_blank(),
        plot.background=element_blank(),
        legend.position="left",
        legend.title=element_blank(),
        legend.text = element_text(size = 16, face = "bold"),
        legend.key = element_blank(),
        legend.box.background =  element_blank()) +
  guides(colour = guide_legend(override.aes = list(shape = 15, size = 10))) +
  geom_text(data = dataset, aes(y = sec_axis_mult * Value1, colour = Group),
            position = position_dodge(width = 0.25),
            vjust = -0.3, size = 4)

Body:
What I'm doing is dynamically labeling the bar graphs based on the coordinates for each patch that's drawn by the bar function.

fig, ax1 = plt.subplots(figsize=(7,5))
ax2=ax1.twinx()
sns.lineplot(x='yq',y='Value2', data=dataset, hue='Group', ax=ax1, legend = None)
ax1.set_xticklabels(ax1.get_xticks(), rotation=45)
ax1.set_ylabel("")
ax1.set_ylim((min(dataset['Value2']) - 0.05, max(dataset['Value2']) + 0.05))
sns.barplot(x='yq', y='Value1', data=dataset, hue='Group',ax=ax2)
ax2.set_yticklabels(['{:.1f}%'.format(a*100) for a in ax2.get_yticks()])
ax2.set_ylabel("")
#iterate through each group of bars
for group in ax2.containers:
    for bar in group:
        #label the bar graphs based on the coordinates of the bar patches
        ax2.text(
            bar.get_xy()[0]+bar.get_width()/2,
            bar.get_height(),
            '{:.1f}%'.format(round(100*bar.get_height(),2)),
            color='black',
            horizontalalignment='center'
        )

Output:

I've adjusted the code to more closely match the desired output that's been added to the original question.

fig, ax1 = plt.subplots(figsize=(7,5))
ax2=ax1.twiny().twinx()
sns.lineplot(x='yq',y='Value2', data=dataset, hue='Group', ax=ax1, legend = None)
ax1.set_xticklabels(dataset['yq'], rotation=45)
ax1.set_ylabel("")
ax1.set_ylim((0, max(dataset['Value2']) + 0.05))
ax2.set_ylim(0, max(dataset['Value2']) + 0.05)
sns.barplot(x='yq', y='Value1', data=dataset, hue='Group',ax=ax2)

#iterate through each group of bars
for group in ax2.containers:
    for bar in group:
        #label the bar graphs based on the coordinates of the bar patches
        ax2.text(
            bar.get_xy()[0]+bar.get_width()/2,
            bar.get_height(),
            '{:.1f}%'.format(100*bar.get_height()),
            color='black',
            horizontalalignment='center'
        )

ax1.yaxis.set_visible(False)
ax2.yaxis.set_visible(False)
ax2.xaxis.set_visible(False)

Outputs:


问:
How to structure Dynamodb correctly to have nested or linked properties?
I am getting started with Dynamodb and I am trying to figure out what is the correct way to structure the following:

I have a user, and each user can have multiple pictures (s3 links and some metadata), with no limit to the amount.

Whenever I am calling for a user I would retrieve all their pictures, there would be no reads on a single picture, and each time a user uploads a picture, I need to store it for the user.

In Mongodb I would have created an array called pictures holding objects with each picture's data. Is this also the correct approach in Dynamodb?

答:
Here is how you can do with dynamodb

```<code>| pk    |   sk     |
| user1 |  metadata | age:24 | name: Jon| ...
| user1 | picture#1234#id1 | url:abc.com/xyz.jpeg | ... some other metadata
| user1 | picture#2456#id2 | url:abc.com/xyz.jpeg | ... some other metadata
| user1 | picture#4567#id3 | url:abc.com/xyz.jpeg | ... some other metadata

</code>```

where 1234, 2456 may represent epoch time uploading the picture.
Now you can do queries like

get me all the pictures in chronological order.

Select * from table where pk=user1 and sk starts with picture#

get me all the pictures uploaded b/w or after certain date.

Select * from table where pk=user1 and sk starts with picture# and sk>picture#1234

Get me user details

Select from table where pk=user1 and sk=metadata

This will make sure few things

No race condition/lock while uploading the picture

you can decide how many images you want to fetch, And you will read only what you need, instead of loading all of them and then filtering.

Body:
Here is how you can do with dynamodb

| pk    |   sk     |
| user1 |  metadata | age:24 | name: Jon| ...
| user1 | picture#1234#id1 | url:abc.com/xyz.jpeg | ... some other metadata
| user1 | picture#2456#id2 | url:abc.com/xyz.jpeg | ... some other metadata
| user1 | picture#4567#id3 | url:abc.com/xyz.jpeg | ... some other metadata

where 1234, 2456 may represent epoch time uploading the picture.
Now you can do queries like

get me all the pictures in chronological order.

Select * from table where pk=user1 and sk starts with picture#

get me all the pictures uploaded b/w or after certain date.

Select * from table where pk=user1 and sk starts with picture# and sk>picture#1234

Get me user details

Select from table where pk=user1 and sk=metadata

This will make sure few things

No race condition/lock while uploading the picture

you can decide how many images you want to fetch, And you will read only what you need, instead of loading all of them and then filtering.


问:
Visual Studio : Linking User Control and Form
I have created dashboard consisting of two windows -  home screen (the Form) and data screen (the User Control).
My home screen is the dashboard and upon clicking on "data" button present on the dashboard, the user is sent to the data screen (where he enters his details) . The way I'm doing this transition between the 2 windows is by making the data screen visible and bringing it to front when data button is pressed.

Q1. Is this the right way to go about switching windows? Is there a better method to do this?

Coming to the main question, the dashboard indicates whether the user has entered data or not and if yes, the user data is displayed. The code to fetch the user data is written in the user control. Now I wish to send this data to the home screen (form) so that the data can be displayed on the dashboard.

Q2. How to link the user control and form - variables wise? How to establish a Bidirectional Communication between form and user control i.e. User control should be able to read form's variables and form should be able to read user control's variables

答:
Here are two approaches...

Tightly Coupled

In UserControlA, I've declared a property of type Form1 (the parent form):

```<code>public partial class UserControlA : UserControl
{

    public UserControlA()
    {
        InitializeComponent();
    }

    private Form1 f1;
    public Form1 F1
    {
        get { return f1; }
        set { f1 = value; }
    }

    private void foo()
    {
        if (f1 != null)
        {
            // ... do something with "f1" ...
        }
    }

}
</code>```

Then, in Form1, I set that property in the Load() event:

```<code>public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        userControlA1.F1 = this;
    }

}
</code>```

This is tightly coupled because now UserControlA has a hard-coded reference to Form1.  This makes it work well with Form1, but is now less flexible as it won't work well with any other forms. If you wanted this approach to work with Form2, for instance, then you'd have to change the hard-coded type in the UserControl.

Use this approach if there is a very strong relationship between the form and the usercontrol and it's likely that the usercontrol will not be used with any other forms, or in any other scenarios.

Loosely Coupled

In UserControlB, I've declared an event (BroadcastName) that will communicate a string to the outside world:

```<code>public partial class UserControlB : UserControl
{

    public delegate void dlgBroadcastName(UserControlB source, string name);
    public event dlgBroadcastName BroadcastName;

    public UserControlB()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (BroadcastName != null)
        {
            BroadcastName(this, textBox1.Text);
        }
    }

}
</code>```

Now, in the Load() event of Form1 (or using the lightning bolt icon in the properties pane), we wire up that BroadcastName event:

```<code>public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        userControlB1.BroadcastName += UserControlB1_BroadcastName;
    }

    private void UserControlB1_BroadcastName(UserControlB source, string name)
    {
        // ... do something to Form1 with the received information in here ...
    }

}
</code>```

This is loosely coupled because UserControlB has no idea who it is communicating with.  It simply raises its event and whoever has subscribed gets notified.  Note that this UserControl can be used with any form, without change.  This is generally a more flexible approach and makes sense when your usercontrol is more generic in nature and will be used in a wider variety of situations.

Body:
Here are two approaches...

Tightly Coupled

In UserControlA, I've declared a property of type Form1 (the parent form):

public partial class UserControlA : UserControl
{

    public UserControlA()
    {
        InitializeComponent();
    }

    private Form1 f1;
    public Form1 F1
    {
        get { return f1; }
        set { f1 = value; }
    }

    private void foo()
    {
        if (f1 != null)
        {
            // ... do something with "f1" ...
        }
    }

}

Then, in Form1, I set that property in the Load() event:

public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        userControlA1.F1 = this;
    }

}

This is tightly coupled because now UserControlA has a hard-coded reference to Form1.  This makes it work well with Form1, but is now less flexible as it won't work well with any other forms. If you wanted this approach to work with Form2, for instance, then you'd have to change the hard-coded type in the UserControl.

Use this approach if there is a very strong relationship between the form and the usercontrol and it's likely that the usercontrol will not be used with any other forms, or in any other scenarios.

Loosely Coupled

In UserControlB, I've declared an event (BroadcastName) that will communicate a string to the outside world:

public partial class UserControlB : UserControl
{

    public delegate void dlgBroadcastName(UserControlB source, string name);
    public event dlgBroadcastName BroadcastName;

    public UserControlB()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (BroadcastName != null)
        {
            BroadcastName(this, textBox1.Text);
        }
    }

}

Now, in the Load() event of Form1 (or using the lightning bolt icon in the properties pane), we wire up that BroadcastName event:

public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        userControlB1.BroadcastName += UserControlB1_BroadcastName;
    }

    private void UserControlB1_BroadcastName(UserControlB source, string name)
    {
        // ... do something to Form1 with the received information in here ...
    }

}

This is loosely coupled because UserControlB has no idea who it is communicating with.  It simply raises its event and whoever has subscribed gets notified.  Note that this UserControl can be used with any form, without change.  This is generally a more flexible approach and makes sense when your usercontrol is more generic in nature and will be used in a wider variety of situations.