问:
Opacity should only affect parent but no child
I have a div which contains text on an images, and what I'm trying to achieve is to lower the opacity of the div so the images can be seen clearly.

with my current script, when I lower the opacity of the div it affects the text too.

but i want it to only affect the div only

CSS

```<code>.page1_text {
        position:absolute;
        background-color:#CC3;
        border-radius:5px 5px 5px 5px;
        padding:20px;
        width:80%;
        left:10%;
        font-size:16px;
        opacity: 0.5;
}
</code>```

HTML

```<code><div class="page1_text">
    <div>This is my test </div>
</div>
</code>```

答:
If you use opacity on the div, it will affect everything in the div

Use background colour with alpha

```<code>background-color: rgba(204, 204, 51, 0.5);
</code>```

the 0.5 at the end is the alpha(opacity), I got the values using photoshop but I am sure there are other ways to convert hex into rgb

for more info see https://css-tricks.com/rgba-browser-support/

Body:
I have a div which contains text on an images, and what I'm trying to achieve is to lower the opacity of the div so the images can be seen clearly.

with my current script, when I lower the opacity of the div it affects the text too.

but i want it to only affect the div only

CSS

.page1_text {
        position:absolute;
        background-color:#CC3;
        border-radius:5px 5px 5px 5px;
        padding:20px;
        width:80%;
        left:10%;
        font-size:16px;
        opacity: 0.5;
}

HTML

This is my test

Body:
If you use opacity on the div, it will affect everything in the div

Use background colour with alpha

background-color: rgba(204, 204, 51, 0.5);

the 0.5 at the end is the alpha(opacity), I got the values using photoshop but I am sure there are other ways to convert hex into rgb

for more info see https://css-tricks.com/rgba-browser-support/


来源: stackexchange

问:
Permission denied in firebase cloud functions
In firebase cloud function I am getting access denied on admin-firebase on read or write to realtime database.
This https://github.com/firebase/firebase-functions/issues/16 does not solve my problem , App engine default service account rights are set to Editor.

I also have Node.js admin sdk configured with service Account Key and there  everything works as expected.

I have set default security rules in db.

This is an example function

```<code>const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
admin.database.enableLogging(true);

//event fires properly
exports.sendNotif = functions.database.ref('/messages/{roomId}/{msgKey}')
    .onWrite(event => {
        const message = event.data.val().text;
    //this executes as expected
        console.log(message);

//here I am getting access denied and consequently function timeout after 60 seconds.
        return admin.database().ref('/userFCMTokens').once('value')
            .then(snap => console.log(snap.val()));
    });
</code>```

and here is log snippet from firebase  realtime db

```<code>Realtime connection established.
2017-06-08T15:19:03.168Z I sendNotif: p:0: connection ready
2017-06-08T15:19:03.168Z I sendNotif: p:0: {"r":28,"a":"gauth","b":{"cred”:”********************”}}
2017-06-08T15:19:03.169Z I sendNotif: p:0: Listen on /userFCMTokens for default
2017-06-08T15:19:03.169Z I sendNotif: p:0: {"r":29,"a":"q","b":{"p":"/userFCMTokens","h":""}}
2017-06-08T15:19:03.538Z I sendNotif: p:0: from server: {"r":28,"b":{"s":"permission_denied","d":"Access denied."}}
2017-06-08T15:19:03.538Z I sendNotif: Auth token revoked: permission_denied/Access denied.
2017-06-08T15:19:03.538Z I sendNotif: c:0:13: Closing realtime connection.
2017-06-08T15:19:03.538Z I sendNotif: c:0:13: Shutting down all connections
2017-06-08T15:19:03.538Z I sendNotif: c:0:13:0 WebSocket is being closed
</code>```

Here without logging on realtime db for brevity:

```<code>2017-06-08T15:26:23.164035495Z D sendNotif: Function execution started
2017-06-08T15:26:23.164076543Z D sendNotif: Billing account not configured. External network is not accessible and quotas are severely limited. Configure billing account to remove these restrictions
2017-06-08T15:26:23.539Z I sendNotif: message console logged
2017-06-08T15:27:23.165321703Z D sendNotif: Function execution took 60002 ms, finished with status: 'timeout'
</code>```

Why I can’t read and write using admin in cloud functions?

答: Try checking permission for “App Engine default service account” on https://console.cloud.google.com/iam-admin/iam/project, and ensure that it says “Editor”.</p>

ContentLicense: CC BY-SA 3.0

Body:
In firebase cloud function I am getting access denied on admin-firebase on read or write to realtime database.
This https://github.com/firebase/firebase-functions/issues/16 does not solve my problem , App engine default service account rights are set to Editor.

I also have Node.js admin sdk configured with service Account Key and there  everything works as expected.

I have set default security rules in db.

This is an example function

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
admin.database.enableLogging(true);

//event fires properly
exports.sendNotif = functions.database.ref('/messages/{roomId}/{msgKey}')
    .onWrite(event => {
        const message = event.data.val().text;
    //this executes as expected
        console.log(message);

//here I am getting access denied and consequently function timeout after 60 seconds.
        return admin.database().ref('/userFCMTokens').once('value')
            .then(snap => console.log(snap.val()));
    });

and here is log snippet from firebase  realtime db

