问:
Bootstrap Grid System - To much empty space
I want to make a Layout like this when the screen ist large:

A | B1

A | B2

C | B3

C | B4

When the screen is small i want like this:

A

A

B1

B2

B3

B4

C

C

With my solution the small screen layout is ok. But on large screen is like this:

A | B1

A | B2

* | B3

* | B4

C

C

= this is empty space. I want C is direct below A for large screen. A than B than C for small screen

See in picture:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />

A

          ...

B

B1

              ...

B2

              ...

B3

              ...

B4

              ...

B5

              ...

c

          ...

```

答:
Use provided .col-*-push-* and .col-*-pull-* utility classes:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />

A

A

B1

B2

B3

B4

C

C

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

<p>Note Bootstrap is mobile first. You need to put them into <em>normal</em> order on mobile and <code>pull</code>/<code>push</code> on larger sizes. </p>

<p>To reset a pull or push on a larger size you need to specify a push/pull of 0 on the larger size. For example, the following only pushes on <code>sm</code> but stops pushing on <code>md</code> and above, allowing B's to group in center on larger screen sizes:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />

<div class="container">
  <div class="row">
    <div class="col-sm-6 col-md-3">
      <div>A</div>
      <div>A</div>
    </div>
    <div class="col-sm-6  col-md-3">
      <div>B1</div>
      <div>B2</div>
    </div>
    <div class="col-sm-6 col-sm-push-6 col-md-3 col-md-push-0">
      <div>B3</div>
      <div>B4</div>
    </div>
    <div class="col-sm-6 col-sm-pull-6 col-md-3 col-md-pull-0">
      <div>C</div>
      <div>C</div>
    </div>
  </div>
</div></code>```

After update, it looks like you are looking for a masonry layout but didn't formulate as such. Bootstrap cannot produce this layout by itself, so you need to use an extra library. Common options are Masonry, Isotope and Bootstrap Waterfall.

Here's how to use Masonry on Bootstrap .col-s and keep it from breaking your layout on small widths:

Load jQuery (js)

Load Bootstrap (css + js)

Load Masonry (js)

Place each of A's B's and C's in distinct .col-*-* of the same .row parent while adding a specific class to that row (I used masonry here).

Place col-xs-12 on each of your col-*-*s. If you don't do this, masonry will display them as columns, side by side, below the breaking point, if the content allows it.

On window.load event, run $('.masonry').masonry() (replace .masonry selector with your own, if you used a different class name on parent .row).

