问:
Sqlite Query to get the details
Hi Let the table be as,

```<code>id      Name
1102    n_1102/abc
1102    n_1102/xyz
1102    n_1102/pqr
</code>```

Please help to get the following data from the table,

for each id, we have many names, but from the name, the first part ie. before '/' is common for all, so if i query as

"Select Name from table where id = 1102", i will get all the details, but i want only the first common part in all the names.

i.e by executing a query for id = 1102, then i should i get name as n_1102 as a single row in the result set.

答:
It sounds like you want to select the portion of the name occurring before the backslash for a given id, but you only want to return one of them.  You can try the following query:

```<code>SELECT DISTINCT
    SUBSTR(name, 1, INSTR(name, '/') - 1)
FROM yourTable
WHERE id = 1102
</code>```

Title: Sqlite Query to get the details

Body:
Hi Let the table be as,

id      Name
1102    n_1102/abc
1102    n_1102/xyz
1102    n_1102/pqr

Please help to get the following data from the table,

for each id, we have many names, but from the name, the first part ie. before '/' is common for all, so if i query as

"Select Name from table where id = 1102", i will get all the details, but i want only the first common part in all the names.

i.e by executing a query for id = 1102, then i should i get name as n_1102 as a single row in the result set.

Body:
It sounds like you want to select the portion of the name occurring before the backslash for a given id, but you only want to return one of them.  You can try the following query:

SELECT DISTINCT
    SUBSTR(name, 1, INSTR(name, '/') - 1)
FROM yourTable
WHERE id = 1102


来源: stackexchange

问:
Select-String in Powershell only displaying part of the line from a text file, need it to display whole thing
I am trying to write a simple PS script to check large .txt log files for a short string: "SRVE0242I:"

```<code>$lines = Select-String -Path $logDir -Pattern "SRVE0242I:" | Select-Object line | Out-String
</code>```

On output though, it only displays the following:

Line

