问:
Pagination for Custom Loop (loop with foreach)
I'm trying to add pagination to a custom loop, but I can't figure out how to do it. When I manage to add "previews" and "next" buttons it always shows the same 10 posts. I found some solutions for a while loop but not for a foreach loop (which I actually never used before).
This is the loop (is get_posts a problem?) :   </p>

```<code><?php
  $news = get_posts(array('posts_per_page' => 10));
  $news['paged'] = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1; ?>

        <?php foreach ($news as $article): ?>
            <div class="col-md-4">
                <h3><a href="<?php echo get_permalink($article->ID); ?>"><?php echo $article->post_title ?></a></h3>
                <hr>
                <p class="desc"><?php echo $article->post_excerpt ?></p>

        <a href="<?php echo get_permalink($article->ID); ?>"><?php echo get_the_post_thumbnail($article->ID,'thumbnail'); ?></a>
                <p class="btn_text"><a href="<?php echo get_permalink($article->ID); ?>"> Ler mais</a></p>
            </div>
        <?php endforeach; ?>

   <?php previous_posts_link( '<<' );
    next_posts_link( '>>', $custom_query->max_num_pages ); ?>
</code>```

答:
```<code><?php
if ( get_query_var('paged') ) {
    $paged = get_query_var('paged');
} elseif ( get_query_var('page') ) { // 'page' is used instead of 'paged' on Static Front Page
    $paged = get_query_var('page');
} else {
    $paged = 1;
}

$custom_query_args = array(
    'post_type' => 'post',
    'posts_per_page' => get_option('posts_per_page'),
    'paged' => $paged,
    'post_status' => 'publish',
    'ignore_sticky_posts' => true,
    //'category_name' => 'custom-cat',
    'order' => 'DESC', // 'ASC'
    'orderby' => 'date' // modified | title | name | ID | rand
);
$custom_query = new WP_Query( $custom_query_args );

if ( $custom_query->have_posts() ) :
    while( $custom_query->have_posts() ) : $custom_query->the_post(); ?>

        <article <?php post_class(); ?>>
            <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
            <small><?php the_time('F jS, Y') ?> by <?php the_author_posts_link() ?></small>
            <div><?php the_excerpt(); ?></div>
        </article>

    <?php
    endwhile;
    ?>

    <?php if ($custom_query->max_num_pages > 1) : // custom pagination  ?>
        <?php
        $orig_query = $wp_query; // fix for pagination to work
        $wp_query = $custom_query;
        ?>
        <nav class="prev-next-posts">
            <div class="prev-posts-link">
                <?php echo get_next_posts_link( 'Older Entries', $custom_query->max_num_pages ); ?>
            </div>
            <div class="next-posts-link">
                <?php echo get_previous_posts_link( 'Newer Entries' ); ?>
            </div>
        </nav>
        <?php
        $wp_query = $orig_query; // fix for pagination to work
        ?>
    <?php endif; ?>

<?php
    wp_reset_postdata(); // reset the query
else:
    echo '<p>'.__('Sorry, no posts matched your criteria.').'</p>';
endif;
?>
</code>```

Source : http://web-profile.net/wordpress/themes/wordpress-custom-loop/

Body:
I'm trying to add pagination to a custom loop, but I can't figure out how to do it. When I manage to add "previews" and "next" buttons it always shows the same 10 posts. I found some solutions for a while loop but not for a foreach loop (which I actually never used before).
This is the loop (is get_posts a problem?) :

<?php
  $news = get_posts(array('posts_per_page' => 10));
  $news['paged'] = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1; ?>

        <?php foreach ($news as $article): ?>

<a href="<?php echo get_permalink($article->ID); ?>"><?php echo $article->post_title ?>

<?php echo $article->post_excerpt ?>

        <a href="<?php echo get_permalink($article->ID); ?>"><?php echo get_the_post_thumbnail($article->ID,'thumbnail'); ?>

<a href="<?php echo get_permalink($article->ID); ?>"> Ler mais

        <?php endforeach; ?>

   <?php previous_posts_link( '<<' );
    next_posts_link( '>>', $custom_query->max_num_pages ); ?>

Body:
<?php
if ( get_query_var('paged') ) {
    $paged = get_query_var('paged');
} elseif ( get_query_var('page') ) { // 'page' is used instead of 'paged' on Static Front Page
    $paged = get_query_var('page');
} else {
    $paged = 1;
}

$custom_query_args = array(
    'post_type' => 'post',
    'posts_per_page' => get_option('posts_per_page'),
    'paged' => $paged,
    'post_status' => 'publish',
    'ignore_sticky_posts' => true,
    //'category_name' => 'custom-cat',
    'order' => 'DESC', // 'ASC'
    'orderby' => 'date' // modified | title | name | ID | rand
);
$custom_query = new WP_Query( $custom_query_args );

if ( $custom_query->have_posts() ) :
    while( $custom_query->have_posts() ) : $custom_query->the_post(); ?>

        <article <?php post_class(); ?>>
            <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
            <small><?php the_time('F jS, Y') ?> by <?php the_author_posts_link() ?></small>
            <div><?php the_excerpt(); ?></div>
        </article>

    <?php
    endwhile;
    ?>

    <?php if ($custom_query->max_num_pages > 1) : // custom pagination  ?>
        <?php
        $orig_query = $wp_query; // fix for pagination to work
        $wp_query = $custom_query;
        ?>
        <nav class="prev-next-posts">
            <div class="prev-posts-link">
                <?php echo get_next_posts_link( 'Older Entries', $custom_query->max_num_pages ); ?>
            </div>
            <div class="next-posts-link">
                <?php echo get_previous_posts_link( 'Newer Entries' ); ?>
            </div>
        </nav>
        <?php
        $wp_query = $orig_query; // fix for pagination to work
        ?>
    <?php endif; ?>

<?php
    wp_reset_postdata(); // reset the query
else:
    echo '<p>'.__('Sorry, no posts matched your criteria.').'</p>';
endif;
?>

Source : http://web-profile.net/wordpress/themes/wordpress-custom-loop/


来源: stackexchange

问:
Directories creation inside the Kubernetes Persistent Volume
How would we create a directory inside the kubernetes persistent volume to mount to use in the  container as subPath ?  eg: mysql directory should be created while claiming the persistent volume </p>

答:
I would probably put an init container into my podspec that simply mounts the volume and runs a mkdir -p to create the directory and then exit. You could also do this in the target container itself with some kind of script.

https://kubernetes.io/docs/concepts/workloads/pods/init-containers/

ContentLicense: CC BY-SA 3.0


问:
inotifywait with Docker command and variable
I am trying to create a shell script that will check for a new file then cp to a Docker Container. The code I have so far is...

```<code>#!/bin/sh

source="/var/www/html/"
dest="dev_ubuntu:/var/www/html/"

inotifywait -m "/var/www/html" -e create -e moved_to |
while read file; do
    sudo docker cp /var/www/html/$file dev_ubuntu:/var/www/html
done
</code>```

But this code gives the following error:

```<code>Setting up watches.
Watches established.
"docker cp" requires exactly 2 argument(s).
See 'docker cp --help'.

Usage:  docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|-
docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH

Copy files/folders between a container and the local filesystem
</code>```

What am I doing wrong?

答:
Do you have spaces in your file names? Use double quotes to avoid separating filenames by words:

```<code>echo $file
sudo docker cp "$file" dev_ubuntu:"$file"
</code>```

I've also echoed the file name to see what is happening.

Body:
I am trying to create a shell script that will check for a new file then cp to a Docker Container. The code I have so far is...

#!/bin/sh

source="/var/www/html/"
dest="dev_ubuntu:/var/www/html/"

inotifywait -m "/var/www/html" -e create -e moved_to |
while read file; do
    sudo docker cp /var/www/html/$file dev_ubuntu:/var/www/html
done

But this code gives the following error:

Setting up watches.
Watches established.
"docker cp" requires exactly 2 argument(s).
See 'docker cp --help'.

Usage:  docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|-
docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH

Copy files/folders between a container and the local filesystem

What am I doing wrong?

Body:
Do you have spaces in your file names? Use double quotes to avoid separating filenames by words:

echo $file
sudo docker cp "$file" dev_ubuntu:"$file"

I've also echoed the file name to see what is happening.


问:
mysql load data local infile
I'm trying to load data into a mysql table using LOAD DATA LOCAL INFILE using the code below.

Mysql:

```<code>LOAD DATA INFILE '/var/www/vhosts/domain.com/httpdocs/test1.csv' INTO TABLE temp_table FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\r\n' IGNORE 1 LINES (recloc,client_acc)
</code>```

Edit: changed LOAD DATA LOCAL INFILE to LOADA DATA INFILE, removed SET id=null, added IGNORE 1 LINES

I'm getting no errors and no imported records.  I believe the issue is related to the column names but i'm having a hard time fully understanding what those names should be. Should they be the actual column names within the CSV? or the field names in the DB Table? I would also like the have an auto_incremented primary key (id).

CSV:

```<code>recloc,client_acc
"NLGSX3","CORPORATE"
"7SC3BA","QUALITY ASSURANCE"
"3B9OHF","90717-6710"
</code>```

Any suggestions to what I may be doing wrong? thanks!

答:
Column names in CSV are not necessary, so you should add IGNORE 1 LINES clause.

Columns in your query (recloc,client_acc) need to match columns in table.
First column from CSV will be inserted into recloc, second into client_acc.

If you don't specifu AUTO_INCREMENT column in the statement, but there is one in the table, it should fill automatically.

ContentLicense: CC BY-SA 2.5

Title: mysql load data local infile

Body:
I'm trying to load data into a mysql table using LOAD DATA LOCAL INFILE using the code below.

Mysql:

LOAD DATA INFILE '/var/www/vhosts/domain.com/httpdocs/test1.csv' INTO TABLE temp_table FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\r\n' IGNORE 1 LINES (recloc,client_acc)

Edit: changed LOAD DATA LOCAL INFILE to LOADA DATA INFILE, removed SET id=null, added IGNORE 1 LINES

I'm getting no errors and no imported records.  I believe the issue is related to the column names but i'm having a hard time fully understanding what those names should be. Should they be the actual column names within the CSV? or the field names in the DB Table? I would also like the have an auto_incremented primary key (id).

CSV:

recloc,client_acc
"NLGSX3","CORPORATE"
"7SC3BA","QUALITY ASSURANCE"
"3B9OHF","90717-6710"

Any suggestions to what I may be doing wrong? thanks!


问:
Batch file not echoing to file
bat file that should echo lines to another .bat file (). I'm sure it was working fine, but for some reason is not now...

```<code>echo @echo off > %USERPROFILE%\Documents\Richmond\check_node.bat
echo pushd >> %USERPROFILE%\Documents\Richmond\check_node.bat
echo tasklist /nh /fi "imagename eq node.exe" | find /i "node.exe" > nul ||(start %USERPROFILE%\Documents\Richmond\server.bat) >> %USERPROFILE%\Documents\Richmond\check_node.bat
</code>```

Outputs only...

```<code>@echo off
pushd
</code>```

It's completely ignoring the last line.

Any help would be appreciated.

答:
You need to escape characters when you want to create a batch file like that :

Give a try for this modification :

