问:
hiera() function and YAML hash lookups
How do I rewrite this YAML so it is more structured, then reference it in Puppet using hiera function?

Currently, I am working with a hieradata syntax that looks very flat and hard to read.

```<code>service::proxy::behind_reverse_proxy: true
service::proxy::proxy_timeout: 300
service::proxy::serverlist:
  - host1.fqdn
  - host2.fqdn
</code>```

And grabbed these in a params.pp file, for example

```<code>$behind_reverse_proxy = hiera('service::proxy::behind_reverse_proxy', 'False')
$serverlist = hiera('service::proxy::serverlist')
</code>```

I thought I could rewrite the YAML like so in an effort to make it more readable...

```<code>service::proxy:
  behind_reverse_proxy: true
  proxy_timeout: 300
  serverlist:
    - host1.fqdn
    - host2.fqdn
</code>```

And updated the params.pp file according to

Hiera Key.subkey syntax

interacting with structured data

```<code>$behind_reverse_proxy = hiera('service::proxy.behind_reverse_proxy', 'False')
$serverlist = hiera('service::proxy.serverlist')
</code>```

However upon puppet agent -t that resulted in

Error 400 on SERVER: Could not find data item service::proxy.serverlist in any Hiera data file and no default supplied

I think these are relevant

```<code>[user@server ~]$ facter -y | grep 'version'
facterversion: 2.4.4
puppetversion: 3.8.2
</code>```

答:
I've never used Hiera, but I think the problem is that you have a sequence (array) when you wanted a mapping (hash).

In the below YAML, the value of the service::proxy key is a sequence with three elements, each of which is a mapping with one key:

```<code>service::proxy:
  - behind_reverse_proxy: true
  - proxy_timeout: 300
  - serverlist:
    - host1.fqdn
    - host2.fqdn
</code>```

What you probably wanted, though, was for service::proxy to be a mapping with three keys:

```<code>service::proxy:
  behind_reverse_proxy: true
  proxy_timeout: 300
  serverlist:
  - host1.fqdn
  - host2.fqdn
</code>```

The examples in the Hiera docs you linked to seem to support this.

Title: hiera() function and YAML hash lookups

Body:
How do I rewrite this YAML so it is more structured, then reference it in Puppet using hiera function?

Currently, I am working with a hieradata syntax that looks very flat and hard to read.

service::proxy::behind_reverse_proxy: true
service::proxy::proxy_timeout: 300
service::proxy::serverlist:
  - host1.fqdn
  - host2.fqdn

And grabbed these in a params.pp file, for example

$behind_reverse_proxy = hiera('service::proxy::behind_reverse_proxy', 'False')
$serverlist = hiera('service::proxy::serverlist')

I thought I could rewrite the YAML like so in an effort to make it more readable...

service::proxy:
  behind_reverse_proxy: true
  proxy_timeout: 300
  serverlist:
    - host1.fqdn
    - host2.fqdn

And updated the params.pp file according to

Hiera Key.subkey syntax

interacting with structured data

$behind_reverse_proxy = hiera('service::proxy.behind_reverse_proxy', 'False')
$serverlist = hiera('service::proxy.serverlist')

However upon puppet agent -t that resulted in

Error 400 on SERVER: Could not find data item service::proxy.serverlist in any Hiera data file and no default supplied

I think these are relevant

[user@server ~]$ facter -y | grep 'version'
facterversion: 2.4.4
puppetversion: 3.8.2

Body:
I've never used Hiera, but I think the problem is that you have a sequence (array) when you wanted a mapping (hash).

In the below YAML, the value of the service::proxy key is a sequence with three elements, each of which is a mapping with one key:

service::proxy:
  - behind_reverse_proxy: true
  - proxy_timeout: 300
  - serverlist:
    - host1.fqdn
    - host2.fqdn

What you probably wanted, though, was for service::proxy to be a mapping with three keys:

service::proxy:
  behind_reverse_proxy: true
  proxy_timeout: 300
  serverlist:
  - host1.fqdn
  - host2.fqdn

The examples in the Hiera docs you linked to seem to support this.


来源: stackexchange

