问:
Selenium looking at a class and determine how many elements are in the class, finally executes an action on all elements found
I need to interact with elements under a class but the number of elements in that class is changing every time I run the script.

To give you context the website is a calendar, where I need to pick a day that I'll use as a template for my work. Every time I run the script (Monthly) the webpage with the calendar is updated to show the current month, thus Selenium picks the same day it did in the previous month. But every month the day Selenium picks has different contents and number of elements change every month. Currently, for example, the script is written to interact with 5 elements, but for next month it won't work because the day picked will have a different number of elements. So every month I have to manually change the script to interact with the correct number of elements.

Here's an example of the element structure of the website:

```<code><ul class="list-unstyled tags-list grid_9">
     <li><!-- react-text: 185 -->Text<!-- /react-text --><i data-id="0" class="icon-cancel pointer icon12
      ml5px error"></i></li>
     <li><!-- react-text: 188 -->Text<!-- /react-text --><i data-id="1" class="icon-cancel pointer icon12
      ml5px error"></i></li>
     <li><!-- react-text: 191 -->Text<!-- /react-text --><i data-id="2" class="icon-cancel pointer icon12
      ml5px error"></i></li>
</ul>
</code>```

So the number of elements that I need to interact within the class 'list-unstyled tags-list grid_9' is always changing. The elements with the id's "0", "1" and "2". Sometimes there might be 4 elements with ID's "0", "1", "2", "3" and sometimes there's 2 elements etc.

I've been trying to figure out how to write a script where Selenium looks inside that class ''list-unstyled tags-list grid_9', see's how many elements are in there and executes a -

```<code>driver.find_element_by_(xpath,class,id whatever).click()
</code>```

on all of the elements found in there.

UPDATE:
So I tried this code:

```<code>tab = driver.find_element_by_css_selector('#postForm > div:nth-child(3) > ul.list-unstyled.tags-list.grid_9')
    hashs = tab.find_elements_by_tag_name('li')
    for element in hashs:
        element.find_element_by_tag_name('i').click()
</code>```

And it gave me this error:

```<code>stale element reference: element is not attached to the page document
</code>```

答:
Stale Element Reference Exception occurs if a page refreshes or an element changes on the page (also refreshes or disappears). In your case, this is likely happening either with tab, hash or 2nd element (cannot say without seeing the page).

To avoid Stale Element Reference Exception, try re-locating elements before interacting with them, something like:

```<code>tab = driver.find_element_by_css_selector('#postForm > div:nth-child(3) > ul.list-unstyled.tags-list.grid_9')
hashs = tab.find_elements_by_tag_name('li')

for i in range(len(hashs)):
    tab = driver.find_element_by_css_selector('#postForm > div:nth-child(3) > ul.list-unstyled.tags-list.grid_9')
    element = tab.find_elements_by_tag_name('li')[i]
    element.find_element_by_tag_name('i').click()
</code>```

Hopefully, this helps. Good luck!

Body:
I need to interact with elements under a class but the number of elements in that class is changing every time I run the script.

To give you context the website is a calendar, where I need to pick a day that I'll use as a template for my work. Every time I run the script (Monthly) the webpage with the calendar is updated to show the current month, thus Selenium picks the same day it did in the previous month. But every month the day Selenium picks has different contents and number of elements change every month. Currently, for example, the script is written to interact with 5 elements, but for next month it won't work because the day picked will have a different number of elements. So every month I have to manually change the script to interact with the correct number of elements.

Here's an example of the element structure of the website:

Text

Text

Text

So the number of elements that I need to interact within the class 'list-unstyled tags-list grid_9' is always changing. The elements with the id's "0", "1" and "2". Sometimes there might be 4 elements with ID's "0", "1", "2", "3" and sometimes there's 2 elements etc.

I've been trying to figure out how to write a script where Selenium looks inside that class ''list-unstyled tags-list grid_9', see's how many elements are in there and executes a -

driver.find_element_by_(xpath,class,id whatever).click()

on all of the elements found in there.

UPDATE:
So I tried this code:

tab = driver.find_element_by_css_selector('#postForm > div:nth-child(3) > ul.list-unstyled.tags-list.grid_9')
    hashs = tab.find_elements_by_tag_name('li')
    for element in hashs:
        element.find_element_by_tag_name('i').click()

And it gave me this error:

stale element reference: element is not attached to the page document

Body:
Stale Element Reference Exception occurs if a page refreshes or an element changes on the page (also refreshes or disappears). In your case, this is likely happening either with tab, hash or 2nd element (cannot say without seeing the page).

To avoid Stale Element Reference Exception, try re-locating elements before interacting with them, something like:

tab = driver.find_element_by_css_selector('#postForm > div:nth-child(3) > ul.list-unstyled.tags-list.grid_9')
hashs = tab.find_elements_by_tag_name('li')

for i in range(len(hashs)):
    tab = driver.find_element_by_css_selector('#postForm > div:nth-child(3) > ul.list-unstyled.tags-list.grid_9')
    element = tab.find_elements_by_tag_name('li')[i]
    element.find_element_by_tag_name('i').click()

Hopefully, this helps. Good luck!


来源: stackexchange

问:
Where is Android Studio Markdown support plugin preview preference?
I want to show preview for markdown.
But it is not shown.

I am using Markdown support by JetBrains. And Android Studio 3.1

I found IntelliJ help.

https://www.jetbrains.com/help/idea/markdown.html

But I can not see that preference.

How can I see markdown preview?

答:
There is another plugin which is "Markdown Navigator Enhanced" and that I tested on Android Studio 3.5.2, it enables a toolbar with some editing functions as well as the preview options.

You can Edit, preview or do both in a split window, you can even show the HTML code.

The plug-in is paid, but it has a 30-days trial that can be good for a short usage.

ContentLicense: CC BY-SA 4.0


问:
How to use "ref" to refer an element in React Stateless Component
I was trying to implement focus for the Submit button with Ref. I wanted to omit refering elements by ID.

```<code>import React, { useRef } from 'react'
import PropTypes from 'prop-types'

export const LabelComponent = () => {

  const createButton = enableCreateButton()
    ? <button ref={(input) => { this.createLabelBtn = input }} >Submit</button>
    : <button disabled ref={(input) => { this.createLabelBtn = input }} >Submit</button>

  const createLabelBtn = useRef();

  const focusCreateBtn = (e) => {
    if ((e.key === 'Enter') && (newLabel.name !== '')) {
      this.createLabelBtn.focus();
    }
  };

  return (
    <div className='create-label-container'>
      <input type='text'
        onKeyDown={(e) => { focusCreateBtn(e) }}
      />

      {createButton}
    </div>
  )
}
</code>```

It gives following error.

Uncaught TypeError: Cannot set property 'createLabelBtn' of undefined

Uncaught TypeError: Cannot set property 'createLabelBtn' of undefined

What could be the issue here.?

答:
Try this</p>

```<code>import React, { useRef, useState } from "react";

const LabelComponent = () => {
  const [name, setName] = useState("");

  const createButton = true ? (
    <button
      ref={input => {
        createLabelBtn.current = input;
      }}
    >
      Submit
    </button>
  ) : (
    <button
      disabled
      ref={input => {
        createLabelBtn.current = input;
      }}
    >
      Submit
    </button>
  );

  const createLabelBtn = useRef();

  const focusCreateBtn = e => {
    if (e.key === "Enter" && name !== "") {
      createLabelBtn.current.focus();
    }
  };

  return (
    <div className="create-label-container">
      <input
        type="text"`enter code here`
        value={name}
        onChange={e => {
          setName(e.target.value);
        }}
        onKeyDown={e => {
          focusCreateBtn(e);
        }}
      />

      {createButton}
    </div>
  );
};

export default LabelComponent;
</code>```

Body:
I was trying to implement focus for the Submit button with Ref. I wanted to omit refering elements by ID.

import React, { useRef } from 'react'
import PropTypes from 'prop-types'

export const LabelComponent = () => {

  const createButton = enableCreateButton()
    ? <button ref={(input) => { this.createLabelBtn = input }} >Submit</button>
    : <button disabled ref={(input) => { this.createLabelBtn = input }} >Submit</button>

  const createLabelBtn = useRef();

  const focusCreateBtn = (e) => {
    if ((e.key === 'Enter') && (newLabel.name !== '')) {
      this.createLabelBtn.focus();
    }
  };

  return (

      <input type='text'
        onKeyDown={(e) => { focusCreateBtn(e) }}
      />

      {createButton}

  )
}

It gives following error.

Uncaught TypeError: Cannot set property 'createLabelBtn' of undefined

Uncaught TypeError: Cannot set property 'createLabelBtn' of undefined

What could be the issue here.?

Body:
Try this

import React, { useRef, useState } from "react";

const LabelComponent = () => {
  const [name, setName] = useState("");

  const createButton = true ? (
    <button
      ref={input => {
        createLabelBtn.current = input;
      }}
    >
      Submit
    </button>
  ) : (
    <button
      disabled
      ref={input => {
        createLabelBtn.current = input;
      }}
    >
      Submit
    </button>
  );

  const createLabelBtn = useRef();

  const focusCreateBtn = e => {
    if (e.key === "Enter" && name !== "") {
      createLabelBtn.current.focus();
    }
  };

  return (
    <div className="create-label-container">
      <input
        type="text"`enter code here`
        value={name}
        onChange={e => {
          setName(e.target.value);
        }}
        onKeyDown={e => {
          focusCreateBtn(e);
        }}
      />

      {createButton}
    </div>
  );
};

export default LabelComponent;


问:
Is it possible to select an anchor tag which contains a h1 which contains the text "Visit Site"?
I am using Cypress.io to test my startup's website and would like to select a specific anchor tag.

However, that anchor tag does not have any unique attribute I can use to identify it, therefore I would like to use a child h1 tag containing the text "Visit Site" to help with identifying the anchor tag.

```<code><a href="/blablabla" target="_blank" rel="noopener noreferrer canonical">
  <h1>Visit Site</h1>
</a>
</code>```

I would not be able to use the href attribute to help identify the anchor tag, as the written test would be used across other pages of the same structure but of different content.

My issue is that I do not know if its possible to select an element based on whether it contains an element of a certain text.

答:
Hi As per your question I'm prepared example please check this link
Example Link

$(document).ready(function(){
$("a").each(function(index,elem){
 let findHeading=$(elem).find("h1:contains('Visit Site')");
  if(findHeading!=undefined)
  {
   console.log("Index "+index);
   console.log("Find H1 "+$(findHeading).html());
  }

})

})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  <h1>Visit Site</h1>

  <h1>Hello</h1>

  <h1>Visit Site</h1>
