问:
My python codes in general are very slow, is this normal?
I recently began self-learning python, and have been using this language for an online course in algorithms. For some reason, many of my codes I created for this course are very slow (relatively to C/C++ Matlab codes I have created in the past), and I'm starting to worry that I am not using python properly.

Here is a simple python and matlab code to compare their speed.

MATLAB

```<code>   for i = 1:100000000
        a = 1 + 1
   end
</code>```

Python

```<code>   for i in list(range(0, 100000000)):
        a=1 + 1
</code>```

The matlab code takes about 0.3 second, and the python code takes about 7 seconds. Is this normal? My python codes for much complex problems are very slow. For example, as a HW assignment, I'm running depth first search on a graph with about 900000 nodes, and this is taking forever. Thank you.

答:
Performance is not an explicit design goal of Python:

Don’t fret too much about performance--plan to optimize later when
  needed.

That's one of the reasons why Python integrated with a lot of high performance calculating backend engines, such as numpy, OpenBLAS and even CUDA, just to name a few.

The best way to go foreward if you want to increase performance is to let high-performance libraries do the heavy lifting for you. Optimizing loops within Python (by using xrange instead of range in Python 2.7) won't get you very dramatic results.

Here is a bit of code that compares different approaches:

Your original list(range())

The suggestes use of xrange()

Leaving the i out

Using numpy to do the addition using numpy array's (vector addition)

Using CUDA to do vector addition on the GPU

Code:

```<code>import timeit
import matplotlib.pyplot as mplplt

iter = 100
testcode = [
    "for i in list(range(1000000)): a = 1+1",
    "for i in xrange(1000000): a = 1+1",
    "for _ in xrange(1000000): a = 1+1",
    "import numpy; one = numpy.ones(1000000); a = one+one",
    "import pycuda.gpuarray as gpuarray; import pycuda.driver as cuda; import pycuda.autoinit; import numpy;" \
    "one_gpu = gpuarray.GPUArray((1000000),numpy.int16); one_gpu.fill(1); a = (one_gpu+one_gpu).get()"
    ]
labels = ["list(range())", "i in xrange()", "_ in xrange()", "numpy", "numpy and CUDA"]

timings = [timeit.timeit(t, number=iter) for t in testcode]

print labels, timings

label_idx = range(len(labels))
mplplt.bar(label_idx, timings)
mplplt.xticks(label_idx, labels)
mplplt.ylabel('Execution time (sec)')
mplplt.title('Timing of integer addition in python 2.7\n(smaller value is better performance)')
mplplt.show()
</code>```

Results (graph) ran on Python 2.7.13 on OSX:

The reason that Numpy performs faster than the CUDA solution is that the overhead of using CUDA does not beat the efficiency of Python+Numpy. For larger, floating point calculations, CUDA does even better than Numpy.

Note that the Numpy solution performs more that 80 times faster than your original solution. If your timings are correct, this would even be faster than Matlab...

A final note on DFS (Depth-afirst-Search): here is an interesting article on DFS in Python.

Body:
I recently began self-learning python, and have been using this language for an online course in algorithms. For some reason, many of my codes I created for this course are very slow (relatively to C/C++ Matlab codes I have created in the past), and I'm starting to worry that I am not using python properly.

Here is a simple python and matlab code to compare their speed.

MATLAB

   for i = 1:100000000
        a = 1 + 1
   end

Python

   for i in list(range(0, 100000000)):
        a=1 + 1

The matlab code takes about 0.3 second, and the python code takes about 7 seconds. Is this normal? My python codes for much complex problems are very slow. For example, as a HW assignment, I'm running depth first search on a graph with about 900000 nodes, and this is taking forever. Thank you.

Body:
Performance is not an explicit design goal of Python:

Don’t fret too much about performance--plan to optimize later when
  needed.

That's one of the reasons why Python integrated with a lot of high performance calculating backend engines, such as numpy, OpenBLAS and even CUDA, just to name a few.

The best way to go foreward if you want to increase performance is to let high-performance libraries do the heavy lifting for you. Optimizing loops within Python (by using xrange instead of range in Python 2.7) won't get you very dramatic results.

Here is a bit of code that compares different approaches:

Your original list(range())

The suggestes use of xrange()

Leaving the i out

Using numpy to do the addition using numpy array's (vector addition)

Using CUDA to do vector addition on the GPU

Code:

import timeit
import matplotlib.pyplot as mplplt

iter = 100
testcode = [
    "for i in list(range(1000000)): a = 1+1",
    "for i in xrange(1000000): a = 1+1",
    "for _ in xrange(1000000): a = 1+1",
    "import numpy; one = numpy.ones(1000000); a = one+one",
    "import pycuda.gpuarray as gpuarray; import pycuda.driver as cuda; import pycuda.autoinit; import numpy;" \
    "one_gpu = gpuarray.GPUArray((1000000),numpy.int16); one_gpu.fill(1); a = (one_gpu+one_gpu).get()"
    ]
labels = ["list(range())", "i in xrange()", "_ in xrange()", "numpy", "numpy and CUDA"]

timings = [timeit.timeit(t, number=iter) for t in testcode]

print labels, timings

label_idx = range(len(labels))
mplplt.bar(label_idx, timings)
mplplt.xticks(label_idx, labels)
mplplt.ylabel('Execution time (sec)')
mplplt.title('Timing of integer addition in python 2.7\n(smaller value is better performance)')
mplplt.show()

Results (graph) ran on Python 2.7.13 on OSX:

The reason that Numpy performs faster than the CUDA solution is that the overhead of using CUDA does not beat the efficiency of Python+Numpy. For larger, floating point calculations, CUDA does even better than Numpy.

Note that the Numpy solution performs more that 80 times faster than your original solution. If your timings are correct, this would even be faster than Matlab...

A final note on DFS (Depth-afirst-Search): here is an interesting article on DFS in Python.


来源: stackexchange

问:
format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘int *’
I'm trying to create a program that will show elements from the int array. But I keep getting the warning. This is probably going to get really downvoted but I don't know where I made a mistake.

Here is the code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
#include <time.h>

int main() {
     int counter;
     int elements[3] = { 22, 52, 95 };

     for (counter = 1; counter <= 3; counter++) {
         printf("Element %d: %d\n", counter, elements);
     }
     return 0;
}
</code>```

答:
I think you mean

```<code>for(counter = 0; counter < 3; counter++)
{
    printf("Element %d: %d\n", counter, elements[counter]);
}
</code>```

Edit:
Clarification: Loop should run from 0 as "C" arrays are 0 based, the max size if up to "n-1" where n is array size. Next %d will need the element not the array itself. To access the array element, you'll need to use the "[]" operator.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to create a program that will show elements from the int array. But I keep getting the warning. This is probably going to get really downvoted but I don't know where I made a mistake.

Here is the code:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
#include <time.h>

int main() {
     int counter;
     int elements[3] = { 22, 52, 95 };

     for (counter = 1; counter <= 3; counter++) {
         printf("Element %d: %d\n", counter, elements);
     }
     return 0;
}

Body:
I think you mean

for(counter = 0; counter < 3; counter++)
{
    printf("Element %d: %d\n", counter, elements[counter]);
}

Edit:
Clarification: Loop should run from 0 as "C" arrays are 0 based, the max size if up to "n-1" where n is array size. Next %d will need the element not the array itself. To access the array element, you'll need to use the "[]" operator.


问:
SPARQL: get biggest city with female mayor
I try to get all cities with a female mayor, but my problem is, that the most mayors if they are in marked in data they are mostly not linked to a person, they are only given as string. So how can I get the gender.

My command to get all mayors is:

```<code>SELECT * WHERE {
 ?city a dbo:City .
 ?city dbo:populationTotal ?pop .
 ?city (dbp:mayor | dbo:mayor | dbp:leader |dbo:leader) ?mayor

}
ORDER BY DESC(?pop)
</code>```

I am not sure if I get all mayors, because there are only 500 mayors versus 19584 cities with given population that sounds less.

For the reason I did not get gender on this way I did a second request to get all female people in DBpedia and try to compare both results, but mostly ends in timeout or "no result"

On example command runs in timeout was:

```<code>SELECT ?name ?sayor WHERE {
 ?person a dbo:Person .
 ?person foaf:gender ?gender .
 FILTER regex(?gender, "^female$", "i") .
 ?person rdfs:label ?name .
 {
  SELECT str(?mayor) AS ?sayor WHERE {
   ?city a dbo:City .
   ?city (dbp:mayor | dbp:leader) ?mayor .
   FILTER (str(?mayor) = str(?name))
  }
 }
}
</code>```

Has anyone an idea to get all cities with female mayor? I am also happy with getting some stimulation's.

答:
this is a particular problem which arises due to multiple factors. Here the main two:

The awkward property structure of dbo:Settlement:
The Infobox of the Wikipedia Template Infobox settlement does not have a direct leader/mayor property. Since these templates were not created with a clear object structure in mind, the leader properties are flattened in this template into:

```<code>| leader_title = [[Mayor of Chicago|Mayor]]
| leader_name = [[Rahm Emanuel]]
| leader_party = [[Democratic Party (United States)|D]]
| leader_title1 = [[City council|Council]]
| leader_name1 = [[Chicago City Council]]
</code>```

Which leaves editors with no real option but to 'misuse' the leader_name property, not to put down the name literal but to point to the resource (person) in question. Different Infobox templates have a mayor/leader property but this is the one most often used to describe cities in the English Wikipedia.

Second, the quite rigid behavior of the DBpedia mappings, which have problems dealing with Infobox properties which could be either a literal or a resource link. At least it is difficult for mapping editors to tackle this. DBpedia is dealing with this (and other issues) right now by introducing RML mappings.

This, of course, can appear in similar fashion in other dbo classes as well. While DBpedia is looking into such issues, up to date mappings from Wikipedia templates to DBpedia ontology is one way to solve this, which is something anyone can contribute.

With this in mind we can solve you origin problem:

```<code>SELECT * WHERE {
   ?plebs rdfs:subClassOf dbo:Settlement.
   ?city a ?plebs .
   ?city (dbp:mayor | dbo:mayor | dbp:leader |dbo:leader | dbo:leaderName) ?mayor .
   ?mayor foaf:gender ?gender.
   ?city dbo:populationTotal ?pop .
   FILTER(str(?gender) = "female")
  }
