问:
Kotlin: workaround for no lateinit when using custom setter?
In my activity I have a field that should be non-nullable and has a custom setter. I want to initialize the field in my onCreate method so I added lateinit to my variable declaration. But, apparently you cannot do that (at the moment): https://discuss.kotlinlang.org/t/lateinit-modifier-is-not-allowed-on-custom-setter/1999.

These are the workarounds I can see:

Do it the Java way. Make the field nullable and initialize it with null. I don't want to do that.

Initialize the field with a "default instance" of the type. That's what I currently do. But that would be too expensive for some types.

Can someone recommend a better way (that does not involve removing the custom setter)?

答:
This can be achieved by using a backing property (as per Pavlus's answer); however, I prefer to wrap it inside a delegate to avoid exposing it outside of the property's context:

```<code>open class LateInit<T: Any> : ReadWriteProperty<Any?, T> {
    protected lateinit var field: T

    final override fun getValue(thisRef: Any?, property: KProperty<*>) = get()
    final override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) = set(value)

    open fun get() = field
    open fun set(value: T) { field = value }
}
</code>```

This provides standard getters and setters that can be overridden with a custom implementation:

```<code>var upperCaseString by object : LateInit<String>() {
    override fun set(value: String) {
        field = value.toUpperCase()
    }
}
</code>```

However, since this implementation requires extending the delegate, the generic type cannot be inferred from the property type. This can overcome by taking the custom getter and setter as parameters:

```<code>class LateInit<T: Any>(private val getter: FieldHolder<T>.() -> T = { field },
                       private val setter: FieldHolder<T>.(T) -> Unit = { field = it }) :
        ReadWriteProperty<Any?, T> {
    private val fieldHolder = FieldHolder<T>()

    override fun getValue(thisRef: Any?, property: KProperty<*>) = fieldHolder.getter()
    override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) =
            fieldHolder.setter(value)

    class FieldHolder<T: Any> {
        lateinit var field: T
    }
}
</code>```

Which can then be used like this:

```<code>private var upperCaseString: String by LateInit(setter = { field = it.toUpperCase() })
</code>```

Body:
This can be achieved by using a backing property (as per Pavlus's answer); however, I prefer to wrap it inside a delegate to avoid exposing it outside of the property's context:

open class LateInit<T: Any> : ReadWriteProperty<Any?, T> {
    protected lateinit var field: T

    final override fun getValue(thisRef: Any?, property: KProperty<*>) = get()
    final override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) = set(value)

    open fun get() = field
    open fun set(value: T) { field = value }
}

This provides standard getters and setters that can be overridden with a custom implementation:

var upperCaseString by object : LateInit<String>() {
    override fun set(value: String) {
        field = value.toUpperCase()
    }
}

However, since this implementation requires extending the delegate, the generic type cannot be inferred from the property type. This can overcome by taking the custom getter and setter as parameters:

class LateInit<T: Any>(private val getter: FieldHolder<T>.() -> T = { field },
                       private val setter: FieldHolder<T>.(T) -> Unit = { field = it }) :
        ReadWriteProperty<Any?, T> {
    private val fieldHolder = FieldHolder<T>()

    override fun getValue(thisRef: Any?, property: KProperty<*>) = fieldHolder.getter()
    override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) =
            fieldHolder.setter(value)

    class FieldHolder<T: Any> {
        lateinit var field: T
    }
}

Which can then be used like this:

private var upperCaseString: String by LateInit(setter = { field = it.toUpperCase() })


来源: stackexchange

问:
How to hide soft keyboard on android after clicking outside EditText?
Ok everyone knows that to hide a keyboard you need to implement:

```<code>InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
</code>```

But the big deal here is how to hide the keyboard when the user touches or selects any other place that is not an EditText or the softKeyboard?

I tried to use the onTouchEvent() on my parent Activity but that only works if user touches outside any other view and there is no scrollview.

I tried to implement a touch, click, focus listener without any success.

I even tried to implement my own scrollview to intercept touch events but I can only get the coordinates of the event and not the view clicked.

Is there a standard way to do this?? in iPhone it was really easy.

答:
Just Add this code in the class
 @Overide</p>

```<code>public boolean dispatchTouchEvent(MotionEvent ev) {
    View view = getCurrentFocus();
    if (view != null && (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_MOVE) && view instanceof EditText && !view.getClass().getName().startsWith("android.webkit.")) {
        int scrcoords[] = new int[2];
        view.getLocationOnScreen(scrcoords);
        float x = ev.getRawX() + view.getLeft() - scrcoords[0];
        float y = ev.getRawY() + view.getTop() - scrcoords[1];
        if (x < view.getLeft() || x > view.getRight() || y < view.getTop() || y > view.getBottom())
            ((InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow((this.getWindow().getDecorView().getApplicationWindowToken()), 0);
    }
    return super.dispatchTouchEvent(ev);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Ok everyone knows that to hide a keyboard you need to implement:

InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);

But the big deal here is how to hide the keyboard when the user touches or selects any other place that is not an EditText or the softKeyboard?

I tried to use the onTouchEvent() on my parent Activity but that only works if user touches outside any other view and there is no scrollview.

I tried to implement a touch, click, focus listener without any success.

I even tried to implement my own scrollview to intercept touch events but I can only get the coordinates of the event and not the view clicked.

Is there a standard way to do this?? in iPhone it was really easy.

Body:
Just Add this code in the class
 @Overide

public boolean dispatchTouchEvent(MotionEvent ev) {
    View view = getCurrentFocus();
    if (view != null && (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_MOVE) && view instanceof EditText && !view.getClass().getName().startsWith("android.webkit.")) {
        int scrcoords[] = new int[2];
        view.getLocationOnScreen(scrcoords);
        float x = ev.getRawX() + view.getLeft() - scrcoords[0];
        float y = ev.getRawY() + view.getTop() - scrcoords[1];
        if (x < view.getLeft() || x > view.getRight() || y < view.getTop() || y > view.getBottom())
            ((InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow((this.getWindow().getDecorView().getApplicationWindowToken()), 0);
    }
    return super.dispatchTouchEvent(ev);
}


问:
Get name of a form submit button Django
I have an array of forms. When the user click to submit one of those forms i want identify which one he decided to submit.
So I have an array of names to name all my submit buttons :

```<code>{% for n in db %}
    ...
    <input type = 'submit' name = '{{ n.movie_id }}' value = 'ok' />
{% endfor %}`
</code>```

I'd like to get this name in my view to create objects in my database.
Is there a way to do it ?

答:
Coming to this late, I know, but you can solve this problem using a button rather than an input.

```<code><button type="submit" name="button1" value="button1press" > Submit </button>
</code>```

Coincidentally available to me while debugging something else ... Django sees

```<code>self.request.POST { 'button1': 'button1press', ... }
</code>```

Title: Get name of a form submit button Django

Body:
I have an array of forms. When the user click to submit one of those forms i want identify which one he decided to submit.
So I have an array of names to name all my submit buttons :

{% for n in db %}
    ...
    <input type = 'submit' name = '{{ n.movie_id }}' value = 'ok' />
{% endfor %}`

I'd like to get this name in my view to create objects in my database.
Is there a way to do it ?

Body:
Coming to this late, I know, but you can solve this problem using a button rather than an input.

<button type="submit" name="button1" value="button1press" > Submit </button>

Coincidentally available to me while debugging something else ... Django sees

self.request.POST { 'button1': 'button1press', ... }


问:
Checking out books in a library management system
I am writing code for a basic library management system, I have a txt file for ID number, book title and then author. I have got to the stage where I have a log in system asking for id numbers etc and I can search for books. Now I need to make it so I can check out the book... I have got it so it will search for the book but then I need to be append the ID number onto the correct book in the txt file. I have got it so at the moment it just appends to the last object. any pointers would be a great help. Thank you.

Present code for searching for books...

```<code>while True:
    n=float(raw_input('Please enter your ID '))
    if n in range (1000,10000):

    break
print 'ID is incorrect, please try again'

with open("txt.txt") as searchfile:
    found = False
    while not found:
        b=str(raw_input('please enter a book '))
        if b == '':
        break  # allow the search-loop to quit on no input
        for line in searchfile:
            if b in line:
                print line
                found = True
                break
        else:
            print 'Please try again'
            searchfile.seek(0)  # reset file to the beginning for next search

searchfile.close()
</code>```

That all works ^^^ then i got to checking out books and got this following code:

```<code>find_book=[]
    with open('txt.txt') as input_file:
        lines = [line.rstrip().split('\t')
                 for line in input_file.readlines()]

if(find_book('0',3))==0:
    print 'availabile'
</code>```

答:
class Library

```<code>Librarians=[["Prashanth","1234"],["Swetha","4321"]]
Students=[["RajaShekar","1111"],["Sandeep","2222"],["Manasa","3333"],["Manoj","4444"],["RamaKrishna","5555"],["Teja","6666"],["Bhavani","7777"],["Sandilya","9999"]]
Rack_Book=[["Physics","Einstin","1000"],["Physics","Einstin","1001"],["Physics","Edison","1002"],["Physics","Einstin","1003"],["Physics","Einstin","1004"],\
      ["Chemistry","Einstin","2000"],["Chemistry","Thamos","2001"],["Chemistry","Einstin","2002"],["Chemistry","Nobel","2003"],["Chemistry","Einstin","2004"]]
Dispatch_Book=[]
def Change_Login(self,name,pin):
    if [name,pin] not in lib.Librarians:
        Librarians=self.Librarians.append([name,pin])
        print("Successfully Changed login details")
    else:
         print("Entered same details only")
def Update_Book(self,name,author,Bid):
    if [name,author,Bid] not in lib.Rack_Book:

        Rack_Book=self.Rack_Book.append([name,author,Bid])
        #print(lib.Rack_Book)
        print("Update Successfully:",[name,author,Bid])
    else:
         print("Book already available with same details")
def Details_Books(self):
    print("--------------------------------------------------")
    print("Book name"," "*9,"Author Name"," "*9,"Book ID")
    print("--------------------------------------------------")

    for i in range(len(lib.Rack_Book)):
        print(lib.Rack_Book[i][0]," "*(20-len(lib.Rack_Book[i][0])),lib.Rack_Book[i][1]," "*(20-len(lib.Rack_Book[i][1])),lib.Rack_Book[i][2])
        print("___________________________________________________")

    print("\nNo of avaliable Books are:",len(lib.Rack_Book))

def Add_Students(self,name,pin):
    if [name,pin] not in lib.Students:
        Students=self.Students.append([name,pin])
        print("Successfully Added with details",[name,pin])
    else:
         print("Students already available with details")
def Delete_Students(self,name,pin):
    if [name,pin] in lib.Students:
        Students=self.Students.remove([name,pin])
        print("Successfully deleted details",[name,pin])
    else:
         print("No students available with details")
def Details_Students(self):
    print("-------------------------------")
    print("Sudent name"," "*9,"R.No")
    print("-------------------------------")

    for i in range(len(lib.Students)):
        print(lib.Students[i][0]," "*(20-len(lib.Students[i][0])),lib.Students[i][1])
        print("_______________________________")
    print("\nNo of Students are:",len(lib.Students))
