问:
PHP Removing duplicate objects from array
I've tried all sorts of PHP logic and PHP's built in functions to remove duplicate values but it is not working no errors shows up but all my JQuery and CSS doesn't work if use array_unique() in_array() to remove the duplicate objects in my array

this is how i am creating my person_row_array inside a while loop:

```<code>$person_row = Person::findByID($pi_claimant_row->person_id);
$person_row_array[] = $person_row;
</code>```

object print_r is below:

```<code>Array
(
[0] => stdClass Object
    (
        [id] => 12
        [flat_no] =>
        [house_no] => *
        [street] =>
        [town] =>
        [postcode] => *
        [county] =>
    )

[1] => stdClass Object
    (
        [id] => 14
        [flat_no] => 2
        [house_no] => 33
        [street] => Street
        [town] => Town
        [postcode] => BB
        [county] => County
    )

[2] => stdClass Object
    (
        [id] => 14
        [flat_no] => 2
        [house_no] => 33
        [street] => Street
        [town] => Town
        [postcode] => BB
        [county] => County
    )

[3] => stdClass Object
    (
        [id] => 14
        [flat_no] => 2
        [house_no] => 33
        [street] => Street
        [town] => Town
        [postcode] => BB
        [county] => County
    )

[4] => stdClass Object
    (
        [id] => 15
        [flat_no] => FN
        [house_no] => HN
        [street] => Street
        [town] => Nelson
        [postcode] => PC
        [county] => Manchester
    )

[5] => stdClass Object
    (
        [id] => 15
        [flat_no] => FN
        [house_no] => HN
        [street] => Street
        [town] => Nelson
        [postcode] => PC
        [county] => Manchester
    )

[6] => stdClass Object
    (
        [id] => 16
        [flat_no] => FN
        [house_no] => house
        [street] => Manchester Road
        [town] => Town
        [postcode] => M1 4MK
        [county] => County
    )

)
</code>```

I want to remove those duplicate ones please help and please do not advise me to use array_unique() I've been trying this for last few hours not working but if you could tell me any other way or add object if already not exits.

Please Note this is fake data i only want to remove those array those have similar ids.

Best regards

答:
You can make it unique for any field (key) like id, name or num    </p>

```<code>function unique_multidimensional_array($array, $key) {
    $temp_array = array();
    $i = 0;
    $key_array = array();

    foreach($array as $val) {
        if (!in_array($val[$key], $key_array)) {
            $key_array[$i] = $val[$key];
            $temp_array[$i] = $val;
        }
        $i++;
    }
    return $temp_array;
}
</code>```

Body:
I've tried all sorts of PHP logic and PHP's built in functions to remove duplicate values but it is not working no errors shows up but all my JQuery and CSS doesn't work if use array_unique() in_array() to remove the duplicate objects in my array

this is how i am creating my person_row_array inside a while loop:

$person_row = Person::findByID($pi_claimant_row->person_id);
$person_row_array[] = $person_row;

object print_r is below:

Array
(
[0] => stdClass Object
    (
        [id] => 12
        [flat_no] =>
        [house_no] => *
        [street] =>
        [town] =>
        [postcode] => *
        [county] =>
    )

[1] => stdClass Object
    (
        [id] => 14
        [flat_no] => 2
        [house_no] => 33
        [street] => Street
        [town] => Town
        [postcode] => BB
        [county] => County
    )

[2] => stdClass Object
    (
        [id] => 14
        [flat_no] => 2
        [house_no] => 33
        [street] => Street
        [town] => Town
        [postcode] => BB
        [county] => County
    )

[3] => stdClass Object
    (
        [id] => 14
        [flat_no] => 2
        [house_no] => 33
        [street] => Street
        [town] => Town
        [postcode] => BB
        [county] => County
    )

[4] => stdClass Object
    (
        [id] => 15
        [flat_no] => FN
        [house_no] => HN
        [street] => Street
        [town] => Nelson
        [postcode] => PC
        [county] => Manchester
    )

[5] => stdClass Object
    (
        [id] => 15
        [flat_no] => FN
        [house_no] => HN
        [street] => Street
        [town] => Nelson
        [postcode] => PC
        [county] => Manchester
    )

[6] => stdClass Object
    (
        [id] => 16
        [flat_no] => FN
        [house_no] => house
        [street] => Manchester Road
        [town] => Town
        [postcode] => M1 4MK
        [county] => County
    )

)

I want to remove those duplicate ones please help and please do not advise me to use array_unique() I've been trying this for last few hours not working but if you could tell me any other way or add object if already not exits.

Please Note this is fake data i only want to remove those array those have similar ids.

Best regards

Body:
You can make it unique for any field (key) like id, name or num

function unique_multidimensional_array($array, $key) {
    $temp_array = array();
    $i = 0;
    $key_array = array();

    foreach($array as $val) {
        if (!in_array($val[$key], $key_array)) {
            $key_array[$i] = $val[$key];
            $temp_array[$i] = $val;
        }
        $i++;
    }
    return $temp_array;
}


来源: stackexchange

问:
Java - how to get a key object (or entry) stored in HashMap by key?
I'd like to get the "canonical" key object for each key usable to query a map. See here:

```<code>Map<UUID, String> map = new HashMap();
UUID a = new UUID("ABC...");
map.put(a, "Tu nejde o zamykání.");

UUID b = new UUID("ABC...");
String string = map.get(b); // This gives that string.

// This is what I am looking for:
UUID againA = map.getEntry(b).key();
boolean thisIsTrue = a == againA;
</code>```

A HashMap uses equals(), which is the same for multiple unique objects. So I want to get the actual key from the map, which will always be the same, no matter what object was used to query the map.

Is there a way to get the actual key object from the map? I don't see anything in the interface, but perhaps some clever trick I overlooked?