ORDER BY DESC(?pop)
</code>```

Which results in this top three:

```<code>http://dbpedia.org/resource/Tokyo   http://dbpedia.org/resource/Yuriko_Koike
"female"@en    13617445
http://dbpedia.org/resource/Mumbai  http://dbpedia.org/resource/Snehal_Ambekar
"female"@en    12442373
http://dbpedia.org/resource/Yuncheng    http://dbpedia.org/resource/Wang_Yuyan
"female"@en    5134779
</code>```

Which seems about right to me.

Body:
I try to get all cities with a female mayor, but my problem is, that the most mayors if they are in marked in data they are mostly not linked to a person, they are only given as string. So how can I get the gender.

My command to get all mayors is:

SELECT * WHERE {
 ?city a dbo:City .
 ?city dbo:populationTotal ?pop .
 ?city (dbp:mayor | dbo:mayor | dbp:leader |dbo:leader) ?mayor

}
ORDER BY DESC(?pop)

I am not sure if I get all mayors, because there are only 500 mayors versus 19584 cities with given population that sounds less.

For the reason I did not get gender on this way I did a second request to get all female people in DBpedia and try to compare both results, but mostly ends in timeout or "no result"

On example command runs in timeout was:

SELECT ?name ?sayor WHERE {
 ?person a dbo:Person .
 ?person foaf:gender ?gender .
 FILTER regex(?gender, "^female$", "i") .
 ?person rdfs:label ?name .
 {
  SELECT str(?mayor) AS ?sayor WHERE {
   ?city a dbo:City .
   ?city (dbp:mayor | dbp:leader) ?mayor .
   FILTER (str(?mayor) = str(?name))
  }
 }
}

Has anyone an idea to get all cities with female mayor? I am also happy with getting some stimulation's.

Body:
this is a particular problem which arises due to multiple factors. Here the main two:

The awkward property structure of dbo:Settlement:
The Infobox of the Wikipedia Template Infobox settlement does not have a direct leader/mayor property. Since these templates were not created with a clear object structure in mind, the leader properties are flattened in this template into:

| leader_title = [[Mayor of Chicago|Mayor]]
| leader_name = [[Rahm Emanuel]]
| leader_party = [[Democratic Party (United States)|D]]
| leader_title1 = [[City council|Council]]
| leader_name1 = [[Chicago City Council]]

Which leaves editors with no real option but to 'misuse' the leader_name property, not to put down the name literal but to point to the resource (person) in question. Different Infobox templates have a mayor/leader property but this is the one most often used to describe cities in the English Wikipedia.

Second, the quite rigid behavior of the DBpedia mappings, which have problems dealing with Infobox properties which could be either a literal or a resource link. At least it is difficult for mapping editors to tackle this. DBpedia is dealing with this (and other issues) right now by introducing RML mappings.

This, of course, can appear in similar fashion in other dbo classes as well. While DBpedia is looking into such issues, up to date mappings from Wikipedia templates to DBpedia ontology is one way to solve this, which is something anyone can contribute.

With this in mind we can solve you origin problem:

SELECT * WHERE {
   ?plebs rdfs:subClassOf dbo:Settlement.
   ?city a ?plebs .
   ?city (dbp:mayor | dbo:mayor | dbp:leader |dbo:leader | dbo:leaderName) ?mayor .
   ?mayor foaf:gender ?gender.
   ?city dbo:populationTotal ?pop .
   FILTER(str(?gender) = "female")
  }
ORDER BY DESC(?pop)

Which results in this top three:

http://dbpedia.org/resource/Tokyo   http://dbpedia.org/resource/Yuriko_Koike
"female"@en    13617445
http://dbpedia.org/resource/Mumbai  http://dbpedia.org/resource/Snehal_Ambekar
"female"@en    12442373
http://dbpedia.org/resource/Yuncheng    http://dbpedia.org/resource/Wang_Yuyan
"female"@en    5134779

Which seems about right to me.


问:
Can i have a child div hide its parent div along with it when clicked?
For example :

```<code><div id="parent">
      <div id="child">Click here</div>
</div>
</code>```

when i click on child, both div will disappear or hidden

答:
Here you go with an working example https://jsfiddle.net/fdaqsks2/

$("#child").click(function(){
    $(this).parent().hide();
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#parent{
  padding: 20px;
  background: red;
}

#child {
  padding:5px;
  background: blue;
  color: #fff;
}</code>```

Click here

```

Body:
For example :

Click here

when i click on child, both div will disappear or hidden

Body:
Here you go with an working example https://jsfiddle.net/fdaqsks2/

$("#child").click(function(){
    $(this).parent().hide();
})

#parent{
  padding: 20px;
  background: red;
}

#child {
  padding:5px;
  background: blue;
  color: #fff;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
      <div id="child">Click here</div>
</div>


问:
Custom account type for secondary user in Android N
My application provides a custom account type, which can be created via

Preferences->Accounts->Add account

Everything works as expected. However, when I change to a non-primary user, my custom user account is not on the list, so I cannot create one.

Any suggestions?

P.S.: Tested on Android 7.1.2 (Google Pixel)

答: Don't know how, but the problem has gone...</p>


答:
You can do by using jquery on() and hide() function. Once you html properly render or loaded then following code will be ready to execute, this is beacuse of $(document).ready(function() {...Execute Once HTML Render...});

So the following code will be functional only click event as you see i am using on('click',function(){...});

```<code>$(document).ready(function() {
  $( "#child" ).on('click',function(){
    $(this).parent().hide();
  });
});
</code>```

Here is an example

Title: Can i have a child div hide its parent div along with it when clicked?

Body:
You can do by using jquery on() and hide() function. Once you html properly render or loaded then following code will be ready to execute, this is beacuse of $(document).ready(function() {...Execute Once HTML Render...});

So the following code will be functional only click event as you see i am using on('click',function(){...});

$(document).ready(function() {
  $( "#child" ).on('click',function(){
    $(this).parent().hide();
  });
});

Here is an example


问:
What's the difference between abstraction and encapsulation?
In interviews I have been asked to explain the difference between abstraction and encapsulation.  My answer has been along the lines of

Abstraction allows us to represent complex real world in simplest manner. It is the process of identifying the relevant qualities and behaviors an object should possess; in other words, to represent the necessary feature without representing the background details.

Encapsulation is a process of hiding all the internal details of an object from the outside real world. The word "encapsulation", is like "enclosing" into a "capsule". It restricts clients from seeing its internal view where the behavior of the abstraction is implemented.

I think with above answer the interviewer was convinced, but then I was asked, if the purpose of both is hiding, then why there is a need to use encapsulation.  At that time I didn't have a good answer for this.

What should I have added to make my answer more complete?

答:
I know there are lot's of answers before me with variety of examples.

Well here is my opinion abstraction is getting interested from reality .

In abstraction we hide something to reduce the complexity of it
and In encapsulation we hide something to protect the data.

So we define encapsulation as wrapping of data and methods in single entity referred as class.

In java we achieve encapsulation using getters and setters not just by wrapping data and methods in it. we also define a way to access that data.
and while accessing data we protect it also.

Techinical e.g would be to define a private data variable call weight.Now we know that weight can't be zero or less than zero in real world scenario.
 Imagine if there are no getters and setters someone could have easily set it to a negative value being public member of class.

Now final difference using one real world example,

Consider a circuit board consisting of switches and buttons.
We wrap all the wires into a a circuit box, so that we can protect someone by not getting in contact directly(encapsulation).

We don't care how those wires are connected to each other we just want an interface to turn on and off switch. That interface is provided by buttons(abstraction)


问:
Is a function definition an object?
Say I have an object and a function definition:

```<code>var jane = {
    firstName: 'Jane',
    lastName: 'Smith',
    describe: function () {
        return 'Person named '+this.firstName+this.lastName
    },
};

function Car (desc) {
    this.desc = desc;
    this.color = "red";
    this.getInfo = function getInfo() {
        return 'A ' + this.color + ' ' + this.desc + '.';
    };
}
</code>```

I can enumerate over the object's key:value pairs thus:

```<code>obj=jane
for (var prop in obj) {
  console.log(`obj.${prop} = ${obj[prop]}`);
}
</code>```

but this fails for the function definition (same for function expression)

```<code>obj=Car.....
</code>```

If a function definition is an object then why can't I enumerate over it's properties? Is there a way do to it?

Thanks

答:
In this case this refers to global object window or to undefined in strict mode.
Use it as constructor:
obj = new Car(desc)

Title: Is a function definition an object?

Body:
Say I have an object and a function definition:

var jane = {
    firstName: 'Jane',
    lastName: 'Smith',
    describe: function () {
        return 'Person named '+this.firstName+this.lastName
    },
};

function Car (desc) {
    this.desc = desc;
    this.color = "red";
    this.getInfo = function getInfo() {
        return 'A ' + this.color + ' ' + this.desc + '.';
    };
}

I can enumerate over the object's key:value pairs thus:

obj=jane
for (var prop in obj) {
  console.log(`obj.${prop} = ${obj[prop]}`);
}

but this fails for the function definition (same for function expression)

obj=Car.....

If a function definition is an object then why can't I enumerate over it's properties? Is there a way do to it?

Thanks


问:
Incomplete type is not allowed error
```<code>Here is my code

#include<iostream>
#include<string>
using namespace std;
class GradeBook; // GradeBook class definition
{
public:
    // constructor initializes courseName
    GradeBook(string name)
    {
        setCourseName(name);
    }
    void setCourseName(string name)
    {
        courseName = name;
    }
    string getCourseName()
    {
        return courseName;
    }
    void displayMessage()
    {
        cout << "Welcome to the grade book for\n" << getCourseName() << "!" << endl;
    }
private:
    string courseName;
};

int main()
{

    GradeBook gradeBook1("CS101 Introduction to C++ Programming");
    GradeBook gradeBook2("Visual C++ introduction");

    cout << "gradeBook1 created for course: " << gradeBook1.getCourseName()
        << "\ngradeBook2 created for course: " << gradeBook2.getCourseName()
        << endl;
    return 0;
}
</code>```

答: Remove the ; after class Gradebook and everything should be fine.

Title: Incomplete type is not allowed error


问:
Why is a container parameter used in a priority queue for overloading?
```<code>std::priority_queue< int, std::vector<int>, std::greater<int> > pq;
</code>```

Why is the vector parameter used?

答:
The priority queue implementation can use different types of containers to build the underlining data structure. You can specify which one you like the most using that template parameter.

Quoting from here

Container -   The type of the underlying container to use to store the
  elements. The container must satisfy the requirements of
  SequenceContainer, and its iterators must satisfy the requirements of
  RandomAccessIterator. Additionally, it must provide the following
  functions with the usual semantics:
      front()
      push_back()
      pop_back()
      The standard containers std::vector and std::deque satisfy these requirements.

Btw, vector is the default one.

Body:
std::priority_queue< int, std::vector<int>, std::greater<int> > pq;

Why is the vector parameter used?


问:
Superpowered: fade-in/fade-out
I was looking for a simple fade-in/fade-out in the documentation, but wasn't able to find anything.

Is is it possible to make a fade-in/fade-out on a looping signal with superpowered?

//edit

I am using the CrossExample and I loop sounds in small pulses. I wanna apply a fade-in and fade-out on the looping signal with superpowered.

答: Depending on the complexity of the signal, you could probably apply a Superpowered3BandEQ and gradually decrease gain toward -40dB (kill point).</p>

Title: Superpowered: fade-in/fade-out


问:
Center form content vertically
I've got the following landing page form (I've cut all the unnecessary stuff I don't think matters leaving only minimum of style). Here is the code (I'm using Bootstrap 3.3.5):

```<code><div class="col-md-6 app-door">
  <form class="image-hover text-center">
    <h3>Application name</h3>
    <div class="landing-page-form-group">
      <label class="landing-page-label">Label: </label>
      <input class="form-control landing-page-input">
    </div>
    <button class="btn">Submit</button>
  </form>
  <div class="center-block app-link some-img"/>
