问:
Is there standard way of making multiple API calls combined into one HTTP request?
While designing rest API's I time to time have challenge to deal with batch operations (e.g. delete or update many entities at once) to reduce overhead of many tcp client connections. And in particular situation problem usually solves by adding custom api method for specific operation (e.g. POST /files/batchDelete which accepts ids at request body) which doesn't look pretty from point of view of rest api design principles but do the job.

But for me general solution for the problem still desirable. Recently I found Google Cloud Storage JSON API batching documentation which for me looks like pretty general solution. I mean similar format may be used for any http api, not just google cloud storage. So my question is - does anybody know kind of general standard (standard or it's draft, guideline, community effort or so) of making multiple API calls combined into one HTTP request?

I'm aware of capabilities of http/2 which include usage of single tcp connection for http requests but my question is addressed to application level. Which in my opinion still make sense because despite of ability to use http/2 taking that on application level seems like the only way to guarantee that for any client including http/1 which is currently the most used version of http.

答:
TL;DR

REST nor HTTP are ideal for batch operations.

Usually caching, which is one of RESTs constraints, which is not optional but mandatory, prevents batch processing in some form.

It might be beneficial to not expose the data to update or remove in batch as own resources but as data elements within a single resource, like a data table in a HTML page. Here updating or removing all or parts of the entries should be straight forward.

If the system in general is write-intensive it is probably better to think of other solutions such as exposing the DB directly to those clients to spare a further level of indirection and complexity.

Utilization of caching may prevent a lot of workload on the server and even spare unnecessary connecctions

To start with, REST nor HTTP are ideal for batch operations. As Jim Webber pointed out the application domain of HTTP is the transfer of documents over the Web. This is what HTTP does and this is what it is good at. However, any business rules we conclude are just a side effect of the document management and we have to come up with solutions to turn this document management side effects to something useful.

As REST is just a generalization of the concepts used in the browsable Web, it is no miracle that the same concepts that apply to Web development also apply to REST development in some form. Thereby a question like how something should be done in REST usually resolves around answering how something should be done on the Web.

As mentioned before, HTTP isn't ideal in terms of batch processing actions. Sure, a GET request may retrieve multiple results, though in reality you obtain one response containing links to further resources. The creation of resources has, according to the HTTP specification, to be indicated with a Location header that points to the newly created resource. POST is defined as an all purpose method that allows to perform tasks according to server-specific semantics. So you could basically use it to create multiple resources at once. However, the HTTP spec clearly lacks support for indicating the creation of multiple resources at once as the Location header may only appear once per response as well as define only one URI in it. So how can a server indicate the creation of multiple resources to the server?

A further indication that HTTP isn't ideal for batch processing is that a URI must reference a single resource. That resource may change over time, though the URI can't ever point to multiple resources at once. The URI itself is, more or less, used as key by caches which store a cacheable response representation for that URI. As a URI may only ever reference one single resource, a cache will also only ever store the representation of one resource for that URI. A cache will invalidate a stored representation for a URI if an unsafe operation is performed on that URI. In case of a DELETE operation, which is by nature unsafe, the representation for the URI the DELETE is performed on will be removed. If you now "redirect" the DELETE operation to remove multiple backing resources at once, how should a cache take notice of that? It only operates on the URI invoked. Hence even when you delete multiple resources in one go via DELETE a cache might still serve clients with outdated information as it simply didn't take notice of the removal yet and its freshness value would still indicate a fresh-enough state. Unless you disable caching by default, which somehow violates one of REST's constraints, or reduce the time period a representation is considered fresh enough to a very low value, clients will probably get served with outdated information. You could of course perform an unsafe operation on each of these URIs then to "clear" the cache, though in that case you could have invoked the DELETE operation on each resource you wanted to batch delete itself to start with.

It gets a bit easier though if the batch of data you want to remove is not explicitly captured via their own resources but as data of a single resource. Think of a data-table on a Web page where you have certain form-elements, such as a checkbox you can click on to mark an entry as delete candidate and then after invoking the submit button send the respective selected elements to the server which performs the removal of these items. Here only the state of one resource is updated and thus a simple POST, PUT or even PATCH operation can be performed on that resource URI. This also goes well with caching as outlined before as only one resource has to be altered, which through the usage of unsafe operations on that URI will automatically lead to an invalidation of any stored representation for the given URI.

The above mentioned usage of form-elements to mark certain elements for removal depends however on the media-type issued. In the case of HTML its forms section specifies the available components and their affordances. An affordance is the knowledge what you can and should do with certain objects. I.e. a button or link may want to be pushed, a text field may expect numeric or alphanumeric input which further may be length limited and so on. Other media types, such as hal-forms, halform or ion, attempt to provide form representations and components for a JSON based notation, however, support for such media-types is still quite limited.

As one of your concerns are the number of client connections to your service, I assume you have a write-intensive scenario as in read-intensive cases caching would probably take away a good chunk of load from your server. I.e. BBC once reported that they could reduce the load on their servers drastically just by introducing a one minute caching interval for recently requested resources. This mainly affected their start page and the linked articles as people clicked on the latest news more often than on old news. On receiving a couple of thousands, if not hundred thousands, request per minute they could, as mentioned before, reduce the number of requests actually reaching the server significantly and therefore take away a huge load on their servers.

Write intensive use-cases however can't take benefit of caching as much as read-intensive cases as the cache would get invalidated quite often and the actual request being forward to the server for processing. If the API is more or less used to perform CRUD operations, as so many "REST" APIs do in reality, it is questionable if it wouldn't be preferable to expose the database directly to the clients. Almost all modern database vendors ship with sophisticated user-right management options and allow to create views that can be exposed to certain users. The "REST API" on top of it basically just adds a further level of indirection and complexity in such a case. By exposing the DB directly, performing batch updates or deletions shouldn't be an issue at all as through the respective query languages support for such operations should already be build into the DB layer.

In regards to the number of connections clients create: HTTP from 1.0 on allows the reusage of connections via the Connection: keep-alive header directive. In HTTP/1.1 persistent connections are used by default if not explicitly requested to close via the respective Connection: close header directive. HTTP/2 introduced full-duplex connections that allow many channels and therefore requests to reuse the same connections at the same time. This is more or less a fix for the connection limitation suggested in RFC 2626 which plenty of Web developers avoided by using CDN and similar stuff. Currently most implementations use a maximum limit of 100 channels and therefore simultaneous downloads via a single connections AFAIK.

Usually opening and closing a connection takes a bit of time and server resources and the more open connections a server has to deal with the more a system may suffer. Though open connections with hardly any traffic aren't a big issue for most servers. While the connection creation was usually considered to be the costly part, through the usage of persistent connections that factor moved now towards the number of requests issued, hence the request for sending out batch-requests, which HTTP is not really made for. Again, as mentioned throughout the post, through the smart utilization of caching plenty of requests may never reach the server at all, if possible. This is probably one of the best optimization strategies to reduce the number of simultaneous requests, as probably plenty of requests might never reach the server at all. Probably the best advice to give is in such a case to have a look at what kind of resources are requested frequently, which requests take up a lot of processing capacity and which ones can easily get responded with by utilizing caching options.


来源: stackexchange

问:
How to Get First Week Saturday date of current month in php?
how to get Saturday first week date of the current month...Actually I have two input data field first is start date and second date input what I am looking for
is first start date is always starts from every week on Saturday and submit report date is always next week Wednesday

First Start Date Input

```<code>$date=date('m/d/Y');
<input id="mock_test_date" name="start date" placeholder="" type="text" class="form-control"
value="date('m/d/Y')" readonly="readonly" />
</code>```

Second Date Input

```<code><input id="mock_test_date" name="start date" placeholder="" type="text" class="form-control"  value="date('m/d/Y', strtotime($date .' +4 day'))" readonly="readonly" />
</code>```

how can I get the First Week Saturday on every month and on the second field I will get date of next Wednesday....if first input Saturday is on month end then i will get next month wednesday date

答:
It is not clear what is being sought. An example would be helpful.
The solution with DateTime as I understand the question:

```<code>$firstSaturdayThisMonth = date_create('first Saturday of this Month');
$wednesdayAfterFirstSaturday = (clone $firstSaturdayThisMonth)->modify('next Wednesday');

echo $firstSaturdayThisMonth->format('D, j.M')
  ." - ".$wednesdayAfterFirstSaturday->format('D, j.M Y');
</code>```

The result of today 19.02.2020:

```<code>Sat, 1.Feb - Wed, 5.Feb 2020
</code>```

ContentLicense: CC BY-SA 4.0

Body:
how to get Saturday first week date of the current month...Actually I have two input data field first is start date and second date input what I am looking for
is first start date is always starts from every week on Saturday and submit report date is always next week Wednesday

First Start Date Input

$date=date('m/d/Y');
<input id="mock_test_date" name="start date" placeholder="" type="text" class="form-control"
value="date('m/d/Y')" readonly="readonly" />

Second Date Input

<input id="mock_test_date" name="start date" placeholder="" type="text" class="form-control"  value="date('m/d/Y', strtotime($date .' +4 day'))" readonly="readonly" />

how can I get the First Week Saturday on every month and on the second field I will get date of next Wednesday....if first input Saturday is on month end then i will get next month wednesday date

Body:
It is not clear what is being sought. An example would be helpful.
The solution with DateTime as I understand the question:

$firstSaturdayThisMonth = date_create('first Saturday of this Month');
$wednesdayAfterFirstSaturday = (clone $firstSaturdayThisMonth)->modify('next Wednesday');

echo $firstSaturdayThisMonth->format('D, j.M')
  ." - ".$wednesdayAfterFirstSaturday->format('D, j.M Y');

The result of today 19.02.2020:

Sat, 1.Feb - Wed, 5.Feb 2020


问:
template0 and template1 database dropped accidently
I did not know that template0 and template1 database templates are required in order to create empty databases. I deleted them in order to clear up postgres. Now I'm not able to create any new database. Gives me this error :

```<code>ERROR:  template database "template1" does not exist
</code>```

What can I do to get things going once again. I'll be very thankful for any help.

答:
on my debian machine, i upgraded some clusters to version 11.
the template[01] databases on the target cluster have been dropped, rendering me with the ones from the older versions.

as root, i created a new cluster with pg_createcluster.

as user postgres:

dump the databases of the new cluster with pg_dumpall (with the --clean flag).

drop the new cluster.

import the resulted source in your cluster with psql.

i would remove the drop role postgres and creation of the same.

best regards,
alex

ContentLicense: CC BY-SA 3.0

Body:
I did not know that template0 and template1 database templates are required in order to create empty databases. I deleted them in order to clear up postgres. Now I'm not able to create any new database. Gives me this error :

ERROR:  template database "template1" does not exist

What can I do to get things going once again. I'll be very thankful for any help.


问:
alphabet split instead of word split using lists
so ive predefined a set of names in a list(lst1) and when the user inputs a name,which doesnt matches the ones in the pre defined list prints a message which returns the element which didnt match along with a message "doesnt belong to our family" but when i run this code, the name gets split into a list like for example instead of "Abby:doesnt belong to our family",it prints "a":doesnt belong...."b":doesnt belong and so on...

heres the code:

```<code>lst1=['john','undertaker','kane','randy']
a1=input().strip()
a=a1.split(',')

user_input=[str(i) for i in a]

for _input in user_input:
    for name in [str(i) for i in str(_input)]:
        if name not in lst1:
            print(f"{name}:Not in family")
</code>```

sample input:
1)Rey mysteiro
2)Randy

