问:
finding if substring exists in file in python
I have 2 files. One is my "keyfile" and other is "lookupfile". I'am trying to check if line in keyfile is present in lookup.Here's my code snippet

```<code>lookupfile = open("riskeng_recon_e_mso_transact_db_msoinputapplication_t2.txt","r")

with open("1.txt","r") as my_file:
    for line in my_file:
        print "-------------checking for "+line+"-----------"
        for x in lookupfile:
            #print x
            if str(line) in str(x):
                print "Line present"+line
</code>```

My 2 files have records in this format.

```<code>Lookupfile:

1234asfd
32453sdfvs
sfgagss234

keyfile:

123
3245
124
</code>```

My issue here is that after taking first record from key file and comparing it with lookupfile, it is not moving forward with the next record in lookupfile.

答:
Create two lists listkf and listlookup by reading the files

```<code>listkf=[]
with open("keyfile", 'r') as kf:
    for line in kf:
        listkf.append(line.strip())    # adding key to list after stripping

listlookup=[]
with open("Lookupfile", 'r') as lf:
    for line in lf:
        listlookup.append(line)
</code>```

Assuming you need line by line match

```<code>for i in range(len(listlookup)):
    if listkf[i] in listlookup[i]:
         print("key exists")
    else:
         print("key does not exist")
</code>```

If key in keyfile is to be looked up in entire Lookupfile

```<code>for x in listkf:
    for y in listlookup:
        if x in str(y):
            print("key ", x, " exists")
            break
</code>```

Body:
I have 2 files. One is my "keyfile" and other is "lookupfile". I'am trying to check if line in keyfile is present in lookup.Here's my code snippet

lookupfile = open("riskeng_recon_e_mso_transact_db_msoinputapplication_t2.txt","r")

with open("1.txt","r") as my_file:
    for line in my_file:
        print "-------------checking for "+line+"-----------"
        for x in lookupfile:
            #print x
            if str(line) in str(x):
                print "Line present"+line

My 2 files have records in this format.

Lookupfile:

1234asfd
32453sdfvs
sfgagss234

keyfile:

123
3245
124

My issue here is that after taking first record from key file and comparing it with lookupfile, it is not moving forward with the next record in lookupfile.

Body:
Create two lists listkf and listlookup by reading the files

listkf=[]
with open("keyfile", 'r') as kf:
    for line in kf:
        listkf.append(line.strip())    # adding key to list after stripping

listlookup=[]
with open("Lookupfile", 'r') as lf:
    for line in lf:
        listlookup.append(line)

Assuming you need line by line match

for i in range(len(listlookup)):
    if listkf[i] in listlookup[i]:
         print("key exists")
    else:
         print("key does not exist")

If key in keyfile is to be looked up in entire Lookupfile

for x in listkf:
    for y in listlookup:
        if x in str(y):
            print("key ", x, " exists")
            break


来源: stackexchange

问:
My loop creating another parent array rather than appending it to where I have pointed?
I need to loop through my database and be able to group between day, time, class, and students. I have been able to use a bunch of if(!isset()) statements to achieve what I am after with this code.

```<code>foreach ($sqlEx as $rows) {
    if(!isset($day) || $day !== $rows['DAY']) {
        $day = $rows['DAY'];
        $scheduleJSON['DAY'] = $day;
    }
    if(!isset($time) || $time !== $rows['CLASSTIME']) {
        $time = $rows['CLASSTIME'];
        $scheduleJSON[$time]= [];
        $scheduleJSON[NULL] = $scheduleJSON[$time];
        unset($scheduleJSON[NULL]);
    }
    if(!isset($instructor) || $instructor !== $rows['INSTRUCTOR']) {
        $instructor = $rows['INSTRUCTOR'];
        $classlevel = $rows['CLASSLEVEL'];
        $maxstudent = $rows['MAXSTUDENT'];
        $scheduleJSON[$time]['CLASSES'][]['CLASS'] = ['INSTRUCTOR' => $instructor, 'CLASS LEVEL' => $classlevel, 'MAX STUDENTS' => $maxstudent];
    } else {
        $studentfirst = $rows['STUDENTFIRST'];
        $studentlast = $rows['STUDENTLAST'];
        $scheduleJSON[$time]['CLASSES']['CLASS']['STUDENTS'][] = ['STUDENT' => ['FIRST NAME' => $studentfirst, 'LAST NAME' => $studentlast]];
    }
}
</code>```

I am looking at getting my array to have this structure:

```<code>$scheduleJSON = [
    'DAY' => NULL, 'TIME' => [
        'CLASSES' => [
            'CLASS' => [
                'INSTRUCTOR' => NULL, 'CLASS LEVEL' => NULL, 'MAX STUDENTS' => NULL, 'STUDENTS' => [
                    'STUDENT' => [
                        'FIRST NAME' => NULL, 'LAST NAME' => NULL, 'DATE OF BIRTH' => NULL, 'PARENT FIRST NAME' => NULL, 'PARENT LAST NAME' => NULL
                    ]
                ]
            ]
        ]
    ]
];
</code>```

However, when I print to JSON encode, my problem, I think, is within my else statement. Instead of appending the STUDENTS as another key => value in the class after MAX STUDENTS, it's creating another CLASS array.

```<code>"DAY": "THURSDAY",
"530": {
    "CLASSES": {
        "0": {
            "CLASS": {
                "INSTRUCTOR": "Teacher",
                "CLASS LEVEL": "JUNIOR",
                "MAX STUDENTS": "8"
            }
        },
        "CLASS": {
            "STUDENTS": [
                {
                    "STUDENT": {
                        "FIRST NAME": "Student",
                        "LAST NAME": ""
                    }
                },
</code>```

Any help at this point would be greatly appreciated - I have been searching the problem and answer for days.

-- EDIT
Array from $sqlEx. Please note that I have removed the name data that did come out with it for privacy.

```<code>array(20) {
  ["DAY"]=>
  string(8) "THURSDAY"
  [0]=>
  string(8) "THURSDAY"
  ["CLASSTIME"]=>
  string(3) "530"
  [1]=>
  string(3) "530"
  ["CLASSLEVEL"]=>
  string(6) "JUNIOR"
  [2]=>
  string(6) "JUNIOR"
  ["MAXSTUDENT"]=>
  string(1) "8"
  [3]=>
  string(1) "8"
  ["INSTRUCTOR"]=>
  string(4) "TEACHER"
  [4]=>
  string(4) "TEACHER"
  ["STUDENTFIRST"]=>
  string(5) "First Name"
  [5]=>
  string(5) "First Name"
  ["STUDENTLAST"]=>
  string(0) ""
  [6]=>
  string(0) ""
  ["STUDENTDOB"]=>
  string(10) "2007-04-28"
  [7]=>
  string(10) "2007-04-28"
  ["PARENTFIRST"]=>
  string(12) "Parent First Name"
  [8]=>
  string(12) "Parent First Name"
  ["PARENTLAST"]=>
  string(6) "Parent Last Name"
  [9]=>
  string(6) "Parent Last Name"
}
</code>```

答:
So after working through the issue with @Erwin, I have finally been able to output the JSON as follows:

```<code>{
"DAY": "THURSDAY",
"530": {
    "CLASSES": {
        "CLASS-1335": {
            "INSTRUCTOR": "TEACHER",
            "CLASS LEVEL": "JUNIOR",
            "MAX STUDENTS": "8",
            "START TIME": "530",
            "FINISH TIME": "730",
            "STUDENTS": [
                {
                    "STUDENT": {
                        "FIRST NAME": "First Name",
                        "LAST NAME": ""
                    }
                }
            ]
        },
        "CLASS-2243": {
            "INSTRUCTOR": "TEACHER",
            "CLASS LEVEL": "SENIOR ",
            "MAX STUDENTS": "8",
            "START TIME": "530",
            "FINISH TIME": "730",
            "STUDENTS": [
                {
                    "STUDENT": {
                        "FIRST NAME": "First Name",
                        "LAST NAME": ""
                    }
                },
                {
                    "STUDENT": {
                        "FIRST NAME": "First Name",
                        "LAST NAME": ""
                    }
                }, ETC...
</code>```

The following is the code that allowed me to accomplish this. I needed to add some more logic into my code to pull a unique identifier for each class (such as CLASS.ID) rather than just blindly adding a new level to the array.

So for each level of this multidimensional array, an if(!isset($var) || $var !== $rows[$val]) {} was needed (in order of parent to child) to discern if the current record being processed had the same property (such as DAY or CLASS TIME) - if the value in any of the statements was different (or not set), set the new variable value and push it into the array.

```<code>foreach ($sqlEx as $rows) {
        if(!isset($day) || $day !== $rows['DAY']) {
            $day = $rows['DAY'];
            $scheduleJSON['DAY'] = $day;
        }
        if(!isset($time) || $time !== $rows['CLASSTIME']) {
            $time = $rows['CLASSTIME'];
            $scheduleJSON[$time]= [];
            $scheduleJSON[NULL] = $scheduleJSON[$time];
            unset($scheduleJSON[NULL]);
        }
        if(!isset($classid) || $classid !== $rows['CLASSID']) {
            $classid = $rows['CLASSID'];
            $instructor = $rows['INSTRUCTOR'];
            $classlevel = $rows['CLASSLEVEL'];
            $maxstudent = $rows['MAXSTUDENT'];
            $finishtime = $rows['CLASSENDTIME'];
            $scheduleJSON[$time]['CLASSES']['CLASS' . '-' . $classid] = [
                'INSTRUCTOR' => $instructor,
                'CLASS LEVEL' => $classlevel,
                'MAX STUDENTS' => $maxstudent,
                'START TIME' => $time,
                'FINISH TIME' => $finishtime
            ];
        }

        $studentfirst = $rows['STUDENTFIRST'];
        $studentlast = $rows['STUDENTLAST'];
        $scheduleJSON[$time]['CLASSES']['CLASS' . '-' . $classid]['STUDENTS'][] = [
            'STUDENT' => [
                'FIRST NAME' => $studentfirst,
                'LAST NAME' => $studentlast
            ]
        ];
    }

    print_r(json_encode($scheduleJSON, JSON_PRETTY_PRINT));
</code>```

This is a decent chunk of code although I am not sure it can be refactored or not, however, it works quite fast and well for my situation - which is creating a grouped list for a class schedule.

Thanks everyone for your help! I have definitely grown from this!

Regards
Michael Z

ContentLicense: CC BY-SA 3.0

Body:
I need to loop through my database and be able to group between day, time, class, and students. I have been able to use a bunch of if(!isset()) statements to achieve what I am after with this code.

foreach ($sqlEx as $rows) {
    if(!isset($day) || $day !== $rows['DAY']) {
        $day = $rows['DAY'];
        $scheduleJSON['DAY'] = $day;
    }
    if(!isset($time) || $time !== $rows['CLASSTIME']) {
        $time = $rows['CLASSTIME'];
        $scheduleJSON[$time]= [];
        $scheduleJSON[NULL] = $scheduleJSON[$time];
        unset($scheduleJSON[NULL]);
    }
    if(!isset($instructor) || $instructor !== $rows['INSTRUCTOR']) {
        $instructor = $rows['INSTRUCTOR'];
        $classlevel = $rows['CLASSLEVEL'];
        $maxstudent = $rows['MAXSTUDENT'];
        $scheduleJSON[$time]['CLASSES'][]['CLASS'] = ['INSTRUCTOR' => $instructor, 'CLASS LEVEL' => $classlevel, 'MAX STUDENTS' => $maxstudent];
    } else {
        $studentfirst = $rows['STUDENTFIRST'];
        $studentlast = $rows['STUDENTLAST'];
        $scheduleJSON[$time]['CLASSES']['CLASS']['STUDENTS'][] = ['STUDENT' => ['FIRST NAME' => $studentfirst, 'LAST NAME' => $studentlast]];
    }
}