$(window).load(function(){
  $('.masonry').masonry();
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* you don't really need CSS for this to work
 * code below is aimed more at making the snippet look good on SO
 */

.a-s {background-color: rgba(255,255,0,.07);}
.b-s {background-color: rgba(255,0,0,.07);}
.c-s {background-color: rgba(0,0,255,.07);}

.body {
  overflow-x:hidden;
  margin: 0;
}
.masonry {
  overflow-x: hidden;
  min-height: 100vh;
}</code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

A

A

B1

B2

B3

B4

B5

B6

C

C

```

Note I don't necessarily recommend Masonry. I personally prefer Bootstrap Waterfall (it's closer to the Pinterest script) but it's not as easy to use as Masonry. I know for a fact Isotope is also a very solid and reliable option but I didn't have the chance to use it as of yet.

Body:
Use provided .col-*-push-* and .col-*-pull-* utility classes:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />

<div class="container">
  <div class="row">
    <div class="col-md-6">
      <div>A</div>
      <div>A</div>
    </div>
    <div class="col-md-6">
      <div>B1</div>
      <div>B2</div>
    </div>
    <div class="col-md-6 col-md-push-6">
      <div>B3</div>
      <div>B4</div>
    </div>
    <div class="col-md-6 col-md-pull-6">
      <div>C</div>
      <div>C</div>
    </div>
  </div>
</div>

Note Bootstrap is mobile first. You need to put them into normal order on mobile and pull/push on larger sizes.

To reset a pull or push on a larger size you need to specify a push/pull of 0 on the larger size. For example, the following only pushes on sm but stops pushing on md and above, allowing B's to group in center on larger screen sizes:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />

<div class="container">
  <div class="row">
    <div class="col-sm-6 col-md-3">
      <div>A</div>
      <div>A</div>
    </div>
    <div class="col-sm-6  col-md-3">
      <div>B1</div>
      <div>B2</div>
    </div>
    <div class="col-sm-6 col-sm-push-6 col-md-3 col-md-push-0">
      <div>B3</div>
      <div>B4</div>
    </div>
    <div class="col-sm-6 col-sm-pull-6 col-md-3 col-md-pull-0">
      <div>C</div>
      <div>C</div>
    </div>
  </div>
</div>

After update, it looks like you are looking for a masonry layout but didn't formulate as such. Bootstrap cannot produce this layout by itself, so you need to use an extra library. Common options are Masonry, Isotope and Bootstrap Waterfall.

Here's how to use Masonry on Bootstrap .col-s and keep it from breaking your layout on small widths:

Load jQuery (js)

Load Bootstrap (css + js)

Load Masonry (js)

Place each of A's B's and C's in distinct .col-*-* of the same .row parent while adding a specific class to that row (I used masonry here).

Place col-xs-12 on each of your col-*-*s. If you don't do this, masonry will display them as columns, side by side, below the breaking point, if the content allows it.

On window.load event, run $('.masonry').masonry() (replace .masonry selector with your own, if you used a different class name on parent .row).

$(window).load(function(){
  $('.masonry').masonry();
})

/* you don't really need CSS for this to work
 * code below is aimed more at making the snippet look good on SO
 */

.a-s {background-color: rgba(255,255,0,.07);}
.b-s {background-color: rgba(255,0,0,.07);}
.c-s {background-color: rgba(0,0,255,.07);}

.body {
  overflow-x:hidden;
  margin: 0;
}
.masonry {
  overflow-x: hidden;
  min-height: 100vh;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/masonry/4.2.0/masonry.pkgd.min.js"></script>

<div class="container">
  <div class="row masonry">
    <div class="col-md-6 col-xs-12 a-s">
      <div>A</div>
      <div>A</div>
    </div>
    <div class="col-md-6 col-xs-12 b-s">
      <div>B1</div>
      <div>B2</div>
      <div>B3</div>
      <div>B4</div>
      <div>B5</div>
      <div>B6</div>
    </div>
    <div class="col-md-6 col-xs-12 c-s">
      <div>C</div>
      <div>C</div>
    </div>
  </div>
</div>

Note I don't necessarily recommend Masonry. I personally prefer Bootstrap Waterfall (it's closer to the Pinterest script) but it's not as easy to use as Masonry. I know for a fact Isotope is also a very solid and reliable option but I didn't have the chance to use it as of yet.


来源: stackexchange

问:
Accessing Parent object in Child serializer in ActiveModelSerializers
Presenting a hypothetical, simplified version of my problem. Imagine I have a website where users can create a Shop with their own branding and choose from a catalog of Products to show in their Shop. Shops & Products have a has-and-belongs-to-many (HABTM) relationship. Each Product has its own Shop-specific route.

```<code>Rails.application.routes.draw do
  resources :shops do
    resources :products
  end
end

class ShopSerializer < ActiveModel::Serializer
  has_many :products
end

class ProductSerializer < ActiveModel::Serializer
  include Rails.application.routes.url_helpers

  attribute :url do
    shop_product_url(NEED SHOP ID, product_id: object.id)
  end
end
</code>```

When a Shop is serialized, and as a result, so is the collection of its Products, I want the Product serializer to be aware of the shop that is serializing it and use that to include the route in the serialized output. How is this possible? I've tried all manner of passing instance_options from the ShopSerializer but it doesn't work as expected.

```<code># this works except is apparently not threadsafe as multiple
# concurrent requests lead to the wrong shop_id being used
# in some of the serialized data
has_many :products do
  ActiveModelSerializers::SerializableResource.new(shop_id: object.id).serializable_hash
end

# shop_id isn't actually available in instance_options
has_many :products do
  ProductSerializer.new(shop_id: object.id)
end
</code>```

答:
Unfortunately serializer associations do not seem to provide a clean way to pass in custom attributes to the child serializers. There are a few not-so-pretty solutions though.

1. Invoke ProductSerializer manually, add URL in ShopSerializer

```<code>class ProductSerializer < ActiveModel::Serializer
end

class ShopSerializer < ActiveModel::Serializer
  include Rails.application.routes.url_helpers

  attribute :products do
    object.products.map do |product|
      ProductSerializer.new(product).serializable_hash.merge(
        url: shop_product_url(object.id, product_id: product.id)
      )
    end
  end
end
</code>```

2. Add shop ID to the Product instances before they are fed to ProductSerializer

```<code>class ProductSerializer < ActiveModel::Serializer
  include Rails.application.routes.url_helpers

  attribute :url do
    shop_product_url(object.shop_id, product_id: object.id)
  end
end

class ShopSerializer < ActiveModel::Serializer
  has_many :products, serializer: ProductSerializer do
    shop = object
    shop.products.map do |product|
      product.dup.tap do |instance|
        instance.singleton_class.send :define_method, :shop_id do
          shop.id
        end
      end
    end
  end
end
</code>```

Both solutions should be thread safe, but the first solution seems like a better idea to me, as the second one makes ProductSerializer unusable on its own — i.e. when just a single Product is serialized without knowing the particular shop it should belong to.

ContentLicense: CC BY-SA 3.0

Body:
Presenting a hypothetical, simplified version of my problem. Imagine I have a website where users can create a Shop with their own branding and choose from a catalog of Products to show in their Shop. Shops & Products have a has-and-belongs-to-many (HABTM) relationship. Each Product has its own Shop-specific route.

Rails.application.routes.draw do
  resources :shops do
    resources :products
  end
end

class ShopSerializer < ActiveModel::Serializer
  has_many :products
end

class ProductSerializer < ActiveModel::Serializer
  include Rails.application.routes.url_helpers

  attribute :url do
    shop_product_url(NEED SHOP ID, product_id: object.id)
  end
end

When a Shop is serialized, and as a result, so is the collection of its Products, I want the Product serializer to be aware of the shop that is serializing it and use that to include the route in the serialized output. How is this possible? I've tried all manner of passing instance_options from the ShopSerializer but it doesn't work as expected.

# this works except is apparently not threadsafe as multiple
# concurrent requests lead to the wrong shop_id being used
# in some of the serialized data
has_many :products do
  ActiveModelSerializers::SerializableResource.new(shop_id: object.id).serializable_hash
end

# shop_id isn't actually available in instance_options
has_many :products do
  ProductSerializer.new(shop_id: object.id)
end

Body:
Unfortunately serializer associations do not seem to provide a clean way to pass in custom attributes to the child serializers. There are a few not-so-pretty solutions though.

1. Invoke ProductSerializer manually, add URL in ShopSerializer

class ProductSerializer < ActiveModel::Serializer
end

class ShopSerializer < ActiveModel::Serializer
  include Rails.application.routes.url_helpers

  attribute :products do
    object.products.map do |product|
      ProductSerializer.new(product).serializable_hash.merge(
        url: shop_product_url(object.id, product_id: product.id)
      )
    end
  end
end

2. Add shop ID to the Product instances before they are fed to ProductSerializer

class ProductSerializer < ActiveModel::Serializer
  include Rails.application.routes.url_helpers

  attribute :url do
    shop_product_url(object.shop_id, product_id: object.id)
  end
end

class ShopSerializer < ActiveModel::Serializer
  has_many :products, serializer: ProductSerializer do
    shop = object
    shop.products.map do |product|
      product.dup.tap do |instance|
        instance.singleton_class.send :define_method, :shop_id do
          shop.id
        end
      end
    end
  end
end

Both solutions should be thread safe, but the first solution seems like a better idea to me, as the second one makes ProductSerializer unusable on its own — i.e. when just a single Product is serialized without knowing the particular shop it should belong to.


问:
Skip all testthat tests when condition not met
What is the proper way to skip all tests in the test directory of an R package when using testthat/devtools infrastructure?  For example, if there is no connection to a database and all the tests rely on that connection, do I need to write a skip in all the files individually or can I write a single skip somewhere?

I have a standard package setup that looks like

mypackage/

...  # other package stuff

tests/

testthat.R

testthat/

test-thing1.R

test-thing2.R

At first I thought I could put a test in the testthat.R file like

```<code>## in testthat.R
library(testthat)
library(mypackage)

fail_test <- function() FALSE
if (fail_test()) test_check("package")
</code>```

but, that didn't work and it looks like calling devtools::test() just ignores that file.  I guess an alternative would be to store all the tests in another directory, but is there a better solution?

答:
The Skipping a test section in the R Packages book covers this use case. Essentially, you write a custom function that checks whatever condition you need to check -- whether or not you can connect to your database -- and then call that function from all tests that require that condition to be satisfied.

Example, parroted from the book:

skip_if_no_db <- function() {
  if (db_conn()) {
    skip("API not available")
  }
}

test_that("foo api returns bar when given baz", {
  skip_if_no_db()
  ...
})
```

I've found this approach more useful than a single switch to toggle off all tests since I tend to have a mix of test that do and don't rely on whatever condition I'm checking and I want to always run as many tests as possible.

Body:
What is the proper way to skip all tests in the test directory of an R package when using testthat/devtools infrastructure?  For example, if there is no connection to a database and all the tests rely on that connection, do I need to write a skip in all the files individually or can I write a single skip somewhere?

I have a standard package setup that looks like

mypackage/

...  # other package stuff

tests/

testthat.R

testthat/

test-thing1.R

test-thing2.R

At first I thought I could put a test in the testthat.R file like

## in testthat.R
library(testthat)
library(mypackage)

fail_test <- function() FALSE
if (fail_test()) test_check("package")

but, that didn't work and it looks like calling devtools::test() just ignores that file.  I guess an alternative would be to store all the tests in another directory, but is there a better solution?

Body:
The Skipping a test section in the R Packages book covers this use case. Essentially, you write a custom function that checks whatever condition you need to check -- whether or not you can connect to your database -- and then call that function from all tests that require that condition to be satisfied.

Example, parroted from the book:

skip_if_no_db <- function() {
  if (db_conn()) {
    skip("API not available")
  }
}

test_that("foo api returns bar when given baz", {
  skip_if_no_db()
  ...
})

I've found this approach more useful than a single switch to toggle off all tests since I tend to have a mix of test that do and don't rely on whatever condition I'm checking and I want to always run as many tests as possible.


问:
java convert object array to int array
how i can do this? i have an object array id like to convert it to int array</p>

答:
if Object[] objectArray like objectArray = {2,23,42,3} then

```<code>public static Integer[] convert(Object[] objectArray){
  Integer[] intArray = new Integer[objectArray.length];

  for(int i=0; i<objectArray.length; i++){
   intArray[i] = (Integer) objectArray[i];
  }

  return intArray;
 }
</code>```

if your objectArray is like Object[] objectArray = new Integer[/*length*/];

You can simply cast (Integer []) objectArray;

ContentLicense: CC BY-SA 2.5

Title: java convert object array to int array

Body:
if Object[] objectArray like objectArray = {2,23,42,3} then

public static Integer[] convert(Object[] objectArray){
  Integer[] intArray = new Integer[objectArray.length];

  for(int i=0; i<objectArray.length; i++){
   intArray[i] = (Integer) objectArray[i];
  }

  return intArray;
 }

if your objectArray is like Object[] objectArray = new Integer[/*length*/];

You can simply cast (Integer []) objectArray;


问:
HTTP Header not set using Curl in C++
I'm very new to HTTP commands and the libcurl library, so there is a good chance that I'm not understanding something fundamental. That said, I am trying to set headers using curl in C++ but when I try to get the Content-Type, a null value is returned. I am not able to figure out why this is happening. Here is the piece of code:

```<code>// HTTP headers to send with request
   struct curl_slist* headers = nullptr;

// Set Content-Type to application/x-hybrid-thrift-binary
   headers = curl_slist_append(headers, "Content-Type: application/x-hybrid-thrift-binary");

   curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
   CURLcode ret = curl_easy_perform(curl);

// Extract the content-type
   char *ct = nullptr;
   ret = curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &ct);
   if(!ret) {
     printf("Content-Type: %s\n", ct);
   }
</code>```

Any help would be highly appreciated!!!

答:
From the libcurl docs:

SYNOPSIS

```<code>#include <curl/curl.h>

 CURLcode curl_easy_getinfo(CURL *handle, CURLINFO_CONTENT_TYPE, char **ct);
</code>```

DESCRIPTION

Pass a pointer to a char pointer to receive the content-type of the downloaded object. This is the value read from the Content-Type: field. If you get NULL, it means that the server didn't send a valid Content-Type header or that the protocol used doesn't support this.

RETURN VALUE

Returns CURLE_OK if the option is supported, and CURLE_UNKNOWN_OPTION if not.

Title: HTTP Header not set using Curl in C++

Body:
I'm very new to HTTP commands and the libcurl library, so there is a good chance that I'm not understanding something fundamental. That said, I am trying to set headers using curl in C++ but when I try to get the Content-Type, a null value is returned. I am not able to figure out why this is happening. Here is the piece of code:

// HTTP headers to send with request
   struct curl_slist* headers = nullptr;

// Set Content-Type to application/x-hybrid-thrift-binary
   headers = curl_slist_append(headers, "Content-Type: application/x-hybrid-thrift-binary");

   curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
   CURLcode ret = curl_easy_perform(curl);

// Extract the content-type
   char *ct = nullptr;
   ret = curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &ct);
   if(!ret) {
     printf("Content-Type: %s\n", ct);
   }

Any help would be highly appreciated!!!

Body:
From the libcurl docs:

SYNOPSIS

#include <curl/curl.h>

 CURLcode curl_easy_getinfo(CURL *handle, CURLINFO_CONTENT_TYPE, char **ct);

DESCRIPTION

Pass a pointer to a char pointer to receive the content-type of the downloaded object. This is the value read from the Content-Type: field. If you get NULL, it means that the server didn't send a valid Content-Type header or that the protocol used doesn't support this.

RETURN VALUE

Returns CURLE_OK if the option is supported, and CURLE_UNKNOWN_OPTION if not.


问:
How to save the html source code while navigating to each link
Here is my code

```<code>driver = webdriver.Chrome()
path = "/home/winpc/test/python/dup/new"
def get_link_urls(url,driver):
    driver.get(url)
    url = urllib.urlopen(url)
    content = url.readlines()
    urls = []
    for link in driver.find_elements_by_tag_name('a'):
        elem = driver.find_element_by_xpath("//*")
        source_code = elem.get_attribute("outerHTML")
        test = link.get_attribute('href')
        if str(test) != 'None':
               file_name=test.rsplit('/')[-1].split('.')[0]
               file_name_formated = file_name + "Copy.html"
               with open(os.path.join(path, file_name_formated), 'wb') as temp_file:
                    temp_file.write(source_code.encode('utf-8'))
        urls.append(link.get_attribute('href'))
    return urls

urls = get_link_urls("http://localhost:8080",driver)
sub_urls = []
for url in urls:
    if str(url) != 'None':
        sub_urls.extend(get_link_urls(url,driver))
</code>```

This code properly navigating each and every link but all the time coppiny only the first html page.I need to save the source code of each and every page navigating.saving part is happening using below code:

```<code>file_name_formated = file_name + "Copy.html"
with open(os.path.join(path, file_name_formated), 'wb') as temp_file:
                temp_file.write(source_code.encode('utf-8'))
</code>```

答:
First of all you're overwriting URL again and again in the function, so fix that one.

For saving page source through selenium, you can use driver.page_source

Additionally, if you want this code to be faster, consider using requests module.

```<code>response = requests.get(url).content
</code>```

Body:
Here is my code

driver = webdriver.Chrome()
path = "/home/winpc/test/python/dup/new"
def get_link_urls(url,driver):
    driver.get(url)
    url = urllib.urlopen(url)
    content = url.readlines()
    urls = []
    for link in driver.find_elements_by_tag_name('a'):
        elem = driver.find_element_by_xpath("//*")
        source_code = elem.get_attribute("outerHTML")
        test = link.get_attribute('href')
        if str(test) != 'None':
               file_name=test.rsplit('/')[-1].split('.')[0]
               file_name_formated = file_name + "Copy.html"
               with open(os.path.join(path, file_name_formated), 'wb') as temp_file:
                    temp_file.write(source_code.encode('utf-8'))
        urls.append(link.get_attribute('href'))
    return urls

urls = get_link_urls("http://localhost:8080",driver)
sub_urls = []
for url in urls:
    if str(url) != 'None':
        sub_urls.extend(get_link_urls(url,driver))

This code properly navigating each and every link but all the time coppiny only the first html page.I need to save the source code of each and every page navigating.saving part is happening using below code:

file_name_formated = file_name + "Copy.html"
with open(os.path.join(path, file_name_formated), 'wb') as temp_file:
                temp_file.write(source_code.encode('utf-8'))

Body:
First of all you're overwriting URL again and again in the function, so fix that one.

For saving page source through selenium, you can use driver.page_source

Additionally, if you want this code to be faster, consider using requests module.

response = requests.get(url).content


问:
Instantiating POJO (LocalDateTime) from YAML Properties File (Java & Spring Boot)
I am trying to load custom properties from a YAML properties file upon initialization using Spring Boot. I have found countless tutorials on how to do that, and they work. The problem is that I can't seem to find a way how to instantiate POJOS, such as for example LocalDateTime. My code is as shown below.

```<code>@Configuration
@ConfigurationProperties(prefix="default-film-showings")
public class FilmShowings {
    private List<FilmShowing> filmShowings;

    //Constructors, Getters, setters etc.

    public static class FilmShowing {
        private Integer id;
        private Film film;
        private Theatre theatre;
        private LocalDateTime dateTime;

        //Constructors, Getters, setters etc.
    }
}
</code>```

My YAML file is currently as follows

```<code>default-film-showings:
  filmShowings:
    - id: 1
      dateTime: 2018-07-13 21:00:00
</code>```

My problem is that I get the following error upon initialisation

```<code>Failed to convert property value of type 'java.lang.String' to required type 'java.time.LocalDateTime' for property 'filmShowings[0].dateTime';
</code>```

I also tried this variant

```<code>default-film-showings:
  filmShowings:
    - id: 1
      dateTime:
        date:
          year: 2018
          month: 7
          day: 13
        time:
          hour: 21
          minute: 0
          second: 0
          nano: 0
</code>```

but I got the following error

```<code>Error creating bean with name 'filmShowings': Could not bind properties to FilmShowings
</code>```

Any help? I looked at the following thread JSON Java 8 LocalDateTime format in Spring Boot but it didn't solve my problem.

On a similar note, is there any way to link the Film POJO attribute to another default property?

Say I have the following in my properties file

```<code>default-films:
  films:
    - id: 1
      filmName: Spider-Man
</code>```

can I add something like this too?

```<code>default-film-showings:
  filmShowings:
    - id: 1
      film: default-films.films[0]
      dateTime: whatever I need to do here to make it work
</code>```

It is reading default-films.films[0] as string and thus not matching 'the YAML' object.

Any help?

答:
Assuming Spring honors the @DateTimeFormat annotation in a @ConfigurationProperties class (I haven't verified that), you've declared the format to be DateTimeFormat.ISO.DATE_TIME which is 2011-12-03T10:15:30+01:00[Europe/Paris]. Your property file has 2018-07-13 21:00:00 which isn't any of the standard formats. How do you expect it to work?

Your datatype is LocalDateTime which doesn't have a concept of time zone, thus contradicting the ISO_DATE_TIME format. However, the time zone is optional is for ISO_DATE_TIME, so this may not be an issue.

Clearly, you're throwing spaghetti at the wall and hoping something would stick. Write a unit test and try to convert the string to whatever datetime object you want. Once you've done that, come back if you've a problem.

Body:
I am trying to load custom properties from a YAML properties file upon initialization using Spring Boot. I have found countless tutorials on how to do that, and they work. The problem is that I can't seem to find a way how to instantiate POJOS, such as for example LocalDateTime. My code is as shown below.

@Configuration
@ConfigurationProperties(prefix="default-film-showings")
public class FilmShowings {
    private List<FilmShowing> filmShowings;

    //Constructors, Getters, setters etc.

    public static class FilmShowing {
        private Integer id;
        private Film film;
        private Theatre theatre;
        private LocalDateTime dateTime;

        //Constructors, Getters, setters etc.
    }
}

My YAML file is currently as follows

default-film-showings:
  filmShowings:
    - id: 1
      dateTime: 2018-07-13 21:00:00

My problem is that I get the following error upon initialisation

Failed to convert property value of type 'java.lang.String' to required type 'java.time.LocalDateTime' for property 'filmShowings[0].dateTime';

I also tried this variant

default-film-showings:
  filmShowings:
    - id: 1
      dateTime:
        date:
          year: 2018
          month: 7
          day: 13
        time:
          hour: 21
          minute: 0
          second: 0
          nano: 0

but I got the following error

Error creating bean with name 'filmShowings': Could not bind properties to FilmShowings

Any help? I looked at the following thread JSON Java 8 LocalDateTime format in Spring Boot but it didn't solve my problem.

On a similar note, is there any way to link the Film POJO attribute to another default property?

Say I have the following in my properties file

default-films:
  films:
    - id: 1
      filmName: Spider-Man

can I add something like this too?

default-film-showings:
  filmShowings:
    - id: 1
      film: default-films.films[0]
      dateTime: whatever I need to do here to make it work

It is reading default-films.films[0] as string and thus not matching 'the YAML' object.

Any help?


问:
How to get changed value from DatagridView's cell?
I tried to to that as:

```<code>private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    string name = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
}
</code>```

It induces an exception System.NullReferenceException always when I edit cell.

答:
There is no error :/ , but to get the changed value you shoud use another Event:

```<code>    private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
    {
        String name = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
    }
</code>```

And every time will be saved changed value in the variable "name" :)

Body:
I tried to to that as:

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    string name = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
}