@echo off
Set "check_node=%USERPROFILE%\Documents\Richmond\check_node.bat"
Set "server=%USERPROFILE%\Documents\Richmond\server.bat"
(
    echo @echo off
    echo pushd
    echo tasklist /nh /fi "imagename eq node.exe" ^| find /i "node.exe" ^>nul ^|^|(start "" "%server%"^)
)> "%check_node%
```

Title: Batch file not echoing to file

Body:
bat file that should echo lines to another .bat file (). I'm sure it was working fine, but for some reason is not now...

echo @echo off > %USERPROFILE%\Documents\Richmond\check_node.bat
echo pushd >> %USERPROFILE%\Documents\Richmond\check_node.bat
echo tasklist /nh /fi "imagename eq node.exe" | find /i "node.exe" > nul ||(start %USERPROFILE%\Documents\Richmond\server.bat) >> %USERPROFILE%\Documents\Richmond\check_node.bat

Outputs only...

@echo off
pushd

It's completely ignoring the last line.

Any help would be appreciated.


问:
Regular Expression Map Implementation in Java
Is there any Java implementation of Map which keys are Regex pattern. Is it possible for such kind of data structure?
Found several handmade solutions like https://wiki.apache.org/jakarta/RegexpKeyedMap, but I want a well tested library.

As a client I want this

```<code>map.put('^RESOURCE.*', () -> { /* some action*/});
map.put('USER|ACCOUNT', () -> { /* do action*/}};
map.put('PRODUCT', () -> { /* do action */}};
</code>```

And e.g.

```<code>String entityType = 'RESOURCE_TYPE_1';
.....
Supplier<MyBatisMapper> action = mapers.get(entityType)
MyBatisMapper mapper = action.get();
mapper.update(entity);
</code>```

It is going to be used as a static configuration. So remove functionality is not essential.

EDITED

Currently we have several large switches in our project and the task is make condition more complex. Like (in pseudo code):

```<code>switch (type) {
    case 'USER' || 'ACCOUNT' : doAction();
    case startsWith('RESOURCE'): doAnotherAction();
    ...
   /* another 10-15 cases */
}
</code>```

I doubt what is the optimal approach. Have several ideas, but none looks nice:

change switch with if/else

make some RegEx container like  dimo414 proposed.

create some classes for configuration. This looks too complex for the problem.

I solved this pretty easy in groovy, making

```<code>def configuration = [
  [matcher: { it.startsWith('RESOURCE' }, action: { /* */}],
  [matcher: { it == 'USER' || it == 'ACCOUNT' }, action: { /* */}]
]
...
def result = configuration.find({ it.matcher(type)}).action();
</code>```

But for Java such solution will be too dirty (due to type casting).

答:
Map has a fairly complex contract that will be difficult (or impossible) to properly follow with the data structure you're describing. For example, there's no meaningful way to implement .entrySet(), since there are unlimited valid keys. Furthermore, the behavior of this "map" doesn't really match the conceptual purpose of a Map, as lookups are expensive (likely O(nk), where k is the complexity of the pattern).

I'd suggest avoiding implementing Map and instead defining a dedicated class that just supports the behavior you need. This might look something like:

```<code>/**
 * Associates a series of regular expressions with values, allowing the values
 * to be looked up by strings that match a pattern.
 *
 * Note this is a linear-time operation, and that patterns are checked in
 * insertion order.
 */
public class RegexLookup<V> {
  // Pattern doesn't override .equals()/.hashCode(), so it can't be the map key
  // use a LinkedHashMap to ensure ordered search
  private final LinkedHashMap<String, Pattern> patterns = new HashMap<>();
  private final HashMap<String, V> values = new HashMap<>();

  /** Associates a regular expression with a value */
  public void putPattern(String regex, V value) {
    putPattern(Pattern.compile(regex), regex);
  }

  /** Associates a regular expression with a value */
  public void putPattern(Pattern pattern, V value) {
    patterns.put(pattern.pattern(), pattern);
    values.put(pattern.pattern(), value);
  }

  /**
   * Looks for a pattern matching the given string, and returns the associated
   * value. If not match is found, returns {@link Optional#absent}.
   */
  public Optional<V> find(String string) {
    for (Entry<String, Pattern> e : patterns.entrySet()) {
      if (e.getValue().matcher(string).matches()) {
        return Optional.of(values.get(e.getKey()));
      }
    }
    return Optional.absent();
  }

  /** Returns a read-only view of the underlying pattern:value mapping. */
  public Map<String, V> asPatternMap() {
    return Collections.unmodifiableMap(values);
  }
}
</code>```

There's a number of benefits to composition rather than inheritence. In addition to not needing to implement the full Map contract, we can also give our methods clearer names and better signatures. .find() clearly conveys we're doing a possibly-expensive search, unlike .get() which is generally implied to be fast.

Your example would end up looking like this (you'll likely want a standard functional interface as the V type, but it depends on what you need):

```<code>RegexLookup<...> configuration = new RegexLookup();
configuration.putPattern('^RESOURCE.*', () -> { /* some action*/});
configuration.putPattern('USER|ACCOUNT', () -> { /* do action*/}};
configuration.putPattern('PRODUCT', () -> { /* do action */}};
</code>```

Then you can retrieve the actions with:

```<code>Optional<...> action = configuration.find(someString);
</code>```

There's some possible improvements to this implementation that might allow us to do better than O(nk), such as constructing conjuctions (|) of patterns and doing essentially a binary search, but the overhead of doing additional regex searches might not be worthwhile (the complexity becomes O(log(n) * k^2), I think), so I'd definitely want to benchmark anything more intricate than the above implementation.

Body:
Is there any Java implementation of Map which keys are Regex pattern. Is it possible for such kind of data structure?
Found several handmade solutions like https://wiki.apache.org/jakarta/RegexpKeyedMap, but I want a well tested library.

As a client I want this

map.put('^RESOURCE.*', () -> { /* some action*/});
map.put('USER|ACCOUNT', () -> { /* do action*/}};
map.put('PRODUCT', () -> { /* do action */}};

And e.g.

String entityType = 'RESOURCE_TYPE_1';
.....
Supplier<MyBatisMapper> action = mapers.get(entityType)
MyBatisMapper mapper = action.get();
mapper.update(entity);

It is going to be used as a static configuration. So remove functionality is not essential.

EDITED

Currently we have several large switches in our project and the task is make condition more complex. Like (in pseudo code):

switch (type) {
    case 'USER' || 'ACCOUNT' : doAction();
    case startsWith('RESOURCE'): doAnotherAction();
    ...
   /* another 10-15 cases */
}

I doubt what is the optimal approach. Have several ideas, but none looks nice:

change switch with if/else

make some RegEx container like  dimo414 proposed.

create some classes for configuration. This looks too complex for the problem.

I solved this pretty easy in groovy, making

def configuration = [
  [matcher: { it.startsWith('RESOURCE' }, action: { /* */}],
  [matcher: { it == 'USER' || it == 'ACCOUNT' }, action: { /* */}]
]
...
def result = configuration.find({ it.matcher(type)}).action();

But for Java such solution will be too dirty (due to type casting).

Body:
Map has a fairly complex contract that will be difficult (or impossible) to properly follow with the data structure you're describing. For example, there's no meaningful way to implement .entrySet(), since there are unlimited valid keys. Furthermore, the behavior of this "map" doesn't really match the conceptual purpose of a Map, as lookups are expensive (likely O(nk), where k is the complexity of the pattern).

I'd suggest avoiding implementing Map and instead defining a dedicated class that just supports the behavior you need. This might look something like:

/**
 * Associates a series of regular expressions with values, allowing the values
 * to be looked up by strings that match a pattern.
 *
 * Note this is a linear-time operation, and that patterns are checked in
 * insertion order.
 */
public class RegexLookup<V> {
  // Pattern doesn't override .equals()/.hashCode(), so it can't be the map key
  // use a LinkedHashMap to ensure ordered search
  private final LinkedHashMap<String, Pattern> patterns = new HashMap<>();
  private final HashMap<String, V> values = new HashMap<>();

  /** Associates a regular expression with a value */
  public void putPattern(String regex, V value) {
    putPattern(Pattern.compile(regex), regex);
  }

  /** Associates a regular expression with a value */
  public void putPattern(Pattern pattern, V value) {
    patterns.put(pattern.pattern(), pattern);
    values.put(pattern.pattern(), value);
  }

  /**
   * Looks for a pattern matching the given string, and returns the associated
   * value. If not match is found, returns {@link Optional#absent}.
   */
  public Optional<V> find(String string) {
    for (Entry<String, Pattern> e : patterns.entrySet()) {
      if (e.getValue().matcher(string).matches()) {
        return Optional.of(values.get(e.getKey()));
      }
    }
    return Optional.absent();
  }

  /** Returns a read-only view of the underlying pattern:value mapping. */
  public Map<String, V> asPatternMap() {
    return Collections.unmodifiableMap(values);
  }
}

There's a number of benefits to composition rather than inheritence. In addition to not needing to implement the full Map contract, we can also give our methods clearer names and better signatures. .find() clearly conveys we're doing a possibly-expensive search, unlike .get() which is generally implied to be fast.

Your example would end up looking like this (you'll likely want a standard functional interface as the V type, but it depends on what you need):

RegexLookup<...> configuration = new RegexLookup();
configuration.putPattern('^RESOURCE.*', () -> { /* some action*/});
configuration.putPattern('USER|ACCOUNT', () -> { /* do action*/}};
configuration.putPattern('PRODUCT', () -> { /* do action */}};

Then you can retrieve the actions with:

Optional<...> action = configuration.find(someString);

There's some possible improvements to this implementation that might allow us to do better than O(nk), such as constructing conjuctions (|) of patterns and doing essentially a binary search, but the overhead of doing additional regex searches might not be worthwhile (the complexity becomes O(log(n) * k^2), I think), so I'd definitely want to benchmark anything more intricate than the above implementation.


问:
(iOS) IAP working but missing in client's Beta using Fabric
I' working on an (ancient) app from a client. The app have been on the App Store for many years and it has working in-app purchases currently.

I'm updating this app and everything IAP related seems to work ok but when I send a beta to my client's test accounts using Crashlytics, the app works ok but the IAP are unavailable for them. Is there any configuration I should do in order to make the IAP working?

答:
Well, I've managed to make it work. I needed to create good ol' provisioning profiles at Apple Dev Center and set Xcode back to manual mode. Once I set distribution provisioning for release builds, everything worked as it should.

I was under the impression that Crashlytics would make everything for me when Xcode was set on automatic mode but it seems that the IAP are more tricky.


问:
Holding a select row into a variable and accessing its fields with informix
Is there a way in Informix to create a ROW type named or unnamed that you can put a row resulted from a select into? I'm working in a stored procedure.

What I want is something like this:

```<code>DEFINE ROW rowVar;

SELECT * INTO rowVar FROM myTableName;
</code>```

Haven't been able to find the correct syntax so far. I want the row object to behave sort-of like it would be SAMEAS with the table columns.

答:
It is not possible to use an "undefined" ROWtype in Informix Stored Procedure Language (SPL).
If you try the following (using Informix 12.10.FC8DE):

```<code>CREATE PROCEDURE sp_dummy();
DEFINE generic_row ROW;
END PROCEDURE;
</code>```

It returns the following error:

```<code>-999    Not implemented yet.
</code>```

The Informix manual does not seem to be correct:

The following statements show examples of generic ROW variables and
  named ROW variables:

DEFINE d ROW;               -- generic ROW variable

If you define the fields of the ROW then you can use it inside the SPL.

Body:
Is there a way in Informix to create a ROW type named or unnamed that you can put a row resulted from a select into? I'm working in a stored procedure.

What I want is something like this:

DEFINE ROW rowVar;

SELECT * INTO rowVar FROM myTableName;

Haven't been able to find the correct syntax so far. I want the row object to behave sort-of like it would be SAMEAS with the table columns.

Body:
It is not possible to use an "undefined" ROWtype in Informix Stored Procedure Language (SPL).
If you try the following (using Informix 12.10.FC8DE):

CREATE PROCEDURE sp_dummy();
DEFINE generic_row ROW;
END PROCEDURE;

It returns the following error:

-999    Not implemented yet.

The Informix manual does not seem to be correct:

The following statements show examples of generic ROW variables and
  named ROW variables:

DEFINE d ROW;               -- generic ROW variable

If you define the fields of the ROW then you can use it inside the SPL.


问:
SWIFT 3 Parse + FB Login
I would like to make a custom login button with 'ParseFacebookUtilsV4'framework.

regarding the documentation of Parse, it should be:

```<code>PFFacebookUtils.logInInBackgroundWithReadPermissions(permissions) {
 (user: PFUser?, error: NSError?) -> Void in
 if let user = user {
 if user.isNew {
 print("User signed up and logged in through Facebook!")
 } else {
 print("User logged in through Facebook!")
 }
 } else {
 print("Uh oh. The user cancelled the Facebook login.")
 }
}
</code>```

The error is:

```<code>Use of unresolved identifier 'permissions'
</code>```

Do you have an idea?

答:
you should add the permissions</p>

```<code>let permissions = ["public_profile", "email", "user_friends"]
PFFacebookUtils.logInInBackground(withReadPermissions: permissions) { (user : PFUser?, error: Error?) in
</code>```

Title: SWIFT 3 Parse + FB Login

Body:
I would like to make a custom login button with 'ParseFacebookUtilsV4'framework.

regarding the documentation of Parse, it should be:

PFFacebookUtils.logInInBackgroundWithReadPermissions(permissions) {
 (user: PFUser?, error: NSError?) -> Void in
 if let user = user {
 if user.isNew {
 print("User signed up and logged in through Facebook!")
 } else {
 print("User logged in through Facebook!")
 }
 } else {
 print("Uh oh. The user cancelled the Facebook login.")
 }
}

The error is:

Use of unresolved identifier 'permissions'

Do you have an idea?

Body:
you should add the permissions

let permissions = ["public_profile", "email", "user_friends"]
PFFacebookUtils.logInInBackground(withReadPermissions: permissions) { (user : PFUser?, error: Error?) in


问:
BASH printf array with field separator and newline on last entry
How can I print out an array in BASH with a field separator between each value and a newline at the end.

The closest I can get with a single printf is printf '%s|' "${arr1[@]}" where | is the field separator.  The problem with this is there is no line break at the end. Any combination of \n I try to put in there either puts in a line break on every entry or none at all!

Is there a way of doing it on one line or do I need to use printf '%s|' "${arr1[@]}";printf "\n"

Thanks,

Geraint

答:
If you don't want to have the | be printed, you could also remove it and just put in a space or whatever seperator you want to use (e.g. , or -):

printf '%s ' "${arr1[@]}" ; printf '\n'

If you need this more often you should use a function, due to writing the same code over and over is not the best way:

```<code>print_array ()
{
  # run through array and print each entry:
  local array
  array=("$@")
  for i in "${array[@]}" ; do
      printf '%s ' "$i"
  done
  # print a new line
  printf '\n'
}
</code>```

usage:

```<code>print_array "${array_name[@]}"
</code>```

example:

```<code>array01=(one two three)
print_array "${array01[@]}"
echo "this should be a new line"
</code>```

output:

```<code>one two three
this should be a new line
</code>```

Body:
If you don't want to have the | be printed, you could also remove it and just put in a space or whatever seperator you want to use (e.g. , or -):

printf '%s ' "${arr1[@]}" ; printf '\n'

If you need this more often you should use a function, due to writing the same code over and over is not the best way:

print_array ()
{
  # run through array and print each entry:
  local array
  array=("$@")
  for i in "${array[@]}" ; do
      printf '%s ' "$i"
  done
  # print a new line
  printf '\n'
}

usage:

print_array "${array_name[@]}"

example:

array01=(one two three)
print_array "${array01[@]}"
echo "this should be a new line"

output:

one two three
this should be a new line


问:
Opencart Extension Installation issue
Facing this problem while installing opencart extension at localhost

答:
You just need to update max_execution_time = 120 value in your php.ini file.

Or

You can add a php.ini file with max_execution_time = 120 value in /admin folder.

Or

You can add below code to .htaccess file too:

php_value max_execution_time 120

This will surely resolve the issue.

Title: Opencart Extension Installation issue


问:
Link to Google Play Store with custom parameter
Is it possible to build a link to Play Store (to my application) with a custom parameter? I would like to be able to read this parameter in my app after installation.
I have found Firebase Dynamic Links but it does not seem to support such functionality</p>

答:
You can use the campaign measurement links.

Link generator:

https://developers.google.com/analytics/devguides/collection/android/v4/campaigns#google-play-url-builder

You can read the params that you define by implementing your own BroadcastReceiver instead of using com.google.android.gms.analytics.CampaignTrackingReceiver.

There in your receiver you can do something like this to get all the params defined in your link.

```<code>   public class InstallReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle extras = intent.getExtras();
            if(extras != null){
              //You will find all of your params under the extra "referrer" like:

              String referrer = extras.getString("referrer");

              //Then you only have to parse it and get the param you need.

            }
       }
   }
