问:
Declaring a variable as final for Firebase function. Checking if username and email exist
I am trying to make a register page. Before registering that user I will try to validate the username and email do not exist in the database. But I somehow cannot set the variable to be false when the username/email already exist so it will end up still registering the user.

How can I do this? Please guide me on this.

Checking if username and email already exist before register user:

```<code>            if (!checkIfUsernameExists(userName) && !checkIfEmailExists(userEmail)){
            registerUser();
        }
</code>```

Method for checking if the username exists or not:

```<code>    public boolean checkIfUsernameExists(String userName){
    boolean isExist = false;
    databaseReferenceUser.orderByChild("userName").equalTo(userName).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()){
                editTextUserNameRegister.setError("Username already exists");
                editTextUserNameRegister.requestFocus();
                final boolean isExist = true;
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    return isExist;
}
</code>```

Method for checking if the email already exists or not:

```<code>    public boolean checkIfEmailExists(String userEmail){
    boolean isExist = false;
    databaseReferenceUser.orderByChild("userEmail").equalTo(userEmail).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()){
                editTextEmailRegister.setError("Email already exists");
                editTextEmailRegister.requestFocus();
                final boolean isExist = true;
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    return isExist;
}
</code>```

答:
You need your own callback to wait for Firebase to return you data. An example would look like this

Define an interface

```<code>public interface UserCallback {
    void onUserExists(Boolean exists);
}
</code>```

Make your method be void and add the callback parameter, making it final so it can be referenced inside the Firebase method

```<code>public void checkIfEmailExists(String userEmail, final UserCallback callback){
databaseReferenceUser.orderByChild("userEmail").equalTo(userEmail).addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()){
            editTextEmailRegister.setError("Email already exists");
            editTextEmailRegister.requestFocus();
            callback.onUserExists(true);
        } else {
            callback.onUserExists(false);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

// return isExist;  // this method is void now
}
</code>```

Now, you must write the other code functionally rather than procedurally.

```<code>checkIfUsernameExists(userName, new UserCallback() {
    @Override
    public void onUserExists(Boolean exists) {
        if (!exists) {
            checkIfEmailExists(userEmail, new UserCallback() {
                // registerUser() if not exists
             }
        }
     }
} );
</code>```

And if you're storing unique usernames / emails, you should not need to check both

A more complete interface definition can be found here Wait Firebase async retrive data in android

Body:
I am trying to make a register page. Before registering that user I will try to validate the username and email do not exist in the database. But I somehow cannot set the variable to be false when the username/email already exist so it will end up still registering the user.

How can I do this? Please guide me on this.

Checking if username and email already exist before register user:

            if (!checkIfUsernameExists(userName) && !checkIfEmailExists(userEmail)){
            registerUser();
        }

Method for checking if the username exists or not:

    public boolean checkIfUsernameExists(String userName){
    boolean isExist = false;
    databaseReferenceUser.orderByChild("userName").equalTo(userName).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()){
                editTextUserNameRegister.setError("Username already exists");
                editTextUserNameRegister.requestFocus();
                final boolean isExist = true;
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    return isExist;
}

Method for checking if the email already exists or not:

    public boolean checkIfEmailExists(String userEmail){
    boolean isExist = false;
    databaseReferenceUser.orderByChild("userEmail").equalTo(userEmail).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()){
                editTextEmailRegister.setError("Email already exists");
                editTextEmailRegister.requestFocus();
                final boolean isExist = true;
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    return isExist;
}

Body:
You need your own callback to wait for Firebase to return you data. An example would look like this

Define an interface

public interface UserCallback {
    void onUserExists(Boolean exists);
}

Make your method be void and add the callback parameter, making it final so it can be referenced inside the Firebase method

public void checkIfEmailExists(String userEmail, final UserCallback callback){
databaseReferenceUser.orderByChild("userEmail").equalTo(userEmail).addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()){
            editTextEmailRegister.setError("Email already exists");
            editTextEmailRegister.requestFocus();
            callback.onUserExists(true);
        } else {
            callback.onUserExists(false);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

// return isExist;  // this method is void now
}

Now, you must write the other code functionally rather than procedurally.