It induces an exception System.NullReferenceException always when I edit cell.

Body:
There is no error :/ , but to get the changed value you shoud use another Event:

    private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
    {
        String name = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
    }

And every time will be saved changed value in the variable "name" :)


问:
I need to create a python list object, or any object, out of a pandas DataFrame object grouping pieces of values from different rows
My DataFrame has a string in the first column, and a number in the second one:

```<code>            GEOSTRING  IDactivity
9     wydm2p01uk0fd2z           2
10    wydm86pg6r3jyrg           2
11    wydm2p01uk0fd2z           2
12    wydm80xfxm9j22v           2
39    wydm9w92j538xze           4
40    wydm8km72gbyuvf           4
41    wydm86pg6r3jyrg           4
42    wydm8mzt874p1v5           4
43    wydm8mzmpz5gkt8           5
44    wydm86pg6r3jyrg           5
45    wydm8w1q8bjfpcj           5
46    wydm8w1q8bjfpcj           5
</code>```

What I want to do is to manipulate this DataFrame in order to have a list object that contains a string, made out of the 5th character for each "GEOSTRING" value, for each different "IDactivity" value.
So in this case, I have 3 different "IDactivity" values, and I will have in my list object 3 strings that look like this:

```<code>['2828', '9888','8888']
</code>```

where again, the symbols you see in each string, are the 5th value of each "GEOSTRING" value.

What I'm asking is a solution, or an approach, that doesn't involve a too complicated for loop and have it as efficient as possible since I have to manipulate lots of data. I'd like it to be clean and fast.

I hope it's clear enough.

答:
this can be done easily as follows as a one liner: (considered to be pretty fast too)

```<code>result = df.groupby('IDactivity')['GEOSTRING'].apply(lambda x:''.join(x.str[4])).tolist()
</code>```

this groups the dataframe by values of IDactivity then select from each corresponding string of GEOSTRING column the 5th element (index 4) and joins it with the other corresponding strings. Finally we add tolist() method to get the output as list not pandas Series.

output:

```<code>['2828', '9888', '8888']
</code>```

Documentation:

pandas.groupby

pandas.apply

Body:
My DataFrame has a string in the first column, and a number in the second one:

            GEOSTRING  IDactivity
9     wydm2p01uk0fd2z           2
10    wydm86pg6r3jyrg           2
11    wydm2p01uk0fd2z           2
12    wydm80xfxm9j22v           2
39    wydm9w92j538xze           4
40    wydm8km72gbyuvf           4
41    wydm86pg6r3jyrg           4
42    wydm8mzt874p1v5           4
43    wydm8mzmpz5gkt8           5
44    wydm86pg6r3jyrg           5
45    wydm8w1q8bjfpcj           5
46    wydm8w1q8bjfpcj           5

What I want to do is to manipulate this DataFrame in order to have a list object that contains a string, made out of the 5th character for each "GEOSTRING" value, for each different "IDactivity" value.
So in this case, I have 3 different "IDactivity" values, and I will have in my list object 3 strings that look like this:

['2828', '9888','8888']

where again, the symbols you see in each string, are the 5th value of each "GEOSTRING" value.

What I'm asking is a solution, or an approach, that doesn't involve a too complicated for loop and have it as efficient as possible since I have to manipulate lots of data. I'd like it to be clean and fast.

I hope it's clear enough.

Body:
this can be done easily as follows as a one liner: (considered to be pretty fast too)

result = df.groupby('IDactivity')['GEOSTRING'].apply(lambda x:''.join(x.str[4])).tolist()

this groups the dataframe by values of IDactivity then select from each corresponding string of GEOSTRING column the 5th element (index 4) and joins it with the other corresponding strings. Finally we add tolist() method to get the output as list not pandas Series.

output:

['2828', '9888', '8888']

Documentation:

pandas.groupby

pandas.apply


问:
Convert HTML file to Excel file using Javascript
I have an HTML string where I want to convert to an Excel file. I have tried the following code, but I cannot see any data in Excel.

```<code>var tableToExcel = (function() {
    var uri = 'data:application/vnd.ms-excel;base64,';
    var template = '<html xmlns:o="urn:schemas-microsoft-com:office:office"xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]>    <xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>';
    var base64 = function(s) {
        return window.btoa(unescape(encodeURIComponent(s)));
    };
    var format = function(s, c) {
        return s.replace(/{(\w+)}/g, function(m, p) {return c[p]; });
    }
    return function(table, name) {
        if (!table.nodeType)
            table = document.getElementById(table);
        var ctx = {
            worksheet: name || 'Worksheet',
            table: table.innerHTML
        };
        window.location.href = uri + base64(format(template, ctx));
    }
})()
</code>```

If I run the above code, Excel is downloading but I can't see any data in Excel.
Is there any other solution where I can convert an HTML file to an Excel file?

答:
Maybe this will do the trick?
 jQuery - table2excel

Looked on CDNJS and found TableExport too, so you can reference remote JS library in script tag...

Here it is on GitHub. Follow their install guide...

Body:
I have an HTML string where I want to convert to an Excel file. I have tried the following code, but I cannot see any data in Excel.

var tableToExcel = (function() {
    var uri = 'data:application/vnd.ms-excel;base64,';
    var template = '
{table}
';
    var base64 = function(s) {
        return window.btoa(unescape(encodeURIComponent(s)));
    };
    var format = function(s, c) {
        return s.replace(/{(\w+)}/g, function(m, p) {return c[p]; });
    }
    return function(table, name) {
        if (!table.nodeType)
            table = document.getElementById(table);
        var ctx = {
            worksheet: name || 'Worksheet',
            table: table.innerHTML
        };
        window.location.href = uri + base64(format(template, ctx));
    }
})()

If I run the above code, Excel is downloading but I can't see any data in Excel.
Is there any other solution where I can convert an HTML file to an Excel file?


问:
How to integrate Skype in my iPhone application
I am new to iOS. I want to integrate Skype in my iPhone application,for this I have searched lot but I have not found a solution for this

How can I get Skype SDK for integration. How can I integrate Skype API in my application. Is there any other way to make developer Skype account

If your people having any sample code please post that.Please help me. Many Thanks.

I have tried some code please see that below but using that code my simulator it's showing alert like below image

my code:-

```<code>- (IBAction)skypeMe:(id)sender {

    BOOL installed = [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"skype:"]];
    if(installed)
    {

        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"skype:echo123?call"]];
    }

    else
    {

        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://itunes.com/apps/skype/skype"]];
    }
}
</code>```

答:
For Swift 3.0 It opens itunes url if it is not installed, otherwise it will open skype.

```<code>@IBAction func btnSkypeLinkPressed(_ sender : UIButton) {

    let installed = UIApplication.shared.canOpenURL(NSURL(string: "skype:")! as URL)
    if installed {
        UIApplication.shared.openURL(NSURL(string: "skype:skypeID")! as URL)

    } else {

        UIApplication.shared.openURL(NSURL(string: "https://itunes.apple.com/in/app/skype/id304878510?mt=8")! as URL)
    }
}
</code>```

and in plist add:

```<code><key>LSApplicationQueriesSchemes</key>
    <array>
    <string>skype</string>
    </array>
</code>```

Hope it will work for swift users Thanks.

Body:
I am new to iOS. I want to integrate Skype in my iPhone application,for this I have searched lot but I have not found a solution for this

How can I get Skype SDK for integration. How can I integrate Skype API in my application. Is there any other way to make developer Skype account

If your people having any sample code please post that.Please help me. Many Thanks.

I have tried some code please see that below but using that code my simulator it's showing alert like below image

my code:-

- (IBAction)skypeMe:(id)sender {

    BOOL installed = [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"skype:"]];
    if(installed)
    {

        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"skype:echo123?call"]];
    }

    else
    {

        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://itunes.com/apps/skype/skype"]];
    }
}

Body:
For Swift 3.0 It opens itunes url if it is not installed, otherwise it will open skype.