(Iterating all entries or keys doesn't count.)

答:
I think there are valid reasons for wanting the actual key. For example, to save memory.  Also keep in mind that the actual key may store other objects. For instance, suppose you have a vertex of a graph. The vertex can store the actual data (Say a String, for instance), as well as the incident vertices. A vertex hash value can be dependent only on the data.  So to look up a vertex with some data,
D, look up a vertex with data, D,and with with no incident values.  Now if you can return the actual vertex in the map you will be able to get the actual incident to the vertex.

It seems to me that many map implementations could easily provide a getEntry method.  For example, the HashMap implementation for get is:

```<code>  public V get(Object key) {
    Node<K,V> e;
    return (e = getNode(hash(key), key)) == null ? null : e.value;
  }

  final Node<K,V> getNode(int hash, Object key) {
    Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (first = tab[(n - 1) & hash]) != null) {
        if (first.hash == hash && // always check first node
            ((k = first.key) == key || (key != null && key.equals(k))))
            return first;
        if ((e = first.next) != null) {
            if (first instanceof TreeNode)
                return ((TreeNode<K,V>)first).getTreeNode(hash, key);
            do {
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    return e;
            } while ((e = e.next) != null);
        }
    }
    return null;
 }
</code>```

One could use the getNode method to return an Entry:

```<code> public getEntry(Object key){
   Node<K,V> e = getNode(hash(key),key);
   if(e == null) return null;
   return new Entry<>(e.key,e.value);
 }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'd like to get the "canonical" key object for each key usable to query a map. See here:

Map<UUID, String> map = new HashMap();
UUID a = new UUID("ABC...");
map.put(a, "Tu nejde o zamykání.");

UUID b = new UUID("ABC...");
String string = map.get(b); // This gives that string.

// This is what I am looking for:
UUID againA = map.getEntry(b).key();
boolean thisIsTrue = a == againA;

A HashMap uses equals(), which is the same for multiple unique objects. So I want to get the actual key from the map, which will always be the same, no matter what object was used to query the map.

Is there a way to get the actual key object from the map? I don't see anything in the interface, but perhaps some clever trick I overlooked?

(Iterating all entries or keys doesn't count.)

Body:
I think there are valid reasons for wanting the actual key. For example, to save memory.  Also keep in mind that the actual key may store other objects. For instance, suppose you have a vertex of a graph. The vertex can store the actual data (Say a String, for instance), as well as the incident vertices. A vertex hash value can be dependent only on the data.  So to look up a vertex with some data,
D, look up a vertex with data, D,and with with no incident values.  Now if you can return the actual vertex in the map you will be able to get the actual incident to the vertex.

It seems to me that many map implementations could easily provide a getEntry method.  For example, the HashMap implementation for get is:

  public V get(Object key) {
    Node<K,V> e;
    return (e = getNode(hash(key), key)) == null ? null : e.value;
  }

  final Node<K,V> getNode(int hash, Object key) {
    Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (first = tab[(n - 1) & hash]) != null) {
        if (first.hash == hash && // always check first node
            ((k = first.key) == key || (key != null && key.equals(k))))
            return first;
        if ((e = first.next) != null) {
            if (first instanceof TreeNode)
                return ((TreeNode<K,V>)first).getTreeNode(hash, key);
            do {
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    return e;
            } while ((e = e.next) != null);
        }
    }
    return null;
 }

One could use the getNode method to return an Entry:

 public getEntry(Object key){
   Node<K,V> e = getNode(hash(key),key);
   if(e == null) return null;
   return new Entry<>(e.key,e.value);
 }

ContentLicense: CC BY-SA 4.0


问:
Threading in C, cross platform
I am dealing with an existing project (in C) that is currently running on a single thread, and we would like to run on multiple platforms AND have multiple threads. Hopefully, there is a library for this, because, IMHO, the Win32 API is like poking yourself in the eye repeatedly. I know about Boost.Thread for C++, but, this must be C (and compilable on MinGW and gcc). Cygwin is not an option, sorry.</p>

答:
Try OpenMP API, it's multi-platform and you can compile it with GCC.

Brief description from the wikipedia:

OpenMP (Open Multi-Processing) is an application programming interface
  (API) that supports multi-platform shared memory multiprocessing
  programming in C, C++, and Fortran,[3] on most platforms, processor
  architectures and operating systems, including Solaris, AIX, HP-UX,
  Linux, macOS, and Windows. It consists of a set of compiler
  directives, library routines, and environment variables that influence
  run-time behavior.

Title: Threading in C, cross platform


问:
Which part of MVC we consider while working with ReactJS
I am new to ReactJS, i know we can consider MVC while working with ReactJS. My Question is
ReactJS Focuses on which of the following part when considering MVC

Model

View

Controller

答:
React is JavaScript library from Facebook, that is designed to create interactive UIs. The main features are that it’s
So, React is often referred to as the View in a MVC structure, Facebook presented their own architecture called Flux </p>


问:
Initializing StringBuilder to use UTF-16 coder
Consider the following code in Java 11:

```<code>StringBuilder sb = new StringBuilder("one");
sb.append("δύο");  // "two"
</code>```

The first line creates a StringBuilder that uses the Latin1 coder (one byte per character). Then the second line causes the StringBuilder to realise that it needs to use the UTF16 coder instead, so it copies its current contents into a new array before appending the new UTF-16 characters.

The StringBuilder class has a constructor overload that takes an initial capacity argument, which is designed to avoid reallocation if you already know the required size of the string to be built. But if you start with an English string and then append a foreign string, this particular constructor overload is useless as it still reallocates the byte array.

Is there a way to create a StringBuilder instance that uses UTF16 right from the start?

答:
Having done a bit more research into this, I'm supplying another answer to my own question (Stack Overflow says it's perfectly acceptable to answer your own question.)

As Slawomir says, StringBuilder gets initialized with Latin1 no matter what. So suppose you primarily write in a language such as Russian, Chinese, Hindi or Greek. You want to build a string whose maximum size you already know, so you use the initial capacity argument:

```<code>StringBuilder sb = new StringBuilder(4096);
sb.append("Здравствуйте!");  // Should easily fit in 4 kilobytes, right?
</code>```

Yet the above call to append throws away the 4KB buffer that you previously initialized and allocates a new buffer. You constructed the StringBuilder with an initial capacity in order to avoid reallocating a buffer, but the StringBuilder reallocated it anyway. And it reallocated it even though it was already big enough!

A workaround is to run java using the JVM option -XX:-CompactStrings.

If you consistently use one of these languages, then your Strings will use UTF-16 anyway, so turning off string compaction at startup will reduce the overhead of checking every string you supply to see if it can be stored using Latin1 encoding.

See also Heinz Kabutz's talk at jPrime Bulgaria, 29 May 2019 where he causes StringBuilder to run out of memory due to this "feature".

Body:
Consider the following code in Java 11:

StringBuilder sb = new StringBuilder("one");
sb.append("δύο");  // "two"

The first line creates a StringBuilder that uses the Latin1 coder (one byte per character). Then the second line causes the StringBuilder to realise that it needs to use the UTF16 coder instead, so it copies its current contents into a new array before appending the new UTF-16 characters.

The StringBuilder class has a constructor overload that takes an initial capacity argument, which is designed to avoid reallocation if you already know the required size of the string to be built. But if you start with an English string and then append a foreign string, this particular constructor overload is useless as it still reallocates the byte array.

Is there a way to create a StringBuilder instance that uses UTF16 right from the start?

Body:
Having done a bit more research into this, I'm supplying another answer to my own question (Stack Overflow says it's perfectly acceptable to answer your own question.)

As Slawomir says, StringBuilder gets initialized with Latin1 no matter what. So suppose you primarily write in a language such as Russian, Chinese, Hindi or Greek. You want to build a string whose maximum size you already know, so you use the initial capacity argument:

StringBuilder sb = new StringBuilder(4096);
sb.append("Здравствуйте!");  // Should easily fit in 4 kilobytes, right?

Yet the above call to append throws away the 4KB buffer that you previously initialized and allocates a new buffer. You constructed the StringBuilder with an initial capacity in order to avoid reallocating a buffer, but the StringBuilder reallocated it anyway. And it reallocated it even though it was already big enough!

A workaround is to run java using the JVM option -XX:-CompactStrings.

If you consistently use one of these languages, then your Strings will use UTF-16 anyway, so turning off string compaction at startup will reduce the overhead of checking every string you supply to see if it can be stored using Latin1 encoding.

See also Heinz Kabutz's talk at jPrime Bulgaria, 29 May 2019 where he causes StringBuilder to run out of memory due to this "feature".


问:
XMLRPC Search product.template returns empty list
I'm having trouble getting a list of records through xmlrpc from the product.template model.

This issue is only present in the product.template model and happens when I attempt to put a search domain in the search criteria.

```<code># Gets the source records for the model we intend to migrate in the database class of script.
def get_records(self,model,filter,fields):
    return self.models.execute_kw(self.db, 1, self.password,model, 'search_read',filter,fields)

#method call
source_recs = source_db.get_records(source_model, [[[SYNC_FLAG,'=',
    False]]] , source_fields)
</code>```

The call to the model only works when the filter is [[]].  All other models run through this script without issue but the above script returns [] instead of a list of records as dictionaries.

Any help figuring out why I cannot use a filter/domain on the search function for product.template would be wonderful.

答: The partner that originally installed and implemented Odoo in our system installed a custom module that extended search_read for products and templates.  This extension is what is clearing the list.  If anyone has worked with OSI and coming up with this issue the module is osi_default_product_category.</p>

Body:
I'm having trouble getting a list of records through xmlrpc from the product.template model.

This issue is only present in the product.template model and happens when I attempt to put a search domain in the search criteria.

# Gets the source records for the model we intend to migrate in the database class of script.
def get_records(self,model,filter,fields):
    return self.models.execute_kw(self.db, 1, self.password,model, 'search_read',filter,fields)

#method call
source_recs = source_db.get_records(source_model, [[[SYNC_FLAG,'=',
    False]]] , source_fields)

The call to the model only works when the filter is [[]].  All other models run through this script without issue but the above script returns [] instead of a list of records as dictionaries.

Any help figuring out why I cannot use a filter/domain on the search function for product.template would be wonderful.


问:
How to run commands in parallel in bash?
This has been asked before and there are a lot of answers but my needs are bit more specific:

The processes I need to run are all long-running processes that won't end (normally).

I don't want to just run them on background since I need to see their output.

If any of the processes exits I want the rest to be automatically killed as well.

If I use Ctrl+C or other signal on the main command used to run them, I want to kill all the processes.

For example using & + wait does not satisfy the last point. GNU parallel seems quite complicated and is possibly able to do this but I can't find a good example how to use it.

答:
The processes I need to run are all long-running processes that won't end (normally).

I'd make them system services using your OS's init system. Let a system designed to manage long running processes manage your long running processes. Why spend your energy reinventing all the features a good init system already has such as auto-restart, log management, and inter-service dependencies?

Let's assume your init system is systemd, which is what modern Red Hat and Debian distros use.

I don't want to just run them on background since I need to see their output.

systemd automatically captures stdout and stderr and saves them in its journal. Commands like systemctl status <service> and journalctl provide many ways to view and search the log data. You can filter by severity level, or by time, or many other metadata fields. You can look at output for a single service or combined output from multiple services.

If any of the processes exits I want the rest to be automatically killed as well.

systemd lets you express this with BindsTo=, Requires=, or other similar options. See the systemd.unit man page for details.

If I use Ctrl+C or other signal on the main command used to run them, I want to kill all the processes.

You can stop services with systemctl stop <service>. It'll stop the named service and its dependents.

For a sampling of all the things systemd can do for you peruse its manual:

systemd.unit

systemd.service


问:
How to insert python lists in HTML table?
I have the following output list from python list.

['N3132-a', '172.20.138.18', '192.168.193.15/24', 'N3132-a.td.com ', 'N3K-C3132Q-40GX', 'FOC2116XCFV', 'NXOS: version 7.0(3)I4(6)']

['N56k-a', '10.249.98.11', '192.168.173.16/24', 'N56k-a.td.com ', 'N5K-C56128P', 'FOC2187FGHJ', 'kickstart: version 7.1(4)N1(1)']

['N3164-b', '172.16.48.14', '192.168.130.12/24', 'N3164-b.td.com ', 'N3K-C3164Q-40GE', 'FDO26HJKL2', 'NXOS: version 7.0(3)I4(6)']

['5596-a', '10.250.98.20', '192.168.170.25/24', '5596-a.td.com ', 'N5K-C5596UP', 'FOX2398HGF', 'kickstart: version 7.1(4)N1(1)']

['N3064-B', '172.17.47.20', '192.168.130.25/24', 'N3064-B.td.com ', 'N3K-C3064PQ-10GX', 'FOC193FGHJNM', 'NXOS: version 7.0(3)I4(6)']

I need to loop this data in html and print this in html table .

I have the following html code which works but creating each table instead of one table

Manual input work like this

```<code><HTML>
<head>
<title>Data</title>

</head>
<body>

    <h1><marquee>Welcome To The Page</marquee></h1>
    <h1>Data :</h1>

    <table  border="4" align="center">

     <th style="background-color:yellow !important;"><h2><br>dc</h2></th>
     <th style="background-color:yellow !important;"><h2><br>proxi</h2></th>
     <th style="background-color:yellow!important;"><h2><br>id</h2></th>
     <th style="background-color:yellow !important;"><h2><br>email</h2></th>
     <th style="background-color:yellow!important;"><h2><br>face-1</h2></th>
     <th style="background-color:yellow!important;"><h2><br>face-2</h2></th>
     <th style="background-color:yellow!important;"><h2><br>face-3</h2></th>
     <tr><td>N3132-a</td><td>172.16.139.15</td><td>192.168.195.15/24</td><td>N3132-a.td.com </td><td>N3K-C3132Q-40GX</td><td>FOC2116</td><td>NXOS: version 7.0(3)I4(6)</td></tr><tr><td>N56k-a</td><td>10.249.99.11</td><td>192.168.175.11/24</td><td>N56k-a.td.com </td><td>N5K-C56128P</td><td>FOC2109L</td><td>kickstart: version 7.1(4)N1(1)</td></tr>

</table>
</body>
</HTML>
</code>```

need to loop that input data in python and print that html file instead of manual data in html table.

答:
You can put whole html in python variable and for list output , you can do like this:</p>

```<code>l=['N3132-a', '172.20.138.18', '192.168.193.15/24', 'N3132-a.td.com ', 'N3K-
C3132Q-40GX', 'FOC2116XCFV', 'NXOS: version 7.0(3)I4(6)']
for item in l:
   print('<td>'+item+'</td>')
</code>```

Body:
I have the following output list from python list.

['N3132-a', '172.20.138.18', '192.168.193.15/24', 'N3132-a.td.com ', 'N3K-C3132Q-40GX', 'FOC2116XCFV', 'NXOS: version 7.0(3)I4(6)']

['N56k-a', '10.249.98.11', '192.168.173.16/24', 'N56k-a.td.com ', 'N5K-C56128P', 'FOC2187FGHJ', 'kickstart: version 7.1(4)N1(1)']

['N3164-b', '172.16.48.14', '192.168.130.12/24', 'N3164-b.td.com ', 'N3K-C3164Q-40GE', 'FDO26HJKL2', 'NXOS: version 7.0(3)I4(6)']

['5596-a', '10.250.98.20', '192.168.170.25/24', '5596-a.td.com ', 'N5K-C5596UP', 'FOX2398HGF', 'kickstart: version 7.1(4)N1(1)']

['N3064-B', '172.17.47.20', '192.168.130.25/24', 'N3064-B.td.com ', 'N3K-C3064PQ-10GX', 'FOC193FGHJNM', 'NXOS: version 7.0(3)I4(6)']

I need to loop this data in html and print this in html table .

I have the following html code which works but creating each table instead of one table

Manual input work like this

<title>Data</title>

<marquee>Welcome To The Page</marquee>

Data :

dc

proxi

id

email

face-1

face-2

face-3

N3132-a	172.16.139.15	192.168.195.15/24	N3132-a.td.com 	N3K-C3132Q-40GX	FOC2116	NXOS: version 7.0(3)I4(6)

N56k-a	10.249.99.11	192.168.175.11/24	N56k-a.td.com 	N5K-C56128P	FOC2109L	kickstart: version 7.1(4)N1(1)

need to loop that input data in python and print that html file instead of manual data in html table.

Body:
You can put whole html in python variable and for list output , you can do like this:

l=['N3132-a', '172.20.138.18', '192.168.193.15/24', 'N3132-a.td.com ', 'N3K-
C3132Q-40GX', 'FOC2116XCFV', 'NXOS: version 7.0(3)I4(6)']
for item in l:
   print('<td>'+item+'</td>')


问:
Why isn't a device token being generated?
I'm trying to use react-native-push-notifications, and I've been stuck on this for a good few days now, and I just can't find a way to get it to work.
I know it's been brought up a few times over the years, with varying degrees of success, and I've tried all of the 'solutions', but with no luck.

NB... I haven't tried it on iOS yet, so this is mostly an Android issue.

I have followed the instructions, and searched the trouble shooting, but I cannot get the device token from onRegister.

I can get a local notification to fire on load, and onNotification is being called upon interaction, but no token.

I'm not sure how relevant this is, but I thought I'd have to give permission(?), but even though requestPermissions is true, I never get asked. I did a little digging, and in node_modules\react-native-push-notification\index.js there are two functions requesting permissions.

This is getting called automatically and has the correct senderID

```<code>// Prevent requestPermissions called twice if ios result is pending
Notifications._requestPermissions
</code>```

This only gets called if I explicitly call PushNotifications.requestPermissions() but the senderID is undefined

```<code>// Stock requestPermissions function
Notifications.requestPermissions
</code>```

I've tried lots of different combinations of adding or removing lines from Gradle and the Manifest, but nothing's worked, so I've started again with just the lines from the documentation.
Originally, I had the call to configurePushNotifications() in my logIn function, but read that it should be called from the highest component before loading the JS, so i moved it to index.js, but it didn't make any difference, still no token.

I'm literally at my wits end, and could really do with some help please, there's a Ferrero Rocher Easter egg up for grabs for whoever solves it!

Thanks xxx

Testing on Windows

Android Device, not emulator

react-native-cli: 2.0.1

react-native: 0.59.5

react-native-push-notification": ^3.1.3,

AndroidManifest

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.myApp">

    <uses-permission android:name="android.permission.INTERNET" />
    <!-- < Only if you're using GCM or localNotificationSchedule() > -->
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <permission
            android:name="${applicationId}.permission.C2D_MESSAGE"
            android:protectionLevel="signature" />
    <uses-permission android:name="${applicationId}.permission.C2D_MESSAGE" />
    <!-- < Only if you're using GCM or localNotificationSchedule() > -->

    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

    <application
            android:name=".MainApplication"
            android:label="@string/app_name"
            android:icon="@mipmap/ic_launcher"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:allowBackup="false"
            android:theme="@style/AppTheme">
        <activity
                android:name=".MainActivity"
                android:label="@string/app_name"
                android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
                android:windowSoftInputMode="adjustResize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />

        <meta-data  android:name="com.dieam.reactnativepushnotification.notification_channel_name"
                    android:value="YOUR NOTIFICATION CHANNEL NAME"/>
        <meta-data  android:name="com.dieam.reactnativepushnotification.notification_channel_description"
                    android:value="YOUR NOTIFICATION CHANNEL DESCRIPTION"/>
        <!-- Change the resource name to your App's accent color - or any other color you want -->
        <meta-data  android:name="com.dieam.reactnativepushnotification.notification_color"
                    android:resource="@android:color/white"/>

        <!-- < Only if you're using GCM or localNotificationSchedule() > -->
        <receiver
                android:name="com.google.android.gms.gcm.GcmReceiver"
                android:exported="true"
                android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <category android:name="${applicationId}" />
            </intent-filter>
        </receiver>
        <!-- < Only if you're using GCM or localNotificationSchedule() > -->

        <!-- < Only if you're using GCM or localNotificationSchedule() > -->
        <service
                android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerServiceGcm"
                android:exported="false" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            </intent-filter>
        </service>
        <!-- </ Only if you're using GCM or localNotificationSchedule() > -->

        <!-- < Else > -->
        <service
                android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerService"
                android:exported="false" >
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <!-- </Else> -->
    </application>

</manifest>
</code>```

app\build.gradle

```<code>apply plugin: "com.android.application"

import com.android.build.OutputFile

project.ext.react = [
    entryFile: "index.js"
]

apply from: "../../node_modules/react-native/react.gradle"

def enableSeparateBuildPerCPUArchitecture = false

def enableProguardInReleaseBuilds = false

android {
    compileSdkVersion rootProject.ext.compileSdkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        applicationId "com.sumoshift"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
        }
    }
    buildTypes {
        release {
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            def versionCodes = ["armeabi-v7a":1, "x86":2, "arm64-v8a": 3, "x86_64": 4]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }
        }
    }
}

dependencies {
    implementation ("com.google.android.gms:play-services-gcm:12.0.1") {
        force = true
    }
    implementation ("com.google.firebase:firebase-messaging:12.0.1") {
        force = true
    }
    implementation project(':react-native-push-notification')
    implementation project(':react-native-gesture-handler')
    implementation project(':react-native-vector-icons')
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
    implementation "com.facebook.react:react-native:+"  // From node_modules
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}

apply plugin: 'com.google.gms.google-services'
</code>```

android\build.gradle

```<code>buildscript {
    ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 16
        compileSdkVersion = 28
        targetSdkVersion = 28
        supportLibVersion = "28.0.0"
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.1'
        classpath 'com.google.gms:google-services:4.0.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenLocal()
        google()
        jcenter()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
    }
}
</code>```

notifications.js

```<code>configurePushNotifications(shouldRegisterDeviceDetails) {
        console.log('notifications Notification configurePushNotifications');

        Notification.create({message: 'Test message working'});

        PushNotification.configure({

            // (optional) called when Token is generated (Android & iOS)
            onRegister:  function (registrationToken) {
                console.log('notifications Notification configurePushNotifications onRegister registrationToken: ', registrationToken);

                if (shouldRegisterDeviceDetails) {
                    console.log('registering device');

                    API.editShifterData(8, {
                        device_token: registrationToken.token,
                        phone_type: registrationToken.os
                    })
                        .then((response) => {
                            console.log('notifications Notification configurePushNotifications onRegister response: ', response);
                        })
                        .catch((error) => {
                            console.log('notifications Notification configurePushNotifications onRegister error: ', error);
                        })
                }
            },

            // (required) Called when a remote or local notification is opened or received
            onNotification: function (notification) {
                console.log('notifications Notification configurePushNotifications onNotification notification: ', notification);

                if (notification.userInteraction) {
                    console.log('notifications Notification configurePushNotifications onNotification userInteraction TRUE');

                    Notification.open(notification);
                } else {
                    console.log('notifications Notification configurePushNotifications onNotification userInteraction FALSE');

                    Notification.create(notification);
                }
            },

            // ANDROID ONLY: GCM Sender ID (optional - not required for local notifications, but is need to receive remote push notifications)
            senderID: "xxxxxxxxxxx",

            // IOS ONLY (optional): default: all - Permissions to register.
            permissions: {
                alert: true,
                badge: true,
                sound: true
            },

            // Should the initial notification be popped automatically
            // default: true
            popInitialNotification: true,

            /**
             * (optional) default: true
             * - Specified if permissions (ios) and token (android and ios) will requested or not,
             * - if not, you must call PushNotificationsHandler.requestPermissions() later
             */
            requestPermissions: true,
        });
    }
</code>```

Thanks again xxx

答:
If anyone runs into the same issue, I had to add some extra lines to the Manifest that weren't mentioned in the package's documentation.

```<code><receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationPublisher"/>
<receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationBootEventReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
    </intent-filter>
</receiver>
<service android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationRegistrationService"/>
</code>```

I'll be totally honest though, looking at the issues section of the package on NPM, it seems like there's so much that hasn't been mentioned, and there are lots of different solutions from different people, so while this is what I used to get it to work, it's a bit of a free for all.

Good luck!

Body:
I'm trying to use react-native-push-notifications, and I've been stuck on this for a good few days now, and I just can't find a way to get it to work.
I know it's been brought up a few times over the years, with varying degrees of success, and I've tried all of the 'solutions', but with no luck.

NB... I haven't tried it on iOS yet, so this is mostly an Android issue.

I have followed the instructions, and searched the trouble shooting, but I cannot get the device token from onRegister.

I can get a local notification to fire on load, and onNotification is being called upon interaction, but no token.

I'm not sure how relevant this is, but I thought I'd have to give permission(?), but even though requestPermissions is true, I never get asked. I did a little digging, and in node_modules\react-native-push-notification\index.js there are two functions requesting permissions.

This is getting called automatically and has the correct senderID

// Prevent requestPermissions called twice if ios result is pending
Notifications._requestPermissions

This only gets called if I explicitly call PushNotifications.requestPermissions() but the senderID is undefined

// Stock requestPermissions function
Notifications.requestPermissions

I've tried lots of different combinations of adding or removing lines from Gradle and the Manifest, but nothing's worked, so I've started again with just the lines from the documentation.
Originally, I had the call to configurePushNotifications() in my logIn function, but read that it should be called from the highest component before loading the JS, so i moved it to index.js, but it didn't make any difference, still no token.

I'm literally at my wits end, and could really do with some help please, there's a Ferrero Rocher Easter egg up for grabs for whoever solves it!

Thanks xxx

Testing on Windows

Android Device, not emulator

react-native-cli: 2.0.1

react-native: 0.59.5

react-native-push-notification": ^3.1.3,

AndroidManifest

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.myApp">

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

    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <permission
            android:name="${applicationId}.permission.C2D_MESSAGE"
            android:protectionLevel="signature" />
    <uses-permission android:name="${applicationId}.permission.C2D_MESSAGE" />

    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

    <application
            android:name=".MainApplication"
            android:label="@string/app_name"
            android:icon="@mipmap/ic_launcher"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:allowBackup="false"
            android:theme="@style/AppTheme">
        <activity
                android:name=".MainActivity"
                android:label="@string/app_name"
                android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
                android:windowSoftInputMode="adjustResize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />

        <meta-data  android:name="com.dieam.reactnativepushnotification.notification_channel_name"
                    android:value="YOUR NOTIFICATION CHANNEL NAME"/>
        <meta-data  android:name="com.dieam.reactnativepushnotification.notification_channel_description"
                    android:value="YOUR NOTIFICATION CHANNEL DESCRIPTION"/>

        <meta-data  android:name="com.dieam.reactnativepushnotification.notification_color"
                    android:resource="@android:color/white"/>

        <receiver
                android:name="com.google.android.gms.gcm.GcmReceiver"
                android:exported="true"
                android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <category android:name="${applicationId}" />
            </intent-filter>
        </receiver>

        <service
                android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerServiceGcm"
                android:exported="false" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            </intent-filter>
        </service>

        <service
                android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerService"
                android:exported="false" >
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

    </application>

</manifest>

app\build.gradle

apply plugin: "com.android.application"

import com.android.build.OutputFile

project.ext.react = [
    entryFile: "index.js"
]

apply from: "../../node_modules/react-native/react.gradle"

def enableSeparateBuildPerCPUArchitecture = false

def enableProguardInReleaseBuilds = false

android {
    compileSdkVersion rootProject.ext.compileSdkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        applicationId "com.sumoshift"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
        }
    }
    buildTypes {
        release {
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            def versionCodes = ["armeabi-v7a":1, "x86":2, "arm64-v8a": 3, "x86_64": 4]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }
        }
    }
}