I am looking at getting my array to have this structure:

$scheduleJSON = [
    'DAY' => NULL, 'TIME' => [
        'CLASSES' => [
            'CLASS' => [
                'INSTRUCTOR' => NULL, 'CLASS LEVEL' => NULL, 'MAX STUDENTS' => NULL, 'STUDENTS' => [
                    'STUDENT' => [
                        'FIRST NAME' => NULL, 'LAST NAME' => NULL, 'DATE OF BIRTH' => NULL, 'PARENT FIRST NAME' => NULL, 'PARENT LAST NAME' => NULL
                    ]
                ]
            ]
        ]
    ]
];

However, when I print to JSON encode, my problem, I think, is within my else statement. Instead of appending the STUDENTS as another key => value in the class after MAX STUDENTS, it's creating another CLASS array.

"DAY": "THURSDAY",
"530": {
    "CLASSES": {
        "0": {
            "CLASS": {
                "INSTRUCTOR": "Teacher",
                "CLASS LEVEL": "JUNIOR",
                "MAX STUDENTS": "8"
            }
        },
        "CLASS": {
            "STUDENTS": [
                {
                    "STUDENT": {
                        "FIRST NAME": "Student",
                        "LAST NAME": ""
                    }
                },

Any help at this point would be greatly appreciated - I have been searching the problem and answer for days.

-- EDIT
Array from $sqlEx. Please note that I have removed the name data that did come out with it for privacy.

array(20) {
  ["DAY"]=>
  string(8) "THURSDAY"
  [0]=>
  string(8) "THURSDAY"
  ["CLASSTIME"]=>
  string(3) "530"
  [1]=>
  string(3) "530"
  ["CLASSLEVEL"]=>
  string(6) "JUNIOR"
  [2]=>
  string(6) "JUNIOR"
  ["MAXSTUDENT"]=>
  string(1) "8"
  [3]=>
  string(1) "8"
  ["INSTRUCTOR"]=>
  string(4) "TEACHER"
  [4]=>
  string(4) "TEACHER"
  ["STUDENTFIRST"]=>
  string(5) "First Name"
  [5]=>
  string(5) "First Name"
  ["STUDENTLAST"]=>
  string(0) ""
  [6]=>
  string(0) ""
  ["STUDENTDOB"]=>
  string(10) "2007-04-28"
  [7]=>
  string(10) "2007-04-28"
  ["PARENTFIRST"]=>
  string(12) "Parent First Name"
  [8]=>
  string(12) "Parent First Name"
  ["PARENTLAST"]=>
  string(6) "Parent Last Name"
  [9]=>
  string(6) "Parent Last Name"
}

Body:
So after working through the issue with @Erwin, I have finally been able to output the JSON as follows:

{
"DAY": "THURSDAY",
"530": {
    "CLASSES": {
        "CLASS-1335": {
            "INSTRUCTOR": "TEACHER",
            "CLASS LEVEL": "JUNIOR",
            "MAX STUDENTS": "8",
            "START TIME": "530",
            "FINISH TIME": "730",
            "STUDENTS": [
                {
                    "STUDENT": {
                        "FIRST NAME": "First Name",
                        "LAST NAME": ""
                    }
                }
            ]
        },
        "CLASS-2243": {
            "INSTRUCTOR": "TEACHER",
            "CLASS LEVEL": "SENIOR ",
            "MAX STUDENTS": "8",
            "START TIME": "530",
            "FINISH TIME": "730",
            "STUDENTS": [
                {
                    "STUDENT": {
                        "FIRST NAME": "First Name",
                        "LAST NAME": ""
                    }
                },
                {
                    "STUDENT": {
                        "FIRST NAME": "First Name",
                        "LAST NAME": ""
                    }
                }, ETC...

The following is the code that allowed me to accomplish this. I needed to add some more logic into my code to pull a unique identifier for each class (such as CLASS.ID) rather than just blindly adding a new level to the array.

So for each level of this multidimensional array, an if(!isset($var) || $var !== $rows[$val]) {} was needed (in order of parent to child) to discern if the current record being processed had the same property (such as DAY or CLASS TIME) - if the value in any of the statements was different (or not set), set the new variable value and push it into the array.

foreach ($sqlEx as $rows) {
        if(!isset($day) || $day !== $rows['DAY']) {
            $day = $rows['DAY'];
            $scheduleJSON['DAY'] = $day;
        }
        if(!isset($time) || $time !== $rows['CLASSTIME']) {
            $time = $rows['CLASSTIME'];
            $scheduleJSON[$time]= [];
            $scheduleJSON[NULL] = $scheduleJSON[$time];
            unset($scheduleJSON[NULL]);
        }
        if(!isset($classid) || $classid !== $rows['CLASSID']) {
            $classid = $rows['CLASSID'];
            $instructor = $rows['INSTRUCTOR'];
            $classlevel = $rows['CLASSLEVEL'];
            $maxstudent = $rows['MAXSTUDENT'];
            $finishtime = $rows['CLASSENDTIME'];
            $scheduleJSON[$time]['CLASSES']['CLASS' . '-' . $classid] = [
                'INSTRUCTOR' => $instructor,
                'CLASS LEVEL' => $classlevel,
                'MAX STUDENTS' => $maxstudent,
                'START TIME' => $time,
                'FINISH TIME' => $finishtime
            ];
        }

        $studentfirst = $rows['STUDENTFIRST'];
        $studentlast = $rows['STUDENTLAST'];
        $scheduleJSON[$time]['CLASSES']['CLASS' . '-' . $classid]['STUDENTS'][] = [
            'STUDENT' => [
                'FIRST NAME' => $studentfirst,
                'LAST NAME' => $studentlast
            ]
        ];
    }

    print_r(json_encode($scheduleJSON, JSON_PRETTY_PRINT));

This is a decent chunk of code although I am not sure it can be refactored or not, however, it works quite fast and well for my situation - which is creating a grouped list for a class schedule.

Thanks everyone for your help! I have definitely grown from this!

Regards
Michael Z


问:
tensorflow, How to index the true value of a tensor?
I have a 1-d tensor like:

```<code>[false, false, true, false, true, false]
</code>```

How to find the index of all the true value?

My solution is:

Turn it to 1 and 0 value

Use argmax API to find one index and then set the one to false/0.

Use argmax again to find the next true/1 value

But this solution is not that good.

答:
```<code>import tensorflow as tf

a = tf.constant([False,False,True,False,True],dtype=tf.bool)
b = tf.where(a)
sess = tf.Session()
print(sess.run(b))
</code>```

Body:
I have a 1-d tensor like:

[false, false, true, false, true, false]

How to find the index of all the true value?

My solution is:

Turn it to 1 and 0 value

Use argmax API to find one index and then set the one to false/0.

Use argmax again to find the next true/1 value

But this solution is not that good.

ContentLicense: CC BY-SA 4.0


问:
Combine Moment object with a time string to get a new moment object
I have a moment object and a seperate time string like this:

```<code>var selectedDay = moment();
var time = '6 PM';
</code>```

I want to combine the 2 I can't figure it out from the documentation, something like this.

```<code>var actualMoment = moment(selectedDay).setTime(time);
</code>```

The time variable could be values like the following: 6 AM, 5 PM, 4:30 PM I could potentially change the format of the time variable if it makes it easier, but the two values still need to be seperate variables.

答:
You can write an extension to your script:

```<code>moment.fn.setTime(str, format){
    var timeParsed = moment(str, format);
    if(timeParsed.isValid() == true)
    {
        return this.hour(timeParsed.hour())
                   .minute(timeParsed.minute())
                   .second(timeParsed.second());
    } else {
        console.warning(" Time couldn't be parsed: " + str + " (format: " format + ")";
        return this;
    }
}
</code>```

Then use it as you used in your example:

```<code>var selectedDay = moment();
var time = '6 PM';
var actualMoment = selectedDay.setTime(time, 'h A');
</code>```

Body:
I have a moment object and a seperate time string like this:

var selectedDay = moment();
var time = '6 PM';

I want to combine the 2 I can't figure it out from the documentation, something like this.

var actualMoment = moment(selectedDay).setTime(time);

The time variable could be values like the following: 6 AM, 5 PM, 4:30 PM I could potentially change the format of the time variable if it makes it easier, but the two values still need to be seperate variables.

Body:
You can write an extension to your script:

moment.fn.setTime(str, format){
    var timeParsed = moment(str, format);
    if(timeParsed.isValid() == true)
    {
        return this.hour(timeParsed.hour())
                   .minute(timeParsed.minute())
                   .second(timeParsed.second());
    } else {
        console.warning(" Time couldn't be parsed: " + str + " (format: " format + ")";
        return this;
    }
}

Then use it as you used in your example:

var selectedDay = moment();
var time = '6 PM';
var actualMoment = selectedDay.setTime(time, 'h A');


问:
AngularJS Filter based on radio selection
I am implementing a search input box that should search based off of a certain property of the objects that are getting iterated over and I would like them to be selected using a radio button.

For example here is my code:

```<code><span style="margin-bottom: 10px; display: inline-block;">Search: <input ng-model="searchText.CustomerName" /> </span>

    <table id="Table1" class="alertTable">
        <thead>
            <tr>
                <th class="xsmCol"><img src="/App_Themes/SkyKick/images/misc/clear.gif" class="iFlag" /></th>
                <th>Subject</th>
                <th>Customer</th>
                <th>Type</th>
                <th>Date</th>
                <th class="smCol">Actions</th>
            </tr>
        </thead>
        <tbody id="tbAlerts">
            <tr ng-repeat-start="alert in alerts | filter:searchText"  > <!-- | filter:searchText -->
                <td><img src="/App_Themes/SkyKick/images/misc/clear.gif" data-tooltip="{{ alert.tooltip }}" class="{{ 'iAlert' + alert.AlertType }}"/></td>
                <td><a href="Show Alert Details" ng-click="showAlertDetails($event)">{{ alert.Summary }}</a></td>
                <td>{{ alert.CustomerName }}</td>
                <td>{{ alert.CreatedDate }}</td>
                <td>{{ alert.Category }}</td>
                <td>
                    <!-- Tricky little widget logic -->

                </td>
            </tr>
            <tr ng-repeat-end class="alertDetail">
                <td></td>
                <td colspan="5" ng-bind-html="alert.Details"></td>
            </tr>
        </tbody>
    </table>
</code>```

As you can see, I am currently filtering based off of the CustomerName field in my array. However, I want to change the logic so that I can select between CustomerName, Subject, Type, and Date using a radio button. So if the user clicks the Date radio button, then the searchText will filter only based off the Date attribute. What is the best way to get this functionality?

答:
angular.module('myApp', []).controller('candidateCtrl', function($scope) {
    $scope.candidates = [
        {name:'Goutam',role:'Engineer',country:'India'},
        {name:'Carl',role:'Engineer',country:'Sweden'},
        {name:'Margareth',role:'Doctor',country:'England'},
        {name:'Hege',role:'Engineer',country:'Norway'},
        {name:'Joe',role:'Engineer',country:'Denmark'},
        {name:'Rathin',role:'Doctor',country:'India'},
        {name:'Birgit',role:'Teacher',country:'Denmark'},
        {name:'Mary',role:'Engineer',country:'England'},
        {name:'Kai',role:'Teacher',country:'Norway'}
        ];

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body ng-app="myApp">

<div class="container" ng-controller="candidateCtrl">
<h2>Bootstrap inline Radio Buttons</h2>
<div class="row">
<div class="col-lg-4">
  <p>Angular JS Filter by Radio Button</p>
  <form>
    <label class="radio-inline">
      <input type="radio" name="optradio" ng-model="searchText.role" value="Engineer">Engineer
    </label>
    <label class="radio-inline">
      <input type="radio" name="optradio" ng-model="searchText.role" value="Doctor">Doctor
    </label>
    <label class="radio-inline">
      <input type="radio" name="optradio" ng-model="searchText.role" value="Teacher">Teacher
    </label>
  </form>

</div>
</div>

<div class="row">
<div class="col-lg-4">

  <table class="table table-hover">
    <thead>
      <tr>
        <th>Name</th>
        <th>Profession</th>
        <th>Country</th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="candidate in candidates | filter:searchText:strict">
        <td>{{candidate.name}}</td>
        <td>{{candidate.role}}</td>
        <td>{{candidate.country}}</td>
      </tr>
    </tbody>
  </table>

</div>
</div>

</div>
</body></code>```

Body:
I am implementing a search input box that should search based off of a certain property of the objects that are getting iterated over and I would like them to be selected using a radio button.

For example here is my code:

Search: <input ng-model="searchText.CustomerName" />

                Subject
                Customer
                Type
                Date
                Actions

                {{ alert.Summary }}
                {{ alert.CustomerName }}
                {{ alert.CreatedDate }}
                {{ alert.Category }}

As you can see, I am currently filtering based off of the CustomerName field in my array. However, I want to change the logic so that I can select between CustomerName, Subject, Type, and Date using a radio button. So if the user clicks the Date radio button, then the searchText will filter only based off the Date attribute. What is the best way to get this functionality?

Body:
angular.module('myApp', []).controller('candidateCtrl', function($scope) {
    $scope.candidates = [
        {name:'Goutam',role:'Engineer',country:'India'},
        {name:'Carl',role:'Engineer',country:'Sweden'},
        {name:'Margareth',role:'Doctor',country:'England'},
        {name:'Hege',role:'Engineer',country:'Norway'},
        {name:'Joe',role:'Engineer',country:'Denmark'},
        {name:'Rathin',role:'Doctor',country:'India'},
        {name:'Birgit',role:'Teacher',country:'Denmark'},
        {name:'Mary',role:'Engineer',country:'England'},
        {name:'Kai',role:'Teacher',country:'Norway'}
        ];

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body ng-app="myApp">

<div class="container" ng-controller="candidateCtrl">
<h2>Bootstrap inline Radio Buttons</h2>
<div class="row">
<div class="col-lg-4">
  <p>Angular JS Filter by Radio Button</p>
  <form>
    <label class="radio-inline">
      <input type="radio" name="optradio" ng-model="searchText.role" value="Engineer">Engineer
    </label>
    <label class="radio-inline">
      <input type="radio" name="optradio" ng-model="searchText.role" value="Doctor">Doctor
    </label>
    <label class="radio-inline">
      <input type="radio" name="optradio" ng-model="searchText.role" value="Teacher">Teacher
    </label>
  </form>

</div>
</div>

<div class="row">
<div class="col-lg-4">

  <table class="table table-hover">
    <thead>
      <tr>
        <th>Name</th>
        <th>Profession</th>
        <th>Country</th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="candidate in candidates | filter:searchText:strict">
        <td>{{candidate.name}}</td>
        <td>{{candidate.role}}</td>
        <td>{{candidate.country}}</td>
      </tr>
    </tbody>
  </table>

</div>
</div>

</div>
</body>


问:
Given a string, how to iterate through many regexes to find a match?
Given a string, and a mapping of regexes to integers, I want to find out which integer the string maps to (assume the string will match exactly one of those regexes)

Is it inefficient to just iterate through the hash of regexes, trying each regex against the string, then outputting the value? Certainly I cannot explicitly enumerate all possible string => integer mappings, but it seems bad to try matching each regex in bunch of regexes.

答:
You say 'it seems bad', but in the end, there is probably nothing you can do: you will have to match each string to a succession of regexes until one matches. You can memoize the results and be smart in other ways, like 'if this regex fails, these other 10 will also fail', but those are all performance optimizations that you may not need.

The simplest optimization may be to create groups of regexes with shared characteristics and first test which group the string is in. If string =~ /^a/ is nil, all other regexes that test for a string starting with a don't need to be tested anymore.

ContentLicense: CC BY-SA 2.5


问:
When a function returns, how to close resource handles in C?
If I open a file handle, but the function encounters other error which is not file error,  before closing the handle, would the file handle be leaked?

```<code>FILE* fp = fopen("test.txt", "r");
if (other_condition) {
    perror("other error occurred!");
    return EXIT_FAILURE;
}
</code>```

How to use C to implement RAII template?

答:
If I open a file handle, but the function returns before closing the handle, would the file handle be leaked?

Yes.

How to use C to implement RAII template?

There's no RAII in C, and no way to implement it portably. OTOH, it's way less critical, as in C all the control flow (with the exception of longjmp) is explicit. There's no such a thing as a stack unwind triggered by an exception, your function returns only when you explicitly return, so you can (and should) clean up explicitly at all return points.

In practice, if you have a block of code that acquires resources (and thus has to clean up if something fails or at the end), it's a common pattern to have single cleanup/exit point at the end and goto to it on failure (plus sentinel values to mark what values haven't been initialized yet; another common option is to clean up strictly in reverse order of initialization and have multiple "entrypoints" to jump to depending from the amount of initialization that succeeded, but IMO it quickly becomes a mess).

```<code>int copy_file(const char *src, const char *dest) {
    int ret = -1;
    FILE *in = NULL;
    FILE *out = NULL;
    char buf[1024];
    size_t rb;
    if((in = fopen(src, "rb")) == NULL) goto cleanup;
    if((out = fopen(dest, "wb")) == NULL) goto cleanup;
    for(;;) {
        rb = fread(buf, 1, sizeof(buf), in);
        if(rb == 0) break;
        if(fwrite(buf, 1, rb, out) != rb) break;
    }
    ret = 0;
    if(ferror(in)) ret = -2;
    else if(ferror(out)) ret = -3;
cleanup:
    if(in) fclose(in);
    if(out) fclose(out);
    return ret;
}
</code>```

Body:
If I open a file handle, but the function encounters other error which is not file error,  before closing the handle, would the file handle be leaked?

FILE* fp = fopen("test.txt", "r");
if (other_condition) {
    perror("other error occurred!");
    return EXIT_FAILURE;
}

How to use C to implement RAII template?

Body:
If I open a file handle, but the function returns before closing the handle, would the file handle be leaked?

Yes.

How to use C to implement RAII template?

There's no RAII in C, and no way to implement it portably. OTOH, it's way less critical, as in C all the control flow (with the exception of longjmp) is explicit. There's no such a thing as a stack unwind triggered by an exception, your function returns only when you explicitly return, so you can (and should) clean up explicitly at all return points.

In practice, if you have a block of code that acquires resources (and thus has to clean up if something fails or at the end), it's a common pattern to have single cleanup/exit point at the end and goto to it on failure (plus sentinel values to mark what values haven't been initialized yet; another common option is to clean up strictly in reverse order of initialization and have multiple "entrypoints" to jump to depending from the amount of initialization that succeeded, but IMO it quickly becomes a mess).

int copy_file(const char *src, const char *dest) {
    int ret = -1;
    FILE *in = NULL;
    FILE *out = NULL;
    char buf[1024];
    size_t rb;
    if((in = fopen(src, "rb")) == NULL) goto cleanup;
    if((out = fopen(dest, "wb")) == NULL) goto cleanup;
    for(;;) {
        rb = fread(buf, 1, sizeof(buf), in);
        if(rb == 0) break;
        if(fwrite(buf, 1, rb, out) != rb) break;
    }
    ret = 0;
    if(ferror(in)) ret = -2;
    else if(ferror(out)) ret = -3;
cleanup:
    if(in) fclose(in);
    if(out) fclose(out);
    return ret;
}


问:
AngularJS - ng-select not working as expected
I have a filter drop down for some tabular data that reads data from a local storage item, the select tag is shown below, and below that is the code to add items to the select tag and the model for the filter.

The issue is that whilst the data filtered is correct when you refresh the page, the selected item only shows the correct value if the local storage value is true.

No matter what value the local storage item is selected="selected" is always added to the "Excluded from Search" option.

Can't for the life of me work out why, any help advice appreciated.

```<code><select class="form-control form-control-sm" ng-model="filterSearch" ng-change="setFilterS()" id="theFilterS" >
    <option ng-selected="{{option.value == filterSearch}}" ng-repeat="option in filterSearchOptions" value="{{option.value}}" >{{option.DisplayName}}</option>
</select>

$scope.filterSearch = localStorage.getItem("FilterSearch");

$scope.filterSearchOptions = [{
        value: '',
        DisplayName: 'All',
    }, {
        value: 'false',
        DisplayName: 'Included in Search',
    }, {
        value: 'true',
        DisplayName: 'Excluded from Search',
    }];
</code>```

答:
You should try with the ng-options directive which IMO gives a simpler approach then ng-repeat

angular.module('app',[]).controller('testCtrl',function($scope){
$scope.filterSearch = 'true';

$scope.filterSearchOptions = [{
        value: '',
        DisplayName: 'All',
    }, {
        value: 'false',
        DisplayName: 'Included in Search',
    }, {
        value: 'true',
        DisplayName: 'Excluded from Search',
    }];
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="testCtrl">
<select
  class="form-control form-control-sm"
  ng-model="filterSearch"
  ng-change="setFilterS()"
  id="theFilterS"
  ng-options="option.value as option.DisplayName for option in filterSearchOptions">
</select>

{{filterSearch}}

</div></code>```

Body:
I have a filter drop down for some tabular data that reads data from a local storage item, the select tag is shown below, and below that is the code to add items to the select tag and the model for the filter.

The issue is that whilst the data filtered is correct when you refresh the page, the selected item only shows the correct value if the local storage value is true.

No matter what value the local storage item is selected="selected" is always added to the "Excluded from Search" option.

Can't for the life of me work out why, any help advice appreciated.

<select class="form-control form-control-sm" ng-model="filterSearch" ng-change="setFilterS()" id="theFilterS" >
    <option ng-selected="{{option.value == filterSearch}}" ng-repeat="option in filterSearchOptions" value="{{option.value}}" >{{option.DisplayName}}</option>
</select>

$scope.filterSearch = localStorage.getItem("FilterSearch");

$scope.filterSearchOptions = [{
        value: '',
        DisplayName: 'All',
    }, {
        value: 'false',
        DisplayName: 'Included in Search',
    }, {
        value: 'true',
        DisplayName: 'Excluded from Search',
    }];

Body:
You should try with the ng-options directive which IMO gives a simpler approach then ng-repeat

angular.module('app',[]).controller('testCtrl',function($scope){
$scope.filterSearch = 'true';

$scope.filterSearchOptions = [{
        value: '',
        DisplayName: 'All',
    }, {
        value: 'false',
        DisplayName: 'Included in Search',
    }, {
        value: 'true',
        DisplayName: 'Excluded from Search',
    }];
    });

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="testCtrl">
<select
  class="form-control form-control-sm"
  ng-model="filterSearch"
  ng-change="setFilterS()"
  id="theFilterS"
  ng-options="option.value as option.DisplayName for option in filterSearchOptions">
</select>

{{filterSearch}}

</div>


问:
About Golang pointer,Why is that?
What happened ?

```<code>var n interface{} = 2
var pn = &n
var pf = (*int64)(unsafe.Pointer(pn))
fmt.Println(pf)
fmt.Println(pn)
fmt.Println(*pn) // 2
fmt.Println(*pf) // not 2
*pf = 9
fmt.Println(*pn) //error invalid memory address or nil pointer dereference
fmt.Println(*pf) // 9
</code>```

My question is Why is *pf not equal to *pn and error ?

Thanks for your reply.

答:
n is of an interface{} type, so in memory it is represented by a struct of 2 values: a type and data. The type comes first. So you dereference it and interpret as a number.

*pf = 9 breaks that structure, so next time you try to dereference it - the runtime fails.

Title: About Golang pointer,Why is that?

Body:
What happened ?

var n interface{} = 2
var pn = &n
var pf = (*int64)(unsafe.Pointer(pn))
fmt.Println(pf)
fmt.Println(pn)
fmt.Println(*pn) // 2
fmt.Println(*pf) // not 2
*pf = 9
fmt.Println(*pn) //error invalid memory address or nil pointer dereference
fmt.Println(*pf) // 9

My question is Why is *pf not equal to *pn and error ?

Thanks for your reply.


问:
How to access data from one view to another view?
I have an UITabBarController with two tabs:

UINavigationController

OptionsViewController : UIViewController

How can I reach data (ie. UILabel.text) set in OptionsViewController, in a new added modal View which has been invoked from UINavigationController?

Edit1:

Scenario: After launching app I select the second tab bar called "Options" where I fill up a textField. The label is set to value from textField. Next I select first tab bar called "Main" where I have a button. I click the button and new modal View appears. In this new modal View I'd like to show the value from textField

答:
I have an easy way to access data between views. Let's try. You have two views named view1 and view2, you can define a View *vc1 property in view2.h, set the vc1 point to view1, when pop the view2, like this:

view1.m

```
//here pop out view1 code
    View2 *view2 = [[View2 alloc] initWithNibName:@"View2" bundle:[NSBundle mainBundle]];
    [self.navigationController pushViewController:view2 animated:YES];
    view2.vc1 = self;  //transfer view1 instance to view2，use vc1 you may handle view1 in view2 directly
        [view2 release];
```

view2.h

```
    #import "view1.h"
    @property (nonatomic, retain) IBOutlet View1 *vc1; //here you could name it as view1 as well :)
```

view2.m

```
    vc1.lblTable.text = @"ok"; //you'll see "ok" in view1
    [self.navigationController popViewControllerAnimated:YES]; //navigate to view1
```

//dont forget release vc1

Body:
I have an easy way to access data between views. Let's try. You have two views named view1 and view2, you can define a View *vc1 property in view2.h, set the vc1 point to view1, when pop the view2, like this:

view1.m

//here pop out view1 code
    View2 *view2 = [[View2 alloc] initWithNibName:@"View2" bundle:[NSBundle mainBundle]];
    [self.navigationController pushViewController:view2 animated:YES];
    view2.vc1 = self;  //transfer view1 instance to view2，use vc1 you may handle view1 in view2 directly
        [view2 release];

view2.h

    #import "view1.h"
    @property (nonatomic, retain) IBOutlet View1 *vc1; //here you could name it as view1 as well :)

view2.m

    vc1.lblTable.text = @"ok"; //you'll see "ok" in view1
    [self.navigationController popViewControllerAnimated:YES]; //navigate to view1

//dont forget release vc1


答:
An interface value contains information about the type of the data it contains and then the actual value (or a pointer to the value). When you cast a pointer to the interface to *int64, the *int64 will point into some random data in the interface value (which today happens to be a pointer to the information about the type, but this is allowed to change, this part of the language is not covered by the compatibility guarantee). When you then overwrite that data, things break, unsafe is called unsafe for a reason.

*pf is not equal to *pn because they have different types even though they might contain the same bit pattern.

Title: About Golang pointer,Why is that?


问:
Grep but very literal
This question might have been asked a million times before, but did’t see my exaxt case.

Suppose a text file contains:

```<code>a
ab
bac
</code>```

Now I want to grep on ‘a’ and have a hit only on the 1st line. After the ‘a’ there’s always a [tab] character.

Anyone any ideas?

Thanks!

Ronald

答:
Try this:

```<code>head -1 *.txt | grep -P "a\t"
</code>```

head will give you specified amount of lines of each file (all txt files in my example) ,  grep -P use the regular expressions as defined by perl (perl has \t as tab)

Title: Grep but very literal

Body:
This question might have been asked a million times before, but did’t see my exaxt case.

Suppose a text file contains:

a
ab
bac

Now I want to grep on ‘a’ and have a hit only on the 1st line. After the ‘a’ there’s always a [tab] character.

Anyone any ideas?

Thanks!

Ronald

Body:
Try this:

head -1 *.txt | grep -P "a\t"

head will give you specified amount of lines of each file (all txt files in my example) ,  grep -P use the regular expressions as defined by perl (perl has \t as tab)


问:
what type of printer to print QR code and how to print qr code with php?
I am creating qrcode generator with php. the application is ready and able to create qr code image successfully. I am planning to buy barcode printer but I am not sure if all barcode printer can print qr code. I have questions regarding this issues.

is there any specific printer to print qr code or any type of barcode printer can print qr code?

do i need to use "printer own programming language" to print qr code? ( i read this blog, she says she need to use "printer own programming language" to print barcode.

答:
If you plan to use a "Barcode Printer" you don't need to build your own barcode image. You can simply send the printer commands to print the type of barcode you want, QRcode or others, and send the data. The printer is taking care of the formatting.

As an example, Zebra Technologies' barcode printers use ZPL (Zebra Printing Language) and you can use the ^BQ command to print a QRcode.

The most critical piece is how you handle the drivers and the connection between the browser and the printer.

Having the printer attached to the PC and controlled by a printer driver may not be the best solution, depending how many time you need to replicate the setup.

You may want to investigate solutions like:

Browser Print: you've a JavaScript API to talk with the printer directly.

Cloud Connect: the printer is connected directly to the server with a secure communication and is the server sending commands to the printer.

Disclaimer: I work for Zebra Technologies, similar solutions may exist for other printers brand, but I'm not familiar with them.


问:
div into a js button
I have a
 that I have formatted very carefully to look nice, and I need to make it have the functionality of a button. How would I go about doing this?

答:
First recommendation is to use a <button> instead. You can style that however you want as well. If that is not an option for some reason, you'll have to do a few different things to create a proper button out of a div element (to ensure that it works with keyboard and screen readers).

Add click handler. Eg btn.addEventListener('click', clickHandler);

Add enter key handler. Eg btn.addEventListener('keyup', keyHandler);

Add button role. role="button"

Add it to tab order: tabindex="0"

var buttons = document.querySelectorAll('.btn');

buttons.forEach(function (btn) {
  btn.addEventListener('click', function(e) {
    console.log('clicked');
  });

  btn.addEventListener('keyup', function(e) {
    if (e.key === 'Enter') {
      console.log('keyup');
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.btn {
  display: inline-block;
  background: #eee;
  border: 1px solid #aaa;
  padding: 6px;
  cursor: pointer;
}</code>```

My Button

My Button

My Button
```

Title: div into a js button

Body:
First recommendation is to use a <button> instead. You can style that however you want as well. If that is not an option for some reason, you'll have to do a few different things to create a proper button out of a div element (to ensure that it works with keyboard and screen readers).

Add click handler. Eg btn.addEventListener('click', clickHandler);

Add enter key handler. Eg btn.addEventListener('keyup', keyHandler);

Add button role. role="button"

Add it to tab order: tabindex="0"

var buttons = document.querySelectorAll('.btn');

buttons.forEach(function (btn) {
  btn.addEventListener('click', function(e) {
    console.log('clicked');
  });

  btn.addEventListener('keyup', function(e) {
    if (e.key === 'Enter') {
      console.log('keyup');
    }
  });
});

.btn {
  display: inline-block;
  background: #eee;
  border: 1px solid #aaa;
  padding: 6px;
  cursor: pointer;
}

<div class="btn" role="button" tabindex="0">My Button</div>

<div class="btn" role="button" tabindex="0">My Button</div>

<div class="btn" role="button" tabindex="0">My Button</div>


问:
How can i prevent duplicate Record in Array
I need to prevent inserting duplicate Rec in $scope.EmployeeList Array   For that i wrote if ($scope.EmployeeList.indexOf(EmpDetails) == -1)  but its not filtering my rec

```<code> $scope.EmployeeList = [];
        var amtArray = [];
        $scope.G_Total = "Total Amount is";
        $scope.SaveDb = function (Isvalid) {
            var EmpDetails = {
                'EmpName': $scope.EmpName,
                'Email': $scope.Email,
                'Cost': $scope.cost

            }
            if ($scope.EmployeeList.indexOf(EmpDetails) == -1) {
                $scope.EmployeeList.push(EmpDetails);
                console.log($scope.EmployeeList);
            }
            else
                alert('Duplicate Value....');
</code>```

答:
You can also use Array.prototype.some to find duplicate value.The some() method tests whether at least one element in the array passes the test implemented by the provided function.

```<code>var empDetails = {name: 'abc', email: 'a@gmail.com'};

let duplicate = $scope.EmployeeList.some(function (emp) {
  return emp.name === empDetails.name && emp.email === empDetails.email;
});

if (!duplicate) {
   $scope.EmployeeList.push(EmpDetails);
}
else
   alert('Duplicate Value....');
</code>```

Body:
I need to prevent inserting duplicate Rec in $scope.EmployeeList Array   For that i wrote if ($scope.EmployeeList.indexOf(EmpDetails) == -1)  but its not filtering my rec

 $scope.EmployeeList = [];
        var amtArray = [];
        $scope.G_Total = "Total Amount is";
        $scope.SaveDb = function (Isvalid) {
            var EmpDetails = {
                'EmpName': $scope.EmpName,
                'Email': $scope.Email,
                'Cost': $scope.cost

            }
            if ($scope.EmployeeList.indexOf(EmpDetails) == -1) {
                $scope.EmployeeList.push(EmpDetails);
                console.log($scope.EmployeeList);
            }
            else
                alert('Duplicate Value....');

Body:
You can also use Array.prototype.some to find duplicate value.The some() method tests whether at least one element in the array passes the test implemented by the provided function.

var empDetails = {name: 'abc', email: 'a@gmail.com'};

let duplicate = $scope.EmployeeList.some(function (emp) {
  return emp.name === empDetails.name && emp.email === empDetails.email;
});

if (!duplicate) {
   $scope.EmployeeList.push(EmpDetails);
}
else
   alert('Duplicate Value....');


问:
Parsing HTML with regular expression
I have a HTML file with this text:

```
...
...
...weeks*<br><br><i>If Yes
, please complete the MYD88 L265P Blood form.<br><br>Optional if the Follow-Up v
isit date is on or after 9/13/2017 (Amendment #8)<br></i>*Offer1
...
...
```

I want to remove everything that is between
 and .

I am trying this but it's not working as the search needs to be performed in multiple lines

```<code>powershell -Command "(gc myFile.XLS) -replace '<br&gt.*</i>', '' | Out-File myFile1.XLS"
</code>```

答:
How about this? This matches content in multiple lines in between 'i' tags. </p>

```<code>[Regex]::Replace($(Get-Content .\myFile.XLS),'<br>.*<br>|<i>(?:.*\r?\n?)*<\/i>','') > myFile.XLS
</code>```

Title: Parsing HTML with regular expression

Body:
I have a HTML file with this text:

...
...
...weeks*

If Yes
, please complete the MYD88 L265P Blood form.

Optional if the Follow-Up v
isit date is on or after 9/13/2017 (Amendment #8)
*Offer1
...
...

I want to remove everything that is between
 and .

I am trying this but it's not working as the search needs to be performed in multiple lines

powershell -Command "(gc myFile.XLS) -replace '<br&gt.*', '' | Out-File myFile1.XLS"

Body:
How about this? This matches content in multiple lines in between 'i' tags.

[Regex]::Replace($(Get-Content .\myFile.XLS),'<br>.*<br>|<i>(?:.*\r?\n?)*<\/i>','') > myFile.XLS


问:
SSIS Join Recordset With Table
I have an SSIS package in which I'm reading the records from a Flat File and storing them in a recordset. Is it possible to compare the values in the recordset with the values in a database table and update the table?

I'm Using SQL Server 2008 R2 and Same version of SSIS.

答:
Usualy I use Lookup-component with option Redirect rows to no match output.
And after that you can use two rowsets which named Lookup No Match Output and Lookup Match Output.

PS. I have three articles about SSIS, but they in Russian (but there is a lot of SQL-scripts and pictures).
If it's interesting you, you can look the following link - https://habrahabr.ru/post/330618/

Title: SSIS Join Recordset With Table


问:
How to Selectively choose rows in a key in map reduce
I have the following csv files with 5 columns and many rows. But I'm showing only first 6 rows.

```<code>Date,Food,Vitamin,Protein,NumStudents
01/01/17, Pasta, A, Yes, 560
01/01/17, Pizza, A, Yes, 730
01/01/17, Burrito, C, Yes, 240
02/01/17, Pizza, A, Yes, 340
02/01/17, Pasta, B, Yes, 450
02/01/17, Beef, B, Yes, 450
</code>```

Now I want to find the sum of NumStudents on a particular day who had only Pizza and Pasta.

In essence for 01/01/17 I only have to sum NumStudents for Pizza and Pasta but not Burrito.

Expected Output

```<code>01/01/17 1290
02/01/17 790
</code>```

Output I'm getting

```<code>01/01/17 1530
02/01/17 1240
</code>```

In my code I'm able to sum NumStudents for all 3 types of food but don't know how to selectively exclude some type of food from my composite key in mapper. Any idea how should I go about it?

Below is my code

```<code>public class GroupMR {

    public static class GroupMapper extends Mapper<LongWritable, Text, DateYear, IntWritable> {

        public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {

            String line = value.toString();
            String[] keyvalue = line.split(",");
            monyeartext.set(new Text(keyvalue[0]));

            //populat.set(Integer.parseInt(keyvalue[5]));
            termText.set(keyvalue[1]);
            try {
                numpass.set(Integer.parseInt(keyvalue[4]));
            }catch (NumberFormatException e){
                System.out.println("not a number");
            }
            DateYear monyear = new DateYear(monyeartext, termText);
            context.write(monyear, numpass);

        }
    }
</code>```

答:
I have reduced the code ,I have picked only month and date  and it is sorted based on year.

```<code>public class GroupMR {

public static class GroupMapper extends Mapper<LongWritable, Text, Text, Text> {

    Text numpass = null;
    Text monyeartext = null;

    public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        String line = value.toString();
        String[] keyvalue = line.split(",");
        String[] monyeartext1 = keyvalue[0].split("/");
        monyeartext = new Text(monyeartext1[2] + "/" +monyeartext1[0] );
        numpass = new Text(keyvalue[1] + "-" + keyvalue[4]);
        context.write(monyeartext, numpass);

    }
}

public static class GroupReducer extends Reducer<Text, Text, Text, IntWritable> {
    public void reduce(Text key, Iterable<Text> values, Context context)
            throws IOException, InterruptedException {
        boolean doesExist = false;
        int sum = 0;
        for (Text val : values) {
            String[] val2 = val.toString().split("-");
            if (val2[0].equals("Pizza") || val2[0].equals("Pasta") ){
                sum += Integer.parseInt(val2[1]);
            }
        }
        context.write(key, new IntWritable(sum));
    }
}

public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
    Configuration conf = new Configuration();
    String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
    if (otherArgs.length < 2) {
        System.err.println("Usage: wordcount <in> [<in>...] <out>");
        System.exit(2);
    }
    Job job = Job.getInstance(conf, "GroupMR");
    job.setJarByClass(GroupMR.class);
    job.setMapperClass(GroupMapper.class);

    job.setReducerClass(GroupReducer.class);
    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(Text.class);

    //for (int i = 0; i < otherArgs.length - 1; ++i) {
        FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
   // }

    FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
    System.exit(job.waitForCompletion(true) ? 0 : 1);
}
</code>```

}

Body:
I have the following csv files with 5 columns and many rows. But I'm showing only first 6 rows.

Date,Food,Vitamin,Protein,NumStudents
01/01/17, Pasta, A, Yes, 560
01/01/17, Pizza, A, Yes, 730
01/01/17, Burrito, C, Yes, 240
02/01/17, Pizza, A, Yes, 340
02/01/17, Pasta, B, Yes, 450
02/01/17, Beef, B, Yes, 450

Now I want to find the sum of NumStudents on a particular day who had only Pizza and Pasta.

In essence for 01/01/17 I only have to sum NumStudents for Pizza and Pasta but not Burrito.

Expected Output

01/01/17 1290
02/01/17 790

Output I'm getting

01/01/17 1530
02/01/17 1240

In my code I'm able to sum NumStudents for all 3 types of food but don't know how to selectively exclude some type of food from my composite key in mapper. Any idea how should I go about it?

Below is my code

public class GroupMR {

    public static class GroupMapper extends Mapper<LongWritable, Text, DateYear, IntWritable> {

        public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {

            String line = value.toString();
            String[] keyvalue = line.split(",");
            monyeartext.set(new Text(keyvalue[0]));

            //populat.set(Integer.parseInt(keyvalue[5]));
            termText.set(keyvalue[1]);
            try {
                numpass.set(Integer.parseInt(keyvalue[4]));
            }catch (NumberFormatException e){
                System.out.println("not a number");
            }
            DateYear monyear = new DateYear(monyeartext, termText);
            context.write(monyear, numpass);

        }
    }

Body:
I have reduced the code ,I have picked only month and date  and it is sorted based on year.

public class GroupMR {

public static class GroupMapper extends Mapper<LongWritable, Text, Text, Text> {

    Text numpass = null;
    Text monyeartext = null;

    public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        String line = value.toString();
        String[] keyvalue = line.split(",");
        String[] monyeartext1 = keyvalue[0].split("/");
        monyeartext = new Text(monyeartext1[2] + "/" +monyeartext1[0] );
        numpass = new Text(keyvalue[1] + "-" + keyvalue[4]);
        context.write(monyeartext, numpass);

    }
}

public static class GroupReducer extends Reducer<Text, Text, Text, IntWritable> {
    public void reduce(Text key, Iterable<Text> values, Context context)
            throws IOException, InterruptedException {
        boolean doesExist = false;
        int sum = 0;
        for (Text val : values) {
            String[] val2 = val.toString().split("-");
            if (val2[0].equals("Pizza") || val2[0].equals("Pasta") ){
                sum += Integer.parseInt(val2[1]);
            }
        }
        context.write(key, new IntWritable(sum));
    }
}

public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
    Configuration conf = new Configuration();
    String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
    if (otherArgs.length < 2) {
        System.err.println("Usage: wordcount <in> [<in>...] <out>");
        System.exit(2);
    }
    Job job = Job.getInstance(conf, "GroupMR");
    job.setJarByClass(GroupMR.class);
    job.setMapperClass(GroupMapper.class);

    job.setReducerClass(GroupReducer.class);
    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(Text.class);

    //for (int i = 0; i < otherArgs.length - 1; ++i) {
        FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
   // }

    FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
    System.exit(job.waitForCompletion(true) ? 0 : 1);
}

}


问:
How to Store Images from URL in Array
i want to store Images in array from URL but i don't know how to implement this functionality.

just like i stored images from drawable in array i want to store images in array from URL.

example of drawable:

```<code>public Integer[] mThumbIds = {
            R.drawable.pic_1, R.drawable.pic_2,
            R.drawable.pic_3, R.drawable.pic_4,
            R.drawable.pic_5, R.drawable.pic_6,
            R.drawable.pic_7, R.drawable.pic_8,
            R.drawable.pic_9, R.drawable.pic_10,
            R.drawable.pic_11, R.drawable.pic_12,
            R.drawable.pic_13, R.drawable.pic_14,
            R.drawable.pic_15
    };
</code>```

i tried this but it didn't work:

```<code>public Integer[] mThumbIds = {
            R.string.http_icons_iconarchive_com_icons_martz90_circle_512_android_icon_png

    };
</code>```

答:
simply first download Lib from http://square.github.io/picasso/

then Picasso.with(context).load("your url of img").into(imageView);

Title: How to Store Images from URL in Array

Body:
i want to store Images in array from URL but i don't know how to implement this functionality.

just like i stored images from drawable in array i want to store images in array from URL.

example of drawable:

public Integer[] mThumbIds = {
            R.drawable.pic_1, R.drawable.pic_2,
            R.drawable.pic_3, R.drawable.pic_4,
            R.drawable.pic_5, R.drawable.pic_6,
            R.drawable.pic_7, R.drawable.pic_8,
            R.drawable.pic_9, R.drawable.pic_10,
            R.drawable.pic_11, R.drawable.pic_12,
            R.drawable.pic_13, R.drawable.pic_14,
            R.drawable.pic_15
    };

i tried this but it didn't work:

public Integer[] mThumbIds = {
            R.string.http_icons_iconarchive_com_icons_martz90_circle_512_android_icon_png

    };


问:
ASP.NET Core Web API HTTP POST returns 404 in Azure
I have this (simplified) ASP.NET Core Web API controller. Both the GET and POST actions works nicely on my own machine. However, deployed to Azure only the GET action works properly. The POST action results in a 404. Any ideas?

```<code>namespace Foo
{
  using System;
  using System.Collections.Generic;
  using Microsoft.AspNetCore.Mvc;

  [RequireHttps]
  [Produces("application/json")]
  [Area("Foo")]
  [Route("[area]/Api/[controller]")]
  public class BarController : Controller
  {
    [HttpGet]
    public IEnumerable<string> Get()
    {
      return new[] {"Hello", "World!"};
    }

    [HttpPost]
    public void Post([FromBody] InputModel model)
    {
    }

    public class InputModel
    {
      public int Foo { get; set; }
    }
  }
}
</code>```

It is an ASP.NET Core MVC application targeting the full .NET framework. It is deployed as an Azure Web App. I have tested both actions on my local machine and in Azure using Postman.

答:
It seems under certain circumstances when an error occurs in a controller, ASP.NET core returns 404 instead of a more appropriate 500. Check out this post:

ASP.NET Core 2.0 site POST request resulting in 404 on Azure

In the answer, it was caused by wrong database connection string (which may be a case when you publish an application to another environment), but it may be something else.

Not sure why it does not throw a normal error, maybe it tries to redirect to a custom error page or something like that.

To check this suggestion, try to remove everything from your POST controller to isolate a problem. If it won't return 404, it means that something in the controller throws an exception.

Body:
I have this (simplified) ASP.NET Core Web API controller. Both the GET and POST actions works nicely on my own machine. However, deployed to Azure only the GET action works properly. The POST action results in a 404. Any ideas?

namespace Foo
{
  using System;
  using System.Collections.Generic;
  using Microsoft.AspNetCore.Mvc;

  [RequireHttps]
  [Produces("application/json")]
  [Area("Foo")]
  [Route("[area]/Api/[controller]")]
  public class BarController : Controller
  {
    [HttpGet]
    public IEnumerable<string> Get()
    {
      return new[] {"Hello", "World!"};
    }

    [HttpPost]
    public void Post([FromBody] InputModel model)
    {
    }

    public class InputModel
    {
      public int Foo { get; set; }
    }
  }
}

It is an ASP.NET Core MVC application targeting the full .NET framework. It is deployed as an Azure Web App. I have tested both actions on my local machine and in Azure using Postman.


问:
Check if Java bytecode contains debug symbols
I would like to know how can I check if a compiled Java class contains debug symbols. The problem is that I compile an application from ant with debug="on", but a specific JVM throws an exception: it says that the debug symbols are missing.

Thanks.

答: The most important thing a class file with debug information will contain is the LineNumberTable which maps bytecode instructions to source line numbers and the LocalVariableTable which tells the debugger where your local variables, including arguments to a method reside inside the VM during execution.</p>


问:
Values from from select form field not updating in laravel
I have a form that with select items from another table. The items list just fine in form view. The problem I am encountering is that the other fields in the form updates just fine except the drop-down lists.

I have checked and confirmed that the fields are all include in the $fillable array in the model.

When i dd($myinputVariable), its showing values of all form inputs.

This my form.

```<code>{!! Form::model($member,  [
    'method' => 'PATCH','id'=>'member-regform',
    'route' => ['members.update', $member->member_registration_number]
]) !!}
<div class="form-group">
{!! Form::label('constituency_id','Constituency') !!}
{!! Form::select('constituency_id',$constituencies,
array('require','class'=>'form-control'))!!}
</div>
<div class="form-group">
{!! Form::label('ward_id','Ward') !!}
{!! Form::select('ward_id',$wards,
array('require','class'=>'form-control'))!!}
</div>
<div class="form-group pull-right">
    {!! Form::submit('Save Changes',
      array('class'=>'btn btn-primary')) !!}
</div>
{!! Form::close() !!}
</div>
</code>```

My controller

```<code>public function __construct()
    {

    $this->constituencies = Constituency::where('county_id',8)->pluck('const_name','id');
    $this->wards = Ward::pluck('ward','id');

      }

public function update(Request $request, $id)
    {
        //
        $member = Member::where('member_registration_number',$id)->first();

          $input = $request->all();

         $member->fill($input)->save();

            Session::flash('message', 'Member successfully updated!');

    return redirect()->back();
    }
</code>```

My Model

```<code>protected $fillable = array('constituency_id','ward_id');
</code>```

After selecting a different ward_id or constituency_id, the value does not change from the older one after update. This issue has troubled my head for hours. Kindly help.

答:
The 3rd element should be the selected value and the options the 4th:

```<code>{!! Form::select('ward_id', $wards, null, ['require', 'class' => 'form-control']) !!}
</code>```

LaravalCollective drop downs

Body:
I have a form that with select items from another table. The items list just fine in form view. The problem I am encountering is that the other fields in the form updates just fine except the drop-down lists.

I have checked and confirmed that the fields are all include in the $fillable array in the model.

When i dd($myinputVariable), its showing values of all form inputs.

This my form.

{!! Form::model($member,  [
    'method' => 'PATCH','id'=>'member-regform',
    'route' => ['members.update', $member->member_registration_number]
]) !!}

{!! Form::label('constituency_id','Constituency') !!}
{!! Form::select('constituency_id',$constituencies,
array('require','class'=>'form-control'))!!}

{!! Form::label('ward_id','Ward') !!}
{!! Form::select('ward_id',$wards,
array('require','class'=>'form-control'))!!}

    {!! Form::submit('Save Changes',
      array('class'=>'btn btn-primary')) !!}

{!! Form::close() !!}

My controller

public function __construct()
    {

    $this->constituencies = Constituency::where('county_id',8)->pluck('const_name','id');
    $this->wards = Ward::pluck('ward','id');

      }

public function update(Request $request, $id)
    {
        //
        $member = Member::where('member_registration_number',$id)->first();

          $input = $request->all();

         $member->fill($input)->save();

            Session::flash('message', 'Member successfully updated!');

    return redirect()->back();
    }

My Model

protected $fillable = array('constituency_id','ward_id');

After selecting a different ward_id or constituency_id, the value does not change from the older one after update. This issue has troubled my head for hours. Kindly help.

Body:
The 3rd element should be the selected value and the options the 4th:

{!! Form::select('ward_id', $wards, null, ['require', 'class' => 'form-control']) !!}

LaravalCollective drop downs


问:
How can I put a link on the right side?
Here is my code:

a{
    display: block;
    border: 3px solid #ffcb08;
    border-radius: 100px;
    text-align: center;
    color: #222;
    text-decoration: none;
    font-weight: 300;
    font-size: 20px;
    padding: 10px;
    box-sizing: border-box;
    margin-top: 15px;
    transition: all .3s;
    -webkit-transition: all .3s;
    -moz-transition: all .3s;
    width: 160px;
    float: right;
}

p{
    border: 1px solid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>
some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here.
Download
</p></code>```

All I'm trying to do is putting that button on the right side without setting position: absolute; to it. How can I do that?

答:
Add float: right to it.

a{
    display: block;
    float: right;
    border: 3px solid #ffcb08;
    border-radius: 100px;
    text-align: center;
    color: #222;
    text-decoration: none;
    font-weight: 300;
    font-size: 20px;
    padding: 10px;
    box-sizing: border-box;
    margin-top: 15px;
    transition: all .3s;
    -webkit-transition: all .3s;
    -moz-transition: all .3s;
    width: 160px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here.
Download</code>```

Title: How can I put a link on the right side?

Body:
Here is my code:

a{
    display: block;
    border: 3px solid #ffcb08;
    border-radius: 100px;
    text-align: center;
    color: #222;
    text-decoration: none;
    font-weight: 300;
    font-size: 20px;
    padding: 10px;
    box-sizing: border-box;
    margin-top: 15px;
    transition: all .3s;
    -webkit-transition: all .3s;
    -moz-transition: all .3s;
    width: 160px;
    float: right;
}

p{
    border: 1px solid;
}

some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here.
Download

All I'm trying to do is putting that button on the right side without setting position: absolute; to it. How can I do that?

Body:
Add float: right to it.

a{
    display: block;
    float: right;
    border: 3px solid #ffcb08;
    border-radius: 100px;
    text-align: center;
    color: #222;
    text-decoration: none;
    font-weight: 300;
    font-size: 20px;
    padding: 10px;
    box-sizing: border-box;
    margin-top: 15px;
    transition: all .3s;
    -webkit-transition: all .3s;
    -moz-transition: all .3s;
    width: 160px;
}

some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here.
<a href="#">Download</a>


问:
Accessing an iframe with nightwatch without a fixed id
I have

```<code><div class="ap-content" id="office-addon">
  <div class="ap-iframe-container iframe-init" id="office-addon__5e83ed1">
    <iframe id="office-addon__5e83ed1">
      <!-- As it appears in the dev console: -->
      #document
      <!DOCTYPE html>
        <html>
          <head></head>
          <body>
            <div id="addon"></div>
          </body>
        </html>
    </iframe>
  <div>
<div>
</code>```

I want to access it with nightwatch like so:

```<code>browser
  .waitForElementPresent('#office-addon', 20000);
  .frame('#office-addon iframe')
  .waitForElementPresent('#addon', 1000)
  .end();
</code>```

But it times out waiting for #addon, though #addon is in the browser. How do I have to write the frame() parameters? The iframe id changes with every page build.

答:
The solution was like following:

```<code>browser.getAttribute('#office-addon iframe', 'id', id => {
  browser
    .frame(id.value)

    ...
});
</code>```

It didn't work directly.

Body:
I have

      #document
      <!DOCTYPE html>

I want to access it with nightwatch like so:

browser
  .waitForElementPresent('#office-addon', 20000);
  .frame('#office-addon iframe')
  .waitForElementPresent('#addon', 1000)
  .end();

But it times out waiting for #addon, though #addon is in the browser. How do I have to write the frame() parameters? The iframe id changes with every page build.

Body:
The solution was like following:

browser.getAttribute('#office-addon iframe', 'id', id => {
  browser
    .frame(id.value)

    ...
});

It didn't work directly.


问:
Why undefined can be covered by with while null can't?
Why can undefined be covered by with while null can't?  And also, let can be covered while var can't (it will throw a error).

So what is the rule that a variable can be redefined?

var obj = {null:1,undefined:2};
with(obj) console.log(null,undefined);```

答:
Because undefined is a predefined global identifier, but null is a literal. Because var is a keyword, but let isn't (in loose mode; it is in strict mode). (In loose mode, it acts like a keyword or identifier depending on where it appears.)

I don't recall why undefined is a predefined global rather than being a keyword. The reason let is only a keyword in strict mode is that it was only added in 2015, 20 years after the language was first defined.


问:
AngularDart Components Dropdown Selects selectionChange event
I'm using material-dropdown-select component, but I didn't find the way to trigger the event when the user changes the  selection.

(on selection change ??)

```<code><material-dropdown-select class="psDropDown" dir="rtl"
                    [buttonText]="dropDownSelectLabel"
                    [selection]="singleSelectModel"
                    [options]="lookUpOptions"
                    ></material-dropdown-select>
</code>```

How can I react to a selection change event

答:
Based on the answer from Günter I wrote this code and it works!</p>

```<code>singleSelectModel.selectionChanges.listen((e)=>onChange());
</code>```

Body:
I'm using material-dropdown-select component, but I didn't find the way to trigger the event when the user changes the  selection.

(on selection change ??)

<material-dropdown-select class="psDropDown" dir="rtl"
                    [buttonText]="dropDownSelectLabel"
                    [selection]="singleSelectModel"
                    [options]="lookUpOptions"
                    ></material-dropdown-select>

How can I react to a selection change event

Body:
Based on the answer from Günter I wrote this code and it works!

singleSelectModel.selectionChanges.listen((e)=>onChange());


问:
How to reduce boilerplate nested Result in Rust
I have code using a nested Result like this:

```<code>fn ip4(s: &str) -> Result<(u8, u8, u8, u8), num::ParseIntError> {
    let t: Vec<_> = s.split('.').collect();
    match t[0].parse::<u8>() {
        Ok(a1) => {
            match t[1].parse::<u8>() {
                Ok(a2) => {
                    match t[2].parse::<u8>() {
                        Ok(a3) => {
                            match t[3].parse::<u8>() {
                                Ok(a4) => {
                                    Ok((a1, a2, a3, a4))
                                }
                                Err(er) => Err(er)
                            }
                        },
                        Err(er) => Err(er)
                    }
                }
                Err(er) => Err(er)
            }
        }
        Err(er) => Err(er),
    }
}
</code>```

Is there any function or composing way to reduce this? Something like Haskell or Scala programmers do:

```<code>fn ip4(s: &str) -> Result<(u8, u8, u8, u8), num::ParseIntError> {
  let t: Vec<_> = s.split('.').collect();
  Result
  .lift((,,,))
  .ap(() -> t[0].parse::<u8>())
  .ap(() -> t[1].parse::<u8>())
  .ap(() -> t[2].parse::<u8>())
  .ap(() -> t[3].parse::<u8>()) // maybe more concise in Haskell or Scala but I think it's enough :)
}
</code>```

答:
The answer to your direct question is the questionmark operator which would allow you to replace your whole match block with

```<code>Ok((
    t[0].parse::<u8>()?,
    t[1].parse::<u8>()?,
    t[2].parse::<u8>()?,
    t[3].parse::<u8>()?,
))
</code>```

where essentially ? will return the error immediately if one is encountered.

That said, Rust already provides APIs for parsing IP addresses. Even if you wanted to maintain your tuple approach (though why would you), you could implement your function as

```<code>fn ip4(s: &str) -> Result<(u8, u8, u8, u8), net::AddrParseError> {
    let addr: net::Ipv4Addr = s.parse()?;
    let octets = addr.octets();
    Ok((octets[0], octets[1], octets[2], octets[3]))
}
</code>```

or just pass around the Ipv4Addr value directly.

Body:
I have code using a nested Result like this:

fn ip4(s: &str) -> Result<(u8, u8, u8, u8), num::ParseIntError> {
    let t: Vec<_> = s.split('.').collect();
    match t[0].parse::<u8>() {
        Ok(a1) => {
            match t[1].parse::<u8>() {
                Ok(a2) => {
                    match t[2].parse::<u8>() {
                        Ok(a3) => {
                            match t[3].parse::<u8>() {
                                Ok(a4) => {
                                    Ok((a1, a2, a3, a4))
                                }
                                Err(er) => Err(er)
                            }
                        },
                        Err(er) => Err(er)
                    }
                }
                Err(er) => Err(er)
            }
        }
        Err(er) => Err(er),
    }
}

Is there any function or composing way to reduce this? Something like Haskell or Scala programmers do:

fn ip4(s: &str) -> Result<(u8, u8, u8, u8), num::ParseIntError> {
  let t: Vec<_> = s.split('.').collect();
  Result
  .lift((,,,))
  .ap(() -> t[0].parse::<u8>())
  .ap(() -> t[1].parse::<u8>())
  .ap(() -> t[2].parse::<u8>())
  .ap(() -> t[3].parse::<u8>()) // maybe more concise in Haskell or Scala but I think it's enough :)
}

Body:
The answer to your direct question is the questionmark operator which would allow you to replace your whole match block with

Ok((
    t[0].parse::<u8>()?,
    t[1].parse::<u8>()?,
    t[2].parse::<u8>()?,
    t[3].parse::<u8>()?,
))

where essentially ? will return the error immediately if one is encountered.

That said, Rust already provides APIs for parsing IP addresses. Even if you wanted to maintain your tuple approach (though why would you), you could implement your function as

fn ip4(s: &str) -> Result<(u8, u8, u8, u8), net::AddrParseError> {
    let addr: net::Ipv4Addr = s.parse()?;
    let octets = addr.octets();
    Ok((octets[0], octets[1], octets[2], octets[3]))
}

or just pass around the Ipv4Addr value directly.


问:
how can I speed up my python code?
It's a program of import multiple images and extract feature using dct and histogram.
1) Import multiple images from folder

2) Make image size 256*256

3) Use image of 64*64 block unit with stride = 32

4) Do dct(8*8 size)

5) make histogram of dct

6) Extract features from dct coefficient histogram

The problem is that it's too slow.
I think it's because there's so many "for loop".

This is my full-code in python.
How can I change my code to speed up?

I am not familiar with python.
Please help me

```<code>import numpy as np
from scipy.fftpack import dct
from PIL import Image
import glob
import matplotlib.pyplot as plt

def find_index(x,key):
    for i in range(0,len(x)):
        if x[i] == key :
            return i
        else:
            i = i+1

def image_open(path):
    image_list = []
    #for filename in glob.glob('path/*.jpg'):
    for filename in glob.glob(path+'/*.jpg'):
     im=Image.open(filename)
     image_list.append(im)

    return image_list

def dct_2(img):
    #Get 2D Cosine Transform of Image
    return dct(dct(np.asarray(img).T, norm='ortho').T, norm='ortho')

def return_array(array):
    zero = [0.0, 0.0, 0.0, 0.0, 0.0]

    range = int((max(array)) - min(array))
    x, bins, patch = plt.hist(array, bins=range)
    x = list(zero) + list(x) + list(zero)
    return x

path = 'C:\\Users\\LG\\PycharmProjects\\photo' #folder that contains many images

images = image_open(path)

row = 0
array_matrix = []
label_matrix = []

for i in range(0, len(images)): #access image
 box3 = (0,0,256,256)
 a = images[i].crop(box3)

 (y,cb,cr) = a.split()  #ycbcr
 width , height = y.size
 y.show()

 for q in range(0, height-32 , 32):  #use image 64*64 block unit
  for w in range(0 , width-32 ,32):
     box1 =(q,w,q+64,w+64)
     block = y.crop(box1)
     array1 , array2 , array3 , array4 , array5 , array6 , array7 , array8 ,array9 = [],[],[],[],[],[],[],[],[]

     for j in range(0,64,8):        #dct
       for n in range(0,64,8):
         box2 = (j,n,j+8,n+8)
         temp = block.crop(box2)
         dct_temp = dct_2(temp)

         array1.append(dct_temp[0,1])
         array2.append(dct_temp[1,0])
         array3.append(dct_temp[0,2])
         array4.append(dct_temp[1,1])
         array5.append(dct_temp[2,0])
         array6.append(dct_temp[0,3])
         array7.append(dct_temp[1,2])
         array8.append(dct_temp[2,1])
         array9.append(dct_temp[3,0])

     x1 = return_array(array1)   #extract feature from dct histogram
     index = find_index(x1, max(x1))
     u = [index - 5, index + 5, 1]
     array_matrix.append(x1[u[0]:u[1] + 1:u[2]])

     x2 = return_array(array2)
     index = find_index(x2, max(x2))
     u = [index - 5, index + 5, 1]
     array_matrix[row].extend(x2[u[0]:u[1] + 1:u[2]])

     x3 = return_array(array3)
     index = find_index(x3, max(x3))
     u = [index - 5, index + 5, 1]
     array_matrix[row].extend(x3[u[0]:u[1] + 1:u[2]])

     x4 = return_array(array4)
     index = find_index(x4, max(x4))
     u = [index - 5, index + 5, 1]
     array_matrix[row].extend(x4[u[0]:u[1] + 1:u[2]])

     x5 = return_array(array5)
     index = find_index(x5, max(x5))
     u = [index - 5, index + 5, 1]
     array_matrix[row].extend(x5[u[0]:u[1] + 1:u[2]])

     x6 = return_array(array6)
     index = find_index(x6, max(x6))
     u = [index - 5, index + 5, 1]
     array_matrix[row].extend(x6[u[0]:u[1] + 1:u[2]])

     x7 = return_array(array7)
     index = find_index(x7, max(x7))
     u = [index - 5, index + 5, 1]
     array_matrix[row].extend(x7[u[0]:u[1] + 1:u[2]])

     x8 = return_array(array8)
     index = find_index(x8, max(x8))
     u = [index - 5, index + 5, 1]
     array_matrix[row].extend(x8[u[0]:u[1] + 1:u[2]])

     x9 = return_array(array9)
     index = find_index(x9, max(x9))
     u = [index - 5, index + 5, 1]
     array_matrix[row].extend(x9[u[0]:u[1] + 1:u[2]])

     print(w/32)

     row = row+1

print(array_matrix)
</code>```

答:
Rather than assuming that a specific section is taking longer than others, I'd recommend profiling your script.  A profiler will collect metrics on how long certain parts of your program takes, and also allow you to better see how much any changes affect the code (makes it better, worse, etc).

Once you know where your problem lies, then you can take a more targeted approach at making it faster.

Have a look at the profiling module: https://docs.python.org/2/library/profile.html

Also have a look at some tutorials:

https://julien.danjou.info/blog/2015/guide-to-python-profiling-cprofile-concrete-case-carbonara

https://zapier.com/engineering/profiling-python-boss/

https://marcobonzanini.com/2015/01/05/my-python-code-is-slow-tips-for-profiling/

Title: how can I speed up my python code?

Body:
It's a program of import multiple images and extract feature using dct and histogram.
1) Import multiple images from folder

2) Make image size 256*256

3) Use image of 64*64 block unit with stride = 32

4) Do dct(8*8 size)

5) make histogram of dct

6) Extract features from dct coefficient histogram

The problem is that it's too slow.
I think it's because there's so many "for loop".

This is my full-code in python.
How can I change my code to speed up?

I am not familiar with python.
Please help me

import numpy as np
from scipy.fftpack import dct
from PIL import Image
import glob
import matplotlib.pyplot as plt

def find_index(x,key):
    for i in range(0,len(x)):
        if x[i] == key :
            return i
        else:
            i = i+1

def image_open(path):
    image_list = []
    #for filename in glob.glob('path/*.jpg'):
    for filename in glob.glob(path+'/*.jpg'):
     im=Image.open(filename)
     image_list.append(im)

    return image_list

def dct_2(img):
    #Get 2D Cosine Transform of Image
    return dct(dct(np.asarray(img).T, norm='ortho').T, norm='ortho')

def return_array(array):
    zero = [0.0, 0.0, 0.0, 0.0, 0.0]

    range = int((max(array)) - min(array))
    x, bins, patch = plt.hist(array, bins=range)
    x = list(zero) + list(x) + list(zero)
    return x

path = 'C:\\Users\\LG\\PycharmProjects\\photo' #folder that contains many images

images = image_open(path)

row = 0
array_matrix = []
label_matrix = []

for i in range(0, len(images)): #access image
 box3 = (0,0,256,256)
 a = images[i].crop(box3)

 (y,cb,cr) = a.split()  #ycbcr
 width , height = y.size
 y.show()

 for q in range(0, height-32 , 32):  #use image 64*64 block unit
  for w in range(0 , width-32 ,32):
     box1 =(q,w,q+64,w+64)
     block = y.crop(box1)
     array1 , array2 , array3 , array4 , array5 , array6 , array7 , array8 ,array9 = [],[],[],[],[],[],[],[],[]

     for j in range(0,64,8):        #dct
       for n in range(0,64,8):
         box2 = (j,n,j+8,n+8)
         temp = block.crop(box2)
         dct_temp = dct_2(temp)

         array1.append(dct_temp[0,1])
         array2.append(dct_temp[1,0])
         array3.append(dct_temp[0,2])
         array4.append(dct_temp[1,1])
         array5.append(dct_temp[2,0])
         array6.append(dct_temp[0,3])
         array7.append(dct_temp[1,2])
         array8.append(dct_temp[2,1])
         array9.append(dct_temp[3,0])

     x1 = return_array(array1)   #extract feature from dct histogram
     index = find_index(x1, max(x1))
     u = [index - 5, index + 5, 1]
     array_matrix.append(x1[u[0]:u[1] + 1:u[2]])

     x2 = return_array(array2)
     index = find_index(x2, max(x2))
     u = [index - 5, index + 5, 1]
     array_matrix[row].extend(x2[u[0]:u[1] + 1:u[2]])

     x3 = return_array(array3)
     index = find_index(x3, max(x3))
     u = [index - 5, index + 5, 1]
     array_matrix[row].extend(x3[u[0]:u[1] + 1:u[2]])

     x4 = return_array(array4)
     index = find_index(x4, max(x4))
     u = [index - 5, index + 5, 1]
     array_matrix[row].extend(x4[u[0]:u[1] + 1:u[2]])

     x5 = return_array(array5)
     index = find_index(x5, max(x5))
     u = [index - 5, index + 5, 1]
     array_matrix[row].extend(x5[u[0]:u[1] + 1:u[2]])

     x6 = return_array(array6)
     index = find_index(x6, max(x6))
     u = [index - 5, index + 5, 1]
     array_matrix[row].extend(x6[u[0]:u[1] + 1:u[2]])

     x7 = return_array(array7)
     index = find_index(x7, max(x7))
     u = [index - 5, index + 5, 1]
     array_matrix[row].extend(x7[u[0]:u[1] + 1:u[2]])

     x8 = return_array(array8)
     index = find_index(x8, max(x8))
     u = [index - 5, index + 5, 1]
     array_matrix[row].extend(x8[u[0]:u[1] + 1:u[2]])

     x9 = return_array(array9)
     index = find_index(x9, max(x9))
     u = [index - 5, index + 5, 1]
     array_matrix[row].extend(x9[u[0]:u[1] + 1:u[2]])

     print(w/32)

     row = row+1

print(array_matrix)


问:
How to force a move of a type which implements the Copy trait?
A custom type by default is moved through default assignment. By implementing the Copy trait, I get "shallow copy semantics" through default assignment. I may also get "deep copy semantics" by implementing the Clone trait.

Is there a way to force a move on a Copy type?

I tried using the move keyword and a closure (let new_id = move || id;) but I get an error message. I'm not into closures yet, but, from seeing them here and there, I thought that that would have worked.

答:
At runtime, copies and moves, in Rust, have the same effect. However, at compile-time, in the case of a move, the variable which an object is moved from is marked as unusable, but not in the case of a copy.

When you're using Copy types, you always want value semantics, and object semantics when not using Copy types.

Objects, in Rust, don't have a consistent address: the addresses often change between moves because of the runtime behavior, i.e. they are owned by exactly one binding. This is very different from other languages!


问:
Check if queue exists in Solace
I'm using Java API to connect to Solace, provision queues and subscribe them to topics. In case those queues are already exists I would like to avoid doing it again. Using Java API is it possible to check if particular queue exists and which topics are mapped to that queue?</p>

答:
The best way to do this is to attempt to provision, and make use of the JCSMPSession.FLAG_IGNORE_ALREADY_EXISTS and JCSMPProperties.IGNORE_DUPLICATE_SUBSCRIPTION_ERROR properties.

Here's an quick example:

```<code>JCSMPProperties properties = new JCSMPProperties();
properties.setProperty(JCSMPProperties.HOST, "your_router_dns_name");
properties.setProperty(JCSMPProperties.USERNAME, "default");
properties.setBooleanProperty(JCSMPProperties.IGNORE_DUPLICATE_SUBSCRIPTION_ERROR, true);

JCSMPSession session =  JCSMPFactory.onlyInstance().createSession(properties);

Queue queue = JCSMPFactory.onlyInstance().createQueue("myqueue");
EndpointProperties props = new EndpointProperties(); // default properties, modify as needed
session.provision(queue, props, JCSMPSession.FLAG_IGNORE_ALREADY_EXISTS);

Topic topic = JCSMPFactory.onlyInstance().createTopic("my/topic");
session.addSubscription(queue, topic, JCSMPSession.WAIT_FOR_CONFIRM);
</code>```

Note that there's no actual method to verify if the queue and topic subscriptions exist using the API. If absolutely necessary, you can make use of SEMP over message bus to execute show commands, but this is pretty unwieldy.

Title: Check if queue exists in Solace

Body:
The best way to do this is to attempt to provision, and make use of the JCSMPSession.FLAG_IGNORE_ALREADY_EXISTS and JCSMPProperties.IGNORE_DUPLICATE_SUBSCRIPTION_ERROR properties.

Here's an quick example:

JCSMPProperties properties = new JCSMPProperties();
properties.setProperty(JCSMPProperties.HOST, "your_router_dns_name");
properties.setProperty(JCSMPProperties.USERNAME, "default");
properties.setBooleanProperty(JCSMPProperties.IGNORE_DUPLICATE_SUBSCRIPTION_ERROR, true);

JCSMPSession session =  JCSMPFactory.onlyInstance().createSession(properties);

Queue queue = JCSMPFactory.onlyInstance().createQueue("myqueue");
EndpointProperties props = new EndpointProperties(); // default properties, modify as needed
session.provision(queue, props, JCSMPSession.FLAG_IGNORE_ALREADY_EXISTS);

Topic topic = JCSMPFactory.onlyInstance().createTopic("my/topic");
session.addSubscription(queue, topic, JCSMPSession.WAIT_FOR_CONFIRM);

Note that there's no actual method to verify if the queue and topic subscriptions exist using the API. If absolutely necessary, you can make use of SEMP over message bus to execute show commands, but this is pretty unwieldy.


问:
compare strings in python with a text file
i have a text file with following data:
deric,
robert,
mathew,

Now, i want the user to input a string and then compare that string with the text file..

```<code> fo = open("d:\\ar.txt", "r")
 file_contents = fo.read()
 print('Enter your password.')
 typedPassword = input()
 for i in file_contents:
     if typedPassword == file_contents:
         print('Access granted')
     else:
         print('Access denied')
</code>```

However, this doesn't seem to work. any thoughts?

答:
Try this:-</p>

```<code>fo = open("poopy.txt", "r")
file_contents = fo.read()
print('Enter your password.')
typedPassword = input()
Flag = 0
for i in file_contents.split('\n'):
    if typedPassword == i:
        Flag = 1
if Flag == 1:
    print('Access Granted')
else:
    print('Access Denied')
</code>```

Body:
i have a text file with following data:
deric,
robert,
mathew,

Now, i want the user to input a string and then compare that string with the text file..

 fo = open("d:\\ar.txt", "r")
 file_contents = fo.read()
 print('Enter your password.')
 typedPassword = input()
 for i in file_contents:
     if typedPassword == file_contents:
         print('Access granted')
     else:
         print('Access denied')

However, this doesn't seem to work. any thoughts?

Body:
Try this:-

fo = open("poopy.txt", "r")
file_contents = fo.read()
print('Enter your password.')
typedPassword = input()
Flag = 0
for i in file_contents.split('\n'):
    if typedPassword == i:
        Flag = 1
if Flag == 1:
    print('Access Granted')
else:
    print('Access Denied')


问:
E4 contribute to a perspective
I have a perspective that is defined in a plugin.xml. Is it possible to contribute with a fragment containing a part sash and some parts to that perspective ?</p>

答:
Sounds like you are using E4 with compatibility layer: you cannot extend an E3 perspective with additional elements using E4 fragments. E3 compat layer works on top of E4, i.e. when the E4 fragments are processed, the E3 perspective is not yet available.

You could achieve this programmatically, but that (E3 and E4 mix) is not supported (at least not up to Eclipse Oxygen as of today).

Title: E4 contribute to a perspective


问:
Impact of locks on multithreading performance
I have a simple class designed to play around with threading. It has a member variable, num, which is initialized to 0, and a method called modify which increments and then decrements num a high number of times. When the program runs, it creates two threads which both run modify, and then starts a timer and starts the threads. It uses a while loop to wait for both threads to finish executing, and then stops the timer and prints the time elapsed to the console. The class:

```<code>public class Threading
{

    public static void Main()
    {
        Threading t = new Threading();
        t.demo();
    }

    private int num = 0;

    public void doThreading()
    {

        Thread t1 = new Thread(modify);
        Thread t2 = new Thread(modify);

        t1.Start();
        t2.Start();

        Stopwatch timer = new Stopwatch();
        timer.Start();

        while (thread1.IsAlive || thread2.IsAlive)
        {

        }

        timer.Stop();
        Console.WriteLine("Took: " + timer.ElapsedMilliseconds + " milliseconds");

        Console.Read();
    }

    public void modify()
    {
        for (int i = 0; i < 1000000000; i++)
        {
            count++;
            count--;
        }
    }
}
</code>```

After running the program, num will not be 0 because of race conditions. When I add locks to the modify method so that num is 0 after running the program:

```<code>public void modify()
    {
        for (int i = 0; i < 1000000000; i++)
        {
            lock (this) { count++; }
            lock (this) { count--; }
        }
    }
</code>```

Then the program takes 8 times as long to execute. I cannot figure out why it would be taking so much longer, I would expect, at most, for it to take 4 times as long to execute. Any idea why it is taking so much longer?

答:
lock can appear to be quite expensive in such a case (all you want is to lock incrementing an int, i.e. make count++ atomic); use Interlocked instead:

```<code>public void modify()
{
    for (int i = 0; i < 1000000000; i++)
    {
        Interlocked.Increment(ref count);
        Interlocked.Decrement(ref count);
    }
}
</code>```

Body:
I have a simple class designed to play around with threading. It has a member variable, num, which is initialized to 0, and a method called modify which increments and then decrements num a high number of times. When the program runs, it creates two threads which both run modify, and then starts a timer and starts the threads. It uses a while loop to wait for both threads to finish executing, and then stops the timer and prints the time elapsed to the console. The class:

public class Threading
{

    public static void Main()
    {
        Threading t = new Threading();
        t.demo();
    }

    private int num = 0;

    public void doThreading()
    {

        Thread t1 = new Thread(modify);
        Thread t2 = new Thread(modify);

        t1.Start();
        t2.Start();

        Stopwatch timer = new Stopwatch();
        timer.Start();

        while (thread1.IsAlive || thread2.IsAlive)
        {

        }

        timer.Stop();
        Console.WriteLine("Took: " + timer.ElapsedMilliseconds + " milliseconds");

        Console.Read();
    }

    public void modify()
    {
        for (int i = 0; i < 1000000000; i++)
        {
            count++;
            count--;
        }
    }
}

After running the program, num will not be 0 because of race conditions. When I add locks to the modify method so that num is 0 after running the program:

public void modify()
    {
        for (int i = 0; i < 1000000000; i++)
        {
            lock (this) { count++; }
            lock (this) { count--; }
        }
    }

Then the program takes 8 times as long to execute. I cannot figure out why it would be taking so much longer, I would expect, at most, for it to take 4 times as long to execute. Any idea why it is taking so much longer?

Body:
lock can appear to be quite expensive in such a case (all you want is to lock incrementing an int, i.e. make count++ atomic); use Interlocked instead:

public void modify()
{
    for (int i = 0; i < 1000000000; i++)
    {
        Interlocked.Increment(ref count);
        Interlocked.Decrement(ref count);
    }
}


问:
how would i remove some portion of
 from a table in php?
this is my table -

```<code> <table>
     <tr>
      <td>ABC</td>
     </tr>
     <tr>
      <td> </td>
     </tr>
 </table>
</code>```

and I want to remove this one table row:

```<code><tr>
   <td> </td>
</tr>
</code>```

my expected output is:

```<code> <table>
   <tr>
     <td>ABC</td>
   </tr>
 </table>
</code>```

is it possible??please help me

答:
You should try this:

```<code><table>
 <tr id="abc>
  <td>ABC</td>
 </tr>
 <tr id="remove">
  <td> </td>
 </tr>
</code>```

```<code><script>
 $('#remove').remove();
</script>
</code>```

Title: how would i remove some portion of <tr><td> from a table in php?

Body:
this is my table -

      ABC

and I want to remove this one table row:

my expected output is:

     ABC

is it possible??please help me

Body:
You should try this:

<table>
 <tr id="abc>
  <td>ABC</td>
 </tr>
 <tr id="remove">
  <td>&nbsp;</td>
 </tr>

<script>
 $('#remove').remove();
</script>