[28/06/17 13:48:27:839] 00000020 ServletWrappe I   SRVE0242I: [User] [User] [com_xxxxxxx_...

And not the full line. Is there a limit to how many characters this pulls? I can't find any info on any restrictions for the Select-String cmdlet. Is there a better way to do this so that I don't a) pull the heading "Line" in my list of lines (Don't really want to create table formatting for such a simple output) and b) get the whole line when I pull the info?

答:
You are seeing it like this because it's displaying the Line property using the default Format-Table view and shortening it to the width of the console.

Do this instead:

```<code>$lines = Select-String -Path $logDir -Pattern "SRVE0242I:" | Select-Object -ExpandProperty line
</code>```

This returns the value of the Line property as a string to the $lines variable. You don't need to use Out-String.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to write a simple PS script to check large .txt log files for a short string: "SRVE0242I:"

$lines = Select-String -Path $logDir -Pattern "SRVE0242I:" | Select-Object line | Out-String

On output though, it only displays the following:

Line

[28/06/17 13:48:27:839] 00000020 ServletWrappe I   SRVE0242I: [User] [User] [com_xxxxxxx_...

And not the full line. Is there a limit to how many characters this pulls? I can't find any info on any restrictions for the Select-String cmdlet. Is there a better way to do this so that I don't a) pull the heading "Line" in my list of lines (Don't really want to create table formatting for such a simple output) and b) get the whole line when I pull the info?

Body:
You are seeing it like this because it's displaying the Line property using the default Format-Table view and shortening it to the width of the console.

Do this instead:

$lines = Select-String -Path $logDir -Pattern "SRVE0242I:" | Select-Object -ExpandProperty line

This returns the value of the Line property as a string to the $lines variable. You don't need to use Out-String.


问:
Wiki API unable to parse JSON
I'm trying to access Wiki api with below query:

https://en.wikipedia.org/w/api.php?action=query&generator=search&gsrsearch=india&gsrnamespace=0&gsrlimit=5&origin=*&prop=extracts&exchars=200&exlimit=max&explaintext=1&exintro=1

I'm getting response, but when I'm using JSON.parse to parse response Mozilla is displaying an error:

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

答:
Try this:

https://en.wikipedia.org/w/api.php?action=query&generator=search&gsrsearch=india&gsrnamespace=0&gsrlimit=5&origin=*&prop=extracts&exchars=200&exlimit=max&explaintext=1&exintro=1&format=json

Add the format=json query parameter. Otherwise you're getting HTML with embedded JSON

Title: Wiki API unable to parse JSON


问:
Javascript Calculation issue when there is a Space during calculating input value

function divideBy() {
  var w = document.getElementById("first").value;
  var x = document.getElementById("second").value;
  var y = w / x;
  y = y.toFixed(2);
  var z = y;
  document.getElementById("answer").innerHTML = z;
  var a = document.getElementById("first1").value;
  var b = document.getElementById("second1").value;
  var c = a / b;
  var d = c;
  d = d.toFixed(2);
  var e = d
  document.getElementById("answer1").innerHTML = e;
  document.getElementById('modal').style.visibility = 'hidden';
  document.getElementById('modal1').style.visibility = 'hidden';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><tr>
  <td class="normal">
    <div align="right">SGST @ 9% :</div>
  </td>
  <td nowrap class="normal">
    <div align="right">
      <div id="divCheckbox1" style="display: none;">
        <input type="number" step=0.001 id="first" value=1 000>
        <input type="number" step=0.001 id="second" value=2 .0>
      </div>
      <button type="button" id="modal1" onclick="divideBy()"></button>
      <span id="answer"></span>
      <span style="display:inline-block; width: 5;"></span>
  </td>
  <tr>
    <td class="normal">
      <div align="right">CGST @ 9% :</div>
    </td>
    <td nowrap class="normal">
      <div align="right">
        <div id="divCheckbox" style="display: none;">
          <input type="number" step=0.001 id="first1" value=1 000>
          <input type="number" step=0.001 id="second1" value=2 .0>
        </div>
        <button type="button" id="modal" onclick="divideBy()"></button>
        <span id=answer1></span>
        <span style="display:inline-block; width: 5;"></span>
    </td></code>```

答:
Since you said its number,its just taking the value before space.

Html:

```<code><tr>
<td class="normal">
<div align="right">SGST @ 9% :</div>
</td>
<td nowrap class="normal">
<div align="right">
  <div id="divCheckbox1" style="display: none;">
    <input step=0.001 id="first" value="1 000">
    <input step=0.001 id="second" value="2 .0">
  </div>
  <button type="button" id="modal1" onclick="divideBy()"></button>
  <span id="answer"></span>
  <span style="display:inline-block; width: 5;"></span>
</td>
</td>
</tr>
<tr>
<td class="normal">
  <div align="right">CGST @ 9% :</div>
</td>
<td nowrap class="normal">
  <div align="right">
    <div id="divCheckbox" style="display: none;">
      <input step=0.001 id="first1" value="1 000">
      <input step=0.001 id="second1" value="2 .0">
    </div>
    <button type="button" id="modal" onclick="divideBy()"></button>
    <span id=answer1></span>
    <span style="display:inline-block; width: 5;"></span>
</td>
</td>
</tr>
</code>```

JS:

```<code>function divideBy() {
var w = document.getElementById("first").value ;
var x = document.getElementById("second").value;
var y = w.replace(" ","") / x.replace(" ","");
y = y.toFixed(2);
var z = y;
document.getElementById("answer").innerHTML = z;
var a = document.getElementById("first1").value;
var b = document.getElementById("second1").value;
var c = a.replace(" ","") / b.replace(" ","");
var d = c;
d = d.toFixed(2);
var e = d
document.getElementById("answer1").innerHTML = e;
document.getElementById('modal').style.visibility = 'hidden';
document.getElementById('modal1').style.visibility = 'hidden';
}
</code>```

Body:
function divideBy() {
  var w = document.getElementById("first").value;
  var x = document.getElementById("second").value;
  var y = w / x;
  y = y.toFixed(2);
  var z = y;
  document.getElementById("answer").innerHTML = z;
  var a = document.getElementById("first1").value;
  var b = document.getElementById("second1").value;
  var c = a / b;
  var d = c;
  d = d.toFixed(2);
  var e = d
  document.getElementById("answer1").innerHTML = e;
  document.getElementById('modal').style.visibility = 'hidden';
  document.getElementById('modal1').style.visibility = 'hidden';
}

SGST @ 9% :

        <input type="number" step=0.001 id="first" value=1 000>
        <input type="number" step=0.001 id="second" value=2 .0>

      <button type="button" id="modal1" onclick="divideBy()"></button>

CGST @ 9% :

          <input type="number" step=0.001 id="first1" value=1 000>
          <input type="number" step=0.001 id="second1" value=2 .0>

        <button type="button" id="modal" onclick="divideBy()"></button>

Body:
Since you said its number,its just taking the value before space.

Html:

<tr>
<td class="normal">
<div align="right">SGST @ 9% :</div>
</td>
<td nowrap class="normal">
<div align="right">
  <div id="divCheckbox1" style="display: none;">
    <input step=0.001 id="first" value="1 000">
    <input step=0.001 id="second" value="2 .0">
  </div>
  <button type="button" id="modal1" onclick="divideBy()"></button>
  <span id="answer"></span>
  <span style="display:inline-block; width: 5;"></span>
</td>
</td>
</tr>
<tr>
<td class="normal">
  <div align="right">CGST @ 9% :</div>
</td>
<td nowrap class="normal">
  <div align="right">
    <div id="divCheckbox" style="display: none;">
      <input step=0.001 id="first1" value="1 000">
      <input step=0.001 id="second1" value="2 .0">
    </div>
    <button type="button" id="modal" onclick="divideBy()"></button>
    <span id=answer1></span>
    <span style="display:inline-block; width: 5;"></span>
</td>
</td>
</tr>

JS:

function divideBy() {
var w = document.getElementById("first").value ;
var x = document.getElementById("second").value;
var y = w.replace(" ","") / x.replace(" ","");
y = y.toFixed(2);
var z = y;
document.getElementById("answer").innerHTML = z;
var a = document.getElementById("first1").value;
var b = document.getElementById("second1").value;
var c = a.replace(" ","") / b.replace(" ","");
var d = c;
d = d.toFixed(2);
var e = d
document.getElementById("answer1").innerHTML = e;
document.getElementById('modal').style.visibility = 'hidden';
document.getElementById('modal1').style.visibility = 'hidden';
}


问:
URL regenerate in magento 2
I am developing my website in Magento 2, I need URL regenerate for products after I changed the category URL.

URL's are not changing for existing products.

Ex:

Category URL's:
New URL:
 http://test.com/jewellery-collections/gold-jewellery/gold-rings
Old URL:
 http://test.com/collections/gold/rings

Product URL's:
 http://test.com/collections/gold/rings/midas-bloom

but the URL should be
 http://test.com/jewellery-collections/gold-jewellery/gold-ringsmidas-bloom

So, Product URL's should be regenerate as per new category URL

答:
A quite simple solution is to use a ready to run Magento 2 module which does exactly the work of an rewrite indexer. You can call this regeneration by code or from command line. A better solution is to do it by code in your own importer module. The regeneration is quite simple

```<code>foreach($list as $product) {
if($store_id === Store::DEFAULT_STORE_ID)
    $product->setStoreId($store_id);
$this->urlPersist->deleteByData([
    UrlRewrite::ENTITY_ID => $product->getId(),
    UrlRewrite::ENTITY_TYPE => ProductUrlRewriteGenerator::ENTITY_TYPE,
    UrlRewrite::REDIRECT_TYPE => 0,
    UrlRewrite::STORE_ID => $store_id
]);
try {
    $this->urlPersist->replace(
        $this->productUrlRewriteGenerator->generate($product)
    );
} catch(\Exception $e) {
    $out->writeln('<error>Duplicated url for '. $product->getId() .'</error>');
} }
</code>```

As you can see Magento 2 offers you a model for regenerate url rewrites \Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator (productUrlRewriteGenerator) which you can inject into your model. This generated url rewrite can be replaced by \Magento\UrlRewrite\Model\UrlPersistInterface (urlPersist). You can run this in a loop for all products after import or for each single product after a change.

Or you can check out https://github.com/Iazel/magento2-regenurl

Title: URL regenerate in magento 2

Body:
A quite simple solution is to use a ready to run Magento 2 module which does exactly the work of an rewrite indexer. You can call this regeneration by code or from command line. A better solution is to do it by code in your own importer module. The regeneration is quite simple

foreach($list as $product) {
if($store_id === Store::DEFAULT_STORE_ID)
    $product->setStoreId($store_id);
$this->urlPersist->deleteByData([
    UrlRewrite::ENTITY_ID => $product->getId(),
    UrlRewrite::ENTITY_TYPE => ProductUrlRewriteGenerator::ENTITY_TYPE,
    UrlRewrite::REDIRECT_TYPE => 0,
    UrlRewrite::STORE_ID => $store_id
]);
try {
    $this->urlPersist->replace(
        $this->productUrlRewriteGenerator->generate($product)
    );
} catch(\Exception $e) {
    $out->writeln('<error>Duplicated url for '. $product->getId() .'</error>');
} }

As you can see Magento 2 offers you a model for regenerate url rewrites \Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator (productUrlRewriteGenerator) which you can inject into your model. This generated url rewrite can be replaced by \Magento\UrlRewrite\Model\UrlPersistInterface (urlPersist). You can run this in a loop for all products after import or for each single product after a change.

Or you can check out https://github.com/Iazel/magento2-regenurl


问:
Qlik CURL With Authentication
I'm trying to get authenticated with Qlik using php and not having much luck.
But I found this code snippet online and just wanting to know how I could achieve this same type of request using CURL and PHP.

```<code>$objHTTP = ObjCreate("Msxml2.XMLHTTP.6.0")
$objHTTP.open ("GET", "http://localhost/qrs/app/?Xrfkey=ABDHEFUELPYRVGLK", False,"my usernamer","my password")
$objHTTP.setRequestHeader("X-Qlik-Xrfkey","ABDHEFUELPYRVGLK")
$objHTTP.send()
$data = $objHTTP.responseText
</code>```

This must be a GET request.

答:
Seem it use GET request with basic authentication.
Please try this

```<code><?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://localhost/qrs/app/?Xrfkey=ABDHEFUELPYRVGLK');
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-Qlik-Xrfkey: ABDHEFUELPYRVGLK"));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

echo $result;
</code>```

Title: Qlik CURL With Authentication

Body:
I'm trying to get authenticated with Qlik using php and not having much luck.
But I found this code snippet online and just wanting to know how I could achieve this same type of request using CURL and PHP.

$objHTTP = ObjCreate("Msxml2.XMLHTTP.6.0")
$objHTTP.open ("GET", "http://localhost/qrs/app/?Xrfkey=ABDHEFUELPYRVGLK", False,"my usernamer","my password")
$objHTTP.setRequestHeader("X-Qlik-Xrfkey","ABDHEFUELPYRVGLK")
$objHTTP.send()
$data = $objHTTP.responseText

This must be a GET request.

Body:
Seem it use GET request with basic authentication.
Please try this

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://localhost/qrs/app/?Xrfkey=ABDHEFUELPYRVGLK');
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-Qlik-Xrfkey: ABDHEFUELPYRVGLK"));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

echo $result;


问:
JavaScript: Case Insenstive Array Search
I have a case like,

```<code>var givenTerms = [Tree, Plant, River, Ocean, Place, Sky];
var check = 'SKY';
if ($.inArray(check, givenTerms()) !== -1) {
    // say it is present in givenTerms
}
</code>```

This case fails as it is case sensitive. I could not use givenTerms.toLowercase() as it is an array and not a single term. Is there any other possibility to make this if case true.

Any suggestion could be helpful.

答:
First you need to update/Create a new array for matching string. Here I update the original collection that match search term. Check the result here</p>

```<code>var givenTerms = [Tree, Plant, River, Ocean, Place, Sky];
var check = 'SKY';
givenTerms = ((givenTerms.toString()).toUpperCase()).split(",");
if (givenTerms.indexOf(check) >= 0) {
    alert(check +" found at "+ givenTerms.indexOf(check));
}
</code>```

Body:
I have a case like,

var givenTerms = [Tree, Plant, River, Ocean, Place, Sky];
var check = 'SKY';
if ($.inArray(check, givenTerms()) !== -1) {
    // say it is present in givenTerms
}

This case fails as it is case sensitive. I could not use givenTerms.toLowercase() as it is an array and not a single term. Is there any other possibility to make this if case true.

Any suggestion could be helpful.

Body:
First you need to update/Create a new array for matching string. Here I update the original collection that match search term. Check the result here

var givenTerms = [Tree, Plant, River, Ocean, Place, Sky];
var check = 'SKY';
givenTerms = ((givenTerms.toString()).toUpperCase()).split(",");
if (givenTerms.indexOf(check) >= 0) {
    alert(check +" found at "+ givenTerms.indexOf(check));
}


问:
Wordpress loading fine first time, but fails loading the second time
I have a wordpress site which loads perfectly the first time, however, if I reload it in any browser, it gives me all sorts of errors such as these ones in FireFox:

```<code>TypeError: $.browser is undefined
ReferenceError: Backbone is not defined
ReferenceError: _ is not defined
or
TypeError: document.body is null
</code>```

and this in Chrome, IE and Opera:

```<code>VM236:1 Uncaught TypeError: Cannot read property 'msie' of undefined
    at eval (eval at <anonymous> (autoptimize_2389e63….js:8), <anonymous>:1:633)
    at eval (eval at <anonymous> (autoptimize_2389e63….js:8), <anonymous>:1:12848)
    at autoptimize_2389e63….js:8
</code>```

I have the autoptimize and above the fold plugins installed. The site loads fine despite of the errors, but a soliloqui slider fails.
If I disable the Optimize Javascript Loading from the Above the fold plugin, the errors disappear, but that beats the purpose.

Please help!

答:
I think your Optimize Javascript Loading uses $.browser...
The $.browser method has been removed as of jQuery 1.9.

jQuery.browser() removed

The jQuery.browser() method has been deprecated since jQuery 1.3 and is removed in 1.9. If needed, it is available as part of the jQuery Migrate plugin. We recommend using feature detection with a library such as Modernizr.

— jQuery Core 1.9 Upgrade Guide.

As stated in the Upgrade Guide you can try using the jQuery Migrate plugin to restore this functionality and let jQuery Tools work.

You can check out this solution. It's pretty straightforward, just copy and paste the following lines of code in header.

```<code><script type="text/javascript">
    jQuery.browser = {};
    (function () {
        jQuery.browser.msie = false;
        jQuery.browser.version = 0;
        if (navigator.userAgent.match(/MSIE ([0-9]+)\./)) {
           jQuery.browser.msie = true;
           jQuery.browser.version = RegExp.$1;
        }
    })();
</script>
</code>```

just try above function...

Body:
I have a wordpress site which loads perfectly the first time, however, if I reload it in any browser, it gives me all sorts of errors such as these ones in FireFox:

TypeError: $.browser is undefined
ReferenceError: Backbone is not defined
ReferenceError: _ is not defined
or
TypeError: document.body is null

and this in Chrome, IE and Opera:

VM236:1 Uncaught TypeError: Cannot read property 'msie' of undefined
    at eval (eval at <anonymous> (autoptimize_2389e63….js:8), <anonymous>:1:633)
    at eval (eval at <anonymous> (autoptimize_2389e63….js:8), <anonymous>:1:12848)
    at autoptimize_2389e63….js:8

I have the autoptimize and above the fold plugins installed. The site loads fine despite of the errors, but a soliloqui slider fails.
If I disable the Optimize Javascript Loading from the Above the fold plugin, the errors disappear, but that beats the purpose.

Please help!

Body:
I think your Optimize Javascript Loading uses $.browser...
The $.browser method has been removed as of jQuery 1.9.

jQuery.browser() removed

The jQuery.browser() method has been deprecated since jQuery 1.3 and is removed in 1.9. If needed, it is available as part of the jQuery Migrate plugin. We recommend using feature detection with a library such as Modernizr.

— jQuery Core 1.9 Upgrade Guide.

As stated in the Upgrade Guide you can try using the jQuery Migrate plugin to restore this functionality and let jQuery Tools work.

You can check out this solution. It's pretty straightforward, just copy and paste the following lines of code in header.

<script type="text/javascript">
    jQuery.browser = {};
    (function () {
        jQuery.browser.msie = false;
        jQuery.browser.version = 0;
        if (navigator.userAgent.match(/MSIE ([0-9]+)\./)) {
           jQuery.browser.msie = true;
           jQuery.browser.version = RegExp.$1;
        }
    })();
</script>

just try above function...


答:
There is! Long story short, Select-Object is doing the truncating here. Here's one way to get the first untruncated line in a Select-String output

```<code>$(Select-String -Path $logDir -Pattern "SRVE0242I:")[0].Line
</code>```

When you run into something like this, you can break down the individual steps to determine what's happening by piping things to Get-Member. Here's what's happening in the code above:

```<code>Select-String <# args #> | Get-Member
</code>```

Select-String gives us a MatchInfo object, which (as you've correctly determined) has a 'Line' property. When run on it's own, Select-String will actually spit out all the information you're looking for, and will not truncate it by default (at least, on v6.0.0-beta). It does give you an array of MatchInfo objects if it finds multiple matches, so you have to index into that array if you just want the first one (like I did above).

```<code>Select-String <# args #> | Select-Object Line | Get-Member
</code>```

Select-Object applies PowerShell's default formatting for objects which, in most cases, will truncate your output for easier viewing. For objects with a bunch of members (like a MatchInfo object), it will try to do one per line by default.

```<code>Select-String <# args #> | Select-Object Line | Out-String | Get-Member
</code>```

Out-String directly translates it's input to a string. That is, rather than trying to cast something to a string or pull a string Property out of an object that's passed to it, it just changes whatever it receives into an object. In this case, it turns the already-formatted MatchInfo output into a string. Nothing happens to the output on the terminal, but Get-Member will reveal a String rather than a MatchInfo object.

It's not directly relevant here, but if you're interested in modifying the default formatting, it's governed by the types.ps1xml file.

Title: Select-String in Powershell only displaying part of the line from a text file, need it to display whole thing

Body:
There is! Long story short, Select-Object is doing the truncating here. Here's one way to get the first untruncated line in a Select-String output

$(Select-String -Path $logDir -Pattern "SRVE0242I:")[0].Line

When you run into something like this, you can break down the individual steps to determine what's happening by piping things to Get-Member. Here's what's happening in the code above:

Select-String <# args #> | Get-Member

Select-String gives us a MatchInfo object, which (as you've correctly determined) has a 'Line' property. When run on it's own, Select-String will actually spit out all the information you're looking for, and will not truncate it by default (at least, on v6.0.0-beta). It does give you an array of MatchInfo objects if it finds multiple matches, so you have to index into that array if you just want the first one (like I did above).

Select-String <# args #> | Select-Object Line | Get-Member

Select-Object applies PowerShell's default formatting for objects which, in most cases, will truncate your output for easier viewing. For objects with a bunch of members (like a MatchInfo object), it will try to do one per line by default.

Select-String <# args #> | Select-Object Line | Out-String | Get-Member

Out-String directly translates it's input to a string. That is, rather than trying to cast something to a string or pull a string Property out of an object that's passed to it, it just changes whatever it receives into an object. In this case, it turns the already-formatted MatchInfo output into a string. Nothing happens to the output on the terminal, but Get-Member will reveal a String rather than a MatchInfo object.

It's not directly relevant here, but if you're interested in modifying the default formatting, it's governed by the types.ps1xml file.


问:
How do I schedule a cron job to run every hour and a half?

Possible Duplicate:

  How can I set cron to run certain commands every one and a half hours?

I know that every two hours is:

```<code>* */2 * * * command-to-run
</code>```

but how do I schedule a cron job to run every hour and a half?

答: I think you would need two cronjobs that run every three hours and are offset by 1.5 hours.</p>

Body:
Possible Duplicate:

  How can I set cron to run certain commands every one and a half hours?

I know that every two hours is:

* */2 * * * command-to-run

but how do I schedule a cron job to run every hour and a half?

ContentLicense: CC BY-SA 2.5


答:
Add finally format JSON string in url

https://en.wikipedia.org/w/api.php?action=query&generator=search&gsrsearch=india&gsrnamespace=0&gsrlimit=5&origin=%2A&prop=extracts&exchars=200&exlimit=max&explaintext=1&exintro=1&format=json

Title: Wiki API unable to parse JSON

Body:
I'm trying to access Wiki api with below query:

https://en.wikipedia.org/w/api.php?action=query&generator=search&gsrsearch=india&gsrnamespace=0&gsrlimit=5&origin=*&prop=extracts&exchars=200&exlimit=max&explaintext=1&exintro=1

I'm getting response, but when I'm using JSON.parse to parse response Mozilla is displaying an error:

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data


问:
Want ajax multiple file upload on my button click event
Here is my .aspx page code

```<code> <form id="form1" runat="server">
    <asp:ToolkitScriptManager runat="server">
    </asp:ToolkitScriptManager>
    <asp:AjaxFileUpload ID="AjaxFileUpload1" runat="server"
        Width="400px" OnUploadComplete="OnUploadComplete" Mode="Auto" />
    <asp:Button ID="abc" runat="server" Text="Button" OnClientClick="$('.ajax__fileupload_uploadbutton').trigger('click');" OnClick="abc_Click" />
</form>
</code>```

.aspx.cs code is

```<code> protected void OnUploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
    {
        string fileName = Path.GetFileName(e.FileName);
        AjaxFileUpload1.SaveAs(Server.MapPath("~/uploads/" + fileName));
    }
    protected void abc_Click(object sender, EventArgs e)
    {
    // need file upload on this click and also need to store some outer data in this click event
    }
</code>```

How can I achieve ajax multiple file upload on my own button click event as I need to upload multiple file and also other some data on this button click

I have placed control html and the .cs code which is working well and is uploading multiple images with event OnUploadComplete but I need to upload images on abc_Click event so that on single click I can upload images as well as I can save data too

答:
There are lots of ways to upload multiple files in Asp.Net.
You Should use following method
HTML:

```<code> <asp:ScriptManager runat="server"></asp:ScriptManager>
<ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1" runat="server" Width="500px" AllowedFileTypes="jpg,jpeg,png" MaximumNumberOfFiles="4" OnUploadComplete="AjaxFileUpload1_UploadComplete" />
</code>```

C# Event

```<code>using System;
using System.IO;

 protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
string fileName = Path.GetFileName(e.FileName);
AjaxFileUpload1.SaveAs(Server.MapPath("~/uploads/" + fileName));
}
</code>```

Or you can use JQuery to upload Multiple files like below.
Download JQuery.js and jQuery.MultiFile.js from JQuery multiple-file-upload plugin

Html:

```<code><asp:FileUpload ID="FileUploadJquery" runat="server" class="multi"/>

<asp:Button ID="btnJqueryMultipleFiles" runat="server" Text="Upload Files Using Jquery" onclick="btnJqueryMultipleFiles_Click"/>
</div>
</code>```

C# Event

```<code>protected void btnUpload_Click(object sender, EventArgs e)
    {
        HttpFileCollection multipleFiles = Request.Files;
        for (int fileCount = 0; fileCount < multipleFiles.Count; fileCount++)
        {
            HttpPostedFile uploadedFile = multipleFiles[fileCount];
            string fileName = Path.GetFileName(uploadedFile.FileName);
            if (uploadedFile.ContentLength > 0 )
            {
                uploadedFile.SaveAs(Server.MapPath("~/Files/") + fileName);
                lblMessage.Text += fileName + "Saved <br>";
            }
        }
   }
</code>```

Body:
Here is my .aspx page code

 <form id="form1" runat="server">
    <asp:ToolkitScriptManager runat="server">
    </asp:ToolkitScriptManager>
    <asp:AjaxFileUpload ID="AjaxFileUpload1" runat="server"
        Width="400px" OnUploadComplete="OnUploadComplete" Mode="Auto" />
    <asp:Button ID="abc" runat="server" Text="Button" OnClientClick="$('.ajax__fileupload_uploadbutton').trigger('click');" OnClick="abc_Click" />
</form>

.aspx.cs code is

 protected void OnUploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
    {
        string fileName = Path.GetFileName(e.FileName);
        AjaxFileUpload1.SaveAs(Server.MapPath("~/uploads/" + fileName));
    }
    protected void abc_Click(object sender, EventArgs e)
    {
    // need file upload on this click and also need to store some outer data in this click event
    }

How can I achieve ajax multiple file upload on my own button click event as I need to upload multiple file and also other some data on this button click

I have placed control html and the .cs code which is working well and is uploading multiple images with event OnUploadComplete but I need to upload images on abc_Click event so that on single click I can upload images as well as I can save data too

Body:
There are lots of ways to upload multiple files in Asp.Net.
You Should use following method
HTML:

 <asp:ScriptManager runat="server"></asp:ScriptManager>
<ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1" runat="server" Width="500px" AllowedFileTypes="jpg,jpeg,png" MaximumNumberOfFiles="4" OnUploadComplete="AjaxFileUpload1_UploadComplete" />

C# Event

using System;
using System.IO;

 protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
string fileName = Path.GetFileName(e.FileName);
AjaxFileUpload1.SaveAs(Server.MapPath("~/uploads/" + fileName));
}

Or you can use JQuery to upload Multiple files like below.
Download JQuery.js and jQuery.MultiFile.js from JQuery multiple-file-upload plugin

Html:

<asp:FileUpload ID="FileUploadJquery" runat="server" class="multi"/>

<asp:Button ID="btnJqueryMultipleFiles" runat="server" Text="Upload Files Using Jquery" onclick="btnJqueryMultipleFiles_Click"/>
</div>

C# Event

protected void btnUpload_Click(object sender, EventArgs e)
    {
        HttpFileCollection multipleFiles = Request.Files;
        for (int fileCount = 0; fileCount < multipleFiles.Count; fileCount++)
        {
            HttpPostedFile uploadedFile = multipleFiles[fileCount];
            string fileName = Path.GetFileName(uploadedFile.FileName);
            if (uploadedFile.ContentLength > 0 )
            {
                uploadedFile.SaveAs(Server.MapPath("~/Files/") + fileName);
                lblMessage.Text += fileName + "Saved <br>";
            }
        }
   }


问:
Swift add icon/image in UITextField
I would like to add icon/image in UITextField. The icon/image should be left to placeholder.

I tried this:

```<code>var imageView = UIImageView();
var image = UIImage(named: "email.png");
imageView.image = image;
emailField.leftView = imageView;
</code>```

Thanks.

答:
I created a simple IBDesignable. Use it however u like. Just make your UITextField confirm to this class.</p>

```<code>import UIKit

@IBDesignable
class RoundTextField : UITextField {
    @IBInspectable var cornerRadius : CGFloat = 0{
        didSet{
            layer.cornerRadius = cornerRadius
            layer.masksToBounds = cornerRadius > 0
        }
    }

    @IBInspectable var borderWidth : CGFloat = 0 {
        didSet{
            layer.borderWidth = borderWidth
        }
    }

    @IBInspectable var borderColor : UIColor? {
        didSet {
            layer.borderColor = borderColor?.cgColor
        }
    }

    @IBInspectable var bgColor : UIColor? {
        didSet {
            backgroundColor = bgColor
        }
    }

    @IBInspectable var leftImage : UIImage? {
        didSet {
            if let image = leftImage{
                leftViewMode = .always
                let imageView = UIImageView(frame: CGRect(x: 20, y: 0, width: 20, height: 20))
                imageView.image = image
                imageView.tintColor = tintColor
                let view = UIView(frame : CGRect(x: 0, y: 0, width: 25, height: 20))
                view.addSubview(imageView)
                leftView = view
            }else {
                leftViewMode = .never
            }

        }
    }

    @IBInspectable var placeholderColor : UIColor? {
        didSet {
            let rawString = attributedPlaceholder?.string != nil ? attributedPlaceholder!.string : ""
            let str = NSAttributedString(string: rawString, attributes: [NSForegroundColorAttributeName : placeholderColor!])
            attributedPlaceholder = str
        }
    }

    override func textRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.insetBy(dx: 50, dy: 5)
    }

    override func editingRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.insetBy(dx: 50, dy: 5)
    }

}
</code>```

Title: Swift add icon/image in UITextField

Body:
I would like to add icon/image in UITextField. The icon/image should be left to placeholder.

I tried this:

var imageView = UIImageView();
var image = UIImage(named: "email.png");
imageView.image = image;
emailField.leftView = imageView;

Thanks.

Body:
I created a simple IBDesignable. Use it however u like. Just make your UITextField confirm to this class.

import UIKit

@IBDesignable
class RoundTextField : UITextField {
    @IBInspectable var cornerRadius : CGFloat = 0{
        didSet{
            layer.cornerRadius = cornerRadius
            layer.masksToBounds = cornerRadius > 0
        }
    }

    @IBInspectable var borderWidth : CGFloat = 0 {
        didSet{
            layer.borderWidth = borderWidth
        }
    }

    @IBInspectable var borderColor : UIColor? {
        didSet {
            layer.borderColor = borderColor?.cgColor
        }
    }

    @IBInspectable var bgColor : UIColor? {
        didSet {
            backgroundColor = bgColor
        }
    }

    @IBInspectable var leftImage : UIImage? {
        didSet {
            if let image = leftImage{
                leftViewMode = .always
                let imageView = UIImageView(frame: CGRect(x: 20, y: 0, width: 20, height: 20))
                imageView.image = image
                imageView.tintColor = tintColor
                let view = UIView(frame : CGRect(x: 0, y: 0, width: 25, height: 20))
                view.addSubview(imageView)
                leftView = view
            }else {
                leftViewMode = .never
            }

        }
    }

    @IBInspectable var placeholderColor : UIColor? {
        didSet {
            let rawString = attributedPlaceholder?.string != nil ? attributedPlaceholder!.string : ""
            let str = NSAttributedString(string: rawString, attributes: [NSForegroundColorAttributeName : placeholderColor!])
            attributedPlaceholder = str
        }
    }

    override func textRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.insetBy(dx: 50, dy: 5)
    }

    override func editingRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.insetBy(dx: 50, dy: 5)
    }

}


问:
PHP: How to remove/disable a selection from a checkbox group if the value is already selected and stored in database previously
Right now I am coding in PHP & HTML

I need to make a selection from the checkbox group
and it goes like this:

The value in the dropdown menu is retrieved from the value stored in the database in table subject. So the checkbox options will appears as (for example) Mathematics, Algebra, Calculus, English, Linguistic etc. -- I have no problem with displaying this one.

Table subject

```<code>subject_id       subject_name
==========       ============
     1            Mathematics
     2            Algebra
     3            Calculus
     4            English
     5            Linguistic
