问:
AutoMapper convert from multiple sources
Let's say I have two model classes:

```<code>public class People {
   public string FirstName {get;set;}
   public string LastName {get;set;}
}
</code>```

Also have a class Phone:

```<code>public class Phone {
   public string Number {get;set;}
}
</code>```

And I want to convert to a PeoplePhoneDto like this:

```<code>public class PeoplePhoneDto {
    public string FirstName {get;set;}
    public string LastName {get;set;}
    public string PhoneNumber {get;set;}
}
</code>```

Let's say in my controller I have:

```<code>var people = repository.GetPeople(1);
var phone = repository.GetPhone(4);

// normally, without automapper I would made
return new PeoplePhoneDto(people, phone) ;
</code>```

Is this possible ?

答:
There's lots of options already provided, but none of them really fit what I wanted. I was falling asleep last night and had the thought:

Lets say you want to map your two classes, People and Phone to PeoplePhoneDto

public class People {
   public string FirstName {get;set;}
   public string LastName {get;set;}
}
```

<p>+</p>

<pre class="lang-cs prettyprint-override"><code>public class Phone {
   public string Number {get;set;}
}
</code>```

=

public class PeoplePhoneDto {
    public string FirstName {get;set;}
    public string LastName {get;set;}
    public string PhoneNumber {get;set;}
}
```

<p>All you really need is another wrapper class for Automapper purposes.</p>

<pre class="lang-cs prettyprint-override"><code>public class PeoplePhone {
    public People People {get;set;}
    public Phone Phone {get;set;}
}
</code>```

And then define the mapping:

CreateMap<PeoplePhone, PeoplePhoneDto>()
```

<p>And use it</p>

<pre class="lang-cs prettyprint-override"><code>var dto = Map<PeoplePhoneDto>(new PeoplePhone
{
    People = people,
    Phone = phone,
});
</code>```

Body:
Let's say I have two model classes:

public class People {
   public string FirstName {get;set;}
   public string LastName {get;set;}
}

Also have a class Phone:

public class Phone {
   public string Number {get;set;}
}

And I want to convert to a PeoplePhoneDto like this:

public class PeoplePhoneDto {
    public string FirstName {get;set;}
    public string LastName {get;set;}
    public string PhoneNumber {get;set;}
}

Let's say in my controller I have:

var people = repository.GetPeople(1);
var phone = repository.GetPhone(4);

// normally, without automapper I would made
return new PeoplePhoneDto(people, phone) ;

Is this possible ?

Body:
There's lots of options already provided, but none of them really fit what I wanted. I was falling asleep last night and had the thought:

Lets say you want to map your two classes, People and Phone to PeoplePhoneDto

public class People {
   public string FirstName {get;set;}
   public string LastName {get;set;}
}

+

public class Phone {
   public string Number {get;set;}
}

=

public class PeoplePhoneDto {
    public string FirstName {get;set;}
    public string LastName {get;set;}
    public string PhoneNumber {get;set;}
}

All you really need is another wrapper class for Automapper purposes.

public class PeoplePhone {
    public People People {get;set;}
    public Phone Phone {get;set;}
}

And then define the mapping:

CreateMap<PeoplePhone, PeoplePhoneDto>()

And use it

var dto = Map<PeoplePhoneDto>(new PeoplePhone
{
    People = people,
    Phone = phone,
});


来源: stackexchange

问:
How to fetch all rows with one matching condition in Sheets?
I have a sheet with two tabs - Common and Dubai.
Common has several columns, namely TGID, CID, City, Country and Comment.
I want to fetch all the records that have Country = Dubai.
Eg.: The formula should help me fetch rows 4 & 5 (Image Attached)
Thanks!
Snippet of sheet</p>

答:
You can use the FILTER function. Based on your snippet, FILTER(A2:E__, D2:D__="Dubai"), where __ is the last row in your data. Also, instead of typing "Dubai" in the formula you can also reference another cell with the country name in it.

Reference: https://support.google.com/docs/answer/3093197?hl=en

ContentLicense: CC BY-SA 4.0


问:
What’s the best way to load a JSONObject from a json text file?
What would be the easiest way to load a file containing JSON into a JSONObject.

At the moment I am using json-lib.

This is what I have, but it throws an exception:

```<code>XMLSerializer xml = new XMLSerializer();
JSON json = xml.readFromFile("samples/sample7.json”);     //line 507
System.out.println(json.toString(2));
</code>```

The output is:

```<code>Exception in thread "main" java.lang.NullPointerException
    at java.io.Reader.<init>(Reader.java:61)
    at java.io.InputStreamReader.<init>(InputStreamReader.java:55)
    at net.sf.json.xml.XMLSerializer.readFromStream(XMLSerializer.java:386)
    at net.sf.json.xml.XMLSerializer.readFromFile(XMLSerializer.java:370)
    at corebus.test.deprecated.TestMain.main(TestMain.java:507)
</code>```

答:
On Google'e Gson library, for having a JsonObject, or more abstract a JsonElement:

```<code>import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

JsonElement json = JsonParser.parseReader( new InputStreamReader(new FileInputStream("/someDir/someFile.json"), "UTF-8") );
</code>```

This is not demanding a given Object structure for receiving/reading the json string.

Edit 2021-May-13:
As I commented myself: This solution does not properly take care of closing streams!

This does:

```<code>JsonElement json = null;
try (Reader reader = new InputStreamReader(new FileInputStream("/someDir/someFile.json"), "UTF-8")) {
    json = JsonParser.parseReader( reader );
} catch (Exception e) {
    // do something
}
</code>```

As one can see the code gets bloated when doing correctly. I would clean-code move the 'loading of a json from a file' into a FileUtils.class; which probably already exists and does super nice adjustable Exception handling...

ContentLicense: CC BY-SA 3.0

Body:
What would be the easiest way to load a file containing JSON into a JSONObject.

At the moment I am using json-lib.

This is what I have, but it throws an exception:

