问:
Kinect V2 read Depth issue
The following C++ code is given which continuously fetches the latest frame from a Kinect 2.

```<code>#include <Kinect.h>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <Windows.h>
#include <iostream>
using namespace std;

const int width = 512;
const int height = 424;
const int colorwidth = 1920;
const int colorheight = 1080;
IDepthFrameReader* reader;     // Kinect depth data source
IKinectSensor* sensor = nullptr;
int main(int argc, char* argv[]) {
    if (FAILED(GetDefaultKinectSensor(&sensor))) {
        return 19;
    }
    if (sensor) {
        sensor->Open();
        IDepthFrameSource* framesource = NULL;
        sensor->get_DepthFrameSource(&framesource);
        framesource->OpenReader(&reader);
        if (framesource) {
            framesource->Release();
            framesource = NULL;
        }
        IDepthFrame* frame = NULL;
        if (SUCCEEDED(reader->AcquireLatestFrame(&frame))) {
            cout << "not bad";
            getchar();
            return 100;
        }
        else{
            cout << "not found";
            getchar();
            return 23;
        }
    }
    else {
        return -1;
    }
}
</code>```

In fact, if I connect Kinect to my laptop or not, the output is no changing and it is: "not found". When I connect Kinect and run the program, the lights of Kinect turns on. In some ready codes, Kinect works correctly. Where is the problem?

答:
You should check out the returned error code for AcquireLatestFrame, maybe it can tell you what's the problem.

Here's a tip: maybe, when you call AcquireLatestFrame, the frame is not available yet. So put this call into a loop, sooner or later the frame will be available.

Title: Kinect V2 read Depth issue

Body:
The following C++ code is given which continuously fetches the latest frame from a Kinect 2.

#include <Kinect.h>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <Windows.h>
#include <iostream>
using namespace std;

const int width = 512;
const int height = 424;
const int colorwidth = 1920;
const int colorheight = 1080;
IDepthFrameReader* reader;     // Kinect depth data source
IKinectSensor* sensor = nullptr;
int main(int argc, char* argv[]) {
    if (FAILED(GetDefaultKinectSensor(&sensor))) {
        return 19;
    }
    if (sensor) {
        sensor->Open();
        IDepthFrameSource* framesource = NULL;
        sensor->get_DepthFrameSource(&framesource);
        framesource->OpenReader(&reader);
        if (framesource) {
            framesource->Release();
            framesource = NULL;
        }
        IDepthFrame* frame = NULL;
        if (SUCCEEDED(reader->AcquireLatestFrame(&frame))) {
            cout << "not bad";
            getchar();
            return 100;
        }
        else{
            cout << "not found";
            getchar();
            return 23;
        }
    }
    else {
        return -1;
    }
}

In fact, if I connect Kinect to my laptop or not, the output is no changing and it is: "not found". When I connect Kinect and run the program, the lights of Kinect turns on. In some ready codes, Kinect works correctly. Where is the problem?


来源: stackexchange

问:
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>```

答:
There's a couple of problems I can see here - you are posting to add/team/add.html and not hitting your post handler. You don't need the action attribute as you're posting to the same endpoint;

```<code><form:form method="POST" modelAttribute="team" >
</code>```

Secondly your are injecting the countries as a map, so these are ID/display values which works great for key/value pairs and for binding a value to a string field. In this case, Spring is trying to bind your country ID (String) to the team.country(Country) field which will fail. To help Spring out you need a databinder; in your controller add;

```<code>@InitBinder
public void initBinder (WebDataBinder binder) {
    binder.registerCustomEditor(Country.class, new CountryEditor());
}
</code>```

and create the property editor class;

```<code>public class CountryEditor extends PropertyEditorSupport {
    @Override
    public void setValue(Object value) {
        super.setValue(value);
    }

    public String getAsText() {
        if (getValue() == null) return null;
        return ((Country) getValue()).getName();
    };

    public void setAsText(String text) throws IllegalArgumentException {
        if (text != null) {
            Country country = // something like filterService.getCountryById(text);
            setValue(country);
        }
    };
}
</code>```

There's more information in the Spring documentation

ContentLicense: CC BY-SA 3.0

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

Body:
There's a couple of problems I can see here - you are posting to add/team/add.html and not hitting your post handler. You don't need the action attribute as you're posting to the same endpoint;

<form:form method="POST" modelAttribute="team" >

Secondly your are injecting the countries as a map, so these are ID/display values which works great for key/value pairs and for binding a value to a string field. In this case, Spring is trying to bind your country ID (String) to the team.country(Country) field which will fail. To help Spring out you need a databinder; in your controller add;

@InitBinder
public void initBinder (WebDataBinder binder) {
    binder.registerCustomEditor(Country.class, new CountryEditor());
}

and create the property editor class;

public class CountryEditor extends PropertyEditorSupport {
    @Override
    public void setValue(Object value) {
        super.setValue(value);
    }

    public String getAsText() {
        if (getValue() == null) return null;
        return ((Country) getValue()).getName();
    };

    public void setAsText(String text) throws IllegalArgumentException {
        if (text != null) {
            Country country = // something like filterService.getCountryById(text);
            setValue(country);
        }
    };
}

There's more information in the Spring documentation


问:
django {% if user.groups == 'FC' %} doens't work
I'm making a website using django.

{% if user.groups == 'FC' %} doesn't work in my template.I have groups like that.

For example, one of my users(username is 'hong) belongs to 'FC' group as you see below.

But,

```<code>{% if user.groups == 'FC' %}
      <li><a href="{% url 'register' %}">register form</a></li>
      <li><a href="{% url 'mypage' %}">fc's my page</a></li>
{% else %}
 <li><a href="{% url 'PT_mypage' %}">fitness' my page</a></li>
{% endif %}
</code>```

if user.groups == ' '  doesn't work.

How I check the users' group? I have to distinguish the users by groups.

答:
try below</p>

```<code>{% for group in  request.user.groups.all %}
{%  if 'FC' == group.name %}
   <<< write your code that you want >>>
{% endif %}
{% endfor %}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm making a website using django.

{% if user.groups == 'FC' %} doesn't work in my template.I have groups like that.