output:
1)rey mysterio
r:Not in family
e:Not in family
y:Not in family
 :Not in family
m:Not in family
y:Not in family
s:Not in family
t:Not in family
e:Not in family
r:Not in family
i:Not in family
o:Not in family

2)randy
r:Not in family
a:Not in family
n:Not in family
d:Not in family
y:Not in family

for some reason this is not working ,any suggestions to improve this code as well as tackle this problem is appreciated!Thanks for helping me out!

答:
You can try this.

```<code>lst1=['john','undertaker','kane','randy'] #use a set instead of a list.
lst1=set(lst1)
user_names=input().split(',')
for user in user_names:
    if user not in lst1: #now for checking membership it takes O(1)  but with list it's O(N)
         print(f'{user} : Not part of the family')
</code>```

user_input=[str(i) for i in a] this is redundant i is already str.

for name in [str(i) for i in str(_input)] is step is why you get individual alphabets.

_input is a string.Let's say _input is 'randy'. When you do for name in [str(i) in str(_input)] which is equivalent to this for name in ['r','a','n','d','y']. And str(_input) is redundant _input is already string and str(i) is also redundant as i is already string.

Body:
so ive predefined a set of names in a list(lst1) and when the user inputs a name,which doesnt matches the ones in the pre defined list prints a message which returns the element which didnt match along with a message "doesnt belong to our family" but when i run this code, the name gets split into a list like for example instead of "Abby:doesnt belong to our family",it prints "a":doesnt belong...."b":doesnt belong and so on...

heres the code:

lst1=['john','undertaker','kane','randy']
a1=input().strip()
a=a1.split(',')

user_input=[str(i) for i in a]

for _input in user_input:
    for name in [str(i) for i in str(_input)]:
        if name not in lst1:
            print(f"{name}:Not in family")

sample input:
1)Rey mysteiro
2)Randy

output:
1)rey mysterio
r:Not in family
e:Not in family
y:Not in family
 :Not in family
m:Not in family
y:Not in family
s:Not in family
t:Not in family
e:Not in family
r:Not in family
i:Not in family
o:Not in family

2)randy
r:Not in family
a:Not in family
n:Not in family
d:Not in family
y:Not in family

for some reason this is not working ,any suggestions to improve this code as well as tackle this problem is appreciated!Thanks for helping me out!

Body:
You can try this.

lst1=['john','undertaker','kane','randy'] #use a set instead of a list.
lst1=set(lst1)
user_names=input().split(',')
for user in user_names:
    if user not in lst1: #now for checking membership it takes O(1)  but with list it's O(N)
         print(f'{user} : Not part of the family')

user_input=[str(i) for i in a] this is redundant i is already str.

for name in [str(i) for i in str(_input)] is step is why you get individual alphabets.

_input is a string.Let's say _input is 'randy'. When you do for name in [str(i) in str(_input)] which is equivalent to this for name in ['r','a','n','d','y']. And str(_input) is redundant _input is already string and str(i) is also redundant as i is already string.


问:
Is there any free open source chart library available for iphone/ipad?
Is there any free open source chart library available for iphone/ipad ?</p>

答:
Tapku library has a line plot chart

http://tapku.com

https://github.com/devinross/tapkulibrary/wiki/Graph

ContentLicense: CC BY-SA 2.5


问:
R ggbiplot installation errer
I know this is a recurrent issue. However, going through all the hits when I google still has not helped me solve the issue. I hope someone can help: Her is what I do:
1: I run

```<code>install.packages('devtools')
library(devtools)
</code>```

This appears to run all right. At least I do not get any error messages.

2: then I do:

```<code>install_github('vqv/ggbiplot', force=TRUE)
</code>```

Then the errors messages comes:

install_github('vqv/ggbiplot', force=TRUE)
  Downloading GitHub repo vqv/ggbiplot@master
  √  checking for file 'C:\Users\jada\AppData\Local\Temp\RtmpgvAEpK\remotes28461c455b1\vqv-ggbiplot-7325e88/DESCRIPTION' ...
  -  preparing 'ggbiplot':
  √  checking DESCRIPTION meta-information ...
  -  checking for LF line-endings in source and make files and shell scripts
  -  checking for empty or unneeded directories
  -  looking to see if a 'data/datalist' file should be added
  -  building 'ggbiplot_0.55.tar.gz'

Installing package into ‘C:/Users/jada/Documents/R/win-library/3.6’
(as ‘lib’ is unspecified)
* installing source package 'ggbiplot' ...
** using staged installation
** R
** data
** byte-compile and prepare package for lazy loading
Error: (converted from warning) package 'ggplot2' was built under R version 3.6.1
Execution halted
ERROR: lazy loading failed for package 'ggbiplot'
* removing 'C:/Users/jada/Documents/R/win-library/3.6/ggbiplot'
Error: Failed to install 'ggbiplot' from GitHub:
  (converted from warning) installation of package ‘C:/Users/jada/AppData/Local/Temp/RtmpgvAEpK/file28421d56f74/ggbiplot_0.55.tar.gz’ had non-zero exit status

If anyone could sort me out here, I would be very happy.
Thank you.

jd

答:
I suggest you to go in the path of the library in your computer (should be c:/Users/jada/Documents/R/win-library/3.6/) and delete the ggbiplot folder. After this, redo the installation process.
In this way you remove every possible problem conflict.

If this doesn't work out try also to delete ggbiplot_0.55.tar.gz in the Temp folder as suggested in the error.

Title: R ggbiplot installation errer

Body:
I know this is a recurrent issue. However, going through all the hits when I google still has not helped me solve the issue. I hope someone can help: Her is what I do:
1: I run

install.packages('devtools')
library(devtools)

This appears to run all right. At least I do not get any error messages.

2: then I do:

install_github('vqv/ggbiplot', force=TRUE)

Then the errors messages comes:

install_github('vqv/ggbiplot', force=TRUE)
  Downloading GitHub repo vqv/ggbiplot@master
  √  checking for file 'C:\Users\jada\AppData\Local\Temp\RtmpgvAEpK\remotes28461c455b1\vqv-ggbiplot-7325e88/DESCRIPTION' ...
  -  preparing 'ggbiplot':
  √  checking DESCRIPTION meta-information ...
  -  checking for LF line-endings in source and make files and shell scripts
  -  checking for empty or unneeded directories
  -  looking to see if a 'data/datalist' file should be added
  -  building 'ggbiplot_0.55.tar.gz'

Installing package into ‘C:/Users/jada/Documents/R/win-library/3.6’
(as ‘lib’ is unspecified)
* installing source package 'ggbiplot' ...
** using staged installation
** R
** data
** byte-compile and prepare package for lazy loading
Error: (converted from warning) package 'ggplot2' was built under R version 3.6.1
Execution halted
ERROR: lazy loading failed for package 'ggbiplot'
* removing 'C:/Users/jada/Documents/R/win-library/3.6/ggbiplot'
Error: Failed to install 'ggbiplot' from GitHub:
  (converted from warning) installation of package ‘C:/Users/jada/AppData/Local/Temp/RtmpgvAEpK/file28421d56f74/ggbiplot_0.55.tar.gz’ had non-zero exit status

If anyone could sort me out here, I would be very happy.
Thank you.

jd


问:
How to understand the concurrency of requests from client-side by gRPC in the TF-Serving example?
Background

According to Serving a TensorFlow Model,

The program in mnist client is about

A client that talks to tensorflow_model_server loaded with mnist model.

The client downloads test images of mnist data set, queries the service with

such test images to get predictions, and calculates the inference error rate.

Problem

I have some difficulties to understand the concurrency of requests from client-side by gRPC.

Define concurrency

Concurrency related code

  for _ in range(num_tests): # <==

    request = predict_pb2.PredictRequest()
    request.model_spec.name = 'mnist'
    request.model_spec.signature_name = 'predict_images'
    image, label = test_data_set.next_batch(1)
    request.inputs['images'].CopyFrom(
        tf.make_tensor_proto(image[0], shape=[1, image[0].size]))

    result_counter.throttle() # <==

    result_future = stub.Predict.future(request, 5.0)  # 5 seconds
    result_future.add_done_callback(
        _create_rpc_callback(label[0], result_counter))
