问:
Spring MVC: The request sent by the client was syntactically incorrect when creating a new entity record
Good afternoon,

I am newbie to Spring MVC. I'm stuck with the following error while running my project "The request sent by the client was syntactically incorrect."

My project has two entities, Team and Country which have a ManyToOne relationship. Both these entities map tables created in mysql database.

I started the project with only the Team entity, and sucessfuly created my classes (DAO, controller, services, etc) and jsp to create new teams.

Now, I created the class Country to relate both entities and I added a dropdown list in the "add-team-form.jsp" to select the country of the new team. This page is correctly displayed (all countries appear in the dropdown list), however, when I click "submit" to create the new team, I get the error "The request sent by the client was syntactically incorrect."

Can you please help me to identify my error? I'm guessing it's in the "add-team-form.jsp".

1 - Entity Team:

```<code>@Entity
@Table(name="teams")
public class Team implements Serializable{

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

@Column(name = "name", length = 40, nullable = false)
private String name;

@Column(name = "rating", length = 6, nullable = false)
private Integer rating;

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "id_country", nullable = false)
private Country country;

public Integer getId() {
    return id;
}
public void setId(Integer id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public Integer getRating() {
    return rating;
}
public void setRating(Integer rating) {
    this.rating = rating;
}
public Country getCountry() {
    return country;
}
public void setCountry(Country country) {
    this.country = country;
}
}
</code>```

2 - Entity Country:

```<code>@Entity
@Table(name = "countries")
public class Country implements Serializable{

@Id
@Column(name= "id_country", length = 6)
private String idCountry;

@Column(name = "name", length = 255, nullable = false)
private String name;

@OneToMany(fetch = FetchType.LAZY, mappedBy = "country")
private List<Team> teams;

public String getIdCountry() {
    return idCountry;
}

public void setIdCountry(String idCountry) {
    this.idCountry = idCountry;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}
}
</code>```

My Team DAO

```<code>@Repository
public class TeamDAOImpl implements TeamDAO {

@Autowired
private SessionFactory sessionFactory;

private Session getCurrentSession() {
    return sessionFactory.getCurrentSession();
}

@Override
public void addTeam(Team team) {

    getCurrentSession().save(team);
}
}
</code>```

My Team Service

```<code>@Service
@Transactional
public class TeamServiceImpl implements TeamService {

@Autowired
private TeamDAO teamDAO;

public void addTeam(Team team) {
    teamDAO.addTeam(team);
}
</code>```

My Team Controller

```<code>@Controller
@RequestMapping(value="/team")
public class TeamController {

@Autowired
private TeamService teamService;

@Autowired
private FilterService filterService;

@RequestMapping(value="/add", method=RequestMethod.GET)
public ModelAndView addTeamPage() {
    ModelAndView modelAndView = new ModelAndView("add-team-form");
    modelAndView.addObject("team", new Team());

    return modelAndView;
}

@RequestMapping(value="/add", method=RequestMethod.POST)
public ModelAndView addingTeam(@ModelAttribute Team team) {

    ModelAndView modelAndView = new ModelAndView("home");

    teamService.addTeam(team);

    String message = "Team was successfully added.";
    modelAndView.addObject("message", message);

    return modelAndView;
}

@ModelAttribute("countryList")
public Map<String, String> getCountryList(){

    Map<String, String> countryList = filterService.getCountries();
    return countryList;
   }

...
}
</code>```

My "add-team-form.jsp"

```<code><%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<?xml version="1.0" encoding="ISO-8859-1" ?>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Add team page</title>
</head>
<body>
    <h1>Add team page</h1>

<form:form method="POST"
        modelAttribute="team"
        action="${pageContext.request.contextPath}/team/add.html">
<table>
    <tbody>
    <tr>
        <td>Name:</td>
        <td><form:input path="name" /></td>
    </tr>
    <tr>
        <td>Rating:</td>
        <td><form:input path="rating" /></td>
    </tr>
    <tr>
    <td><label>Country</label></td>
    <td>
        <form:select path="country.idCountry">
            <form:options items="${countryList}" />
        </form:select>
    </td>
    <tr>
        <td><input type="submit" value="Add" /></td>
        <td></td>
    </tr>

</tbody>
</table>
</form:form>

</body>
</html>
</code>```

There is no error showing in the console of eclipse, but here is the error im receiving from the browser:

```<code>HTTP Status 400 -

type Status report

message

description The request sent by the client was syntactically incorrect.
Apache Tomcat/7.0.47
</code>```

答: The error you are receiving generally happens if a parameter is missing or is in a different format and cannot be converted to the expected type.Check the values being passed to the Team object.You can either log the request and response or set the log level to "DEBUG",this will display the exact error in logs.</p>

Body:
Good afternoon,

I am newbie to Spring MVC. I'm stuck with the following error while running my project "The request sent by the client was syntactically incorrect."

My project has two entities, Team and Country which have a ManyToOne relationship. Both these entities map tables created in mysql database.

I started the project with only the Team entity, and sucessfuly created my classes (DAO, controller, services, etc) and jsp to create new teams.

Now, I created the class Country to relate both entities and I added a dropdown list in the "add-team-form.jsp" to select the country of the new team. This page is correctly displayed (all countries appear in the dropdown list), however, when I click "submit" to create the new team, I get the error "The request sent by the client was syntactically incorrect."

Can you please help me to identify my error? I'm guessing it's in the "add-team-form.jsp".

1 - Entity Team:

@Entity
@Table(name="teams")
public class Team implements Serializable{

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

@Column(name = "name", length = 40, nullable = false)
private String name;

@Column(name = "rating", length = 6, nullable = false)
private Integer rating;

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "id_country", nullable = false)
private Country country;

public Integer getId() {
    return id;
}
public void setId(Integer id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public Integer getRating() {
    return rating;
}
public void setRating(Integer rating) {
    this.rating = rating;
}
public Country getCountry() {
    return country;
}
public void setCountry(Country country) {
    this.country = country;
}
}

2 - Entity Country:

@Entity
@Table(name = "countries")
public class Country implements Serializable{

@Id
@Column(name= "id_country", length = 6)
private String idCountry;

@Column(name = "name", length = 255, nullable = false)
private String name;

@OneToMany(fetch = FetchType.LAZY, mappedBy = "country")
private List<Team> teams;

public String getIdCountry() {
    return idCountry;
}

public void setIdCountry(String idCountry) {
    this.idCountry = idCountry;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}
}

My Team DAO

@Repository
public class TeamDAOImpl implements TeamDAO {

@Autowired
private SessionFactory sessionFactory;

private Session getCurrentSession() {
    return sessionFactory.getCurrentSession();
}

@Override
public void addTeam(Team team) {

    getCurrentSession().save(team);
}
}

My Team Service

@Service
@Transactional
public class TeamServiceImpl implements TeamService {

@Autowired
private TeamDAO teamDAO;

public void addTeam(Team team) {
    teamDAO.addTeam(team);
}

My Team Controller

@Controller
@RequestMapping(value="/team")
public class TeamController {

@Autowired
private TeamService teamService;

@Autowired
private FilterService filterService;

@RequestMapping(value="/add", method=RequestMethod.GET)
public ModelAndView addTeamPage() {
    ModelAndView modelAndView = new ModelAndView("add-team-form");
    modelAndView.addObject("team", new Team());

    return modelAndView;
}

@RequestMapping(value="/add", method=RequestMethod.POST)
public ModelAndView addingTeam(@ModelAttribute Team team) {

    ModelAndView modelAndView = new ModelAndView("home");

    teamService.addTeam(team);

    String message = "Team was successfully added.";
    modelAndView.addObject("message", message);

    return modelAndView;
}

@ModelAttribute("countryList")
public Map<String, String> getCountryList(){

    Map<String, String> countryList = filterService.getCountries();
    return countryList;
   }

...
}

My "add-team-form.jsp"

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<?xml version="1.0" encoding="ISO-8859-1" ?>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Add team page</title>

Add team page

<form:form method="POST"
        modelAttribute="team"
        action="${pageContext.request.contextPath}/team/add.html">

        Name:
        <form:input path="name" />

        Rating:
        <form:input path="rating" />

    Country

        <form:select path="country.idCountry">
            <form:options items="${countryList}" />
        </form:select>