</div>
</code>```

..and css

```<code>.image-hover {
  width: 300px;
  height: 300px;
  background-color: rgba(0, 0, 0, 0.7) !important;
  position: absolute;
  z-index: 100;
  color: #cccccc;
  margin: 0 auto;
  left: 0;
  right: 0;
  border-radius: 25px;
}

.landing-page-form-group {
  padding-top: 16px;
  padding-bottom: 16px;
}

.landing-page-label {
  width: 100px;
  vertical-align: middle;
}

.landing-page-input {
  width: 150px;
  display: inline-block;
}

.app-link {
  width: 300px;
  height: 300px;
  background-size: 100% 100%;
  border-radius: 25px;
}

.some-img {
  background-image: url("http://dl.hiapphere.com/data/icon/201511/HiAppHere_com_com.ludicside.mrsquare.png");
}
</code>```

I want to center all the form inputs and etc vertically. I've tried such things as playing with position (relative on parent, absolute on child), vertical-align, top, maybe something else I don't remember right now as I spent lots of hours trying.

I'm not a great specialist in frontend development (I mean html/css) so I will be extremely happy to see understanding although the problem seems to be basic enough.

Thank you for any ideas!

答:
This is my solution:
https://jsfiddle.net/0x9epxah/1/

add div .inner-form:

```<code><div class="col-md-6 app-door">
  <form class="image-hover text-center">
    <div class="inner-form">
      <h3>Application name</h3>
      <div class="landing-page-form-group">
        <label class="landing-page-label">Label: </label>
        <input class="form-control landing-page-input">
      </div>
      <button class="btn">Submit</button>
    </div>
  </form>
  <div class="center-block app-link some-img"/>
