问:
Variable column name in row using php 5.1.6
Something is wrong with my syntax.  I am trying to use a php variable as the column name of the row I am currently reading.  below is a snippet of my code.
The first echo of folder properly displays for word "organizations" (the column name I want, and the last echo properly display the contents of the $row_ridoh['organization'] which is 1, but the echo in the middle with the variable coded does not work. Please advise.

```<code>while($row_ridoh = mysql_fetch_array($ridoh)) {
  echo('folder: ' . $folder);
  echo('heres the real PROBLEM: ' . $row_ridoh[${$folder}]);
  echo('</br>row organizations: ' . $row_ridoh['organizations']);
  if ($row_ridoh["{$folder}"] == '1') {
    echo('keyword in if: ' . $folder);
  }
}
</code>```

I made the suggested changes to code:

```<code>     while($row_ridoh = mysql_fetch_array($ridoh)){
      echo('folder: ' . $folder);
      echo('here the real PROBLEM: ' .  $row_ridoh[$folder]);
        echo('</br>row organizations: ' . $row_ridoh['organizations']);
        if ($row_ridoh[$folder] == '1')
        {  echo('keyword in if: ' . $folder); }
      }
</code>```

The echo for 'REAL PROBLEM" still not displaying.
Here is my output when executed:

folder: organizations

Notice: Undefined index: organizations in /export/webs/inside.health/includes/sql/checkuser.php on line 30

here the real PROBLEM:

row organizations: 1

Again - thanks for the help.  I updated the code to include the var_dump.  It is listed below:

array(26) { [0]=> string(1) "1" ["id"]=> string(1) "1" [1]=> string(5) "admin" ["username"]=> string(5) "admin" [2]=> string(8) "r1health" ["password"]=> string(8) "r1health" [3]=> string(19) "2017-06-29 10:48:34" ["modified"]=> string(19) "2017-06-29 10:48:34" [4]=> string(1) "1" ["accomplishments"]=> string(1) "1" [5]=> string(1) "1" ["actions"]=> string(1) "1" [6]=> string(1) "1" ["complaints"]=> string(1) "1" [7]=> string(1) "1" ["diseases"]=> string(1) "1" [8]=> string(1) "1" ["entity"]=> string(1) "1" [9]=> string(1) "1" ["milestones"]=> string(1) "1" [10]=> string(1) "1" ["organizations"]=> string(1) "1" [11]=> string(1) "1" ["publications"]=> string(1) "1" [12]=> string(1) "1" ["specimens"]=> string(1) "1" }

It does have the column name correctly labeled as 'organizations'. The $folder variable is set in code above.  As displayed in the echo output "folder: organizations".

Looking forward to other suggestions to try.  Do you think it has anything to do with my version of php 5.1.6?

答:
This syntax, ${$folder}, tries access a variable that has the same name as the string stored in $folder. From what I gather, you just want the string stored in $folder. So, change $row_ridoh[${$folder}] to $row_ridoh[$folder].

EDIT:

I just noticed this as well: if ($row_ridoh["{$folder}"] == '1') {. This is different from what you're printing out and is also wrong. This should be changed from $row_ridoh["{$folder}"] to $row_ridoh[$folder].

Body:
Something is wrong with my syntax.  I am trying to use a php variable as the column name of the row I am currently reading.  below is a snippet of my code.
The first echo of folder properly displays for word "organizations" (the column name I want, and the last echo properly display the contents of the $row_ridoh['organization'] which is 1, but the echo in the middle with the variable coded does not work. Please advise.

while($row_ridoh = mysql_fetch_array($ridoh)) {
  echo('folder: ' . $folder);
  echo('heres the real PROBLEM: ' . $row_ridoh[${$folder}]);
  echo('
row organizations: ' . $row_ridoh['organizations']);
  if ($row_ridoh["{$folder}"] == '1') {
    echo('keyword in if: ' . $folder);
  }
}

I made the suggested changes to code:

     while($row_ridoh = mysql_fetch_array($ridoh)){
      echo('folder: ' . $folder);
      echo('here the real PROBLEM: ' .  $row_ridoh[$folder]);
        echo('
row organizations: ' . $row_ridoh['organizations']);
        if ($row_ridoh[$folder] == '1')
        {  echo('keyword in if: ' . $folder); }
      }

The echo for 'REAL PROBLEM" still not displaying.
Here is my output when executed:

folder: organizations

Notice: Undefined index: organizations in /export/webs/inside.health/includes/sql/checkuser.php on line 30

here the real PROBLEM:

row organizations: 1

Again - thanks for the help.  I updated the code to include the var_dump.  It is listed below:

array(26) { [0]=> string(1) "1" ["id"]=> string(1) "1" [1]=> string(5) "admin" ["username"]=> string(5) "admin" [2]=> string(8) "r1health" ["password"]=> string(8) "r1health" [3]=> string(19) "2017-06-29 10:48:34" ["modified"]=> string(19) "2017-06-29 10:48:34" [4]=> string(1) "1" ["accomplishments"]=> string(1) "1" [5]=> string(1) "1" ["actions"]=> string(1) "1" [6]=> string(1) "1" ["complaints"]=> string(1) "1" [7]=> string(1) "1" ["diseases"]=> string(1) "1" [8]=> string(1) "1" ["entity"]=> string(1) "1" [9]=> string(1) "1" ["milestones"]=> string(1) "1" [10]=> string(1) "1" ["organizations"]=> string(1) "1" [11]=> string(1) "1" ["publications"]=> string(1) "1" [12]=> string(1) "1" ["specimens"]=> string(1) "1" }

It does have the column name correctly labeled as 'organizations'. The $folder variable is set in code above.  As displayed in the echo output "folder: organizations".

Looking forward to other suggestions to try.  Do you think it has anything to do with my version of php 5.1.6?


来源: stackexchange

问:
Issue using PHP cURL with the Streamable API
I am hoping to build a video upload using the Streamable API and PHP with cURL. https://streamable.com/documentation#upload-video-file

What I'm trying to accomplish is:

User fills out a form of info and selects a video file from their computer/device to upload

Submits the form, PHP handles it from there to talk to the Streamable API to upload the video via the form to my Streamable account, then return the shortcode from Streamable for me to store in a MySQL database with the rest of their info

I've tried, with success, using the curl command via terminal. But, I'm having issues with pulling it off via php form submission.

This is an example of the command I used in terminal to upload, which worked:

```<code>curl https://api.streamable.com/upload -u my_email:my_pass -F file=@path/to/file.mp4
</code>```

With PHP, I have a pretty simple cURL script thanks to the tons of help online. I guess you could say I'm pretty new to using cURL.

```<code>$url = 'https://api.streamable.com/upload -u my_email.com:my_pass -F file=@path/to/file.mp4';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
</code>```

With that, I'm getting a HTTP 400 error.
https://streamable.com/documentation#errors

..codes in the 400 range indicate client errors...

I guess that's what's messing me up here?

I tried it this way, but I get the same error.

```<code>$pass = 'my_email:my_pass';
$postFields = array(
 'file' => '/path/to/file.mp4',
 'title' => 'Example Title'
);
$url = 'https://api.streamable.com/upload';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERPWD, $pass);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
</code>```

I used print_r(curl_getinfo($ch)); to see what's happening, and this is what it's spitting out - maybe this can be useful for some help:

Array ( [url] => https://api.streamable.com/upload
-u my_email:my_pass -F file=@/Path/to/file.mp4 [content_type] => [http_code] => 400 [header_size] => 66 [request_size] => 277 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 0.36033 [namelookup_time] => 0.00138 [connect_time] => 0.082871 [pretransfer_time] => 0.283219 [size_upload] => 0 [size_download] => 0 [speed_download] => 0 [speed_upload] => 0 [download_content_length] => 0 [upload_content_length] => 275 [starttransfer_time] => 0.36031 [redirect_time] => 0 [redirect_url] => [primary_ip] => xx.xx.xxx.xxx [certinfo] => Array ( ) [primary_port] => 443 [local_ip] => 192.168.0.1 [local_port] => 57288 )

答:
There are couple of things you need to change here:

Set CURLOPT_SSL_VERIFYPEER to false. It can be used to verify peer's certificate. If we specify it as false, it will accept any server(peer) certificate.

```<code>curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
</code>```

Here's a good read on the implication of turning CURLOPT_SSL_VERIFYPEER on and off, If CURLOPT_SSL_VERIFYPEER is false, is the data transfer no longer secure?

CURLOPT_POSTFIELDS is used to specify full data we want to submit with the POST request. The $postFields array should be converted to URL-encoded query string using http_build_query() function, so that it could be sent as application/x-www-form-urlencoded.

```<code>curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postFields));
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am hoping to build a video upload using the Streamable API and PHP with cURL. https://streamable.com/documentation#upload-video-file

What I'm trying to accomplish is:

User fills out a form of info and selects a video file from their computer/device to upload

Submits the form, PHP handles it from there to talk to the Streamable API to upload the video via the form to my Streamable account, then return the shortcode from Streamable for me to store in a MySQL database with the rest of their info

I've tried, with success, using the curl command via terminal. But, I'm having issues with pulling it off via php form submission.

This is an example of the command I used in terminal to upload, which worked:

curl https://api.streamable.com/upload -u my_email:my_pass -F file=@path/to/file.mp4

With PHP, I have a pretty simple cURL script thanks to the tons of help online. I guess you could say I'm pretty new to using cURL.

$url = 'https://api.streamable.com/upload -u my_email.com:my_pass -F file=@path/to/file.mp4';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);

With that, I'm getting a HTTP 400 error.
https://streamable.com/documentation#errors

..codes in the 400 range indicate client errors...

I guess that's what's messing me up here?

I tried it this way, but I get the same error.

$pass = 'my_email:my_pass';
$postFields = array(
 'file' => '/path/to/file.mp4',
 'title' => 'Example Title'
);
$url = 'https://api.streamable.com/upload';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERPWD, $pass);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);

I used print_r(curl_getinfo($ch)); to see what's happening, and this is what it's spitting out - maybe this can be useful for some help:

Array ( [url] => https://api.streamable.com/upload
-u my_email:my_pass -F file=@/Path/to/file.mp4 [content_type] => [http_code] => 400 [header_size] => 66 [request_size] => 277 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 0.36033 [namelookup_time] => 0.00138 [connect_time] => 0.082871 [pretransfer_time] => 0.283219 [size_upload] => 0 [size_download] => 0 [speed_download] => 0 [speed_upload] => 0 [download_content_length] => 0 [upload_content_length] => 275 [starttransfer_time] => 0.36031 [redirect_time] => 0 [redirect_url] => [primary_ip] => xx.xx.xxx.xxx [certinfo] => Array ( ) [primary_port] => 443 [local_ip] => 192.168.0.1 [local_port] => 57288 )

Body:
There are couple of things you need to change here:

Set CURLOPT_SSL_VERIFYPEER to false. It can be used to verify peer's certificate. If we specify it as false, it will accept any server(peer) certificate.

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

Here's a good read on the implication of turning CURLOPT_SSL_VERIFYPEER on and off, If CURLOPT_SSL_VERIFYPEER is false, is the data transfer no longer secure?

CURLOPT_POSTFIELDS is used to specify full data we want to submit with the POST request. The $postFields array should be converted to URL-encoded query string using http_build_query() function, so that it could be sent as application/x-www-form-urlencoded.

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postFields));

ContentLicense: CC BY-SA 3.0


问:
Unique Key Constraint
What's the best practice in handling data insertion/update on a table with unique key constraints at the application level? These are what I came up with:

1. Run a query on the table before inserting data to see if it will violate the constraint.

Pros

You have full control so you don't have to deal with any DBMS specific error messages.

Addtional layer of data integrity check

Cons

There might be a performance hit since there will be no constraint violation most of the time.

You will need to lock the table while you run the query for duplicate data.

2. Do nothing. Update the table and see what sticks.

Pros

Simple!

Faster overall since you don't have to run an additional query everytime you update a table.

Cons

Your validation routine depends on the database layer.

If the data doesn't stick, you have to wade through the stack trace to find the cause.

Which one is the more widely accepted solution? Are there alternatives to these?

I'm using Java, JPA, Hibernate, and Spring BTW. Any suggestions, even framework specific, are welcome!

Thanks!

答:
I like the "optimistic" approach ("do nothing"). You already enumerated the pros.
You are right that in this case you delegate validation to the DB layer. But inf you are using JPA the DB layer is also generated by java layer, so actually your validation depends on your annotation in java code. Therefore it is not a big crime.</p>

ContentLicense: CC BY-SA 2.5

Title: Unique Key Constraint


问:
Why is it hard to convert SVG to PDF client-side, isn't PDF vector format?
I'm trying to convert via javascript an svg file to a pdf file. I thought it would be simple.

But everything I've seen online rasterizes the svg and the resulting pdf looks blurry. For example:

http://ihaochi.com/svg_to_pdf/
(which converts svg to a png then puts it into a pdf document via jspdf)

But shouldn't pdf have vector capabilities? Ie, I don't want an image inside a pdf. I want numeric values kind of the way svg works, because it prints better that way.

答:
I have tested many JavaScript libraries that convert SVG to PDF for my web project including the above-mentioned one, and experienced over and over the same thing that the pdf gets produced at only screen-resolution. Finally, I have made very good experience with css2pdf (http://www.cloudformatter.com/css2pdf). It uses a small JavaScript library called "XEPOnline javascript" to extract the content of the svg including all the css-styling on the client-side, and sends this information to a XEP rendering engine on amazon cloud for generating the pdf. The output pdf file is high-resolution, please check out my example fiddle where I export Plotly.js and C3.js svg charts to pdf: http://jsfiddle.net/3hs7cs4f/10/

Here is the corresponding code to the fiddle:

```<code><link href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.css" rel="stylesheet" />
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<script src="http://www.cloudformatter.com/Resources/Pages/CSS2Pdf/Scrip /xeponline.jqplugin.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.js"></script>

<script>
function addnsandprint(){
$('#c3_chart').find('svg').attr('xmlns','http://www.w3.org/2000/svg');
xepOnline.Formatter.Format('c3_chart',{pageWidth:'11in', pageHeight:'8.5in',render:'download', srctype:'svg'});
}
</script>

<body>
<br><br>
<!-- Source and on-click event for plotly.js -->
<div id="plotly_chart" style="width: 90%; height: 270px"></div>
<button onclick="return xepOnline.Formatter.Format('plotly_chart',{pageWidth:'11in', pageHeight:'8.5in',render:'download', srctype:'svg'});">Get plotly_PDF</button>

<!-- Source and on-click event for c3.js-->
<div id="c3_chart" style="width: 90%; height: 270px"></div>
<button onclick="return addnsandprint()">Get c3_PDF</button>

<!-- JAVASCRIPT for plotly.js chart -->
<script type="text/javascript">
 Chart = document.getElementById('plotly_chart');
 Plotly.plot( Chart, [{
   x: [1, 2, 3, 4, 5],
   y: [1, 2, 4, 8, 16] }], {
   margin: { t: 0 } } );
</script>

<!-- JAVASCRIPT for j3.js chart -->
<script type="text/javascript">
   var chart = c3.generate({
   bindto: '#c3_chart',
   padding: {
       top: 10,
       right: 70,
       bottom: 50,
       left: 75,
   },
   data: {
       columns: [
           ['data1', 100, 200, 150, 300, 200],
           ['data2', 400, 500, 250, 700, 300],
       ]
   }});
</script>
</code>```

I would like to thank Kevin Brown (https://stackoverflow.com/users/2491227/kevin-brown) for his great help on getting everything running, please also have a look at my previous post SVG to PDF conversion working for Plotly.js but not for C3.js

Body:
I have tested many JavaScript libraries that convert SVG to PDF for my web project including the above-mentioned one, and experienced over and over the same thing that the pdf gets produced at only screen-resolution. Finally, I have made very good experience with css2pdf (http://www.cloudformatter.com/css2pdf). It uses a small JavaScript library called "XEPOnline javascript" to extract the content of the svg including all the css-styling on the client-side, and sends this information to a XEP rendering engine on amazon cloud for generating the pdf. The output pdf file is high-resolution, please check out my example fiddle where I export Plotly.js and C3.js svg charts to pdf: http://jsfiddle.net/3hs7cs4f/10/

Here is the corresponding code to the fiddle:

<link href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.css" rel="stylesheet" />
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<script src="http://www.cloudformatter.com/Resources/Pages/CSS2Pdf/Scrip /xeponline.jqplugin.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.js"></script>

<script>
function addnsandprint(){
$('#c3_chart').find('svg').attr('xmlns','http://www.w3.org/2000/svg');
xepOnline.Formatter.Format('c3_chart',{pageWidth:'11in', pageHeight:'8.5in',render:'download', srctype:'svg'});
}
</script>

<body>
<br><br>
<!-- Source and on-click event for plotly.js -->
<div id="plotly_chart" style="width: 90%; height: 270px"></div>
<button onclick="return xepOnline.Formatter.Format('plotly_chart',{pageWidth:'11in', pageHeight:'8.5in',render:'download', srctype:'svg'});">Get plotly_PDF</button>

<!-- Source and on-click event for c3.js-->
<div id="c3_chart" style="width: 90%; height: 270px"></div>
<button onclick="return addnsandprint()">Get c3_PDF</button>

<!-- JAVASCRIPT for plotly.js chart -->
<script type="text/javascript">
 Chart = document.getElementById('plotly_chart');
 Plotly.plot( Chart, [{
   x: [1, 2, 3, 4, 5],
   y: [1, 2, 4, 8, 16] }], {
   margin: { t: 0 } } );
</script>

<!-- JAVASCRIPT for j3.js chart -->
<script type="text/javascript">
   var chart = c3.generate({
   bindto: '#c3_chart',
   padding: {
       top: 10,
       right: 70,
       bottom: 50,
       left: 75,
   },
   data: {
       columns: [
           ['data1', 100, 200, 150, 300, 200],
           ['data2', 400, 500, 250, 700, 300],
       ]
   }});
</script>

I would like to thank Kevin Brown (https://stackoverflow.com/users/2491227/kevin-brown) for his great help on getting everything running, please also have a look at my previous post SVG to PDF conversion working for Plotly.js but not for C3.js


问:
Xamarin Forms crash when debugging
I'm trying to debugging an Xamarin Forms application but when i start the debug it's open and close the application and stop the debugger.

I'm Using VS2015 and all updates of Xamarin forms and supports

答:
The problem is:
"When i used a CRUD project with references in Android Project, if i have system.Drawing it's not build because the Android Project not accept System.Drawing.</p>

Title: Xamarin Forms crash when debugging


问:
Find number of replacements when using a global Regular Expression
I have a sentence (string) containing words. I want to replace all occurrences of a word with another. I use newString = oldString.replace(/w1/gi, w2);, but now I need to report to the user how many words I actually replaced.

Is there a quick way to do it without resorting to:

Replacing one word at a time and counting.

Comparing oldString to newString word-by-word and tallying the differences?
(The easy case is if oldString === newString => 0 replacements, but beyond that, I'll have to run over both and compare).

Is there any RegEx "trickery" I can use here, or should I just avoid using the g flag?

答:
Option 1: Using the replace callback

By using the callback, you can increment a counter, and then return the new word in the callback, this allows you to traverse the string only 1 time, and achieve a count.

var string = 'Hello, hello, hello, this is so awesome';
var count = 0;
string = string.replace(/hello/gi, function() {
  count++;
  return 'hi';
});

console.log('New string:', string);
console.log('Words replaced', count);```
</div>
</div>
</p>

<h1>Option 2: Using <code>split</code> <strong><em>and</em></strong> <code>join</code></h1>

<p>Also using the split method, instead of using regex, just join with the new word to create the new string. This solution allows you to avoid using regex at all to achieve counts.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var string = 'Hello, hello, hello, this is so awesome';

string = string.split(/hello/i);
var count = string.length - 1;
string = string.join('Hi');

console.log('New string:', string);
console.log('Words replaced', count);</code>```

Body:
Option 1: Using the replace callback

By using the callback, you can increment a counter, and then return the new word in the callback, this allows you to traverse the string only 1 time, and achieve a count.

var string = 'Hello, hello, hello, this is so awesome';
var count = 0;
string = string.replace(/hello/gi, function() {
  count++;
  return 'hi';
});

console.log('New string:', string);
console.log('Words replaced', count);

Option 2: Using split and join

Also using the split method, instead of using regex, just join with the new word to create the new string. This solution allows you to avoid using regex at all to achieve counts.

var string = 'Hello, hello, hello, this is so awesome';

string = string.split(/hello/i);
var count = string.length - 1;
string = string.join('Hi');

console.log('New string:', string);
console.log('Words replaced', count);


问:
Django system check stuck on unreachable url
In my project I have requests library that sends POST request. Url for that request is hardcoded in function, which is accessed from views.py.

The problem is that when I dont have internet connection, or host, on which url is pointing, is down, I cant launch developer server, it gets stuck on Performing system check. However, if I comment the line with url, or change it to guarantee working host, check is going well.

What is good workaround here ?

views.py

```<code>def index(request):
    s = Sync()
    s.do()
    return HttpResponse("Hello, world. You're at the polls index.")
</code>```

sync.py

```<code>class Sync:
    def do(self):
        reservations = Reservation.objects.filter(is_synced=False)
        for reservation in reservations:
            serializer = ReservationPKSerializer(reservation)
            dictionary = {'url': 'url', 'hash': 'hash', 'json': serializer.data}
            encoded_data = json.dumps(dictionary)
            r = requests.post('http://gservice.ca29983.tmweb.ru/gdocs/do.php', headers={'Content-Type': 'application/json'}, data=encoded_data)
            if r.status_code == 200:
                reservation.is_synced = True
                reservation.save()
</code>```

答:
It might appear to be stuck because requests automatically retries the connection a few times. Try reducing the retry count to 0 or 1 with:

Can I set max_retries for requests.request?

Body:
In my project I have requests library that sends POST request. Url for that request is hardcoded in function, which is accessed from views.py.

The problem is that when I dont have internet connection, or host, on which url is pointing, is down, I cant launch developer server, it gets stuck on Performing system check. However, if I comment the line with url, or change it to guarantee working host, check is going well.

What is good workaround here ?

views.py

def index(request):
    s = Sync()
    s.do()
    return HttpResponse("Hello, world. You're at the polls index.")

sync.py

class Sync:
    def do(self):
        reservations = Reservation.objects.filter(is_synced=False)
        for reservation in reservations:
            serializer = ReservationPKSerializer(reservation)
            dictionary = {'url': 'url', 'hash': 'hash', 'json': serializer.data}
            encoded_data = json.dumps(dictionary)
            r = requests.post('http://gservice.ca29983.tmweb.ru/gdocs/do.php', headers={'Content-Type': 'application/json'}, data=encoded_data)
            if r.status_code == 200:
                reservation.is_synced = True
                reservation.save()


答: A unique key is usually a business requirement, so you should use the business layer to check whether the one you intend to use is available. Delegating the checking to the database is an optimization, that should only be done when needed.</p>

Title: Unique Key Constraint

Body:
What's the best practice in handling data insertion/update on a table with unique key constraints at the application level? These are what I came up with:

1. Run a query on the table before inserting data to see if it will violate the constraint.

Pros

You have full control so you don't have to deal with any DBMS specific error messages.

Addtional layer of data integrity check

Cons

There might be a performance hit since there will be no constraint violation most of the time.

You will need to lock the table while you run the query for duplicate data.

2. Do nothing. Update the table and see what sticks.

Pros

Simple!

Faster overall since you don't have to run an additional query everytime you update a table.

Cons

Your validation routine depends on the database layer.

If the data doesn't stick, you have to wade through the stack trace to find the cause.

Which one is the more widely accepted solution? Are there alternatives to these?

I'm using Java, JPA, Hibernate, and Spring BTW. Any suggestions, even framework specific, are welcome!

Thanks!


问:
Creating two textfields with only bottom border swift
I'm trying to create two UITextFields that both only have the bottom border, I got some code from another StackOverflow and it worked. However, when I copy and pasted the code again for my second TextField it only shows one TextField with the bottom border.

Here is the code:

```<code> let border = CALayer()
 let width = CGFloat(2.0)
 border.borderColor = UIColor.gray.cgColor
 border.frame = CGRect(x: 0, y: emailText.frame.size.height -
width, width:  emailText.frame.size.width, height:
emailText.frame.size.height)

border.frame = CGRect(x: 0, y: passwordText.frame.size.height
- width, width:  passwordText.frame.size.width, height:
passwordText.frame.size.height)

    border.borderWidth = width
    passwordText.layer.addSublayer(border)
    passwordText.layer.masksToBounds = true

    border.borderWidth = width
    emailText.layer.addSublayer(border)
    emailText.layer.masksToBounds = true
</code>```

Thanks for the help!

答:
The best you could without writing redundant code is that you create a function, pass the textfields you want to border as parameters and keep the styling code in there like so:

```<code>func setBorder(tf: UITextField) {

    let border = CALayer()
    let width = CGFloat(2.0)

    border.borderColor = UIColor.gray.cgColor
    border.frame = CGRect(x: 0, y: tf.frame.size.height - width,
    width:  tf.frame.size.width, height:
    tf.frame.size.height)
    border.borderWidth = width

    tf.layer.addSublayer(border)
    tf.layer.masksToBounds = true
}
</code>```

Call this function in viewDidLoad:

```<code>setBorder(tf: emailText)
setBorder(tf: passwordText)
</code>```

Hope this helps!

Body:
I'm trying to create two UITextFields that both only have the bottom border, I got some code from another StackOverflow and it worked. However, when I copy and pasted the code again for my second TextField it only shows one TextField with the bottom border.

Here is the code:

 let border = CALayer()
 let width = CGFloat(2.0)
 border.borderColor = UIColor.gray.cgColor
 border.frame = CGRect(x: 0, y: emailText.frame.size.height -
width, width:  emailText.frame.size.width, height:
emailText.frame.size.height)

border.frame = CGRect(x: 0, y: passwordText.frame.size.height
- width, width:  passwordText.frame.size.width, height:
passwordText.frame.size.height)

    border.borderWidth = width
    passwordText.layer.addSublayer(border)
    passwordText.layer.masksToBounds = true

    border.borderWidth = width
    emailText.layer.addSublayer(border)
    emailText.layer.masksToBounds = true

Thanks for the help!

Body:
The best you could without writing redundant code is that you create a function, pass the textfields you want to border as parameters and keep the styling code in there like so:

func setBorder(tf: UITextField) {

    let border = CALayer()
    let width = CGFloat(2.0)

    border.borderColor = UIColor.gray.cgColor
    border.frame = CGRect(x: 0, y: tf.frame.size.height - width,
    width:  tf.frame.size.width, height:
    tf.frame.size.height)
    border.borderWidth = width

    tf.layer.addSublayer(border)
    tf.layer.masksToBounds = true
}

Call this function in viewDidLoad:

setBorder(tf: emailText)
setBorder(tf: passwordText)

Hope this helps!


问:
DJANGO REST API: Not NULL Constraint Failed
I'm working on a User Preferences viewset in DJANGO REST API in which a user can get a list of preferences along with updating the preferences. In Postman i can get the user's preferences, but when i go to 'put' i'm getting the following error:  Integrity Error --NOT NULL constraint failed: pugorugh_userpref.age --any reason this might be happening?

The UserPref Model is below:

```<code>class UserPref(models.Model):
    user = models.ForeignKey(User)
    age = models.CharField(choices=AGE, max_length=7, default='b,y,a,s')
    gender = models.CharField(choices=GENDER_PREF, max_length=3, default='m,f')
    size = models.CharField(choices=SIZE_PREF, max_length=8, default='s,m,l,xl')

    def __str__(self):
        return '{} preferences'.format(self.user)

def create_user_preference(sender, **kwargs):
    user = kwargs['instance']

    if kwargs['created']:
        user_pref = UserPref(user=user)
        user_pref.save()

post_save.connect(create_user_preference, sender=User)
</code>```

Here is my ViewSet:

```<code>class UserPrefViewSet(
    mixins.RetrieveModelMixin,
    mixins.UpdateModelMixin,
    viewsets.GenericViewSet):
    """View to get and update User Preferences."""
    permission_classes = (permissions.IsAuthenticated,)
    queryset = models.UserPref.objects.all()
    serializer_class = serializers.UserPrefSerializer

    # /api/user/preferences/
    @list_route(methods=['get', 'put'])
    def preferences(self, request, pk=None):
        user = request.user
        user_pref = models.UserPref.objects.get(user=user)

        if request.method == 'PUT':
            data = request.data
            user_pref.age = data.get('age')
            user_pref.gender = data.get('gender')
            user_pref.size = data.get('size')
            user_pref.save()

        serializer = serializers.UserPrefSerializer(user_pref)
        return Response(serializer.data)
</code>```

and SERIALIZER

```<code>class UserPrefSerializer(serializers.ModelSerializer):
    extra_kwargs = {
        'user': {'write_only': True}
    }

    class Meta:
        fields = (
            'age',
            'gender',
            'size'
        )
        model = models.UserPref
</code>```

答:
Looks like PUT data doesnt contain age value. Since age field is not nullable, blank age value raise error.
Try to fix this:

```<code>user_pref.age = data.get('age') or user_pref.age
...
user_pref.save()
</code>```

this allows not to change age if value not in request data.

Body:
I'm working on a User Preferences viewset in DJANGO REST API in which a user can get a list of preferences along with updating the preferences. In Postman i can get the user's preferences, but when i go to 'put' i'm getting the following error:  Integrity Error --NOT NULL constraint failed: pugorugh_userpref.age --any reason this might be happening?

The UserPref Model is below:

class UserPref(models.Model):
    user = models.ForeignKey(User)
    age = models.CharField(choices=AGE, max_length=7, default='b,y,a,s')
    gender = models.CharField(choices=GENDER_PREF, max_length=3, default='m,f')
    size = models.CharField(choices=SIZE_PREF, max_length=8, default='s,m,l,xl')

    def __str__(self):
        return '{} preferences'.format(self.user)

def create_user_preference(sender, **kwargs):
    user = kwargs['instance']

    if kwargs['created']:
        user_pref = UserPref(user=user)
        user_pref.save()

post_save.connect(create_user_preference, sender=User)

Here is my ViewSet:

class UserPrefViewSet(
    mixins.RetrieveModelMixin,
    mixins.UpdateModelMixin,
    viewsets.GenericViewSet):
    """View to get and update User Preferences."""
    permission_classes = (permissions.IsAuthenticated,)
    queryset = models.UserPref.objects.all()
    serializer_class = serializers.UserPrefSerializer

    # /api/user/preferences/
    @list_route(methods=['get', 'put'])
    def preferences(self, request, pk=None):
        user = request.user
        user_pref = models.UserPref.objects.get(user=user)

        if request.method == 'PUT':
            data = request.data
            user_pref.age = data.get('age')
            user_pref.gender = data.get('gender')
            user_pref.size = data.get('size')
            user_pref.save()

        serializer = serializers.UserPrefSerializer(user_pref)
        return Response(serializer.data)

and SERIALIZER

class UserPrefSerializer(serializers.ModelSerializer):
    extra_kwargs = {
        'user': {'write_only': True}
    }

    class Meta:
        fields = (
            'age',
            'gender',
            'size'
        )
        model = models.UserPref

Body:
Looks like PUT data doesnt contain age value. Since age field is not nullable, blank age value raise error.
Try to fix this:

user_pref.age = data.get('age') or user_pref.age
...
user_pref.save()

this allows not to change age if value not in request data.


问:
Change elements positions in an array and shift elements in between
I would like to pick an element in an array, move it to another index, and then "shift/rotate" the "in-between" elements by 1.

Imagine a drag and drop functionality, if the index from is less than index to, then I would like to shift to be to the left, and else shift to be to the right.

Input:

let data = [ 0, 1, 2, 3, 4, 5, 6 ]

Task1:
insertAndShift(data, 0, 3): Take element at index 0, shift indexes 1, 2, 3 to the left, and then insert index 0 at 3

Expected Output:

[ 1, 2, 3, 0, 4, 5, 6 ]

Task2:
insertAndShift(data, 3, 0) Take element at index 3, shift indexes 0, 1, 2 to the right and then insert index 3 at 0

Expected Output:

[ 0, 1, 2, 3, 4, 5, 6 ]

I tried this:

Following Rotating an array in place, ugly and not working code (temp always undefined + result is not complete + possible work only for RIGHT):

```<code>insertAndShift(data, from, to)
{
    if(from < to)
    {
        // rotate in between - LEFT

    }
    else
    {
        // swap elements
        let temp = data[from];
        data[from] = data[to];
        data[to] = temp;

        // rotate in between - RIGHT
        let newData = this.rotate(data.slice(to, from - 1), 1)

        let result = [];
        result.push(data.slice(0,1));
        newData.map((element) => result.push(element))
        for(let i = from+1; i < data.length; i++)
        {
            result.push(data[i]);
        }

        this.setState({data: result})
    }
}

rotate(arr, k) {
    var l = arr.length;
    arr = this.reverseArr(arr, 0, l - 1);
    arr = this.reverseArr(arr, 0, k - 1);
    arr = this.reverseArr(arr, k, l - 1);
    return arr;
}

reverseArr(arr, left, right) {
    while (left < right) {
        var temp = arr[left];
        arr[left] = arr[right];
        arr[right] = temp;
        left++;
        right--;
    }
    return arr;
}
</code>```

Also following Javascript (dynamic) insert into array, then shift all elements underneath +1, which returns only 1 item:

```<code>else
{
    let result = data.splice(to, 1, data[from]);
    this.setState({allTasksArray: result})
}
</code>```

How can I achieve this for both Left and Right?

答:
You can use Array.prototype.splice to cut out the element you want and insert at the desired index (the shifting will happen automatically):

function insertAndShift(arr, from, to) {
    let cutOut = arr.splice(from, 1) [0]; // cut the element at index 'from'
    arr.splice(to, 0, cutOut);            // insert it at index 'to'
}

let data = [ 0, 1, 2, 3, 4, 5, 6 ];

insertAndShift(data, 0, 3);
console.log("[" + data + "]");

insertAndShift(data, 3, 0);
console.log("[" + data + "]");```

Body:
I would like to pick an element in an array, move it to another index, and then "shift/rotate" the "in-between" elements by 1.

Imagine a drag and drop functionality, if the index from is less than index to, then I would like to shift to be to the left, and else shift to be to the right.

Input:

let data = [ 0, 1, 2, 3, 4, 5, 6 ]

Task1:
insertAndShift(data, 0, 3): Take element at index 0, shift indexes 1, 2, 3 to the left, and then insert index 0 at 3

Expected Output:

[ 1, 2, 3, 0, 4, 5, 6 ]

Task2:
insertAndShift(data, 3, 0) Take element at index 3, shift indexes 0, 1, 2 to the right and then insert index 3 at 0

Expected Output:

[ 0, 1, 2, 3, 4, 5, 6 ]

I tried this:

Following Rotating an array in place, ugly and not working code (temp always undefined + result is not complete + possible work only for RIGHT):

insertAndShift(data, from, to)
{
    if(from < to)
    {
        // rotate in between - LEFT

    }
    else
    {
        // swap elements
        let temp = data[from];
        data[from] = data[to];
        data[to] = temp;

        // rotate in between - RIGHT
        let newData = this.rotate(data.slice(to, from - 1), 1)

        let result = [];
        result.push(data.slice(0,1));
        newData.map((element) => result.push(element))
        for(let i = from+1; i < data.length; i++)
        {
            result.push(data[i]);
        }

        this.setState({data: result})
    }
}

rotate(arr, k) {
    var l = arr.length;
    arr = this.reverseArr(arr, 0, l - 1);
    arr = this.reverseArr(arr, 0, k - 1);
    arr = this.reverseArr(arr, k, l - 1);
    return arr;
}

reverseArr(arr, left, right) {
    while (left < right) {
        var temp = arr[left];
        arr[left] = arr[right];
        arr[right] = temp;
        left++;
        right--;
    }
    return arr;
}

Also following Javascript (dynamic) insert into array, then shift all elements underneath +1, which returns only 1 item:

else
{
    let result = data.splice(to, 1, data[from]);
    this.setState({allTasksArray: result})
}

How can I achieve this for both Left and Right?


问:
How to unfold a single column with R dataframe/data.table,
I have the following R data.table (though I'm happy to work with a dataframe for this small dataset)

```<code>library(data.table)

dt = readcsv(...)
head(dt)

   column1 column2  column3  column4    column5   column6
 1     5   456421   437141 1.044105     32935      893562
 2    42   756152   714126 1.058850     45913     1470278
 3    36   157817   150205 1.050677     14558      308022
 4    20   181700   172716 1.052016     15077      354416
</code>```

I would like to merge column2 and column3 into one column, keeping all of their associated rows, and using a binary label to keep track of where these values originally came from. The data.table I have in mind is in the following format:

```<code>   column1 combined column4   column5   column6   from_column_2
 1     5   456421   1.044105  32935      893562   TRUE
 2     5   437141   1.044105  32935      893562   FALSE
 3    42   756152   1.058850  45913     1470278   TRUE
 4    42   714126   1.058850  45913     1470278   FALSE
 5    36   157817   1.050677  14558      308022   TRUE
 6    36   150205   1.050677  14558      308022   FALSE
 ....
</code>```

I'm very confused how one would do this with data.table. Most operations are "table-wide". As for using dplyr or tidyr, I'm not sure how I'm filtering anything...

答:
I would implement this as:

```<code>library(tidyverse)
df = read_csv(...)

df %>%
  gather(from_col, combined, column2, column3) %>%
  mutate(from_column_2 = ifelse(from_col == "column2", T, F))
</code>```

Best of luck!

Body:
I have the following R data.table (though I'm happy to work with a dataframe for this small dataset)

library(data.table)

dt = readcsv(...)
head(dt)

   column1 column2  column3  column4    column5   column6
 1     5   456421   437141 1.044105     32935      893562
 2    42   756152   714126 1.058850     45913     1470278
 3    36   157817   150205 1.050677     14558      308022
 4    20   181700   172716 1.052016     15077      354416

I would like to merge column2 and column3 into one column, keeping all of their associated rows, and using a binary label to keep track of where these values originally came from. The data.table I have in mind is in the following format:

   column1 combined column4   column5   column6   from_column_2
 1     5   456421   1.044105  32935      893562   TRUE
 2     5   437141   1.044105  32935      893562   FALSE
 3    42   756152   1.058850  45913     1470278   TRUE
 4    42   714126   1.058850  45913     1470278   FALSE
 5    36   157817   1.050677  14558      308022   TRUE
 6    36   150205   1.050677  14558      308022   FALSE
 ....

I'm very confused how one would do this with data.table. Most operations are "table-wide". As for using dplyr or tidyr, I'm not sure how I'm filtering anything...

Body:
I would implement this as:

library(tidyverse)
df = read_csv(...)

df %>%
  gather(from_col, combined, column2, column3) %>%
  mutate(from_column_2 = ifelse(from_col == "column2", T, F))

Best of luck!


问:
Cannot see what is in design preview on android studio?
This is how Android Studio looks for me:

When I pick a number text and put it on a blue screen, I cannot see it to edit it. Why is that?

答:
At the very top where it says Pixel XL (to the left of it). To the right of the refresh icon.

You have 3 different boxes. The box in the middle is all blue, see it? great. Click on the box on the left that has zero blue. What do you get now?


问:
Understanding the Silverlight Dispatcher
I had a Invalid Cross Thread access issue, but a little research and I managed to fix it by using the Dispatcher.

Now in my app I have objects with lazy loading. I'd make an Async call using WCF and as usual I use the Dispatcher to update my objects DataContext, however it didn't work for this scenario. I did however find a solution here. Here's what I don't understand.

In my UserControl I have code to call an Toggle method on my object. The call to this method is within a Dispatcher like so.

```<code>Dispatcher.BeginInvoke( () => _CurrentPin.ToggleInfoPanel() );
</code>```

As I mentioned before this was not enough to satisfy Silverlight. I had to make another Dispatcher call within my object. My object is NOT a UIElement, but a simple class that handles all its own loading/saving.

So the problem was fixed by calling

```<code>Deployment.Current.Dispatcher.BeginInvoke( () => dataContext.Detail = detail );
</code>```

within my class.

Why did I have to call the Dispatcher twice to achieve this? Shouldn't a high-level call be enough? Is there a difference between the Deployment.Current.Dispatcher and the Dispatcher in a UIElement?

答:
If you use the MVVM light toolkit you could use the DispatcherHelper class in the Galasoft.MvvmLight.Threading namespace in the Extras dll. It checks the access and uses a static property for the dispatcher, similar to the SmartDispatcher.

In your App.xaml.cs startup event call:

```<code>DispatcherHelper.Initialize();
</code>```

Then anywhere you need to use a dispatcher use:

```<code>   DispatcherHelper.CheckBeginInvokeOnUI(() => // do stuff; );
</code>```

Body:
I had a Invalid Cross Thread access issue, but a little research and I managed to fix it by using the Dispatcher.

Now in my app I have objects with lazy loading. I'd make an Async call using WCF and as usual I use the Dispatcher to update my objects DataContext, however it didn't work for this scenario. I did however find a solution here. Here's what I don't understand.

In my UserControl I have code to call an Toggle method on my object. The call to this method is within a Dispatcher like so.

Dispatcher.BeginInvoke( () => _CurrentPin.ToggleInfoPanel() );

As I mentioned before this was not enough to satisfy Silverlight. I had to make another Dispatcher call within my object. My object is NOT a UIElement, but a simple class that handles all its own loading/saving.

So the problem was fixed by calling

Deployment.Current.Dispatcher.BeginInvoke( () => dataContext.Detail = detail );

within my class.

Why did I have to call the Dispatcher twice to achieve this? Shouldn't a high-level call be enough? Is there a difference between the Deployment.Current.Dispatcher and the Dispatcher in a UIElement?

Body:
If you use the MVVM light toolkit you could use the DispatcherHelper class in the Galasoft.MvvmLight.Threading namespace in the Extras dll. It checks the access and uses a static property for the dispatcher, similar to the SmartDispatcher.

In your App.xaml.cs startup event call:

DispatcherHelper.Initialize();

Then anywhere you need to use a dispatcher use:

   DispatcherHelper.CheckBeginInvokeOnUI(() => // do stuff; );


问:
Cannot find OpenTK.Audio.OpenAL C# Tutorial
I want to make an App using Xamarin.Android (which includes OpenTK library that contains an OpenAL Wrapper) that processes audio files (changes pitch, speeds up, slows down or reverse the audio). I know nothing about audio files or OpenAL and there seems to be no tutorials for OpenTK's OpenAL wrapper.</p>

答:
I had the same problem. I suggest checking out the included example, that will at least get you playing something.

Also, there are many vanilla OpenAL tutorials floating around the internet, I'd check those out next. The OpenTK function names, parameters, etc are essentially identical.

Alternatively, check out NAudio, another c# audio library. You'll find many YouTube tutorials for this one.


问:
How to get rid of degree sign?
Here is my code:

```<code>temperature = forecast.find(class_ = "myforecast-current-lrg").get_text()
temperature.replace("u'\N{DEGREE SIGN}'", '')
</code>```

However this has not worked, and I was wondering what approach to use to remove a degree sign from my string.

答:
Try:

```<code>temperature = temperature.replace(u'\N{DEGREE SIGN}', '')
</code>```

(strings are immutable, so .replace does not change the string, it creates a new string)

Title: How to get rid of degree sign?

Body:
Here is my code:

temperature = forecast.find(class_ = "myforecast-current-lrg").get_text()
temperature.replace("u'\N{DEGREE SIGN}'", '')

However this has not worked, and I was wondering what approach to use to remove a degree sign from my string.

Body:
Try:

temperature = temperature.replace(u'\N{DEGREE SIGN}', '')

(strings are immutable, so .replace does not change the string, it creates a new string)


问:
Removing elements from list
I have an array of length 900 and I want to remove the last 200 elements. I do not mind creating a new array but I want to code to be an concise and efficient as possible.

```<code>    f = [1,2,3,4,5,3,2,3,2,4,5,2....] #random one digit numbers of length 400.
    t=400
    x=200
    while(t>x):
        f = np.delete(f,t)
        t = t-1
</code>```

while this certainly works, I am looking for something that will preform the same task in less lines or at greater speed.

Title: Removing elements from list

Body:
I have an array of length 900 and I want to remove the last 200 elements. I do not mind creating a new array but I want to code to be an concise and efficient as possible.

    f = [1,2,3,4,5,3,2,3,2,4,5,2....] #random one digit numbers of length 400.
    t=400
    x=200
    while(t>x):
        f = np.delete(f,t)
        t = t-1

while this certainly works, I am looking for something that will preform the same task in less lines or at greater speed.

Body:
You can use list slicing:

f = [1,2,3,4,5,3,2,3,2,4,5,2....]

f = f[:-200]


问:
How to push a new page when clicking ion-item and retrieve data
I am using Ionic 2 and a list of clickable ion-item with details arrow:

```<code><ion-item-group>
    <button ion-item (click)="onWhenItemClick()">
      Quand
      <ion-note item-end>{{ date }}</ion-note>
    </button>
    <button ion-item (click)="onWhereItemClick()">
      Où
      <ion-note item-end>{{ location }}</ion-note>
    </button>
  </ion-item-group>
</code>```

As there is this arrow I would expect (as a user) to see a new page sliding from right to left when clicking on of these items.

For your information, each ion-item should bring me to a page that only displays a list of radio items.

I would like to recreate the same mechanisms as a select or a modal but with a page.

So basically I want to push a new page (easy) and be able to pop/dismiss it and handle this dismissal with as function like onDismiss().

How would you do that?
Pushing the new page is not

答:
To go to a new page you would need to use,

```<code>navCtrl.push(PageName)
</code>```

To send data along with the push,

```<code>navCtrl.push(PageName,{Param1:"your data"})
</code>```

To retrieve the pushed data from other page,

```<code>navParams.get("Param1")
</code>```

In your case, you can pass some data while pushing your page like this,

```<code>onWhenItemClick(itemData){
  this.navCtrl.push(PageName,{Param1:itemData)
}
</code>```

and retrieve your data from the other page

Body:
I am using Ionic 2 and a list of clickable ion-item with details arrow:

<ion-item-group>
    <button ion-item (click)="onWhenItemClick()">
      Quand
      <ion-note item-end>{{ date }}</ion-note>
    </button>
    <button ion-item (click)="onWhereItemClick()">
      Où
      <ion-note item-end>{{ location }}</ion-note>
    </button>
  </ion-item-group>

As there is this arrow I would expect (as a user) to see a new page sliding from right to left when clicking on of these items.

For your information, each ion-item should bring me to a page that only displays a list of radio items.

I would like to recreate the same mechanisms as a select or a modal but with a page.

So basically I want to push a new page (easy) and be able to pop/dismiss it and handle this dismissal with as function like onDismiss().

How would you do that?
Pushing the new page is not

Body:
To go to a new page you would need to use,

navCtrl.push(PageName)

To send data along with the push,

navCtrl.push(PageName,{Param1:"your data"})

To retrieve the pushed data from other page,

navParams.get("Param1")

In your case, you can pass some data while pushing your page like this,

onWhenItemClick(itemData){
  this.navCtrl.push(PageName,{Param1:itemData)
}

and retrieve your data from the other page


问:
Why does e.currentTarget change with jQuery's event delegation?
http://jsbin.com/xaguxuhiwu/1/edit?html,js,console,output

```<code>  <div id="container">
    <button id="foo">Foo button</button>
    <button id="bar">Bar button</button>
  </div>

$('#container').on('click', function(e) {
  var targetId = e.target.getAttribute('id');
  // Manually do event delegation
  if (targetId === 'foo') {
    var currentId = e.currentTarget.getAttribute('id');
    console.log('without delegation, currentTarget is: ' + currentId);
  }
});

$('#container').on('click', '#foo', function(e) {
    var currentId = e.currentTarget.getAttribute('id');
    console.log('with delegation, currentTarget is: ' + currentId);
});
</code>```

Basically, my understanding of e.currentTarget for an event is that it reflects the point to which the event has bubbled to. Since I have an event listener on the #container element, I would expect the currentTarget to be container in both scenarios.

This is true for the standard on handler, as shown by the first example. However, when using event delegation (the #foo argument on the second click), currentTarget changes to be the inner button.

Why does the e.currentTarget change between the two scenarios?
 Specifically, in the latter case, does this mean that jQuery is not putting the event listener on the parent (#container) element?

答:
Basically it's because of jQuery magic behind the scenes. The jQuery event object that wraps the native event is changing the currentTarget, to be what might be more-convenient.

To access the value normally pointed to by currentTarget, jQuery events have delegateTarget.

This property is most often useful in delegated events attached by .delegate() or .on(), where the event handler is attached at an ancestor of the element being processed. It can be used, for example, to identify and remove event handlers at the delegation point.

For non-delegated event handlers attached directly to an element, event.delegateTarget will always be equal to event.currentTarget.

You can see that in the originalEvent, currentTarget has the value you would expect.

$('#container').on('click', function(e) {
    console.log('without delegation:');
    console.log('target: ' + e.target.getAttribute('id'));
    console.log('currentTarget: ' + e.currentTarget.getAttribute('id'));
    console.log('originalEvent.currentTarget: ' + e.originalEvent.currentTarget.getAttribute('id'));
    console.log('delegateTarget: ' + e.delegateTarget.getAttribute('id'));
    console.log('--');
});
$('#container').on('click', '#foo', function(e) {
    console.log('with delegation:');
    console.log('target: ' + e.target.getAttribute('id'));
    console.log('currentTarget: ' + e.currentTarget.getAttribute('id'));
    console.log('originalEvent.currentTarget: ' + e.originalEvent.currentTarget.getAttribute('id'));
    console.log('delegateTarget: ' + e.delegateTarget.getAttribute('id'));
    console.log('--');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="container">
    <button id="foo">Foo button</button>
    <button id="bar">Bar button</button>
</div></code>```

Body:
http://jsbin.com/xaguxuhiwu/1/edit?html,js,console,output

    <button id="foo">Foo button</button>
    <button id="bar">Bar button</button>

$('#container').on('click', function(e) {
  var targetId = e.target.getAttribute('id');
  // Manually do event delegation
  if (targetId === 'foo') {
    var currentId = e.currentTarget.getAttribute('id');
    console.log('without delegation, currentTarget is: ' + currentId);
  }
});

$('#container').on('click', '#foo', function(e) {
    var currentId = e.currentTarget.getAttribute('id');
    console.log('with delegation, currentTarget is: ' + currentId);
});

Basically, my understanding of e.currentTarget for an event is that it reflects the point to which the event has bubbled to. Since I have an event listener on the #container element, I would expect the currentTarget to be container in both scenarios.

This is true for the standard on handler, as shown by the first example. However, when using event delegation (the #foo argument on the second click), currentTarget changes to be the inner button.

Why does the e.currentTarget change between the two scenarios?
 Specifically, in the latter case, does this mean that jQuery is not putting the event listener on the parent (#container) element?

Body:
Basically it's because of jQuery magic behind the scenes. The jQuery event object that wraps the native event is changing the currentTarget, to be what might be more-convenient.

To access the value normally pointed to by currentTarget, jQuery events have delegateTarget.

This property is most often useful in delegated events attached by .delegate() or .on(), where the event handler is attached at an ancestor of the element being processed. It can be used, for example, to identify and remove event handlers at the delegation point.

For non-delegated event handlers attached directly to an element, event.delegateTarget will always be equal to event.currentTarget.

You can see that in the originalEvent, currentTarget has the value you would expect.

$('#container').on('click', function(e) {
    console.log('without delegation:');
    console.log('target: ' + e.target.getAttribute('id'));
    console.log('currentTarget: ' + e.currentTarget.getAttribute('id'));
    console.log('originalEvent.currentTarget: ' + e.originalEvent.currentTarget.getAttribute('id'));
    console.log('delegateTarget: ' + e.delegateTarget.getAttribute('id'));
    console.log('--');
});
$('#container').on('click', '#foo', function(e) {
    console.log('with delegation:');
    console.log('target: ' + e.target.getAttribute('id'));
    console.log('currentTarget: ' + e.currentTarget.getAttribute('id'));
    console.log('originalEvent.currentTarget: ' + e.originalEvent.currentTarget.getAttribute('id'));
    console.log('delegateTarget: ' + e.delegateTarget.getAttribute('id'));
    console.log('--');
});

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

<div id="container">
    <button id="foo">Foo button</button>
    <button id="bar">Bar button</button>
</div>


问:
ion-input only allows one character to be entered at a time
On the landing page of my app I have an input box where a user needs to enter an ID to join an event. This has always been working without any issues, but now suddenly (without changing anything on that page) it only allows me to enter one character every time I focus the input box. (So if I deselect it and select it again, I can add another digit).

This only happens on iOS. In the browser and on Android it works as it should.

There are no errors in the console and I'm not changing the value of that variable programmatically anywhere.

page.ts

```<code>eventId: string;
</code>```

page.html

```<code>    <ion-list>
      <ion-item>
        <ion-input type="tel" [(ngModel)]="eventId" placeholder="Event ID" clearInput></ion-input>
      </ion-item>
    </ion-list>
</code>```

I really don't have any ideas what could cause such a behaviour, especially because I haven't changed that code in a long time.

I already spent more time on this issue that I would like to admit, maybe I'm missing something obvious?

Thanks for your help.

答:
After an hour of digging through the commit history, I finally found what caused it. I was trying to suppress the magnifying glass using css:

```<code>* {
  -webkit-user-select: none; // Hide the "bubble" on press
}
</code>```

This caused the issue. I don't really understand why, but at least it's working again now.

Body:
On the landing page of my app I have an input box where a user needs to enter an ID to join an event. This has always been working without any issues, but now suddenly (without changing anything on that page) it only allows me to enter one character every time I focus the input box. (So if I deselect it and select it again, I can add another digit).

This only happens on iOS. In the browser and on Android it works as it should.

There are no errors in the console and I'm not changing the value of that variable programmatically anywhere.

page.ts

eventId: string;

page.html

    <ion-list>
      <ion-item>
        <ion-input type="tel" [(ngModel)]="eventId" placeholder="Event ID" clearInput></ion-input>
      </ion-item>
    </ion-list>

I really don't have any ideas what could cause such a behaviour, especially because I haven't changed that code in a long time.

I already spent more time on this issue that I would like to admit, maybe I'm missing something obvious?

Thanks for your help.

Body:
After an hour of digging through the commit history, I finally found what caused it. I was trying to suppress the magnifying glass using css:

* {
  -webkit-user-select: none; // Hide the "bubble" on press
}

This caused the issue. I don't really understand why, but at least it's working again now.


问:
drawing rectangle
I am writing a program that accepts coordinates from the user and drawing some shapes on the screen with stars(*)

e.g Rectangle i.e rectangle=100,150,50,50 as x,y,width,height. how can I do it??

答:
If it's only rectangles, then putting the following in your paint method should work...

```<code>int xIncrement = (int)g.getFont().getStringBounds("*", null).getWidth();
int yIncrement = (int)g.getFont().getStringBounds("*", null).getHeight();
for(int i = y; i < y + height; i += xIncrement)
    for(int j = x; j < x + width; j += yIncrement)
        g.drawString("*", j, i);
</code>```

For triangles and other shapes it's a bit tougher, but you can figures out the gradients of the lines separating the points, and therefore get the initial x for each line.

Generally, try to avoid 'star drawing'...

OwnerDisplayName: marry

Title: drawing rectangle

Body:
If it's only rectangles, then putting the following in your paint method should work...

int xIncrement = (int)g.getFont().getStringBounds("*", null).getWidth();
int yIncrement = (int)g.getFont().getStringBounds("*", null).getHeight();
for(int i = y; i < y + height; i += xIncrement)
    for(int j = x; j < x + width; j += yIncrement)
        g.drawString("*", j, i);

For triangles and other shapes it's a bit tougher, but you can figures out the gradients of the lines separating the points, and therefore get the initial x for each line.

Generally, try to avoid 'star drawing'...


问:
Select deserialiser based on Serialised data
Sorry for the bad title, but I wasn't sure on how to name it. I need to find a way to handle the following:

I have a class

```<code>public class Event
{
     public ushort Id;
}
</code>```

This class consumer of my framework have to inherit their custom event of. So let's say if they want to create the following:

```<code>public class OnConnect : Event
{
     ...
}
</code>```

The ID is used to identify in a server/client enviroment, when the serialized byte[] data is transfered, to which event you have to deserialize the byte data. So basically in the byte[] data, the first 2 bytes contain the ushort id. Then I can read this, get the associacted type and call the correct deserializer.

But as the time showed, one potential issue or wrong usage, is, that the consumer forgets to assign a unique ushort id in their custom events or use the same id for multiple events as they don't check for that. Teaching them to use an enum as an example, tended to cause some additional problems. Anyways even if it seem easy to manage, our reports claim that this is a common issue.

So I want now to automate this to remove this possible issue. But I have really hard times, finding a possible way to solve this, as I have the following structure:

A server/client enviroment, where the process I choose, has to deliver the same result on both ends

The events itself cannot be used to initialize this number as it isn't always the same order when event x is first used.

First I thought about dependency injection with an interface like IRequireId or so and on my retrieve medthod like x.componentes.Where(c=>c is IRequireId) I assign a unique id to the event and store it somewhere else and when the event is initialized I can get the id from there. The problem with this is, that I cannot ensure, that the x.components.Where is retrieving the components in the same order as on the other peers on the network. Thus different id's could be assigned.

So I think DI is off the road. Has someone else any idea, or an idea on how to make sure, that my retrievement method does save any order, so that it is the same on each peer on the network?

As of writing this I had the idea of maybe using a HashSet and write my own GetHashcode that does reproduce the same hashcode on each peer. And then iterating over the hashset and doe the DI on the IRequireId interface. But how could I write a hashcode generation that is the same on each peer on the network? That would need and id again. Damn it.

Please help x) I'm a bit lost currently.
tia Synergi

EDIT

I forgot to note, as someone already asked this, why not simply add the type as a string into the byte array?

As this is a network enviroment, we do care about the size of the byte array. And if we just want to send let's say 4 bytes of data in an event and the byte[] itself is 20 bytes long because of 16 bytes of a string containing the type, than this is inacceptable.

EDIT

Thx to the hint with the class name I'm now able to solve it.

I use the class name to generate a hashcode

I can then use this to ensure order in my get method

And finally I can do DI with creating an ushort id

awesome thx for the help

答:
I solved similar situations in different ways. I will summarise the details. Choose the best option that suites you.

You can assign predefined Id values to your serialisers and override as necessary -

```<code>public interface IEvent
{
    ushort Id { get; }
}

public class Event: IEvent
{
    public virtual ushort Id { get { return 500; } } // a generic code for generic Event
}

public class OnConnect: Event
{
    public override ushort Id { get { return 505; } } // a more customised error code for generic Event
}
</code>```

the benefit of this scenario is that you get predefined codes and no one need to assign them as they are readonly properties.

Second approach is using the class name as the code. Since all classes are going to have unique name, so you will always get a unique key for each event as long as you maintain the name properly. A little less rigid than the previous approach but still maintainable -

```<code>public interface IEvent
{
    ushort Id { get; }
}

public class Event: IEvent
{
    public virtual ushort Id {
        get {
            var name = this.GetType().Name.Replace("Event", "");
            return name == "" ? "Generic" : name;
            //will return "Generic" for base
        }
    }
}

public class OnConnectEvent: Event
{
    //no need to override the base class will handle everything, just make sure
    //the name is correct
    //will return "OnConnect"
}

public class OnDisconnectEvent: Event
{
    //no need to override the base class will handle everything, just make sure
    //the names are correct
    //will return "OnDisconnect"
}
</code>```

you can customise even farther by making the event class abstract, in case you don't need a generic default event.

Body:
Sorry for the bad title, but I wasn't sure on how to name it. I need to find a way to handle the following:

I have a class

public class Event
{
     public ushort Id;
}

This class consumer of my framework have to inherit their custom event of. So let's say if they want to create the following:

public class OnConnect : Event
{
     ...
}

The ID is used to identify in a server/client enviroment, when the serialized byte[] data is transfered, to which event you have to deserialize the byte data. So basically in the byte[] data, the first 2 bytes contain the ushort id. Then I can read this, get the associacted type and call the correct deserializer.

But as the time showed, one potential issue or wrong usage, is, that the consumer forgets to assign a unique ushort id in their custom events or use the same id for multiple events as they don't check for that. Teaching them to use an enum as an example, tended to cause some additional problems. Anyways even if it seem easy to manage, our reports claim that this is a common issue.

So I want now to automate this to remove this possible issue. But I have really hard times, finding a possible way to solve this, as I have the following structure:

A server/client enviroment, where the process I choose, has to deliver the same result on both ends

The events itself cannot be used to initialize this number as it isn't always the same order when event x is first used.

First I thought about dependency injection with an interface like IRequireId or so and on my retrieve medthod like x.componentes.Where(c=>c is IRequireId) I assign a unique id to the event and store it somewhere else and when the event is initialized I can get the id from there. The problem with this is, that I cannot ensure, that the x.components.Where is retrieving the components in the same order as on the other peers on the network. Thus different id's could be assigned.

So I think DI is off the road. Has someone else any idea, or an idea on how to make sure, that my retrievement method does save any order, so that it is the same on each peer on the network?

As of writing this I had the idea of maybe using a HashSet and write my own GetHashcode that does reproduce the same hashcode on each peer. And then iterating over the hashset and doe the DI on the IRequireId interface. But how could I write a hashcode generation that is the same on each peer on the network? That would need and id again. Damn it.

Please help x) I'm a bit lost currently.
tia Synergi

EDIT

I forgot to note, as someone already asked this, why not simply add the type as a string into the byte array?

As this is a network enviroment, we do care about the size of the byte array. And if we just want to send let's say 4 bytes of data in an event and the byte[] itself is 20 bytes long because of 16 bytes of a string containing the type, than this is inacceptable.

EDIT

Thx to the hint with the class name I'm now able to solve it.

I use the class name to generate a hashcode

I can then use this to ensure order in my get method

And finally I can do DI with creating an ushort id

awesome thx for the help

Body:
I solved similar situations in different ways. I will summarise the details. Choose the best option that suites you.

You can assign predefined Id values to your serialisers and override as necessary -

public interface IEvent
{
    ushort Id { get; }
}

public class Event: IEvent
{
    public virtual ushort Id { get { return 500; } } // a generic code for generic Event
}

public class OnConnect: Event
{
    public override ushort Id { get { return 505; } } // a more customised error code for generic Event
}

the benefit of this scenario is that you get predefined codes and no one need to assign them as they are readonly properties.

Second approach is using the class name as the code. Since all classes are going to have unique name, so you will always get a unique key for each event as long as you maintain the name properly. A little less rigid than the previous approach but still maintainable -

public interface IEvent
{
    ushort Id { get; }
}

public class Event: IEvent
{
    public virtual ushort Id {
        get {
            var name = this.GetType().Name.Replace("Event", "");
            return name == "" ? "Generic" : name;
            //will return "Generic" for base
        }
    }
}

public class OnConnectEvent: Event
{
    //no need to override the base class will handle everything, just make sure
    //the name is correct
    //will return "OnConnect"
}

public class OnDisconnectEvent: Event
{
    //no need to override the base class will handle everything, just make sure
    //the names are correct
    //will return "OnDisconnect"
}

you can customise even farther by making the event class abstract, in case you don't need a generic default event.


答:
To put it simply, the "#foo" is the current DOM element, as that is what you clicked on. It is simply a DOM element who's parent (or parent's parent, etc) happens to be "#container".

The answer to your question therefore is "The current DOM element within the event bubbling phase." [as per jQuery docs) is "#foo".

Likewise if you called $(document).on("click","#foo",... your currentTarget would also be "#foo".

Title: Why does e.currentTarget change with jQuery's event delegation?


答:
Just remove the extra double quotes and reassign it to your variable:</p>

```<code>temperature = temperature.replace(u'\N{DEGREE SIGN}', '')
</code>```

Title: How to get rid of degree sign?

Body:
Just remove the extra double quotes and reassign it to your variable:

temperature = temperature.replace(u'\N{DEGREE SIGN}', '')


问:
Scintilla: How do you find the byte position given a specific character position
Given a specific character index on a line, e.g. 10th character on line 3, is there an easy way to calculate Scintilla's 'position' of that character?

It's straight forward when using ASCII characters but I can't see an easy way to do it when using multi-byte UTF-8 characters, where a single character may take up several byte positions.

答:
Did you tried: SCI_FINDCOLUMN ?:

SCI_FINDCOLUMN(int line, int column)

This message returns the position of a column on a line taking the width of tabs into account. It treats a multi-byte character as a single column. Column numbers, like lines start at 0.


问:
How to open update electron browser window with a new html file
I am new to electron. I have two html pages and I want to open the second page when a button clicked. I have code this as follow, but I just get a blank window; not the second page.

This is index.js

```<code>const electron = require('electron')
const {app, BrowserWindow} = electron

app.on('ready',()=>{
  let win = new BrowserWindow({width:960, hehight:540})
  win.loadURL(`file://${__dirname}/login.html`)
})

exports.openWindow = (fileName) => {
  let win = new BrowserWindow({width:960, height:540})
  win.loadURL(`file://${__dirname}/` + fileName + `.html`)
}
</code>```

This is login.js

```<code>const remote = require('electron').remote
const index = remote.require('./index.js')

var login = document.getElementById('login')
login.addEventListner('click', () => {
  var window = remote.getCurrentWindow()
  index.openWindow('pageTwo')
  window.close()
}, false)
</code>```

login is the id of the html button.

I want to get the page two. How can I perform this?

答:
I have looked at your code and from what I see you are requiring your main process, you can't do this, you need to use IPC to send a message from your render process or use the remote BrowserWindow object and get the window from an ID and use loadURL.

Using IPC

index.js

```<code>const { ipcMain } = require("electron");

ipcMain.on("changeWindow", function(event, arg) {
    switch (arg) {
        case "page1":
            win.loadURL("Page1 URL");
            break;
        case "page2":
            win.loadURL("Page2 URL");
            break;
        case "page3":
            win.loadURL("Page3 URL");
            break;
        ...
    }
});
</code>```

login.js

```<code>const { ipcRenderer } = require("electron");

function onButtonClick() {
    ipcRenderer.send("changeWindow", "page2");
}
</code>```

Second option using BrowserWindow remotely.

login.js

```<code>const { BrowserWindow } = require("electron").remote;

function onButtonClick() {
    let win = BrowserWindow.fromId("ID of your window");

    win.loadURL("URL you want to load (your login.html file)");
}

// OR

function onButtonClick() {
    let win = BrowserWindow.getFocusedWindow();

    win.loadURL("URL you want to load (your login.html file)");
}

// OR

function onButtonClick() {
    /*
        Not the best method but would work.
     */

    let wins = BrowserWindow.getAllWindows();

    let windowIndex = /* index of your window in the wins array */

    wins[windowIndex].loadURL("URL you want to load (your login.html file)");
}
</code>```

Body:
I am new to electron. I have two html pages and I want to open the second page when a button clicked. I have code this as follow, but I just get a blank window; not the second page.

This is index.js

const electron = require('electron')
const {app, BrowserWindow} = electron

app.on('ready',()=>{
  let win = new BrowserWindow({width:960, hehight:540})
  win.loadURL(`file://${__dirname}/login.html`)
})

exports.openWindow = (fileName) => {
  let win = new BrowserWindow({width:960, height:540})
  win.loadURL(`file://${__dirname}/` + fileName + `.html`)
}

This is login.js

const remote = require('electron').remote
const index = remote.require('./index.js')

var login = document.getElementById('login')
login.addEventListner('click', () => {
  var window = remote.getCurrentWindow()
  index.openWindow('pageTwo')
  window.close()
}, false)

login is the id of the html button.

I want to get the page two. How can I perform this?

Body:
I have looked at your code and from what I see you are requiring your main process, you can't do this, you need to use IPC to send a message from your render process or use the remote BrowserWindow object and get the window from an ID and use loadURL.

Using IPC

index.js

const { ipcMain } = require("electron");

ipcMain.on("changeWindow", function(event, arg) {
    switch (arg) {
        case "page1":
            win.loadURL("Page1 URL");
            break;
        case "page2":
            win.loadURL("Page2 URL");
            break;
        case "page3":
            win.loadURL("Page3 URL");
            break;
        ...
    }
});

login.js

const { ipcRenderer } = require("electron");

function onButtonClick() {
    ipcRenderer.send("changeWindow", "page2");
}

Second option using BrowserWindow remotely.

login.js

const { BrowserWindow } = require("electron").remote;

function onButtonClick() {
    let win = BrowserWindow.fromId("ID of your window");

    win.loadURL("URL you want to load (your login.html file)");
}

// OR

function onButtonClick() {
    let win = BrowserWindow.getFocusedWindow();

    win.loadURL("URL you want to load (your login.html file)");
}

// OR

function onButtonClick() {
    /*
        Not the best method but would work.
     */

    let wins = BrowserWindow.getAllWindows();

    let windowIndex = /* index of your window in the wins array */

    wins[windowIndex].loadURL("URL you want to load (your login.html file)");
}


问:
Get Common values in an single array
I want to get common values in an single array. Below I have shared my code for your reference

```<code>    $itemsVisible = $cart->getQuote()->getAllVisibleItems();

    $pack = array();
    foreach($itemsVisible as $key => $item) {
       $productid = $item->getProductId();
       $select = "SELECT `pay4later_package` FROM `pay4later_payment` where `product_id`=".$productid;
       $query = $connection->fetchall($select);
       $pack[] = array_column($query, 'pay4later_package');
    }
    $paypack = call_user_func_array('array_merge', $pack);
</code>```

Output:

```<code>$paypack = {ONIF6: 6 Months Interest Free Credit (0%),ONIF6: 6 Months Interest Free Credit (0%),ONIF12: 12 Months Interest Free Credit (0%)}
</code>```

Above output have two common values (i.e) ONIF6: 6 Months Interest Free Credit (0%),ONIF6: 6 Months Interest Free Credit (0%).

How to get those two common values in an array?

答:
You could use array_count_values() and array_filter() with filtering callbacks.

```<code>$multiple = array_filter(
    array_count_values($paypack),
    function ($count) { return $count > 1; }
);

$paypack = array_filter(
    $paypack,
    function ($value) use ($multiple) { return isset($multiple[$value]); }
);
</code>```

Title: Get Common values in an single array

Body:
I want to get common values in an single array. Below I have shared my code for your reference

    $itemsVisible = $cart->getQuote()->getAllVisibleItems();

    $pack = array();
    foreach($itemsVisible as $key => $item) {
       $productid = $item->getProductId();
       $select = "SELECT `pay4later_package` FROM `pay4later_payment` where `product_id`=".$productid;
       $query = $connection->fetchall($select);
       $pack[] = array_column($query, 'pay4later_package');
    }
    $paypack = call_user_func_array('array_merge', $pack);

Output:

$paypack = {ONIF6: 6 Months Interest Free Credit (0%),ONIF6: 6 Months Interest Free Credit (0%),ONIF12: 12 Months Interest Free Credit (0%)}

Above output have two common values (i.e) ONIF6: 6 Months Interest Free Credit (0%),ONIF6: 6 Months Interest Free Credit (0%).

How to get those two common values in an array?

Body:
You could use array_count_values() and array_filter() with filtering callbacks.

$multiple = array_filter(
    array_count_values($paypack),
    function ($count) { return $count > 1; }
);

$paypack = array_filter(
    $paypack,
    function ($value) use ($multiple) { return isset($multiple[$value]); }
);


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

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

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

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

答:
Two options:

you rework your design to become easier to test. For example by getting rid of that that new Obj2() call. Instead, you could pass a factory for Obj2 objects to that class; and use that. The factory returns mocked objects; you are fine. Or you look into other mechanisms for dependency injection.

you turn to PowerMock(ito) which allows for mocking calls to new; as outlined here for example.

My personal two cent: I recommend to go for option 1 - it is always better to improve the design; instead of using the big (ugly) PowerMock hammer to "fix" design problems. So, a simple example would like:

```<code>public class EnclosingClass {
  private final Obj2Factory factory;
  EnclosingClass(Obj2Factory factory) {
    this.factory = factory;
  }
 void a() {
   Ob2 two = factory.make();
 }
</code>```

Title: How to mock a downstream method call?

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

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

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

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

Body:
Two options:

you rework your design to become easier to test. For example by getting rid of that that new Obj2() call. Instead, you could pass a factory for Obj2 objects to that class; and use that. The factory returns mocked objects; you are fine. Or you look into other mechanisms for dependency injection.

you turn to PowerMock(ito) which allows for mocking calls to new; as outlined here for example.

My personal two cent: I recommend to go for option 1 - it is always better to improve the design; instead of using the big (ugly) PowerMock hammer to "fix" design problems. So, a simple example would like:

public class EnclosingClass {
  private final Obj2Factory factory;
  EnclosingClass(Obj2Factory factory) {
    this.factory = factory;
  }
 void a() {
   Ob2 two = factory.make();
 }


问:
Storing ZonedDateTime in Postgres database
I am using ZonedDateTime in my JPA entities. I am also using Postgres db. By default postgres creates table schema as bytea column type.

Two question I have

Is it OK to store this info as bytea format?

If I were to do SQL comparison, let’s say I want entries greater than given date, how do I write this comparison in SQL, meaning how do I convert bytea back to Date?

答:
First of all JPA just map basic and most common types.

Bytea is the type that postgres end up using when you declare a field of a type not supported, and there isn't an annotation to say how to treat it.
See https://www.postgresql.org/docs/9.0/static/datatype-binary.html.
The reasoning for using bytea is that when the type can't be mapped it assumes you want the object to be stored serialized.

At this time JPA doesn't support Java 8 types, more info on JPA standard at:
https://vladmihalcea.com/whats-new-in-jpa-2-2-java-8-date-and-time-types/

You can create a custom datatype with hibernate, some time ago i posted on this in a play framework group:

https://groups.google.com/d/msg/play-framework/3AtNiMf_WBM/LBMeztlXBAAJ

Bye

Hans


问:
How to add a second condition in a rails Active Record query
I want to do something like SQL AND to add a second condition to this:

```<code>Article
  .where("date_trunc('day', created_at) = ?", Date.yesterday-(params[:increment].to_i))
  .order('articles.created_at DESC')
</code>```

The second condition is if the 'site_id' attribute = "HIDE".

Thanks in advance for any tips.

答:
Just add another where clause with the required condition:

```<code>Article
  .where("date_trunc('day', created_at) = ?", Date.yesterday-(params[:increment].to_i))
  .where(site_id: 'HIDE')
  .order('articles.created_at DESC')
</code>```

Body:
I want to do something like SQL AND to add a second condition to this:

Article
  .where("date_trunc('day', created_at) = ?", Date.yesterday-(params[:increment].to_i))
  .order('articles.created_at DESC')

The second condition is if the 'site_id' attribute = "HIDE".

Thanks in advance for any tips.

Body:
Just add another where clause with the required condition:

Article
  .where("date_trunc('day', created_at) = ?", Date.yesterday-(params[:increment].to_i))
  .where(site_id: 'HIDE')
  .order('articles.created_at DESC')


问:
Convert a key string to a SecretKeys object in tozny/java-aes-crypto
I'm using java-aes-crypto for encrypting strings in android. After generating key using this code

```<code>AesCbcWithIntegrity.SecretKeys keys = AesCbcWithIntegrity.generateKey();
</code>```

and I'm saving it as String(.toString()) in a file and after that I'm trying to retrieve it from that file and convert it to the same object. How can I do that?

答:
Use the following static method in the AesCbcWithIntegrity class (link):

```<code>/**
 * An aes key derived from a base64 encoded key. This does not generate the
 * key. It's not random or a PBE key.
 *
 * @param keysStr a base64 encoded AES key / hmac key as base64(aesKey) : base64(hmacKey).
 * @return an AES and HMAC key set suitable for other functions.
 */
public static SecretKeys keys(String keysStr) throws InvalidKeyException {...}
</code>```

It properly parses the previously serialized keys into the encryption key and the integrity key.

Body:
I'm using java-aes-crypto for encrypting strings in android. After generating key using this code

AesCbcWithIntegrity.SecretKeys keys = AesCbcWithIntegrity.generateKey();

and I'm saving it as String(.toString()) in a file and after that I'm trying to retrieve it from that file and convert it to the same object. How can I do that?

Body:
Use the following static method in the AesCbcWithIntegrity class (link):

/**
 * An aes key derived from a base64 encoded key. This does not generate the
 * key. It's not random or a PBE key.
 *
 * @param keysStr a base64 encoded AES key / hmac key as base64(aesKey) : base64(hmacKey).
 * @return an AES and HMAC key set suitable for other functions.
 */
public static SecretKeys keys(String keysStr) throws InvalidKeyException {...}

It properly parses the previously serialized keys into the encryption key and the integrity key.


问:
can not load oci8 -> Fatal error: Call to undefined function oci_connect()
I want to connect to my oracle database, but i have a problem with function oci_connect. i have tried to uncomment this:

```<code>extension=php_oci8.dll
</code>```

but, still have an error :

Fatal error: Call to undefined function oci_connect() in C:\xampp\htdocs\testing\db.php on line 71

But, when i check in phpinfo(), oci8 still not loaded and i can not connect to my oracle database. i already restart my apache. How i fix this problem ? Canyou help me?

Thank you..

答:
In Ubuntu 16.04, using PHP 5.6, with 64bit os, try this:

Install the packages:

```<code>sudo apt-get install php5.6-dev build-essential php-pear libaio1
</code>```

Download the latest version of the packages from:

```<code>http://www.oracle.com/technetwork/topics/linuxx86-64soft-092277.html
</code>```

Search for these packages, according with the latest version:

```<code>oracle-instantclientXX.X-basic-XX.X.X.X.X-X.x86_64.rpm
oracle-instantclientXX.X-devel-XX.X.X.X.X-X.x86_64.rpm
</code>```

Converting packages:

```<code>sudo apt-get install alien
sudo alien oracle-instantclientXX.X-basic-XX.X.X.X.X-X.x86_64.rpm
sudo alien oracle-instantclientXX.X-devel-XX.X.X.X.X-X.x86_64.rpm
</code>```

Installing:

```<code>sudo dpkg -i oracle-instantclientXX.X-basic_XX.X.X.X.X-X_amd64.deb
sudo dpkg -i oracle-instantclientXX.X-devel_XX.X.X.X.X-X_amd64.deb
</code>```

Installing oci8:

```<code>sudo pecl install oci8-2.0.12

*Build process completed successfully
Installing '/usr/lib/php/20131226/oci8.so'
install ok: channel://pecl.php.net/oci8-2.0.12
configuration option "php_ini" is not set to php.ini location
You should add "extension=oci8.so" to php.ini*
</code>```

Add the extension to php:

```<code>sudo gedit /etc/php/5.6/apache2/php.ini
</code>```

add the extension:

```<code>extension=oci8.so
</code>```

Restart apache:

```<code>sudo service apache2 restart
</code>```

That's it.

Body:
I want to connect to my oracle database, but i have a problem with function oci_connect. i have tried to uncomment this:

extension=php_oci8.dll

but, still have an error :

Fatal error: Call to undefined function oci_connect() in C:\xampp\htdocs\testing\db.php on line 71

But, when i check in phpinfo(), oci8 still not loaded and i can not connect to my oracle database. i already restart my apache. How i fix this problem ? Canyou help me?

Thank you..

Body:
In Ubuntu 16.04, using PHP 5.6, with 64bit os, try this:

Install the packages:

sudo apt-get install php5.6-dev build-essential php-pear libaio1

Download the latest version of the packages from:

http://www.oracle.com/technetwork/topics/linuxx86-64soft-092277.html

Search for these packages, according with the latest version:

oracle-instantclientXX.X-basic-XX.X.X.X.X-X.x86_64.rpm
oracle-instantclientXX.X-devel-XX.X.X.X.X-X.x86_64.rpm

Converting packages:

sudo apt-get install alien
sudo alien oracle-instantclientXX.X-basic-XX.X.X.X.X-X.x86_64.rpm
sudo alien oracle-instantclientXX.X-devel-XX.X.X.X.X-X.x86_64.rpm

Installing:

sudo dpkg -i oracle-instantclientXX.X-basic_XX.X.X.X.X-X_amd64.deb
sudo dpkg -i oracle-instantclientXX.X-devel_XX.X.X.X.X-X_amd64.deb

Installing oci8:

sudo pecl install oci8-2.0.12

*Build process completed successfully
Installing '/usr/lib/php/20131226/oci8.so'
install ok: channel://pecl.php.net/oci8-2.0.12
configuration option "php_ini" is not set to php.ini location
You should add "extension=oci8.so" to php.ini*

Add the extension to php:

sudo gedit /etc/php/5.6/apache2/php.ini

add the extension:

extension=oci8.so

Restart apache:

sudo service apache2 restart

That's it.


问:
Change telegram bot owner
We have created telegram bot which has many difficult operations. Bot was created by one developer using his phone number. Is it possible change bot's owner or add another user as admin to bot? </p>

答:
the developer can delete all of other bots and channel and chat history, then use CHANGE NUMBER in setting and transfer the bot to new virgin mobile number.
after this, the developer can login again with his/her own mobile number to telegram as new account.

Title: Change telegram bot owner


问:
Excel vba Error 5 Invalid procedure call or argument with power operand
Please consider this sub:

```<code>Sub TestPower()

    Dim dbl As Double

    dbl = -0.682434999562851

    Debug.Print (-0.682434999562851 ^ 0.2)
    Debug.Print (dbl ^ 0.2)
End Sub
</code>```

On the second "debug.print" command, I'm getting an Error 5: Invalid procedure call or argument.

Excel Office 2016.

Any ideas?

答: It seems that when you use the literal, VBA interprets the expression (-0.6824 ^ 0.2) as (-(0.6824 ^ 0.2)), but when you use the variable, it realizes you're trying to compute a fractional power of a negative number and gives up.</p>

Body:
Please consider this sub:

Sub TestPower()

    Dim dbl As Double

    dbl = -0.682434999562851

    Debug.Print (-0.682434999562851 ^ 0.2)
    Debug.Print (dbl ^ 0.2)
End Sub

On the second "debug.print" command, I'm getting an Error 5: Invalid procedure call or argument.

Excel Office 2016.

Any ideas?