@IBAction func btnSkypeLinkPressed(_ sender : UIButton) {

    let installed = UIApplication.shared.canOpenURL(NSURL(string: "skype:")! as URL)
    if installed {
        UIApplication.shared.openURL(NSURL(string: "skype:skypeID")! as URL)

    } else {

        UIApplication.shared.openURL(NSURL(string: "https://itunes.apple.com/in/app/skype/id304878510?mt=8")! as URL)
    }
}

and in plist add:

<key>LSApplicationQueriesSchemes</key>
    <array>
    <string>skype</string>
    </array>

Hope it will work for swift users Thanks.


问:
What is the delay for an Azure function to be triggered for EventHub?
I am using a Standard App Service plan for a bunch of my Azure functions. My functions read from EventHubs and forward data to another destination. However they seem either not triggered or when they are, only after a long delay (ten minutes or more).
This happened to both Azure-created EventHubs (like insights-operational-logs for Activity Logs) and my own. I was able to send and receive data from these EventHubs almost instantly using my own sender and receiver clients (e.g with https://github.com/Azure/azure-event-hubs-node), so there is data there in the hubs.

So my questions are:
 1. What's the typical delay for the trigger?
 2. How do I know if my functions are triggered for all events (or how do I debug for that case)?
 3. How do I configure the triggering to be fast?

I already set my Function App to be Always On. I am just using the Portal to see the invocation and my functions logs. Also I am using node.js and not familar with C# and the whole WebJob history.

答:
It turned out that my functions were using all wrong connection strings. Unfortunately these connection strings were created by Azure Portal itself when I setup the integration via the standard editor.
Once I corrected my EventHub binding via the advanced editor according to this: (https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-event-hubs):

```<code>"connection" must be the name of an app setting that contains the connection string to the event hub's namespace. Copy this connection string by clicking the Connection Information button for the namespace, not the event hub itself. This connection string must have at least read permissions to activate the trigger.
</code>```

my functions were triggered almost instantly!

(Specifically, the bindings created by the portal use the eventhub namespace as the path, and the connection strings created have the "Endpoint" pointing to the hub.)

Body:
It turned out that my functions were using all wrong connection strings. Unfortunately these connection strings were created by Azure Portal itself when I setup the integration via the standard editor.
Once I corrected my EventHub binding via the advanced editor according to this: (https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-event-hubs):

"connection" must be the name of an app setting that contains the connection string to the event hub's namespace. Copy this connection string by clicking the Connection Information button for the namespace, not the event hub itself. This connection string must have at least read permissions to activate the trigger.

my functions were triggered almost instantly!

(Specifically, the bindings created by the portal use the eventhub namespace as the path, and the connection strings created have the "Endpoint" pointing to the hub.)


问:
Realm - Failed to connect to endpoint ':::9080': Connection refused
I am getting the below error when starting the Realm object server. I am running the server on Mac.

Realm Mobile Platform version is 1.8.1

2017-07-08T09:48:06.362Z - info: Logging to console at level 'info'.
2017-07-08T09:48:06.438Z - info: Realm Object Server sync engine listening on 127.0.0.1:27800.
2017-07-08T09:48:06.484Z - info: permission: Seed permission-Realms
2017-07-08T09:48:06.496Z - info: Realm Object Server web server listening on 127.0.0.1:27080.
2017-07-08T09:48:06.498Z - info: http proxy listening on :::9080.
2017-07-08T09:48:06.503Z - info: client: Opening Realm file: /Users/vkuppusamy/Documents/realm-mobile-platform/realm-object-server/object-server/root_dir/internal_data/auth.realm
2017-07-08T09:48:06.503Z - info: client: Connection[1]: Session[1]: Starting session for '/Users/vkuppusamy/Documents/realm-mobile-platform/realm-object-server/object-server/root_dir/internal_data/auth.realm'
2017-07-08T09:48:06.503Z - info: client: Connection[1]: Resolving ':::9080'
2017-07-08T09:48:06.503Z - info: client: Connection[1]: Connecting to endpoint ':::9080' (1/1)
2017-07-08T09:48:06.503Z - error: client: Connection[1]: Failed to connect to endpoint ':::9080': Connection refused
2017-07-08T09:48:06.503Z - error: client: Connection[1]: Failed to connect to ':::9080': All endpoints failed
2017-07-08T09:48:06.504Z - info: client: Opening Realm file: /Users/vkuppusamy/Documents/realm-mobile-platform/realm-object-server/object-server/realm-object-server/listener/__admin.realm
2017-07-08T09:48:06.504Z - info: client: Connection[2]: Session[2]: Starting session for '/Users/vkuppusamy/Documents/realm-mobile-platform/realm-object-server/object-server/realm-object-server/listener/_

答: You can ignore that - it's likely due to clients trying to connect before the server has initialized completely.</p>


答:
Here's a solution involving a temp column, and taking inspiration for the key operation from this answer:

```<code># create a temp column with the character we want from each string
dframe['Temp'] = dframe['GEOSTRING'].apply(lambda x: x[4])

# groupby ID and then concatenate using a sneaky call to .sum()
dframe.groupby('IDactivity')['Temp'].sum().tolist()
</code>```

Result:

```<code>['2828', '9888', '8888']
</code>```

Title: I need to create a python list object, or any object, out of a pandas DataFrame object grouping pieces of values from different rows

Body:
Here's a solution involving a temp column, and taking inspiration for the key operation from this answer:

# create a temp column with the character we want from each string
dframe['Temp'] = dframe['GEOSTRING'].apply(lambda x: x[4])

# groupby ID and then concatenate using a sneaky call to .sum()
dframe.groupby('IDactivity')['Temp'].sum().tolist()

Result:

['2828', '9888', '8888']


问:
tcl thread::send -async not works
I want to send message to thread in synchronous mode and get result using trace variable metohd. The problem is that I dont get any response from thread. When I send message in normal mode (thread:: send thread_id {command} var) then I also get the result which is saved in var. Could anyone point out where I make mistake ? Below I pass my code :</p>

```<code>trace add variable res write {apply {{v1 v2 op} {
  upvar 1 $v1 v
  puts "updated variable to $v"}}}

set th [thread::create {

  puts "new thread id : [thread::id]"
  proc fun {n} {
     return [expr {$n*2}]
  }
  thread::wait
}]
# thread::send $th [list fun $t] res
thread::send -async $th [list fun 43] res
</code>```

答: Are you waiting for events in the source/main thread? If you aren't, you'll never process the asynchronous response message that causes the res variable to be set.

Title: tcl thread::send -async not works

Body:
I want to send message to thread in synchronous mode and get result using trace variable metohd. The problem is that I dont get any response from thread. When I send message in normal mode (thread:: send thread_id {command} var) then I also get the result which is saved in var. Could anyone point out where I make mistake ? Below I pass my code :

trace add variable res write {apply {{v1 v2 op} {
  upvar 1 $v1 v
  puts "updated variable to $v"}}}

set th [thread::create {

  puts "new thread id : [thread::id]"
  proc fun {n} {
     return [expr {$n*2}]
  }
  thread::wait
}]
# thread::send $th [list fun $t] res
thread::send -async $th [list fun 43] res


问:
Spark: How to prevent DataFrameWriter from dropping the partitioning columns on call to write.partitionBy?
we are using below method to save a spark sql dataframe

```<code>public DataFrameWriter<T> partitionBy(scala.collection.Seq<String> colNames)
</code>```

from the docs:

Partitions the output by the given columns on the file system. If
  specified, the output is laid out on the file system similar to Hive's
  partitioning scheme. As an example, when we partition a dataset by
  year and then month, the directory layout would look like:

  - year=2016/month=01/

  - year=2016/month=02/

our code looks like this:

```<code>df.repartition(new Column("day")).write.partitionBy("day").mode(SaveMode.Overwrite).parquet(outputPath)
</code>```

we get the directory layout we expect, but we find the parquet files don't have the day column in them anymore. we would like the parquet files to have the day column. how can we do this?

答: the best solution is to add a duplicate day column to the dataframe which would get dropped in the parquet file but the original day column will still be there.

Body:
we are using below method to save a spark sql dataframe

public DataFrameWriter<T> partitionBy(scala.collection.Seq<String> colNames)

from the docs:

Partitions the output by the given columns on the file system. If
  specified, the output is laid out on the file system similar to Hive's
  partitioning scheme. As an example, when we partition a dataset by
  year and then month, the directory layout would look like:

  - year=2016/month=01/

  - year=2016/month=02/

our code looks like this:

df.repartition(new Column("day")).write.partitionBy("day").mode(SaveMode.Overwrite).parquet(outputPath)

we get the directory layout we expect, but we find the parquet files don't have the day column in them anymore. we would like the parquet files to have the day column. how can we do this?


问:
How to integrate Karma with Rails asset pipeline?
I would like to use the Karma test runner in my AngularJS + Rails project. Has anyone integrated them successfully? More specifically, I'm interested to know how to integrate with the asset pipeline (I have files with extension .coffee.erb, which would need to be preprocessed twice).

I use Karma version 0.10.1 and Rails 4.

Any help / examples would be appreciated.

答:
I got Karma and Angular to play nice by doing the following:

Add to your development.rb file:

config.assets.prefix = "/dev-assets"

This will precompile your assets into public/dev-assets folder, the same way production will go to public/assets. You can then add to your karma config:

```<code>files: [
    ...
    './public/dev-assets/*.js'`,
    ...
];
</code>```

Body:
I got Karma and Angular to play nice by doing the following:

Add to your development.rb file:

config.assets.prefix = "/dev-assets"

This will precompile your assets into public/dev-assets folder, the same way production will go to public/assets. You can then add to your karma config:

files: [
    ...
    './public/dev-assets/*.js'`,
    ...
];


问:
Align text under left side of image
I am trying to align both paragraphs under the left side of an image, but I can't seem to figure it out. I am also trying to make the width of the text the same width of the image. I need to keep the div align="center" in there so the bootstrap row is on the center of the page. Please help!

Here is an image from my web design on how i'm trying to align it. http://i.imgur.com/kIbyBUS.png

Here is the html code.
https://jsfiddle.net/kvu7y8ym/

EXAMPLE WEB DESIGN

Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    Vestibulum lobortis diam ut ipsum egestas scelerisque. Nam semper lorem
    at cursus pulvinar. Ut luct diam.

```

答:
The simplest to accomplish that is to use 2 wrappers, an inline-block and a table-caption.

The table-caption will keep the text within the image's edges, and the inline-block will be centered with the text-align: center set on the #preview element.

#preview {
  text-align: center;
}

.inline-block {
  display: inline-block;
}

.tbl-caption {
  display: table-caption;
  text-align: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <div id="preview" class="col-lg-4 col-md-6 col-sm-12">
    <div class="inline-block">
      <div class="tbl-caption">
        <img id="img" src="http://i.imgur.com/HHGHTsu.png">
        <p><b>EXAMPLE WEB DESIGN</b></p>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum lobortis diam ut ipsum egestas scelerisque. Nam semper lorem at cursus pulvinar. Ut luct diam.</p>
      </div>
    </div>
  </div>
</div>
  </code>```

Title: Align text under left side of image

Body:
The simplest to accomplish that is to use 2 wrappers, an inline-block and a table-caption.

The table-caption will keep the text within the image's edges, and the inline-block will be centered with the text-align: center set on the #preview element.