def Collect_Books(self,name,author,Bid):
    if [name,author,Bid] in lib.Rack_Book:
        Dispatch_Book=self.Dispatch_Book.append([name,author,Bid])
        Rack_Book=self.Rack_Book.remove([name,author,Bid])
        print("Book collected succesfully:" ,[name,author,Bid])
    else:
       print("Enter details wrong:")
def Return_Book(self,name,author,Bid):
    if [name,author,Bid] in lib.Dispatch_Book:
        Dispatch_Book=self.Dispatch_Book.remove([name,author,Bid])
        Rack_Book=lib.Rack_Book.append([name,author,Bid])
        print("Return Successfully:",[name,author,Bid])
    else:
       print("Enter details wrong:")

lib=Library()
print("Welcome to Library")
while(True):
print('''Select your Option
 1:Librarian Login
 2:Student Login
 3:Exit''')

opt1=int(input("Please Enter your option:"))

if opt1==1:
    i=1
    while (i<4):
        usrlib=input("Please Enter your Name:")
        pinlib=input("Please Enter your Login PIN:")

        if [usrlib,pinlib] in lib.Librarians:
            print("Access Granted")
            i=5
            while(True):
                print('''Select your Option
                 0:Change Username or Password
                 1:Add Books
                 2:Books Details
                 3:Add Students
                 4:Remove Students
                 5:Students details
                 6:Exit or Back''')
                opt2=int(input("Please Enter your option:"))
                if opt2==0:
                    usrlib1=input("Please Enter User Name to chane:")
                    pinlib2=input("Please Enter Login PIN to change:")
                    lib.Change_Login(usrlib1,pinlib2)

                elif opt2==1:
                    name=input("Please Enter your Book Name:")
                    author=input("Please Enter your Book Author:")
                    Bid=input("Please Enter your Book Id:")
                    lib.Update_Book(name.capitalize(),author.capitalize(),Bid)

                elif opt2==2:
                    lib.Details_Books()

                elif opt2==3:
                    name=input("Please Enter Student Name:")
                    pin=input("Please Enter Student R.No:")
                    lib.Add_Students(name.capitalize(),pin)
                elif opt2==4:
                    name=input("Please Enter Student Name:")
                    pin=input("Please Enter Student R.No:")
                    lib.Delete_Students(name.capitalize(),pin)
                elif opt2==5:
                    lib.Details_Students()
                elif opt2==6:
                    print("Back to Menu")
                    break
                else:
                    print("Wrong input")
                    continue

        else:
            print("Access Denied \nUser name or PIN Entered wrong")
            print("\nYou have more",(3-i),"attempts")
            i+=1
            if i==4:
                print("Failed login within 3 attempts")
elif opt1==2:
    i=1
    while (i<4):
        usrstd=input("Please Enter your Name:")
        pinstd=input("Please Enter your R.No:")

        if [usrstd,pinstd] in lib.Students:
            print("Access Granted")
            i=5
            while(True):
                print('''Select your Option
                     1:Collect Book
                     2:Return Books
                     3:Exit or Back
                     ''')
                opt2=int(input("Please Enter your option:"))
                if opt2==1:
                    print("Availablie Books are:\n")
                    lib.Details_Books()
                    name=input("Please Enter your Book Name:")
                    author=input("Please Enter your Book Author:")
                    Bid=input("Please Enter your Book Id:")
                    lib.Collect_Books(name.capitalize(),author.capitalize(),Bid)
                elif opt2==2:
                    name=input("Please Enter your Book Name:")
                    author=input("Please Enter your Book Author:")
                    Bid=input("Please Enter your Book Id:")
                    lib.Return_Book(name.capitalize(),author.capitalize(),Bid)
                elif opt2==3:
                    print("Back to Menu")
                    break

                else:
                    print("Wrong input")

        else:
            print("Access Denied \nUser name or PIN Entered wrong")
            print("\nYou have more",(3-i),"attempts")
            i+=1
            if i==4:
                print("Failed login within 3 attempts")

elif opt1==3:
    print("Exit Successfully")
    break

else:
    print("Wrong input")
</code>```

This is Library management program , I take initially some books , some students and two librarians. Librarians can only check book details,student details and they only add or remove student logins. Students login with there details and collect the books from available books ,return books which is taken. If student collect the book , the book details append in to dispatched list and remove from the available list.

Body:
I am writing code for a basic library management system, I have a txt file for ID number, book title and then author. I have got to the stage where I have a log in system asking for id numbers etc and I can search for books. Now I need to make it so I can check out the book... I have got it so it will search for the book but then I need to be append the ID number onto the correct book in the txt file. I have got it so at the moment it just appends to the last object. any pointers would be a great help. Thank you.

Present code for searching for books...

while True:
    n=float(raw_input('Please enter your ID '))
    if n in range (1000,10000):

    break
print 'ID is incorrect, please try again'

with open("txt.txt") as searchfile:
    found = False
    while not found:
        b=str(raw_input('please enter a book '))
        if b == '':
        break  # allow the search-loop to quit on no input
        for line in searchfile:
            if b in line:
                print line
                found = True
                break
        else:
            print 'Please try again'
            searchfile.seek(0)  # reset file to the beginning for next search

searchfile.close()

That all works ^^^ then i got to checking out books and got this following code:

find_book=[]
    with open('txt.txt') as input_file:
        lines = [line.rstrip().split('\t')
                 for line in input_file.readlines()]

if(find_book('0',3))==0:
    print 'availabile'

Body:
class Library

Librarians=[["Prashanth","1234"],["Swetha","4321"]]
Students=[["RajaShekar","1111"],["Sandeep","2222"],["Manasa","3333"],["Manoj","4444"],["RamaKrishna","5555"],["Teja","6666"],["Bhavani","7777"],["Sandilya","9999"]]
Rack_Book=[["Physics","Einstin","1000"],["Physics","Einstin","1001"],["Physics","Edison","1002"],["Physics","Einstin","1003"],["Physics","Einstin","1004"],\
      ["Chemistry","Einstin","2000"],["Chemistry","Thamos","2001"],["Chemistry","Einstin","2002"],["Chemistry","Nobel","2003"],["Chemistry","Einstin","2004"]]
Dispatch_Book=[]
def Change_Login(self,name,pin):
    if [name,pin] not in lib.Librarians:
        Librarians=self.Librarians.append([name,pin])
        print("Successfully Changed login details")
    else:
         print("Entered same details only")
def Update_Book(self,name,author,Bid):
    if [name,author,Bid] not in lib.Rack_Book:

        Rack_Book=self.Rack_Book.append([name,author,Bid])
        #print(lib.Rack_Book)
        print("Update Successfully:",[name,author,Bid])
    else:
         print("Book already available with same details")
def Details_Books(self):
    print("--------------------------------------------------")
    print("Book name"," "*9,"Author Name"," "*9,"Book ID")
    print("--------------------------------------------------")

    for i in range(len(lib.Rack_Book)):
        print(lib.Rack_Book[i][0]," "*(20-len(lib.Rack_Book[i][0])),lib.Rack_Book[i][1]," "*(20-len(lib.Rack_Book[i][1])),lib.Rack_Book[i][2])
        print("___________________________________________________")

    print("\nNo of avaliable Books are:",len(lib.Rack_Book))

def Add_Students(self,name,pin):
    if [name,pin] not in lib.Students:
        Students=self.Students.append([name,pin])
        print("Successfully Added with details",[name,pin])
    else:
         print("Students already available with details")
def Delete_Students(self,name,pin):
    if [name,pin] in lib.Students:
        Students=self.Students.remove([name,pin])
        print("Successfully deleted details",[name,pin])
    else:
         print("No students available with details")
def Details_Students(self):
    print("-------------------------------")
    print("Sudent name"," "*9,"R.No")
    print("-------------------------------")

    for i in range(len(lib.Students)):
        print(lib.Students[i][0]," "*(20-len(lib.Students[i][0])),lib.Students[i][1])
        print("_______________________________")
    print("\nNo of Students are:",len(lib.Students))
def Collect_Books(self,name,author,Bid):
    if [name,author,Bid] in lib.Rack_Book:
        Dispatch_Book=self.Dispatch_Book.append([name,author,Bid])
        Rack_Book=self.Rack_Book.remove([name,author,Bid])
        print("Book collected succesfully:" ,[name,author,Bid])
    else:
       print("Enter details wrong:")
def Return_Book(self,name,author,Bid):
    if [name,author,Bid] in lib.Dispatch_Book:
        Dispatch_Book=self.Dispatch_Book.remove([name,author,Bid])
        Rack_Book=lib.Rack_Book.append([name,author,Bid])
        print("Return Successfully:",[name,author,Bid])
    else:
       print("Enter details wrong:")

lib=Library()
print("Welcome to Library")
while(True):
print('''Select your Option
 1:Librarian Login
 2:Student Login
 3:Exit''')

opt1=int(input("Please Enter your option:"))

if opt1==1:
    i=1
    while (i<4):
        usrlib=input("Please Enter your Name:")
        pinlib=input("Please Enter your Login PIN:")

        if [usrlib,pinlib] in lib.Librarians:
            print("Access Granted")
            i=5
            while(True):
                print('''Select your Option
                 0:Change Username or Password
                 1:Add Books
                 2:Books Details
                 3:Add Students
                 4:Remove Students
                 5:Students details
                 6:Exit or Back''')
                opt2=int(input("Please Enter your option:"))
                if opt2==0:
                    usrlib1=input("Please Enter User Name to chane:")
                    pinlib2=input("Please Enter Login PIN to change:")
                    lib.Change_Login(usrlib1,pinlib2)

                elif opt2==1:
                    name=input("Please Enter your Book Name:")
                    author=input("Please Enter your Book Author:")
                    Bid=input("Please Enter your Book Id:")
                    lib.Update_Book(name.capitalize(),author.capitalize(),Bid)

                elif opt2==2:
                    lib.Details_Books()

                elif opt2==3:
                    name=input("Please Enter Student Name:")
                    pin=input("Please Enter Student R.No:")
                    lib.Add_Students(name.capitalize(),pin)
                elif opt2==4:
                    name=input("Please Enter Student Name:")
                    pin=input("Please Enter Student R.No:")
                    lib.Delete_Students(name.capitalize(),pin)
                elif opt2==5:
                    lib.Details_Students()
                elif opt2==6:
                    print("Back to Menu")
                    break
                else:
                    print("Wrong input")
                    continue

        else:
            print("Access Denied \nUser name or PIN Entered wrong")
            print("\nYou have more",(3-i),"attempts")
            i+=1
            if i==4:
                print("Failed login within 3 attempts")
elif opt1==2:
    i=1
    while (i<4):
        usrstd=input("Please Enter your Name:")
        pinstd=input("Please Enter your R.No:")

        if [usrstd,pinstd] in lib.Students:
            print("Access Granted")
            i=5
            while(True):
                print('''Select your Option
                     1:Collect Book
                     2:Return Books
                     3:Exit or Back
                     ''')
                opt2=int(input("Please Enter your option:"))
                if opt2==1:
                    print("Availablie Books are:\n")
                    lib.Details_Books()
                    name=input("Please Enter your Book Name:")
                    author=input("Please Enter your Book Author:")
                    Bid=input("Please Enter your Book Id:")
                    lib.Collect_Books(name.capitalize(),author.capitalize(),Bid)
                elif opt2==2:
                    name=input("Please Enter your Book Name:")
                    author=input("Please Enter your Book Author:")
                    Bid=input("Please Enter your Book Id:")
                    lib.Return_Book(name.capitalize(),author.capitalize(),Bid)
                elif opt2==3:
                    print("Back to Menu")
                    break

                else:
                    print("Wrong input")

        else:
            print("Access Denied \nUser name or PIN Entered wrong")
            print("\nYou have more",(3-i),"attempts")
            i+=1
            if i==4:
                print("Failed login within 3 attempts")

elif opt1==3:
    print("Exit Successfully")
    break

else:
    print("Wrong input")

This is Library management program , I take initially some books , some students and two librarians. Librarians can only check book details,student details and they only add or remove student logins. Students login with there details and collect the books from available books ,return books which is taken. If student collect the book , the book details append in to dispatched list and remove from the available list.


问:
openlayers strategy: ol.loadingstrategy.bbox does'nt work with wfs features
I tried to visualize parcels in wfs with openlayers 4 (max 1000) with this code.
But the extent does not change at each movement or zoom of the view map, or the new features do not load in the layer?</p>

```<code> var parcellaireSource =  new ol.source.Vector({
    format: new ol.format.GeoJSON(),
    url: function (extent) {
      return  'https://wxs.ign.fr/api key/geoportail/wfs?request=GetCapabilities&SERVICE=WFS&VERSION=2.0.0&request=GetFeature&typename=BDPARCELLAIRE-VECTEUR_WLD_BDD_WGS84G:parcelle&outputFormat=application/json&srsname=EPSG:2154&bbox='+ extent.join(',') + ',EPSG:3857';

          },

    strategy: ol.loadingstrategy.bbox
    });
     var parcellairewfs =  new ol.layer.Vector({
    source: parcellaireSource
  });
     map.addLayer(parcellairewfs);