</div>
</code>```

and this css class:

```<code>.inner-form {
  position: absolute;
  top: 50%; left: 50%;
  transform: translate(-50%,-50%);
}
</code>```

Title: Center form content vertically

Body:
I've got the following landing page form (I've cut all the unnecessary stuff I don't think matters leaving only minimum of style). Here is the code (I'm using Bootstrap 3.3.5):

  <form class="image-hover text-center">

Application name

      Label:
      <input class="form-control landing-page-input">

    <button class="btn">Submit</button>
  </form>

..and css

.image-hover {
  width: 300px;
  height: 300px;
  background-color: rgba(0, 0, 0, 0.7) !important;
  position: absolute;
  z-index: 100;
  color: #cccccc;
  margin: 0 auto;
  left: 0;
  right: 0;
  border-radius: 25px;
}

.landing-page-form-group {
  padding-top: 16px;
  padding-bottom: 16px;
}

.landing-page-label {
  width: 100px;
  vertical-align: middle;
}

.landing-page-input {
  width: 150px;
  display: inline-block;
}

.app-link {
  width: 300px;
  height: 300px;
  background-size: 100% 100%;
  border-radius: 25px;
}

.some-img {
  background-image: url("http://dl.hiapphere.com/data/icon/201511/HiAppHere_com_com.ludicside.mrsquare.png");
}

I want to center all the form inputs and etc vertically. I've tried such things as playing with position (relative on parent, absolute on child), vertical-align, top, maybe something else I don't remember right now as I spent lots of hours trying.

I'm not a great specialist in frontend development (I mean html/css) so I will be extremely happy to see understanding although the problem seems to be basic enough.

Thank you for any ideas!

Body:
This is my solution:
https://jsfiddle.net/0x9epxah/1/

add div .inner-form:

<div class="col-md-6 app-door">
  <form class="image-hover text-center">
    <div class="inner-form">
      <h3>Application name</h3>
      <div class="landing-page-form-group">
        <label class="landing-page-label">Label: </label>
        <input class="form-control landing-page-input">
      </div>
      <button class="btn">Submit</button>
    </div>
  </form>
  <div class="center-block app-link some-img"/>
</div>

and this css class:

.inner-form {
  position: absolute;
  top: 50%; left: 50%;
  transform: translate(-50%,-50%);
}


问:
requests module not working in pycharm (only)
I was trying to create a web scraping program , which uses bs4 and requests library. What i noticed that whenever pycharm encounters import requests it just gets stuck and throws an error when i press return .The error is :

```<code>>>> import requests

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\HP\64bit\lib\site-packages\requests\__init__.py", line 43, in <module>
    import urllib3
  File "C:\Users\HP\64bit\lib\site-packages\urllib3\__init__.py", line 8, in <module>
    from .connectionpool import (
  File "C:\Users\HP\64bit\lib\site-packages\urllib3\connectionpool.py", line 3, in <module>
    import logging
  File "C:\Users\HP\AppData\Local\Programs\Python\Python36\Lib\logging\__init__.py", line 28, in <module>
    from string import Template
  File "C:\Users\HP\PycharmProjects\Automate\string.py", line 28, in <module>
    t = int(input())
ValueError: invalid literal for int() with base 10: ''
>>>
</code>```

Trying to do the same in IDLE shell or cmd window works just fine
I'm using windows 10 64-bit , python 64-bit 3.6.2rc1 & Pycharm 2017.1.4 community edition.

答:
Your PYTHONPATH is screwed up, which is probably due to PyCharm's option to add the project root to PYTHONPATH (the option is in the "run" settings).

Due to the messed-up PYTHONPATH, the string import inside requests imports your string.py instead of the same module from the stdlib (the traceback clearly shows this by the way).

Easiest solution? Don't have top-level .py files, put them inside a package. That way only your package will be importable as a top-level package in PYTHONPATH but you don't end up having tons of new top-level modules.

Body:
I was trying to create a web scraping program , which uses bs4 and requests library. What i noticed that whenever pycharm encounters import requests it just gets stuck and throws an error when i press return .The error is :

>>> import requests

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\HP\64bit\lib\site-packages\requests\__init__.py", line 43, in <module>
    import urllib3
  File "C:\Users\HP\64bit\lib\site-packages\urllib3\__init__.py", line 8, in <module>
    from .connectionpool import (
  File "C:\Users\HP\64bit\lib\site-packages\urllib3\connectionpool.py", line 3, in <module>
    import logging
  File "C:\Users\HP\AppData\Local\Programs\Python\Python36\Lib\logging\__init__.py", line 28, in <module>
    from string import Template
  File "C:\Users\HP\PycharmProjects\Automate\string.py", line 28, in <module>
    t = int(input())
ValueError: invalid literal for int() with base 10: ''
>>>

Trying to do the same in IDLE shell or cmd window works just fine
I'm using windows 10 64-bit , python 64-bit 3.6.2rc1 & Pycharm 2017.1.4 community edition.


问:
Auto-login after email validation and redirection to 'fos_user_profile_edit' path
We're building a business app from the ground up in Symfony 3, and I've run into a bit of a snag with the user validation flow: after the user creates an account they will receive a validation email, then(after clicking the confirmation/validation link) they should be automatically authentificated and redirected to the edit profile.
But unfortunately they are redirected to the login page without any authentification.

Anyone had any experience with this, or able to point me in the right direction?

答:
Which version of user bunle have you?

It is as folow, If email configuration has been set properly, when user are create (registerAction), FOSUserEvents::REGISTRATION_SUCCESS event are dispatch and EmailConfirmationListener catch its and send email with the generated token.
This token is save in session and user have to be connected by using email confirmation with it related confirmation token confirmAction

All depend on if admin email is set properly or not have a look there :
https://symfony.com/doc/master/bundles/FOSUserBundle/emails.html#registration-confirmation

If email has not been set properly addRegistrationSection by default:

```<code>fos_user:
# ...
    registration:
        confirmation:
            enabled: false
</code>```

User should be connected directly

Body:
Which version of user bunle have you?

It is as folow, If email configuration has been set properly, when user are create (registerAction), FOSUserEvents::REGISTRATION_SUCCESS event are dispatch and EmailConfirmationListener catch its and send email with the generated token.
This token is save in session and user have to be connected by using email confirmation with it related confirmation token confirmAction

All depend on if admin email is set properly or not have a look there :
https://symfony.com/doc/master/bundles/FOSUserBundle/emails.html#registration-confirmation

If email has not been set properly addRegistrationSection by default:

fos_user:
# ...
    registration:
        confirmation:
            enabled: false

User should be connected directly


问:
PHP / JAVASCRIPT / Mysql: Preventing javascript injections
This may be a possible duplicate of this question here, but it doesn´t really adress and answer my question in a way that I (stupid-head) can understand it.

Ok, I´ve got a webpage formular as seen in my previous question. Before using $txtpost for mysql query injection, I now added $ txtpost = htmlentities($txtpost, ENT_QUOTES);, which  should protect me from XSS-attacks. But, as a user points out on php.net, won´t protect me from javascript injections. That said, how can I prevent such javascript injections? As you can see in the code from the previous question, i don´t know what exactly will be entered into the text field, so I can´t only allow specific values. Note that all code from the previous question, which was wrong, is now repaired and it all works fine at the moment.

VicStudio

答:
Well, it is true that you won't be protected from people putting HTML into your database.

First of all

```<code>$txtpost = htmlentities($txtpost, ENT_QUOTES);
</code>```

Will escape quotes, rendering an SQL-injection less probable. But I can still do OR 1 = 1. Which renders every statement true. Modern technology relies on prepared statements (How to replace MySQL functions with PDO?)

If you read the above you'll see a PDO example of prepared statement. You can also do this with MySQLi. It prevents the fact that people can do SQL injection.

Second:
Yes, I can still put things like

```<code><a href="javascript:alert(1)">XSS</a>
</code>```

Into your database. You should define the elements you like into your database by using a sanity function. PHP gives you several

filter_input: Allows you to filter and sanitize certain input.

strip_tags: allows you to strip all tags and/or use a white list of tags you do want to allow.

htmlspecialchars: converts all special characters into entities. Like " to &quot.

The conclusion is that you need to be in control. You decide what goes onto your page. So if you want to be safe you can filter everything and put it on your page as plain text. For safety I recommend sanitizing three times. Before the stuff is posted, when it is passed onto the database and again when it is put onto the page. This way you minimalize the danger of having an injection.

Body:
Well, it is true that you won't be protected from people putting HTML into your database.

First of all

$txtpost = htmlentities($txtpost, ENT_QUOTES);

Will escape quotes, rendering an SQL-injection less probable. But I can still do OR 1 = 1. Which renders every statement true. Modern technology relies on prepared statements (How to replace MySQL functions with PDO?)

If you read the above you'll see a PDO example of prepared statement. You can also do this with MySQLi. It prevents the fact that people can do SQL injection.

Second:
Yes, I can still put things like

<a href="javascript:alert(1)">XSS</a>

Into your database. You should define the elements you like into your database by using a sanity function. PHP gives you several

filter_input: Allows you to filter and sanitize certain input.

strip_tags: allows you to strip all tags and/or use a white list of tags you do want to allow.

htmlspecialchars: converts all special characters into entities. Like " to &quot.

The conclusion is that you need to be in control. You decide what goes onto your page. So if you want to be safe you can filter everything and put it on your page as plain text. For safety I recommend sanitizing three times. Before the stuff is posted, when it is passed onto the database and again when it is put onto the page. This way you minimalize the danger of having an injection.


问:
How can I tell whether an element matches a selector?
Let's say I've got a DOM element - how can I tell whether it matches a jQuery selector, such as p or .myclass? It's easy to use the selector to match children of the element, but I want a true/false answer to whether this particular element match?

The element may not have an ID (and I can't assign it a random one for reasons beyond this), so I can't apply my selector to the element's parent and look for children with the same ID as mine.

Will this work as intended? I can't figure out Javascript object comparisons.

```<code>$(selector, myElement.parentNode).each({
  if (this == myElement) // Found it
});
</code>```

Seems like there would be an easy way to see whether a DOM element matches a jQuery selector...

答:
Without jQuery, using Element.matches():

var elements = document.querySelectorAll('div');

console.log(
   elements[0].matches('.foo'),         // true
   elements[0].matches('.bar'),         // false
   elements[1].matches('[title=bar]'),  // true
)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='foo'></div>
<div title='bar'></div></code>```

See supported browsers list

OwnerDisplayName: sam

Body:
Let's say I've got a DOM element - how can I tell whether it matches a jQuery selector, such as p or .myclass? It's easy to use the selector to match children of the element, but I want a true/false answer to whether this particular element match?

The element may not have an ID (and I can't assign it a random one for reasons beyond this), so I can't apply my selector to the element's parent and look for children with the same ID as mine.

Will this work as intended? I can't figure out Javascript object comparisons.

$(selector, myElement.parentNode).each({
  if (this == myElement) // Found it
});

Seems like there would be an easy way to see whether a DOM element matches a jQuery selector...

Body:
Without jQuery, using Element.matches():

var elements = document.querySelectorAll('div');

console.log(
   elements[0].matches('.foo'),         // true
   elements[0].matches('.bar'),         // false
   elements[1].matches('[title=bar]'),  // true
)

<div class='foo'></div>
<div title='bar'></div>

See supported browsers list

ContentLicense: CC BY-SA 4.0


问:
Why after installing Android Studio on Windows 10 I don't need to install JDK? Is it already there?
I have used android studio on windows 7, every time I install android studio I had to install jdk and configure environment path first . but in windows 10 when I installed android studio it didn't ask me for jdk and I can use android studio without any problem I also installed an app in my mobile everything works fine.

I went to cmd to check if jdk is installed I type java -version and javac but both came up with error.

If the JDK is not installed then how come android studio is working?

答: For some time now Android Studio includes its own private java runtime in jre folder. </p>


问:
Output in makefile at top-level
I am setting a variable in a makefile like this:

```<code>SOMEVAR = foo
</code>```

This makefile later includes some other makefile in which the actual building of programs takes place:

```<code>include generic/Makefile.common
</code>```

So no build targets are defined in the first makefile, it's only setting up variables which are then used by the common generic makefile to do the actual package building.

Now I know that I should be careful when using foo, so to remind myself of this, I want to print a warning message whenever this makefile is used to setup the make process. The problem is that I cannot just insert an echo command after the variable definition, because we are not yet building something there.

Is there a solution (more elegant than adding a fake target where the message is printed which would destroy the separation of setting variables and building)?

答:
```<code>SOMEVAR = foo
$(warning be careful with foo)
</code>```

ContentLicense: CC BY-SA 2.5

Title: Output in makefile at top-level

Body:
I am setting a variable in a makefile like this:

SOMEVAR = foo

This makefile later includes some other makefile in which the actual building of programs takes place:

include generic/Makefile.common

So no build targets are defined in the first makefile, it's only setting up variables which are then used by the common generic makefile to do the actual package building.

Now I know that I should be careful when using foo, so to remind myself of this, I want to print a warning message whenever this makefile is used to setup the make process. The problem is that I cannot just insert an echo command after the variable definition, because we are not yet building something there.

Is there a solution (more elegant than adding a fake target where the message is printed which would destroy the separation of setting variables and building)?


问:
How create entity. Hibernate
Each company has two properties, they are company name and estimated annual earnings.
There are two types of companies: 1- Main company, 2 - Subsidiary company.
The company can belong only to one company but can have a few child companies.</p>

答:
With @Entity you define a class to become an entity. with @Column you define which attributes map to which table columns. After that you need to define your relationships, in this case a self reference to the same table (parent company to child company), you can define it like this:

```<code>@ManyToOne
private Company parentCompany;
@OneToMany(mappedBy = "parentCompany", fetch = FetchType.EAGER)
private Set<Company> childCompanies;
</code>```

Title: How create entity. Hibernate

Body:
With @Entity you define a class to become an entity. with @Column you define which attributes map to which table columns. After that you need to define your relationships, in this case a self reference to the same table (parent company to child company), you can define it like this:

@ManyToOne
private Company parentCompany;
@OneToMany(mappedBy = "parentCompany", fetch = FetchType.EAGER)
private Set<Company> childCompanies;


问:
Dropdownlist SelectedItemChanged Event in MVC4 Razor?
Is there any event available for Dropdownlist like onChange, etc. in MVC4? Do we have to use Javascript/jQuery in order to make some manipulations like DropwowlistSelectedItemChanged, etc? Or there is a way only using the Razor or MVC4 features?

On the other hand, could you please give me some examples how can I retrieve data and change a label's text with this data according to a Dropdownlist Selected Value? For example when selecting a City from Dropdownlist, I want to get an address data from database by using the selected city id and then show retrieved address on a label. I would be appreciated if you clarify me about the issue above and give me an example to achieve this.

Controller:

```<code>private void PopulateMeetingsDropDownList(object selectedMeetings = null)
    {
        var meetingsQuery = repository.Meetings
            .Join(repository.Cities, m => m.MeetingCityId, c => c.CityID,
                (m, c) => new
                {
                    CityID = c.CityID,
                    CityName = c.CityName,
                    MeetingDate = m.MeetingStartDate
                }
            )
            .OrderBy(x => x.CityID)
            .AsEnumerable()
            .Select(
                i => new
                {
                    CityID = i.CityID,
                    DisplayValue = string.Format(
                        "{0} ({1:dd MMMM yyyy})",
                        i.CityName, i.MeetingDate)
                }
            ).ToList();
        ViewData["MeetingId"] = new SelectList(meetingsQuery, "CityID", "DisplayValue", selectedMeetings);
    }
</code>```

View:

```<code><label>Meeting</label>
@Html.DropDownListFor(m => m.MeetingId, ViewData["MeetingId"] as SelectList,"---- Select ----", new { name = "meetingId", id = "meetingId"})
</code>```

答:
You must use onchange property in a new {} side of declaring class property like this example</p>

```
@Html.DropDownListFor(model => model.IpoId, new SelectList(Model.IpoList, "Value", "Text", Model.IpoId), "--انتخاب کنید--", new {@class = "chzn-select chzn-rtl", @onchange = "IpoFilterOnChange();" })
```

Body:
Is there any event available for Dropdownlist like onChange, etc. in MVC4? Do we have to use Javascript/jQuery in order to make some manipulations like DropwowlistSelectedItemChanged, etc? Or there is a way only using the Razor or MVC4 features?

On the other hand, could you please give me some examples how can I retrieve data and change a label's text with this data according to a Dropdownlist Selected Value? For example when selecting a City from Dropdownlist, I want to get an address data from database by using the selected city id and then show retrieved address on a label. I would be appreciated if you clarify me about the issue above and give me an example to achieve this.

Controller:

private void PopulateMeetingsDropDownList(object selectedMeetings = null)
    {
        var meetingsQuery = repository.Meetings
            .Join(repository.Cities, m => m.MeetingCityId, c => c.CityID,
                (m, c) => new
                {
                    CityID = c.CityID,
                    CityName = c.CityName,
                    MeetingDate = m.MeetingStartDate
                }
            )
            .OrderBy(x => x.CityID)
            .AsEnumerable()
            .Select(
                i => new
                {
                    CityID = i.CityID,
                    DisplayValue = string.Format(
                        "{0} ({1:dd MMMM yyyy})",
                        i.CityName, i.MeetingDate)
                }
            ).ToList();
        ViewData["MeetingId"] = new SelectList(meetingsQuery, "CityID", "DisplayValue", selectedMeetings);
    }

View:

Meeting
@Html.DropDownListFor(m => m.MeetingId, ViewData["MeetingId"] as SelectList,"---- Select ----", new { name = "meetingId", id = "meetingId"})

Body:
You must use onchange property in a new {} side of declaring class property like this example

@Html.DropDownListFor(model => model.IpoId, new SelectList(Model.IpoList, "Value", "Text", Model.IpoId), "--انتخاب کنید--", new {@class = "chzn-select chzn-rtl", @onchange = "IpoFilterOnChange();" })


问:
Only one match is returned after using (.|\s)*
String:

```<code>Person1(has(1, 1) has(2, 2)
    has(3, 3)
    had(4, 4) had(5, 5))
Person2(has(6, 6) had(7, 7))
</code>```

I'd like to select all contents in has() for Person1, i.e ['1, 1', '2, 2', '3, 3'].

I tried: has\((\d, \d)\)(.|\s)*Person2 with Global pattern flags, but only 1, 1 was returned.

答:
I think you may try this approach which i guess is dynamic and simple for all person. It splits and parse the string and push each desired array in a dictionary of Person.

Sample Source (run here):

```<code>import re

regex = r"has\(\s*(\d+)\s*,\s*(\d+)\s*\)"

dict={}
test_str = ("Person1(has(1, 1) has(2, 2)\n"
    "    has(3, 3) \n"
    "    had(4, 4) had(5, 5))\n"
    "Person2(had(6, 6) has(7, 7))\n"
    "Person3(had(6, 6) has(8, 8))")

res=re.split(r"(Person\d+)",test_str)
currentKey="";
for rs in res:
    if "Person" in rs:
        currentKey=rs;
    elif currentKey !="":
        matches = re.finditer(regex, rs, re.DOTALL)
        ar=[]
        for match in matches:
            ar.append(match.group(1)+","+match.group(2))
        dict[currentKey]=ar;
print(dict)
</code>```

output would be:

```<code>{'Person1': ['1,1', '2,2', '3,3'], 'Person2': ['7,7'], 'Person3': ['8,8']}
</code>```

Body:
String:

Person1(has(1, 1) has(2, 2)
    has(3, 3)
    had(4, 4) had(5, 5))
Person2(has(6, 6) had(7, 7))

I'd like to select all contents in has() for Person1, i.e ['1, 1', '2, 2', '3, 3'].

I tried: has\((\d, \d)\)(.|\s)*Person2 with Global pattern flags, but only 1, 1 was returned.

Body:
I think you may try this approach which i guess is dynamic and simple for all person. It splits and parse the string and push each desired array in a dictionary of Person.

Sample Source (run here):

import re

regex = r"has\(\s*(\d+)\s*,\s*(\d+)\s*\)"

dict={}
test_str = ("Person1(has(1, 1) has(2, 2)\n"
    "    has(3, 3) \n"
    "    had(4, 4) had(5, 5))\n"
    "Person2(had(6, 6) has(7, 7))\n"
    "Person3(had(6, 6) has(8, 8))")

res=re.split(r"(Person\d+)",test_str)
currentKey="";
for rs in res:
    if "Person" in rs:
        currentKey=rs;
    elif currentKey !="":
        matches = re.finditer(regex, rs, re.DOTALL)
        ar=[]
        for match in matches:
            ar.append(match.group(1)+","+match.group(2))
        dict[currentKey]=ar;
print(dict)

output would be:

{'Person1': ['1,1', '2,2', '3,3'], 'Person2': ['7,7'], 'Person3': ['8,8']}


问:
Sending email in java but shows that try to connect SMTP
I am trying to send email using JavaMail, but it does not work. Below is my code. Could anyone help me? Thanks in advance.

Here is my controller class responsible for sending email:

```<code>package com;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailService {
    private static MailService theService = null;
    private static Session mailSession;
    private static final String HOST = "localhost";
    private static final int PORT =465;
    private static final String USER = "rouaharonnie@gmail.com"; //
    private static final String PASSWORD = "admin"; //
    private static final String FROM = "rouaharonnie@gmail.com";
    public static void sendMessage(String recipient, String subject, String message) throws MessagingException {
        if (theService==null) {
            theService = new MailService();
        }
        MimeMessage mimeMessage = new MimeMessage(mailSession);

        mimeMessage.setFrom(new InternetAddress(FROM));
        mimeMessage.setSender(new InternetAddress(FROM));
        mimeMessage.setSubject(subject);
        mimeMessage.setContent(message, "text/plain");
        mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));

        Transport transport = mailSession.getTransport("smtps");
        transport.connect(HOST,PORT,USER,PASSWORD);
           // transport.connect();
        transport.sendMessage(mimeMessage, mimeMessage.getRecipients(Message.RecipientType.TO));
        transport.close();
    }

    private MailService() {
        Properties props = new Properties();

        props.put("mail.transport.protocol", "smtps");
        props.put("mail.smtps.host", HOST);
        props.put("mail.smtps.user", USER);
        props.put("mail.smtps.password", PASSWORD);
        props.put("mail.smtps.auth", "false");
        props.put("mail.smtp.from", FROM);
        props.put("mail.smtps.quitwait", "false");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.port",PORT);

        mailSession = Session.getDefaultInstance(props);
        mailSession.setDebug(true);
    }
}
</code>```

But it shows this error when I invoke sendMessage() method.

```<code>DEBUG: setDebug: JavaMail version 1.5.6
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle]
DEBUG SMTP: useEhlo true, useAuth false
DEBUG SMTP: trying to connect to host "localhost", port 465, isSSL true
</code>```

答: Try use 587 port and more one thing you must check turn off security in your mailbox and permit untrusted application access to your mailbox</p>

Body:
I am trying to send email using JavaMail, but it does not work. Below is my code. Could anyone help me? Thanks in advance.

Here is my controller class responsible for sending email:

package com;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailService {
    private static MailService theService = null;
    private static Session mailSession;
    private static final String HOST = "localhost";
    private static final int PORT =465;
    private static final String USER = "rouaharonnie@gmail.com"; //
    private static final String PASSWORD = "admin"; //
    private static final String FROM = "rouaharonnie@gmail.com";
    public static void sendMessage(String recipient, String subject, String message) throws MessagingException {
        if (theService==null) {
            theService = new MailService();
        }
        MimeMessage mimeMessage = new MimeMessage(mailSession);

        mimeMessage.setFrom(new InternetAddress(FROM));
        mimeMessage.setSender(new InternetAddress(FROM));
        mimeMessage.setSubject(subject);
        mimeMessage.setContent(message, "text/plain");
        mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));

        Transport transport = mailSession.getTransport("smtps");
        transport.connect(HOST,PORT,USER,PASSWORD);
           // transport.connect();
        transport.sendMessage(mimeMessage, mimeMessage.getRecipients(Message.RecipientType.TO));
        transport.close();
    }

    private MailService() {
        Properties props = new Properties();

        props.put("mail.transport.protocol", "smtps");
        props.put("mail.smtps.host", HOST);
        props.put("mail.smtps.user", USER);
        props.put("mail.smtps.password", PASSWORD);
        props.put("mail.smtps.auth", "false");
        props.put("mail.smtp.from", FROM);
        props.put("mail.smtps.quitwait", "false");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.port",PORT);

        mailSession = Session.getDefaultInstance(props);
        mailSession.setDebug(true);
    }
}