#preview {
  text-align: center;
}

.inline-block {
  display: inline-block;
}

.tbl-caption {
  display: table-caption;
  text-align: left;
}

<div>
  <div id="preview" class="col-lg-4 col-md-6 col-sm-12">
    <div class="inline-block">
      <div class="tbl-caption">
        <img id="img" src="http://i.imgur.com/HHGHTsu.png">
        <p><b>EXAMPLE WEB DESIGN</b></p>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum lobortis diam ut ipsum egestas scelerisque. Nam semper lorem at cursus pulvinar. Ut luct diam.</p>
      </div>
    </div>
  </div>
</div>


问:
A short way to capture/back-reference every digit of a number individually
So basically I want to reformat a 10 digit number like so:

```<code>1234567890 --> (123) 456-7890
</code>```

A long way to do this would be to have each number be its own capture group and then back-reference each one individually:

```<code>'([0-9])([0-9])...([0-9])' --> (\1\2\3) \4\5\6-\7\8\9\10
</code>```

This seems unnecessary and verbose, but when I try the following

```<code>'([0-9]){10}'
</code>```

There appears to be only one back-reference and its of the last digit in the number.

Is there is a more elegant way to reference each character as its own capture group?

Thanks!

答:
The following pattern will do the job: ^(\d{3})(\d{3})(\d{4})$

^(\d{3}): beginning of the string, then exactly 3 digits

(\d{3}): exactly 3 digits

(\d{4})$: exactly 4 digits, then end of the string.

Then replace by: (\1) \2-\3

Body:
So basically I want to reformat a 10 digit number like so:

1234567890 --> (123) 456-7890

A long way to do this would be to have each number be its own capture group and then back-reference each one individually:

'([0-9])([0-9])...([0-9])' --> (\1\2\3) \4\5\6-\7\8\9\10

This seems unnecessary and verbose, but when I try the following

'([0-9]){10}'

There appears to be only one back-reference and its of the last digit in the number.

Is there is a more elegant way to reference each character as its own capture group?

Thanks!


问:
Silverlight context menu: how to determine which menu was clicked?
I have the following context menu:

```<code>                <ListBox x:Name="sectionList" Margin="56,8,15,0" FontSize="64" SelectionChanged="SectionList_SelectionChanged">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <StackPanel>
                                <toolkit:ContextMenuService.ContextMenu>
                                    <toolkit:ContextMenu>
                                        <toolkit:MenuItem Header="Hide this section from this list" Click="ContextMenuItem_Click" />
                                    </toolkit:ContextMenu>
                                </toolkit:ContextMenuService.ContextMenu>
                                <TextBlock Text="{Binding DisplayName}" />
                            </StackPanel>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
</code>```

As you can see, each displayed item has its own context menu. Each context menu is hooked up to the same event handler:

```<code>    private void ContextMenuItem_Click(object sender, RoutedEventArgs e)
    {

    }
</code>```

From this method, how can I tell which context menu was clicked? I want to know what the DataContext for the corresponding DataTemplate is.

答:
You can get the item the ListBoxItem is bound to by casting the sender as a FrameworkElement to get access to the DataContext:

```<code>(sender as FrameworkElement).DataContext
</code>```

You can then cast this to the appropriate model class and access the details you need. e.g.:

```<code>((sender as FrameworkElement).DataContext as ItemViewModel).DisplayName
</code>```

Body:
I have the following context menu:

                <ListBox x:Name="sectionList" Margin="56,8,15,0" FontSize="64" SelectionChanged="SectionList_SelectionChanged">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <StackPanel>
                                <toolkit:ContextMenuService.ContextMenu>
                                    <toolkit:ContextMenu>
                                        <toolkit:MenuItem Header="Hide this section from this list" Click="ContextMenuItem_Click" />
                                    </toolkit:ContextMenu>
                                </toolkit:ContextMenuService.ContextMenu>
                                <TextBlock Text="{Binding DisplayName}" />
                            </StackPanel>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>

As you can see, each displayed item has its own context menu. Each context menu is hooked up to the same event handler:

    private void ContextMenuItem_Click(object sender, RoutedEventArgs e)
    {

    }

From this method, how can I tell which context menu was clicked? I want to know what the DataContext for the corresponding DataTemplate is.

Body:
You can get the item the ListBoxItem is bound to by casting the sender as a FrameworkElement to get access to the DataContext:

(sender as FrameworkElement).DataContext

You can then cast this to the appropriate model class and access the details you need. e.g.:

((sender as FrameworkElement).DataContext as ItemViewModel).DisplayName


问:
Pattern match an array of Regex's in Scala
I have an array of regex's in Scala, and am trying to verify that a message body contains anything in the regex. However, in the messageBody variable I'm getting a Pattern type is incompatible with given type, expected Array[Regex], found Array[String]. How can I pass in a proper case?

A few other posts have suggested using Pattern but that hasn't worked in my case.

```<code>  val messageBody: Array[String] = message.body.split(' ')
  val unsubscribeTriggers: Array[Regex] = Array("unsubscribe/i".r, "stop/i".r, "stopall/i".r, "cancel/i".r, "end/i".r, "quit/i".r)\

  if (messageBody.length == 1) {
        unsubscribeTriggers match {
          case `messageBody` => true

          case _ => false

        }
}
</code>```

答:
You expect too much magic from the compiler. If you have a collection of regexes, you have to check yourself against every element:

```<code>val unsubscribeTriggers: Array[Regex] = Array("(?i)unsubscribe".r, "(?i)stop".r)

val body = "sToP"
val matchFound = unsubscribeTriggers.exists { p: Regex =>
 body match {
  case p() => true
  case _ => false
 }
}
println(matchFound)
</code>```

Regex is made case insensitive by adding (?i) at the start. Try it.

Body:
I have an array of regex's in Scala, and am trying to verify that a message body contains anything in the regex. However, in the messageBody variable I'm getting a Pattern type is incompatible with given type, expected Array[Regex], found Array[String]. How can I pass in a proper case?

A few other posts have suggested using Pattern but that hasn't worked in my case.

  val messageBody: Array[String] = message.body.split(' ')
  val unsubscribeTriggers: Array[Regex] = Array("unsubscribe/i".r, "stop/i".r, "stopall/i".r, "cancel/i".r, "end/i".r, "quit/i".r)\

  if (messageBody.length == 1) {
        unsubscribeTriggers match {
          case `messageBody` => true

          case _ => false

        }
}

Body:
You expect too much magic from the compiler. If you have a collection of regexes, you have to check yourself against every element:

val unsubscribeTriggers: Array[Regex] = Array("(?i)unsubscribe".r, "(?i)stop".r)

val body = "sToP"
val matchFound = unsubscribeTriggers.exists { p: Regex =>
 body match {
  case p() => true
  case _ => false
 }
}
println(matchFound)

Regex is made case insensitive by adding (?i) at the start. Try it.


问:
JPOS Configuration Problems for an Epson POS printer in Windows
I'm trying to print using jPOS in Windows and get the following exception:

```<code>jpos.JposException: Could not connect to service with logicalName = Printer: Exception.message=jp.co.epson.uposcommon.util.EpsonJposServiceInstanceFactory
    at jpos.loader.simple.SimpleServiceConnection.connect(Unknown Source)
    at jpos.BaseJposControl.open(Unknown Source)
...
</code>```

More information:

I'm trying to port our Java printing software from Linux (where it works well) to Windows. We are using an Epson TM-T70 receipt printer. I installed the regular printer drivers and was immediately able to print stuff using notepad, for instance.

Now I installed the Epson JavaPoS ADK. I configured the printer using the SetupPOS application that comes with the ADK. I created a new configuration for my printer with Logical Device Name "Printer". I saved everything and it created the jpos.xml file.

When I try run our application and it executes printer.open("Printer") where "Printer" is the logical device name and printer is a POSPrinter instance, I get the exception above.

I know that my generated jpos.xml file is being used because if I provide a random logical device name, I get a different exception.

I guess the problem is in the port configuration of SetupPOS. The printer is connected through USB. I tried the Port name that appears in the windows printer properties (ESDPRT001) and I even tried all combiniations of COM1 to COM10 but nothing works.

Does anyone have some suggestion? Thanks!

答:
I Solved this adding the following library paths to java project:

C:\Program Files\EPSON\JavaPOS\lib

C:\Program Files\EPSON\JavaPOS\SetupPOS

Body:
I'm trying to print using jPOS in Windows and get the following exception:

jpos.JposException: Could not connect to service with logicalName = Printer: Exception.message=jp.co.epson.uposcommon.util.EpsonJposServiceInstanceFactory
    at jpos.loader.simple.SimpleServiceConnection.connect(Unknown Source)
    at jpos.BaseJposControl.open(Unknown Source)
...

More information:

I'm trying to port our Java printing software from Linux (where it works well) to Windows. We are using an Epson TM-T70 receipt printer. I installed the regular printer drivers and was immediately able to print stuff using notepad, for instance.

Now I installed the Epson JavaPoS ADK. I configured the printer using the SetupPOS application that comes with the ADK. I created a new configuration for my printer with Logical Device Name "Printer". I saved everything and it created the jpos.xml file.

When I try run our application and it executes printer.open("Printer") where "Printer" is the logical device name and printer is a POSPrinter instance, I get the exception above.

I know that my generated jpos.xml file is being used because if I provide a random logical device name, I get a different exception.

I guess the problem is in the port configuration of SetupPOS. The printer is connected through USB. I tried the Port name that appears in the windows printer properties (ESDPRT001) and I even tried all combiniations of COM1 to COM10 but nothing works.

Does anyone have some suggestion? Thanks!


问:
Impossible to have two sagas that handle the same message type
I have 2 different sagas (I mean saga types) that handle the same message.

```<code>     public class AttachMessageToBugSaga : TpSaga<AttachMessageToBugSagaData>, IAmStartedByMessages<MessageIsNotAttached>, IHandleMessages<MessageAttachedToGeneralMessage>
    {
        public override void ConfigureHowToFindSaga()
        {
            ConfigureMapping<MessageAttachedToGeneralMessage>(
             saga => saga.Id,
             message => message.SagaId
             );
        }
        public void Handle(MessageIsNotAttachedToBug message)
        {
            Send(new AttachMessageToGeneralCommand { MessageId = 66, GeneralId = 13 });
        }

        public void Handle(MessageAttachedToGeneralMessage message)
        {
            //do some stuf fhere
        }
    }

    public class AttachMessageToBugSagaData : IContainSagaData
    {
        public Guid Id { get; set; }
        public string Originator { get; set; }
        public string OriginalMessageId { get; set; }
    }

    public class AttachMessageToRequestSaga : TpSaga<AttachMessageToRequestSagaData>, IAmStartedByMessages<MessageIsNotAttachedToRequest>, IHandleMessages<MessageAttachedToGeneralMessage>
    {
        public override void ConfigureHowToFindSaga()
        {
            ConfigureMapping<MessageAttachedToGeneralMessage>(
             saga => saga.Id,
             message => message.SagaId
             );
        }

        public void Handle(MessageIsNotAttachedMessageToRequest message)
        {
            //do some stuff here
        }

        public void Handle(MessageAttachedToGeneralMessage message)
        {
            //do some stuff here
        }
    }

    public class AttachMessageToRequestSagaData : IContainSagaData
    {
        public Guid Id { get; set; }
        public string Originator { get; set; }
        public string OriginalMessageId { get; set; }
    }
</code>```