For example, one of my users(username is 'hong) belongs to 'FC' group as you see below.

But,

{% if user.groups == 'FC' %}

register form

fc's my page

{% else %}

fitness' my page

{% endif %}

if user.groups == ' '  doesn't work.

How I check the users' group? I have to distinguish the users by groups.

Body:
try below

{% for group in  request.user.groups.all %}
{%  if 'FC' == group.name %}
   <<< write your code that you want >>>
{% endif %}
{% endfor %}


问:
How to include a specific font family not found at Google Fonts?
I want to use a font type called Daniel, but it's not found at Google Fonts.
Is there any way to use this type of font at my web site?  </p>

答:
You have to download fonts files and delcare a font-face in your css.
You can check www.w3schools.com for more details. Here is an example :</p>

```<code>@font-face {
    font-family: Montserrat;
    src: url("./fonts/Montserrat-Regular.otf");
    font-weight: normal;
    font-style: normal;
}@font-face {
    font-family: Montserrat;
    src: url("./fonts/Montserrat-Bold.otf");
    font-weight: bold;
    font-style: normal;
}@font-face {
    font-family: Montserrat Light;
    src: url("./fonts/Montserrat-Light.otf");
    font-weight: normal;
    font-style: normal;
}@font-face {
    font-family: Montserrat Thin;
    src: url("./fonts/Montserrat-Thin.otf");
    font-weight: normal;
    font-style: normal;
}@font-face {
    font-family: Montserrat Medium;
    src: url("./fonts/Montserrat-Medium.otf");
    font-weight: normal;
    font-style: normal;
}@font-face {
    font-family: Montserrat SemiBold;
    src: url("./fonts/Montserrat-SemiBold.otf");
    font-weight: normal;
    font-style: normal;
}
</code>```

Body:
You have to download fonts files and delcare a font-face in your css.
You can check www.w3schools.com for more details. Here is an example :

@font-face {
    font-family: Montserrat;
    src: url("./fonts/Montserrat-Regular.otf");
    font-weight: normal;
    font-style: normal;
}@font-face {
    font-family: Montserrat;
    src: url("./fonts/Montserrat-Bold.otf");
    font-weight: bold;
    font-style: normal;
}@font-face {
    font-family: Montserrat Light;
    src: url("./fonts/Montserrat-Light.otf");
    font-weight: normal;
    font-style: normal;
}@font-face {
    font-family: Montserrat Thin;
    src: url("./fonts/Montserrat-Thin.otf");
    font-weight: normal;
    font-style: normal;
}@font-face {
    font-family: Montserrat Medium;
    src: url("./fonts/Montserrat-Medium.otf");
    font-weight: normal;
    font-style: normal;
}@font-face {
    font-family: Montserrat SemiBold;
    src: url("./fonts/Montserrat-SemiBold.otf");
    font-weight: normal;
    font-style: normal;
}


问:
OMNeT++ cPacket as std::bitset to apply Reed-Solomon encoding
Having a packet

```<code>cPacket *pk
</code>```

how can I obtain the bit representation of it? For example, in the form of

```<code>std::bitset<pk->getBitLength()> pk_bits;
</code>```

My final goal is to apply an encoding scheme to the packet, i.e. Reed-Solomon encoding.

答:
As @rcgldr commented, a simple cPacket in itself does not hold any data, at least not in the sense of how real packets do. And it's not necessary in most models, because they operate on a higher, more abstract level, which makes working with them easier, and running them faster.

The information that travels between the nodes of the simulation is what you put in the fields of your messages (preferably custom made using the message compiler of OMNeT++, from .msg files).

This is, however, completely independent of the bitLength/byteLength properties of the cPacket class, which is just a number that can be set to any value for any message.

You can, of course, choose to model a realistic protocol by adding fields to your message that correspond to a real(istic) network protocol header, like TCP or IP, or even something you just made up. But this still doesn't provide any (reliable) byte-sequence-like access to the contents, because it is not always trivial how the individual fields should be serialized into simple octets.

To achieve this, INET for example has separate *[De]Serializer classes for a number of its custom message types. You can do the same with yours if you want.

A simpler solution would be to represent any payload in the packet by adding an std::vector<unsigned char> or even an std::bitset if you prefer that. And just treat that part separately from the easily accessible fields, applying any encoding on its content.

And finally, just like with any question like "how to add an encryption library to a simulation and use it to transform packets": Are you sure that adding a real byte-by-byte encoder/serializer/etc. to a simulation is the right choice to achieve what you're trying to do? I mean, it could be, and it's possible, but there might be better/simpler/faster ways. In terms of modeling.

Body:
Having a packet

cPacket *pk

how can I obtain the bit representation of it? For example, in the form of

std::bitset<pk->getBitLength()> pk_bits;

My final goal is to apply an encoding scheme to the packet, i.e. Reed-Solomon encoding.


问:
Jar File - main class not found
So I have the following project Structure:
I have a package called "com.github.liketechnik". My main class is Build in this package ("com.github.liketechnik.Build").

I programmatically put the compiled classes from there into a jar file with a correct manifest, e. g. containing a version attribute and a Main-Class entry "com.github.liketechnik.Build". The classes inside the jar are contained under "com/github/liketechnik/Build.class".

When running  java -jar output.jar it fails directly: "Error: Mainclass com.github.liketechnik.Build could not be found or loaded" (translated from german). When running the class directly via java -cp build/main com.github.liketechnik.Build (e. g. the class files directly, outside the jar), it works without proplems.

I tried this hours and also searched every single file for typos, so I appreciate any help with this problem as all other threads concerning such problems did not help with mine. If you need any more Information or the sourcecode directly I've no problems with giving this to you.

EDIT: Added structure of jar file.

The jar file has the following structure:

one dir "META-INF" containing "MANIFEST.MF" with the mentioned entries.

one dir structure "com/github/liketechnik/Build.class" (for example, contains other classes (in subpackages) too.

Manifest:

```<code>Manifest-Version: 1.0
Main-Class: com.github.liketechnik.Build
</code>```

Build.java:

```<code>package com.github.liketechnik;

public class Build {

    public static void main(String[] args) {
        System.out.println("Hi");
    }
}
</code>```

Output when manually running: Hi (as expected)
Output when running from jar: Fehler: Hauptklasse com.github.liketechnik.Build konnte nicht gefunden oder geladen werden (Why?)

答:
Ok, seems like creating .jar archives programmatically is not as easy as it seems. It seems like beneath the .zip specifications  one needs to handle (see this question) is another caveat, so the entries need to be added following the directory hierachy.

Example:
Assume you have directories a and b, b containing files test.class toll.class, you have to first add a, then b and then the files inside b . Otherwise it won't work.

Title: Jar File - main class not found

Body:
So I have the following project Structure:
I have a package called "com.github.liketechnik". My main class is Build in this package ("com.github.liketechnik.Build").

I programmatically put the compiled classes from there into a jar file with a correct manifest, e. g. containing a version attribute and a Main-Class entry "com.github.liketechnik.Build". The classes inside the jar are contained under "com/github/liketechnik/Build.class".

When running  java -jar output.jar it fails directly: "Error: Mainclass com.github.liketechnik.Build could not be found or loaded" (translated from german). When running the class directly via java -cp build/main com.github.liketechnik.Build (e. g. the class files directly, outside the jar), it works without proplems.

I tried this hours and also searched every single file for typos, so I appreciate any help with this problem as all other threads concerning such problems did not help with mine. If you need any more Information or the sourcecode directly I've no problems with giving this to you.

EDIT: Added structure of jar file.

The jar file has the following structure:

one dir "META-INF" containing "MANIFEST.MF" with the mentioned entries.

one dir structure "com/github/liketechnik/Build.class" (for example, contains other classes (in subpackages) too.

Manifest:

Manifest-Version: 1.0
Main-Class: com.github.liketechnik.Build

Build.java:

package com.github.liketechnik;

public class Build {

    public static void main(String[] args) {
        System.out.println("Hi");
    }
}

Output when manually running: Hi (as expected)
Output when running from jar: Fehler: Hauptklasse com.github.liketechnik.Build konnte nicht gefunden oder geladen werden (Why?)


问:
Java String Match returning false even if its true
temp.matches this regular expression is returning false even though there is proper matching expression (SOUTH, NORTH, )

temp value after execution SOUTH, NORTH,

```<code>import java.util.Arrays;
public class DirReduction {

    public static String[] dirReduc(String[] arr) {

        boolean check=false;
        String inputToString =Arrays.toString(arr);
        String str1 = inputToString.replace("]", ", ").replace("[", ""),temp;
        do {
            temp=str1.replaceAll("NORTH, SOUTH, " , "").replaceAll("SOUTH, NORTH, " , "").replaceAll("EAST, WEST, " , "").replaceAll("WEST, EAST, " , "");
            check = temp.matches(".*\\b(NORTH, SOUTH, |SOUTH, NORTH, |EAST, WEST, |WEST, EAST, )\\b.*");
            System.out.println(temp);
            str1=temp;
        }while(check);

        String[] splitArray = str1.split(", ");
        String[] fi =new String[splitArray.length];
        int i=0;
        for(String item:splitArray) {
            fi[i++]=item;
        }
        System.out.println(Arrays.toString(fi));
        return fi;
    }

    public static void main(String[] args) {
        String[] input = new String[] { "NORTH","SOUTH","SOUTH","EAST","WEST","NORTH"};
        dirReduc(input);
    }
}
</code>```

答: I assume your replaceAll statement does not replace anything. Your input string does not have spaces after the comma, but your search mask has a space. So nothing will be found to be replaced.</p>

Body:
temp.matches this regular expression is returning false even though there is proper matching expression (SOUTH, NORTH, )

temp value after execution SOUTH, NORTH,

import java.util.Arrays;
public class DirReduction {

    public static String[] dirReduc(String[] arr) {

        boolean check=false;
        String inputToString =Arrays.toString(arr);
        String str1 = inputToString.replace("]", ", ").replace("[", ""),temp;
        do {
            temp=str1.replaceAll("NORTH, SOUTH, " , "").replaceAll("SOUTH, NORTH, " , "").replaceAll("EAST, WEST, " , "").replaceAll("WEST, EAST, " , "");
            check = temp.matches(".*\\b(NORTH, SOUTH, |SOUTH, NORTH, |EAST, WEST, |WEST, EAST, )\\b.*");
            System.out.println(temp);
            str1=temp;
        }while(check);

        String[] splitArray = str1.split(", ");
        String[] fi =new String[splitArray.length];
        int i=0;
        for(String item:splitArray) {
            fi[i++]=item;
        }
        System.out.println(Arrays.toString(fi));
        return fi;
    }

    public static void main(String[] args) {
        String[] input = new String[] { "NORTH","SOUTH","SOUTH","EAST","WEST","NORTH"};
        dirReduc(input);
    }
}


问:
Export layer with hue and saturation mask to PNG with javascript
i'm working on the script that will export all layers in PNG but I have some problem with layer that has Hue & saturation or layer mask. It consider two different layers and export 2 images. Is there anyway to export layer to image with layer mask on it ?
Thanks</p>

答:
What you will have to so is destructive In that exporting the layers to pngs you will alter the original .PSD.

What I recommend you do in this case it to flatten the layer with the hue & saturation mask on it. This can be done by applying the mask or more easily adding a new blank layer above the hue & saturation and merge down. That way you'll only get one image for that layer.

Do NOT save over your original .psd or you'll lose the h&s layer

```<code>loop over all image layers
  is it an image layer? (export as normal)
  is it a hue & saturation layer? - Add new layer above, merge it down
  export current layer as .png
</code>```

Body:
What you will have to so is destructive In that exporting the layers to pngs you will alter the original .PSD.

What I recommend you do in this case it to flatten the layer with the hue & saturation mask on it. This can be done by applying the mask or more easily adding a new blank layer above the hue & saturation and merge down. That way you'll only get one image for that layer.

Do NOT save over your original .psd or you'll lose the h&s layer

loop over all image layers
  is it an image layer? (export as normal)
  is it a hue & saturation layer? - Add new layer above, merge it down
  export current layer as .png


问:
Python Selenium Script Crashes After Adding If Else
I just need a little help as i have already developed my small script but adding a new functionality is creating problems. The problem is with adding If else statement. The script crashes if it does not find any element so I want to bypass it by placing an ifelse condition, i.e. if the element is present it should click the button else it should move on to the next line.

Below is my code

```<code>driver.find_element_by_css_selector('input.whsOnd.zHQkBf').send_keys(password)

    time.sleep(2)
    driver.find_element_by_id("passwordNext").click()
    time.sleep(2)

    driver.get(comment_url)
    time.sleep(2)

    driver.find_element_by_xpath("//button[@class='yt-uix-button yt-uix-button-size-default yt-uix-button-default yt-uix-button-empty yt-uix-button-has-icon no-icon-markup comment-action-buttons-renderer-thumb yt-uix-sessionlink sprite-comment-actions sprite-like i-a-v-sprite-like']").click()
    time.sleep(2)
    driver.find_element_by_xpath("//button[@class='yt-uix-button yt-uix-button-size-small yt-uix-button-link comment-renderer-reply comment-simplebox-trigger']").click()
    time.sleep(2)
    driver.find_element_by_class_name("comment-simplebox-text").send_keys(comment)
    time.sleep(2)
    driver.find_element_by_xpath("//button[@class='yt-uix-button yt-uix-button-size-default yt-uix-button-primary yt-uix-button-empty comment-simplebox-submit yt-uix-sessionlink']").click()
    time.sleep(2)
</code>```

The code i want to add is :

```<code>if driver.find_element_by_xpath ...... exists,
then
   driver.find_element_by_xpath("//*[@class=\"leaflet-control-zoom-in\"]").click()
   driver.find_element_by_xpath("//*[@class=\"leaflet-control-zoom-in\"]").click()
   driver.find_element_by_xpath("//*[@class=\"leaflet-control-zoom-in\"]").click()
   driver.find_element_by_xpath("//*[@class=\"leaflet-control-zoom-in\"]").click()
   print("Zoom in 4x. Successful")
else
   print("Element does not exist, it failed.")
</code>```

Whether I add only ( if) or if (if driver.find_element_by_xpath("") the script crashes within miliseconds and doesnt even open.

答:
You need to try to catch an exception, and if you  catch it, do something in except block. Speaking about your scenario you probably need to catch selenium.common.exceptions.NoSuchElementException. So the code may look like:

```<code>from selenium.common.exceptions import NoSuchElementException

try:
   driver.find_element_by_xpath("//*[@class=\"leaflet-control-zoom-in\"]").click()
   driver.find_element_by_xpath("//*[@class=\"leaflet-control-zoom-in\"]").click()
   driver.find_element_by_xpath("//*[@class=\"leaflet-control-zoom-in\"]").click()
   driver.find_element_by_xpath("//*[@class=\"leaflet-control-zoom-in\"]").click()
   print("Zoom in 4x. Successful")
except NoSuchElementException:
   print("Element does not exist, it failed.")
</code>```

Body:
I just need a little help as i have already developed my small script but adding a new functionality is creating problems. The problem is with adding If else statement. The script crashes if it does not find any element so I want to bypass it by placing an ifelse condition, i.e. if the element is present it should click the button else it should move on to the next line.

Below is my code

driver.find_element_by_css_selector('input.whsOnd.zHQkBf').send_keys(password)

    time.sleep(2)
    driver.find_element_by_id("passwordNext").click()
    time.sleep(2)

    driver.get(comment_url)
    time.sleep(2)

    driver.find_element_by_xpath("//button[@class='yt-uix-button yt-uix-button-size-default yt-uix-button-default yt-uix-button-empty yt-uix-button-has-icon no-icon-markup comment-action-buttons-renderer-thumb yt-uix-sessionlink sprite-comment-actions sprite-like i-a-v-sprite-like']").click()
    time.sleep(2)
    driver.find_element_by_xpath("//button[@class='yt-uix-button yt-uix-button-size-small yt-uix-button-link comment-renderer-reply comment-simplebox-trigger']").click()
    time.sleep(2)
    driver.find_element_by_class_name("comment-simplebox-text").send_keys(comment)
    time.sleep(2)
    driver.find_element_by_xpath("//button[@class='yt-uix-button yt-uix-button-size-default yt-uix-button-primary yt-uix-button-empty comment-simplebox-submit yt-uix-sessionlink']").click()
    time.sleep(2)

The code i want to add is :

if driver.find_element_by_xpath ...... exists,
then
   driver.find_element_by_xpath("//*[@class=\"leaflet-control-zoom-in\"]").click()
   driver.find_element_by_xpath("//*[@class=\"leaflet-control-zoom-in\"]").click()
   driver.find_element_by_xpath("//*[@class=\"leaflet-control-zoom-in\"]").click()
   driver.find_element_by_xpath("//*[@class=\"leaflet-control-zoom-in\"]").click()
   print("Zoom in 4x. Successful")
else
   print("Element does not exist, it failed.")

Whether I add only ( if) or if (if driver.find_element_by_xpath("") the script crashes within miliseconds and doesnt even open.

Body:
You need to try to catch an exception, and if you  catch it, do something in except block. Speaking about your scenario you probably need to catch selenium.common.exceptions.NoSuchElementException. So the code may look like:

from selenium.common.exceptions import NoSuchElementException

try:
   driver.find_element_by_xpath("//*[@class=\"leaflet-control-zoom-in\"]").click()
   driver.find_element_by_xpath("//*[@class=\"leaflet-control-zoom-in\"]").click()
   driver.find_element_by_xpath("//*[@class=\"leaflet-control-zoom-in\"]").click()
   driver.find_element_by_xpath("//*[@class=\"leaflet-control-zoom-in\"]").click()
   print("Zoom in 4x. Successful")
except NoSuchElementException:
   print("Element does not exist, it failed.")


问:
Swift 3 - Core Data Saving with one-to-many relationship
I'm working with core data and i have two entity:

SwimmingPool
Parameters
Each swimming pool can have multiple parameters

I have already saved and fetched data for swimming pool.

I've saved them trough a form.

In my AppDelegate i have:

```<code>let ad = UIApplication.shared.delegate as! AppDelegate
let context = ad.persistentContainer.viewContext
</code>```

and here's the func:

```<code> var swimmingpool: SwimminPool!

    if swimmingPoolToEdit == nil {
        swimming = SwimminPool(context: context)
    } else {
        swimming = swimmingPoolToEdit
    }

    if let name =  swimmingName.text {
        swimming.name = name
    }
    if let volume = swimmingVolume.text {
        swimming.volume = volume
.........................................................
ad.saveContext()
</code>```

and i perform the fetch like so:

```<code>var controller: NSFetchedResultsController<SwimmingPool>!

func attemptFetch() {

    let fetchRequest: NSFetchRequest<SwimminPool> = SwimminPool.fetchRequest()
    let dataSort = NSSortDescriptor(key: "createdAt", ascending: false)

    fetchRequest.sortDescriptors = [dataSort]

     let controller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)

    controller.delegate = self
    self.controller = controller

    do {
        try controller.performFetch()
    } catch {
        let error = error as NSError
        print("\(error.debugDescription)")
    }
}
</code>```

Through a segue i pass all the data to a new controller and through a new form (in an another controller) i'm trying to save the data for the parameters and connect them to the the specific swimming pool.

Do i need to save the data like i did for the swimming pool and the relationship will automatically connect the two entities or do i need to connect them upon saving?

I'm new to swift and i'm not sure how to save related datas

The connection will be made upon saving or when i will perform the parameters fetch?

Thank you!

答:
If you want to add Parameters to a specific SwimmingPool

In the segue pass the specific SwimmingPool instance to the form controller.

Create Parameters instances by inserting them into the context.

Add the relationship to the SwimmingPool instance by calling insert on the parameter attribute / relationship or the generated accessor addToParameter of the NSManagedObject subclass.

Save the context. (important as last step).

Note : To avoid confusion name an Entity always in singular form (e.g. SwimmingPool / Parameter), a one-to-one relationship also in singular form (e.g. parameter) and  a one-to-many relationship in plural form (e.g. parameters)

PS: You question is ambiguous: You are writing Each swimming pool can have multiple parameters but the model design is Each parameter can have multiple swimming pools

Body:
I'm working with core data and i have two entity:

SwimmingPool
Parameters
Each swimming pool can have multiple parameters

I have already saved and fetched data for swimming pool.

I've saved them trough a form.

In my AppDelegate i have:

let ad = UIApplication.shared.delegate as! AppDelegate
let context = ad.persistentContainer.viewContext

and here's the func:

 var swimmingpool: SwimminPool!

    if swimmingPoolToEdit == nil {
        swimming = SwimminPool(context: context)
    } else {
        swimming = swimmingPoolToEdit
    }

    if let name =  swimmingName.text {
        swimming.name = name
    }
    if let volume = swimmingVolume.text {
        swimming.volume = volume
.........................................................
ad.saveContext()

and i perform the fetch like so:

var controller: NSFetchedResultsController<SwimmingPool>!

func attemptFetch() {

    let fetchRequest: NSFetchRequest<SwimminPool> = SwimminPool.fetchRequest()
    let dataSort = NSSortDescriptor(key: "createdAt", ascending: false)

    fetchRequest.sortDescriptors = [dataSort]

     let controller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)

    controller.delegate = self
    self.controller = controller

    do {
        try controller.performFetch()
    } catch {
        let error = error as NSError
        print("\(error.debugDescription)")
    }
}

Through a segue i pass all the data to a new controller and through a new form (in an another controller) i'm trying to save the data for the parameters and connect them to the the specific swimming pool.

Do i need to save the data like i did for the swimming pool and the relationship will automatically connect the two entities or do i need to connect them upon saving?

I'm new to swift and i'm not sure how to save related datas

The connection will be made upon saving or when i will perform the parameters fetch?

Thank you!


问:
Symfony3 save every update into database
I´m new on symfony and postgreSQL and I´m trying to save a log of database updates/deletes
I´ve created this table

```<code>CREATE TABLE  "public"."changes" (
  "id" INT NOT NULL ,
  "id_user" INT NOT NULL,
  "operation" VARCHAR(45) NOT NULL,
  "table" VARCHAR(45) NOT NULL,
  "column" VARCHAR(45) NOT NULL,
  "old_data" TEXT NOT NULL,
  "new_data" TEXT NOT NULL,
  "ts" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY ("id"),
  CONSTRAINT "user"
    FOREIGN KEY ("id_user")
    REFERENCES "public"."users" ("id")
    ON DELETE NO ACTION
    ON UPDATE NO ACTION);
</code>```

And what I need is to save into this table every time I do sumething like

```<code>/**
 * @Route("/insert", name="insert")
 */
public function insertAction(Request $request)
{
    $em = $this->get('doctrine')->getManager();

    $info = new Info();
    $info->setMail($request->request->get('mail'));
    $info->setName($request->request->get('name'));
    $info->setLastname($request->request->get('lastname'));

    $em->persist($info);

    $em->flush();

}
</code>```

I´m thinking about creating an object/array with the table/column/data and after the flush if everything is ok, call a global function to add the data into the changes table.
Is there a easy way / good practice to do this?

答:
First of all you don't need to implement this king of logic yourself. Doctrine tracks entity insertions, updates, field changes and deletes internally, and creates corresponding events that you can listen to. For instance, when you create new Info entity and persist it, Doctrine will dispatch prePersist event when you call flush operation. You could create event subscriber to subscribe on such events and do your logic there.

To fully understand Doctrine lifecycle events check out official doctrine documentation: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html

Event subscriber creation described in the Symfony documentation: http://symfony.com/doc/current/doctrine/event_listeners_subscribers.html#creating-the-subscriber-class

Also you can try out existing third-party bundle that will log entity insertions, updates and deletes: https://github.com/simplethings/EntityAuditBundle It also supports versioning.

Body:
I´m new on symfony and postgreSQL and I´m trying to save a log of database updates/deletes
I´ve created this table

CREATE TABLE  "public"."changes" (
  "id" INT NOT NULL ,
  "id_user" INT NOT NULL,
  "operation" VARCHAR(45) NOT NULL,
  "table" VARCHAR(45) NOT NULL,
  "column" VARCHAR(45) NOT NULL,
  "old_data" TEXT NOT NULL,
  "new_data" TEXT NOT NULL,
  "ts" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY ("id"),
  CONSTRAINT "user"
    FOREIGN KEY ("id_user")
    REFERENCES "public"."users" ("id")
    ON DELETE NO ACTION
    ON UPDATE NO ACTION);

And what I need is to save into this table every time I do sumething like

/**
 * @Route("/insert", name="insert")
 */
public function insertAction(Request $request)
{
    $em = $this->get('doctrine')->getManager();

    $info = new Info();
    $info->setMail($request->request->get('mail'));
    $info->setName($request->request->get('name'));
    $info->setLastname($request->request->get('lastname'));

    $em->persist($info);

    $em->flush();

}

I´m thinking about creating an object/array with the table/column/data and after the flush if everything is ok, call a global function to add the data into the changes table.
Is there a easy way / good practice to do this?


问:
VBA, Parse by "|" and Transpose, Next row
I have the following data in a cells A1

```<code>|stack|over|flow|
</code>```

and cells A2..

```<code>|today|is|friday
</code>```

How can I delimit this and transpose it into a vertical/column based view view?

Delimiting will give me data row based, which is good but that I have to transpose this manually each time. I plan to do this for many rows. I realized this could be tricky as the next row will need to be pushed back down for each time.

Result A1:A6:

```<code>Stack

Over

flow

today

is

friday
</code>```

Edit

答:
You can do this with Power Query or Get & Transform

Data --> Get & Transform Data --> From Table/Range

Then in the Query Editor

Split Column by Delimiter

Use a Custom Delimiter:  the Pipe |

Split at left most (to get rid of that first pipe

Remove Column 1 (the blank column)

Split Column by delimiter

Use the Advanced Option and select to split into rows

Save and you are done.

Body:
I have the following data in a cells A1

|stack|over|flow|

and cells A2..

|today|is|friday

How can I delimit this and transpose it into a vertical/column based view view?

Delimiting will give me data row based, which is good but that I have to transpose this manually each time. I plan to do this for many rows. I realized this could be tricky as the next row will need to be pushed back down for each time.

Result A1:A6:

Stack

Over

flow

today

is

friday

Edit


问:
Can't make 2 Player Tic Tac Toe game work JavaScript
HTML

```<code><div class="container"> <-- div container -->

<div id="div1" onclick="canvasClicked(1);"></div>
<div id="div2" onclick="canvasClicked(2);"></div>
<div id="div3" onclick="canvasClicked(3);"></div>
<div id="div4" onclick="canvasClicked(4);"></div>
<div id="div5" onclick="canvasClicked(5);"></div>
<div id="div6" onclick="canvasClicked(6);"></div>
<div id="div7" onclick="canvasClicked(7);"></div>
<div id="div8" onclick="canvasClicked(8);"></div>
<div id="div9" onclick="canvasClicked(9);"></div>

</div> <-- div container end -->
</code>```

Css

```<code>  .container{     /*some css*/
border: 2px solid red;
width: 400px;
height: 400px;
margin: 0 auto;
margin-top: 10%;
}

.container div{
float: left;
height: 132px;
width: 131.3px;
border: 1px solid black;
}
</code>```

JavaScript

```<code>var painted; //global variables
var content;
var winningCombinations;
var theCanvas;
var c;
var cxt;
var w;
var y;

var turn = 0;
var squaresFilled = 0; //global variables end

window.onload = function(){               //instantiating variables
painted = new Array();   //to check if the canvas contains something already
content = new Array();  //to see what the canvas contains 'X' or 'O'

winningCombinations = [[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],
[1,5,9],[3,5,7]]; //all possible combinations :P

for(var i=0; i<=8; i++){
    painted[i] = false;
    content[i]=false;
}
}

function canvasClicked(number){

theCanvas = "div" + number; //takes the div Id from html
c = document.getElementById(theCanvas);

if(painted[number-1]==false){
    if(turn%2==0){               //use X here
        c.innerHTML = '<img src="cross image" alt="x" width=100%
height=100%>';
        content[number-1] = 'X'; //storing value in content array
    }else{                       // user O here
        c.innerHTML = '<img src=" O image" height="100%"
width="100%" alt="O">';
        content[number-1] = 'O'; //storing value in content array
    }
}
else{
    alert('This block is already occupied, try another block');
    turn--;
    squaresFilled--;
}
turn++;
painted[number-1]= true;
squaresFilled++;
checkForWinner(content[number-1]);

if(squaresFilled == 9){
    alert('It is a TIE');
    playAgain();
}
}

function checkForWinner(symbol){  // This functions seems to be the problem

for(var a = 0; a < winningCombinations.length; a++){

    if(content[winningCombinations[a][0]]==symbol &&
content[winningCombinations[a][1]]==symbol && content[winningCombinations[a]
[2]]==symbol){
        console.log(symbol + ' won!!');
    }

}
}
function playAgain(){ // just another function to reset the game
    y=confirm("PLAY AGAIN?");
    if(y==true){
        location.reload(true);
    }else{
        alert('Good Bye Then!!');
    }
}
</code>```

It runs normally but the results are not expected. It sometimes randomly make anyone winner(i guess), i can't seem to find the bug, i used debugger as well but i just can't find the problem...any help would be appreciated.
Thanks

答:
I know I should help you with your code, but I decided to use parts of your code and suggest you an approach:
HTML :

```<code><div class="turnInfo" id="turnInfo">Turn : O</div>
<div class="container">
  <div id="div1" cell="1" onclick="canvasClicked(this);"></div>
  <div id="div2" cell="2" onclick="canvasClicked(this);"></div>
  <div id="div3" cell="3" onclick="canvasClicked(this);"></div>
  <div id="div4" cell="4" onclick="canvasClicked(this);"></div>
  <div id="div5" cell="5" onclick="canvasClicked(this);"></div>
  <div id="div6" cell="6" onclick="canvasClicked(this);"></div>
  <div id="div7" cell="7" onclick="canvasClicked(this);"></div>
  <div id="div8" cell="8" onclick="canvasClicked(this);"></div>
  <div id="div9" cell="9" onclick="canvasClicked(this);"></div>
</div>
</code>```

CSS :

```<code>.turnInfo{
    text-align:center;
    font-size:40px;
    font-weight:bold;
    margin-top: 6%;
    margin-bottom:10px;
}
.container{     /*some css*/
    border: 2px solid red;
    width: 400px;
    height: 400px;
    margin: 0 auto;
}

.container div{
    float: left;
    height: 102px;
    width: 131.3px;
    border: 1px solid black;
    text-align:center;
    padding-top:30px;
    font-size:50px;
}
</code>```

JS :
Variables

```<code>var cells = [0,0,0,0,0,0,0,0,0,0]; // make it 10 for the sake of array index
var turn = 'O'; // first turn : O
var infoDiv = document.getElementById('turnInfo');
</code>```

Toggle the Trun

```<code>function toggleTurn(){
   turn = turn == 'O' ? 'X' : 'O';
   infoDiv.innerHTML = 'Turn : '+turn;
   return turn;
}
</code>```

Canvas Click Handler

```<code>function canvasClicked(cell){
   var cellIndex = cell.getAttribute('cell');
   if(!cells[cellIndex]){
      cells[cellIndex] = toggleTurn();
      cell.innerHTML = turn; // you can add image here.
      checkWinner();
   }
}
</code>```

Check Result function

```<code>function checkWinner(){
   winningCombinations = [
     [1,2,3],
     [4,5,6],
     [7,8,9],
     [1,4,7],
     [2,5,8],
     [3,6,9],
     [1,5,9],
     [3,5,7]
   ]; //all possible combinations :P
   for(var index=0; index <  winningCombinations.length;index++){
       winCond = winningCombinations[index];
       if(cells[winCond[0]] != 0 &&
          cells[winCond[0]] == cells[winCond[1]] &&
          cells[winCond[1]] == cells[winCond[2]])
       {
          alert(turn + ' is winner');
          playAgain();
          return;
       }
   }

   var allCellsFilled = 1;
   for(var index =1; index < cells.length; index++){
       if(!cells[index]){
          allCellsFilled = 0;
          break;
       }
   }
   if(allCellsFilled){
      alert('Game is draw!');
      playAgain();
   }
}
</code>```

New Game function

```<code>function playAgain(){ // just another function to reset the game
    y=confirm("PLAY AGAIN?");
    if(y==true){
        location.reload(true);
    }else{
        alert('Good Bye Then!!');
    }
}
</code>```

You can see it here : https://codepen.io/FaridNaderi/pen/awROjY

Hope it helps.

Body:
HTML

 <-- div container -->

 <-- div container end -->

Css

  .container{     /*some css*/
border: 2px solid red;
width: 400px;
height: 400px;
margin: 0 auto;
margin-top: 10%;
}

.container div{
float: left;
height: 132px;
width: 131.3px;
border: 1px solid black;
}

JavaScript

var painted; //global variables
var content;
var winningCombinations;
var theCanvas;
var c;
var cxt;
var w;
var y;

var turn = 0;
var squaresFilled = 0; //global variables end

window.onload = function(){               //instantiating variables
painted = new Array();   //to check if the canvas contains something already
content = new Array();  //to see what the canvas contains 'X' or 'O'

winningCombinations = [[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],
[1,5,9],[3,5,7]]; //all possible combinations :P

for(var i=0; i<=8; i++){
    painted[i] = false;
    content[i]=false;
}
}

function canvasClicked(number){

theCanvas = "div" + number; //takes the div Id from html
c = document.getElementById(theCanvas);

if(painted[number-1]==false){
    if(turn%2==0){               //use X here
        c.innerHTML = '';
        content[number-1] = 'X'; //storing value in content array
    }else{                       // user O here
        c.innerHTML = '';
        content[number-1] = 'O'; //storing value in content array
    }
}
else{
    alert('This block is already occupied, try another block');
    turn--;
    squaresFilled--;
}
turn++;
painted[number-1]= true;
squaresFilled++;
checkForWinner(content[number-1]);

if(squaresFilled == 9){
    alert('It is a TIE');
    playAgain();
}
}

function checkForWinner(symbol){  // This functions seems to be the problem

for(var a = 0; a < winningCombinations.length; a++){

    if(content[winningCombinations[a][0]]==symbol &&
content[winningCombinations[a][1]]==symbol && content[winningCombinations[a]
[2]]==symbol){
        console.log(symbol + ' won!!');
    }

}
}
function playAgain(){ // just another function to reset the game
    y=confirm("PLAY AGAIN?");
    if(y==true){
        location.reload(true);
    }else{
        alert('Good Bye Then!!');
    }
}

It runs normally but the results are not expected. It sometimes randomly make anyone winner(i guess), i can't seem to find the bug, i used debugger as well but i just can't find the problem...any help would be appreciated.
Thanks

Body:
I know I should help you with your code, but I decided to use parts of your code and suggest you an approach:
HTML :

<div class="turnInfo" id="turnInfo">Turn : O</div>
<div class="container">
  <div id="div1" cell="1" onclick="canvasClicked(this);"></div>
  <div id="div2" cell="2" onclick="canvasClicked(this);"></div>
  <div id="div3" cell="3" onclick="canvasClicked(this);"></div>
  <div id="div4" cell="4" onclick="canvasClicked(this);"></div>
  <div id="div5" cell="5" onclick="canvasClicked(this);"></div>
  <div id="div6" cell="6" onclick="canvasClicked(this);"></div>
  <div id="div7" cell="7" onclick="canvasClicked(this);"></div>
  <div id="div8" cell="8" onclick="canvasClicked(this);"></div>
  <div id="div9" cell="9" onclick="canvasClicked(this);"></div>
</div>

CSS :

.turnInfo{
    text-align:center;
    font-size:40px;
    font-weight:bold;
    margin-top: 6%;
    margin-bottom:10px;
}
.container{     /*some css*/
    border: 2px solid red;
    width: 400px;
    height: 400px;
    margin: 0 auto;
}

.container div{
    float: left;
    height: 102px;
    width: 131.3px;
    border: 1px solid black;
    text-align:center;
    padding-top:30px;
    font-size:50px;
}

JS :
Variables

var cells = [0,0,0,0,0,0,0,0,0,0]; // make it 10 for the sake of array index
var turn = 'O'; // first turn : O
var infoDiv = document.getElementById('turnInfo');

Toggle the Trun

function toggleTurn(){
   turn = turn == 'O' ? 'X' : 'O';
   infoDiv.innerHTML = 'Turn : '+turn;
   return turn;
}

Canvas Click Handler

function canvasClicked(cell){
   var cellIndex = cell.getAttribute('cell');
   if(!cells[cellIndex]){
      cells[cellIndex] = toggleTurn();
      cell.innerHTML = turn; // you can add image here.
      checkWinner();
   }
}

Check Result function

function checkWinner(){
   winningCombinations = [
     [1,2,3],
     [4,5,6],
     [7,8,9],
     [1,4,7],
     [2,5,8],
     [3,6,9],
     [1,5,9],
     [3,5,7]
   ]; //all possible combinations :P
   for(var index=0; index <  winningCombinations.length;index++){
       winCond = winningCombinations[index];
       if(cells[winCond[0]] != 0 &&
          cells[winCond[0]] == cells[winCond[1]] &&
          cells[winCond[1]] == cells[winCond[2]])
       {
          alert(turn + ' is winner');
          playAgain();
          return;
       }
   }

   var allCellsFilled = 1;
   for(var index =1; index < cells.length; index++){
       if(!cells[index]){
          allCellsFilled = 0;
          break;
       }
   }
   if(allCellsFilled){
      alert('Game is draw!');
      playAgain();
   }
}

New Game function

function playAgain(){ // just another function to reset the game
    y=confirm("PLAY AGAIN?");
    if(y==true){
        location.reload(true);
    }else{
        alert('Good Bye Then!!');
    }
}

You can see it here : https://codepen.io/FaridNaderi/pen/awROjY

Hope it helps.


问:
SQL return list of ntext and convert it to XML
I have a query that will return and a list of ntext, and in these ntext they contain XML value.
my question is how to convert each of ntext to xml and do logic with it

Query:

```<code>select a.content
from dbo.content as a
inner join dbo.xml_collection_tbl as b on a.xml_fg_id = b.xml_collection_id
where a.inherit_from='val1' and b.collection_title='val2' and a.content_table= 'val3'
</code>```

result:

what I want to do here is to check rather the Query returns contain the value that I looking for. lets say the page title = "hello World"

I tried below.But it returns many empty rows and with one correct row

```<code>select cast(a.content_html as xml).query('(//root[pagetitle/text()="AAA"])') content_html1
from dbo.content as a
inner join dbo.xml_collection_tbl as b on a.xml_fg_id = b.xml_collection_id
where a.inherit_from='val1' and b.collection_title='val2' and a.content_table= 'val3'
</code>```

expected result is: return only one row where it's not empty (row 54)

答:
Demo of XQuery expression https://learn.microsoft.com/en-us/sql/xquery/xquery-language-reference-sql-server to filter data</p>

```<code>with sd as (
    select cast(content_html as xml) as col
    from (
        values
        ('<root><pagetitle>FFF</pagetitle></root>')
        ,('<root><pagetitle>AAA</pagetitle></root>')
    ) as a(content_html)
)
select t.n.value('.[1]', 'varchar(100)') as content_html1
from sd
cross apply col.nodes('root/pagetitle[text()="AAA"]') t(n)
</code>```

Body:
I have a query that will return and a list of ntext, and in these ntext they contain XML value.
my question is how to convert each of ntext to xml and do logic with it

Query:

select a.content
from dbo.content as a
inner join dbo.xml_collection_tbl as b on a.xml_fg_id = b.xml_collection_id
where a.inherit_from='val1' and b.collection_title='val2' and a.content_table= 'val3'

result:

what I want to do here is to check rather the Query returns contain the value that I looking for. lets say the page title = "hello World"

I tried below.But it returns many empty rows and with one correct row

select cast(a.content_html as xml).query('(//root[pagetitle/text()="AAA"])') content_html1
from dbo.content as a
inner join dbo.xml_collection_tbl as b on a.xml_fg_id = b.xml_collection_id
where a.inherit_from='val1' and b.collection_title='val2' and a.content_table= 'val3'

expected result is: return only one row where it's not empty (row 54)

Body:
Demo of XQuery expression https://learn.microsoft.com/en-us/sql/xquery/xquery-language-reference-sql-server to filter data

with sd as (
    select cast(content_html as xml) as col
    from (
        values
        ('<root><pagetitle>FFF</pagetitle></root>')
        ,('<root><pagetitle>AAA</pagetitle></root>')
    ) as a(content_html)
)
select t.n.value('.[1]', 'varchar(100)') as content_html1
from sd
cross apply col.nodes('root/pagetitle[text()="AAA"]') t(n)


问:
Table myapp_tableName already exists
i have created a django app and add some model fields on models.py

1.logo

2.shirt

and their attributes are
pid, name and org
then i added a new attribute price to them. and execute command python manage.py makemigrations and python manage.py migrate i got the error 'Table buapp_dealer already exists.

here is my models.py

```<code>from django.db import models

# Create your models here.

class founder(models.Model):
    name=models.CharField(max_length=30)
    address=models.CharField(max_length=50)
    country=models.CharField(max_length=20)
    email=models.EmailField(null=True)
    headshot=models.ImageField(upload_to='images',null=True)
    def __str__(self):
        return self.name
    __repr__=__str__

class supporter(models.Model):
    name=models.CharField(max_length=30)
    address=models.CharField(max_length=20)
    email=models.EmailField(null=True)
    headshot=models.ImageField(upload_to='images',null=True)
    def __str__(self):
        return self.name
    __repr__=__str__

    class Admin:
        list_display=('name','address','email')

class dealer(models.Model):
    name=models.CharField(max_length=30)
    address=models.CharField(max_length=40)
    #city=models.CharField(max_length=60)
    country=models.CharField(max_length=50)
    website=models.URLField(null=True)
    rep=models.IntegerField(null=True)
    def __str__(self):
        return self.name
    __repr__=__str__

    class Admin:
        list_display=('name','address','country')
        list_filter=('name','country')
        ordering=('rep',)
        search_fields=('name')

class tshirt(models.Model):
    price=models.FloatField(default=0.0)
    name=models.CharField(max_length=50,default='default')
    fontimage=models.ImageField(upload_to='images/tshirts',null=True)
    backimage=models.ImageField(upload_to='images/tshirts',null=True)
    def __str__(self):
        return str(self.pid)
    __repr__=__str__
    class Admin:
        list_display=('pid','price','fontimage')
        list_filter=('price')
        ordering=('-pid')
        search_fields=('name')

class logo(models.Model):
    pid=models.IntegerField()
    price=models.FloatField(default=0.0)
    org=models.CharField(max_length=50)
    img=models.ImageField(upload_to='images/tshirts',null=True)
    def __str__(self):
        return str(self.pid)
    __repr__=__str__
    class Admin:
        list_display=('pid','price','img')
        list_filter=('price')
        ordering=('-pid')
        search_fields=('org')

class final(models.Model):
    pid=models.IntegerField()
    price=models.FloatField(default=0.00)
    fontimg=models.ImageField(upload_to='images/finals',null=True)
    backimg=models.ImageField(upload_to='images/finals',null=True)
    def __str__(self):
        return str(self.pid)
    __repr__=__str__
</code>```

答:
The solution is :

```<code>python manage.py makemigrations

python manage.py migrate --fake buapp_dealer

python manage.py migrate
</code>```

It should solve your problem

Title: Table myapp_tableName already exists

Body:
i have created a django app and add some model fields on models.py

1.logo

2.shirt

and their attributes are
pid, name and org
then i added a new attribute price to them. and execute command python manage.py makemigrations and python manage.py migrate i got the error 'Table buapp_dealer already exists.

here is my models.py

from django.db import models

# Create your models here.

class founder(models.Model):
    name=models.CharField(max_length=30)
    address=models.CharField(max_length=50)
    country=models.CharField(max_length=20)
    email=models.EmailField(null=True)
    headshot=models.ImageField(upload_to='images',null=True)
    def __str__(self):
        return self.name
    __repr__=__str__

class supporter(models.Model):
    name=models.CharField(max_length=30)
    address=models.CharField(max_length=20)
    email=models.EmailField(null=True)
    headshot=models.ImageField(upload_to='images',null=True)
    def __str__(self):
        return self.name
    __repr__=__str__

    class Admin:
        list_display=('name','address','email')

class dealer(models.Model):
    name=models.CharField(max_length=30)
    address=models.CharField(max_length=40)
    #city=models.CharField(max_length=60)
    country=models.CharField(max_length=50)
    website=models.URLField(null=True)
    rep=models.IntegerField(null=True)
    def __str__(self):
        return self.name
    __repr__=__str__

    class Admin:
        list_display=('name','address','country')
        list_filter=('name','country')
        ordering=('rep',)
        search_fields=('name')

class tshirt(models.Model):
    price=models.FloatField(default=0.0)
    name=models.CharField(max_length=50,default='default')
    fontimage=models.ImageField(upload_to='images/tshirts',null=True)
    backimage=models.ImageField(upload_to='images/tshirts',null=True)
    def __str__(self):
        return str(self.pid)
    __repr__=__str__
    class Admin:
        list_display=('pid','price','fontimage')
        list_filter=('price')
        ordering=('-pid')
        search_fields=('name')

class logo(models.Model):
    pid=models.IntegerField()
    price=models.FloatField(default=0.0)
    org=models.CharField(max_length=50)
    img=models.ImageField(upload_to='images/tshirts',null=True)
    def __str__(self):
        return str(self.pid)
    __repr__=__str__
    class Admin:
        list_display=('pid','price','img')
        list_filter=('price')
        ordering=('-pid')
        search_fields=('org')

class final(models.Model):
    pid=models.IntegerField()
    price=models.FloatField(default=0.00)
    fontimg=models.ImageField(upload_to='images/finals',null=True)
    backimg=models.ImageField(upload_to='images/finals',null=True)
    def __str__(self):
        return str(self.pid)
    __repr__=__str__

Body:
The solution is :

python manage.py makemigrations

python manage.py migrate --fake buapp_dealer

python manage.py migrate

It should solve your problem


问:
Exception while running number of queries concurrently on DB2
We are testing an application specific Design where we need to show progressive counts after firing many queries simultaneously.

When we are firing a single query, we are successfully able to get Results Asynchronously.

But, when we are firing 3-4 queries simultaneously, after a significant amount of time & after getting some records for each query
we are getting an exception which states

“com.ibm.db2.jcc.c.SqlException: DB2 SQL error: SQLCODE: -1218, SQLSTATE: 57011, SQLERRMC: 4099”

Because of this, all the queries fired do not get executed completely.

There is no problem if these queries are fired one by one. (query2 starts executing after query1 completes & so on)

After looking for this SQLCODE in Control Center we found out the details which are,

SQL1218N  There are no pages currently available in bufferpool

```<code>  "<buffpool-num>".
</code>```

Explanation:

All of the pages in the bufferpool are currently being used. A request
to use another page failed.

The statement may be successful if executed again. If this error occurs
frequently, some or all of the following actions may prevent further
failures:

increase the bufferpool size

decrease the maximum number of database agents and/or connections

decrease the maximum degree of parallelism

decrease the prefetch size for table spaces that are in this

bufferpool

move some table spaces into other bufferpools.

sqlcode: -1218

sqlstate: 57011

On our DB instance, we already had a buffer pool of 32K page size & even after creating another buffer pool
of 32K, the problem persists.

Can anyone kindly help us in solving the problem.

Thanks & Regards,

Ravindra Jain

答:
We are committing after each record is inserted/updated.
So, redo log is not a problem. (buffer pool will never be over-flooded).

32K is the page size of the buffer pool & buffer pool contains 10000 pages.
So, are these configurations appropriate for the buffer pool?

OwnerDisplayName: Ravindra Jain

ContentLicense: CC BY-SA 2.5

Body:
We are testing an application specific Design where we need to show progressive counts after firing many queries simultaneously.

When we are firing a single query, we are successfully able to get Results Asynchronously.

But, when we are firing 3-4 queries simultaneously, after a significant amount of time & after getting some records for each query
we are getting an exception which states

“com.ibm.db2.jcc.c.SqlException: DB2 SQL error: SQLCODE: -1218, SQLSTATE: 57011, SQLERRMC: 4099”

Because of this, all the queries fired do not get executed completely.

There is no problem if these queries are fired one by one. (query2 starts executing after query1 completes & so on)

After looking for this SQLCODE in Control Center we found out the details which are,

SQL1218N  There are no pages currently available in bufferpool

  "<buffpool-num>".

Explanation:

All of the pages in the bufferpool are currently being used. A request
to use another page failed.

The statement may be successful if executed again. If this error occurs
frequently, some or all of the following actions may prevent further
failures:

increase the bufferpool size

decrease the maximum number of database agents and/or connections

decrease the maximum degree of parallelism

decrease the prefetch size for table spaces that are in this

bufferpool

move some table spaces into other bufferpools.

sqlcode: -1218

sqlstate: 57011

On our DB instance, we already had a buffer pool of 32K page size & even after creating another buffer pool
of 32K, the problem persists.

Can anyone kindly help us in solving the problem.

Thanks & Regards,

Ravindra Jain


问:
UITableView Only Scroll Down
I want to configure a UITableView so that it can only scroll down. In other words, disable the table view from scrolling upward. How would one go about doing that?

答:
Details

Xcode 14.2

Swift  5.7.2

Solution

```<code>import UIKit

class ViewController: UIViewController {
    private weak var tableView: UITableView!
    private var previousContentOffset = CGPoint()
    override func viewDidLoad() {
        super.viewDidLoad()
        let tableView = UITableView()
        tableView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(tableView)
        tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
        tableView.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor).isActive = true
        tableView.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor).isActive = true
        tableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
        self.tableView = tableView
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .gray
    }
}

// MARK: UITableViewDelegate

extension ViewController: UITableViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView === tableView {
            if previousContentOffset.y > scrollView.contentOffset.y {
                scrollView.contentOffset.y = previousContentOffset.y
            }
            previousContentOffset = scrollView.contentOffset
        }
    }
}

// MARK: UITableViewDataSource

extension ViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int { 1 }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 1000 }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.textLabel?.text = "\(indexPath)"
        return cell
    }
}
</code>```

Title: UITableView Only Scroll Down

Body:
Details

Xcode 14.2

Swift  5.7.2

Solution

import UIKit

class ViewController: UIViewController {
    private weak var tableView: UITableView!
    private var previousContentOffset = CGPoint()
    override func viewDidLoad() {
        super.viewDidLoad()
        let tableView = UITableView()
        tableView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(tableView)
        tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
        tableView.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor).isActive = true
        tableView.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor).isActive = true
        tableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
        self.tableView = tableView
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .gray
    }
}

// MARK: UITableViewDelegate

extension ViewController: UITableViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView === tableView {
            if previousContentOffset.y > scrollView.contentOffset.y {
                scrollView.contentOffset.y = previousContentOffset.y
            }
            previousContentOffset = scrollView.contentOffset
        }
    }
}

// MARK: UITableViewDataSource

extension ViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int { 1 }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 1000 }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.textLabel?.text = "\(indexPath)"
        return cell
    }
}