But it shows this error when I invoke sendMessage() method.

DEBUG: setDebug: JavaMail version 1.5.6
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle]
DEBUG SMTP: useEhlo true, useAuth false
DEBUG SMTP: trying to connect to host "localhost", port 465, isSSL true


问:
SQL Grouping and dense rank concept
I have a data set that looks like:

```<code> cust   city    hotel_id amount
 -------------------------------
   A    1        252    3160
   B    1        256    1893
   C    2        105    2188
   D    2        105    3054
   E    3        370    6107
   F    2        110    3160
   G    2        150    1893
   H    3        310    2188
   I    1        252    3160
   J    1        250    4000
   K    3        370    5000
   L    3        311    1095
</code>```

Query to display the top 3 hotels by revenue (Sum of amount) for each city?
Since same hotel can be booked by other customer in same city so we need to sum the amount to find total amount.

Expected output:

```<code>city    hotel_id    amount
---------------------------
  1       252        6320
  1       250        4000
  1       256        1893

  2       105        5242
  2       110        3160
  2       150        1893

  3       370       11107
  3       310        2188
  3       311        1095
</code>```

答:
To get the total sum for each hotel_id you need to group by that column first, then group by the city for syntax purposes. The #tmp table here should have all of the data you need, so then you just have to select the top 3 entries for each city from there.</p>

```<code>SELECT city, hotel_id, SUM(amount) AS 'total' INTO #tmp
FROM [table]
GROUP BY hotel_id, city

(SELECT TOP 3 *
FROM #tmp
WHERE city = 1)
UNION
(SELECT TOP 3 *
FROM #tmp
WHERE city = 2)
UNION
(SELECT TOP 3 *
FROM #tmp
WHERE city = 3)
</code>```

Title: SQL Grouping and dense rank concept

Body:
I have a data set that looks like:

 cust   city    hotel_id amount
 -------------------------------
   A    1        252    3160
   B    1        256    1893
   C    2        105    2188
   D    2        105    3054
   E    3        370    6107
   F    2        110    3160
   G    2        150    1893
   H    3        310    2188
   I    1        252    3160
   J    1        250    4000
   K    3        370    5000
   L    3        311    1095

Query to display the top 3 hotels by revenue (Sum of amount) for each city?
Since same hotel can be booked by other customer in same city so we need to sum the amount to find total amount.

Expected output:

city    hotel_id    amount
---------------------------
  1       252        6320
  1       250        4000
  1       256        1893

  2       105        5242
  2       110        3160
  2       150        1893

  3       370       11107
  3       310        2188
  3       311        1095

Body:
To get the total sum for each hotel_id you need to group by that column first, then group by the city for syntax purposes. The #tmp table here should have all of the data you need, so then you just have to select the top 3 entries for each city from there.

SELECT city, hotel_id, SUM(amount) AS 'total' INTO #tmp
FROM [table]
GROUP BY hotel_id, city

(SELECT TOP 3 *
FROM #tmp
WHERE city = 1)
UNION
(SELECT TOP 3 *
FROM #tmp
WHERE city = 2)
UNION
(SELECT TOP 3 *
FROM #tmp
WHERE city = 3)


问:
Pulling a dynamic key value from a JSON array search result query
I use Wikipedia API to search for Wiki articles. When I click the submit button I get an Array in JSON as a result :

```<code>0 {ns: 0, title: "Help", size: 3677, wordcount: 433, snippet: "<span class=\"searchmatch\">Help</span> is any form …mmand-line shells that invokes documentations and", …}

1 {ns: 0, title: "Online help", size: 7326, wordcount: 380, snippet: "(HTML), which includes HTML <span class=\"searchmat…earchmatch\">help</span> is also provided via live", …}

2 {ns: 0, title: "Help desk", size: 9491, wordcount: 1296, snippet: "A <span class=\"searchmatch\">help</span> desk is a …ated to a company's or institution's products and", …}

...
</code>```