</code>```

答:
It's done with

```<code>  url: function (extent,resolution) {if (resolution<1) {return ....
</code>```

in the vectorsource calculation and adding resolution parameter to the function

Body:
I tried to visualize parcels in wfs with openlayers 4 (max 1000) with this code.
But the extent does not change at each movement or zoom of the view map, or the new features do not load in the layer?

 var parcellaireSource =  new ol.source.Vector({
    format: new ol.format.GeoJSON(),
    url: function (extent) {
      return  'https://wxs.ign.fr/api key/geoportail/wfs?request=GetCapabilities&SERVICE=WFS&VERSION=2.0.0&request=GetFeature&typename=BDPARCELLAIRE-VECTEUR_WLD_BDD_WGS84G:parcelle&outputFormat=application/json&srsname=EPSG:2154&bbox='+ extent.join(',') + ',EPSG:3857';

          },

    strategy: ol.loadingstrategy.bbox
    });
     var parcellairewfs =  new ol.layer.Vector({
    source: parcellaireSource
  });
     map.addLayer(parcellairewfs);

Body:
It's done with

  url: function (extent,resolution) {if (resolution<1) {return ....

in the vectorsource calculation and adding resolution parameter to the function


问:
how to read JSON data from url sent from Angular 2 using asp.net
I am developing a simple Angular 2 reactive form. I am using ASP.NET and SQL server as my backend to store form data. I send the form data from angular 2 using angular service to asp.net page, there  I can't able to read those form data.

This is my angular code to send form data.

```<code>import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from  'rxjs/observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import { User } from './signup.interface';

@Injectable()
export class SignupService {
    headers: Headers;
    options: RequestOptions;

    private producturl = "http://172.21.41.70:8081/DB-Connect/";
    constructor(private _http: Http) {
        this.headers = new Headers({
            'Content-Type': 'application/json'
         });
          this.options = new RequestOptions({ headers: this.headers });
    }

    postDetails(user: User): Observable<User[]> {
       // console.log(user);
        let body = JSON.stringify(user);
        console.log(body);
        return this._http.post(this.producturl, body, this.options)
            .map((response: Response) => response)
            .do(data => console.log(JSON.stringify(data)))
            .catch(this.handleError);
    }

    /*private extractData(res: Response) {
        console.log(res);
        let body = res.json();
        return body || {};
    }*/

    private handleError(error: Response) {
        console.log(error);
        return Observable.throw(error.json().error());
    }
}
</code>```

This my asp.net code

```<code>   Response.ContentType = "text/plain";
        using (WebClient wc = new WebClient())
        {
            var json = wc.DownloadString("http://localhost:4200");
            Response.Write(json);
        }
</code>```

While execute the code i am getting angular index page completely as a output.I am not getting any JSON data which I sent.

```<code><!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Demo</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
<script type="text/javascript" src="inline.bundle.js"></script><script type="text/javascript" src="polyfills.bundle.js"></script><script type="text/javascript" src="styles.bundle.js"></script><script type="text/javascript" src="vendor.bundle.js"></script><script type="text/javascript" src="main.bundle.js"></script></body>
</html>
</code>```

Please help me to read JSON data in asp.net page. Thanks in advance

答:
The Angular 2 project with .NET as backend can be done with Visual studio 2017 and .NET SDK framework installed.

Install visual studio 2017.

install .net sdk framework.

Go to File -> New -> Project -> ASP .NET core web application and give okay.

Then select Angular to create our Angular application.

Code Angular part inside ClientApp folder. It also contain two demo
files for our reference.

Create one C# file inside Controllers folder for backend access.For example I
created the file named ValuesController.cs

We can call that C# controller file from Angular service file as 'api/Values'
(Please refer this URL in ValuesController.cs)

We can code our backend code inside the ValuesController.cs  file inside
individual get,post functions. In that controller file we can get and post data.

Thank you.

Body:
I am developing a simple Angular 2 reactive form. I am using ASP.NET and SQL server as my backend to store form data. I send the form data from angular 2 using angular service to asp.net page, there  I can't able to read those form data.

This is my angular code to send form data.

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from  'rxjs/observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import { User } from './signup.interface';

@Injectable()
export class SignupService {
    headers: Headers;
    options: RequestOptions;

    private producturl = "http://172.21.41.70:8081/DB-Connect/";
    constructor(private _http: Http) {
        this.headers = new Headers({
            'Content-Type': 'application/json'
         });
          this.options = new RequestOptions({ headers: this.headers });
    }

    postDetails(user: User): Observable<User[]> {
       // console.log(user);
        let body = JSON.stringify(user);
        console.log(body);
        return this._http.post(this.producturl, body, this.options)
            .map((response: Response) => response)
            .do(data => console.log(JSON.stringify(data)))
            .catch(this.handleError);
    }

    /*private extractData(res: Response) {
        console.log(res);
        let body = res.json();
        return body || {};
    }*/

    private handleError(error: Response) {
        console.log(error);
        return Observable.throw(error.json().error());
    }
}

This my asp.net code

   Response.ContentType = "text/plain";
        using (WebClient wc = new WebClient())
        {
            var json = wc.DownloadString("http://localhost:4200");
            Response.Write(json);
        }

While execute the code i am getting angular index page completely as a output.I am not getting any JSON data which I sent.

<!doctype html>

  <meta charset="utf-8">
  <title>Demo</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <app-root></app-root>

Please help me to read JSON data in asp.net page. Thanks in advance


问:
Tool to get fonts used in afp file
Does anyone know how can we get the fonts used in an Afp file .

I have tried Afp explorer , but it's not helping.

Please provide some suggestions on this.

答:
I use this one:
Extract_Afp_Resources</p>

```<code>USAGE:

extract_afp_resources.exe -i input_file [-o output_file] [-r resource_dir] [-l] [-v]

Explanation of options:

-i     input_file The input AFP file from which to extract resources
-o     output_file Output AFP created without resources. This argument is optional.
-r     resource_dir Directory into which resources are to be extracted.
-l     List mode. Inline resources are listed but not extracted.
-v     Verbose mode
</code>```

Title: Tool to get fonts used in afp file

Body:
I use this one:
Extract_Afp_Resources

USAGE:

extract_afp_resources.exe -i input_file [-o output_file] [-r resource_dir] [-l] [-v]

Explanation of options:

-i     input_file The input AFP file from which to extract resources
-o     output_file Output AFP created without resources. This argument is optional.
-r     resource_dir Directory into which resources are to be extracted.
-l     List mode. Inline resources are listed but not extracted.
-v     Verbose mode


问:
How to configure socket.io sticky session on bluemix
I need to deploy a socket.io application on IBM Bluemix with multiple cloudfoundry instances to ensure load balancing.

I followed socket.io documentation and this link to use sticky session and to be sure each socket goes to the correct instance.

Unfortunately, my client is disconnected just after connect event and error '400 xhr poll' error is fired.

Here is my server code :

```<code>const cookieParser = require('cookie-parser')
const session = require('express-session')
const redis = require('redis')
const app = require('express')()
const http = require('http').Server(app)
const io = require('socket.io')(http)
const RedisStore = require('connect-redis')(session)
const redisUrl = 'myredis'

var session = session({
  store: new RedisStore({client: client}),
  secret: 'mysecret',
  name: 'jsessionid',
  resave: true,
  saveUninitialized: true
})

app.use(cookieParser)
app.use(session)

io.on('connection', function (socket) {
  console.log('a user is connected')

  socket.on('testPing', function () {
      socket.emit('testPong', {})
  })
})

http.listen(process.env.PORT || 3000, function () {
  console.log('listening on *:' + (process.env.PORT || 3000))
})
</code>```

after several hours searching on Google, I don't know what to try anymore. I really need some help.

Thank you in advance!

答:
I did this recently (although without Redis), to fix the same issue; socket.io and load balancers don't play well together out of the box. The key is to use a JSESSIONID cookie, for session affinity. This was my code: </p>

```<code>const expressSession = require('express-session');
</code>```

<p>... </p>

```<code>var app = express();
</code>```

<p>... </p>

```<code>app.use(
    expressSession({
      key: 'JSESSIONID', // use a sticky session to make sockets work
      secret: 'arbitrary-secret',
      cookie: {
         maxAge: 24 * 60 * 60 * 1000, // 1 day
         secure: false
      },
      saveUninitialized: false,
      resave: false
   })
);
//setting up socket.io for realtime communication
var http = require('http').Server(app);
var io = require('socket.io')(http);
</code>```

Body:
I need to deploy a socket.io application on IBM Bluemix with multiple cloudfoundry instances to ensure load balancing.

I followed socket.io documentation and this link to use sticky session and to be sure each socket goes to the correct instance.

Unfortunately, my client is disconnected just after connect event and error '400 xhr poll' error is fired.

Here is my server code :

const cookieParser = require('cookie-parser')
const session = require('express-session')
const redis = require('redis')
const app = require('express')()
const http = require('http').Server(app)
const io = require('socket.io')(http)
const RedisStore = require('connect-redis')(session)
const redisUrl = 'myredis'

var session = session({
  store: new RedisStore({client: client}),
  secret: 'mysecret',
  name: 'jsessionid',
  resave: true,
  saveUninitialized: true
})

app.use(cookieParser)
app.use(session)

io.on('connection', function (socket) {
  console.log('a user is connected')

  socket.on('testPing', function () {
      socket.emit('testPong', {})
  })
})

http.listen(process.env.PORT || 3000, function () {
  console.log('listening on *:' + (process.env.PORT || 3000))
})

after several hours searching on Google, I don't know what to try anymore. I really need some help.

Thank you in advance!

Body:
I did this recently (although without Redis), to fix the same issue; socket.io and load balancers don't play well together out of the box. The key is to use a JSESSIONID cookie, for session affinity. This was my code:

const expressSession = require('express-session');

...

var app = express();

...

app.use(
    expressSession({
      key: 'JSESSIONID', // use a sticky session to make sockets work
      secret: 'arbitrary-secret',
      cookie: {
         maxAge: 24 * 60 * 60 * 1000, // 1 day
         secure: false
      },
      saveUninitialized: false,
      resave: false
   })
);
//setting up socket.io for realtime communication
var http = require('http').Server(app);
var io = require('socket.io')(http);


问:
How did they do this? [iPhone layout]
checkout this app:

 If you swipe left in main image (the black shoes) you can see another image.

Can anyone try this app (Fashiolista, it's free and signup isn't required) and
say me how can I do an effect like that?

Thank you guys.

答:
They seem to be using Core Animation to modify the images' alpha and animate the images out and in.

Check out Introduction to Core Animation Programming Guide.

*edit:

They could also be using UIViews animation API. This is probably even simpler.
View Programming Guide - Animations

ContentLicense: CC BY-SA 2.5

Title: How did they do this? [iPhone layout]


问:
Bootstrap 3.3.7 - carousel not showing content of div marked with class - 'item'
I have created a simple page which contain only one bootstrap carousel.

I have included following script files

bootstrap.css

jquery-1.11.1.min.js

bootstrap.js

Problem: I can see only image sliding.  Other content of div with the class 'item' is not appearing on the slides.  I want to include other stuff over the image to add more description.  Just like this link.

But I cant see other content, can see only images sliding.  Am i missing any style sheet or js file?

                                <-- I cant see below divs !-->

Example headline.

Note: If you're viewing this page via a file:// URL, the "next" and "previous" Glyphicon buttons on the left and right might not load/display properly due to web browser security rules.

Sign up today

Another example headline.

Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.

Learn more

                            img class="third-slide" src="" alt="Third slide">

One more for good measure.

Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.

Browse gallery

                            Letf
                            Previous

                            Next

     ```

Here is jsfiddle link.

答:
check the third section of your code

\
"img class="third-slide" src="" alt="Third slide">"

you missed to insert the "<" ... http://prntscr.com/hjaonu

Body:
I have created a simple page which contain only one bootstrap carousel.

I have included following script files

bootstrap.css

jquery-1.11.1.min.js

bootstrap.js

Problem: I can see only image sliding.  Other content of div with the class 'item' is not appearing on the slides.  I want to include other stuff over the image to add more description.  Just like this link.

But I cant see other content, can see only images sliding.  Am i missing any style sheet or js file?

                                <-- I cant see below divs !-->

Example headline.

Note: If you're viewing this page via a file:// URL, the "next" and "previous" Glyphicon buttons on the left and right might not load/display properly due to web browser security rules.

Sign up today

Another example headline.

Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.

Learn more

                            img class="third-slide" src="" alt="Third slide">

One more for good measure.

Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.

Browse gallery

                            Letf
                            Previous

                            Next

Here is jsfiddle link.


问:
Group by List using inner list
Below is my List collection.

```<code>public class A
{
    public String id{ get; set; }
    public string name{ get; set; }
    public List<B> nestedList { get; set; }
}
public class B
{
    public String innerid{ get; set; }
    public string innername { get; set; }
}
</code>```

I want to use group by on nested collection properties
So I can have output as

```<code>  innerid="1",
  innername="Name1",
    {
      id= "1", name= "One"
      id= "2", name= "Two"
      id= "4", name= "Four"
    }
  innerid="2",
  innername="Name2",
    {
      id= "3", name= "Three"
      id= "6", name= "Six"
      id= "8", name= "Eight"
    }
</code>```

I tried
.GroupBy(a => a.nestedList.First().innerid).ToList()
But I am not getting required output.

答:
You want to reverse the hierarchy, so grouping by the nested-B and list the parent-A as children?

```<code>var groups = aList
   .SelectMany(a => a.nestedList.Select(b => new { A = a, B = b }))
   .GroupBy(x => new { x.B.innerid, x.B.innername })
   .Select(g => new {
       g.Key.innerid,
       g.Key.innername,
       aItems = g.Select(x => new { x.A.id, x.A.name })
    });
</code>```

Instead of selecting anonymous types you can also select the original A and B instances.

Title: Group by List using inner list

Body:
Below is my List collection.

public class A
{
    public String id{ get; set; }
    public string name{ get; set; }
    public List nestedList { get; set; }
}
public class B
{
    public String innerid{ get; set; }
    public string innername { get; set; }
}

I want to use group by on nested collection properties
So I can have output as

  innerid="1",
  innername="Name1",
    {
      id= "1", name= "One"
      id= "2", name= "Two"
      id= "4", name= "Four"
    }
  innerid="2",
  innername="Name2",
    {
      id= "3", name= "Three"
      id= "6", name= "Six"
      id= "8", name= "Eight"
    }

I tried
.GroupBy(a => a.nestedList.First().innerid).ToList()
But I am not getting required output.

Body:
You want to reverse the hierarchy, so grouping by the nested-B and list the parent-A as children?

var groups = aList
   .SelectMany(a => a.nestedList.Select(b => new { A = a, B = b }))
   .GroupBy(x => new { x.B.innerid, x.B.innername })
   .Select(g => new {
       g.Key.innerid,
       g.Key.innername,
       aItems = g.Select(x => new { x.A.id, x.A.name })
    });

Instead of selecting anonymous types you can also select the original A and B instances.


问:
EMACS auto-complete: Error running timer ‘ac-update-greedy’: (wrong-number-of-arguments setq 1)
Upgraded from:
EMACS 23.4-bin-i386 with auto-complete-1.3.1, where AC-Mode worked perfect

to

GNU Emacs 25.3.1 (x86_64-w64-mingw32) of 2017-09-17 with auto-complete-1.5.1 on Windows10

.emacs configuration is:

```<code>(add-to-list 'load-path "~/EMACS/EMACS_Extentions/auto-complete-1.5.1/")
(require 'auto-complete-config)
(ac-config-default)
(add-to-list 'ac-dictionary-directories "~/.emacs.d/ac-dict")
(add-to-list 'ac-user-dictionary-files "~/.emacs.d/ac-dict/org.dict")
(add-to-list 'ac-modes 'org-mode)
</code>```

Now I got the following Error:

```<code>Auto-Complete mode enabled in current buffer
You can run the command ‘auto-complete-mode’ with M-x au-compl- RET
Auto-Complete mode enabled in current buffer
Error running timer ‘ac-update-greedy’: (wrong-number-of-arguments setq 1)[2 times]
auto-complete error: (wrong-number-of-arguments setq 1)
</code>```

Saw already the same problem posted on GIT-HUB:
https://github.com/auto-complete/auto-complete/issues/442 but there is not a solution for it at all.

Would be happy for any suggestions!

答: After a few attempts and another EMACS start, a plausible error message appeared, which helped me further. Auto-Completion now probably has a dependency on popup.el. After I integrated this, auto-complete works fine again.

Body:
Upgraded from:
EMACS 23.4-bin-i386 with auto-complete-1.3.1, where AC-Mode worked perfect

to

GNU Emacs 25.3.1 (x86_64-w64-mingw32) of 2017-09-17 with auto-complete-1.5.1 on Windows10

.emacs configuration is:

(add-to-list 'load-path "~/EMACS/EMACS_Extentions/auto-complete-1.5.1/")
(require 'auto-complete-config)
(ac-config-default)
(add-to-list 'ac-dictionary-directories "~/.emacs.d/ac-dict")
(add-to-list 'ac-user-dictionary-files "~/.emacs.d/ac-dict/org.dict")
(add-to-list 'ac-modes 'org-mode)

Now I got the following Error:

Auto-Complete mode enabled in current buffer
You can run the command ‘auto-complete-mode’ with M-x au-compl- RET
Auto-Complete mode enabled in current buffer
Error running timer ‘ac-update-greedy’: (wrong-number-of-arguments setq 1)[2 times]
auto-complete error: (wrong-number-of-arguments setq 1)

Saw already the same problem posted on GIT-HUB:
https://github.com/auto-complete/auto-complete/issues/442 but there is not a solution for it at all.

Would be happy for any suggestions!


问:
Reversing elements of an array
Given an array  a and two other  int variables,  k and  temp, write a loop that reverses the elements of the array.

```<code>for (k = 0; k < a.length-1; k++) {
  temp = a[k];
  a[k] = a[a.length-1-k];
  a[a.length-1-k] = temp;
}
</code>```

This is not working. Any idea why?

答:
Try this will simply work:

```<code>public class ReverseArray{
    public static void main(String[] args){
        int[] a ={1,2,3,4,5};
        for(int i=a.length-1;i>=0;i--){
            System.out.print(a[i]);
        }
    }
}
</code>```

Title: Reversing elements of an array

Body:
Given an array  a and two other  int variables,  k and  temp, write a loop that reverses the elements of the array.

for (k = 0; k < a.length-1; k++) {
  temp = a[k];
  a[k] = a[a.length-1-k];
  a[a.length-1-k] = temp;
}

This is not working. Any idea why?

LastEditorDisplayName: Roger Pate

Body:
Try this will simply work:

public class ReverseArray{
    public static void main(String[] args){
        int[] a ={1,2,3,4,5};
        for(int i=a.length-1;i>=0;i--){
            System.out.print(a[i]);
        }
    }
}


问:
asp.net calendar control: is it good?
I'm looking to determine if I'm going to use the calendar control that's out-of-the-box in ASP.NET 4 or if I should look elsewhere, may be a jQuery calendar that just receives json or another .net server option.

Has anyone worked with the native calendar control?

Thanks.

答:
I personally do not like asp.net native calendar control due to lack of extensibility. I would create a JQuery control since it will be more responsive(client-side).
Or take a look here: http://www.eworldui.net/</p>

Title: asp.net calendar control: is it good?


问:
Function that transforms a list in a list of dictionary
I have to make a function whose purpose is taking in parameter a list.

Such as this one :

```<code>['music', ' extension=mp3', 'reports/INFOB131', ' extension=doc,docx,pdf', ' name_contains=INFOB131', ' max_size=100000', 'reports/INFOB132', ' extension=doc,docx,pdf', ' name_contains=INFOB132', ' max_size=100000', 'games', ' name_contains=SC2,Wesnoth', 'pictures/Namur', ' extension=jpeg', ' min_size=5000000', ' name_contains=cercle', 'pictures/autres', ' extension=jpeg', ' min_size=5000000']
</code>```

And return a list similar to this :

```<code>data_config = [{'music' : {'extension':'mp3'}}, {'reports/INFOB131': {'extension': ['doc', 'docx','pdf'], 'name_contains':'INFOB131', 'max_size':100000}}, {'reports/INFOB132': {'extension': ['doc', 'docx','pdf'], 'name_contains':'INFOB132', 'max_size':100000}}]
</code>```

So I made that function :

```<code>def my_function(list_in_question, my_config_list =[], prev_list = []):
    """ """
    enumerated_list = list(enumerate(list_in_question))

    if not '=' in enumerated_list[0][1]:
        main_key = enumerated_list[0][1]# référencé avant assignement
        pre_dict = {main_key : {}}

        for i in enumerated_list[1:]:

            if '=' in i[1] :
                splitted = i[1].split('=')
                prev_list.append({splitted[0] : splitted[1]})

            elif not '=' in i[1] and i[1] != main_key:
                for j in prev_list:
                    pre_dict[main_key].update(j)

                my_config_list.append(pre_dict)

                return my_function(list_in_question[i[0]:])

            elif not '=' in i[1] and i[1] == main_key and main_key!= enumerated_list[0][1]:
                return my_config_list
    else:
        print("The format of the file containig the data in not adequate !")
</code>```

But I don't understand why when I execute it this way :

```<code>new_lines = ['music', ' extension=mp3', '', 'reports/INFOB131', ' extension=doc,docx,pdf', ' name_contains=INFOB131', ' max_size=100000', '', 'reports/INFOB132', ' extension=doc,docx,pdf', ' name_contains=INFOB132', ' max_size=100000', '', 'games', ' name_contains=SC2,Wesnoth', '', 'pictures/Namur', ' extension=jpeg', ' min_size=5000000', ' name_contains=cercle', '', 'pictures/autres', ' extension=jpeg', ' min_size=5000000']

my_function(new_lines)
</code>```

I end up with this output...

```<code>None
</code>```

I would be very grateful if someone could help me,

Thank you !

PS : If anyone have an idea of how I could do without loop and do it in a recursive way, it would be awesome !

Everyone... Thank you !!! You really hepled me, all your answers are awesome, I have some issues to understand some parts so I'll be annoying just a little longer with some questions of you code. Anyway, thank you for the time you took to help me, you were all more than great help !!!

答:
One more way of doing it:</p>

```<code>import re

def my_function(list_in_question, my_config_list=[], prev_list=[]):
    """ """
    result = {}
    main_key = ''

    for element in list_in_question:
        if element == '':
            main_key = ''
        if re.search('=', element):
            key, value = element.split('=')
            print "key, value = ", key, value
            if re.search(',', value):
                value_list = value.split(',')
                print "value list =", value_list
                result[main_key][key] = value_list
            else:
                result[main_key][key] = value

        else:
            main_key = element
            result[main_key] = {}

    return (result)

new_lines = ['music', ' extension=mp3', '', 'reports/INFOB131', ' extension=doc,docx,pdf', ' name_contains=INFOB131',
             ' max_size=100000', '', 'reports/INFOB132', ' extension=doc,docx,pdf', ' name_contains=INFOB132',
             ' max_size=100000', '', 'games', ' name_contains=SC2,Wesnoth', '', 'pictures/Namur', ' extension=jpeg',
             ' min_size=5000000', ' name_contains=cercle', '', 'pictures/autres', ' extension=jpeg',
             ' min_size=5000000']

print (my_function(new_lines))
</code>```

Body:
I have to make a function whose purpose is taking in parameter a list.

Such as this one :

['music', ' extension=mp3', 'reports/INFOB131', ' extension=doc,docx,pdf', ' name_contains=INFOB131', ' max_size=100000', 'reports/INFOB132', ' extension=doc,docx,pdf', ' name_contains=INFOB132', ' max_size=100000', 'games', ' name_contains=SC2,Wesnoth', 'pictures/Namur', ' extension=jpeg', ' min_size=5000000', ' name_contains=cercle', 'pictures/autres', ' extension=jpeg', ' min_size=5000000']

And return a list similar to this :

data_config = [{'music' : {'extension':'mp3'}}, {'reports/INFOB131': {'extension': ['doc', 'docx','pdf'], 'name_contains':'INFOB131', 'max_size':100000}}, {'reports/INFOB132': {'extension': ['doc', 'docx','pdf'], 'name_contains':'INFOB132', 'max_size':100000}}]

So I made that function :

def my_function(list_in_question, my_config_list =[], prev_list = []):
    """ """
    enumerated_list = list(enumerate(list_in_question))

    if not '=' in enumerated_list[0][1]:
        main_key = enumerated_list[0][1]# référencé avant assignement
        pre_dict = {main_key : {}}

        for i in enumerated_list[1:]:

            if '=' in i[1] :
                splitted = i[1].split('=')
                prev_list.append({splitted[0] : splitted[1]})

            elif not '=' in i[1] and i[1] != main_key:
                for j in prev_list:
                    pre_dict[main_key].update(j)

                my_config_list.append(pre_dict)

                return my_function(list_in_question[i[0]:])

            elif not '=' in i[1] and i[1] == main_key and main_key!= enumerated_list[0][1]:
                return my_config_list
    else:
        print("The format of the file containig the data in not adequate !")

But I don't understand why when I execute it this way :

new_lines = ['music', ' extension=mp3', '', 'reports/INFOB131', ' extension=doc,docx,pdf', ' name_contains=INFOB131', ' max_size=100000', '', 'reports/INFOB132', ' extension=doc,docx,pdf', ' name_contains=INFOB132', ' max_size=100000', '', 'games', ' name_contains=SC2,Wesnoth', '', 'pictures/Namur', ' extension=jpeg', ' min_size=5000000', ' name_contains=cercle', '', 'pictures/autres', ' extension=jpeg', ' min_size=5000000']

my_function(new_lines)

I end up with this output...

None

I would be very grateful if someone could help me,

Thank you !

PS : If anyone have an idea of how I could do without loop and do it in a recursive way, it would be awesome !

Everyone... Thank you !!! You really hepled me, all your answers are awesome, I have some issues to understand some parts so I'll be annoying just a little longer with some questions of you code. Anyway, thank you for the time you took to help me, you were all more than great help !!!

Body:
One more way of doing it:

import re

def my_function(list_in_question, my_config_list=[], prev_list=[]):
    """ """
    result = {}
    main_key = ''

    for element in list_in_question:
        if element == '':
            main_key = ''
        if re.search('=', element):
            key, value = element.split('=')
            print "key, value = ", key, value
            if re.search(',', value):
                value_list = value.split(',')
                print "value list =", value_list
                result[main_key][key] = value_list
            else:
                result[main_key][key] = value

        else:
            main_key = element
            result[main_key] = {}

    return (result)

new_lines = ['music', ' extension=mp3', '', 'reports/INFOB131', ' extension=doc,docx,pdf', ' name_contains=INFOB131',
             ' max_size=100000', '', 'reports/INFOB132', ' extension=doc,docx,pdf', ' name_contains=INFOB132',
             ' max_size=100000', '', 'games', ' name_contains=SC2,Wesnoth', '', 'pictures/Namur', ' extension=jpeg',
             ' min_size=5000000', ' name_contains=cercle', '', 'pictures/autres', ' extension=jpeg',
             ' min_size=5000000']

print (my_function(new_lines))


问:
show error message when the course is already register in php
i want this code to show me a error message when student already register a course     </p>

```<code> $reds = mysqli_query($db,"SELECT count(*) FROM `course` " );
    $row = mysqli_fetch_row($reds);
    $num = $row[0];

echo $num>0 ; die();
   var_dump($num) ;die();
    if ($num>0){
   // echo "record already exits";
}

else {

    $sd = "INSERT INTO `users_course`(users_id,course_id) VALUES ( ' {$_SESSION['users_id']}', '$course_id')";
    $r = mysqli_query($db, $sd);
        if ($r) {

        $m = ' register';
        header('location: registercourse.php'); //redirect to index page after inserting
</code>```

答:
You just need to pass users_id in your query to check if a particular student (user id) has registered for the course or not.

```<code>$reds = mysqli_query($db,"SELECT count(*) FROM `users_course` where users_id = `".$_SESSION['users_id']."` and course_id='".$course_id."'" );
</code>```

Because with current SELECT query, you are checking only if there is any course present in the course table. So as there would be some rows, it is giving your error message that course is already there.

Hope this is the clear explaination for you.

Body:
i want this code to show me a error message when student already register a course

 $reds = mysqli_query($db,"SELECT count(*) FROM `course` " );
    $row = mysqli_fetch_row($reds);
    $num = $row[0];

echo $num>0 ; die();
   var_dump($num) ;die();
    if ($num>0){
   // echo "record already exits";
}

else {

    $sd = "INSERT INTO `users_course`(users_id,course_id) VALUES ( ' {$_SESSION['users_id']}', '$course_id')";
    $r = mysqli_query($db, $sd);
        if ($r) {

        $m = ' register';
        header('location: registercourse.php'); //redirect to index page after inserting

Body:
You just need to pass users_id in your query to check if a particular student (user id) has registered for the course or not.

$reds = mysqli_query($db,"SELECT count(*) FROM `users_course` where users_id = `".$_SESSION['users_id']."` and course_id='".$course_id."'" );

Because with current SELECT query, you are checking only if there is any course present in the course table. So as there would be some rows, it is giving your error message that course is already there.

Hope this is the clear explaination for you.


问:
How to make div loop around in section
I'm working on a Roulette site, but i don't have any idea how to make the divs loop around.
I need the divs to loop around when they get out of the section border.

$("#right").click(function() {
  $("#one").css("left", "300px");
  $("#two").css("left", "300px");
  $("#three").css("left", "300px");
  $("#four").css("left", "300px");
  $("#five").css("left", "300px");
  $("#six").css("left", "300px");

});

$("#left").click(function() {
  $("#one").css("left", "0px");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>section {
  width: 80%;
  height: 50px;
  border: 5px solid gray;
  margin: auto;
  padding: 7px;
  z-index: 1;
  transition: left 2s ease;
  overflow: hidden;
}

div#one {
  width: 15%;
  height: 50px;
  background: black;
  float: left;
  z-index: -1;
  left: 0px;
  position: relative;
  transition: left 2s ease;
  loop: true;
}

div#six {
  width: 15%;
  height: 50px;
  margin-left: 5px;
  background: red;
  float: left;
  z-index: -1;
  left: 0px;
  position: relative;
  transition: left 2s ease;
  loop: true;
}

div#five {
  width: 15%;
  height: 50px;
  background: black;
  float: left;
  margin-left: 5px;
  z-index: -1;
  left: 0px;
  position: relative;
  transition: left 2s ease;
}

div#two {
  width: 15%;
  height: 50px;
  margin-left: 5px;
  background: red;
  float: left;
  z-index: -1;
  left: 0px;
  position: relative;
  transition: left 2s ease;
}

div#three {
  width: 15%;
  height: 50px;
  margin-left: 5px;
  background: black;
  float: left;
  z-index: -1;
  left: 0px;
  position: relative;
  transition: left 2s ease;
}

div#four {
  width: 15%;
  height: 50px;
  margin-left: 5px;
  background: red;
  float: left;
  z-index: -1;
  left: 0px;
  position: relative;
  transition: left 2s ease;
}</code>```

<button id="right">
left: 100px;
</button>```

so when i click on the button, it should move and then once they go out of the section border, the divs should loop around to the left and show again on the left.

Thanks in advance!

答:
Just add a class with keyframe animation to your jquery code, and set the pixels and time you want:

$("#right").click(function() {
    $("div").addClass("animate")
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>section {
  width: 80%;
  height: 50px;
  border: 5px solid gray;
  margin: auto;
  padding: 7px;
  z-index: 1;
  transition: left 2s ease;
  overflow: hidden;
}

div#one {
  width: 15%;
  height: 50px;
  background: black;
  float: left;
  z-index: -1;
  left: 0px;
  position: relative;
}

div#six {
  width: 15%;
  height: 50px;
  margin-left: 5px;
  background: red;
  float: left;
  z-index: -1;
  left: 0px;
  position: relative;
}

div#five {
  width: 15%;
  height: 50px;
  background: black;
  float: left;
  margin-left: 5px;
  z-index: -1;
  left: 0px;
  position: relative;
}

div#two {
  width: 15%;
  height: 50px;
  margin-left: 5px;
  background: red;
  float: left;
  z-index: -1;
  left: 0px;
  position: relative;
}

div#three {
  width: 15%;
  height: 50px;
  margin-left: 5px;
  background: black;
  float: left;
  z-index: -1;
  left: 0px;
  position: relative;
}

div#four {
  width: 15%;
  height: 50px;
  margin-left: 5px;
  background: red;
  float: left;
  z-index: -1;
  left: 0px;
  position: relative;
}
.animate{
  animation: roulette  7s linear infinite;
}
@keyframes roulette {
    from {left: -550px;}
    to {left: 550px;}
}</code>```

<button id="right">
left: 100px;
</button>```