XMLSerializer xml = new XMLSerializer();
JSON json = xml.readFromFile("samples/sample7.json”);     //line 507
System.out.println(json.toString(2));

The output is:

Exception in thread "main" java.lang.NullPointerException
    at java.io.Reader.<init>(Reader.java:61)
    at java.io.InputStreamReader.<init>(InputStreamReader.java:55)
    at net.sf.json.xml.XMLSerializer.readFromStream(XMLSerializer.java:386)
    at net.sf.json.xml.XMLSerializer.readFromFile(XMLSerializer.java:370)
    at corebus.test.deprecated.TestMain.main(TestMain.java:507)

Body:
On Google'e Gson library, for having a JsonObject, or more abstract a JsonElement:

import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

JsonElement json = JsonParser.parseReader( new InputStreamReader(new FileInputStream("/someDir/someFile.json"), "UTF-8") );

This is not demanding a given Object structure for receiving/reading the json string.

Edit 2021-May-13:
As I commented myself: This solution does not properly take care of closing streams!

This does:

JsonElement json = null;
try (Reader reader = new InputStreamReader(new FileInputStream("/someDir/someFile.json"), "UTF-8")) {
    json = JsonParser.parseReader( reader );
} catch (Exception e) {
    // do something
}

As one can see the code gets bloated when doing correctly. I would clean-code move the 'loading of a json from a file' into a FileUtils.class; which probably already exists and does super nice adjustable Exception handling...


问:
close icon doesn't appear
I was trying to add a text popup box on my page, and this code helped me but I need to add a close icon (which is an image in my code)..

but it doesn't work :/

here is my code:

```<code>function show_hide_box(an, width, height, borderStyle) {

if (navigator.userAgent.indexOf("MSIE") != -1) {
    var browserIsIE = true;
} else { browserIsIE = false; }

var href = an.href;
var boxdiv = document.getElementById(href);

if (boxdiv != null) {
if (boxdiv.style.display=='none') {
  move_box(an, boxdiv);
  boxdiv.style.display='block';
} else
  boxdiv.style.display='none';
return false;
}

boxdiv = document.createElement('div');
boxdiv.setAttribute('id', href);
boxdiv.style.display = 'block';
boxdiv.style.position = 'absolute';
boxdiv.style.width = width + 'px';
boxdiv.style.height = height + 'px';
boxdiv.style.border = borderStyle;
boxdiv.style.backgroundColor = '#FFF';

var inClosebox = document.createElement("div");
inClosebox.setAttribute('id', 'Close');
inClosebox.style.position = 'absolute';

if (browserIsIE) {
  inClosebox.style.left = '-1px';
  inClosebox.style.top = '0px';
} else {
  inClosebox.style.left = '-15px';
  inClosebox.style.top = '-15px';
}

inClosebox.style.visibility = 'hidden';

var inImage2 = document.createElement("img");
inImage2.onclick = function () { this.document.close(); };
inImage2.setAttribute('src', '../../Images/closebox.png');
inImage2.setAttribute('width', '30');
inImage2.setAttribute('height', '30');
inImage2.setAttribute('border', '0');
inImage2.style.cursor = 'pointer';
inClosebox.appendChild(inImage2);

var contents = document.createElement('iframe');
contents.scrolling = 'yes';
contents.frameBorder = '0';
contents.style.width = width + 'px';
contents.style.height = height + 'px';
contents.src = href;

boxdiv.appendChild(contents);
boxdiv.appendChild(inClosebox);
document.body.appendChild(boxdiv);
move_box(an, boxdiv);

return false;
}
</code>```

can any help me please?

答:
That should mean that the path of src is wrong. ie, ../../Images/closebox.png

Add this to your code and see whether this works

```<code>inImage2.setAttribute('alt', 'Close');
</code>```

Even if this doesn't work, it shows you that something else is wrong with the code.

Its a very good practice to add alt attribute to img tag always.

Update:

I just saw this inClosebox.style.visibility = 'hidden';
You are appending img to that and so how are you gonna possibly make it visible when the parent is hidden?

Beats me. Or do you have extra code? If no, please remove that line and try.

Title: close icon doesn't appear

Body:
I was trying to add a text popup box on my page, and this code helped me but I need to add a close icon (which is an image in my code)..

but it doesn't work :/

here is my code:

function show_hide_box(an, width, height, borderStyle) {

if (navigator.userAgent.indexOf("MSIE") != -1) {
    var browserIsIE = true;
} else { browserIsIE = false; }

var href = an.href;
var boxdiv = document.getElementById(href);

if (boxdiv != null) {
if (boxdiv.style.display=='none') {
  move_box(an, boxdiv);
  boxdiv.style.display='block';
} else
  boxdiv.style.display='none';
return false;
}

boxdiv = document.createElement('div');
boxdiv.setAttribute('id', href);
boxdiv.style.display = 'block';
boxdiv.style.position = 'absolute';
boxdiv.style.width = width + 'px';
boxdiv.style.height = height + 'px';
boxdiv.style.border = borderStyle;
boxdiv.style.backgroundColor = '#FFF';

var inClosebox = document.createElement("div");
inClosebox.setAttribute('id', 'Close');
inClosebox.style.position = 'absolute';

if (browserIsIE) {
  inClosebox.style.left = '-1px';
  inClosebox.style.top = '0px';
} else {
  inClosebox.style.left = '-15px';
  inClosebox.style.top = '-15px';
}

inClosebox.style.visibility = 'hidden';

var inImage2 = document.createElement("img");
inImage2.onclick = function () { this.document.close(); };
inImage2.setAttribute('src', '../../Images/closebox.png');
inImage2.setAttribute('width', '30');
inImage2.setAttribute('height', '30');
inImage2.setAttribute('border', '0');
inImage2.style.cursor = 'pointer';
inClosebox.appendChild(inImage2);

var contents = document.createElement('iframe');
contents.scrolling = 'yes';
contents.frameBorder = '0';
contents.style.width = width + 'px';
contents.style.height = height + 'px';
contents.src = href;

boxdiv.appendChild(contents);
boxdiv.appendChild(inClosebox);
document.body.appendChild(boxdiv);
move_box(an, boxdiv);

return false;
}

can any help me please?

Body:
That should mean that the path of src is wrong. ie, ../../Images/closebox.png

Add this to your code and see whether this works

inImage2.setAttribute('alt', 'Close');

Even if this doesn't work, it shows you that something else is wrong with the code.

Its a very good practice to add alt attribute to img tag always.

Update:

I just saw this inClosebox.style.visibility = 'hidden';
You are appending img to that and so how are you gonna possibly make it visible when the parent is hidden?

Beats me. Or do you have extra code? If no, please remove that line and try.


问:
Getting the context of a specific page in Wagtail / Puput
I have a Django/Wagtail/Puput site with this structure:

```<code>RootPage
  |
  |- BlogPage (Puput)
  |- InformationPage
</code>```

I'm trying to display summary info from the Puput blog on the InformationPage. This works with this code, as long as I only have one BlogPage:

```<code>class InformationPage(Page):
    body = RichTextField(verbose_name=_("body"))

    . . .

    def get_context(self, request, *args, **kwargs):
        context = super(InformationPage, self).get_context(
            request, *args, **kwargs)
        context['blog_page'] = BlogPage.objects.first()
        context['information_page'] = self
        return context
</code>```

But I'm trying to make it work with more than one blog page. It seems like this should work:

```<code>class InformationPage(Page):
    body = RichTextField(verbose_name=_("body"))
    blog_page = models.ForeignKey('wagtailcore.Page', on_delete=models.PROTECT, related_name="information_blog")

    content_panels = [
        MultiFieldPanel(
            [
                FieldPanel("title", classname="title"),
                FieldPanel("body", classname="full"),
                PageChooserPanel('blog_page'),
            ],
            heading=_("Content"),
        )]

    def get_context(self, request, *args, **kwargs):
        context = super(InformationPage, self).get_context(
            request, *args, **kwargs)
        context['blog_page'] = self.blog_page
        context['information_page'] = self
        return context
</code>```

But it doesn't. This was suggested by @gasman here.  In other words, if I refer to the blog page properties using context['blog_page'] = BlogPage.objects.first(), everything works fine, but switching it out to use context['blog_page'] = self.blog_page (and selecting the correct blog page in the admin) does not work.

Without switching it out, I think I can only ever have a single instance of BlogPage, because all InformationPages will have to pull from the first instance.

Any thoughts?

答:
You haven't given a description of the problem beyond "it doesn't work", so I'm only guessing here, but you're presumably trying to output fields of the blog page that are part of the BlogPage model. This doesn't work because blog_page is defined as a foreign key to wagtailcore.Page, and so accessing self.blog_page only gives you a basic Page object consisting of the core fields such as title. You can retrieve the full BlogPage object by accessing self.blog_page.specific:

```<code>context['blog_page'] = self.blog_page.specific
</code>```

However, a smarter approach is to change your foreign key to point to BlogPage, since presumably choosing any other page type is not valid here:

```<code>blog_page = models.ForeignKey('my_blog_app.BlogPage', on_delete=models.PROTECT, related_name="information_blog")
</code>```

With this change, self.blog_page will return a BlogPage instance directly, and there's no need for .specific.

Body:
I have a Django/Wagtail/Puput site with this structure:

RootPage
  |
  |- BlogPage (Puput)
  |- InformationPage

I'm trying to display summary info from the Puput blog on the InformationPage. This works with this code, as long as I only have one BlogPage:

class InformationPage(Page):
    body = RichTextField(verbose_name=_("body"))

    . . .

    def get_context(self, request, *args, **kwargs):
        context = super(InformationPage, self).get_context(
            request, *args, **kwargs)
        context['blog_page'] = BlogPage.objects.first()
        context['information_page'] = self
        return context

But I'm trying to make it work with more than one blog page. It seems like this should work:

class InformationPage(Page):
    body = RichTextField(verbose_name=_("body"))
    blog_page = models.ForeignKey('wagtailcore.Page', on_delete=models.PROTECT, related_name="information_blog")

    content_panels = [
        MultiFieldPanel(
            [
                FieldPanel("title", classname="title"),
                FieldPanel("body", classname="full"),
                PageChooserPanel('blog_page'),
            ],
            heading=_("Content"),
        )]

    def get_context(self, request, *args, **kwargs):
        context = super(InformationPage, self).get_context(
            request, *args, **kwargs)
        context['blog_page'] = self.blog_page
        context['information_page'] = self
        return context

But it doesn't. This was suggested by @gasman here.  In other words, if I refer to the blog page properties using context['blog_page'] = BlogPage.objects.first(), everything works fine, but switching it out to use context['blog_page'] = self.blog_page (and selecting the correct blog page in the admin) does not work.

Without switching it out, I think I can only ever have a single instance of BlogPage, because all InformationPages will have to pull from the first instance.

Any thoughts?

Body:
You haven't given a description of the problem beyond "it doesn't work", so I'm only guessing here, but you're presumably trying to output fields of the blog page that are part of the BlogPage model. This doesn't work because blog_page is defined as a foreign key to wagtailcore.Page, and so accessing self.blog_page only gives you a basic Page object consisting of the core fields such as title. You can retrieve the full BlogPage object by accessing self.blog_page.specific:

context['blog_page'] = self.blog_page.specific

However, a smarter approach is to change your foreign key to point to BlogPage, since presumably choosing any other page type is not valid here:

blog_page = models.ForeignKey('my_blog_app.BlogPage', on_delete=models.PROTECT, related_name="information_blog")

With this change, self.blog_page will return a BlogPage instance directly, and there's no need for .specific.


问:
Recursive generic function with type passed as a parameter
I want to have a recursive generic function, but I cannot use type passed as an argument in generic function invocation, cause of

```<code>'memberType' refers to a value, but is being used as a type here.
</code>```

Is there a way to pass memberType to generic method invocation?

Example:

```<code>class Packet {
  header: Header
  body: Body

  static MEMBERS = [
    ['header', Header, 0,  6],
    ['body',   Body,   6, 10],
  ]
}

class Header {
  size: number
  ttl: number

  static MEMBERS = [
      ['size', 'number',   0,  2],
      ['ttl',  'number',   2,  3],
  ]
}

class Body {
  raw: string

  static MEMBERS = [
      ['raw', 'string',   0,  10]
  ]
}

class Deserializer {
  static Deserialize<T>(serialized: string, type: { new(): T ;}): T {
      const obj = new type();

      const members = obj.constructor['MEMBERS'];

      for(const member of members) {
          var [memberName, memberType, startOffset, len] = member;
          const serializedMember = serialized.substr(startOffset, len) // cut string holding serialized member (like 'qwertyuiop' from example)

          if(memberType == 'number') { // handle primitive type differently
            obj[memberName] = parseInt(serializedMember);
          } else if(memberType == 'string') { // handle primitive type differently
            obj[memberName] = serializedMember

          } else { // handle non primitives, like Header and Body

// *** issue is on the following line ***
            obj[memberName] = Deserialize<memberType>() // 'memberType' refers to a value, but is being used as a type here.
          }

      }

      return obj as T;
  }
}

//                  HEADRBOOOOOOODY - description of `serialized` string below
//                  SSTTL (where SS = header.size, TTL = header.ttl)
const serialized = '11222qwertyuiop'
const packet: Packet = Deserializer.Deserialize<Packet>(serialized, Packet)

// expected `packet` object structure after running `Deserialize`
// Packet
//   * header -> Header
//                 * size -> 11
//                 * ttl  -> 222
//   * body -> Body
//               * raw -> BOOOOOOODY
</code>```

答:
Right, memberType is a value, not a type.  You could get its type from the compiler as typeof memberType, but in your case the recursive call to Deserialize needs arguments, from which the generic type parameter can be inferred as typeof memberType if you pass it in:

```<code>obj[memberName] = Deserializer.Deserialize(serializedMember, memberType);
</code>```

That should clear up the problem you asked about, but the example code has a lot of type errors and implicit any issues which you should probably address.

One way to address them is via slight refactoring and the judicious use of type assertions to deal with the places that the compiler can't verify as safe (e.g. obj[memberName] = parseInt(...) won't work without an assertion because the compiler won't realize that the property at memberName should be a number, since it's a higher order inference it can't perform).  Maybe something like:

```<code>type DeserializableClass<T> = {
  new(): T,
  MEMBERS: readonly {
    [K in keyof T]: readonly [K, string | DeserializableClass<T[K]>, number, number]
  }[keyof T][]
}

class Deserializer {
  static Deserialize<T>(serialized: string, type: DeserializableClass<T>): T {
    const obj = new type();

    const members = type.MEMBERS;

    for (const member of members) {
      var [memberName, memberType, startOffset, len] = member;
      const serializedMember = serialized.substr(startOffset, len) // cut string holding serialized member (like 'qwertyuiop' from example)

      if (typeof memberType !== "string") {
        obj[memberName] = Deserializer.Deserialize(serializedMember, memberType);
      } else if (memberType == 'number') { // handle primitive type differently
        obj[memberName] = parseInt(serializedMember) as any as T[keyof T];
      } else if (memberType == 'string') { // handle primitive type differently
        obj[memberName] = serializedMember as any as T[keyof T];
      }

    }
    return obj;
  }
}
</code>```

Here we've described more exactly what kind of class can be deserialized: it has to have a MEMBERS property with the right sort of array of tuples.  Note that this isn't perfectly type safe because T[keyof T] is too wide, and you can keep changing things to be safer, but at that point I'd be inclined to make your MEMBERS property hold deserializers for primitives also and give up on the strings.  Note how the compiler sees the recursive Deserialize call as acceptable, but it still needs to be told that the string and number cases work.

Also, in order for this to accept Packet you need to ensure that your MEMBERS static properties are sufficiently literal (tuples tend to get widened to arrays); an easy way to do that is with a const assertion, like:

```<code>static MEMBERS = [
  ['size', 'number', 0, 2],
  ['ttl', 'number', 2, 3],
] as const
</code>```

Anyway I won't go farther into the refactoring than this for now.  Hope this helps.  Good luck!

Playground link to code

Body:
I want to have a recursive generic function, but I cannot use type passed as an argument in generic function invocation, cause of

'memberType' refers to a value, but is being used as a type here.

Is there a way to pass memberType to generic method invocation?

Example:

class Packet {
  header: Header
  body: Body

  static MEMBERS = [
    ['header', Header, 0,  6],
    ['body',   Body,   6, 10],
  ]
}

class Header {
  size: number
  ttl: number

  static MEMBERS = [
      ['size', 'number',   0,  2],
      ['ttl',  'number',   2,  3],
  ]
}

class Body {
  raw: string

  static MEMBERS = [
      ['raw', 'string',   0,  10]
  ]
}

class Deserializer {
  static Deserialize<T>(serialized: string, type: { new(): T ;}): T {
      const obj = new type();

      const members = obj.constructor['MEMBERS'];

      for(const member of members) {
          var [memberName, memberType, startOffset, len] = member;
          const serializedMember = serialized.substr(startOffset, len) // cut string holding serialized member (like 'qwertyuiop' from example)

          if(memberType == 'number') { // handle primitive type differently
            obj[memberName] = parseInt(serializedMember);
          } else if(memberType == 'string') { // handle primitive type differently
            obj[memberName] = serializedMember

          } else { // handle non primitives, like Header and Body

// *** issue is on the following line ***
            obj[memberName] = Deserialize<memberType>() // 'memberType' refers to a value, but is being used as a type here.
          }

      }

      return obj as T;
  }
}

//                  HEADRBOOOOOOODY - description of `serialized` string below
//                  SSTTL (where SS = header.size, TTL = header.ttl)
const serialized = '11222qwertyuiop'
const packet: Packet = Deserializer.Deserialize<Packet>(serialized, Packet)

// expected `packet` object structure after running `Deserialize`
// Packet
//   * header -> Header
//                 * size -> 11
//                 * ttl  -> 222
//   * body -> Body
//               * raw -> BOOOOOOODY

Body:
Right, memberType is a value, not a type.  You could get its type from the compiler as typeof memberType, but in your case the recursive call to Deserialize needs arguments, from which the generic type parameter can be inferred as typeof memberType if you pass it in:

obj[memberName] = Deserializer.Deserialize(serializedMember, memberType);

That should clear up the problem you asked about, but the example code has a lot of type errors and implicit any issues which you should probably address.

One way to address them is via slight refactoring and the judicious use of type assertions to deal with the places that the compiler can't verify as safe (e.g. obj[memberName] = parseInt(...) won't work without an assertion because the compiler won't realize that the property at memberName should be a number, since it's a higher order inference it can't perform).  Maybe something like:

type DeserializableClass<T> = {
  new(): T,
  MEMBERS: readonly {
    [K in keyof T]: readonly [K, string | DeserializableClass<T[K]>, number, number]
  }[keyof T][]
}

class Deserializer {
  static Deserialize<T>(serialized: string, type: DeserializableClass<T>): T {
    const obj = new type();

    const members = type.MEMBERS;

    for (const member of members) {
      var [memberName, memberType, startOffset, len] = member;
      const serializedMember = serialized.substr(startOffset, len) // cut string holding serialized member (like 'qwertyuiop' from example)

      if (typeof memberType !== "string") {
        obj[memberName] = Deserializer.Deserialize(serializedMember, memberType);
      } else if (memberType == 'number') { // handle primitive type differently
        obj[memberName] = parseInt(serializedMember) as any as T[keyof T];
      } else if (memberType == 'string') { // handle primitive type differently
        obj[memberName] = serializedMember as any as T[keyof T];
      }

    }
    return obj;
  }
}

Here we've described more exactly what kind of class can be deserialized: it has to have a MEMBERS property with the right sort of array of tuples.  Note that this isn't perfectly type safe because T[keyof T] is too wide, and you can keep changing things to be safer, but at that point I'd be inclined to make your MEMBERS property hold deserializers for primitives also and give up on the strings.  Note how the compiler sees the recursive Deserialize call as acceptable, but it still needs to be told that the string and number cases work.

Also, in order for this to accept Packet you need to ensure that your MEMBERS static properties are sufficiently literal (tuples tend to get widened to arrays); an easy way to do that is with a const assertion, like:

static MEMBERS = [
  ['size', 'number', 0, 2],
  ['ttl', 'number', 2, 3],
] as const

Anyway I won't go farther into the refactoring than this for now.  Hope this helps.  Good luck!

<a href="https://www.typescriptlang.org/play?strictPropertyInitialization=false#code/MYGwhgzhAEASCmYAm8BO0DeAoa0IEsAveALmgDsBXAWwCM0doAXJkMquhxiJsJ-YNACyAUSEAhEQCUAytAC80ANqNcSgOQFi6gDTR1Heql3QADHoBMAXR2rl6liBMGaRkxb0BmG4yvRI0MAA9uQ8WAC+0FhYoJAw4kFIAJ6YjKhgAO5kPKj45ADm0bg8fALCYpKyCsp2GukZzjl5+Sbm0ACMpla+-jDBoUwR0bFQ0AAKYMAA1vBMqbgAFogoqGQIyAy4tIlJZAnJRXi8-IKiEtJyiiq4aupLG8Z66yt6bQBsPjf228km+0l6N56TqfaB+AL9MLhaJYJhJAAO8GgABF4BA0PgwCAiGBaCB4ABhcBQAA8ABUAHzVbC4cjwDIACgAlGQybZcGdKjIyKhliEQCkaTclABpaB5aAzJJBABm0DJVh5fPIAuUIr0TQK0AAPii0RisTi8YTiRByaKrBS9IY0NbXGhurhwkopbL5VYlN1oTFTXr0blDcR0EKSic-QbscRyRSGf7MZH4EhskxcgU9HDEWRUXHA7j8US4tGWfL5jdIXMgrQAFbVOkZZgI+DMgDch1w5eg1HgnFQMEUGfgADpORdW3YZUF0AyO12e9A3bOjBAmaWvgA3MDoJSLtAAOTAXb0O9QZMbGt4qCYAHkZTL0Uw9PjyH5FMfW192yEeHgI0RE0JuyMaocwTJBBwgShaByWML2vW970feByBXAB6FDAkoOZNXyaAFiCEAkGaH8A1AztALQaAGWxGZ9AARwyNA4UofAgnhdRoBlVAgmoaB4AADwPeF8SZNsbnwOUGQHBdyJPRtoAAQnkRQACJsOUlchQ-edq23GT9y7F9wxIv9UEHbNf2IWMLP-GSjxk09ESZd8P0ieAQHRcUJOPBykSU-QbWMDToDQ3CwHIJB8WgeFcmofB+DXJEB2gQjbzQJDWCSOwvkrKtdJ7fT4EM+FN3RABJcgmCs4ziCQACexXAIwpSAIyRdeBpTlBVnK+Vz3KRcTKO8uS-M0FNmnUIKQoWMKIqRaL8Fi+LErklKZTSiqBSym4cryowCsMkC-1qmTen8chmpgVrXU6qxupub0ersXkmEoVByG0qtnOhb0Qq0v6vlgEQAEFkSkcQrwhyGr2RABNaAAFpkrRYBcnhfgQnnOUAANDpqrGjlTHD6BAIIMiwX7-v+mQZDJMkABlKIyJZeWganqnuFZwL-PRaYZxQObQQdHBXKIO1xxNqnUdp2gsWX6MYpJmNY9QYi-OZiumWYyAmTW5kUczqsFg34z-EkdZmJgY3FpA9HN2YRPJ9D+MRYAmAlrGNYt-GcvgV2CcoV3XqRMAZTd9BUEochyCIrHjcDeAscd8ZJgtpPcAAKlw5YKPhqlngYCnKY-TOtCRXOOnaNOi+L5hWFwcvZYsKvM5+FJy-+Kvq+gTP6gRqlwahiHYaAA" rel="nofollow noreferrer">Playground link to code


问:
Combine two NumPy arrays into one structured array for appending to a PyTables table
I have two unstructured NumPy arrays a and b with shapes (N,) and (N, 256, 2) respectively and dtype np.float. I wish to combine these into a single structured array with shape (N,) and dtype [('field1', np.float), ('field2', np.float, (256, 2))].

The documentation on this is surprisingly lacking. I've found methods like np.lib.recfunctions.merge_arrays but have not been able to find the precise combination of features required to do this.

For the sake of avoiding the XY problem, I'll state my wider aims.

I have a PyTables table with layout {"field1": tables.FloatCol(), "field2": tables.FloatCol(shape = (256, 2))}. The two NumPy arrays represent N new rows to be appended to each of these fields. N is large, so I wish to do this with a single efficient table.append(rows) call, rather than the slow process of looping through table.row['field'] = ....

The table.append documentation says

The rows argument may be any object which can be converted to a structured array compliant with the table structure (otherwise, a ValueError is raised). This includes NumPy structured arrays, lists of tuples or array records, and a string or Python buffer.

Converting my arrays to an appropriate structured array seems to be what I should be doing here. I'm looking for speed, and I anticipate the other options being slower.

Body:
Define the dtype, and create an empty/zeros array:

In [163]: dt = np.dtype([('field1', np.float), ('field2', np.float, (4, 2))])
In [164]: arr = np.zeros(3, dt)     # float display is prettier
In [165]: arr
Out[165]:
array([(0., [[0., 0.], [0., 0.], [0., 0.], [0., 0.]]),
       (0., [[0., 0.], [0., 0.], [0., 0.], [0., 0.]]),
       (0., [[0., 0.], [0., 0.], [0., 0.], [0., 0.]])],
      dtype=[('field1', '<f8'), ('field2', '<f8', (4, 2))])

Assign values field by field:

In [166]: arr['field1'] = np.arange(3)
In [167]: arr['field2'].shape
Out[167]: (3, 4, 2)
In [168]: arr['field2'] = np.arange(24).reshape(3,4,2)
In [169]: arr
Out[169]:
array([(0., [[ 0.,  1.], [ 2.,  3.], [ 4.,  5.], [ 6.,  7.]]),
       (1., [[ 8.,  9.], [10., 11.], [12., 13.], [14., 15.]]),
       (2., [[16., 17.], [18., 19.], [20., 21.], [22., 23.]])],
      dtype=[('field1', '<f8'), ('field2', '<f8', (4, 2))])

np.rec does have a function that works similarly:

In [174]: np.rec.fromarrays([np.arange(3.), np.arange(24).reshape(3,4,2)], dtype=dt)
Out[174]:
rec.array([(0., [[ 0.,  1.], [ 2.,  3.], [ 4.,  5.], [ 6.,  7.]]),
           (1., [[ 8.,  9.], [10., 11.], [12., 13.], [14., 15.]]),
           (2., [[16., 17.], [18., 19.], [20., 21.], [22., 23.]])],
          dtype=[('field1', '<f8'), ('field2', '<f8', (4, 2))])

This is the same, except fields can be accessed as attributes (as well).  Under the covers it does the same by-field assignment.

numpy.lib.recfunctions is another collection of structured array functions.  These too mostly follow the by-field assignment approach.


问:
Laravel Eloquent - Attach vs. SyncWithoutDetaching
What is the difference between syncWithoutDetaching and attach in Laravel?</p>

答:
Let's assume that you have auto-increment primary key id in your pivot table, you will notice:

attach() will add the new records to the pivot table, and pre-existed relations will get fresh ids.

sync() will remove all existed relations and set only provided in current request, with fresh ids too.

syncWithoutDetaching() will not remove all existing relations missing from the one provided in current process, then the pre-existed rows won't get new ids.


问:
How to use python tornado @gen.coroutine with long running functions
I have a web app that is also doing really intensive data processing.
Some of the functions are extremely slow (think a couple of minutes).

Until now I had an architecture that was spawning new threads/process per connection so those slow functions don't block other users. But this is consuming way too much memory and it is against tornado architecture.

So I am wondering if there is a solution to this kind of issue.
My code look like this:

```<code># code that is using to much memory because of the new threads being spawned
def handler():
   thread = Thread(target = really_slow_function)
   thread.start()
   thread.join()
   return "done"

def really_slow_function():
   # this is an example of an intensive function
   # which should be treated as a blackbox
   sleep(100)
   return "done"
</code>```

After refactoring I have the following code:

```<code>#code that doesn't scale because all the requests are block on that one slow request.
@gen.coroutine
def handler():
   yield really_slow_function()
   raise gen.Return("done")

def really_slow_function():
   # this is an example of an intensive function
   # which should be treated as a blackbox
   sleep(100)
   return "done"
</code>```

The issue with this refactor is that the tornado server is blocking on the really_slow_function and not able to serve the other requests in the meantime.

So the question is: is there a way of refactoring the handler WITHOUT touching the really_slow_function and WITHOUT creating new threads/process?

答:
Use a ThreadPoolExecutor (from the concurrent.futures package) to run long-running function in separate threads without starting a new thread each time.

```<code>async def handler():
    await IOLoop.current().run_in_executor(None, really_slow_function)
    return "done"
</code>```

If you want to control exactly how many threads are eligible to run this function, you can make your own executor and pass it instead of None.

Body:
I have a web app that is also doing really intensive data processing.
Some of the functions are extremely slow (think a couple of minutes).

Until now I had an architecture that was spawning new threads/process per connection so those slow functions don't block other users. But this is consuming way too much memory and it is against tornado architecture.

So I am wondering if there is a solution to this kind of issue.
My code look like this:

# code that is using to much memory because of the new threads being spawned
def handler():
   thread = Thread(target = really_slow_function)
   thread.start()
   thread.join()
   return "done"

def really_slow_function():
   # this is an example of an intensive function
   # which should be treated as a blackbox
   sleep(100)
   return "done"

After refactoring I have the following code:

#code that doesn't scale because all the requests are block on that one slow request.
@gen.coroutine
def handler():
   yield really_slow_function()
   raise gen.Return("done")

def really_slow_function():
   # this is an example of an intensive function
   # which should be treated as a blackbox
   sleep(100)
   return "done"

The issue with this refactor is that the tornado server is blocking on the really_slow_function and not able to serve the other requests in the meantime.

So the question is: is there a way of refactoring the handler WITHOUT touching the really_slow_function and WITHOUT creating new threads/process?

Body:
Use a ThreadPoolExecutor (from the concurrent.futures package) to run long-running function in separate threads without starting a new thread each time.

async def handler():
    await IOLoop.current().run_in_executor(None, really_slow_function)
    return "done"

If you want to control exactly how many threads are eligible to run this function, you can make your own executor and pass it instead of None.


问:
How to patch the python 3 breakpoint() builtin?
I wrote a decorator that halts my program with breakpoint() if a critical error happens.

```<code>def the_breakpoint_dec(func):
    @functools.wraps(func):
    async def my_wrapper(func):
       retval=await func(*args,**kwargs)
       return retval if retval else breakpoint()
    return my_wrapper
</code>```

I'm doing unit testing and want to make sure the breakpoint hits, without actually triggering it, so I've been trying to patch breakpoint() with the @mock.patch decorator, but it's not working. Some of the tested paths to breakpoint of the 20 or so i've tried
are

```<code>@mock.patch('pdb.breakpoint')
@mock.patch('builtins.breakpoint')
@mock.patch('builtins.pdb.breakpoint')
@mock.patch('my_module.breakpoint')
@mock.patch('my_module.builtins.breakpoint')
@mock.patch('sys.breakpointhook')
@mock.patch('my_module.sys.breakpointhook')
@mock.patch('my_decorator_module.sys.breakpointhook')
@mock.patch('my_decorator_module.sys.breakpoint')

</code>```

I then make the test function def and pass in the mock:

```<code>#testmodule.py
pytestmark=pytest.mark.asyncio
@mock.patch('just_another_path_to_breakpoint()_that_doesnt_work')
async def test_func_to_test(self, mock_breakpoint, some_other_mock):
    mock_breakpoint.return_value=None
    await decorated_func()
    mock_breakpoint.assert_called() # never hit because pdb prompt opens in interpreter
</code>```

module under test

```<code>#moduleundertest.py

class bar:
    @the_breakpoint_dec
    async def decorated_func(self):
        for i in range(3)
            try:
                return await something_likely_to_fail()
            except:
                pass
</code>```

Initially the breakpoint() I wanted to patch was being called from the mentioned decorator. After several hours of failures I commented out the decorator and moved breakpoint() directly into the method under test. The the patching still failed. What is the proper way to patch this builtin, and if some special thing must be done to patch it when it's in a decorator, what thing is that?

答:
To solve, upgrade your project to 3.8!

I tried to reproduce your scenario in 3.8 and couldn't, the patching worked fine for me. But then when trying with 3.7 and below, the patching stopped working and my program would enter the breakpoint. I have no explanation for this.

Here's a complete running example I coded up. It runs the function_to_test, simulating success and then failure (True/False). As proven by the asserts it only invokes breakpoint() in the failure case, but the test exits cleanly due to our mocked breakpoint() -- at least in 3.8.

```<code>from unittest import mock
import functools
import asyncio

def break_if_function_fails(func):
    @functools.wraps(func)
    async def my_wrapper(*args, **kwargs):
        retval = await func(*args, **kwargs)
        return retval if retval else breakpoint()
    return my_wrapper

@break_if_function_fails
async def function_to_test(retval):
    return retval

@mock.patch('builtins.breakpoint')
async def do_test(mock_breakpoint):
    print('Entering test')
    await function_to_test(True)
    mock_breakpoint.assert_not_called()
    await function_to_test(False)
    mock_breakpoint.assert_called()
    print('Exiting test')

asyncio.run(do_test())
</code>```

The exact same code does not finish but triggers the breakpoint in 3.7.

If you must stay with 3.7, you can still do

```<code>@mock.patch('builtins.breakpoint')
async def do_test(mock_breakpoint):
    backup_breakpoint = builtins.breakpoint
    builtins.breakpoint = mock_breakpoint
    ...
    builtins.breakpoint = backup_breakpoint
</code>```

but this is obviously ugly.

Body:
I wrote a decorator that halts my program with breakpoint() if a critical error happens.

def the_breakpoint_dec(func):
    @functools.wraps(func):
    async def my_wrapper(func):
       retval=await func(*args,**kwargs)
       return retval if retval else breakpoint()
    return my_wrapper

I'm doing unit testing and want to make sure the breakpoint hits, without actually triggering it, so I've been trying to patch breakpoint() with the @mock.patch decorator, but it's not working. Some of the tested paths to breakpoint of the 20 or so i've tried
are

@mock.patch('pdb.breakpoint')
@mock.patch('builtins.breakpoint')
@mock.patch('builtins.pdb.breakpoint')
@mock.patch('my_module.breakpoint')
@mock.patch('my_module.builtins.breakpoint')
@mock.patch('sys.breakpointhook')
@mock.patch('my_module.sys.breakpointhook')
@mock.patch('my_decorator_module.sys.breakpointhook')
@mock.patch('my_decorator_module.sys.breakpoint')

I then make the test function def and pass in the mock:

#testmodule.py
pytestmark=pytest.mark.asyncio
@mock.patch('just_another_path_to_breakpoint()_that_doesnt_work')
async def test_func_to_test(self, mock_breakpoint, some_other_mock):
    mock_breakpoint.return_value=None
    await decorated_func()
    mock_breakpoint.assert_called() # never hit because pdb prompt opens in interpreter

module under test

#moduleundertest.py

class bar:
    @the_breakpoint_dec
    async def decorated_func(self):
        for i in range(3)
            try:
                return await something_likely_to_fail()
            except:
                pass

Initially the breakpoint() I wanted to patch was being called from the mentioned decorator. After several hours of failures I commented out the decorator and moved breakpoint() directly into the method under test. The the patching still failed. What is the proper way to patch this builtin, and if some special thing must be done to patch it when it's in a decorator, what thing is that?

Body:
To solve, upgrade your project to 3.8!

I tried to reproduce your scenario in 3.8 and couldn't, the patching worked fine for me. But then when trying with 3.7 and below, the patching stopped working and my program would enter the breakpoint. I have no explanation for this.

Here's a complete running example I coded up. It runs the function_to_test, simulating success and then failure (True/False). As proven by the asserts it only invokes breakpoint() in the failure case, but the test exits cleanly due to our mocked breakpoint() -- at least in 3.8.

from unittest import mock
import functools
import asyncio

def break_if_function_fails(func):
    @functools.wraps(func)
    async def my_wrapper(*args, **kwargs):
        retval = await func(*args, **kwargs)
        return retval if retval else breakpoint()
    return my_wrapper

@break_if_function_fails
async def function_to_test(retval):
    return retval

@mock.patch('builtins.breakpoint')
async def do_test(mock_breakpoint):
    print('Entering test')
    await function_to_test(True)
    mock_breakpoint.assert_not_called()
    await function_to_test(False)
    mock_breakpoint.assert_called()
    print('Exiting test')

asyncio.run(do_test())

The exact same code does not finish but triggers the breakpoint in 3.7.

If you must stay with 3.7, you can still do

@mock.patch('builtins.breakpoint')
async def do_test(mock_breakpoint):
    backup_breakpoint = builtins.breakpoint
    builtins.breakpoint = mock_breakpoint
    ...
    builtins.breakpoint = backup_breakpoint

but this is obviously ugly.


问:
Laravel Carbon returns incorrect time
I have an issue with my Laravel app that I'm developing, the returns time is incorrect, I did specify the timezone on both config/app.php and php.ini file, and I did clear the cache on Laravel using the following commands:

```<code>php artisan cache:clear
php artisan view:clear
php artisan config:cache
</code>```

Also, I restarted my PHP service after changing the timezone in php.ini file.
I'm using XAMPP as a server.

Please note: the only correct time is by using pure php function!

Anyone can help me in resolving this issue?

答:
The time is correct: Z at the end of the string means GMT (Zulu timezone).

When a Carbon instance is output in a JSON response, it's always converted in the ISO-8601 string and given in GMT timezone, as it's the standard and very recommended way to exchange date information between systems (and so in a JSON API). If you try to pass new Date('2020-08-20T06:46:34.407Z') in a browser, you will see that it's automatically converted by the browser into the user timezone.

If you try:

```<code>Carbon::now()->format('Y-m-d H:i:s.u')
</code>```

You will see it uses the timezone you chose. And you also make it appear in the output:

```<code>Carbon::now()->format('Y-m-d H:i:s.u e')
</code>```

So a system/browser in a different timezone won't mess it up.

Still the best move is to work with UTC on your server side and only use the Asia/Riyadh at the very last moment when you want to display the date on a particular user you know is in this timezone.

I explained it more in details here: https://medium.com/@kylekatarnls/always-use-utc-dates-and-times-8a8200ca3164

Title: Laravel Carbon returns incorrect time

Body:
I have an issue with my Laravel app that I'm developing, the returns time is incorrect, I did specify the timezone on both config/app.php and php.ini file, and I did clear the cache on Laravel using the following commands:

php artisan cache:clear
php artisan view:clear
php artisan config:cache

Also, I restarted my PHP service after changing the timezone in php.ini file.
I'm using XAMPP as a server.

Please note: the only correct time is by using pure php function!

Anyone can help me in resolving this issue?

Body:
The time is correct: Z at the end of the string means GMT (Zulu timezone).

When a Carbon instance is output in a JSON response, it's always converted in the ISO-8601 string and given in GMT timezone, as it's the standard and very recommended way to exchange date information between systems (and so in a JSON API). If you try to pass new Date('2020-08-20T06:46:34.407Z') in a browser, you will see that it's automatically converted by the browser into the user timezone.

If you try:

Carbon::now()->format('Y-m-d H:i:s.u')

You will see it uses the timezone you chose. And you also make it appear in the output:

Carbon::now()->format('Y-m-d H:i:s.u e')

So a system/browser in a different timezone won't mess it up.

Still the best move is to work with UTC on your server side and only use the Asia/Riyadh at the very last moment when you want to display the date on a particular user you know is in this timezone.

I explained it more in details here: https://medium.com/@kylekatarnls/always-use-utc-dates-and-times-8a8200ca3164


问:
Using Xcode 11.4.1, Why do these errors show in the animation part?
Why am I getting these errors when I try to call the animation function, handleTapAnimation(), inside of viewDidLoad()? I provided a relevant screenshot below the code snippet.

For reference, I am using Xcode 11.4.1 as my IDE.

```<code>import UIKit

class ViewController: UIViewController {

  // Other methods

  override func viewDidLoad() {
    super.viewDidLoad()

    setupLabel()
    setupStackView()

    //animation
    view.addGestureRecognizer(UITapGestureRecognizer(target: self,
                                                     action: #selector(handleTapAinmation)))

  }
  @objc fileprivate func handleTapAnimation() {
    print ("Animating")

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

      self.titleLabel.transform = CGAffineTransform(translationX: -30, y: 0)

    }) { (_) in
      UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {

        self.titleLabel.alpha = 0
        self.titleLabel.transform =
        self.titleLabel.transform.translatedBy(x: 0,y: -200)

      })
    }

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

      self.titleLabel.transform = CGAffineTransform(translationX: -30, y: 0)

    }) { (_) in
      UIView.animate(withDuration: 0.5, delay: 0.5, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {

        self.bodyLabel.alpha = 0
        self.bodyLabel.transform =
          self.bodyLabel.transform.translatedBy(x: 0,y: -200)

      })
    }
  }
</code>```

Any help is much appreciated.

答:
just copy the line 46 and paste it into viewdidload()
and put the handleTapAnimation() func to the viewcontroller class because you wrote it outside the viewcontroller as iguess</p>

Body:
Why am I getting these errors when I try to call the animation function, handleTapAnimation(), inside of viewDidLoad()? I provided a relevant screenshot below the code snippet.

For reference, I am using Xcode 11.4.1 as my IDE.

import UIKit

class ViewController: UIViewController {

  // Other methods

  override func viewDidLoad() {
    super.viewDidLoad()

    setupLabel()
    setupStackView()

    //animation
    view.addGestureRecognizer(UITapGestureRecognizer(target: self,
                                                     action: #selector(handleTapAinmation)))

  }
  @objc fileprivate func handleTapAnimation() {
    print ("Animating")

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

      self.titleLabel.transform = CGAffineTransform(translationX: -30, y: 0)

    }) { (_) in
      UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {

        self.titleLabel.alpha = 0
        self.titleLabel.transform =
        self.titleLabel.transform.translatedBy(x: 0,y: -200)

      })
    }

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

      self.titleLabel.transform = CGAffineTransform(translationX: -30, y: 0)

    }) { (_) in
      UIView.animate(withDuration: 0.5, delay: 0.5, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {

        self.bodyLabel.alpha = 0
        self.bodyLabel.transform =
          self.bodyLabel.transform.translatedBy(x: 0,y: -200)

      })
    }
  }