</code>```

So after that, a student can choose their subject and it will be stored in another table named student_subject where it stores the student_id and the subject_id (to store what subjects did a student chose)
Example:

table student_subject

```<code>    student_id       subject_id
    ==========       ===========
        1                 1
        1                 2
        1                 3
        2                 1
        2                 3
</code>```

Now, the student comes again to add another subject to his profile. The same checkbox option will be displayed as mentioned earlier in (1) but I would love to disabled/remove/not display the already selected option from being selectable again to avoid redundancy.

I really have no idea on how to create this function. I know there are a lot of experienced programmers and developera here so I wish you could show me the right way. Your guidance is highly appreciated.

答:
You should not remove/disabled/not display the existing subjects.

First, you should check for existing rows for student_subject table and render it in HTML checkbox as selected.

Second, while student makes changes for subject selection in edit mode, check with the database rows with student and subject ids in a loop.

If submitted subject id for the student is not available in the database, insert that value to the table.

If submitted subject id for the student is available in the database, do nothing with it.

Check for the removed subject from submitted values with the database, and delete from the database.

If you want to disable existing subjects, use readonly to the checkbox if the subject is assigned to the student.

Body:
Right now I am coding in PHP & HTML

I need to make a selection from the checkbox group
and it goes like this:

The value in the dropdown menu is retrieved from the value stored in the database in table subject. So the checkbox options will appears as (for example) Mathematics, Algebra, Calculus, English, Linguistic etc. -- I have no problem with displaying this one.

Table subject

subject_id       subject_name
==========       ============
     1            Mathematics
     2            Algebra
     3            Calculus
     4            English
     5            Linguistic

So after that, a student can choose their subject and it will be stored in another table named student_subject where it stores the student_id and the subject_id (to store what subjects did a student chose)
Example:

table student_subject

    student_id       subject_id
    ==========       ===========
        1                 1
        1                 2
        1                 3
        2                 1
        2                 3

Now, the student comes again to add another subject to his profile. The same checkbox option will be displayed as mentioned earlier in (1) but I would love to disabled/remove/not display the already selected option from being selectable again to avoid redundancy.

I really have no idea on how to create this function. I know there are a lot of experienced programmers and developera here so I wish you could show me the right way. Your guidance is highly appreciated.


问:
Django - run a function every x seconds
I'm working on a Django app. I have an API endpoint, which if requested, must carry out a function that must be repeated a few times (until a certain condition is true). How I'm dealing with it right now is -

```<code>def shut_down(request):
  # Do some stuff
  while True:
    result = some_fn()
    if result:
      break
    time.sleep(2)

  return True