Realtime connection established.
2017-06-08T15:19:03.168Z I sendNotif: p:0: connection ready
2017-06-08T15:19:03.168Z I sendNotif: p:0: {"r":28,"a":"gauth","b":{"cred”:”********************”}}
2017-06-08T15:19:03.169Z I sendNotif: p:0: Listen on /userFCMTokens for default
2017-06-08T15:19:03.169Z I sendNotif: p:0: {"r":29,"a":"q","b":{"p":"/userFCMTokens","h":""}}
2017-06-08T15:19:03.538Z I sendNotif: p:0: from server: {"r":28,"b":{"s":"permission_denied","d":"Access denied."}}
2017-06-08T15:19:03.538Z I sendNotif: Auth token revoked: permission_denied/Access denied.
2017-06-08T15:19:03.538Z I sendNotif: c:0:13: Closing realtime connection.
2017-06-08T15:19:03.538Z I sendNotif: c:0:13: Shutting down all connections
2017-06-08T15:19:03.538Z I sendNotif: c:0:13:0 WebSocket is being closed

Here without logging on realtime db for brevity:

2017-06-08T15:26:23.164035495Z D sendNotif: Function execution started
2017-06-08T15:26:23.164076543Z D sendNotif: Billing account not configured. External network is not accessible and quotas are severely limited. Configure billing account to remove these restrictions
2017-06-08T15:26:23.539Z I sendNotif: message console logged
2017-06-08T15:27:23.165321703Z D sendNotif: Function execution took 60002 ms, finished with status: 'timeout'

Why I can’t read and write using admin in cloud functions?


问:
Controlling Video with Gestures
I have a video playing a camera rotating around a 3D model. I want to be able to sweep left to right to play the video forwards and right to left to play the video backwards.

Can this be done on iOS 4 and how?

Cheers

答: Add a UISwipeGestureRecognizer to the view that holds the video, and configure it.</p>

ContentLicense: CC BY-SA 2.5

Title: Controlling Video with Gestures


问:
transforming a string into a list in python
For example, I have a string = "[1,2,3,4]" and I want to only have the [1,2,3,4], I tried doing list(mystring) but it gives me:

```<code>['[', '1', ',', '2', ',', '3', ',', '4', ']']
</code>```

I just want to chop off the "" of the string "[1,2,3,4]".

the output I want can be made with the print, it will output:

```<code>[1,2,3,4]
</code>```

but I don't know how to get that output into a variable, can someone help?

答:
Use some string functions</p>

```<code>s = "[1,2,3,4]"
s_list = [int(x) for x in s.strip('[]').split(',')]
</code>```

Body:
For example, I have a string = "[1,2,3,4]" and I want to only have the [1,2,3,4], I tried doing list(mystring) but it gives me:

['[', '1', ',', '2', ',', '3', ',', '4', ']']

I just want to chop off the "" of the string "[1,2,3,4]".

the output I want can be made with the print, it will output:

[1,2,3,4]

but I don't know how to get that output into a variable, can someone help?

Body:
Use some string functions

s = "[1,2,3,4]"
s_list = [int(x) for x in s.strip('[]').split(',')]


问:
Directing to filtered pages from Wordpress Admin Sub Menus
I want to add two additional sub-menu items to my Wordpress Admin menu. The top-level menu I want to hook into is the 'Products' menu created by WooCommerce.

```<code>edit.php?post_type=product
</code>```

The content I want the menu items to show can be accessed by filtering the products by Product Category. E.g.

```<code>http://dev3.benefacto.org/wp-admin/edit.php?s&post_type=product&product_cat=manchester
</code>```

I've come up with a working solution (below) to do this - but it is inelegant because it requires calling a function when I feel like I should be able to simply add something into the 'menu slug' variable perhaps.

Any thoughts much appreciated.

```<code>// Hook into the Admin Menu

add_action( 'admin_menu', 'lnz_wp_adminmenu_addproductpages' );

// Add Product Categories
function lnz_wp_adminmenu_addproductpages() {
add_submenu_page( 'edit.php?post_type=product', 'Manchester Charities - Page', 'Manchester Charities- Menu', 'manage_options', 'product_cat_manchester', 'lnz_wp_adminmenu_redirectmanchester' );
add_submenu_page( 'edit.php?post_type=product', 'London Charities - Page', 'London Charities- Menu', 'manage_options', 'product_cat_london', 'lnz_wp_adminmenu_redirectlondon' );
}

// Create Redirects for relevant links
function lnz_wp_adminmenu_redirectmanchester() {
   header('Location: http://dev3.benefacto.org/wp-admin/edit.php?s&post_type=product&product_cat=manchester');
   exit();
}

function lnz_wp_adminmenu_redirectlondon() {
   header('Location: http://dev3.benefacto.org/wp-admin/edit.php?s&post_type=product&product_cat=london');
   exit();
}
</code>```

答:
As far as I know, there's no direct way to achieve this using WP hooks or modifying something like global $submenu...

It can be done with jQuery modifying the href attribute of the submenu items:

```<code>add_action( 'admin_menu', function() {
    add_submenu_page( 'edit.php?post_type=product', 'Manchester', 'Manchester', 'manage_options', 'cat_manchester', '__return_null' );
    add_submenu_page( 'edit.php?post_type=product', 'London', 'London', 'manage_options', 'cat_london', '__return_null' );
});

add_action('admin_footer', function(){
    ?>
    <script>
        jQuery(document).ready( function($) {
            var admin_url = 'http://dev3.benefacto.org/wp-admin/edit.php';
            $('#menu-posts-product').find('a[href*="cat_manchester"]').attr('href',admin_url+'?s&post_type=product&product_cat=manchester');
            $('#menu-posts-product').find('a[href*="cat_london"]').attr('href',admin_url+'?s&post_type=product&product_cat=london');
        });
    </script>
    <?php
});
</code>```

Body:
I want to add two additional sub-menu items to my Wordpress Admin menu. The top-level menu I want to hook into is the 'Products' menu created by WooCommerce.

edit.php?post_type=product

The content I want the menu items to show can be accessed by filtering the products by Product Category. E.g.

http://dev3.benefacto.org/wp-admin/edit.php?s&post_type=product&product_cat=manchester

I've come up with a working solution (below) to do this - but it is inelegant because it requires calling a function when I feel like I should be able to simply add something into the 'menu slug' variable perhaps.

Any thoughts much appreciated.

// Hook into the Admin Menu

add_action( 'admin_menu', 'lnz_wp_adminmenu_addproductpages' );

// Add Product Categories
function lnz_wp_adminmenu_addproductpages() {
add_submenu_page( 'edit.php?post_type=product', 'Manchester Charities - Page', 'Manchester Charities- Menu', 'manage_options', 'product_cat_manchester', 'lnz_wp_adminmenu_redirectmanchester' );
add_submenu_page( 'edit.php?post_type=product', 'London Charities - Page', 'London Charities- Menu', 'manage_options', 'product_cat_london', 'lnz_wp_adminmenu_redirectlondon' );
}

// Create Redirects for relevant links
function lnz_wp_adminmenu_redirectmanchester() {
   header('Location: http://dev3.benefacto.org/wp-admin/edit.php?s&post_type=product&product_cat=manchester');
   exit();
}

function lnz_wp_adminmenu_redirectlondon() {
   header('Location: http://dev3.benefacto.org/wp-admin/edit.php?s&post_type=product&product_cat=london');
   exit();
}

Body:
As far as I know, there's no direct way to achieve this using WP hooks or modifying something like global $submenu...

It can be done with jQuery modifying the href attribute of the submenu items:

add_action( 'admin_menu', function() {
    add_submenu_page( 'edit.php?post_type=product', 'Manchester', 'Manchester', 'manage_options', 'cat_manchester', '__return_null' );
    add_submenu_page( 'edit.php?post_type=product', 'London', 'London', 'manage_options', 'cat_london', '__return_null' );
});

add_action('admin_footer', function(){
    ?>
    <script>
        jQuery(document).ready( function($) {
            var admin_url = 'http://dev3.benefacto.org/wp-admin/edit.php';
            $('#menu-posts-product').find('a[href*="cat_manchester"]').attr('href',admin_url+'?s&post_type=product&product_cat=manchester');
            $('#menu-posts-product').find('a[href*="cat_london"]').attr('href',admin_url+'?s&post_type=product&product_cat=london');
        });
    </script>
    <?php
});


问:
php DOMXpath, help getting node value
I have this XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<cfdi:Comprobante >
<cfdi:Conceptos>
<cfdi:Concepto cantidad="1.00" unidad="PZA" noIdentificacion="RRGARACION" descripcion="51571 CADENA ORO AMRILLO 45CMTS FAVOR DE SOLDAR EL ESLABON DE LADO DEL BROCHE" valorUnitario="81.90" importe="81.90" />
<cfdi:Concepto cantidad="1.00" unidad="PZA" noIdentificacion="RRGARACION" descripcion="51570 CADENA ORO BLANCO C/CORAZON FAVOR DE SOLDAR A 16 CMTS DEL BROCHE" valorUnitario="206.90" importe="206.90" />
<cfdi:/Conceptos>
<cfdi:Impuestos>
<cfdi:Traslados>
<cfdi:Traslado impuesto="IVA" tasa="16" importe="46.20" />
</cfdi:Traslados>
</cfdi:Impuestos>
</cfdi:Comprobante>
</code>```

and I need to get the "46.20" value of Traslado / importe. how can I do it? I tried something like this:

```<code>$xp = new DOMXpath($xml);
$data['IVA']= getpath("//@Traslados[@impuesto='IVA']/@importe");
</code>```

but didn't work.

答:
So for starters, you're working with invalid XML. It should look something like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<cfdi:Comprobante xmlns:cfdi="https://some/uri">
    <cfdi:Conceptos>
        <cfdi:Concepto cantidad="1.00" unidad="PZA" noIdentificacion="RRGARACION" descripcion="51571 CADENA ORO AMRILLO 45CMTS FAVOR DE SOLDAR EL ESLABON DE LADO DEL BROCHE" valorUnitario="81.90" importe="81.90" />
        <cfdi:Concepto cantidad="1.00" unidad="PZA" noIdentificacion="RRGARACION" descripcion="51570 CADENA ORO BLANCO C/CORAZON FAVOR DE SOLDAR A 16 CMTS DEL BROCHE" valorUnitario="206.90" importe="206.90" />
    </cfdi:Conceptos>
    <cfdi:Impuestos>
        <cfdi:Traslados>
            <cfdi:Traslado impuesto="IVA" tasa="16" importe="46.20" />
        </cfdi:Traslados>
    </cfdi:Impuestos>
</cfdi:Comprobante>
</code>```

(Note the xmlns attribute and the correct closing slashes.)

Next, you're calling a function getpath which came from where? I don't know. But you're passing it an invalid XPath query. You're looking for the attribute of the Traslados element when you want the Traslado element instead. Try this out:

```<code>$xml = <<< XML
<?xml version="1.0" encoding="utf-8"?>
<cfdi:Comprobante xmlns:cfdi="https://some/uri">
    <cfdi:Conceptos>
        <cfdi:Concepto cantidad="1.00" unidad="PZA" noIdentificacion="RRGARACION" descripcion="51571 CADENA ORO AMRILLO 45CMTS FAVOR DE SOLDAR EL ESLABON DE LADO DEL BROCHE" valorUnitario="81.90" importe="81.90" />
        <cfdi:Concepto cantidad="1.00" unidad="PZA" noIdentificacion="RRGARACION" descripcion="51570 CADENA ORO BLANCO C/CORAZON FAVOR DE SOLDAR A 16 CMTS DEL BROCHE" valorUnitario="206.90" importe="206.90" />
    </cfdi:Conceptos>
    <cfdi:Impuestos>
        <cfdi:Traslados>
            <cfdi:Traslado impuesto="IVA" tasa="16" importe="46.20" />
        </cfdi:Traslados>
    </cfdi:Impuestos>
</cfdi:Comprobante>
XML;

$doc = new DomDocument();
$doc->loadXML($xml);
$xp = new DOMXpath($doc);
$xp->registerNamespace("cfdi", "https://some/uri");
$nodes = $xp->query("//cfdi:Traslados/*[@impuesto='IVA']/@importe");
foreach ($nodes as $node) {
    var_dump($node->nodeValue);
}
</code>```

Title: php DOMXpath, help getting node value

Body:
I have this XML:

<?xml version="1.0" encoding="utf-8"?>
<cfdi:Comprobante >
<cfdi:Conceptos>
<cfdi:Concepto cantidad="1.00" unidad="PZA" noIdentificacion="RRGARACION" descripcion="51571 CADENA ORO AMRILLO 45CMTS FAVOR DE SOLDAR EL ESLABON DE LADO DEL BROCHE" valorUnitario="81.90" importe="81.90" />
<cfdi:Concepto cantidad="1.00" unidad="PZA" noIdentificacion="RRGARACION" descripcion="51570 CADENA ORO BLANCO C/CORAZON FAVOR DE SOLDAR A 16 CMTS DEL BROCHE" valorUnitario="206.90" importe="206.90" />
<cfdi:/Conceptos>
<cfdi:Impuestos>
<cfdi:Traslados>
<cfdi:Traslado impuesto="IVA" tasa="16" importe="46.20" />
</cfdi:Traslados>
</cfdi:Impuestos>
</cfdi:Comprobante>

and I need to get the "46.20" value of Traslado / importe. how can I do it? I tried something like this:

$xp = new DOMXpath($xml);
$data['IVA']= getpath("//@Traslados[@impuesto='IVA']/@importe");

but didn't work.

Body:
So for starters, you're working with invalid XML. It should look something like this:

<?xml version="1.0" encoding="utf-8"?>
<cfdi:Comprobante xmlns:cfdi="https://some/uri">
    <cfdi:Conceptos>
        <cfdi:Concepto cantidad="1.00" unidad="PZA" noIdentificacion="RRGARACION" descripcion="51571 CADENA ORO AMRILLO 45CMTS FAVOR DE SOLDAR EL ESLABON DE LADO DEL BROCHE" valorUnitario="81.90" importe="81.90" />
        <cfdi:Concepto cantidad="1.00" unidad="PZA" noIdentificacion="RRGARACION" descripcion="51570 CADENA ORO BLANCO C/CORAZON FAVOR DE SOLDAR A 16 CMTS DEL BROCHE" valorUnitario="206.90" importe="206.90" />
    </cfdi:Conceptos>
    <cfdi:Impuestos>
        <cfdi:Traslados>
            <cfdi:Traslado impuesto="IVA" tasa="16" importe="46.20" />
        </cfdi:Traslados>
    </cfdi:Impuestos>
</cfdi:Comprobante>

(Note the xmlns attribute and the correct closing slashes.)

Next, you're calling a function getpath which came from where? I don't know. But you're passing it an invalid XPath query. You're looking for the attribute of the Traslados element when you want the Traslado element instead. Try this out:

$xml = <<< XML
<?xml version="1.0" encoding="utf-8"?>
<cfdi:Comprobante xmlns:cfdi="https://some/uri">
    <cfdi:Conceptos>
        <cfdi:Concepto cantidad="1.00" unidad="PZA" noIdentificacion="RRGARACION" descripcion="51571 CADENA ORO AMRILLO 45CMTS FAVOR DE SOLDAR EL ESLABON DE LADO DEL BROCHE" valorUnitario="81.90" importe="81.90" />
        <cfdi:Concepto cantidad="1.00" unidad="PZA" noIdentificacion="RRGARACION" descripcion="51570 CADENA ORO BLANCO C/CORAZON FAVOR DE SOLDAR A 16 CMTS DEL BROCHE" valorUnitario="206.90" importe="206.90" />
    </cfdi:Conceptos>
    <cfdi:Impuestos>
        <cfdi:Traslados>
            <cfdi:Traslado impuesto="IVA" tasa="16" importe="46.20" />
        </cfdi:Traslados>
    </cfdi:Impuestos>
</cfdi:Comprobante>
XML;

$doc = new DomDocument();
$doc->loadXML($xml);
$xp = new DOMXpath($doc);
$xp->registerNamespace("cfdi", "https://some/uri");
$nodes = $xp->query("//cfdi:Traslados/*[@impuesto='IVA']/@importe");
foreach ($nodes as $node) {
    var_dump($node->nodeValue);
}


问:
Mongo - update a field with result of another field when a document is updated
I'm working with mongoose to manage my mongoDB collections.
I have one collection that contains two numeric fields. I want to set another field with the result of dividing these two fields every time that one of them is updated.

Let's sat this is my mongo collection:

```<code>{
  id: 1,
  num1: 100,
  num2: 50,
  result: 2
},
{
  id: 2,
  num1: 200,
  num2: 10,
  result: 20
},
{
  id: 1,
  num1: 40,
  num2: 5,
  result: 8
}
</code>```

Now, the item with id 2 is updated, and num1 is set to 50. I want to recalculate and set result field with the new correct value (10).

(for updating items, I use the bulk.find().upsert().updateOne() funciton).

How can I do it with the less performance impact?

答:
You can use a pre-save hook to do the calculation:

```<code>schema.pre('save', function(next) {
    this.result = this.num1 / this.num2;
    next();
});
</code>```

...where 'schema' is your Mongoose schema.

Then when you update num1 or num2, the result will be calculated and saved.

Body:
I'm working with mongoose to manage my mongoDB collections.
I have one collection that contains two numeric fields. I want to set another field with the result of dividing these two fields every time that one of them is updated.

Let's sat this is my mongo collection:

{
  id: 1,
  num1: 100,
  num2: 50,
  result: 2
},
{
  id: 2,
  num1: 200,
  num2: 10,
  result: 20
},
{
  id: 1,
  num1: 40,
  num2: 5,
  result: 8
}

Now, the item with id 2 is updated, and num1 is set to 50. I want to recalculate and set result field with the new correct value (10).

(for updating items, I use the bulk.find().upsert().updateOne() funciton).

How can I do it with the less performance impact?

Body:
You can use a pre-save hook to do the calculation:

schema.pre('save', function(next) {
    this.result = this.num1 / this.num2;
    next();
});

...where 'schema' is your Mongoose schema.

Then when you update num1 or num2, the result will be calculated and saved.


问:
Angular refreshing page with a button
What I want to do is have a button that does the same thing as the refresh button in chrome does.  I have tried location.reload(), and it doesn't seem to really do anything.  Is there any way to do this?</p>

```<code>exit() {
    location.reload();
  }

 <button [routerLink]="['/dashboard']" (click)="exit()">Exit</button>
</code>```

答: Try this: window.location.reload();

Title: Angular refreshing page with a button

Body:
What I want to do is have a button that does the same thing as the refresh button in chrome does.  I have tried location.reload(), and it doesn't seem to really do anything.  Is there any way to do this?

exit() {
    location.reload();
  }

 <button [routerLink]="['/dashboard']" (click)="exit()">Exit</button>

Body: Try this: window.location.reload();


问:
How to open a sliding panel when a grid row is selected
I want to slide open a panel on the right of the grid when I select a grid row. I want to show some details regarding the clicked row in this panel. This is somewhat like what the row expander plugin does, but I want the panel to open on the right side and take the height of the grid.

Is there already a plugin which achieves this? If not, what components can I use to get this done? I am not requesting the code, but would appreciate any pointers.

答:
You don't need a plugin for that.

All plugins somehow modify the rows which are displayed (insert a row body, insert summary rows, insert groupers etc. etc.), which you clearly don't want.

Since you want the slide-in panel to take up the full height of the grid, you could just add a form to the dockedItems of the grid, and set the dock:'right' configuration on the form. You would set hidden:true for a start, and in the selectionchange listener of the grid you would show the form and use loadRecord(selection[0]) to load the record into it. (Or you could use a container and some bindings instead of a form).


问:
How do I get my stored procedure to work?
I'm using MySQL to create a stored procedure that will do a search with varied search filters. I have been reading multiple things on how to get this task done, and while it seems to work for every single person that has used their stored procedure, I cannot figure out why it doesn't work when I do it. Here is what I am trying to do:

```<code>Create Procedure spSearchInventory
@SKU int(25),
@ItemName varchar(40),
@RetailPrice decimal(7,2),
@WholesalePrice decimal(7,2),
@DateOfPurchase date,
@DateOfPost date
As
Begin

    SELECT * FROM inventory WHERE
    (SKU = @SKU OR @SKU IS NULL) AND
    (ItemName = @ItemName OR @ItemName IS NULL) AND
    (RetailPrice = @RetailPrice OR @RetailPrice IS NULL) AND
    (WholesalePrice = @WholesalePrice OR @WholesalePrice IS NULL) AND
    (DateOfPurchase = @DateOfPurchase OR @DateOfPurchase IS NULL) AND
    (DateOfPost = @DateOfPost OR @DateOfPost IS NULL)
END
</code>```

The error it gives me is right at the top  "@SKU int (25)". The error it reads is, "Syntax Error: '@SKU' (at text suffix) is not a valid input at this position. I am new to SQL, so this may be a simple issue, however, this is the exact same stored procedure that others have used, and gotten success from, so I'm not sure why it won't work when I try to do it.

答:
Brandon,
you are using SQL Server syntax in your procedure. To use MySQL syntax:</p>

```<code>create procedure spSearchInventory (
in_SKU int,
in_ItemName varchar(40),
in_RetailPrice decimal(7,2),
in_WholesalePrice decimal(7,2),
in_DateOfPurchase date,
in_DateOfPost date
)
begin

SELECT *
FROM inventory
WHERE
    (SKU = in_SKU OR in_SKU IS NULL) AND
    (ItemName = in_ItemName OR in_ItemName IS NULL) AND
    (RetailPrice = in_RetailPrice OR in_RetailPrice IS NULL) AND
    (WholesalePrice = in_WholesalePrice OR in_WholesalePrice IS NULL) AND
    (DateOfPurchase = in_DateOfPurchase OR in_DateOfPurchase IS NULL) AND
    (DateOfPost = in_DateOfPost OR in_DateOfPost IS NULL);

END
</code>```

Body:
I'm using MySQL to create a stored procedure that will do a search with varied search filters. I have been reading multiple things on how to get this task done, and while it seems to work for every single person that has used their stored procedure, I cannot figure out why it doesn't work when I do it. Here is what I am trying to do:

Create Procedure spSearchInventory
@SKU int(25),
@ItemName varchar(40),
@RetailPrice decimal(7,2),
@WholesalePrice decimal(7,2),
@DateOfPurchase date,
@DateOfPost date
As
Begin

    SELECT * FROM inventory WHERE
    (SKU = @SKU OR @SKU IS NULL) AND
    (ItemName = @ItemName OR @ItemName IS NULL) AND
    (RetailPrice = @RetailPrice OR @RetailPrice IS NULL) AND
    (WholesalePrice = @WholesalePrice OR @WholesalePrice IS NULL) AND
    (DateOfPurchase = @DateOfPurchase OR @DateOfPurchase IS NULL) AND
    (DateOfPost = @DateOfPost OR @DateOfPost IS NULL)
END

The error it gives me is right at the top  "@SKU int (25)". The error it reads is, "Syntax Error: '@SKU' (at text suffix) is not a valid input at this position. I am new to SQL, so this may be a simple issue, however, this is the exact same stored procedure that others have used, and gotten success from, so I'm not sure why it won't work when I try to do it.

Body:
Brandon,
you are using SQL Server syntax in your procedure. To use MySQL syntax:

create procedure spSearchInventory (
in_SKU int,
in_ItemName varchar(40),
in_RetailPrice decimal(7,2),
in_WholesalePrice decimal(7,2),
in_DateOfPurchase date,
in_DateOfPost date
)
begin

SELECT *
FROM inventory
WHERE
    (SKU = in_SKU OR in_SKU IS NULL) AND
    (ItemName = in_ItemName OR in_ItemName IS NULL) AND
    (RetailPrice = in_RetailPrice OR in_RetailPrice IS NULL) AND
    (WholesalePrice = in_WholesalePrice OR in_WholesalePrice IS NULL) AND
    (DateOfPurchase = in_DateOfPurchase OR in_DateOfPurchase IS NULL) AND
    (DateOfPost = in_DateOfPost OR in_DateOfPost IS NULL);

END


问:
Continously Reading from Multiple TCP Connections on CF
I have a simple TCP server that is able to listen for and accept multiple connections on a port. It then continuously waits for data to read from its connections. It uses a wrapper class for a TcpClient called ConnectedClient for convenience, and a list (dictionary) of ConnectedClients to keep track of all the connections. It basically goes like this:

```<code>/* this method waits to accept connections indefinitely until it receives
   the signal from the GUI thread to stop. When a connection is accepted, it
   adds the connection to the list and calls a method called ProcessClient,
   which returns almost immediately.*/
public void waitForConnections() {
        // this method has access to a TcpListener called listener that was started elsewhere
        try {
            while (!_abort) {
                TcpClient socketClient = listener.AcceptTcpClient();

                //Connected client constructor takes the TcpClient as well as a callback that it uses to print status messages to the GUI if
                ConnectedClient client = new ConnectedClient(socketClient, onClientUpdate);
                clients.Add(client.id, client);
                ProcessClient(client);
            }
        }
        catch (Exception e) {
            onStatusUpdate("Exception Occurred: " + e.Message);
        }
    }

    /* This method doesn't do much other than call BeginRead on the connection */
    private void ProcessClient(ConnectedClient client) {
        try {
            // wrapper class contains an internal buffer for extracting data as well as a TcpClient
            NetworkStream stream = client.tcpClient.GetStream();
            stream.BeginRead(client.buffer, 0, client.tcpClient.ReceiveBufferSize, new AsyncCallback(StreamReadCompleteCallback), client);
        }
        catch (Exception ex) {
            onStatusUpdate(ex.Message);
        }
    }
</code>```

In my callback function, StreamReadCompleteCallback, I call EndRead, checking the return value of EndRead to detect whether the connection has been closed. If the return value is greater than zero, I extract/process the read data and call BeginRead again on the same client. If the return value is zero, the connection has been closed and I remove the connection (delete from list, close the TcpClient, etc).

```<code>    private void StreamReadCompleteCallback(IAsyncResult ar) {
        ConnectedClient client = (ConnectedClient)ar.AsyncState;

        try {
            NetworkStream stream = client.tcpClient.GetStream();

            int read = stream.EndRead(ar);
            if (read != 0) {
                // data extraction/light processing of received data
                client.Append(read);
                stream.BeginRead(client.buffer, 0, client.tcpClient.ReceiveBufferSize, new AsyncCallback(StreamReadCompleteCallback), client);
            }
            else {
                DisconnectClient(client);
            }
        }
        catch (Exception ex) {
            onStatusUpdate(ex.Message);
        }
    }
</code>```

All of this works fine, I can accept connections and read from multiple client devices, etc.

My question is: This method of continuously reading from connected clients causes each connection to have a worker thread that is waiting for BeginRead to return.

So if I have 10 connections, I have 10 BeginReads going.

It seems wasteful to have so many worker threads sitting around waiting to read. Is there some other, better way to accomplish this? I eventually run out of memory to add connections if I have a high number of active connections.

Would having a thread that polls the DataAvailable property of each connection until something shows up, and then makes a thread to read/process be a solution?

Or is creating all these worker threads not as big of a deal as I think?

答:
This method of continuously reading from connected clients causes each connection to have a worker thread that is waiting for BeginRead to return

No, it doesn't. In fact, using BeginRead() or one of the other asynchronous alternatives to processing I/O on a Socket object is the most scalable approach to use.

Would having a thread that polls the DataAvailable property of each connection until something shows up, and then makes a thread to read/process be a solution?

No. This would be horrible. Polling a socket, via DataAvailable or Select(), is terribly inefficient, forcing a huge amount of CPU time to be invested just checking on the socket state. The OS provides good asynchronous mechanisms for handling this; a polling implementation ignores that and does all the work itself.

Or is creating all these worker threads not as big of a deal as I think?

You aren't creating the threads you think you are. When you use the asynchronous APIs, they make use of a feature in windows called I/O Completion Ports. An I/O Completion Port is associated with an I/O operation, and a thread can wait on a port. But one thread can handle waiting on a large number of operations, so having ten outstanding read operations does not in fact cause ten different threads to be created.

.NET manages a pool of threads to handle these operations, managed as part of the ThreadPool class. You can monitor that class to see the behavior of the IOCP pool (which is different from the worker thread pool used for QueueUserWorkItem()).

.NET will assign new IOCP objects and threads as needed to service your network I/O operations. You can rest assured that it will do so in a reasonable, efficient manner.

At very large scales, the overhead of the garbage collection of the objects associated with read operations may come into play. In this case, you can use the ReceiveAsync() method, which allows you to reuse your own pool of state objects for the operations, so that you aren't constantly creating and discarding objects.

Another issue that may come up is memory fragmentation, especially in the large-object heap (depending on the size of the buffers you use). When you start a read operation on a socket, the buffer has to be pinned, preventing .NET from compacting the heap in which it resides.

But these issues aren't reasons to avoid using the asynchronous APIs (and in fact, the second issue happens regardless). They are just things to be aware of. Using the asynchronous API is in fact the best way to go.

That said, BeginReceive() is "old school". It works, but you can wrap a BeginReceive() operation in a Task (see Task.FromAsync() and TPL and Traditional .NET Framework Asynchronous Programming), or you can wrap the entire Socket in a NetworkStream object (which has ReadAsync() and similar methods), which will allow you to write your asynchronous code in a more readable way that doesn't require the use of explicit callback methods. And for scenarios where the network I/O always culminates in some interaction with the UI, allows you to use async/await to do so, again in a more readable, easier-to-write way.

Body:
I have a simple TCP server that is able to listen for and accept multiple connections on a port. It then continuously waits for data to read from its connections. It uses a wrapper class for a TcpClient called ConnectedClient for convenience, and a list (dictionary) of ConnectedClients to keep track of all the connections. It basically goes like this:

/* this method waits to accept connections indefinitely until it receives
   the signal from the GUI thread to stop. When a connection is accepted, it
   adds the connection to the list and calls a method called ProcessClient,
   which returns almost immediately.*/
public void waitForConnections() {
        // this method has access to a TcpListener called listener that was started elsewhere
        try {
            while (!_abort) {
                TcpClient socketClient = listener.AcceptTcpClient();

                //Connected client constructor takes the TcpClient as well as a callback that it uses to print status messages to the GUI if
                ConnectedClient client = new ConnectedClient(socketClient, onClientUpdate);
                clients.Add(client.id, client);
                ProcessClient(client);
            }
        }
        catch (Exception e) {
            onStatusUpdate("Exception Occurred: " + e.Message);
        }
    }

    /* This method doesn't do much other than call BeginRead on the connection */
    private void ProcessClient(ConnectedClient client) {
        try {
            // wrapper class contains an internal buffer for extracting data as well as a TcpClient
            NetworkStream stream = client.tcpClient.GetStream();
            stream.BeginRead(client.buffer, 0, client.tcpClient.ReceiveBufferSize, new AsyncCallback(StreamReadCompleteCallback), client);
        }
        catch (Exception ex) {
            onStatusUpdate(ex.Message);
        }
    }

In my callback function, StreamReadCompleteCallback, I call EndRead, checking the return value of EndRead to detect whether the connection has been closed. If the return value is greater than zero, I extract/process the read data and call BeginRead again on the same client. If the return value is zero, the connection has been closed and I remove the connection (delete from list, close the TcpClient, etc).

    private void StreamReadCompleteCallback(IAsyncResult ar) {
        ConnectedClient client = (ConnectedClient)ar.AsyncState;

        try {
            NetworkStream stream = client.tcpClient.GetStream();

            int read = stream.EndRead(ar);
            if (read != 0) {
                // data extraction/light processing of received data
                client.Append(read);
                stream.BeginRead(client.buffer, 0, client.tcpClient.ReceiveBufferSize, new AsyncCallback(StreamReadCompleteCallback), client);
            }
            else {
                DisconnectClient(client);
            }
        }
        catch (Exception ex) {
            onStatusUpdate(ex.Message);
        }
    }

All of this works fine, I can accept connections and read from multiple client devices, etc.

My question is: This method of continuously reading from connected clients causes each connection to have a worker thread that is waiting for BeginRead to return.

So if I have 10 connections, I have 10 BeginReads going.

It seems wasteful to have so many worker threads sitting around waiting to read. Is there some other, better way to accomplish this? I eventually run out of memory to add connections if I have a high number of active connections.

Would having a thread that polls the DataAvailable property of each connection until something shows up, and then makes a thread to read/process be a solution?

Or is creating all these worker threads not as big of a deal as I think?


问:
How use get method in redux
I am new to redux can anyone tell me how to use redux in GET method, can any one explain With example, it will be more helpful for me.</p>

答:
To use a GET method another application in Redux, you must to do this:

First define the action:

action/index.js

```<code>import axios from 'axios';

export const FETCH_DATA = 'FETCH_DATA';

const ROOT_URL = 'http://host:port';

export function fetchData(){
    const request = axios.get(`${ROOT_URL}/condition_type`)
    return {
        type: FETCH_DATA,
        payload: request
    }
}
</code>```

reducer/index.js

```<code>import { combineReducers } from 'redux';

import ConditionReducer from './reducer_data';

const rootReducer = combineReducers({
    data: DataReducer,
});

export default rootReducer;
</code>```

reducer/reducer_data.js

```<code>import {FETCH_DATA} from '../actions/index';

export default function(state = [], action){

    switch (action.type) {
        case FETCH_DATA:
            return action.payload.data
            break;
        default:
            return state;

    }
}
</code>```

components/some_component.js

```<code>import React ,{Component} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {fetchData} from '../../actions/index';

class DataIndex extends Component {
    componentWillMount(){
        this.props.fetchData();
    }

    render (){
        return(
            <div>
            Do what you want with the information
            {this.props.data}
            </div>
        )
    }
}

function mapStateToProps(state){
    return {data: state.data};
}

export default connect(mapStateToProps, {fetchData})(DataIndex);
</code>```

Title: How use get method in redux

Body:
To use a GET method another application in Redux, you must to do this:

First define the action:

action/index.js

import axios from 'axios';

export const FETCH_DATA = 'FETCH_DATA';

const ROOT_URL = 'http://host:port';

export function fetchData(){
    const request = axios.get(`${ROOT_URL}/condition_type`)
    return {
        type: FETCH_DATA,
        payload: request
    }
}

reducer/index.js

import { combineReducers } from 'redux';

import ConditionReducer from './reducer_data';

const rootReducer = combineReducers({
    data: DataReducer,
});

export default rootReducer;

reducer/reducer_data.js

import {FETCH_DATA} from '../actions/index';

export default function(state = [], action){

    switch (action.type) {
        case FETCH_DATA:
            return action.payload.data
            break;
        default:
            return state;

    }
}

components/some_component.js

import React ,{Component} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {fetchData} from '../../actions/index';

class DataIndex extends Component {
    componentWillMount(){
        this.props.fetchData();
    }

    render (){
        return(
            <div>
            Do what you want with the information
            {this.props.data}
            </div>
        )
    }
}

function mapStateToProps(state){
    return {data: state.data};
}

export default connect(mapStateToProps, {fetchData})(DataIndex);


问:
How to filter on most recent value for specific column
Running a query that has multiple rows showing db table statistics, in both a before and after status after a scheduled job that runs on either Sat/Sun.

```<code>Select [batchNum] ,[RunDate] ,[tableName] ,[numberofRows] ,[dataSize]
FROM TableNames
ORDER BY RunDate ASC
</code>```

The before/after is differentiated by the batch number. So for example, this table has batch numbers 2-159. Where '158' is the 'before' job/batch from the scheduled job that ran this past weekend, and batch 159 would be the 'after.

```<code>    batchNum    RunDate             tableName   numberofRows    dataSize
    158         06/04/2017 04:30:51 TableData1  1700            104
    158         06/04/2017 04:30:51 TableData2  1276             99
    158         06/04/2017 04:30:51 TableData3  1700            157
    158         06/04/2017 04:30:51 TableData4   200             47

    159         06/04/2017 05:30:51 TableData1  1500             85
    159         06/04/2017 05:30:55 TableData2  1134             94
    159         06/04/2017 05:30:57 TableData3  1500            101
    159         06/04/2017 05:30:59 TableData4   167             40
</code>```

Since the batch will always be revolving, I'd like to filter this query to only return rows of most recent batchNum for the most recent weekend, any time i run it through out the year.

答:
try this</p>

```<code>select * from (
Select [batchNum] ,[RunDate] ,[tableName] ,[numberofRows] ,[dataSize],
row_number() over(partition by tableName  order by batchNum desc) rang
FROM TableNames
) tmp where rang=1
</code>```

Body:
Running a query that has multiple rows showing db table statistics, in both a before and after status after a scheduled job that runs on either Sat/Sun.

Select [batchNum] ,[RunDate] ,[tableName] ,[numberofRows] ,[dataSize]
FROM TableNames
ORDER BY RunDate ASC

The before/after is differentiated by the batch number. So for example, this table has batch numbers 2-159. Where '158' is the 'before' job/batch from the scheduled job that ran this past weekend, and batch 159 would be the 'after.

    batchNum    RunDate             tableName   numberofRows    dataSize
    158         06/04/2017 04:30:51 TableData1  1700            104
    158         06/04/2017 04:30:51 TableData2  1276             99
    158         06/04/2017 04:30:51 TableData3  1700            157
    158         06/04/2017 04:30:51 TableData4   200             47

    159         06/04/2017 05:30:51 TableData1  1500             85
    159         06/04/2017 05:30:55 TableData2  1134             94
    159         06/04/2017 05:30:57 TableData3  1500            101
    159         06/04/2017 05:30:59 TableData4   167             40

Since the batch will always be revolving, I'd like to filter this query to only return rows of most recent batchNum for the most recent weekend, any time i run it through out the year.

Body:
try this

select * from (
Select [batchNum] ,[RunDate] ,[tableName] ,[numberofRows] ,[dataSize],
row_number() over(partition by tableName  order by batchNum desc) rang
FROM TableNames
) tmp where rang=1


问:
How to make concrete implementation more generic
I have this interface

```<code> public interface IMapper
{
    bool CanMap(List<Field> fields);
    AccountHolder Map(List<Field> fields);
}
</code>```

I have multiple classes that implements this interface. Given below is an example of this implementation.

```<code>public class DepositorMapper : IMapper
{
    private readonly IFormUIElementHelper _formHelper;

    public DepositorMapper(IFormUIElementHelper formHelper)
    {
        _formHelper = formHelper;
    }

    public bool CanMap(List<Fields> fields)
    {
        var taxId = _formHelper.GetFieldValue<string>(fields, FormsAttributes.DepositorTaxId);

        return !string.IsNullOrWhiteSpace(DepositorTaxId);
    }
}
</code>```

The only difference in each concrete implementation is the  'FormsAttributes.DepositorTaxId'. How can i make this more generic?

答:
You can make an abstract class like that: </p>

```<code>public abstract class BaseDepositorMapper : IMapper
{
    private readonly IFormUIElementHelper _formHelper;

    public BaseDepositorMapper (IFormUIElementHelper formHelper)
    {
        _formHelper = formHelper;
    }

    public bool CanMap(List<Fields> fields)
    {
        var taxId = _formHelper.GetFieldValue<string>(fields, GetDepositorTaxId());

        return !string.IsNullOrWhiteSpace(taxId);
    }

    public abstract DepositorTaxIdType GetDepositorTaxId();
}
</code>```

Body:
I have this interface

 public interface IMapper
{
    bool CanMap(List<Field> fields);
    AccountHolder Map(List<Field> fields);
}

I have multiple classes that implements this interface. Given below is an example of this implementation.

public class DepositorMapper : IMapper
{
    private readonly IFormUIElementHelper _formHelper;

    public DepositorMapper(IFormUIElementHelper formHelper)
    {
        _formHelper = formHelper;
    }

    public bool CanMap(List<Fields> fields)
    {
        var taxId = _formHelper.GetFieldValue<string>(fields, FormsAttributes.DepositorTaxId);

        return !string.IsNullOrWhiteSpace(DepositorTaxId);
    }
}

The only difference in each concrete implementation is the  'FormsAttributes.DepositorTaxId'. How can i make this more generic?

Body:
You can make an abstract class like that:

public abstract class BaseDepositorMapper : IMapper
{
    private readonly IFormUIElementHelper _formHelper;

    public BaseDepositorMapper (IFormUIElementHelper formHelper)
    {
        _formHelper = formHelper;
    }

    public bool CanMap(List<Fields> fields)
    {
        var taxId = _formHelper.GetFieldValue<string>(fields, GetDepositorTaxId());

        return !string.IsNullOrWhiteSpace(taxId);
    }

    public abstract DepositorTaxIdType GetDepositorTaxId();
}


问:
When adhering to Liskov Substitution Principle (LSP) can a child class implement additional interface?
Consider this ruby example

```<code>class Animal
  def walk
     # In our universe all animals walk, even whales
     puts "walking"
  end

  def run
    # Implementing to conform to LSP, even though only some animals run
    raise NotImplementedError
  end
end

class Cat < Animal
  def run
    # Dogs run differently, and Whales, can't run at all
    puts "running like a cat"
  end

  def sneer_majesticly
    # Only cats can do this.
    puts "meh"
  end
end
</code>```

Does method sneer_majesticly violate LSP, being defined only on Cat, since this interfaces is not implemented nor needed on Animal?

答: LSP says you can drop in any implementation of the base type/interface, and it should continue to work. So no reason why it should violate that, although it raises interesting questions about why you need to implement that additional interface in one implementation and not others. Are you following the single responsibility principle?</p>

Body:
Consider this ruby example

class Animal
  def walk
     # In our universe all animals walk, even whales
     puts "walking"
  end

  def run
    # Implementing to conform to LSP, even though only some animals run
    raise NotImplementedError
  end
end

class Cat < Animal
  def run
    # Dogs run differently, and Whales, can't run at all
    puts "running like a cat"
  end

  def sneer_majesticly
    # Only cats can do this.
    puts "meh"
  end
end

Does method sneer_majesticly violate LSP, being defined only on Cat, since this interfaces is not implemented nor needed on Animal?


问:
Why does git fetch via hudson fail, while git fetch via the command line works?
I'm trying to fetch a read-only git repository from github and have it be built via hudson.  This process is failing.

This is the hudson output:

```<code>Started by an SCM change
Checkout:workspace / d:\hudson\home\jobs\gdcm-hudson\workspace - hudson.remoting.LocalChannel@19ba1d8
Using strategy: Default
Checkout:workspace / d:\hudson\home\jobs\gdcm-hudson\workspace - hudson.remoting.LocalChannel@19ba1d8
GitAPI created
Fetching changes from the remote Git repository
Fetching upstream changes from git://github.com/malaterre/gdcm.git
[workspace] $ "C:\Program Files (x86)\Git\bin\git.exe" fetch -t git://github.com/malaterre/gdcm.git +refs/heads/*:refs/remotes/origin/*
[workspace] $ "C:\Program Files (x86)\Git\bin\git.exe" ls-tree HEAD
ERROR: Problem fetching from origin / origin - could be unavailable. Continuing anyway
ERROR: Could not fetch from any repository
FATAL: Could not fetch from any repository
hudson.plugins.git.GitException: Could not fetch from any repository
    at hudson.plugins.git.GitSCM$2.invoke(GitSCM.java:674)
    at hudson.plugins.git.GitSCM$2.invoke(GitSCM.java:641)
    at hudson.FilePath.act(FilePath.java:753)
    at hudson.FilePath.act(FilePath.java:735)
    at hudson.plugins.git.GitSCM.checkout(GitSCM.java:641)
    at hudson.model.AbstractProject.checkout(AbstractProject.java:1061)
    at hudson.model.AbstractBuild$AbstractRunner.checkout(AbstractBuild.java:479)
    at hudson.model.AbstractBuild$AbstractRunner.run(AbstractBuild.java:411)
    at hudson.model.Run.run(Run.java:1273)
    at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:46)
    at hudson.model.ResourceController.execute(ResourceController.java:88)
    at hudson.model.Executor.run(Executor.java:129)
</code>```

When I run that fetch command directly via the git bash command line, I get no response (which I assume means it's worked).

I looked at this possible solution:
http://issues.hudson-ci.org/browse/HUDSON-7141?page=com.atlassian.jira.plugin.system.issuetabpanels%3Aall-tabpanel

But using that version of the plugin did not change this behavior.

I haven't even gotten to having it work with cmake yet, just downloaded consistently.  How can I get this to work?

edit: This problem is not a repro of Problem cloning / fetching repository using Git plugin for Hudson on Windows, because I'm not running as a service on a server.

答:
Yes, I just fixed this exact problem. If you open a windows explorer to d:\hudson\home\jobs\gdcm-hudson\workspace you should be able to see a .git directory and nothing else. There should be a working copy but there isn't. To fix this you have to "prime" the repository by running

```<code>git pull git://github.com/malaterre/gdcm.git
</code>```

This should create a bunch of other files in d:\hudson\home\jobs\gdcm-hudson\workspace along side the .git directory and you should be able to perform a build in hudson.

Body:
I'm trying to fetch a read-only git repository from github and have it be built via hudson.  This process is failing.

This is the hudson output:

Started by an SCM change
Checkout:workspace / d:\hudson\home\jobs\gdcm-hudson\workspace - hudson.remoting.LocalChannel@19ba1d8
Using strategy: Default
Checkout:workspace / d:\hudson\home\jobs\gdcm-hudson\workspace - hudson.remoting.LocalChannel@19ba1d8
GitAPI created
Fetching changes from the remote Git repository
Fetching upstream changes from git://github.com/malaterre/gdcm.git
[workspace] $ "C:\Program Files (x86)\Git\bin\git.exe" fetch -t git://github.com/malaterre/gdcm.git +refs/heads/*:refs/remotes/origin/*
[workspace] $ "C:\Program Files (x86)\Git\bin\git.exe" ls-tree HEAD
ERROR: Problem fetching from origin / origin - could be unavailable. Continuing anyway
ERROR: Could not fetch from any repository
FATAL: Could not fetch from any repository
hudson.plugins.git.GitException: Could not fetch from any repository
    at hudson.plugins.git.GitSCM$2.invoke(GitSCM.java:674)
    at hudson.plugins.git.GitSCM$2.invoke(GitSCM.java:641)
    at hudson.FilePath.act(FilePath.java:753)
    at hudson.FilePath.act(FilePath.java:735)
    at hudson.plugins.git.GitSCM.checkout(GitSCM.java:641)
    at hudson.model.AbstractProject.checkout(AbstractProject.java:1061)
    at hudson.model.AbstractBuild$AbstractRunner.checkout(AbstractBuild.java:479)
    at hudson.model.AbstractBuild$AbstractRunner.run(AbstractBuild.java:411)
    at hudson.model.Run.run(Run.java:1273)
    at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:46)
    at hudson.model.ResourceController.execute(ResourceController.java:88)
    at hudson.model.Executor.run(Executor.java:129)

When I run that fetch command directly via the git bash command line, I get no response (which I assume means it's worked).

I looked at this possible solution:
http://issues.hudson-ci.org/browse/HUDSON-7141?page=com.atlassian.jira.plugin.system.issuetabpanels%3Aall-tabpanel

But using that version of the plugin did not change this behavior.

I haven't even gotten to having it work with cmake yet, just downloaded consistently.  How can I get this to work?

edit: This problem is not a repro of Problem cloning / fetching repository using Git plugin for Hudson on Windows, because I'm not running as a service on a server.

Body:
Yes, I just fixed this exact problem. If you open a windows explorer to d:\hudson\home\jobs\gdcm-hudson\workspace you should be able to see a .git directory and nothing else. There should be a working copy but there isn't. To fix this you have to "prime" the repository by running

git pull git://github.com/malaterre/gdcm.git

This should create a bunch of other files in d:\hudson\home\jobs\gdcm-hudson\workspace along side the .git directory and you should be able to perform a build in hudson.


问:
Intune Graph API data extracts - very little data to work with
Im curious if there is more data available for Azure AD devices / Intune devices from the Graph API to match up with the manual device reports available from both portals?

https://graph.microsoft.com/v1.0/devices/ or Beta

developer . microsoft . com /en-us/graph/docs/api-reference/beta/resources/device

Below is what im looking at. Anyone had any success at getting more data from the API ?

Data comparison

答:
I'm an engineer working on Microsoft Intune, specifically on the integration between Microsoft Graph and Intune.

All the details available in the Intune Azure Portal can be found on the managedDevice entity. The Intune Azure Portal itself is built on top of the Microsoft Graph APIs, so anything you can see or do in the portal you can do via the APIs.

If you are still having problems finding specific APIs let me know, and I should be able to help you find the information.

Peter


问:
UITableView's deselectRowAtIndexPath prevents cell's subviews from changing background color
I am working on a tableview with custom cells. I need to highlight current selected (active) cell by setting background color for the title label, which is an immediate subview of cell.contentView. My code logic is like this (revised for better understanding):

```<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    UITableViewCell *previousActiveCell = [tableView cellForRowAtIndexPath:_indexPathActiveCell]; // previous selection
    UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath: indexPath]; // current selection

    UILabel *labelpreviousActiveCellTitle = [previousActiveCell.contentView viewWithTag:SUBVIEW_TAG_TITLE_LABEL];
    UILabel *labelSelectedCellTitle = [selectedCell.contentView viewWithTag:SUBVIEW_TAG_TITLE_LABEL];

    labelpreviousActiveCellTitle.backgroundColor = [UIColor clearColor]; // remove highlighting from previous selection
    labelSelectedCellTitle.backgroundColor = [UIColor redColor]; // highlighted

    _indexPathActiveCell = indexPath; // update _indexPathActiveCell with current selection
}
</code>```

The problem is, when a new cell is selected, the highlighting background color appears for a very short moment, about half a second, and then disappears. If I comment out the calling for deselectRowAtIndexPath,

```<code>// [tableView deselectRowAtIndexPath:indexPath animated:YES];
</code>```

the highlighting background color will retain. My guess is that deselectRowAtIndexPath remembers all the subviews' previous background color and when it recovers the cell from the shaded background, it changes all the subviews' background color back.

My workaround is adding a delay like this:

```<code>dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    labelpreviousActiveCellTitle.backgroundColor = [UIColor clearColor];
    labelSelectedCellTitle.backgroundColor = [UIColor redColor];
});
</code>```

and it works. Note that I also tried a shorter delay like 0.01 second which did not work.

Setting the delay time with a magic number is an unpleasant way. My question is, is there any better way to set the background color for cell's subviews in tableview's didSelectRowAtIndexPath delegate method? Thanks in advance.

答:
Make a temporary variable which will hold the selected cell in your view controller.I am using a custom cell. It's not so important here though

```<code>var selectedCellIndex:IndexPath?
</code>```

in your viewDidLoad initialize this like this.

```<code>selectedCellIndex = IndexPath.init(row: -1, section: 0)// first row starts with 0 you know.
</code>```

in your cellForRowAtIndexPath function modify it like this.

```<code>public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "chatCell", for: indexPath) as! sampleTableViewCell

    if indexPath.row == selectedCellIndex?.row {
        cell.label.backgroundColor = UIColor.green
    }
    else {
        cell.label.backgroundColor = UIColor.clear
    }
    cell.selectionStyle = .none //For removing grey color while cell selection.
    return cell

}
</code>```

change your didSelectRowAtIndexPath like this.

```<code>public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    selectedCellIndex = indexPath
    tableView.reloadRows(at: tableView.indexPathsForVisibleRows!, with: .none) //reload only visible cells. don't call reloadData it's expensive.

}
</code>```

Here is the output:

Body:
I am working on a tableview with custom cells. I need to highlight current selected (active) cell by setting background color for the title label, which is an immediate subview of cell.contentView. My code logic is like this (revised for better understanding):

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    UITableViewCell *previousActiveCell = [tableView cellForRowAtIndexPath:_indexPathActiveCell]; // previous selection
    UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath: indexPath]; // current selection

    UILabel *labelpreviousActiveCellTitle = [previousActiveCell.contentView viewWithTag:SUBVIEW_TAG_TITLE_LABEL];
    UILabel *labelSelectedCellTitle = [selectedCell.contentView viewWithTag:SUBVIEW_TAG_TITLE_LABEL];

    labelpreviousActiveCellTitle.backgroundColor = [UIColor clearColor]; // remove highlighting from previous selection
    labelSelectedCellTitle.backgroundColor = [UIColor redColor]; // highlighted

    _indexPathActiveCell = indexPath; // update _indexPathActiveCell with current selection
}

The problem is, when a new cell is selected, the highlighting background color appears for a very short moment, about half a second, and then disappears. If I comment out the calling for deselectRowAtIndexPath,

// [tableView deselectRowAtIndexPath:indexPath animated:YES];

the highlighting background color will retain. My guess is that deselectRowAtIndexPath remembers all the subviews' previous background color and when it recovers the cell from the shaded background, it changes all the subviews' background color back.

My workaround is adding a delay like this:

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    labelpreviousActiveCellTitle.backgroundColor = [UIColor clearColor];
    labelSelectedCellTitle.backgroundColor = [UIColor redColor];
});