When I run the sample I get an exception :

System.InvalidCastException: Unable to cast object of type 'MyCustomPlugin.AttachMessageToGeneralSagaData' to type 'MyCustomPlugin.AttachMessageToRequestSagaData'.

I understand why it happens, but I still need some workaround. I tried to implement my own IFindSagas class :

```<code>public class SagaFinder : IFindSagas<AttachMessageToGeneralSagaData>.Using<MessageAttachedToGeneralMessage>,
IFindSagas<AttachMessageToRequestSagaData>.Using<MessageAttachedToGeneralMessage>,
IFindSagas<AttachMessageToRequestSagaData>.Using<MessageIsNotAttachedToRequest>,
IFindSagas<AttachMessageToRequestSagaData>.Using<MessageIsNotAttachedToBug>
{
    AttachMessageToGeneralSagaData IFindSagas<AttachMessageToGeneralSagaData>.Using<MessageAttachedToGeneralMessage>.FindBy(MessageAttachedToGeneralMessage message)
    {
        return ObjectFactory.GetInstance<AttachMessageToGeneralSagaData>();
    }

    AttachMessageToRequestSagaData IFindSagas<AttachMessageToRequestSagaData>.Using<MessageAttachedToGeneralMessage>.FindBy(MessageAttachedToGeneralMessage message)
    {
        return ObjectFactory.GetInstance<AttachMessageToRequestSagaData>();
    }

    public AttachMessageToRequestSagaData FindBy(MessageIsNotAttachedToRequest message)
    {
        return new AttachMessageToRequestSagaData();
    }

    public AttachMessageToRequestSagaData FindBy(MessageIsNotAttachedToBug message)
    {
        return new AttachMessageToRequestSagaData();
    }
}
</code>```

But I do not get into my finders for "MessageAttachedToGeneralMessage".
Please tell me if there is some other workaround, or how to make this example working.

答:
Finally (after digging into the source code) I've found the solution. It seems the only way is to implement my own SagaPersister, where I can do anything I want.

Default implementation in NserviceBus of InMemorySagaPersister has the following code :

```<code>    T ISagaPersister.Get<T>(Guid sagaId)
    {
        ISagaEntity result;
        data.TryGetValue(sagaId, out result);

        return (T)result;
    }
</code>```

And exception occurs while casting .

Body:
I have 2 different sagas (I mean saga types) that handle the same message.

     public class AttachMessageToBugSaga : TpSaga<AttachMessageToBugSagaData>, IAmStartedByMessages<MessageIsNotAttached>, IHandleMessages<MessageAttachedToGeneralMessage>
    {
        public override void ConfigureHowToFindSaga()
        {
            ConfigureMapping<MessageAttachedToGeneralMessage>(
             saga => saga.Id,
             message => message.SagaId
             );
        }
        public void Handle(MessageIsNotAttachedToBug message)
        {
            Send(new AttachMessageToGeneralCommand { MessageId = 66, GeneralId = 13 });
        }

        public void Handle(MessageAttachedToGeneralMessage message)
        {
            //do some stuf fhere
        }
    }

    public class AttachMessageToBugSagaData : IContainSagaData
    {
        public Guid Id { get; set; }
        public string Originator { get; set; }
        public string OriginalMessageId { get; set; }
    }

    public class AttachMessageToRequestSaga : TpSaga<AttachMessageToRequestSagaData>, IAmStartedByMessages<MessageIsNotAttachedToRequest>, IHandleMessages<MessageAttachedToGeneralMessage>
    {
        public override void ConfigureHowToFindSaga()
        {
            ConfigureMapping<MessageAttachedToGeneralMessage>(
             saga => saga.Id,
             message => message.SagaId
             );
        }

        public void Handle(MessageIsNotAttachedMessageToRequest message)
        {
            //do some stuff here
        }

        public void Handle(MessageAttachedToGeneralMessage message)
        {
            //do some stuff here
        }
    }

    public class AttachMessageToRequestSagaData : IContainSagaData
    {
        public Guid Id { get; set; }
        public string Originator { get; set; }
        public string OriginalMessageId { get; set; }
    }

When I run the sample I get an exception :

System.InvalidCastException: Unable to cast object of type 'MyCustomPlugin.AttachMessageToGeneralSagaData' to type 'MyCustomPlugin.AttachMessageToRequestSagaData'.

I understand why it happens, but I still need some workaround. I tried to implement my own IFindSagas class :

public class SagaFinder : IFindSagas<AttachMessageToGeneralSagaData>.Using<MessageAttachedToGeneralMessage>,
IFindSagas<AttachMessageToRequestSagaData>.Using<MessageAttachedToGeneralMessage>,
IFindSagas<AttachMessageToRequestSagaData>.Using<MessageIsNotAttachedToRequest>,
IFindSagas<AttachMessageToRequestSagaData>.Using<MessageIsNotAttachedToBug>
{
    AttachMessageToGeneralSagaData IFindSagas<AttachMessageToGeneralSagaData>.Using<MessageAttachedToGeneralMessage>.FindBy(MessageAttachedToGeneralMessage message)
    {
        return ObjectFactory.GetInstance<AttachMessageToGeneralSagaData>();
    }

    AttachMessageToRequestSagaData IFindSagas<AttachMessageToRequestSagaData>.Using<MessageAttachedToGeneralMessage>.FindBy(MessageAttachedToGeneralMessage message)
    {
        return ObjectFactory.GetInstance<AttachMessageToRequestSagaData>();
    }

    public AttachMessageToRequestSagaData FindBy(MessageIsNotAttachedToRequest message)
    {
        return new AttachMessageToRequestSagaData();
    }

    public AttachMessageToRequestSagaData FindBy(MessageIsNotAttachedToBug message)
    {
        return new AttachMessageToRequestSagaData();
    }
}

But I do not get into my finders for "MessageAttachedToGeneralMessage".
Please tell me if there is some other workaround, or how to make this example working.

Body:
Finally (after digging into the source code) I've found the solution. It seems the only way is to implement my own SagaPersister, where I can do anything I want.

Default implementation in NserviceBus of InMemorySagaPersister has the following code :

    T ISagaPersister.Get<T>(Guid sagaId)
    {
        ISagaEntity result;
        data.TryGetValue(sagaId, out result);

        return (T)result;
    }

And exception occurs while casting .


问:
Scala: Replace all space characters with %20
I need to replace all space characters with %20. I wrote this in Scala

```<code>strToConvert.map(c => if (Character.isSpaceChar(c)) "%20" else c).mkString
</code>```

Is there any better way to do this in Scala?

[Edit]
Lets assume replaceAll is not available and we'd like to implement algorithm similar to replaceAll method

答:
you can use String.replaceAll(what_to_replace, with_what).

eg. to replace single whitespace with %20

```<code>scala> val input = "this is my http request          execute me"
input: String = this is my http request          execute me

scala> input.replaceAll(" ", "%20")
res1: String = this%20is%20my%20http%20request%20%20%20%20%20%20%20%20%20%20execute%20me
</code>```

or use \\s regex (matches single whitespace character)

```<code>scala> input.replaceAll("\\s", "%20")
res2: String = this%20is%20my%20http%20request%20%20%20%20%20%20%20%20%20%20execute%20me
</code>```

If you want multiple whitespaces to replace to one single %20, then use \\s+ which matches sequence of one or more whitespace characters

```<code>scala> input.replaceAll("\\s+", "%20")
res3: String = this%20is%20my%20http%20request%20execute%20me
</code>```

Body:
I need to replace all space characters with %20. I wrote this in Scala

strToConvert.map(c => if (Character.isSpaceChar(c)) "%20" else c).mkString

Is there any better way to do this in Scala?

[Edit]
Lets assume replaceAll is not available and we'd like to implement algorithm similar to replaceAll method

Body:
you can use String.replaceAll(what_to_replace, with_what).

eg. to replace single whitespace with %20

scala> val input = "this is my http request          execute me"
input: String = this is my http request          execute me

scala> input.replaceAll(" ", "%20")
res1: String = this%20is%20my%20http%20request%20%20%20%20%20%20%20%20%20%20execute%20me

or use \\s regex (matches single whitespace character)

scala> input.replaceAll("\\s", "%20")
res2: String = this%20is%20my%20http%20request%20%20%20%20%20%20%20%20%20%20execute%20me

If you want multiple whitespaces to replace to one single %20, then use \\s+ which matches sequence of one or more whitespace characters

scala> input.replaceAll("\\s+", "%20")
res3: String = this%20is%20my%20http%20request%20execute%20me


问:
How to reuse Dagger Module
```<code>mNetComponent = DaggerNetComponent.builder()
            .appModule(new AppModule(this))
            .build();

signInComponent= DaggerSignInComponent.builder()
            .appModule(new AppModule(this))
            .build();
</code>```

This is how i am building my components but is it possible to reuse the AppModule created in DaggerNetComponent on DaggerSignInComponent

答: I was having trouble with using dependency because of singleton and also i was using modules which caused troubles. took the youtube tutorial https://www.youtube.com/watch?v=-Xk1LNrjarw&list=PLuR1PJnGR-Ih-HXnGSpnqjdhdvqcwhfFU&index=6</p>

Title: How to reuse Dagger Module

Body:
mNetComponent = DaggerNetComponent.builder()
            .appModule(new AppModule(this))
            .build();

signInComponent= DaggerSignInComponent.builder()
            .appModule(new AppModule(this))
            .build();

This is how i am building my components but is it possible to reuse the AppModule created in DaggerNetComponent on DaggerSignInComponent


问:
Use sed/awk to remove the last portion of a delimited-text column
I have a file with rows of values. The first column, a PacBio read ID, is a forward-slash-delimited value. I would like to modify the column by removing the final slash and values beyond it. Ideally the result would be stream-able (sed/awk, etc.) and would not rely on the number of forward slashes (i.e. the solution should work whether there is a single forward slash, or three, as below.) </p>

```<code># example row
m54151_170617_100137/4194626/10117_11723/0_1606 1257    1606

# desired row
m54151_170617_100137/4194626/10117_11723    1257    1606
</code>```

Body:
I have a file with rows of values. The first column, a PacBio read ID, is a forward-slash-delimited value. I would like to modify the column by removing the final slash and values beyond it. Ideally the result would be stream-able (sed/awk, etc.) and would not rely on the number of forward slashes (i.e. the solution should work whether there is a single forward slash, or three, as below.)

# example row
m54151_170617_100137/4194626/10117_11723/0_1606 1257    1606

# desired row
m54151_170617_100137/4194626/10117_11723    1257    1606

Body:
awk '{print substr($1,1,40),$2,$3}' OFS="\t" file

m54151_170617_100137/4194626/10117_11723    1257    1606


问:
beepbeepboopbeep
```<code>import java.util.Scanner;
import java.util.Arrays;

public class Lab_07_03 {
    public static void main(String args[]) {
        final int BOOP = 10;
        int i = 0;
        int j = 0; //
        int countr = 0;
        Scanner scnr = new Scanner(System.in);
        int[] countArray = new int[BOOP];
        System.out.println("Enter integers between 1 and 100: ");
        for (i = 0; i < BOOP; i++) {
            countArray[i] = scnr.nextInt(); // array reads user inputs
            if (countArray[i] == 0) {
                break; // 0 signals end of user input
            }
        }
        for (j = 0; countArray[j] != 0; j++) {
            for (i = 0; countArray[i] != 0; i++) {
                if (countArray[j] == countArray[i]) {
                    countr++; // number of times a number appears in an array
                }
            }
            if (countr > 1) {
                System.out.println(countArray[j] + " occurs " + countr + " times.");
                countr = 0;
            } else {
                System.out.println(countArray[j] + " occurs " + countr + " time.");
                countr = 0;
            }
        }
    }
}
</code>```