```

Based on my understanding, the above code is executed sequentially in the for loop.
I have read posts about condition variable, lock in Python. Since I don't even see multiple threads defined to send request, I don't think the code is related to concurrency even if I set the flag to e.g., 10. (Define concurrency)

I may overlook gRPC if I have some misunderstanding.

If the code is not real concurrency, how to make it right?

答:
gRPC Python uses a background thread to polling messages from lower level. In order to run RPC concurrently, you can create multiple RPC futures in your thread. When any RPC is finished (result gathered by the background thread), then your callback will be invoked.

https://github.com/grpc/grpc/blob/0b4a9d6ba0a60a1982d81da6bb6b730a5c443c44/src/python/grpcio/grpc/_channel.py#L1126

Hope this helps, feel free to ask for more details.

Body:
Background

According to Serving a TensorFlow Model,

The program in mnist client is about

A client that talks to tensorflow_model_server loaded with mnist model.

The client downloads test images of mnist data set, queries the service with

such test images to get predictions, and calculates the inference error rate.

Problem

I have some difficulties to understand the concurrency of requests from client-side by gRPC.

Define concurrency

Concurrency related code

  for _ in range(num_tests): # <==

    request = predict_pb2.PredictRequest()
    request.model_spec.name = 'mnist'
    request.model_spec.signature_name = 'predict_images'
    image, label = test_data_set.next_batch(1)
    request.inputs['images'].CopyFrom(
        tf.make_tensor_proto(image[0], shape=[1, image[0].size]))

    result_counter.throttle() # <==

    result_future = stub.Predict.future(request, 5.0)  # 5 seconds
    result_future.add_done_callback(
        _create_rpc_callback(label[0], result_counter))

Based on my understanding, the above code is executed sequentially in the for loop.
I have read posts about condition variable, lock in Python. Since I don't even see multiple threads defined to send request, I don't think the code is related to concurrency even if I set the flag to e.g., 10. (Define concurrency)

I may overlook gRPC if I have some misunderstanding.

If the code is not real concurrency, how to make it right?


问:
How do you apply a Combine operator only after the first message has been received?
In Combine, using only the built-in operators, is there a way to skip an operator on the first value but then apply that operator for all subsequent values?

Consider the following:

```<code>publisher
  .debounce(...)
  .sink(...)
</code>```

In this arrangement, debounce will wait for the specified timeout to elapse before passing on the value to sink. However, there are many times when you only want debounce to kick-in after the first element. For example, if the user is trying to filter a list of contacts, it's very possible that they only enter one letter into a text field. If that's the case, the application should probably start filtering immediately, without having to wait for the debounce to timeout.

I'm aware of the Drop publishers, but I can't seem to find a combination of them that will perform more of a "skip" operation such that the sink receives every value, but the debounce is ignored on the first value.

Something like the following:

```<code>publisher
  .if_first_element_passthrough_to_sink(...), else_debounce(...)
  .sink(...)
</code>```

Is something like this possible with the built-in operators?

Clarification

Some clarification since my original posting wasn't as clear as it should have been... The answer provided by Asperi below is very close, but ideally the first element in a sequence is always delivered, then debounce would kick in.

Imagine the user is typing the following:

A B C ... (pauses typing for a few seconds) ... D ... (pauses) ... E F G

What I would like is:

A, D and E are delivered immediately.

B C is coalesced into just C using debounce

F G is coalesced into just G using debounce

答:
If I correctly understood your needs it can be achieved based on Concatenate as like the following (in pseudo-code):

```<code>let originalPublisher = ...
let publisher = Publishers.Concatenate(
        prefix: originalPublisher.first(),
        suffix: originalPublisher.debounce(for: 0.5, scheduler: RunLoop.main))
    .eraseToAnyPublisher()
</code>```

so, prefix just sends first element downstream from original publisher and finished, afterwards suffix just pass all following elements using debounce.

Body:
In Combine, using only the built-in operators, is there a way to skip an operator on the first value but then apply that operator for all subsequent values?

Consider the following:

publisher
  .debounce(...)
  .sink(...)

In this arrangement, debounce will wait for the specified timeout to elapse before passing on the value to sink. However, there are many times when you only want debounce to kick-in after the first element. For example, if the user is trying to filter a list of contacts, it's very possible that they only enter one letter into a text field. If that's the case, the application should probably start filtering immediately, without having to wait for the debounce to timeout.

I'm aware of the Drop publishers, but I can't seem to find a combination of them that will perform more of a "skip" operation such that the sink receives every value, but the debounce is ignored on the first value.

Something like the following:

publisher
  .if_first_element_passthrough_to_sink(...), else_debounce(...)
  .sink(...)

Is something like this possible with the built-in operators?

Clarification

Some clarification since my original posting wasn't as clear as it should have been... The answer provided by Asperi below is very close, but ideally the first element in a sequence is always delivered, then debounce would kick in.

Imagine the user is typing the following:

A B C ... (pauses typing for a few seconds) ... D ... (pauses) ... E F G

What I would like is:

A, D and E are delivered immediately.

B C is coalesced into just C using debounce

F G is coalesced into just G using debounce

Body:
If I correctly understood your needs it can be achieved based on Concatenate as like the following (in pseudo-code):

let originalPublisher = ...
let publisher = Publishers.Concatenate(
        prefix: originalPublisher.first(),
        suffix: originalPublisher.debounce(for: 0.5, scheduler: RunLoop.main))
    .eraseToAnyPublisher()

so, prefix just sends first element downstream from original publisher and finished, afterwards suffix just pass all following elements using debounce.


问:
How to use draggable sections like on iGoogle?
When viewing iGoogle, each section is able to be drag-and-dropped to anywhere else on the page and then the state of the page is saved. I am curious on how this is done as I would like to provide this functionality as part of a proof of concept?

UPDATE

How do you make it so that the layout you changed to is saved for the next load? I am going to guess this is some sort of cookie?

答:
I hate to give a short answer on this, but there are several dozen different JavaScript libraries that provide this type of functionality, and lots of tutorials and howto guides available on google:

http://www.google.com/search?q=javascript+draggable

Some JavaScript libraries/frameworks you might want to take a look at:

jQuery

MooTools

Yahoo User Interface (YUI) library

OwnerDisplayName: Ascalonian

OwnerDisplayName: matt b


问:
Boundaries and contours in Matlab
I have a binary image with non closed curves of 1-pixel width on it. I want to grab this curves as a list of points (in proper order). I found bwboundaries function which tries to wrap all non-zero pixels and thus in this case returns duplicate points:

```<code>>> A = [0 0 0; 1 1 1; 0 0 0];
>> b = bwboundaries(A)

ans =

    [5x2 double]

>> b{1}

ans =

     2     1
     2     2
     2     3
     2     2
     2     1
</code>```

bwtraceboundary do the same

```<code>>> bwtraceboundary(A, [2 1], 'E')

ans =

     2     1
     2     2
     2     3
     2     2
     2     1
</code>```

Is there any standard method to get matrix like [2 1; 2 2; 2 3] immediately?

答:
It produces double entries because your region is only one pixel wide. I don't think there's a standard method that handles your special problem directly. However, you can simply use the unique() function to eliminate double entries of the result.

To keep the original order of the points, just do:

```<code>b = bwboundaries(A);
[dummy, ind] = unique(b{1}, 'rows', 'first');
contour = b{1}(sort(ind), :);
</code>```

Title: Boundaries and contours in Matlab

Body:
I have a binary image with non closed curves of 1-pixel width on it. I want to grab this curves as a list of points (in proper order). I found bwboundaries function which tries to wrap all non-zero pixels and thus in this case returns duplicate points:

>> A = [0 0 0; 1 1 1; 0 0 0];
>> b = bwboundaries(A)

ans =

    [5x2 double]

>> b{1}

ans =

     2     1
     2     2
     2     3
     2     2
     2     1

bwtraceboundary do the same

>> bwtraceboundary(A, [2 1], 'E')

ans =

     2     1
     2     2
     2     3
     2     2
     2     1

Is there any standard method to get matrix like [2 1; 2 2; 2 3] immediately?

Body:
It produces double entries because your region is only one pixel wide. I don't think there's a standard method that handles your special problem directly. However, you can simply use the unique() function to eliminate double entries of the result.

To keep the original order of the points, just do:

b = bwboundaries(A);
[dummy, ind] = unique(b{1}, 'rows', 'first');
contour = b{1}(sort(ind), :);


问:
How to parallelize an array shift with OpenMP?
How can I parallelize an array shift with OpenMP?

I've tryed a few things but didn't get any accurate results for the following example (which rotates the elements of an array of Carteira objects, for a permutation algorithm):

```<code>void rotaciona(int i)
{
    Carteira aux = this->carteira[i];
    for(int c = i; c < this->size - 1; c++)
    {
        this->carteira[c] = this->carteira[c+1];
    }
    this->carteira[this->size-1] = aux;
}
</code>```

Thank you very much!

答:
Though your sample doesn't show any explicit openmp pragma's, I don't think it could work easily:

you are doing an in-place operation with overlapping regions.
If you split the loop in chunks, you'll have race conditions at the boundaries (because el[n] gets copied from el[n+1], which might already have been updated in another thread).

I suggest that you do manual chunking (which can be done), but I suspect that openmp parallel for is not flexible enough (haven't tried), so you could just have a parallell region that does the work in chunks, and fixup the boundary elements after a thread barrier/end of parallel block

Other thoughts:

if your values are POD, you can use memmove instead

if you can, simply switch to a list

.

```<code>std::list<Carteira> items(3000);

// rotation is now simply:
items.push_back(items.front());
items.erase(items.begin());
</code>```

Body:
How can I parallelize an array shift with OpenMP?

I've tryed a few things but didn't get any accurate results for the following example (which rotates the elements of an array of Carteira objects, for a permutation algorithm):

void rotaciona(int i)
{
    Carteira aux = this->carteira[i];
    for(int c = i; c < this->size - 1; c++)
    {
        this->carteira[c] = this->carteira[c+1];
    }
    this->carteira[this->size-1] = aux;
}

Thank you very much!

Body:
Though your sample doesn't show any explicit openmp pragma's, I don't think it could work easily:

you are doing an in-place operation with overlapping regions.
If you split the loop in chunks, you'll have race conditions at the boundaries (because el[n] gets copied from el[n+1], which might already have been updated in another thread).

I suggest that you do manual chunking (which can be done), but I suspect that openmp parallel for is not flexible enough (haven't tried), so you could just have a parallell region that does the work in chunks, and fixup the boundary elements after a thread barrier/end of parallel block

Other thoughts:

if your values are POD, you can use memmove instead

if you can, simply switch to a list

.

std::list<Carteira> items(3000);

// rotation is now simply:
items.push_back(items.front());
items.erase(items.begin());


问:
what does the term `fac` mean in Haskell?
What does the term fac mean in Haskell? I've seen it on many occasions but it appears to not have any definition of being of any type. I know it has something to do with factorials but am not quite sure what people mean when they refer to the term fac.

Here's an example:

```<code>sumFacs n = fac 0 + fac 1 + ... + fac (n-1) + fac n
</code>```

答: It's the abbreviation for factorial.</p>

Body:
What does the term fac mean in Haskell? I've seen it on many occasions but it appears to not have any definition of being of any type. I know it has something to do with factorials but am not quite sure what people mean when they refer to the term fac.

Here's an example:

sumFacs n = fac 0 + fac 1 + ... + fac (n-1) + fac n

Body: It's the abbreviation for factorial.


问:
how can I convert rows with date range to rows with each date in rage?
Lets say I have the following data pulled from a database:

```<code>data = [
    {'db_id': 1, 'start': '2020-02-02', 'end': '2020-02-05'},
    {'db_id': 2, 'start': '2020-02-04', 'end': '2020-02-06'},
    {'db_id': 3, 'start': '2020-02-02', 'end': '2020-02-04'}
]
df = pd.DataFrame(data)
</code>```

I want to convert this into a row for each date/db_id combination, inclusive of the start and end date.  So I want to end up with the following DataFrame:

```<code>result_data = [
    {'db_id': 1, 'date': '2020-02-02'},
    {'db_id': 1, 'date': '2020-02-03'},
    {'db_id': 1, 'date': '2020-02-04'},
    {'db_id': 1, 'date': '2020-02-05'},
    {'db_id': 2, 'date': '2020-02-04'},
    {'db_id': 2, 'date': '2020-02-05'},
    {'db_id': 2, 'date': '2020-02-06'},
    {'db_id': 3, 'date': '2020-02-02'},
    {'db_id': 3, 'date': '2020-02-03'},
    {'db_id': 3, 'date': '2020-02-04'},
]