</code>```

While I know that this is a terrible approach and that I shouldn't be blocking for 2 seconds, I can't figure out how to get around it.

This works, after say a wait of 4 seconds. But I'd like something that keeps the loop running in the background, and stop once some_fn returns True. (Also, it is certain that some_fn will return True)

EDIT -

Reading Oz123's response gave me an idea which seems to work. Here's what I did -

```<code>def shut_down(params):
    # Do some stuff
    # Offload the blocking job to a new thread

    t = threading.Thread(target=some_fn, args=(id, ), kwargs={})
    t.setDaemon(True)
    t.start()

    return True

def some_fn(id):
    while True:
        # Do the job, get result in res
        # If the job is done, return. Or sleep the thread for 2 seconds before trying again.

        if res:
            return
        else:
            time.sleep(2)
</code>```

This does the job for me. It's simple but I don't know how efficient multithreading is in conjunction with Django.

If anyone can point out pitfalls of this, criticism is appreciated.

答:
For many small projects celery is overkill. For those projects you can use schedule, it's very easy to use.

With this library you can make any function execute a task periodically:

```<code>import schedule
import time

def job():
    print("I'm working...")

schedule.every(10).minutes.do(job)
schedule.every().hour.do(job)
schedule.every().day.at("10:30").do(job)
schedule.every().monday.do(job)
schedule.every().wednesday.at("13:15").do(job)

while True:
    schedule.run_pending()
    time.sleep(1)
</code>```

The example runs in a blocking manner, but if you look in the FAQ, you will find that you can also run tasks in a parallel thread, such that you are not blocking, and remove the task once not needed anymore:

```<code>import threading
import time

from schedule import Scheduler

def run_continuously(self, interval=1):
    """Continuously run, while executing pending jobs at each elapsed
    time interval.
    @return cease_continuous_run: threading.Event which can be set to
    cease continuous run.
    Please note that it is *intended behavior that run_continuously()
    does not run missed jobs*. For example, if you've registered a job
    that should run every minute and you set a continuous run interval
    of one hour then your job won't be run 60 times at each interval but
    only once.
    """

    cease_continuous_run = threading.Event()

    class ScheduleThread(threading.Thread):

        @classmethod
        def run(cls):
            while not cease_continuous_run.is_set():
                self.run_pending()
                time.sleep(interval)

    continuous_thread = ScheduleThread()
    continuous_thread.setDaemon(True)
    continuous_thread.start()
    return cease_continuous_run

Scheduler.run_continuously = run_continuously
</code>```

Here is an example for usage in a class method:

```<code>    def foo(self):
        ...
        if some_condition():
           return schedule.CancelJob  # a job can dequeue it

    # can be put in __enter__ or __init__
    self._job_stop = self.scheduler.run_continuously()

    logger.debug("doing foo"...)
    self.foo() # call foo
    self.scheduler.every(5).seconds.do(
        self.foo) # schedule foo for running every 5 seconds

    ...
    # later on foo is not needed any more:
    self._job_stop.set()

    ...

    def __exit__(self, exec_type, exc_value, traceback):
        # if the jobs are not stop, you can stop them
        self._job_stop.set()