Any help is much appreciated.


问:
Modify Azure B2C sign in V1 policy/user flow minimum password length restriction
We have a special case where, for our Azure B2C users, we set the forceChangePasswordOnNextLogin property for a user account when creating it. For logging in, the user signs in through a SignIn V1 User Flow, which allows the user to change their password on their initial login.

We now want to change the password complexity to allow 10 characters instead of Azure's default 8. Is there a way to accomplish this without the use of custom policies or v2 user flows (since the sign in v2 user flow dos not allow a user to change their password)?

Thanks in advance!

Edit: Let me describe our workflow. This is what we have right now:

I create a B2C user and with an initial temporary password. The user is created through the Graph API and I set forceChangePasswordOnNextLogin to true.

I send the user this temporary password

The user logs himself/herself in using the sign in v1 user flow/policy

The policy forces the user to change his/her password

So far, this is working just fine. However, we now want that when the user is forced to change his/her password, they do so with custom password security requirements (minimum of 10 characters required).

答:
You need to use custom policies. We never recommend sending passwords in emails either. Look at our invite sample, since your moving to custom policies it’s worth implementing.

https://github.com/azure-ad-b2c/samples/blob/master/policies/invite/README.md


问:
Liquidsoap: how to remove track from playlist?
I have a goal to stream new files from a directory with Liquidsoap.