and it works. Note that I also tried a shorter delay like 0.01 second which did not work.

Setting the delay time with a magic number is an unpleasant way. My question is, is there any better way to set the background color for cell's subviews in tableview's didSelectRowAtIndexPath delegate method? Thanks in advance.

Body:
Make a temporary variable which will hold the selected cell in your view controller.I am using a custom cell. It's not so important here though

var selectedCellIndex:IndexPath?

in your viewDidLoad initialize this like this.

selectedCellIndex = IndexPath.init(row: -1, section: 0)// first row starts with 0 you know.

in your cellForRowAtIndexPath function modify it like this.

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "chatCell", for: indexPath) as! sampleTableViewCell

    if indexPath.row == selectedCellIndex?.row {
        cell.label.backgroundColor = UIColor.green
    }
    else {
        cell.label.backgroundColor = UIColor.clear
    }
    cell.selectionStyle = .none //For removing grey color while cell selection.
    return cell

}

change your didSelectRowAtIndexPath like this.

public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    selectedCellIndex = indexPath
    tableView.reloadRows(at: tableView.indexPathsForVisibleRows!, with: .none) //reload only visible cells. don't call reloadData it's expensive.

}

Here is the output:


问:
Flex mx:Canvas label is seen null
The problem is that when the label is not fit the size of accordion, the end of the label is seen as "Hello, my name inull" instead of "Hello, my name is Can." I cannot wide the size of the accordion due to other component size.
It can be seen as "Hello, my name is..", however I cold not find a solution.
I tried the truncateToFit="true" tag but I think it is not used here.
Here is the flex code;