</code>```

Docs: https://developers.google.com/analytics/devguides/collection/android/v4/campaigns

Body:
You can use the campaign measurement links.

Link generator:

https://developers.google.com/analytics/devguides/collection/android/v4/campaigns#google-play-url-builder

You can read the params that you define by implementing your own BroadcastReceiver instead of using com.google.android.gms.analytics.CampaignTrackingReceiver.

There in your receiver you can do something like this to get all the params defined in your link.

   public class InstallReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle extras = intent.getExtras();
            if(extras != null){
              //You will find all of your params under the extra "referrer" like:

              String referrer = extras.getString("referrer");

              //Then you only have to parse it and get the param you need.

            }
       }
   }

Docs: https://developers.google.com/analytics/devguides/collection/android/v4/campaigns


问:
Loading Data from Spark to HBase
Its just a FAQ.

Is there any inbuilt python library available in Spark 1.6.1 that I can use to integrate with HBase through pyspark?

There are 3rd party libraries present on internet, but my organization is reluctant to use them.

Regards,
AS

答:
Spark hasn't officially released packages for HBase but efforts are underway.

You can check Spark Packages where you can find some libraries being built for HBase.

You can read Spark SQL Data Sources API: Unified Data Access for the Apache Spark Platform too which is very informative.

Title: Loading Data from Spark to HBase


问:
Can TypeScript express subtype polymorphism for statics on a class
Im looking a way to write an implementation in ts able to deny some statements with lookup typings

Having this implementation:

```<code>function animalDecorator <O extends propertyof Animal>(property: O) {
// should allow only properties from
// a class that extends from Animal

}

class Animal { }

class Cat extends Animal {
  static claws: any
}

class Stone {
  static shape: any
}
</code>```

Then, typing this code, only first statement should be valid

```<code>animalDecorator(Cat.claws) //allow
animalDecorator(Stone.shape) //deny
</code>```

答:
You can use the typeof operator to get the type of the static side of a class.

In other words, you can declare your function as

```<code>function animalDecorator(target: typeof Animal, property: any) { /*...*/ }
</code>```

If you wanted to use the type of target somehow, you could use generics:

```<code>function animalDecorators<T extends typeof Animal>(target: T, property: any): T { /*...*/ }
</code>```

Lastly, there's no way to restrict values from arbitrary places, but you can restrict your function to only property names such as the following:

```<code>function animalDecorators<T extends typeof Animal>(target: T, property: keyof T) { /*...*/ }
</code>```

So that you can write animalDecorator(Cat, "claws") but not animalDecorator(Cat, "shape").

Body:
Im looking a way to write an implementation in ts able to deny some statements with lookup typings

Having this implementation:

function animalDecorator <O extends propertyof Animal>(property: O) {
// should allow only properties from
// a class that extends from Animal

}

class Animal { }

class Cat extends Animal {
  static claws: any
}

class Stone {
  static shape: any
}

Then, typing this code, only first statement should be valid

animalDecorator(Cat.claws) //allow
animalDecorator(Stone.shape) //deny

Body:
You can use the typeof operator to get the type of the static side of a class.

In other words, you can declare your function as

function animalDecorator(target: typeof Animal, property: any) { /*...*/ }

If you wanted to use the type of target somehow, you could use generics:

function animalDecorators<T extends typeof Animal>(target: T, property: any): T { /*...*/ }

Lastly, there's no way to restrict values from arbitrary places, but you can restrict your function to only property names such as the following:

function animalDecorators<T extends typeof Animal>(target: T, property: keyof T) { /*...*/ }

So that you can write animalDecorator(Cat, "claws") but not animalDecorator(Cat, "shape").


问:
Overriding keypress
I know this may be an easy answer to some of you but i dont know how to properly do this. Ive created a text editor, that also has a docking window that will display functions. I have it set up in the menu that F8 is the shortcut key for showing the function window. I would also like to catch the F8 keypress event to parse the current data for the functions in the program but I cant get this to happen.. </p>

答: I'm not sure to understand everything, but can't you use the KeyPress Event available in any Control ?</p>

Title: Overriding keypress


问:
In react can I render a component's children without a wrapper?
I want to do:

```<code>  render: () ->
      {@props.children}
</code>```

It is making me do:

```<code>  render: () ->
      <div>{@props.children}</div>
</code>```

The reason I want to do the former is because the rendered children have their owner-based context set. But if I render them with the  wrapper then the  element which is the parent does not have its context set. This then generates a warning:

owner-based and parent-based contexts differ (values: undefined vs [object Object]) for key (x)

This is discussed here: https://gist.github.com/jimfb/0eb6e61f300a8c1b2ce7

But no solution is offered.

The warning occurs because the component which renders the child is the 'owner' and that is settting context but the div wrapper element is the 'parent' and has no context. My idea was to get rid of the div. But I can't get rid of it.

答:
In situations where a single child is required:

```<code>render() {
    return React.Children.only(this.props.children)
}
</code>```

This is what react-redux uses in connect(), FWIW.

Body:
I want to do:

  render: () ->
      {@props.children}

It is making me do:

  render: () ->

{@props.children}

The reason I want to do the former is because the rendered children have their owner-based context set. But if I render them with the  wrapper then the  element which is the parent does not have its context set. This then generates a warning:

owner-based and parent-based contexts differ (values: undefined vs [object Object]) for key (x)

This is discussed here: https://gist.github.com/jimfb/0eb6e61f300a8c1b2ce7

But no solution is offered.

The warning occurs because the component which renders the child is the 'owner' and that is settting context but the div wrapper element is the 'parent' and has no context. My idea was to get rid of the div. But I can't get rid of it.

Body:
In situations where a single child is required:

render() {
    return React.Children.only(this.props.children)
}

This is what react-redux uses in connect(), FWIW.


问:
'User' object has no attribute 'allow_add_item'
I tried to extend my user model with the following profile model, but I get an Attribute Error

User' object has no attribute 'allow_add_item

My app model has the following class. Please tell me which corrections are needed.

```<code>class CustomUser(models.Model):
    user = models.OneToOneField(User, related_name="dcf_profile")
    phone = models.CharField(_('phone'), max_length=30, null=True, blank=True)
    receive_news = models.BooleanField(_('receive news'), default=True, db_index=True)
    def allow_add_item(self):
        if self.item_set.count() > settings.DCF_ITEM_PER_USER_LIMIT:
            return False
        else:
            return True

class Item(models.Model):
    slug = models.SlugField(blank=True, null=True, max_length=100)
    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
    group = models.ForeignKey(Group, verbose_name=_('group'))
    title = models.CharField(_('title'), max_length=100)
    description = models.TextField(_('description'))

    price = models.DecimalField(_('price'), max_digits=10, decimal_places=2)
    phone = models.CharField(_('phone'), max_length=30)
    is_active = models.BooleanField(_('display'), default=True, db_index=True)
    updated = models.DateTimeField(_('updated'), auto_now=True, db_index=True)
    posted = models.DateTimeField(_('posted'), auto_now_add=True)

    def __unicode__(self):
        return self.title
    class Meta:
        verbose_name = _('item')
        verbose_name_plural = _('items')
        ordering = ('-updated', )
    def get_absolute_url(self):
        return reverse('item', kwargs={
            'pk': self.pk,
            'slug': self.slug
        })
    def get_title(self):
        return u'%s' % self.title
    def get_description(self):
        return u'%s' % self.description[:155]
    def get_keywords(self):
        # TODO need more optimal keywords selection
        return ",".join(set(self.description.split()))
    def get_related(self):
        # TODO Need more complicated related select
        return Item.objects.exclude(pk=self.pk)[:settings.DCF_RELATED_LIMIT]
    def save(self, *args, **kwargs):
        if self.slug is None:
            self.slug = slugify(unidecode(self.title))
        super(Item, self).save(*args, **kwargs)
</code>```

My views.py contains :

```<code>@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
    if not self.request.user.allow_add_item():
        messages.error(self.request, _('You have reached the limit!'))
        return redirect(reverse('my'))