1. Inotify tracks target folder and adds all new files to playlist:

```<code>#!/bin/bash
inotifywait -e close_write --format '%f' -m "/my/folder" | \
(
while read NEWFILE
do
echo $NEWFILE >> playlist.txt
done
)
</code>```

2. Liquidsoap plays playlist.txt

```<code>#!/usr/bin/liquidsoap
radio = mksafe(playlist(loop=false,mode='normal',reload=0,reload_mode="watch", "playlist.txt"))
</code>```

3. last step: Liquidsoap should remove track from playlist.txt after it have been played

Need help with removing!

答:
To remove some track after it has been played just add prefix="tmp:"

```<code>radio = mksafe(playlist(prefix="tmp:",loop=false,mode='normal',reload=0,reload_mode="watch", "playlist.txt"))
</code>```

Body:
I have a goal to stream new files from a directory with Liquidsoap.

1. Inotify tracks target folder and adds all new files to playlist:

#!/bin/bash
inotifywait -e close_write --format '%f' -m "/my/folder" | \
(
while read NEWFILE
do
echo $NEWFILE >> playlist.txt
done
)

2. Liquidsoap plays playlist.txt

#!/usr/bin/liquidsoap
radio = mksafe(playlist(loop=false,mode='normal',reload=0,reload_mode="watch", "playlist.txt"))