Title: How to make div loop around in section

Body:
I'm working on a Roulette site, but i don't have any idea how to make the divs loop around.
I need the divs to loop around when they get out of the section border.

$("#right").click(function() {
  $("#one").css("left", "300px");
  $("#two").css("left", "300px");
  $("#three").css("left", "300px");
  $("#four").css("left", "300px");
  $("#five").css("left", "300px");
  $("#six").css("left", "300px");

});

$("#left").click(function() {
  $("#one").css("left", "0px");
});

section {
  width: 80%;
  height: 50px;
  border: 5px solid gray;
  margin: auto;
  padding: 7px;
  z-index: 1;
  transition: left 2s ease;
  overflow: hidden;
}

div#one {
  width: 15%;
  height: 50px;
  background: black;
  float: left;
  z-index: -1;
  left: 0px;
  position: relative;
  transition: left 2s ease;
  loop: true;
}

div#six {
  width: 15%;
  height: 50px;
  margin-left: 5px;
  background: red;
  float: left;
  z-index: -1;
  left: 0px;
  position: relative;
  transition: left 2s ease;
  loop: true;
}

div#five {
  width: 15%;
  height: 50px;
  background: black;
  float: left;
  margin-left: 5px;
  z-index: -1;
  left: 0px;
  position: relative;
  transition: left 2s ease;
}