</code>```

答:
It's hard to tell for sure, because the code you have posted has indentation errors other than the one you are asking about.

But your message indicates that you haven't defined the method you are trying to call. If you want your class CustomUser to have a method allow_add_item() then the method definition must be inside the class. What I see is a line of code that calls post_save.connect() and the definition of allow_add_item() only after that. If you do that, it isn't a member of the class, it is just a function with the misleading argument self that makes it look like a method.

You need to indent it to put it inside the class definition. And not have extraneous code in between.

```<code>class CustomUser(models.Model):
    ...
    def allow_add_item(self):
        if self.item_set.count() > settings.DCF_ITEM_PER_USER_LIMIT:
            return False
        else:
            return True
</code>```

Body:
I tried to extend my user model with the following profile model, but I get an Attribute Error

User' object has no attribute 'allow_add_item

My app model has the following class. Please tell me which corrections are needed.

class CustomUser(models.Model):
    user = models.OneToOneField(User, related_name="dcf_profile")
    phone = models.CharField(_('phone'), max_length=30, null=True, blank=True)
    receive_news = models.BooleanField(_('receive news'), default=True, db_index=True)
    def allow_add_item(self):
        if self.item_set.count() > settings.DCF_ITEM_PER_USER_LIMIT:
            return False
        else:
            return True

class Item(models.Model):
    slug = models.SlugField(blank=True, null=True, max_length=100)
    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
    group = models.ForeignKey(Group, verbose_name=_('group'))
    title = models.CharField(_('title'), max_length=100)
    description = models.TextField(_('description'))

    price = models.DecimalField(_('price'), max_digits=10, decimal_places=2)
    phone = models.CharField(_('phone'), max_length=30)
    is_active = models.BooleanField(_('display'), default=True, db_index=True)
    updated = models.DateTimeField(_('updated'), auto_now=True, db_index=True)
    posted = models.DateTimeField(_('posted'), auto_now_add=True)

    def __unicode__(self):
        return self.title
    class Meta:
        verbose_name = _('item')
        verbose_name_plural = _('items')
        ordering = ('-updated', )
    def get_absolute_url(self):
        return reverse('item', kwargs={
            'pk': self.pk,
            'slug': self.slug
        })
    def get_title(self):
        return u'%s' % self.title
    def get_description(self):
        return u'%s' % self.description[:155]
    def get_keywords(self):
        # TODO need more optimal keywords selection
        return ",".join(set(self.description.split()))
    def get_related(self):
        # TODO Need more complicated related select
        return Item.objects.exclude(pk=self.pk)[:settings.DCF_RELATED_LIMIT]
    def save(self, *args, **kwargs):
        if self.slug is None:
            self.slug = slugify(unidecode(self.title))
        super(Item, self).save(*args, **kwargs)

My views.py contains :

@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
    if not self.request.user.allow_add_item():
        messages.error(self.request, _('You have reached the limit!'))
        return redirect(reverse('my'))

Body:
It's hard to tell for sure, because the code you have posted has indentation errors other than the one you are asking about.

But your message indicates that you haven't defined the method you are trying to call. If you want your class CustomUser to have a method allow_add_item() then the method definition must be inside the class. What I see is a line of code that calls post_save.connect() and the definition of allow_add_item() only after that. If you do that, it isn't a member of the class, it is just a function with the misleading argument self that makes it look like a method.

You need to indent it to put it inside the class definition. And not have extraneous code in between.

class CustomUser(models.Model):
    ...
    def allow_add_item(self):
        if self.item_set.count() > settings.DCF_ITEM_PER_USER_LIMIT:
            return False
        else:
            return True


问:
My sorting algorithm doesn't work
As homework, we were supposed to implement a few functions and then come up with a sorting algorithm potentially implementing those functions. first of all, these are the two needed functions:

```<code>remove :: (Ord a) => a -> [a] -> [a]
remove a (x:[]) = x:[]
remove a (x:xs) =
  if a == x
    then xs
    else x:(remove a xs)
</code>```

and:

```<code>smallest :: (Ord a) => [a] -> a
smallest (x:y:[]) =
  if x < y
    then x
    else y
smallest (x:y:xs) =
  if x < y
    then smallest (x:xs)
    else smallest (y:xs)
</code>```

My sorting Algorithm is just supposed to take the smallest element and put it at the beginning of the list:

```<code>sort :: (Integral a) => [a] -> [a]
sort [] = []
sort x = smallest x : sort (rest x)
      where
        rest = remove (smallest x) x
</code>```

The Error I get is

Couldn't match expected type ‘[a] -> [a]’ with actual type ‘[a]’

The function ‘rest’ is applied to one argument,
but its type ‘[a]’ has none
In the first argument of ‘sort’, namely ‘(rest x)’
In the second argument of ‘(:)’, namely ‘sort (rest x)’

I'm surely missing something obvious, but I can't figure out what it is. help me pls.

答:
Compile Error

If we look at the entire error message from ghci, which is:

```<code>    * Couldn't match expected type `[a] -> [a]' with actual type `[a]'
    * The function `rest' is applied to one argument,
      but its type `[a]' has none
      In the first argument of `sort', namely `(rest x)'
      In the second argument of `(:)', namely `sort (rest x)'
    * Relevant bindings include
        rest :: [a]
          (bound at ...)
        x :: [a]
          (bound at ...)
        sort :: [a] -> [a]
          (bound at ...)
Failed, modules loaded: none.
</code>```

We see that rest :: [a].
But you are attempting to apply something to rest here:

```<code>sort x = smallest x : sort (rest x)
</code>```

But you had already applied x here:

```<code>rest = remove (smallest x) x
</code>```

So, simply change the former to:

```<code>sort x = smallest x : sort rest
</code>```

And it will compile. That said, I haven't checked the logic of the algorithm itself.

Fixing the logic:

I rewrote the code with the LambdaCase extension which looks neater.
I also renamed your sorting function to sort' so that it doesn't clash with Data.List (sort).

You had 2 problems in sort'. First, you didn't handle the case of a singleton list, which resulted in a non-exhaustive pattern match. I added the clause [x] -> [x] for this. Second, you should use a let binding to evaluate smallest xs only once, I fixed that too. Third, you had the problem that Thomas M. DuBuisson described, which I fixed. And below is the code, with quickCheck and all.

```<code>remove :: Eq a => a -> [a] -> [a]
remove a = \case
  []     -> []
  (x:xs) -> if a == x then xs else x : remove a xs

smallest :: Ord a => [a] -> a
smallest = \case
  (x:y:[]) -> if x < y then x else y
  (x:y:xs) -> if x < y then smallest (x:xs) else smallest (y:xs)

sort' :: Ord a => [a] -> [a]
sort' = \case
  [ ] -> [ ]
  [x] -> [x]
  xs  -> let s = smallest xs in s : sort' (remove s xs)

prop_sort :: Ord a => [a] -> Bool
prop_sort xs = sort xs == sort' xs
</code>```

Running QuickCheck:

```<code>> quickCheck prop_sort
+++ OK, passed 100 tests.
</code>```

With the alternate changes proposed by Willem Van Onsem, smallest, sort instead looks as:

```<code>smallest :: Ord a => [a] -> a
smallest = \case
  [x]      -> x
  (x:y:xs) -> if x < y then smallest (x:xs) else smallest (y:xs)

sort' :: Ord a => [a] -> [a]
sort' = \case
  [] -> []
  xs -> let s = smallest xs in s : sort' (remove s xs)
</code>```

smallest can also be written as a fold:

```<code>import Data.List (foldl1)

smallest :: Ord a => [a] -> a
smallest = foldl1 $ \x y -> if x < y then x else y
</code>```

and even shorter with by also using min :: Ord a => a -> a -> a:

```<code>import Data.List (foldl1)

smallest :: Ord a => [a] -> a
smallest = foldl1 min
</code>```

wherefore our solution can be written, in total as:

```<code>sort' :: Ord a => [a] -> [a]
sort' = \case [] -> [] ; xs -> let s = foldl1 min xs in s : sort' (remove s xs)
</code>```

Title: My sorting algorithm doesn't work

Body:
As homework, we were supposed to implement a few functions and then come up with a sorting algorithm potentially implementing those functions. first of all, these are the two needed functions:

remove :: (Ord a) => a -> [a] -> [a]
remove a (x:[]) = x:[]
remove a (x:xs) =
  if a == x
    then xs
    else x:(remove a xs)

and:

smallest :: (Ord a) => [a] -> a
smallest (x:y:[]) =
  if x < y
    then x
    else y
smallest (x:y:xs) =
  if x < y
    then smallest (x:xs)
    else smallest (y:xs)

My sorting Algorithm is just supposed to take the smallest element and put it at the beginning of the list:

sort :: (Integral a) => [a] -> [a]
sort [] = []
sort x = smallest x : sort (rest x)
      where
        rest = remove (smallest x) x

The Error I get is

Couldn't match expected type ‘[a] -> [a]’ with actual type ‘[a]’

The function ‘rest’ is applied to one argument,
but its type ‘[a]’ has none
In the first argument of ‘sort’, namely ‘(rest x)’
In the second argument of ‘(:)’, namely ‘sort (rest x)’

I'm surely missing something obvious, but I can't figure out what it is. help me pls.

Body:
Compile Error

If we look at the entire error message from ghci, which is:

    * Couldn't match expected type `[a] -> [a]' with actual type `[a]'
    * The function `rest' is applied to one argument,
      but its type `[a]' has none
      In the first argument of `sort', namely `(rest x)'
      In the second argument of `(:)', namely `sort (rest x)'
    * Relevant bindings include
        rest :: [a]
          (bound at ...)
        x :: [a]
          (bound at ...)
        sort :: [a] -> [a]
          (bound at ...)
Failed, modules loaded: none.

We see that rest :: [a].
But you are attempting to apply something to rest here:

sort x = smallest x : sort (rest x)

But you had already applied x here:

rest = remove (smallest x) x

So, simply change the former to:

sort x = smallest x : sort rest

And it will compile. That said, I haven't checked the logic of the algorithm itself.

Fixing the logic:

I rewrote the code with the LambdaCase extension which looks neater.
I also renamed your sorting function to sort' so that it doesn't clash with Data.List (sort).

You had 2 problems in sort'. First, you didn't handle the case of a singleton list, which resulted in a non-exhaustive pattern match. I added the clause [x] -> [x] for this. Second, you should use a let binding to evaluate smallest xs only once, I fixed that too. Third, you had the problem that Thomas M. DuBuisson described, which I fixed. And below is the code, with quickCheck and all.

remove :: Eq a => a -> [a] -> [a]
remove a = \case
  []     -> []
  (x:xs) -> if a == x then xs else x : remove a xs

smallest :: Ord a => [a] -> a
smallest = \case
  (x:y:[]) -> if x < y then x else y
  (x:y:xs) -> if x < y then smallest (x:xs) else smallest (y:xs)

sort' :: Ord a => [a] -> [a]
sort' = \case
  [ ] -> [ ]
  [x] -> [x]
  xs  -> let s = smallest xs in s : sort' (remove s xs)

prop_sort :: Ord a => [a] -> Bool
prop_sort xs = sort xs == sort' xs

Running QuickCheck:

> quickCheck prop_sort
+++ OK, passed 100 tests.

With the alternate changes proposed by Willem Van Onsem, smallest, sort instead looks as:

smallest :: Ord a => [a] -> a
smallest = \case
  [x]      -> x
  (x:y:xs) -> if x < y then smallest (x:xs) else smallest (y:xs)

sort' :: Ord a => [a] -> [a]
sort' = \case
  [] -> []
  xs -> let s = smallest xs in s : sort' (remove s xs)

smallest can also be written as a fold:

import Data.List (foldl1)

smallest :: Ord a => [a] -> a
smallest = foldl1 $ \x y -> if x < y then x else y

and even shorter with by also using min :: Ord a => a -> a -> a:

import Data.List (foldl1)

smallest :: Ord a => [a] -> a
smallest = foldl1 min

wherefore our solution can be written, in total as:

sort' :: Ord a => [a] -> [a]
sort' = \case [] -> [] ; xs -> let s = foldl1 min xs in s : sort' (remove s xs)


问:
Get number from specific line in notepad++
I have line like this:

```<code><action actionid="9717" script="other/yackal.lua" />
</code>```

How do I get only numbers from "actionid="9717"".

2nd same but with:

```<code>uniqueid="9717"
</code>```

3rd

```<code><action fromaid="44850" toaid="44856" script="quests/reward.lua"/>
</code>```

Is it possible to get all numbers from this?
I mean, 44850, 44851, 44852, ..., 44856. Also it should search for the fromaid and to aid, because I have lines with fromid and toid which should not be taken.

Thanks for help!

答:
Try to use Regex to extract numbers after second word and between double quotes.

like (<action )[a-z](=")(*?)(")

I don't have notepad++ on my linux :(

Body:
I have line like this:

<action actionid="9717" script="other/yackal.lua" />

How do I get only numbers from "actionid="9717"".

2nd same but with:

uniqueid="9717"

3rd

<action fromaid="44850" toaid="44856" script="quests/reward.lua"/>

Is it possible to get all numbers from this?
I mean, 44850, 44851, 44852, ..., 44856. Also it should search for the fromaid and to aid, because I have lines with fromid and toid which should not be taken.

Thanks for help!


问:
value not appearing in the rest of my code
I'm populating my "filteredLocations" array by using this: </p>

```<code>    let sampleRef = FIRDatabase.database().reference().child("SamplePost").child("post")

    sampleRef.observeSingleEvent(of:.value, with: {(snapshot) in
        if  let result = snapshot.children.allObjects as? [FIRDataSnapshot] {
            for child in result{
                let dictionary = child.value as? [String: AnyObject]
                let lat = dictionary?["lat"] as! Double
                let long = dictionary?["long"] as! Double
                let structure = MapPoints(Latitude: lat, Longitude: long)
                self.filteredLocations.append(structure)
                print("This is the amount in here \(self.filteredLocations.count)")

            }
        }
    })
</code>```

<p>the print statement within the my snapshot returns 2, but when I print filteredLocations.count anywhere else it returns 0. I have the Firebase code at the start of the viewdidload </p>

答:
Your problem is that "sampleRef.observeSingleEvent" is asynchronous. What this means is that it is run in a background thread waiting for data while the app continues executing functions like viewWillAppear etc on the main thread.

By the time you get data back from the server the other print count methods would have already been executed before the array was populated with data.

To get a better understanding of this. Place a UIButton on your controller and bind it to a function that prints the array count. Then start the app and press the button. It should print 2 as by the time you press the button you should have got data back from the server.

Body:
I'm populating my "filteredLocations" array by using this:

    let sampleRef = FIRDatabase.database().reference().child("SamplePost").child("post")

    sampleRef.observeSingleEvent(of:.value, with: {(snapshot) in
        if  let result = snapshot.children.allObjects as? [FIRDataSnapshot] {
            for child in result{
                let dictionary = child.value as? [String: AnyObject]
                let lat = dictionary?["lat"] as! Double
                let long = dictionary?["long"] as! Double
                let structure = MapPoints(Latitude: lat, Longitude: long)
                self.filteredLocations.append(structure)
                print("This is the amount in here \(self.filteredLocations.count)")

            }
        }
    })

the print statement within the my snapshot returns 2, but when I print filteredLocations.count anywhere else it returns 0. I have the Firebase code at the start of the viewdidload


问:
Laravel ioc automatic resolution - works from controller but not from custom class
Namespaces omitted for brevity...

I have written the following service provider and registered in config/app.php:

```<code>class OfferServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->registerLossControlManager();
    }

    protected function registerLossControlManager()
    {
        $this->app->bind('LossControlInterface', 'LossControl');
    }
}
</code>```

Here is my LossControlInterface

```<code>interface LossControlInterface
{
    /**
     * @param int $demandId
     * @param float $offerTotal
     * @param float $productTotal
     * @param null|int $partnerId
     * @return mixed
     */
    public function make($demandId, $offerTotal, $productTotal, $partnerId = null);

    /**
     * @return float
     */
    public function getAcceptableLoss();

    /**
     * @return bool
     */
    public function isAcceptable();

    /**
     * @return bool
     */
    public function isUnacceptable();

    /**
     * @return null
     */
    public function reject();
}
</code>```

Now within the controller, I can inject the LossController as follows:

```<code>use LossControlInterface as LossControl;

class HomeController extends BaseController {
   public function __construct(LossControl $lossControl)
    {
        $this->lossControl = $lossControl;
    }

    public function getLossThresholds()
    {
        $lossControl = $this->lossControl->make(985, 1000, null);

        var_dump('Acceptable Loss: ' . $lossControl->getAcceptableLoss());
        var_dump('Actual Loss: ' . $lossControl->calculateLoss());
        var_dump('Acceptable? ' . $lossControl->isAcceptable());

    }
}
</code>```

However if I try to dependency inject the LossControlInterface from within a custom class called by a command:

```<code>[2014-09-02 13:09:52] development.ERROR: exception 'ErrorException' with message 'Argument 11 passed to Offer::__construct() must be an instance of LossControlInterface, none given, called in /home/vagrant/Code/.../ProcessOffer.php on line 44 and defined' in /home/vagrant/Code/.../Offer.php:79
</code>```

It appears as though I am unable to dependency inject the interface into a custom class, but I can when dependency injecting into a controller.

Any thoughts on what Im doing wrong or have omitted to get the automatic resolution working?

答:
In laravel 5.4  (https://github.com/laravel/framework/pull/18271) you need to use the new makeWith method of the IoC container.

```<code>App::makeWith( 'App\MyNameSpace\MyClass', [ $id ] );
</code>```

if you still use 5.3 or below, the above answers will work.

Body:
Namespaces omitted for brevity...

I have written the following service provider and registered in config/app.php:

class OfferServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->registerLossControlManager();
    }

    protected function registerLossControlManager()
    {
        $this->app->bind('LossControlInterface', 'LossControl');
    }
}

Here is my LossControlInterface

interface LossControlInterface
{
    /**
     * @param int $demandId
     * @param float $offerTotal
     * @param float $productTotal
     * @param null|int $partnerId
     * @return mixed
     */
    public function make($demandId, $offerTotal, $productTotal, $partnerId = null);

    /**
     * @return float
     */
    public function getAcceptableLoss();

    /**
     * @return bool
     */
    public function isAcceptable();

    /**
     * @return bool
     */
    public function isUnacceptable();

    /**
     * @return null
     */
    public function reject();
}

Now within the controller, I can inject the LossController as follows:

use LossControlInterface as LossControl;

class HomeController extends BaseController {
   public function __construct(LossControl $lossControl)
    {
        $this->lossControl = $lossControl;
    }

    public function getLossThresholds()
    {
        $lossControl = $this->lossControl->make(985, 1000, null);

        var_dump('Acceptable Loss: ' . $lossControl->getAcceptableLoss());
        var_dump('Actual Loss: ' . $lossControl->calculateLoss());
        var_dump('Acceptable? ' . $lossControl->isAcceptable());

    }
}

However if I try to dependency inject the LossControlInterface from within a custom class called by a command:

[2014-09-02 13:09:52] development.ERROR: exception 'ErrorException' with message 'Argument 11 passed to Offer::__construct() must be an instance of LossControlInterface, none given, called in /home/vagrant/Code/.../ProcessOffer.php on line 44 and defined' in /home/vagrant/Code/.../Offer.php:79

It appears as though I am unable to dependency inject the interface into a custom class, but I can when dependency injecting into a controller.

Any thoughts on what Im doing wrong or have omitted to get the automatic resolution working?