3. last step: Liquidsoap should remove track from playlist.txt after it have been played

Need help with removing!

Body:
To remove some track after it has been played just add prefix="tmp:"

radio = mksafe(playlist(prefix="tmp:",loop=false,mode='normal',reload=0,reload_mode="watch", "playlist.txt"))


问:
Dynamic Data passing to Facebook and linkedIn sharing
I have a HTML page where I am using javascript to load contents based on query string value..
In javascript, I have some dynamic code to load separate data on the page based on this query string value.

Now my page link looks like

```<code>https://example.com?datatype=1
https://example.com?datatype=2
https://example.com?datatype=3
</code>```

Based on this my page data will vary.
Now I want to Add Facebook and LInked in Sharing on this and want to send custom information to share on facebook and LinkedIn.

As per my R&d, this data can be posted using metatags.
As I told you that My page is a pure client-side page. So these meta tags will not work for dynamic data.

Can anyone suggest how I can Post URL, title, and description to this linkedIn and facebook.

Thanks in Advance

Body:
I have a HTML page where I am using javascript to load contents based on query string value..
In javascript, I have some dynamic code to load separate data on the page based on this query string value.

Now my page link looks like

https://example.com?datatype=1
https://example.com?datatype=2
https://example.com?datatype=3

Based on this my page data will vary.
Now I want to Add Facebook and LInked in Sharing on this and want to send custom information to share on facebook and LinkedIn.

As per my R&d, this data can be posted using metatags.
As I told you that My page is a pure client-side page. So these meta tags will not work for dynamic data.

Can anyone suggest how I can Post URL, title, and description to this linkedIn and facebook.

Thanks in Advance

Body:
So, I want to focus in on one thing you have stated here:

As per my R&d, this data can be posted using metatags. As I told you that My page is a pure client-side page. So these meta tags will not work for dynamic data.

That's actually not the complete story.  Even if your webpage is "pure client-side", you still absolutely need to have an HTML framework to hold this, even if it's as minimal as: <html><head><script type="text/javascript" src="...."></head></html>.  What you will need to do is to edit the document being served for your client-side application.

You did not mention a language, so, let's just assume you're using ReactJS.  The procedure here will be the same for other client-side pages.

After making a react project, I have this file, ./public/index.html, and in it is...

<!doctype html>
<html lang="en">
    <head>
        <title>Scheduler</title>
        <meta charset="utf-8" />
        <link id="css-root" href="" rel="stylesheet" type="text/css" />
    </head>
    ...
</html>

All you need to do is to insert the og: tags to your for LinkedIn.  Just use the tags as described by the Official LinkedIn Share Documentation.  This should look like this...

<meta property='og:title' content='Title of the article"/>

<meta property='og:image' content='//media.example.com/ 1234567.jpg"/>

<meta property='og:description' content='Description that will show in the preview"/>