问:
Android Graphics Memory Limits
I am creating an android game using opengl and a cocos2d port (http://code.google.com/p/cocos2d-android-1). I am targeting a wide range of devices and want to ensure that it performs well. I only test on a nexus one and am hoping to get some input from people with experience on slower devices.

Currently the game uses two 1024x1024 textures as well as two 256x256 textures. Is this within the limits of most devices? Anyone have any rule of thumb or experience with graphics memory limits in these cases? If gfx memory is exceeded does it page to normal memory?

答:
Afaik the Memory Limits for textures are the same as the memory limits of your app, which is 16 megs in most situations I believe, although it might be all available phone memory that's accessible.

I've loaded MUCH more than this into my apps before I ran into problems, at least one 2048x2048 texture and several 512x512 textures, all 8888 in memory.

I've never had a oom error on texture binding, only on loading bitmaps, so I hope that helps.

ContentLicense: CC BY-SA 2.5

Title: Android Graphics Memory Limits


问:
Print with POS printers using android built-in print framework
Most of companies producing POS printers (or label printers) which connects to mobile devices provide SDK for developers to send data to the printer.

Is it possible to use android default print framework (added in android 4.4) for sending data to these kind of printers?
(writing render codes is much easier!)

答:
If the printer manufacturer offers a compatible print driver app for Android, yes. Otherwise, no.

IOW, you need to ask the printer manufacturer.

Note that this is not unique to POS printers — the same thing is true of every printer. Either there is an Android print driver app, or there is not.

ContentLicense: CC BY-SA 3.0


问:
how do i make a loop to display the next 3 even number?
hello all i'm trying to make javascript to display an evens numbers by using a form with start number and number of evens to display. user will enter starting number and enter the number of even to display.
say start at 7 number of evens is 3 should display 8 10 12.  just need some direction. thanks

my code:

```<code><html>
<head>
<title>evens</title>
<div class="container">
           <h1>Enter Number</h1>
           <form name="number" class="form-inline">
           <div class="form-group">
            <label for="starting">Starting Number</label>
            <input type="text" id="starting" class="form-control">
           </div> <div class="form-group">
               <label for="step">numbers of evens</label>
               <input type="text" id="step" class="form-control">
           </div>
</code>```

```<code>           <button type="button" onclick="evenDisplay()" class="btn" >submit</button>

<script>

function evenDisplay() {

    var starting = document.getElementById("starting").value;
    var step = document.getElementById("step").value;
    var evens = [];

    for (i = starting;  i <=12; i++) { /* this loop would show as much as evens number as long value of i<= set to  and doesn't care if the user enter the number of evens */
        i % 2 || evens.push(i);
    }
   console.log(evens)

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

答:
All looks well, but you're probably better with a while loop since you want to loop until evens contains step values.

```<code>var currentVal = starting;
while(evens.length < step){
   currentVal % 2 || evens.push(currentVal);
   currentVal++;
}
</code>```

Body:
hello all i'm trying to make javascript to display an evens numbers by using a form with start number and number of evens to display. user will enter starting number and enter the number of even to display.
say start at 7 number of evens is 3 should display 8 10 12.  just need some direction. thanks

my code:

<title>evens</title>

Enter Number

           <form name="number" class="form-inline">

            Starting Number
            <input type="text" id="starting" class="form-control">

               numbers of evens
               <input type="text" id="step" class="form-control">

           <button type="button" onclick="evenDisplay()" class="btn" >submit</button>

Body:
All looks well, but you're probably better with a while loop since you want to loop until evens contains step values.

var currentVal = starting;
while(evens.length < step){
   currentVal % 2 || evens.push(currentVal);
   currentVal++;
}


问:
Mockito : Testing void methods gives InvalidUseOfMatchersException
I'm having problems with two void methods. In encouragedVenturesScoring I've followed this answer mocking an arraylist that will be looped in a for loop and haven't mocked the list, but passed a real list and added mocked objects.

Mockito gives me an InvalidUseOfMatchersException on this line

verify(effectList.get(Mockito.anyInt())).execute(playerHandler);

There are lots of questions on SO on this exception , and I think it's because of anyInt(). Anyway I changed it to

```<code>verify(effectList.get(0)).execute(playerHandler);
</code>```

And now it's saying Wanted but not invoked effect.execute(playerHandler)
Actually there were zero interactions with this mock

Is it because I put doNothing ?
doNothing().when(effect).execute(playerHandler);

In my second method militaryStrengthScoring() method is there a way to skip the first chunk of code and just test the if..else condition? What would be the best approach to test this method?

Thank you for your time.

This is the class to be tested

```<code> public class EndGameScoringBaseController implements EndGameScoringHandler {

private static final int[] TERRITORIES_REWARD = {0,0,1,4,10,20};
private static final int[] CHARACTERS_REWARD = {1,3,6,10,15,21};
private static final int RESOURCES_RATE = 5;
private static final int FIRST_MILITARY_REWARD = 5;
private static final int SECOND_MILITARY_REWARD = 2;

private PlayerHandler player;

public EndGameScoringBaseController(PlayerHandler player) {
    super();
    this.player = player;
}

@Override
public void encouragedVenturesScoring() {
    for (DevelopmentCard card : player.getPlayer().getPersonalBoard().getVentures()) {
        for (Effect e : card.getPermanentEffects())
            e.execute(player);
    }
}

@Override
public void militaryStrengthScoring(GameController game) {
    Set<Integer> points = new HashSet<>();
    int myPoints = this.player.getPointsHandler().getMilitaryPoints();

    for (PlayerHandler p: game.getPlayers()) {
        points.add(p.getPointsHandler().getMilitaryPoints());
    }
    int[] rank = new int[points.size()];
    int j = 0;
    for (Integer i : points) {
        rank[j] = i;
        j++;
    }

    Arrays.sort(rank);

    if (rank[rank.length-1] == myPoints) {
        player.getPointsHandler().winMilitaryPoints(FIRST_MILITARY_REWARD);
    }
    else if (rank[rank.length-2] == myPoints) {
        player.getPointsHandler().winVictoryPoints(SECOND_MILITARY_REWARD);
    }

}
</code>```

Tested method for encouragedVenturesScoring

```<code>@Test
public void encouragedVenturesScoringTest() {
    //given
    List<DevelopmentCard> ventureList;
    ventureList = Arrays.asList(developmentCard, developmentCard);
    when(playerHandler.getPlayer().getPersonalBoard().getVentures()).thenReturn(ventureList);
    List<Effect> effectList;
    effectList = Arrays.asList(effect, effect);
    when(developmentCard.getPermanentEffects()).thenReturn(effectList);
    doNothing().when(effect).execute(playerHandler);

    //when
    endgameController.encouragedVenturesScoring();

    //then
    verify(effectList.get(Mockito.anyInt())).execute(playerHandler);
}
</code>```

Incomplete tested method for militaryStrengthScoring

```<code>@Test
public void militaryStrengthScoringTest() {

//given
when(playerHandler.getPointsHandler().getMilitaryPoints()).thenReturn(4);
doNothing().when(playerHandler.getPointsHandler()).winMilitaryPoints(FIRST_MILITARY_REWARD);

//when
endgameController.militaryStrengthScoring(gameController);

//then
/../
}
</code>```

答:
You're right that this is the problem:

```<code>verify(effectList.get(Mockito.anyInt())).execute(playerHandler);
</code>```

Mockito only allows for calls like any() and anyInt() to stand in for parameters to the mock themselves, due to the internal implementation of matchers.

```<code>/*  OK */  when(yourMock.yourMethod(anyInt())).thenReturn(42);
/* BAD */  when(yourList.get(anyInt()).yourMethod(0)).thenReturn(42);

/*  OK */  verify(yourMock).yourMethod(anyInt());
/* BAD */  verify(yourList.get(anyInt())).yourMethod(0);
</code>```

The failure with get(0) is likely an actual failure, and may be related to the fact that your encouragedVenturesScoringTest is actually not calling encouragedVenturesScoring, it's calling influencedCharactersScoring. If this continues to give you trouble after fixing that error, in ways related to Mockito, please edit your question.

Body:
I'm having problems with two void methods. In encouragedVenturesScoring I've followed this answer mocking an arraylist that will be looped in a for loop and haven't mocked the list, but passed a real list and added mocked objects.

Mockito gives me an InvalidUseOfMatchersException on this line

verify(effectList.get(Mockito.anyInt())).execute(playerHandler);

There are lots of questions on SO on this exception , and I think it's because of anyInt(). Anyway I changed it to

verify(effectList.get(0)).execute(playerHandler);

And now it's saying Wanted but not invoked effect.execute(playerHandler)
Actually there were zero interactions with this mock

Is it because I put doNothing ?
doNothing().when(effect).execute(playerHandler);

In my second method militaryStrengthScoring() method is there a way to skip the first chunk of code and just test the if..else condition? What would be the best approach to test this method?

Thank you for your time.

This is the class to be tested

 public class EndGameScoringBaseController implements EndGameScoringHandler {

private static final int[] TERRITORIES_REWARD = {0,0,1,4,10,20};
private static final int[] CHARACTERS_REWARD = {1,3,6,10,15,21};
private static final int RESOURCES_RATE = 5;
private static final int FIRST_MILITARY_REWARD = 5;
private static final int SECOND_MILITARY_REWARD = 2;

private PlayerHandler player;

public EndGameScoringBaseController(PlayerHandler player) {
    super();
    this.player = player;
}

@Override
public void encouragedVenturesScoring() {
    for (DevelopmentCard card : player.getPlayer().getPersonalBoard().getVentures()) {
        for (Effect e : card.getPermanentEffects())
            e.execute(player);
    }
}

@Override
public void militaryStrengthScoring(GameController game) {
    Set<Integer> points = new HashSet<>();
    int myPoints = this.player.getPointsHandler().getMilitaryPoints();

    for (PlayerHandler p: game.getPlayers()) {
        points.add(p.getPointsHandler().getMilitaryPoints());
    }
    int[] rank = new int[points.size()];
    int j = 0;
    for (Integer i : points) {
        rank[j] = i;
        j++;
    }

    Arrays.sort(rank);

    if (rank[rank.length-1] == myPoints) {
        player.getPointsHandler().winMilitaryPoints(FIRST_MILITARY_REWARD);
    }
    else if (rank[rank.length-2] == myPoints) {
        player.getPointsHandler().winVictoryPoints(SECOND_MILITARY_REWARD);
    }

}

Tested method for encouragedVenturesScoring

@Test
public void encouragedVenturesScoringTest() {
    //given
    List<DevelopmentCard> ventureList;
    ventureList = Arrays.asList(developmentCard, developmentCard);
    when(playerHandler.getPlayer().getPersonalBoard().getVentures()).thenReturn(ventureList);
    List<Effect> effectList;
    effectList = Arrays.asList(effect, effect);
    when(developmentCard.getPermanentEffects()).thenReturn(effectList);
    doNothing().when(effect).execute(playerHandler);

    //when
    endgameController.encouragedVenturesScoring();

    //then
    verify(effectList.get(Mockito.anyInt())).execute(playerHandler);
}

Incomplete tested method for militaryStrengthScoring

@Test
public void militaryStrengthScoringTest() {

//given
when(playerHandler.getPointsHandler().getMilitaryPoints()).thenReturn(4);
doNothing().when(playerHandler.getPointsHandler()).winMilitaryPoints(FIRST_MILITARY_REWARD);

//when
endgameController.militaryStrengthScoring(gameController);

//then
/../
}

Body:
You're right that this is the problem:

verify(effectList.get(Mockito.anyInt())).execute(playerHandler);

Mockito only allows for calls like any() and anyInt() to stand in for parameters to the mock themselves, due to the internal implementation of matchers.

/*  OK */  when(yourMock.yourMethod(anyInt())).thenReturn(42);
/* BAD */  when(yourList.get(anyInt()).yourMethod(0)).thenReturn(42);

/*  OK */  verify(yourMock).yourMethod(anyInt());
/* BAD */  verify(yourList.get(anyInt())).yourMethod(0);

The failure with get(0) is likely an actual failure, and may be related to the fact that your encouragedVenturesScoringTest is actually not calling encouragedVenturesScoring, it's calling influencedCharactersScoring. If this continues to give you trouble after fixing that error, in ways related to Mockito, please edit your question.


问:
SQL: get attributes from nested query
How can I return d.title or u.name in the outer SELECT clause?

```<code>SELECT c.id, c.name
FROM components c
INNER JOIN publications p
ON c.id = p.component_id
AND p.document_id IN
    (SELECT d.id FROM documents d WHERE user_id IN
        (SELECT u.id FROM users u WHERE u.brand_id IN (39, 41)
    )
)
</code>```

I get this error when I throw d.title in the top line:

```<code>missing FROM-clause entry for table "d" LINE 1
</code>```

The package I'm using needs these values returned on the top line to make any use out of them in the result.

Structure

A User has many Documents, and Publications is the join table between Documents and Components.

答:
Use below query -

```<code>SELECT c.id, c.name, d.title, u.name
FROM components c
INNER JOIN publications p ON c.id = p.component_id
INNER JOIN documents d ON d.id = p.document_id
INNER JOIN users u ON d.user_id = u.id
AND u.brand_id IN (39, 41)
</code>```

Hope this helps.

Title: SQL: get attributes from nested query

Body:
How can I return d.title or u.name in the outer SELECT clause?

SELECT c.id, c.name
FROM components c
INNER JOIN publications p
ON c.id = p.component_id
AND p.document_id IN
    (SELECT d.id FROM documents d WHERE user_id IN
        (SELECT u.id FROM users u WHERE u.brand_id IN (39, 41)
    )
)

I get this error when I throw d.title in the top line:

missing FROM-clause entry for table "d" LINE 1

The package I'm using needs these values returned on the top line to make any use out of them in the result.

Structure

A User has many Documents, and Publications is the join table between Documents and Components.

Body:
Use below query -

SELECT c.id, c.name, d.title, u.name
FROM components c
INNER JOIN publications p ON c.id = p.component_id
INNER JOIN documents d ON d.id = p.document_id
INNER JOIN users u ON d.user_id = u.id
AND u.brand_id IN (39, 41)

Hope this helps.


问:
Is it possible to wrap table rows responsively?
Is it possible to wrap a table row and its contents (tds) so that the table stays responsive? For example:

```<code><table>
<tr>
<td><!---content---></td>
<td><!---content---></td>
<td><!---content---></td>
<td><!---content---></td>
<td><!---content---></td>
</tr>
<tr>
<td><!---content---></td>
<td><!---content---></td>
<td><!---content---></td>
<td><!---content---></td>
<td><!---content---></td>
</tr>
</table>
</code>```

Can those two rows of 5 become two rows of 4 and a row of 2 for some screen sizes, or three rows of 3 and one row of 1 for others, and so on?

Have tried floats and inline styling but the rows are always on the next line, and never flush next to one another so the td areas look seamless. I have no access to the html of the table structure, so I'm trying to target it with CSS or even Javascript/jQuery.

Any ideas?

答:
1) For your purposes you can use different types of table and show/hide some of them depending on screen size
Here is the solution for your case:

HTML:

.table-xs {
  display: none;
  border: 1px solid black;
}

.table-xs td {
  border: 1px solid blue;
  text-align: center;
}

@media (max-width: 540px) {
  .table-xs {
    display: table;
  }
}

/* === medium === */
.table-md {
  display: none;
  border: 1px solid black;
}

.table-md td {
  border: 1px solid red;
  text-align: center;
}

@media (min-width: 541px) and (max-width: 720px) {
  .table-md {
    display: table;
  }
}

/* === large === */
.table-lg {
  display: none;
  border: 1px solid black;
}

.table-lg td {
  border: 1px solid green;
  text-align: center;
}

@media (min-width: 721px) {
  .table-lg {
    display: table;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="table-lg">
  <tr>
    <td>content</td>
    <td>content</td>
    <td>content</td>
    <td>content</td>
    <td>content</td>
  </tr>
  <tr>
    <td>content</td>
    <td>content</td>
    <td>content</td>
    <td>content</td>
    <td>content</td>
  </tr>
</table>

<table class="table-md">
  <tr>
    <td>content</td>
    <td>content</td>
    <td>content</td>
    <td>content</td>
  </tr>
  <tr>
    <td>content</td>
    <td>content</td>
    <td>content</td>
    <td>content</td>
  </tr>
    <tr>
    <td colspan="2">content</td>
    <td colspan="2">content</td>
  </tr>
</table>

<table class="table-xs">
  <tr>
    <td>content</td>
    <td>content</td>
    <td>content</td>
  </tr>
  <tr>
    <td>content</td>
    <td>content</td>
    <td>content</td>
  </tr>
  <tr>
    <td>content</td>
    <td>content</td>
    <td>content</td>
  </tr>
    <tr>
    <td colspan="3">content</td>
  </tr>
</table></code>```

2) You can use flexbox instead of table

Body:
Is it possible to wrap a table row and its contents (tds) so that the table stays responsive? For example:

Can those two rows of 5 become two rows of 4 and a row of 2 for some screen sizes, or three rows of 3 and one row of 1 for others, and so on?

Have tried floats and inline styling but the rows are always on the next line, and never flush next to one another so the td areas look seamless. I have no access to the html of the table structure, so I'm trying to target it with CSS or even Javascript/jQuery.

Any ideas?

Body:
1) For your purposes you can use different types of table and show/hide some of them depending on screen size
Here is the solution for your case:

HTML:

.table-xs {
  display: none;
  border: 1px solid black;
}

.table-xs td {
  border: 1px solid blue;
  text-align: center;
}

@media (max-width: 540px) {
  .table-xs {
    display: table;
  }
}

/* === medium === */
.table-md {
  display: none;
  border: 1px solid black;
}

.table-md td {
  border: 1px solid red;
  text-align: center;
}

@media (min-width: 541px) and (max-width: 720px) {
  .table-md {
    display: table;
  }
}

/* === large === */
.table-lg {
  display: none;
  border: 1px solid black;
}

.table-lg td {
  border: 1px solid green;
  text-align: center;
}

@media (min-width: 721px) {
  .table-lg {
    display: table;
  }
}

<table class="table-lg">
  <tr>
    <td>content</td>
    <td>content</td>
    <td>content</td>
    <td>content</td>
    <td>content</td>
  </tr>
  <tr>
    <td>content</td>
    <td>content</td>
    <td>content</td>
    <td>content</td>
    <td>content</td>
  </tr>
</table>

<table class="table-md">
  <tr>
    <td>content</td>
    <td>content</td>
    <td>content</td>
    <td>content</td>
  </tr>
  <tr>
    <td>content</td>
    <td>content</td>
    <td>content</td>
    <td>content</td>
  </tr>
    <tr>
    <td colspan="2">content</td>
    <td colspan="2">content</td>
  </tr>
</table>

<table class="table-xs">
  <tr>
    <td>content</td>
    <td>content</td>
    <td>content</td>
  </tr>
  <tr>
    <td>content</td>
    <td>content</td>
    <td>content</td>
  </tr>
  <tr>
    <td>content</td>
    <td>content</td>
    <td>content</td>
  </tr>
    <tr>
    <td colspan="3">content</td>
  </tr>
</table>

2) You can use flexbox instead of table


问:
Creating polymorphic associations has_many/has_one
I have two rails models - Shipments and Notes.
Notes is a polymorphic association with a body and status.

A shipment can have many notes. (has_many :notes, as: :notable)

However, I'd also like to create a has_one relationship in Shipments to show the most recent note with a status that isn't null.

I've tried a few different things but with no luck, including the code below. Anyone know how I can do this? I'm using ruby on rails 4. Please let me know if I can provide any other information.

has_one :last_note_with_status, -> {
  where('notes.notable_type = Shipment')
  .where('notes.status is not null')
  .order(created_at: :desc) }, class_name: 'Note'

答:
Maybe you don't need a has_one clause to achieve that. I think the best way to achieve it is to create a couple scopes on notes:

```<code>class Note
  scope :latest, order(created_at: :desc).limit(1)
  scope :with_status, where("status is not null")
end
</code>```

and declare a method in your shipment class:

```<code>class Shipment
  def latest_note_with_status
    notes.latest.with_status.first
  end
end
</code>```

Body:
Maybe you don't need a has_one clause to achieve that. I think the best way to achieve it is to create a couple scopes on notes:

class Note
  scope :latest, order(created_at: :desc).limit(1)
  scope :with_status, where("status is not null")
end

and declare a method in your shipment class:

class Shipment
  def latest_note_with_status
    notes.latest.with_status.first
  end
end


问:
Basic Flow Control in JavaScript
Could you, please, explain to me, how to write really basic flow control in JavaScript? Thank you.</p>

```<code>flow([

  function(callback) { /* do something */ callback(); /* run next function */ },
  function(callback) { /* do something */ callback(); /* run next function */ },
  function(callback) { /* do something */ callback(); /* run next function */ },
  function(callback) { /* do something */ callback();  }

], function() {

  alert("Done.");

});
</code>```

答:
I've been doing quite a bit of that in a recent project. I've written some code to help manage it. Here's the code. You pass the bundledAsync function an object with a "calls" parameter and a "bundleCallback" parameter. The calls parameter is an array of objets representing the function you want to call. In the fn param, you store a reference to the actual parameter. In the "args" param, you store your arguments. The last argument of each of the functions you pass in must be a callback, which must be called.

I'm miserable at documenting my code and making it useful to others, but this is really really useful to me. I suspect someone else has written something similar, perhaps properly documented. If you can't find it, and need help figuring this out, let me know.

```<code>/**
  This is a way to submit multiple async calls, and be notified when they've all finished

  ```

  NameSpace.bundledAsync({
    calls:[
      {
        fn:  service.getGroups,
        args: [
          function(listsArg){
            listsSummary = listsArg;
          }
        ],
        calls: function(){return UNAB.Util.makeArray(listsSummary, function(list){
          return {
            fn: service.getGroup,
            args: [list.id, function(resp){listsDetail.push(resp)}]
          }
        })}
      }
    ],
    bundleCallback: function(){
      callback(listsDetail)
    }
  });

  ```

  @class bundledAsync
  @static

*/

NameSpace.bundledAsync = function(options){

    var callbacksLeft = 0;
    var calls = $.grep(options.calls, function(call){return call});

    if(options.hasOwnProperty("bundleCallback") && typeof options.bundleCallback != "function"){
      throw new Error("bundleCallback, passed to bundledAsync, must be a function.");
    }

    if(options.chain){ // if this is true, sibling calls will run in succession, not in parallel
      calls.reverse();
      var newCalls = [calls.pop()];
      var lastCall = newCalls[0];
      while(calls.length > 0){
        if(lastCall.calls){
          throw new Error("You can't nest calls if you're in chain mode");
        }
        lastCall.calls = [calls.pop()];
        lastCall = lastCall.calls[0];
      }
      calls = newCalls;
    }

    var decrimentCallbacksLeft = function(){
      if(options.name){
        // log.debug("Starting decrimentCallbacksLeft for: " + options.name + ". Decrimenting callbacksLeft to: " + (callbacksLeft - 1));
      }
      if(--callbacksLeft == 0 && options.bundleCallback){
        // log.debug("No callbacks left. Calling bundleCallback for name: " + options.name);
        options.bundleCallback();
      }
    }

    var doCalls = function(callsToDo){

      if(typeof callsToDo == "function"){
        callsToDo = callsToDo();
      }else{
        callsToDo = $.extend(true, [], callsToDo);// in case we want to reuse the calls
      }

      // right away, return if the calls are empty
      // check to make sure callbacksLeft == 0, because
      // we may be dealing with nested calls
      if(callsToDo.length ==0 && callbacksLeft == 0){
        // log.debug("callsToDo is empty, so call the callback right away.");
        options.bundleCallback();
        return null;
      }

      callbacksLeft += callsToDo.length;
      $.each(callsToDo, function(index, call){
        var numFns = 0;
        // // Look through the args searching for functions.
        // // When one is found, wrap it with our own function.
        // // This assumes that each function has exactly one
        // // callback, and that each callback is called exactly once
        // args can be a function which will return the args,
        // that way, you don't have to determine the args for the function until the moment it's called
        call.args = call.jitArgs? call.args():call.args;
        $.each(call.args, function(index, arg){
          if(typeof arg === "function"){
            numFns++;
            // Here's where we wrap the original function's callback
            call.args[index] = function(){
              // when we get to this point, we know that the original function has totally completed,
              // and we can call any functions chained to this one, or finish the whole process
              arg.apply(null, arguments); // call the original callback
              if(call.calls){
                // maybe we don't want to create the child calls until after
                // the parent has returned. In that case, pass a function instead of an array
                if(typeof call.calls === "function"){
                  call.calls = call.calls();
                }
                // if this call has any call of its own, send those out now
                doCalls(call.calls);
              }
              decrimentCallbacksLeft();
            }
          }
        });
        if(numFns!=1){
          throw new Error("Each function passed to bundledAsync must have one and only one arg which is a function");
        }
        // if(call.fn.length != call.args.length){
        //   log.warn("The current function is being called with a different number of arguments that that with which it was declared. Should be: "+call.fn.length+", was: "+call.args.length+" \n" + call.fn.toString());
        // }
        call.fn.apply(null, call.args);
      });
    }

    doCalls(calls);
  }
</code>```

Title: Basic Flow Control in JavaScript

Body:
Could you, please, explain to me, how to write really basic flow control in JavaScript? Thank you.

flow([

  function(callback) { /* do something */ callback(); /* run next function */ },
  function(callback) { /* do something */ callback(); /* run next function */ },
  function(callback) { /* do something */ callback(); /* run next function */ },
  function(callback) { /* do something */ callback();  }

], function() {

  alert("Done.");

});

Body:
I've been doing quite a bit of that in a recent project. I've written some code to help manage it. Here's the code. You pass the bundledAsync function an object with a "calls" parameter and a "bundleCallback" parameter. The calls parameter is an array of objets representing the function you want to call. In the fn param, you store a reference to the actual parameter. In the "args" param, you store your arguments. The last argument of each of the functions you pass in must be a callback, which must be called.

I'm miserable at documenting my code and making it useful to others, but this is really really useful to me. I suspect someone else has written something similar, perhaps properly documented. If you can't find it, and need help figuring this out, let me know.

/**
  This is a way to submit multiple async calls, and be notified when they've all finished

  <pre>

  NameSpace.bundledAsync({
    calls:[
      {
        fn:  service.getGroups,
        args: [
          function(listsArg){
            listsSummary = listsArg;
          }
        ],
        calls: function(){return UNAB.Util.makeArray(listsSummary, function(list){
          return {
            fn: service.getGroup,
            args: [list.id, function(resp){listsDetail.push(resp)}]
          }
        })}
      }
    ],
    bundleCallback: function(){
      callback(listsDetail)
    }
  });

  </pre>

  @class bundledAsync
  @static

*/