问:
How to call a function after HTML content refresh in angular2?
When I hit an api to get data from server in constructor and store it in local variable. I loop this variable in html to build table and show data in table. But when I call a function on api success and in it I loop the same variable which is used in HTML, the loop in function will run first and after that HTML loop. My requirement is to run HTML loop first and after its completion loop in function.

HTML CODE

```<code><table>
   <tr *ngFor="let booking of jobHistory>
      <td>{{booking}}</td>
   </tr>
</table>
</code>```

TYPESCRIPT CODE

```<code>jobHistory : any;
constructor()
{
  this.service.getCustomerJobHistory().subscribe(   res => { this.jobHistory = res},
                                                    err => console.log(err),
                                                    () => this.setRating()
                                              );

}

setRating()
{
   //I want to run this loop after HTML loop completion.
   for(let booking of this.jobHistory)
   {
     console.log(booking);
   }
}
</code>```

答:
Basically, you could use the 'last' operator of *ngFor</p>

```<code><table>
   <tr *ngFor="let booking of jobHistory; let l=last">
      <td>{{booking}} {{ l ? setRatings() : null}}</td>
   </tr>
</table>
</code>```

Body:
When I hit an api to get data from server in constructor and store it in local variable. I loop this variable in html to build table and show data in table. But when I call a function on api success and in it I loop the same variable which is used in HTML, the loop in function will run first and after that HTML loop. My requirement is to run HTML loop first and after its completion loop in function.