<meta property='og:url' content='//www.example.com/URL of the article" />

Hope this helps!


问:
Best Way to Update/Edit an Array Element in SwiftUI
I have an array of identifiable Training elements.  Each Training element only has two properties, name and isRequired.

What is the most straight-forward (Swiftyiest) way to update the existing values of an array element to new edited values... the edited values will then later be submitted to the database.

Is it possible to set the state in the EditTraining View (Child) to the passed in (Parent) values and then edit the state in the child view?

I've been stuck on this longer than I'll ever admit.

Thank you very much for any help at all!

Here is the code:

```<code>import SwiftUI

struct Training: Identifiable {
    let id: String
    let trainingName: String
    let isRequired: Bool
}

class GetTrainings: ObservableObject {
    @Published var items = [Training]()

    init() {
        self.items = [
            Training(id: "ttt1", trainingName: "Safety", isRequired: true),
            Training(id: "ttt2", trainingName: "Administrative", isRequired: false),
            Training(id: "ttt3", trainingName: "Computer", isRequired: true),
            Training(id: "ttt4", trainingName: "People", isRequired: true),
            Training(id: "ttt5", trainingName: "Managerial", isRequired: true),
        ]
    }
}

struct TrainingList: View {

    @ObservedObject var trainings = GetTrainings()

    var body: some View {
        NavigationView {
            VStack {
                List {

                    ForEach(trainings.items) { training in

                        HStack {
                            NavigationLink(destination: TrainingView(training: training)) {
                                Text("\(training.trainingName)")
                            }
                        }
                    }

                }
            }.navigationBarTitle("Training List")
        }
    }
}

struct TrainingView: View {

    var training: Training

    var body: some View {

        VStack {

            Text("\(training.trainingName)").font(.body)
            Text("\(training.isRequired == true ? "Required Training" : "Training Not Required")")

            HStack {
                NavigationLink(destination: EditTraining(training: training)) {
                    Text("Edit Training Details")
                }
            }
        }.navigationBarTitle("\(training.trainingName) Page", displayMode: .inline)

    }
}

struct EditTraining: View {

    var training: Training

    // Can I set the state values to the passed in values ???
    @State private var newName: String = ""
    @State private var isRequiredTraining: Bool = false
    //@Binding var name: String = training.trainingName ????

    private func submitData() {

        let newName = self.newName
        let newBoolVal = self.isRequiredTraining

        print("Firebase Sync Id is :\(training.id) Text: \(newName) and Bool: \(newBoolVal)")

    }

    var body: some View {
        VStack {
            Form {
                Section (header: Text("Edit"))  {

                    Text("\(training.trainingName)")
                    /* TextField should Populate With passed In Training Name Here*/
                    TextField("New Name", text: self.$newName)
                    Toggle(isOn: self.$isRequiredTraining) {
                        Text("Is Required")
                    }
                }

                Section {

                    Button(action: {
                        self.submitData()
                    }) {
                        Text("Submit")
                    }

                }
            }
        }.navigationBarTitle("Edit Training Page", displayMode: .inline)
    }
}

struct ContentView: View {

    var body: some View {

        VStack {

            TrainingList()

        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
</code>```

答:
This is the case when as I see it is more preferable to use ObservableObject for models, because it allows to pass by reference model object deep into hierarchy and keep it up to date during workflow.

Here is a solution. Tested with Xcode 11.4 / iOS 13.4

```<code>class Training: ObservableObject, Identifiable {
    let id: String
    @Published var trainingName: String
    @Published var isRequired: Bool

    init(id: String, trainingName: String, isRequired: Bool) {
        self.id = id
        self.trainingName = trainingName
        self.isRequired = isRequired
    }
}

class GetTrainings: ObservableObject {
    @Published var items = [Training]()

    init() {
        self.items = [
            Training(id: "ttt1", trainingName: "Safety", isRequired: true),
            Training(id: "ttt2", trainingName: "Administrative", isRequired: false),
            Training(id: "ttt3", trainingName: "Computer", isRequired: true),
            Training(id: "ttt4", trainingName: "People", isRequired: true),
            Training(id: "ttt5", trainingName: "Managerial", isRequired: true),
        ]
    }
}

struct TrainingList: View {

    @ObservedObject var trainings = GetTrainings()

    var body: some View {
        NavigationView {
            VStack {
                List {

                    ForEach(trainings.items) { training in

                        HStack {
                            NavigationLink(destination: TrainingView(training: training)) {
                                Text("\(training.trainingName)")
                            }
                        }
                    }

                }
            }.navigationBarTitle("Training List")
            .onAppear {
                self.trainings.objectWillChange.send() // refresh
            }
        }
    }
}

struct TrainingView: View {

    @ObservedObject var training: Training

    var body: some View {

        VStack {

            Text("\(training.trainingName)").font(.body)
            Text("\(training.isRequired == true ? "Required Training" : "Training Not Required")")

            HStack {
                NavigationLink(destination: EditTraining(training: training)) {
                    Text("Edit Training Details")
                }
            }
        }.navigationBarTitle("\(training.trainingName) Page", displayMode: .inline)

    }
}

struct EditTraining: View {

    @ObservedObject var training: Training

    @State private var newName: String
    @State private var isRequiredTraining: Bool

    init(training: Training) {
        self.training = training
        self._newName = State(initialValue: training.trainingName)
        self._isRequiredTraining = State(initialValue: training.isRequired)
    }

    private func submitData() {

        let newName = self.newName
        let newBoolVal = self.isRequiredTraining

        print("Firebase Sync Id is :\(training.id) Text: \(newName) and Bool: \(newBoolVal)")

        self.training.trainingName = newName
        self.training.isRequired = newBoolVal
    }

    var body: some View {
        VStack {
            Form {
                Section (header: Text("Edit"))  {

                    Text("\(training.trainingName)")
                    /* TextField should Populate With passed In Training Name Here*/
                    TextField("New Name", text: self.$newName)
                    Toggle(isOn: self.$isRequiredTraining) {
                        Text("Is Required")
                    }
                }

                Section {

                    Button(action: {
                        UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder),
                            to:nil, from:nil, for:nil)
                        self.submitData()
                    }) {
                        Text("Submit")
                    }

                }
            }
        }.navigationBarTitle("Edit Training Page", displayMode: .inline)
    }
}
</code>```

Body:
I have an array of identifiable Training elements.  Each Training element only has two properties, name and isRequired.

What is the most straight-forward (Swiftyiest) way to update the existing values of an array element to new edited values... the edited values will then later be submitted to the database.

Is it possible to set the state in the EditTraining View (Child) to the passed in (Parent) values and then edit the state in the child view?

I've been stuck on this longer than I'll ever admit.

Thank you very much for any help at all!

Here is the code:

import SwiftUI

struct Training: Identifiable {
    let id: String
    let trainingName: String
    let isRequired: Bool
}

class GetTrainings: ObservableObject {
    @Published var items = [Training]()

    init() {
        self.items = [
            Training(id: "ttt1", trainingName: "Safety", isRequired: true),
            Training(id: "ttt2", trainingName: "Administrative", isRequired: false),
            Training(id: "ttt3", trainingName: "Computer", isRequired: true),
            Training(id: "ttt4", trainingName: "People", isRequired: true),
            Training(id: "ttt5", trainingName: "Managerial", isRequired: true),
        ]
    }
}

struct TrainingList: View {

    @ObservedObject var trainings = GetTrainings()

    var body: some View {
        NavigationView {
            VStack {
                List {

                    ForEach(trainings.items) { training in

                        HStack {
                            NavigationLink(destination: TrainingView(training: training)) {
                                Text("\(training.trainingName)")
                            }
                        }
                    }

                }
            }.navigationBarTitle("Training List")
        }
    }
}

struct TrainingView: View {

    var training: Training

    var body: some View {

        VStack {

            Text("\(training.trainingName)").font(.body)
            Text("\(training.isRequired == true ? "Required Training" : "Training Not Required")")

            HStack {
                NavigationLink(destination: EditTraining(training: training)) {
                    Text("Edit Training Details")
                }
            }
        }.navigationBarTitle("\(training.trainingName) Page", displayMode: .inline)

    }
}

struct EditTraining: View {

    var training: Training

    // Can I set the state values to the passed in values ???
    @State private var newName: String = ""
    @State private var isRequiredTraining: Bool = false
    //@Binding var name: String = training.trainingName ????

    private func submitData() {

        let newName = self.newName
        let newBoolVal = self.isRequiredTraining

        print("Firebase Sync Id is :\(training.id) Text: \(newName) and Bool: \(newBoolVal)")

    }

    var body: some View {
        VStack {
            Form {
                Section (header: Text("Edit"))  {

                    Text("\(training.trainingName)")
                    /* TextField should Populate With passed In Training Name Here*/
                    TextField("New Name", text: self.$newName)
                    Toggle(isOn: self.$isRequiredTraining) {
                        Text("Is Required")
                    }
                }

                Section {

                    Button(action: {
                        self.submitData()
                    }) {
                        Text("Submit")
                    }

                }
            }
        }.navigationBarTitle("Edit Training Page", displayMode: .inline)
    }
}

struct ContentView: View {