NameSpace.bundledAsync = function(options){

    var callbacksLeft = 0;
    var calls = $.grep(options.calls, function(call){return call});

    if(options.hasOwnProperty("bundleCallback") && typeof options.bundleCallback != "function"){
      throw new Error("bundleCallback, passed to bundledAsync, must be a function.");
    }

    if(options.chain){ // if this is true, sibling calls will run in succession, not in parallel
      calls.reverse();
      var newCalls = [calls.pop()];
      var lastCall = newCalls[0];
      while(calls.length > 0){
        if(lastCall.calls){
          throw new Error("You can't nest calls if you're in chain mode");
        }
        lastCall.calls = [calls.pop()];
        lastCall = lastCall.calls[0];
      }
      calls = newCalls;
    }

    var decrimentCallbacksLeft = function(){
      if(options.name){
        // log.debug("Starting decrimentCallbacksLeft for: " + options.name + ". Decrimenting callbacksLeft to: " + (callbacksLeft - 1));
      }
      if(--callbacksLeft == 0 && options.bundleCallback){
        // log.debug("No callbacks left. Calling bundleCallback for name: " + options.name);
        options.bundleCallback();
      }
    }

    var doCalls = function(callsToDo){

      if(typeof callsToDo == "function"){
        callsToDo = callsToDo();
      }else{
        callsToDo = $.extend(true, [], callsToDo);// in case we want to reuse the calls
      }

      // right away, return if the calls are empty
      // check to make sure callbacksLeft == 0, because
      // we may be dealing with nested calls
      if(callsToDo.length ==0 && callbacksLeft == 0){
        // log.debug("callsToDo is empty, so call the callback right away.");
        options.bundleCallback();
        return null;
      }

      callbacksLeft += callsToDo.length;
      $.each(callsToDo, function(index, call){
        var numFns = 0;
        // // Look through the args searching for functions.
        // // When one is found, wrap it with our own function.
        // // This assumes that each function has exactly one
        // // callback, and that each callback is called exactly once
        // args can be a function which will return the args,
        // that way, you don't have to determine the args for the function until the moment it's called
        call.args = call.jitArgs? call.args():call.args;
        $.each(call.args, function(index, arg){
          if(typeof arg === "function"){
            numFns++;
            // Here's where we wrap the original function's callback
            call.args[index] = function(){
              // when we get to this point, we know that the original function has totally completed,
              // and we can call any functions chained to this one, or finish the whole process
              arg.apply(null, arguments); // call the original callback
              if(call.calls){
                // maybe we don't want to create the child calls until after
                // the parent has returned. In that case, pass a function instead of an array
                if(typeof call.calls === "function"){
                  call.calls = call.calls();
                }
                // if this call has any call of its own, send those out now
                doCalls(call.calls);
              }
              decrimentCallbacksLeft();
            }
          }
        });
        if(numFns!=1){
          throw new Error("Each function passed to bundledAsync must have one and only one arg which is a function");
        }
        // if(call.fn.length != call.args.length){
        //   log.warn("The current function is being called with a different number of arguments that that with which it was declared. Should be: "+call.fn.length+", was: "+call.args.length+" \n" + call.fn.toString());
        // }
        call.fn.apply(null, call.args);
      });
    }

    doCalls(calls);
  }


问:
SQLite - No error when updating a deleted row
I'm trying to force an error condition to test some exception handling by updating a row after it has been deleted using the following steps:

```<code>1. Load record into GUI
2. Pull .db3 file to Windows
3. Delete record with sqlite3
4. Push .db3 file back to Android
3. Save record from GUI
</code>```

However, there is no exception thrown from ExecuteNonQuery() nor is there anything in logcat.

Why, if for Step 3, the DB file is instead renamed an exception thrown, but not when deleting the record?

Update: Deleting the record directly from the device with sqlite3 results in this same behavior.

Note: Samsung Galaxy Tab2 requires the PIE (Position Independent Execution) version.

答: I am not entirely sure about the sql3 data provider. However, you would want to use a query function, not a non query for the delete. Get the rows affected by deletion in the query. And then throw and exception ad required for the scenario when no rows are returned.</p>

Body:
I'm trying to force an error condition to test some exception handling by updating a row after it has been deleted using the following steps:

1. Load record into GUI
2. Pull .db3 file to Windows
3. Delete record with sqlite3
4. Push .db3 file back to Android
3. Save record from GUI

However, there is no exception thrown from ExecuteNonQuery() nor is there anything in logcat.

Why, if for Step 3, the DB file is instead renamed an exception thrown, but not when deleting the record?

Update: Deleting the record directly from the device with sqlite3 results in this same behavior.

Note: Samsung Galaxy Tab2 requires the PIE (Position Independent Execution) version.


问:
Python/Django recursion issue with saved querysets
I have user profiles that are each assigned a manager. I thought using recursion would be a good way to query every employee at every level under a particular manager. The goal is, if the CEO were to sign in, he should be able to query everyone at the company - but If I sign on I can only see people in my immediate team and the people below them, etc. until you get to the low level employees.

However when I run the following:

```<code>def team_training_list(request):
 # pulls all training documents from training document model
 user = request.user
 manager_direct_team = Profile.objects.filter(manager=user)
 query = Profile.objects.filter(first_name='fake')
 trickle_team = manager_loop(manager_direct_team, query)
 # manager_trickle_team = manager_direct_team | trickle_team
 print(trickle_team)

def manager_loop(list, query):
 for member in list:
    user_instance = User.objects.get(username=member)
    has_team = Profile.objects.filter(manager=user_instance)
    if has_team:
        query = query | has_team
        manager_loop(has_team, query)

    else:
        continue

 return query
</code>```

It only returns the last query that was run instead of the compiled queryset that I am trying to grow. I've tried placing 'return' before 'manager_loop(has_team, query) in order save the values but it also kills the loop at the first non-manager employee instead of continuing to the next employee.

I'm new to django so if there is an better way than recursion to pull the information that I need, I'd appreciate suggestions on that too.

EDIT:
As requested, here is the profile model.

```<code>class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=30, blank=False)
    last_name = models.CharField(max_length=30, blank=False)
    email = models.EmailField( blank=True, help_text='Optional',)
    receive_email_notifications = models.BooleanField(default=False)
    mobile_number = models.CharField(
        max_length=15,
        blank=True,
        help_text='Optional'
    )
    carrier_options = (
        (None, ''),
        ('@txt.att.net', 'AT&T'),
        ('@messaging.sprintpcs.com', 'Sprint'),
        ('@tmomail.net', 'T-Mobile'),
        ('@vtext.com', 'Verizon'),
    )
    mobile_carrier = models.CharField(max_length=25, choices=carrier_options, blank=True,
                                      help_text='Optional')

    receive_sms_notifications = models.BooleanField(default=False)
    job_title = models.ForeignKey(JobTitle, unique=False, null=True)
    manager = models.ForeignKey(User, unique=False, blank=True, related_name='+', null=True)
</code>```

答:
Ok, so it's a hierarchical model.

The problem with your current approach is this line:

```<code>query = query | has_team
</code>```

This reassigns the local name query to a new queryset, but does not reassign the name in the caller. (Well, that's what I think it's trying to do - I am a little rusty but I don't think you can just | together querysets like that.) You'd also need something like:

```<code>query = manager_loop(has_team, query)
</code>```

to propagate the changes via the returned object.

That said, while Django doesn't have built-in support for recursive queries, there are some third party packages that do. Old answers eg (Django self-recursive foreignkey filter query for all childs and Creating efficient database queries for hierarchical models (django)) recommend django-mptt. Your tag mentions postgres, so this post might be relevant:
https://two-wrongs.com/fast-sql-for-inheritance-in-a-django-hierarchy

If you don't use a third-party approach, it should be possible to clean up the evolution of the queryset - cast it to a set and use update or something, since you're accumulating profiles. But the key error is not using the returned modified object.

Body:
I have user profiles that are each assigned a manager. I thought using recursion would be a good way to query every employee at every level under a particular manager. The goal is, if the CEO were to sign in, he should be able to query everyone at the company - but If I sign on I can only see people in my immediate team and the people below them, etc. until you get to the low level employees.

However when I run the following:

def team_training_list(request):
 # pulls all training documents from training document model
 user = request.user
 manager_direct_team = Profile.objects.filter(manager=user)
 query = Profile.objects.filter(first_name='fake')
 trickle_team = manager_loop(manager_direct_team, query)
 # manager_trickle_team = manager_direct_team | trickle_team
 print(trickle_team)

def manager_loop(list, query):
 for member in list:
    user_instance = User.objects.get(username=member)
    has_team = Profile.objects.filter(manager=user_instance)
    if has_team:
        query = query | has_team
        manager_loop(has_team, query)

    else:
        continue

 return query

It only returns the last query that was run instead of the compiled queryset that I am trying to grow. I've tried placing 'return' before 'manager_loop(has_team, query) in order save the values but it also kills the loop at the first non-manager employee instead of continuing to the next employee.

I'm new to django so if there is an better way than recursion to pull the information that I need, I'd appreciate suggestions on that too.

EDIT:
As requested, here is the profile model.

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=30, blank=False)
    last_name = models.CharField(max_length=30, blank=False)
    email = models.EmailField( blank=True, help_text='Optional',)
    receive_email_notifications = models.BooleanField(default=False)
    mobile_number = models.CharField(
        max_length=15,
        blank=True,
        help_text='Optional'
    )
    carrier_options = (
        (None, ''),
        ('@txt.att.net', 'AT&T'),
        ('@messaging.sprintpcs.com', 'Sprint'),
        ('@tmomail.net', 'T-Mobile'),
        ('@vtext.com', 'Verizon'),
    )
    mobile_carrier = models.CharField(max_length=25, choices=carrier_options, blank=True,
                                      help_text='Optional')

    receive_sms_notifications = models.BooleanField(default=False)
    job_title = models.ForeignKey(JobTitle, unique=False, null=True)
    manager = models.ForeignKey(User, unique=False, blank=True, related_name='+', null=True)

Body:
Ok, so it's a hierarchical model.

The problem with your current approach is this line:

query = query | has_team

This reassigns the local name query to a new queryset, but does not reassign the name in the caller. (Well, that's what I think it's trying to do - I am a little rusty but I don't think you can just | together querysets like that.) You'd also need something like:

query = manager_loop(has_team, query)

to propagate the changes via the returned object.

That said, while Django doesn't have built-in support for recursive queries, there are some third party packages that do. Old answers eg (Django self-recursive foreignkey filter query for all childs and Creating efficient database queries for hierarchical models (django)) recommend django-mptt. Your tag mentions postgres, so this post might be relevant:
https://two-wrongs.com/fast-sql-for-inheritance-in-a-django-hierarchy

If you don't use a third-party approach, it should be possible to clean up the evolution of the queryset - cast it to a set and use update or something, since you're accumulating profiles. But the key error is not using the returned modified object.


问:
Python Histogram of Oriented Gradients
I am trying to implement this version of Histogram of Oriented Gradients(HOG). My code is below. The only difference in my code is that I've used opencv to read the image and convert it to grayscale.

```<code>import cv2
import matplotlib.pyplot as plt
from skimage.feature import hog
from skimage import data, color, exposure

filename = 'match1/hockey15.jpg'
im = cv2.imread(filename)
gr = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

print im.shape
image = gr

fd, hog_image = hog(image, orientations=8, pixels_per_cell=(16, 16),
                    cells_per_block=(1, 1), visualise=True)

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4), sharex=True, sharey=True)

ax1.axis('off')
ax1.imshow(image, cmap=plt.cm.gray)
ax1.set_title('Input image')
ax1.set_adjustable('box-forced')

# Rescale histogram for better display
hog_image_rescaled = exposure.rescale_intensity(hog_image, in_range=(0, 0.02))

ax2.axis('off')
ax2.imshow(hog_image_rescaled, cmap=plt.cm.gray)
ax2.set_title('Histogram of Oriented Gradients')
ax1.set_adjustable('box-forced')
plt.show()
</code>```

A sample input and output are:

Input:

Output:

Why is the output so cluttered? I have even tried the image with the astronaut in the skimage link above. For this too, I get a lot of clutter and the output is not at all like what is shown in the link. How can I fix this?

答: I'm not sure why but the mistake is due to reading the image and converting it to grayscale with opencv. Doing both with matplotlib like the tutorial suggests, gives me the correct result.</p>

Title: Python Histogram of Oriented Gradients

Body:
I am trying to implement this version of Histogram of Oriented Gradients(HOG). My code is below. The only difference in my code is that I've used opencv to read the image and convert it to grayscale.

import cv2
import matplotlib.pyplot as plt
from skimage.feature import hog
from skimage import data, color, exposure

filename = 'match1/hockey15.jpg'
im = cv2.imread(filename)
gr = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

print im.shape
image = gr

fd, hog_image = hog(image, orientations=8, pixels_per_cell=(16, 16),
                    cells_per_block=(1, 1), visualise=True)

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4), sharex=True, sharey=True)