HTML CODE

      {{booking}}

TYPESCRIPT CODE

jobHistory : any;
constructor()
{
  this.service.getCustomerJobHistory().subscribe(   res => { this.jobHistory = res},
                                                    err => console.log(err),
                                                    () => this.setRating()
                                              );

}

setRating()
{
   //I want to run this loop after HTML loop completion.
   for(let booking of this.jobHistory)
   {
     console.log(booking);
   }
}

Body:
Basically, you could use the 'last' operator of *ngFor

<table>
   <tr *ngFor="let booking of jobHistory; let l=last">
      <td>{{booking}} {{ l ? setRatings() : null}}</td>
   </tr>
</table>


问:
How to pass and echo data of textareas which are in a loop?
I have a scenario in which I don't know the number of textareas which are on my form and I want to save all data of all texareas in different fields of the database.

I print my textareas with a loop in my form like this:

```<code><?php
for ($a = 0; $a < count($model_main_heading); $a++) {
    ?>
    <textarea cols="100" rows="5" name="text_area_<?php echo $a+1; ?>">
        Your Text Goes Here....!!!!
        Kindly make new paragraph for your every bullet point :)
    </textarea>
    <?php
    echo '<br>';
}
?>
</code>```

Now I want to pass all data of all textareas to another page where I write the query for insertion into database. To get the data of textareas I write the following code but it cannot get all data of all textareas:

```<code>$model_headings = explode (',', $_POST['model_headings']);
for ($a = 0; $a < count($model_headings); $a++) {
    $b = $a + 1;
    echo '<br>';
    echo mysql_real_escape_string($_POST['text_area_'.$b.''][$a]);
    //echo $text_area[$a];
}
</code>```

Can anyone help me?

答:
Remove the line

```<code>echo mysql_real_escape_string ($_POST['text_area_'.$b.''][$a]);
</code>```

paste line

```<code>echo mysql_real_escape_string ($_POST['text_area_'.$b]);
</code>```

Body:
I have a scenario in which I don't know the number of textareas which are on my form and I want to save all data of all texareas in different fields of the database.

I print my textareas with a loop in my form like this:

<?php
for ($a = 0; $a < count($model_main_heading); $a++) {
    ?>
    <textarea cols="100" rows="5" name="text_area_<?php echo $a+1; ?>">
        Your Text Goes Here....!!!!
        Kindly make new paragraph for your every bullet point :)
    </textarea>
    <?php
    echo '
';
}
?>

Now I want to pass all data of all textareas to another page where I write the query for insertion into database. To get the data of textareas I write the following code but it cannot get all data of all textareas:

$model_headings = explode (',', $_POST['model_headings']);
for ($a = 0; $a < count($model_headings); $a++) {
    $b = $a + 1;
    echo '
';
    echo mysql_real_escape_string($_POST['text_area_'.$b.''][$a]);
    //echo $text_area[$a];
}