I need to pull the value of the title and use it inside the HTML in a results list and at the same time put it inside the url so the user can click on a result and go to the corresponding page. (url:http://../[title])

The array is located in data.query.search

Since the results are dynamic I would probably need some kind of a for loop that will iterate through this array no matter how many results there are. I have tried with this for loop but it doesn't work.

```<code>console.log(data.query.search); //shows array in console
          data.query.search =""; //the location of JSON array
 for (i = 0; i < data.query.search["results"].length; i++) {
  data.query.search["results"][i]["title"];
  console.log("results");
}
</code>```

I suspect that I am not targeting the array elements,keys and values properly. I am grateful for any suggestion. Cheers.

答:
Here you go with a solution https://jsfiddle.net/oebq0ywj/

var data = { query: { search: [
  {ns: 0, title: "Help", size: 3677, wordcount: 433},
  {ns: 0, title: "Online help", size: 7326, wordcount: 380},
  {ns: 0, title: "Help desk", size: 9491, wordcount: 1296}
]}};

for(var i in data.query.search) {
 console.log(data.query.search[i].title);
}```

Body:
I use Wikipedia API to search for Wiki articles. When I click the submit button I get an Array in JSON as a result :

0 {ns: 0, title: "Help", size: 3677, wordcount: 433, snippet: "Help is any form …mmand-line shells that invokes documentations and", …}

1 {ns: 0, title: "Online help", size: 7326, wordcount: 380, snippet: "(HTML), which includes HTML help is also provided via live", …}

2 {ns: 0, title: "Help desk", size: 9491, wordcount: 1296, snippet: "A help desk is a …ated to a company's or institution's products and", …}

...

I need to pull the value of the title and use it inside the HTML in a results list and at the same time put it inside the url so the user can click on a result and go to the corresponding page. (url:http://../[title])

The array is located in data.query.search

Since the results are dynamic I would probably need some kind of a for loop that will iterate through this array no matter how many results there are. I have tried with this for loop but it doesn't work.

console.log(data.query.search); //shows array in console
          data.query.search =""; //the location of JSON array
 for (i = 0; i < data.query.search["results"].length; i++) {
  data.query.search["results"][i]["title"];
  console.log("results");
}

I suspect that I am not targeting the array elements,keys and values properly. I am grateful for any suggestion. Cheers.


问:
Import RTF with images in xbap
I need to import a RTF document into a FlowDocument for further parsing.. But I have a very strange problem:

```<code>public string ConvertRTF(byte[] bytes)
{
    if (bytes == null)
    {
        throw new ArgumentNullException();
    }

    FlowDocument document = new FlowDocument();

    // open the file for reading
    using (MemoryStream stream = new MemoryStream(bytes, true))
    {
        // create a TextRange around the entire document
        TextRange documentTextRange = new TextRange(document.ContentStart, document.ContentEnd);
        if (documentTextRange.CanLoad(DataFormats.Rtf))
            documentTextRange.Load(stream, DataFormats.Rtf);
    }

    return XamlWriter.Save(document);

}
</code>```

I have tested this method in three different projects:

Wpf stand alone app: gives me no problems what so ever, but alas, I cannot use this kind of application.

Console app: it often works, but it breaks on the documents with image from time to time, and I cannot get my finger around when it breaks and why... The error I am receiving is on the Load method of TextRange: "Unrecognized structure in data format 'Rich Text Format'. Parameter name: stream"

Xbap application: Does not even get past the CanLoad method... :( So gives me jack whathisname as a result...

The stange thing is, that when I test it with the console app it works without errors in the following construction:

```<code>[STAThread]
static void Main(string[] args)
{
    OpenFileDialog dialog = new OpenFileDialog
    {
        Filter = "import files (*.rtf)|*.rtf"
    };

    if (dialog.ShowDialog() != DialogResult.OK)
        return;

    byte[] data;
    using (Stream filestream = dialog.OpenFile())
    {
        int offset = 0;
        data = new byte[filestream.Length];
        int remaining = data.Length;
        while (remaining > 0)
        {
            int read = filestream.Read(data, offset, remaining);
            if (read <= 0)
                throw new EndOfStreamException
                    (String.Format("End of stream reached with {0} bytes left to read", remaining));
            remaining -= read;
            offset += read;
        }
    }

    FlowDocument document = new FlowDocument();

    using (MemoryStream stream = new MemoryStream(data))
    {
        // create a TextRange around the entire document
        TextRange documentTextRange = new TextRange(document.ContentStart, document.ContentEnd);
        documentTextRange.Load(stream, DataFormats.Rtf);
    }

    Console.WriteLine("test ok");
}
</code>```

Which just make me clueless, because that is exactly what I am doing but then phased in two steps... first retrieve the bits, then use the memorystream to make it into a RTF... :(

Can it be that there might be a conflict in some dll version somehow? We are using 3.5 SP1 for our project...

Can someone help me find a solution for one of last two posibilities mentioned above?

Thanks

答:
Cannot be done apparently.

What we ended up with is sending the rtf to the server who has more privileges, and send the result back to the client. Nasty, but it works.

OwnerDisplayName: Arcturus

Title: Import RTF with images in xbap

Body:
I need to import a RTF document into a FlowDocument for further parsing.. But I have a very strange problem:

public string ConvertRTF(byte[] bytes)
{
    if (bytes == null)
    {
        throw new ArgumentNullException();
    }

    FlowDocument document = new FlowDocument();

    // open the file for reading
    using (MemoryStream stream = new MemoryStream(bytes, true))
    {
        // create a TextRange around the entire document
        TextRange documentTextRange = new TextRange(document.ContentStart, document.ContentEnd);
        if (documentTextRange.CanLoad(DataFormats.Rtf))
            documentTextRange.Load(stream, DataFormats.Rtf);
    }

    return XamlWriter.Save(document);

}

I have tested this method in three different projects:

Wpf stand alone app: gives me no problems what so ever, but alas, I cannot use this kind of application.

Console app: it often works, but it breaks on the documents with image from time to time, and I cannot get my finger around when it breaks and why... The error I am receiving is on the Load method of TextRange: "Unrecognized structure in data format 'Rich Text Format'. Parameter name: stream"

Xbap application: Does not even get past the CanLoad method... :( So gives me jack whathisname as a result...

The stange thing is, that when I test it with the console app it works without errors in the following construction:

[STAThread]
static void Main(string[] args)
{
    OpenFileDialog dialog = new OpenFileDialog
    {
        Filter = "import files (*.rtf)|*.rtf"
    };

    if (dialog.ShowDialog() != DialogResult.OK)
        return;

    byte[] data;
    using (Stream filestream = dialog.OpenFile())
    {
        int offset = 0;
        data = new byte[filestream.Length];
        int remaining = data.Length;
        while (remaining > 0)
        {
            int read = filestream.Read(data, offset, remaining);
            if (read <= 0)
                throw new EndOfStreamException
                    (String.Format("End of stream reached with {0} bytes left to read", remaining));
            remaining -= read;
            offset += read;
        }
    }

    FlowDocument document = new FlowDocument();

    using (MemoryStream stream = new MemoryStream(data))
    {
        // create a TextRange around the entire document
        TextRange documentTextRange = new TextRange(document.ContentStart, document.ContentEnd);
        documentTextRange.Load(stream, DataFormats.Rtf);
    }

    Console.WriteLine("test ok");
}

Which just make me clueless, because that is exactly what I am doing but then phased in two steps... first retrieve the bits, then use the memorystream to make it into a RTF... :(

Can it be that there might be a conflict in some dll version somehow? We are using 3.5 SP1 for our project...

Can someone help me find a solution for one of last two posibilities mentioned above?

Thanks

LastEditorDisplayName: Arcturus


问:
DispatchQueue sync block vs async block
Assume I have the following DispatchQueue:

```<code>let myqueue = DispatchQueue(label: "myqueue")
</code>```

What is the difference between async block and sync block? Can someone explain what it means?

e.g In the main thread, in the middle execution of the main thread. What will it happen if I call myqueue.async{...} or myqueue.sync{...}

e.g

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    myqueue.async{...}

    myqueue.sync{...}
}
</code>```

答:
I don't know why my question above is being voted down. as @rmaddy mentioned, the Apple doc for async and sync are unless.

Anyways, I did experiment tested myself for question. So I am going to post my answer here.

What is the difference between async block and sync block? Can someone explain what it means?

Answer: For the code in the async, the line just below the async block will be executed immediately after the dispatchQueue finishes its dispatch job, i.e there are no blocking / waiting for the completion of the async block.
On the other hand, for the sync block, the line just below the sync block will be blocked and waiting for the completion of the sync block. Hence, in such case, the sequence of the execution of the code are ensured to be run in one line by one line sequentially.

e.g In the main thread, in the middle execution of the main thread. What will it happen if I call myqueue.async{...} or myqueue.sync{...}?

Answer: myqueue is just a queue. So the elements(dispatched code blocks/jobs/tasks/actions named whatever you like) can be running the main thread or not in the main thread. If we call myqueue.async{...} in the main thread, the dispatched code block will not run in the main thread and will dispatch to another thread for its execution. If we call myqueue.sync{...} in the main thread, the code block will just like a normal code statement so the line just after it will be blocked until the code block is finished and the execution of the them are all happening in the main thread.

For example, since viewDidLoad is always being run in the main thread, if we call myqueue.async{...} inside viewDidLoad, the {...} block will be dispatched to another thread to be executed and the line just below it won't wait for its completion and the execution won't blocked. If we call myqueue.sync{...}, the {...} block will happen in the main thread. So the line just below the block will just wait for completion of the block.

Title: DispatchQueue sync block vs async block

Body:
Assume I have the following DispatchQueue:

let myqueue = DispatchQueue(label: "myqueue")

What is the difference between async block and sync block? Can someone explain what it means?

e.g In the main thread, in the middle execution of the main thread. What will it happen if I call myqueue.async{...} or myqueue.sync{...}

e.g

override func viewDidLoad() {
    super.viewDidLoad()

    myqueue.async{...}

    myqueue.sync{...}
}


问:
CoreData and tableview
How can a tableview (in another view controller) read this data from first view controller?

Should I put this into array or something? This is code for retrieving saved data, I already managed to save data.

```<code>do {
    let request = NSFetchRequest(entityName: "Users")
    let results = try context.executeFetchRequest(request)
    if results.count > 0 {
        for item in results as! [NSManagedObject] {
            let name = item.valueForKey("username")
            let password = item.valueForKey("passwords")
            print(name!, password!)
            array.append (name, password) // this do not work, can't put that in array so tableview can read array in another vc.
        }
    }
}
</code>```

When I put name and password objects in array it says:

Cannot convert any object to array string

How can I retrieve core data to array so tableview can read from array, or should it read from coredata directly?

答:
If you want to share data from VC A to VC B, you should use segue method and the display data in the tableView.
Segue method

```<code>self.performSegue(withIdentifier: "identifier", sender: nil)
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "identifier" {
        let destination = segue.destination as! AlreadyStartViewController
        destination.variable = variable /*and other*/
    }
}
</code>```

And then display data in the tableView
If you want to ask me about code - ask

Title: CoreData and tableview

Body:
How can a tableview (in another view controller) read this data from first view controller?

Should I put this into array or something? This is code for retrieving saved data, I already managed to save data.

do {
    let request = NSFetchRequest(entityName: "Users")
    let results = try context.executeFetchRequest(request)
    if results.count > 0 {
        for item in results as! [NSManagedObject] {
            let name = item.valueForKey("username")
            let password = item.valueForKey("passwords")
            print(name!, password!)
            array.append (name, password) // this do not work, can't put that in array so tableview can read array in another vc.
        }
    }
}

When I put name and password objects in array it says:

Cannot convert any object to array string

How can I retrieve core data to array so tableview can read from array, or should it read from coredata directly?

Body:
If you want to share data from VC A to VC B, you should use segue method and the display data in the tableView.
Segue method

self.performSegue(withIdentifier: "identifier", sender: nil)
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "identifier" {
        let destination = segue.destination as! AlreadyStartViewController
        destination.variable = variable /*and other*/
    }
}