Body:
In laravel 5.4  (https://github.com/laravel/framework/pull/18271) you need to use the new makeWith method of the IoC container.

App::makeWith( 'App\MyNameSpace\MyClass', [ $id ] );

if you still use 5.3 or below, the above answers will work.


问:
OpenID Connect Token endpoint returning a bad request
I am using OneLogin OpenID Connect, I did the initial redirect to OpenID server, put username and password in and OneLogin redirected me to the callback url I provided. I have received a "Code" from this and would like to exchange this code for turning it into an access_token.

I am trying to make a request to the token endpoint but it is returning a 400 Bad Request with this error:

"error_description": "invalid authorization header value format"

I have attached a screenshot below. I didn't have "Client_Secret" in the Authorization header before, I looked around and tried it with "Basic" as well. But none of it seems to work.

Can anyone help me with some insight?

I was also following these two tutorials:
https://openidconnect.net

https://developers.onelogin.com/openid-connect/connect-to-onelogin

I have looked on here to see if I was doing anything wrong. But I still get the same error.
https://connect2id.com/learn/openid-connect#token-endpoint

答:
Your Authorization header has an incorrect format, it should look like the example below for the username "username" and the password "password".

Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=

The variable dXNlcm5hbWU6cGFzc3dvcmQ= is found by concatenating username and password with a colon as separator (username:password) and calculating the Base64 value of this new string (dXNlcm5hbWU6cGFzc3dvcmQ=).

Postman does that for you, just click on the Authorization tab next to Headers. You'll probably need Basic Auth.

ContentLicense: CC BY-SA 4.0


问:
How to substract values off two different tables in SQL reporting Builder
I am having trouble subtracting these two values off my table since I am actually lost on subtraction clause because I have been trying to subtract the values with no success, Here is my query :

```<code> SELECT
 HQCO.HQCo,
 HQCO.Name Name1,
 JCJP.Contract,
 JCJP.Item It1,
 JCJP.Phase ph1,
 JCCP.CostType,
 JCCI.Item It2,
 JCCI.Description Desc1,
 JCCP.Phase ph2,
 JCJP.Description Desc2,
 JCCT.Description Desc3,
 JCCH.UM,
 JCCP.CurrEstUnits,
 JCCP.CurrEstCost,
 JCCP.ActualUnits,
 JCCP.ActualCost,
 JCCM.Description Desc4,
 JCJP.JCCo,
 JCCP.ProjCost,
 JCCP.RemainCmtdCost,
 JCCP.ProjPlug,
 JCCP.Mth,
 JCCI.BilledAmt BilledAmt1,
 JCCM.BilledAmt BilledAmt2,

 JCCM.udGEACrev,
 JCCP.Job,
 JCCM.Department,
 JCJM.ProjectMgr,
 JCMP.Name Name2

 FROM

     Viewpoint.dbo.JCCP
       INNER JOIN Viewpoint.dbo.HQCO ON JCCP.JCCo = HQCO.HQCo
       INNER JOIN Viewpoint.dbo.JCCT ON JCCP.PhaseGroup = JCCT.PhaseGroup
 AND JCCP.CostType = JCCT.CostType
       LEFT OUTER JOIN Viewpoint.dbo.JCCH ON JCCP.JCCo = JCCH.JCCo AND
 JCCP.Job = JCCH.Job
       AND JCCP.PhaseGroup = JCCH.PhaseGroup AND JCCP.Phase = JCCH.Phase
 AND JCCP.CostType = JCCH.CostType
       LEFT OUTER JOIN Viewpoint.dbo.JCJP ON JCCP.JCCo = JCJP.JCCo AND
 JCCP.Job = JCJP.Job
       AND JCCP.PhaseGroup = JCJP.PhaseGroup AND JCCP.Phase  = JCJP.Phase
 AND JCJP.JCCo = 1
       LEFT OUTER JOIN Viewpoint.dbo.JCCI ON JCJP.JCCo = JCCI.JCCo AND
 JCJP.Contract = JCCI.Contract AND JCJP.Item  = JCCI.Item
       INNER JOIN Viewpoint.dbo.JCCM ON JCCI.JCCo = JCCM.JCCo AND
 JCCI.Contract = JCCM.Contract
       INNER JOIN Viewpoint.dbo.JCJM ON JCCM.JCCo = JCJM.JCCo AND
 JCCM.Contract = JCJM.Job
       LEFT OUTER JOIN Viewpoint.dbo.JCMP ON JCJM.JCCo = JCMP.JCCo AND
 JCJM.ProjectMgr = JCMP.ProjectMgr

 WHERE
    JCCP.Mth < {ts '2017-06-02 00:00:00'}
    AND JCJM.ProjectMgr = 12
    AND JCCM.Department = '10'
 ORDER BY JCJP.Contract, JCJP.Item, JCJP.Phase, JCCP.CostType
</code>```

This is the table :
table

What I am trying to do is subtract the Sum of the actual cost from the Billed Amount 2. thanks in advance.

答:
as they are both numeric you should just be able to minus them</p>

```<code>SELECT
 HQCO.HQCo,
 HQCO.Name Name1,
 JCJP.Contract,
 JCJP.Item It1,
 JCJP.Phase ph1,
 JCCP.CostType,
 JCCI.Item It2,
 JCCI.Description Desc1,
 JCCP.Phase ph2,
 JCJP.Description Desc2,
 JCCT.Description Desc3,
 JCCH.UM,
 JCCP.CurrEstUnits,
 JCCP.CurrEstCost,
 JCCP.ActualUnits,
 JCCP.ActualCost,
 JCCM.Description Desc4,
 JCJP.JCCo,
 JCCP.ProjCost,
 JCCP.RemainCmtdCost,
 JCCP.ProjPlug,
 JCCP.Mth,
 JCCI.BilledAmt BilledAmt1,
 JCCM.BilledAmt BilledAmt2,
 JCCM.BilledAmt - JCCP.ActualCost As BilledCostDifference,
 JCCM.udGEACrev,
 JCCP.Job,
 JCCM.Department,
 JCJM.ProjectMgr,
 JCMP.Name Name2

 FROM

     Viewpoint.dbo.JCCP
       INNER JOIN Viewpoint.dbo.HQCO ON JCCP.JCCo = HQCO.HQCo
       INNER JOIN Viewpoint.dbo.JCCT ON JCCP.PhaseGroup = JCCT.PhaseGroup
 AND JCCP.CostType = JCCT.CostType
       LEFT OUTER JOIN Viewpoint.dbo.JCCH ON JCCP.JCCo = JCCH.JCCo AND
 JCCP.Job = JCCH.Job
       AND JCCP.PhaseGroup = JCCH.PhaseGroup AND JCCP.Phase = JCCH.Phase
 AND JCCP.CostType = JCCH.CostType
       LEFT OUTER JOIN Viewpoint.dbo.JCJP ON JCCP.JCCo = JCJP.JCCo AND
 JCCP.Job = JCJP.Job
       AND JCCP.PhaseGroup = JCJP.PhaseGroup AND JCCP.Phase  = JCJP.Phase
 AND JCJP.JCCo = 1
       LEFT OUTER JOIN Viewpoint.dbo.JCCI ON JCJP.JCCo = JCCI.JCCo AND
 JCJP.Contract = JCCI.Contract AND JCJP.Item  = JCCI.Item
       INNER JOIN Viewpoint.dbo.JCCM ON JCCI.JCCo = JCCM.JCCo AND
 JCCI.Contract = JCCM.Contract
       INNER JOIN Viewpoint.dbo.JCJM ON JCCM.JCCo = JCJM.JCCo AND
 JCCM.Contract = JCJM.Job
       LEFT OUTER JOIN Viewpoint.dbo.JCMP ON JCJM.JCCo = JCMP.JCCo AND
 JCJM.ProjectMgr = JCMP.ProjectMgr

 WHERE
    JCCP.Mth < {ts '2017-06-02 00:00:00'}
    AND JCJM.ProjectMgr = 12
    AND JCCM.Department = '10'
 ORDER BY JCJP.Contract, JCJP.Item, JCJP.Phase, JCCP.CostType
</code>```

Body:
I am having trouble subtracting these two values off my table since I am actually lost on subtraction clause because I have been trying to subtract the values with no success, Here is my query :

 SELECT
 HQCO.HQCo,
 HQCO.Name Name1,
 JCJP.Contract,
 JCJP.Item It1,
 JCJP.Phase ph1,
 JCCP.CostType,
 JCCI.Item It2,
 JCCI.Description Desc1,
 JCCP.Phase ph2,
 JCJP.Description Desc2,
 JCCT.Description Desc3,
 JCCH.UM,
 JCCP.CurrEstUnits,
 JCCP.CurrEstCost,
 JCCP.ActualUnits,
 JCCP.ActualCost,
 JCCM.Description Desc4,
 JCJP.JCCo,
 JCCP.ProjCost,
 JCCP.RemainCmtdCost,
 JCCP.ProjPlug,
 JCCP.Mth,
 JCCI.BilledAmt BilledAmt1,
 JCCM.BilledAmt BilledAmt2,

 JCCM.udGEACrev,
 JCCP.Job,
 JCCM.Department,
 JCJM.ProjectMgr,
 JCMP.Name Name2

 FROM

     Viewpoint.dbo.JCCP
       INNER JOIN Viewpoint.dbo.HQCO ON JCCP.JCCo = HQCO.HQCo
       INNER JOIN Viewpoint.dbo.JCCT ON JCCP.PhaseGroup = JCCT.PhaseGroup
 AND JCCP.CostType = JCCT.CostType
       LEFT OUTER JOIN Viewpoint.dbo.JCCH ON JCCP.JCCo = JCCH.JCCo AND
 JCCP.Job = JCCH.Job
       AND JCCP.PhaseGroup = JCCH.PhaseGroup AND JCCP.Phase = JCCH.Phase
 AND JCCP.CostType = JCCH.CostType
       LEFT OUTER JOIN Viewpoint.dbo.JCJP ON JCCP.JCCo = JCJP.JCCo AND
 JCCP.Job = JCJP.Job
       AND JCCP.PhaseGroup = JCJP.PhaseGroup AND JCCP.Phase  = JCJP.Phase
 AND JCJP.JCCo = 1
       LEFT OUTER JOIN Viewpoint.dbo.JCCI ON JCJP.JCCo = JCCI.JCCo AND
 JCJP.Contract = JCCI.Contract AND JCJP.Item  = JCCI.Item
       INNER JOIN Viewpoint.dbo.JCCM ON JCCI.JCCo = JCCM.JCCo AND
 JCCI.Contract = JCCM.Contract
       INNER JOIN Viewpoint.dbo.JCJM ON JCCM.JCCo = JCJM.JCCo AND
 JCCM.Contract = JCJM.Job
       LEFT OUTER JOIN Viewpoint.dbo.JCMP ON JCJM.JCCo = JCMP.JCCo AND
 JCJM.ProjectMgr = JCMP.ProjectMgr

 WHERE
    JCCP.Mth < {ts '2017-06-02 00:00:00'}
    AND JCJM.ProjectMgr = 12
    AND JCCM.Department = '10'
 ORDER BY JCJP.Contract, JCJP.Item, JCJP.Phase, JCCP.CostType

This is the table :
table

What I am trying to do is subtract the Sum of the actual cost from the Billed Amount 2. thanks in advance.

Body:
as they are both numeric you should just be able to minus them

SELECT
 HQCO.HQCo,
 HQCO.Name Name1,
 JCJP.Contract,
 JCJP.Item It1,
 JCJP.Phase ph1,
 JCCP.CostType,
 JCCI.Item It2,
 JCCI.Description Desc1,
 JCCP.Phase ph2,
 JCJP.Description Desc2,
 JCCT.Description Desc3,
 JCCH.UM,
 JCCP.CurrEstUnits,
 JCCP.CurrEstCost,
 JCCP.ActualUnits,
 JCCP.ActualCost,
 JCCM.Description Desc4,
 JCJP.JCCo,
 JCCP.ProjCost,
 JCCP.RemainCmtdCost,
 JCCP.ProjPlug,
 JCCP.Mth,
 JCCI.BilledAmt BilledAmt1,
 JCCM.BilledAmt BilledAmt2,
 JCCM.BilledAmt - JCCP.ActualCost As BilledCostDifference,
 JCCM.udGEACrev,
 JCCP.Job,
 JCCM.Department,
 JCJM.ProjectMgr,
 JCMP.Name Name2

 FROM

     Viewpoint.dbo.JCCP
       INNER JOIN Viewpoint.dbo.HQCO ON JCCP.JCCo = HQCO.HQCo
       INNER JOIN Viewpoint.dbo.JCCT ON JCCP.PhaseGroup = JCCT.PhaseGroup
 AND JCCP.CostType = JCCT.CostType
       LEFT OUTER JOIN Viewpoint.dbo.JCCH ON JCCP.JCCo = JCCH.JCCo AND
 JCCP.Job = JCCH.Job
       AND JCCP.PhaseGroup = JCCH.PhaseGroup AND JCCP.Phase = JCCH.Phase
 AND JCCP.CostType = JCCH.CostType
       LEFT OUTER JOIN Viewpoint.dbo.JCJP ON JCCP.JCCo = JCJP.JCCo AND
 JCCP.Job = JCJP.Job
       AND JCCP.PhaseGroup = JCJP.PhaseGroup AND JCCP.Phase  = JCJP.Phase
 AND JCJP.JCCo = 1
       LEFT OUTER JOIN Viewpoint.dbo.JCCI ON JCJP.JCCo = JCCI.JCCo AND
 JCJP.Contract = JCCI.Contract AND JCJP.Item  = JCCI.Item
       INNER JOIN Viewpoint.dbo.JCCM ON JCCI.JCCo = JCCM.JCCo AND
 JCCI.Contract = JCCM.Contract
       INNER JOIN Viewpoint.dbo.JCJM ON JCCM.JCCo = JCJM.JCCo AND
 JCCM.Contract = JCJM.Job
       LEFT OUTER JOIN Viewpoint.dbo.JCMP ON JCJM.JCCo = JCMP.JCCo AND
 JCJM.ProjectMgr = JCMP.ProjectMgr

 WHERE
    JCCP.Mth < {ts '2017-06-02 00:00:00'}
    AND JCJM.ProjectMgr = 12
    AND JCCM.Department = '10'
 ORDER BY JCJP.Contract, JCJP.Item, JCJP.Phase, JCCP.CostType


问:
MATLAB: How to count number frequency columnwise, in continuous blocks
I have a matrix a in Matlab that looks like the following:

```<code>a = zeros(10,3);
a(3:6,1)=2; a(5:9,3)=1; a(5:7,2)=3; a(8:10,1)=2;

a =
 0     0     0
 0     0     0
 2     0     0
 2     0     0
 2     3     1
 2     3     1
 0     3     1
 2     0     1
 2     0     1
 2     0     0
</code>```

I would like to obtain a cell array with the number of times that each number appears in a column. Also, it should be ordered depending on the element value, regardless of the column number. In the example above I would like to obtain the cell:

```<code>b = {[5],[4,3],[3]}
</code>```

Because the number 1 appears once for 5 times, the number 2 twice in blocks of 4 and 3, and the number 3 once for 3 times. As you can see the recurrences are ordered according to the element value and not to the number of the column where the elements appear.

答:
The hard part is finding and separating the blocks.  diff will find the starting point of any run of numbers, which is the starting point for this solution:

```<code>b = [zeros(1,size(a,2)); a; zeros(1,size(a,2))];
idx = diff(b)~=0;
block_values = b(idx);
block_lengths = diff([0; find(idx)]);
</code>```

Now we have two vectors of the values of each block, and how long they are, and they just need to be captured in the cell array, ignoring the zero blocks

```<code>c = accumarray(block_values(block_values~=0), block_lengths(block_values~=0), [], @(x) {x}).';
</code>```

Body:
I have a matrix a in Matlab that looks like the following:

a = zeros(10,3);
a(3:6,1)=2; a(5:9,3)=1; a(5:7,2)=3; a(8:10,1)=2;

a =
 0     0     0
 0     0     0
 2     0     0
 2     0     0
 2     3     1
 2     3     1
 0     3     1
 2     0     1
 2     0     1
 2     0     0

I would like to obtain a cell array with the number of times that each number appears in a column. Also, it should be ordered depending on the element value, regardless of the column number. In the example above I would like to obtain the cell:

b = {[5],[4,3],[3]}

Because the number 1 appears once for 5 times, the number 2 twice in blocks of 4 and 3, and the number 3 once for 3 times. As you can see the recurrences are ordered according to the element value and not to the number of the column where the elements appear.

Body:
The hard part is finding and separating the blocks.  diff will find the starting point of any run of numbers, which is the starting point for this solution:

b = [zeros(1,size(a,2)); a; zeros(1,size(a,2))];
idx = diff(b)~=0;
block_values = b(idx);
block_lengths = diff([0; find(idx)]);

Now we have two vectors of the values of each block, and how long they are, and they just need to be captured in the cell array, ignoring the zero blocks

c = accumarray(block_values(block_values~=0), block_lengths(block_values~=0), [], @(x) {x}).';


问:
How to turn Highchart scrollable?
I have many columns to set in my chart, but the chart has width and label rotation fixed, so I need expand columns width to keep labels looks better.

Example:

var labels = ['Column 1', 'Column 2', 'Column 3', 'Column 4', 'Column 5', 'Column 6', 'Column 7'];
Highcharts.chart('myChart', {
  chart: {
    type: 'column'
  },
  title: {
    text: ''
  },
  xAxis: {
    categories: labels,
    labels: {
      rotation: 0
    }
  },
  plotOptions: {
    column: {
      stacking: 'normal'
    }
  },
  series: [{
    data: [1,2,3,4,5,6,7]
  }, {
    data: [2,3,4,5,6,7,8]
  }, {
    data: [3,4,5,6,7,8,9]
  }]

});
console.log('jia')```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#myChart {
  width: 300px;
  height: 300px;
}</code>```

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

```

I tried to use HighStocks, but I couldn't change xAxis categories to custom text, I think it's just for time.

How can I set fixed width to chart column and add scroll to the chart made with HighCharts?

答:
Include highstock.js and set max in xAxis for number of columns to appear

var labels = ['Column 1', 'Column 2', 'Column 3', 'Column 4', 'Column 5', 'Column 6', 'Column 7'];
Highcharts.chart('myChart', {
  chart: {
    type: 'column'
  },
  title: {
    text: ''
  },
  yAxis: {
    max: 30, //add for max y value(based on sum of series)
  },
  xAxis: {
    categories: labels,
    labels: {
      rotation: 0
    },
    min: 0,
    max: 1, //max number of columns you want 1 means two column will show
    scrollbar: {
      enabled: true //enables scrolling
    },
  },
  plotOptions: {
    column: {
      stacking: 'normal'
    }
  },
  series: [{
    data: [1, 2, 3, 4, 5, 6, 7]
  }, {
    data: [2, 3, 4, 5, 6, 7, 8]
  }, {
    data: [3, 4, 5, 6, 7, 8, 9]
  }]

});
console.log('jia')```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#myChart {
  width: 300px;
  height: 300px;
}</code>```

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

```