div#two {
  width: 15%;
  height: 50px;
  margin-left: 5px;
  background: red;
  float: left;
  z-index: -1;
  left: 0px;
  position: relative;
  transition: left 2s ease;
}

div#three {
  width: 15%;
  height: 50px;
  margin-left: 5px;
  background: black;
  float: left;
  z-index: -1;
  left: 0px;
  position: relative;
  transition: left 2s ease;
}

div#four {
  width: 15%;
  height: 50px;
  margin-left: 5px;
  background: red;
  float: left;
  z-index: -1;
  left: 0px;
  position: relative;
  transition: left 2s ease;
}

<button id="right">
left: 100px;
</button>

so when i click on the button, it should move and then once they go out of the section border, the divs should loop around to the left and show again on the left.

Thanks in advance!

Body:
Just add a class with keyframe animation to your jquery code, and set the pixels and time you want:

$("#right").click(function() {
    $("div").addClass("animate")
})

section {
  width: 80%;
  height: 50px;
  border: 5px solid gray;
  margin: auto;
  padding: 7px;
  z-index: 1;
  transition: left 2s ease;
  overflow: hidden;
}

div#one {
  width: 15%;
  height: 50px;
  background: black;
  float: left;
  z-index: -1;
  left: 0px;
  position: relative;
}