</code>```

Title: Django - run a function every x seconds

Body:
I'm working on a Django app. I have an API endpoint, which if requested, must carry out a function that must be repeated a few times (until a certain condition is true). How I'm dealing with it right now is -

def shut_down(request):
  # Do some stuff
  while True:
    result = some_fn()
    if result:
      break
    time.sleep(2)

  return True

While I know that this is a terrible approach and that I shouldn't be blocking for 2 seconds, I can't figure out how to get around it.

This works, after say a wait of 4 seconds. But I'd like something that keeps the loop running in the background, and stop once some_fn returns True. (Also, it is certain that some_fn will return True)

EDIT -

Reading Oz123's response gave me an idea which seems to work. Here's what I did -

def shut_down(params):
    # Do some stuff
    # Offload the blocking job to a new thread

    t = threading.Thread(target=some_fn, args=(id, ), kwargs={})
    t.setDaemon(True)
    t.start()

    return True

def some_fn(id):
    while True:
        # Do the job, get result in res
        # If the job is done, return. Or sleep the thread for 2 seconds before trying again.

        if res:
            return
        else:
            time.sleep(2)

This does the job for me. It's simple but I don't know how efficient multithreading is in conjunction with Django.

If anyone can point out pitfalls of this, criticism is appreciated.

Body:
For many small projects celery is overkill. For those projects you can use schedule, it's very easy to use.

With this library you can make any function execute a task periodically:

import schedule
import time

def job():
    print("I'm working...")

schedule.every(10).minutes.do(job)
schedule.every().hour.do(job)
schedule.every().day.at("10:30").do(job)
schedule.every().monday.do(job)
schedule.every().wednesday.at("13:15").do(job)

while True:
    schedule.run_pending()
    time.sleep(1)

The example runs in a blocking manner, but if you look in the FAQ, you will find that you can also run tasks in a parallel thread, such that you are not blocking, and remove the task once not needed anymore:

import threading
import time

from schedule import Scheduler

def run_continuously(self, interval=1):
    """Continuously run, while executing pending jobs at each elapsed
    time interval.
    @return cease_continuous_run: threading.Event which can be set to
    cease continuous run.
    Please note that it is *intended behavior that run_continuously()
    does not run missed jobs*. For example, if you've registered a job
    that should run every minute and you set a continuous run interval
    of one hour then your job won't be run 60 times at each interval but
    only once.
    """

    cease_continuous_run = threading.Event()

    class ScheduleThread(threading.Thread):

        @classmethod
        def run(cls):
            while not cease_continuous_run.is_set():
                self.run_pending()
                time.sleep(interval)

    continuous_thread = ScheduleThread()
    continuous_thread.setDaemon(True)
    continuous_thread.start()
    return cease_continuous_run

Scheduler.run_continuously = run_continuously

Here is an example for usage in a class method:

    def foo(self):
        ...
        if some_condition():
           return schedule.CancelJob  # a job can dequeue it

    # can be put in __enter__ or __init__
    self._job_stop = self.scheduler.run_continuously()

    logger.debug("doing foo"...)
    self.foo() # call foo
    self.scheduler.every(5).seconds.do(
        self.foo) # schedule foo for running every 5 seconds

    ...
    # later on foo is not needed any more:
    self._job_stop.set()

    ...

    def __exit__(self, exec_type, exc_value, traceback):
        # if the jobs are not stop, you can stop them
        self._job_stop.set()

ContentLicense: CC BY-SA 4.0


问:
Can I use SQL's IN(...) statement for a namedQuery?
How can I use IN at my namedQuery?

```<code>@NamedQueries(
 {
 @NamedQuery(name = "GetAvailableProducts", query = new StringBuilder("").append("SELECT   p   FROM Product p WHERE p.type= :type AND (p.available IN ('I want to define changeable size of an array or sometinhg like that') OR p.available = :available)")),
 }
</code>```

I mean that I can set 'type' parameter (I defined it as a variable----> :type) and I want to define variables inside of IN statement to. However the number of parameters are not constant. I want to define an array or something like that :array[] and I want to set it when I call that namedQuery.

答:
Did you try something like

```<code>SELECT   p   FROM Product p WHERE p.type= :type AND (p.available IN
('foo', 'bar') OR p.available = :available)
</code>```

(if "available" is a string)

or

```<code>SELECT   p   FROM Product p WHERE p.type= :type AND (p.available IN
(1, 2, 3) OR p.available = :available)
</code>```

(if available is a number)?

Body:
How can I use IN at my namedQuery?

@NamedQueries(
 {
 @NamedQuery(name = "GetAvailableProducts", query = new StringBuilder("").append("SELECT   p   FROM Product p WHERE p.type= :type AND (p.available IN ('I want to define changeable size of an array or sometinhg like that') OR p.available = :available)")),
 }

I mean that I can set 'type' parameter (I defined it as a variable----> :type) and I want to define variables inside of IN statement to. However the number of parameters are not constant. I want to define an array or something like that :array[] and I want to set it when I call that namedQuery.

Body:
Did you try something like

SELECT   p   FROM Product p WHERE p.type= :type AND (p.available IN
('foo', 'bar') OR p.available = :available)

(if "available" is a string)

or

SELECT   p   FROM Product p WHERE p.type= :type AND (p.available IN
(1, 2, 3) OR p.available = :available)

(if available is a number)?


问:
Scrape JSON from webpage with C#
New to C# here and to running asynchronous tasks.

I'm trying to scrape some music album info from a website. The webpage's search produces a JSON object in plaintext, but I can't seem to access any DOM info. Here's what I tried (using HtmlAgilityPack):

```<code>using HtmlAgilityPack;
using System;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1 {
public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
    }

    public async Task<String> AlbumScraper(string albumname) {

        HtmlWeb web = new HtmlWeb();

        string albumurl = Uri.EscapeUriString("https://www.metal-archives.com/search/ajax-album-search/?field=title&query=" + albumname);
        Console.Write(albumurl);
        var albumdoc = await Task.Factory.StartNew(() => web.Load(albumurl));
        string albumjson = "";

        if (albumdoc.DocumentNode != null) {
            albumjson = albumdoc.DocumentNode.InnerText;
        }

        return albumjson;
    }

    private async void Form1_Load(object sender, EventArgs e) {
        string rawtext = await AlbumScraper("rust+in+peace");
        Console.Write(rawtext);
    }
}
}
</code>```

How can I grab the JSON text generated? I can see it clearly when I load the "albumurl" URL...

答:
You can generate it by online tool http://json2csharp.com/
Then add generated class to your code

```<code>public class AlbumSearchResponse
    {
        public string error { get; set; }
        public int iTotalRecords { get; set; }
        public int iTotalDisplayRecords { get; set; }
        public int sEcho { get; set; }
        public List<List<string>> aaData { get; set; }
    }
</code>```

convert your response text to class

```<code>var data = JsonConvert.DeserializeObject<AlbumSearchResponse>(response);
        foreach (var item in data.aaData)
        {
            //do whatever your want with data
        }
</code>```

also you need add newtonsoft json package from nuget to get JsonConvert working

Title: Scrape JSON from webpage with C#

Body:
New to C# here and to running asynchronous tasks.

I'm trying to scrape some music album info from a website. The webpage's search produces a JSON object in plaintext, but I can't seem to access any DOM info. Here's what I tried (using HtmlAgilityPack):

using HtmlAgilityPack;
using System;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1 {
public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
    }

    public async Task<String> AlbumScraper(string albumname) {

        HtmlWeb web = new HtmlWeb();

        string albumurl = Uri.EscapeUriString("https://www.metal-archives.com/search/ajax-album-search/?field=title&query=" + albumname);
        Console.Write(albumurl);
        var albumdoc = await Task.Factory.StartNew(() => web.Load(albumurl));
        string albumjson = "";

        if (albumdoc.DocumentNode != null) {
            albumjson = albumdoc.DocumentNode.InnerText;
        }

        return albumjson;
    }

    private async void Form1_Load(object sender, EventArgs e) {
        string rawtext = await AlbumScraper("rust+in+peace");
        Console.Write(rawtext);
    }
}
}

How can I grab the JSON text generated? I can see it clearly when I load the "albumurl" URL...

Body:
You can generate it by online tool http://json2csharp.com/
Then add generated class to your code

public class AlbumSearchResponse
    {
        public string error { get; set; }
        public int iTotalRecords { get; set; }
        public int iTotalDisplayRecords { get; set; }
        public int sEcho { get; set; }
        public List<List<string>> aaData { get; set; }
    }

convert your response text to class

var data = JsonConvert.DeserializeObject<AlbumSearchResponse>(response);
        foreach (var item in data.aaData)
        {
            //do whatever your want with data
        }

also you need add newtonsoft json package from nuget to get JsonConvert working


问:
Generating PDF in windows forms using XML reader
My windows form contains a textbox in which we need to enter html tags,One button to generate PDF.
And we need to load the textbox content into XML Reader and process each element of XML recursively then we need to generate a PDF file.
The PDF file must contain the data i.e;
for example if I entered  tag in the text box in the pdf file it must display a table.
I am very new to Windows forms and XML also can any one help me to complete this task</p>

答:
Got Answer with this simple code

```<code>Document document = new Document();
PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\MySamplePDF.pdf", FileMode.Create));
document.Open();
iTextSharp.text.html.simpleparser.HTMLWorker hw =
             new iTextSharp.text.html.simpleparser.HTMLWorker(document);
hw.Parse(new StringReader(htmlText));
document.Close();
</code>```

but my problem is the path I want to select the path dynamically.Can any one help me how to set the path dynamically in the above code.

Body:
Got Answer with this simple code

Document document = new Document();
PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\MySamplePDF.pdf", FileMode.Create));
document.Open();
iTextSharp.text.html.simpleparser.HTMLWorker hw =
             new iTextSharp.text.html.simpleparser.HTMLWorker(document);
hw.Parse(new StringReader(htmlText));
document.Close();

but my problem is the path I want to select the path dynamically.Can any one help me how to set the path dynamically in the above code.


问:
Integrate an Xcode project into another
I am building an iOS application in Swift 3. It uses a QRCode reader to scan QRCode and I downloaded the QRCodeReaderViewController.

I am new to iOS. Please help me integrate these files into my project.

答:
Check the installation process of your QRCodeViewController in the link you provided above. Its clearly mentioned there. You can QRCodeViewController using cocoa pods or manully also.
Adding this line pod 'QRCodeReaderViewController', '~> 4.0.2' to pods and pod install u can add QRCodeViewController to your project.

You can even simply drag and drop the QRCodeViewController project in your working project. Just import the required files and implemet the required delegate methods in your class  and you are good to go.

Hope it helps. Happy Coding!!

Title: Integrate an Xcode project into another


问:
Unable to apply CSS in Angular using ng-class
I am stuck at it for a long long time now and I really need help. I have a div section which I want to display on the click of a button. For which I use CSS classes.

Here is the DIV section

```<code>    <div class="elen-main--left-menu--collapsed " ng-class="collapsedMenuAvailable">
    <div class="icon-propal icon_active">
        <img src="content/img/icon_propal_white.svg" alt="" width="18" />
    </div>

    <div class="icon-contrat">
        <img src="content/img/icon_contrat_grey.svg" alt="" width="18" />
    </div>
    <div class="left--menu--expand" ng-click="vm.showVerticalBanner">
        <img src="content/img/arrow-expandMenu-grey.svg" alt="" width="13">
    </div>
</div>
</code>```

collapsedMenuAvailable is changed to the value from my controller.
CONTROLLER

```<code>vm.hideVerticalBanner = function () {
                $scope.collapsedMenuAvailable = 'expandCollapsedMenu';
                $('.elen-main--left-menu').addClass('collapseLeftMenu');
                $('.elen-main--left-menu').css('overflow', 'hidden');
                setTimeout(function () {
                    // $('.elen-main--left-menu--collapsed').addClass('expandCollapsedMenu');
                    $('.elen-main--content').css('width', 'calc(100% - 6rem)');
                }, 200);

                $('.elen-main--left-menu').removeClass('expandLeftMenu');
                $('.elen-main--left-menu--collapsed').removeClass('collapseCollapsedMenu');
            }