        <input type="submit" value="Add" />

</form:form>

There is no error showing in the console of eclipse, but here is the error im receiving from the browser:

HTTP Status 400 -

type Status report

message

description The request sent by the client was syntactically incorrect.
Apache Tomcat/7.0.47


来源: stackexchange

问:
Sorting of files based on version number in the middle of the file name
I am new to the power shell. I am trying to sort a list of files which are having version number in the middle of the name.

Here is the list of files :

```<code>sample-file-1.1.0-patch.zip
sample-file-1.1.1-patch.zip
sample-file-1.1.2-patch.zip
sample-file-1.1.2.1-fix-patch.zip
sample-file-1.1.3-patch.zip
sample-file-1.1.3.1-fix-patch.zip
..
sample-file-1.1.15-patch.zip
sample-file-1.1.15.1-fix-patch.zip
sample-file-1.1.15.2-fix-patch.zip
..
sample-file-2.0.0-patch.zip
sample-file-2.0.1-patch.zip
..
</code>```

I would request you to help me with the sorting logic.

Thanks

答:
The simplest approach with your sample input is the following, which assumes that the first digit following - starts the version number and that it ends with the last digit before a subsequent -:

```<code>Get-ChildItem *.zip | Sort-Object { [version]($_.Name -replace '^[^\d]+-(.*\d)-.*', '$1') }
</code>```

$_.Name -replace '^[^\d]+-(.*\d)-.*', '$1' extracts the version number from each file name as a string.

[version] casts that string to a version-number object (System.Version)[1]
, which is sortable based on the version-number components.

Passing the whole expression as a script block { ... } to Sort-Object means that sorting is based on the [version] instances returned by the script block, evaluated for each input filename.

[1] PSv5.1 introduced a related type, [System.Management.Automation.SemanticVersion], based on semantic versioning, which wouldn't work here, however, because it only supports 3 version-number components.

ContentLicense: CC BY-SA 3.0

Body:
I am new to the power shell. I am trying to sort a list of files which are having version number in the middle of the name.

Here is the list of files :

sample-file-1.1.0-patch.zip
sample-file-1.1.1-patch.zip
sample-file-1.1.2-patch.zip
sample-file-1.1.2.1-fix-patch.zip
sample-file-1.1.3-patch.zip
sample-file-1.1.3.1-fix-patch.zip
..
sample-file-1.1.15-patch.zip
sample-file-1.1.15.1-fix-patch.zip
sample-file-1.1.15.2-fix-patch.zip
..
sample-file-2.0.0-patch.zip
sample-file-2.0.1-patch.zip
..

I would request you to help me with the sorting logic.

Thanks

Body:
The simplest approach with your sample input is the following, which assumes that the first digit following - starts the version number and that it ends with the last digit before a subsequent -:

Get-ChildItem *.zip | Sort-Object { [version]($_.Name -replace '^[^\d]+-(.*\d)-.*', '$1') }

$_.Name -replace '^[^\d]+-(.*\d)-.*', '$1' extracts the version number from each file name as a string.

[version] casts that string to a version-number object (System.Version)[1]
, which is sortable based on the version-number components.

Passing the whole expression as a script block { ... } to Sort-Object means that sorting is based on the [version] instances returned by the script block, evaluated for each input filename.

[1] PSv5.1 introduced a related type, [System.Management.Automation.SemanticVersion], based on semantic versioning, which wouldn't work here, however, because it only supports 3 version-number components.


问:
NuGet Packages not being restored with TFS
I'm running into an issue with some NuGet packages not being restored during the msbuild process in a TFS build definition.

I have a total of nine NuGet packages in my solution and I can see seven of nine getting restored from the packages folder, however the other two never get restored or even attempted to be restored.  The packages are listed in the packages.config and the corresponding folders exist in the build directory.

I've tried adding the additional NuGet Restore mentioned in this MS document and I've tried running the NuGet command manually without success.

Additional Details:

The solution is for a .Net website that doesn't have a project file

NuGet.exe version is 2.8.60318.667

TFS 2015

msbuild.exe 14.0.23107

Targeting .Net Framework 4.0 (But have tried 4.5 as well with the same result)

AWSSDK.Core and AWSSDK.DynamoDBv2 are not being restored.

Contents of packages.config:

```<code><?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="AWSSDK.Core" version="3.3.15" targetFramework="net40" requireReinstallation="true" />
  <package id="AWSSDK.DynamoDBv2" version="3.3.4.14" targetFramework="net40" requireReinstallation="true" />
  <package id="Microsoft.Bcl" version="1.1.10" targetFramework="net40" requireReinstallation="true" />
  <package id="Microsoft.Bcl.Async" version="1.0.168" targetFramework="net40" />
  <package id="Microsoft.Bcl.Build" version="1.0.14" targetFramework="net40" />
  <package id="RestSharp" version="105.2.3" targetFramework="net40" requireReinstallation="true" />
  <package id="StackExchange.Redis" version="1.1.603" targetFramework="net40" requireReinstallation="true" />
  <package id="Twilio" version="4.7.2" targetFramework="net40" />
  <package id="Twilio.Lookups" version="1.1.0" targetFramework="net40" />
</packages>
</code>```

From the TFS Output:

```<code>> Build started 6/29/2017 11:51:47 PM.
>      1>Project "B:\site_agent\_work\4d978bf9\Site\Site.sln" on node 1 (default targets).
>      1>ValidateSolutionConfiguration:
>          Building solution configuration "Debug|Any CPU". B:\site_agent\_work\4d978bf9\Site\site.metaproj(0,0): Warning MSB3268:
> The primary reference
> "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.dll"
> could not be resolved because it has an indirect dependency on the
> framework assembly "System.Runtime, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a" which could not be resolved in the
> currently targeted framework. ".NETFramework,Version=v4.5". To resolve
> this problem, either remove the reference
> "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.dll"
> or retarget your application to a framework version which contains
> "System.Runtime, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a".
>      1>Project "B:\site_agent\_work\4d978bf9\Site\Site.sln" (1) is building "B:\site_agent\_work\4d978bf9\Site\site.metaproj" (2) on node
> 1 (default targets).
>      2>B:\site_agent\_work\4d978bf9\Site\site.metaproj : warning MSB3268: The primary reference
> "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.dll"
> could not be resolved because it has an indirect dependency on the
> framework assembly "System.Runtime, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a" which could not be resolved in the
> currently targeted framework. ".NETFramework,Version=v4.5". To resolve
> this problem, either remove the reference
> "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.dll"
> or retarget your application to a framework version which contains
> "System.Runtime, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a".
> B:\site_agent\_work\4d978bf9\Site\site.metaproj(0,0): Warning MSB3268:
> The primary reference
> "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.dll"
> could not be resolved because it has an indirect dependency on the
> framework assembly "System.Threading.Tasks, Version=4.0.0.0,
> Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" which could not be
> resolved in the currently targeted framework.
> ".NETFramework,Version=v4.5". To resolve this problem, either remove
> the reference
> "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.dll"
> or retarget your application to a framework version which contains
> "System.Threading.Tasks, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a".
>      2>B:\site_agent\_work\4d978bf9\Site\site.metaproj : warning MSB3268: The primary reference
> "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.dll"
> could not be resolved because it has an indirect dependency on the
> framework assembly "System.Threading.Tasks, Version=4.0.0.0,
> Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" which could not be
> resolved in the currently targeted framework.
> ".NETFramework,Version=v4.5". To resolve this problem, either remove
> the reference
> "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.dll"
> or retarget your application to a framework version which contains
> "System.Threading.Tasks, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a".
> B:\site_agent\_work\4d978bf9\Site\site.metaproj(0,0): Warning MSB3268:
> The primary reference
> "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.Extensions.dll"
> could not be resolved because it has an indirect dependency on the
> framework assembly "System.Threading.Tasks, Version=4.0.0.0,
> Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" which could not be
> resolved in the currently targeted framework.
> ".NETFramework,Version=v4.5". To resolve this problem, either remove
> the reference
> "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.Extensions.dll"
> or retarget your application to a framework version which contains
> "System.Threading.Tasks, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a".
>      2>B:\site_agent\_work\4d978bf9\Site\site.metaproj : warning MSB3268: The primary reference
> "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.Extensions.dll"
> could not be resolved because it has an indirect dependency on the
> framework assembly "System.Threading.Tasks, Version=4.0.0.0,
> Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" which could not be
> resolved in the currently targeted framework.
> ".NETFramework,Version=v4.5". To resolve this problem, either remove
> the reference
> "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.Extensions.dll"
> or retarget your application to a framework version which contains
> "System.Threading.Tasks, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a".
> B:\site_agent\_work\4d978bf9\Site\site.metaproj(0,0): Warning MSB3268:
> The primary reference
> "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.Extensions.dll"
> could not be resolved because it has an indirect dependency on the
> framework assembly "System.Runtime, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a" which could not be resolved in the
> currently targeted framework. ".NETFramework,Version=v4.5". To resolve
> this problem, either remove the reference
> "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.Extensions.dll"
> or retarget your application to a framework version which contains
> "System.Runtime, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a".
>      2>B:\site_agent\_work\4d978bf9\Site\site.metaproj : warning MSB3268: The primary reference
> "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.Extensions.dll"
> could not be resolved because it has an indirect dependency on the
> framework assembly "System.Runtime, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a" which could not be resolved in the
> currently targeted framework. ".NETFramework,Version=v4.5". To resolve
> this problem, either remove the reference
> "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.Extensions.dll"
> or retarget your application to a framework version which contains
> "System.Runtime, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a".
> B:\site_agent\_work\4d978bf9\Site\site.metaproj(0,0): Warning MSB3268:
> The primary reference
> "B:\site_agent\_work\4d978bf9\Site\packages\StackExchange.Redis.1.1.603\lib\net40\StackExchange.Redis.dll"
> could not be resolved because it has an indirect dependency on the
> framework assembly "System.Runtime, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a" which could not be resolved in the
> currently targeted framework. ".NETFramework,Version=v4.5". To resolve
> this problem, either remove the reference
> "B:\site_agent\_work\4d978bf9\Site\packages\StackExchange.Redis.1.1.603\lib\net40\StackExchange.Redis.dll"
> or retarget your application to a framework version which contains
> "System.Runtime, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a".
>      2>B:\site_agent\_work\4d978bf9\Site\site.metaproj : warning MSB3268: The primary reference
> "B:\site_agent\_work\4d978bf9\Site\packages\StackExchange.Redis.1.1.603\lib\net40\StackExchange.Redis.dll"
> could not be resolved because it has an indirect dependency on the
> framework assembly "System.Runtime, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a" which could not be resolved in the
> currently targeted framework. ".NETFramework,Version=v4.5". To resolve
> this problem, either remove the reference
> "B:\site_agent\_work\4d978bf9\Site\packages\StackExchange.Redis.1.1.603\lib\net40\StackExchange.Redis.dll"
> or retarget your application to a framework version which contains
> "System.Runtime, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a".
> B:\site_agent\_work\4d978bf9\Site\site.metaproj(0,0): Warning MSB3268:
> The primary reference
> "B:\site_agent\_work\4d978bf9\Site\packages\StackExchange.Redis.1.1.603\lib\net40\StackExchange.Redis.dll"
> could not be resolved because it has an indirect dependency on the
> framework assembly "System.Threading.Tasks, Version=4.0.0.0,
> Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" which could not be
> resolved in the currently targeted framework.
> ".NETFramework,Version=v4.5". To resolve this problem, either remove
> the reference
> "B:\site_agent\_work\4d978bf9\Site\packages\StackExchange.Redis.1.1.603\lib\net40\StackExchange.Redis.dll"
> or retarget your application to a framework version which contains
> "System.Threading.Tasks, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a".
>      2>B:\site_agent\_work\4d978bf9\Site\site.metaproj : warning MSB3268: The primary reference
> "B:\site_agent\_work\4d978bf9\Site\packages\StackExchange.Redis.1.1.603\lib\net40\StackExchange.Redis.dll"
> could not be resolved because it has an indirect dependency on the
> framework assembly "System.Threading.Tasks, Version=4.0.0.0,
> Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" which could not be
> resolved in the currently targeted framework.
> ".NETFramework,Version=v4.5". To resolve this problem, either remove
> the reference
> "B:\site_agent\_work\4d978bf9\Site\packages\StackExchange.Redis.1.1.603\lib\net40\StackExchange.Redis.dll"
> or retarget your application to a framework version which contains
> "System.Threading.Tasks, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a".
>          Copying file from "B:\site_agent\_work\4d978bf9\Site\site\Bin\AjaxControlToolkit.dll" to
> "site\\Bin\AjaxControlToolkit.dll".
>          Copying file from "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.Extensions.Desktop.dll"
> to "site\\Bin\Microsoft.Threading.Tasks.Extensions.Desktop.dll".
>          Copying file from "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.Extensions.Desktop.xml"
> to "site\\Bin\Microsoft.Threading.Tasks.Extensions.Desktop.xml".
>          Copying file from "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.1.1.10\lib\net40\System.IO.dll"
> to "site\\Bin\System.IO.dll".
>          Copying file from "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.1.1.10\lib\net40\System.IO.xml"
> to "site\\Bin\System.IO.xml".
>          Copying file from "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.1.1.10\lib\net40\System.Threading.Tasks.dll"
> to "site\\Bin\System.Threading.Tasks.dll".
>          Copying file from "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.1.1.10\lib\net40\System.Threading.Tasks.xml"
> to "site\\Bin\System.Threading.Tasks.xml".
>          Copying file from "B:\site_agent\_work\4d978bf9\Site\packages\Twilio.4.7.2\lib\3.5\Twilio.Api.dll"
> to "site\\Bin\Twilio.Api.dll".
>          Copying file from "B:\site_agent\_work\4d978bf9\Site\packages\Twilio.4.7.2\lib\3.5\Twilio.Api.pdb"
> to "site\\Bin\Twilio.Api.pdb".
>          Copying file from "B:\site_agent\_work\4d978bf9\Site\packages\Twilio.4.7.2\lib\3.5\Twilio.Api.xml"
> to "site\\Bin\Twilio.Api.xml".
>          Copying file from "B:\site_agent\_work\4d978bf9\Site\packages\Twilio.Lookups.1.1.0\lib\3.5\Twilio.Lookups.dll"
> to "site\\Bin\Twilio.Lookups.dll".
>          Copying file from "B:\site_agent\_work\4d978bf9\Site\packages\Twilio.Lookups.1.1.0\lib\3.5\Twilio.Lookups.pdb"
> to "site\\Bin\Twilio.Lookups.pdb".
>          C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_compiler.exe -v
> /localhost_55535 -p site\ -u -f
</code>```

答:
It appears that without a project file in the solution it doesn't automatically restore the dlls from the packages directory unless you add the .refresh file to the bin folder.  Once I did that all of the package dlls were getting copied out of their respective folders in the packages directory for the solution to the bin folder before msbuild was called to start the compile.

Summary of solution:

Add the .refresh file in the bin folder to TFS

Ensure the packages folder and it's contents are checked into TFS

Do not add the actual dlls in the bin folder to TFS

Set the TFS build step to Restore NuGet packages.

Ensure you have a packages.config in the root of the Web Site code

Body:
I'm running into an issue with some NuGet packages not being restored during the msbuild process in a TFS build definition.

I have a total of nine NuGet packages in my solution and I can see seven of nine getting restored from the packages folder, however the other two never get restored or even attempted to be restored.  The packages are listed in the packages.config and the corresponding folders exist in the build directory.

I've tried adding the additional NuGet Restore mentioned in this MS document and I've tried running the NuGet command manually without success.

Additional Details:

The solution is for a .Net website that doesn't have a project file

NuGet.exe version is 2.8.60318.667

TFS 2015

msbuild.exe 14.0.23107

Targeting .Net Framework 4.0 (But have tried 4.5 as well with the same result)

AWSSDK.Core and AWSSDK.DynamoDBv2 are not being restored.

Contents of packages.config:

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="AWSSDK.Core" version="3.3.15" targetFramework="net40" requireReinstallation="true" />
  <package id="AWSSDK.DynamoDBv2" version="3.3.4.14" targetFramework="net40" requireReinstallation="true" />
  <package id="Microsoft.Bcl" version="1.1.10" targetFramework="net40" requireReinstallation="true" />
  <package id="Microsoft.Bcl.Async" version="1.0.168" targetFramework="net40" />
  <package id="Microsoft.Bcl.Build" version="1.0.14" targetFramework="net40" />
  <package id="RestSharp" version="105.2.3" targetFramework="net40" requireReinstallation="true" />
  <package id="StackExchange.Redis" version="1.1.603" targetFramework="net40" requireReinstallation="true" />
  <package id="Twilio" version="4.7.2" targetFramework="net40" />
  <package id="Twilio.Lookups" version="1.1.0" targetFramework="net40" />
</packages>

From the TFS Output:

> Build started 6/29/2017 11:51:47 PM.
>      1>Project "B:\site_agent\_work\4d978bf9\Site\Site.sln" on node 1 (default targets).
>      1>ValidateSolutionConfiguration:
>          Building solution configuration "Debug|Any CPU". B:\site_agent\_work\4d978bf9\Site\site.metaproj(0,0): Warning MSB3268:
> The primary reference
> "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.dll"
> could not be resolved because it has an indirect dependency on the
> framework assembly "System.Runtime, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a" which could not be resolved in the
> currently targeted framework. ".NETFramework,Version=v4.5". To resolve
> this problem, either remove the reference
> "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.dll"
> or retarget your application to a framework version which contains
> "System.Runtime, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a".
>      1>Project "B:\site_agent\_work\4d978bf9\Site\Site.sln" (1) is building "B:\site_agent\_work\4d978bf9\Site\site.metaproj" (2) on node
> 1 (default targets).
>      2>B:\site_agent\_work\4d978bf9\Site\site.metaproj : warning MSB3268: The primary reference
> "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.dll"
> could not be resolved because it has an indirect dependency on the
> framework assembly "System.Runtime, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a" which could not be resolved in the
> currently targeted framework. ".NETFramework,Version=v4.5". To resolve
> this problem, either remove the reference
> "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.dll"
> or retarget your application to a framework version which contains
> "System.Runtime, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a".
> B:\site_agent\_work\4d978bf9\Site\site.metaproj(0,0): Warning MSB3268:
> The primary reference
> "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.dll"
> could not be resolved because it has an indirect dependency on the
> framework assembly "System.Threading.Tasks, Version=4.0.0.0,
> Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" which could not be
> resolved in the currently targeted framework.
> ".NETFramework,Version=v4.5". To resolve this problem, either remove
> the reference
> "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.dll"
> or retarget your application to a framework version which contains
> "System.Threading.Tasks, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a".
>      2>B:\site_agent\_work\4d978bf9\Site\site.metaproj : warning MSB3268: The primary reference
> "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.dll"
> could not be resolved because it has an indirect dependency on the
> framework assembly "System.Threading.Tasks, Version=4.0.0.0,
> Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" which could not be
> resolved in the currently targeted framework.
> ".NETFramework,Version=v4.5". To resolve this problem, either remove
> the reference
> "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.dll"
> or retarget your application to a framework version which contains
> "System.Threading.Tasks, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a".
> B:\site_agent\_work\4d978bf9\Site\site.metaproj(0,0): Warning MSB3268:
> The primary reference
> "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.Extensions.dll"
> could not be resolved because it has an indirect dependency on the
> framework assembly "System.Threading.Tasks, Version=4.0.0.0,
> Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" which could not be
> resolved in the currently targeted framework.
> ".NETFramework,Version=v4.5". To resolve this problem, either remove
> the reference
> "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.Extensions.dll"
> or retarget your application to a framework version which contains
> "System.Threading.Tasks, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a".
>      2>B:\site_agent\_work\4d978bf9\Site\site.metaproj : warning MSB3268: The primary reference
> "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.Extensions.dll"
> could not be resolved because it has an indirect dependency on the
> framework assembly "System.Threading.Tasks, Version=4.0.0.0,
> Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" which could not be
> resolved in the currently targeted framework.
> ".NETFramework,Version=v4.5". To resolve this problem, either remove
> the reference
> "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.Extensions.dll"
> or retarget your application to a framework version which contains
> "System.Threading.Tasks, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a".
> B:\site_agent\_work\4d978bf9\Site\site.metaproj(0,0): Warning MSB3268:
> The primary reference
> "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.Extensions.dll"
> could not be resolved because it has an indirect dependency on the
> framework assembly "System.Runtime, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a" which could not be resolved in the
> currently targeted framework. ".NETFramework,Version=v4.5". To resolve
> this problem, either remove the reference
> "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.Extensions.dll"
> or retarget your application to a framework version which contains
> "System.Runtime, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a".
>      2>B:\site_agent\_work\4d978bf9\Site\site.metaproj : warning MSB3268: The primary reference
> "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.Extensions.dll"
> could not be resolved because it has an indirect dependency on the
> framework assembly "System.Runtime, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a" which could not be resolved in the
> currently targeted framework. ".NETFramework,Version=v4.5". To resolve
> this problem, either remove the reference
> "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.Extensions.dll"
> or retarget your application to a framework version which contains
> "System.Runtime, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a".
> B:\site_agent\_work\4d978bf9\Site\site.metaproj(0,0): Warning MSB3268:
> The primary reference
> "B:\site_agent\_work\4d978bf9\Site\packages\StackExchange.Redis.1.1.603\lib\net40\StackExchange.Redis.dll"
> could not be resolved because it has an indirect dependency on the
> framework assembly "System.Runtime, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a" which could not be resolved in the
> currently targeted framework. ".NETFramework,Version=v4.5". To resolve
> this problem, either remove the reference
> "B:\site_agent\_work\4d978bf9\Site\packages\StackExchange.Redis.1.1.603\lib\net40\StackExchange.Redis.dll"
> or retarget your application to a framework version which contains
> "System.Runtime, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a".
>      2>B:\site_agent\_work\4d978bf9\Site\site.metaproj : warning MSB3268: The primary reference
> "B:\site_agent\_work\4d978bf9\Site\packages\StackExchange.Redis.1.1.603\lib\net40\StackExchange.Redis.dll"
> could not be resolved because it has an indirect dependency on the
> framework assembly "System.Runtime, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a" which could not be resolved in the
> currently targeted framework. ".NETFramework,Version=v4.5". To resolve
> this problem, either remove the reference
> "B:\site_agent\_work\4d978bf9\Site\packages\StackExchange.Redis.1.1.603\lib\net40\StackExchange.Redis.dll"
> or retarget your application to a framework version which contains
> "System.Runtime, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a".
> B:\site_agent\_work\4d978bf9\Site\site.metaproj(0,0): Warning MSB3268:
> The primary reference
> "B:\site_agent\_work\4d978bf9\Site\packages\StackExchange.Redis.1.1.603\lib\net40\StackExchange.Redis.dll"
> could not be resolved because it has an indirect dependency on the
> framework assembly "System.Threading.Tasks, Version=4.0.0.0,
> Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" which could not be
> resolved in the currently targeted framework.
> ".NETFramework,Version=v4.5". To resolve this problem, either remove
> the reference
> "B:\site_agent\_work\4d978bf9\Site\packages\StackExchange.Redis.1.1.603\lib\net40\StackExchange.Redis.dll"
> or retarget your application to a framework version which contains
> "System.Threading.Tasks, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a".
>      2>B:\site_agent\_work\4d978bf9\Site\site.metaproj : warning MSB3268: The primary reference
> "B:\site_agent\_work\4d978bf9\Site\packages\StackExchange.Redis.1.1.603\lib\net40\StackExchange.Redis.dll"
> could not be resolved because it has an indirect dependency on the
> framework assembly "System.Threading.Tasks, Version=4.0.0.0,
> Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" which could not be
> resolved in the currently targeted framework.
> ".NETFramework,Version=v4.5". To resolve this problem, either remove
> the reference
> "B:\site_agent\_work\4d978bf9\Site\packages\StackExchange.Redis.1.1.603\lib\net40\StackExchange.Redis.dll"
> or retarget your application to a framework version which contains
> "System.Threading.Tasks, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b03f5f7f11d50a3a".
>          Copying file from "B:\site_agent\_work\4d978bf9\Site\site\Bin\AjaxControlToolkit.dll" to
> "site\\Bin\AjaxControlToolkit.dll".
>          Copying file from "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.Extensions.Desktop.dll"
> to "site\\Bin\Microsoft.Threading.Tasks.Extensions.Desktop.dll".
>          Copying file from "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.Extensions.Desktop.xml"
> to "site\\Bin\Microsoft.Threading.Tasks.Extensions.Desktop.xml".
>          Copying file from "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.1.1.10\lib\net40\System.IO.dll"
> to "site\\Bin\System.IO.dll".
>          Copying file from "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.1.1.10\lib\net40\System.IO.xml"
> to "site\\Bin\System.IO.xml".
>          Copying file from "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.1.1.10\lib\net40\System.Threading.Tasks.dll"
> to "site\\Bin\System.Threading.Tasks.dll".
>          Copying file from "B:\site_agent\_work\4d978bf9\Site\packages\Microsoft.Bcl.1.1.10\lib\net40\System.Threading.Tasks.xml"
> to "site\\Bin\System.Threading.Tasks.xml".
>          Copying file from "B:\site_agent\_work\4d978bf9\Site\packages\Twilio.4.7.2\lib\3.5\Twilio.Api.dll"
> to "site\\Bin\Twilio.Api.dll".
>          Copying file from "B:\site_agent\_work\4d978bf9\Site\packages\Twilio.4.7.2\lib\3.5\Twilio.Api.pdb"
> to "site\\Bin\Twilio.Api.pdb".
>          Copying file from "B:\site_agent\_work\4d978bf9\Site\packages\Twilio.4.7.2\lib\3.5\Twilio.Api.xml"
> to "site\\Bin\Twilio.Api.xml".
>          Copying file from "B:\site_agent\_work\4d978bf9\Site\packages\Twilio.Lookups.1.1.0\lib\3.5\Twilio.Lookups.dll"
> to "site\\Bin\Twilio.Lookups.dll".
>          Copying file from "B:\site_agent\_work\4d978bf9\Site\packages\Twilio.Lookups.1.1.0\lib\3.5\Twilio.Lookups.pdb"
> to "site\\Bin\Twilio.Lookups.pdb".
>          C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_compiler.exe -v
> /localhost_55535 -p site\ -u -f


问:
Want to extract all images frame by frame in video while video is getting played in AVPlayer
Extract all images frame by frame in video while video is getting played in AVPlayer.

For example if video is 30 fps and video duration is 10 secs then I should be able to get 300 images from video.

Currently I am extracting images using this code:

[self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, fps) queue:dispatch_get_main_queue() usingBlock:

```<code>^(CMTime time) {
    [weakSelf readNextMovieFrame];
}];
(void) readNextMovieFrame {

CMTime outputItemTime = [[self playerItem] currentTime];

CMTime t = [[self playerItem] currentTime];
CMTime d = [[self playerItem] duration];

if ([_output hasNewPixelBufferForItemTime:outputItemTime]) {
    CVPixelBufferRef buffer = [_output copyPixelBufferForItemTime:outputItemTime itemTimeForDisplay:nil];

    CIImage *image = [CIImage imageWithCVPixelBuffer:buffer];

    UIImage *imageUI = [self makeUIImageFromCIImage:image];

    [self saveImage];

    //CFRelease(sampleBuffer);
    CVBufferRelease(buffer);

}
</code>```

}