Can anyone help me?

Body:
Remove the line

echo mysql_real_escape_string ($_POST['text_area_'.$b.''][$a]);

paste line

echo mysql_real_escape_string ($_POST['text_area_'.$b]);


问:
match words in all rows in same column
There is a column in table 'mytable' named 'Description'.

```<code>+----+-------------------------------+
| ID | Description                   |
+----+-------------------------------+
| 1  | My NAME is Sajid KHAN         |
| 2  | My Name is Ahmed Khan         |
| 3  | MY friend name is Salman Khan |
+----+-------------------------------+
</code>```

I need to write an Oracle SQL query/procedure/function to list the distinct words in the column.

The output should be:

```<code>+------------------+-------+
| Word             | Count |
+------------------+-------+
| MY               |     3 |
| NAME             |     3 |
| IS               |     3 |
| SAJID            |     1 |
| KHAN             |     3 |
| AHMED            |     1 |
| FRIEND           |     1 |
| SALMAN           |     1 |
+------------------+-------+
</code>```

Word matching should be case-insensitive.

I am using Oracle 12.1.

答:
Let's suppose we would somehow manage to split every description in words.
So, instead of single row with Id = 1 and Description = 'My NAME is Sajid KHAN' we'd have 5 rows like this

```<code>ID  | Description
--- | ------------
 1  | My
 1  | NAME
 1  | is
 1  | Sajid
 1  | KHAN
</code>```