</code>```

But still it doesn't apply the CSS. However if I put the classname which is 'expandCollapsedMenu' in the div section, the CSS is applied.

what is possibly wrong ?

答:
The below scenario explains how the ng-class is working. The class should be first and you can have an optional condition following that.

var app =angular.module("myapp", [])
app.controller("ctrl", function($scope){
$scope.isClass = false;
$scope.hide = function(){
$scope.isClass=!$scope.isClass;
}
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hidden{
display:none;
}</code>```

<button ng-click="hide()">Toggle</button>

```

Body:
I am stuck at it for a long long time now and I really need help. I have a div section which I want to display on the click of a button. For which I use CSS classes.

Here is the DIV section

collapsedMenuAvailable is changed to the value from my controller.
CONTROLLER

vm.hideVerticalBanner = function () {
                $scope.collapsedMenuAvailable = 'expandCollapsedMenu';
                $('.elen-main--left-menu').addClass('collapseLeftMenu');
                $('.elen-main--left-menu').css('overflow', 'hidden');
                setTimeout(function () {
                    // $('.elen-main--left-menu--collapsed').addClass('expandCollapsedMenu');
                    $('.elen-main--content').css('width', 'calc(100% - 6rem)');
                }, 200);

                $('.elen-main--left-menu').removeClass('expandLeftMenu');
                $('.elen-main--left-menu--collapsed').removeClass('collapseCollapsedMenu');
            }

But still it doesn't apply the CSS. However if I put the classname which is 'expandCollapsedMenu' in the div section, the CSS is applied.

what is possibly wrong ?

Body:
The below scenario explains how the ng-class is working. The class should be first and you can have an optional condition following that.

var app =angular.module("myapp", [])
app.controller("ctrl", function($scope){
$scope.isClass = false;
$scope.hide = function(){
$scope.isClass=!$scope.isClass;
}
})

.hidden{
display:none;
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div id="parent" ng-app="myapp" ng-controller="ctrl">
<button ng-click="hide()">Toggle</button>
<div style="background-color:red;width:100px;height:100px" ng-class="{hidden:isClass}">
</div>


问:
Failed to build AOSP [run_soong_ui] Error 1
I'm trying to compile android version 7.1.2 master branch. I already set up following the instructions from source.android.com. When I run make -j8 I got this error and also an error message from jack-server which I think maybe is related to the build error. The last messages of the verbose output:

[ 41% 1715/4084] Ensuring Jack server is installed and started

  FAILED: setup-jack-server

  /bin/bash -c "(prebuilts/sdk/tools/jack-admin install-server
prebuilts/sdk/tools/jack-launcher.jar prebuilts/sdk/tools/jack-server-4.11.ALPHA.jar  2>&1 || (exit 0) ) && (JACK_SERVER_VM_ARGUMENTS=\"-Dfile.encoding=UTF-8 -XX:+TieredCompilation\" prebuilts/sdk/tools/jack-admin start-server 2>&1 || exit 0 ) &&
 (prebuilts/sdk/tools/jack-admin update server prebuilts/sdk/tools/jack-server-4.11.ALPHA.jar 4.11.ALPHA 2>&1 || exit 0 ) && (prebuilts/sdk/tools/jack-admin update jack prebuilts/sdk/tools/jacks/jack-4.31.CANDIDATE.jar 4.31.CANDIDATE || exit 47 )"

  Jack server already installed in "/home/fabio/.jack-server"

  Communication error with Jack server (28), try 'jack-diagnose' or see Jack server log

  Communication error with Jack server 28. Try 'jack-diagnose'

  Communication error with Jack server 28. Try 'jack-diagnose'

  [ 42% 1719/4084] Docs droiddoc: out/target/common/docs/api-stubs

  DroidDoc took 687 sec. to write docs to out/target/common/docs/api-stubs
  [ 42% 1720/4084] Docs droiddoc: out/target/common/docs/test-api-stubs

  DroidDoc took 687 sec. to write docs to out/target/common/docs/test-api-stubs

  [ 42% 1721/4084] Docs droiddoc: out/target/common/docs/system-api-stubs

  DroidDoc took 705 sec. to write docs to out/target/common/docs/system-api-stubs

  [ 42% 1722/4084] //external/llvm:libLLVM link libLLVM.so

  ninja: build stopped: subcommand failed.

  16:58:24 ninja failed with: exit status 1

  build/core/main.mk:21: recipe for target 'run_soong_ui' failed

  make: *** [run_soong_ui] Error 1

答: Try increasing heap size with java option '-Xmx'</p>


问:
Trigger Animation on Scroll
Basically i'd like to trigger this box animation after the user scrolls down by adding a class.

Can't seem to make this work for me, I'm probably doing something fundamentally wrong. Below is my current code, can anyone give me pointers as to what I'm doing wrong? Thanks!

HTML

```<code><svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     width="600px" height="600px" viewBox="0 0 600 600" enable-background="new 0 0 600 600" xml:space="preserve">
    <rect class="box" x="147.297" y="237.162" fill="#FFFFFF" stroke="#000000" stroke-width="8" stroke-miterlimit="10" width="305.405" height="125.676"/>
</svg>
</code>```

CSS

```<code>     @keyframes offset{
    100%{
      stroke-dashoffset:0;
    }
  }

.box{
    stroke:transparent;
}
  .box.draw{
    stroke:#202020;
    stroke-width:5;
    stroke-dasharray:910;
    stroke-dashoffset:910;
    animation: offset 5s linear forwards;
  }
</code>```

jQuery/JS

```<code>$(function() {
    var boxDraw = $(".box");
    $(window).scroll(function() {
        var scroll = $(window).scrollTop();

        if (scroll >= 400) {
            box.addClass("draw");
        }
    });
});
</code>```

Additionally, how might it be possible to trigger an animation after a certain point in the page, rather than a scroll value? Any help would be appreciated.

答:
@Capsule has figured it out. Your correct JS code:

```<code>$(function() {
    var boxDraw = $(".box");
    $(window).scroll(function() {
        var scroll = $(window).scrollTop();

        if (scroll >= 400) {
            boxDraw.addClass("draw");
        }
    });
});
</code>```

To trigger the scroll when a certain element is in view, again @Capsule has pointed it out but here's the code

```<code>$(function() {
    var boxDraw = $(".box");
    var boxDrawTop = boxDraw.offset().top;
    var windowHeight = $(window).height();

    $(window).scroll(function() {
        var scroll = $(window).scrollTop();

        // let's fire up animation when .box is in view

        if ( scroll >= ( boxDrawTop - windowHeight )) {
            boxDraw.addClass("draw");
        }
    });
});
</code>```

Title: Trigger Animation on Scroll

Body:
Basically i'd like to trigger this box animation after the user scrolls down by adding a class.

Can't seem to make this work for me, I'm probably doing something fundamentally wrong. Below is my current code, can anyone give me pointers as to what I'm doing wrong? Thanks!

HTML

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     width="600px" height="600px" viewBox="0 0 600 600" enable-background="new 0 0 600 600" xml:space="preserve">
    <rect class="box" x="147.297" y="237.162" fill="#FFFFFF" stroke="#000000" stroke-width="8" stroke-miterlimit="10" width="305.405" height="125.676"/>
</svg>

CSS

     @keyframes offset{
    100%{
      stroke-dashoffset:0;
    }
  }

.box{
    stroke:transparent;
}
  .box.draw{
    stroke:#202020;
    stroke-width:5;
    stroke-dasharray:910;
    stroke-dashoffset:910;
    animation: offset 5s linear forwards;
  }

jQuery/JS

$(function() {
    var boxDraw = $(".box");
    $(window).scroll(function() {
        var scroll = $(window).scrollTop();

        if (scroll >= 400) {
            box.addClass("draw");
        }
    });
});

Additionally, how might it be possible to trigger an animation after a certain point in the page, rather than a scroll value? Any help would be appreciated.

Body:
@Capsule has figured it out. Your correct JS code:

$(function() {
    var boxDraw = $(".box");
    $(window).scroll(function() {
        var scroll = $(window).scrollTop();

        if (scroll >= 400) {
            boxDraw.addClass("draw");
        }
    });
});

To trigger the scroll when a certain element is in view, again @Capsule has pointed it out but here's the code

$(function() {
    var boxDraw = $(".box");
    var boxDrawTop = boxDraw.offset().top;
    var windowHeight = $(window).height();

    $(window).scroll(function() {
        var scroll = $(window).scrollTop();

        // let's fire up animation when .box is in view

        if ( scroll >= ( boxDrawTop - windowHeight )) {
            boxDraw.addClass("draw");
        }
    });
});


问:
How to use Templates on javascript?
I Have A function that add html to a div.

```<code>var user = $("#ddlUser").val();
    var role = $("#ddlUserRole").val();

    var html = '<div class="calendaruser">';
    html += '<span>' + user + '</span> <button type="button" class="btn btn-default btn-xs">הסר משתמש</button>';
    html += '<div>' + role + '</div>';
    html += '</div>';

    $("#divCalendarUsers").append(html);
</code>```

i'm looking for a better way to use the template.

答:
You can use the template literal:

A little sample:

  <!DOCTYPE html>

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

  ```

Title: How to use Templates on javascript?

Body:
I Have A function that add html to a div.

var user = $("#ddlUser").val();
    var role = $("#ddlUserRole").val();

    var html = '
';
    html += '' + user + ' <button type="button" class="btn btn-default btn-xs">הסר משתמש</button>';
    html += '
' + role + '
';
    html += '
';

    $("#divCalendarUsers").append(html);

i'm looking for a better way to use the template.

Body:
You can use the template literal:

A little sample:

  <!DOCTYPE html>
  <html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Array2Table</title>
  </head>
  <body>
    <div id="tableContent"></div>
    <script>
      var country = ["Country1", "Country2", "Country3"];
      var capital = ["City1", "City2" , "City3"];

      const tmpl = (country,capital) => `
          <table><thead>
          <tr><th>Country<th>Capital<tbody>
          ${country.map( (cell, index) => `
              <tr><td>${cell}<td>${capital[index]}</tr>
          `).join('')}
          </table>`;
      tableContent.innerHTML=tmpl(country, capital);
      </script>
  </body>
  </html>


问:
Bitwise Operation on a byte and an int
I have a byte array represented as

```<code>char * bytes = getbytes(object); //some api function
</code>```

I want to check whether the bit at some position x is set.

I've been trying this

```<code>int mask = 1 << x % 8;
y= bytes[x>>3] & mask;
</code>```

However y returns as all zeros? What am I doing incorrectly and is there an easier way to check if a bit is set?

EDIT:

I did run this as well. It didn't return with the expected result either.

