问:
How to make div have the same height as the smallest div?
So I have a list next to a video player, as seen here

I want the menu to be scrollable, and only have it as big as the video player. The problem is that the video player is responsive, so the height can vary based upon how wide the screen is.

The HTML code looks a bit like this:

```<code><div class="row justify-content-center" id="chat">
    <div class="col-9">
        <video id="my-video" class="video-js vjs-big-play-centered" controls preload="auto">
        </video>
    </div>
    <div class="col-3">
          <ul class="nav nav-pills flex-column list-scroll">
            <li class="nav-item">
              <a class="nav-link active" href="#">Active</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#">Link</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#">Link</a>
            </li><li class="nav-item">
              <a class="nav-link" href="#">Link</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#">Link</a>
            </li><li class="nav-item">
              <a class="nav-link" href="#">Link</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#">Link</a>
            </li><li class="nav-item">
              <a class="nav-link" href="#">Link</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#">Link</a>
            </li><li class="nav-item">
              <a class="nav-link" href="#">Link</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#">Link</a>
            </li>
            <li class="nav-item">
              <a class="nav-link disabled" href="#">Disabled</a>
            </li>
          </ul>
        </div>
</div>
</code>```

答:
You can use position: absolute on the scrollable element to remove it from the flow of the page, and use overflow-y: scroll