ax1.axis('off')
ax1.imshow(image, cmap=plt.cm.gray)
ax1.set_title('Input image')
ax1.set_adjustable('box-forced')

# Rescale histogram for better display
hog_image_rescaled = exposure.rescale_intensity(hog_image, in_range=(0, 0.02))

ax2.axis('off')
ax2.imshow(hog_image_rescaled, cmap=plt.cm.gray)
ax2.set_title('Histogram of Oriented Gradients')
ax1.set_adjustable('box-forced')
plt.show()

A sample input and output are:

Input:

Output:

Why is the output so cluttered? I have even tried the image with the astronaut in the skimage link above. For this too, I get a lot of clutter and the output is not at all like what is shown in the link. How can I fix this?


问:
Polymer style google-map
How can styles be applied to the Polymer 1 google-map tag?

The documentation suggests that an object of styles can be passed in via a 'styles' property on the tag.

However, when using something like this which previously worked without issue, the style is not being loaded in.

I've tried replacing the code from snazzymaps with an object (as opposed to an array), but that doesn't work.

答:
Expanding on my previous comment / answer to Dian Carlos, here is code I finally used

Assuming that styledMapDef holds the map styles definitions object

```<code>var styledMapType = new google.maps.StyledMapType(styledMapDef, {name: 'Styled'});
this.map.setOptions( {"mapTypeControl":"true","mapTypeControlOptions":{"position":"3", "mapTypeIds": ["roadmap", "satellite", "hybrid", "terrain", "styled"]}, "scaleControl": "true"} );
this.map.mapTypes.set('styled', styledMapType);
this.map.setMapTypeId('styled');
</code>```

Title: Polymer style google-map

Body:
Expanding on my previous comment / answer to Dian Carlos, here is code I finally used

Assuming that styledMapDef holds the map styles definitions object

var styledMapType = new google.maps.StyledMapType(styledMapDef, {name: 'Styled'});
this.map.setOptions( {"mapTypeControl":"true","mapTypeControlOptions":{"position":"3", "mapTypeIds": ["roadmap", "satellite", "hybrid", "terrain", "styled"]}, "scaleControl": "true"} );
this.map.mapTypes.set('styled', styledMapType);
this.map.setMapTypeId('styled');


问:
Passing variables from controller to view in php
I am building a php framework (MVC) for learning purposes. i need help with sending variables from my controller to the view.

HomeController

```<code><?php
class HomeController{
    public function home()
    {
        $some_var = "Do Something";
        return view("home.php",compact('some_var'));
    }
}
?>
</code>```

I want to be able to access the $some_var variable in my view

view

```<code><h3>$some_var</h3>
</code>```

答:
To make the variables from the controller accessible in the html file, you get the variables from the compact function using php's extract function extract function documentation before including the html file

```<code>   <?php

// Controller Class

class Controller
{
    public function someMethod()
    {
        $variable = "SomeVar";
        return view("home.php",compact('variable'));
    }
}

// template loader

function view($page,$variables=[])
{
    if(count($variables))
    {
        extract($variables);
    }
    require $page;
}
</code>```

this makes $variable accessible in the index.php file

Body:
I am building a php framework (MVC) for learning purposes. i need help with sending variables from my controller to the view.

HomeController

<?php
class HomeController{
    public function home()
    {
        $some_var = "Do Something";
        return view("home.php",compact('some_var'));
    }
}
?>

I want to be able to access the $some_var variable in my view

view

$some_var

Body:
To make the variables from the controller accessible in the html file, you get the variables from the compact function using php's extract function extract function documentation before including the html file

   <?php

// Controller Class

class Controller
{
    public function someMethod()
    {
        $variable = "SomeVar";
        return view("home.php",compact('variable'));
    }
}

// template loader

function view($page,$variables=[])
{
    if(count($variables))
    {
        extract($variables);
    }
    require $page;
}

this makes $variable accessible in the index.php file


问:
Ext Js Listview columns are not hiding or widening properly
I have an Ext Js listview that I am attempting to get rid, or make my Id column smaller.  Right now it's the following code

```<code>    this.relList = new Ext.list.ListView({
        singleSelect: true,
        store: this.buildStore(),
        columns: [{
            header: 'Id',
            dataIndex: 'Id',
            hidden: true
        }, {
            header: 'Name',
            dataIndex: 'Name',
        }]
    });
</code>```

When this ListView is displayed, it still shows the Id column even though I told it to hide it.  Furthermore, if I change the hidden:true to width: 1 to make the Id column small, the Name column no longer shows and the Id column takes up the whole listview.

How can I hide this column?

答: Why use the Id column at all? you can access the data via record.data or through the store itself and do not need to add it as a column</p>

Body:
I have an Ext Js listview that I am attempting to get rid, or make my Id column smaller.  Right now it's the following code

    this.relList = new Ext.list.ListView({
        singleSelect: true,
        store: this.buildStore(),
        columns: [{
            header: 'Id',
            dataIndex: 'Id',
            hidden: true
        }, {
            header: 'Name',
            dataIndex: 'Name',
        }]
    });

When this ListView is displayed, it still shows the Id column even though I told it to hide it.  Furthermore, if I change the hidden:true to width: 1 to make the Id column small, the Name column no longer shows and the Id column takes up the whole listview.

How can I hide this column?


问:
Handling Google App Engine datastore NoneType errors
I wish to handle NoneType errors from the Google App Engine ndb Datastore.

Here is my code:

```<code>def post(self):
    # get the email and password from the login form
    global u_qry
    email = self.request.get("email")
    password = self.request.get("password")

    try:
        u_qry = user_db.User.get_by_email(email)
    except BaseException, e:
        self.response.out.write(e, u_qry)
    else:
        self.response.out.write("User Recognised")
        self.response.out.write(u_qry)
</code>```

When the user does not exist, the except clause is not catching any error.

```<code>Output:
User Recognised None
</code>```

why is the except clause not catching this error? What exception can be used to catch this error?

I realise I can use if/else statements on this, but would like to learn how to use the try/except clause in GAE.

Thanks.

答:
While you're not showing the way the User.get_by_email() function is implemented I suspect it is simply based on a query. And returning an empty result from a query is a perfectly valid situation - no existing datastore entity matches the query. It's not an exception.

If you intend to consider such case an exception you have to raise one yourself inside User.get_by_email() and in that case you'd be able to catch it in your post() function.

Alternatively you can directly check u_qry for a None value.

Body:
I wish to handle NoneType errors from the Google App Engine ndb Datastore.

Here is my code:

def post(self):
    # get the email and password from the login form
    global u_qry
    email = self.request.get("email")
    password = self.request.get("password")

    try:
        u_qry = user_db.User.get_by_email(email)
    except BaseException, e:
        self.response.out.write(e, u_qry)
    else:
        self.response.out.write("User Recognised")
        self.response.out.write(u_qry)

When the user does not exist, the except clause is not catching any error.

Output:
User Recognised None

why is the except clause not catching this error? What exception can be used to catch this error?

I realise I can use if/else statements on this, but would like to learn how to use the try/except clause in GAE.

Thanks.


问:
How to use tm package for text analytics in Hebrew or Arabic
I would like to use tm package for Hebrew or Arabic text analysis. I tried several methods to see if tm will be able to process some words but i ran into an error, Is there a way to solve this issue?</p>

```<code> text  <- "הנוסעים חיכו זמן רב לנסיעה"
 Encoding(text)
#[1] "unknown"
 Encoding(text)  <- "UTF-8"
 ap.corpus <- Corpus(DataframeSource(data.frame(text)))
 ap.corpus <- tm_map(ap.corpus, removePunctuation)
 ap.corpus <- tm_map(ap.corpus, content_transformer(tolower))
Error in FUN(content(x), ...) :
  invalid input 'הנוסעים חיכו זמן רב לנסיעה' in 'utf8towcs'
</code>```

答:
Here is the answer, we need to add this encoding method:

```<code>iconv(text, "ISO-8859-8", "UTF-8")[1]
</code>```

Instead of using : Encoding(text)  <- "UTF-8"

Body:
I would like to use tm package for Hebrew or Arabic text analysis. I tried several methods to see if tm will be able to process some words but i ran into an error, Is there a way to solve this issue?

 text  <- "הנוסעים חיכו זמן רב לנסיעה"
 Encoding(text)
#[1] "unknown"
 Encoding(text)  <- "UTF-8"
 ap.corpus <- Corpus(DataframeSource(data.frame(text)))
 ap.corpus <- tm_map(ap.corpus, removePunctuation)
 ap.corpus <- tm_map(ap.corpus, content_transformer(tolower))
Error in FUN(content(x), ...) :
  invalid input 'הנוסעים חיכו זמן רב לנסיעה' in 'utf8towcs'

Body:
Here is the answer, we need to add this encoding method:

iconv(text, "ISO-8859-8", "UTF-8")[1]

Instead of using : Encoding(text)  <- "UTF-8"


问:
Value error with labelencoder and OneHotEncoder
I'm trying to turn a categorical string column into several dummy variable binary columns, but I'm getting a valueerror.

Here's the code:

```<code>import sys, os
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from dateutil import parser
import math
import traceback
import logging
datasetMod = pd.read_csv('data.csv')

X = datasetMod.iloc[:, 3:6].values
y = datasetMod.iloc[:, 1].values
print(X[:, 0])

# Encoding categorical data
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
try:
    labelencoder_X = LabelEncoder()
    X[:, 0] = labelencoder_X.fit_transform(X[:, 0])
    onehotencoder = OneHotEncoder(categorical_features = [0])
    X = onehotencoder.fit_transform(X).toarray()
except Exception as e:
    exc_type, exc_obj, exc_tb = sys.exc_info()
    fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
    print(exc_type, fname, exc_tb.tb_lineno)
</code>```