```<code>  int k = x >> 3;
   int mask = x % 8;
    unsigned char byte = bytes[k];
   return (byte & mask);
</code>```

it failed an assert true ctest I ran. Byte and Mask at this time where "0002" and 2 respectively when printed from gdb.

edit 2: This is how I set the bits in the first place. I'm just trying to write a test to verify they are set.

unsigned long x = somehash(void* a);

unsigned int mask = 1 << (x % 8);

```<code>unsigned int location = x >> 3;
char* filter = getData(ref);

filter[location] |= mask;
</code>```

答:
This would be one (crude perhaps) way from the top of my head:

```<code>#include "stdio.h"
#include "stdlib.h"

// this function *changes* the byte array
int getBit(char *b, int bit)
{
  int bitToCheck = bit % 8;
  b = b + (bitToCheck ? (bit / 8) : (bit / 8 - 1));

  if (bitToCheck)
    *b = (*b) >> (8 - bitToCheck);

  return (*b) & 1;
}

int main(void)
{
  char *bytes = calloc(2, 1);
  *(bytes + 1)= 5;  // writing to the appropiate bits
  printf("%d\n", getBit(bytes, 16)); // checking the 16th bit from the left
  return 0;
}
</code>```

Assumptions:

A byte is represented as:

```<code>----------------------------------------
| 2^7 | 2^6 | 2^5 | 2^4 | 2^3 |...     |
----------------------------------------
</code>```

The left most bit is considered bit number 1 and the right most bit is considered the max. numbered bit (16th bit in a 2 byte object).

It's OK to overwrite the actual byte object (if this is not wanted, use memcpy).

Title: Bitwise Operation on a byte and an int

Body:
I have a byte array represented as

char * bytes = getbytes(object); //some api function

I want to check whether the bit at some position x is set.

I've been trying this

int mask = 1 << x % 8;
y= bytes[x>>3] & mask;

However y returns as all zeros? What am I doing incorrectly and is there an easier way to check if a bit is set?

EDIT:

I did run this as well. It didn't return with the expected result either.

  int k = x >> 3;
   int mask = x % 8;
    unsigned char byte = bytes[k];
   return (byte & mask);

it failed an assert true ctest I ran. Byte and Mask at this time where "0002" and 2 respectively when printed from gdb.

edit 2: This is how I set the bits in the first place. I'm just trying to write a test to verify they are set.

unsigned long x = somehash(void* a);

unsigned int mask = 1 << (x % 8);

unsigned int location = x >> 3;
char* filter = getData(ref);

filter[location] |= mask;

Body:
This would be one (crude perhaps) way from the top of my head:

#include "stdio.h"
#include "stdlib.h"

// this function *changes* the byte array
int getBit(char *b, int bit)
{
  int bitToCheck = bit % 8;
  b = b + (bitToCheck ? (bit / 8) : (bit / 8 - 1));

  if (bitToCheck)
    *b = (*b) >> (8 - bitToCheck);

  return (*b) & 1;
}

int main(void)
{
  char *bytes = calloc(2, 1);
  *(bytes + 1)= 5;  // writing to the appropiate bits
  printf("%d\n", getBit(bytes, 16)); // checking the 16th bit from the left
  return 0;
}

Assumptions:

A byte is represented as:

----------------------------------------
| 2^7 | 2^6 | 2^5 | 2^4 | 2^3 |...     |
----------------------------------------

The left most bit is considered bit number 1 and the right most bit is considered the max. numbered bit (16th bit in a 2 byte object).

It's OK to overwrite the actual byte object (if this is not wanted, use memcpy).


问:
Change text color of selected item in spinner
How can I change the font color of the selected item in a spinner?

I am able to change the background color of the selected item, the color of the dropdown item etc, but not the text color of selected item... how can I do that?

my code is:
this is spinner i am using--:

```<code><Spinner
                android:id="@+id/spinner1"
                android:layout_width="wrap_content"
                android:layout_height="32dip"
                android:background="@drawable/mybg"
                android:divider="@drawable/list_divider"
                android:drawSelectorOnTop="true"
                android:popupBackground="#D3D5D3"
                android:prompt="@string/activityy_prompt"
                />
</code>```

this is mybg.xml

```<code><!-- <item android:drawable="@drawable/blue" android:state_pressed="false"/> -->
<!-- <item android:drawable="@drawable/back11"/> -->

<item android:drawable="@drawable/greenyellow1" android:state_focused="true" android:state_pressed="false"/>
<item android:drawable="@drawable/greenyellow1" android:state_focused="true" android:state_pressed="true"/>
<item android:drawable="@drawable/greenyellow1" android:state_focused="false" android:state_pressed="true"/>
<item android:drawable="@drawable/greenyellow1" android:state_selected="true"/>
<item android:drawable="@drawable/back11"/>
</code>```

using these i am not able to change the text color of selecetd item...

答:
some of you that using MaterialBetterSpinner and Binding your Layouts,
 all the above won't help, try this, hope it helps you:

```<code>public class MyAdapter extends ArrayAdapter<String> {

        public MyAdapter(Context context, int textViewResourceId, List<String> objects) {
            super(context, textViewResourceId, objects);

        }

        @Override
        public View getDropDownView(int position, View convertView, ViewGroup parent) {
            return getCustomView(position, convertView, parent);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            return getCustomView(position, convertView, parent);
        }

        public View getCustomView(int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            final YourXMLBinding rowBinding = DataBindingUtil.inflate(inflater, R.layout.yourXML, parent,false);
            rowBinding.tv1.setText(mMy.getValues().get(position));
            if(position == mMy.getCurrentIndex()) {
                rowBinding.tv1.setTypeface(Typer.set(getContext()).getFont(Font.ROBOTO_BOLD));//change font
                rowBinding.tv1.setTextColor(ContextCompat.getColor(getContext(), R.color.yourColor));//change color
            }
            return rowBinding.getRoot();
        }
    }
</code>```

yourXML is something like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<layout>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:background="@color/colorBackgroundStart">
        <TextView
            android:id="@+id/tv1"
            android:layout_width="0dp"
            android:layout_weight="0.7"
            android:layout_height="30dp"
            android:textColor="#fff"
            android:textSize="16dp"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="8dp"/>

</layout>
</code>```

create a spinner with this adapter and yourXML :

```<code>final MyAdapter adapter = new MyAdapter(getContext(), R.layout.yourXML, s.getValues());

final MaterialBetterSpinner spinner = new MaterialBetterSpinner(getContext());
spinner.setAdapter(adapter);
</code>```

Body:
How can I change the font color of the selected item in a spinner?

I am able to change the background color of the selected item, the color of the dropdown item etc, but not the text color of selected item... how can I do that?

my code is:
this is spinner i am using--:

<Spinner
                android:id="@+id/spinner1"
                android:layout_width="wrap_content"
                android:layout_height="32dip"
                android:background="@drawable/mybg"
                android:divider="@drawable/list_divider"
                android:drawSelectorOnTop="true"
                android:popupBackground="#D3D5D3"
                android:prompt="@string/activityy_prompt"
                />

this is mybg.xml

<item android:drawable="@drawable/greenyellow1" android:state_focused="true" android:state_pressed="false"/>
<item android:drawable="@drawable/greenyellow1" android:state_focused="true" android:state_pressed="true"/>
<item android:drawable="@drawable/greenyellow1" android:state_focused="false" android:state_pressed="true"/>
<item android:drawable="@drawable/greenyellow1" android:state_selected="true"/>
<item android:drawable="@drawable/back11"/>

using these i am not able to change the text color of selecetd item...

Body:
some of you that using MaterialBetterSpinner and Binding your Layouts,
 all the above won't help, try this, hope it helps you:

public class MyAdapter extends ArrayAdapter<String> {

        public MyAdapter(Context context, int textViewResourceId, List<String> objects) {
            super(context, textViewResourceId, objects);

        }

        @Override
        public View getDropDownView(int position, View convertView, ViewGroup parent) {
            return getCustomView(position, convertView, parent);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            return getCustomView(position, convertView, parent);
        }

        public View getCustomView(int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            final YourXMLBinding rowBinding = DataBindingUtil.inflate(inflater, R.layout.yourXML, parent,false);
            rowBinding.tv1.setText(mMy.getValues().get(position));
            if(position == mMy.getCurrentIndex()) {
                rowBinding.tv1.setTypeface(Typer.set(getContext()).getFont(Font.ROBOTO_BOLD));//change font
                rowBinding.tv1.setTextColor(ContextCompat.getColor(getContext(), R.color.yourColor));//change color
            }
            return rowBinding.getRoot();
        }
    }

yourXML is something like this:

<?xml version="1.0" encoding="utf-8"?>
<layout>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:background="@color/colorBackgroundStart">
        <TextView
            android:id="@+id/tv1"
            android:layout_width="0dp"
            android:layout_weight="0.7"
            android:layout_height="30dp"
            android:textColor="#fff"
            android:textSize="16dp"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="8dp"/>

</layout>

create a spinner with this adapter and yourXML :

final MyAdapter adapter = new MyAdapter(getContext(), R.layout.yourXML, s.getValues());

final MaterialBetterSpinner spinner = new MaterialBetterSpinner(getContext());
spinner.setAdapter(adapter);


问:
C non-blocking keyboard input
I'm trying to write a program in C (on Linux) that loops until the user presses a key, but shouldn't require a keypress to continue each loop.

Is there a simple way to do this? I figure I could possibly do it with select() but that seems like a lot of work.

Alternatively, is there a way to catch a ctrl-c keypress to do cleanup before the program closes instead of non-blocking io?

答: The curses library can be used for this purpose. Of course, select() and signal handlers can be used too to a certain extent.

OwnerDisplayName: Zxaos

Title: C non-blocking keyboard input

LastEditorDisplayName: Zxaos

OwnerDisplayName: PolyThinker


答:
Expression 'IN' in JPQL is equal to writing multiple 'OR' statements, in your case an example of 'IN' would be:

```<code>... p.available IN ('US', 'GB') ...
</code>```

Which I believe is equal to:

```<code>... p.available = 'US' OR p.available = 'GB' ...
</code>```

Here's a link that explains it well: OpenJPA: IN Expression

EDIT
P.S. Assuming p.available is String (character type)

EDIT2
The author has edited question so many times that I can't follow up him :) As for the actual question about passing array for IN-expression, here's a link of similar question on StackOverflow: JPQL IN clause - Arrays

Title: Can I use SQL's IN(...) statement for a namedQuery?

Body:
Expression 'IN' in JPQL is equal to writing multiple 'OR' statements, in your case an example of 'IN' would be:

... p.available IN ('US', 'GB') ...

Which I believe is equal to:

... p.available = 'US' OR p.available = 'GB' ...

Here's a link that explains it well: OpenJPA: IN Expression

EDIT
P.S. Assuming p.available is String (character type)

EDIT2
The author has edited question so many times that I can't follow up him :) As for the actual question about passing array for IN-expression, here's a link of similar question on StackOverflow: JPQL IN clause - Arrays


答: To use template in javascript, try handlebarsjs.</p>

Title: How to use Templates on javascript?


问:
Problems with Applescript and Automator after macOS update
I had an Automator app that was working perfectly.
I use it to open Safari and fill a form with data taken from a numbers document.

To select the input fields I use something like:

```<code>do JavaScript "document.getElementById('Name').value = '" & name & "';
</code>```

But as soon as the app gets to that line, it encounters an error and stops. I tried several other commands using do JavaScript but nothing seems to work.

I'm not sure if this issue is related to the update. Could the do JavaScript command change?

答:
Do JavaScript has to address a tab in a Safari window</p>

```<code>tell application "Safari"
    activate
    set jScript to "yourscriptcode;"
    do JavaScript jScript in current tab of first window