```<code>   <mx:Accordion x="0" y="2" width="200" height="100%" id="accSettings" styleName="accordionStyle">
            <mx:Canvas id="emptyCanvas" visible="false" includeInLayout="false">
            </mx:Canvas>
        </mx:Accordion>
        <mx:VBox visible="false" width="100%">
 <mx:Canvas id="screenToVMTab" label="Hello, my name is Can!" width="100%" height="100%">
                <mx:VBox width="100%" height="100%" verticalGap="0" id="vbScreenToVMTab" >
                </mx:VBox>
            </mx:Canvas>
    </mx:VBox>
</code>```

Also, tried to remove height and width tags, not fixed.
Thank you!

答:
Try this:

```<code><mx:Accordion left="2" top="2" width="130" bottom="2" id="accSettings" styleName="accordionStyle">
    <mx:Canvas id="emptyCanvas" label="Empty Canvas" visible="true" includeInLayout="true" width="100%" height="100%">
        <mx:Label text="Inside Empty Canvas." />
    </mx:Canvas>
    <mx:Canvas id="screenToVMTab" label="Hello, my name is Can!" width="100%" height="100%">
        <mx:VBox width="100%" height="100%" verticalGap="0" id="vbScreenToVMTab" >
            <mx:Label text="Inside VBox. Label 1"/>
            <mx:Label text="Inside VBox. Label 2"/>
        </mx:VBox>
    </mx:Canvas>
</mx:Accordion>
</code>```