</code>```

Note:  you can see the second A tag h1 contain has hello word

Body:
I am using Cypress.io to test my startup's website and would like to select a specific anchor tag.

However, that anchor tag does not have any unique attribute I can use to identify it, therefore I would like to use a child h1 tag containing the text "Visit Site" to help with identifying the anchor tag.

Visit Site

I would not be able to use the href attribute to help identify the anchor tag, as the written test would be used across other pages of the same structure but of different content.

My issue is that I do not know if its possible to select an element based on whether it contains an element of a certain text.

Body:
Hi As per your question I'm prepared example please check this link
Example Link

$(document).ready(function(){
$("a").each(function(index,elem){
 let findHeading=$(elem).find("h1:contains('Visit Site')");
  if(findHeading!=undefined)
  {
   console.log("Index "+index);
   console.log("Find H1 "+$(findHeading).html());
  }

})

})

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="/blablabla" target="_blank" rel="noopener noreferrer canonical">
  <h1>Visit Site</h1>
</a>
<a href="/blablabla" target="_blank" rel="noopener noreferrer canonical">
  <h1>Hello</h1>
</a>
<a href="/blablabla" target="_blank" rel="noopener noreferrer canonical">
  <h1>Visit Site</h1>
</a>

Note:  you can see the second A tag h1 contain has hello word


问:
How can images be modified and appended to the end of a list with python using PIL?
Using a for loop I am trying to modify the color values of an image and then append the modified copy of the image to a list.  Every time I run my for loop, all images in my list are modified rather than the for loop generating a new copy that gets appended to the end of the list.  As a result, all images end up looking like the last iteration of the for loop. My current code is as follows. Please advise.</p>

```<code>import PIL
from PIL import Image
from PIL import ImageEnhance

pic=Image.open("pic.gif")
pic=pic.convert('RGB')
width, height = pic.size

pics=[]
for intens in [.1, .5, .9]:
    for x in range(pic.width):
        for y in range(pic.height):
            a = pic.getpixel((x,y))
            a = (int(a[0]*intens), a[1], a[2])
            pic.putpixel((x,y),a)
    pics.append(pic)
</code>```

答:
To solve this I wrapped my list of intensities with another for loop in order to iterate through everything 3 more times.</p>
```<code>import PIL
from PIL import Image
from PIL import ImageEnhance

pic=Image.open("pic.gif")
pic=pic.convert('RGB')
width, height = pic.size

pics=[]
for i in range(3):
    for intens in [.1, .5, .9]:
        for x in range(pic.width):
            for y in range(pic.height):
                a = pic.getpixel((x,y))
                a = (int(a[0]*intens), a[1], a[2])
                pic.putpixel((x,y),a)
    pics.append(pic)
</code>```

Body:
Using a for loop I am trying to modify the color values of an image and then append the modified copy of the image to a list.  Every time I run my for loop, all images in my list are modified rather than the for loop generating a new copy that gets appended to the end of the list.  As a result, all images end up looking like the last iteration of the for loop. My current code is as follows. Please advise.

import PIL
from PIL import Image
from PIL import ImageEnhance

pic=Image.open("pic.gif")
pic=pic.convert('RGB')
width, height = pic.size

pics=[]
for intens in [.1, .5, .9]:
    for x in range(pic.width):
        for y in range(pic.height):
            a = pic.getpixel((x,y))
            a = (int(a[0]*intens), a[1], a[2])
            pic.putpixel((x,y),a)
    pics.append(pic)

Body:
To solve this I wrapped my list of intensities with another for loop in order to iterate through everything 3 more times.

import PIL
from PIL import Image
from PIL import ImageEnhance

pic=Image.open("pic.gif")
pic=pic.convert('RGB')
width, height = pic.size

pics=[]
for i in range(3):
    for intens in [.1, .5, .9]:
        for x in range(pic.width):
            for y in range(pic.height):
                a = pic.getpixel((x,y))
                a = (int(a[0]*intens), a[1], a[2])
                pic.putpixel((x,y),a)
    pics.append(pic)


问:
laravel: check the user received email today in laravel using carbon today
I want to check that the user received email on that day or not. I already create DB table(name is Email Save) to detect that email sending or not. so i try to if statement in this

if (EmailSave::where('created_at')-> Carbon::today()) {
```

this one didnt work. Anyone can help on this. I give my code over here

答:
Your Syntax is wrong.

Change :

```<code>if (EmailSave::where('created_at')-> Carbon::today()) {
</code>```

To:

```<code>if (EmailSave::where('created_at', Carbon::today())->exists()) {
</code>```

Documentation:

https://laravel.com/docs/5.8/eloquent#retrieving-models

https://laravel.com/docs/5.8/queries#aggregates

Body:
I want to check that the user received email on that day or not. I already create DB table(name is Email Save) to detect that email sending or not. so i try to if statement in this