dependencies {
    implementation ("com.google.android.gms:play-services-gcm:12.0.1") {
        force = true
    }
    implementation ("com.google.firebase:firebase-messaging:12.0.1") {
        force = true
    }
    implementation project(':react-native-push-notification')
    implementation project(':react-native-gesture-handler')
    implementation project(':react-native-vector-icons')
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
    implementation "com.facebook.react:react-native:+"  // From node_modules
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}

apply plugin: 'com.google.gms.google-services'

android\build.gradle

buildscript {
    ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 16
        compileSdkVersion = 28
        targetSdkVersion = 28
        supportLibVersion = "28.0.0"
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.1'
        classpath 'com.google.gms:google-services:4.0.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenLocal()
        google()
        jcenter()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
    }
}

notifications.js

configurePushNotifications(shouldRegisterDeviceDetails) {
        console.log('notifications Notification configurePushNotifications');

        Notification.create({message: 'Test message working'});

        PushNotification.configure({

            // (optional) called when Token is generated (Android & iOS)
            onRegister:  function (registrationToken) {
                console.log('notifications Notification configurePushNotifications onRegister registrationToken: ', registrationToken);

                if (shouldRegisterDeviceDetails) {
                    console.log('registering device');

                    API.editShifterData(8, {
                        device_token: registrationToken.token,
                        phone_type: registrationToken.os
                    })
                        .then((response) => {
                            console.log('notifications Notification configurePushNotifications onRegister response: ', response);
                        })
                        .catch((error) => {
                            console.log('notifications Notification configurePushNotifications onRegister error: ', error);
                        })
                }
            },

            // (required) Called when a remote or local notification is opened or received
            onNotification: function (notification) {
                console.log('notifications Notification configurePushNotifications onNotification notification: ', notification);

                if (notification.userInteraction) {
                    console.log('notifications Notification configurePushNotifications onNotification userInteraction TRUE');

                    Notification.open(notification);
                } else {
                    console.log('notifications Notification configurePushNotifications onNotification userInteraction FALSE');

                    Notification.create(notification);
                }
            },

            // ANDROID ONLY: GCM Sender ID (optional - not required for local notifications, but is need to receive remote push notifications)
            senderID: "xxxxxxxxxxx",

            // IOS ONLY (optional): default: all - Permissions to register.
            permissions: {
                alert: true,
                badge: true,
                sound: true
            },

            // Should the initial notification be popped automatically
            // default: true
            popInitialNotification: true,

            /**
             * (optional) default: true
             * - Specified if permissions (ios) and token (android and ios) will requested or not,
             * - if not, you must call PushNotificationsHandler.requestPermissions() later
             */
            requestPermissions: true,
        });
    }