Here's the error:

```<code><class 'ValueError'> multipleLinearRegression.py 23
</code>```

The result from that print statement of that column is:

```<code>['Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Weekend' 'Workday' 'Workday' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend']
</code>```

There doesn't seem to be anything wrong with the strings themselves, no whitespaces inbetween, no numeric like notation. So I don't understand why i'm getting a valuetype can't convert string to float error.

Any help would be highly appreciated.

Update

The onehotencoder works somewhat fine now, but the final result is of type object, while it's supposed to be of type float64:

```<code>labelencoder_X = LabelEncoder()
X[:, 1] = labelencoder_X.fit_transform(X[:, 1])
X[:, 2] = labelencoder_X.fit_transform(X[:, 2])
X[:, 3] = labelencoder_X.fit_transform(X[:, 3])
onehotencoder = OneHotEncoder(categorical_features = [1,2,3])
onehotencoder.fit(X[:, 1])
onehotencoder.fit(X[:, 2])
onehotencoder.fit(X[:, 3])
onehotencoder.transform(X[:, 1])
onehotencoder.transform(X[:, 2])
onehotencoder.transform(X[:, 3])
X = onehotencoder.toArray()
</code>```

Update 2

```<code>from sklearn.preprocessing import LabelEncoder, OneHotEncoder

labelencoder_X = LabelEncoder()
X[:, 1] = labelencoder_X.fit_transform(X[:, 1])
X[:, 2] = labelencoder_X.fit_transform(X[:, 2])
X[:, 3] = labelencoder_X.fit_transform(X[:, 3])

onehotencoder = OneHotEncoder(categorical_features = [1,2,3])
X[:, 1] = onehotencoder.fit_transform(X[:, 1]).toarray()
X[:, 2] = onehotencoder.fit_transform(X[:, 2]).toarray()
X[:, 3] = onehotencoder.fit_transform(X[:, 3]).toarray()

print(X.dtype) #object
</code>```

Final Code

Since the categorical_features already dictates the indexes, i can fit_transform() on the whole matrix X. Thanks to @mkos for the patience!

```<code>from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X = LabelEncoder()
X[:, 1] = labelencoder_X.fit_transform(X[:, 1])
X[:, 2] = labelencoder_X.fit_transform(X[:, 2])
X[:, 3] = labelencoder_X.fit_transform(X[:, 3])
onehotencoder = OneHotEncoder(categorical_features = [1,2,3])
X = onehotencoder.fit_transform(X)
</code>```

答:
This should do the trick:

```<code>onehotencoder = OneHotEncoder(categorical_features = [1,2,3])
X = onehotencoder.fit_transform(X)
</code>```

you can print it with:

```<code>print(X.toArray())
</code>```

Having X as a sparse matrix is not bad, because it saves memory. If you want to see it, then you convert it to regular np.array with toArray().

Body:
I'm trying to turn a categorical string column into several dummy variable binary columns, but I'm getting a valueerror.

Here's the code:

import sys, os
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from dateutil import parser
import math
import traceback
import logging
datasetMod = pd.read_csv('data.csv')

X = datasetMod.iloc[:, 3:6].values
y = datasetMod.iloc[:, 1].values
print(X[:, 0])

# Encoding categorical data
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
try:
    labelencoder_X = LabelEncoder()
    X[:, 0] = labelencoder_X.fit_transform(X[:, 0])
    onehotencoder = OneHotEncoder(categorical_features = [0])
    X = onehotencoder.fit_transform(X).toarray()
except Exception as e:
    exc_type, exc_obj, exc_tb = sys.exc_info()
    fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
    print(exc_type, fname, exc_tb.tb_lineno)

Here's the error:

<class 'ValueError'> multipleLinearRegression.py 23

The result from that print statement of that column is:

['Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Weekend' 'Workday' 'Workday' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday' 'Workday'
 'Workday' 'Workday' 'Workday' 'Workday' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend' 'Weekend'
 'Weekend' 'Weekend' 'Weekend' 'Weekend']

There doesn't seem to be anything wrong with the strings themselves, no whitespaces inbetween, no numeric like notation. So I don't understand why i'm getting a valuetype can't convert string to float error.

Any help would be highly appreciated.

Update

The onehotencoder works somewhat fine now, but the final result is of type object, while it's supposed to be of type float64:

labelencoder_X = LabelEncoder()
X[:, 1] = labelencoder_X.fit_transform(X[:, 1])
X[:, 2] = labelencoder_X.fit_transform(X[:, 2])
X[:, 3] = labelencoder_X.fit_transform(X[:, 3])
onehotencoder = OneHotEncoder(categorical_features = [1,2,3])
onehotencoder.fit(X[:, 1])
onehotencoder.fit(X[:, 2])
onehotencoder.fit(X[:, 3])
onehotencoder.transform(X[:, 1])
onehotencoder.transform(X[:, 2])
onehotencoder.transform(X[:, 3])
X = onehotencoder.toArray()

Update 2

from sklearn.preprocessing import LabelEncoder, OneHotEncoder

labelencoder_X = LabelEncoder()
X[:, 1] = labelencoder_X.fit_transform(X[:, 1])
X[:, 2] = labelencoder_X.fit_transform(X[:, 2])
X[:, 3] = labelencoder_X.fit_transform(X[:, 3])

onehotencoder = OneHotEncoder(categorical_features = [1,2,3])
X[:, 1] = onehotencoder.fit_transform(X[:, 1]).toarray()
X[:, 2] = onehotencoder.fit_transform(X[:, 2]).toarray()
X[:, 3] = onehotencoder.fit_transform(X[:, 3]).toarray()

print(X.dtype) #object

Final Code

Since the categorical_features already dictates the indexes, i can fit_transform() on the whole matrix X. Thanks to @mkos for the patience!

from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X = LabelEncoder()
X[:, 1] = labelencoder_X.fit_transform(X[:, 1])
X[:, 2] = labelencoder_X.fit_transform(X[:, 2])
X[:, 3] = labelencoder_X.fit_transform(X[:, 3])
onehotencoder = OneHotEncoder(categorical_features = [1,2,3])
X = onehotencoder.fit_transform(X)

Body:
This should do the trick:

onehotencoder = OneHotEncoder(categorical_features = [1,2,3])
X = onehotencoder.fit_transform(X)

you can print it with:

print(X.toArray())

Having X as a sparse matrix is not bad, because it saves memory. If you want to see it, then you convert it to regular np.array with toArray().


问:
Good pattern for multiphase algorithm?
Is there a pattern (refactoring) to improve this piece of code?

```<code>    int phase = 0;
    foreach (var some in arrayOfSome)
    {
        if (phase == 0)
        {
            bool result = DoSomething_0(some);
            if (result) phase = 1;
        }
        else if (phase == 1)
        {
            bool result = DoSomething_1(some);
            if (result) phase = 0;

            result = DoSomething_1_0(some);
            if (result) phase = 2;
        }
        else if (phase == 2)
        {
            bool result = DoSomething_2(some);
            if (result) break;
        }
    }
</code>```

First of all, I want to reduce the number of conditional operators and make the code more readable.

答:
Don't see the need for refactoring here. Maybe you could reduce some lines and write it like this:

```<code>int phase = 0;
foreach (var some in arrayOfSome)
{
    if (phase == 0)
    {
        if (DoSomething_0(some)) phase = 1;
    }
    if (phase == 1)
    {
        if (DoSomething_1(some)) phase = 0;
        if (DoSomething_1_0(some)) phase = 2;
    }
    if (phase == 2)
    {
        if (DoSomething_2(some)) break;
    }
}
</code>```

If you are concerned with too many if's within a for (again it is readable in your case) you can have a look at Flattening Arrow Code

Title: Good pattern for multiphase algorithm?

Body:
Is there a pattern (refactoring) to improve this piece of code?

    int phase = 0;
    foreach (var some in arrayOfSome)
    {
        if (phase == 0)
        {
            bool result = DoSomething_0(some);
            if (result) phase = 1;
        }
        else if (phase == 1)
        {
            bool result = DoSomething_1(some);
            if (result) phase = 0;

            result = DoSomething_1_0(some);
            if (result) phase = 2;
        }
        else if (phase == 2)
        {
            bool result = DoSomething_2(some);
            if (result) break;
        }
    }

First of all, I want to reduce the number of conditional operators and make the code more readable.

Body:
Don't see the need for refactoring here. Maybe you could reduce some lines and write it like this:

int phase = 0;
foreach (var some in arrayOfSome)
{
    if (phase == 0)
    {
        if (DoSomething_0(some)) phase = 1;
    }
    if (phase == 1)
    {
        if (DoSomething_1(some)) phase = 0;
        if (DoSomething_1_0(some)) phase = 2;
    }
    if (phase == 2)
    {
        if (DoSomething_2(some)) break;
    }
}

If you are concerned with too many if's within a for (again it is readable in your case) you can have a look at Flattening Arrow Code


问:
Conditional postinstall in package.json depending on your OS?
Here in my package.json i'm running into this issue when going between my Linux machine and Windows machine:

```<code>"postinstall": "node.exe node_modules/bower/bin/bower install" (for Windows)
"postinstall": "./node_modules/bower/bin/bower install" (for Linux)
</code>```

I have to keep swapping these lines depending on my environment - how can I do this cross-OS so it will work in both places?

I want to do something like:

```<code>"postinstall": isOSWindows ? "node.exe node_modules/bower/bin/bower install" : "./node_modules/bower/bin/bower install"
</code>```

答:
First thing is that I think you do not need switch OS to run bower from local dependencies.

After you install bower as devDepedency you can set for example script in package.json

```<code>"scripts":{
  "postinstall": "bower install"
}
</code>```

And then run npm install, should work.

This is possible because after installing bower as local dependency in node_modules folder an executable version of bower script is generated in .bin folder

Or if you want to switch between OS you can use this technique.

To not have to long script command I put this into external script and use process.platform, something like that script.js

```<code>const {exec} = require('child_process');

if (process.platform !== 'win32') {
  // run scripts for Windows
  return;
}

const commands = [
  'set NODE_ENV=e2e_tests',
  'npm run start-local-test-environment',
  'grunt build',
  'nightwatch ./test/e2e/tests --skipgroup common,helpers --env chrome'
];

const executedCommands = exec(commands.join('&&'), (error) => {
  if (error) {
    throw error;
 }
});
</code>```

and then in package.json script you can have:

"postinstall": "node ./scripts/script.js",

Body:
Here in my package.json i'm running into this issue when going between my Linux machine and Windows machine:

"postinstall": "node.exe node_modules/bower/bin/bower install" (for Windows)
"postinstall": "./node_modules/bower/bin/bower install" (for Linux)

I have to keep swapping these lines depending on my environment - how can I do this cross-OS so it will work in both places?

I want to do something like:

"postinstall": isOSWindows ? "node.exe node_modules/bower/bin/bower install" : "./node_modules/bower/bin/bower install"

Body:
First thing is that I think you do not need switch OS to run bower from local dependencies.

After you install bower as devDepedency you can set for example script in package.json

"scripts":{
  "postinstall": "bower install"
}

And then run npm install, should work.

This is possible because after installing bower as local dependency in node_modules folder an executable version of bower script is generated in .bin folder

Or if you want to switch between OS you can use this technique.

To not have to long script command I put this into external script and use process.platform, something like that script.js

const {exec} = require('child_process');

if (process.platform !== 'win32') {
  // run scripts for Windows
  return;
}

const commands = [
  'set NODE_ENV=e2e_tests',
  'npm run start-local-test-environment',
  'grunt build',
  'nightwatch ./test/e2e/tests --skipgroup common,helpers --env chrome'
];

const executedCommands = exec(commands.join('&&'), (error) => {
  if (error) {
    throw error;
 }
});

and then in package.json script you can have:

"postinstall": "node ./scripts/script.js",


问:
How to create a hand with 13 playing cards in it
I was given a project in computer science, however I can't figure out how to get 13 cards into my hand. There is a memory error in the hand class, but I can't figure out why, it isn't putting 13 cards in each hand. Here is my code so far: </p>

```<code>#Keshav Ramesh
#Project 8

import random

class card:
    def __init__(self, suit, value):
        self.suit=suit
        self.value=value

    #methods
    def printer(self):
        print("{0}  {1}".format(self.suit, self.value))

    def __lt__(self, other):
        if(self.value == other.value):
            return self.suit < other.suit
        elif (self.value != other.value):
            return self.value < other.value
    def __gt__(self, other):
        return not(self<other)

    def __str__(self):
        return "Suit: " + str(self.suit) + " value: " + str(self.value)

class deck:
    def __init__(self):
        self.x=[]
        self.load()
        random.shuffle(self.x)

    def load(self):
        for i in range(1, 5):
            for j in range(2, 14):
                self.x.append(card(i, j))

    def deal(self):
        return self.x.pop()

p = deck()
class hand:
    def __init__(self):
        self.x=[]
        self.hand_count=0
        while len(self.x) != 13:
            self.x.append(p.deal())

    def accept(self, a):
        self.x.append(a)
        self.hand_count= self.hand_count + 1

    def play(self):
        self.hand_count = self.hand_count - 1
        return self.x.pop()

    def handPrinter(self):
        while len(self.x) != 0:
            result = (self.pop())
            print("{0}  {1}".format(result.suit, result.value))
</code>```

答:
When you do

```<code>result = (self.pop())
</code>```

in the handPrinter method maybe you meant to do

```<code>result = (self.x.pop())
</code>```

That was causing an error when executing your code. Also, in the __init__ method of Card class you should ident self.suit = suit and self.value = value.

Other than that, by adding

```<code>h = hand()
h.handPrinter()
</code>```

at the end, everything seems to be working fine to me.

Body:
I was given a project in computer science, however I can't figure out how to get 13 cards into my hand. There is a memory error in the hand class, but I can't figure out why, it isn't putting 13 cards in each hand. Here is my code so far:

#Keshav Ramesh
#Project 8

import random

class card:
    def __init__(self, suit, value):
        self.suit=suit
        self.value=value

    #methods
    def printer(self):
        print("{0}  {1}".format(self.suit, self.value))

    def __lt__(self, other):
        if(self.value == other.value):
            return self.suit < other.suit
        elif (self.value != other.value):
            return self.value < other.value
    def __gt__(self, other):
        return not(self<other)

    def __str__(self):
        return "Suit: " + str(self.suit) + " value: " + str(self.value)

class deck:
    def __init__(self):
        self.x=[]
        self.load()
        random.shuffle(self.x)

    def load(self):
        for i in range(1, 5):
            for j in range(2, 14):
                self.x.append(card(i, j))

    def deal(self):
        return self.x.pop()

p = deck()
class hand:
    def __init__(self):
        self.x=[]
        self.hand_count=0
        while len(self.x) != 13:
            self.x.append(p.deal())

    def accept(self, a):
        self.x.append(a)
        self.hand_count= self.hand_count + 1

    def play(self):
        self.hand_count = self.hand_count - 1
        return self.x.pop()

    def handPrinter(self):
        while len(self.x) != 0:
            result = (self.pop())
            print("{0}  {1}".format(result.suit, result.value))

Body:
When you do

result = (self.pop())

in the handPrinter method maybe you meant to do

result = (self.x.pop())

That was causing an error when executing your code. Also, in the __init__ method of Card class you should ident self.suit = suit and self.value = value.

Other than that, by adding

h = hand()
h.handPrinter()

at the end, everything seems to be working fine to me.


问:
Regex-How to prevent repeated special characters?
I don't have an experience on Regular Expressions. I need to a regular expression which doesn't allow to repeat of special characters (+-*/& etc.)
The string can contain digits, alphanumerics, and special characters.

This should be valid : abc,df

This should be invalid : abc-,df

i will be really appreciated if you can help me ! Thanks for advance.

答:
[\,\+\-\*\/\&]{2,} Add more characters in the square bracket if you want.

Demo https://regex101.com/r/CBrldL/2


问:
Getting a List from another class
I've been trying to figure out how to make a List from classA accessible for ClassB
I've tried creating an instance/object of the list but it always returns empty when I get the size of the list (while in the main class its not empty).

Example:

ClassA:

```<code>List<String> players = new ArrayList<String>();
</code>```

If i used players.size() here it would return 2 for example

in ClassB I tried the following:

```<code> ClassA classA = new ClassA();
 List<String> newList = classA.players;
</code>```

newList.size() will always return 0 no matter what.

I've also tried using a getter but that doesn't seem to make a difference.

Example:

ClassA:

```<code>List<String> players = new ArrayList<String>();
public List<String> getList(){
    return this.players;
}
</code>```

ClassB:

```<code>ClassA.getList().size()
</code>```

This will also always return 0

How would I properly do this? I tried using a static and that seemed to work but i've been told:

"Static is not the right tool for the job. It's a memory management
  tool, not an access modifier."

He told me:

Instead of static and instead of creating new instances, you can pass
  instances to other classes by adding them as parameters to the
  constructor

However I don't really get what he means. If someone could explain this with an example that would be amazing. Thanks in advance!

Edit: Since a lot of you don't quite get where i want to go with this i'll post my source:
refered to as ClassA in the example

```<code>public class TeamManager {

String prefix = new Messages().prefix;
List<String> players = new ArrayList<String>();
List<String> human = new ArrayList<String>();
List<String> infected = new ArrayList<String>();

void join(Player p){
    if(!players.contains(p.getName())){
        players.add(p.getName());
        teleportToLobby(p);
        for (String temp : players) {
            Bukkit.getPlayer(temp).sendMessage("§e§l"+p.getName()+ " has joined infection. §7("+players.size()+"/16)");
        }
    }else{
        p.sendMessage(prefix + "§cFailed. You are already in the game!");
    }
}
void leave(Player p){
    if(players.contains(p.getName())){
        p.teleport(Bukkit.getWorlds().get(0).getSpawnLocation());
        players.remove(p.getName());
        for (String temp : players) {
            Bukkit.getPlayer(temp).sendMessage("§7§l"+p.getName()+ " has left infection. §7("+players.size()+"/16)");
        }
    }else{
        p.sendMessage(prefix + "§cYou are not in a game!");
    }
}
void addToHumans(String playername){
    human.add(playername);
}
void removeFromHumans(String playername){
    human.remove(playername);
}
void addToInfected(String playername){
    infected.add(playername);
}
void removeFromInfected(String playername){
    infected.remove(playername);
}

void teleportToLobby(Player p){
    Location lobby = getLocFromConfig("lobby");
    if(lobby != null){
        p.teleport(lobby);
        p.sendMessage(prefix + "§aSuccessfully added to game!");
    }else{
        p.sendMessage(prefix + "§cLobby not set! Make sure to set a lobby using /infection setlobby");
    }
}
void startGame(){
    /*if(human.size() >= 4){
    }*/
    for (String temp : players) {
        Bukkit.getPlayer(temp).sendMessage("Game will start shortly!");
    }
}
Location getLocFromConfig(String locationName){
    if(Main.plugin.getConfig().get("lobby") != null){
        double x = Main.plugin.getConfig().getInt(locationName+".x");
        double y = Main.plugin.getConfig().getInt(locationName+".y");
        double z = Main.plugin.getConfig().getInt(locationName+".z");
        World world = Main.plugin.getServer().getWorld(Main.plugin.getConfig().getString(locationName+".world"));
        Location l = new Location(world, x, y, z);
        return l;
    }else{
        Bukkit.getLogger().warning("[Infection] Lobby has not been set!");
        return null;
    }
}
int getPlayersInLobby(){
    return players.size();
}

public List<String> getPlayers(){
    List<String> players = this.players;
    return players;
}
public List<String> getHumans(){
    return human;
}
public List<String> getInfected(){
    return infected;
}
</code>```

}

Events class (referred to in the example as ClassB)

```<code>public class Events implements Listener{

TeamManager teamman = new TeamManager();
List<String> players = teamman.getPlayers();
List<String> humans = teamman.getHumans();
List<String> infected = teamman.getInfected();
@EventHandler
public void onPlayerJoin(PlayerJoinEvent e){
    //Player p = (Player) e.getPlayer();
    //e.setJoinMessage("["+lvl+"]" + e.getPlayer().getName() +"has joined the game!");
    //p.setDisplayName("[lvl1]"+p.getName());

}
@EventHandler
public void onPlayerDamage(EntityDamageByEntityEvent  e){
    if(e.getEntity() instanceof Player){
        Player p = (Player) e.getEntity();
        Bukkit.getServer().broadcastMessage("Players: "+ players);
        if(players.contains(p.getName())){
            if((p.getHealth() - p.getLastDamage()) < 1){
                for (String temp : players) {
                    Bukkit.getPlayer(temp).sendMessage("§c"+p.getName()+" got infected by "+p.getKiller().getName()+"!");
                }
                e.setCancelled(true);
                 p.setHealth(20);
                 teamman.addToInfected(p.getName());
                 teamman.removeFromHumans(p.getName());
                 p.sendMessage("§cYou have been infected!!");
            }
        }
    }
}
</code>```

}

As said above i want to be able to access the lists from TeamManager and use them in Events. And as explained players is empty in the Events class. I hope this helps.