div#six {
  width: 15%;
  height: 50px;
  margin-left: 5px;
  background: red;
  float: left;
  z-index: -1;
  left: 0px;
  position: relative;
}

div#five {
  width: 15%;
  height: 50px;
  background: black;
  float: left;
  margin-left: 5px;
  z-index: -1;
  left: 0px;
  position: relative;
}

div#two {
  width: 15%;
  height: 50px;
  margin-left: 5px;
  background: red;
  float: left;
  z-index: -1;
  left: 0px;
  position: relative;
}

div#three {
  width: 15%;
  height: 50px;
  margin-left: 5px;
  background: black;
  float: left;
  z-index: -1;
  left: 0px;
  position: relative;
}

div#four {
  width: 15%;
  height: 50px;
  margin-left: 5px;
  background: red;
  float: left;
  z-index: -1;
  left: 0px;
  position: relative;
}
.animate{
  animation: roulette  7s linear infinite;
}
@keyframes roulette {
    from {left: -550px;}
    to {left: 550px;}
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
  <div id="one"></div>
  <div id="two"></div>
  <div id="three"></div>
  <div id="four"></div>
  <div id="five"></div>
  <div id="six"></div>
</section>

<button id="right">
left: 100px;
</button>


问:
How Make a 2d cube via css
i want have an animation like this:
i want one Square fade in a place holder like code below

```<code>#item1_placeholder{
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 7%;
    content: "";
    display: block;
    padding-bottom: 7%;
                                    border: 3px solid #F4DC03;
</code>```

}

and i want this placeholder and cube resize with resizing display window,

then this Square rotate like a 2d cube in some direction like first show the front, then turn to left, then turn to top

can anyone help me!!!

答:
Check THIS

play around with the css how you like to make the cube

Title: How Make a 2d cube via css

Body:
i want have an animation like this:
i want one Square fade in a place holder like code below

#item1_placeholder{
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 7%;
    content: "";
    display: block;
    padding-bottom: 7%;
                                    border: 3px solid #F4DC03;

}

and i want this placeholder and cube resize with resizing display window,

then this Square rotate like a 2d cube in some direction like first show the front, then turn to left, then turn to top

can anyone help me!!!


问:
How to disable the auto layout of the IntelliJ IDEA UML Diagram?
I've moved from Eclipse to IntelliJ IDEA and I like the its responsiveness.

In Eclipse I use ObjectAid to assist in designing my application structure. IntelliJ IDEA does have a UML diagram but it got really annoying when it keeps re-adjusting my diagram layout to what it thinks is a neat structure. Everytime I add/remove a class, it will re-adjust the layout. It may look neat, but it makes little sense to me. I like to manually place my class model in the exact place I leave it. Why oh why does IntelliJ think it knows best? Can I change this behavior? I can't find any settings in the settings menu.

答:
You can disable this behaviour in the preferences under "Tools" -> "Diagrams". There is an option "Do relayout when new elements were added" which you need to disable.

Note: IntelliJ 2016.3


问:
How can i set @media only screen less then 320px for indetificator?
I have this piece of code. I'm  beginner :/

https://ibb.co/ccrFFG
Id like to add some responsibility by
@media only screen and (max-width: 320px) {}
but it doesnt works with IDs. How would you change the code pls? :)

Thanks

答:
From your code, I don't know exactly what you are trying to achieve but I will advise you to use the code below as a guide.</p>

```<code>  @media screen and (max-width: 320px) {
    #yourID {
        width: 260px !important;
    }
 }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
From your code, I don't know exactly what you are trying to achieve but I will advise you to use the code below as a guide.

  @media screen and (max-width: 320px) {
    #yourID {
        width: 260px !important;
    }
 }


答:
I don't know what is the structure of your database but i think you have to change this query 'SELECT count() FROM course '
to "SELECT count() FROM users_course WHERE course_id = '{$_SESSION['users_id']}' AND user_id = '$course_id'"

Title: show error message when the course is already register in php


问:
Do i need to flush OPCACHE during update magento
I updated my magento and also the (PHP) frameworks with it, a verry simple question where i can't find the answer.

Do i need to flush/clear the OPcache during (before of after) an update of the PhP frameworks?

Is it possible that when i don't do it that there are corrupt files or errors showing up?

答:
Depends on your opcache configuration (php.ini), have a look at the documentation.

See particulary :

opcache.validate-timestamps

opcache.revalidate-freq

If you enable revalidate, you never have to invalidate manually your opcache.

PS : if you disable invalidation, you have to clear opcache after updating your sources.


问:
javascript interactive stack which can push and pop using browser window
I am trying to make an interactive stack application using javascript in browser but I cannot clear my console after every actions.

```<code> <script>
        var st1 = 10;
        var stk1 = new Array(10);
        var count = 0;

        function push1(v) {
            if (st1 === 0) {
                rpiseconsole.log("Stack Overflow");
            }

            else {
                st1 = st1 - 1;
                stk1[st1] = v;

                print1();
            }
        }

        function pop1() {
            var temp = stk1[st1];

            st1 = st1 + 1;
            print1();
            return temp;
        }

        function print1() {
            for (var i = st1; i < 10; i++) {
                rpiseconsole.log(stk1[i]);
            }
        };

        function doJob() {
            var x = document.getElementById("t").value;

            push1(x);
            document.getElementById("t").value = "";
        }

        function doJob1() {
            var p = pop1();
            document.getElementById("t1").value = p;
        }