Thanks again xxx

Body:
If anyone runs into the same issue, I had to add some extra lines to the Manifest that weren't mentioned in the package's documentation.

<receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationPublisher"/>
<receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationBootEventReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
    </intent-filter>
</receiver>
<service android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationRegistrationService"/>

I'll be totally honest though, looking at the issues section of the package on NPM, it seems like there's so much that hasn't been mentioned, and there are lots of different solutions from different people, so while this is what I used to get it to work, it's a bit of a free for all.

Good luck!


问:
Find the name(s) of students who have secured maximum marks in each subject
Write a query to display subject names and student name who have secured maximum marks in each subject ordered by subject_name in ascending order. The solution has to be implemented in subquery.

I have used below query :

```<code> select subject_name, student_name
 from subject s
 inner join mark m
 on s.subject_id=m.subject_id
 inner join student s1
  on m.student_id=s1.student_id
  where student_id in  (select student_id
                          from mark
                         having max(value)
                          group by s.subject_id)
  order by s.subject_name;
</code>```

But this code gives an error at the 10th line of invalid relational operator

PLEASE HELP!!

答:
Try the following

```<code>SELECT
    SB.SUBJECT_NAME,
    S.STUDENT_NAME
FROM
    STUDENT S,
    SUBJECT SB,
    (
        SELECT
            STUDENT_ID,
            SUBJECT_ID,
            MARKS
        FROM
            MARKS
        WHERE
            ( SUBJECT_ID,
              MARKS ) IN (
                SELECT
                    M.SUBJECT_ID,
                    MAX(M.MARKS)
                FROM
                    MARKS M
                GROUP BY
                    M.SUBJECT_ID
            )
    ) MM
WHERE
    S.STUDENT_ID = MM.STUDENT_ID
    AND SB.SUBJECT_ID = MM.SUBJECT_ID;
</code>```

Demo

Thanks

Body:
Write a query to display subject names and student name who have secured maximum marks in each subject ordered by subject_name in ascending order. The solution has to be implemented in subquery.

I have used below query :

 select subject_name, student_name
 from subject s
 inner join mark m
 on s.subject_id=m.subject_id
 inner join student s1
  on m.student_id=s1.student_id
  where student_id in  (select student_id
                          from mark
                         having max(value)
                          group by s.subject_id)
  order by s.subject_name;

But this code gives an error at the 10th line of invalid relational operator

PLEASE HELP!!

Body:
Try the following

SELECT
    SB.SUBJECT_NAME,
    S.STUDENT_NAME
FROM
    STUDENT S,
    SUBJECT SB,
    (
        SELECT
            STUDENT_ID,
            SUBJECT_ID,
            MARKS
        FROM
            MARKS
        WHERE
            ( SUBJECT_ID,
              MARKS ) IN (
                SELECT
                    M.SUBJECT_ID,
                    MAX(M.MARKS)
                FROM
                    MARKS M
                GROUP BY
                    M.SUBJECT_ID
            )
    ) MM
WHERE
    S.STUDENT_ID = MM.STUDENT_ID
    AND SB.SUBJECT_ID = MM.SUBJECT_ID;

Demo

Thanks


问:
My CSS Changes are not affecting my web pages in any way at all
I am having some issues with using Bootstrap for the first time. For some reason no matter what changes I make to my custom css it does not affect the bootstrap css or the regular html of the layout. I am currently trying to build my first website in visual studio and have been advised to work with bootstrap however I cannot seem to get it to work the way I want it to. I have successfully created web elements that I want without the use of bootstrap however when I try to use bootstrap it just does not want to display any of my custom css no matter what I do.

As I stated above, the first thing I tried was editing the bootstrap css directly, which had absolutely no effect on the layout of my webpages. After this, I discovered it was a good idea to create a seperate main.css file and then link it in to bootstrap file, with any changes being made to the main.css file should change the bootstrap css without having to mess up the bootstrap file. However, using this method none of the changes alter the way the webpages are displayed in any way. After this, I decided to follow this tutorial https://websitesetup.org/bootstrap-tutorial-for-beginners/ step by step, even though it is a notepad++ tutorial and not a visual studio tutorial. Even following this tutorial step by step none of the changes made to the css are displayed on the webpage.