答:
i think your problem is that you are not thinking about the objects independently. Only when you initialize the instance of class A inside class B can that instance be mutated.

You can then pass the object around from class B to where ever you would like, but you cant initialize class A from class a then directly use it in class B unless you pass it to class B

Title: Getting a List from another class

Body:
I've been trying to figure out how to make a List from classA accessible for ClassB
I've tried creating an instance/object of the list but it always returns empty when I get the size of the list (while in the main class its not empty).

Example:

ClassA:

List<String> players = new ArrayList<String>();

If i used players.size() here it would return 2 for example

in ClassB I tried the following:

 ClassA classA = new ClassA();
 List<String> newList = classA.players;

newList.size() will always return 0 no matter what.

I've also tried using a getter but that doesn't seem to make a difference.

Example:

ClassA:

List<String> players = new ArrayList<String>();
public List<String> getList(){
    return this.players;
}

ClassB:

ClassA.getList().size()

This will also always return 0

How would I properly do this? I tried using a static and that seemed to work but i've been told:

"Static is not the right tool for the job. It's a memory management
  tool, not an access modifier."

He told me:

Instead of static and instead of creating new instances, you can pass
  instances to other classes by adding them as parameters to the
  constructor

However I don't really get what he means. If someone could explain this with an example that would be amazing. Thanks in advance!

Edit: Since a lot of you don't quite get where i want to go with this i'll post my source:
refered to as ClassA in the example

public class TeamManager {

String prefix = new Messages().prefix;
List<String> players = new ArrayList<String>();
List<String> human = new ArrayList<String>();
List<String> infected = new ArrayList<String>();

void join(Player p){
    if(!players.contains(p.getName())){
        players.add(p.getName());
        teleportToLobby(p);
        for (String temp : players) {
            Bukkit.getPlayer(temp).sendMessage("§e§l"+p.getName()+ " has joined infection. §7("+players.size()+"/16)");
        }
    }else{
        p.sendMessage(prefix + "§cFailed. You are already in the game!");
    }
}
void leave(Player p){
    if(players.contains(p.getName())){
        p.teleport(Bukkit.getWorlds().get(0).getSpawnLocation());
        players.remove(p.getName());
        for (String temp : players) {
            Bukkit.getPlayer(temp).sendMessage("§7§l"+p.getName()+ " has left infection. §7("+players.size()+"/16)");
        }
    }else{
        p.sendMessage(prefix + "§cYou are not in a game!");
    }
}
void addToHumans(String playername){
    human.add(playername);
}
void removeFromHumans(String playername){
    human.remove(playername);
}
void addToInfected(String playername){
    infected.add(playername);
}
void removeFromInfected(String playername){
    infected.remove(playername);
}

void teleportToLobby(Player p){
    Location lobby = getLocFromConfig("lobby");
    if(lobby != null){
        p.teleport(lobby);
        p.sendMessage(prefix + "§aSuccessfully added to game!");
    }else{
        p.sendMessage(prefix + "§cLobby not set! Make sure to set a lobby using /infection setlobby");
    }
}
void startGame(){
    /*if(human.size() >= 4){
    }*/
    for (String temp : players) {
        Bukkit.getPlayer(temp).sendMessage("Game will start shortly!");
    }
}
Location getLocFromConfig(String locationName){
    if(Main.plugin.getConfig().get("lobby") != null){
        double x = Main.plugin.getConfig().getInt(locationName+".x");
        double y = Main.plugin.getConfig().getInt(locationName+".y");
        double z = Main.plugin.getConfig().getInt(locationName+".z");
        World world = Main.plugin.getServer().getWorld(Main.plugin.getConfig().getString(locationName+".world"));
        Location l = new Location(world, x, y, z);
        return l;
    }else{
        Bukkit.getLogger().warning("[Infection] Lobby has not been set!");
        return null;
    }
}
int getPlayersInLobby(){
    return players.size();
}

public List<String> getPlayers(){
    List<String> players = this.players;
    return players;
}
public List<String> getHumans(){
    return human;
}
public List<String> getInfected(){
    return infected;
}

}

Events class (referred to in the example as ClassB)

public class Events implements Listener{

TeamManager teamman = new TeamManager();
List<String> players = teamman.getPlayers();
List<String> humans = teamman.getHumans();
List<String> infected = teamman.getInfected();
@EventHandler
public void onPlayerJoin(PlayerJoinEvent e){
    //Player p = (Player) e.getPlayer();
    //e.setJoinMessage("["+lvl+"]" + e.getPlayer().getName() +"has joined the game!");
    //p.setDisplayName("[lvl1]"+p.getName());

}
@EventHandler
public void onPlayerDamage(EntityDamageByEntityEvent  e){
    if(e.getEntity() instanceof Player){
        Player p = (Player) e.getEntity();
        Bukkit.getServer().broadcastMessage("Players: "+ players);
        if(players.contains(p.getName())){
            if((p.getHealth() - p.getLastDamage()) < 1){
                for (String temp : players) {
                    Bukkit.getPlayer(temp).sendMessage("§c"+p.getName()+" got infected by "+p.getKiller().getName()+"!");
                }
                e.setCancelled(true);
                 p.setHealth(20);
                 teamman.addToInfected(p.getName());
                 teamman.removeFromHumans(p.getName());
                 p.sendMessage("§cYou have been infected!!");
            }
        }
    }
}

}

As said above i want to be able to access the lists from TeamManager and use them in Events. And as explained players is empty in the Events class. I hope this helps.


问:
Content Type Not Updated docx,xlsx,pptx in SharePoint
SharePoint library items has document has (.docx, .xlsx, .pptx) extension and item associated with custom content type(Blank word document, Document). When user tries to change custom content type to OOTB content type(Document). It’s not updating even there is no error.

Steps to Reproduce:
1.Create a custom content type that parent as "Document".
2.Associate the content type into the document library and add "content types" to All documents view.
3.When library items has document has (.docx,.xlsx,.pptx) extension and item associated with  custom content type.
4.Now try to change custom content type to OOTB "Document" content type and vice-versa.
5.It’s not updating even there is  no error.

Please help on this i faced this issue only in (.docx,.xlsx,.pptx) extensions.

Thanks,
Rajendhiran M

答: Which SharePoint version are you using? May be you can monitor/check SPLogs while updating the content type.


问:
can not able to change ip address with domain name
I want to replace my ip address with my already bought domain name. How can I do so?

As I'm using amazon EC2 Instance. I changed record of my ROUTE S2 to point to my ip. When I open my website, it's opening but when I click on any menu, domain name changed to IP again.

I tried changing my wordpress index.php file. I changes IP address with my domain name. It's not solving the issue..

Any Solution Friends?

答:
Yash,

You must access the domain's panel and look at change DNS things (you will need to know your nameservers for this ~~ contact your hosting provider). Or you can simply try to edit the DNS records, in specifically the A one, pointing to your hosting IP address.

If you have any doubt else, please let me know.


答:
The API does not list hidden as a valid property for each object in the columns config. http://dev.sencha.com/deploy/dev/docs/?class=Ext.list.ListView

From what I see, ListView doesn't support hiding columns. You may need to use a GridPanel.

Like The Scrum Meister said. If you don't need it displayed ever, it shouldn't be listed as a column.

Title: Ext Js Listview columns are not hiding or widening properly


问:
Oracle Debugging won't work SQL developer 4.2.0.17
I have debugging privs and compiled my packages and package bodies for debug. When I try to launch the debugger, I get the following.  </p>

```<code>Executing PL/SQL: ALTER SESSION SET PLSQL_DEBUG=TRUE
Executing PL/SQL: CALL DBMS_DEBUG_JDWP.CONNECT_TCP( 'XX.XX.XX.XXX', 'YYYYY' )
ORA-30683: failure establishing connection to debugger
ORA-12535: TNS:operation timed out
ORA-06512: at "SYS.DBMS_DEBUG_JDWP", line 68
ORA-06512: at line 1
Process exited.
Disconnecting from the database ZZZ
</code>```

<p>I tried setting DatabaseDebuggerDisableJDWP=true in my ide.properites file (all of them), and it didn't help.  </p>

答:
Try this resolve:

Tools -> Preferences -> Debugger - set the Prompt for debugger host for database debugging.

Set your machine ip address when it prompt and i think it will be work.

Body:
I have debugging privs and compiled my packages and package bodies for debug. When I try to launch the debugger, I get the following.

Executing PL/SQL: ALTER SESSION SET PLSQL_DEBUG=TRUE
Executing PL/SQL: CALL DBMS_DEBUG_JDWP.CONNECT_TCP( 'XX.XX.XX.XXX', 'YYYYY' )
ORA-30683: failure establishing connection to debugger
ORA-12535: TNS:operation timed out
ORA-06512: at "SYS.DBMS_DEBUG_JDWP", line 68
ORA-06512: at line 1
Process exited.
Disconnecting from the database ZZZ

I tried setting DatabaseDebuggerDisableJDWP=true in my ide.properites file (all of them), and it didn't help.


问:
How to mock a downstream method call?
I have an issue where I have some code like

```<code>public void a() {
    Obj1 one = Obj1();
    Obj2 two = Obj2();
    one.b();
    two.c();
}
</code>```

I'm trying to call the a() method, and I would like the b() method to execute but I would like to mock out the c() method.

What is the best way to do this, since Obj2 two gets declared within a()?

答:
Here is a working example test, using the JMockit library (which I develop):</p>

```<code>@Test
public void exampleTest(@Mocked Obj2 anyObj2) {
    new A().a();

    // In case we want to check two.c() was called:
    new Verifications() {{ anyObj2.c(); }};
}
</code>```

Title: How to mock a downstream method call?

Body:
I have an issue where I have some code like

public void a() {
    Obj1 one = Obj1();
    Obj2 two = Obj2();
    one.b();
    two.c();
}

I'm trying to call the a() method, and I would like the b() method to execute but I would like to mock out the c() method.

What is the best way to do this, since Obj2 two gets declared within a()?

Body:
Here is a working example test, using the JMockit library (which I develop):

@Test
public void exampleTest(@Mocked Obj2 anyObj2) {
    new A().a();

    // In case we want to check two.c() was called:
    new Verifications() {{ anyObj2.c(); }};
}


问:
Is there a way to validate Sabre webservices availability
Is there a way to validate Sabre webservices availability without making any webservice method call? Something like HttpResponse check?

Edit - I wanted to validate Webservice's availability and not booking availability. To build a dashboard to monitor the webservice availability (active or down).

答:
Given how dynamic availability is, what is available one moment is not necessarily available the next. So the only way to know if an itinerary is still available, is to actually book it.

Response to updated question:
There is no specific resource for this, up time should 99% of the time, so I don't think that you would need to validate, the actual call should be enough.

More so, Sabre was recommending using persistent connections as a way to avoid even the handshake.