</script>
</code>```

I am expecting that every time I click on the push button it will print the array of stack and clear the previous results in the console and when I click on the pop button it will take out the last data and print the remaining array into the textarea.

I cannot get the clear option in console and I cannot output my array to the textarea in the same order as I put items into the stack.

答:
Write a method clearConsole() and invoke it before every print command

```<code>function clearConsole() {
  document.getElementById( "rpiseconsole" ).innerHTML = "";
}
</code>```

Demo

var st1 = 10;
var stk1 = new Array(10);
var count = 0;

function push1(v) {
  if (st1 === 0) {
    rpiseconsole.log("Stack Overflow");
  } else {
    st1 = st1 - 1;
    stk1[st1] = v;
    print1();
  }
}

function pop1() {

  var temp = stk1[st1];

  st1 = st1 + 1;
  print1();
  return temp;

}

function print1() {
  clearConsole();
  for (var i = st1; i < 10; i++) {
    rpiseconsole.log(stk1[i]);
  }
};

function doJob() {
  var x = document.getElementById("t").value;
  push1(x);
  document.getElementById("t").value = "";
}

function doJob1() {
  var p = pop1();
  document.getElementById("t1").value = p;
}

function clearConsole() {
  document.getElementById( "rpiseconsole" ).innerHTML = "";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js">
</script>
<div>Procedural Stack with Tight Coupling</div>
<div id="rpisesetup">

  <textarea id="rpiseconsole"></textarea>
  <script src="https://sites.google.com/a/rajeshpatkar.com/library/hub/rpiseconsole.js">
  </script>
  <textarea id="t"></textarea>
  <textarea id="t1"></textarea>
  <button onclick="doJob()">push</button>
  <button onclick="doJob1()">pop</button>
</div></code>```

Body:
I am trying to make an interactive stack application using javascript in browser but I cannot clear my console after every actions.

I am expecting that every time I click on the push button it will print the array of stack and clear the previous results in the console and when I click on the pop button it will take out the last data and print the remaining array into the textarea.

I cannot get the clear option in console and I cannot output my array to the textarea in the same order as I put items into the stack.

Body:
Write a method clearConsole() and invoke it before every print command

function clearConsole() {
  document.getElementById( "rpiseconsole" ).innerHTML = "";
}

Demo

var st1 = 10;
var stk1 = new Array(10);
var count = 0;

function push1(v) {
  if (st1 === 0) {
    rpiseconsole.log("Stack Overflow");
  } else {
    st1 = st1 - 1;
    stk1[st1] = v;
    print1();
  }
}

function pop1() {

  var temp = stk1[st1];

  st1 = st1 + 1;
  print1();
  return temp;

}

function print1() {
  clearConsole();
  for (var i = st1; i < 10; i++) {
    rpiseconsole.log(stk1[i]);
  }
};

function doJob() {
  var x = document.getElementById("t").value;
  push1(x);
  document.getElementById("t").value = "";
}

function doJob1() {
  var p = pop1();
  document.getElementById("t1").value = p;
}