Title: How to turn Highchart scrollable?

Body:
I have many columns to set in my chart, but the chart has width and label rotation fixed, so I need expand columns width to keep labels looks better.

Example:

var labels = ['Column 1', 'Column 2', 'Column 3', 'Column 4', 'Column 5', 'Column 6', 'Column 7'];
Highcharts.chart('myChart', {
  chart: {
    type: 'column'
  },
  title: {
    text: ''
  },
  xAxis: {
    categories: labels,
    labels: {
      rotation: 0
    }
  },
  plotOptions: {
    column: {
      stacking: 'normal'
    }
  },
  series: [{
    data: [1,2,3,4,5,6,7]
  }, {
    data: [2,3,4,5,6,7,8]
  }, {
    data: [3,4,5,6,7,8,9]
  }]

});
console.log('jia')

#myChart {
  width: 300px;
  height: 300px;
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

I tried to use HighStocks, but I couldn't change xAxis categories to custom text, I think it's just for time.

How can I set fixed width to chart column and add scroll to the chart made with HighCharts?

Body:
Include highstock.js and set max in xAxis for number of columns to appear

var labels = ['Column 1', 'Column 2', 'Column 3', 'Column 4', 'Column 5', 'Column 6', 'Column 7'];
Highcharts.chart('myChart', {
  chart: {
    type: 'column'
  },
  title: {
    text: ''
  },
  yAxis: {
    max: 30, //add for max y value(based on sum of series)
  },
  xAxis: {
    categories: labels,
    labels: {
      rotation: 0
    },
    min: 0,
    max: 1, //max number of columns you want 1 means two column will show
    scrollbar: {
      enabled: true //enables scrolling
    },
  },
  plotOptions: {
    column: {
      stacking: 'normal'
    }
  },
  series: [{
    data: [1, 2, 3, 4, 5, 6, 7]
  }, {
    data: [2, 3, 4, 5, 6, 7, 8]
  }, {
    data: [3, 4, 5, 6, 7, 8, 9]
  }]

});
console.log('jia')

#myChart {
  width: 300px;
  height: 300px;
}

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>

<body>
  <script src="https://code.highcharts.com/stock/highstock.js"></script>
  <div id="myChart"></div>
</body>

</html>


问:
String delimiter is affecting some instances of its individual characters
So basically, I'm trying to print out a human readable list of file and directory sizes (without the current directory listed) with the following code

```<code>du -arh | sort -nr | tail -n +2 | awk -F"./" '{print $1 $2 $3}' | head -n $NUM
</code>```

The NUM variable is just an argument given for the amount of items listed.

The output of the above without the awk delimiter command is

4.0K  ./url-list

  4.0K  ./testurl.sh

  4.0K  ./diskhogger.sh

  4.0K  ./backup/url-list

  4.0K  ./backup.sh

However, adding the awk command outputs

4.0K  url-list

  4.0K    testurl.sh

  4.0K    diskhogger.sh

  4.0K    backuurl-list

  4.0K    backup.sh

A similar output occurs whenever there is a notable subdirectory.

./Library/Cache - LibrarCache, etc.

To be clear, I am attempting to cut out the "./" at the beginning of the file name without affecting the other forward slashes. My preferred output would be:

4.0K  url-list

  4.0K    testurl.sh

  4.0K    diskhogger.sh

  4.0K    backup/url-list

  4.0K    backup.sh

where the "backup/url-list" isn't affected.

Is the '.' in my delimiter a special character I don't know about? If not, what exactly is going on here?

I'm new to shell so any info on this would be great.

Thanks!

Edited for clarity.

答:
you can get rid of some other commands if you're using awk

```<code>du -arh | sort -nr | awk -v len="$NUM" 'NR>1{gsub("\\.\\/",""); print} NR==len{exit}'
</code>```

or simply use

```<code>... | sed 's_\./__' | head ...
</code>```

Body:
So basically, I'm trying to print out a human readable list of file and directory sizes (without the current directory listed) with the following code

du -arh | sort -nr | tail -n +2 | awk -F"./" '{print $1 $2 $3}' | head -n $NUM

The NUM variable is just an argument given for the amount of items listed.

The output of the above without the awk delimiter command is

4.0K  ./url-list

  4.0K  ./testurl.sh

  4.0K  ./diskhogger.sh

  4.0K  ./backup/url-list

  4.0K  ./backup.sh

However, adding the awk command outputs

4.0K  url-list

  4.0K    testurl.sh

  4.0K    diskhogger.sh

  4.0K    backuurl-list

  4.0K    backup.sh

A similar output occurs whenever there is a notable subdirectory.

./Library/Cache - LibrarCache, etc.

To be clear, I am attempting to cut out the "./" at the beginning of the file name without affecting the other forward slashes. My preferred output would be:

4.0K  url-list

  4.0K    testurl.sh

  4.0K    diskhogger.sh

  4.0K    backup/url-list

  4.0K    backup.sh

where the "backup/url-list" isn't affected.

Is the '.' in my delimiter a special character I don't know about? If not, what exactly is going on here?

I'm new to shell so any info on this would be great.

Thanks!

Edited for clarity.

Body:
you can get rid of some other commands if you're using awk

du -arh | sort -nr | awk -v len="$NUM" 'NR>1{gsub("\\.\\/",""); print} NR==len{exit}'

or simply use

... | sed 's_\./__' | head ...


问:
Scala Play 2.5 object ws is not a member of package play.api.libs
I'm trying to use the WS library in Play, but the import shown in all the tutorials I found doesn't work.

Has it changed somehow and the tutorials were not updated or is there something wrong with my setup?

I'm using:
Scala 2.11
Play 2.5

This is in my build.sbt:

```<code>libraryDependencies ++= Seq(
   ws
)
</code>```

This is the import in the code:

```<code>import play.api.libs.ws._
</code>```

And this is the error:

object ws is not a member of package play.api.libs

Note: I saw the WS library was made optional in version 2.4 according to: https://www.playframework.com/documentation/2.4.x/Migration23#Play-WS

I tried using this import: import play.api.Play.current but I still get errors

Any ideas?

答:
Ok after spending a long time debugging, adding removing different version of the WS dependencie, the only thing I hadn't tried was restarting the sbt server.

So the solution is, when you add a new dependency or plugin etc, you must restart your server.

Body:
I'm trying to use the WS library in Play, but the import shown in all the tutorials I found doesn't work.

Has it changed somehow and the tutorials were not updated or is there something wrong with my setup?

I'm using:
Scala 2.11
Play 2.5

This is in my build.sbt:

libraryDependencies ++= Seq(
   ws
)

This is the import in the code:

import play.api.libs.ws._

And this is the error:

object ws is not a member of package play.api.libs

Note: I saw the WS library was made optional in version 2.4 according to: https://www.playframework.com/documentation/2.4.x/Migration23#Play-WS

I tried using this import: import play.api.Play.current but I still get errors

Any ideas?


问:
Joomla 2.5 - How to fix 404 Not Found error after restoration using akeeba kickstart
After kickstarting a Joomla 2.5.22 on a new server in a sub-folder, the only page that works well is the home page, the rest give me (404 Not Found).

Tried many solutions found on the web even on Akeeba website here but still can't solve this issue.

I know that it's a path issue as if I add the sub-folder name in the address of the page that gives 404 error, the page displays properly.

Eg : www.testing.ca/mysub-folder/contact.html  = Works well !!!

How do I dynamically add the sub-folder name for the entire site? or a best solution to solve this?

答:
In your .htaccess file, replace the following:

```<code># RewriteBase
</code>```

With:

```<code>RewriteBase /mysub-folder/
</code>```

Open your configuration.php file, and change:

```<code>$live_site = ''
</code>```

to:

```<code>$live_site = 'http://www.[yourdomain].com';
</code>```

Also in the configuration.php file, change the tmp and the log paths to the correct physical location.

Body:
In your .htaccess file, replace the following:

# RewriteBase

With:

RewriteBase /mysub-folder/

Open your configuration.php file, and change:

$live_site = ''

to:

$live_site = 'http://www.[yourdomain].com';

Also in the configuration.php file, change the tmp and the log paths to the correct physical location.


问:
how to wrap the width of gridview item dynamically in android

I am developing an application in android.i want to set the gridview item dynamically as shown in the below image.someone suggest with a solution .

答:
You can control the size of your item from within the grid adapter - more specifically in your overridden getView() method :

```<code>@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    View v = LayoutInflater.from(ctx).inflate(R.layout.grid_item, null);

    // ...

    AbsListView.LayoutParams lp = new AbsListView.LayoutParams(AbsListView.LayoutParams.
        WRAP_CONTENT, AbsListView.LayoutParams.WRAP_CONTENT);
    lp.width = getResources().getDimensionPixelSize(R.dimen.card_width);
    lp.height = getResources().getDimensionPixelSize(R.dimen.card_height);
    v.setLayoutParams(lp);

    return v;
}
</code>```

Body:
You can control the size of your item from within the grid adapter - more specifically in your overridden getView() method :

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    View v = LayoutInflater.from(ctx).inflate(R.layout.grid_item, null);

    // ...

    AbsListView.LayoutParams lp = new AbsListView.LayoutParams(AbsListView.LayoutParams.
        WRAP_CONTENT, AbsListView.LayoutParams.WRAP_CONTENT);
    lp.width = getResources().getDimensionPixelSize(R.dimen.card_width);
    lp.height = getResources().getDimensionPixelSize(R.dimen.card_height);
    v.setLayoutParams(lp);

    return v;
}


问:
Unable to understand boost function solr query
I am new to solr and trying to understand how boost function works.

Below in an existing query -