And then display data in the tableView
If you want to ask me about code - ask


问:
Move a project to an exsisting Repo
I have a project i have been working on for about a year. I kept the project on git, and committed often so it has a lot of history and a lot of previous data but the original local file has been corrupted. I downloaded the latest version of my project from Github. I want to move this new local project to the existing repo and keep all of its history, how could I do this?</p>

答:
If I am understanding you correct, you are having a local version of repository and a remote one. And both of them have different commit history. Now you want to move files of the remote repository to local repository but preserve the history of local git repository.

History and all the information of a repository is found in .git folder which is hidden. If you don't want to bring the history to local git folder, and just want to update files, you can clone to another place, then copy required content to local folder and not touching .git folder.

After that using git status will tell you which files have been changed. This will not affect the commit history of your local git repo.

Title: Move a project to an exsisting Repo


问:
C recursive program to find the maximum element from array
So I have a task in my training that sounds like this:
Write a subprogram that will recursively find the maximum element from an array and also write the main function to call it.
What I failed to fully understand is what recursion is. I wanted to ask you guys if my code is recursive or not. And if not what changes should I make/ what recursion really means?

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

int find_maximum(int[], int);

int main() {
  int c, array[100], size, location, maximum;

  printf("Input number of elements in array\n");
  scanf("%d", &size);

  printf("Enter %d integers\n", size);

  for (c = 0; c < size; c++)
    scanf("%d", &array[c]);

  location = find_maximum(array, size);
  maximum  = array[location];

  printf("Maximum element location = %d and value = %d.\n", location + 1, maximum);
  return 0;
}

int find_maximum(int a[], int n) {
  int c, max, index;

  max = a[0];
  index = 0;

  for (c = 1; c < n; c++) {
    if (a[c] > max) {
       index = c;
       max = a[c];
    }
  }

  return index;
}
</code>```

Thank you all for your time!

答:
NO it is not recursive function

to know about recursion this link is very useful https://www.khanacademy.org/computing/computer-science/algorithms/recursive-algorithms/a/recursion/

to make a recursion function to solve your problem try this

you can try this pseudo code declare your array global and a max=0 global and size global

```<code>int find_maximum(int i)
{
if (i == size )
    return max;
else if ( max < array[i])
    max =array [i];
return find_maximum(i+1);
}
</code>```

where i is the array index

Body:
So I have a task in my training that sounds like this:
Write a subprogram that will recursively find the maximum element from an array and also write the main function to call it.
What I failed to fully understand is what recursion is. I wanted to ask you guys if my code is recursive or not. And if not what changes should I make/ what recursion really means?

#include <stdio.h>

int find_maximum(int[], int);

int main() {
  int c, array[100], size, location, maximum;

  printf("Input number of elements in array\n");
  scanf("%d", &size);

  printf("Enter %d integers\n", size);

  for (c = 0; c < size; c++)
    scanf("%d", &array[c]);

  location = find_maximum(array, size);
  maximum  = array[location];

  printf("Maximum element location = %d and value = %d.\n", location + 1, maximum);
  return 0;
}

int find_maximum(int a[], int n) {
  int c, max, index;

  max = a[0];
  index = 0;

  for (c = 1; c < n; c++) {
    if (a[c] > max) {
       index = c;
       max = a[c];
    }
  }

  return index;
}

Thank you all for your time!

Body:
NO it is not recursive function

to know about recursion this link is very useful https://www.khanacademy.org/computing/computer-science/algorithms/recursive-algorithms/a/recursion/

to make a recursion function to solve your problem try this

you can try this pseudo code declare your array global and a max=0 global and size global

int find_maximum(int i)
{
if (i == size )
    return max;
else if ( max < array[i])
    max =array [i];
return find_maximum(i+1);
}

where i is the array index


问:
Show No Internet Connection Message Like Instagram
I was wondering how can i show a 'No Internet Connection' Just how like Instagram does it,

As an Example :

That see-through custom message animating to show under the navigationController . Would really love to get this to my project ,
thank you for you help

答:
So here's a pic of the storyboard like this :-

"No internet connection" is a label, and the red view underneath is just to test the see through property of the label. If you are designing the UI in code, you can probably make a label similar to mine and place it to the top of the Navigation bar by using it's frame property.

The button here I'm using is just to show the label pop up on the scene (since it's just a demo answer). In your case, if the internet is not available, you will proceed to show the pop up.

So if you are making the UI in code, make sure to make the label in the viewDidLoad method. I have made an IBOutlet and the viewDidLoad now looks like this:-

```<code>override func viewDidLoad() {
        super.viewDidLoad()

        let transform = CGAffineTransform(translationX: 0, y: -label.frame.height)
        label.alpha = 0
        label.transform = transform
    }
</code>```

On the view loading, I'm moving the label behind the navigation bar, using CGAffineTransform. The distance, how much to move up is the label's height, since we don't want any part to be clipped on the scene.

Next step, is just a fix. I'm making alpha = 0, because navBar is translucent is nature and hence will change it's colour, since our label is behind it. So setting alpha to 0, takes care of it, and in third step apply the transform.

Now, if the internet connection is not available, we should pop out the label under the navBar. The code will look something like this:-

```<code>fun checkInternet() {
// called by some of your observer, which checks for changes in internet connection

    if !isInternetAvailable {

       UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.3, initialSpringVelocity: 0, options: .curveLinear, animations: {

        self.label.alpha = 0.5
        self.label.transform = .identity
    }, completion: nil)
     }
}
</code>```

So here, I'll show the pop up with an animation using UIView.animate with some spring damping, so it has a nice bouncy effect to it. I'm setting the alpha to 0.5, since you mentioned you want a see through label, and I'm setting the label to a transform which will bring it back to it's original position when it was created, that's why I'm using .identity.
You can play around usingSpringWithDamping values and change options to have different effects.

Body:
So here's a pic of the storyboard like this :-

"No internet connection" is a label, and the red view underneath is just to test the see through property of the label. If you are designing the UI in code, you can probably make a label similar to mine and place it to the top of the Navigation bar by using it's frame property.

The button here I'm using is just to show the label pop up on the scene (since it's just a demo answer). In your case, if the internet is not available, you will proceed to show the pop up.

So if you are making the UI in code, make sure to make the label in the viewDidLoad method. I have made an IBOutlet and the viewDidLoad now looks like this:-

override func viewDidLoad() {
        super.viewDidLoad()

        let transform = CGAffineTransform(translationX: 0, y: -label.frame.height)
        label.alpha = 0
        label.transform = transform
    }

On the view loading, I'm moving the label behind the navigation bar, using CGAffineTransform. The distance, how much to move up is the label's height, since we don't want any part to be clipped on the scene.

Next step, is just a fix. I'm making alpha = 0, because navBar is translucent is nature and hence will change it's colour, since our label is behind it. So setting alpha to 0, takes care of it, and in third step apply the transform.

Now, if the internet connection is not available, we should pop out the label under the navBar. The code will look something like this:-

fun checkInternet() {
// called by some of your observer, which checks for changes in internet connection

    if !isInternetAvailable {

       UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.3, initialSpringVelocity: 0, options: .curveLinear, animations: {

        self.label.alpha = 0.5
        self.label.transform = .identity
    }, completion: nil)
     }
}

So here, I'll show the pop up with an animation using UIView.animate with some spring damping, so it has a nice bouncy effect to it. I'm setting the alpha to 0.5, since you mentioned you want a see through label, and I'm setting the label to a transform which will bring it back to it's original position when it was created, that's why I'm using .identity.
You can play around usingSpringWithDamping values and change options to have different effects.


问:
Is there a way I can get an Enum value by its number in the sequence?
I have this enum:

```<code>public enum PTI
{
    UserInput = 0,
    Five = 5,
    Ten = 10,
    Fifteen = 15
}

public static partial class Extensions
{
    public static string Text(this PTI time)
    {
        switch (time)
        {
            case PTI.UserInput: return "User Input";
            case PTI.Ten: return "10 seconds";
            case PTI.Five: return "5 seconds";
            case PTI.Fifteen: return "15 seconds";
        }
        return "";
    }
}
</code>```

It's a simple case but I am using it as an example. In my code I need to pass the value of the enum to a function so I came up with this:

```<code>if (selectedIndex == 1) App.DB.UpdateSetting(Settings.Pti, PTI.UserInput);
if (selectedIndex == 2) App.DB.UpdateSetting(Settings.Pti, PTI.Five);
if (selectedIndex == 3) App.DB.UpdateSetting(Settings.Pti, PTI.Ten);
if (selectedIndex == 4) App.DB.UpdateSetting(Settings.Pti, PTI.Fifteen);
</code>```

It's not ideal.  Maybe a Case would help here but my point is that all I get is a number from 1 to 4 and from this I need to get the ENUM value.

Is there some way that I could get the ENUM value from the value of selectedIndex without an if or case construct?

Background - Here's where the value of selectedIndex comes from. It's from a picker in a Xamarin Form XAML

```<code><Picker x:Name="ptiPicker" IsVisible="false" SelectedIndexChanged="ptiOnPickerSelectedIndexChanged">
                                            <Picker.Items>
                                                <x:String>User input</x:String>
                                                <x:String>5 seconds</x:String>
                                                <x:String>10 seconds</x:String>
                                                <x:String>15 seconds</x:String>
                                            </Picker.Items>
                                        </Picker>
</code>```

Note:

If it was possible I would be happy to add some extension method to the enum if that would help get what I needed. Just not sure how to do that.

答:
You can cast your int with PTI like in this program

```<code>public class Program
{
    public static void Main(string[] args)
    {

        //Your code goes here
        Console.WriteLine(""+(PTI)2);
        Console.WriteLine(""+(PTI)5);
    }
}