.chat > .col-3 > .nav {
  position: absolute;
  top: 0; left: 0; right: 0; bottom: 0;
  overflow-y: scroll;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
  <div class="row justify-content-center chat" id="chat">
    <div class="col-9">
      <video id="my-video" class="video-js vjs-big-play-centered" controls preload="auto">
        </video>
    </div>
    <div class="col-3">
      <ul class="nav nav-pills flex-column list-scroll">
        <li class="nav-item">
          Active
        </li>
        <li class="nav-item">
          Link
        </li>
        <li class="nav-item">
          Link
        </li>
        <li class="nav-item">
          Link
        </li>
        <li class="nav-item">
          Link
        </li>
        <li class="nav-item">
          Link
        </li>
        <li class="nav-item">
          Link
        </li>
        <li class="nav-item">
          Link
        </li>
        <li class="nav-item">
          Link
        </li>
        <li class="nav-item">
          Link
        </li>
        <li class="nav-item">
          Link
        </li>
        <li class="nav-item">
          Disabled
        </li>
      </ul>
    </div>
  </div>
</div></code>```

Body:
So I have a list next to a video player, as seen here

I want the menu to be scrollable, and only have it as big as the video player. The problem is that the video player is responsive, so the height can vary based upon how wide the screen is.

The HTML code looks a bit like this:

        <video id="my-video" class="video-js vjs-big-play-centered" controls preload="auto">
        </video>

              Active

              Link

              Link

              Link

              Link

              Link

              Link

              Link

              Link

              Link

              Link

              Disabled

Body:
You can use position: absolute on the scrollable element to remove it from the flow of the page, and use overflow-y: scroll

.chat > .col-3 > .nav {
  position: absolute;
  top: 0; left: 0; right: 0; bottom: 0;
  overflow-y: scroll;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
  <div class="row justify-content-center chat" id="chat">
    <div class="col-9">
      <video id="my-video" class="video-js vjs-big-play-centered" controls preload="auto">
        </video>
    </div>
    <div class="col-3">
      <ul class="nav nav-pills flex-column list-scroll">
        <li class="nav-item">
          <a class="nav-link active" href="#">Active</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Link</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Link</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Link</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Link</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Link</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Link</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Link</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Link</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Link</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Link</a>
        </li>
        <li class="nav-item">
          <a class="nav-link disabled" href="#">Disabled</a>
        </li>
      </ul>
    </div>
  </div>
</div>


来源: stackexchange

问:
create sql database from sql express database
I am working on asp.net membership website. I created the membership provider automatically, and now its stored in sql express database within the solution. I want to move all the tables to sql database instead of sql express. Last night I attached the sql express database to the sql server management studio, and I was able to see all the objects. Then, I run my solution in visual studio, and I got error: LOGIN FAILED for the sql express database, and the solution wasn't running.
I have two questions.
1. Why is that happening?
2. If I create the same database in sql server with the same objects, and then point to the sql server database instead of sql express database, will I have problems with the membershop provider?
Thanks in advance.</p>

答:
It sounds like you've moved a database from one host (running SQL Server Express) to another host (running a non-Express SKU). Is this correct?

Ensure that your membership connection string is pointing to the new location of the membership (the non-Express SQL Server). Ensure the logins and users are setup properly in the new SQL Server instance, as expected.

ContentLicense: CC BY-SA 2.5


问:
Airflow - run task regardless of upstream success/fail
I have a DAG which fans out to multiple independent units in parallel. This runs in AWS, so we have tasks which scale our AutoScalingGroup up to the maximum number of workers when the DAG starts, and to the minimum when the DAG completes. The simplified version looks like this:

```<code>           | - - taskA - - |
           |               |
scaleOut - | - - taskB - - | - scaleIn
           |               |
           | - - taskC - - |
</code>```

However, some of the tasks in the parallel set fail occasionally, and I can't get the scaleDown task to run when any of the A-C tasks fail.

What's the best way to have a task execute at the end of the DAG, once all other tasks have completed (success or fail)? The depends_on_upstream setting sounded like what we needed, but didn't actually do anything based on testing.

答:
All operators have an argument trigger_rule which can be set to 'all_done', which will trigger that task regardless of the failure or success of the previous task(s).

You could set the trigger rule for the task you want to run to 'all_done' instead of the default 'all_success'.

A simple bash operator task with that argument would look like:

```<code>task = BashOperator(
    task_id="hello_world",
    bash_command="echo Hello World!",
    trigger_rule="all_done",
    dag=dag
    )
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a DAG which fans out to multiple independent units in parallel. This runs in AWS, so we have tasks which scale our AutoScalingGroup up to the maximum number of workers when the DAG starts, and to the minimum when the DAG completes. The simplified version looks like this:

           | - - taskA - - |
           |               |
scaleOut - | - - taskB - - | - scaleIn
           |               |
           | - - taskC - - |

However, some of the tasks in the parallel set fail occasionally, and I can't get the scaleDown task to run when any of the A-C tasks fail.

What's the best way to have a task execute at the end of the DAG, once all other tasks have completed (success or fail)? The depends_on_upstream setting sounded like what we needed, but didn't actually do anything based on testing.

Body:
All operators have an argument trigger_rule which can be set to 'all_done', which will trigger that task regardless of the failure or success of the previous task(s).

You could set the trigger rule for the task you want to run to 'all_done' instead of the default 'all_success'.

A simple bash operator task with that argument would look like:

task = BashOperator(
    task_id="hello_world",
    bash_command="echo Hello World!",
    trigger_rule="all_done",
    dag=dag
    )


问:
Country Selector with Flags with jQuery
I want to populate my dropdown list with countries and relevant flags. I went through this question.

Html Country List with flags

But still can't understand because the working model is broken.
How to do this?

答:
And here's a searchable dropdown based on select2:

```<code>$(function() {
  var isoCountries = [
    { id: 'AF', text: 'Afghanistan'},
    { id: 'AX', text: 'Aland Islands'},
    { id: 'AL', text: 'Albania'},
    { id: 'DZ', text: 'Algeria'},
    { id: 'AS', text: 'American Samoa'},
    // etc
  ];

  function formatCountry (country) {
    if (!country.id) { return country.text; }
    var $country = $(
      '<span class="flag-icon flag-icon-'+ country.id.toLowerCase() +' flag-icon-squared"></span>' +
      '<span class="flag-text">'+ country.text+"</span>"
    );
    return $country;
  };

  //Assuming you have a select element with name country
  // e.g. <select name="name"></select>

  $("[name='country']").select2({
    placeholder: "Select a country",
    templateResult: formatCountry,
    data: isoCountries
  });

});
</code>```

jsFiddle

ContentLicense: CC BY-SA 4.0

Title: Country Selector with Flags with jQuery

Body:
And here's a searchable dropdown based on select2:

$(function() {
  var isoCountries = [
    { id: 'AF', text: 'Afghanistan'},
    { id: 'AX', text: 'Aland Islands'},
    { id: 'AL', text: 'Albania'},
    { id: 'DZ', text: 'Algeria'},
    { id: 'AS', text: 'American Samoa'},
    // etc
  ];

  function formatCountry (country) {
    if (!country.id) { return country.text; }
    var $country = $(
      '<span class="flag-icon flag-icon-'+ country.id.toLowerCase() +' flag-icon-squared"></span>' +
      '<span class="flag-text">'+ country.text+"</span>"
    );
    return $country;
  };

  //Assuming you have a select element with name country
  // e.g. <select name="name"></select>

  $("[name='country']").select2({
    placeholder: "Select a country",
    templateResult: formatCountry,
    data: isoCountries
  });

});

jsFiddle


问:
LaravelFacebookSDK Operation timed out after 0 milliseconds with 0 out of 0 bytes received
How I can increment the timeout from the laravelfacebooksdk, i get the error:

[Facebook\Exceptions\FacebookSDKException]
Operation timed out after 0 milliseconds with 0 out of 0 bytes received

Note that i use the wrapper laravel facebook sdk

答:
I modified this files to allow a new http_client_handler
I create a new instance and in this updated the htt_client_handler, updated the composer.json for read the Facebooksdk classes.

composer.json

```<code>"autoload": {"classmap":
["database","/var/www/laravel/vendor/facebook/graph-sdk/src/Facebook"]
</code>```

class xxx.php

```<code>class LongerTimeoutHttpClient extends
Facebook\HttpClients\FacebookStreamHttpClient
{public function send($url, $method, $body, array $headers, $timeOut){
$timeOut *= 4;
return parent::send($url, $method, $body, $headers, $timeOut);}}

public function handle(SammyK\LaravelFacebookSdk\LaravelFacebookSdk $fb)
{
$fbStream = new Facebook\HttpClients\FacebookStream;
$fb2 = $fb->newInstance([
'app_id' => env('FACEBOOK_APP_ID'),
'app_secret' => env('FACEBOOK_APP_SECRET'),
'default_graph_version' => 'v2.9',
'http_client_handler' => new LongerTimeoutHttpClient($fbStream),]);
}
</code>```

In this way i allow the value timeout in the instances $fb.

Body:
I modified this files to allow a new http_client_handler
I create a new instance and in this updated the htt_client_handler, updated the composer.json for read the Facebooksdk classes.

composer.json

"autoload": {"classmap":
["database","/var/www/laravel/vendor/facebook/graph-sdk/src/Facebook"]

class xxx.php

class LongerTimeoutHttpClient extends
Facebook\HttpClients\FacebookStreamHttpClient
{public function send($url, $method, $body, array $headers, $timeOut){
$timeOut *= 4;
return parent::send($url, $method, $body, $headers, $timeOut);}}

public function handle(SammyK\LaravelFacebookSdk\LaravelFacebookSdk $fb)
{
$fbStream = new Facebook\HttpClients\FacebookStream;
$fb2 = $fb->newInstance([
'app_id' => env('FACEBOOK_APP_ID'),
'app_secret' => env('FACEBOOK_APP_SECRET'),
'default_graph_version' => 'v2.9',
'http_client_handler' => new LongerTimeoutHttpClient($fbStream),]);
}

In this way i allow the value timeout in the instances $fb.


问:
Python Exception: ValueError: too many values to unpack (expected 2)
im trying to find the mistake in my code.
My IDE (Coderunner on Mac) only says this:

```<code>File "A3.py", line 27, in <module>
ValueError: too many values to unpack (expected 2)
</code>```

I never had this exception. I don't know how to handle it and where the problem is. What I am doing wrong?

This is my code... I commented line 27.

```<code>with open("spd.txt", encoding="utf-8") as f:
    text = f.read()
text = text.replace("\xad", "")

words = []
for word in text.lower().split():
    word = word.strip("‚‘!,.:«»-()'_#-–„“■;+*?")
    if word != "":
        if not word[-1].isalnum():
            print(repr(word))
        words.append(word)

trigrams = {}
for i in range(len(words)-2):
       word = words[i]
       nextword = words[i + 1]
       nextnextword = words[i + 2]
       key = (word, nextword, nextnextword)
       trigrams[key] = trigrams.get(key, 0) + 1

l = list(trigrams.items())
l.sort(key=lambda x: (x[1], x[0]))
l.reverse()

for key, count in trigrams: #This is line 27
    if count < 5:
        break
    word = key[0]
    nextword = key[1]
    nextnextword = key[2]
    print(word, nextword, nextnextword, count)
</code>```

答:
When your do

```<code>for key, count in trigrams:
    # do stuff
</code>```

it is equivalent to:

```<code>it = iter(trigrams)
while True:
    try:
        key, count = it.__next__()
        # do stuff
    except StopIteration:
        break
</code>```

This is what Python does behind the scenes when you iterate over an iterable. As you can see from the above code, a function call to the __next__() method of the trigrams dictionary's iterator is made when trigrams is iterated over. The __next__() function only returns the next key in the dictionary though. eg:

```<code>>>> d = {'a': 1, 'b': 2}
>>> iter(d).__next__()
'a'
>>>
</code>```

So when you try to unpack the return value of iter(trigrams).__next__(), Python raises an error because only one value is returned, not two. eg:

```<code>>>> d = {'a': 1, 'b': 2}
>>> a, b = iter(d).__next__()
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    a, b = iter(d).__next__()
ValueError: not enough values to unpack (expected 2, got 1)
>>>
</code>```

To fix this, you need to use the dict.items() method to return a tuple which contains a key, value pair which you can then unpack. From the documentation on .items():

Return a new view of the dictionary’s items ((key, value) pairs). See the documentation of view objects.

```<code>for key, count in trigrams.items(): # Use the .items() method
    if count < 5:
        break
    word = key[0]
    nextword = key[1]
    nextnextword = key[2]
    print(word, nextword, nextnextword, count)
</code>```

Body:
im trying to find the mistake in my code.
My IDE (Coderunner on Mac) only says this:

File "A3.py", line 27, in <module>
ValueError: too many values to unpack (expected 2)

I never had this exception. I don't know how to handle it and where the problem is. What I am doing wrong?

This is my code... I commented line 27.

with open("spd.txt", encoding="utf-8") as f:
    text = f.read()
text = text.replace("\xad", "")

words = []
for word in text.lower().split():
    word = word.strip("‚‘!,.:«»-()'_#-–„“■;+*?")
    if word != "":
        if not word[-1].isalnum():
            print(repr(word))
        words.append(word)

trigrams = {}
for i in range(len(words)-2):
       word = words[i]
       nextword = words[i + 1]
       nextnextword = words[i + 2]
       key = (word, nextword, nextnextword)
       trigrams[key] = trigrams.get(key, 0) + 1

l = list(trigrams.items())
l.sort(key=lambda x: (x[1], x[0]))
l.reverse()

for key, count in trigrams: #This is line 27
    if count < 5:
        break
    word = key[0]
    nextword = key[1]
    nextnextword = key[2]
    print(word, nextword, nextnextword, count)

Body:
When your do

for key, count in trigrams:
    # do stuff

it is equivalent to:

it = iter(trigrams)
while True:
    try:
        key, count = it.__next__()
        # do stuff
    except StopIteration:
        break

This is what Python does behind the scenes when you iterate over an iterable. As you can see from the above code, a function call to the __next__() method of the trigrams dictionary's iterator is made when trigrams is iterated over. The __next__() function only returns the next key in the dictionary though. eg:

>>> d = {'a': 1, 'b': 2}
>>> iter(d).__next__()
'a'
>>>

So when you try to unpack the return value of iter(trigrams).__next__(), Python raises an error because only one value is returned, not two. eg:

>>> d = {'a': 1, 'b': 2}
>>> a, b = iter(d).__next__()
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    a, b = iter(d).__next__()
ValueError: not enough values to unpack (expected 2, got 1)
>>>

To fix this, you need to use the dict.items() method to return a tuple which contains a key, value pair which you can then unpack. From the documentation on .items():

Return a new view of the dictionary’s items ((key, value) pairs). See the documentation of view objects.

for key, count in trigrams.items(): # Use the .items() method
    if count < 5:
        break
    word = key[0]
    nextword = key[1]
    nextnextword = key[2]
    print(word, nextword, nextnextword, count)


问:
SQL: Get value at index in binary value
Is there a SQL command that could be used in a query, stored procedure, function, that would work against a Binary Type similar to the following C# code?

```<code>if (someBinaryArray[index] == 0) {
...
</code>```

I'm wanting to check if an index of a position in the binary is a certain value instead of pulling the entire array down and doing the comparison?

答:
If you work on MSSQL Server, you can use the READTEXT command</p>

```<code>CREATE TABLE #t (b varbinary(1))

DECLARE @ptrval varbinary(16)
SELECT @ptrval = TEXTPTR(mybinarraycolumn)
FROM mytable WHERE pk = @pk

INSERT INTO #t (b)
READTEXT pub_info.pr_info @ptrval @index 1

DECLARE @b varbinary(1)
SELECT @b = b FROM #t
</code>```

OwnerDisplayName: HBoss

Title: SQL: Get value at index in binary value

Body:
Is there a SQL command that could be used in a query, stored procedure, function, that would work against a Binary Type similar to the following C# code?

if (someBinaryArray[index] == 0) {
...

I'm wanting to check if an index of a position in the binary is a certain value instead of pulling the entire array down and doing the comparison?

Body:
If you work on MSSQL Server, you can use the READTEXT command

CREATE TABLE #t (b varbinary(1))

DECLARE @ptrval varbinary(16)
SELECT @ptrval = TEXTPTR(mybinarraycolumn)
FROM mytable WHERE pk = @pk

INSERT INTO #t (b)
READTEXT pub_info.pr_info @ptrval @index 1

DECLARE @b varbinary(1)
SELECT @b = b FROM #t

OwnerDisplayName: devio


问:
Can the VM of MVVM be reused?
I just need a simple clarification:

I have an example application with a Model of a ball, and two views (lets say one shows the ball and lets you resize if with the mouse, change it's colour with a click, the second has a control with two child controls (size textbox and colour picker)).

Does MVVM say I must have two VM here, one for each specific View, or am I allowed to reuse the VM without breaking the pattern?

As a follow up question, if I am required to have two VM's is it legitimate, according to the pattern to have one as a derived type of the other, or both as derived types of a base class, or composite classes based on common parts? Basically fulfilling the need for two types but improving reuse?

My example is contrived, I've tried to make the point that both Views affect the same two properties of the model. Max size, available colours, etc are the same between both views.

Thanks

答:
Although not directly answering your question, check out this insightful post from Josh Smith regarding the re-use of ViewModels and the "friction" caused from sharing: http://groups.google.com/group/wpf-disciples/msg/c29b3935ec9d3c4e

He is basically proposing an improvement to MVVM (calling it MMVVVM; phew!) - the extra MV is for ModelView. As the others have mentioned, the ViewModel is specific to a View and re-using that is not very likely. But rather, create a wrapper around the Model (the ModelView), which can be re-used with any ViewModel.

Title: Can the VM of MVVM be reused?


问:
Querying XML with Python
Consider the following XML code.

```<code><?xml version="1.0"?>
<data>
    <element>This is the first sentence.<button>Click</button>some more text.
</element>
</data>
</code>```

I am using Python module xml.etree.ElementTree.
I know that I can access to elements and texts with the following Python code

```<code>import xml.etree.ElementTree as ET

name = 'data.xml'
tree = ET.parse(name)
root = tree.getroot()
element = root[0].tag
first_text = root[0].text #This is the first sentence
button = root[0][0].tag #button
buttontext = root[0][0].text #click
</code>```

But how do I access to text "some more text" with Python?
I haven't found the solution yet...
You can also suggest some other Python module if it's better way to do that.

That XML-code is just an example.

答: you are looking for the .tail attribute of the <button> element: https://docs.python.org/3/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.tail

Title: Querying XML with Python

Body:
Consider the following XML code.

<?xml version="1.0"?>
<data>
    <element>This is the first sentence.<button>Click</button>some more text.
</element>
</data>

I am using Python module xml.etree.ElementTree.
I know that I can access to elements and texts with the following Python code

import xml.etree.ElementTree as ET

name = 'data.xml'
tree = ET.parse(name)
root = tree.getroot()
element = root[0].tag
first_text = root[0].text #This is the first sentence
button = root[0][0].tag #button
buttontext = root[0][0].text #click

But how do I access to text "some more text" with Python?
I haven't found the solution yet...
You can also suggest some other Python module if it's better way to do that.

That XML-code is just an example.


问:
What does an implicit enumeration conversion convert?
From C# 5.0 Specification

6.1.3 Implicit enumeration conversions

An implicit enumeration conversion permits the
  decimal-integer-literal 0 to be converted to any enum-type and  to
  any nullable-type whose underlying type is an enum-type. In the latter
  case the conversion is evaluated by  converting to the underlying
  enum-type and wrapping the result (§4.1.10).

Does "the decimal-integer-literal 0" mean the integer value 0?

If yes, why does an implicit enumeration conversion not permit other integer values such as 1, 2, 3, ... to be converted to any enum-type?

Thanks.

答:
Yes, it means the literal 0. For example:

```<code>static void Main()
{
   Method(0);
}

static void Method(DayOfWeek dow)
{
  Console.WriteLine(dow);
}
</code>```

should print Sunday to the console. If you change 0 into 1, the program is illegal (compile-time error).

Only the (compile-time constant) zero has an implicit conversion to the enum type. For other values, you need an explicit cast instead, as in Method((DayOfWeek)1);.

Edit: This explains how the rules are. If you want to know why they chose those rules, I recommend the links in the comments (to your question above) by  Damien_The_Unbeliever and CodeCaster.

Body:
Yes, it means the literal 0. For example:

static void Main()
{
   Method(0);
}

static void Method(DayOfWeek dow)
{
  Console.WriteLine(dow);
}

should print Sunday to the console. If you change 0 into 1, the program is illegal (compile-time error).

Only the (compile-time constant) zero has an implicit conversion to the enum type. For other values, you need an explicit cast instead, as in Method((DayOfWeek)1);.

Edit: This explains how the rules are. If you want to know why they chose those rules, I recommend the links in the comments (to your question above) by  Damien_The_Unbeliever and CodeCaster.


问:
How can I write/define different IDs to Mifare Classic 1k cards so that I can read them with rdm6300 card reader
I'm using javaxsmartcardio at the moment but I don't know how this library works. I have an acr122u reader/writer and I only want to use it as writer so that I can write cards and read them on my RFID doorlock project with rdm6300 card reader. So far I've managed to read 2 cards which both were written to be used in social utilities. That's why I've written my arduino code according to 1 card is autherized and the other is not. But I want to write my own cards and put my own specific password so only the cards I give autherization will unlock the door. I'm all set with the doorlock part but I'cant write my own cards.Please help me out. Thanks in advance.</p>

答:
Mifare uses 13.56 MHz. The RDM6300 is 125 KHz.

You'll need to replace one to be compatible with the other for your project.


问:
How do I delete Zelle graphics text from the screen in Python?
I would like to delete text that I have graphically displayed so I can write new text without overlap.  I  have included my code below.  Thank you again for your time.

```<code>from graphics import*
import random

# Function for winning
def youwin():
    txt = Text(Point(250,100), "You are a Winner!")
    txt.setTextColor(color_rgb(0,255,200))
    txt.setSize(30)
    txt.setFace('courier')
    txt.draw(win)

# Function for losing
def youlose():

txt= Text(Point(250,100), "You are a Loser!")
txt.setTextColor(color_rgb(0,255,0))
txt.setSize(30)
txt.setFace('courier')
txt.draw(win)

# Sets a Window
win = GraphWin("My Window", 800, 600)
win.setBackground('White')

# loops 10 Times and picks out 3 random gif's.
# Then displays each image on the screen in a row.

for x in range(10):

cards = ["1.png","2.png","3.png"]
rand_card1 = random.choice(cards)
img1 = Image(Point(100, 250), rand_card1)
rand_card2 = random.choice(cards)
img2 = Image(Point(300, 250), rand_card2)
rand_card3 = random.choice(cards)
img3 = Image(Point(500, 250), rand_card3)

img1.draw(win)
img2.draw(win)
img3.draw(win)

# checks to see if you are a winner

if rand_card1 == rand_card2 and rand_card2 == rand_card3:
    youwin()
else:
    youlose()

# waits for a mouse click.  In the future this will be a button.
win.getMouse()
img1.undraw()
img2.undraw()
img3.undraw()

#win.close()#
</code>```

This is the output I currently get:

答:
I would like to delete text that I have graphically displayed so I can
  write new text

Don't.  You can reuse the text object via setText().  A simple example:

```<code>import time  # just for demonstration
from graphics import *

win = GraphWin("My Window", 800, 600)

txt = Text(Point(250,100), "You are a Loser!")
txt.setSize(30)
txt.draw(win)

time.sleep(3)

txt.setText("You are a Winner!")

time.sleep(3)
</code>```

If you want the text to disappear for a time, just txt.setText('') until you need it again.

Body:
I would like to delete text that I have graphically displayed so I can write new text without overlap.  I  have included my code below.  Thank you again for your time.

from graphics import*
import random

# Function for winning
def youwin():
    txt = Text(Point(250,100), "You are a Winner!")
    txt.setTextColor(color_rgb(0,255,200))
    txt.setSize(30)
    txt.setFace('courier')
    txt.draw(win)

# Function for losing
def youlose():

txt= Text(Point(250,100), "You are a Loser!")
txt.setTextColor(color_rgb(0,255,0))
txt.setSize(30)
txt.setFace('courier')
txt.draw(win)

# Sets a Window
win = GraphWin("My Window", 800, 600)
win.setBackground('White')

# loops 10 Times and picks out 3 random gif's.
# Then displays each image on the screen in a row.

for x in range(10):

cards = ["1.png","2.png","3.png"]
rand_card1 = random.choice(cards)
img1 = Image(Point(100, 250), rand_card1)
rand_card2 = random.choice(cards)
img2 = Image(Point(300, 250), rand_card2)
rand_card3 = random.choice(cards)
img3 = Image(Point(500, 250), rand_card3)

img1.draw(win)
img2.draw(win)
img3.draw(win)

# checks to see if you are a winner

if rand_card1 == rand_card2 and rand_card2 == rand_card3:
    youwin()
else:
    youlose()

# waits for a mouse click.  In the future this will be a button.
win.getMouse()
img1.undraw()
img2.undraw()
img3.undraw()

#win.close()#

This is the output I currently get:

Body:
I would like to delete text that I have graphically displayed so I can
  write new text

Don't.  You can reuse the text object via setText().  A simple example:

import time  # just for demonstration
from graphics import *

win = GraphWin("My Window", 800, 600)

txt = Text(Point(250,100), "You are a Loser!")
txt.setSize(30)
txt.draw(win)

time.sleep(3)

txt.setText("You are a Winner!")

time.sleep(3)

If you want the text to disappear for a time, just txt.setText('') until you need it again.


问:
Fluent Nhibernate many-to-many where table has multiple columns
I am trying to to map a many to many relationship using Fluent NHibernate.

I have a table User and a second table Organization. The association table is UserOrganization which contains the UserId and OrganizationId. The UserOrganization table also contains a few other fields (YearBegan, YearEnd).

How would I go ahead and map those using fluent mapping.

Thanks

答:
You should probably make UserOrganization its own entity that contains those fields.  That also gives you more flexibility in terms of cascading updates and deletes.</p>

```<code>public class UserOrganization {
    public virtual User User { get; set; }
    public virtual Organization Organization { get; set; }
    public virtual DateTime YearBegan { get; set; }
    public virtual DateTime YearEnd { get; set; }
}
</code>```

Body:
You should probably make UserOrganization its own entity that contains those fields.  That also gives you more flexibility in terms of cascading updates and deletes.

public class UserOrganization {
    public virtual User User { get; set; }
    public virtual Organization Organization { get; set; }
    public virtual DateTime YearBegan { get; set; }
    public virtual DateTime YearEnd { get; set; }
}


问:
How to render java.awt.Graphics2D in PdfDocument using iText7?
```<code>//writer is an instance of PdfWriter
PdfContentByte contentByte = writer.getDirectContent();
PdfTemplate temp = contentByte.createTemplate(width ,height);
Graphics2D g2d = temp.createGraphics(width, height);
Rectangle2D r2d = new Rectangle2D.Double(0,0,width ,height);
//chart is an instance of JFreeChart and info is the information required for rendering a chart in JFreeChart
chart.draw(g2d,r2d,info);
img = Image.getInstance(temp);
document.add(img);
</code>```

This is the code in iText 5. How to obtain the Graphics2D object using Itext7?

答:
Ran into the same issue updating the version and this was the solution I ended up with:

```<code>document.add(convertChartToImage(chart));
</code>```

Where convertChartToImage(...) is the following:

```<code>private Image convertChartToImage(JFreeChart chart) throws IOException {
    Image result = null;
    BufferedImage original = chart.createBufferedImage(WIDTH, HEIGHT);
    try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {

        ImageIO.write(original, "png", os);
        os.flush();

        ImageData image = ImageDataFactory.create(os.toByteArray());

        result = new Image(image);
    }

    return result;
}
</code>```

Hope this helps. There might be a better way.

Body:
//writer is an instance of PdfWriter
PdfContentByte contentByte = writer.getDirectContent();
PdfTemplate temp = contentByte.createTemplate(width ,height);
Graphics2D g2d = temp.createGraphics(width, height);
Rectangle2D r2d = new Rectangle2D.Double(0,0,width ,height);
//chart is an instance of JFreeChart and info is the information required for rendering a chart in JFreeChart
chart.draw(g2d,r2d,info);
img = Image.getInstance(temp);
document.add(img);

This is the code in iText 5. How to obtain the Graphics2D object using Itext7?

Body:
Ran into the same issue updating the version and this was the solution I ended up with:

document.add(convertChartToImage(chart));

Where convertChartToImage(...) is the following:

private Image convertChartToImage(JFreeChart chart) throws IOException {
    Image result = null;
    BufferedImage original = chart.createBufferedImage(WIDTH, HEIGHT);
    try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {

        ImageIO.write(original, "png", os);
        os.flush();

        ImageData image = ImageDataFactory.create(os.toByteArray());

        result = new Image(image);
    }

    return result;
}

Hope this helps. There might be a better way.


问:
Distinct enclosing environment, function environment, etc. in R
I have a few questions about the different environments of a function. Take the following example:

```<code>environment(sd)
# <environment: namespace:stats>
</code>```

Does namespace:stats point to the enclosing environment of function sd?

```<code>pryr::where(sd)
# <environment: package:stats>
</code>```

Does package:stats point to the binding environment of function sd?

According to Advanced R by Hadley Wickham: "The enclosing environment belongs to the function, and never changes..."

But the enclosing environment of function can be changed like the below:

```<code>new.env <- new.env()
environment(f) <- new.env
</code>```

A function' environment property indicates a function's executing environment, correct? An online article regarding R finding stuff through environments

To sum up my questions:

Can we actually change the enclosing environment of a function or not?

What are those two different environments of the stats package?

What is the function's environment?

It's similar to a previous post in here.

答:
TLDR:

indeed, you can change the enclosing environment. Hadley was probably talking about packaged functions.

the enclosing and the binding environment. You were correct.

that's the execution environment. It only exists for the time the function runs.

Function environments

You have to distinguish 4 different environments when talking about a function:

the binding environment is the environment where the function is found (i.e. where its name exists). This is where the actual binding of an object to its name is done. find() gives you the binding environment.

the enclosing environment is the environment where the function is originally created. This is not necessarily the same as the binding environment (see examples below). environment() gives you the enclosing environment.

the local environment is the environment within the function. You call that the execution environment.

the parent frame or calling environment is the environment from where the function was called.

Why does this matter

Every environment has a specific function:

the binding environment is the environment where you find the function.

the local environment is the first environment where R looks for objects.

the general rule is: if R doesn't find an object in the local environment, it then looks in the enclosing environment and so on. The last enclosing environment is always emptyenv().

the parent frame is where R looks for the value of the objects passed as
arguments.

You can change the enclosing environment

Indeed, you can change the enclosing environment. It is the enclosing environment of a function from a package you cannot change. In that case you don't change the enclosing environment, you actually create a copy in the new environment:

```<code>> ls()
character(0)
> environment(sd)
<environment: namespace:stats>
> environment(sd) <- globalenv()
> environment(sd)
<environment: R_GlobalEnv>
> ls()
[1] "sd"
> find("sd")
[1] ".GlobalEnv"    "package:stats" # two functions sd now
> rm(sd)
> environment(sd)
<environment: namespace:stats>
</code>```

In this case, the second sd has the global environment as the enclosing and binding environment, but the original sd is still found inside the package environment, and its enclosing environment is still the namespace of that package

The confusion might arise when you do the following:

```<code>> f <- sd
> environment(f)
<environment: namespace:stats>
> find("f")
[1] ".GlobalEnv"
</code>```

What happens here? The enclosing environment is still the namespace ''stats''. That's where the function is created. However, the binding environment is now the global environment. That's where the name "f" is bound to the object.

We can change the enclosing environment to a new environment e. If you check now, the enclosing environment becomes e, but e itself is empty. f is still bound in the global environment.

```<code>> e <- new.env()
> e
<environment: 0x000000001852e0a8>
> environment(f) <- e
> find("f")
[1] ".GlobalEnv"
> environment(f)
<environment: 0x000000001852e0a8>
> ls(e)
character(0)
</code>```

The enclosing environment of e is the global environment. So f still works as if its enclosure was the global environment. The environment e is enclosed in it, so if something isn't found in e, the function looks in the global environment and so on.

But because e is an environment, R calls that a parent environment.

```<code>> parent.env(e)
<environment: R_GlobalEnv>
> f(1:3)
[1] 1
</code>```

Namespaces and package environments

This principle is also the "trick" packages use:

the function is created in the namespace. This is an environment that is enclosed by the namespaces of other imported packages, and eventually the global environment.

the binding for the function is created in the package environment. This is an environment that encloses the global environment and possible other packages.

The reason for this is simple: objects can only be found inside the environment you are in, or in its enclosing environments.

a function must be able to find other functions(objects), so the local environment must be enclosed by possibly the namespaces of other packages it imports, the base package and lastly the global environment.

a function must be findable from within the global environment. Hence the binding (i.e. the name of the function) must be in an environment that is enclosed by the global environment. This is the package environment (NOT the namespace!)

An illustration:

Now suppose you make an environment with the empty environment as a parent. If you use this as an enclosing environment for a function, nothing works any longer. Because now you circumvent all the package environments, so you can't find a single function any more.

```<code>> orphan <- new.env(parent = emptyenv())
> environment(f) <- orphan
> f(1:3)
Error in sqrt(var(if (is.vector(x) || is.factor(x)) x else as.double(x),  :
  could not find function "sqrt"
</code>```

The parent frame

This is where it gets interesting. The parent frame or calling environment, is the environment where the values passed as arguments are looked up. But that parent frame can be the local environment of another function. In this case R looks first in that local environment of that other function, and then in the enclosing environment of the calling function, and so all the way up to the global environment, the environments of the attached packages until it reaches the empty environment. That's where the "object not found" bug sleeps.

Body:
I have a few questions about the different environments of a function. Take the following example:

environment(sd)
# <environment: namespace:stats>

Does namespace:stats point to the enclosing environment of function sd?

pryr::where(sd)
# <environment: package:stats>

Does package:stats point to the binding environment of function sd?

According to Advanced R by Hadley Wickham: "The enclosing environment belongs to the function, and never changes..."

But the enclosing environment of function can be changed like the below:

new.env <- new.env()
environment(f) <- new.env

A function' environment property indicates a function's executing environment, correct? An online article regarding R finding stuff through environments

To sum up my questions:

Can we actually change the enclosing environment of a function or not?

What are those two different environments of the stats package?

What is the function's environment?

It's similar to a previous post in here.

Body:
TLDR:

indeed, you can change the enclosing environment. Hadley was probably talking about packaged functions.

the enclosing and the binding environment. You were correct.

that's the execution environment. It only exists for the time the function runs.

Function environments

You have to distinguish 4 different environments when talking about a function:

the binding environment is the environment where the function is found (i.e. where its name exists). This is where the actual binding of an object to its name is done. find() gives you the binding environment.

the enclosing environment is the environment where the function is originally created. This is not necessarily the same as the binding environment (see examples below). environment() gives you the enclosing environment.

the local environment is the environment within the function. You call that the execution environment.

the parent frame or calling environment is the environment from where the function was called.

Why does this matter

Every environment has a specific function:

the binding environment is the environment where you find the function.

the local environment is the first environment where R looks for objects.

the general rule is: if R doesn't find an object in the local environment, it then looks in the enclosing environment and so on. The last enclosing environment is always emptyenv().

the parent frame is where R looks for the value of the objects passed as
arguments.

You can change the enclosing environment

Indeed, you can change the enclosing environment. It is the enclosing environment of a function from a package you cannot change. In that case you don't change the enclosing environment, you actually create a copy in the new environment:

> ls()
character(0)
> environment(sd)
<environment: namespace:stats>
> environment(sd) <- globalenv()
> environment(sd)
<environment: R_GlobalEnv>
> ls()
[1] "sd"
> find("sd")
[1] ".GlobalEnv"    "package:stats" # two functions sd now
> rm(sd)
> environment(sd)
<environment: namespace:stats>

In this case, the second sd has the global environment as the enclosing and binding environment, but the original sd is still found inside the package environment, and its enclosing environment is still the namespace of that package

The confusion might arise when you do the following:

> f <- sd
> environment(f)
<environment: namespace:stats>
> find("f")
[1] ".GlobalEnv"

What happens here? The enclosing environment is still the namespace ''stats''. That's where the function is created. However, the binding environment is now the global environment. That's where the name "f" is bound to the object.

We can change the enclosing environment to a new environment e. If you check now, the enclosing environment becomes e, but e itself is empty. f is still bound in the global environment.

> e <- new.env()
> e
<environment: 0x000000001852e0a8>
> environment(f) <- e
> find("f")
[1] ".GlobalEnv"
> environment(f)
<environment: 0x000000001852e0a8>
> ls(e)
character(0)

The enclosing environment of e is the global environment. So f still works as if its enclosure was the global environment. The environment e is enclosed in it, so if something isn't found in e, the function looks in the global environment and so on.

But because e is an environment, R calls that a parent environment.

> parent.env(e)
<environment: R_GlobalEnv>
> f(1:3)
[1] 1

Namespaces and package environments

This principle is also the "trick" packages use:

the function is created in the namespace. This is an environment that is enclosed by the namespaces of other imported packages, and eventually the global environment.

the binding for the function is created in the package environment. This is an environment that encloses the global environment and possible other packages.

The reason for this is simple: objects can only be found inside the environment you are in, or in its enclosing environments.

a function must be able to find other functions(objects), so the local environment must be enclosed by possibly the namespaces of other packages it imports, the base package and lastly the global environment.

a function must be findable from within the global environment. Hence the binding (i.e. the name of the function) must be in an environment that is enclosed by the global environment. This is the package environment (NOT the namespace!)

An illustration:

Now suppose you make an environment with the empty environment as a parent. If you use this as an enclosing environment for a function, nothing works any longer. Because now you circumvent all the package environments, so you can't find a single function any more.

> orphan <- new.env(parent = emptyenv())
> environment(f) <- orphan
> f(1:3)
Error in sqrt(var(if (is.vector(x) || is.factor(x)) x else as.double(x),  :
  could not find function "sqrt"

The parent frame

This is where it gets interesting. The parent frame or calling environment, is the environment where the values passed as arguments are looked up. But that parent frame can be the local environment of another function. In this case R looks first in that local environment of that other function, and then in the enclosing environment of the calling function, and so all the way up to the global environment, the environments of the attached packages until it reaches the empty environment. That's where the "object not found" bug sleeps.


问:
Proper updating of a 32bit method to 64bit support
I have a method I am trying to update to 64-bit support for my app. I have lots of these warnings.

The issue is with the below example. I get the warning:

Implicit conversion loses integer precision NSInteger to int

```<code>- (int)  aMethod {
    NSUserDefaults *u = [NSUserDefaults standardUserDefaults];
    return [u integerForKey:@"someKey"];
}
</code>```

If I change the return type to NSInteger I get

Conflicting return type in implementation of aMethod int vs NSInteger aka long

```<code>-(NSInteger)  aMethod {
    NSUserDefaults *u = [NSUserDefaults standardUserDefaults];
    return [u integerForKey:@"someKey"];
}
</code>```

I have tried casting the return type

return (NSInteger)[u integerForKey:@"someKey"];

or

return (long)[u integerForKey:@"someKey"];

But I can't get the error to go away unless I cast it to (int)

return (int)[u integerForKey:@"someKey"];

I have read many SO questions but I can't seem to get a good answer.

What is the proper way of updating this method?

答:
The method:

```<code>- (int) aMethod ...
</code>```

returns a value of type int. The method may first declared, probably in a header (.h) file, and then defined in an implementation (.m) file.

The statement:

```<code>return [u integerForKey:@"someKey"];
</code>```

returns the result of calling integerForKey:, which is a value of type NSInteger.

NSInteger is not a type defined by the (Objective-)C language, rather it is a type alias (typedef) defined in the frameworks intended to represent the "natural" integer size on the platform. It is an alias for int on 32-bit platforms and long on 64-bit.

So your compiler error is telling you that the (now) 64-bit value is being truncated to fit a 32-bit result. There is no single right way to fix this, it depends on what the use of the value associated with @someKey is:

If the value should now be 64-bit then change the return type of aMethod; both in its separate declaration, if it has one, and in its implementation; to NSInteger. You will also need to check that wherever the method is called that returning an NSInteger value is acceptable, and you may need to make follow-on changes to variable types etc. You also need to look at places where the value associated with the key is set.

If the value associated with the key may remain as 32-bit then you can use intForKey: instead of integerForKey and leave the return type as is. You should also change where the key is set to store an int

HTH

Correction

There is (no longer?) a convenience method intForKey: on NSUserDefaults. Alternatives include: integerForKey: and casting; objectForKey: to obtain an NSNumber reference and then intValue; etc.

Body:
I have a method I am trying to update to 64-bit support for my app. I have lots of these warnings.

The issue is with the below example. I get the warning:

Implicit conversion loses integer precision NSInteger to int

- (int)  aMethod {
    NSUserDefaults *u = [NSUserDefaults standardUserDefaults];
    return [u integerForKey:@"someKey"];
}

If I change the return type to NSInteger I get

Conflicting return type in implementation of aMethod int vs NSInteger aka long

-(NSInteger)  aMethod {
    NSUserDefaults *u = [NSUserDefaults standardUserDefaults];
    return [u integerForKey:@"someKey"];
}

I have tried casting the return type

return (NSInteger)[u integerForKey:@"someKey"];

or

return (long)[u integerForKey:@"someKey"];

But I can't get the error to go away unless I cast it to (int)

return (int)[u integerForKey:@"someKey"];

I have read many SO questions but I can't seem to get a good answer.

What is the proper way of updating this method?

Body:
The method:

- (int) aMethod ...

returns a value of type int. The method may first declared, probably in a header (.h) file, and then defined in an implementation (.m) file.

The statement:

return [u integerForKey:@"someKey"];

returns the result of calling integerForKey:, which is a value of type NSInteger.

NSInteger is not a type defined by the (Objective-)C language, rather it is a type alias (typedef) defined in the frameworks intended to represent the "natural" integer size on the platform. It is an alias for int on 32-bit platforms and long on 64-bit.

So your compiler error is telling you that the (now) 64-bit value is being truncated to fit a 32-bit result. There is no single right way to fix this, it depends on what the use of the value associated with @someKey is:

If the value should now be 64-bit then change the return type of aMethod; both in its separate declaration, if it has one, and in its implementation; to NSInteger. You will also need to check that wherever the method is called that returning an NSInteger value is acceptable, and you may need to make follow-on changes to variable types etc. You also need to look at places where the value associated with the key is set.

If the value associated with the key may remain as 32-bit then you can use intForKey: instead of integerForKey and leave the return type as is. You should also change where the key is set to store an int

HTH

Correction

There is (no longer?) a convenience method intForKey: on NSUserDefaults. Alternatives include: integerForKey: and casting; objectForKey: to obtain an NSNumber reference and then intValue; etc.


问:
How to batch-copy the 10 newest files to a directory in Windows?
I use the following script to keep only the newest 360 files (a year, daily-made backup) in the directory:

```<code>for /f "skip=360 eol=: delims=" %%F in ('dir /b /o-d /a-d *.*') do @del "%%F"
</code>```

How to afterwards copy the newest 7 files to another directory?

答:
<pre class="lang-dos prettyprint-override"><code>@echo off
    setlocal enableextensions disabledelayedexpansion

    rem Three alternatives

    rem Pure arithmetics
    set "numFiles=7"
    for /f "delims=" %%a in ('dir /b /o-d /a-d') do (
        2>nul set /a "1/numFiles", "numFiles-=!!numFiles" && (
            echo copy "%%~fa" x:\somewehere
        )
    )

    rem Pure arithmetics 2 - No negation operator
    set "numFiles=7"
    for /f "delims=" %%a in ('dir /b /o-d /a-d') do (
        2>nul set /a "1/numFiles", "numFiles-=1" && (
            echo copy "%%~fa" x:\somewehere
        )
    )

    rem Number list of files
    set "numFiles=7"
    for /f "tokens=1,* delims=:" %%a in ('
        dir /b /o-d /a-d
        ^| findstr /n "^"
    ') do if %%a leq %numFiles% (
        echo copy "%%~fb" x:\somewehere
    )
</code>```

Body:
I use the following script to keep only the newest 360 files (a year, daily-made backup) in the directory:

for /f "skip=360 eol=: delims=" %%F in ('dir /b /o-d /a-d *.*') do @del "%%F"

How to afterwards copy the newest 7 files to another directory?


问:
Crop UIImage to center square
I get images that are in 1920x1080 resolution. I am attempting to crop them to the center square area (ie 1080x1080 square in the center). The resolution may change in the future. Would it be possible to crop the image this way? I have tried a couple things posted on SO, but I always get an image that is 660x1080 if I try to crop then center. Here is an image depicting what I want to achieve.

Basically the red is original, green is what I want, and yellow is just showing mixX and midY lines.

The code I tried.

```<code>func imageByCroppingImage(image: UIImage, toSize size: CGSize) -> UIImage{
    let newCropWidth: CGFloat?
    let newCropHeight: CGFloat?

    if image.size.width < image.size.height {
        if image.size.width < size.width {
            newCropWidth = size.width
        } else {
            newCropWidth = image.size.width
        }
        newCropHeight = (newCropWidth! * size.height) / size.width
    } else {
        if image.size.height < size.height {
            newCropHeight = size.height
        } else {
            newCropHeight = image.size.height
        }
        newCropWidth = (newCropHeight! * size.width) / size.height
    }

    let x = image.size.width / 2.0 - newCropWidth! / 2.0
    let y = image.size.height / 2.0 - newCropHeight! / 2.0

    let cropRect = CGRect(x: x, y: y, width: newCropWidth!, height: newCropHeight!)
    let imageRef = image.cgImage!.cropping(to: cropRect)

    let cropped = UIImage(cgImage: imageRef!, scale: 1.0, orientation: .right)
    return cropped
}
</code>```

And then I pass that method a CGSize(1080, 1080). I get an image that is 660, 1080. Any thoughts?

The intent is to crop the image, not to just display it centered.

答:
You can use the same approach I used in this answer without the line UIBezierPath(ovalIn: breadthRect).addClip()

```<code>extension UIImage {
    var isPortrait:  Bool    { size.height > size.width }
    var isLandscape: Bool    { size.width > size.height }
    var breadth:     CGFloat { min(size.width, size.height) }
    var breadthSize: CGSize  { .init(width: breadth, height: breadth) }
    func squared(isOpaque: Bool = false) -> UIImage? {
        guard let cgImage = cgImage?
            .cropping(to: .init(origin: .init(x: isLandscape ? ((size.width-size.height)/2).rounded(.down) : 0,
                                              y: isPortrait  ? ((size.height-size.width)/2).rounded(.down) : 0),
                                size: breadthSize)) else { return nil }
        let format = imageRendererFormat
        format.opaque = isOpaque
        return UIGraphicsImageRenderer(size: breadthSize, format: format).image { _ in
            UIImage(cgImage: cgImage, scale: 1, orientation: imageOrientation)
            .draw(in: .init(origin: .zero, size: breadthSize))
        }
    }
}
</code>```

```<code>let imageURL = URL(string: "http://i.stack.imgur.com/Xs4RX.jpg")!
let image = UIImage(data: try! Data(contentsOf: imageURL))!

let squared = image.squared()
</code>```

Title: Crop UIImage to center square

Body:
I get images that are in 1920x1080 resolution. I am attempting to crop them to the center square area (ie 1080x1080 square in the center). The resolution may change in the future. Would it be possible to crop the image this way? I have tried a couple things posted on SO, but I always get an image that is 660x1080 if I try to crop then center. Here is an image depicting what I want to achieve.

Basically the red is original, green is what I want, and yellow is just showing mixX and midY lines.

The code I tried.

func imageByCroppingImage(image: UIImage, toSize size: CGSize) -> UIImage{
    let newCropWidth: CGFloat?
    let newCropHeight: CGFloat?

    if image.size.width < image.size.height {
        if image.size.width < size.width {
            newCropWidth = size.width
        } else {
            newCropWidth = image.size.width
        }
        newCropHeight = (newCropWidth! * size.height) / size.width
    } else {
        if image.size.height < size.height {
            newCropHeight = size.height
        } else {
            newCropHeight = image.size.height
        }
        newCropWidth = (newCropHeight! * size.width) / size.height
    }

    let x = image.size.width / 2.0 - newCropWidth! / 2.0
    let y = image.size.height / 2.0 - newCropHeight! / 2.0

    let cropRect = CGRect(x: x, y: y, width: newCropWidth!, height: newCropHeight!)
    let imageRef = image.cgImage!.cropping(to: cropRect)

    let cropped = UIImage(cgImage: imageRef!, scale: 1.0, orientation: .right)
    return cropped
}

And then I pass that method a CGSize(1080, 1080). I get an image that is 660, 1080. Any thoughts?

The intent is to crop the image, not to just display it centered.

Body:
You can use the same approach I used in this answer without the line UIBezierPath(ovalIn: breadthRect).addClip()

extension UIImage {
    var isPortrait:  Bool    { size.height > size.width }
    var isLandscape: Bool    { size.width > size.height }
    var breadth:     CGFloat { min(size.width, size.height) }
    var breadthSize: CGSize  { .init(width: breadth, height: breadth) }
    func squared(isOpaque: Bool = false) -> UIImage? {
        guard let cgImage = cgImage?
            .cropping(to: .init(origin: .init(x: isLandscape ? ((size.width-size.height)/2).rounded(.down) : 0,
                                              y: isPortrait  ? ((size.height-size.width)/2).rounded(.down) : 0),
                                size: breadthSize)) else { return nil }
        let format = imageRendererFormat
        format.opaque = isOpaque
        return UIGraphicsImageRenderer(size: breadthSize, format: format).image { _ in
            UIImage(cgImage: cgImage, scale: 1, orientation: imageOrientation)
            .draw(in: .init(origin: .zero, size: breadthSize))
        }
    }
}

let imageURL = URL(string: "http://i.stack.imgur.com/Xs4RX.jpg")!
let image = UIImage(data: try! Data(contentsOf: imageURL))!

let squared = image.squared()


问:
Android: How to perform Url Request via Wifi
is there a possiblity to explicitely use the wifi connection for doing Http Url requests?
In fact i just need to know if an internet connection (access to google.com for example) is possible via wifi.
(not via 2g / 3g / ..)</p>

答:
As far as I know, no. This is all abstracted from us by the platform.

But you can check to see if WIFI is available:

```<code>        ConnectivityManager conMan = (ConnectivityManager)
            getSystemService(Context.CONNECTIVITY_SERVICE);
        if(conMan!=null){
            try {
                NetworkInfo[] networkInfos = conMan.getAllNetworkInfo();
                for(NetworkInfo ni : networkInfos){
                    if(ni.isAvailable() && ni.isConnected() && ni.getTypeName().equals("WIFI")){
                        result = true;
                        break;
                    }
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
</code>```

Body:
As far as I know, no. This is all abstracted from us by the platform.

But you can check to see if WIFI is available:

        ConnectivityManager conMan = (ConnectivityManager)
            getSystemService(Context.CONNECTIVITY_SERVICE);
        if(conMan!=null){
            try {
                NetworkInfo[] networkInfos = conMan.getAllNetworkInfo();
                for(NetworkInfo ni : networkInfos){
                    if(ni.isAvailable() && ni.isConnected() && ni.getTypeName().equals("WIFI")){
                        result = true;
                        break;
                    }
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }


问:
Google spanner structs as parameter
When using the spanner python client (but perhaps the problem is more general) it seems impossible to pass structs to the query as a parameter.

Consider following setup:

```<code>from google.cloud.proto.spanner.v1 import type_pb2
from google.cloud import spanner

spanner_client = spanner.Client()
instance = spanner_client.instance('myinstance')
database = instance.database('mydb')
</code>```

If I want to translate following query into using paramaters

```<code>select * from UNNEST(ARRAY[STRUCT<foo INT64, bar INT64>(1, 2)])
</code>```

By doing

```<code>STRUCT_TYPE = type_pb2.StructType()
FOO = type_pb2.StructType.Field(name='foo', type=type_pb2.Type(code=type_pb2.INT64))
BAR = type_pb2.StructType.Field(name='bar', type=type_pb2.Type(code=type_pb2.INT64))

STRUCT_TYPE.fields.extend([FOO, BAR])

database.execute_sql('select * from UNNEST(ARRAY[@struct])',
    params={'struct': [1,2]},
    param_types={'struct': STRUCT_TYPE})
</code>```

Would give me

```<code>TypeError: Parameter to MergeFrom() must be instance of same class: expected Type got StructType.
</code>```

Is there any way to allow passing of structs?

答: You can't pass structs right now. This is something we're addressing but no firm timeline.</p>

Title: Google spanner structs as parameter

Body:
When using the spanner python client (but perhaps the problem is more general) it seems impossible to pass structs to the query as a parameter.

Consider following setup:

from google.cloud.proto.spanner.v1 import type_pb2
from google.cloud import spanner

spanner_client = spanner.Client()
instance = spanner_client.instance('myinstance')
database = instance.database('mydb')

If I want to translate following query into using paramaters

select * from UNNEST(ARRAY[STRUCT<foo INT64, bar INT64>(1, 2)])

By doing

STRUCT_TYPE = type_pb2.StructType()
FOO = type_pb2.StructType.Field(name='foo', type=type_pb2.Type(code=type_pb2.INT64))
BAR = type_pb2.StructType.Field(name='bar', type=type_pb2.Type(code=type_pb2.INT64))

STRUCT_TYPE.fields.extend([FOO, BAR])

database.execute_sql('select * from UNNEST(ARRAY[@struct])',
    params={'struct': [1,2]},
    param_types={'struct': STRUCT_TYPE})

Would give me

TypeError: Parameter to MergeFrom() must be instance of same class: expected Type got StructType.

Is there any way to allow passing of structs?


问:
Korn Shell - env, printenv, export - How to get CRLF as a delimiter
This seems simple, but I can't find anything on how to do this : I'm basically using a KSH variable to build my email body text.  In an error/exception situation I want to dump the env/printenv/export as well using '\n' as a delimiter.

```<code>if (( $status != 0 ))
then
    MESSAGE="${MESSAGE}\n"
    MESSAGE="${MESSAGE}\n\tBatch Process\t: ${BATCHPROCESS}"
    MESSAGE="${MESSAGE}\n\tEnvironment\t: ${ENVTEXT}"
    MESSAGE="${MESSAGE}\n\tDate/Time\t: ${STARTDATETIME}"
    MESSAGE="${MESSAGE}\n\nRuntime:"
    MESSAGE="${MESSAGE}\n$(env)"
    echo -e $MESSAGE >>  ${MAILFILE1}
    mail -s"FAILURE - ${SUBJECT} " $MAILLIST <  ${MAILFILE1}
</code>```

So, according to the documentation on env/printenv/export, it's already using LF as a delimiter, but when I receive the email, it's just one big BLOCK of text :

```<code>Runtime:

Runtime:
</code>```

What I want is each variable on a separate line :

```<code>Runtime :
ACCESSDB=[Sybase-Database]
ACCESSSRV=[Sybase-Server]
...etc...
</code>```

Is there anyway to force a '\n' in place of the LF currently being used?

UPDATE : I'm using sed -s 's/$/\r\n/g' and it's formatting the env output, but now the entire email body text gets sent as an attachment :

```<code>if (( $status != 0 ))
then
    MESSAGE="${MESSAGE}\n"
    MESSAGE="${MESSAGE}\n\tBatch Process\t: ${BATCHPROCESS}"
    MESSAGE="${MESSAGE}\n\tEnvironment\t: ${ENVTEXT}"
    MESSAGE="${MESSAGE}\n\tDate/Time\t: ${STARTDATETIME}"
    env | sort | sed 's/$/\r\n/g' > ${TEMPFILES}/env.txt
    MESSAGE="${MESSAGE}\n\nRuntime:"
    MESSAGE="${MESSAGE}\n$(cat ${TEMPFILES}/env.txt)"

    echo -e "$MESSAGE" >>  ${MAILFILE1}
    mail -s"FAILURE - ${SUBJECT} " $MAILLIST <  ${MAILFILE1}
</code>```

Any ideas?  I'm thinking it's some kinda mail setting on max email size, but I'm a Java programmer more than a shell scripter...

CLOSE SOLUTION : Turns out the \r\n was causing the attachment issue [https://access.redhat.com/solutions/1136493].  So I used sed -s 's/$/\n/g' and this is pretty close to what I wanted except the env is output using double lines :

```<code>if (( $status != 0 ))
then
    MESSAGE="${MESSAGE}\n"
    MESSAGE="${MESSAGE}\n\tBatch Process\t: ${BATCHPROCESS}"
    MESSAGE="${MESSAGE}\n\tEnvironment\t: ${ENVTEXT}"
    MESSAGE="${MESSAGE}\n\tDate/Time\t: ${STARTDATETIME}"
    MESSAGE="${MESSAGE}\n\nRuntime:"
    MESSAGE="${MESSAGE}\n$(env | sort | sed 's/$/\n/g')"

    echo -e "$MESSAGE" >>  ${MAILFILE1}
    mail -s"FAILURE - ${SUBJECT} " $MAILLIST <  ${MAILFILE1}
</code>```

Produces output :

```<code>Runtime:
ACCESSDB=[Sybase-Database]

ACCESSSRV=[Sybase-server]

ARCHIVEDB=[Sybase-Database]

ASBIN=[Directory-Path]
</code>```

FINAL SOLUTION : Implemented markp's fix and then just took out my sed -s stuff and it works correctly :

```<code>if (( $status != 0 ))
then
    MESSAGE="${MESSAGE}\n"
    MESSAGE="${MESSAGE}\n\tBatch Process\t: ${BATCHPROCESS}"
    MESSAGE="${MESSAGE}\n\tEnvironment\t: ${ENVTEXT}"
    MESSAGE="${MESSAGE}\n\tDate/Time\t: ${STARTDATETIME}"
    MESSAGE="${MESSAGE}\n\nRuntime:"
    MESSAGE="${MESSAGE}\n$(env | sort)"

    echo -e "$MESSAGE" >>  ${MAILFILE1}
    mail -s"FAILURE - ${SUBJECT} " $MAILLIST <  ${MAILFILE1}
</code>```

tia,  adym

答:
Try wrapping $MESSAGES in double quotes to maintain special formatting, white space, etc:

```<code>echo -e "$MESSAGE" >>  ${MAILFILE1}
</code>```

Whether or not you get what you expect with the 'echo -e' and 'mail -s' commands will depend on which version of said commands you're using.

Body:
This seems simple, but I can't find anything on how to do this : I'm basically using a KSH variable to build my email body text.  In an error/exception situation I want to dump the env/printenv/export as well using '\n' as a delimiter.

if (( $status != 0 ))
then
    MESSAGE="${MESSAGE}\n"
    MESSAGE="${MESSAGE}\n\tBatch Process\t: ${BATCHPROCESS}"
    MESSAGE="${MESSAGE}\n\tEnvironment\t: ${ENVTEXT}"
    MESSAGE="${MESSAGE}\n\tDate/Time\t: ${STARTDATETIME}"
    MESSAGE="${MESSAGE}\n\nRuntime:"
    MESSAGE="${MESSAGE}\n$(env)"
    echo -e $MESSAGE >>  ${MAILFILE1}
    mail -s"FAILURE - ${SUBJECT} " $MAILLIST <  ${MAILFILE1}

So, according to the documentation on env/printenv/export, it's already using LF as a delimiter, but when I receive the email, it's just one big BLOCK of text :

Runtime:

Runtime:

What I want is each variable on a separate line :

Runtime :
ACCESSDB=[Sybase-Database]
ACCESSSRV=[Sybase-Server]
...etc...

Is there anyway to force a '\n' in place of the LF currently being used?

UPDATE : I'm using sed -s 's/$/\r\n/g' and it's formatting the env output, but now the entire email body text gets sent as an attachment :

if (( $status != 0 ))
then
    MESSAGE="${MESSAGE}\n"
    MESSAGE="${MESSAGE}\n\tBatch Process\t: ${BATCHPROCESS}"
    MESSAGE="${MESSAGE}\n\tEnvironment\t: ${ENVTEXT}"
    MESSAGE="${MESSAGE}\n\tDate/Time\t: ${STARTDATETIME}"
    env | sort | sed 's/$/\r\n/g' > ${TEMPFILES}/env.txt
    MESSAGE="${MESSAGE}\n\nRuntime:"
    MESSAGE="${MESSAGE}\n$(cat ${TEMPFILES}/env.txt)"

    echo -e "$MESSAGE" >>  ${MAILFILE1}
    mail -s"FAILURE - ${SUBJECT} " $MAILLIST <  ${MAILFILE1}

Any ideas?  I'm thinking it's some kinda mail setting on max email size, but I'm a Java programmer more than a shell scripter...

CLOSE SOLUTION : Turns out the \r\n was causing the attachment issue [https://access.redhat.com/solutions/1136493].  So I used sed -s 's/$/\n/g' and this is pretty close to what I wanted except the env is output using double lines :

if (( $status != 0 ))
then
    MESSAGE="${MESSAGE}\n"
    MESSAGE="${MESSAGE}\n\tBatch Process\t: ${BATCHPROCESS}"
    MESSAGE="${MESSAGE}\n\tEnvironment\t: ${ENVTEXT}"
    MESSAGE="${MESSAGE}\n\tDate/Time\t: ${STARTDATETIME}"
    MESSAGE="${MESSAGE}\n\nRuntime:"
    MESSAGE="${MESSAGE}\n$(env | sort | sed 's/$/\n/g')"

    echo -e "$MESSAGE" >>  ${MAILFILE1}
    mail -s"FAILURE - ${SUBJECT} " $MAILLIST <  ${MAILFILE1}

Produces output :

Runtime:
ACCESSDB=[Sybase-Database]

ACCESSSRV=[Sybase-server]

ARCHIVEDB=[Sybase-Database]

ASBIN=[Directory-Path]

FINAL SOLUTION : Implemented markp's fix and then just took out my sed -s stuff and it works correctly :

if (( $status != 0 ))
then
    MESSAGE="${MESSAGE}\n"
    MESSAGE="${MESSAGE}\n\tBatch Process\t: ${BATCHPROCESS}"
    MESSAGE="${MESSAGE}\n\tEnvironment\t: ${ENVTEXT}"
    MESSAGE="${MESSAGE}\n\tDate/Time\t: ${STARTDATETIME}"
    MESSAGE="${MESSAGE}\n\nRuntime:"
    MESSAGE="${MESSAGE}\n$(env | sort)"

    echo -e "$MESSAGE" >>  ${MAILFILE1}
    mail -s"FAILURE - ${SUBJECT} " $MAILLIST <  ${MAILFILE1}

tia,  adym

Body:
Try wrapping $MESSAGES in double quotes to maintain special formatting, white space, etc:

echo -e "$MESSAGE" >>  ${MAILFILE1}

Whether or not you get what you expect with the 'echo -e' and 'mail -s' commands will depend on which version of said commands you're using.


问:
Jasmine Unit Testing: How can I spy on Function.prototype.call() in a function parameter that is passed to my method under test?
I want to use jasmine to test a function that takes in a Function parameter

```<code>var functionUnderTest = function(functionParameter) {
     functionParameter.call();
}
</code>```

functionParameter above is a Javascript Function and the call method is the method defined on the Function.prototype. How can I spy on the call property to make sure it's called?

The following doesn't seem to be working

```<code>it("should call the functionParameter passed to it", function() {
    var mockFunction = function() {};

    spyOn(mockFunction, 'call');
    functionUnderTest(mockFunction);

    expect(mockFunction.call).toHaveBeenCalled();
}
</code>```

as it results in an:

```<code>Error: Expected spy call to have been called.
</code>```

Presumably because the jasmine spy has it's own call() function.

I also tried this, but it isn't working either:

```<code>it("should call the functionParameter passed to it", function() {
    var mockFunction = function() {};

    spyOn(mockFunction.prototype, 'call');
    functionUnderTest(mockFunction);

    expect(mockFunction.prototype.call).toHaveBeenCalled();
}
</code>```

this time, the error is:

```<code>TypeError: Cannot read property 'slice' of undefined
</code>```

with a callstack pointing to:

```<code>Expectation.toHaveBeenCalled
</code>```

Is what I'm trying to do possible? I've been at this for hours and it seems like I'm missing something fundamental in my understanding of jasmine.

答:
As suggested by Bergi, the following works:</p>

```<code>it("should call the functionParameter passed to it", function() {
    var mockFunction = jasmine.createSpy('mockFunction')

    functionUnderTest(mockFunction);

    expect(mockFunction).toHaveBeenCalled();
}
</code>```

Body:
I want to use jasmine to test a function that takes in a Function parameter

var functionUnderTest = function(functionParameter) {
     functionParameter.call();
}

functionParameter above is a Javascript Function and the call method is the method defined on the Function.prototype. How can I spy on the call property to make sure it's called?

The following doesn't seem to be working

it("should call the functionParameter passed to it", function() {
    var mockFunction = function() {};

    spyOn(mockFunction, 'call');
    functionUnderTest(mockFunction);

    expect(mockFunction.call).toHaveBeenCalled();
}

as it results in an:

Error: Expected spy call to have been called.

Presumably because the jasmine spy has it's own call() function.

I also tried this, but it isn't working either:

it("should call the functionParameter passed to it", function() {
    var mockFunction = function() {};

    spyOn(mockFunction.prototype, 'call');
    functionUnderTest(mockFunction);

    expect(mockFunction.prototype.call).toHaveBeenCalled();
}

this time, the error is:

TypeError: Cannot read property 'slice' of undefined

with a callstack pointing to:

Expectation.toHaveBeenCalled

Is what I'm trying to do possible? I've been at this for hours and it seems like I'm missing something fundamental in my understanding of jasmine.

Body:
As suggested by Bergi, the following works:

it("should call the functionParameter passed to it", function() {
    var mockFunction = jasmine.createSpy('mockFunction')

    functionUnderTest(mockFunction);

    expect(mockFunction).toHaveBeenCalled();
}


问:
Select multiple/random elements from an arraylist
How would I select random elements from an array list, except for one element?
Here's my arraylist:

```<code>ArrayList <String> provinces = new ArrayList();

Collections.addAll(
    provinces,
    "New Brunswick",
    "Saskatchewan",
    "Ontario",
    "Nova Scotia",
    "Quebec",
    "Alberta");
</code>```

For this example, I would like to select at random the other elements, except for Saskatchewan.

I've tried doing:

```<code> for(int i == provinces.get (0); i < provinces.get(1); i > provinces.get(2); i < provinces.get(5)) {

     int getPossibleAnswers = (int) Math.floor(Math.random()*i);
     String displayPossibleAnswers = provinces.get(getPossibleAnswers);
     outputAnswers.append(displayPossibleAnswers + "\n");
     }
</code>```

Obviously, this code doesn't work, and I don't know what to do.
Thanks in advance!

答:
Build a list of all the index values, except for the index to Saskatchewan, then shuffle that.

```<code>List<String> provinces = Arrays.asList("New Brunswick", "Saskatchewan", "Ontario", "Nova Scotia", "Quebec", "Alberta");

List<Integer> indexes = new ArrayList<>();
for (int i = 0; i < provinces.size(); i++)
    if (! provinces.get(i).equals("Saskatchewan"))
        indexes.add(i);
Collections.shuffle(indexes);

StringBuilder outputAnswers = new StringBuilder();
for (int i : indexes)
    outputAnswers.append(provinces.get(i) + "\n");

System.out.print(outputAnswers);
</code>```

Sample Output

Nova Scotia
Quebec
Ontario
Alberta
New Brunswick
```

Body:
How would I select random elements from an array list, except for one element?
Here's my arraylist:

ArrayList <String> provinces = new ArrayList();

Collections.addAll(
    provinces,
    "New Brunswick",
    "Saskatchewan",
    "Ontario",
    "Nova Scotia",
    "Quebec",
    "Alberta");

For this example, I would like to select at random the other elements, except for Saskatchewan.

I've tried doing:

 for(int i == provinces.get (0); i < provinces.get(1); i > provinces.get(2); i < provinces.get(5)) {

     int getPossibleAnswers = (int) Math.floor(Math.random()*i);
     String displayPossibleAnswers = provinces.get(getPossibleAnswers);
     outputAnswers.append(displayPossibleAnswers + "\n");
     }

Obviously, this code doesn't work, and I don't know what to do.
Thanks in advance!

Body:
Build a list of all the index values, except for the index to Saskatchewan, then shuffle that.

List<String> provinces = Arrays.asList("New Brunswick", "Saskatchewan", "Ontario", "Nova Scotia", "Quebec", "Alberta");

List<Integer> indexes = new ArrayList<>();
for (int i = 0; i < provinces.size(); i++)
    if (! provinces.get(i).equals("Saskatchewan"))
        indexes.add(i);
Collections.shuffle(indexes);

StringBuilder outputAnswers = new StringBuilder();
for (int i : indexes)
    outputAnswers.append(provinces.get(i) + "\n");

System.out.print(outputAnswers);

Sample Output

Nova Scotia
Quebec
Ontario
Alberta
New Brunswick


问:
How to build a json file in jenkins inside a for loop
Im trying to build a json file in a jenkins job.

I have a list of repos with a list of branches for each repo. I want to take this data and build a json file with it.

the end result should look like

```<code>[
    {
    "name": "repoName",
    "branches" :
        [
        "name" : "branchName",
        "name" : "branchName2"
        ]
    },
    {
    "name": "repoName2",
    "branches" :
        [
        "name" : "branchName",
        "name" : "branchName2",
        "name" : "branchName3",
        ]
    }
]
</code>```

repoName and branchName both come from vars.

my code looks like this

```<code>script {
    node{
        unstash 'build'
        env.WORKSPACE = pwd()
        def buildConfig = load "GenerateBuildSelections.Groovy"
        def repos = buildConfig.GetListOfRepos("${env.WORKSPACE}/Repos.json")

        for(i = 0; i < repos.size(); i++){
            def repoName = repos[i]
            httpRequest acceptType: 'APPLICATION_JSON', authentication: '********-****-****-****-************', consoleLogResponseBody: true, contentType: 'APPLICATION_JSON', outputFile: "branches_${repoName}.json", responseHandle: 'NONE', url: "https://api.github.com/repos/GenesisGaming/${repoName}/branches"
            env.WORKSPACE = pwd()
            def branches = buildConfig.GetListOfBranches("${env.WORKSPACE}/branches_${repoName}.json")

            //How do I save the Repo name with the branches here without overwriting the builder everytime
         }
     }
 }
</code>```

I want to be able to save each repo with the list of branches all to the same json. I cant figure out how to do this without overwriting it every time.

答:
burnettk pointed me towards using a hashmap which worked perfectly. Here is the updated code that saves it to a json.</p>

```<code>pipeline {
agent any

stages {
    stage ('Create Build Parameters'){
        steps{
            sh 'echo !---SETUP---!'
            git credentialsId: '', url: 'https://github.com/GenesisGaming/DevOpsJenkins.git'
            httpRequest acceptType: 'APPLICATION_JSON', authentication: '', consoleLogResponseBody: false, contentType: 'APPLICATION_JSON', outputFile: 'Repos.json', responseHandle: 'NONE', url: 'https://api.github.com/search/code?q=org:GenesisGaming+filename:Project.xml&per_page=100'
            readFile 'Repos.json'
            stash includes: '**', name: 'build'
            script {
                node{
                    unstash 'build'
                    env.WORKSPACE = pwd()
                    def buildConfig = load "GenerateBuildSelections.Groovy"
                    def repos = buildConfig.GetListOfRepos("${env.WORKSPACE}/Repos.json")

                    def dataMap = new HashMap<String,List>()
                    for(i = 0; i < repos.size(); i++){
                        def repoName = repos[i]
                        httpRequest acceptType: 'APPLICATION_JSON', authentication: '', consoleLogResponseBody: false, contentType: 'APPLICATION_JSON', outputFile: "branches_${repoName}.json", responseHandle: 'NONE', url: "https://api.github.com/repos/GenesisGaming/${repoName}/branches"
                        env.WORKSPACE = pwd()
                        def branches = buildConfig.GetListOfBranches("${env.WORKSPACE}/branches_${repoName}.json")
                        dataMap.put("${repoName}", "${branches}")

                    }
                    def builder = new groovy.json.JsonBuilder(dataMap)
                    new File("/home/service/BuildSelectionOptions/options.json").write(builder.toPrettyString())
                }
            }
        }
    }
}
post {
    always {
        sh 'echo !---Cleanup---!'
        cleanWs()
    }
}
}
</code>```

Body:
Im trying to build a json file in a jenkins job.

I have a list of repos with a list of branches for each repo. I want to take this data and build a json file with it.

the end result should look like

[
    {
    "name": "repoName",
    "branches" :
        [
        "name" : "branchName",
        "name" : "branchName2"
        ]
    },
    {
    "name": "repoName2",
    "branches" :
        [
        "name" : "branchName",
        "name" : "branchName2",
        "name" : "branchName3",
        ]
    }
]

repoName and branchName both come from vars.

my code looks like this

script {
    node{
        unstash 'build'
        env.WORKSPACE = pwd()
        def buildConfig = load "GenerateBuildSelections.Groovy"
        def repos = buildConfig.GetListOfRepos("${env.WORKSPACE}/Repos.json")

        for(i = 0; i < repos.size(); i++){
            def repoName = repos[i]
            httpRequest acceptType: 'APPLICATION_JSON', authentication: '********-****-****-****-************', consoleLogResponseBody: true, contentType: 'APPLICATION_JSON', outputFile: "branches_${repoName}.json", responseHandle: 'NONE', url: "https://api.github.com/repos/GenesisGaming/${repoName}/branches"
            env.WORKSPACE = pwd()
            def branches = buildConfig.GetListOfBranches("${env.WORKSPACE}/branches_${repoName}.json")

            //How do I save the Repo name with the branches here without overwriting the builder everytime
         }
     }
 }

I want to be able to save each repo with the list of branches all to the same json. I cant figure out how to do this without overwriting it every time.

Body:
burnettk pointed me towards using a hashmap which worked perfectly. Here is the updated code that saves it to a json.

pipeline {
agent any

stages {
    stage ('Create Build Parameters'){
        steps{
            sh 'echo !---SETUP---!'
            git credentialsId: '', url: 'https://github.com/GenesisGaming/DevOpsJenkins.git'
            httpRequest acceptType: 'APPLICATION_JSON', authentication: '', consoleLogResponseBody: false, contentType: 'APPLICATION_JSON', outputFile: 'Repos.json', responseHandle: 'NONE', url: 'https://api.github.com/search/code?q=org:GenesisGaming+filename:Project.xml&per_page=100'
            readFile 'Repos.json'
            stash includes: '**', name: 'build'
            script {
                node{
                    unstash 'build'
                    env.WORKSPACE = pwd()
                    def buildConfig = load "GenerateBuildSelections.Groovy"
                    def repos = buildConfig.GetListOfRepos("${env.WORKSPACE}/Repos.json")

                    def dataMap = new HashMap<String,List>()
                    for(i = 0; i < repos.size(); i++){
                        def repoName = repos[i]
                        httpRequest acceptType: 'APPLICATION_JSON', authentication: '', consoleLogResponseBody: false, contentType: 'APPLICATION_JSON', outputFile: "branches_${repoName}.json", responseHandle: 'NONE', url: "https://api.github.com/repos/GenesisGaming/${repoName}/branches"
                        env.WORKSPACE = pwd()
                        def branches = buildConfig.GetListOfBranches("${env.WORKSPACE}/branches_${repoName}.json")
                        dataMap.put("${repoName}", "${branches}")

                    }
                    def builder = new groovy.json.JsonBuilder(dataMap)
                    new File("/home/service/BuildSelectionOptions/options.json").write(builder.toPrettyString())
                }
            }
        }
    }
}
post {
    always {
        sh 'echo !---Cleanup---!'
        cleanWs()
    }
}
}


问:
drop duplicate rows based on some columns in excel using python
```<code>import pandas as pd
toclean = pd.ExcelFile(r'C:\Users\Desktop\New Microsoft Excel Worksheet.xlsx',sheetname=0)

df4 = toclean.drop_duplicates(subset='A', keep='last')

df4.save(r'C:\Users\Desktop\final.xlsx')
</code>```

I have a sheet in excel which has some info lets say

name    diad    ad  fa

3   23  2   3

2   2   1   1

2   2   3   2

1

now my output should look like

3   23  2   3

2   2   1   1

1

答:
Other than

df4.save(r'C:\Users\Desktop\final.xlsx')

I think the above looks good. Just replace this line with df4.to_excel(NEW FILE NAME)

Body:
import pandas as pd
toclean = pd.ExcelFile(r'C:\Users\Desktop\New Microsoft Excel Worksheet.xlsx',sheetname=0)

df4 = toclean.drop_duplicates(subset='A', keep='last')

df4.save(r'C:\Users\Desktop\final.xlsx')

I have a sheet in excel which has some info lets say

name    diad    ad  fa

3   23  2   3

2   2   1   1

2   2   3   2

1

now my output should look like

3   23  2   3

2   2   1   1

1


问:
fgets skip lines, it doesn't read all lines
I'm new to fgets, I have this code to read the row, but apparently until it reaches that line it will skip for no reason... Here is the data in my txt file that I make it to read.

```<code>ABCDEF1   SDDFS775A                                        QQ            O9
ABCDEF1   SDDFS77577432B                                                            3.00
ABCDEF1   1234567C     newCODE    123456       123456789                        83131          DIED
ABCDEF1   1234567C                                               999999                                9999999  999999                  999999
ABCDEF1   1234567D            20170606                51QAZZ  345DDW                                                  LOVE
</code>```

Code:

```<code>$handle = @fopen($name, 'r');
if ($handle) {
    while ($row = fgets($handle,4096)) {
        echo $row;
    }
}
</code>```

I can read until this row

```<code>ABCDEF1   1234567C                                               999999
</code>```

but I can't read this row

```<code>ABCDEF1   1234567D            20170606                51QAZZ  345DDW                                                  LOVE
</code>```

Any reason why?

答:
The problem with your code is with the method fgets: string fgets ( resource $handle [, int $length ] ). The second parameter is the length of the characters that will read. See the documentation here

You should leave the second parameter empty. Try this:

```<code>$fp = fopen("fichero.txt", "r");
   while(!feof($fp)) {
       $linea = fgets($fp);
       echo $linea . "<br />";
}
fclose($fp);
</code>```

Body:
I'm new to fgets, I have this code to read the row, but apparently until it reaches that line it will skip for no reason... Here is the data in my txt file that I make it to read.

ABCDEF1   SDDFS775A                                        QQ            O9
ABCDEF1   SDDFS77577432B                                                            3.00
ABCDEF1   1234567C     newCODE    123456       123456789                        83131          DIED
ABCDEF1   1234567C                                               999999                                9999999  999999                  999999
ABCDEF1   1234567D            20170606                51QAZZ  345DDW                                                  LOVE

Code:

$handle = @fopen($name, 'r');
if ($handle) {
    while ($row = fgets($handle,4096)) {
        echo $row;
    }
}

I can read until this row

ABCDEF1   1234567C                                               999999

but I can't read this row

ABCDEF1   1234567D            20170606                51QAZZ  345DDW                                                  LOVE

Any reason why?

Body:
The problem with your code is with the method fgets: string fgets ( resource $handle [, int $length ] ). The second parameter is the length of the characters that will read. See the documentation here

You should leave the second parameter empty. Try this:

$fp = fopen("fichero.txt", "r");
   while(!feof($fp)) {
       $linea = fgets($fp);
       echo $linea . "<br />";
}
fclose($fp);


问:
Store data from twitter api javascript (nodejs)
I seem to be having an issue. I'm trying to export data from the twitter api but I can't. Here's what my code looks like :

```<code>/// Twitter.js
module.exports = Twitter

function Twitter(twitter) {
    this.twitter = twitter
}

Twitter.prototype.friends = function(params) {
    this.twitter.get('friends/list', params, (err, data) => {
        if (err)
            console.log(err)

        console.log(data) // this prints data to the console but
                          // I want to export and save in a data structure
                          // array or object
    }
}

///bot.js
var Twit = require('twit')
var config = require('/path_to_config.js')
var init = Twit(config)
var Twitter = require('/path_to_Twitter.js')

var bot = new Twitter(config)
bot.friends({ screen_name: 'myscreenname'})
</code>```

If I try returning the data parameter it returns undefined and if I push data.users to an array it returns an empty array. Any help is and will be appreciated.

答:
Looks like it might be an async problem. I'm not familiar with the Twitter API, but you could try (or a variation of) the following:

```<code>Twitter.prototype.friends = function(params, cb) {
  this.twitter.get('friends/list', params, cb);
};
</code>```

And then:

```<code>var bot = new Twitter(config)
bot.friends({ screen_name: 'myscreenname'}, (err, data) => {
  // Do something with the data here.
  console.log('data', data);
});
</code>```

It's the same logic, but moving the async response to a place more useful to what you might be trying to do.

Body:
I seem to be having an issue. I'm trying to export data from the twitter api but I can't. Here's what my code looks like :

/// Twitter.js
module.exports = Twitter

function Twitter(twitter) {
    this.twitter = twitter
}

Twitter.prototype.friends = function(params) {
    this.twitter.get('friends/list', params, (err, data) => {
        if (err)
            console.log(err)

        console.log(data) // this prints data to the console but
                          // I want to export and save in a data structure
                          // array or object
    }
}

///bot.js
var Twit = require('twit')
var config = require('/path_to_config.js')
var init = Twit(config)
var Twitter = require('/path_to_Twitter.js')

var bot = new Twitter(config)
bot.friends({ screen_name: 'myscreenname'})

If I try returning the data parameter it returns undefined and if I push data.users to an array it returns an empty array. Any help is and will be appreciated.

Body:
Looks like it might be an async problem. I'm not familiar with the Twitter API, but you could try (or a variation of) the following:

Twitter.prototype.friends = function(params, cb) {
  this.twitter.get('friends/list', params, cb);
};

And then:

var bot = new Twitter(config)
bot.friends({ screen_name: 'myscreenname'}, (err, data) => {
  // Do something with the data here.
  console.log('data', data);
});

It's the same logic, but moving the async response to a place more useful to what you might be trying to do.


问:
How can I make a TimerTask run in a certain period and to
I have a method that has to take a picture of the screen every 0.5 seconds and saves the image in a place on the HD. But I need him to run between 11:55 a.m. and 4:55 p.m. to 5:00 p.m.

I just got to start the Task and I could not stop it.

My doubt is:

How could I schedule, for the thread to run only within a certain period of time.

```<code>public class Main {

private Toolkit a = Toolkit.getDefaultToolkit();
private Dimension screenSize = a.getScreenSize();
private Rectangle screenLimit = new Rectangle(screenSize);
private Robot robot;

private File file;

BufferedImage img;

private final static int TWO_AM = 11;
private final static int ZERO_MINUTES = 28;

private static Date getTomorrowMorning1145AM(){

    Date date2am = new java.util.Date();
       date2am.setHours(TWO_AM);
       date2am.setMinutes(ZERO_MINUTES);

       return date2am;
  }

public Main() {

    String path = "c:\\print\\"+System.getProperty("user.name")+"\\";

    try {
        robot = new Robot();
        file = new File(path);
    } catch (AWTException e1) {
        e1.printStackTrace();
    }

    if(!file.exists()){
        file.mkdirs();
    }

    TimerTask tt = new TimerTask() {

        @Override
        public void run() {

            try {
                tirarPrint(path+"print_" + new Date().getTime() + ".jpg");
            } catch (IOException | AWTException e) {
                e.printStackTrace();
            }

        }
    };

    Timer t = new Timer();

    t.schedule(tt, 0, 500);

}

private void tirarPrint(String caminho) throws AWTException, IOException {

    img = robot.createScreenCapture(screenLimit);
    ImageIO.write(img, "jpg", new File(caminho));

 }

public static void main(String[] args) {
    new Main();
  }
}
</code>```

答: You could use windows task scheduler to run the program on a schedule, or if you want the program to control it, you could have a loop that runs continuously, sleeping for 30 seconds then checks the time, and runs the code if it is the desired time.</p>

Body:
I have a method that has to take a picture of the screen every 0.5 seconds and saves the image in a place on the HD. But I need him to run between 11:55 a.m. and 4:55 p.m. to 5:00 p.m.

I just got to start the Task and I could not stop it.

My doubt is:

How could I schedule, for the thread to run only within a certain period of time.

public class Main {

private Toolkit a = Toolkit.getDefaultToolkit();
private Dimension screenSize = a.getScreenSize();
private Rectangle screenLimit = new Rectangle(screenSize);
private Robot robot;

private File file;

BufferedImage img;

private final static int TWO_AM = 11;
private final static int ZERO_MINUTES = 28;

private static Date getTomorrowMorning1145AM(){

    Date date2am = new java.util.Date();
       date2am.setHours(TWO_AM);
       date2am.setMinutes(ZERO_MINUTES);

       return date2am;
  }

public Main() {

    String path = "c:\\print\\"+System.getProperty("user.name")+"\\";

    try {
        robot = new Robot();
        file = new File(path);
    } catch (AWTException e1) {
        e1.printStackTrace();
    }

    if(!file.exists()){
        file.mkdirs();
    }

    TimerTask tt = new TimerTask() {

        @Override
        public void run() {

            try {
                tirarPrint(path+"print_" + new Date().getTime() + ".jpg");
            } catch (IOException | AWTException e) {
                e.printStackTrace();
            }

        }
    };

    Timer t = new Timer();

    t.schedule(tt, 0, 500);

}

private void tirarPrint(String caminho) throws AWTException, IOException {

    img = robot.createScreenCapture(screenLimit);
    ImageIO.write(img, "jpg", new File(caminho));

 }

public static void main(String[] args) {
    new Main();
  }
}


问:
Filter csv list with awk
I have the following (much longer) csv list:

```<code>...
"AT3";"AT32";"AT322";"504";"50401"
"AT2";"AT13";"AT322";"504";"50401"
"AT2";"AT13";"AT31243";"604";"503401"
...
</code>```

Now, I'd like to filter all rows which contain "AT13" in the 2nd column.

I tried: awk 'BEGIN {FS=","} {if($2 == "AT13") print}' GISA-OpenData.csv > WIEN.csv
But it doesn't give my any output. Does anyone know what could be the error here? WIEN.csv is always empty.

many thanks

答:
You can use:

```<code>awk -F";" '$2=="\"AT13\""' GISA-OpenData.csv > WIEN.csv
</code>```

Since your field seperator (FS) is just a comma, you have to search when $2 has the value you want surrounded by double quotes, which we escape here.

You could also do a regex like search so you don't have to monkey with escaping:

```<code>awk -F";" '$2~"AT13"' GISA-OpenData.csv > WIEN.csv
</code>```

Title: Filter csv list with awk

Body:
I have the following (much longer) csv list:

...
"AT3";"AT32";"AT322";"504";"50401"
"AT2";"AT13";"AT322";"504";"50401"
"AT2";"AT13";"AT31243";"604";"503401"
...

Now, I'd like to filter all rows which contain "AT13" in the 2nd column.

I tried: awk 'BEGIN {FS=","} {if($2 == "AT13") print}' GISA-OpenData.csv > WIEN.csv
But it doesn't give my any output. Does anyone know what could be the error here? WIEN.csv is always empty.

many thanks

Body:
You can use:

awk -F";" '$2=="\"AT13\""' GISA-OpenData.csv > WIEN.csv

Since your field seperator (FS) is just a comma, you have to search when $2 has the value you want surrounded by double quotes, which we escape here.

You could also do a regex like search so you don't have to monkey with escaping:

awk -F";" '$2~"AT13"' GISA-OpenData.csv > WIEN.csv