答:
I use the following to extract an image from a video on iOS.</p>

```<code>- (UIImage *)getVideoImageAtTime:(CMTime)time player:(AVPlayer *)player {
    NSError *error = nil;
    AVAsset *asset = player.currentItem.asset;
    AVAssetImageGenerator *ig = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    CGImageRef image = [ig copyCGImageAtTime:time actualTime:nil error:&error];
    UIImage *screenShot = [UIImage imageWithCGImage:image];
    CGImageRelease(image);
    return error ? screenShot : nil;
}
</code>```

Body:
Extract all images frame by frame in video while video is getting played in AVPlayer.

For example if video is 30 fps and video duration is 10 secs then I should be able to get 300 images from video.

Currently I am extracting images using this code:

[self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, fps) queue:dispatch_get_main_queue() usingBlock:

^(CMTime time) {
    [weakSelf readNextMovieFrame];
}];
(void) readNextMovieFrame {

CMTime outputItemTime = [[self playerItem] currentTime];

CMTime t = [[self playerItem] currentTime];
CMTime d = [[self playerItem] duration];

if ([_output hasNewPixelBufferForItemTime:outputItemTime]) {
    CVPixelBufferRef buffer = [_output copyPixelBufferForItemTime:outputItemTime itemTimeForDisplay:nil];

    CIImage *image = [CIImage imageWithCVPixelBuffer:buffer];

    UIImage *imageUI = [self makeUIImageFromCIImage:image];

    [self saveImage];

    //CFRelease(sampleBuffer);
    CVBufferRelease(buffer);

}

}