public enum PTI
{
    UserInput = 0,
    Five = 5,
    Ten = 10,
    Fifteen = 15
}
</code>```

If the integer has a valid value existing in the enum you get the enum, if not you will get the integer unchanged as the result of the program above shows below:

```<code>2
Five
</code>```

Body:
I have this enum:

public enum PTI
{
    UserInput = 0,
    Five = 5,
    Ten = 10,
    Fifteen = 15
}

public static partial class Extensions
{
    public static string Text(this PTI time)
    {
        switch (time)
        {
            case PTI.UserInput: return "User Input";
            case PTI.Ten: return "10 seconds";
            case PTI.Five: return "5 seconds";
            case PTI.Fifteen: return "15 seconds";
        }
        return "";
    }
}

It's a simple case but I am using it as an example. In my code I need to pass the value of the enum to a function so I came up with this:

if (selectedIndex == 1) App.DB.UpdateSetting(Settings.Pti, PTI.UserInput);
if (selectedIndex == 2) App.DB.UpdateSetting(Settings.Pti, PTI.Five);
if (selectedIndex == 3) App.DB.UpdateSetting(Settings.Pti, PTI.Ten);
if (selectedIndex == 4) App.DB.UpdateSetting(Settings.Pti, PTI.Fifteen);

It's not ideal.  Maybe a Case would help here but my point is that all I get is a number from 1 to 4 and from this I need to get the ENUM value.

Is there some way that I could get the ENUM value from the value of selectedIndex without an if or case construct?

Background - Here's where the value of selectedIndex comes from. It's from a picker in a Xamarin Form XAML

<Picker x:Name="ptiPicker" IsVisible="false" SelectedIndexChanged="ptiOnPickerSelectedIndexChanged">
                                            <Picker.Items>
                                                <x:String>User input</x:String>
                                                <x:String>5 seconds</x:String>
                                                <x:String>10 seconds</x:String>
                                                <x:String>15 seconds</x:String>
                                            </Picker.Items>
                                        </Picker>

Note:

If it was possible I would be happy to add some extension method to the enum if that would help get what I needed. Just not sure how to do that.

Body:
You can cast your int with PTI like in this program

public class Program
{
    public static void Main(string[] args)
    {

        //Your code goes here
        Console.WriteLine(""+(PTI)2);
        Console.WriteLine(""+(PTI)5);
    }
}

public enum PTI
{
    UserInput = 0,
    Five = 5,
    Ten = 10,
    Fifteen = 15
}

If the integer has a valid value existing in the enum you get the enum, if not you will get the integer unchanged as the result of the program above shows below:

2
Five


问:
SQL Server Stored Procedure Optimization
I have the following stored procedure running against an ExtractedMessages table which might contain up to 100M records (100,000,000).

For the purpose of my application, this stored procedure should run in less than one second

```<code>CREATE PROCEDURE GetNextMessages
    @taskId bigint
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @ci INT
    DECLARE @cr INT

    SELECT
        @ci = CurrentIndex, @cr = CurrentResources
    FROM
        ExtractedTasks
    WHERE
        Id = @taskId

    UPDATE ExtractedTasks
    SET CurrentIndex = @ci + @cr
    WHERE Id = @taskId

    SELECT *
    FROM ExtractedMessages
    WHERE TaskId = @taskId
    ORDER BY Id
        OFFSET @ci ROWS
        FETCH NEXT @cr ROWS ONLY
END
</code>```

NB: cr can not be more than 1500

答:
Instead of querying your table twice you could do the following:

```<code>DECLARE @ci INT
DECLARE @cr INT

DECLARE @T TABLE (
    ci INT
    , cr INT
    );

UPDATE ExtractedTasks
SET CurrentIndex = CurrentIndex + CurrentResources
OUTPUT DELETED.CurrentIndex, DELETED.CurrentResources
INTO @T (ci, cr)
WHERE Id = @taskId;

SELECT
    @ci = ci, @cr = cr
FROM
    @T

SELECT *
FROM ExtractedMessages
WHERE TaskId = @taskId
ORDER BY Id
    OFFSET @ci ROWS
    FETCH NEXT @cr  ROWS ONLY
</code>```

The key here is OUTPUT clause. It's going to insert deleted records (pre-update values) into a table variable. Which means you replace multiple selects from a table with one. Other than correct indexes I don't see anything for improvement.

Also, make sure you select just the columns you need, not everything. It's generally a good practice to list exact columns you need.

Body:
I have the following stored procedure running against an ExtractedMessages table which might contain up to 100M records (100,000,000).

For the purpose of my application, this stored procedure should run in less than one second

CREATE PROCEDURE GetNextMessages
    @taskId bigint
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @ci INT
    DECLARE @cr INT

    SELECT
        @ci = CurrentIndex, @cr = CurrentResources
    FROM
        ExtractedTasks
    WHERE
        Id = @taskId

    UPDATE ExtractedTasks
    SET CurrentIndex = @ci + @cr
    WHERE Id = @taskId

    SELECT *
    FROM ExtractedMessages
    WHERE TaskId = @taskId
    ORDER BY Id
        OFFSET @ci ROWS
        FETCH NEXT @cr ROWS ONLY
END

NB: cr can not be more than 1500

Body:
Instead of querying your table twice you could do the following:

DECLARE @ci INT
DECLARE @cr INT

DECLARE @T TABLE (
    ci INT
    , cr INT
    );

UPDATE ExtractedTasks
SET CurrentIndex = CurrentIndex + CurrentResources
OUTPUT DELETED.CurrentIndex, DELETED.CurrentResources
INTO @T (ci, cr)
WHERE Id = @taskId;

SELECT
    @ci = ci, @cr = cr
FROM
    @T

SELECT *
FROM ExtractedMessages
WHERE TaskId = @taskId
ORDER BY Id
    OFFSET @ci ROWS
    FETCH NEXT @cr  ROWS ONLY

The key here is OUTPUT clause. It's going to insert deleted records (pre-update values) into a table variable. Which means you replace multiple selects from a table with one. Other than correct indexes I don't see anything for improvement.

Also, make sure you select just the columns you need, not everything. It's generally a good practice to list exact columns you need.


问:
Auto detect rotation and rotate video accordingly with mencoder, handbrake cli or ffmpeg
I have found questions on rotating videos with mencoder and ffmpeg however I am after a fully automated solution.

Can anybody help with this.

I want to

Detect the video orientation

Rotate if needed

Reset the meta data on the video (otherwise watching on a iOS device will cause unwanted rotation)

Save video in desired format

The reason for this is a wish to use the processed videos in a HTML5 video player. If I rotate without resetting the meta data iOS devices will read the meta and further rotate causing the video to be out by another 90 degrees.

答:
I use a little script and HandBrakeCLI for this.

Attention, the "--rotate" parameter has changed with HandBrake 1.0, this will work with 1.0.7:

```<code>for i in *.mp4
do
  r=$(exiftool -Rotation $i | cut -d ":" -f2 | sed 's/^[ ]*//')
  HandBrakeCLI -i $i -o ./out/$i --rotate=angle=$r -e x264 -q 21 -X 1000
done
</code>```

Body:
I use a little script and HandBrakeCLI for this.

Attention, the "--rotate" parameter has changed with HandBrake 1.0, this will work with 1.0.7:

for i in *.mp4
do
  r=$(exiftool -Rotation $i | cut -d ":" -f2 | sed 's/^[ ]*//')
  HandBrakeCLI -i $i -o ./out/$i --rotate=angle=$r -e x264 -q 21 -X 1000
done


问:
Storing an unknown function from another class to execute later on itself
I have a class that parameters there can change, i'm creating a class that sorts groups of the first class, by the given parameter it needed to be sorted by.

```<code>class class1
{
   private int p1;
   private int p2;
 //and etc depending on the need of it
}
</code>```

for each parameter there is a get function.

i tried to do the following:

```<code>class class2<T>
{
   private Func<T> getValue;
   public class2(Func<T> getValue)
   {
       this.getValue = getValue;
   }

 public void Add(class1 cs)
 {
     //here is where i want to execute getValue on cs itself to compare them to one another.
 }
}
</code>```

I have tried doing the following in the main class:

```<code>  class Program
    {
        static void Main(string[] args)
        {
            class1 c1 = new class1(1, 2);
            class2<int> c2 = new class2<int>(c1.getp1)
        }
    }
</code>```

but it only stores the the function for c1, and i cant execute it as i need it.

Is there a way to do it?
Thanks ahead for the help and sorry for the dumb explanation.

答:
Your question is a little confusing, but I think what you want is this:</p>

```<code>class class1
    {
        private int _p1;
        private int _p2;
        //and etc depending on the need of it

        public class1(int p1, int p2)
        {
            _p1 = p1;
            _p2 = p2;
        }

        public int getp1()
        {
            return 1;
        }
    }

    class class2<T>
    {
        private Func<T> getValue;

        public class2(Func<T> getValue)
        {
            this.getValue = getValue;
        }

        public void Add(class1 cs)
        {
            //here is where i want to execute getValue on cs itself to compare them to one another.
            getValue();
        }
    }

class Program
        {
        static void Main(string[] args)
        {
            class1 c1 = new class1(1, 2);
            Func<int> getp1 = c1.getp1;
            class2<int> c2 = new class2<int>(getp1);
            c2.Add(c1);
        }
    }
</code>```

Body:
I have a class that parameters there can change, i'm creating a class that sorts groups of the first class, by the given parameter it needed to be sorted by.

class class1
{
   private int p1;
   private int p2;
 //and etc depending on the need of it
}

for each parameter there is a get function.

i tried to do the following:

class class2<T>
{
   private Func<T> getValue;
   public class2(Func<T> getValue)
   {
       this.getValue = getValue;
   }

 public void Add(class1 cs)
 {
     //here is where i want to execute getValue on cs itself to compare them to one another.
 }
}

I have tried doing the following in the main class:

  class Program
    {
        static void Main(string[] args)
        {
            class1 c1 = new class1(1, 2);
            class2<int> c2 = new class2<int>(c1.getp1)
        }
    }

but it only stores the the function for c1, and i cant execute it as i need it.

Is there a way to do it?
Thanks ahead for the help and sorry for the dumb explanation.

Body:
Your question is a little confusing, but I think what you want is this:

class class1
    {
        private int _p1;
        private int _p2;
        //and etc depending on the need of it

        public class1(int p1, int p2)
        {
            _p1 = p1;
            _p2 = p2;
        }

        public int getp1()
        {
            return 1;
        }
    }

    class class2<T>
    {
        private Func<T> getValue;

        public class2(Func<T> getValue)
        {
            this.getValue = getValue;
        }

        public void Add(class1 cs)
        {
            //here is where i want to execute getValue on cs itself to compare them to one another.
            getValue();
        }
    }

class Program
        {
        static void Main(string[] args)
        {
            class1 c1 = new class1(1, 2);
            Func<int> getp1 = c1.getp1;
            class2<int> c2 = new class2<int>(getp1);
            c2.Add(c1);
        }
    }