result_df = pd.DataFrame(result_data)
</code>```

What is an efficient way to do this in pandas (the data set has several hundred thousand rows).

Body:
Lets say I have the following data pulled from a database:

data = [
    {'db_id': 1, 'start': '2020-02-02', 'end': '2020-02-05'},
    {'db_id': 2, 'start': '2020-02-04', 'end': '2020-02-06'},
    {'db_id': 3, 'start': '2020-02-02', 'end': '2020-02-04'}
]
df = pd.DataFrame(data)

I want to convert this into a row for each date/db_id combination, inclusive of the start and end date.  So I want to end up with the following DataFrame:

result_data = [
    {'db_id': 1, 'date': '2020-02-02'},
    {'db_id': 1, 'date': '2020-02-03'},
    {'db_id': 1, 'date': '2020-02-04'},
    {'db_id': 1, 'date': '2020-02-05'},
    {'db_id': 2, 'date': '2020-02-04'},
    {'db_id': 2, 'date': '2020-02-05'},
    {'db_id': 2, 'date': '2020-02-06'},
    {'db_id': 3, 'date': '2020-02-02'},
    {'db_id': 3, 'date': '2020-02-03'},
    {'db_id': 3, 'date': '2020-02-04'},
]

result_df = pd.DataFrame(result_data)

What is an efficient way to do this in pandas (the data set has several hundred thousand rows).

Body:
Construct a new dataframe from genex

df_final = pd.DataFrame(((i, d) for i, s, e in zip(df.db_id, df.start, df.end)
                                    for d in pd.date_range(s, e, freq='D')),
                        columns=['db_id', 'date'])

Out[90]:
   db_id       date
0      1 2020-02-02
1      1 2020-02-03
2      1 2020-02-04
3      1 2020-02-05
4      2 2020-02-04
5      2 2020-02-05
6      2 2020-02-06
7      3 2020-02-02
8      3 2020-02-03
9      3 2020-02-04


问:
How to restrict an element value being lower than another in XML Schema?
I needed to have a restriction on an element. Given two elements like:

```<code><xs:element name="lowerValue" type="xs:int" minOccurs="0" maxOccurs="1" />
     <xs:element name="higgerValue" type="xs:int" minOccurs="0" maxOccurs="1">
          <xs:simpleType>
               <xs:restriction base="xs:string">
                      <xs:minLength value= lowerValue />
               </xs:restriction>
          </xs:simpleType>
</xs:element>
</code>```

In higgerValue needed to restrict the value to be no lower than lowerValue.

It is possible? How do I can do set the minimun value accepted the value of another element?

答:
In XSD 1.1 you can define an assertion. The assertion goes on the containing element (let's say container is the parent of both lowerValue and higherValue). Then on the definition of element container, you can write <xs:assert test="higherValue gt lowerValue"/>.

Cross-element constraints aren't possible in XSD 1.0.

Body:
I needed to have a restriction on an element. Given two elements like:

<xs:element name="lowerValue" type="xs:int" minOccurs="0" maxOccurs="1" />
     <xs:element name="higgerValue" type="xs:int" minOccurs="0" maxOccurs="1">
          <xs:simpleType>
               <xs:restriction base="xs:string">
                      <xs:minLength value= lowerValue />
               </xs:restriction>
          </xs:simpleType>
</xs:element>

In higgerValue needed to restrict the value to be no lower than lowerValue.

It is possible? How do I can do set the minimun value accepted the value of another element?


问:
Can I write my simple Python code in a better way?
I should rewrite my own function in a better way. The function takes an iterator and a sequence of boolean functions and returns an iterator of the elements in the input iterator which returns a truthy value.

```<code>def allTrue (iterator, funz):
for i in iterator:
    count = 0
    for f in funz:
        if f(i):
            count = count+1
        if count==len(funz):
            yield i
</code>```

I tried to write this:

```<code>def allTrue2 (iterator, funz):
    return (filter (f , iterator) for f in funz)
</code>```

But it's wrong. How could I improve the code?

Output:

```<code>print(list(allTrue(range(50),
               (lambda x: x % 3 == 0,
                lambda x: x > 10,
                lambda x: x < 44)
               )))

>>> [12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42]
</code>```

答:
```<code>def allTrue(iterator, funz):
    for i in iterator:
        if all(f(i) for f in funz):
            yield i
</code>```

Body:
I should rewrite my own function in a better way. The function takes an iterator and a sequence of boolean functions and returns an iterator of the elements in the input iterator which returns a truthy value.

def allTrue (iterator, funz):
for i in iterator:
    count = 0
    for f in funz:
        if f(i):
            count = count+1
        if count==len(funz):
            yield i

I tried to write this:

def allTrue2 (iterator, funz):
    return (filter (f , iterator) for f in funz)

But it's wrong. How could I improve the code?

Output:

print(list(allTrue(range(50),
               (lambda x: x % 3 == 0,
                lambda x: x > 10,
                lambda x: x < 44)
               )))

>>> [12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42]


问:
I'm trying to load a PDF using PDF Box however, the PDF just wont open. I'm not sure whats wrong in my code
<blockquote>
  <p>"Im not sure exactly what the problem is here so if anyone has any suggestions feel free to hit me with it. I am all ears!"  </p>
</blockquote>

```<code>     private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
      try {
        //Loading an existing PDF document
        File file = new File("C:\\Users\\Cayde\\OneDrive\\Desktop");
        PDDocument document = PDDocument.load(file);

        //Instantiating the PDFRenderer class
        PDFRenderer renderer = new PDFRenderer(document);

        //Rendering an image from the PDF document
        BufferedImage image = renderer.renderImage(0);

        try {
            //Writing the image to a file
            ImageIO.write(image, "JPEG", new File("C:\\Users\\Cayde\\OneDrive\\Desktop\\Open"));
        } catch (IOException ex) {
            Logger.getLogger(AFTO781.class.getName()).log(Level.SEVERE, null, ex);
        }

        System.out.println("Image created");

        //Closing the document
        document.close();
    } catch (IOException ex) {
        Logger.getLogger(AFTO781.class.getName()).log(Level.SEVERE, null, ex);
    }
</code>```

答:
"C:\\Users\\Cayde\\OneDrive\\Desktop" is most likely a directory. Your file is likely named like "C:\\Users\\Cayde\\OneDrive\\Desktop\\myfile.pdf".

The File where you are saving the image is most likely also a directory.

Body:
"Im not sure exactly what the problem is here so if anyone has any suggestions feel free to hit me with it. I am all ears!"

     private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
      try {
        //Loading an existing PDF document
        File file = new File("C:\\Users\\Cayde\\OneDrive\\Desktop");
        PDDocument document = PDDocument.load(file);

        //Instantiating the PDFRenderer class
        PDFRenderer renderer = new PDFRenderer(document);

        //Rendering an image from the PDF document
        BufferedImage image = renderer.renderImage(0);

        try {
            //Writing the image to a file
            ImageIO.write(image, "JPEG", new File("C:\\Users\\Cayde\\OneDrive\\Desktop\\Open"));
        } catch (IOException ex) {
            Logger.getLogger(AFTO781.class.getName()).log(Level.SEVERE, null, ex);
        }

        System.out.println("Image created");

        //Closing the document
        document.close();
    } catch (IOException ex) {
        Logger.getLogger(AFTO781.class.getName()).log(Level.SEVERE, null, ex);
    }


问:
Aurora Serverless 'deadtime'
I am running a SQL RDS with AWS Serverless, and run into errors when I test APIs. At the beginning of the day I will get a 502 error, however this resolves after I retry 1-4 times. I believe this error is due to some 'deadtime' that occurs when serverless is trying to 'boot up' from 0 capacity units after a period of inactivity? This does not seem to occur when the server is idle at 1 cap unit.

The only solution I have been able to think of is setting the server capacity min to 1 but this seems to defeat the purpose of serverless + increases price.

Has anyone else run into this problem/successfully implemented a solution?

答:
Before you run the API tests, you can start a paused serverless DB by sending it a scale command:

```<code>aws rds modify-current-db-cluster-capacity --db-cluster-identifier mydatabase --capacity 1
</code>```

and then poll every few seconds to see if it is available:

```<code>aws rds describe-db-clusters --db-cluster-identifier mydatabase | jq -r '.DBClusters[].Status'
</code>```

Once it is available you should be able to test your APIs without getting 502 errors.

Title: Aurora Serverless 'deadtime'

Body:
Before you run the API tests, you can start a paused serverless DB by sending it a scale command:

aws rds modify-current-db-cluster-capacity --db-cluster-identifier mydatabase --capacity 1

and then poll every few seconds to see if it is available:

aws rds describe-db-clusters --db-cluster-identifier mydatabase | jq -r '.DBClusters[].Status'

Once it is available you should be able to test your APIs without getting 502 errors.


问:
Testing removal of django whitenoise
In my django microservice, I have copied some of the whitenoise related code along with other code which I don't need because it should get handled at the CDN level. I have removed "whitenoise.middleware.WhiteNoiseMiddleware" from the settings.py but I'm not sure how to check if I need to remove anything else. In simple words, how do I check if my microservice is using whitenoise or not?

答: You can check your logs. If you see some urls for your static files, then it means your microservice serves static files.</p>

Title: Testing removal of django whitenoise


问:
Overlay Image above Embedded pdf
I am attempting to overlay an image above a pdf embedded in and iFrame.

This code results in the image falling behind the iFrame (tested by changing the bottom attribute to -10px and the bottom of the image becomes visable)

The only two methods I was aware of were using z-index, and the fact position absolute should place the object on top, but neither appear to be working.

```<code><div id="images" style="float:right;position:relative" width="400" height="250">
    <img src="images/Next_Black_Arrow.png" style="height:25px;width25px;float: left;z-index=10;position:absolute;bottom:10px;left:250px;">
    <iframe SRC="testFiles/Categories of pattern matching characters.pdf#toolbar=0&navpanes=0&scrollbar=0" style="z-index=1;position:relative;"  width="400" height="250"></iframe>
    </div>