Body:
I use the following to extract an image from a video on iOS.

- (UIImage *)getVideoImageAtTime:(CMTime)time player:(AVPlayer *)player {
    NSError *error = nil;
    AVAsset *asset = player.currentItem.asset;
    AVAssetImageGenerator *ig = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    CGImageRef image = [ig copyCGImageAtTime:time actualTime:nil error:&error];
    UIImage *screenShot = [UIImage imageWithCGImage:image];
    CGImageRelease(image);
    return error ? screenShot : nil;
}


问:
How to swap places left to right of a few <option>, not all of them from within <select> using toggle button
How do I make a few <option> LangLEFT to switch position with a few <option> LangRIGHT and vise versa using a ON/OFF or LEFT/RIGHT toggle button or by using a radio button or a check box or another select menu.

I want a few <option> LangLEFT  to tugle with a few <option> LangRIGHT and swap places, without swap places of the <select> names codes.

NOTE: Only a few <option> should switch places, NOT all <option>.

EXAMPLE: The "language value" should swap places, but the "auto value" should NOT.

HTML:

```<code><textarea name="uLEFT" cols="71" rows="7" wrap="physical" id="SeekBoxLEFT"></textarea>

<textarea name="uRIGHT" cols="71" rows="7" wrap="physical" id="SeekBoxRIGHT" ></textarea>

<select name="LangLEFT">
<option selected value="auto">Auto Identify language</option>
<option value="en">English</option>
<option value="ru">Russian</option>
</select>

<select name="LangRIGHT">
<option value="en">English</option>
<option value="ru">Russian</option>
</select>
</code>```

答:
  $(document).ready(function(){
   $("#right").on("click",function(){
      $("#left_select").insertAfter("#right_select");
      });
      $("#left").on("click",function(){
      $("#right_select").insertAfter("#left_select");
      });
   });```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <script src="https://cdn.jsdelivr.net/jquery/3.2.1/jquery.min.js"></script>
 <input type="button" id="right" value="Change To Right" >
 <input type="button" id="left" value="Change To Left" >

         <select id="left_select" name="LangLEFT">
          <option selected value="auto">Auto Identify language</option>
          <option value="en">English</option>
          <option value="ru">Russian</option>
         </select>
         <select id="right_select" name="LangRIGHT">
          <option value="en">English</option>
          <option value="ru">Russian</option>
         </select></code>```

Body:
How do I make a few <option> LangLEFT to switch position with a few <option> LangRIGHT and vise versa using a ON/OFF or LEFT/RIGHT toggle button or by using a radio button or a check box or another select menu.

I want a few <option> LangLEFT  to tugle with a few <option> LangRIGHT and swap places, without swap places of the <select> names codes.

NOTE: Only a few <option> should switch places, NOT all <option>.

EXAMPLE: The "language value" should swap places, but the "auto value" should NOT.

HTML:

<textarea name="uLEFT" cols="71" rows="7" wrap="physical" id="SeekBoxLEFT"></textarea>

<textarea name="uRIGHT" cols="71" rows="7" wrap="physical" id="SeekBoxRIGHT" ></textarea>

<select name="LangLEFT">
<option selected value="auto">Auto Identify language</option>
<option value="en">English</option>
<option value="ru">Russian</option>
</select>

<select name="LangRIGHT">
<option value="en">English</option>
<option value="ru">Russian</option>
</select>

Body:
  $(document).ready(function(){
   $("#right").on("click",function(){
      $("#left_select").insertAfter("#right_select");
      });
      $("#left").on("click",function(){
      $("#right_select").insertAfter("#left_select");
      });
   });

 <script src="https://cdn.jsdelivr.net/jquery/3.2.1/jquery.min.js"></script>
 <input type="button" id="right" value="Change To Right" >
 <input type="button" id="left" value="Change To Left" >

         <select id="left_select" name="LangLEFT">
          <option selected value="auto">Auto Identify language</option>
          <option value="en">English</option>
          <option value="ru">Russian</option>
         </select>
         <select id="right_select" name="LangRIGHT">
          <option value="en">English</option>
          <option value="ru">Russian</option>
         </select>


问:
Multiple goroutines listening on one channel
I have multiple goroutines trying to receive on the same channel simultaneously. It seems like the last goroutine that starts receiving on the channel gets the value. Is this somewhere in the language spec or is it undefined behaviour?