in this form it'd be trivial, something like

```<code>select Description, count(*) from data_in_new_form group by Description
</code>```

So, let's do this using recursive query.

create table mytable
as
select 1 as ID, 'My NAME is Sajid KHAN' as Description from dual
union all
select 2, 'My Name is Ahmed Khan' from dual
union all
select 3, 'MY friend name is Salman Khan' from dual
union all
select 4, 'test, punctuation! it is' from dual
;

with
rec (id, str, depth, element_value) as
(
    -- Anchor member.
    select id, upper(Description) as str, 1 as depth, REGEXP_SUBSTR( upper(Description), '(.*?)( |$)', 1, 1, NULL, 1 ) AS element_value
     from mytable
    UNION ALL
    -- Recursive member.
    select id, str, depth + 1, REGEXP_SUBSTR( str ,'(.*?)( |$)', 1, depth+1, NULL, 1 ) AS element_value
     from rec
    where depth < regexp_count(str, ' ')+1
)
, data as (
select * from rec
--order by id, depth
)
select element_value, count(*) from data
group by element_value
order by element_value
;
```

<p>Please notice this version doesn't do anything about punctuation assuming words are separated with spaces.</p>

<p><strong>UPDATE</strong> alternative way using hierarchic query</p>

```with rec as
(
    SELECT id, LEVEL AS depth,
    REGEXP_SUBSTR( upper(description) ,'(.*?)( |$)', 1, LEVEL, NULL, 1 ) AS element_value
    FROM   mytable
    CONNECT BY LEVEL <= regexp_count(description, ' ')+1
    and prior id = id
    and prior SYS_GUID() is not null
)
, data as (
select * from rec
--order by id, depth
)
select element_value, count(*) from data
group by element_value
order by 2 desc
;
```

Title: match words in all rows in same column

Body:
There is a column in table 'mytable' named 'Description'.

+----+-------------------------------+
| ID | Description                   |
+----+-------------------------------+
| 1  | My NAME is Sajid KHAN         |
| 2  | My Name is Ahmed Khan         |
| 3  | MY friend name is Salman Khan |
+----+-------------------------------+

I need to write an Oracle SQL query/procedure/function to list the distinct words in the column.

The output should be:

+------------------+-------+
| Word             | Count |
+------------------+-------+
| MY               |     3 |
| NAME             |     3 |
| IS               |     3 |
| SAJID            |     1 |
| KHAN             |     3 |
| AHMED            |     1 |
| FRIEND           |     1 |
| SALMAN           |     1 |
+------------------+-------+

Word matching should be case-insensitive.

I am using Oracle 12.1.

Body:
Let's suppose we would somehow manage to split every description in words.
So, instead of single row with Id = 1 and Description = 'My NAME is Sajid KHAN' we'd have 5 rows like this

ID  | Description
--- | ------------
 1  | My
 1  | NAME
 1  | is
 1  | Sajid
 1  | KHAN

in this form it'd be trivial, something like

select Description, count(*) from data_in_new_form group by Description

So, let's do this using recursive query.

create table mytable
as
select 1 as ID, 'My NAME is Sajid KHAN' as Description from dual
union all
select 2, 'My Name is Ahmed Khan' from dual
union all
select 3, 'MY friend name is Salman Khan' from dual
union all
select 4, 'test, punctuation! it is' from dual
;

with
rec (id, str, depth, element_value) as
(
    -- Anchor member.
    select id, upper(Description) as str, 1 as depth, REGEXP_SUBSTR( upper(Description), '(.*?)( |$)', 1, 1, NULL, 1 ) AS element_value
     from mytable
    UNION ALL
    -- Recursive member.
    select id, str, depth + 1, REGEXP_SUBSTR( str ,'(.*?)( |$)', 1, depth+1, NULL, 1 ) AS element_value
     from rec
    where depth < regexp_count(str, ' ')+1
)
, data as (
select * from rec
--order by id, depth
)
select element_value, count(*) from data
group by element_value
order by element_value
;

Please notice this version doesn't do anything about punctuation assuming words are separated with spaces.

UPDATE alternative way using hierarchic query

with rec as
(
    SELECT id, LEVEL AS depth,
    REGEXP_SUBSTR( upper(description) ,'(.*?)( |$)', 1, LEVEL, NULL, 1 ) AS element_value
    FROM   mytable
    CONNECT BY LEVEL <= regexp_count(description, ' ')+1
    and prior id = id
    and prior SYS_GUID() is not null
)
, data as (
select * from rec
--order by id, depth
)
select element_value, count(*) from data
group by element_value
order by 2 desc
;


问:
How do I change the exported name decoration for __stdcall in VC++?
This is how I have my export function declared at the moment:

```<code>extern "C" __declspec(dllexport)
Iexport_class* __stdcall GetExported_Class();
</code>```

When VS2008 compiled the source for this, the dll produced contains this under its export table:

```<code>_GetExported_Class@0
</code>```

For compatibility with other compilers I need the above decoration to look like this instead:

```<code>GetExported_Class
</code>```

Changing the calling convention to __cdecl will decorate it to the way I want but the convention would be wrong so I can't use that. I need it to be decorated the way __cdecl looks but uses __stdcall instead.

Is there anyway to do this without using a .def file? Is there a switch or an option I can pass to the link.exe linker that can make it decorate the export name to the way I want?

Thanks

答:
I don't understand why you don't want to use a .def file, but this is your only option.

The linker supports an export switch, but it cannot be used with functions that are __stdcall annotated:

http://msdn.microsoft.com/en-US/library/7k30y2k5.aspx

The def file way is pretty much the only solution.

Body:
This is how I have my export function declared at the moment:

extern "C" __declspec(dllexport)
Iexport_class* __stdcall GetExported_Class();

When VS2008 compiled the source for this, the dll produced contains this under its export table:

_GetExported_Class@0

For compatibility with other compilers I need the above decoration to look like this instead:

GetExported_Class

Changing the calling convention to __cdecl will decorate it to the way I want but the convention would be wrong so I can't use that. I need it to be decorated the way __cdecl looks but uses __stdcall instead.

Is there anyway to do this without using a .def file? Is there a switch or an option I can pass to the link.exe linker that can make it decorate the export name to the way I want?

Thanks


问:
copy all request attributes in class attributes
In my controller I have methods to store and update. As you see, I am copying $request attributes in $tour attributes one by one:

```<code>class TourController extends Controller
{
    public function store(Request $request, Tour $tour)
        {
          $tour->name = $request->name;
          $tour->flight = $request->flight;
          $tour->price = $request->price;
          $tour->description = $request->description;
          $tour->save();
          return redirect('home/tour/see');
        }
    public function update(Request $request)
        {
            $tour = Tour::find($request->id);
            $tour->name = $request->name;
            $tour->flight = $request->flight;
            $tour->price = $request->price;
            $tour->description = $request->description;
            $tour->save();
            return redirect('home/tour/see');
        }
}
</code>```

It seems, I'm repeating my code, and my question is, is there a way to copy all of them at once? How to copy all request attributes in tour attributes?

答:
You Can also Try this:

```<code>Tour::create($request->all());
</code>```

for more
See laravel docs

Body:
In my controller I have methods to store and update. As you see, I am copying $request attributes in $tour attributes one by one:

class TourController extends Controller
{
    public function store(Request $request, Tour $tour)
        {
          $tour->name = $request->name;
          $tour->flight = $request->flight;
          $tour->price = $request->price;
          $tour->description = $request->description;
          $tour->save();
          return redirect('home/tour/see');
        }
    public function update(Request $request)
        {
            $tour = Tour::find($request->id);
            $tour->name = $request->name;
            $tour->flight = $request->flight;
            $tour->price = $request->price;
            $tour->description = $request->description;
            $tour->save();
            return redirect('home/tour/see');
        }
}

It seems, I'm repeating my code, and my question is, is there a way to copy all of them at once? How to copy all request attributes in tour attributes?

Body:
You Can also Try this:

Tour::create($request->all());

for more
See laravel docs


问:
CakePHP returns ?? when querying MySQL for Chinese Characters
We started adding Chinese language support to our application. Our DB Charset is set to UTF8 and I can successfully query from MySQL CLI and see the word in Chinese characters

However, when I try to use CakePHP query method "findAll", the value is returned as ?? instead of the Chinese characters

Our DB config in database.php looks like this:

```<code>public $default = array(
                'datasource' => 'Database/Mysql',
                'persistent' => true,
                'host' => 'localhost',
                'login' => 'root',
                'password' => '******',
                'database' => '******',
                'prefix' => '******',
                'encoding' => 'utf8'
        );