</code>```

*Applogies for the lack of separated css

While that works, unfortunately it doesn't if you change the iframe link to a pdf.

See http://jsfiddle.net/vr4rX/4/

I think it must be a bug in the adobe reader. Could really do with a work around.

答:
have a look at my solution: http://jsfiddle.net/vr4rX/1/

HTML:

```<code><div id="images">
    <img src="http://t1.ftcdn.net/jpg/00/02/78/72/400_F_2787285_mlDf8ah974XHflVFrbQB3FM6Qxu1MT.jpg" />
    <iframe SRC="http://www.google.de"  width="400" height="250"></iframe>
</div>
</code>```

CSS:

```<code>#images {
    float:right;
    width: 400px;
    height: 250px;
    position: relative;
    z-index: 1;
}

#images img {
   height:25px;
    width:25px;
    z-index=2;
    position:absolute;
    bottom:20px;
    right:20px;
}
</code>```

Title: Overlay Image above Embedded pdf

Body:
I am attempting to overlay an image above a pdf embedded in and iFrame.

This code results in the image falling behind the iFrame (tested by changing the bottom attribute to -10px and the bottom of the image becomes visable)

The only two methods I was aware of were using z-index, and the fact position absolute should place the object on top, but neither appear to be working.

*Applogies for the lack of separated css

While that works, unfortunately it doesn't if you change the iframe link to a pdf.

See http://jsfiddle.net/vr4rX/4/

I think it must be a bug in the adobe reader. Could really do with a work around.

Body:
have a look at my solution: http://jsfiddle.net/vr4rX/1/

HTML:

<div id="images">
    <img src="http://t1.ftcdn.net/jpg/00/02/78/72/400_F_2787285_mlDf8ah974XHflVFrbQB3FM6Qxu1MT.jpg" />
    <iframe SRC="http://www.google.de"  width="400" height="250"></iframe>
</div>

CSS:

#images {
    float:right;
    width: 400px;
    height: 250px;
    position: relative;
    z-index: 1;
}

#images img {
   height:25px;
    width:25px;
    z-index=2;
    position:absolute;
    bottom:20px;
    right:20px;
}


问:
Javascript click function only selects the first element or all elements at once
I made a simple unordered list with checkboxes and want a class with strikethrough text to be applied to the li that the checkbox belongs to. The methods I've tried either only work on the first element or get applied to all of them at once.

The HTML:

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="style.css">
  <title>Document</title>
</head>
<body>
  <h1>Todo List</h1>
  <ul>
    <li>
      <input type="checkbox">
      List Item 1
    </li>
    <li>
      <input type="checkbox">
      List Item 2
    </li>
    <li>
      <input type="checkbox">
      List Item 3
    </li>
  </ul>
</body>
</html>
</code>```

The Javascript (only selects the first one):

```<code>document.querySelector("input").addEventListener("click", addStrike);

function addStrike() {
  document.querySelector("li").classList.toggle("completed");
}
</code>```

(selects all at once, when using this code I had the jquery CDN in my html)

```<code>$("li").on("click", addStrike);

function addStrike() {
  $("li").toggleClass("completed")
}
</code>```

答:
If you would rather apply the class 'completed' (and for that the style) when the check box is checked, I would recommend doing this, with jQuery:

```<code>$(".strikeCheckbox").change(function() {
    if(this.checked) {
        $(this).parent().addClass("completed")
    } else {
        $(this).parent().removeClass("completed")
    }
});
</code>```

You can change the parent function for a specific prev(...) if you want.

Body:
I made a simple unordered list with checkboxes and want a class with strikethrough text to be applied to the li that the checkbox belongs to. The methods I've tried either only work on the first element or get applied to all of them at once.

The HTML:

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="style.css">
  <title>Document</title>

Todo List

      <input type="checkbox">
      List Item 1

      <input type="checkbox">
      List Item 2

      <input type="checkbox">
      List Item 3

The Javascript (only selects the first one):

document.querySelector("input").addEventListener("click", addStrike);

function addStrike() {
  document.querySelector("li").classList.toggle("completed");
}

(selects all at once, when using this code I had the jquery CDN in my html)

$("li").on("click", addStrike);

function addStrike() {
  $("li").toggleClass("completed")
}

Body:
If you would rather apply the class 'completed' (and for that the style) when the check box is checked, I would recommend doing this, with jQuery:

$(".strikeCheckbox").change(function() {
    if(this.checked) {
        $(this).parent().addClass("completed")
    } else {
        $(this).parent().removeClass("completed")
    }
});

You can change the parent function for a specific prev(...) if you want.


Title: How to replace the value of a dataframe column with the value of another column using groupby.first()?

Body:
I have a df like this:

               Value1     Value2
2008-01-01       -1          4
2008-01-01       -1          5
2008-01-03       -1          6
2008-02-25        0          7
2008-02-26       -1          8
2008-02-27        0          9
2008-03-02        5         10
2008-03-16       -1         11
2008-03-17       -1         12
2009-04-04       -1         13
2009-04-07        0         14

I want to check the first value1 of every Year-Month. If it's < 0, I want value2 to replace with value1. How can I do that?

In this example, the result should be:

               Value1     Value2
2008-01-01       -1         -1
2008-01-01       -1          5
2008-01-03       -1          6
2008-02-25        0          7
2008-02-26       -1          8
2008-02-27        0          9
2008-03-02        5         10
2008-03-16       -1         11
2008-03-17       -1         12
2009-04-04       -1         -1
2009-04-07        0         14

Because only 2008-01, 2009-04 first value1 are negative, 2008-2, 2008-03 first value1 are positive, just leave it.

I used:

g = df.groupby([df.index.year,df.index.month])

if g['value1'].first() < 0:
   g['value1'].first() = g['value2'].first()

it doesn't seem to work. Thanks.

Body:
My approach with groupby().head() to extract the index and loc to update:

s = df.groupby(df.index.to_period('M'), as_index=False).head(1)
df.loc[s[s['Value1'].lt(0)].index, 'Value1'] = df['Value2']

Output:

            Value1  Value2
2008-01-01       5       5
2008-01-03      -1       6
2008-02-25       0       7
2008-02-26      -1       8
2008-02-27       0       9
2008-03-02       5      10
2008-03-16      -1      11
2008-03-17      -1      12
2009-04-04      13      13
2009-04-07       0      14


问:
how to iterate over array[string] in spark scala?
enter image description herehere is my sample input:

```<code>val list=List("a;bc:de;f","uvw:xy;z","123:456")
</code>```

I am applying following operation

val upper=list.map(x=>x.split(":")).map(x=>x.split(";"))

but it is throwing error-
error: value split is not a member of Array[String]

can anyone help how to use both split so that i can get answer!

Thank you in advance.

答:
Using list.map(x=>x.split(":")) will give you a list of Array.

```<code>upper: List[Array[String]] = List(Array(a;bc, de;f), Array(uvw, xy;z), Array(123, 456))
</code>```

Mapping afterwards, you can see that the item will be an array where you are trying to run split on.

You might useflatMap instead which will first give you List(a;bc, de;f, uvw, xy;z, 123, 456) and then you can use map on those items splitting on ;

```<code>val upper = list.flatMap(_.split(":")).map(_.split(";"))
</code>```

Output

```<code>upper: List[Array[String]] = List(Array(a, bc), Array(de, f), Array(uvw), Array(xy, z), Array(123), Array(456))
</code>```

Body:
enter image description herehere is my sample input:

val list=List("a;bc:de;f","uvw:xy;z","123:456")

I am applying following operation

val upper=list.map(x=>x.split(":")).map(x=>x.split(";"))

but it is throwing error-
error: value split is not a member of Array[String]

can anyone help how to use both split so that i can get answer!

Thank you in advance.

Body:
Using list.map(x=>x.split(":")) will give you a list of Array.

upper: List[Array[String]] = List(Array(a;bc, de;f), Array(uvw, xy;z), Array(123, 456))

Mapping afterwards, you can see that the item will be an array where you are trying to run split on.

You might useflatMap instead which will first give you List(a;bc, de;f, uvw, xy;z, 123, 456) and then you can use map on those items splitting on ;

val upper = list.flatMap(_.split(":")).map(_.split(";"))

Output

upper: List[Array[String]] = List(Array(a, bc), Array(de, f), Array(uvw), Array(xy, z), Array(123), Array(456))


问:
Setting the color of the Vuetify app-bar extension
I want to change the color of the v-app-bar extension so it is a different color to the v-app-bar. There seems to be nothing in the documentation but I imagine such a simple change cant be that difficult and many people would want to make this change. I have tried changing it with CSS to no avail.</p>

```<code>  <v-app-bar
    app
    extensionHeight="35px"
    class="light-blue darken-4 px-2"
  >

    // This is the part I want to appear a separate color.
    <template
      v-slot:extension
      class="extension-style"
    >
      <v-tabs align-with-title>
        <v-tab>Browsing History</v-tab>
        <v-tab>Todays Deals</v-tab>
        <v-tab>Your Store</v-tab>
        <v-tab>Gift Cards</v-tab>
        <v-tab>Registry</v-tab>
        <v-tab>Sell</v-tab>
      </v-tabs>
    </template>

  </v-app-bar>
</code>```

答:
I struggled with this for a while, but eventually succeeded in making the change through CSS because I couldn't find any help in the Vuetify Docs

In my .vue file where the v-app-bar is defined I added the following lines:

```<code><style>
div.v-toolbar__extension {
  background-color: green;
}
</style>
</code>```