Right now I am trying to sort the array so that it prints the numbers in ascending order, and does not print any duplicate numbers. However this is proving difficult and I suspect it is because my array is of length 100 when only 10 slots are used. My reasoning for this is that the array length is supposed to be determined by the user input. Is there a better way to do this?

with an input of 2 5 6 5 4 3 23 43 2 0 output looks like this:
Enter integers between 1 and 100:
2 occurs 2 times.
5 occurs 2 times.
6 occurs 1 time.
5 occurs 2 times.
4 occurs 1 time.
3 occurs 1 time.
23 occurs 1 time.
43 occurs 1 time.
2 occurs 2 times.

答:
I have edited your code to fit with an ArrayList of Integers. Also I have initiated countr with 1 because each element inside the ArrayList will have at-least 1 instance. Read the comments in the code for more clarification

```<code>public static void main (String args []) {
final int BOOP = 10;// BOOP really got me :P
  int i = 0;
  int j = 0;  //
  int countr = 1;

  Scanner scnr = new Scanner(System.in);

   ArrayList<Integer> countArray = new ArrayList();

   System.out.println("Enter integers between 1 and 100: ");

   for(i = 0; i < BOOP ; i++) {
    countArray.add(scnr.nextInt()); //array reads user inputs

    if (countArray.get(i)== 0) {
      break;          //0 signals end of user input

    }

   }

  for (j = 0;j< countArray.size()-1; j++){// you want to ignore that last 0 hence -1
  for (i = j+1;i< countArray.size()-1; i++) {
      if (countArray.get(j) == countArray.get(i)) {
       countr++;   //number of times a number appears in an array
       countArray.remove(i);//Remove that duplicate element
       i--;// if a match is found, stay on the current index because the list was moved by 1 unit
      }

    }

    if (countr > 1) {
     System.out.println(countArray.get(j) + " occurs " + countr + " times. ");
     countr = 1;
    }
    else {
       System.out.println(countArray.get(j) + " occurs " + countr + " time. ");
     countr = 1;
    }
}

}
</code>```

Title: beepbeepboopbeep

Body:
import java.util.Scanner;
import java.util.Arrays;

public class Lab_07_03 {
    public static void main(String args[]) {
        final int BOOP = 10;
        int i = 0;
        int j = 0; //
        int countr = 0;
        Scanner scnr = new Scanner(System.in);
        int[] countArray = new int[BOOP];
        System.out.println("Enter integers between 1 and 100: ");
        for (i = 0; i < BOOP; i++) {
            countArray[i] = scnr.nextInt(); // array reads user inputs
            if (countArray[i] == 0) {
                break; // 0 signals end of user input
            }
        }
        for (j = 0; countArray[j] != 0; j++) {
            for (i = 0; countArray[i] != 0; i++) {
                if (countArray[j] == countArray[i]) {
                    countr++; // number of times a number appears in an array
                }
            }
            if (countr > 1) {
                System.out.println(countArray[j] + " occurs " + countr + " times.");
                countr = 0;
            } else {
                System.out.println(countArray[j] + " occurs " + countr + " time.");
                countr = 0;
            }
        }
    }
}

Right now I am trying to sort the array so that it prints the numbers in ascending order, and does not print any duplicate numbers. However this is proving difficult and I suspect it is because my array is of length 100 when only 10 slots are used. My reasoning for this is that the array length is supposed to be determined by the user input. Is there a better way to do this?

with an input of 2 5 6 5 4 3 23 43 2 0 output looks like this:
Enter integers between 1 and 100:
2 occurs 2 times.
5 occurs 2 times.
6 occurs 1 time.
5 occurs 2 times.
4 occurs 1 time.
3 occurs 1 time.
23 occurs 1 time.
43 occurs 1 time.
2 occurs 2 times.

Body:
I have edited your code to fit with an ArrayList of Integers. Also I have initiated countr with 1 because each element inside the ArrayList will have at-least 1 instance. Read the comments in the code for more clarification

public static void main (String args []) {
final int BOOP = 10;// BOOP really got me :P
  int i = 0;
  int j = 0;  //
  int countr = 1;

  Scanner scnr = new Scanner(System.in);

   ArrayList<Integer> countArray = new ArrayList();

   System.out.println("Enter integers between 1 and 100: ");

   for(i = 0; i < BOOP ; i++) {
    countArray.add(scnr.nextInt()); //array reads user inputs

    if (countArray.get(i)== 0) {
      break;          //0 signals end of user input

    }

   }

  for (j = 0;j< countArray.size()-1; j++){// you want to ignore that last 0 hence -1
  for (i = j+1;i< countArray.size()-1; i++) {
      if (countArray.get(j) == countArray.get(i)) {
       countr++;   //number of times a number appears in an array
       countArray.remove(i);//Remove that duplicate element
       i--;// if a match is found, stay on the current index because the list was moved by 1 unit
      }

    }

    if (countr > 1) {
     System.out.println(countArray.get(j) + " occurs " + countr + " times. ");
     countr = 1;
    }
    else {
       System.out.println(countArray.get(j) + " occurs " + countr + " time. ");
     countr = 1;
    }
}

}