Title: Flex mx:Canvas label is seen null

Body:
The problem is that when the label is not fit the size of accordion, the end of the label is seen as "Hello, my name inull" instead of "Hello, my name is Can." I cannot wide the size of the accordion due to other component size.
It can be seen as "Hello, my name is..", however I cold not find a solution.
I tried the truncateToFit="true" tag but I think it is not used here.
Here is the flex code;

   <mx:Accordion x="0" y="2" width="200" height="100%" id="accSettings" styleName="accordionStyle">
            <mx:Canvas id="emptyCanvas" visible="false" includeInLayout="false">
            </mx:Canvas>
        </mx:Accordion>
        <mx:VBox visible="false" width="100%">
 <mx:Canvas id="screenToVMTab" label="Hello, my name is Can!" width="100%" height="100%">
                <mx:VBox width="100%" height="100%" verticalGap="0" id="vbScreenToVMTab" >
                </mx:VBox>
            </mx:Canvas>
    </mx:VBox>

Also, tried to remove height and width tags, not fixed.
Thank you!

Body:
Try this:

<mx:Accordion left="2" top="2" width="130" bottom="2" id="accSettings" styleName="accordionStyle">
    <mx:Canvas id="emptyCanvas" label="Empty Canvas" visible="true" includeInLayout="true" width="100%" height="100%">
        <mx:Label text="Inside Empty Canvas." />
    </mx:Canvas>
    <mx:Canvas id="screenToVMTab" label="Hello, my name is Can!" width="100%" height="100%">
        <mx:VBox width="100%" height="100%" verticalGap="0" id="vbScreenToVMTab" >
            <mx:Label text="Inside VBox. Label 1"/>
            <mx:Label text="Inside VBox. Label 2"/>
        </mx:VBox>
    </mx:Canvas>