```<code>c := make(chan string)
for i := 0; i < 5; i++ {
    go func(i int) {
        <-c
        c <- fmt.Sprintf("goroutine %d", i)
    }(i)
}
c <- "hi"
fmt.Println(<-c)
</code>```

Output:

```<code>goroutine 4
</code>```

Example On Playground

EDIT:

I just realized that it's more complicated than I thought. The message gets passed around all the goroutines.

```<code>c := make(chan string)
for i := 0; i < 5; i++ {
    go func(i int) {
        msg := <-c
        c <- fmt.Sprintf("%s, hi from %d", msg, i)
    }(i)
}
c <- "original"
fmt.Println(<-c)
</code>```

Output:

```<code>original, hi from 0, hi from 1, hi from 2, hi from 3, hi from 4
</code>```

NOTE: the above output is outdated in more recent versions of Go (see comments)

Example On Playground

答:
For multiple goroutine listen on one channel, yes, it's possible. the key point is the message itself, you can define some message like that:

```<code>package main

import (
    "fmt"
    "sync"
)

type obj struct {
    msg string
    receiver int
}

func main() {
    ch := make(chan *obj) // both block or non-block are ok
    var wg sync.WaitGroup
    receiver := 25 // specify receiver count

    sender := func() {
        o := &obj {
            msg: "hello everyone!",
            receiver: receiver,
        }
        ch <- o
    }
    recv := func(idx int) {
        defer wg.Done()
        o := <-ch
        fmt.Printf("%d received at %d\n", idx, o.receiver)
        o.receiver--
        if o.receiver > 0 {
            ch <- o // forward to others
        } else {
            fmt.Printf("last receiver: %d\n", idx)
        }
    }

    go sender()
    for i:=0; i<reciever; i++ {
        wg.Add(1)
        go recv(i)
    }

    wg.Wait()
}
</code>```

The output is random:

```<code>5 received at 25
24 received at 24
6 received at 23
7 received at 22
8 received at 21
9 received at 20
10 received at 19
11 received at 18
12 received at 17
13 received at 16
14 received at 15
15 received at 14
16 received at 13
17 received at 12
18 received at 11
19 received at 10
20 received at 9
21 received at 8
22 received at 7
23 received at 6
2 received at 5
0 received at 4
1 received at 3
3 received at 2
4 received at 1
last receiver 4
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have multiple goroutines trying to receive on the same channel simultaneously. It seems like the last goroutine that starts receiving on the channel gets the value. Is this somewhere in the language spec or is it undefined behaviour?

c := make(chan string)
for i := 0; i < 5; i++ {
    go func(i int) {
        <-c
        c <- fmt.Sprintf("goroutine %d", i)
    }(i)
}
c <- "hi"
fmt.Println(<-c)

Output:

goroutine 4

Example On Playground

EDIT:

I just realized that it's more complicated than I thought. The message gets passed around all the goroutines.

c := make(chan string)
for i := 0; i < 5; i++ {
    go func(i int) {
        msg := <-c
        c <- fmt.Sprintf("%s, hi from %d", msg, i)
    }(i)
}
c <- "original"
fmt.Println(<-c)

Output:

original, hi from 0, hi from 1, hi from 2, hi from 3, hi from 4

NOTE: the above output is outdated in more recent versions of Go (see comments)

Example On Playground

Body:
For multiple goroutine listen on one channel, yes, it's possible. the key point is the message itself, you can define some message like that:

package main

import (
    "fmt"
    "sync"
)

type obj struct {
    msg string
    receiver int
}

func main() {
    ch := make(chan *obj) // both block or non-block are ok
    var wg sync.WaitGroup
    receiver := 25 // specify receiver count

    sender := func() {
        o := &obj {
            msg: "hello everyone!",
            receiver: receiver,
        }
        ch <- o
    }
    recv := func(idx int) {
        defer wg.Done()
        o := <-ch
        fmt.Printf("%d received at %d\n", idx, o.receiver)
        o.receiver--
        if o.receiver > 0 {
            ch <- o // forward to others
        } else {
            fmt.Printf("last receiver: %d\n", idx)
        }
    }

    go sender()
    for i:=0; i<reciever; i++ {
        wg.Add(1)
        go recv(i)
    }

    wg.Wait()
}

The output is random:

5 received at 25
24 received at 24
6 received at 23
7 received at 22
8 received at 21
9 received at 20
10 received at 19
11 received at 18
12 received at 17
13 received at 16
14 received at 15
15 received at 14
16 received at 13
17 received at 12
18 received at 11
19 received at 10
20 received at 9
21 received at 8
22 received at 7
23 received at 6
2 received at 5
0 received at 4
1 received at 3
3 received at 2
4 received at 1
last receiver 4


问:
How to check if a windows user has access (Windows Integrated Security authentication) to SQL Server Analysis Services (SSAS) Server via impersonation
For a SQL Server instance, to check if a windows user is present and has any access or not one can try various ways as detailed here.

I'm looking for something similar for SQL Server Analysis Services (SSAS) server.

I went into properties of SSAS Server from right-click context menu and on Security tab I can see that there are several windows users already configured:

Is there any way to check from a client application (written in C#) by making some sort of test connection or does SSAS also maintains some metadata database of its own like master database in SQL Server instance (DB engine) which can be queried. I checked the Databases node in SSAS server but I don't see any default databases there:

In the client application I'm working upon, I've windows user name and password as input. In my client application there is a simple winform with two text boxes to take AD user name and password which need to be connected to a SSAS Server. My gut feel is that password is of no relevance here as SSAS supports only Windows integrated authentication mode. My client application would be running under an account which already has access to SSAS server I'm trying to connect.

Update: After getting help from @Vaishali, I'm able to figure out that it is possible to make a test connection to an SSAS server using ADOMD.Net.

Now, the problem here is that the connection string implicitly uses the AD account of the user with which I'm running the client application to connect to the SSAS server. I don't think it would be possible mention an windows AD account user name and password explicitly in the ADOMD.Net connection strings while using Windows Integrated authentication. Even connection strings of SQL Server don't allow mentioning the windows username and password explicitly in the connection string as mentioned here.

Update 2: I have got a lead from one of my friends that it is possible to fire some MDX query on SSAS to get user access details.

Update 3: SSAS server supports only Windows Integrated Security mode of authentication unlike SQL Server DB engine which also supports userid-password based SQL authentication. So, some form of impersonation would be required to fire MDX queries on behalf of other user for which I'm trying to check access on SSAS server through Windows Integrated Security only.

答:
Hmphh...It was quite a journey to really be able to nail it through ADOMD.Net.

Core methodology: The core philosophy is the fact that connection to SSAS server supports only Windows Integrated Security based authentication. The SQL authentication like we do for sa user in SQL Server isn't supported in SSAS.

So, the basic idea was to try to connect to the SSAS server using Windows Integrated Security based authentication and fire an MDX query in the context of the user we are trying to check. If the query gets executed successfully then the user has access. If the query execution returns an error/exception then the user doesn't have access.

Please note that just to be able to open a connection to the SSAS server is not an indicator of user-access due to reasons described here. You must fire a query to check access.

For ADOMD.Net until v12.x:

Now, we know that Windows Integrated Security based authentication always takes the user details from the user-context under which the application/process is running. You can not pass the user credentials in the connection string of ADOMD.Net connection. Here is the code I wrote to accomplish it. You need to refer to Microsoft.AnalysisServices.AdomdClient.dll in your C# project.

```<code>using Microsoft.AnalysisServices.AdomdClient;
public static int IsSsasAccessibleToUser(string ssasServerName)
{
    var hasAccess = 0;
    try
    {
        using (var adomdConnection = new AdomdConnection($"provider=olap;datasource={ssasServerName};Catalog=myDatabaseName"))
        using (var adomdCommand = new AdomdCommand())
        {
            adomdCommand.CommandText = "SELECT [CATALOG_NAME] AS [DATABASE],CUBE_CAPTION AS [CUBE/PERSPECTIVE],BASE_CUBE_NAME FROM $system.MDSchema_Cubes WHERE CUBE_SOURCE = 1";
            adomdCommand.Connection = adomdConnection;
            adomdConnection.Open();
            adomdCommand.ExecuteNonQuery();
            Log("ExecuteNonQuery call succeeded so the user has access");
            hasAccess = 1;
        }
    }
    catch (Exception ex)
    {
        Log("There was an error firing query on the database in SSAS server. so user doesn't have access");
    }
    return hasAccess;
}
</code>```

Now, to leverage Windows Integrated Security based authentication we can run this code in two ways:

Out-Proc Impersonation : Put this code inside a console application. Use the "Run as different  user" option in the context menu when we right click the exe. Put the credentials of the user Y (let's say) so that application starts in the context of user Y for which we need to validate the access on SSAS server. ADOMD.Net will use user Y's identity while connecting using Windows Integrated Security for SSAS server. If code succeeds the user has access.

In-Proc Impersonation: The other case could be that you are running the application as user X but you want to test the access of user Y. Here effectively you require in-place impersonation while running the above code. For achieving it I used a famous NuGet package "Simple Impersonation" which uses the default .Net library classes WindowsImpersonationContext and WindowsIdentity . Creator of this NuGet package had first posted a great answer here.

Observation in SQL Server Profiler: After you've impersonated user Y, you will clearly see the MDX query getting fired in the context of user Y if you capture the session as shown below:

Caveats and concerns:

One issue that I faced while using this in-proc impersonation is that it doesn't work if the SSAS server is located on the same machine where the application code is running. This is due to the inherent behavior of native LogonUser API (using LOGON32_LOGON_NEW_CREDENTIALS LogonType) which is called during impersonation calls by the NuGete package. You can try other logon types as detailed here which suites you need.

You require password of the user as well along with the domain name and user name to do impersonation.

For ADOMD.Net v13.x onwards

Then, I came across this ChangeEffectiveUser API documentation on MSDN here. But, intellisense wasn't showing this API. Then I found out this API got added in ADOMD.Net with SQL Server 2016 release. There are various ways to get the latest release:

C:\Program Files\Microsoft.NET\ADOMD.NET\130\Microsoft.AnalysisServices.AdomdClient.dll
I'm not sure who dumps this file at this location. Is it part of Microsoft.Net extensions or SQL Server installation.

In Installation folder of Microsoft SQL Server. I got it at path - C:\Program Files\Microsoft SQL Server\130\Setup Bootstrap\Update Cache\KB3182545\ServicePack\x64\Microsoft.AnalysisServices.AdomdClient.dll

NuGet package here. For some weird reason best known to MS the NuGet package of v13.x of ADOMD.Net has been named Unofficial.Microsoft.AnalysisServices.AdomdClient. Not sure why they introduced a separate NuGet package with Unofficial prefix when this should have been simply the next version of the already existing NuGet package Microsoft.AnalysisServices.AdomdClient present here.

So the new API ChangeEffectiveUser present in latest version on AdomdConnection clas can be used easily to impersonate any user as below:

```<code>adomdConnection.Open();
//impersonate the user after opening the connection
adomdConnection.ChangeEffectiveUser("domainName\UserNameBeingImpersonated");
//now the query gets fired in the context of the impersonated user
adomdCommand.ExecuteNonQuery();
</code>```

Observing Impersonation in SQL Server Profiler: Although one peculiar observation I had in the SQL Server Profiler is that the logs of query being fired still shows the name of the original user with which your application process is running.

So to check whether impersonation is happening or not I removed the access rights of the user domainName\UserNameBeingImpersonated from SSAS server. After that, when I ran the above code again then it resulted in exception whose message clearly states that -  the user domainName\UserNameBeingImpersonated doesn't have permission on the SSAS server or the database doesn't exist. This error message clearly suggests that impersonation is working.

Advantages and Backward compatibility of this approach:

Although the API is very recent as it came up with SQL Server 2016 but I was able to use it successfully with SSAS server 2014 as well. So it looks fairly backward compatible.

This API works irrespective of whether your SSAS server is local or remote.

You just require the domain name and user name for doing impersonation. No password require.

What to do if we simply want to check the access on the SSAS server without involving any database present on the SSAS server?

Change the connection string to not involve any database. Remove the Catalog key as following connection string - "provider=olap;datasource={ssasServerName};"

Fire the following query instead to check access - SELECT * FROM $System.discover_locks in the code snippet shown initially in the post.

Body:
Hmphh...It was quite a journey to really be able to nail it through ADOMD.Net.

Core methodology: The core philosophy is the fact that connection to SSAS server supports only Windows Integrated Security based authentication. The SQL authentication like we do for sa user in SQL Server isn't supported in SSAS.

So, the basic idea was to try to connect to the SSAS server using Windows Integrated Security based authentication and fire an MDX query in the context of the user we are trying to check. If the query gets executed successfully then the user has access. If the query execution returns an error/exception then the user doesn't have access.

Please note that just to be able to open a connection to the SSAS server is not an indicator of user-access due to reasons described here. You must fire a query to check access.

For ADOMD.Net until v12.x:

Now, we know that Windows Integrated Security based authentication always takes the user details from the user-context under which the application/process is running. You can not pass the user credentials in the connection string of ADOMD.Net connection. Here is the code I wrote to accomplish it. You need to refer to Microsoft.AnalysisServices.AdomdClient.dll in your C# project.

using Microsoft.AnalysisServices.AdomdClient;
public static int IsSsasAccessibleToUser(string ssasServerName)
{
    var hasAccess = 0;
    try
    {
        using (var adomdConnection = new AdomdConnection($"provider=olap;datasource={ssasServerName};Catalog=myDatabaseName"))
        using (var adomdCommand = new AdomdCommand())
        {
            adomdCommand.CommandText = "SELECT [CATALOG_NAME] AS [DATABASE],CUBE_CAPTION AS [CUBE/PERSPECTIVE],BASE_CUBE_NAME FROM $system.MDSchema_Cubes WHERE CUBE_SOURCE = 1";
            adomdCommand.Connection = adomdConnection;
            adomdConnection.Open();
            adomdCommand.ExecuteNonQuery();
            Log("ExecuteNonQuery call succeeded so the user has access");
            hasAccess = 1;
        }
    }
    catch (Exception ex)
    {
        Log("There was an error firing query on the database in SSAS server. so user doesn't have access");
    }
    return hasAccess;
}

Now, to leverage Windows Integrated Security based authentication we can run this code in two ways:

Out-Proc Impersonation : Put this code inside a console application. Use the "Run as different  user" option in the context menu when we right click the exe. Put the credentials of the user Y (let's say) so that application starts in the context of user Y for which we need to validate the access on SSAS server. ADOMD.Net will use user Y's identity while connecting using Windows Integrated Security for SSAS server. If code succeeds the user has access.

In-Proc Impersonation: The other case could be that you are running the application as user X but you want to test the access of user Y. Here effectively you require in-place impersonation while running the above code. For achieving it I used a famous NuGet package "Simple Impersonation" which uses the default .Net library classes WindowsImpersonationContext and WindowsIdentity . Creator of this NuGet package had first posted a great answer here.

Observation in SQL Server Profiler: After you've impersonated user Y, you will clearly see the MDX query getting fired in the context of user Y if you capture the session as shown below:

Caveats and concerns:

One issue that I faced while using this in-proc impersonation is that it doesn't work if the SSAS server is located on the same machine where the application code is running. This is due to the inherent behavior of native LogonUser API (using LOGON32_LOGON_NEW_CREDENTIALS LogonType) which is called during impersonation calls by the NuGete package. You can try other logon types as detailed here which suites you need.

You require password of the user as well along with the domain name and user name to do impersonation.

For ADOMD.Net v13.x onwards

Then, I came across this ChangeEffectiveUser API documentation on MSDN here. But, intellisense wasn't showing this API. Then I found out this API got added in ADOMD.Net with SQL Server 2016 release. There are various ways to get the latest release:

C:\Program Files\Microsoft.NET\ADOMD.NET\130\Microsoft.AnalysisServices.AdomdClient.dll
I'm not sure who dumps this file at this location. Is it part of Microsoft.Net extensions or SQL Server installation.

In Installation folder of Microsoft SQL Server. I got it at path - C:\Program Files\Microsoft SQL Server\130\Setup Bootstrap\Update Cache\KB3182545\ServicePack\x64\Microsoft.AnalysisServices.AdomdClient.dll

NuGet package here. For some weird reason best known to MS the NuGet package of v13.x of ADOMD.Net has been named Unofficial.Microsoft.AnalysisServices.AdomdClient. Not sure why they introduced a separate NuGet package with Unofficial prefix when this should have been simply the next version of the already existing NuGet package Microsoft.AnalysisServices.AdomdClient present here.

So the new API ChangeEffectiveUser present in latest version on AdomdConnection clas can be used easily to impersonate any user as below:

adomdConnection.Open();
//impersonate the user after opening the connection
adomdConnection.ChangeEffectiveUser("domainName\UserNameBeingImpersonated");
//now the query gets fired in the context of the impersonated user
adomdCommand.ExecuteNonQuery();

Observing Impersonation in SQL Server Profiler: Although one peculiar observation I had in the SQL Server Profiler is that the logs of query being fired still shows the name of the original user with which your application process is running.

So to check whether impersonation is happening or not I removed the access rights of the user domainName\UserNameBeingImpersonated from SSAS server. After that, when I ran the above code again then it resulted in exception whose message clearly states that -  the user domainName\UserNameBeingImpersonated doesn't have permission on the SSAS server or the database doesn't exist. This error message clearly suggests that impersonation is working.

Advantages and Backward compatibility of this approach:

Although the API is very recent as it came up with SQL Server 2016 but I was able to use it successfully with SSAS server 2014 as well. So it looks fairly backward compatible.

This API works irrespective of whether your SSAS server is local or remote.

You just require the domain name and user name for doing impersonation. No password require.

What to do if we simply want to check the access on the SSAS server without involving any database present on the SSAS server?

Change the connection string to not involve any database. Remove the Catalog key as following connection string - "provider=olap;datasource={ssasServerName};"

Fire the following query instead to check access - SELECT * FROM $System.discover_locks in the code snippet shown initially in the post.


问:
SQLite non-exclusive RESERVED lock?
I've been looking into improving SQLite performance for my site, especially with regard to transactions. In essence what I'm looking for is a way to defer database writes in a process so that they can all be done at once. However, while I'm accumulating update queries, I would like other processes to be able to both read from and write to the database, and only lock the file for writing once a commit is issued in a process.

In looking at the documentation, it seems as though once an update command is issued in a transaction the process gets a RESERVED lock, which (if I remember correctly) means that any other process that attempts to either add an update query to its own transaction or commit the transaction is unable to do so, and therefore blocks until the transaction commits on the process with the lock.

I'm sure there are very good data integrity reasons against this particular feature. All I can say is that in my case there's no danger in performing these updates simultaneously.

One solution is that in each process I could accumulate the text of the queries I wish to invoke in an array, then loop down it once I'm ready to write, but I'm wondering if it's possible the SQLite transaction can be made to do this for me automatically.

update: What I mean when I say "doing all my updates at once" is essentially using transactions in SQLite to only get an EXCLUSIVE lock and write to disk once per processes, rather than once per query. This leads to 100x speedups using SQLite.

I've done some basic testing and it seems that once you have multiple processes adding queries to their transactions, once you hit an update query that process attempts to get the RESERVED lock. Since only once process can have the reserved lock, this means that any other processes attempting to get the lock will block until the process with the lock finished the transaction.

I will admit that this problem might be a premature optimization as I have yet to encounter any performace penalties, but I have run some simple tests and 100 users each creating and running a transaction with 100 queries takes about 4 seconds in PHP on my machine.

答:
Better than to attach a database is to just create a temporary table. (CREATE TEMPORARY ...)

And take a look at the new WAL journal mode, which does exacly what you are trying to do manually and it allows simultanious writes and reads (not simultanious writes though).

#pragma journal_mode=WAL

OwnerDisplayName: nobody

ContentLicense: CC BY-SA 2.5

Title: SQLite non-exclusive RESERVED lock?

LastEditorDisplayName: nobody


问:
Learning Python the Hard Way ex40, don't understand Study Drill 2
http://learnpythonthehardway.org/book/ex40.html

Put the lyrics in a separate variable, then pass that variable to the class to use instead.

I don't understand how to do this, and I'm not even entirely sure what he means by that. Does he mean to define the variables within the class?

```<code>class Song(object):

    def __init__(self, lyrics):
        self.lyrics = lyrics

    def sing_me_a_song(self):
        for line in self.lyrics:
            print line

happy_bday = Song(["Happy birthday to you",
                   "I don't want to get sued",
                   "So I'll stop right there"])