When I simply add the html I want to the layout page without linking the bootstrap or main.css to the layout page the features work as intended, but I cannot customize some things with html so I need to get it working with css.

I have done a few google searches for solutions to this issue and tried several, such as moving code from the body of the layout page to the footer, ensuring the file directory for the .css files is correct, including capital letters, but I cannot seem to find where the issue is.

This is how I linked my layout page to the main.css file which contains the css for altering the nav bar of my webpages:

```<code><head>

    <link rel="stylesheet" type="text/css" href="Main.css">
  this is the link to the Main.css file with my custom .css that I used in the layout view in visual studio

    <link rel="stylesheet" href="BSProject/css/bootstrap.min.css">
  This is the link to the bootstrap file I used when following the above tutorial and added this to the head of the index.html file

    <title>Home</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
</code>```

This is the stuff I put in my main.css file, while also finding the .nav classes in the bootstrap.css and trying to put this information in the bootstrap file also.

```<code>/* The navigation bar */
.navbar {
    overflow: hidden;
    background-color: #333;
    position: fixed; /* Set the navbar to fixed position */
    top: 0; /* Position the navbar at the top of the page */
    width: 100%; /* Full width */
}

    /* Links inside the navbar */
    .navbar a {
        float: left;
        display: block;
        color: #f2f2f2;
        text-align: center;
        padding: 14px 16px;
        text-decoration: none;
    }

        /* Change background on mouse-over */
        .navbar a:hover {
            background: #ddd;
            color: black;
        }

        /* Main content */
        .main {
            margin-top: 30px; /* Add a top margin to avoid content overlay */
        }
</code>```

I am trying to change the colour of the nav bar, the colour of the text, the colour of the text on scroll over, the colour of the text on the nav bar of the page that is currently being viewed, the text type/size/position and I want the nav bar to be fixed at the top of the page so that as you scroll down the page you can still see the nav bar at the top of the window. And I want the nav bar to scale with the size of the window for mobile users, a feature that is included in bootstrap. I understand everything I mentioned is not present in the above css, this is because I wanted to test it was functional before I began typing out all the css I need.

I can already do all of this without using bootstrap but for this project I am required to use it and I just can't seem to display anything other than the default bootstrap nav bar no matter what I change in the css.

答:
First of all move your style Link after Viewport and also move your custom css file Main.css after Bootstrap.min.css. Try this I hope it'll resolve your issue. Thanks

```<code><head>
    <title>Home</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- StyleSheet -->
    <link rel="stylesheet" href="BSProject/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="Main.css">
</head>
</code>```

Body:
I am having some issues with using Bootstrap for the first time. For some reason no matter what changes I make to my custom css it does not affect the bootstrap css or the regular html of the layout. I am currently trying to build my first website in visual studio and have been advised to work with bootstrap however I cannot seem to get it to work the way I want it to. I have successfully created web elements that I want without the use of bootstrap however when I try to use bootstrap it just does not want to display any of my custom css no matter what I do.

As I stated above, the first thing I tried was editing the bootstrap css directly, which had absolutely no effect on the layout of my webpages. After this, I discovered it was a good idea to create a seperate main.css file and then link it in to bootstrap file, with any changes being made to the main.css file should change the bootstrap css without having to mess up the bootstrap file. However, using this method none of the changes alter the way the webpages are displayed in any way. After this, I decided to follow this tutorial https://websitesetup.org/bootstrap-tutorial-for-beginners/ step by step, even though it is a notepad++ tutorial and not a visual studio tutorial. Even following this tutorial step by step none of the changes made to the css are displayed on the webpage.

When I simply add the html I want to the layout page without linking the bootstrap or main.css to the layout page the features work as intended, but I cannot customize some things with html so I need to get it working with css.

I have done a few google searches for solutions to this issue and tried several, such as moving code from the body of the layout page to the footer, ensuring the file directory for the .css files is correct, including capital letters, but I cannot seem to find where the issue is.

This is how I linked my layout page to the main.css file which contains the css for altering the nav bar of my webpages:

    <link rel="stylesheet" type="text/css" href="Main.css">
  this is the link to the Main.css file with my custom .css that I used in the layout view in visual studio

    <link rel="stylesheet" href="BSProject/css/bootstrap.min.css">
  This is the link to the bootstrap file I used when following the above tutorial and added this to the head of the index.html file

    <title>Home</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

This is the stuff I put in my main.css file, while also finding the .nav classes in the bootstrap.css and trying to put this information in the bootstrap file also.

/* The navigation bar */
.navbar {
    overflow: hidden;
    background-color: #333;
    position: fixed; /* Set the navbar to fixed position */
    top: 0; /* Position the navbar at the top of the page */
    width: 100%; /* Full width */
}

    /* Links inside the navbar */
    .navbar a {
        float: left;
        display: block;
        color: #f2f2f2;
        text-align: center;
        padding: 14px 16px;
        text-decoration: none;
    }

        /* Change background on mouse-over */
        .navbar a:hover {
            background: #ddd;
            color: black;
        }

        /* Main content */
        .main {
            margin-top: 30px; /* Add a top margin to avoid content overlay */
        }

I am trying to change the colour of the nav bar, the colour of the text, the colour of the text on scroll over, the colour of the text on the nav bar of the page that is currently being viewed, the text type/size/position and I want the nav bar to be fixed at the top of the page so that as you scroll down the page you can still see the nav bar at the top of the window. And I want the nav bar to scale with the size of the window for mobile users, a feature that is included in bootstrap. I understand everything I mentioned is not present in the above css, this is because I wanted to test it was functional before I began typing out all the css I need.

I can already do all of this without using bootstrap but for this project I am required to use it and I just can't seem to display anything other than the default bootstrap nav bar no matter what I change in the css.

Body:
First of all move your style Link after Viewport and also move your custom css file Main.css after Bootstrap.min.css. Try this I hope it'll resolve your issue. Thanks

<head>
    <title>Home</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- StyleSheet -->
    <link rel="stylesheet" href="BSProject/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="Main.css">
</head>


问:
how to print ipdata language name using javascript?
Hi guys I need to know how to print the language name in ipdata
I have this code at the bottom working well and the results appear correct but when I get the name of the language the results show the language name = undefined;

results

```<code>184.23.215.250
United States
<img src="https://ipdata.co/flags/us.png">
US
North America
Sonic Telecom LLC
undefined
</code>```

my js vars is

```<code>var country_name = response.country_name;
var flag = response.flag;
var country_code = response.country_code;
var continent_name = response.continent_name;
var organisation = response.organisation;
var lang = response.languages.name;
</code>```

you can try it from http://tiger222.atwebpages.com/set.php

You will find the data correct but, how do I get the language name correctly ?

var lang = response.languages->name; this is not working

var lang = response.languages.name; and this is not working

答:
This is array</p>

```<code>var lang = response.languages[0].name;
</code>```

Body:
Hi guys I need to know how to print the language name in ipdata
I have this code at the bottom working well and the results appear correct but when I get the name of the language the results show the language name = undefined;

results

184.23.215.250
United States

US
North America
Sonic Telecom LLC
undefined

my js vars is

var country_name = response.country_name;
var flag = response.flag;
var country_code = response.country_code;
var continent_name = response.continent_name;
var organisation = response.organisation;
var lang = response.languages.name;

you can try it from http://tiger222.atwebpages.com/set.php

You will find the data correct but, how do I get the language name correctly ?

var lang = response.languages->name; this is not working

var lang = response.languages.name; and this is not working

Body:
This is array

var lang = response.languages[0].name;


问:
Display nested JSON data using Javascript
Afternoon all,

I'm trying to parse data from a nested json object.

For example: member.accuracy

Currently, it's returning the result undefined.

My code:

JSON (places.json):

```<code>{
"request_time": "2019-05-30T13:48:39+01:00",
"source": "Network Rail",
"acknowledgements": "Contains information of Network Rail Infrastructure Limited. License http://www.networkrail.co.uk/data-feeds/terms-and-conditions/",
"member": [
{
"type": "train_station",
"name": "London Euston",
"latitude": 51.528135,
"longitude": -0.133924,
"accuracy": 100,
"station_code": "EUS",
"tiploc_code": "EUSTON"
}
]
}
</code>```

HTML:

```<code>   <html>
    <head>
    <meta content="text/html; charset=utf-8">
    <title>AJAX JSON by Javatpoint</title>
    <script type="application/javascript">
    function load()
    {
       var url = "http://myurl.places.json?";
       var request;

       if(window.XMLHttpRequest){
        request=new XMLHttpRequest();//for Chrome, mozilla etc
       }
       else if(window.ActiveXObject){
        request=new ActiveXObject("Microsoft.XMLHTTP");//for IE only
       }
       request.onreadystatechange  = function(){
          if (request.readyState == 4  )
          {
            var jsonObj = JSON.parse(request.responseText);//JSON.parse() returns JSON object
            document.getElementById("date").innerHTML =  jsonObj.request_time;
            document.getElementById("time").innerHTML = jsonObj.member.accuracy;
          }
       }
       request.open("GET", url, true);
       request.send();
    }
    </script>
    </head>
    <body onload="load()">

    Date: <span id="date"></span><br/>
    Time: <span id="time"></span><br/>

    </body>
    </html>
</code>```

Any help would be much appreciated!

Thanks,

Brad

答:
As you can see in the json file, the member property holds an array, containing one object. To get accuracy, you must access it with an index:

var jsonObj = {
  "member": [{
    "type": "train_station",
    "name": "London Euston",
    "latitude": 51.528135,
    "longitude": -0.133924,
    "accuracy": 100,
    "station_code": "EUS",
    "tiploc_code": "EUSTON"
  }]
}
console.log(jsonObj.member[0].accuracy)```

Be aware that if you're fetching this data from some sort of API, there may be more than one object present in this array in future fetches, and the first element (index 0) may not be the one you're looking for.

Body:
Afternoon all,

I'm trying to parse data from a nested json object.

For example: member.accuracy

Currently, it's returning the result undefined.

My code:

JSON (places.json):

{
"request_time": "2019-05-30T13:48:39+01:00",
"source": "Network Rail",
"acknowledgements": "Contains information of Network Rail Infrastructure Limited. License http://www.networkrail.co.uk/data-feeds/terms-and-conditions/",
"member": [
{
"type": "train_station",
"name": "London Euston",
"latitude": 51.528135,
"longitude": -0.133924,
"accuracy": 100,
"station_code": "EUS",
"tiploc_code": "EUSTON"
}
]
}

HTML:

    <meta content="text/html; charset=utf-8">
    <title>AJAX JSON by Javatpoint</title>

    Date:

    Time:

Any help would be much appreciated!

Thanks,

Brad

Body:
As you can see in the json file, the member property holds an array, containing one object. To get accuracy, you must access it with an index:

var jsonObj = {
  "member": [{
    "type": "train_station",
    "name": "London Euston",
    "latitude": 51.528135,
    "longitude": -0.133924,
    "accuracy": 100,
    "station_code": "EUS",
    "tiploc_code": "EUSTON"
  }]
}
console.log(jsonObj.member[0].accuracy)

Be aware that if you're fetching this data from some sort of API, there may be more than one object present in this array in future fetches, and the first element (index 0) may not be the one you're looking for.


答:
In the source data, languages is an array, e.g.

```<code>"languages": [
    {
        "name": "English",
        "native": "English"
    }
],
</code>```

Therefore it can potentially contain multiple entries.

Assuming you just want the first language in the list, then you can address the first index of the array directly, like this:

```<code>var lang = response.languages[0].name;
</code>```

P.S. -> is not valid syntax in JavaScript. You were perhaps thinking of PHP syntax there.

Title: how to print ipdata language name using javascript?

Body:
In the source data, languages is an array, e.g.

"languages": [
    {
        "name": "English",
        "native": "English"
    }
],

Therefore it can potentially contain multiple entries.

Assuming you just want the first language in the list, then you can address the first index of the array directly, like this:

var lang = response.languages[0].name;

P.S. -> is not valid syntax in JavaScript. You were perhaps thinking of PHP syntax there.


问:
How to create a conditional string that's based on two variables without a bunch of if elses (JavaScript)
I am trying to create a custom string to be shown to the user, which is based on two variables.

Here is the example that I am trying to build:

let url1;
let url2;
if (containsData1) {
  url1 = "http://test";
}

if (containsData2) {
  url2 = "http://test2";
}

let finalString = '';
if (url1 && url2) {
  finalString = 'The url 1 is ' + url1 + ' and url 2 is ' + url2;
} else if (!url1 && url2) {
  finalString = 'There isnt data for url1. Url2 is ' + url2;
} else if (url1 && !url2) {
  finalString = 'The url 1 is ' + url1 + '. There isnt data for url2';
} else if (!url1 && !url2) {
  finalString = 'There isnt data for url1. There isnt data for url2';
}
```

However I would like to this in a proper way, without using this bunch of if elses, any suggestions on how to accomplish this?

Thanks.

答:
I'm sure we could get even more precise with the ternary statements: </p>

```<code>let url1 = containsData1;
let url2 = containsData2;

let finalString = url1 ? `The url 1 is ${url1}` : 'There is no data for url 1';

if (url1 && url2) {finalString += ` and url 2 is ${url2}.`}
if (!url2) {finalString += '. There is no data for url2.'}
</code>```

Body:
I am trying to create a custom string to be shown to the user, which is based on two variables.

Here is the example that I am trying to build:

let url1;
let url2;
if (containsData1) {
  url1 = "http://test";
}

if (containsData2) {
  url2 = "http://test2";
}

let finalString = '';
if (url1 && url2) {
  finalString = 'The url 1 is ' + url1 + ' and url 2 is ' + url2;
} else if (!url1 && url2) {
  finalString = 'There isnt data for url1. Url2 is ' + url2;
} else if (url1 && !url2) {
  finalString = 'The url 1 is ' + url1 + '. There isnt data for url2';
} else if (!url1 && !url2) {
  finalString = 'There isnt data for url1. There isnt data for url2';
}

However I would like to this in a proper way, without using this bunch of if elses, any suggestions on how to accomplish this?

Thanks.

Body:
I'm sure we could get even more precise with the ternary statements:

let url1 = containsData1;
let url2 = containsData2;

let finalString = url1 ? `The url 1 is ${url1}` : 'There is no data for url 1';

if (url1 && url2) {finalString += ` and url 2 is ${url2}.`}
if (!url2) {finalString += '. There is no data for url2.'}


问:
How do you convert a byte array to a hexadecimal string, and vice versa?
How can you convert a byte array to a hexadecimal string and vice versa?</p>

答:
I came up with a different code that is tolerant to extra characters (whitespace, dash...). It is mostly inspired from some acceptably-fast answers here. It allows parsing of the following "file"

```<code>00-aa-84-fb
12 32 FF CD
12 00
12_32_FF_CD
1200d5e68a
</code>```

```<code>/// <summary>Reads a hex string into bytes</summary>
public static IEnumerable<byte> HexadecimalStringToBytes(string hex) {
    if (hex == null)
        throw new ArgumentNullException(nameof(hex));

    char c, c1 = default(char);
    bool hasc1 = false;
    unchecked   {
        for (int i = 0; i < hex.Length; i++) {
            c = hex[i];
            bool isValid = 'A' <= c && c <= 'f' || 'a' <= c && c <= 'f' || '0' <= c && c <= '9';
            if (!hasc1) {
                if (isValid) {
                    hasc1 = true;
                }
            } else {
                hasc1 = false;
                if (isValid) {
                    yield return (byte)((GetHexVal(c1) << 4) + GetHexVal(c));
                }
            }

            c1 = c;
        }
    }
}

/// <summary>Reads a hex string into a byte array</summary>
public static byte[] HexadecimalStringToByteArray(string hex)
{
    if (hex == null)
        throw new ArgumentNullException(nameof(hex));

    var bytes = new List<byte>(hex.Length / 2);
    foreach (var item in HexadecimalStringToBytes(hex)) {
        bytes.Add(item);
    }

    return bytes.ToArray();
}

private static byte GetHexVal(char val)
{
    return (byte)(val - (val < 0x3A ? 0x30 : val < 0x5B ? 0x37 : 0x57));
    //                   ^^^^^^^^^^^^^^^^^   ^^^^^^^^^^^^^^^^^   ^^^^
    //                       digits 0-9       upper char A-Z     a-z
}
</code>```

Please refer to full code when copying. Unit tests included.

Some might say it is too much tolerant to extra chars. So don't rely on this code to perform validation (or change it).

OwnerDisplayName: alextansc

LastEditorDisplayName: alextansc

Body:
I came up with a different code that is tolerant to extra characters (whitespace, dash...). It is mostly inspired from some acceptably-fast answers here. It allows parsing of the following "file"

00-aa-84-fb
12 32 FF CD
12 00
12_32_FF_CD
1200d5e68a

/// <summary>Reads a hex string into bytes</summary>
public static IEnumerable<byte> HexadecimalStringToBytes(string hex) {
    if (hex == null)
        throw new ArgumentNullException(nameof(hex));

    char c, c1 = default(char);
    bool hasc1 = false;
    unchecked   {
        for (int i = 0; i < hex.Length; i++) {
            c = hex[i];
            bool isValid = 'A' <= c && c <= 'f' || 'a' <= c && c <= 'f' || '0' <= c && c <= '9';
            if (!hasc1) {
                if (isValid) {
                    hasc1 = true;
                }
            } else {
                hasc1 = false;
                if (isValid) {
                    yield return (byte)((GetHexVal(c1) << 4) + GetHexVal(c));
                }
            }

            c1 = c;
        }
    }
}

/// <summary>Reads a hex string into a byte array</summary>
public static byte[] HexadecimalStringToByteArray(string hex)
{
    if (hex == null)
        throw new ArgumentNullException(nameof(hex));

    var bytes = new List<byte>(hex.Length / 2);
    foreach (var item in HexadecimalStringToBytes(hex)) {
        bytes.Add(item);
    }

    return bytes.ToArray();
}

private static byte GetHexVal(char val)
{
    return (byte)(val - (val < 0x3A ? 0x30 : val < 0x5B ? 0x37 : 0x57));
    //                   ^^^^^^^^^^^^^^^^^   ^^^^^^^^^^^^^^^^^   ^^^^
    //                       digits 0-9       upper char A-Z     a-z
}

Please refer to full code when copying. Unit tests included.

Some might say it is too much tolerant to extra chars. So don't rely on this code to perform validation (or change it).


答:
Languages is an array so you would have to map on its elements and get name out of it.

```<code>"languages": [
    {
        "name": "English",
        "native": "English"
    }
],
</code>```

It may break if there are no languages in the array so you can do defensive code like below:

```<code>var lang = (response.languages && response.languages.length && response.languages[0].name) || '';
</code>```

const response = {
    "ip": "12.00.00.01",
    "is_eu": false,
    "city": "Any City",
    "region": "Pennsylvania",
    "region_code": "PA",
    "country_name": "United States",
    "country_code": "US",
    "continent_name": "North America",
    "continent_code": "NA",
    "latitude": 49.9776,
    "longitude": -95.3099,
    "asn": "AS7018",
    "organisation": "AT&T Services, Inc.",
    "postal": "18083",
    "calling_code": "1",
    "flag": "https://ipdata.co/flags/us.png",
    "emoji_flag": "\ud83c\uddfa\ud83c\uddf8",
    "emoji_unicode": "U+1F1FA U+1F1F8",
    "carrier": {
        "name": "AT&T",
        "mcc": "310",
        "mnc": "016"
    },
    "languages": [
        {
            "name": "English",
            "native": "English"
        }
    ],
    "currency": {
        "name": "US Dollar",
        "code": "USD",
        "symbol": "$",
        "native": "$",
        "plural": "US dollars"
    },
    "time_zone": {
        "name": "America/New_York",
        "abbr": "EDT",
        "offset": "-0400",
        "is_dst": true,
        "current_time": "2019-05-30T08:52:43.569643-04:00"
    },
    "threat": {
        "is_tor": false,
        "is_proxy": false,
        "is_anonymous": false,
        "is_known_attacker": false,
        "is_known_abuser": false,
        "is_threat": false,
        "is_bogon": false
    },
    "count": "1501"
};
var country_name = response.country_name;
var flag = response.flag;
var country_code = response.country_code;
var continent_name = response.continent_name;
var organisation = response.organisation;
var lang = response.languages[0].name;