</mx:Accordion>


问:
Objective C - HTTP GET Request API
I've been trying to query Tesco's API Service. Although I've managed comfortably on Python with this, I have been having some trouble with making a request using Objective C. Nothing is being logged on the output. Any help would be appreciated. The program code is shown below:</p>

```<code>#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        NSURLSessionConfiguration *defaultSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultSessionConfiguration];

        NSURL *url = [NSURL URLWithString:@"https://dev.tescolabs.com/product/?gtin=4548736003446"];
        NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];

        NSString *postParams = @"subscription key=93a6e21eed2e4ca3a858a0f1fc5aaf03";
        NSData *postData = [postParams dataUsingEncoding:NSUTF8StringEncoding];

        [urlRequest setHTTPMethod:@"GET"];
        [urlRequest setHTTPBody:postData];

        NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            NSLog(@"Response: %@",response);
            NSLog(@"Data: %@",data);
            NSLog(@"Error: %@",error);
        }];
        [dataTask resume];
    }
    return 0;
}
</code>```

答:
```<code>#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        NSURLSessionConfiguration *defaultSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultSessionConfiguration];

        NSURL *url = [NSURL URLWithString:@"https://dev.tescolabs.com/product/? ... "];

        NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithURL: url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            NSLog(@"Response: %@",response);
            NSLog(@"Data: %@",data);
            NSLog(@"Error: %@",error);
            CFRunLoopStop(CFRunLoopGetCurrent());
            exit(EXIT_SUCCESS);
        }];
        [dataTask resume];
    }

    CFRunLoopRun();
    return 0;
}
</code>```

Title: Objective C - HTTP GET Request API