```<code>    http://solr_slave_2/solr/datCore/select?indent=on&q=qq=live+scores:+england+vs+new+zealand+champions+trophy&q={!boost+b%3D$dateboost+v%3D$qq+defType%3Ddismax}&dateboost=recip(ms(NOW/DATE,createdDate),3.16e-8,1,1)&defType=dismax&qf=title+subject&fq=(filetype:text)&start=0&rows=20&fl=title,subject,createdDate,score
</code>```

Find below result set of the query above -

```<code>  <doc>
  <str name="subject">
  Get live cricket score & live commentary of 3rd wamp-up match between India vs New Zealand on Times of India.
  </str>
  <str name="title">Champions Trophy, warm-up: India v New Zealand</str>
  <date name="createdDate">2017-05-28T09:33:51Z</date>
  <float name="score">39.4114</float>
  </doc>
  <doc>
  <str name="subject">
  Get all the live updates from Match 6 of the Champions Trophy between England and New Zealand.
  </str>
  <str name="title">Champions Trophy Live: England v New Zealand</str>
  <date name="createdDate">2017-06-06T08:56:29Z</date>
  <float name="score">37.291893</float>
  </doc>
</code>```

Can anybody please help me understand how the above score is being calculated?

Is it on the maximum number of words matched in fields? or is the frequency of individual words used to calculate score? or something else?

Please guide.

Thanks,

Vibhav

P.S - If anybody chooses to down-vote the question, please do mention reason in comments so that I can improve the details in this question.

答:
Without having access to your Solr instance is impossible to figure out how is your score calculated because it depends on a lot of factors (matches, terms, fields, frequencies, etc). My advice just add debugQuery=true to your query and check the debug output that you'll get (one additional section), which among other things contain how is your query transformed and how is the score calculated, be prepared because the output is quite verbose.

I strongly recommend you to use http://splainer.io/ is a really helpful representation of how the score is being calculated and which are the more important factors impacting your scoring.

Body:
I am new to solr and trying to understand how boost function works.

Below in an existing query -

    http://solr_slave_2/solr/datCore/select?indent=on&q=qq=live+scores:+england+vs+new+zealand+champions+trophy&q={!boost+b%3D$dateboost+v%3D$qq+defType%3Ddismax}&dateboost=recip(ms(NOW/DATE,createdDate),3.16e-8,1,1)&defType=dismax&qf=title+subject&fq=(filetype:text)&start=0&rows=20&fl=title,subject,createdDate,score

Find below result set of the query above -

  <doc>
  <str name="subject">
  Get live cricket score & live commentary of 3rd wamp-up match between India vs New Zealand on Times of India.
  </str>
  <str name="title">Champions Trophy, warm-up: India v New Zealand</str>
  <date name="createdDate">2017-05-28T09:33:51Z</date>
  <float name="score">39.4114</float>
  </doc>
  <doc>
  <str name="subject">
  Get all the live updates from Match 6 of the Champions Trophy between England and New Zealand.
  </str>
  <str name="title">Champions Trophy Live: England v New Zealand</str>
  <date name="createdDate">2017-06-06T08:56:29Z</date>
  <float name="score">37.291893</float>
  </doc>

Can anybody please help me understand how the above score is being calculated?

Is it on the maximum number of words matched in fields? or is the frequency of individual words used to calculate score? or something else?

Please guide.

Thanks,

Vibhav

P.S - If anybody chooses to down-vote the question, please do mention reason in comments so that I can improve the details in this question.


问:
Change properties of view inside RemoteView
I have an app widget that has a TextView I need to change textColor, shadowColor, and gravity of.

While I can easily set textColor with view.settextColor() and Gravity with view.setInt(); to the RemoteView, i can't find a way to set shadowColor.

The shadow's color depends on the text's color selected (black on withe or white on black only) and it is needed for legibility.

I tried inflating different layouts with both text and shadow colors already set and it worked, but the widget's definition XML requires a single initial layout to be declared and I'd end up with two identical id's for its textViews, so I don't know if i should.

If i can't set it programmatically what options do i have left?

Thanks.

答:
```<code>public Bitmap buildUpdate(String time)
{
   Bitmap myBitmap = Bitmap.createBitmap(160, 84, Bitmap.Config.ARGB_4444);
   Canvas myCanvas = new Canvas(myBitmap);
   Paint paint = new Paint();
   paint.setAntiAlias(true);
   paint.setSubpixelText(true);
   paint.setStyle(Paint.Style.FILL);
   paint.setColor(Color.WHITE);
   paint.setTextSize(65);
   paint.setTextAlign(Align.CENTER);
   myCanvas.drawText(time, 80, 60, paint);
   return myBitmap;
</code>```

}

```<code>String time = (String) DateFormat.format(mTimeFormat, mCalendar);
RemoteViews views = new RemoteViews(getPackageName(), R.layout.main);
views.setImageViewBitmap(R.id.TimeView, buildUpdate(time));
</code>```

Source : How to use a custom typeface in a widget?

Body:
public Bitmap buildUpdate(String time)
{
   Bitmap myBitmap = Bitmap.createBitmap(160, 84, Bitmap.Config.ARGB_4444);
   Canvas myCanvas = new Canvas(myBitmap);
   Paint paint = new Paint();
   paint.setAntiAlias(true);
   paint.setSubpixelText(true);
   paint.setStyle(Paint.Style.FILL);
   paint.setColor(Color.WHITE);
   paint.setTextSize(65);
   paint.setTextAlign(Align.CENTER);
   myCanvas.drawText(time, 80, 60, paint);
   return myBitmap;

}

String time = (String) DateFormat.format(mTimeFormat, mCalendar);
RemoteViews views = new RemoteViews(getPackageName(), R.layout.main);
views.setImageViewBitmap(R.id.TimeView, buildUpdate(time));

Source : How to use a custom typeface in a widget?


问:
pandas remove rows from dataframe based on multiple conditions without for loops
I have a 6 column pandas data frame data I want to process and remove some rows based on certain conditions. the data frame is tab separated and looks like this:

```<code>RO52_HUMAN  TRIM6_HUMAN 1.83e-136   471 45.86   216
RO52_HUMAN  TRI68_HUMAN 6.46e-127   482 42.946  207
RO52_HUMAN  TRI22_HUMAN 6.49e-121   491 41.344  203
RO52_HUMAN  TRI38_HUMAN 7.15e-117   458 42.358  194
RO52_HUMAN  TRIM5_HUMAN 3.6e-114    499 40.281  201
RO52_HUMAN  TRI39_HUMAN 2.56e-111   490 39.388  193
RO52_HUMAN  TRI11_HUMAN 2.35e-109   471 43.524  205
RO52_HUMAN  TRI27_HUMAN 1.44e-108   495 37.576  186
RO52_HUMAN  TRI34_HUMAN 6.12e-105   500 43.0    215
RO52_HUMAN  TRI17_HUMAN 1.79e-87    461 37.093  171
</code>```

the criteria for removing the rows depends on thefirst two columns only. I also have a dictionary whole keys are protein IDs like those in the first two columns and the values are also a list of other protein IDs. basically I want to remove all the rows if:

the value of the first column is in the dictionary as a key and if the value of the second column is in the values of for that key inside the dictionary. I wrote the reverse logic for this and trying to execute it some how (instead to keep the rows that do not satisfy these conditions) what I wrote is this

```<code>blast_out_filtered_df = blast_out_df[ -blast_out_df[0].isin(homolog_dict.keys()) | (blast_out_df[0].isin(homolog_dict.keys() & -blast_out_df[1].isin(homolog_dict[blast_out_df[0]]) ) ) ]
</code>```

The data frame that I read into my file is called blast_out_df and the new data frame that I'm trying to create with the filtered rows is blast_out_filtered_df.
Ofcrourse running this code is giving me the following error:

```<code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\mstambou\AppData\Local\Continuum\Anaconda\lib\site-
packages\pandas\core\generic.py", line 806, in __hash__
' hashed'.format(self.__class__.__name__))
TypeError: 'Series' objects are mutable, thus they cannot be hashed
</code>```

This is because I'm trying to index the dictionary with the value of a column at a particular row. How can I do this operation efficiently? I implemented it usint .iterrrows() method however I have over a million rows and this is just too slow. Any suggestions? Thank you.

The dictionary looks like this:

```<code>homolog_dict['MAPK5_MOUSE']
['MAPK5_HUMAN']
</code>```

In this case the key is 'MAPK5_MOUSE' and the value is ['MAPK5_HUMAN'] a list of one

答:
was able to find a solution by doing this:

```<code>dct_2 = dict(RO52_HUMAN=['TRI68_HUMAN', 'TRI67_HUMAN'])

blast_out_df[map(isnt_in, zip(blast_out_df[1], blast_out_df[0].map(dct_2)))]
</code>```

and by defining my own function:

```<code>def isnt_in(lst_item):
    if str(lst_item[1])== 'nan':
        return True
    return lst_item[0] not in lst_item[1]
</code>```

The map function on it's own won't cut since the values for my dictionary are lists. Also I had to define my own function because map will return np.nan values if I cant find the keys to that dictionary, the function will return True in these cases for the purpose of this task.

Body:
I have a 6 column pandas data frame data I want to process and remove some rows based on certain conditions. the data frame is tab separated and looks like this:

RO52_HUMAN  TRIM6_HUMAN 1.83e-136   471 45.86   216
RO52_HUMAN  TRI68_HUMAN 6.46e-127   482 42.946  207
RO52_HUMAN  TRI22_HUMAN 6.49e-121   491 41.344  203
RO52_HUMAN  TRI38_HUMAN 7.15e-117   458 42.358  194
RO52_HUMAN  TRIM5_HUMAN 3.6e-114    499 40.281  201
RO52_HUMAN  TRI39_HUMAN 2.56e-111   490 39.388  193
RO52_HUMAN  TRI11_HUMAN 2.35e-109   471 43.524  205
RO52_HUMAN  TRI27_HUMAN 1.44e-108   495 37.576  186
RO52_HUMAN  TRI34_HUMAN 6.12e-105   500 43.0    215
RO52_HUMAN  TRI17_HUMAN 1.79e-87    461 37.093  171

the criteria for removing the rows depends on thefirst two columns only. I also have a dictionary whole keys are protein IDs like those in the first two columns and the values are also a list of other protein IDs. basically I want to remove all the rows if:

the value of the first column is in the dictionary as a key and if the value of the second column is in the values of for that key inside the dictionary. I wrote the reverse logic for this and trying to execute it some how (instead to keep the rows that do not satisfy these conditions) what I wrote is this

blast_out_filtered_df = blast_out_df[ -blast_out_df[0].isin(homolog_dict.keys()) | (blast_out_df[0].isin(homolog_dict.keys() & -blast_out_df[1].isin(homolog_dict[blast_out_df[0]]) ) ) ]

The data frame that I read into my file is called blast_out_df and the new data frame that I'm trying to create with the filtered rows is blast_out_filtered_df.
Ofcrourse running this code is giving me the following error:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\mstambou\AppData\Local\Continuum\Anaconda\lib\site-
packages\pandas\core\generic.py", line 806, in __hash__
' hashed'.format(self.__class__.__name__))
TypeError: 'Series' objects are mutable, thus they cannot be hashed

This is because I'm trying to index the dictionary with the value of a column at a particular row. How can I do this operation efficiently? I implemented it usint .iterrrows() method however I have over a million rows and this is just too slow. Any suggestions? Thank you.

The dictionary looks like this:

homolog_dict['MAPK5_MOUSE']
['MAPK5_HUMAN']

In this case the key is 'MAPK5_MOUSE' and the value is ['MAPK5_HUMAN'] a list of one

Body:
was able to find a solution by doing this:

dct_2 = dict(RO52_HUMAN=['TRI68_HUMAN', 'TRI67_HUMAN'])

blast_out_df[map(isnt_in, zip(blast_out_df[1], blast_out_df[0].map(dct_2)))]

and by defining my own function:

def isnt_in(lst_item):
    if str(lst_item[1])== 'nan':
        return True
    return lst_item[0] not in lst_item[1]

The map function on it's own won't cut since the values for my dictionary are lists. Also I had to define my own function because map will return np.nan values if I cant find the keys to that dictionary, the function will return True in these cases for the purpose of this task.