end tell
</code>```

Body:
I had an Automator app that was working perfectly.
I use it to open Safari and fill a form with data taken from a numbers document.

To select the input fields I use something like:

do JavaScript "document.getElementById('Name').value = '" & name & "';

But as soon as the app gets to that line, it encounters an error and stops. I tried several other commands using do JavaScript but nothing seems to work.

I'm not sure if this issue is related to the update. Could the do JavaScript command change?

Body:
Do JavaScript has to address a tab in a Safari window

tell application "Safari"
    activate
    set jScript to "yourscriptcode;"
    do JavaScript jScript in current tab of first window
end tell


问:
Extract word after specific word from text file and put into XML file between specific tag
I need to Read a value from text file and put that value between tags of a XML file using batch commands.

The text file. text.txt

Input:

```<code>First 10
Second 13
Intersection aktivieren
</code>```

Output file : data.xml

```<code><First>10</First>
<Second>13</Second>
</code>```

答:
One possible batch code for this task is:

```<code>@echo off
if not exist "text.txt" goto :EOF
del "data.xml" 2>nul
for /F "usebackq tokens=1,2" %%I in ("text.txt") do echo ^<%%I^>%%J^</%%I^>>>"data.xml"
</code>```

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

del /?

echo /?

for /?

goto /?

if /?

Read also the Microsoft article about Using Command Redirection Operators.

The angle brackets of the XML tags must be escaped with caret character ^ to be interpreted as literal characters and not as redirection operators.

Of course the third line in data.xml is <Intersection>aktivieren</Intersection>.

The following batch file code could be used to process only lines with First or Second (case-insensitive) as first space/tab delimited string.

@echo off
if not exist "text.txt" goto :EOF
del "data.xml" 2>nul
for /F "usebackq tokens=1,2" %%I in ("text.txt") do (
    if /I "%%I" == "First" (
        echo ^<%%I^>%%J^</%%I^>>>"data.xml"
    ) else if /I "%%I" == "Second" (
        echo ^<%%I^>%%J^</%%I^>>>"data.xml"
    )
)
```

Body:
I need to Read a value from text file and put that value between tags of a XML file using batch commands.

The text file. text.txt

Input:

First 10
Second 13
Intersection aktivieren

Output file : data.xml

<First>10</First>
<Second>13</Second>

Body:
One possible batch code for this task is:

@echo off
if not exist "text.txt" goto :EOF
del "data.xml" 2>nul
for /F "usebackq tokens=1,2" %%I in ("text.txt") do echo ^<%%I^>%%J^</%%I^>>>"data.xml"

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

del /?

echo /?

for /?

goto /?

if /?

Read also the Microsoft article about Using Command Redirection Operators.

The angle brackets of the XML tags must be escaped with caret character ^ to be interpreted as literal characters and not as redirection operators.

Of course the third line in data.xml is <Intersection>aktivieren</Intersection>.

The following batch file code could be used to process only lines with First or Second (case-insensitive) as first space/tab delimited string.

@echo off
if not exist "text.txt" goto :EOF
del "data.xml" 2>nul
for /F "usebackq tokens=1,2" %%I in ("text.txt") do (
    if /I "%%I" == "First" (
        echo ^<%%I^>%%J^</%%I^>>>"data.xml"
    ) else if /I "%%I" == "Second" (
        echo ^<%%I^>%%J^</%%I^>>>"data.xml"
    )
)


问:
How to replace Email id text before @ with * in swift 3.0
Hello I have not get perfect solution for how to replace Email Id text before @ with * like

suppose my email id is XXXXXXX@gmail.com then my output I want like *******@gmail.com

I try like this

```<code>    let delimiter = "@"
    let newstr = "Himmoradiya@gmail.com"
    var token = newstr.components(separatedBy: delimiter)

    let newQuery = (token[0] as NSString).replacingCharacters(
        in: NSMakeRange(0,token[0].characters.count), with: "*")
</code>```

Any suggestion is accepted.

Thank you.

答:
Use init(repeating:count:)

```<code>  let newstr = "Himmoradiya@gmail.com"
  var token = newstr.components(separatedBy: "@")
  let newQuery = String(repeating: "*", count: token[0].characters.count)  //check array length before using index
  print(newQuery + "@" +  token[1] ) // *******@gmail.com
</code>```

Body:
Hello I have not get perfect solution for how to replace Email Id text before @ with * like

suppose my email id is XXXXXXX@gmail.com then my output I want like *******@gmail.com

I try like this

    let delimiter = "@"
    let newstr = "Himmoradiya@gmail.com"
    var token = newstr.components(separatedBy: delimiter)

    let newQuery = (token[0] as NSString).replacingCharacters(
        in: NSMakeRange(0,token[0].characters.count), with: "*")

Any suggestion is accepted.

Thank you.

Body:
Use init(repeating:count:)

  let newstr = "Himmoradiya@gmail.com"
  var token = newstr.components(separatedBy: "@")
  let newQuery = String(repeating: "*", count: token[0].characters.count)  //check array length before using index
  print(newQuery + "@" +  token[1] ) // *******@gmail.com


问:
SQL conditional that searches for substring and returns 'true' or 'false'
I need to do a mapping that is taxing my handle on SQL.

I need to know if a substring exists in a CSV contained in a table cell.  If so, I need it to return the string 'true' else 'false'

This query works in that it returns the CSV I need to check:

```<code>select table.value from table where table.user_id = 1 and table.keyname = 'email_list'
</code>```

I was attempting to include that SQL inside a conditional like this:

```<code>IF ( (select table.value from table where table.user_id = 1 and
table.keyname = 'email_list') LIKE '%substring%') THEN 'true' ELSE 'false'
</code>```

But no luck so far. This is actually one component of a much bigger query mapping different elements from one table to another so I really need it to just return a string of 'true' or 'false' for it to work appropriately.

Table structure looks something like this:

```<code>User   KEYNAME        value (in the form of CSV)
1       email_list   george@gmail.com, george@yahoo.com
2       email_list
3       email_list   kiley@yahoo.com
4       email_list   kim@gmail.com, kimmy@hotmail.com, wondergirl@yahoo.com
</code>```

答:
SELECT table.value
FROM table
WHERE EXISTS
(select table.value FROM table WHERE table.user_id = 1 AND table.keyname = 'email_list' AND table.value LIKE '%substring%');

I hope this will solve the issue.

Body:
I need to do a mapping that is taxing my handle on SQL.

I need to know if a substring exists in a CSV contained in a table cell.  If so, I need it to return the string 'true' else 'false'

This query works in that it returns the CSV I need to check:

select table.value from table where table.user_id = 1 and table.keyname = 'email_list'

I was attempting to include that SQL inside a conditional like this:

IF ( (select table.value from table where table.user_id = 1 and
table.keyname = 'email_list') LIKE '%substring%') THEN 'true' ELSE 'false'

But no luck so far. This is actually one component of a much bigger query mapping different elements from one table to another so I really need it to just return a string of 'true' or 'false' for it to work appropriately.

Table structure looks something like this:

User   KEYNAME        value (in the form of CSV)
1       email_list   george@gmail.com, george@yahoo.com
2       email_list
3       email_list   kiley@yahoo.com
4       email_list   kim@gmail.com, kimmy@hotmail.com, wondergirl@yahoo.com


问:
How to fetch images from firebase storage and show as a thumbnail?
I want to develop an application in which recycler listview fetch data from firebase database shows details to user like name, age, city and profile picture.

How to get profile picture from firebase storage and show in recycler list view and show as thumbnail.

```<code>     @Override
     public void onBindViewHolder(final UserViewHolder holder, final int position, Context context) {

    this.context = context;

    final BusinessDetailModel businessDetailModel = list.get(position);

    Picasso.with(context).load(list.get(position).getImageUrl()).resize(80, 80).into(holder.thumbnail);
    holder.businessName.setText(businessDetailModel.businessName);
    holder.businessCity.setText(businessDetailModel.city);
    holder.businessRating.setText(businessDetailModel.ratingValue + "");
</code>```

Solution,

You can add global variable:

```<code>   private Context context;
</code>```

then assign the context from here:

```<code>   @Override
    public FeedAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {

View v=LayoutInflater.from(parent.getContext()).inflate(R.layout.feedholder, parent, false);

ViewHolder vh = new ViewHolder(v);
// set the Context here
context = parent.getContext();
return vh;
}
</code>```

答:
When you have uploaded image in Firebase Storage, they have given you the URL for that image.

Use that path and make code for display thumbnail.

Firebase didn't provided the Thumbnail, so you have to make code for that.

Body:
I want to develop an application in which recycler listview fetch data from firebase database shows details to user like name, age, city and profile picture.

How to get profile picture from firebase storage and show in recycler list view and show as thumbnail.

     @Override
     public void onBindViewHolder(final UserViewHolder holder, final int position, Context context) {

    this.context = context;

    final BusinessDetailModel businessDetailModel = list.get(position);

    Picasso.with(context).load(list.get(position).getImageUrl()).resize(80, 80).into(holder.thumbnail);
    holder.businessName.setText(businessDetailModel.businessName);
    holder.businessCity.setText(businessDetailModel.city);
    holder.businessRating.setText(businessDetailModel.ratingValue + "");

Solution,

You can add global variable:

   private Context context;

then assign the context from here:

   @Override
    public FeedAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {

View v=LayoutInflater.from(parent.getContext()).inflate(R.layout.feedholder, parent, false);

ViewHolder vh = new ViewHolder(v);
// set the Context here
context = parent.getContext();
return vh;
}