console.log(lang);```

Body:
Languages is an array so you would have to map on its elements and get name out of it.

"languages": [
    {
        "name": "English",
        "native": "English"
    }
],

It may break if there are no languages in the array so you can do defensive code like below:

var lang = (response.languages && response.languages.length && response.languages[0].name) || '';

const response = {
    "ip": "12.00.00.01",
    "is_eu": false,
    "city": "Any City",
    "region": "Pennsylvania",
    "region_code": "PA",
    "country_name": "United States",
    "country_code": "US",
    "continent_name": "North America",
    "continent_code": "NA",
    "latitude": 49.9776,
    "longitude": -95.3099,
    "asn": "AS7018",
    "organisation": "AT&T Services, Inc.",
    "postal": "18083",
    "calling_code": "1",
    "flag": "https://ipdata.co/flags/us.png",
    "emoji_flag": "\ud83c\uddfa\ud83c\uddf8",
    "emoji_unicode": "U+1F1FA U+1F1F8",
    "carrier": {
        "name": "AT&T",
        "mcc": "310",
        "mnc": "016"
    },
    "languages": [
        {
            "name": "English",
            "native": "English"
        }
    ],
    "currency": {
        "name": "US Dollar",
        "code": "USD",
        "symbol": "$",
        "native": "$",
        "plural": "US dollars"
    },
    "time_zone": {
        "name": "America/New_York",
        "abbr": "EDT",
        "offset": "-0400",
        "is_dst": true,
        "current_time": "2019-05-30T08:52:43.569643-04:00"
    },
    "threat": {
        "is_tor": false,
        "is_proxy": false,
        "is_anonymous": false,
        "is_known_attacker": false,
        "is_known_abuser": false,
        "is_threat": false,
        "is_bogon": false
    },
    "count": "1501"
};
var country_name = response.country_name;
var flag = response.flag;
var country_code = response.country_code;
var continent_name = response.continent_name;
var organisation = response.organisation;
var lang = response.languages[0].name;

console.log(lang);


问:
The application at <path> does not exist or is not accessible using Appium
I'm learning appium using eclipse and got stuck on launching my emulator. I tried different things such as moving the file around in the folder structure but I keep getting file does not exist or is not accessible I tried searching for the answer but nothing is helping.

```<code>package myAppiumTutorial;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;

import org.openqa.selenium.remote.DesiredCapabilities;

import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import io.appium.java_client.remote.MobileCapabilityType;

public class Base {