I determined "div.v-toolbar__extension" was the correct element by inspecting the page through chrome, if you've defined a class or id, the name may be different.

Note: My editor automatically applied "scoped" to the "style" section. This tripped me up for a while as the CSS had no effect until I removed the scoped keyword.

Edit: If you wish to keep the "scoped" styling, the alternative would be to use:

```<code><style scoped>
/deep/ div.v-toolbar__extension {
  background-color: green;
}
</style>
</code>```

Body:
I want to change the color of the v-app-bar extension so it is a different color to the v-app-bar. There seems to be nothing in the documentation but I imagine such a simple change cant be that difficult and many people would want to make this change. I have tried changing it with CSS to no avail.

  <v-app-bar
    app
    extensionHeight="35px"
    class="light-blue darken-4 px-2"
  >

    // This is the part I want to appear a separate color.
    <template
      v-slot:extension
      class="extension-style"
    >
      <v-tabs align-with-title>
        <v-tab>Browsing History</v-tab>
        <v-tab>Todays Deals</v-tab>
        <v-tab>Your Store</v-tab>
        <v-tab>Gift Cards</v-tab>
        <v-tab>Registry</v-tab>
        <v-tab>Sell</v-tab>
      </v-tabs>
    </template>

  </v-app-bar>

Body:
I struggled with this for a while, but eventually succeeded in making the change through CSS because I couldn't find any help in the Vuetify Docs

In my .vue file where the v-app-bar is defined I added the following lines:

<style>
div.v-toolbar__extension {
  background-color: green;
}
</style>

I determined "div.v-toolbar__extension" was the correct element by inspecting the page through chrome, if you've defined a class or id, the name may be different.

Note: My editor automatically applied "scoped" to the "style" section. This tripped me up for a while as the CSS had no effect until I removed the scoped keyword.

Edit: If you wish to keep the "scoped" styling, the alternative would be to use:

<style scoped>
/deep/ div.v-toolbar__extension {
  background-color: green;
}
</style>


答:
You need to select all the checkboxes, loop over them, and attach the event.

function cbClicked (event) {
  // reference the checkbox
  var cb = event.target
  // find it was checked
  var isChecked = cb.checked
  cb.closest("li")  // find the parent li
    .classList.toggle("done", isChecked) // toggle the class
}

// Select all the checkboxes
var checkboxes = document.querySelectorAll('ul input[type="checkbox"]')