if (EmailSave::where('created_at')-> Carbon::today()) {

this one didnt work. Anyone can help on this. I give my code over here

Body:
Your Syntax is wrong.

Change :

if (EmailSave::where('created_at')-> Carbon::today()) {

To:

if (EmailSave::where('created_at', Carbon::today())->exists()) {

Documentation:

https://laravel.com/docs/5.8/eloquent#retrieving-models

https://laravel.com/docs/5.8/queries#aggregates


问:
One-way one-to-one relationship with EF Core
What I want to achieve, is have a model CommentsThread that can be attached to any other model that needs comments, be it Chapter, BlogPost, UserProfile, or what have you. Basically, the structure I need is

```<code>CommentsThread
  int ID

Chapter
  int ID
  int Thread FK(CommentsThread.ID)

BlogPost
  int ID
  int Thread FK(CommentsThread.ID)

UserProfile
  int ID
  int Thread FK(CommentsThread.ID)
</code>```

however I have no idea how to configure it properly in EF core, without having to add nullable references to Chapter, BlogPost and UserProfile to the CommentsThread model.

My code for CommentsThread is as follows:

public class CommentsThread
{
    [Key]
    [Required]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public ICollection<Comment> Comments { get; set; }
}
```

<p>And <code>Chapter</code>, omitting any irrelevant properties, is</p>

<pre class="lang-cs prettyprint-override"><code>public class Chapter
{
    [Key]
    [Required]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public CommentsThread CommentsThread { get; set; }
}
</code>```

With the following Fluent config (again, skipping the irrelevant bits):

builder.Entity<CommentsThread>()
    .HasMany(ct => ct.Comments)
    .WithOne()
    .OnDelete(DeleteBehavior.Cascade);

builder.Entity<Chapter>()
    .HasOne(c => c.CommentsThread)
    .WithOne()
    .OnDelete(DeleteBehavior.Cascade);
```

<p>On <code>dotnet ef migrations add X</code> it throws this output into the console.</p>

<hr>

<p><strong>Update:</strong></p>

<p>So, I tried explicitly adding <code>public int CommentsThreadId { get; set; }</code> to the <code>Chapter</code> and changing the config to</p>

```builder.Entity<Chapter>()
    .HasOne(c => c.CommentsThread)
    .WithOne()
    .HasForeignKey<Chapter>(c => c.CommentsThreadId)
    .OnDelete(DeleteBehavior.Cascade);
```

<p>That did make the migration go through, but failed on <code>database update</code> with</p>

```The CREATE UNIQUE INDEX statement terminated because a duplicate key was found for the object name 'dbo.Chapters' and the index name 'IX_Chapters_CommentsThreadId'. The duplicate key value is (0).
The statement has been terminated.
```

答:
AFAIK, there are two ways to configure 1-1 relationship:

https://www.entityframeworktutorial.net/efcore/one-to-one-conventions-entity-framework-core.aspx

https://weblogs.asp.net/manavi/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-2-table-per-type-tpt

the 1st post requires reference from each model. but you mentioned:

without having to add nullable references

then, only the 2nd concept (Table Per Type) can reach your goal, but the post is too old code to EF Core.

Here are new data models:

```<code>public class CommentsThread
{
    [Key]
    [Required]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    public string Title { get; set; }

    public ICollection<ThreadComment> Comments { get; set; }
}

[Table(nameof(Chapter))]
public class Chapter
{
    [Key]
    [Required]
    [ForeignKey(nameof(CommentsThread))]
    public int Id { get; set; }

    public int Number { get; set; }

    public CommentsThread CommentsThread { get; set; }
}
[Table(nameof(BlogPost))]
public class BlogPost
{
    [Key]
    [Required]
    [ForeignKey(nameof(CommentsThread))]
    public int Id { get; set; }

    public string Author { get; set; }

    public CommentsThread CommentsThread { get; set; }
}

[Table(nameof(UserProfile))]
public class UserProfile
{
    [Key]
    [Required]
    [ForeignKey(nameof(CommentsThread))]
    public int Id { get; set; }
    public string Bio { get; set; }

    public CommentsThread CommentsThread { get; set; }
}

public class ThreadComment
{
    [Key]
    [Required]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    public string Content { get; set; }

    public CommentsThread CommentsThread { get; set; }
}
</code>```

Here is sample context:

```<code>public class ApplicationDbContext : IdentityDbContext
{
    public virtual DbSet<CommentsThread> CommentsThreads { get; set; }
    public virtual DbSet<Chapter> Chapters { get; set; }
    public virtual DbSet<BlogPost> BlogPosts { get; set; }
    public virtual DbSet<UserProfile> UserProfiles { get; set; }
    public virtual DbSet<ThreadComment> ThreadComments { get; set; }

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<Chapter>().ToTable(nameof(Chapter));
        modelBuilder.Entity<BlogPost>().ToTable(nameof(BlogPost));
        modelBuilder.Entity<UserProfile>().ToTable(nameof(UserProfile));
    }
}
</code>```

Here is generated migration code:

```<code>public partial class AddCommentsThread : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
            name: "CommentsThreads",
            columns: table => new
            {
                Id = table.Column<int>(nullable: false)
                    .Annotation("SqlServer:Identity", "1, 1"),
                Title = table.Column<string>(nullable: false)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_CommentsThreads", x => x.Id);
            });

        migrationBuilder.CreateTable(
            name: "BlogPost",
            columns: table => new
            {
                Id = table.Column<int>(nullable: false),
                Author = table.Column<string>(nullable: true)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_BlogPost", x => x.Id);
                table.ForeignKey(
                    name: "FK_BlogPost_CommentsThreads_Id",
                    column: x => x.Id,
                    principalTable: "CommentsThreads",
                    principalColumn: "Id",
                    onDelete: ReferentialAction.Cascade);
            });

        migrationBuilder.CreateTable(
            name: "Chapter",
            columns: table => new
            {
                Id = table.Column<int>(nullable: false),
                Number = table.Column<int>(nullable: false)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_Chapter", x => x.Id);
                table.ForeignKey(
                    name: "FK_Chapter_CommentsThreads_Id",
                    column: x => x.Id,
                    principalTable: "CommentsThreads",
                    principalColumn: "Id",
                    onDelete: ReferentialAction.Cascade);
            });

        migrationBuilder.CreateTable(
            name: "ThreadComments",
            columns: table => new
            {
                Id = table.Column<int>(nullable: false)
                    .Annotation("SqlServer:Identity", "1, 1"),
                Content = table.Column<string>(nullable: false),
                CommentsThreadId = table.Column<int>(nullable: true)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_ThreadComments", x => x.Id);
                table.ForeignKey(
                    name: "FK_ThreadComments_CommentsThreads_CommentsThreadId",
                    column: x => x.CommentsThreadId,
                    principalTable: "CommentsThreads",
                    principalColumn: "Id",
                    onDelete: ReferentialAction.Restrict);
            });

        migrationBuilder.CreateTable(
            name: "UserProfile",
            columns: table => new
            {
                Id = table.Column<int>(nullable: false),
                Bio = table.Column<string>(nullable: true)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_UserProfile", x => x.Id);
                table.ForeignKey(
                    name: "FK_UserProfile_CommentsThreads_Id",
                    column: x => x.Id,
                    principalTable: "CommentsThreads",
                    principalColumn: "Id",
                    onDelete: ReferentialAction.Cascade);
            });

        migrationBuilder.CreateIndex(
            name: "IX_ThreadComments_CommentsThreadId",
            table: "ThreadComments",
            column: "CommentsThreadId");
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropTable(
            name: "BlogPost");

        migrationBuilder.DropTable(
            name: "Chapter");

        migrationBuilder.DropTable(
            name: "ThreadComments");

        migrationBuilder.DropTable(
            name: "UserProfile");

        migrationBuilder.DropTable(
            name: "CommentsThreads");
    }
}
</code>```

Here is screenshot for result:

Body:
What I want to achieve, is have a model CommentsThread that can be attached to any other model that needs comments, be it Chapter, BlogPost, UserProfile, or what have you. Basically, the structure I need is

CommentsThread
  int ID

Chapter
  int ID
  int Thread FK(CommentsThread.ID)

BlogPost
  int ID
  int Thread FK(CommentsThread.ID)

UserProfile
  int ID
  int Thread FK(CommentsThread.ID)

however I have no idea how to configure it properly in EF core, without having to add nullable references to Chapter, BlogPost and UserProfile to the CommentsThread model.

My code for CommentsThread is as follows:

public class CommentsThread
{
    [Key]
    [Required]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public ICollection<Comment> Comments { get; set; }
}

And Chapter, omitting any irrelevant properties, is

public class Chapter
{
    [Key]
    [Required]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public CommentsThread CommentsThread { get; set; }
}

With the following Fluent config (again, skipping the irrelevant bits):

builder.Entity<CommentsThread>()
    .HasMany(ct => ct.Comments)
    .WithOne()
    .OnDelete(DeleteBehavior.Cascade);

builder.Entity<Chapter>()
    .HasOne(c => c.CommentsThread)
    .WithOne()
    .OnDelete(DeleteBehavior.Cascade);

On dotnet ef migrations add X it throws this output into the console.

Update:

So, I tried explicitly adding public int CommentsThreadId { get; set; } to the Chapter and changing the config to

builder.Entity<Chapter>()
    .HasOne(c => c.CommentsThread)
    .WithOne()
    .HasForeignKey<Chapter>(c => c.CommentsThreadId)
    .OnDelete(DeleteBehavior.Cascade);

That did make the migration go through, but failed on database update with

The CREATE UNIQUE INDEX statement terminated because a duplicate key was found for the object name 'dbo.Chapters' and the index name 'IX_Chapters_CommentsThreadId'. The duplicate key value is (0).
The statement has been terminated.

Body:
AFAIK, there are two ways to configure 1-1 relationship:

https://www.entityframeworktutorial.net/efcore/one-to-one-conventions-entity-framework-core.aspx

https://weblogs.asp.net/manavi/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-2-table-per-type-tpt

the 1st post requires reference from each model. but you mentioned:

without having to add nullable references

then, only the 2nd concept (Table Per Type) can reach your goal, but the post is too old code to EF Core.

Here are new data models:

public class CommentsThread
{
    [Key]
    [Required]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    public string Title { get; set; }

    public ICollection<ThreadComment> Comments { get; set; }
}

[Table(nameof(Chapter))]
public class Chapter
{
    [Key]
    [Required]
    [ForeignKey(nameof(CommentsThread))]
    public int Id { get; set; }

    public int Number { get; set; }

    public CommentsThread CommentsThread { get; set; }
}
[Table(nameof(BlogPost))]
public class BlogPost
{
    [Key]
    [Required]
    [ForeignKey(nameof(CommentsThread))]
    public int Id { get; set; }

    public string Author { get; set; }

    public CommentsThread CommentsThread { get; set; }
}

[Table(nameof(UserProfile))]
public class UserProfile
{
    [Key]
    [Required]
    [ForeignKey(nameof(CommentsThread))]
    public int Id { get; set; }
    public string Bio { get; set; }

    public CommentsThread CommentsThread { get; set; }
}

public class ThreadComment
{
    [Key]
    [Required]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    public string Content { get; set; }

    public CommentsThread CommentsThread { get; set; }
}

Here is sample context:

public class ApplicationDbContext : IdentityDbContext
{
    public virtual DbSet<CommentsThread> CommentsThreads { get; set; }
    public virtual DbSet<Chapter> Chapters { get; set; }
    public virtual DbSet<BlogPost> BlogPosts { get; set; }
    public virtual DbSet<UserProfile> UserProfiles { get; set; }
    public virtual DbSet<ThreadComment> ThreadComments { get; set; }

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<Chapter>().ToTable(nameof(Chapter));
        modelBuilder.Entity<BlogPost>().ToTable(nameof(BlogPost));
        modelBuilder.Entity<UserProfile>().ToTable(nameof(UserProfile));
    }
}

Here is generated migration code:

public partial class AddCommentsThread : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
            name: "CommentsThreads",
            columns: table => new
            {
                Id = table.Column<int>(nullable: false)
                    .Annotation("SqlServer:Identity", "1, 1"),
                Title = table.Column<string>(nullable: false)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_CommentsThreads", x => x.Id);
            });

        migrationBuilder.CreateTable(
            name: "BlogPost",
            columns: table => new
            {
                Id = table.Column<int>(nullable: false),
                Author = table.Column<string>(nullable: true)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_BlogPost", x => x.Id);
                table.ForeignKey(
                    name: "FK_BlogPost_CommentsThreads_Id",
                    column: x => x.Id,
                    principalTable: "CommentsThreads",
                    principalColumn: "Id",
                    onDelete: ReferentialAction.Cascade);
            });

        migrationBuilder.CreateTable(
            name: "Chapter",
            columns: table => new
            {
                Id = table.Column<int>(nullable: false),
                Number = table.Column<int>(nullable: false)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_Chapter", x => x.Id);
                table.ForeignKey(
                    name: "FK_Chapter_CommentsThreads_Id",
                    column: x => x.Id,
                    principalTable: "CommentsThreads",
                    principalColumn: "Id",
                    onDelete: ReferentialAction.Cascade);
            });

        migrationBuilder.CreateTable(
            name: "ThreadComments",
            columns: table => new
            {
                Id = table.Column<int>(nullable: false)
                    .Annotation("SqlServer:Identity", "1, 1"),
                Content = table.Column<string>(nullable: false),
                CommentsThreadId = table.Column<int>(nullable: true)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_ThreadComments", x => x.Id);
                table.ForeignKey(
                    name: "FK_ThreadComments_CommentsThreads_CommentsThreadId",
                    column: x => x.CommentsThreadId,
                    principalTable: "CommentsThreads",
                    principalColumn: "Id",
                    onDelete: ReferentialAction.Restrict);
            });

        migrationBuilder.CreateTable(
            name: "UserProfile",
            columns: table => new
            {
                Id = table.Column<int>(nullable: false),
                Bio = table.Column<string>(nullable: true)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_UserProfile", x => x.Id);
                table.ForeignKey(
                    name: "FK_UserProfile_CommentsThreads_Id",
                    column: x => x.Id,
                    principalTable: "CommentsThreads",
                    principalColumn: "Id",
                    onDelete: ReferentialAction.Cascade);
            });

        migrationBuilder.CreateIndex(
            name: "IX_ThreadComments_CommentsThreadId",
            table: "ThreadComments",
            column: "CommentsThreadId");
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropTable(
            name: "BlogPost");

        migrationBuilder.DropTable(
            name: "Chapter");

        migrationBuilder.DropTable(
            name: "ThreadComments");

        migrationBuilder.DropTable(
            name: "UserProfile");

        migrationBuilder.DropTable(
            name: "CommentsThreads");
    }
}

Here is screenshot for result:


问:
How to select a certain cell from a table
I have 14 generated cells.

How can I select a specific cell from the 14 cells and control it? I want only one cell to be unique, the rest to be how they are displayed in the code, normally.

var isCol = 0;
var board = [];
for (r = 0; r < 7; r++) {
  var line = [];
  for (c = 0; c < 7; c++) {
    line.push(r);
  }
  board.push(line);
}

function prs(c, r) {
  showTable(c, r);
  isCol = (isCol + 1) % 2;
}

function toColor(col, row, chosen_col, chosen_row) {
  var ret = false;
  switch (isCol) {
    case 0:
      if (row == chosen_row) {
        ret = true;
      }
      break;
    case 1:
      if (col == chosen_col) {
        ret = true;
      }
      break;
  }

  return ret;
}

function showTable(chosen_col, chosen_row) {
  var str = "";
  str += "
";
  for (row = 0; row < 7; row++) {
    str += "
";
    for (col = 0; col < 7; col++) {
      str += "";
      str += RandomGenerator(50, 500);
      str += "	";
    }
    str += "
";
  }
  str += "
";

  document.getElementById("ff").innerHTML = str;
}

function RandomGenerator(min, max) {
  return Math.floor(Math.random() * (max - min) + min);
}

showTable(-1);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>td {
  border: 2px solid black;
  width: 10px;
  height: 10px;
}

td:hover {
  background-color: lightgreen;
}

.grn {
  background-color: green;
  color: white;
}</code>```