bulls_on_parade = Song(["They rally around the family",
                        "With pockets full of shells"])

happy_bday.sing_me_a_song()

bulls_on_parade.sing_me_a_song()
</code>```

答:
```<code>class Song(object):

    def __init__(self):
        self.lyrics =(["Happy birthday to you",
                       "I don' want to get sued",
                       "So I'll stop right there",
                       "They rally around the family",
                       "With pockets full of shells"])

    def sing_me_a_song(self):
        for line in self.lyrics:
            print line

happy_bday = Song()

happy_bday.sing_me_a_song()
</code>```

Body:
http://learnpythonthehardway.org/book/ex40.html

Put the lyrics in a separate variable, then pass that variable to the class to use instead.

I don't understand how to do this, and I'm not even entirely sure what he means by that. Does he mean to define the variables within the class?

class Song(object):

    def __init__(self, lyrics):
        self.lyrics = lyrics

    def sing_me_a_song(self):
        for line in self.lyrics:
            print line

happy_bday = Song(["Happy birthday to you",
                   "I don't want to get sued",
                   "So I'll stop right there"])

bulls_on_parade = Song(["They rally around the family",
                        "With pockets full of shells"])

happy_bday.sing_me_a_song()

bulls_on_parade.sing_me_a_song()


问:
Is it possible to do things at an OS level when designing an iOS app like stopping the user from using other apps?
Could I use the frameworks provided by Apple and be within their terms of service and make an app that stops users from using specified other apps that they personally specify as not wanting themselves to use?

Edit: ideally this would stop them from using the other apps at all times, not just when they have the app that blocks them from doing it open.

答:
No, you can't. iOS apps cannot affect other apps or block them from running.

There is a "kiosk mode" that you can put an iOS device into that prevents switching apps, but it requires that the user set it up, and it locks the device to just that app.


问:
Mechanism to Constantly Check HTTP Endpoint (every 10 seconds) using Java Spring
Lets say there's an external HTTP Endpoint (REST based) which is updating its data every ten seconds.

How to create a mechanism using Java 1.7 and Spring MVC for REST (this is not Spring Boot) that constantly calls the Endpoint and returns the results?

Is there an API to use to do this?

e.g.

Call a proper HTTP GET request

```<code>https://api.app.com/v1/exchangeRates/Europe?name=acme_company
</code>```

returns:

```<code>{ "name" : "acme_company", "price" : "20 EUR"}
</code>```

but the price changes every 10 seconds?

What options are out there to use when using Java 1.7 and Spring 4?

答:
Spring provides an @Scheduled annotation

```<code>@Scheduled(fixedRate=5000)
public void doSomething() {
    // something that should execute periodically
}
</code>```

More information here.

Body:
Lets say there's an external HTTP Endpoint (REST based) which is updating its data every ten seconds.

How to create a mechanism using Java 1.7 and Spring MVC for REST (this is not Spring Boot) that constantly calls the Endpoint and returns the results?

Is there an API to use to do this?

e.g.

Call a proper HTTP GET request

https://api.app.com/v1/exchangeRates/Europe?name=acme_company

returns:

{ "name" : "acme_company", "price" : "20 EUR"}

but the price changes every 10 seconds?

What options are out there to use when using Java 1.7 and Spring 4?

Body:
Spring provides an @Scheduled annotation

@Scheduled(fixedRate=5000)
public void doSomething() {
    // something that should execute periodically
}

More information here.


问:
C#, variable value as a part of an object name?
For example i have a player object with a list of suits of cards it has.

```<code>player.card[0] = "diamonds";
player.card[1] = "clubs";
player.card[2] = "spades";
etc...
</code>```

also i have 4 hidden pictureboxes with an image of suites ( pb_spades , pb_hearts m etc. )

and another 4 pictureboxs ( pb_playerCard1 , pb_playerCard2 , etc. ) to which I have to assign an image from a hidden pb corresponding to the suit of card the player object has.

Therefor

```<code>if ( player.card[0] == "diamonds" ) { pb_playerCard1.Image = pb_diamonds.Image; }
</code>```

of course, doing it all with IFs would take quite a long time... Can I somehow use variable value as a part of an objects name?

kinda

```<code>for (int i = 1; i != 5; i++)
{
pb_playerCard+'i'.Image = pb_+'player.card[i+1]'.Image;
}
</code>```

答:
Create a class Suite that has all properties, like this:

```<code>class Suite {
   public string Name { get; set; }
   public Image Image { get; set; }
</code>```

and then create a static object for each color:

```<code>   public static Diamonds = new Suite { Name = "Diamonds", Image = Resources.DiamondImage };
   // ...

 }
</code>```

Now you can use Suite.Diamonds.

Even better is to use a Flyweight pattern to avoid the static fields. You use the Flyweight to implement the Card class.

Body:
For example i have a player object with a list of suits of cards it has.

player.card[0] = "diamonds";
player.card[1] = "clubs";
player.card[2] = "spades";
etc...

also i have 4 hidden pictureboxes with an image of suites ( pb_spades , pb_hearts m etc. )

and another 4 pictureboxs ( pb_playerCard1 , pb_playerCard2 , etc. ) to which I have to assign an image from a hidden pb corresponding to the suit of card the player object has.

Therefor

if ( player.card[0] == "diamonds" ) { pb_playerCard1.Image = pb_diamonds.Image; }

of course, doing it all with IFs would take quite a long time... Can I somehow use variable value as a part of an objects name?

kinda

for (int i = 1; i != 5; i++)
{
pb_playerCard+'i'.Image = pb_+'player.card[i+1]'.Image;
}

Body:
Create a class Suite that has all properties, like this:

class Suite {
   public string Name { get; set; }
   public Image Image { get; set; }

and then create a static object for each color:

   public static Diamonds = new Suite { Name = "Diamonds", Image = Resources.DiamondImage };
   // ...

 }

Now you can use Suite.Diamonds.

Even better is to use a Flyweight pattern to avoid the static fields. You use the Flyweight to implement the Card class.


问:
No such file or directory mysql
Hello I am getting the following error while trying to connect to a database with mysql with php:

```<code>Warning: mysqli_connect(): (HY000/2002): No such file or directory in /Users/minimoe/db.php on line 5
</code>```

Here is the code that I ran:

```<code>$db = mysqli_connect('localhost','','','scheduler');
echo $db;
</code>```

(I've also attempted to replace the second parameter with 'root' as well but this changes nothing)
Edit:
I've also tried: mysqli_connect('localhost','minimoe','','scheduler'); but this hasn't worked

I've also tried: mysqli_connect('localhost','root','','scheduler'); but this hasn't worked
 / end of edit

So my question is: How can I connect to my database using mysql and php and fix this error?

Some info:

1. I am using php built in web server by running php -S localhost:3306

2. php version 5.6.30

3. Server version: 5.7.18 Homebrew

Extra info:

However I ran the following code using postgresql (I created a test db in psql) and it worked fine:

```<code> $db = pg_connect("host=localhost dbname=scheduler user=minimoe password=''");
</code>```

 Because I am fairly certain this question will be flagged as a duplicate, even though I haven't found an answer that will work for me, yet (although I have not googled the entirety of the vast web

I have tested several other similar questions answers in stack overflow to no avail, yet.

Some answers in other stack overflows that hasn't worked for me after trying them:

1. replacing mysql_connect with mysqli_connect (because I'm already using this)

2. replacing localhost with http://127.0.0.1/, this doesn't work for me either

3. replacing mysqli_connect with mysql() function

I hope I've provided enough info, comment if you need anything else to solve this. Thank you

答:
You must have set a password while setting up mysql. If you did so, try:</p>

```<code>$db = mysqli_connect('localhost','root','YOUR_PASSWORD','scheduler');
</code>```

Title: No such file or directory mysql

Body:
Hello I am getting the following error while trying to connect to a database with mysql with php:

Warning: mysqli_connect(): (HY000/2002): No such file or directory in /Users/minimoe/db.php on line 5

Here is the code that I ran:

$db = mysqli_connect('localhost','','','scheduler');
echo $db;

(I've also attempted to replace the second parameter with 'root' as well but this changes nothing)
Edit:
I've also tried: mysqli_connect('localhost','minimoe','','scheduler'); but this hasn't worked

I've also tried: mysqli_connect('localhost','root','','scheduler'); but this hasn't worked
 / end of edit

So my question is: How can I connect to my database using mysql and php and fix this error?

Some info:

1. I am using php built in web server by running php -S localhost:3306

2. php version 5.6.30

3. Server version: 5.7.18 Homebrew

Extra info:

However I ran the following code using postgresql (I created a test db in psql) and it worked fine:

 $db = pg_connect("host=localhost dbname=scheduler user=minimoe password=''");

 Because I am fairly certain this question will be flagged as a duplicate, even though I haven't found an answer that will work for me, yet (although I have not googled the entirety of the vast web

I have tested several other similar questions answers in stack overflow to no avail, yet.

Some answers in other stack overflows that hasn't worked for me after trying them:

1. replacing mysql_connect with mysqli_connect (because I'm already using this)

2. replacing localhost with http://127.0.0.1/, this doesn't work for me either

3. replacing mysqli_connect with mysql() function

I hope I've provided enough info, comment if you need anything else to solve this. Thank you

Body:
You must have set a password while setting up mysql. If you did so, try:

$db = mysqli_connect('localhost','root','YOUR_PASSWORD','scheduler');


问:
Node.js Unhandled promise rejection
I'm trying to make a login with node.js using passport but I'm having a problem when a username that's not in the DB tries to login. I get the following error (node:9708) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: deferred.resolve is not a function.

Login Function:

```<code>exports.login = function(username, password) {
    var deferred = Q.defer;

    MongoClient.connect(mongodbUrl, function(err, db) {
        var collection = db.collection('users');

        collection.findOne({'username' : username}).then(function(result) {
            if (result === null) {
                console.log('User not found:', username);
                deferred.resolve(false);
            } else {
                var hash = result.password;
                console.log('User found:', username);

                if (bcrypt.compareSync(password, hash)) {
                    deferred.resolve(result);
                } else {
                    console.log('Authentication for ' + username + 'failed');
                    deferred.resolve(false);
                }
            }

            db.close();
        });
    }).catch(err => console.log(err));

    return deferred.promise;
};
</code>```

Passport.use Function:

```<code>passport.use('local-signin', new LocalStrategy({passReqToCallback : true}, function(req, username, password, done) {
    funct.login(username, password).then(function(user) {
        if (user) {
            console.log(user.username + 'logged in');
            req.session.success = 'Welcome, ' + user.username + '!';
            done(null, user);
        }

        if (!user) {
            console.log('Failed login attempt');
            req.session.error = 'Your Password or Username is incorrect! Please try again.';
            done(null, user);
        }
    }).fail(function(err) {
        console.log(err.body);
    });
}));
</code>```

答:
Promises can be resolved or rejected. You have to program for both cases. Add a .catch to the end of your code like so:</p>

```<code>collection.findOne({'username' : username}).then().catch(err => console.log(err))
</code>```

Title: Node.js Unhandled promise rejection

Body:
I'm trying to make a login with node.js using passport but I'm having a problem when a username that's not in the DB tries to login. I get the following error (node:9708) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: deferred.resolve is not a function.

Login Function:

exports.login = function(username, password) {
    var deferred = Q.defer;

    MongoClient.connect(mongodbUrl, function(err, db) {
        var collection = db.collection('users');

        collection.findOne({'username' : username}).then(function(result) {
            if (result === null) {
                console.log('User not found:', username);
                deferred.resolve(false);
            } else {
                var hash = result.password;
                console.log('User found:', username);

                if (bcrypt.compareSync(password, hash)) {
                    deferred.resolve(result);
                } else {
                    console.log('Authentication for ' + username + 'failed');
                    deferred.resolve(false);
                }
            }

            db.close();
        });
    }).catch(err => console.log(err));

    return deferred.promise;
};

Passport.use Function:

passport.use('local-signin', new LocalStrategy({passReqToCallback : true}, function(req, username, password, done) {
    funct.login(username, password).then(function(user) {
        if (user) {
            console.log(user.username + 'logged in');
            req.session.success = 'Welcome, ' + user.username + '!';
            done(null, user);
        }

        if (!user) {
            console.log('Failed login attempt');
            req.session.error = 'Your Password or Username is incorrect! Please try again.';
            done(null, user);
        }
    }).fail(function(err) {
        console.log(err.body);
    });
}));

Body:
Promises can be resolved or rejected. You have to program for both cases. Add a .catch to the end of your code like so:

collection.findOne({'username' : username}).then().catch(err => console.log(err))


问:
Merging two datasets using the last value of a string
I found the following code to pull off the last value in a string:

```<code>tail(strsplit("The quick brown fox",split = " ")[[1]],1)
</code>```

which correctly returns the value of "fox". I'm trying to apply this same principle to a text variable using the following code:

```<code>policy.data$LastName <- tail(strsplit(policy.data$Name,split = " ")[[1]],1)
</code>```

but this code gives me the following error:

Error in strsplit(policy.data$Name, split = " ") : non-character argument*

I do not understand why the code works when the string is specified but not with a text variable. I have a data set that has a full first and last name ("Jane Doe") and a data set that has the first initial and last name ("J Doe").  What I am really trying to do is merge the two datasets using last name ("Doe") so if there is a way to do this without creating a separate variable called "LastName" in each dataset, I would be very interested in that solution as well.

答:
Convert   policy.data$LastName to character using as.character():

```<code>   policy <- data.frame(LastName=c("The quick brown fox"))
   policy
    policy$LastName # it's considered as factor not character
  # so convert to character

  as.character(policy$LastName)
  tail(strsplit(as.character(policy$LastName),split = " ")[[1]],1)