    public static void main(String[] args) throws MalformedURLException {
        // TODO Auto-generated method stub
        File f = new File("scr");
        File fs = new File(f,"ApiDemos-debug.apk");
        DesiredCapabilities cap = new DesiredCapabilities();
        cap.setCapability(MobileCapabilityType.DEVICE_NAME, "MyFirstEmu");
        cap.setCapability(MobileCapabilityType.APP, fs.getAbsolutePath());
        AndroidDriver<AndroidElement> driver = new AndroidDriver<>(new URL("http://127.0.0.1:4723/wd/hub"),cap);
</code>```

Logs from appium

```<code>[Appium] Setting automation to 'UiAutomator1'.
[Appium] Appium v1.13.0 creating new AndroidDriver (v4.15.1) session
[Appium] Capabilities:
[Appium]   platformName: android
[Appium]   app: C:\Users\Zamranj\eclipse-workspaceNew\AppiumIntro\scr\ApiDemos-debug.apk
[Appium]   deviceName: MyFirstEmu
[debug] [BaseDriver] W3C capabilities {"alwaysMatch":{"platformNa... and MJSONWP desired capabilities {"app":"C:\\Users\\Zamranj\... were provided
[debug] [BaseDriver] Creating session with W3C capabilities: {"alwaysMatch":{"platformNa...
[BaseDriver] Session created with session id: 638fc0a9-1aa0-4b56-ba69-3c854b8e1816
[ADB] Found 1 'build-tools' folders under 'C:\Users\Zamranj\AppData\Local\Android\Sdk' (newest first):
[ADB]     C:/Users/Zamranj/AppData/Local/Android/Sdk/build-tools/28.0.3
[ADB] Using 'adb.exe' from 'C:\Users\Zamranj\AppData\Local\Android\Sdk\platform-tools\adb.exe'
[AndroidDriver] Retrieving device list
[debug] [ADB] Trying to find a connected android device
[debug] [ADB] Getting connected devices...
[debug] [ADB] 1 device(s) connected
[AndroidDriver] Using device: emulator-5554
[ADB] Using 'adb.exe' from 'C:\Users\Zamranj\AppData\Local\Android\Sdk\platform-tools\adb.exe'
[debug] [ADB] Setting device id to emulator-5554
[debug] [ADB] Running 'C:\Users\Zamranj\AppData\Local\Android\Sdk\platform-tools\adb.exe -P 5037 -s emulator-5554 shell getprop ro.build.version.sdk'
[debug] [ADB] Current device property 'ro.build.version.sdk': 25
[debug] [ADB] Device API level: 25
[AndroidDriver] Consider setting 'automationName' capability to 'uiautomator2' on Android >= 6, since UIAutomator framework is not maintained anymore by the OS vendor.
[debug] [AndroidDriver] Shutting down Android driver
[debug] [AndroidDriver] Called deleteSession but bootstrap wasn't active
[debug] [ADB] Running 'C:\Users\Zamranj\AppData\Local\Android\Sdk\platform-tools\adb.exe -P 5037 -s emulator-5554 shell am force-stop io.appium.unlock'
[debug] [AndroidDriver] Not cleaning generated files. Add `clearSystemFiles` capability if wanted.
[debug] [BaseDriver] Event 'newSessionStarted' logged at 1559218980295 (07:23:00 GMT-0500 (Central Daylight Time))
[debug] [W3C] Encountered internal error running command: Error: The application at 'C:\Users\Zamranj\eclipse-workspaceNew\AppiumIntro\scr\ApiDemos-debug.apk' does not exist or is not accessible
[debug] [W3C]     at APPLICATIONS_CACHE_GUARD.acquire (C:\Users\Zamranj\AppData\Roaming\npm\node_modules\appium\node_modules\appium-base-driver\lib\basedriver\helpers.js:159:13)
[HTTP] <-- POST /wd/hub/session 500 2956 ms - 835
[HTTP]
</code>```

Location of my apk

enter image description here

答:
I believe your problem lies with the way you're trying to load your file in.

Try the following:

File f = new File(classLoader.getResource("ApiDemos-debug.apk").getFile());

Please also take a look at the following:

Class.getResource(String)

Class.getResourceAsStream(String)

Body:
I'm learning appium using eclipse and got stuck on launching my emulator. I tried different things such as moving the file around in the folder structure but I keep getting file does not exist or is not accessible I tried searching for the answer but nothing is helping.

package myAppiumTutorial;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;

import org.openqa.selenium.remote.DesiredCapabilities;

import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import io.appium.java_client.remote.MobileCapabilityType;

public class Base {

    public static void main(String[] args) throws MalformedURLException {
        // TODO Auto-generated method stub
        File f = new File("scr");
        File fs = new File(f,"ApiDemos-debug.apk");
        DesiredCapabilities cap = new DesiredCapabilities();
        cap.setCapability(MobileCapabilityType.DEVICE_NAME, "MyFirstEmu");
        cap.setCapability(MobileCapabilityType.APP, fs.getAbsolutePath());
        AndroidDriver<AndroidElement> driver = new AndroidDriver<>(new URL("http://127.0.0.1:4723/wd/hub"),cap);

Logs from appium

[Appium] Setting automation to 'UiAutomator1'.
[Appium] Appium v1.13.0 creating new AndroidDriver (v4.15.1) session
[Appium] Capabilities:
[Appium]   platformName: android
[Appium]   app: C:\Users\Zamranj\eclipse-workspaceNew\AppiumIntro\scr\ApiDemos-debug.apk
[Appium]   deviceName: MyFirstEmu
[debug] [BaseDriver] W3C capabilities {"alwaysMatch":{"platformNa... and MJSONWP desired capabilities {"app":"C:\\Users\\Zamranj\... were provided
[debug] [BaseDriver] Creating session with W3C capabilities: {"alwaysMatch":{"platformNa...
[BaseDriver] Session created with session id: 638fc0a9-1aa0-4b56-ba69-3c854b8e1816
[ADB] Found 1 'build-tools' folders under 'C:\Users\Zamranj\AppData\Local\Android\Sdk' (newest first):
[ADB]     C:/Users/Zamranj/AppData/Local/Android/Sdk/build-tools/28.0.3
[ADB] Using 'adb.exe' from 'C:\Users\Zamranj\AppData\Local\Android\Sdk\platform-tools\adb.exe'
[AndroidDriver] Retrieving device list
[debug] [ADB] Trying to find a connected android device
[debug] [ADB] Getting connected devices...
[debug] [ADB] 1 device(s) connected
[AndroidDriver] Using device: emulator-5554
[ADB] Using 'adb.exe' from 'C:\Users\Zamranj\AppData\Local\Android\Sdk\platform-tools\adb.exe'
[debug] [ADB] Setting device id to emulator-5554
[debug] [ADB] Running 'C:\Users\Zamranj\AppData\Local\Android\Sdk\platform-tools\adb.exe -P 5037 -s emulator-5554 shell getprop ro.build.version.sdk'
[debug] [ADB] Current device property 'ro.build.version.sdk': 25
[debug] [ADB] Device API level: 25
[AndroidDriver] Consider setting 'automationName' capability to 'uiautomator2' on Android >= 6, since UIAutomator framework is not maintained anymore by the OS vendor.
[debug] [AndroidDriver] Shutting down Android driver
[debug] [AndroidDriver] Called deleteSession but bootstrap wasn't active
[debug] [ADB] Running 'C:\Users\Zamranj\AppData\Local\Android\Sdk\platform-tools\adb.exe -P 5037 -s emulator-5554 shell am force-stop io.appium.unlock'
[debug] [AndroidDriver] Not cleaning generated files. Add `clearSystemFiles` capability if wanted.
[debug] [BaseDriver] Event 'newSessionStarted' logged at 1559218980295 (07:23:00 GMT-0500 (Central Daylight Time))
[debug] [W3C] Encountered internal error running command: Error: The application at 'C:\Users\Zamranj\eclipse-workspaceNew\AppiumIntro\scr\ApiDemos-debug.apk' does not exist or is not accessible
[debug] [W3C]     at APPLICATIONS_CACHE_GUARD.acquire (C:\Users\Zamranj\AppData\Roaming\npm\node_modules\appium\node_modules\appium-base-driver\lib\basedriver\helpers.js:159:13)
[HTTP] <-- POST /wd/hub/session 500 2956 ms - 835
[HTTP]

Location of my apk

enter image description here


问:
Why does it always return true?
Beginner question, sorry if it's not the right place to ask
Trying to learn how logic works in JS, can't figure this out

```<code>if (firstSymbol === "A" || "a" || "D" || "d") {
    if (secondSymbol === "z") {
        alert("It does!");
        break;
    }
}
</code>```

I expect it to say "It does!" and break in case if the firstSymbol is A, a, D or d AND the secondSymbol is z , but for some reason it says "It does!" and breaks regardless of what the firstSymbol is and only checks if the secondSymbol is z.

答:
Just to add something to the boilerplate, these are some examples to accomplish what you're trying to do, with tons of possibilities.

Tests covered:

using array.includes

using array.indexOf

using array.find

using array.some

WHY didn't your code work?

It didn't work because javascript evaluates the following expression: "A" || "a" || "D" || "d" to "A", because "A" is truthy. If you need to compare with multiple values, either use an array, either write the condition for each of them:
firstSymbol === "A" || firstSymbol === "D" ||...

Examples mentioned above:

/* Original code */
/*
if (firstSymbol === "A" || "a" || "D" || "d") {if (secondSymbol === "z") alert("It does!"); break;}
*/

let firstSymbol = "d", secondSymbol = "z";

// Using .includes
if (["A","a","D","d"].includes(firstSymbol) && secondSymbol === "z") console.log('it does, with .includes');

// Cleverer .includes due to the nature of the input.
if (["a","d"].includes(firstSymbol.toLowerCase()) && secondSymbol === "z") console.log('it does, with cleverer .includes');

// Using .indexOf
if (["A","a","D","d"].indexOf(firstSymbol) > -1 && secondSymbol === "z") console.log('it does, with .indexOf');

// Using .find
if (["A","a","D","d"].find(i => i === firstSymbol) && secondSymbol === "z") console.log('it does, with .find');

// Using. some
if (["A","a","D","d"].some(i => i === firstSymbol) && secondSymbol === "z") console.log('it does, with .some');```

Title: Why does it always return true?

Body:
Beginner question, sorry if it's not the right place to ask
Trying to learn how logic works in JS, can't figure this out

if (firstSymbol === "A" || "a" || "D" || "d") {
    if (secondSymbol === "z") {
        alert("It does!");
        break;
    }
}

I expect it to say "It does!" and break in case if the firstSymbol is A, a, D or d AND the secondSymbol is z , but for some reason it says "It does!" and breaks regardless of what the firstSymbol is and only checks if the secondSymbol is z.


问:
Function returns an error (ESLint) move function to body root
I have the following function.the code does what i need it to do,however its not structured correctly because of the declarations therefore it gives "(ESLint) move function to body root" error :

This is my code:

```<code>function onSuccess(result) {

            if (result) {
                 function GetTotal(result) {

                    var totBal = 0;
                    var str = 'R';
                    for (var i = 0; i < result.length; i++) {
                        totBal += result[i].Price;
                    }
                    str += totBal.toFixed(2);
                    return str;
                }
                var span = document.getElementById("Total");
                span.innerHTML = GetTotal(result);
            }
        }
</code>```

This is what i tried:

```<code>function onSuccess(result) {
        var fn;
        if (result) {
          fn=function GetTotal(result) {

                var totBal = 0;
                var str = 'R';
                for (var i = 0; i < result.length; i++) {
                    totBal += result[i].Price;
                }
                str += totBal.toFixed(2);
                return str;
            };
            var span = document.getElementById("Total");
            span.innerHTML = GetTotal(result);
        }
    }
</code>```

the "(ESLint) move function to body root" gets solved But with the above it returns an error saying "getTotal is not defined"

答:
On your second example the function is now inside the variable fn. You can access it by calling fn(). Another option is to rename the variable to reflect the function behavior and then call it by its new name.

var fn;
fn=function GetTotal(result) {
  console.log('function called!');
}

fn();```

Body:
I have the following function.the code does what i need it to do,however its not structured correctly because of the declarations therefore it gives "(ESLint) move function to body root" error :

This is my code:

function onSuccess(result) {

            if (result) {
                 function GetTotal(result) {

                    var totBal = 0;
                    var str = 'R';
                    for (var i = 0; i < result.length; i++) {
                        totBal += result[i].Price;
                    }
                    str += totBal.toFixed(2);
                    return str;
                }
                var span = document.getElementById("Total");
                span.innerHTML = GetTotal(result);
            }
        }

This is what i tried:

function onSuccess(result) {
        var fn;
        if (result) {
          fn=function GetTotal(result) {

                var totBal = 0;
                var str = 'R';
                for (var i = 0; i < result.length; i++) {
                    totBal += result[i].Price;
                }
                str += totBal.toFixed(2);
                return str;
            };
            var span = document.getElementById("Total");
            span.innerHTML = GetTotal(result);
        }
    }

the "(ESLint) move function to body root" gets solved But with the above it returns an error saying "getTotal is not defined"


问:
C# Signature Matching with Public Key
I'm working with a third party attempting to establish digital signature matching in both directions.  On my side we are using C# while the third party is using Java.  So far I am able to generate a key pairing within OpenSSL and use the private key to generate a signature which they are able to match in their Java environment (C# code below).  Going the opposite direction, how do I use the generated public key to create a matching signature?

I've attempted using the same code below simply changing the CngKeyBlobFormat when importing the public key but all other types produce an error.

On both sides the following OpenSSL commands were used to generate the public and private keys:

```<code>openssl genrsa -des3 -out my_rsa_key_pair 2048

openssl pkcs8 -topk8 -inform PEM -in my_rsa_key_pair -outform PEM -out private_key.pem -nocrypt

openssl rsa -in my_rsa_key_pair -outform PEM -pubout -out public_key.pem
</code>```

This is the C# code used to generate a signature from the private key:

```<code>byte[] keyBytes = Convert.FromBase64String(privateKey);
byte[] valueBytes = Encoding.UTF8.GetBytes(stringToSign);
byte[] signedBytes;

using (CngKey key = CngKey.Import(keyBytes, CngKeyBlobFormat.Pkcs8PrivateBlob))
using (RSA rsa = new RSACng(key))
{
    signedBytes = rsa.SignData(valueBytes, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
    return Convert.ToBase64String(signedBytes);
}
</code>```

Using the public key I need to generate a signature within C# that matches what was generated with the private key. What is the proper way to do this?

答:
There are a lot of posts surrounding signature generation / verification and after hitting on the right key words I found the answer in the following post. Given the above code and method of generating public/private key pairings the answer in this post will successfully validate the signature generated with a private key using only the public key. Leaving this open for anyone searching for both sides of the solution:
Verify signature generated with RSA 2048-bit key, SHA256 algorithm and PKCSv1.5 padding</p>

Title: C# Signature Matching with Public Key

Body:
I'm working with a third party attempting to establish digital signature matching in both directions.  On my side we are using C# while the third party is using Java.  So far I am able to generate a key pairing within OpenSSL and use the private key to generate a signature which they are able to match in their Java environment (C# code below).  Going the opposite direction, how do I use the generated public key to create a matching signature?

I've attempted using the same code below simply changing the CngKeyBlobFormat when importing the public key but all other types produce an error.

On both sides the following OpenSSL commands were used to generate the public and private keys:

openssl genrsa -des3 -out my_rsa_key_pair 2048

openssl pkcs8 -topk8 -inform PEM -in my_rsa_key_pair -outform PEM -out private_key.pem -nocrypt

openssl rsa -in my_rsa_key_pair -outform PEM -pubout -out public_key.pem

This is the C# code used to generate a signature from the private key:

byte[] keyBytes = Convert.FromBase64String(privateKey);
byte[] valueBytes = Encoding.UTF8.GetBytes(stringToSign);
byte[] signedBytes;

using (CngKey key = CngKey.Import(keyBytes, CngKeyBlobFormat.Pkcs8PrivateBlob))
using (RSA rsa = new RSACng(key))
{
    signedBytes = rsa.SignData(valueBytes, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
    return Convert.ToBase64String(signedBytes);
}

Using the public key I need to generate a signature within C# that matches what was generated with the private key. What is the proper way to do this?


问:
How can I tell which login is being used to connect to a SQL Server linked server?
I can get information about a linked server using the sp_linked_servers stored procedure.  What the SP does not give me, however, is login info entered via sp_addlinkedsrvlogin.

How can I tell which login is being used to connect to the linked server?

答:
Figured it out:</p>

```<code>select s.name, l.remote_name
from sys.linked_logins l
join sys.servers s on s.server_id = l.server_id
</code>```

Body:
Figured it out:

select s.name, l.remote_name
from sys.linked_logins l
join sys.servers s on s.server_id = l.server_id