// loop over all the checkboxes
checkboxes.forEach( function (cb) {
  // attach the event listener to each one
  cb.addEventListener("change", cbClicked)
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.done {
  text-decoration: line-through;
}</code>```

      <input type="checkbox">
      List Item 1

      <input type="checkbox">
      List Item 2

      <input type="checkbox">
      List Item 3

```
</div>
</div>
</p>

<p>If you want to use jQuery it is similar, jQuery just does the looping for you</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function cbClicked (event) {
  // reference the checkbox
  var cb = this
  var isChecked = this.checked
  $(cb).closest("li")  // find the parent li
    .toggleClass("done", isChecked) // toggle the class
}

// Select all the checkboxes
var checkboxes = $('ul input[type="checkbox"]').on("change", cbClicked)</code>```

.done {
  text-decoration: line-through;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
    <li>
      <input type="checkbox">
      List Item 1
    </li>
    <li>
      <input type="checkbox">
      List Item 2
    </li>
    <li>
      <input type="checkbox">
      List Item 3
    </li>
  </ul></code>```

And it can be done with Just CSS

input:checked + label {
  text-decoration: line-through;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
    <li>
      <input type="checkbox" id="cb1">
      <label for="cb1">List Item 1</label>
    </li>
    <li>
      <input type="checkbox" id="c2">
      <label for="cb2">List Item 2</label>
    </li>
    <li>
      <input type="checkbox" id="cb3">
      <label for="cb3">List Item 3</label>
    </li>
  </ul></code>```

Title: Javascript click function only selects the first element or all elements at once

Body:
You need to select all the checkboxes, loop over them, and attach the event.

function cbClicked (event) {
  // reference the checkbox
  var cb = event.target
  // find it was checked
  var isChecked = cb.checked
  cb.closest("li")  // find the parent li
    .classList.toggle("done", isChecked) // toggle the class
}

// Select all the checkboxes
var checkboxes = document.querySelectorAll('ul input[type="checkbox"]')

// loop over all the checkboxes
checkboxes.forEach( function (cb) {
  // attach the event listener to each one
  cb.addEventListener("change", cbClicked)
})

.done {
  text-decoration: line-through;
}

<ul>
    <li>
      <input type="checkbox">
      List Item 1
    </li>
    <li>
      <input type="checkbox">
      List Item 2
    </li>
    <li>
      <input type="checkbox">
      List Item 3
    </li>
  </ul>

If you want to use jQuery it is similar, jQuery just does the looping for you

function cbClicked (event) {
  // reference the checkbox
  var cb = this
  var isChecked = this.checked
  $(cb).closest("li")  // find the parent li
    .toggleClass("done", isChecked) // toggle the class
}

// Select all the checkboxes
var checkboxes = $('ul input[type="checkbox"]').on("change", cbClicked)

.done {
  text-decoration: line-through;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
    <li>
      <input type="checkbox">
      List Item 1
    </li>
    <li>
      <input type="checkbox">
      List Item 2
    </li>
    <li>
      <input type="checkbox">
      List Item 3
    </li>
  </ul>

And it can be done with Just CSS

input:checked + label {
  text-decoration: line-through;
}

<ul>
    <li>
      <input type="checkbox" id="cb1">
      <label for="cb1">List Item 1</label>
    </li>
    <li>
      <input type="checkbox" id="c2">
      <label for="cb2">List Item 2</label>
    </li>
    <li>
      <input type="checkbox" id="cb3">
      <label for="cb3">List Item 3</label>
    </li>
  </ul>


问:
Error when rendering html/css code to pdf with dompdf or tcpd
By entering the html / css code to the function of dompdf, this prints a wrong pdf, where all the text is overwritten on the same line and makes nonsense page breaks

I tried to print the same html with tcpdf and other applications without getting the expected results, all the words are always rendered in the same line, and the css is not shown

This is the the c ode html of what i want to print in pdf

This is my file controller to print the PDF

```<code>namespace App\Http\Controllers;

use App\Files;
use Illuminate\Http\Request;
use Elibyy\TCPDF\Facades\TCPDF;
use Dompdf\Dompdf;

public function index()
{
    header('Content-type: application/pdf');
    http_response_code(200);
    include 'l_vars/planilla_solicitud_logistica.php';

   $dompdf = new Dompdf();
   $dompdf->set_option('isHtml5ParserEnabled', true);
   $dompdf->loadHtml($planilla);
   $dompdf->render();
   $dompdf->stream();
}
</code>```

This is the html code of the spreadsheet that I want to process in a pdf, this information must be dynamic since it will feed from the database

```

                Solicitud de Logistica de Viajes

                    Codigo: SPS-FAD-007

                        Edicion: 1

                        Revision: 0

                    Pag 1 de 2

                    Fecha 17/10/2018

            Datos del Solicitante

Nombre y Apellido del Solicitante

 Eleazar Ortega

Cedula de Identidad

 V. 20.616.897

Unidad o Area

 IT

Sede

 Chuao

Fecha de Solicitud

 01/01/2023

            NACIONAL (VENEZUELA)

Traslado en Vehiculo de la Empresa

                    Motivo del Viaje

Traslado a Aeropuerto

            Tipo de Traslado

            Traslado Terrestre Nacional (Venezuela)

Fecha de Salida:  01/01/2023

Hora:  10:00

Origen y/o Direccion

Tiempo de Espera

Destino y/o Direccion

Fecha de Retorno:  01/01/2023

Hora:  10:00

Fecha de Salida:  01/01/2023

Hora:  10:00

Origen y/o Direccion

Tiempo de Espera

Destino y/o Direccion

Fecha de Retorno:  01/01/2023

Hora:  10:00

Fecha de Salida:  01/01/2023

Hora:  10:00

Origen y/o Direccion

Tiempo de Espera

Destino y/o Direccion

Fecha de Retorno:  01/01/2023

Hora:  10:00

            Traslado Terrestre Urbano (Venezuela)

Fecha de Salida:  01/01/2023

Hora:  10:00

Origen y/o Direccion

Tiempo de Espera

Destino y/o Direccion

Fecha de Retorno:  01/01/2023

Hora:  10:00

Fecha de Salida:  01/01/2023

Hora:  10:00

Origen y/o Direccion

Tiempo de Espera

Destino y/o Direccion

Fecha de Retorno:  01/01/2023

Hora:  10:00

Fecha de Salida:  01/01/2023

Hora:  10:00

Origen y/o Direccion

Tiempo de Espera

Destino y/o Direccion

Fecha de Retorno:  01/01/2023

Hora:  10:00

            Traslado Terrestre Urbano (Venezuela)

Fecha de Salida:  01/01/2023

Hora:  10:00

Origen

Destino

Fecha de Retorno:  01/01/2023

Hora:  10:00

Fecha de Salida:  01/01/2023

Hora:  10:00

Origen

Destino

Fecha de Retorno:  01/01/2023

Hora:  10:00

Fecha de Salida:  01/01/2023

Hora:  10:00

Origen

Destino

Fecha de Retorno:  01/01/2023

Hora:  10:00

            Hospedaje

Fecha de Entrada:  01/01/2023

Fecha de Salida:  01/01/2023

Lugar o Ciudad: Cabimas Hotel Europa

Fecha de Entrada:  01/01/2023

Fecha de Salida:  01/01/2023

Lugar o Ciudad: Cabimas Hotel Europa

Fecha de Entrada:  01/01/2023

Fecha de Salida:  01/01/2023

Lugar o Ciudad: Cabimas Hotel Europa

            Observaciones

                Aprobado Por

                Recibido Por

Nombre y Apellido del Supervisor Inmeadiato

 Nombre y Apellido

Cargo

Firma

                Control y Gestion de Calidad

                Departamento de Reservaciones

                Junta Directiva

                Nombre:

                Fecha:

                Firma:

                Nombre:

                Fecha:

                Firma:

                Nombre:

                Fecha:

                Firma:

```

Me gustaria saber que esta ocasionando el error de manera que pueda imprimir una planilla pdf,

答: "display : flex" isn't supported in dompdf library</p>

Body:
By entering the html / css code to the function of dompdf, this prints a wrong pdf, where all the text is overwritten on the same line and makes nonsense page breaks

I tried to print the same html with tcpdf and other applications without getting the expected results, all the words are always rendered in the same line, and the css is not shown

This is the the c ode html of what i want to print in pdf

This is my file controller to print the PDF

namespace App\Http\Controllers;

use App\Files;
use Illuminate\Http\Request;
use Elibyy\TCPDF\Facades\TCPDF;
use Dompdf\Dompdf;

public function index()
{
    header('Content-type: application/pdf');
    http_response_code(200);
    include 'l_vars/planilla_solicitud_logistica.php';

   $dompdf = new Dompdf();
   $dompdf->set_option('isHtml5ParserEnabled', true);
   $dompdf->loadHtml($planilla);
   $dompdf->render();
   $dompdf->stream();
}

This is the html code of the spreadsheet that I want to process in a pdf, this information must be dynamic since it will feed from the database

                Solicitud de Logistica de Viajes

                    Codigo: SPS-FAD-007

                        Edicion: 1

                        Revision: 0

                    Pag 1 de 2

                    Fecha 17/10/2018

            Datos del Solicitante

Nombre y Apellido del Solicitante

 Eleazar Ortega

Cedula de Identidad

 V. 20.616.897

Unidad o Area

 IT

Sede

 Chuao

Fecha de Solicitud

 01/01/2023

            NACIONAL (VENEZUELA)

Traslado en Vehiculo de la Empresa

                    Motivo del Viaje

Traslado a Aeropuerto

            Tipo de Traslado

            Traslado Terrestre Nacional (Venezuela)

Fecha de Salida:  01/01/2023

Hora:  10:00

Origen y/o Direccion

Tiempo de Espera

Destino y/o Direccion

Fecha de Retorno:  01/01/2023

Hora:  10:00

Fecha de Salida:  01/01/2023

Hora:  10:00

Origen y/o Direccion

Tiempo de Espera

Destino y/o Direccion

Fecha de Retorno:  01/01/2023

Hora:  10:00

Fecha de Salida:  01/01/2023

Hora:  10:00

Origen y/o Direccion

Tiempo de Espera

Destino y/o Direccion

Fecha de Retorno:  01/01/2023

Hora:  10:00

            Traslado Terrestre Urbano (Venezuela)

Fecha de Salida:  01/01/2023

Hora:  10:00

Origen y/o Direccion

Tiempo de Espera

Destino y/o Direccion

Fecha de Retorno:  01/01/2023

Hora:  10:00

Fecha de Salida:  01/01/2023

Hora:  10:00

Origen y/o Direccion

Tiempo de Espera

Destino y/o Direccion

Fecha de Retorno:  01/01/2023

Hora:  10:00

Fecha de Salida:  01/01/2023

Hora:  10:00

Origen y/o Direccion

Tiempo de Espera

Destino y/o Direccion

Fecha de Retorno:  01/01/2023

Hora:  10:00

            Traslado Terrestre Urbano (Venezuela)

Fecha de Salida:  01/01/2023

Hora:  10:00

Origen

Destino

Fecha de Retorno:  01/01/2023

Hora:  10:00

Fecha de Salida:  01/01/2023

Hora:  10:00

Origen

Destino

Fecha de Retorno:  01/01/2023

Hora:  10:00

Fecha de Salida:  01/01/2023

Hora:  10:00

Origen

Destino

Fecha de Retorno:  01/01/2023

Hora:  10:00

            Hospedaje

Fecha de Entrada:  01/01/2023

Fecha de Salida:  01/01/2023

Lugar o Ciudad: Cabimas Hotel Europa

Fecha de Entrada:  01/01/2023

Fecha de Salida:  01/01/2023

Lugar o Ciudad: Cabimas Hotel Europa

Fecha de Entrada:  01/01/2023

Fecha de Salida:  01/01/2023

Lugar o Ciudad: Cabimas Hotel Europa

            Observaciones

                Aprobado Por

                Recibido Por

Nombre y Apellido del Supervisor Inmeadiato

 Nombre y Apellido

Cargo

Firma

                Control y Gestion de Calidad

                Departamento de Reservaciones

                Junta Directiva

                Nombre:

                Fecha:

                Firma:

                Nombre:

                Fecha:

                Firma:

                Nombre:

                Fecha:

                Firma:

Me gustaria saber que esta ocasionando el error de manera que pueda imprimir una planilla pdf,


问:
How to get Min String Length, Greater Than 0, in every Column of a Datatable
I checked this page already = How to get Max String Length in every Column of a Datatable

I have a .NET DataTable (loaded from flat files, 50+ columns, 500K records). All columns are String type. Column can have NULL or Empty value. I want the Min Length of each column of the datatable where Length>0 (excluding the NULL or Empty values ).

in SQL the query would be (for single column) = select MIN(LEN(Field))  [MinLen] from MyDataTable where len(Field) > 0

I can run "foreach DataColumn" and get individual column's MinLength but takes time. Would like to get all the MinValues > 0 in one shot, if possible. Thanks.

答:
Hey, this is solution:

```<code>private void AddNullAllowedColumn()
{
    DataColumn column;
    column = new DataColumn("classID",
        System.Type.GetType("System.Int32"));
    column.AllowDBNull = false;// this is solution

    DataTable table;
    table = new DataTable();
    table.Columns.Add(column);
}
</code>```

Body:
Hey, this is solution:

private void AddNullAllowedColumn()
{
    DataColumn column;
    column = new DataColumn("classID",
        System.Type.GetType("System.Int32"));
    column.AllowDBNull = false;// this is solution

    DataTable table;
    table = new DataTable();
    table.Columns.Add(column);
}


问:
Unable to get data using ReactNative fetch
I'm trying to fetch data from an API(I created my own Rest API using JSON-server). But I'm unable to fetch anything. however, I'm able to see the data when I navigate to localhost:3000/events. There's no other error in my app. I only get this when I run the app it says network request failed. All the components are working fine. Just not getting the data. I've tried some other online APIs still not getting any response. I've tried with async/await. I'm using the app with IOS but have tried with Andriod as well. Same problem occurs. Attaching the code snippets. Any help would be highly appreciated. Thanks

Created the getEvent Function:

```<code>const { manifest } = Constants;
const api = manifest.packagerOpts.dev
  ? manifest.debuggerHost.split(`:`).shift().concat(`:3000`)
  : `api.example.com`;

const url = `http://${api}/events`;

export function getEvents() {
  return fetch(url)
  .then(response => response.json())
  .then(events => events.map(e => ({ ...e, date: new Date(e.date) })))
}
</code>```

Using it inside the componentDidMount

```<code>componentDidMount() {
    // getEvents().then(events => this.setState({ events }));

    setInterval(() => {
      this.setState({
        events: this.state.events.map(evt => ({
          ...evt,
          timer: Date.now()
        }))
      });
    }, 1000);

    this.props.navigation.addListener("didFocus", () => {
      getEvents().then(events => this.setState({ events }));
    });
  }
</code>```

Data that I'm trying to fetch.

```<code>{
  "events": [
    {
      "title": "Demo a new app",
      "date": "2020-03-29T13:45:18.000Z",
      "id": "001c9b6d-00a9-465c-a2d3-afb7176a0a87"
    }
  ]
}
</code>```

答:
you can use axios as of fetch , it is also used to hit API's and get response from them , and it is simple and easy way as compare to fetch.

run npm i react-native-axios on your project root floder to install the library and import it and use it , here is an example of axios , in which the user will login to screen and will hit the login API , the user enter their credentials and if they are correct as in API then user will get response or user will login successfully.

```<code>    import axios from "axios";
export default class Login extends Component {
  constructor(props) {
    super(props);
    this.state = {
      email: "",
      password: "",
      }
  };

  onPresssighnin = () => {
      var data = {
       //parameters to pass API
        Email: this.state.email,
        Password: this.state.password,
      };
      axios
        .post(" insert API url here", data, {
          "Content-Type": "application/json"
        })
        .then(
          response => {
           //get response here
            alert(JSON.stringify(response))
                      },
          error => {
            //get errormessage here
            errormessage = error.Message;
            alert(errormessage);
          }
        );
    }
  };
  render() {
      return (
              <View style={styles.logoContainer}>
             <Input
                    borderless
                    placeholder="Email"
                    onChangeText={email => this.setState({ email })}
                    iconContent={
                      <Icon
                        size={16}
                        color={ditsTheme.COLORS.ICON}
                        name="ic_mail_24px"
                        family="DitsExtra"
                        style={styles.inputIcons}
                      />
                    }
                  />
                  <Input
                    password
                    borderless
                    placeholder="Password"
                    onChangeText={password =>this.setState({ password })}
                    iconContent={
                      <Icon
                        size={16}
                        color={ditsTheme.COLORS.ICON}
                        name="padlock-unlocked"
                        family="DitsExtra"
                        style={styles.inputIcons}
                      />
                    }
                  />

                    <Button
                      color="primary"
                      style={styles.createButton}
                      onPress={this.onPresssighnin} >
                      <Text bold size={14} color={ditsTheme.COLORS.WHITE}>
                        SIGN IN
                      </Text>
                    </Button>
              </View>
      )
    }
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'rgb(32, 53, 70)',
    flexDirection: 'column',
  },
    buttonText: {
    textAlign: 'center',
    color: 'rgb(32, 53, 70)',
    fontWeight: 'bold',
    fontSize: 18
  }
})
</code>```

Feel free for Doubts.

Body:
I'm trying to fetch data from an API(I created my own Rest API using JSON-server). But I'm unable to fetch anything. however, I'm able to see the data when I navigate to localhost:3000/events. There's no other error in my app. I only get this when I run the app it says network request failed. All the components are working fine. Just not getting the data. I've tried some other online APIs still not getting any response. I've tried with async/await. I'm using the app with IOS but have tried with Andriod as well. Same problem occurs. Attaching the code snippets. Any help would be highly appreciated. Thanks

Created the getEvent Function:

const { manifest } = Constants;
const api = manifest.packagerOpts.dev
  ? manifest.debuggerHost.split(`:`).shift().concat(`:3000`)
  : `api.example.com`;

const url = `http://${api}/events`;

export function getEvents() {
  return fetch(url)
  .then(response => response.json())
  .then(events => events.map(e => ({ ...e, date: new Date(e.date) })))
}