    var body: some View {

        VStack {

            TrainingList()

        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Body:
This is the case when as I see it is more preferable to use ObservableObject for models, because it allows to pass by reference model object deep into hierarchy and keep it up to date during workflow.

Here is a solution. Tested with Xcode 11.4 / iOS 13.4

class Training: ObservableObject, Identifiable {
    let id: String
    @Published var trainingName: String
    @Published var isRequired: Bool

    init(id: String, trainingName: String, isRequired: Bool) {
        self.id = id
        self.trainingName = trainingName
        self.isRequired = isRequired
    }
}

class GetTrainings: ObservableObject {
    @Published var items = [Training]()

    init() {
        self.items = [
            Training(id: "ttt1", trainingName: "Safety", isRequired: true),
            Training(id: "ttt2", trainingName: "Administrative", isRequired: false),
            Training(id: "ttt3", trainingName: "Computer", isRequired: true),
            Training(id: "ttt4", trainingName: "People", isRequired: true),
            Training(id: "ttt5", trainingName: "Managerial", isRequired: true),
        ]
    }
}

struct TrainingList: View {

    @ObservedObject var trainings = GetTrainings()

    var body: some View {
        NavigationView {
            VStack {
                List {

                    ForEach(trainings.items) { training in

                        HStack {
                            NavigationLink(destination: TrainingView(training: training)) {
                                Text("\(training.trainingName)")
                            }
                        }
                    }

                }
            }.navigationBarTitle("Training List")
            .onAppear {
                self.trainings.objectWillChange.send() // refresh
            }
        }
    }
}

struct TrainingView: View {

    @ObservedObject var training: Training

    var body: some View {

        VStack {

            Text("\(training.trainingName)").font(.body)
            Text("\(training.isRequired == true ? "Required Training" : "Training Not Required")")

            HStack {
                NavigationLink(destination: EditTraining(training: training)) {
                    Text("Edit Training Details")
                }
            }
        }.navigationBarTitle("\(training.trainingName) Page", displayMode: .inline)

    }
}

struct EditTraining: View {

    @ObservedObject var training: Training

    @State private var newName: String
    @State private var isRequiredTraining: Bool

    init(training: Training) {
        self.training = training
        self._newName = State(initialValue: training.trainingName)
        self._isRequiredTraining = State(initialValue: training.isRequired)
    }

    private func submitData() {

        let newName = self.newName
        let newBoolVal = self.isRequiredTraining

        print("Firebase Sync Id is :\(training.id) Text: \(newName) and Bool: \(newBoolVal)")

        self.training.trainingName = newName
        self.training.isRequired = newBoolVal
    }

    var body: some View {
        VStack {
            Form {
                Section (header: Text("Edit"))  {

                    Text("\(training.trainingName)")
                    /* TextField should Populate With passed In Training Name Here*/
                    TextField("New Name", text: self.$newName)
                    Toggle(isOn: self.$isRequiredTraining) {
                        Text("Is Required")
                    }
                }

                Section {

                    Button(action: {
                        UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder),
                            to:nil, from:nil, for:nil)
                        self.submitData()
                    }) {
                        Text("Submit")
                    }

                }
            }
        }.navigationBarTitle("Edit Training Page", displayMode: .inline)
    }
}


问:
bitbucket git clone results in 'fatal: unable to access ... could not load PEM client certificate, OpenSSL error error:02001003...'
I am trying to clone a git repo via the URL and have the command as follows:

```<code>git clone https://LastName%20FirstName%20CertNumber:Token@bitbucket.../someProject/someProject.git
</code>```

but keep running into the same error.

```<code>Clone failed: unable to access 'https://LastName%20FirstName%20CertNumber:Token@bitbucket.../someProject/someProject.git/': could not load PEM client certificate, OpenSSL error error:02001003:system library:fopen:No such process, (no key found, wrong pass phrase, or wrong file format?)
</code>```

I checked my git config and the properties are all set properly:

```<code>http.sslcert=someCert.crt
http.sslkey=someKey.key
http.sslcainfo=someCa.cer
http.sslverify=true
http.sslcertpasswordprotected=true
</code>```

What could be giving me this error?

答:
The key part of the error message is:

no key found, wrong pass phrase, or wrong file format?

As mentioned here:

For a SSL verification you need:

a cert in PEM format,

its associated private key (in openssl format) and

the root certificate of the certification authoritity that signed your certificate in pem format.

Maybe one of those elements is missing (try and use full absolute path for those files, as seen here), or is in the wrong format (like the someCa.cer file, which might or might not be in PEM format).

Body:
I am trying to clone a git repo via the URL and have the command as follows:

git clone https://LastName%20FirstName%20CertNumber:Token@bitbucket.../someProject/someProject.git

but keep running into the same error.

Clone failed: unable to access 'https://LastName%20FirstName%20CertNumber:Token@bitbucket.../someProject/someProject.git/': could not load PEM client certificate, OpenSSL error error:02001003:system library:fopen:No such process, (no key found, wrong pass phrase, or wrong file format?)

I checked my git config and the properties are all set properly:

http.sslcert=someCert.crt
http.sslkey=someKey.key
http.sslcainfo=someCa.cer
http.sslverify=true
http.sslcertpasswordprotected=true

What could be giving me this error?


问:
Datatables buttons not showing for Bootstrap example
Any idea why the buttons (csv, excel, pdf, print etc) are not showing when using this code for bootstrap?

https://datatables.net/extensions/buttons/examples/styling/bootstrap4.html

I have this for styles:

```<code><link href="//stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
<link href="//cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css" rel="stylesheet">
<link href="//cdn.datatables.net/buttons/1.5.6/css/buttons.bootstrap4.min.css" rel="stylesheet">
</code>```

This for scripts:

```<code><script src="//code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="//stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="//cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
<script src="//cdn.datatables.net/buttons/1.5.6/js/dataTables.buttons.min.js"></script>
<script src="//cdn.datatables.net/buttons/1.5.6/js/buttons.bootstrap4.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
<script src="//cdn.datatables.net/buttons/1.5.6/js/buttons.html5.min.js"></script>
<script src="//cdn.datatables.net/buttons/1.5.6/js/buttons.print.min.js"></script>
<script src="//cdn.datatables.net/buttons/1.5.6/js/buttons.colVis.min.js"></script>
</code>```

And this JS:

```<code>$(document).ready(function(){
  var table = $('#reminders').DataTable({
    "lengthMenu": [[50, 100, 1000, -1], [50, 100, 1000, "All"]],
    "initComplete": function(){
      $("#reminders").show();
    },
    buttons: ['copy', 'csv', 'excel', 'pdf', 'print', 'colvis']
  });
  table.buttons().container().appendTo( '#example_wrapper .col-md-6:eq(0)' );
});
</code>```

But the buttons are not showing... If I uncomment the dom and use Blfrtip the buttons do show, but I am curious as why the method in the example (without dom) isn't working...

答:
I just checked, and the DOM for the wrapper is not ready yet right after the DataTable() call. I'm using AJAX to get the data. But adding the call in the initComplete property worked:

```<code>$(document).ready(function() {
    var table = $('#reminders').DataTable({
    //"dom": 'Blfrtip',
    "lengthMenu": [
      [50, 100, 1000, -1],
      [50, 100, 1000, "All"]
    ],
    "initComplete": function() {
        table.buttons().container().appendTo('#reminders_wrapper .col-md-6:eq(0)');
        $("#reminders").show();
    },
    "buttons": ['copy', 'csv', 'excel', 'pdf', 'print', 'colvis']
    // Rest of configuration.
  });
});
</code>```

Body:
Any idea why the buttons (csv, excel, pdf, print etc) are not showing when using this code for bootstrap?

https://datatables.net/extensions/buttons/examples/styling/bootstrap4.html

I have this for styles:

<link href="//stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
<link href="//cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css" rel="stylesheet">
<link href="//cdn.datatables.net/buttons/1.5.6/css/buttons.bootstrap4.min.css" rel="stylesheet">

This for scripts:

And this JS:

$(document).ready(function(){
  var table = $('#reminders').DataTable({
    "lengthMenu": [[50, 100, 1000, -1], [50, 100, 1000, "All"]],
    "initComplete": function(){
      $("#reminders").show();
    },
    buttons: ['copy', 'csv', 'excel', 'pdf', 'print', 'colvis']
  });
  table.buttons().container().appendTo( '#example_wrapper .col-md-6:eq(0)' );
});

But the buttons are not showing... If I uncomment the dom and use Blfrtip the buttons do show, but I am curious as why the method in the example (without dom) isn't working...

Body:
I just checked, and the DOM for the wrapper is not ready yet right after the DataTable() call. I'm using AJAX to get the data. But adding the call in the initComplete property worked:

$(document).ready(function() {
    var table = $('#reminders').DataTable({
    //"dom": 'Blfrtip',
    "lengthMenu": [
      [50, 100, 1000, -1],
      [50, 100, 1000, "All"]
    ],
    "initComplete": function() {
        table.buttons().container().appendTo('#reminders_wrapper .col-md-6:eq(0)');
        $("#reminders").show();
    },
    "buttons": ['copy', 'csv', 'excel', 'pdf', 'print', 'colvis']
    // Rest of configuration.
  });
});


问:
How to redirect properly in Django URL , I am having issue in redirecting

Having issue with redirecting, I am at registration page("accounts/register") on my website where I want if someone register then a verification code will send on his email id and to verify we have a url "accounts/verify". but when I am trying to register it register a user but does not send them on "accounts/verify" instead it send that to "accounts/register/accounts/verify" ,

Also please let me know how to use user email address, while registering him into database. I just want his email id to send verification code.

Here is my URL.py of my app:

```<code>from django.contrib import admin
from django.urls import path,include
from . import views
from django.contrib.auth.models import User

    urlpatterns = [
        path('login/', views.login, name='Login-Page'),
        path('register/', views.register, name='Registeration-page'),
        path('logout/', views.logout),
        path('verify/', views.verify, name='verification page')
</code>```

Here is my View.py for registration and profile:

```<code>from django.shortcuts import render, redirect
import requests
from django.contrib.auth.models import User, auth
from django.contrib import messages
from datetime import date
import smtplib
import random
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def register(request):

    if request.method == 'POST':
        first_name = request.POST['first_name']
        last_name = request.POST['last_name']
        username = request.POST['username']
        email = request.POST['email']
        password1 = request.POST['password1']
        password2 = request.POST['password2']

        if password1==password2:
            if User.objects.filter(username=username).exists():
                messages.info(request, "Username already taken")
                return redirect('accounts/register')
            elif User.objects.filter(email=email).exists():
                messages.info(request, "email already taken")
                return redirect('accounts/register')
            else:
                user = User.objects.create_user(username=username, password=password1, email=email, first_name=first_name, last_name=last_name)
                user.save();
                return redirect('accounts/verify') # 'accounts/login'
        else:
            messages.info(request,"password not matched")
            return redirect('accounts/register')

    else:
        return render(request, 'register.html')

def verify(request):
    if request.method == 'POST':
        sender_address = 'xyz@gmail.com'
        sender_pass = 'password'
        user_email = register.user.objects.email
        receiver_address = user_email
        passd = random.randrange(111111,10000000,39)
        mail_content = "Hello This is your verficatiob code   " + str(passd)

        def check(code):
            if code==passd:
                return redirect('accounts/login')
            else:
                messages.info(request,"Code is incorrect")
                return redirect('accounts/verify')

        message = MIMEMultipart()
        message['From'] = sender_address
        message['To'] = receiver_address
        message['Subject'] = 'Verification Code'
        message.attach(MIMEText(mail_content, 'plain'))
        session = smtplib.SMTP(EMAIL_HOST, EMAIL_PORT)
        session.starttls()
        session.login(sender_address, sender_pass)
        text = message.as_string()
        session.sendmail(sender_address, receiver_address, text)
        session.quit()
        print('Mail Sent')
        code = request.POST['code']

        check(code)
    else:
        return render(request, 'email_verify.html')
</code>```

Here is my register template:

```<code><div class="limiter">
        <div class="container-login100" style="background-image: url ('/images/bg-01.jpg');">
            <div class="wrap-login100 p-l-55 p-r-55 p-t-65 p-b-54">
                <form action="{{register}}" method="post">
                    {% csrf_token %}
                <!--<form class="login100-form validate-form">-->
                    <span class="login100-form-title p-b-49">
                        Registration
                    </span>
                    <div>
                    {% for message in messages %}
                    <input class="wrap-input validate-input m-b-23" data-validate="{{message}}">
                    {% endfor %}
                    </div>

                    <div class="wrap-input100 validate-input m-b-23" data-validate = "First name is reauired">
                        <span class="label-input100"><th>first name</th></span>
                        <input class="input100" type="text" name="first_name" placeholder="Type your First name">
                        <span class="focus-input100" data-symbol=""></span>
                    </div>
                    <div class="wrap-input100 validate-input m-b-23" data-validate = "Last name is reauired">
                        <span class="label-input100"><th>last name</th></span>
                        <input class="input100" type="text" name="last_name" placeholder="Type your Last name">
                        <span class="focus-input100" data-symbol=""></span>
                    </div>
                    <div class="wrap-input100 validate-input" data-validate="Username is required">
                        <span class="label-input100">Username</span>
                        <input class="input100" type="username" name="username" placeholder="Type your username">
                        <span class="focus-input100" data-symbol=""></span>
                    </div>
                    <div class="wrap-input100 validate-input" data-validate="email is required">
                        <span class="label-input100">email</span>
                        <input class="input100" type="email" name="email" placeholder="Type your email">
                        <span class="focus-input100" data-symbol=""></span>
                    </div>

                    <div class="wrap-input100 validate-input" data-validate="password is required">
                        <span class="label-input100">Password</span>
                        <input class="input100" type="password" name="password1" placeholder="Type your password">
                        <span class="focus-input100" data-symbol=""></span>
                    </div>
                    <div class="wrap-input100 validate-input" data-validate="confirm password is required">
                        <span class="label-input100">Confirm Password</span>
                        <input class="input100" type="password" name="password2" placeholder="Type your password Again">
                        <span class="focus-input100" data-symbol=""></span>
                    </div>
                    <br>
                    <div class="container-login100-form-btn">
                        <div class="wrap-login100-form-btn">
                            <div class="login100-form-bgbtn"></div>
                            <button class="login100-form-btn">
                                Register
                            </button>
                        </div>
                    </div>
                </form>
             </div>
          </div>
       </div>
</code>```

This is the error:

```<code>Page not found (404)
Request Method: GET
Request URL:    localhost/accounts/register/accounts/verify
Using the URLconf defined in made.urls, Django tried these URL patterns, in this order:

admin/
[name='Homepage']
accounts/ login/ [name='Login-Page']
accounts/ register/ [name='Registeration-page']
accounts/ logout/
accounts/ verify/ [name='verification page']
</code>```

答:
```<code>from django.contrib import admin
from django.urls import path,include
from . import views
from django.contrib.auth.models import User

    urlpatterns = [
        path('login/', views.login, name='Login-Page'),
        path('register/', views.register, name='Registeration-page'),
        path('logout/', views.logout),
        path('verify/', views.verify, name='verificationPage')
</code>```

#

```<code>def verify(request):
    if request.method == 'POST':
        sender_address = 'xyz@gmail.com'
        sender_pass = 'password'
        user_email = register.user.objects.email
        receiver_address = user_email
        passd = random.randrange(111111,10000000,39)
        mail_content = "Hello This is your verficatiob code   " + str(passd)

        def check(code):
            if code==passd:
                return redirect('accounts/login')
            else:
                messages.info(request,"Code is incorrect")
                return HttpResponseRedirect(reverse('verificationPage')) # you'r issus
                #Or    return HttpResponseRedirect("/Yourapp/verify")
        message = MIMEMultipart()
        message['From'] = sender_address
        message['To'] = receiver_address
        message['Subject'] = 'Verification Code'
        message.attach(MIMEText(mail_content, 'plain'))
        session = smtplib.SMTP(EMAIL_HOST, EMAIL_PORT)
        session.starttls()
        session.login(sender_address, sender_pass)
        text = message.as_string()
        session.sendmail(sender_address, receiver_address, text)
        session.quit()
        print('Mail Sent')
        code = request.POST['code']

        check(code)
    else:
        return render(request, 'email_verify.html')
</code>```

Body:
Having issue with redirecting, I am at registration page("accounts/register") on my website where I want if someone register then a verification code will send on his email id and to verify we have a url "accounts/verify". but when I am trying to register it register a user but does not send them on "accounts/verify" instead it send that to "accounts/register/accounts/verify" ,

Also please let me know how to use user email address, while registering him into database. I just want his email id to send verification code.

Here is my URL.py of my app:

from django.contrib import admin
from django.urls import path,include
from . import views
from django.contrib.auth.models import User