Body:
I've been trying to query Tesco's API Service. Although I've managed comfortably on Python with this, I have been having some trouble with making a request using Objective C. Nothing is being logged on the output. Any help would be appreciated. The program code is shown below:

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        NSURLSessionConfiguration *defaultSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultSessionConfiguration];

        NSURL *url = [NSURL URLWithString:@"https://dev.tescolabs.com/product/?gtin=4548736003446"];
        NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];

        NSString *postParams = @"subscription key=93a6e21eed2e4ca3a858a0f1fc5aaf03";
        NSData *postData = [postParams dataUsingEncoding:NSUTF8StringEncoding];

        [urlRequest setHTTPMethod:@"GET"];
        [urlRequest setHTTPBody:postData];

        NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            NSLog(@"Response: %@",response);
            NSLog(@"Data: %@",data);
            NSLog(@"Error: %@",error);
        }];
        [dataTask resume];
    }
    return 0;
}


问:
Wordpress Plugin -> Is there an API call to get what the URL will be of an article?
I'm writing a wordpress plugin and I have a hook for everytime the publisher publishes an article. I'm sending some of that data to a server. Is there an API in wordpress I can call that will tell me what the URL of the article would be?

for example....
I'll know what the article ID is and can craft a URL like
http://thedomain.com/?p=1234
however that won't be the URL that the users sees, it would be more like http://thedomain.com/news/this-is-an-article

Is there a way in wordpress to get the final URL?

gracias

答: Sure. $link = get_permalink(1234);

Body: Sure. $link = get_permalink(1234);


问:
Jquery toggle not working when toggling back
I am using jquery toggle, to show one image and then when the user clicks on an element, change to another image and if they click again show the original image. Like an open close kind of thing. It works when I first click, but nothing after that. Here is my jquery

```<code> $(".filterInventory").on("click", function () {

    $(".inventory-search").toggle();
    $(".filer-arrow.down").hide();
    $(".filer-arrow.up").show();

    return false;

});
</code>```

and here is the HTML

```<code><div class="container container-padding-top inventory-search-button">
        <div class="row">
            <div class="col-md-12">
                <a href="#" class="filterInventory">Filter <img src="~/Images/icons/down-arrow-white.png" class="filer-arrow down" alt="Filter Arrow" /><img src="~/Images/icons/up-arrow-white.png" class="filer-arrow up" alt="Filter Arrow" /></a>
            </div>
        </div>
    </div>
</code>```

CSS:

```<code>#communities a.filterInventory img.up {
    display: none;
}

#communities .filterInventory .filer-arrow {
    height: 10px;
}
</code>```

答:
Hide one of the image initally

```<code>$('img.down').hide();
</code>```

Then simply toggle between them

```<code>$(".filterInventory").click(function () {
    $(".filterInventory img").toggle();
});
</code>```

Body:
I am using jquery toggle, to show one image and then when the user clicks on an element, change to another image and if they click again show the original image. Like an open close kind of thing. It works when I first click, but nothing after that. Here is my jquery

 $(".filterInventory").on("click", function () {

    $(".inventory-search").toggle();
    $(".filer-arrow.down").hide();
    $(".filer-arrow.up").show();

    return false;

});

and here is the HTML

                Filter

CSS:

#communities a.filterInventory img.up {
    display: none;
}

#communities .filterInventory .filer-arrow {
    height: 10px;
}

Body:
Hide one of the image initally

$('img.down').hide();

Then simply toggle between them

$(".filterInventory").click(function () {
    $(".filterInventory img").toggle();
});


问:
Meaning of "IconResource= ..\.. ,(number)"
My first question in Stackoverflow, I'm thinking in making a litle program to edit some folder icons on Windows, I searched for the meaning of the number after the path of the icon but find no answer, the system icons have diferent values, i.e:

Music Folder

```<code>IconResource=%SystemRoot%\system32\imageres.dll,-108
</code>```

Pictures Folder

```<code>IconResource=%SystemRoot%\system32\imageres.dll,-113
</code>```

When we manually change an icon from a folder,usually is used(to  keep it in a removable media):

IconResource=..\Icons\icon.ico,0

There is any influence in that last number? Or it doesn't matter for that purpose?

答:
.EXE and .DLL files can contain more than one icon. ,0 is the first icon in the file, this syntax can also be used for .ICO files that only contain one icon.

Positive numbers simply refer to the order the icons are stored in the executable file (,0 is the first, ,1 is the second and ,2 is the third etc.). This order is the same as the order of icons in the standard pick icon dialog in Windows (shortcut properties etc.).

A negative number is the resource id of the icon, this is a number chosen by the author of said executable and can be stable over time even if the number if icons changes if the author chooses to use stable resource ids.

See also:
How the shell converts an icon location into an icon

Body:
My first question in Stackoverflow, I'm thinking in making a litle program to edit some folder icons on Windows, I searched for the meaning of the number after the path of the icon but find no answer, the system icons have diferent values, i.e:

Music Folder

IconResource=%SystemRoot%\system32\imageres.dll,-108

Pictures Folder

IconResource=%SystemRoot%\system32\imageres.dll,-113

When we manually change an icon from a folder,usually is used(to  keep it in a removable media):

IconResource=..\Icons\icon.ico,0

There is any influence in that last number? Or it doesn't matter for that purpose?


问:
How to destined messages from an local queue manger to another queue manager of an local queue
Hi I am preparing for an exam.
Can anyone able to help me find the correct answer.

An application connects to local queue manager QM1 and puts messages on remote queue QR1.

QR1 has been defined with target queue QL2, target queue manager QM2,
and XMITQ QM2.

QL2 is defined as a local queue in QM2. For security purposes,
another queue manager, QM3, has been created behind a firewall and
all messages destined for QL2 on QM2 need to be routed to QL3 on QM3.

Assuming QM2 and QM3 are interconnected, what changes does the system administrator need to make to achieve this without application failure?

A. Create an alias queue on QM2 pointing to QL3 on QM3.

B. Create a remote queue on QM2 pointing to QL3 on QM3.

C. Alter the QR1 RQMNAME parameter to point to QM3 and RNAME parameter to QL3 with XMITQ QM2.

D. Alter the QR1 RQMNAME parameter to point to QM3 and RNAME parameter to QL3 with XMITQ QM3.

答:
Given the details provided in the question and the four answers provided C is the most correct.

There could still be impact to the application if QR1 is open for OUTPUT by the application at the time of the alter.  The application would either need to be stopped while the the QREMOTE is altered or the FORCE option would need to be used in which case the application would receive a MQRC 2041 (MQRC_OBJECT_CHANGED) the next time it attempted to PUT a message to the queue.  The FORCE option would require the application to handle that exception and reopen the queue, many application do not handle this exception so may need to be restarted anyway.

This answer also make assumptions that the RCVR channel from QM1 to QM2 is either not locked down with a low privileged MCAUSER or if it is locked down that it would have permission to put the the XMITQ QM3.

Answer B could be a potential solution as well if the original local queue QL2 on QM2 is deleted first and a new remote queue called QL2 is defined on QM2 which would point to QL3 on QM3.


问:
Send JSON response from middleware
here's the code:

```<code>public Task Invoke(HttpContext httpContext)
        {
            if (Http_Server.mode == 2)
                return InteractivityTask(httpContext);
            else
                return _next(httpContext);
        }

public async Task<HttpResponse> InteractivityTask(HttpContext httpContext) {

            HttpResponse response = httpContext.Response;
            string s = getResponseBody();
            response.Clear();
            MemoryStream ms = GenerateStreamFromString(s);
            response.Body = ms;
            response.ContentType = "application/json";//not sure
            }
            return response;
        }

public MemoryStream GenerateStreamFromString(string value)
        {
            return new MemoryStream(Encoding.UTF8.GetBytes(value ?? ""));
        }
</code>```

I am not receiving the body of the response, just the status code with blank body received.

答:
Try this:

```<code>response.Body.Write(ms.ToArray(), 0, (int)ms.Length);
</code>```

Instead of:

```<code>response.Body = ms;
</code>```

Title: Send JSON response from middleware

Body:
here's the code:

public Task Invoke(HttpContext httpContext)
        {
            if (Http_Server.mode == 2)
                return InteractivityTask(httpContext);
            else
                return _next(httpContext);
        }

public async Task<HttpResponse> InteractivityTask(HttpContext httpContext) {

            HttpResponse response = httpContext.Response;
            string s = getResponseBody();
            response.Clear();
            MemoryStream ms = GenerateStreamFromString(s);
            response.Body = ms;
            response.ContentType = "application/json";//not sure
            }
            return response;
        }

public MemoryStream GenerateStreamFromString(string value)
        {
            return new MemoryStream(Encoding.UTF8.GetBytes(value ?? ""));
        }

I am not receiving the body of the response, just the status code with blank body received.

Body:
Try this:

response.Body.Write(ms.ToArray(), 0, (int)ms.Length);

Instead of:

response.Body = ms;


问:
ASP.NET MVC: Generating dynamic sitemaps for SEO purposes
I want to add/remove urls to sitemaps whenever a user deletes or submits information.

I have a few questions:

Should I put slugs on the URL in the sitemap? Products/Details/1/my-slug -> URL works without slug.

Should I Use an action to generate a sitemap? In robots.txt I'll link to this action.

If not action, are there libraries that allow me to easily edit sitemap.xml files?

Sitemaps has a limit to the # of URLs and size, is there a way to automatically create more sitemaps when this limit is met? I'd have to also update the robots.txt and add more links to sitemaps.

答: The ASP.NET MVC SiteMap Provider project has support for automatically generating the sitemap XML for search engines, including the ability to break up large sitemaps into multiple files.</p>


问:
How can I define a Swift Protocol so that the implementation can be a property _or_ a method?
Here's what I want to do:

```<code>import Foundation
import UIKit

protocol PlayableMediaItem {
    func title() -> String
    func albumArt() -> UIImage
    func audioFileURL() -> URL
}

struct AudioTrack : Codable, PlayableMediaItem {
    var title: String
    var desc:String
    var albumArtDemoName:String
    var audioDemoFilename:String

    func albumArt() -> UIImage {
        let image = UIImage(named: albumArtDemoName)
        return image!
    }

    func audioFileURL() -> URL {
        return Bundle.main.url(forResource: audioDemoFilename, withExtension: "mp3")!
    }
}
</code>```

But I get the error that AudioTrack doesn't conform to the PlayableMediaItem protocol because the title property isn't a method, it's a property.

How can I set this up so that title, albumArt, etc. can be implemented as either properties or methods, so long as they give me back the right type?

Some of my implementations of this might just be properties, while others are computed.

答:
Just declare it as a property in the protocol, and use a computed property instead of using a method:</p>