Using it inside the componentDidMount

componentDidMount() {
    // getEvents().then(events => this.setState({ events }));

    setInterval(() => {
      this.setState({
        events: this.state.events.map(evt => ({
          ...evt,
          timer: Date.now()
        }))
      });
    }, 1000);

    this.props.navigation.addListener("didFocus", () => {
      getEvents().then(events => this.setState({ events }));
    });
  }

Data that I'm trying to fetch.

{
  "events": [
    {
      "title": "Demo a new app",
      "date": "2020-03-29T13:45:18.000Z",
      "id": "001c9b6d-00a9-465c-a2d3-afb7176a0a87"
    }
  ]
}

Body:
you can use axios as of fetch , it is also used to hit API's and get response from them , and it is simple and easy way as compare to fetch.

run npm i react-native-axios on your project root floder to install the library and import it and use it , here is an example of axios , in which the user will login to screen and will hit the login API , the user enter their credentials and if they are correct as in API then user will get response or user will login successfully.

    import axios from "axios";
export default class Login extends Component {
  constructor(props) {
    super(props);
    this.state = {
      email: "",
      password: "",
      }
  };

  onPresssighnin = () => {
      var data = {
       //parameters to pass API
        Email: this.state.email,
        Password: this.state.password,
      };
      axios
        .post(" insert API url here", data, {
          "Content-Type": "application/json"
        })
        .then(
          response => {
           //get response here
            alert(JSON.stringify(response))
                      },
          error => {
            //get errormessage here
            errormessage = error.Message;
            alert(errormessage);
          }
        );
    }
  };
  render() {
      return (
              <View style={styles.logoContainer}>
             <Input
                    borderless
                    placeholder="Email"
                    onChangeText={email => this.setState({ email })}
                    iconContent={
                      <Icon
                        size={16}
                        color={ditsTheme.COLORS.ICON}
                        name="ic_mail_24px"
                        family="DitsExtra"
                        style={styles.inputIcons}
                      />
                    }
                  />
                  <Input
                    password
                    borderless
                    placeholder="Password"
                    onChangeText={password =>this.setState({ password })}
                    iconContent={
                      <Icon
                        size={16}
                        color={ditsTheme.COLORS.ICON}
                        name="padlock-unlocked"
                        family="DitsExtra"
                        style={styles.inputIcons}
                      />
                    }
                  />

                    <Button
                      color="primary"
                      style={styles.createButton}
                      onPress={this.onPresssighnin} >
                      <Text bold size={14} color={ditsTheme.COLORS.WHITE}>
                        SIGN IN
                      </Text>
                    </Button>
              </View>
      )
    }
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'rgb(32, 53, 70)',
    flexDirection: 'column',
  },
    buttonText: {
    textAlign: 'center',
    color: 'rgb(32, 53, 70)',
    fontWeight: 'bold',
    fontSize: 18
  }
})

Feel free for Doubts.


问:
How do you stop a thead background color from leaking when there are rounded corners?
I have a table with rounded corners. I've specified a different background colour only for the thead.

On all browsers other than Firefox, the background colour leaks through the rounded corner. I've set overflow to hidden but that doesn't seem to help.

How can I stop the background colour from leaking through the rounded corner of the table?

Here's the code:
https://codepen.io/ayushn21/pen/OJVRMgG

Thanks!

答:
You could add border-top-left-radius:10px; and border-top-right-radius:10px; to the first/last th cells.

You might also want to add background-clip:padding-box; to those cells, if it's still happening.

I found these tricks in this CSS-tricks article.


问:
Oracle returns wrong values with LENGTH and INSTR
I'm aiming to retrieve the position of chars in a string, plus the length of a string.

The value of the notes field in the  internal_notes table, for the row with ticket_id equal to 1679467247 is literally 'this is a test note'.

When I use the functions against the literal stirngs they work, but when I retrieve the info directly from the table column, the values are just wrong.

Any ideas as to what might be happening?

select notes,
       LENGTH(notes),
       INSTR(notes,' ')
FROM   internal_notes
where  ticket_id = 1679467247

union

select 'this is a test note',
       LENGTH('this is a test note'),
       INSTR('this is a test note',' ')
from   dual
```

<p>This returns the following:</p>

```NOTES               LENGTH(NOTES) INSTR(NOTES,' ')
------------------- ------------- ----------------
this is a test note            32                11
this is a test note            19                5
```

答:
You can get this apparent inconsistency if you have zero-width characters in the value; for example:

```<code>create table internal_notes(ticket_id number, notes varchar2(32 char));
insert into internal_notes(ticket_id, notes)
values (1679467247, unistr('\200c\200cthis is a test note\200c\200c\200c\200c\200c\200c\200c\200c\200c\200c\200c'));
insert into internal_notes(ticket_id, notes)
values (1679467248, unistr('\200c\200cthis is a test note'));
insert into internal_notes(ticket_id, notes)
values (1679467249, 'this is a test note');

select notes,
       LENGTH(notes),
       INSTR(notes,' ')
FROM   internal_notes
where  ticket_id = 1679467247;

NOTES                            LENGTH(NOTES) INSTR(NOTES,'')
-------------------------------- ------------- ---------------
this is a test note                         32               7
</code>```

I said 'apparent inconsistency' because those numbers are correct; they just don't look it if you can't see some of the characters. Invisible characters still count.

As @MTO suggested you can use the dump() function to see exactly what is stored in the table, in decimal or hex representation, or mixed with 'normal' characters which can be a bit easier to interpret:

```<code>select notes,
       LENGTH(notes),
       INSTR(notes,' '),
       dump(notes, 1000) as dmp
FROM   internal_notes;

NOTES                            LENGTH(NOTES) INSTR(NOTES,'')
-------------------------------- ------------- ---------------
DMP
----------------------------------------------------------------------------------------------------------------------------------------------------------------------
this is a test note                         32               7
Typ=1 Len=58: e2,80,8c,e2,80,8c,t,h,i,s, ,i,s, ,a, ,t,e,s,t, ,n,o,t,e,e2,80,8c,e2,80,8c,e2,80,8c,e2,80,8c,e2,80,8c,e2,80,8c,e2,80,8c,e2,80,8c,e2,80,8c,e2,80,8c,e2,80,
8c

this is a test note                         21               7
Typ=1 Len=25: e2,80,8c,e2,80,8c,t,h,i,s, ,i,s, ,a, ,t,e,s,t, ,n,o,t,e

this is a test note                         19               5
Typ=1 Len=19: t,h,i,s, ,i,s, ,a, ,t,e,s,t, ,n,o,t,e
</code>```

db<>fiddle - though that is showing the zero-width characters as question marks, unlike SQL Developer and SQL*Plus.

Other zero-width characters are available (space, non-joiner, joiner), and you might see something different in your dump - it just has to be something your client doesn't display at all. Whatever is in there, if it affects all rows and not just that single ticket, then how and why is probably down to whatever front-end/application populates the table - possibly from a character set mismatch, but it could be intentional. If it is just that ticket then that note is an interesting test...

Body:
I'm aiming to retrieve the position of chars in a string, plus the length of a string.

The value of the notes field in the  internal_notes table, for the row with ticket_id equal to 1679467247 is literally 'this is a test note'.

When I use the functions against the literal stirngs they work, but when I retrieve the info directly from the table column, the values are just wrong.

Any ideas as to what might be happening?

select notes,
       LENGTH(notes),
       INSTR(notes,' ')
FROM   internal_notes
where  ticket_id = 1679467247

union

select 'this is a test note',
       LENGTH('this is a test note'),
       INSTR('this is a test note',' ')
from   dual

This returns the following:

NOTES               LENGTH(NOTES) INSTR(NOTES,' ')
------------------- ------------- ----------------
this is a test note            32                11
this is a test note            19                5

Body:
You can get this apparent inconsistency if you have zero-width characters in the value; for example:

create table internal_notes(ticket_id number, notes varchar2(32 char));
insert into internal_notes(ticket_id, notes)
values (1679467247, unistr('\200c\200cthis is a test note\200c\200c\200c\200c\200c\200c\200c\200c\200c\200c\200c'));
insert into internal_notes(ticket_id, notes)
values (1679467248, unistr('\200c\200cthis is a test note'));
insert into internal_notes(ticket_id, notes)
values (1679467249, 'this is a test note');

select notes,
       LENGTH(notes),
       INSTR(notes,' ')
FROM   internal_notes
where  ticket_id = 1679467247;

NOTES                            LENGTH(NOTES) INSTR(NOTES,'')
-------------------------------- ------------- ---------------
this is a test note                         32               7

I said 'apparent inconsistency' because those numbers are correct; they just don't look it if you can't see some of the characters. Invisible characters still count.

As @MTO suggested you can use the dump() function to see exactly what is stored in the table, in decimal or hex representation, or mixed with 'normal' characters which can be a bit easier to interpret:

select notes,
       LENGTH(notes),
       INSTR(notes,' '),
       dump(notes, 1000) as dmp
FROM   internal_notes;

NOTES                            LENGTH(NOTES) INSTR(NOTES,'')
-------------------------------- ------------- ---------------
DMP
----------------------------------------------------------------------------------------------------------------------------------------------------------------------
this is a test note                         32               7
Typ=1 Len=58: e2,80,8c,e2,80,8c,t,h,i,s, ,i,s, ,a, ,t,e,s,t, ,n,o,t,e,e2,80,8c,e2,80,8c,e2,80,8c,e2,80,8c,e2,80,8c,e2,80,8c,e2,80,8c,e2,80,8c,e2,80,8c,e2,80,8c,e2,80,
8c

this is a test note                         21               7
Typ=1 Len=25: e2,80,8c,e2,80,8c,t,h,i,s, ,i,s, ,a, ,t,e,s,t, ,n,o,t,e

this is a test note                         19               5
Typ=1 Len=19: t,h,i,s, ,i,s, ,a, ,t,e,s,t, ,n,o,t,e

db<>fiddle - though that is showing the zero-width characters as question marks, unlike SQL Developer and SQL*Plus.

Other zero-width characters are available (space, non-joiner, joiner), and you might see something different in your dump - it just has to be something your client doesn't display at all. Whatever is in there, if it affects all rows and not just that single ticket, then how and why is probably down to whatever front-end/application populates the table - possibly from a character set mismatch, but it could be intentional. If it is just that ticket then that note is an interesting test...