    urlpatterns = [
        path('login/', views.login, name='Login-Page'),
        path('register/', views.register, name='Registeration-page'),
        path('logout/', views.logout),
        path('verify/', views.verify, name='verification page')

Here is my View.py for registration and profile:

from django.shortcuts import render, redirect
import requests
from django.contrib.auth.models import User, auth
from django.contrib import messages
from datetime import date
import smtplib
import random
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def register(request):

    if request.method == 'POST':
        first_name = request.POST['first_name']
        last_name = request.POST['last_name']
        username = request.POST['username']
        email = request.POST['email']
        password1 = request.POST['password1']
        password2 = request.POST['password2']

        if password1==password2:
            if User.objects.filter(username=username).exists():
                messages.info(request, "Username already taken")
                return redirect('accounts/register')
            elif User.objects.filter(email=email).exists():
                messages.info(request, "email already taken")
                return redirect('accounts/register')
            else:
                user = User.objects.create_user(username=username, password=password1, email=email, first_name=first_name, last_name=last_name)
                user.save();
                return redirect('accounts/verify') # 'accounts/login'
        else:
            messages.info(request,"password not matched")
            return redirect('accounts/register')

    else:
        return render(request, 'register.html')

def verify(request):
    if request.method == 'POST':
        sender_address = 'xyz@gmail.com'
        sender_pass = 'password'
        user_email = register.user.objects.email
        receiver_address = user_email
        passd = random.randrange(111111,10000000,39)
        mail_content = "Hello This is your verficatiob code   " + str(passd)

        def check(code):
            if code==passd:
                return redirect('accounts/login')
            else:
                messages.info(request,"Code is incorrect")
                return redirect('accounts/verify')

        message = MIMEMultipart()
        message['From'] = sender_address
        message['To'] = receiver_address
        message['Subject'] = 'Verification Code'
        message.attach(MIMEText(mail_content, 'plain'))
        session = smtplib.SMTP(EMAIL_HOST, EMAIL_PORT)
        session.starttls()
        session.login(sender_address, sender_pass)
        text = message.as_string()
        session.sendmail(sender_address, receiver_address, text)
        session.quit()
        print('Mail Sent')
        code = request.POST['code']

        check(code)
    else:
        return render(request, 'email_verify.html')

Here is my register template:

                <form action="{{register}}" method="post">
                    {% csrf_token %}

                        Registration

                    {% for message in messages %}
                    <input class="wrap-input validate-input m-b-23" data-validate="{{message}}">
                    {% endfor %}

                        first name
                        <input class="input100" type="text" name="first_name" placeholder="Type your First name">

                        last name
                        <input class="input100" type="text" name="last_name" placeholder="Type your Last name">

                        Username
                        <input class="input100" type="username" name="username" placeholder="Type your username">

                        email
                        <input class="input100" type="email" name="email" placeholder="Type your email">

                        Password
                        <input class="input100" type="password" name="password1" placeholder="Type your password">

                        Confirm Password
                        <input class="input100" type="password" name="password2" placeholder="Type your password Again">

                            <button class="login100-form-btn">
                                Register
                            </button>

                </form>

This is the error:

Page not found (404)
Request Method: GET
Request URL:    localhost/accounts/register/accounts/verify
Using the URLconf defined in made.urls, Django tried these URL patterns, in this order:

admin/
[name='Homepage']
accounts/ login/ [name='Login-Page']
accounts/ register/ [name='Registeration-page']
accounts/ logout/
accounts/ verify/ [name='verification page']

Body:
from django.contrib import admin
from django.urls import path,include
from . import views
from django.contrib.auth.models import User

    urlpatterns = [
        path('login/', views.login, name='Login-Page'),
        path('register/', views.register, name='Registeration-page'),
        path('logout/', views.logout),
        path('verify/', views.verify, name='verificationPage')

#

def verify(request):
    if request.method == 'POST':
        sender_address = 'xyz@gmail.com'
        sender_pass = 'password'
        user_email = register.user.objects.email
        receiver_address = user_email
        passd = random.randrange(111111,10000000,39)
        mail_content = "Hello This is your verficatiob code   " + str(passd)

        def check(code):
            if code==passd:
                return redirect('accounts/login')
            else:
                messages.info(request,"Code is incorrect")
                return HttpResponseRedirect(reverse('verificationPage')) # you'r issus
                #Or    return HttpResponseRedirect("/Yourapp/verify")
        message = MIMEMultipart()
        message['From'] = sender_address
        message['To'] = receiver_address
        message['Subject'] = 'Verification Code'
        message.attach(MIMEText(mail_content, 'plain'))
        session = smtplib.SMTP(EMAIL_HOST, EMAIL_PORT)
        session.starttls()
        session.login(sender_address, sender_pass)
        text = message.as_string()
        session.sendmail(sender_address, receiver_address, text)
        session.quit()
        print('Mail Sent')
        code = request.POST['code']

        check(code)
    else:
        return render(request, 'email_verify.html')


问:
Android emulator is not working in Android studio
I'm getting this error:

```<code>12:53 PM    Emulator: C:\Users\tenni\AppData\Local\Android\Sdk\emulator\qemu\windows-x86_64\qemu-system-x86_64.exe: error while loading state for instance 0x0 of device 'goldfish_pipe'

12:53 PM    Emulator: deleteSnapshot: for default_boot

12:53 PM    Emulator: Process finished with exit code 0
</code>```

I have looked for similar posts on this website and tried updating HAXM to the latest version, and created a new virtual device, but that has not fixed the problem.
Maybe Android studio is not using the latest HAXM I installed?

I'm very new to using Android studio and developing apps so any help would be appreciated!

EDIT

Here's a picture of the version of my HAXM by going to settings > appearance and behavior > system settings > android sdk > sdk tools

答:
This is a known bug and is fixed in the latest version of android studio.
https://issuetracker.google.com/issues/132481542

You can also try a work around by  by changing the cpu core from 4 to 1.

Body:
I'm getting this error:

12:53 PM    Emulator: C:\Users\tenni\AppData\Local\Android\Sdk\emulator\qemu\windows-x86_64\qemu-system-x86_64.exe: error while loading state for instance 0x0 of device 'goldfish_pipe'

12:53 PM    Emulator: deleteSnapshot: for default_boot

12:53 PM    Emulator: Process finished with exit code 0

I have looked for similar posts on this website and tried updating HAXM to the latest version, and created a new virtual device, but that has not fixed the problem.
Maybe Android studio is not using the latest HAXM I installed?

I'm very new to using Android studio and developing apps so any help would be appreciated!

EDIT

Here's a picture of the version of my HAXM by going to settings > appearance and behavior > system settings > android sdk > sdk tools