</code>```

Try it online

output:

```<code>        LastName
   1 The quick brown fox
  [1] The quick brown fox
  Levels: The quick brown fox
  [1] "The quick brown fox"
  [1] "fox"
</code>```

Body:
I found the following code to pull off the last value in a string:

tail(strsplit("The quick brown fox",split = " ")[[1]],1)

which correctly returns the value of "fox". I'm trying to apply this same principle to a text variable using the following code:

policy.data$LastName <- tail(strsplit(policy.data$Name,split = " ")[[1]],1)

but this code gives me the following error:

Error in strsplit(policy.data$Name, split = " ") : non-character argument*

I do not understand why the code works when the string is specified but not with a text variable. I have a data set that has a full first and last name ("Jane Doe") and a data set that has the first initial and last name ("J Doe").  What I am really trying to do is merge the two datasets using last name ("Doe") so if there is a way to do this without creating a separate variable called "LastName" in each dataset, I would be very interested in that solution as well.

Body:
Convert   policy.data$LastName to character using as.character():

   policy <- data.frame(LastName=c("The quick brown fox"))
   policy
    policy$LastName # it's considered as factor not character
  # so convert to character

  as.character(policy$LastName)
  tail(strsplit(as.character(policy$LastName),split = " ")[[1]],1)

Try it online

output:

        LastName
   1 The quick brown fox
  [1] The quick brown fox
  Levels: The quick brown fox
  [1] "The quick brown fox"
  [1] "fox"


问:
Facing issues when writing multiple rows to a csv file in python 3.6
My requirement is to read all the files in the directory and get the length of the file, and word count of each file and store it as a row in a CSV file.

Following is my Python code.
      #Iterating through the list directory

```<code> for filename in os.listdir(passedArgument1):
  #Opening each file in the directory
   with open(passedArgument1+filename,"r",encoding="ISO-8859-1") as f:
    actualWordCount = 0
  # Getting the file Size
    fileSize=os.path.getsize(passedArgument1+filename)
    for line in f:
  # Getting the word count
      actualWordCount+=writeToExcelFile(line)
  # Writing to a file
      with open('output.csv', 'w') as csvfile:
       spamwriter = csv.writer(csvfile, delimiter=' ', quotechar='|',   quoting=csv.QUOTE_MINIMAL)
       spamwriter.writerow([actualWordCount,fileSize])
</code>```

When I am writing to the CSV file, it writes only one record that is the last file. I have checked writerows method but not sure how it works.Any help is appreciated on achieving my requirement in Python 3.x.

答:
Try this?</p>

```<code>csvfile = open('output.csv', 'w')
# do your loop here and write/append to csvfile
csvfile.close()
</code>```

Body:
My requirement is to read all the files in the directory and get the length of the file, and word count of each file and store it as a row in a CSV file.

Following is my Python code.
      #Iterating through the list directory

 for filename in os.listdir(passedArgument1):
  #Opening each file in the directory
   with open(passedArgument1+filename,"r",encoding="ISO-8859-1") as f:
    actualWordCount = 0
  # Getting the file Size
    fileSize=os.path.getsize(passedArgument1+filename)
    for line in f:
  # Getting the word count
      actualWordCount+=writeToExcelFile(line)
  # Writing to a file
      with open('output.csv', 'w') as csvfile:
       spamwriter = csv.writer(csvfile, delimiter=' ', quotechar='|',   quoting=csv.QUOTE_MINIMAL)
       spamwriter.writerow([actualWordCount,fileSize])

When I am writing to the CSV file, it writes only one record that is the last file. I have checked writerows method but not sure how it works.Any help is appreciated on achieving my requirement in Python 3.x.

Body:
Try this?

csvfile = open('output.csv', 'w')
# do your loop here and write/append to csvfile
csvfile.close()


问:
How To Tell If User Is Signed Into Site From Socket.io Event
I am using express session to log users into my site. When they are logged in I can access their req.user which contains info about the user such as username, account age, ect.

The problem is that I need to be able to check if the user is signed in, inside of a socket.io event handler

```<code>io.sockets.on('connection', function (socket) {
   console.log(socket.request.session.id);
   io.sockets.on('message', function (socket) {
       //check if user is logged on here and if so broadcast the message to sockets
   })
});
</code>```

As you can see I would need to be able to access req.user which I can't because it's inside a socket.io event handler, is there any other way I can tell if the user is logged in?

答:
Hmm...to be honest I'm still not 100% clear what you are doing, but instead of using the user you can also look at directly using the sockets (since you don't seem to need other user data aside from their login status):

1) You are trying to send a message from a connected socket to all other connected sockets (i.e. from a logged in user to other logged in users)

In this case, you will probably be instantiating a socket somewhere in your client-side javascript, such that each new client will open a new socket.

So, to ensure that all sockets available are for logged in clients, you can place the code for opening a new socket inside your login function, and simply use the server to broadcast to all connected sockets except the sender:

```<code>io.sockets.on('connection', function (socket) {
    console.log(socket.request.session.id);
    io.sockets.on('message', function (data) {
        //check if user is logged on here and if so broadcast the message to sockets
      socket.broadcast.emit('message', data);
    })
</code>```

});

2) You are trying to send a message from one socket to another connected socket (i.e. from one user to another specific logged in user)

Similarly, have your socket opened only during/after the login process.

Then, on your client side, you can do something like:

socket.emit('message', "target_id");

so that on the server side you can do:

```<code>socket.on("message", function(id) {
       socket.to(id).emit("message");
}
</code>```

Does this help in any way?

Body:
I am using express session to log users into my site. When they are logged in I can access their req.user which contains info about the user such as username, account age, ect.

The problem is that I need to be able to check if the user is signed in, inside of a socket.io event handler

io.sockets.on('connection', function (socket) {
   console.log(socket.request.session.id);
   io.sockets.on('message', function (socket) {
       //check if user is logged on here and if so broadcast the message to sockets
   })
});

As you can see I would need to be able to access req.user which I can't because it's inside a socket.io event handler, is there any other way I can tell if the user is logged in?

Body:
Hmm...to be honest I'm still not 100% clear what you are doing, but instead of using the user you can also look at directly using the sockets (since you don't seem to need other user data aside from their login status):

1) You are trying to send a message from a connected socket to all other connected sockets (i.e. from a logged in user to other logged in users)

In this case, you will probably be instantiating a socket somewhere in your client-side javascript, such that each new client will open a new socket.

So, to ensure that all sockets available are for logged in clients, you can place the code for opening a new socket inside your login function, and simply use the server to broadcast to all connected sockets except the sender:

io.sockets.on('connection', function (socket) {
    console.log(socket.request.session.id);
    io.sockets.on('message', function (data) {
        //check if user is logged on here and if so broadcast the message to sockets
      socket.broadcast.emit('message', data);
    })

});

2) You are trying to send a message from one socket to another connected socket (i.e. from one user to another specific logged in user)

Similarly, have your socket opened only during/after the login process.

Then, on your client side, you can do something like:

socket.emit('message', "target_id");

so that on the server side you can do:

socket.on("message", function(id) {
       socket.to(id).emit("message");
}

Does this help in any way?