</code>```

Also we have this line set in core.php:

```<code>Configure::write('App.encoding', 'UTF-8');
</code>```

We don't have any views set for this, we are using REST APIs so we are mainly just doing an "echo" in the Controller method for whatever response we get from the DB.

I also tried to create a test file and write this code in it:

```<code><?php echo '基本' ?>
</code>```

And it worked fine.

Any suggestions on how to get this to work?

答:
Turned out that I needed to install php-mbstring which wasn't installed
Once I installed it and restarted apache, it worked like a charm</p>

Body:
We started adding Chinese language support to our application. Our DB Charset is set to UTF8 and I can successfully query from MySQL CLI and see the word in Chinese characters

However, when I try to use CakePHP query method "findAll", the value is returned as ?? instead of the Chinese characters

Our DB config in database.php looks like this:

public $default = array(
                'datasource' => 'Database/Mysql',
                'persistent' => true,
                'host' => 'localhost',
                'login' => 'root',
                'password' => '******',
                'database' => '******',
                'prefix' => '******',
                'encoding' => 'utf8'
        );

Also we have this line set in core.php:

Configure::write('App.encoding', 'UTF-8');

We don't have any views set for this, we are using REST APIs so we are mainly just doing an "echo" in the Controller method for whatever response we get from the DB.

I also tried to create a test file and write this code in it:

<?php echo '基本' ?>

And it worked fine.

Any suggestions on how to get this to work?


问:
facing problems using checkbox form-controls in cakephp project using materialize css framework
My cakephp template file is

```<code><div class="row">
<div class="members form col l6 m8 s12 offset-l3 offset-m2 ">
<h3>Introduce a Member</h3>
<div class="divider"></div>
<br>
    <?= $this->Form->create($member) ?>
        <div class='input-field'>
            <?= $this->Form->input('name',array('div'=>'input')); ?>
        </div>
        <div class='input-field'>
            <?= $this->Form->input('father_or_husband'); ?>
        </div>
        <div class='input-field'>
            <?= $this->Form->input('age'); ?>
        </div>
        <div class='input-field'>
            <?= $this->Form->input('post'); ?>
        </div>
        <div class='input-field'>
            <?= $this->Form->input('school_name'); ?>
        </div>
        <div class='input-field'>
            <?= $this->Form->input('current_status'); ?>
        </div><br>
        <div class="row">
            <?= $this->Form->input('date_of_retirement',array(
                                                        'type'=>'date',
                                                            'class'=>'datepicker'
                                                            )); ?>
        </div>
        <div class="input-field row">
            <?=
                $this->Form->input('payment_status',array('type'=>'checkbox'));
             ?>
        </div><br>
        <?= $this->Form->button(__('Submit'),['class'=>'waves-effect waves-light btn']); ?>
    <?= $this->Form->end() ?>
</div>
</code>```

Although I am trying to use the checkbox and datepicker here. But they did not appear in my project when browsed. Please help?

答:
@Aditya Soni, Materialize checkboxes are wrapped in  tags. I had the same problem.
In order to solve this problem, I had to use jquery to wrap my checkboxes in  tags withing my code like below:

Body:
My cakephp template file is

Introduce a Member

    <?= $this->Form->create($member) ?>

            <?= $this->Form->input('name',array('div'=>'input')); ?>

            <?= $this->Form->input('father_or_husband'); ?>

            <?= $this->Form->input('age'); ?>

            <?= $this->Form->input('post'); ?>

            <?= $this->Form->input('school_name'); ?>

            <?= $this->Form->input('current_status'); ?>

            <?= $this->Form->input('date_of_retirement',array(
                                                        'type'=>'date',
                                                            'class'=>'datepicker'
                                                            )); ?>

            <?=
                $this->Form->input('payment_status',array('type'=>'checkbox'));
             ?>

        <?= $this->Form->button(__('Submit'),['class'=>'waves-effect waves-light btn']); ?>
    <?= $this->Form->end() ?>

Although I am trying to use the checkbox and datepicker here. But they did not appear in my project when browsed. Please help?

Body:
@Aditya Soni, Materialize checkboxes are wrapped in <label> tags. I had the same problem.
In order to solve this problem, I had to use jquery to wrap my checkboxes in <label> tags withing my code like below:

<script>
$('#PaymentStatus').wrap("<label></label>");
</script>


问:
Expected Expression Error xCode for iOS
I get an xCode error for "Expected Expression" on the last line for ]];

```<code>[[sections addObject: @[@"Section",
                      @[@"Videos", @"YOUTUBE", @"UClNZzDwpw3jSjf8bWCMkvrg" ],
                      @[@"Twitter", @"TWITTER", @"TheMC_OG"],
                      @[@"Facebook", @"FACEBOOK", @"1450927785128543" ],
                      @[@"Instagram", @"INSTAGRAM", @"1468344498"]],
                      @[@"Whiskey Ducks", @"WEB", @[@"http://WhiskeyDucks.us" ]],
                      @[@"Apparel", @"WEB", @[@"http://GcpMC.Spreadshirt.com" ]],
]];
</code>```

Im new to Coding and need help fixing this.

here is the full code if you need it in universal Config.m

答:
Try this :</p>

```<code>[sections addObject:@[@"Section",@[@"Videos", @"YOUTUBE", @"UClNZzDwpw3jSjf8bWCMkvrg" ],@[@"Twitter", @"TWITTER", @"TheMC_OG"],@[@"Facebook", @"FACEBOOK", @"1450927785128543"],@[@"Instagram", @"INSTAGRAM", @"1468344498"],@[@"Whiskey Ducks", @"WEB"], @[@"http://WhiskeyDucks.us"],@[@"Apparel", @"WEB"], @[@"http://GcpMC.Spreadshirt.com"]]];
</code>```

Title: Expected Expression Error xCode for iOS

Body:
I get an xCode error for "Expected Expression" on the last line for ]];

[[sections addObject: @[@"Section",
                      @[@"Videos", @"YOUTUBE", @"UClNZzDwpw3jSjf8bWCMkvrg" ],
                      @[@"Twitter", @"TWITTER", @"TheMC_OG"],
                      @[@"Facebook", @"FACEBOOK", @"1450927785128543" ],
                      @[@"Instagram", @"INSTAGRAM", @"1468344498"]],
                      @[@"Whiskey Ducks", @"WEB", @[@"http://WhiskeyDucks.us" ]],
                      @[@"Apparel", @"WEB", @[@"http://GcpMC.Spreadshirt.com" ]],
]];

Im new to Coding and need help fixing this.

here is the full code if you need it in universal Config.m

Body:
Try this :

[sections addObject:@[@"Section",@[@"Videos", @"YOUTUBE", @"UClNZzDwpw3jSjf8bWCMkvrg" ],@[@"Twitter", @"TWITTER", @"TheMC_OG"],@[@"Facebook", @"FACEBOOK", @"1450927785128543"],@[@"Instagram", @"INSTAGRAM", @"1468344498"],@[@"Whiskey Ducks", @"WEB"], @[@"http://WhiskeyDucks.us"],@[@"Apparel", @"WEB"], @[@"http://GcpMC.Spreadshirt.com"]]];