function clearConsole() {
  document.getElementById( "rpiseconsole" ).innerHTML = "";
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js">
</script>
<div>Procedural Stack with Tight Coupling</div>
<div id="rpisesetup">

  <textarea id="rpiseconsole"></textarea>
  <script src="https://sites.google.com/a/rajeshpatkar.com/library/hub/rpiseconsole.js">
  </script>
  <textarea id="t"></textarea>
  <textarea id="t1"></textarea>
  <button onclick="doJob()">push</button>
  <button onclick="doJob1()">pop</button>
</div>


问:
git add repositories into subdirectory preserving history
I have to add one git repository into a subfolder into another repository preserving history of both repositories (merge a composer package repository into the main repository to require with type 'path'). The goal is to have just one repository with all project specific packages in one repository at the end.

I tried the subtree workflow, but with the merge command

```<code>git merge -s ours --no-commit repo/branch
</code>```

I get the following error:

```<code>fatal: refusing to merge unrelated histories
</code>```

How can I manage this?

Thank you for your answers!

Sebastian

答:
From git documentation.

--allow-unrelated-histories

By default, git merge command refuses to merge histories that do not
share a common ancestor. This option can be used to override this
safety when merging histories of two projects that started their lives
independently. As that is a very rare occasion, no configuration
variable to enable this by default exists and will not be added.

Use --allow-unrelated-histories to merge two unrelated histories with git merge command.

Body:
I have to add one git repository into a subfolder into another repository preserving history of both repositories (merge a composer package repository into the main repository to require with type 'path'). The goal is to have just one repository with all project specific packages in one repository at the end.

I tried the subtree workflow, but with the merge command

git merge -s ours --no-commit repo/branch

I get the following error:

fatal: refusing to merge unrelated histories

How can I manage this?

Thank you for your answers!

Sebastian


问:
master local ref ''local out of date'' after fetching in git
I am checking a private remote repo using:

```<code>git remote show origin
</code>```

I get

```<code>* remote origin
  Fetch URL:
  Push  URL:
  HEAD branch: master
  Remote branches:
    master                                      tracked
  Local branches configured for 'git pull':
    master            merges with remote master
  Local refs configured for 'git push':
    master            pushes to master            (local out of date)
</code>```

I read  (local out of date) so I do

```<code>git fetch origin
</code>```

then I repeat the git remote show origin but master is still out of date.
Why is that?

答:
Git has an interface which allows changes in the remote repository to be visible in the local setup via something called remote tracking branches.  These remote tracking branches, which are actually local, mainly exist to represent the state of the remote repository at some point in time.  By default, a local branch called master would track a remote tracking branch called origin/master.  This should not be confused with origin master, which you might see in a Git command to refer to the true remote master branch which lives on your Git repo.

When you do git fetch origin, you update the remote tracking branch for master, but not the actual local master branch.  To make the out of date message go away, you can bring those latest changes into the local master:

```<code>git merge origin/master
</code>```

You could also rebase your local branch on the remote master:

```<code>git rebase origin/master
</code>```

Note that most of the time you would probably just update your working local branch via a git pull, e.g.

```<code>git pull origin master
# or
git pull --rebase origin master
</code>```

Body:
I am checking a private remote repo using:

git remote show origin

I get

* remote origin
  Fetch URL:
  Push  URL:
  HEAD branch: master
  Remote branches:
    master                                      tracked
  Local branches configured for 'git pull':
    master            merges with remote master
  Local refs configured for 'git push':
    master            pushes to master            (local out of date)

I read  (local out of date) so I do

git fetch origin

then I repeat the git remote show origin but master is still out of date.
Why is that?

Body:
Git has an interface which allows changes in the remote repository to be visible in the local setup via something called remote tracking branches.  These remote tracking branches, which are actually local, mainly exist to represent the state of the remote repository at some point in time.  By default, a local branch called master would track a remote tracking branch called origin/master.  This should not be confused with origin master, which you might see in a Git command to refer to the true remote master branch which lives on your Git repo.

When you do git fetch origin, you update the remote tracking branch for master, but not the actual local master branch.  To make the out of date message go away, you can bring those latest changes into the local master:

git merge origin/master

You could also rebase your local branch on the remote master:

git rebase origin/master

Note that most of the time you would probably just update your working local branch via a git pull, e.g.

git pull origin master
# or
git pull --rebase origin master


问:
React router in TypeScript- both router and own props
my component has some own props

```<code>class Props {
  wizard: WizardConfig;
}
</code>```

and I want to access router history so I also pass router props

```<code>type PropsType = Props & RouteComponentProps<{}>;

class Wizard extends React.Component<PropsType> {}
</code>```

The problem is that in component's usage

```<code> <Wizard wizard={someWizar} />
</code>```

I get errors that RouteComponentProps props are not passed so for example:
   Property 'match' is missing in type '{ wizard: WizardConfig; }'

I tried to do:

```<code>export default withRouter(Wizard);
</code>```

but it didn't help.

答:
Fixed by changing

```<code>export default withRouter(Wizard);
</code>```

to

```<code>export default withRouter<PropsType>(Wizard);
</code>```

Body:
my component has some own props

class Props {
  wizard: WizardConfig;
}

and I want to access router history so I also pass router props

type PropsType = Props & RouteComponentProps<{}>;

class Wizard extends React.Component<PropsType> {}

The problem is that in component's usage

 <Wizard wizard={someWizar} />

I get errors that RouteComponentProps props are not passed so for example:
   Property 'match' is missing in type '{ wizard: WizardConfig; }'

I tried to do:

export default withRouter(Wizard);

but it didn't help.

Body:
Fixed by changing

export default withRouter(Wizard);

to

export default withRouter<PropsType>(Wizard);


问:
Add a class to the body - PHP Wordpress
I am trying to add a class to the body in a WordPress theme so that when there are no posts on a page it will not show the search bar. I have in my functions.php right now this to look for one certain page, and if there are no posts.

```<code><?php
add_filter( 'body_class', 'custom_class' );
function custom_class( $classes ) {
    if(strpos($_SERVER['REQUEST_URI'], 'agent') !== false ){
        $classes[] = 'noSearchBar';
    }
    if(!have_posts() ){
      $classes[] = 'noSearchBar';
    }
    return $classes;
}
?>
</code>```

Which works for most of the pages, but on some pages it is using a different template so instead of calling the posts with have_posts like this:

```<code><?php
   global $wp_query;

   if ( have_posts() ) :
       while ( have_posts() ) : the_post();

           get_template_part('template-parts/property-for-listing');

       endwhile;
       wp_reset_postdata();
   else:
       ?>
<h4><?php esc_html_e('Sorry No Results Found', 'houzez') ?></h4>
<?php
   endif;
   ?>
</code>```

Its is bringing it up like this:

```<code><?php
   global $wp_query, $paged;
   if(!$fave_prop_no){
       $posts_per_page  = 9;
   } else {
       $posts_per_page = $fave_prop_no;
   }
   $latest_listing_args = array(
       'post_type' => 'property',
       'posts_per_page' => $posts_per_page,
       'paged' => $paged,
       'post_status' => 'publish'
   );

   $latest_listing_args = apply_filters( 'houzez_property_filter', $latest_listing_args );

   $latest_listing_args = houzez_prop_sort ( $latest_listing_args );
   $wp_query = new WP_Query( $latest_listing_args );

   if ( $wp_query->have_posts() ) :
       while ( $wp_query->have_posts() ) : $wp_query->the_post();

           get_template_part('template-parts/property-for-listing');

       endwhile;
   else:
       get_template_part('template-parts/property', 'none');
   endif;
   ?>
</code>```

Which is making my function not work. There is only 1 line of code in the template-parts/property-none and its just saying the same thing the other files are. So I'm not sure why the other template would not add the body class.

答:
You can do like this example,

```<code><?php
add_filter( 'body_class', 'custom_class' );
function custom_class( $classes ) {
  if ( is_single('post') ) {
     $classes[] = 'SearchBar';
  }else{
     $classes[] = 'noSearchBar';
  }
  return $classes;
}
?>
</code>```

The following example will work for single post page. For more conditions.visit

Hope this will helps you.

Title: Add a class to the body - PHP Wordpress

Body:
I am trying to add a class to the body in a WordPress theme so that when there are no posts on a page it will not show the search bar. I have in my functions.php right now this to look for one certain page, and if there are no posts.

<?php
add_filter( 'body_class', 'custom_class' );
function custom_class( $classes ) {
    if(strpos($_SERVER['REQUEST_URI'], 'agent') !== false ){
        $classes[] = 'noSearchBar';
    }
    if(!have_posts() ){
      $classes[] = 'noSearchBar';
    }
    return $classes;
}
?>

Which works for most of the pages, but on some pages it is using a different template so instead of calling the posts with have_posts like this:

<?php
   global $wp_query;

   if ( have_posts() ) :
       while ( have_posts() ) : the_post();

           get_template_part('template-parts/property-for-listing');

       endwhile;
       wp_reset_postdata();
   else:
       ?>

<?php esc_html_e('Sorry No Results Found', 'houzez') ?>

<?php
   endif;
   ?>

Its is bringing it up like this:

<?php
   global $wp_query, $paged;
   if(!$fave_prop_no){
       $posts_per_page  = 9;
   } else {
       $posts_per_page = $fave_prop_no;
   }
   $latest_listing_args = array(
       'post_type' => 'property',
       'posts_per_page' => $posts_per_page,
       'paged' => $paged,
       'post_status' => 'publish'
   );

   $latest_listing_args = apply_filters( 'houzez_property_filter', $latest_listing_args );

   $latest_listing_args = houzez_prop_sort ( $latest_listing_args );
   $wp_query = new WP_Query( $latest_listing_args );

   if ( $wp_query->have_posts() ) :
       while ( $wp_query->have_posts() ) : $wp_query->the_post();

           get_template_part('template-parts/property-for-listing');

       endwhile;
   else:
       get_template_part('template-parts/property', 'none');
   endif;
   ?>

Which is making my function not work. There is only 1 line of code in the template-parts/property-none and its just saying the same thing the other files are. So I'm not sure why the other template would not add the body class.

Body:
You can do like this example,

<?php
add_filter( 'body_class', 'custom_class' );
function custom_class( $classes ) {
  if ( is_single('post') ) {
     $classes[] = 'SearchBar';
  }else{
     $classes[] = 'noSearchBar';
  }
  return $classes;
}
?>

The following example will work for single post page. For more conditions.visit

Hope this will helps you.


问:
splitting string in SQL Server
Could you please help me with this task. I have a table with two columns (ID, String). String in that column is separated by '#'. And I need to produce column "Cut"

答:
This should to the trick. Split your string in rows and then select distinct values. If you need the String column also, just join your table on id.

```<code>declare @tbl as table (
    id int
    ,string varchar(25)
)

insert into @tbl values (1, 'A#B#C')
insert into @tbl values (1, 'A#B#C')
insert into @tbl values (1, 'A#B#C')
insert into @tbl values (2, 'K#L#X#W#I')
insert into @tbl values (2, 'K#L#X#W#I')
insert into @tbl values (2, 'K#L#X#W#I')
insert into @tbl values (2, 'K#L#X#W#I')
insert into @tbl values (3, 'G')

SELECT DISTINCT [Id], Split.a.value('.', 'VARCHAR(5)') AS [Cut]
FROM (
    SELECT [Id], CAST('<M>' + REPLACE([String], '#', '</M><M>') + '</M>' AS XML) AS [String]
    FROM  @tbl
) AS A CROSS APPLY [String].nodes ('/M') AS Split(a);
</code>```

Title: splitting string in SQL Server

Body:
This should to the trick. Split your string in rows and then select distinct values. If you need the String column also, just join your table on id.

declare @tbl as table (
    id int
    ,string varchar(25)
)

insert into @tbl values (1, 'A#B#C')
insert into @tbl values (1, 'A#B#C')
insert into @tbl values (1, 'A#B#C')
insert into @tbl values (2, 'K#L#X#W#I')
insert into @tbl values (2, 'K#L#X#W#I')
insert into @tbl values (2, 'K#L#X#W#I')
insert into @tbl values (2, 'K#L#X#W#I')
insert into @tbl values (3, 'G')

SELECT DISTINCT [Id], Split.a.value('.', 'VARCHAR(5)') AS [Cut]
FROM (
    SELECT [Id], CAST('<M>' + REPLACE([String], '#', '</M><M>') + '</M>' AS XML) AS [String]
    FROM  @tbl
) AS A CROSS APPLY [String].nodes ('/M') AS Split(a);


问:
How can I stop execution of an outer function within a callback
Lets imagine I have a scenario like this:

```<code>async function some_func() {
  await some_query.catch(async (e) => {
    await some_error_code()
  })

  console.log('The above function ran without an error')
}
</code>```

I only wish for the console.log() to be reached if the asynchronous function ran successfully.  At the moment, my solution is:

```<code>async function some_func() {
  let did_error = false
  await some_query.catch(async (e) => {
    await some_error_code()
    did_error = true
  })

  if (did_error) return

  console.log('The above function ran without an error')
}
</code>```

But that's not great.  Is there any way of handling this without the added bulk?  Similar to multiple for loops:

```<code>outer: for (let i = 0; i < 10; i++) {
  for (let j = 0; j < 10; j++) {
    continue outer;
  }
  console.log('Never called')
}
</code>```

答:
You would usually write either

```<code>function some_func() {
  return some_query().then(res => {
    console.log('The above function ran without an error')
  }, (e) => {
    return some_error_code()
  })
}
</code>```

or

```<code>async function some_func() {
  try {
    await some_query()
  } catch(e) {
    await some_error_code()
    return
  }
  console.log('The above function ran without an error')
}
</code>```

But that's not great. Is there any way of handling this similar to multiple for loops

Yes, it's also possible to use a block:

```<code>async function some_func() {
  noError: {
    try {
      await some_query()
    } catch(e) {
      await some_error_code()
      break noError
    }
    console.log('The above function ran without an error')
  }
  console.log('This will always run afterwards')
}
</code>```

Body:
Lets imagine I have a scenario like this:

async function some_func() {
  await some_query.catch(async (e) => {
    await some_error_code()
  })

  console.log('The above function ran without an error')
}

I only wish for the console.log() to be reached if the asynchronous function ran successfully.  At the moment, my solution is:

async function some_func() {
  let did_error = false
  await some_query.catch(async (e) => {
    await some_error_code()
    did_error = true
  })

  if (did_error) return

  console.log('The above function ran without an error')
}

But that's not great.  Is there any way of handling this without the added bulk?  Similar to multiple for loops:

outer: for (let i = 0; i < 10; i++) {
  for (let j = 0; j < 10; j++) {
    continue outer;
  }
  console.log('Never called')
}

Body:
You would usually write either

function some_func() {
  return some_query().then(res => {
    console.log('The above function ran without an error')
  }, (e) => {
    return some_error_code()
  })
}

or

async function some_func() {
  try {
    await some_query()
  } catch(e) {
    await some_error_code()
    return
  }
  console.log('The above function ran without an error')
}

But that's not great. Is there any way of handling this similar to multiple for loops

Yes, it's also possible to use a block:

async function some_func() {
  noError: {
    try {
      await some_query()
    } catch(e) {
      await some_error_code()
      break noError
    }
    console.log('The above function ran without an error')
  }
  console.log('This will always run afterwards')
}


问:
.NET XSD validation confusion
I am attempting to use an XmlReader and associated XmlReaderSettings object to perform XSD validation on some documents. I am declaring a ValidationEventHandler which I was expecting would get called whenever the reader encounters a validation problem. However I am getting an XSDValidationException when I attempt to create the reader.

Any idea what would cause the exception? The message is:

System.Xml.Schema.XmlSchemaValidationException: The 'http://www.w3.org/XML/1998/namespace:base' attribute is not declared.

Could there be an issue with one of the underlying schemas?

答: Search your schemas and your document for an xml:base attribute. If present, then the schema defining that attribute will need to be in your schema set.

Title: .NET XSD validation confusion


问:
Lifetime of the pointers
I was watching the video of Symbio C++ Seminar with Herb Sutter - (Thrill of a) Lifetime 20.6.2016,
https://www.youtube.com/watch?v=7b75rcHg7z0&t=917s

The following code  has been written from the video 11::24.
p1, p2, and p3 pointers must be invalidated when the scope goes out.
It must give error when trying to dereference the pointers.

I'm using online https://wandbox.org/ environment. Both gcc and clang is giving the following results. Which must be wrong.

Can someone check the same code on Visual Stdio.

Thanks

```<code>#include <iostream>
using namespace std;
#include <vector>
#include <memory>
#include <cstdio>
#include <cassert>
#include <string>
#include <iterator>
#include <algorithm>
#include <array>

int* p1 = nullptr; int* p2 = nullptr; int* p3 = nullptr;

int main() {
    {
        int i = 1;
        struct MyStruct { char a; int i; char c;} s = {'a', 2, 'c'};
        array<int,7> arr = {0,1,2,3,4,5,6};
        p1 = &i;
        p2 = &s.i;
        p3 = & arr[2];
        *p1 =*p2= *p3 = 42;
        cout << *p1 << *p2 << *p3 << endl;
    }
    *p1 = 1; // This must give error
    *p2 = 2;
    *p3 = 3;
    cout << *p1 << *p2 << *p3 << endl;
}
</code>```

This is the output:

```<code>424242
123
</code>```

答:
The behaviour of the code is undefined.

After the first cout statement, the pointers are dangling. They were pointing to variables that had automatic storage duration, and are now out of scope.

A C++ compiler is not required to issue a diagnostic (a dangling pointer cannot always be identified at compilation time), although some will warn you if you have the appropriate flags set. You can cut down the source of the undefined behaviour to

```<code>int main()
{
    int* p;
    {
        int n;
        p = &n;
    }
    *p = 0; // oops
}
</code>```

Title: Lifetime of the pointers

Body:
I was watching the video of Symbio C++ Seminar with Herb Sutter - (Thrill of a) Lifetime 20.6.2016,
https://www.youtube.com/watch?v=7b75rcHg7z0&t=917s

The following code  has been written from the video 11::24.
p1, p2, and p3 pointers must be invalidated when the scope goes out.
It must give error when trying to dereference the pointers.

I'm using online https://wandbox.org/ environment. Both gcc and clang is giving the following results. Which must be wrong.

Can someone check the same code on Visual Stdio.

Thanks

#include <iostream>
using namespace std;
#include <vector>
#include <memory>
#include <cstdio>
#include <cassert>
#include <string>
#include <iterator>
#include <algorithm>
#include <array>

int* p1 = nullptr; int* p2 = nullptr; int* p3 = nullptr;

int main() {
    {
        int i = 1;
        struct MyStruct { char a; int i; char c;} s = {'a', 2, 'c'};
        array<int,7> arr = {0,1,2,3,4,5,6};
        p1 = &i;
        p2 = &s.i;
        p3 = & arr[2];
        *p1 =*p2= *p3 = 42;
        cout << *p1 << *p2 << *p3 << endl;
    }
    *p1 = 1; // This must give error
    *p2 = 2;
    *p3 = 3;
    cout << *p1 << *p2 << *p3 << endl;
}

This is the output:

424242
123

Body:
The behaviour of the code is undefined.

After the first cout statement, the pointers are dangling. They were pointing to variables that had automatic storage duration, and are now out of scope.

A C++ compiler is not required to issue a diagnostic (a dangling pointer cannot always be identified at compilation time), although some will warn you if you have the appropriate flags set. You can cut down the source of the undefined behaviour to

int main()
{
    int* p;
    {
        int n;
        p = &n;
    }
    *p = 0; // oops
}