```<code>import Foundation
import UIKit

protocol PlayableMediaItem {
    var title: String { get }
    var albumArt: UIImage { get }
    var audioFileURL: URL { get }
}

struct AudioTrack : Codable, PlayableMediaItem {
    var title: String
    var desc:String
    var albumArtDemoName:String
    var audioDemoFilename:String

    var albumArt: UIImage {
        let image = UIImage(named: albumArtDemoName)
        return image!
    }

    var audioFileURL: URL {
        return Bundle.main.url(forResource: audioDemoFilename, withExtension: "mp3")!
    }
}
</code>```

Body:
Here's what I want to do:

import Foundation
import UIKit

protocol PlayableMediaItem {
    func title() -> String
    func albumArt() -> UIImage
    func audioFileURL() -> URL
}

struct AudioTrack : Codable, PlayableMediaItem {
    var title: String
    var desc:String
    var albumArtDemoName:String
    var audioDemoFilename:String

    func albumArt() -> UIImage {
        let image = UIImage(named: albumArtDemoName)
        return image!
    }

    func audioFileURL() -> URL {
        return Bundle.main.url(forResource: audioDemoFilename, withExtension: "mp3")!
    }
}

But I get the error that AudioTrack doesn't conform to the PlayableMediaItem protocol because the title property isn't a method, it's a property.

How can I set this up so that title, albumArt, etc. can be implemented as either properties or methods, so long as they give me back the right type?

Some of my implementations of this might just be properties, while others are computed.

Body:
Just declare it as a property in the protocol, and use a computed property instead of using a method:

import Foundation
import UIKit

protocol PlayableMediaItem {
    var title: String { get }
    var albumArt: UIImage { get }
    var audioFileURL: URL { get }
}

struct AudioTrack : Codable, PlayableMediaItem {
    var title: String
    var desc:String
    var albumArtDemoName:String
    var audioDemoFilename:String

    var albumArt: UIImage {
        let image = UIImage(named: albumArtDemoName)
        return image!
    }

    var audioFileURL: URL {
        return Bundle.main.url(forResource: audioDemoFilename, withExtension: "mp3")!
    }
}


问:
Android RxJava2 Handle Orientation Changed
I'm new at this library, so if you got any tips or suggestions are more than welcome.
I got RxJava2 running and executing a longNetworkOperation fake method, the flow is this:

Create the observable:  Observable.just("str1")

Change the execution thread: .subscribeOn(Schedulers.newThread())

Implement the map interface which will execute the LongRunningProcess:

```<code>.map(new Function<String, String>() {
     @Override
     public String apply(String cad){ // cad is the input value
            Log.d(TAG,"long operation in thread: "+Thread.currentThread().getName()); //output thread name
            return " longNetworkOperation result => "+doLongNetworkOperation(); //here we do the background operations
            }})
</code>```

Get the results in Main Thread: .observeOn(AndroidSchedulers.mainThread())

Add the observer which get notified for the results: .subscribe(observer);

And the observer:

```<code> Observer observer = new Observer() {
    @Override
    public void onSubscribe(Disposable d) { Log.d(TAG,"onSubscribe, thread name >> "+Thread.currentThread().getName()); }

    @Override
    public void onNext(Object value) { Log.d(TAG,"on next, input value:<<"+value.toString()+">>  thread name >>"+Thread.currentThread().getName());}

    @Override
    public void onError(Throwable e) { Log.d(TAG,"error >>"+e.toString()); }

    @Override
    public void onComplete() {
        Log.d(TAG,"onCompleted  thread name >> "+Thread.currentThread().getName());
        tvRxJava = (TextView) findViewById(R.id.tv_rxjava); //update the reference of tvRxJava.
        tvRxJava.setText("process executed..."); //this line does not change the value of the TextView tvRxJava.
    }
};
</code>```

This works fine, with no device rotation, but if you rotate the device while doLongNetworkOperation is running in the background the TextView tvRxJava does not update value.
not even with a new inject.

```<code>tvRxJava = (TextView) findViewById(R.id.tv_rxjava);
</code>```

How do you manage orientation change in android with RxJava2??

This is my gradle dep:

```<code>compile 'io.reactivex.rxjava2:rxjava:2.0.5'//rxjava2
compile 'io.reactivex.rxjava2:rxandroid:2.0.1' //rxjava2 for android
</code>```

答:
Normally I would like to have cache mechanism for the observable in order to get back the result again in case of configuration changes (which forces activity recreation).
I am sharing two very good article which will give you very clear picture, in order to solve this problem.

First

Second

I am currently following the second approach in my application.

Body:
I'm new at this library, so if you got any tips or suggestions are more than welcome.
I got RxJava2 running and executing a longNetworkOperation fake method, the flow is this:

Create the observable:  Observable.just("str1")

Change the execution thread: .subscribeOn(Schedulers.newThread())

Implement the map interface which will execute the LongRunningProcess:

.map(new Function<String, String>() {
     @Override
     public String apply(String cad){ // cad is the input value
            Log.d(TAG,"long operation in thread: "+Thread.currentThread().getName()); //output thread name
            return " longNetworkOperation result => "+doLongNetworkOperation(); //here we do the background operations
            }})

Get the results in Main Thread: .observeOn(AndroidSchedulers.mainThread())

Add the observer which get notified for the results: .subscribe(observer);

And the observer:

 Observer observer = new Observer() {
    @Override
    public void onSubscribe(Disposable d) { Log.d(TAG,"onSubscribe, thread name >> "+Thread.currentThread().getName()); }

    @Override
    public void onNext(Object value) { Log.d(TAG,"on next, input value:<<"+value.toString()+">>  thread name >>"+Thread.currentThread().getName());}

    @Override
    public void onError(Throwable e) { Log.d(TAG,"error >>"+e.toString()); }

    @Override
    public void onComplete() {
        Log.d(TAG,"onCompleted  thread name >> "+Thread.currentThread().getName());
        tvRxJava = (TextView) findViewById(R.id.tv_rxjava); //update the reference of tvRxJava.
        tvRxJava.setText("process executed..."); //this line does not change the value of the TextView tvRxJava.
    }
};

This works fine, with no device rotation, but if you rotate the device while doLongNetworkOperation is running in the background the TextView tvRxJava does not update value.
not even with a new inject.

tvRxJava = (TextView) findViewById(R.id.tv_rxjava);

How do you manage orientation change in android with RxJava2??

This is my gradle dep:

compile 'io.reactivex.rxjava2:rxjava:2.0.5'//rxjava2
compile 'io.reactivex.rxjava2:rxandroid:2.0.1' //rxjava2 for android


答:
Change your protocol to use properties instead of functions. That way implementing struct/class can decide to have it implemented as real property or computed one.</p>

```<code>protocol PlayableMediaItem {
    var title: String { get }
    var albumArt: UIImage { get }
    var audioFileURL: URL { get }
}
</code>```

Title: How can I define a Swift Protocol so that the implementation can be a property _or_ a method?

Body:
Change your protocol to use properties instead of functions. That way implementing struct/class can decide to have it implemented as real property or computed one.

protocol PlayableMediaItem {
    var title: String { get }
    var albumArt: UIImage { get }
    var audioFileURL: URL { get }
}


问:
transforming a string into a list in python
For example, I have a string = "[1,2,3,4]" and I want to only have the [1,2,3,4], I tried doing list(mystring) but it gives me:

```<code>['[', '1', ',', '2', ',', '3', ',', '4', ']']
</code>```

I just want to chop off the "" of the string "[1,2,3,4]".

the output I want can be made with the print, it will output:

```<code>[1,2,3,4]
</code>```

but I don't know how to get that output into a variable, can someone help?

答:
You can use list comprehension and check for digits, like:

```<code> s = "[1,2,3,4]"
 lst = [int(x) for x in s if x.isdigit()]
</code>```

output:

```<code>[1, 2, 3, 4]
</code>```

Body:
For example, I have a string = "[1,2,3,4]" and I want to only have the [1,2,3,4], I tried doing list(mystring) but it gives me:

['[', '1', ',', '2', ',', '3', ',', '4', ']']

I just want to chop off the "" of the string "[1,2,3,4]".

the output I want can be made with the print, it will output:

[1,2,3,4]

but I don't know how to get that output into a variable, can someone help?

Body:
You can use list comprehension and check for digits, like:

 s = "[1,2,3,4]"
 lst = [int(x) for x in s if x.isdigit()]

output:

[1, 2, 3, 4]


问:
Change admin password in drupal 7
I am using built in Drupal 7 user module, fore user registration, forgot-your-password-emails and all that stuff.

I have forgotten my admin password. I have access to my website which is hosted on 1and1.com and also have access to mysql?

Is it possible to change password or email address through SQL so that I can access the admin page?

If it possible how? Can you somebody help me with this?

Thanks!

答:
Tested and it works!

With the access to the table "users"  in your Database via PhpMyAdmin for example (i.e. this table can have a prefix that you have already mentionned during the Drupal installation part, so yourPrefix_ can be your project's name as mywebsitename_, and in this case you'll have mywebsitename_users).

You should alter the "pass" column associated with the "uid" column with the value 1 (i.e 1 for the admin user account).

As the encrypted value for the password: Admin_12345 is =>

$S$DifCVXg9tNtHadziyyQJQVLAaZzW5EgS6OjR56D.mk8MpNQs1II2

You can accede to your admin account after replacing the old hashed password value stored in your database that you have totally forgotten.

Don't forget to change the password: Admin_12345 after you accede to your account with an other one.

Title: Change admin password in drupal 7


问:
understanding model defined in torch7 deep learning framework
I am trying to understand a deep learning model defined in torch7 framework here: code

I am new to deep learning and torch7 framework. I have tried reading the documentation of nn graph module of torch, however, I don't understand what this line represents:

```<code>local e1 = - nn.SpatialConvolution(input_nc, ngf, 4, 4, 2, 2, 1, 1)
</code>```

What is happening with = -?

The torch tutorials which I've seen define a model using a simple straight-forward way:

```<code>...
model = nn.Sequential()
model:add(...)
...
</code>```

However, the code I'm referring to, uses = - and - operations which I don't understand; neither I can find any tutorial which defines a model in this manner. Please help me to understand the code.

答:
This is an alternative syntax to write models using the nngraph package. You have basically two possibilities, either using the __call__ operator (()) or using the __unm__ (unary multiplication, placing a - sign before an expression) and the __sub__ (binary subtraction -) to make "your code looks like a data flow".

Have a look at the documentation of the nngraph package, this could help you understanding the syntax: https://github.com/torch/nngraph#two-hidden-layers-mlp

Body:
I am trying to understand a deep learning model defined in torch7 framework here: code

I am new to deep learning and torch7 framework. I have tried reading the documentation of nn graph module of torch, however, I don't understand what this line represents:

local e1 = - nn.SpatialConvolution(input_nc, ngf, 4, 4, 2, 2, 1, 1)

What is happening with = -?

The torch tutorials which I've seen define a model using a simple straight-forward way:

...
model = nn.Sequential()
model:add(...)
...

However, the code I'm referring to, uses = - and - operations which I don't understand; neither I can find any tutorial which defines a model in this manner. Please help me to understand the code.