问:
How to dynamically change page title and description in ClojureScript / Reagent
Is there a simple way to change document title and description (or other [:html [:head [:meta tags) from ClojureScript Reagent application? For example on every bidi route match change the title and description to match the new page content.

Preferably this should work without using js/window so that the same code can be used in a browser as well as in server isomorphic pre-rendering (which I need for SEO).

In the JavaScript/React world there are react-document-meta and react-side-effect which can probably be converted to Reagent components. But this way of handling side effects seems like a hack and probably simpler solution can be done in pure ClojureScript.

答:
I'm not using bidi, but a similar bidirectional router silk together with re-frame. For every page change, we trigger a :set-current-route event which will be handled centrally.

The handler for :set-current-route will then

```<code>(set! (.-title js/document) "dynamic title")
</code>```

Body:
I'm not using bidi, but a similar bidirectional router silk together with re-frame. For every page change, we trigger a :set-current-route event which will be handled centrally.

The handler for :set-current-route will then

(set! (.-title js/document) "dynamic title")


答:
```<code><div class="container">
   <div class="row">
      <div id="preview" class="col-lg-offset-4 col-md-offset-3 col-lg-4 col-md-6 col-sm-12">
        <img id="img" src="http://i.imgur.com/HHGHTsu.png">
        <p><b>EXAMPLE WEB DESIGN</b></p>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    Vestibulum lobortis diam ut ipsum egestas scelerisque. Nam semper lorem
    at cursus pulvinar. Ut luct diam.</p>
     </div>
   </div>
</div>
</code>```

I'd do it this way if you're using Bootstrap (which it seems like you are because you're using col-lg-4 etc.

When you use those classes they expect to be inside container and then inside a row use different offsets to center the content after that, see example above.

Title: Align text under left side of image

Body:
I am trying to align both paragraphs under the left side of an image, but I can't seem to figure it out. I am also trying to make the width of the text the same width of the image. I need to keep the div align="center" in there so the bootstrap row is on the center of the page. Please help!

Here is an image from my web design on how i'm trying to align it. http://i.imgur.com/kIbyBUS.png

Here is the html code.
https://jsfiddle.net/kvu7y8ym/

EXAMPLE WEB DESIGN

Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    Vestibulum lobortis diam ut ipsum egestas scelerisque. Nam semper lorem
    at cursus pulvinar. Ut luct diam.

Body:
<div class="container">
   <div class="row">
      <div id="preview" class="col-lg-offset-4 col-md-offset-3 col-lg-4 col-md-6 col-sm-12">
        <img id="img" src="http://i.imgur.com/HHGHTsu.png">
        <p><b>EXAMPLE WEB DESIGN</b></p>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    Vestibulum lobortis diam ut ipsum egestas scelerisque. Nam semper lorem
    at cursus pulvinar. Ut luct diam.</p>
     </div>
   </div>
</div>

I'd do it this way if you're using Bootstrap (which it seems like you are because you're using col-lg-4 etc.

When you use those classes they expect to be inside container and then inside a row use different offsets to center the content after that, see example above.


问:
Find/parse server-side <?abc?>-like tags in html document
I guess I need some regex help. I want to find all tags like <?abc?> so that I can replace it with whatever the results are for the code ran inside. I just need help regexing the tag/code string, not parsing the code inside :p.

<?abc print 'test' ?> would result in test

Edit:  Not specifically but in general, matching (<?[chars] (code group) ?>)

答:
This will build up a new copy of the string source, replacing <?abc code?> with the result of process(code)

```<code>Regex abcTagRegex = new Regex(@"\<\?abc(?<code>.*?)\?>");

StringBuilder newSource = new StringBuilder();
int curPos = 0;

foreach (Match abcTagMatch in abcTagRegex.Matches(source)) {
    string code = abcTagMatch.Groups["code"].Value;
    string result = process(code);

    newSource.Append(source.Substring(curPos, abcTagMatch.Index));
    newSource.Append(result);
    curPos = abcTagMatch.Index + abcTagMatch.Length;
}

newSource.Append(source.Substring(curPos));
source = newSource.ToString();
</code>```

N.B. I've not been able to test this code, so some of the functions may be slightly the wrong name, or there may be some off-by-one errors.

Body:
This will build up a new copy of the string source, replacing <?abc code?> with the result of process(code)

Regex abcTagRegex = new Regex(@"\<\?abc(?<code>.*?)\?>");

StringBuilder newSource = new StringBuilder();
int curPos = 0;

foreach (Match abcTagMatch in abcTagRegex.Matches(source)) {
    string code = abcTagMatch.Groups["code"].Value;
    string result = process(code);

    newSource.Append(source.Substring(curPos, abcTagMatch.Index));
    newSource.Append(result);
    curPos = abcTagMatch.Index + abcTagMatch.Length;
}

newSource.Append(source.Substring(curPos));
source = newSource.ToString();

N.B. I've not been able to test this code, so some of the functions may be slightly the wrong name, or there may be some off-by-one errors.


Title: Subsetting data through a pairwise condition (coordinates) given through another matrix

Body:
I have the following problem. I want to subset data from data.frame A through the coordinates in matrix B. The matching must be pairwise between the coordinates of data.frame A and matrix B, for instance:

      lon   lat
315 10.47 52.26
342 10.47 52.37
314 10.36 52.26
341 10.36 52.37
316 10.58 52.26
288 10.47 52.15
343 10.58 52.37
287 10.36 52.15
369 10.47 52.48

Those are the coordinates, I want to use to select the rows, which have the same coordinates as in data.frame A.

Subset of data.frame A:

structure(list(V13138 = c(-15.0545539855957, -15.0118608474731,
-14.8698711395264, -14.7185792922974, -14.5449771881104, -14.3298683166504,
-14.093412399292, -13.8265686035156, -13.5609474182129, -13.2979116439819,
-12.9872589111328, -16.1379947662354, -16.0786437988281, -16.0000076293945,
-15.9013233184814, -15.8254327774048, -15.7928791046143, -15.7776985168457,
-15.7719392776489, -15.6555442810059, -15.5040102005005, -15.299674987793,
-15.1203699111938, -14.9610414505005, -14.9183511734009, -14.8809566497803,
-14.8522186279297, -14.7452983856201, -14.6159820556641, -14.4459781646729,
-14.2792196273804, -14.1135988235474, -13.919620513916, -13.7100219726562,
-13.4647169113159, -13.2096605300903, -12.9506988525391, -12.6352672576904,
-16.0543613433838, -15.9694194793701, -15.8757200241089, -15.7634477615356,
-15.6610631942749, -15.5705652236938, -15.4900894165039, -15.4035835266113,
-15.2854766845703, -15.1539916992188, -15.0065212249756, -14.8876695632935,
-14.7782440185547, -14.7028961181641, -14.6101722717285, -14.512882232666,
-14.3619556427002, -14.2041110992432, -14.0312938690186, -13.8672027587891,
-13.7057323455811, -13.5090990066528, -13.2931470870972, -13.0507898330688,
-12.7776670455933, -12.495795249939, -12.1937398910522, -15.8203887939453,
-15.7082033157349, -15.5987091064453, -15.4917774200439, -15.390435218811,
-15.2902202606201, -15.1883487701416, -15.0730466842651, -14.9352264404297,
-14.8101224899292, -14.6887359619141, -14.5857553482056, -14.479567527771,
-14.3734302520752, -14.2455368041992, -14.1091232299805, -13.9528331756592,
-13.7913122177124, -13.6249303817749), V13139 = c(-7.07704830169678,
-7.36577892303467, -7.60899782180786, -7.85753965377808, -8.1030740737915,
-8.29149341583252, -8.45194625854492, -8.52234935760498, -8.58086585998535,
-8.62695598602295, -8.63118934631348, -3.46103024482727, -3.60997128486633,
-3.75486493110657, -3.90544772148132, -4.07107162475586, -4.2713623046875,
-4.53771257400513, -4.8378758430481, -5.18377256393433, -5.52214574813843,
-5.85517549514771, -6.14670562744141, -6.42839002609253, -6.70926380157471,
-6.97871208190918, -7.23635053634644, -7.43477869033813, -7.61982440948486,
-7.77778148651123, -7.9507007598877, -8.140061378479, -8.27810287475586,
-8.39971256256104, -8.4821662902832, -8.54337215423584, -8.59362697601318,
-8.6127290725708, -3.92732691764832, -4.10400390625, -4.28167676925659,
-4.4712872505188, -4.68312835693359, -4.91524791717529, -5.20708131790161,
-5.51510334014893, -5.85246753692627, -6.17613887786865, -6.49274349212646,
-6.75846433639526, -7.00491952896118, -7.21479940414429, -7.39973735809326,
-7.57557010650635, -7.69487333297729, -7.81140756607056, -7.91438579559326,
-8.01808547973633, -8.12346649169922, -8.21732807159424, -8.30572509765625,
-8.38486099243164, -8.45881938934326, -8.52587699890137, -8.57262134552002,
-4.34183073043823, -4.54555749893188, -4.76105737686157, -4.99724388122559,
-5.26278305053711, -5.53893136978149, -5.85093879699707, -6.16052055358887,
-6.46362257003784, -6.73704147338867, -6.99943161010742, -7.20827674865723,
-7.38761377334595, -7.53203630447388, -7.64012908935547, -7.74198341369629,
-7.82141494750977, -7.89632749557495, -7.96634721755981), V13140 = c(2.38613152503967,
2.37324142456055, 2.38662815093994, 2.38441777229309, 2.35186982154846,
2.31384658813477, 2.2728853225708, 2.23825240135193, 2.20144987106323,
2.15977454185486, 2.13386940956116, 2.9677951335907, 2.92966151237488,
2.8759753704071, 2.8214259147644, 2.76297402381897, 2.70412373542786,
2.6543300151825, 2.61105895042419, 2.60811114311218, 2.60745763778687,
2.60840320587158, 2.60350298881531, 2.59271574020386, 2.54244041442871,
2.47917294502258, 2.40393853187561, 2.35462546348572, 2.31852698326111,
2.31014728546143, 2.29225921630859, 2.26293158531189, 2.23773765563965,
2.21094441413879, 2.18223357200623, 2.15001082420349, 2.11311554908752,
2.08600211143494, 2.89936757087708, 2.89069938659668, 2.87734007835388,
2.85613536834717, 2.8233802318573, 2.78204131126404, 2.73941993713379,
2.70192885398865, 2.68653988838196, 2.66766142845154, 2.64770603179932,
2.62153196334839, 2.5882031917572, 2.53414297103882, 2.46355938911438,
2.38226866722107, 2.31638383865356, 2.26739454269409, 2.24680852890015,
2.23866200447083, 2.23337078094482, 2.22489714622498, 2.21137762069702,
2.19127559661865, 2.16362285614014, 2.13074207305908, 2.08486270904541,
2.85043382644653, 2.87193655967712, 2.88829565048218, 2.89718008041382,
2.88119888305664, 2.85316681861877, 2.81990385055542, 2.7852942943573,
2.75193023681641, 2.72042202949524, 2.6889750957489, 2.650550365448,
2.60602164268494, 2.55256152153015, 2.48241400718689, 2.40686845779419,
2.32716631889343, 2.27034878730774, 2.23567771911621), lon = structure(c(10.36,
10.47, 10.58, 10.69, 10.8, 10.91, 11.02, 11.13, 11.24, 11.35,
11.46, 8.6, 8.71, 8.82, 8.93, 9.04, 9.15, 9.26, 9.37, 9.48, 9.59,
9.7, 9.81, 9.92, 10.03, 10.14, 10.25, 10.36, 10.47, 10.58, 10.69,
10.8, 10.91, 11.02, 11.13, 11.24, 11.35, 11.46, 8.6, 8.71, 8.82,
8.93, 9.04, 9.15, 9.26, 9.37, 9.48, 9.59, 9.7, 9.81, 9.92, 10.03,
10.14, 10.25, 10.36, 10.47, 10.58, 10.69, 10.8, 10.91, 11.02,
11.13, 11.24, 11.35, 11.46, 8.6, 8.71, 8.82, 8.93, 9.04, 9.15,
9.26, 9.37, 9.48, 9.59, 9.7, 9.81, 9.92, 10.03, 10.14, 10.25,
10.36, 10.47, 10.58), .Dim = 84L), lat = structure(c(52.15, 52.15,
52.15, 52.15, 52.15, 52.15, 52.15, 52.15, 52.15, 52.15, 52.15,
52.26, 52.26, 52.26, 52.26, 52.26, 52.26, 52.26, 52.26, 52.26,
52.26, 52.26, 52.26, 52.26, 52.26, 52.26, 52.26, 52.26, 52.26,
52.26, 52.26, 52.26, 52.26, 52.26, 52.26, 52.26, 52.26, 52.26,
52.37, 52.37, 52.37, 52.37, 52.37, 52.37, 52.37, 52.37, 52.37,
52.37, 52.37, 52.37, 52.37, 52.37, 52.37, 52.37, 52.37, 52.37,
52.37, 52.37, 52.37, 52.37, 52.37, 52.37, 52.37, 52.37, 52.37,
52.48, 52.48, 52.48, 52.48, 52.48, 52.48, 52.48, 52.48, 52.48,
52.48, 52.48, 52.48, 52.48, 52.48, 52.48, 52.48, 52.48, 52.48,
52.48), .Dim = 84L)), .Names = c("V13138", "V13139", "V13140",
"lon", "lat"), row.names = 287:370, class = "data.frame")

Matrix B with coordinates:

 structure(list(lon = structure(c(10.47, 10.47, 10.36, 10.36,
10.58, 10.47, 10.58, 10.36, 10.47), .Dim = 9L), lat = structure(c(52.26,
52.37, 52.26, 52.37, 52.26, 52.15, 52.37, 52.15, 52.48), .Dim = 9L)), .Names = c("lon",
"lat"), out.attrs = structure(list(dim = c(27L, 23L), dimnames = structure(list(
    Var1 = c("Var1= 8.60", "Var1= 8.71", "Var1= 8.82", "Var1= 8.93",
    "Var1= 9.04", "Var1= 9.15", "Var1= 9.26", "Var1= 9.37", "Var1= 9.48",
    "Var1= 9.59", "Var1= 9.70", "Var1= 9.81", "Var1= 9.92", "Var1=10.03",
    "Var1=10.14", "Var1=10.25", "Var1=10.36", "Var1=10.47", "Var1=10.58",
    "Var1=10.69", "Var1=10.80", "Var1=10.91", "Var1=11.02", "Var1=11.13",
    "Var1=11.24", "Var1=11.35", "Var1=11.46"), Var2 = c("Var2=51.05",
    "Var2=51.16", "Var2=51.27", "Var2=51.38", "Var2=51.49", "Var2=51.60",
    "Var2=51.71", "Var2=51.82", "Var2=51.93", "Var2=52.04", "Var2=52.15",
    "Var2=52.26", "Var2=52.37", "Var2=52.48", "Var2=52.59", "Var2=52.70",
    "Var2=52.81", "Var2=52.92", "Var2=53.03", "Var2=53.14", "Var2=53.25",
    "Var2=53.36", "Var2=53.47")), .Names = c("Var1", "Var2"))), .Names = c("dim",
"dimnames")), row.names = c(315L, 342L, 314L, 341L, 316L, 288L,
343L, 287L, 369L), class = "data.frame")

Body:
Matrix B has to have the same column names for the columns with the lon and lat coordinates as data.frame A. In the given data, the column names are lon and lat in both objects:

head.matrix(data.frame.A)

       V13138    V13139   V13140   lon   lat
287 -15.05455 -7.077048 2.386132 10.36 52.15
288 -15.01186 -7.365779 2.373241 10.47 52.15
289 -14.86987 -7.608998 2.386628 10.58 52.15
290 -14.71858 -7.857540 2.384418 10.69 52.15
291 -14.54498 -8.103074 2.351870 10.80 52.15
292 -14.32987 -8.291493 2.313847 10.91 52.15

matrix.B

        lon   lat
    315 10.47 52.26
    342 10.47 52.37
    314 10.36 52.26
    341 10.36 52.37
    316 10.58 52.26
    288 10.47 52.15
    343 10.58 52.37
    287 10.36 52.15
    369 10.47 52.48

To subset data from data.frame A through the coordinates in matrix B, just use the following code:

subset.A <- merge(data.frame.A, matrix.B)

    lon   lat    V13138    V13139   V13140
1 10.36 52.15 -15.05455 -7.077048 2.386132
2 10.36 52.26 -14.74530 -7.434779 2.354625
3 10.36 52.37 -14.36196 -7.694873 2.316384
4 10.47 52.15 -15.01186 -7.365779 2.373241
5 10.47 52.26 -14.61598 -7.619824 2.318527
6 10.47 52.37 -14.20411 -7.811408 2.267395
7 10.47 52.48 -13.79131 -7.896327 2.270349
8 10.58 52.26 -14.44598 -7.777781 2.310147
9 10.58 52.37 -14.03129 -7.914386 2.246809

It's a really simple solution. The columns with the coordinates will be placed in the first 2 columns of the subset.