checkIfUsernameExists(userName, new UserCallback() {
    @Override
    public void onUserExists(Boolean exists) {
        if (!exists) {
            checkIfEmailExists(userEmail, new UserCallback() {
                // registerUser() if not exists
             }
        }
     }
} );

And if you're storing unique usernames / emails, you should not need to check both

A more complete interface definition can be found here Wait Firebase async retrive data in android


来源: stackexchange

问:
SQL querying two sources
I have a View and Table as example below

Table1

```<code>+---------+------+
| Country | City |
+---------+------+
| UK      | LDN  |
| US      | NEY  |
| US      | LAX  |
+---------+------+
</code>```

View1

```<code>+---------+---------+-------+
| Column1 | Column2 | Site  |
+---------+---------+-------+
| Test    | Test2   | UKLDN |
| Test    | Test2   | USNEY |
| Test    | Test2   | USLAX |
| Test    | Test2   | PELMA |
+---------+---------+-------+
</code>```

The result i'm trying to achieve is show all rows from View1, that have a View1.Site column matching Table1.Country and Table1.City. My confusion is how do to it as i'm not an sql person but more C# etc.

The resulting data I want to create is below. I don't know if I can do this solely from View1 or what functions to use.

Result

```<code>+---------+---------+-------+---------------+
| Column1 | Column2 | Site  | ExistInTable1 |
+---------+---------+-------+---------------+
| Test    | Test2   | UKLDN | Y             |
| Test    | Test2   | USNEY | Y             |
| Test    | Test2   | USLAX | Y             |
| Test    | Test2   | PELMA | N             |
+---------+---------+-------+---------------+
</code>```

Thanks

答:
You can try this.</p>

```<code>SELECT V.*, CASE WHEN T.Country IS NULL THEN 'N' ELSE 'Y' END ExistInTable1 FROM View1 V
LEFT JOIN Table1 T ON V.Site = (T.Country + T.City)
</code>```

ContentLicense: CC BY-SA 3.0

Title: SQL querying two sources

Body:
I have a View and Table as example below

Table1

+---------+------+
| Country | City |
+---------+------+
| UK      | LDN  |
| US      | NEY  |
| US      | LAX  |
+---------+------+

View1

+---------+---------+-------+
| Column1 | Column2 | Site  |
+---------+---------+-------+
| Test    | Test2   | UKLDN |
| Test    | Test2   | USNEY |
| Test    | Test2   | USLAX |
| Test    | Test2   | PELMA |
+---------+---------+-------+

The result i'm trying to achieve is show all rows from View1, that have a View1.Site column matching Table1.Country and Table1.City. My confusion is how do to it as i'm not an sql person but more C# etc.

The resulting data I want to create is below. I don't know if I can do this solely from View1 or what functions to use.

Result

+---------+---------+-------+---------------+
| Column1 | Column2 | Site  | ExistInTable1 |
+---------+---------+-------+---------------+
| Test    | Test2   | UKLDN | Y             |
| Test    | Test2   | USNEY | Y             |
| Test    | Test2   | USLAX | Y             |
| Test    | Test2   | PELMA | N             |
+---------+---------+-------+---------------+

Thanks

Body:
You can try this.

SELECT V.*, CASE WHEN T.Country IS NULL THEN 'N' ELSE 'Y' END ExistInTable1 FROM View1 V
LEFT JOIN Table1 T ON V.Site = (T.Country + T.City)


问:
Have a main table auto-update sub-tables on separate worksheets (Excel 2010)
I have been trying to figure this out for a while and although I've found partial answers here and there, I haven't found a complete solution.

Here are the facts:

I'm using Excel 2010 and can't install add-ons or extensions.

Worksheet "All Audits" - This has data relating to all active audits and is our master list.

There is data in columns A:L

There is a header in row 1 and data in the rows below

Column D and E contain primary and secondary audit leads

Manual updates will occur on this sheet

All other worksheets have the same headings and structure

Worksheet "Department1"

This page will list all audits belonging to Department 1 (whether as primary or secondary)

Worksheet "Department2"

This page will list all audits belonging to Department 2 (whether as primary or secondary)

Essentially I want to make it so as audits are updated manually in the main list, Excel will automatically copy/paste the row to the next blank row in the appropriate Department sheet depending on which owner/department is identified in column D and E.

Any help would be tremendously appreciated!

答:
PivotTables would be the best option for this task. They allow you to quickly summarize your data using labels or categories, and allow for slicers that can make the data even easier to consume.

There are numerous ways to design the PivotTable, but it will be up to you to decide what works best for your aesthetic. My recommendation would be to start with formatting your master as a Table (if it isnt already) and then naming it (All_Audits_Master would be a good name). Then in your master list add a column that calculates your two groups. So for example, the formula would look something like:

=If(OR([Primary Department]="Department1", [Secondary Department]="Department1"), "Department1", If(Or([Primary Department]="Department2", [Secondary Department]="Department2"), "Department2", "")

This formula may look complicated at first, but all it does is uses the column names [Some Name] to check for a value, and labels the calculated column appropriately. If the record doesn't belong to either department, it returns a blank string.

Once you have that column (be sure to put it at the end so it doesn't interfere with pasting in your data) you just need two pivot tables. The first will use a filter for Department1, the second for Department2.

From there, I would put each of your columns that you want in your report within the Rows field. You can also use values if you want to summarize anything. For example, you could put a Count of RecordID into Values to count the number of records by department.

Ultimately there will be some up-front time cost of learning PivotTables but I assure you that if you can't use PivotTables yet, you will not want to mess with VBA. I spent literal months learning things in VBA that a PivotTable could have done for me in minutes. Additionally, once you do learn Pivot's more thoroughly, a lot more concepts will make sense (and will be available to you) in VBA.

Check out this tutorial to get started if you are a more visual learner: https://www.youtube.com/watch?v=peNTp5fuKFg.

EDIT: The only thing to note is that the pivot table won't auto update. You have two options there:

Have users refresh the pivot after updating the master (Data > Refresh or Refresh All), or write a macro that handles that (using events, but this is not recommended unless as a last resort).


问:
Git_can't push locate update to remote branch successfully
```<code> $git log
 commit e9b08e2b428f9dd58aa0b792ebeb29da4270dfab (HEAD -> master)

 $git remote -v
 origin  https://github.com/Shell_learning (fetch)
 origin  https://github.com/Shell_learning (push)

 $git branch -a
 * master

 $git push -u origin master
 remote: Not Found
 fatal: repository 'https://github.com/Shell_learning/' not found

 $git remote add origin https://github.com/ekoopgj/Shell_learning
 fatal: remote origin already exists.
 #It is really strange that the repository already exists ,but I can't push my local update to remote branch.
</code>```

I have created a repository in my github like below:

So , please tell me what's the issue.

答:
The URL you're currently using for your origin remote is not correct. The format for a GitHub repository URL should follow https://github.com/username/repository.git

Once you have defined a remote, you can't change it by using git remote add - you have to use git remote set-url.

This script should update your origin to the correct URL.

```<code>git remote set-url origin https://github.com/ekoopgj/Shell_learning.git
</code>```

Body:
 $git log
 commit e9b08e2b428f9dd58aa0b792ebeb29da4270dfab (HEAD -> master)

 $git remote -v
 origin  https://github.com/Shell_learning (fetch)
 origin  https://github.com/Shell_learning (push)

 $git branch -a
 * master

 $git push -u origin master
 remote: Not Found
 fatal: repository 'https://github.com/Shell_learning/' not found

 $git remote add origin https://github.com/ekoopgj/Shell_learning
 fatal: remote origin already exists.
 #It is really strange that the repository already exists ,but I can't push my local update to remote branch.

I have created a repository in my github like below:

So , please tell me what's the issue.

Body:
The URL you're currently using for your origin remote is not correct. The format for a GitHub repository URL should follow https://github.com/username/repository.git

Once you have defined a remote, you can't change it by using git remote add - you have to use git remote set-url.

This script should update your origin to the correct URL.

git remote set-url origin https://github.com/ekoopgj/Shell_learning.git


问:
Loop through all pixels and get/set individual pixel color in OpenGL?
I wrote a little thingy with Processing that I now would like to make a Mac OS X Screen Saver of. However, diving in to OpenGL was not as easy as I thought it would be.

Basically I want to loop through all pixels on screen and based on that pixels color set another pixels color.

The Processing code looks like this:

```<code>void setup(){
  size(500,500, P2D);
  frameRate(30);
  background(255);
}

void draw(){
 for(int x = 0; x<width; x++){
  for(int y = 0; y<height; y++){
     float xRand2 = x+random(2);
     float yRand2 = y+random(2);

     int xRand = int(xRand2);
     int yRand = int(yRand2);

     if(get(x,y) == -16777216){
     set(x+xRand, y+yRand, #FFFFFF);
     }
     else if(get(x,y) == -1){
     set(x+xRand, y+yRand, #000000);
     }
   }
 }
}
</code>```

It's not very pretty and nor is it very effective. However, I'd like to find out how to do something similiar with OpenGL. I don't even know where to start.

答:
The basic idea of OpenGL is that you never set the values of individual pixels manually, because that's often too slow. Instead you render triangles and do all kinds of tricks with them, like textures, blending, etc.

In order to freely program what each individual pixel does in OpenGL, you need to use a technique called shaders. And that's not very easy if you haven't done anything similar before. The idea of shaders is that GPU executes them instead of CPU, which results in very good performance and takes the load off from the CPU. But in your case it is probably a better idea to do it with CPU and not with shaders and OpenGL, as that approach is much easier to start with.

I recommend you use a library like SDL (or possibly glfw), which lets you do things with pixels without hardware acceleration. You can still do it with OpenGL too, though. By using the function glDrawPixels. That function draws raw pixel data to the screen. But it's probably not very fast.

So start by reading some tutorials about SDL, for example.

Edit: If you want to use shaders, the difficulty with them (among other things) is that you can't specify coordinates to which set pixel values. And you can't get pixel values directly from the screen either. One way to do it with shaders would be the following:

Set up two textures: texture A and texture B

Bind one of the textures as a target that you render everything to

Bind another one of the textures as an input texture for the shader

Render a full-screen quadrangle using your shader and show the result on the screen

Swap textures A and B so you became to use your previous result as your next input

Render again

ContentLicense: CC BY-SA 2.5

Body:
I wrote a little thingy with Processing that I now would like to make a Mac OS X Screen Saver of. However, diving in to OpenGL was not as easy as I thought it would be.

Basically I want to loop through all pixels on screen and based on that pixels color set another pixels color.

The Processing code looks like this:

void setup(){
  size(500,500, P2D);
  frameRate(30);
  background(255);
}

void draw(){
 for(int x = 0; x<width; x++){
  for(int y = 0; y<height; y++){
     float xRand2 = x+random(2);
     float yRand2 = y+random(2);

     int xRand = int(xRand2);
     int yRand = int(yRand2);

     if(get(x,y) == -16777216){
     set(x+xRand, y+yRand, #FFFFFF);
     }
     else if(get(x,y) == -1){
     set(x+xRand, y+yRand, #000000);
     }
   }
 }
}

It's not very pretty and nor is it very effective. However, I'd like to find out how to do something similiar with OpenGL. I don't even know where to start.


问:
`pointer-events: none;` does not work for iframe in Edge
I'm applying pointer-events: none; on iframe, it works fine in all major browsers except for the Edge (tested with Edge 16).
In Edge, I still can click anything inside the iframe. I've also tried to apply the styling to iframe's parent div, but nothing works.
Note: I can't apply it inside of the iframe

```<code><div style="pointer-events: none;">
  <iframe>...</iframe>
</div>

<iframe style="pointer-events: none;">...</iframe>
</code>```

Is there a workaround?
Thanks!

答:
True, that CSS property it's kind of buggy. Try to add inside app.css the property:

```<code>.upgrade-banner .row .col.upgrade {
    ...
    pointer-events: none;
}
</code>```

to all the clickable items inside your iframe.

Testing this from browserstack (Edge 16) works fine:

Body:
I'm applying pointer-events: none; on iframe, it works fine in all major browsers except for the Edge (tested with Edge 16).
In Edge, I still can click anything inside the iframe. I've also tried to apply the styling to iframe's parent div, but nothing works.
Note: I can't apply it inside of the iframe

  ...

...

Is there a workaround?
Thanks!

Body:
True, that CSS property it's kind of buggy. Try to add inside app.css the property:

.upgrade-banner .row .col.upgrade {
    ...
    pointer-events: none;
}

to all the clickable items inside your iframe.

Testing this from browserstack (Edge 16) works fine:


问:
Selecting specific part of an HTML text
I have a function that returns some HTML fragment that I store in a variable called data, with its whole structure. What I want is to extract from it some of those parts.

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script id="hello">

    </script>
</head>
<body>

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

For example, I want to get the body and save it in a new variable:

```<code>var body = data.split("<body")[1].split(">").slice(1).join(">").split("</body>")[0];
</code>```

Where data is the HTML text as a string that the original function is returning.

Is there any way I could save an specific script, from its ID (in this case with id = hello), and save it in another variable??

Thank you very much

答:
$html = document.querySelector("body").innerHTML;
$hello = document.getElementById("hello").innerHTML;
console.log($html);
console.log($hello);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script id="hello">
        // script data
    </script>
</head>
<body>

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

Title: Selecting specific part of an HTML text

Body:
I have a function that returns some HTML fragment that I store in a variable called data, with its whole structure. What I want is to extract from it some of those parts.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

For example, I want to get the body and save it in a new variable:

var body = data.split("").slice(1).join(">").split("")[0];

Where data is the HTML text as a string that the original function is returning.

Is there any way I could save an specific script, from its ID (in this case with id = hello), and save it in another variable??

Thank you very much

Body:
$html = document.querySelector("body").innerHTML;
$hello = document.getElementById("hello").innerHTML;
console.log($html);
console.log($hello);

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script id="hello">
        // script data
    </script>
</head>
<body>

</body>
</html>


问:
advanced custom field -wordpress+ repeater
I combined a slider with the repeater fields.
under the repeater I have 2 subfields. one called “image” and the other “title”

this slider has a class called “selected-item” that dynamically appear when an image is selected. (when this class is on an image the image change it’s size).

How can I define that when the class “selected-item” is on some image also the “title” form the same row of the image will appear?

this is the code the displays the images:

```<code>    <?php

// check if the repeater field has rows of data
 $i = 1;
if( have_rows('carousel_images') ):
    // loop through the rows use_cases_fields data
    while ( have_rows('carousel_images') ) : the_row();
          $title=get_sub_field('image_carousel_discription');
        $image = get_sub_field('image_carousel1');

        if( !empty($image) ):
            // vars

            // thumbnail
            $thumb = $image;

            $i++;

            ?>

   <h1 data-row="< echo $i; >">   <?php echo $title ?>     </h1>
                <li> <a href="#home"><img  data-row="< echo $i; >" src="<?php echo $thumb ?>"/></a> </li>

        <?php endif; ?>

        <?php
    endwhile;
endif;
?>
</code>```

?>

答:
Keep the title hidden in the beginning and then show the title when selected-item class is applied. If h1 is going to be always next to the image tag then use the + selector.

```<code>h1 { display: none; }
.selected-item + h1 { display: block; }
</code>```

Or you can detect a class change event using jquery.

function checkForChanges()
{
    if ($('img').hasClass('selected-item'))
        $('h1').css('display','block');
    else
        setTimeout(checkForChanges, 500);
}

checkForChanges();

$("#click").on('click', function(){
    $('img').addClass("selected-item");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>    h1 { display: none; } /* Keep the title hidden in the beginning */
     /* Show the title when selected-item class is applied */</code>```

title

click me
```

ContentLicense: CC BY-SA 4.0

Body:
I combined a slider with the repeater fields.
under the repeater I have 2 subfields. one called “image” and the other “title”

this slider has a class called “selected-item” that dynamically appear when an image is selected. (when this class is on an image the image change it’s size).

How can I define that when the class “selected-item” is on some image also the “title” form the same row of the image will appear?

this is the code the displays the images:

    <?php

// check if the repeater field has rows of data
 $i = 1;
if( have_rows('carousel_images') ):
    // loop through the rows use_cases_fields data
    while ( have_rows('carousel_images') ) : the_row();
          $title=get_sub_field('image_carousel_discription');
        $image = get_sub_field('image_carousel1');

        if( !empty($image) ):
            // vars

            // thumbnail
            $thumb = $image;

            $i++;

            ?>

   <h1 data-row="< echo $i; >">   <?php echo $title ?>

 <img  data-row="< echo $i; >" src="<?php echo $thumb ?>"/>

        <?php endif; ?>

        <?php
    endwhile;
endif;
?>

?>

Body:
Keep the title hidden in the beginning and then show the title when selected-item class is applied. If h1 is going to be always next to the image tag then use the + selector.

h1 { display: none; }
.selected-item + h1 { display: block; }

Or you can detect a class change event using jquery.

function checkForChanges()
{
    if ($('img').hasClass('selected-item'))
        $('h1').css('display','block');
    else
        setTimeout(checkForChanges, 500);
}

checkForChanges();

$("#click").on('click', function(){
    $('img').addClass("selected-item");
});

    h1 { display: none; } /* Keep the title hidden in the beginning */
     /* Show the title when selected-item class is applied */

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<img src="http://via.placeholder.com/100x100" width="100" height="100">
<h1>title</h1>
<div id="click">click me</div>


问:
Logical algorithm to generate paths
I'm trying to develop an algorithm to create a symfony template service.
I want to check if a template exists in a subset of paths, ordered.

Given an array of parameter like this (already ordered like I want):

```<code>$params = ['O', 'U', 'W', 'P']
</code>```

How can I output this array?

```<code>$urls = [
    'O/U/W/P/template',
    'O/U/W/template',
    'O/U/P/template',
    'O/U/template',
    'O/W/P/template',
    'O/W/template',
    'O/P/template',
    'O/template',
    'U/W/P/template',
    'U/W/template',
    'U/P/template',
    'U/template',
    'W/P/template',
    'W/template',
    'P/template',
    'template'
];
</code>```

I can perform for a little list of parameters (like everyone can do it I suppose) with a code like this :

```<code>private function getPaths($template, $params)
{
    $urls           = [];
    $alreadyPerform = [];
    $paramsCounter = count($params);

    for ($i = 0; $i < $paramsCounter; $i++) {
        for ($j = 0; $j < $paramsCounter; $j++) {
            if ($i !== $j && !in_array($params[$j], $alreadyPerform, true)) {
                $urls[] = sprintf(
                    '/%s/%s/%s.html.twig', $params[$i], $params[$j], $template
                );
            }
        }
        $alreadyPerform[] = $params[$i];
        $urls[] = sprintf('/%s/%s.html.twig', $params[$i], $template);
    }
    $urls[] = sprintf('%s.html.twig', $template);

    return $urls;
}
</code>```

This function work like I wanted until today (max 3 parameters), but I want to add one parameters today, maybe more after.

Thank you very much for your help !

Cheers.

答:
Using recursion, you can do the following:

```<code>/**
 * @param array $elements
 * @param array $extra
 *
 * @return Generator
 */
function gen(array $elements, array $extra = []): \Generator {

    foreach ($elements as $i => $head) {
        foreach (gen(array_slice($elements, $i + 1), $extra) as $tail) {
            yield array_merge([$head], $tail);
        }
    }

    yield $extra;
}
</code>```

demo: https://3v4l.org/gJB8q

Or without recursion:

```<code>/**
 * @param array $elements
 *
 * @return Generator
 */
function gen2(array $elements): \Generator {

    for ($num = count($elements), $i = pow(2, $num) - 1; $i >= 1; $i -= 2) {
        $r = [];
        for ($j = 0; $j < $num; $j += 1) {
            if ($i & (1 << ($num - $j - 1))) {
                $r[] = $elements[$j];
            }
        }

        yield $r;
    }
}
</code>```

demo: https://3v4l.org/grKXo

Title: Logical algorithm to generate paths

Body:
I'm trying to develop an algorithm to create a symfony template service.
I want to check if a template exists in a subset of paths, ordered.

Given an array of parameter like this (already ordered like I want):

$params = ['O', 'U', 'W', 'P']

How can I output this array?

$urls = [
    'O/U/W/P/template',
    'O/U/W/template',
    'O/U/P/template',
    'O/U/template',
    'O/W/P/template',
    'O/W/template',
    'O/P/template',
    'O/template',
    'U/W/P/template',
    'U/W/template',
    'U/P/template',
    'U/template',
    'W/P/template',
    'W/template',
    'P/template',
    'template'
];

I can perform for a little list of parameters (like everyone can do it I suppose) with a code like this :

private function getPaths($template, $params)
{
    $urls           = [];
    $alreadyPerform = [];
    $paramsCounter = count($params);

    for ($i = 0; $i < $paramsCounter; $i++) {
        for ($j = 0; $j < $paramsCounter; $j++) {
            if ($i !== $j && !in_array($params[$j], $alreadyPerform, true)) {
                $urls[] = sprintf(
                    '/%s/%s/%s.html.twig', $params[$i], $params[$j], $template
                );
            }
        }
        $alreadyPerform[] = $params[$i];
        $urls[] = sprintf('/%s/%s.html.twig', $params[$i], $template);
    }
    $urls[] = sprintf('%s.html.twig', $template);

    return $urls;
}

This function work like I wanted until today (max 3 parameters), but I want to add one parameters today, maybe more after.

Thank you very much for your help !

Cheers.

Body:
Using recursion, you can do the following:

/**
 * @param array $elements
 * @param array $extra
 *
 * @return Generator
 */
function gen(array $elements, array $extra = []): \Generator {

    foreach ($elements as $i => $head) {
        foreach (gen(array_slice($elements, $i + 1), $extra) as $tail) {
            yield array_merge([$head], $tail);
        }
    }

    yield $extra;
}

demo: https://3v4l.org/gJB8q

Or without recursion:

/**
 * @param array $elements
 *
 * @return Generator
 */
function gen2(array $elements): \Generator {

    for ($num = count($elements), $i = pow(2, $num) - 1; $i >= 1; $i -= 2) {
        $r = [];
        for ($j = 0; $j < $num; $j += 1) {
            if ($i & (1 << ($num - $j - 1))) {
                $r[] = $elements[$j];
            }
        }

        yield $r;
    }
}

demo: https://3v4l.org/grKXo


问:
"Security" problem with NHibernate on deployed web application
I've deployed to a server a web application that uses NHibernate. The application compiles and runs fine on my local dev machine, but there's an issue with NHibernate on the new server. I get the following error:

Description: The application attempted
  to perform an operation not allowed by
  the security policy.  To grant this
  application the required permission
  please contact your system
  administrator or change the
  application's trust level in the
  configuration file.

Exception Details:
  System.Security.SecurityException:
  Request for the permission of type
  'System.Configuration.ConfigurationPermission,
  System.Configuration, Version=4.0.0.0,
  Culture=neutral,
  PublicKeyToken=tokenkeyhere'
  failed.

It suggests to change the application's "trust level" in the configuration file. How exactly do I do that? This is the first time I've deployed a NHibernate web app, so I'm at a loss.

答:
We've been looking at this a lot lately.  Here is a link on running NHibernate in medium trust

This is the most succinct explanation I've seen of the different trust levels: Trust Levels Demystified

From the article:

```<code>- Full trust – your code can do anything that the account running it can do.
- High trust – same as above except your code cannot call into unmanaged code. i.e. Win32 APIs, COM interop.
- Medium trust – same as above except your code cannot see any part of the file system except its application directory.
- Low trust – same as above except your code cannot make any out-of-process calls. i.e. calls to a database, network, etc.
- Minimal trust – code is restricted from anything but the most trival processing (calculating algorithms).
</code>```

Body:
We've been looking at this a lot lately.  Here is a link on running NHibernate in medium trust

This is the most succinct explanation I've seen of the different trust levels: Trust Levels Demystified

From the article:

- Full trust – your code can do anything that the account running it can do.
- High trust – same as above except your code cannot call into unmanaged code. i.e. Win32 APIs, COM interop.
- Medium trust – same as above except your code cannot see any part of the file system except its application directory.
- Low trust – same as above except your code cannot make any out-of-process calls. i.e. calls to a database, network, etc.
- Minimal trust – code is restricted from anything but the most trival processing (calculating algorithms).


问:
Status bar is hidden but the tint is still seen
I have an Android app which has a activity that plays a video. While usually some activities in my app have dynamic status bar color, I have hidden the status bar when the video activity is in landscape. But even if I hide the status bar by fullscreen, the tint for the status bar still remains. Please tell me how I can hide the status bar tint.

Code for setting the status bar color

```<code> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                SystemBarTintManager tintManager = new SystemBarTintManager(((Activity) context));
                tintManager.setStatusBarTintEnabled(true);
                tintManager.setNavigationBarTintEnabled(false);
                tintManager.setTintColor(Color.parseColor("#" + dynamicColor));
                float f = Float.parseFloat(".7");
                tintManager.setTintAlpha(f);
            }
</code>```

The code I use for removing the status bar color

```<code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                SystemBarTintManager tintManager = new SystemBarTintManager(this);
                tintManager.setStatusBarTintEnabled(false);
                tintManager.setNavigationBarTintEnabled(false);
                float f = Float.parseFloat("0");
                tintManager.setTintAlpha(f);
                getWindow().setStatusBarColor(Color.TRANSPARENT);
            }
</code>```

Now in the tint removing code, I have set the flag setStatusBarEnabled to false. Even setStatusBarColor  is TRANSPARENT. Any help will be greatly appreciated.

答:
Try this:

```<code>View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
ActionBar actionBar = getActionBar();
actionBar.hide();
</code>```

These flags get reset once you move to a different view or activity.

Body:
I have an Android app which has a activity that plays a video. While usually some activities in my app have dynamic status bar color, I have hidden the status bar when the video activity is in landscape. But even if I hide the status bar by fullscreen, the tint for the status bar still remains. Please tell me how I can hide the status bar tint.

Code for setting the status bar color

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                SystemBarTintManager tintManager = new SystemBarTintManager(((Activity) context));
                tintManager.setStatusBarTintEnabled(true);
                tintManager.setNavigationBarTintEnabled(false);
                tintManager.setTintColor(Color.parseColor("#" + dynamicColor));
                float f = Float.parseFloat(".7");
                tintManager.setTintAlpha(f);
            }

The code I use for removing the status bar color

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                SystemBarTintManager tintManager = new SystemBarTintManager(this);
                tintManager.setStatusBarTintEnabled(false);
                tintManager.setNavigationBarTintEnabled(false);
                float f = Float.parseFloat("0");
                tintManager.setTintAlpha(f);
                getWindow().setStatusBarColor(Color.TRANSPARENT);
            }

Now in the tint removing code, I have set the flag setStatusBarEnabled to false. Even setStatusBarColor  is TRANSPARENT. Any help will be greatly appreciated.

Body:
Try this:

View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
ActionBar actionBar = getActionBar();
actionBar.hide();

These flags get reset once you move to a different view or activity.


问:
Changing Type from Content To Global or VDC Drupal
I'm using Drupal 7 with the view_database_connector module. I'm currently working with a view that consists of a table displaying database information. My goal is to have a field with action buttons corresponding to each row, such as delete.

I am not allowed to use global php as a field.

I've attempted to make a custom module following this. I can currently use this module on content tables, however, when I try to use it on my view_database_connector table, I'm unable to add it as a field, since it's not apart of the same group.

Here's where I set up the information for making the action:

```<code>function mymodule_views_data_alter(&$data) {
  // debug($data['node']);
  $data['node']['actions'] = array(
    'title' => t('Actions'),
    'help' => t('Clickable links to actions a user may perform on a Node.'),
    'field' => array(
      'handler' => 'mymodule_views_handler_field_actions',
      'group' => 'Content',
      'click sortable' => FALSE,
    ),
  );
}
</code>```

I've tried deleting Content, changing it to global, and changing it to the VDC type, but none of that changes it into Global or VDC.

Alternatively, if there's an easier way just to hook into a field that has a button to run my code which will download a file, that could circumvent this issue.

答:
You don't have to create this feature on your own - it already exists in views. There is a field type with actions as delete.

Other option is to use option called "rewrite value of this field" (or similar). With it you can make your field from views interface, and totally rewrite it's output. You can use token and some of them for sure contains node id, so you can use it to generate link to node deleting/editing/viewing pages.

Body:
I'm using Drupal 7 with the view_database_connector module. I'm currently working with a view that consists of a table displaying database information. My goal is to have a field with action buttons corresponding to each row, such as delete.

I am not allowed to use global php as a field.

I've attempted to make a custom module following this. I can currently use this module on content tables, however, when I try to use it on my view_database_connector table, I'm unable to add it as a field, since it's not apart of the same group.

Here's where I set up the information for making the action:

function mymodule_views_data_alter(&$data) {
  // debug($data['node']);
  $data['node']['actions'] = array(
    'title' => t('Actions'),
    'help' => t('Clickable links to actions a user may perform on a Node.'),
    'field' => array(
      'handler' => 'mymodule_views_handler_field_actions',
      'group' => 'Content',
      'click sortable' => FALSE,
    ),
  );
}

I've tried deleting Content, changing it to global, and changing it to the VDC type, but none of that changes it into Global or VDC.

Alternatively, if there's an easier way just to hook into a field that has a button to run my code which will download a file, that could circumvent this issue.


问:
'Show' segue in Xcode 6 presents the viewcontroller as a modal in iOS 7
I have two view controllers in my iPhone application (built with swift) built with Xcode 6.1 and uses storyboards.

The first view controller is embedded in a navigation controller in the storyboard and the segue for the second view controller is a 'Show' segue.

When the application is run, it properly shows the transition as a push in iOS 8.x, but in iOS 7.x it appears as a modal without the navigation bar.

My application requirement is to show the transition as a push regardless of whether it's iOS 7 or iOS 8. Any ideas to get this working as push in both versions of the iOS?

I saw a related post where this issue is mentioned, but could not find a solution to the problem: Adaptive segue in storyboard Xcode 6. Is push deprecated?

Any help is appreciated...

Thanks

答:
When a "Show" segue comes up as a modal segue in testing it is usually one of two problems:

The first view controller is not inside a navigation controller.

The storyboard XML is corrupted.

The solution to #2 is usually to remove and replace the segue, and it should correct itself. Sometimes just switching to some other presentation style, running, and switching back to "Show" fixes it.

This can also happen to "Show Detail" segues, and it can be more insidious.

Example:
I have a series of view controllers arranged in a UISplitViewController. They have segues Show->Show->Show->Show Detail. The last segue kept coming up modal. I tried everything to fix that last segue. The problem was that the upstream Show segue had been corrupted into a Show Detail segue (even though the storyboard still said it was a Show segue). I had been testing on iPhone, and I did not discover the real problem until I ran it on the iPad simulator. The segues were now Show->Show->Show Detail->Show Detail. On the iPhone the third segue looked just like a Show because it collapsed onto the navigation controller. However, it is still the detail view controller, and you cannot have a Show Detail from a detail view controller, so the OS does what it can to get your view controller on screen and displays it modally.

Lesson 1: Always test your UISplitViewController on iPad to make sure the segues are doing what you think.

Lesson 2: If your segue is coming up modal unexpectedly, check the upstream segues for corruption as well as the segue in question.


问:
Get IIS bindings at runtime
I wonder how to get the IIS binding settings of the current site (host name, port, IP address) at runtime using ASP.NET.
Does .NET provide any way to get these information?

Edit: I need a way to get the http and https ports configured to redirect to the right port when switching from http to https, and back from https to http if other ports then 80/443 are used. Is there a way to do this without extended privileges?

Regards

答:
The only way to achieve that (without being an administrator) is using Microsoft.Web.Administration. I just wrote a quick blog on how to do that, see:

http://blogs.msdn.com/b/carlosag/archive/2011/01/21/get-iis-bindings-at-runtime-without-being-an-administrator.aspx

Basically since IIS has a feature we call Worker Process isolation it is possible to read the configuration from an Application itself without the need of being administrator. If you use ADSI, Metabase, or any other way, you will require being an administrator.

Title: Get IIS bindings at runtime


问:
How to differentiate the summary from the description in TortoiseGit commits?
On Github, for example, we can put a Summary message in the commits, but we can also put a Description message, so when a colaborator wants to see a description of the commit, he can know more details of it:

How can we do it when commiting a message in TortoiseGit, as he only gives you 1 input to write your message?

答:
That's just an additional input field on GitHub. Both lines are concatenated with an empty line.

So, in TortoiseGit just use an empty line as separator (that's the official git convention: use the first line as subject and the following lines as body/description, cf. https://git-scm.com/docs/git-commit#_discussion and https://chris.beams.io/posts/git-commit/).


问:
Excel VBA - Sub not finishing after Call with Target
I'm trying to make an a Worksheet that adapts depending on the different selections on the page. There are 3 cells wills drop down lists that will modify the page depending on the selected value. When I launch the sub directly in the Worksheet_SelectionChange it works without problems (as it's only one) but as I needed 3 I wanted to launch it depending on which cell you select. The problem I have now is that the selection works (test done with Showmsg) but everything that should happen after doesn't.

```<code>Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Selection.Count = 1 Then
        If Not Intersect(Target, Range("D25")) Is Nothing Then
            Call LineBlock_Change(Target)
        End If
    End If
End Sub

---------

Sub LineBlock_Change(ByVal Target As Range) 'D25
    Select Case Target
    Case "Non Protected / Non Redundant"
        ' Affichage 1 Ligne
        Columns("J:O").Hidden = True
    Case Else
        ' Affichage 2 Ligne
        Columns("J:O").Hidden = False
    End Select
End Sub
</code>```

The thing is that when I use the same code of the Sub in Worksheet_SelectionChange(with a limitation on the Cell that can be selected) It does work but while trying to lunch with a Sub it doesn't. I personnaly don't know if it can be followed up like that or if I need to rethink the way of doing it.

Thanks in advance for any help.

Update : As I noticed that I might have some problems really explain what I can't do I will try an other approach.
I have this code :

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Count > 1 Then Exit Sub
    If Target.Address <> "$D$25" Then Exit Sub
    Select Case Target
     Case "Non Protected / Non Redundant"
        ' Affichage 1 Ligne
        Columns("J:O").Hidden = True
    Case Else
       ' Affichage 2 Ligne
        Columns("J:O").Hidden = False
    End Select
End Sub
</code>```

It does exactly what I desire, when D25 has the string : "Non Protected / Non Redundant" it hides the Columns J:O. Now my problem is that D25 is not the only condition that I wish to have that will hide/unhide columns/rows. And such I'm trying to write a code that would launch a sub depending on which Cell is selected and what is inside of it.
Though when I try to write the code in a way that it would work as a sub it doesn't reacts the way I would like (hiding the columns).

答:
```<code>Sub LineBlock_Change(ByVal Target As Range) 'D25

    Stop '<-  see what happens
    Select Case Target

    Case "Non Protected / Non Redundant"
        ' Affichage 1 Ligne
        Columns("J:O").Hidden = True
    Case Else
        ' Affichage 2 Ligne
        Columns("J:O").Hidden = False
    End Select

End Sub
</code>```

The problem in LineBlock are the following:

Column should be Columns()

Columns("J:O").EntireRow.Hidden = True hides the whole worksheeet. That's great! But you probably need to remove the EntireRow part.

Edit:

Upon the update, reading that "D25 is not the only condition that I wish to have that will hide/unhide columns/rows" this is what you should do:

```<code>Select Case True

    Case Target = "Non Protected / Non Redundant"
        'some action
    Case Range("A1") = "something else"
        'some other action
    Case Else
        Columns("J:O").Hidden = False
End Select
</code>```

Body:
I'm trying to make an a Worksheet that adapts depending on the different selections on the page. There are 3 cells wills drop down lists that will modify the page depending on the selected value. When I launch the sub directly in the Worksheet_SelectionChange it works without problems (as it's only one) but as I needed 3 I wanted to launch it depending on which cell you select. The problem I have now is that the selection works (test done with Showmsg) but everything that should happen after doesn't.

Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Selection.Count = 1 Then
        If Not Intersect(Target, Range("D25")) Is Nothing Then
            Call LineBlock_Change(Target)
        End If
    End If
End Sub

---------

Sub LineBlock_Change(ByVal Target As Range) 'D25
    Select Case Target
    Case "Non Protected / Non Redundant"
        ' Affichage 1 Ligne
        Columns("J:O").Hidden = True
    Case Else
        ' Affichage 2 Ligne
        Columns("J:O").Hidden = False
    End Select
End Sub

The thing is that when I use the same code of the Sub in Worksheet_SelectionChange(with a limitation on the Cell that can be selected) It does work but while trying to lunch with a Sub it doesn't. I personnaly don't know if it can be followed up like that or if I need to rethink the way of doing it.

Thanks in advance for any help.

Update : As I noticed that I might have some problems really explain what I can't do I will try an other approach.
I have this code :

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Count > 1 Then Exit Sub
    If Target.Address <> "$D$25" Then Exit Sub
    Select Case Target
     Case "Non Protected / Non Redundant"
        ' Affichage 1 Ligne
        Columns("J:O").Hidden = True
    Case Else
       ' Affichage 2 Ligne
        Columns("J:O").Hidden = False
    End Select
End Sub

It does exactly what I desire, when D25 has the string : "Non Protected / Non Redundant" it hides the Columns J:O. Now my problem is that D25 is not the only condition that I wish to have that will hide/unhide columns/rows. And such I'm trying to write a code that would launch a sub depending on which Cell is selected and what is inside of it.
Though when I try to write the code in a way that it would work as a sub it doesn't reacts the way I would like (hiding the columns).

Body:
Sub LineBlock_Change(ByVal Target As Range) 'D25

    Stop '<-  see what happens
    Select Case Target

    Case "Non Protected / Non Redundant"
        ' Affichage 1 Ligne
        Columns("J:O").Hidden = True
    Case Else
        ' Affichage 2 Ligne
        Columns("J:O").Hidden = False
    End Select

End Sub

The problem in LineBlock are the following:

Column should be Columns()

Columns("J:O").EntireRow.Hidden = True hides the whole worksheeet. That's great! But you probably need to remove the EntireRow part.

Edit:

Upon the update, reading that "D25 is not the only condition that I wish to have that will hide/unhide columns/rows" this is what you should do:

Select Case True

    Case Target = "Non Protected / Non Redundant"
        'some action
    Case Range("A1") = "something else"
        'some other action
    Case Else
        Columns("J:O").Hidden = False
End Select


问:
Multidimensional array with jquery templates
I have the following javascript object

```<code>var arr = [
    [
        { "id": 1, "name": "one" },
        { "id": 2, "name": "two" },
        { "id": 3, "name": "three" }
    ],
    [
        { "id": 4, "name": "four" },
        { "id": 5, "name": "five" },
        { "id": 6, "name": "six" }
    ],
]
</code>```

I'm trying to use jquery templates to create the following HTML

```<code><div class="row">
    <div class="cell">
        <span>1</span> : <span>one</span>
    </div>
    <div class="cell">
        <span>2</span> : <span>two</span>
    </div>
    <div class="cell">
        <span>3</span> : <span>three</span>
    </div>
</div>
<div class="row">
    <div class="cell">
        <span>4</span> : <span>four</span>
    </div>
    <div class="cell">
        <span>5</span> : <span>five</span>
    </div>
    <div class="cell">
        <span>6</span> : <span>six</span>
    </div>
</div>
</code>```

I am using the following templates with no luck :(

```<code><script id="rowTemplate" type="text/x-jQuery-tmpl">
    <div class="row">
        {{tmpl "#cellTemplate"}}
    </div>
</script>
<script id="cellTemplate" type="text/x-jQuery-tmpl">
    <div class="cell">
        <span>${id}</span> : <span>${name}</span>
    </div>
</script>
</code>```

The line that calls the template is the following:

```<code>$("#rowTemplate").tmpl(arr).replaceAll("#somediv");
</code>```

I am getting only one row with one cell with no data...

```<code><div class="row">
    <div class="cell">
        <span></span> : <span></span>
    </div>
</div>
</code>```

What am I doing wrong?

答:
I think the problem is with usage of replaceAll and the missing parameter to tmpl in the template.
Try this(used replaceWith for #someDiv and passed $data as tmpl parameter for child template):</p>

```<code><script type="text/javascript">
    var arr =
    [
        [
            {
                    "id": 1,
                    "name": "one"
            },
            {
                    "id": 2,
                    "name": "two"
            },
            {
                    "id": 3,
                    "name": "three"
            }
        ],
        [
            {
                    "id": 4,
                    "name": "four"
            },
            {
                    "id": 5,
                    "name": "five"
            },
            {
                    "id": 6,
                    "name": "six"
            }
        ]
    ];

    $(function(){
         $("#somediv").replaceWith($("#rowTemplate").tmpl(arr));
    });
</script>
<script id="rowTemplate" type="text/x-jQuery-tmpl">
            <div class="row">
                {{tmpl($data) "#cellTemplate"}}
            </div>
</script>
<script id="cellTemplate" type="text/x-jQuery-tmpl">
        <div class = "cell"><span>${id}</span>:<span>${name}</span></div>
</script>
<div id="somediv"></div>
</code>```

Body:
I have the following javascript object

var arr = [
    [
        { "id": 1, "name": "one" },
        { "id": 2, "name": "two" },
        { "id": 3, "name": "three" }
    ],
    [
        { "id": 4, "name": "four" },
        { "id": 5, "name": "five" },
        { "id": 6, "name": "six" }
    ],
]

I'm trying to use jquery templates to create the following HTML

        1 : one

        2 : two

        3 : three

        4 : four

        5 : five

        6 : six

I am using the following templates with no luck :(

The line that calls the template is the following:

$("#rowTemplate").tmpl(arr).replaceAll("#somediv");

I am getting only one row with one cell with no data...

         :

What am I doing wrong?

Body:
I think the problem is with usage of replaceAll and the missing parameter to tmpl in the template.
Try this(used replaceWith for #someDiv and passed $data as tmpl parameter for child template):

<script type="text/javascript">
    var arr =
    [
        [
            {
                    "id": 1,
                    "name": "one"
            },
            {
                    "id": 2,
                    "name": "two"
            },
            {
                    "id": 3,
                    "name": "three"
            }
        ],
        [
            {
                    "id": 4,
                    "name": "four"
            },
            {
                    "id": 5,
                    "name": "five"
            },
            {
                    "id": 6,
                    "name": "six"
            }
        ]
    ];

    $(function(){
         $("#somediv").replaceWith($("#rowTemplate").tmpl(arr));
    });
</script>
<script id="rowTemplate" type="text/x-jQuery-tmpl">
            <div class="row">
                {{tmpl($data) "#cellTemplate"}}
            </div>
</script>
<script id="cellTemplate" type="text/x-jQuery-tmpl">
        <div class = "cell"><span>${id}</span>:<span>${name}</span></div>
</script>
<div id="somediv"></div>


问:
Leader key is ignored if I keep it pressed and I do multiple combinations
When I do <c-o><c-o><c-o>, and keep the control key pressed, it will jump 3 times backwards in the jumplist but if I do noremap <leader>o <c-o> then <leader>o<leader>o<leader>o, and keep the leader key pressed as I did with control, it will move backward the first time then it enter in editing mode and add an o. Leader key is ignored if we keep it pressed.

Is there a solution?

答:
Modifier keys like Ctrl, Alt and Shift can be kept in pressed state while you type additional keys; all keys will receive the modifier(s). That's a feature of keyboard input, nothing special about Vim.

For the Leader key, you cannot assign a modifier. It has to be a "real" key (possibly with modifiers). As the Leader key just starts a mapping sequence, you cannot keep it pressed. The closest you can achieve is a repeated mapping of it:

```<code>:nnoremap <Leader><Leader> :echo "pressed twice"<CR>
</code>```

If you want to define a mapping that can be repeated with a single key press, you have to use a single key with (e.g. <C-g>, or ) or without (not much left there in Vim, maybe ,).

Body:
Modifier keys like Ctrl, Alt and Shift can be kept in pressed state while you type additional keys; all keys will receive the modifier(s). That's a feature of keyboard input, nothing special about Vim.

For the Leader key, you cannot assign a modifier. It has to be a "real" key (possibly with modifiers). As the Leader key just starts a mapping sequence, you cannot keep it pressed. The closest you can achieve is a repeated mapping of it:

:nnoremap <Leader><Leader> :echo "pressed twice"<CR>

If you want to define a mapping that can be repeated with a single key press, you have to use a single key with (e.g. <C-g>, or <A-g>) or without (not much left there in Vim, maybe ,).


问:
best practice? where to store an image in angular?
I'm currently learning angular as I'm about to start a boat load of projects at work using it. Anyways, I'm just playing around with some stuff and I'm having some trouble figuring out the best place to store an image file. I've had success with the index.html file and the style.css setting a background image. But now I'm trying to use some pictures on the component level and just having some difficulty. Any advice would be greatly appreciated.</p>

答:
If you want too many images in your application then upload your images to some server there lots of image servers out there.
But if you have few images then you can store in

```<code>src/assets/images
</code>```

folder. Access them directly by setting the path in image URL.

Body:
If you want too many images in your application then upload your images to some server there lots of image servers out there.
But if you have few images then you can store in

src/assets/images

folder. Access them directly by setting the path in image URL.


问:
header not being set in storage promise
I am trying to add a header to my api call however, i need to get auth token and set that to the header. But when i try and run the bellow code it doesn't set it, only sets the Content-Type.

```<code>import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Component, Injectable} from '@angular/core';
import { Storage } from "@ionic/storage";
import 'rxjs/add/operator/map';

@Injectable()
@Component({
  providers: [HttpClient]
})
export class DataProvider {
  public token:string;

constructor(public http: HttpClient, public storage: Storage) {}

getsomething(){

 let headers = new HttpHeaders();
 headers = headers.set('Content-Type', 'application/json');
 this.storage.get('token').then((val) => {
   this.token = val;
   console.log(this.token);
   headers = headers.set('AuthToken', this.token);
 });

 console.log(headers);

 return this.http.get('http://localhost:54951/getfarms', {
   headers: headers
 });
</code>```

}

答:
You can try using Observable.flatMap as in below example</p>

```<code>import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Storage } from "@ionic/storage";
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/mergeMap';

@Injectable()
export class DataProvider {
  constructor(public http: HttpClient, public storage: Storage) { }

  getsomething() {
    return Observable.fromPromise(this.storage.get('token')).flatMap((token) => {
      console.log(token);
      let headers = new HttpHeaders();
      headers = headers.set('Content-Type', 'application/json');
      headers = headers.set('AuthToken', token);
      console.log(headers);

      return this.http.get('http://localhost:54951/getfarms', {
        headers: headers
      });
    });
  }
}
</code>```

Title: header not being set in storage promise

Body:
I am trying to add a header to my api call however, i need to get auth token and set that to the header. But when i try and run the bellow code it doesn't set it, only sets the Content-Type.

import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Component, Injectable} from '@angular/core';
import { Storage } from "@ionic/storage";
import 'rxjs/add/operator/map';

@Injectable()
@Component({
  providers: [HttpClient]
})
export class DataProvider {
  public token:string;

constructor(public http: HttpClient, public storage: Storage) {}

getsomething(){

 let headers = new HttpHeaders();
 headers = headers.set('Content-Type', 'application/json');
 this.storage.get('token').then((val) => {
   this.token = val;
   console.log(this.token);
   headers = headers.set('AuthToken', this.token);
 });

 console.log(headers);

 return this.http.get('http://localhost:54951/getfarms', {
   headers: headers
 });

}

Body:
You can try using Observable.flatMap as in below example

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Storage } from "@ionic/storage";
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/mergeMap';

@Injectable()
export class DataProvider {
  constructor(public http: HttpClient, public storage: Storage) { }

  getsomething() {
    return Observable.fromPromise(this.storage.get('token')).flatMap((token) => {
      console.log(token);
      let headers = new HttpHeaders();
      headers = headers.set('Content-Type', 'application/json');
      headers = headers.set('AuthToken', token);
      console.log(headers);

      return this.http.get('http://localhost:54951/getfarms', {
        headers: headers
      });
    });
  }
}


问:
Programmatically defining the height of a notification content extension
The width:height ratio of a notification extension can be defined through attribute UNNotificationExtensionInitialContentSizeRatio in the extension's Info.plist file. But can this value somehow be changed after the respective UIViewController is loaded?

The documentation on Apple's site indicates that it is indeed possible:

You can change the size of your view controller after your extension
  loads.

But how? I've tried changing the extension's main UIView's frame, like so...

```<code>func didReceive(_ notification: UNNotification) {

    self.view.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: 100.0)
    self.view.setNeedsUpdateConstraints()
    self.view.setNeedsLayout()
}
</code>```

...but only the view's frame is correctly updated, leaving the whole notification container with an empty white area at the bottom.

I've also attempted some less obvious solutions, including changing the frame at different points in the controller's lifecycle and setting the UIWindow's frame directly. None were successful so far.

Any idea if the height can be changed programmatically?

Thank you in advance for any answer.

答: You can override the size by using the preferredContentSize property of UIViewController.

Body:
The width:height ratio of a notification extension can be defined through attribute UNNotificationExtensionInitialContentSizeRatio in the extension's Info.plist file. But can this value somehow be changed after the respective UIViewController is loaded?

The documentation on Apple's site indicates that it is indeed possible:

You can change the size of your view controller after your extension
  loads.

But how? I've tried changing the extension's main UIView's frame, like so...

func didReceive(_ notification: UNNotification) {

    self.view.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: 100.0)
    self.view.setNeedsUpdateConstraints()
    self.view.setNeedsLayout()
}

...but only the view's frame is correctly updated, leaving the whole notification container with an empty white area at the bottom.

I've also attempted some less obvious solutions, including changing the frame at different points in the controller's lifecycle and setting the UIWindow's frame directly. None were successful so far.

Any idea if the height can be changed programmatically?

Thank you in advance for any answer.


问:
Should a descendant class' method's variable that is identical to Self, have access to its ancestor's protected methods?
This question arose from an issue that surfaced when using method chaining (fluent interface), and I suppose that's one of the only reasons it might be an issue at all.

To illustrate, I'll use an example using method chaining:

In unit A:

```<code>TParent = class
protected
  function DoSomething: TParent;
end;
</code>```

In unit B:

```<code>TChild = class(TParent)
public
  procedure DoAnotherThing;
end;

implementation

procedure TChild.DoAnotherThing;
begin
  DoSomething.DoSomething
end;
</code>```

I want to keep the DoSomething procedure protected and visible only to class descendants.

This won't compile, throwing a

cannot access protected symbol TParent.DoSomething

because DoSomething returns a TParent and the subsequent DoSomething call is issued from a TParent object in another unit (so the protection kicks in and the function is inaccessible). (thanks, David Heffernan, for the explanation)

To reduce it to its bare essence, something like TParent(Self).DoSomething is not possible inside the TChild class.

My question:

since the compiler does know that a copy of the Self parameter is being accessed from within the child class, would there be instances in which the ability to access the ancestor's protected methods breaks encapsulation? I'm only talking about dereferencing the typecasted Self from inside a descendant's class method. I'm aware that outside of this class, that parameter should not have access to the ancestor's protected methods (in another unit), of course.

Again, in short: when a variable, that is identical to the Self parameter, is dereferenced INSIDE one of its own class methods, would it be unsafe for the compiler to allow it access to its parent's protected methods (just like the Self parameter itself)?

It's a pretty theoretical question, but I'd be interested if it would have any negative impact on compiled code or encapsulation, if the compiler would allow this.

Thanks.

答:
protected means that you have access to those methods in your own instance. It does not mean that you have access to those methods on any other instances which are of a type you are deriving from.

The reason you can call DoSomething in TChild is because only Self has access to protected members of its ancestors.

The fact that in this particular case the result of the DoSomething method equals Self cannot be evaluated by the compiler (except by some static code analysis which I doubt any OOP language compiler out there does).

C++ solves this with being able to make TChild a friend class of TParent and thus giving it access to those methods.

In Delphi you get that feature if you put both classes into the same unit. If you want to keep both classes in their own units you can still use that feature by declaring a "cracker class". Just make a class that inherits from TParent and put that into the same unit as TChild. Then you can cast the result of DoSomething to that class and access the protected methods of TParent.

```<code>type
  TChild = class(TParent)
  public
    procedure DoAnotherThing;
  end;

implementation

type
  TParentAccess = class(TParent);

procedure TChild.DoAnotherThing;
begin
  TParentAccess(DoSomething).DoSomething;
end;
</code>```

Update 6.12.2017:

You can also add a method to your TChild class to mimic the "friend status" (thanks Ken Bourassa).

```<code>type
  TChild = class(TParent)
  private
    type
      TParentAccess = class(TParent);
    function DoSomething: TParentAccess; inline;
  public
    procedure DoAnotherThing;
  end;

implementation

function TChild.DoSomething: TParentAccess;
begin
  Result := TParentAccess(inherited DoSomething);
end;

procedure TChild.DoAnotherThing;
begin
  DoSomething.DoSomething;
end;
</code>```

A third possibility would be using a class helper to make the method accessible. This has the benefit of easy reusability as you just need to add the helper unit to any unit where you have a child of TParent and need access.

```<code>type
  TParentHelper = class helper for TParent
  public
    function DoSomething: TParent; inline;
  end;

implementation

function TParentHelper.DoSomething: TParent;
begin
  Result := inherited DoSomething;
end;
</code>```

Body:
This question arose from an issue that surfaced when using method chaining (fluent interface), and I suppose that's one of the only reasons it might be an issue at all.

To illustrate, I'll use an example using method chaining:

In unit A:

TParent = class
protected
  function DoSomething: TParent;
end;

In unit B:

TChild = class(TParent)
public
  procedure DoAnotherThing;
end;

implementation

procedure TChild.DoAnotherThing;
begin
  DoSomething.DoSomething
end;

I want to keep the DoSomething procedure protected and visible only to class descendants.

This won't compile, throwing a

cannot access protected symbol TParent.DoSomething

because DoSomething returns a TParent and the subsequent DoSomething call is issued from a TParent object in another unit (so the protection kicks in and the function is inaccessible). (thanks, David Heffernan, for the explanation)

To reduce it to its bare essence, something like TParent(Self).DoSomething is not possible inside the TChild class.

My question:

since the compiler does know that a copy of the Self parameter is being accessed from within the child class, would there be instances in which the ability to access the ancestor's protected methods breaks encapsulation? I'm only talking about dereferencing the typecasted Self from inside a descendant's class method. I'm aware that outside of this class, that parameter should not have access to the ancestor's protected methods (in another unit), of course.

Again, in short: when a variable, that is identical to the Self parameter, is dereferenced INSIDE one of its own class methods, would it be unsafe for the compiler to allow it access to its parent's protected methods (just like the Self parameter itself)?

It's a pretty theoretical question, but I'd be interested if it would have any negative impact on compiled code or encapsulation, if the compiler would allow this.

Thanks.

Body:
protected means that you have access to those methods in your own instance. It does not mean that you have access to those methods on any other instances which are of a type you are deriving from.

The reason you can call DoSomething in TChild is because only Self has access to protected members of its ancestors.

The fact that in this particular case the result of the DoSomething method equals Self cannot be evaluated by the compiler (except by some static code analysis which I doubt any OOP language compiler out there does).

C++ solves this with being able to make TChild a friend class of TParent and thus giving it access to those methods.

In Delphi you get that feature if you put both classes into the same unit. If you want to keep both classes in their own units you can still use that feature by declaring a "cracker class". Just make a class that inherits from TParent and put that into the same unit as TChild. Then you can cast the result of DoSomething to that class and access the protected methods of TParent.

type
  TChild = class(TParent)
  public
    procedure DoAnotherThing;
  end;

implementation

type
  TParentAccess = class(TParent);

procedure TChild.DoAnotherThing;
begin
  TParentAccess(DoSomething).DoSomething;
end;

Update 6.12.2017:

You can also add a method to your TChild class to mimic the "friend status" (thanks Ken Bourassa).

type
  TChild = class(TParent)
  private
    type
      TParentAccess = class(TParent);
    function DoSomething: TParentAccess; inline;
  public
    procedure DoAnotherThing;
  end;

implementation

function TChild.DoSomething: TParentAccess;
begin
  Result := TParentAccess(inherited DoSomething);
end;

procedure TChild.DoAnotherThing;
begin
  DoSomething.DoSomething;
end;

A third possibility would be using a class helper to make the method accessible. This has the benefit of easy reusability as you just need to add the helper unit to any unit where you have a child of TParent and need access.

type
  TParentHelper = class helper for TParent
  public
    function DoSomething: TParent; inline;
  end;

implementation

function TParentHelper.DoSomething: TParent;
begin
  Result := inherited DoSomething;
end;


问:
Showing current location in offline mode with gps
Hi I am a bit new to android and I have been wanted to develop an android app which is supposed to show the current location of the user on a map like google map in offline mode. Can I show the location with just GPS and without Internet connection ?  Needless to say that this offline thing is vitally important for me. Any help would be appreciated. Tnx in advance</p>

答:
You can get the GPS location (although it will be less precise without GSM tower localisation). However, the map part may be tricky. You can use the Google Maps API in your app, like MapActivity, but the map itself has to be downloaded from the web.

So you will need some custom solution for this, probably through a different map provider than Google Maps.

You may be able to do it a bit differently - obtain the location in your app and then open Google Maps with an Intent, passing the received coordinates. This should allow the user to use any offline-stored maps they may have.


答:
You probably already tried this but just in case:

```<code>View decorView = getWindow().getDecorView();
// Hide the status bar.
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
// Remember that you should never show the action bar if the
// status bar is hidden, so hide that too if necessary.
ActionBar actionBar = getActionBar();
actionBar.hide();
</code>```

Comes from
https://developer.android.com/training/system-ui/status.html

Title: Status bar is hidden but the tint is still seen

Body:
You probably already tried this but just in case:

View decorView = getWindow().getDecorView();
// Hide the status bar.
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
// Remember that you should never show the action bar if the
// status bar is hidden, so hide that too if necessary.
ActionBar actionBar = getActionBar();
actionBar.hide();

Comes from
https://developer.android.com/training/system-ui/status.html


问:
SoapUI not finding my wsdl: fail to load url
Following is wsdl code

while I use it for analysis it give me error of prototype can you help

```<code><?xml version='1.0' encoding='UTF-8'?><!-- Published by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is JAX-WS RI 2.2.8 svn-revision#13980. --><!-- Generated by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is JAX-WS RI 2.2.8 svn-revision#13980. --><definitions xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsp="http://www.w3.org/ns/ws-policy" xmlns:wsp1_2="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://service.vep.mbca.com/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://service.vep.mbca.com/" name="ProcessCreditDecisionServiceService">
<import namespace="http://iservice.vep.mbca.com/" location="https://localhost:443/vepapi/web-service/mbfs/processCreditDecision?wsdl=1"/>
<binding xmlns:ns1="http://iservice.vep.mbca.com/" name="ProcessCreditDecisionServicePortBinding" type="ns1:IProcessCreditDecisionService">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/>
<operation name="processCreditDecision">
<soap:operation soapAction=""/>
<input>
<soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>
</output>
</operation>

</binding>

<service name="ProcessCreditDecisionServiceService">
<port name="ProcessCreditDecisionServicePort" binding="tns:ProcessCreditDecisionServicePortBinding">
<soap:address location="https://localhost:443/vepapi/web-service/mbfs/processCreditDecision"/>
</port>
</service>
</definitions>
</code>```

答:
WSDL issues happen in SOAP UI sometimes when the end-points you are trying  to hit is either not active or does not exist.

```<code><soap:address location="https://localhost:443/vepapi/web-service/mbfs/processCreditDecision"/>
</code>```

Perform schema validation once, check whether you are abiding to the rules. In specific, check the binding part.

Cross validate the end point you are pointing in the soap request and the one in the wsdl.

check the endpoints.

Body:
Following is wsdl code

while I use it for analysis it give me error of prototype can you help

<?xml version='1.0' encoding='UTF-8'?><definitions xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsp="http://www.w3.org/ns/ws-policy" xmlns:wsp1_2="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://service.vep.mbca.com/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://service.vep.mbca.com/" name="ProcessCreditDecisionServiceService">
<import namespace="http://iservice.vep.mbca.com/" location="https://localhost:443/vepapi/web-service/mbfs/processCreditDecision?wsdl=1"/>
<binding xmlns:ns1="http://iservice.vep.mbca.com/" name="ProcessCreditDecisionServicePortBinding" type="ns1:IProcessCreditDecisionService">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/>
<operation name="processCreditDecision">
<soap:operation soapAction=""/>
<input>
<soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>
</output>
</operation>

</binding>

<service name="ProcessCreditDecisionServiceService">
<port name="ProcessCreditDecisionServicePort" binding="tns:ProcessCreditDecisionServicePortBinding">
<soap:address location="https://localhost:443/vepapi/web-service/mbfs/processCreditDecision"/>
</port>
</service>
</definitions>

Body:
WSDL issues happen in SOAP UI sometimes when the end-points you are trying  to hit is either not active or does not exist.

<soap:address location="https://localhost:443/vepapi/web-service/mbfs/processCreditDecision"/>

Perform schema validation once, check whether you are abiding to the rules. In specific, check the binding part.

Cross validate the end point you are pointing in the soap request and the one in the wsdl.

check the endpoints.


问:
How Django signal receiver should handle errors?
Cite from docs:

...look at the **kwargs argument. All signals send keyword arguments,
  and may change those keyword arguments at any time. In the case of
  request_finished, it’s documented as sending no arguments, which means
  we might be tempted to write our signal handling as
  my_callback(sender).

This would be wrong – in fact, Django will throw an error if you do
  so. That’s because at any point arguments could get added to the
  signal and your receiver must be able to handle those new arguments.

I don't get it. Why 'arguments could be added at any time', isn't interfaces in programs exist to be constant and everybody should be aware of them? Or does these words mean, that every receiver must always fail silently? Because it is obvious if, sender would randomly change interface, receivers will fail and throw errors.

This would be wrong – in fact, Django will throw an error if you do
  so.

Throwing errors is wrong when using signals or what did they meant?

答:
Throwing errors is wrong when using signals or what did they meant?

They only mean that the **kwargs is required when you call signal receiver function. Throwing errors when using signals is not wrong a priori. In conclusion, remind to always include the kwargs when you need to define a receiver function, as the docs says:

```<code>def my_callback(sender, **kwargs):
    print("Request finished!")
</code>```

Body:
Throwing errors is wrong when using signals or what did they meant?

They only mean that the **kwargs is required when you call signal receiver function. Throwing errors when using signals is not wrong a priori. In conclusion, remind to always include the kwargs when you need to define a receiver function, as the docs says:

def my_callback(sender, **kwargs):
    print("Request finished!")


问:
What are some good sql databases for home Vista computer?
I have been trying for a long time to get SQL Server Express on my computer to practice my C#/SQL with and I still haven't gotten it to work.

Are there other programs I can use to setup an SQL database to practice with?  If so, which are the best ones for Vista?

EDIT:
To be clear I am not new to SQL programming, I just haven't done any in a while and want to stay fresh.  So I would like something that has most of the features of forms of SQL I would use professionally.

答:
SQL Server Express generally should be the natural choice for practice with .NET and C#.

If you have no prior experience in working with SQL Server and its Express version one most confusing thing is that SQL Server Express is not installed as default instance, but as SQLEXPRESS instance. So you have to use "Data Source=.\SQLEXPRESS" in your connection string.

In case you can not overcome issues with SQL Express you can try Postgres, but you will need to download and use .NET Data Provider for Postgres.

OwnerDisplayName: GordonG

LastEditorDisplayName: GordonG

OwnerDisplayName: Dmytro Malenko


问:
Warbler - no such file to load error
I am following the guide located here to install Redmine to Tomcat, but I am running into problems running Warbler. When I try running

```<code>ruby /var/lib/gems/1.8/gems/warbler-1.2.1/bin/warble config
</code>```

I get this error

```<code>/var/lib/gems/1.8/gems/warbler-1.2.1/bin/warble:10:in `require': no such file to load -- warbler (LoadError)
from /var/lib/gems/1.8/gems/warbler-1.2.1/bin/warble:10
</code>```

I searched around and found that this is caused by not requiring rubygems. When I try to fix this and run

```<code>ruby -rubygems /var/lib/gems/1.8/gems/warbler-1.2.1/bin/warble config
</code>```

I now run into this error

```<code>warble aborted!
no such file to load -- /var/lib/gems/1.8/gems/jruby-rack-1.0.5/lib/jruby-rack-1.0.5.jar
/usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
</code>```

When I run the last command with --trace I get this

```<code>warble aborted!
no such file to load -- /var/lib/gems/1.8/gems/jruby-rack-1.0.5/lib/jruby-rack-1.0.5.jar
/usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
/usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `require'
/var/lib/gems/1.8/gems/jruby-rack-1.0.5/lib/jruby-rack.rb:6
/usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
/usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `require'
/var/lib/gems/1.8/gems/warbler-1.2.1/lib/warbler/config.rb:254:in `default_jar_files'
/var/lib/gems/1.8/gems/warbler-1.2.1/lib/warbler/config.rb:140:in `initialize'
/var/lib/gems/1.8/gems/warbler-1.2.1/lib/warbler/task.rb:47:in `new'
/var/lib/gems/1.8/gems/warbler-1.2.1/lib/warbler/task.rb:47:in `initialize'
/var/lib/gems/1.8/gems/warbler-1.2.1/lib/warbler/application.rb:25:in `new'
/var/lib/gems/1.8/gems/warbler-1.2.1/lib/warbler/application.rb:25:in `load_rakefile'
/var/lib/gems/1.8/gems/rake-0.8.7/lib/rake.rb:2000:in `run'
/var/lib/gems/1.8/gems/rake-0.8.7/lib/rake.rb:2068:in `standard_exception_handling'
/var/lib/gems/1.8/gems/rake-0.8.7/lib/rake.rb:1998:in `run'
/var/lib/gems/1.8/gems/warbler-1.2.1/lib/warbler/application.rb:68:in `run'
/var/lib/gems/1.8/gems/warbler-1.2.1/bin/warble:11
</code>```

The file /var/lib/gems/1.8/gems/jruby-rack-1.0.5/lib/jruby-rack-1.0.5.jar exists, so I'm not sure why it is running into problems.

Here is the output of gem list, just in case it is useful.

```<code>abstract (1.0.0)
actionmailer (3.0.3, 2.3.5)
actionpack (3.0.3, 2.3.5)
activemodel (3.0.3)
activerecord (3.0.3, 2.3.5)
activerecord-jdbc-adapter (1.1.1)
activerecord-jdbcmysql-adapter (1.1.1)
activeresource (3.0.3, 2.3.5)
activesupport (3.0.3, 2.3.5)
arel (2.0.7)
bouncy-castle-java (1.5.0145.2)
builder (3.0.0, 2.1.2)
bundler (1.0.7)
cgi_multipart_eof_fix (2.5.0)
daemon_controller (0.2.5)
daemons (1.1.0)
erubis (2.6.6)
fastthread (1.0.7)
file-tail (1.0.5)
gdata (1.1.1)
gem_plugin (0.2.3)
gruff (0.3.6)
i18n (0.5.0, 0.4.2)
jdbc-mysql (5.1.13)
jruby-jars (1.5.6)
jruby-openssl (0.7.2)
jruby-rack (1.0.5)
mail (2.2.14)
mime-types (1.16)
mongrel (1.1.5)
mysql (2.8.1)
passenger (3.0.2)
polyglot (0.3.1)
rack (1.0.1)
rack-mount (0.6.13)
rack-test (0.5.7)
rails (3.0.3, 2.3.5)
railties (3.0.3)
rake (0.8.7)
rmagick (2.13.1)
rubyzip (0.9.4)
spruz (0.2.2)
thor (0.14.6)
treetop (1.4.9)
tzinfo (0.3.24)
warbler (1.2.1)
</code>```

答:
A temporary solution is to use an older version of jruby-rack:

gem uninstall jruby-rack

If you remove this gems, one or more dependencies will not be met.
Continue with Uninstall? [Yn]

Type Y

gem install jruby-rack -v 1.0.3

Title: Warbler - no such file to load error

Body:
I am following the guide located here to install Redmine to Tomcat, but I am running into problems running Warbler. When I try running

ruby /var/lib/gems/1.8/gems/warbler-1.2.1/bin/warble config

I get this error

/var/lib/gems/1.8/gems/warbler-1.2.1/bin/warble:10:in `require': no such file to load -- warbler (LoadError)
from /var/lib/gems/1.8/gems/warbler-1.2.1/bin/warble:10

I searched around and found that this is caused by not requiring rubygems. When I try to fix this and run

ruby -rubygems /var/lib/gems/1.8/gems/warbler-1.2.1/bin/warble config

I now run into this error

warble aborted!
no such file to load -- /var/lib/gems/1.8/gems/jruby-rack-1.0.5/lib/jruby-rack-1.0.5.jar
/usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'

When I run the last command with --trace I get this

warble aborted!
no such file to load -- /var/lib/gems/1.8/gems/jruby-rack-1.0.5/lib/jruby-rack-1.0.5.jar
/usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
/usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `require'
/var/lib/gems/1.8/gems/jruby-rack-1.0.5/lib/jruby-rack.rb:6
/usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
/usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `require'
/var/lib/gems/1.8/gems/warbler-1.2.1/lib/warbler/config.rb:254:in `default_jar_files'
/var/lib/gems/1.8/gems/warbler-1.2.1/lib/warbler/config.rb:140:in `initialize'
/var/lib/gems/1.8/gems/warbler-1.2.1/lib/warbler/task.rb:47:in `new'
/var/lib/gems/1.8/gems/warbler-1.2.1/lib/warbler/task.rb:47:in `initialize'
/var/lib/gems/1.8/gems/warbler-1.2.1/lib/warbler/application.rb:25:in `new'
/var/lib/gems/1.8/gems/warbler-1.2.1/lib/warbler/application.rb:25:in `load_rakefile'
/var/lib/gems/1.8/gems/rake-0.8.7/lib/rake.rb:2000:in `run'
/var/lib/gems/1.8/gems/rake-0.8.7/lib/rake.rb:2068:in `standard_exception_handling'
/var/lib/gems/1.8/gems/rake-0.8.7/lib/rake.rb:1998:in `run'
/var/lib/gems/1.8/gems/warbler-1.2.1/lib/warbler/application.rb:68:in `run'
/var/lib/gems/1.8/gems/warbler-1.2.1/bin/warble:11

The file /var/lib/gems/1.8/gems/jruby-rack-1.0.5/lib/jruby-rack-1.0.5.jar exists, so I'm not sure why it is running into problems.

Here is the output of gem list, just in case it is useful.

abstract (1.0.0)
actionmailer (3.0.3, 2.3.5)
actionpack (3.0.3, 2.3.5)
activemodel (3.0.3)
activerecord (3.0.3, 2.3.5)
activerecord-jdbc-adapter (1.1.1)
activerecord-jdbcmysql-adapter (1.1.1)
activeresource (3.0.3, 2.3.5)
activesupport (3.0.3, 2.3.5)
arel (2.0.7)
bouncy-castle-java (1.5.0145.2)
builder (3.0.0, 2.1.2)
bundler (1.0.7)
cgi_multipart_eof_fix (2.5.0)
daemon_controller (0.2.5)
daemons (1.1.0)
erubis (2.6.6)
fastthread (1.0.7)
file-tail (1.0.5)
gdata (1.1.1)
gem_plugin (0.2.3)
gruff (0.3.6)
i18n (0.5.0, 0.4.2)
jdbc-mysql (5.1.13)
jruby-jars (1.5.6)
jruby-openssl (0.7.2)
jruby-rack (1.0.5)
mail (2.2.14)
mime-types (1.16)
mongrel (1.1.5)
mysql (2.8.1)
passenger (3.0.2)
polyglot (0.3.1)
rack (1.0.1)
rack-mount (0.6.13)
rack-test (0.5.7)
rails (3.0.3, 2.3.5)
railties (3.0.3)
rake (0.8.7)
rmagick (2.13.1)
rubyzip (0.9.4)
spruz (0.2.2)
thor (0.14.6)
treetop (1.4.9)
tzinfo (0.3.24)
warbler (1.2.1)


问:
GitHub error "Failed to get HEAD"
I'm new to GitHub and mainly going to be using it to backup service and to show off code. Anyhow, I'm trying to get my latest program up there and am getting the error in the title of this thread when I try to push.

Repro steps:

Sit in Starbucks with crappy wifi (Could this be related to the problem? Serious question.)

Open latest version of GitHub for latest Macintosh operating system

File --> New Repository

Local Path --> the folder that contains my XCode project

Name --> give it a name

Publish

Sync

Push .... Get error

Look in my XCode project's folder and it looks like an empty subfolder with the name of my GitHub project was created there. Huh?

答:
```<code>git reset
</code>```

And then come back to GitHub Desktop. That works in my case.

Title: GitHub error "Failed to get HEAD"

Body:
git reset

And then come back to GitHub Desktop. That works in my case.