```

答:
You can create a ID for that row

EG

```<code><td id = "uniqueCell"> ... </td>
</code>```

Then in your javascript you can do the following.

```<code>var uniqueCell = document.getElementById('uniqueCell');
</code>```

then use that variable to do what you need to do

Body:
I have 14 generated cells.

How can I select a specific cell from the 14 cells and control it? I want only one cell to be unique, the rest to be how they are displayed in the code, normally.

var isCol = 0;
var board = [];
for (r = 0; r < 7; r++) {
  var line = [];
  for (c = 0; c < 7; c++) {
    line.push(r);
  }
  board.push(line);
}

function prs(c, r) {
  showTable(c, r);
  isCol = (isCol + 1) % 2;
}

function toColor(col, row, chosen_col, chosen_row) {
  var ret = false;
  switch (isCol) {
    case 0:
      if (row == chosen_row) {
        ret = true;
      }
      break;
    case 1:
      if (col == chosen_col) {
        ret = true;
      }
      break;
  }

  return ret;
}

function showTable(chosen_col, chosen_row) {
  var str = "";
  str += "
";
  for (row = 0; row < 7; row++) {
    str += "
";
    for (col = 0; col < 7; col++) {
      str += "";
      str += RandomGenerator(50, 500);
      str += "	";
    }
    str += "
";
  }
  str += "
";

  document.getElementById("ff").innerHTML = str;
}

function RandomGenerator(min, max) {
  return Math.floor(Math.random() * (max - min) + min);
}

showTable(-1);

td {
  border: 2px solid black;
  width: 10px;
  height: 10px;
}

td:hover {
  background-color: lightgreen;
}

.grn {
  background-color: green;
  color: white;
}

Body:
You can create a ID for that row

EG

<td id = "uniqueCell"> ... </td>

Then in your javascript you can do the following.

var uniqueCell = document.getElementById('uniqueCell');

then use that variable to do what you need to do


问:
Attempting to add a strongly typed view does not find any classes in the MVC project
I have a very odd problem. Whenever I try to use the "Add View" dialog in ASP.NET MVC2 and then try to "Create a strongly-typed view" by selecting a "View data class" from the drop down of available classes none of the classes ("models") in my MVC project are showing up.

The very odd part is all of the assemblies that my MVC project is referencing, even other projects in the solution, their classes are showing up. I have tried cleaning, rebuilding, cleaning the obj folder but every single time for some reason none of the classes in my actual MVC assembly are showing up. It was working fine before but now it doesn't anymore and I can't really think of anything that has changed.

Anyone experienced this issue before?
Thanks for the help!

Image of example:

答: Please make sure that you are marking them as "Public", and compile it once before opening the AddView Dialog box.</p>

ContentLicense: CC BY-SA 3.0


问:
How to avoid unnecessary rendering in component with hooks
Hello I have a themeprovider with two themes with the Emotion provider theme

and I have a component Header where I get this theme through useTheme:

```<code>const Header = () => {
  const Theme = useTheme();
  const [text, setText] = useState('');
  console.log(Theme, 'this is header');
  const handleClick = () => {
    setText('');
  };
  return (
    <Container theme={Theme}>
      <Content theme={Theme} flexdirection={'column'}>
        <textarea
          onKeyPress={e => {
            if (e.key === 'Enter') {
              e.preventDefault();
            }
            if (e.key === 'Enter') {
              handleClick();
            }
          }}
          value={text}
          onChange={e => setText(e.target.value)}
          placeholder="Digite aqui sua mensagem"
        />
        <Top theme={Theme} />
        <NavBar theme={Theme} />
      </Content>
    </Container>
  );
};
</code>```

and then I pass my theme as props for a child:

```<code>const NavBar = props => {
  console.log(props.theme, 'this is nav bar');
  return (
    <Nav>
      <ul>
        <li>
          <a href="#home">home</a>
        </li>
        <li>
          <a href="#homex">test</a>
        </li>
        <li>
          <a href="#homexv">test</a>
        </li>
      </ul>
    </Nav>
  );
};
</code>```

But in this component I have a textfield where I will render when typing, but my theme is rendering together as in the gif:

here's my hook to control the theme:

```<code>export default function useAppTheme(defaultTheme = lightTheme) {
  const [theme, _setTheme] = useState(getInitialTheme);

  function getInitialTheme() {
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme === 'dark' || savedTheme === 'light') {
      return JSON.parse(savedTheme) === 'dark' ? darkTheme : defaultTheme;
    } else {
      return defaultTheme;
    }
  }

  useEffect(() => {
    localStorage.setItem('theme', JSON.stringify(theme.type));
  }, [theme]);

  return {
    theme,
    setTheme: ({ setTheme, ...theme }) => {
      if (theme.type === 'dark') {
        return _setTheme(darkTheme);
      } else {
        return _setTheme(lightTheme);
      }
    },
  };
}
</code>```

and my principal component:

```<code>export default function App() {
  const { theme, setTheme } = useAppTheme();

  useEffect(() => {
    console.log('rendering app');
  });

  return (
    <ThemeProvider theme={theme}>
      <GlobalStyle />
      <div className="App">
        <Header />
        <button
          css={css`
            background: red;
            width: 100px;
            height: 50px;
            border-radius: 10px;
          `}
          onClick={() =>
            setTheme(
              theme.type === 'dark' ? { type: 'light' } : { type: 'dark' },
            )
          }
        >
          a
        </button>
      </div>
    </ThemeProvider>
</code>```

答:
As I understand, your code is working as expected. I think I can explain it as below.

Header is re-rendered because of state update (calling setText onChange). If a component is re-rendered, every child component will need to re-render (even if the props don't change). You can opt-out from this re-rendering using shouldComponentUpdate or being a PureComponent or memoized function(al) component. Here, as we can see NavBar is just a state functional component and it will re-rendered on every state updates. Please see here for details.

You can solve this using React.memo like below:-

```<code>const NavBar = React.memo(props => {
  console.log(props.theme, 'this is nav bar');
  return (
    <Nav>
      <ul>
        <li>
          <a href="#home">home</a>
        </li>
        <li>
          <a href="#homex">test</a>
        </li>
        <li>
          <a href="#homexv">test</a>
        </li>
      </ul>
    </Nav>
  );
});
</code>```

Now your component will not get re-rendered unless the props actually changed.

Body:
Hello I have a themeprovider with two themes with the Emotion provider theme

and I have a component Header where I get this theme through useTheme:

const Header = () => {
  const Theme = useTheme();
  const [text, setText] = useState('');
  console.log(Theme, 'this is header');
  const handleClick = () => {
    setText('');
  };
  return (
    <Container theme={Theme}>
      <Content theme={Theme} flexdirection={'column'}>
        <textarea
          onKeyPress={e => {
            if (e.key === 'Enter') {
              e.preventDefault();
            }
            if (e.key === 'Enter') {
              handleClick();
            }
          }}
          value={text}
          onChange={e => setText(e.target.value)}
          placeholder="Digite aqui sua mensagem"
        />
        <Top theme={Theme} />
        <NavBar theme={Theme} />
      </Content>
    </Container>
  );
};

and then I pass my theme as props for a child:

const NavBar = props => {
  console.log(props.theme, 'this is nav bar');
  return (

          home

          test

          test

  );
};

But in this component I have a textfield where I will render when typing, but my theme is rendering together as in the gif:

here's my hook to control the theme:

export default function useAppTheme(defaultTheme = lightTheme) {
  const [theme, _setTheme] = useState(getInitialTheme);

  function getInitialTheme() {
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme === 'dark' || savedTheme === 'light') {
      return JSON.parse(savedTheme) === 'dark' ? darkTheme : defaultTheme;
    } else {
      return defaultTheme;
    }
  }

  useEffect(() => {
    localStorage.setItem('theme', JSON.stringify(theme.type));
  }, [theme]);

  return {
    theme,
    setTheme: ({ setTheme, ...theme }) => {
      if (theme.type === 'dark') {
        return _setTheme(darkTheme);
      } else {
        return _setTheme(lightTheme);
      }
    },
  };
}

and my principal component:

export default function App() {
  const { theme, setTheme } = useAppTheme();

  useEffect(() => {
    console.log('rendering app');
  });

  return (
    <ThemeProvider theme={theme}>
      <GlobalStyle />

        <button
          css={css`
            background: red;
            width: 100px;
            height: 50px;
            border-radius: 10px;
          `}
          onClick={() =>
            setTheme(
              theme.type === 'dark' ? { type: 'light' } : { type: 'dark' },
            )
          }
        >
          a
        </button>

    </ThemeProvider>

Body:
As I understand, your code is working as expected. I think I can explain it as below.

Header is re-rendered because of state update (calling setText onChange). If a component is re-rendered, every child component will need to re-render (even if the props don't change). You can opt-out from this re-rendering using shouldComponentUpdate or being a PureComponent or memoized function(al) component. Here, as we can see NavBar is just a state functional component and it will re-rendered on every state updates. Please see here for details.

You can solve this using React.memo like below:-

const NavBar = React.memo(props => {
  console.log(props.theme, 'this is nav bar');
  return (
    <Nav>
      <ul>
        <li>
          <a href="#home">home</a>
        </li>
        <li>
          <a href="#homex">test</a>
        </li>
        <li>
          <a href="#homexv">test</a>
        </li>
      </ul>
    </Nav>
  );
});

Now your component will not get re-rendered unless the props actually changed.


问:
How to pull out text within an h3 tag class in selenium using python?
I currently am having difficulty extracting text from the following page:

I have tried browser.find_element_by_class_name("W6bZuc.YMllz").text

and also

browser.find_element_by_tag_name("h3").text

but these all come up empty. Is there a way to get the h3 element consistently using selenium webdriver in python? Thanks.

答:
Try use .get_attribute('innerHTML'):

```<code>driver.find_element_by_css_selector('.W6bZuc.YMllz').get_attribute('innerHTML')
</code>```

Body:
Try use .get_attribute('innerHTML'):

driver.find_element_by_css_selector('.W6bZuc.YMllz').get_attribute('innerHTML')


问:
How to scroll the page to the very bottom in Android Espresso?
I need to check the presence of the button that is located below. To do this, scroll through the page

```<code>@Test
public void checkMoneyBackButton() throws Exception {

    onView(withId(R.id.btnAuthLogin)).perform(click());

    Thread.sleep(10000);
    onView(withId(R.id.etSessionKey1)).perform(typeText("1234"));
    closeSoftKeyboard();

    SystemClock.sleep(45000);

    ViewInteraction viewInteraction = Espresso.onView(withText("**** 0431"));
    viewInteraction.perform(click());

    Thread.sleep(3000);

    onView(withId(R.id.cardContainer))
            .perform(swipeUp());

    onView(withId(R.id.statementMoneyBack)).check(matches(isDisplayed()));
}
</code>```

But using this code, I get an error:

```<code> Error performing 'fast swipe' on view 'with id:...
</code>```

答:
Add Barista into your Espresso and use this command. Barista will help you  for some action in your automation (Especially if your background is not engineering like me).</p>

```<code>scrollTo(R.id.far_away_widget);
scrollTo(R.string.text);
scrollTo("A widget with this text");
</code>```

Body:
I need to check the presence of the button that is located below. To do this, scroll through the page

@Test
public void checkMoneyBackButton() throws Exception {

    onView(withId(R.id.btnAuthLogin)).perform(click());

    Thread.sleep(10000);
    onView(withId(R.id.etSessionKey1)).perform(typeText("1234"));
    closeSoftKeyboard();

    SystemClock.sleep(45000);

    ViewInteraction viewInteraction = Espresso.onView(withText("**** 0431"));
    viewInteraction.perform(click());

    Thread.sleep(3000);

    onView(withId(R.id.cardContainer))
            .perform(swipeUp());

    onView(withId(R.id.statementMoneyBack)).check(matches(isDisplayed()));
}

But using this code, I get an error:

 Error performing 'fast swipe' on view 'with id:...

Body:
Add Barista into your Espresso and use this command. Barista will help you  for some action in your automation (Especially if your background is not engineering like me).

scrollTo(R.id.far_away_widget);
scrollTo(R.string.text);
scrollTo("A widget with this text");


问:
How to rearrange numbers using SED (transposition)
I have a line:

```<code>The ID number for product is 721- 971-4321.`
</code>```

I want to swap the area code and exchange it for the number inside, like so: 971- 721-4321

Here is what I have:

```<code>17s/\([654]\)-\([817]\)/\2-\1/
</code>```

So the number is on line 17 in a .txt file. There is other stuff on the line but I want to only change the number.

Whenever I run the script nothing happens. Any advice how to fix this.

答:
Could you please try following.

```<code>sed 's/\([^0-9]*\)\([^-]*\)\([^0-9]*\)\([^-]*\)\(.*\)/\1\4\3\2\5/' Input_file
</code>```

Explanation: I am using here back reference capability of sed here. Where by using regex I am creating 5 temporary buffers and then accessing them in reorder to make output as per OP's request.

Output will be as follows.

```<code>The ID number for product is 971- 721-4321.
</code>```

Body:
I have a line:

The ID number for product is 721- 971-4321.`

I want to swap the area code and exchange it for the number inside, like so: 971- 721-4321

Here is what I have:

17s/\([654]\)-\([817]\)/\2-\1/

So the number is on line 17 in a .txt file. There is other stuff on the line but I want to only change the number.

Whenever I run the script nothing happens. Any advice how to fix this.

Body:
Could you please try following.

sed 's/\([^0-9]*\)\([^-]*\)\([^0-9]*\)\([^-]*\)\(.*\)/\1\4\3\2\5/' Input_file

Explanation: I am using here back reference capability of sed here. Where by using regex I am creating 5 temporary buffers and then accessing them in reorder to make output as per OP's request.

Output will be as follows.

The ID number for product is 971- 721-4321.


问:
google Safebrowsing api v4 always returns empty response
I am using safe browsing api v4 in my android code.I am using Asynctask and request safebrowsing api using httpurlconnection.The response is always empty.

I have tested my connection using test url http://malware.testing.google.test/testing/malware/ also, then too it returns empty.

```<code>class Malicious extends AsyncTask<String, Void, Wrapper> {
    private OnTaskCompleted listener;

    public Malicious(OnTaskCompleted listener){
        this.listener=listener;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    protected Wrapper doInBackground(String... args) {
        String postURL = "https://safebrowsing.googleapis.com/v4/threatMatches:find?key=APIKEY";

        String requestBody = "{" +
                "    \"client\": {" +
                "      \"clientId\":      \"twittersentidetector\"," +
                "      \"clientVersion\": \"1.0\"" +
                "    }," +
                "    \"threatInfo\": {" +
                "      \"threatTypes\":      [\"MALWARE\", \"SOCIAL_ENGINEERING\"]," +
                "      \"platformTypes\":    [\"ANY_PLATFORM\"]," +
                "      \"threatEntryTypes\": [\"URL\"]," +
                "      \"threatEntries\": [" +
                "        {\"url\": \"" + args[0] + "\"}," +
                "      ]" +
                "    }" +
                "  }";

        URL url;
        StringBuffer response = new StringBuffer();
        try {
            url = new URL(postURL);
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException("invalid url");
        }

        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(false);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("User-Agent", USER_AGENT);
            conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
            try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) {
                byte[] b = requestBody.getBytes();
                wr.write(b);
                wr.flush();
                wr.close();
            }

            // handle the response
            int status = conn.getResponseCode();
            if (status != 200) {
                throw new IOException("Post failed with error code " + status);
            } else {
                BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
            }

            //Here is your json in string format
            String responseJSON = response.toString();
            Wrapper w = new Wrapper();
            w.responce = responseJSON;
            w.url = args[0];

            return w;
        }

    }

    @Override
    protected void onPostExecute(Wrapper xml) {

        if(xml.responce.length()==0){
            showtoast("safe");
        }
        else{
            showtoast("not safe");
            listener.onTaskCompleted(xml.url);
        }

    }

}
</code>```

For test url also it shows safe.The api panel shows requests are made,I don't know what I'm doing wrong, I'm using the V4 API the most recent version but no matter what URL use, always show it's safe.

答:
It returns empty if URL is not in threat list but you can test your code using these URLs.

https://testsafebrowsing.appspot.com/s/phishing.html
  https://testsafebrowsing.appspot.com/s/malware.html
  https://testsafebrowsing.appspot.com/s/malware_in_iframe.html
  https://testsafebrowsing.appspot.com/s/unwanted.html
  https://testsafebrowsing.appspot.com/s/content.exe
  https://testsafebrowsing.appspot.com/apiv4/IOS/MALWARE/URL/

There are more on this site (From https://testsafebrowsing.appspot.com/  )

Body:
I am using safe browsing api v4 in my android code.I am using Asynctask and request safebrowsing api using httpurlconnection.The response is always empty.

I have tested my connection using test url http://malware.testing.google.test/testing/malware/ also, then too it returns empty.

class Malicious extends AsyncTask<String, Void, Wrapper> {
    private OnTaskCompleted listener;

    public Malicious(OnTaskCompleted listener){
        this.listener=listener;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    protected Wrapper doInBackground(String... args) {
        String postURL = "https://safebrowsing.googleapis.com/v4/threatMatches:find?key=APIKEY";

        String requestBody = "{" +
                "    \"client\": {" +
                "      \"clientId\":      \"twittersentidetector\"," +
                "      \"clientVersion\": \"1.0\"" +
                "    }," +
                "    \"threatInfo\": {" +
                "      \"threatTypes\":      [\"MALWARE\", \"SOCIAL_ENGINEERING\"]," +
                "      \"platformTypes\":    [\"ANY_PLATFORM\"]," +
                "      \"threatEntryTypes\": [\"URL\"]," +
                "      \"threatEntries\": [" +
                "        {\"url\": \"" + args[0] + "\"}," +
                "      ]" +
                "    }" +
                "  }";

        URL url;
        StringBuffer response = new StringBuffer();
        try {
            url = new URL(postURL);
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException("invalid url");
        }

        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(false);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("User-Agent", USER_AGENT);
            conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
            try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) {
                byte[] b = requestBody.getBytes();
                wr.write(b);
                wr.flush();
                wr.close();
            }

            // handle the response
            int status = conn.getResponseCode();
            if (status != 200) {
                throw new IOException("Post failed with error code " + status);
            } else {
                BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
            }

            //Here is your json in string format
            String responseJSON = response.toString();
            Wrapper w = new Wrapper();
            w.responce = responseJSON;
            w.url = args[0];

            return w;
        }

    }

    @Override
    protected void onPostExecute(Wrapper xml) {

        if(xml.responce.length()==0){
            showtoast("safe");
        }
        else{
            showtoast("not safe");
            listener.onTaskCompleted(xml.url);
        }

    }

}

For test url also it shows safe.The api panel shows requests are made,I don't know what I'm doing wrong, I'm using the V4 API the most recent version but no matter what URL use, always show it's safe.


问:
Python MySql Insert not working
I am using python MySQL API to connect to Mysql database from python program. I am facing a problem from few days. I am unable to insert records into the database and dont know whats the reason. Here is the way i connect and insert records into the database.

```<code>db = MySQLdb.connect("localhost","root","padmaramulu","pdfsearch" )
cursor = db.cursor()
#cursor.execute("""CREATE TABLE IF NOT EXISTS documents (docid INT NOT NULL ,PRIMARY KEY(docid),docname CHAR(30)) engine=innodb""")
temp = "hello";number = 2;
cursor.execute( 'insert into documents(docid,docname) values("%d","%s")' % (number,temp) )
db.close()
</code>```

Why is it so?

答: Before closing the connection, you should add db.commit().

Title: Python MySql Insert not working

Body:
I am using python MySQL API to connect to Mysql database from python program. I am facing a problem from few days. I am unable to insert records into the database and dont know whats the reason. Here is the way i connect and insert records into the database.

db = MySQLdb.connect("localhost","root","padmaramulu","pdfsearch" )
cursor = db.cursor()
#cursor.execute("""CREATE TABLE IF NOT EXISTS documents (docid INT NOT NULL ,PRIMARY KEY(docid),docname CHAR(30)) engine=innodb""")
temp = "hello";number = 2;
cursor.execute( 'insert into documents(docid,docname) values("%d","%s")' % (number,temp) )
db.close()

Why is it so?


问:
How to predict future Stock using LSTM Keras
First of all, I must say, I'm a beginner to this AI things. I followed most of the tutorials about stock market predictions and all of them are pretty much same. These tutorials using a data set and split in to two sets. First one is Training set and the 2nd one is Test set. They are using Closing price of the stocks to train and make a model. From that model, they insert test data set which contain the closing price and showing two graphs. Then they say the actual and the predicted graphs are pretty much same.
The github repo of the tutorial. -
https://github.com/surajr/Stock-Predictor-using-LSTM/blob/master/Stock-Predictor-using-LSTM.ipynb
This is my question,
1. Why all those tutorials are putting closing price in the testing set also? They are only suppose to insert dates right? Because we are predicting the closing price. This is confusing. Please explain me.
2. No one is telling me how to predict next 7 days values. So if we have a model, how to get next 7 days closing value?

Please help me to clarify this. Thanks a lot.

答:
Why all those tutorials are putting closing price in the testing set also?
-> It is easy to understand that closing price is a kind of input variable which is required to calculate stock price.

As I see the code, it seems predict stock price with 22days history

X_train (1173, 22, 3)
y_train (1173,)
X_test (130, 22, 3)
y_test (130,)

I think you should re-train with (~~~, 7, 3) to predict price of 7 days after today.


问:
Throw same error format as `class-validator` in NestJS
Let's have this controller in NestJS project:

```<code>  @Post('resetpassword')
  @HttpCode(200)
  async requestPasswordReset(
    @Body() body: RequestPasswordResetDTO,
  ): Promise<boolean> {
    try {
      return await this.authService.requestPasswordReset(body);
    } catch (e) {
      if (e instanceof EntityNotFoundError) {
        // Throw same exception format as class-validator throwing (ValidationError)
      } else throw e;
    }
  }
</code>```

Dto definition:

```<code>export class RequestPasswordResetDTO {
  @IsNotEmpty()
  @IsEmail()
  public email!: string;
}
</code>```

I want to throw error in ValidationError format (property, value, constraints, etc) when this.authService.requestPasswordReset(body); throws an EntityNotFoundError exception.

How I can create this error manually? Those errors are just thrown when DTO validation by class-validator fails. And those can be just static validations, not async database validations.

So the final API response format should be for example:

```<code>{
    "statusCode": 400,
    "error": "Bad Request",
    "message": [
        {
            "target": {
                "email": "not@existing.email"
            },
            "value": "not@existing.email",
            "property": "email",
            "children": [],
            "constraints": {
                "exists": "email address does not exists"
            }
        }
    ]
}
</code>```

I need it to have consistent error handling :)

答:
You could use an Exception Filter to create your customized response to that exception
First we define the Exception Filter:

import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { Request, Response } from 'express';
// import { EntityNotFoundError } from 'wherever';

@Catch(EntityNotFoundError)
export class EntityNotFoundExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    const status = exception.getStatus();

    response
      .status(status)
      .json({
        "statusCode": 400,
        "error": "Bad Request",
        "message": [
          {
            "target": {},
            "property": "email",
            "children": [],
            "constraints": {
              "isEmail": "email must be an email"
            }
          },
          // other field exceptions
        ]
      });
  }
}
```

<p>Then back in your controller, you use the filter:</p>

<pre class="lang-js prettyprint-override"><code>  // ...
  import { EntityNotFoundExceptionFilter } from 'its module';
  // ...
  @Post('resetpassword')
  @HttpCode(200)
  @UseFilters(EntityNotFoundExceptionFilter)
  async requestPasswordReset(
    @Body() body: RequestPasswordResetDTO
  ): Promise<boolean> {
      return await this.authService.requestPasswordReset(body);
  }
</code>```

This should work just fine.

Body:
Let's have this controller in NestJS project:

  @Post('resetpassword')
  @HttpCode(200)
  async requestPasswordReset(
    @Body() body: RequestPasswordResetDTO,
  ): Promise<boolean> {
    try {
      return await this.authService.requestPasswordReset(body);
    } catch (e) {
      if (e instanceof EntityNotFoundError) {
        // Throw same exception format as class-validator throwing (ValidationError)
      } else throw e;
    }
  }

Dto definition:

export class RequestPasswordResetDTO {
  @IsNotEmpty()
  @IsEmail()
  public email!: string;
}

I want to throw error in ValidationError format (property, value, constraints, etc) when this.authService.requestPasswordReset(body); throws an EntityNotFoundError exception.

How I can create this error manually? Those errors are just thrown when DTO validation by class-validator fails. And those can be just static validations, not async database validations.

So the final API response format should be for example:

{
    "statusCode": 400,
    "error": "Bad Request",
    "message": [
        {
            "target": {
                "email": "not@existing.email"
            },
            "value": "not@existing.email",
            "property": "email",
            "children": [],
            "constraints": {
                "exists": "email address does not exists"
            }
        }
    ]
}

I need it to have consistent error handling :)

Body:
You could use an Exception Filter to create your customized response to that exception
First we define the Exception Filter:

import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { Request, Response } from 'express';
// import { EntityNotFoundError } from 'wherever';

@Catch(EntityNotFoundError)
export class EntityNotFoundExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    const status = exception.getStatus();

    response
      .status(status)
      .json({
        "statusCode": 400,
        "error": "Bad Request",
        "message": [
          {
            "target": {},
            "property": "email",
            "children": [],
            "constraints": {
              "isEmail": "email must be an email"
            }
          },
          // other field exceptions
        ]
      });
  }
}

Then back in your controller, you use the filter:

  // ...
  import { EntityNotFoundExceptionFilter } from 'its module';
  // ...
  @Post('resetpassword')
  @HttpCode(200)
  @UseFilters(EntityNotFoundExceptionFilter)
  async requestPasswordReset(
    @Body() body: RequestPasswordResetDTO
  ): Promise<boolean> {
      return await this.authService.requestPasswordReset(body);
  }

This should work just fine.


问:
Having an issue reading a string from a file of names in C
I am reading through a text file that has a line on each name. I need to generate a random number from 0-99 to determine the index of the name to choose. When I use the method fscanf() and then I try to display the string that I read, a blank string is outputted. I have tested it and I am entering the if statement to assign the string to the variable, there just seems to be an issue with assigning the name. </p>

```<code>int indexOfName = rand() % 100;
        printf("%d\n", indexOfName);

        FILE *fileOfNames;
        char str[30];
        char *filename = "theFilePath";

        fileOfNames = fopen(filename, "r");
        rewind(fileOfNames);
        if (fileOfNames == NULL)
        {
            printf("Could not open file %s", filename);
            return 1;
        }
        int i = 0;
        while (fgets(str, 30, fileOfNames) != NULL)
        {
            if (i == indexOfName)
            {
                fscanf(fileOfNames, "%s", str);
            }
            i++;
        }
        printf("%s\n", str);
        fclose(fileOfNames);
        return 0;
</code>```

答:
You need to break after if (i == indexOfName). Otherwise, you will just overwrite str until you reach the end of the file.

You probably don't even want fscanf in the if statement as while (fgets(str, 30, fileOfNames) != NULL) writes the line to str allready.

Body:
I am reading through a text file that has a line on each name. I need to generate a random number from 0-99 to determine the index of the name to choose. When I use the method fscanf() and then I try to display the string that I read, a blank string is outputted. I have tested it and I am entering the if statement to assign the string to the variable, there just seems to be an issue with assigning the name.

int indexOfName = rand() % 100;
        printf("%d\n", indexOfName);

        FILE *fileOfNames;
        char str[30];
        char *filename = "theFilePath";

        fileOfNames = fopen(filename, "r");
        rewind(fileOfNames);
        if (fileOfNames == NULL)
        {
            printf("Could not open file %s", filename);
            return 1;
        }
        int i = 0;
        while (fgets(str, 30, fileOfNames) != NULL)
        {
            if (i == indexOfName)
            {
                fscanf(fileOfNames, "%s", str);
            }
            i++;
        }
        printf("%s\n", str);
        fclose(fileOfNames);
        return 0;


问:
Typescript - Getting the type of properties in my interface to avoid using any
I have an interface like:

```<code>interface OktaUser {
    someId: number;
    email: string;
    email_verified: boolean;
}
</code>```

I then have some method to get these properties out as requested:

```<code>async getOktaUserProperty(key: keyof OktaUser): Promise<any> {
        // Do some stuff

        return oktaUser[key];
}
</code>```

Is there any way I can avoid using any in the return, I could manually do Promise<number | string | boolean> but makes it a little cumbersome to maintain.

Any ideas?

Thanks.

答:
Try this playground link. It uses several features of TypeScript including generics and index types.</p>

```<code>interface OktaUser {
    someId: number;
    email: string;
    email_verified: boolean;
}

function getOktaUserProperty<TKey extends keyof OktaUser>(key: TKey): OktaUser[TKey] {
    const x: OktaUser = {
        someId: 10,
        email: 'foo',
        email_verified: true,
    };

    return x[key]
}

const y = getOktaUserProperty('email'); // string
const z = getOktaUserProperty('someId'); // number
</code>```

Body:
I have an interface like:

interface OktaUser {
    someId: number;
    email: string;
    email_verified: boolean;
}

I then have some method to get these properties out as requested:

async getOktaUserProperty(key: keyof OktaUser): Promise<any> {
        // Do some stuff

        return oktaUser[key];
}

Is there any way I can avoid using any in the return, I could manually do Promise<number | string | boolean> but makes it a little cumbersome to maintain.

Any ideas?

Thanks.

Body:
Try this playground link. It uses several features of TypeScript including generics and index types.

interface OktaUser {
    someId: number;
    email: string;
    email_verified: boolean;
}

function getOktaUserProperty<TKey extends keyof OktaUser>(key: TKey): OktaUser[TKey] {
    const x: OktaUser = {
        someId: 10,
        email: 'foo',
        email_verified: true,
    };

    return x[key]
}

const y = getOktaUserProperty('email'); // string
const z = getOktaUserProperty('someId'); // number


答:
Why all those tutorials are putting closing price in the testing set also?

The ultimate goal is to predict the movement (growth), Which is closing minus- opening price. The ultimate model is the model that calculates the growth in test data set very close to what the actual growth is. The growth is the main problem that the model is trying solve and is the point of reference when you calculate the accuracy of the trained model.

They are only suppose to insert dates right? Because we are predicting the closing price

The model is predicting the growth based on given factors. For a company, you have many factors that are quantified, per day. I suspect the tutorial you did uses a testing set extracted for one particular day and different stocks. Like extracting all parameters for all companies but only in 10th of January and then check how accurate the trained model is. The training set on the other hand contains the stock for more than one day most of the time.

No one is telling me how to predict next 7 days values. So if we have a model, how to get next 7 days closing value?

To predict the stock price relatively accurate, you need a well-trained model. To do this you need to train your model based on many many factors. Same model cannot predict stock in different countries. One model might be suitable to predict technology stocks (AAPL) but not other fields.

Overall, this is a complicated subject. Financial advisers pay a massive amount of money just to use reliable models. Most of them use multiple models based on their client's portfolio. These tutorials introduce the subject to you and teach you the main concept. IMHO, I would say the next step would be learning and then competing in Kaggle.

Title: How to predict future Stock using LSTM Keras

Body:
First of all, I must say, I'm a beginner to this AI things. I followed most of the tutorials about stock market predictions and all of them are pretty much same. These tutorials using a data set and split in to two sets. First one is Training set and the 2nd one is Test set. They are using Closing price of the stocks to train and make a model. From that model, they insert test data set which contain the closing price and showing two graphs. Then they say the actual and the predicted graphs are pretty much same.
The github repo of the tutorial. -
https://github.com/surajr/Stock-Predictor-using-LSTM/blob/master/Stock-Predictor-using-LSTM.ipynb
This is my question,
1. Why all those tutorials are putting closing price in the testing set also? They are only suppose to insert dates right? Because we are predicting the closing price. This is confusing. Please explain me.
2. No one is telling me how to predict next 7 days values. So if we have a model, how to get next 7 days closing value?

Please help me to clarify this. Thanks a lot.


问:
XML Structure in SQL Server
I have the following code which works fine and returns the expected results:

```<code>DECLARE @xmlList xml
SET @xmlList = '<Tx><T>1</T><T>2</T><T>3</T></Tx>'

SELECT
        X.Y.value('.', 'varchar(10)') AS [ID], 'OK' AS [Status]
    FROM @xmlList.nodes('/Tx/T') X(Y)
</code>```

However, it also accept when I provide it with the following structure and returns the ssame results:

```<code>SET @xmlList = '<Tx><T>1</T></Tx><Tx><T>2</T><T>3</T></Tx>'
</code>```

Notice how I don't have a root element.

My question is, what do I need to change to make the code accept the first structure as valid and reject the other?

Thanks,

TheBlueSky

答:
If you are only want to query one Tx node (the first) you can do like this

```<code>SELECT
  X.Y.value('.', 'varchar(10)') AS [ID], 'OK' AS [Status]
FROM @xmlList.nodes('/Tx[1]/T') X(Y)
</code>```

You could also check the number of root nodes and call raiserror if you have more than one root.

```<code>select @xmlList.query('count(/Tx)').value('.', 'int')
</code>```

The technique used before the xml datatype only accepted one root node. sp_xml_preparedocument will raise and exception if there are more than one root.

```<code>declare @idoc int
exec sp_xml_preparedocument @idoc out, @xmlList
exec sp_xml_removedocument @idoc
</code>```

Title: XML Structure in SQL Server

Body:
I have the following code which works fine and returns the expected results:

DECLARE @xmlList xml
SET @xmlList = '<Tx><T>1</T><T>2</T><T>3</T></Tx>'

SELECT
        X.Y.value('.', 'varchar(10)') AS [ID], 'OK' AS [Status]
    FROM @xmlList.nodes('/Tx/T') X(Y)

However, it also accept when I provide it with the following structure and returns the ssame results:

SET @xmlList = '<Tx><T>1</T></Tx><Tx><T>2</T><T>3</T></Tx>'

Notice how I don't have a root element.

My question is, what do I need to change to make the code accept the first structure as valid and reject the other?

Thanks,

TheBlueSky

Body:
If you are only want to query one Tx node (the first) you can do like this

SELECT
  X.Y.value('.', 'varchar(10)') AS [ID], 'OK' AS [Status]
FROM @xmlList.nodes('/Tx[1]/T') X(Y)

You could also check the number of root nodes and call raiserror if you have more than one root.

select @xmlList.query('count(/Tx)').value('.', 'int')

The technique used before the xml datatype only accepted one root node. sp_xml_preparedocument will raise and exception if there are more than one root.

declare @idoc int
exec sp_xml_preparedocument @idoc out, @xmlList
exec sp_xml_removedocument @idoc


问:
Scraping a website that has certain problems
I want to scrape this website and scrape all articles by this author, with Python(response or Selenium libraries) and put them in PDF file.

However, when I click on the button "Show More" that is in the bottom, after 8 times, it doesn't anymore display more articles, hence I can't access them all(idea was to automate selenium, to click on it until all articles are showed, and then scrape them all). Is there a workaround? Alternative ways I can access all articles chronologically and scrape them?

My idea was to somehow analyze if the links come from alternative source, but I'm clueless. However, I scraped successfully those articles that are displayed.

Thanks in advance!

答:
Use findElements and search for
...
 which will give you a list of all titles. Each time when you click the Show more the size of the list will get extended by 10 or so. So the idea is to simply click the button untill the size of the list does not change. Use a while loop. Something like:

```<code>List<WebElements> oldList = Driver.findElements(by.cssSelector("h2.css-
    1j9dxys.e1xfvim30"));

List<WebElements> newList = new ArrayList<>();

WebElement button = Driver.findElement(by.xpath("//button[text()='Show More']"));

while(newList.size!=oldList.size){
    button.click();
    newList = List<WebElements> newList = Driver.findElements(by.cssSelector("h2.css-
    1j9dxys.e1xfvim30));
}
</code>```

I might have some mistakes in the code but the idea is there. Good luck!

Body:
Use findElements and search for <h2 class="css-1j9dxys e1xfvim30">...</h2> which will give you a list of all titles. Each time when you click the Show more the size of the list will get extended by 10 or so. So the idea is to simply click the button untill the size of the list does not change. Use a while loop. Something like:

List<WebElements> oldList = Driver.findElements(by.cssSelector("h2.css-
    1j9dxys.e1xfvim30"));

List<WebElements> newList = new ArrayList<>();

WebElement button = Driver.findElement(by.xpath("//button[text()='Show More']"));

while(newList.size!=oldList.size){
    button.click();
    newList = List<WebElements> newList = Driver.findElements(by.cssSelector("h2.css-
    1j9dxys.e1xfvim30));
}

I might have some mistakes in the code but the idea is there. Good luck!


问:
How do you run Cleanmgr.exe remotely?
I'm having some trouble getting Clean Manager on Windows 10 to run remotely. I've seen a few different things were you can edit the registry and modify the /sageset or /sagerun to be specific things then run it remotely, but it seems no matter what I do the CleanMgr runs locally on my machine rather than running remotely.

I believe this is the closest I've gotten to get it to run remotely... It seems to still just run locally on my machine though.

Any ideas?

( All variables are set before this portion of the script, this is just a small portion of what's going on that I'm stuck on )

```<code>## Starts cleanmgr.exe
Function Start-CleanMGR {
    Write-Host "Please provide your A-Account details to continue with this cleanup."
    $creds = Get-Credential
    Enter-PSSession -ComputerName $computername -Credential $creds
    try {
        $cleanmgr = Start-Process -Credential $creds -FilePath "C:\Windows\System32\cleanmgr.exe" -ArgumentList '/verylowdisk' -Wait -Verbose
        if ($cleanmgr) {
            Write-Host "Clean Manager ran successfully!                                                                   " -NoNewline -ForegroundColor Green
            Write-Host "[DONE]" -ForegroundColor Green -BackgroundColor Black
        }
    }
    catch [System.Exception] {
        Write-host "Cleanmgr is not installed! To use this portion of the script you must install the following windows features:" -NoNewline -ForegroundColor DarkGray
        Write-host "[ERROR]" -ForegroundColor Red -BackgroundColor Black
    }
} Start-CleanMGR
</code>```

答:
PowerShell always runs in the user context of the user who started the session. This is by design.

You can not run a GUI based application remotely using PowerShell. It is a Windows security boundary.

To run GUI apps, someone must be logged on, and you cannot use PowerShell to run code as the logged-on user.

You are also prompting for info, so, someone must be logged on.

If you are expecting a user to prived info, then you need to:

Create the script

Deploy the script to the user's machine or a files share from wich it
can be ran

Tell the user how to do it or create a batch file they would double
click to run the PowerShell script

Or

Set the script to run as a scheduled task at log on or at some point during the day, as the user credentials.

Variables have the scope and you cannot use local variables in a remote context unless they are scoped for that.

About Remote Variables

Using local variables

You can use local variables in remote commands, but the variable must
  be defined in the local session.

Beginning in PowerShell 3.0, you can use the Using scope modifier to
  identify a local variable in a remote command.

The syntax of Using is as follows:

```<code>$Using:<VariableName>
</code>```

Still, the remote variable is not something you will do in your use case since you cannot do what you are after natively with PowerShell. You'll need a 3rdP tool like MS SysInternals PSExec to run code remotely as the logged-on user.

Using PsExec

Usage: psexec [\computer[,computer2[,...] | @file]][-u user [-p
  psswd][-n s][-r servicename][-h][-l][-s|-e][-x][-i [session]][-c
  executable [-f|-v]][-w directory][-d][-][-a n,n,...] cmd
  [arguments]

-i    Run the program so that it interacts with the desktop of the specified session on the remote system. If no session is specified the
  process runs in the console session.

-u    Specifies optional user name for login to remote computer.

Title: How do you run Cleanmgr.exe remotely?

Body:
I'm having some trouble getting Clean Manager on Windows 10 to run remotely. I've seen a few different things were you can edit the registry and modify the /sageset or /sagerun to be specific things then run it remotely, but it seems no matter what I do the CleanMgr runs locally on my machine rather than running remotely.

I believe this is the closest I've gotten to get it to run remotely... It seems to still just run locally on my machine though.

Any ideas?

( All variables are set before this portion of the script, this is just a small portion of what's going on that I'm stuck on )

## Starts cleanmgr.exe
Function Start-CleanMGR {
    Write-Host "Please provide your A-Account details to continue with this cleanup."
    $creds = Get-Credential
    Enter-PSSession -ComputerName $computername -Credential $creds
    try {
        $cleanmgr = Start-Process -Credential $creds -FilePath "C:\Windows\System32\cleanmgr.exe" -ArgumentList '/verylowdisk' -Wait -Verbose
        if ($cleanmgr) {
            Write-Host "Clean Manager ran successfully!                                                                   " -NoNewline -ForegroundColor Green
            Write-Host "[DONE]" -ForegroundColor Green -BackgroundColor Black
        }
    }
    catch [System.Exception] {
        Write-host "Cleanmgr is not installed! To use this portion of the script you must install the following windows features:" -NoNewline -ForegroundColor DarkGray
        Write-host "[ERROR]" -ForegroundColor Red -BackgroundColor Black
    }
} Start-CleanMGR

Body:
PowerShell always runs in the user context of the user who started the session. This is by design.

You can not run a GUI based application remotely using PowerShell. It is a Windows security boundary.

To run GUI apps, someone must be logged on, and you cannot use PowerShell to run code as the logged-on user.

You are also prompting for info, so, someone must be logged on.

If you are expecting a user to prived info, then you need to:

Create the script

Deploy the script to the user's machine or a files share from wich it
can be ran

Tell the user how to do it or create a batch file they would double
click to run the PowerShell script

Or

Set the script to run as a scheduled task at log on or at some point during the day, as the user credentials.

Variables have the scope and you cannot use local variables in a remote context unless they are scoped for that.

About Remote Variables

Using local variables

You can use local variables in remote commands, but the variable must
  be defined in the local session.

Beginning in PowerShell 3.0, you can use the Using scope modifier to
  identify a local variable in a remote command.

The syntax of Using is as follows:

$Using:<VariableName>

Still, the remote variable is not something you will do in your use case since you cannot do what you are after natively with PowerShell. You'll need a 3rdP tool like MS SysInternals PSExec to run code remotely as the logged-on user.

Using PsExec

Usage: psexec [\computer[,computer2[,...] | @file]][-u user [-p
  psswd][-n s][-r servicename][-h][-l][-s|-e][-x][-i [session]][-c
  executable [-f|-v]][-w directory][-d][-][-a n,n,...] cmd
  [arguments]

-i    Run the program so that it interacts with the desktop of the specified session on the remote system. If no session is specified the
  process runs in the console session.

-u    Specifies optional user name for login to remote computer.


问:
Retrofit2 with Kotlin
I want to consume an API with this result:

```<code>{"result":true,"status":"success"}
</code>```

It seems the problem is in Kotlin. Here's my code:

```<code>class MainActivity : AppCompatActivity() {
private var response:Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {

    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    getRetrofit()

    btnLogin.setOnClickListener {

        getResponse()
        Toast.makeText(this,response.toString(),Toast.LENGTH_LONG).show()
    }
}

private fun getRetrofit(): Retrofit {
    return Retrofit.Builder()
        .baseUrl("http://192.168.43.243:2001/")
        .addConverterFactory(GsonConverterFactory.create())
        .build()
}

private fun getResponse() {
    doAsync {
        val call = getRetrofit().create(APIService::class.java).getResponse().execute()
        val res = call.body() as APIResponse
        uiThread {
            if(res.status == "success") {
                response = res.response

            }else{
                //showErrorDialog()
            }
        }
    }
}
</code>```

My variable 'response' always returns 'false' and I want to consume the API value. so 'response' should have a 'true' value.
Do you have any suggestion?

Thank you so much!

答:
Your response schema is

```<code>{
  "result":true,
  "status":"success"
}
</code>```

So, in your response schema, there is only result and status. But in your getResponse(), you assign boolean variable response with res.response. You are using response instead of result.

```<code>  if(res.status == "success") {
     response = res.response // error here
  }else{
      //showErrorDialog()
  }
</code>```

You initialize your response variable with false, your variable response always return false.
So you must change the code as follow

```<code>if(res.status == "success") {
     response = res.result // solved here
  }else{
      //showErrorDialog()
  }
</code>```

If my solution is something wrong, please free to know.

Title: Retrofit2 with Kotlin

Body:
I want to consume an API with this result:

{"result":true,"status":"success"}

It seems the problem is in Kotlin. Here's my code:

class MainActivity : AppCompatActivity() {
private var response:Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {

    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    getRetrofit()

    btnLogin.setOnClickListener {

        getResponse()
        Toast.makeText(this,response.toString(),Toast.LENGTH_LONG).show()
    }
}

private fun getRetrofit(): Retrofit {
    return Retrofit.Builder()
        .baseUrl("http://192.168.43.243:2001/")
        .addConverterFactory(GsonConverterFactory.create())
        .build()
}

private fun getResponse() {
    doAsync {
        val call = getRetrofit().create(APIService::class.java).getResponse().execute()
        val res = call.body() as APIResponse
        uiThread {
            if(res.status == "success") {
                response = res.response

            }else{
                //showErrorDialog()
            }
        }
    }
}

My variable 'response' always returns 'false' and I want to consume the API value. so 'response' should have a 'true' value.
Do you have any suggestion?

Thank you so much!

Body:
Your response schema is

{
  "result":true,
  "status":"success"
}

So, in your response schema, there is only result and status. But in your getResponse(), you assign boolean variable response with res.response. You are using response instead of result.

  if(res.status == "success") {
     response = res.response // error here
  }else{
      //showErrorDialog()
  }

You initialize your response variable with false, your variable response always return false.
So you must change the code as follow

if(res.status == "success") {
     response = res.result // solved here
  }else{
      //showErrorDialog()
  }

If my solution is something wrong, please free to know.


问:
Odoo 11 user cannot create new contact despite extra permissions set
I'm running Odoo 11.0 CE 20180126.

Normal users get an error when trying to create a new partner under contacts, telling them that they need to be admin.
The extra permissions to create contacts are set, the buttons appears and the form can be called. But the below error message immediately pops up.

Weirdly enough users can edit existing contacts but not create new ones.

Any help is greatly appreciated.

答: The issue was an interaction with another module which restricted the access. Solution was to remove the unused module.</p>


问:
Dimension in particle swarm optimization algorithm
In particle swarm optimization algorithm, what is the dimension exactly mean. Is it the number of particles (population size) in the search space? or it is the coordinates of each particle?</p>

答:
By xij, it is meant that i th particle is taken from j dimensional search space. If number of particles is limited by n, number of dimensions of the search space is restricted by m, then i is less than equal to n, j is less than equal to m.  So dimension means the coordinates of the position of the particle. Number of velocity components will be the same as the number of coordinates of the particle. In mathematical problems like

Minimize x2 – 5x + 20,   always j = 1


问:
Ckeditor drop down issue on Bootstrap modal (Open and close immediately on click)
I have opened ckeditor inside bootstrap modal but format and size drop down are not working properly. When I click on size or format drop down it opens and close immediately, I read that it is a bug in ckeditor for bootstrap modal. I found solution online for it but that is not working.

solution I found online and not working :-

```<code>    $.fn.modal.Constructor.prototype.enforceFocus = function() {
    modal_this = this
    $(document).on('focusin.modal', function(e) {
        if (modal_this.$element[0] !== e.target && !modal_this.$element.has(e.target).length &&
            !$(e.target.parentNode).hasClass('cke_dialog_ui_input_select') &&
            !$(e.target.parentNode).hasClass('cke_dialog_ui_input_text')) {
            modal_this.$element.focus()
        }
    })
  };
</code>```

JS from where I call jsp and where ck editor:

```<code>  $scope.emailMsgSetting = function(msgId, headerName) {
  $ocLazyLoad.load({
      name: 'emailSettingsModule',
      files: ['/doc/jsp/portal/viewMessageSettings.js']
  }).then(function() {
      var url = makeURL("/doc/jsp/portal/viewMessageSettings.jsp?");
      $scope.dataURL = url;
  }, function(e) {
      console.log(e);
  });
}
</code>```

JSP where I have implemented ck editor

```<code><div class="col-sm-11 nopadright" ng-if="showckeditor">
   <textarea ng-model="$parent.msgTypeBody" ck-editor insert-tag="strTagName" height="ckEditorheight" extra-plugins= "strTagName"></textarea>
  </div>
</code>```

Thanks..

答:
I'm using BS4 and ckEditor and ran into the same issue in IE (but not Edge, Chrome, FF, etc.) -- the drop down flashes and then disappears.  It seems that the modal was hijacking the event.    I tried the solution of the OP but it didn't work for me.  Here's what did work --  after loading the BS script and the CK editor script, show the dialog in Bootstrap (this is critical --you have to have the dialog created or created/shown).  Then --

```<code>$.fn.modal.Constructor.prototype._enforceFocus = function () {
        modal_this = this
        $(document).on('focusin.bs.modal', function (e) {

            if (e.target.className == "cke_panel_frame") {
                $(e.target).focus();
            }
        })
    };
</code>```

I'm using BS4, so it's "focusin.bs.modal", not "focusin.modal".  The drop down lists are all in the ck_panel_frame.  So, when that frame has focus, I set the focus right back on the frame so that it doesn't get trapped by the modal itself.

Body:
I have opened ckeditor inside bootstrap modal but format and size drop down are not working properly. When I click on size or format drop down it opens and close immediately, I read that it is a bug in ckeditor for bootstrap modal. I found solution online for it but that is not working.

solution I found online and not working :-

    $.fn.modal.Constructor.prototype.enforceFocus = function() {
    modal_this = this
    $(document).on('focusin.modal', function(e) {
        if (modal_this.$element[0] !== e.target && !modal_this.$element.has(e.target).length &&
            !$(e.target.parentNode).hasClass('cke_dialog_ui_input_select') &&
            !$(e.target.parentNode).hasClass('cke_dialog_ui_input_text')) {
            modal_this.$element.focus()
        }
    })
  };

JS from where I call jsp and where ck editor:

  $scope.emailMsgSetting = function(msgId, headerName) {
  $ocLazyLoad.load({
      name: 'emailSettingsModule',
      files: ['/doc/jsp/portal/viewMessageSettings.js']
  }).then(function() {
      var url = makeURL("/doc/jsp/portal/viewMessageSettings.jsp?");
      $scope.dataURL = url;
  }, function(e) {
      console.log(e);
  });
}

JSP where I have implemented ck editor

   <textarea ng-model="$parent.msgTypeBody" ck-editor insert-tag="strTagName" height="ckEditorheight" extra-plugins= "strTagName"></textarea>

Thanks..

Body:
I'm using BS4 and ckEditor and ran into the same issue in IE (but not Edge, Chrome, FF, etc.) -- the drop down flashes and then disappears.  It seems that the modal was hijacking the event.    I tried the solution of the OP but it didn't work for me.  Here's what did work --  after loading the BS script and the CK editor script, show the dialog in Bootstrap (this is critical --you have to have the dialog created or created/shown).  Then --

$.fn.modal.Constructor.prototype._enforceFocus = function () {
        modal_this = this
        $(document).on('focusin.bs.modal', function (e) {

            if (e.target.className == "cke_panel_frame") {
                $(e.target).focus();
            }
        })
    };

I'm using BS4, so it's "focusin.bs.modal", not "focusin.modal".  The drop down lists are all in the ck_panel_frame.  So, when that frame has focus, I set the focus right back on the frame so that it doesn't get trapped by the modal itself.