问:
How to debug kuberenetes system pod elections on masters?
I'm trying to make SSL work with kubernetes, but am stuck with leader election problem. So I think I should be seeing scheduler and controller system pods somewhere, while all I have is this:

kubectl get po --namespace=kube-system
NAME                             READY     STATUS    RESTARTS   AGE
kube-apiserver-10.255.12.200     1/1       Running   0          18h
kube-apiserver-10.255.16.111     1/1       Running   0          20h
kube-apiserver-10.255.17.12      1/1       Running   0          20h
scheduler-master-10.255.12.200   2/2       Running   0          20h
scheduler-master-10.255.16.111   2/2       Running   0          20h
scheduler-master-10.255.17.12    2/2       Running   0          20h

as for comparison, on my other clusters, I can see more pods:

kubectl get po --namespace=kube-system
NAME                                    READY     STATUS    RESTARTS   AGE
kube-apiserver-10.255.0.248             1/1       Running   1          30d
kube-apiserver-10.255.1.112             1/1       Running   1          30d
kube-apiserver-10.255.1.216             1/1       Running   1          30d
kube-controller-manager-10.255.1.216    1/1       Running   3          30d
kube-scheduler-10.255.1.216             1/1       Running   1          30d
scheduler-master-10.255.0.248           2/2       Running   2          30d
scheduler-master-10.255.1.112           2/2       Running   2          30d
scheduler-master-10.255.1.216           2/2       Running   2          30d

Does anybody knows how to debug this ? Pod logs doesn't show much, and my pods are stuck in pending state.

答:
Several things could be happening:

Were the two clusters created the same way? Note that, depending on the cluster, some services like the scheduler or the controller could be running on bare metal. If that is the case, then you should check the logs inside the node using, for instance, systemctl status <name-of-the-service>.service (in case it is using systemd).

In case these modules are meant to be running as pods, then I would advise you to go to the master node and check /etc/kubernetes/manifests. You should find the maniphests of the services you are looking for. If they are not, then you have the reason why you do not find the pods in the system. If the pods are there, then check if the arguments are properly set (especially the --leader-elect one)


来源: stackexchange

问:
How to bind server side data to some html element using vue.js
I have a server-side node app and I would like to add some basic web interface for the app. I'm following introductory vue.js tutorials, but don't see anything related to what I'm trying to do.

Imagine, that I have this server-side node app:

```<code>var state = { message: 'hello world', count: 0 };
function work() {
    state.message = 'hello world ' + (state.count++);
}
setInterval(work, 1000);
</code>```

Now, to add the web interface for the app I added some basic http server code:

```<code>var state = { message: 'hello world', count: 0 };
function work() {
    state.message = 'hello world ' + (state.count++);
}
setInterval(work, 1000);

var http = require('http');
var port = process.env.PORT || 1337;

http.createServer(function (req, res) {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('message: ' + state.message+'\n');
}).listen(port);
</code>```

It "works": if I refresh page I'll see value of my state of the app. Now I want to update this simple app to automatically update view on client side to reflect any changes to the state that were done on server side. I could change that web page to automatically refresh every second or something like that to reflect any server changes, but I'm looking for something that was designed to do exactly that. Eventually I'll need to make that web interface to be able to change some of that server state (to change state.count for example). How can this be done with vue.js, or I should use something else for that or should I simply code all that logic to pass updated state.count using http POST/GET to my web interface?

答:
What you are describing is websockets. With your current code, you are creating a connection, and then closing the connection when you call res.end.

You want something that allows an open connection between server and front-end without needing a constant request. Take a look at https://socket.io/ and specific Vue implementation:

https://medium.com/@michaelmangial1/getting-started-with-vue-js-socket-io-8d385ffb9782

ContentLicense: CC BY-SA 4.0

Body:
I have a server-side node app and I would like to add some basic web interface for the app. I'm following introductory vue.js tutorials, but don't see anything related to what I'm trying to do.

Imagine, that I have this server-side node app:

var state = { message: 'hello world', count: 0 };
function work() {
    state.message = 'hello world ' + (state.count++);
}
setInterval(work, 1000);

Now, to add the web interface for the app I added some basic http server code:

var state = { message: 'hello world', count: 0 };
function work() {
    state.message = 'hello world ' + (state.count++);
}
setInterval(work, 1000);

var http = require('http');
var port = process.env.PORT || 1337;

http.createServer(function (req, res) {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('message: ' + state.message+'\n');
}).listen(port);

It "works": if I refresh page I'll see value of my state of the app. Now I want to update this simple app to automatically update view on client side to reflect any changes to the state that were done on server side. I could change that web page to automatically refresh every second or something like that to reflect any server changes, but I'm looking for something that was designed to do exactly that. Eventually I'll need to make that web interface to be able to change some of that server state (to change state.count for example). How can this be done with vue.js, or I should use something else for that or should I simply code all that logic to pass updated state.count using http POST/GET to my web interface?

ContentLicense: CC BY-SA 3.0


问:
Accept server's self-signed ssl certificate in Java client
It looks like a standard question, but I couldn't find clear directions anywhere.

I have java code trying to connect to a server with probably self-signed (or expired) certificate. The code reports the following error :

```<code>[HttpMethodDirector] I/O exception (javax.net.ssl.SSLHandshakeException) caught
when processing request: sun.security.validator.ValidatorException: PKIX path
building failed: sun.security.provider.certpath.SunCertPathBuilderException:
unable to find valid certification path to requested target
</code>```

As I understand it, I have to use keytool and tell java that it's OK to allow this connection.

All instructions to fix this problem assume I'm fully proficient with keytool, such as

generate private key for server and import it into keystore

Is there anybody who could post detailed instructions?

I'm running unix, so bash script would be best.

Not sure if it's important, but code executed in jboss.

答:
Trust all SSL certificates:-
You can bypass SSL if you want to test on the testing server.
But do not use this code for production.

```<code>public static class NukeSSLCerts {
protected static final String TAG = "NukeSSLCerts";

public static void nuke() {
    try {
        TrustManager[] trustAllCerts = new TrustManager[] {
            new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    X509Certificate[] myTrustedAnchors = new X509Certificate[0];
                    return myTrustedAnchors;
                }

                @Override
                public void checkClientTrusted(X509Certificate[] certs, String authType) {}

                @Override
                public void checkServerTrusted(X509Certificate[] certs, String authType) {}
            }
        };

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        });
    } catch (Exception e) {
    }
}
</code>```

}

Please call this function in onCreate() function in Activity or in your Application Class.

```<code>NukeSSLCerts.nuke();
</code>```

This can be used for Volley in Android.

Body:
It looks like a standard question, but I couldn't find clear directions anywhere.

I have java code trying to connect to a server with probably self-signed (or expired) certificate. The code reports the following error :

[HttpMethodDirector] I/O exception (javax.net.ssl.SSLHandshakeException) caught
when processing request: sun.security.validator.ValidatorException: PKIX path
building failed: sun.security.provider.certpath.SunCertPathBuilderException:
unable to find valid certification path to requested target

As I understand it, I have to use keytool and tell java that it's OK to allow this connection.

All instructions to fix this problem assume I'm fully proficient with keytool, such as

generate private key for server and import it into keystore

Is there anybody who could post detailed instructions?

I'm running unix, so bash script would be best.

Not sure if it's important, but code executed in jboss.

Body:
Trust all SSL certificates:-
You can bypass SSL if you want to test on the testing server.
But do not use this code for production.

public static class NukeSSLCerts {
protected static final String TAG = "NukeSSLCerts";

public static void nuke() {
    try {
        TrustManager[] trustAllCerts = new TrustManager[] {
            new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    X509Certificate[] myTrustedAnchors = new X509Certificate[0];
                    return myTrustedAnchors;
                }

                @Override
                public void checkClientTrusted(X509Certificate[] certs, String authType) {}

                @Override
                public void checkServerTrusted(X509Certificate[] certs, String authType) {}
            }
        };

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        });
    } catch (Exception e) {
    }
}

}

Please call this function in onCreate() function in Activity or in your Application Class.

NukeSSLCerts.nuke();

This can be used for Volley in Android.


问:
How to insert value into foreign key in SQL server? (Avoid the duplicate key.)
I create two table. They connected by primary key and foreign key. When I insert new values, it said cannot insert duplicate key in object. Here are my tables

```<code>create table person (
sinNum int primary key not null,
gender varchar(6) not null check (gender in ('male','female')) default 'female',
age int not null check (age>=18 and age<=100),
emailAddr varchar (50) not null,
phoneNum int not null,
)

create table employee (
empId int identity (1,1) unique,
lastName varchar (30) not null,
firstName varchar (30) not null,
sinNum int unique foreign key references person (sinNum),
departmentId int foreign key references department (departmentId),
position varchar (20) not null check (position in ('clerk','assistant','supervisor','manager','director','president')) default'clerk',
baseSalary float not null
)
</code>```

Here are my insert statements

```<code>insert into person (sinNum,gender,age,emailAddr, phoneNum) values (333,
'female', 24, 'dds', 2121)

insert into employee(lastName,firstName, sinNum, departmentId,
position,baseSalary) values ('Snow','John',333,20,'clerk',4000)
</code>```

Here are the error messages

Violation of PRIMARY KEY constraint 'PK__person__228E26BE3A9512B2'.
  Cannot insert duplicate key in object 'dbo.person'. The duplicate key
  value is (333).

Can anyone show me the way please? Many thanks

答:
Since sinNum is your primary key, if you try to INSERT a new row containing the same value it will reject you.

Just use the following query to delete the rows before adding it again.

```<code>DELETE FROM person WHERE sinNum = 333;
</code>```

You can also update/merge the row or simply not add it, since you have done it already.

Body:
I create two table. They connected by primary key and foreign key. When I insert new values, it said cannot insert duplicate key in object. Here are my tables

create table person (
sinNum int primary key not null,
gender varchar(6) not null check (gender in ('male','female')) default 'female',
age int not null check (age>=18 and age<=100),
emailAddr varchar (50) not null,
phoneNum int not null,
)

create table employee (
empId int identity (1,1) unique,
lastName varchar (30) not null,
firstName varchar (30) not null,
sinNum int unique foreign key references person (sinNum),
departmentId int foreign key references department (departmentId),
position varchar (20) not null check (position in ('clerk','assistant','supervisor','manager','director','president')) default'clerk',
baseSalary float not null
)

Here are my insert statements

insert into person (sinNum,gender,age,emailAddr, phoneNum) values (333,
'female', 24, 'dds', 2121)

insert into employee(lastName,firstName, sinNum, departmentId,
position,baseSalary) values ('Snow','John',333,20,'clerk',4000)

Here are the error messages

Violation of PRIMARY KEY constraint 'PK__person__228E26BE3A9512B2'.
  Cannot insert duplicate key in object 'dbo.person'. The duplicate key
  value is (333).

Can anyone show me the way please? Many thanks

Body:
Since sinNum is your primary key, if you try to INSERT a new row containing the same value it will reject you.

Just use the following query to delete the rows before adding it again.

DELETE FROM person WHERE sinNum = 333;

You can also update/merge the row or simply not add it, since you have done it already.


问:
Searching a 3D array for closest point satisfying a certain predicate
I'm looking for an enumeration algorithm to search through a 3D array "sphering" around a given starting point.

Given an array a of size NxNxN where each N is 2^k for some k, and a point p in that array. The algorithm I'm looking for should do the following: If a[p] satisfies a certain predicate, the algorithm stops and p is returned. Otherwise the next point q is checked, where q is another point in the array that is the closest to p and hasn't been visited yet. If that doesn't match either, the next q'is checked an so on until in the worst case the whole array has been searched.

By "closest" here the perfect solution would be the point q that has the smallest Euclidean distance to p. As only discrete points have to be considered, perhaps some clever enumeration algorithm woukd make that possible. However, if this gets too complicated, the smallest Manhattan distance would be fine too. If there are several nearest points, it doesn't matter which one should be considered next.

Is there already an algorithm that can be used for this task?

答:
This is pseudocode for a simple algorithm that will search in increasing-radius spherical husks until it either finds a point or it runs out of array. Let us assume that condition returns either true or false and has access to the x, y, z coordinates being tested and the array itself, returning false (instead of exploding) for out-of-bounds coordinates:

```<code>def find_from_center(center, max_radius, condition) returns a point
  let radius = 0
  while radius < max_radius,
     let point = find_in_spherical_husk(center, radius, condition)
     if (point != null) return point
     radius ++
  return null
</code>```

the hard part is inside find_in_spherical_husk. We are interested in checking out points such that

```<code>dist(center, p) >= radius AND dist(center, p) < radius+1
</code>```

which will be our operating definition of husk. We could iterate over the whole 3D array in O(n^3) looking for those, but that would be really expensive in terms of time. A better pseudocode is the following:

```<code>def find_in_spherical_husk(center, radius, condition)
   let z = center.z - radius // current slice height
   let r = 0 // current circle radius; maxes at equator, then decreases
   while z <= center + radius,
     let z_center = (z, center.x, point.y)
     let point = find_in_z_circle(z_center, r)
     if (point != null) return point
     // prepare for next z-sliced cirle
     z ++
     r = sqrt(radius*radius - (z-center.z)*(z-center.z))
</code>```

the idea here is to slice each husk into circles along the z-axis (any axis will do), and then look at each slice separately. If you were looking at the earth, and the poles were the z axis, you would be slicing from north to south. Finally, you would implement find_in_z_circle(z_center, r, condition) to look at the circumference of each of those circles. You can avoid some math there by using the Bresenham circle-drawing algorithm; but I assume that the savings are negligible compared with the cost of checking condition.

Body:
This is pseudocode for a simple algorithm that will search in increasing-radius spherical husks until it either finds a point or it runs out of array. Let us assume that condition returns either true or false and has access to the x, y, z coordinates being tested and the array itself, returning false (instead of exploding) for out-of-bounds coordinates:

def find_from_center(center, max_radius, condition) returns a point
  let radius = 0
  while radius < max_radius,
     let point = find_in_spherical_husk(center, radius, condition)
     if (point != null) return point
     radius ++
  return null

the hard part is inside find_in_spherical_husk. We are interested in checking out points such that

dist(center, p) >= radius AND dist(center, p) < radius+1

which will be our operating definition of husk. We could iterate over the whole 3D array in O(n^3) looking for those, but that would be really expensive in terms of time. A better pseudocode is the following:

def find_in_spherical_husk(center, radius, condition)
   let z = center.z - radius // current slice height
   let r = 0 // current circle radius; maxes at equator, then decreases
   while z <= center + radius,
     let z_center = (z, center.x, point.y)
     let point = find_in_z_circle(z_center, r)
     if (point != null) return point
     // prepare for next z-sliced cirle
     z ++
     r = sqrt(radius*radius - (z-center.z)*(z-center.z))

the idea here is to slice each husk into circles along the z-axis (any axis will do), and then look at each slice separately. If you were looking at the earth, and the poles were the z axis, you would be slicing from north to south. Finally, you would implement find_in_z_circle(z_center, r, condition) to look at the circumference of each of those circles. You can avoid some math there by using the Bresenham circle-drawing algorithm; but I assume that the savings are negligible compared with the cost of checking condition.


问:
Why is the body height=0 on a newly created Jhipster project?
I just created my first jhipster application and followed the instructions on how to set up my IDE (eclipse).

After that, I ran the gradle bootRun task (in eclipse), and everything went fine.

When I visited the localhost address, the page was blank. Investigating the issue in firefox (f12), it showed that the body had a height of 0.

After trying to manually stretch the html body by setting its height manually to 100vt in the index.html file, another investigation via f12 showed, that the new settings was applied (the height was 100vt now), but the page was still blank.

What could be the issue? I already confirmed, that all needed files exist, so it cannot be a file not found issue

Interestingly, the page's name is displayed in the tab. As the name is defined in the index.html's header, the file must be correctly deployed, but there must be some kind of problem in the generated part.

EDIT

running yarn run webpack:build

```<code>yarn run v0.23.2
$ yarn run cleanup && yarn run webpack:build:vendor && yarn run webpack:build:dev
yarn run v0.23.2
$ rimraf build/{aot,www}
The command "rimraf" is either spelled incorrectly or could not be found
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
</code>```

EDIT 2

As someone mentioned in a comment, I may have to run yarn install, but this gives me the following error, which I do not understand at all...

```<code>error C:\CUBE\workspace\cube\node_modules\generator-jhipster: Command failed.
Exit code: 1
Command: C:\WINDOWS\system32\cmd.exe
Arguments: /d /s /c tabtab install --name jhipster --auto
Directory: C:\CUBE\workspace\cube\node_modules\generator-jhipster
Output:
Fri, 30 Jun 2017 14:40:09 GMT tabtab:installer Installing completion script to fish directory
fs.js:641
  return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
                 ^
Error: ENOENT: no such file or directory, open 'C:\CUBE\workspace\cube\node_modules\tabtab\scripts\C:\Program Files\Git\usr\bin\bash.sh'
    at Error (native)
    at Object.fs.openSync (fs.js:641:18)
    at fs.readFileSync (fs.js:509:33)
    at Complete.script (C:\CUBE\workspace\cube\node_modules\tabtab\src\complete.js:373:14)
    at Installer.writeTo (C:\CUBE\workspace\cube\node_modules\tabtab\src\installer.js:91:34)
    at Installer.handle (C:\CUBE\workspace\cube\node_modules\tabtab\src\installer.js:80:21)
    at Commands.install (C:\CUBE\workspace\cube\node_modules\tabtab\src\commands\index.js:75:22)
    at Object.<anonymous> (C:\CUBE\workspace\cube\node_modules\tabtab\src\cli.js:33:16)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
</code>```

答:
It seems that the generation missed something.

When I started using JHipster I has similar problems.

I solved them by following the installation instructions (again). At the first try I got problems, then I re-installed all those components and then I re-generated my app.

The second time I had no problems and all went good!

In my opinion some errors come out during generation process, that's why your page comes blank. Try to re-install, or simply update, your tools and plugins and then re-generate your project.

Follow this link for further informations.

Body:
I just created my first jhipster application and followed the instructions on how to set up my IDE (eclipse).

After that, I ran the gradle bootRun task (in eclipse), and everything went fine.

When I visited the localhost address, the page was blank. Investigating the issue in firefox (f12), it showed that the body had a height of 0.

After trying to manually stretch the html body by setting its height manually to 100vt in the index.html file, another investigation via f12 showed, that the new settings was applied (the height was 100vt now), but the page was still blank.

What could be the issue? I already confirmed, that all needed files exist, so it cannot be a file not found issue

Interestingly, the page's name is displayed in the tab. As the name is defined in the index.html's header, the file must be correctly deployed, but there must be some kind of problem in the generated part.

EDIT

running yarn run webpack:build

yarn run v0.23.2
$ yarn run cleanup && yarn run webpack:build:vendor && yarn run webpack:build:dev
yarn run v0.23.2
$ rimraf build/{aot,www}
The command "rimraf" is either spelled incorrectly or could not be found
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

EDIT 2

As someone mentioned in a comment, I may have to run yarn install, but this gives me the following error, which I do not understand at all...

error C:\CUBE\workspace\cube\node_modules\generator-jhipster: Command failed.
Exit code: 1
Command: C:\WINDOWS\system32\cmd.exe
Arguments: /d /s /c tabtab install --name jhipster --auto
Directory: C:\CUBE\workspace\cube\node_modules\generator-jhipster
Output:
Fri, 30 Jun 2017 14:40:09 GMT tabtab:installer Installing completion script to fish directory
fs.js:641
  return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
                 ^
Error: ENOENT: no such file or directory, open 'C:\CUBE\workspace\cube\node_modules\tabtab\scripts\C:\Program Files\Git\usr\bin\bash.sh'
    at Error (native)
    at Object.fs.openSync (fs.js:641:18)
    at fs.readFileSync (fs.js:509:33)
    at Complete.script (C:\CUBE\workspace\cube\node_modules\tabtab\src\complete.js:373:14)
    at Installer.writeTo (C:\CUBE\workspace\cube\node_modules\tabtab\src\installer.js:91:34)
    at Installer.handle (C:\CUBE\workspace\cube\node_modules\tabtab\src\installer.js:80:21)
    at Commands.install (C:\CUBE\workspace\cube\node_modules\tabtab\src\commands\index.js:75:22)
    at Object.<anonymous> (C:\CUBE\workspace\cube\node_modules\tabtab\src\cli.js:33:16)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.


问:
How to make button's "pushed" effect?
I have 3 buttons that represents 3 states. I'd like when I push some of them that button stays in visual "push" state and other 2 are in normal non-pushed state.

Here's the code I use:

if (itemType === 'default') {
  document.getElementById("defaultMode").classList.remove('non-pushed');
  document.getElementById("defaultMode").classList.add('pushed');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.pushed {
  border-style: inset;
}

.non-pushed {
  border-style: solid;
}</code>```

<button id="defaultMode" class="non-pushed" onclick="setMode('link', 'default');">Default</button>
<button id="orthoMode" onclick="setMode('link', 'ortho');">Ortho</button>
<button id="cornerMode" onclick="setMode('link', 'corner');">Corner</button>```

But, it's not working.

答:
You don't need javascript for this. CSS is enough. Use :active pseudoclass.

button {
  background-color: #ccc;
  border: outset 3px #666;
}

button:hover {
  background-color: #E5E5E5;
}

button:active {
  background-color: #bbb;
  border: inset 3px #666;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button>Hello!</button></code>```

Title: How to make button's "pushed" effect?

Body:
I have 3 buttons that represents 3 states. I'd like when I push some of them that button stays in visual "push" state and other 2 are in normal non-pushed state.

Here's the code I use:

if (itemType === 'default') {
  document.getElementById("defaultMode").classList.remove('non-pushed');
  document.getElementById("defaultMode").classList.add('pushed');
}

.pushed {
  border-style: inset;
}

.non-pushed {
  border-style: solid;
}

<button id="defaultMode" class="non-pushed" onclick="setMode('link', 'default');">Default</button>
<button id="orthoMode" onclick="setMode('link', 'ortho');">Ortho</button>
<button id="cornerMode" onclick="setMode('link', 'corner');">Corner</button>

But, it's not working.

Body:
You don't need javascript for this. CSS is enough. Use :active pseudoclass.

button {
  background-color: #ccc;
  border: outset 3px #666;
}

button:hover {
  background-color: #E5E5E5;
}

button:active {
  background-color: #bbb;
  border: inset 3px #666;
}

<button>Hello!</button>


答:
itemType is undefined one .you should define var itemType = 'default'

or

You could create the function in DOM

function setMode(link,itemType){
if (itemType === 'default') {
  document.getElementById("defaultMode").classList.remove('non-pushed');
  document.getElementById("defaultMode").classList.add('pushed');
  console.log(document.getElementById("defaultMode").outerHTML)
}
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.pushed {
    border-style: inset;
}

.non-pushed {
    border-style: solid;
}</code>```

<button id="defaultMode" class="non-pushed" onclick="setMode('link', 'default')">Default</button>
<button id="orthoMode" onclick="setMode('link', 'ortho');">Ortho</button>
<button id="cornerMode" onclick="setMode('link', 'corner');">Corner</button>```

Title: How to make button's "pushed" effect?

Body:
itemType is undefined one .you should define var itemType = 'default'

or

You could create the function in DOM

function setMode(link,itemType){
if (itemType === 'default') {
  document.getElementById("defaultMode").classList.remove('non-pushed');
  document.getElementById("defaultMode").classList.add('pushed');
  console.log(document.getElementById("defaultMode").outerHTML)
}
}

.pushed {
    border-style: inset;
}

.non-pushed {
    border-style: solid;
}

<button id="defaultMode" class="non-pushed" onclick="setMode('link', 'default')">Default</button>
<button id="orthoMode" onclick="setMode('link', 'ortho');">Ortho</button>
<button id="cornerMode" onclick="setMode('link', 'corner');">Corner</button>


问:
Twig function for repeating template
I'm new to Twig and recently started a project. In this I use a Star Rating Display very often, which needs also some values, e.g the rating to display or the size.

Currently, I always use

```<code><div class="ratingarea">
    {% include 'Artist:rating.html.twig'
    with {'rating': artist.rating, 'size': 'medium' } %}
</div>
</code>```

everywhere, which does the job, but I was wondering, if there's the option to reduce this to a function that only takes the parameters and returns the desired template, something like this:

```<code><div class="ratingarea"> {% rating(2.8, 'medium') %} </div>
</code>```

Is this possible? Or another way to improve this?

This is the template:

```<code><span>
  <div class="review-rating">
    <div class="rating {{size}}-rating">
      <div class="stars stars-fontawesome-o top-art">
        <select class="list-rating fontawesome-o "
                 data-current-rating="{{rating}}">
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
          <option value="4">4</option>
          <option value="5">5</option>
        </select>
      </div>
    </div>
  </div>
</span>
</code>```

答:
You can rely on macro's,

macro.twig

```<code>{% macro rating(rating, size) %}
<span>
  <div class="review-rating">
    <div class="rating {{size}}-rating">
      <div class="stars stars-fontawesome-o top-art">
        <select class="list-rating fontawesome-o " data-current-rating="{{rating}}">
          {% for i in 1..5 %}
          <option value="{{ i }}">{{ i }}</option>
          {% endfor %}
        </select>
      </div>
    </div>
  </div>
</span>
{% endmacro %}
</code>```

template.twig

```<code>{# import the macro's in the file "macro.twig" as the namespace `macro` #}
{% import "macro.twig" as macro %}
{{ macro.rating(2.5, 'medium') }}
</code>```

twigfiddle

Title: Twig function for repeating template

Body:
I'm new to Twig and recently started a project. In this I use a Star Rating Display very often, which needs also some values, e.g the rating to display or the size.

Currently, I always use

    {% include 'Artist:rating.html.twig'
    with {'rating': artist.rating, 'size': 'medium' } %}

everywhere, which does the job, but I was wondering, if there's the option to reduce this to a function that only takes the parameters and returns the desired template, something like this:

 {% rating(2.8, 'medium') %}

Is this possible? Or another way to improve this?

This is the template:

        <select class="list-rating fontawesome-o "
                 data-current-rating="{{rating}}">
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
          <option value="4">4</option>
          <option value="5">5</option>
        </select>

Body:
You can rely on macro's,

macro.twig

{% macro rating(rating, size) %}
<span>
  <div class="review-rating">
    <div class="rating {{size}}-rating">
      <div class="stars stars-fontawesome-o top-art">
        <select class="list-rating fontawesome-o " data-current-rating="{{rating}}">
          {% for i in 1..5 %}
          <option value="{{ i }}">{{ i }}</option>
          {% endfor %}
        </select>
      </div>
    </div>
  </div>
</span>
{% endmacro %}

template.twig

{# import the macro's in the file "macro.twig" as the namespace `macro` #}
{% import "macro.twig" as macro %}
{{ macro.rating(2.5, 'medium') }}

twigfiddle


问:
Use of undeclared identifier in Xcode 9.0
I am trying to integrate this framework manually in my Xcode project. As I am structuring my project, I am adding it inside a folder [not a group]. So then the problem is started, "use of undeclared identifier SkyFloatingLabelTextField. What should I do to make it work properly?

I tried the same in sample project as well and the error is same.

I am not getting any options when trying drag and drop the folder to the project structure. The same when try adding through "Add Files".

答:
I added the Sources folder inside another folder at the workspace.

Added the folder using "Add Files to ..." option.

Checked the Target Membership for all the files inside Sources folder, as it was not checked.

Although, it looks like source code of SkyFloatingLabelTextField, has not been updated for Swift4. You may need to do it yourself.


问:
convert text to image in php
I would like to style a text string taken from a form field and then convert it to a transparent .PNG (alpha BG).

Is this possible with PHP? If so, would you kindly show me how this would be achieved

答:
```<code>$image = imagecreate(widthyouwant,heightyouwant);
$bg = imagecolorallocatealpha($image,255,255,255,0);
$black = imagecolorallocate($image,255,255,255);
imagettftext($image,fontsize, 0, x, y, $black, "fontlocation", $_GET['text']);
header('Content-Type: image/png');
imagepng($image);
</code>```

You could then display the image by going
I think thats correct, been awhile since I've done this.

ContentLicense: CC BY-SA 2.5

Title: convert text to image in php

Body:
$image = imagecreate(widthyouwant,heightyouwant);
$bg = imagecolorallocatealpha($image,255,255,255,0);
$black = imagecolorallocate($image,255,255,255);
imagettftext($image,fontsize, 0, x, y, $black, "fontlocation", $_GET['text']);
header('Content-Type: image/png');
imagepng($image);

You could then display the image by going
I think thats correct, been awhile since I've done this.


问:
r - Count/percentage specific result per day
I have a dataset of about 15.000 observations spanning a couple of months.
Each date has a varying number of observations.
The result of each observation is either "1" or "0".

```<code>Obs   Reslt  Date         ....
1     0      19-02-2017
2     1      19-02-2017
3     0      19-02-2017
4     0      19-02-2017
5     1      20-02-2017
6     1      20-02-2017
7     0      20-02-2017
8     0      20-02-2017
</code>```

I would like to know the percentage of observation per day that have a result of "1".

In the example above the result would be:

```<code>19-02-2017 - 25%
20-02-2017 - 50%
</code>```

I was wondering if someone could help me with this.
Thank you!

答:
```<code>library('scales') #useful in percent conversion
> dat
  Obs Reslt       Date
1   1     0 19-02-2017
2   2     1 19-02-2017
3   3     0 19-02-2017
4   4     0 19-02-2017
5   5     1 20-02-2017
6   6     1 20-02-2017
7   7     0 20-02-2017
8   8     0 20-02-2017
res <- aggregate(dat$Reslt, by=list(Date=dat$Date), FUN=mean) #calculate mean from each group of rows based on row values in column Date
res[,2] <- res[,2]*100 #small manipulation of data to get procentage
res[,2] <- percent(res[,2] / 100)
>res
        Date   x
1 19-02-2017 25%
2 20-02-2017 50%
</code>```

Body:
I have a dataset of about 15.000 observations spanning a couple of months.
Each date has a varying number of observations.
The result of each observation is either "1" or "0".

Obs   Reslt  Date         ....
1     0      19-02-2017
2     1      19-02-2017
3     0      19-02-2017
4     0      19-02-2017
5     1      20-02-2017
6     1      20-02-2017
7     0      20-02-2017
8     0      20-02-2017

I would like to know the percentage of observation per day that have a result of "1".

In the example above the result would be:

19-02-2017 - 25%
20-02-2017 - 50%

I was wondering if someone could help me with this.
Thank you!


问:
Regular expression involving ">"
I have a file, file.fas, containing DNA like:

```<code>>1 CHROMOSOME "rest of header"
ATTCTGAGATCTGAGATCTGAGATCTGAGA

>1 CHROMOSOME "rest of header"
TCTGAGATCTATTCTGAGATCTATTCTGAGATCT
</code>```

Ideally, I would like replace the "1" with "Chr 1", so that it would look like:

```<code>>Chr1 CHROMOSOME "rest of header"
ATTCTGAGATCTGAGATCTGAGATCTGAGA

>Chr1 CHROMOSOME "rest of header"
TCTGAGATCTATTCTGAGATCTATTCTGAGATCT
</code>```

I first tried it with sed, find op grep, e.g.

```<code>grep '>1' -f file.fas
</code>```

Yet, it does not work. Does anyone has an idea why not?

答:
Use this command </p>

```<code>sed 's@>1@>Chr1@g' file.fas

s - means substituion

@ - seperator

>1 - pattern to search for and replace

@ - seperator

>Chr1- pattern to substitue

@ - sperator

g - substitute all occurences
</code>```

Title: Regular expression involving ">"

Body:
I have a file, file.fas, containing DNA like:

>1 CHROMOSOME "rest of header"
ATTCTGAGATCTGAGATCTGAGATCTGAGA

>1 CHROMOSOME "rest of header"
TCTGAGATCTATTCTGAGATCTATTCTGAGATCT

Ideally, I would like replace the "1" with "Chr 1", so that it would look like:

>Chr1 CHROMOSOME "rest of header"
ATTCTGAGATCTGAGATCTGAGATCTGAGA

>Chr1 CHROMOSOME "rest of header"
TCTGAGATCTATTCTGAGATCTATTCTGAGATCT

I first tried it with sed, find op grep, e.g.

grep '>1' -f file.fas

Yet, it does not work. Does anyone has an idea why not?

Body:
Use this command

sed 's@>1@>Chr1@g' file.fas

s - means substituion

@ - seperator

>1 - pattern to search for and replace

@ - seperator

>Chr1- pattern to substitue

@ - sperator

g - substitute all occurences


问:
JavaScript replace all ignoring case sensitivity
I am trying to replace all the occurences of a value in a string and with another value

what I have so far is

var result = "Cooker Works"
var searchterm = "cooker wor";

searchterm.split(" ").forEach(function (item) {
   result = result.replace(new RegExp(item, 'g'), "" + item + "");
});

console.log(result)```
</div>
</div>
</p>

<p>The result I am after should look like</p>

```result = "Cooker Wors";
```

I am having problems handling the case, Is there any way I can ignore this and still get the result I am after

答:
You need to use i modifier for case-insensitive matching

```<code>new RegExp(item, 'ig')
</code>```

var result = "Cooker Works"
var searchterm = "cooker wor";

searchterm.split(" ").forEach(function(item) {
  var matchs = result.match(new RegExp(item, 'ig'));
  if (matchs.length)
    result = result.replace(new RegExp(item, 'ig'), "" + matchs[0] + "");
});

console.log(result)```

Body:
I am trying to replace all the occurences of a value in a string and with another value

what I have so far is

var result = "Cooker Works"
var searchterm = "cooker wor";

searchterm.split(" ").forEach(function (item) {
   result = result.replace(new RegExp(item, 'g'), "" + item + "");
});

console.log(result)

The result I am after should look like

result = "Cooker Wors";

I am having problems handling the case, Is there any way I can ignore this and still get the result I am after

Body:
You need to use i modifier for case-insensitive matching

new RegExp(item, 'ig')

var result = "Cooker Works"
var searchterm = "cooker wor";

searchterm.split(" ").forEach(function(item) {
  var matchs = result.match(new RegExp(item, 'ig'));
  if (matchs.length)
    result = result.replace(new RegExp(item, 'ig'), "<strong>" + matchs[0] + "</strong>");
});

console.log(result)


问:
System.Diagnostics.Process.Start not work from on asp.net using IIS
I Have Asp.Net server, when I run it as debug on local its work fine.
But when I try to run it on IIS and get it from browser it does not work

For example line :
System.Diagnostics.Process.Start(@"c:\Program Files (x86)\Microsoft Office\Office12\excel.exe");

I have tried
System.Diagnostics.Process.Start not work from an IIS
And does not helped me

Thanks a lot

答:
@Thomas is right. you shouldn't try to launch another process from an unmonitored process like w3wp.exe. This is against best practices.

There are code samples available online which provide ways to read/write excel files.

Read Excel File into DataSet in ASP.NET Using C#

Manipulate Excel File with ASP.NET

Read Data From an Excel File (.xls) in ASP.NET

Read and Import Excel File into DataSet or DataTable using C# and VB.Net in ASP.Net


答:
You need to add case-insensitive modifier. do something like this:

    var result = "Cooker Works"
    var searchterm = "cooker wor";

    searchterm.split(" ").forEach(function (item) {
    result = result.replace(new RegExp('(' + item + ')', 'gi'),'$1');
    });
    console.log(result);```

Title: JavaScript replace all ignoring case sensitivity

Body:
You need to add case-insensitive modifier. do something like this:

    var result = "Cooker Works"
    var searchterm = "cooker wor";

    searchterm.split(" ").forEach(function (item) {
    result = result.replace(new RegExp('(' + item + ')', 'gi'),'<strong>$1</strong>');
    });
    console.log(result);


问:
How to make Android phone's back button work using Ajax in Javascript?
I have the following code to handle the back button of devices from Framework 7 in Javascript. I'd like to know if all subsequent pages are using Ajax, how do I use the back button to move back to my earlier page. At the moment, pressing the Back button, always prompts for the user if he wants to exit the app. The app has 20 pages, but they are all shown as Ajax pages and not a HTML page.

```<code><!-- We don't need full layout here, because this page will be parsed with Ajax-->
</code>```

Please help.  Thanks for the help!

```<code>        function onLoad() {
            document.addEventListener("deviceready", onDeviceReady, false);
        }
        // device APIs are available
        function onDeviceReady() {
            // Register the event listener
            document.addEventListener("backbutton", onBackKeyDown, false);
            document.addEventListener("menubutton", onMenuKeyDown, false);
        }
        // Handle the back button
        function onBackKeyDown(e) {
            e.preventDefault();
            navigator.notification.confirm("Are you sure you want to exit?", onConfirm, "Confirmation", "Yes,No");
            //navigator.app.backHistory();

            if (document.getElementById('#homepage')) {
                e.preventDefault();
                navigator.app.exitApp();
                navigator.notification.confirm("Are you sure you want to exit?", onConfirm, "Confirmation", "Yes,No");
            } else {
                navigator.app.backHistory();//This line doesn't work when tried on the if function - it seems useless - maybe not supported anymore?
                //the code never gets here coz other pages are simply loaded as Ajax, and there is only 1 index.html - how to fix?
            }
        }

        function onConfirm(button) {
            if (button == 2) { //If the user selected No, then we just do nothing
                return;
            } else {
                navigator.app.exitApp(); // Otherwise we quit the app.
            }
        }
        // Handle the menu button
        function onMenuKeyDown() {}
</code>```

答:
On framework 7 application you can handle back button to back to your earlier page using mainView.router.back().

```function onBackKeyDown(e) {

    if(mainView.activePage.name == 'yourhomepagename') {
        e.preventDefault();
        navigator.notification.confirm("Are you sure you want to exit?", onConfirm, "Confirmation", "Yes,No");
    } else {
        mainView.router.back({ ignoreCache: true });
    }

}```

Body:
I have the following code to handle the back button of devices from Framework 7 in Javascript. I'd like to know if all subsequent pages are using Ajax, how do I use the back button to move back to my earlier page. At the moment, pressing the Back button, always prompts for the user if he wants to exit the app. The app has 20 pages, but they are all shown as Ajax pages and not a HTML page.

Please help.  Thanks for the help!

        function onLoad() {
            document.addEventListener("deviceready", onDeviceReady, false);
        }
        // device APIs are available
        function onDeviceReady() {
            // Register the event listener
            document.addEventListener("backbutton", onBackKeyDown, false);
            document.addEventListener("menubutton", onMenuKeyDown, false);
        }
        // Handle the back button
        function onBackKeyDown(e) {
            e.preventDefault();
            navigator.notification.confirm("Are you sure you want to exit?", onConfirm, "Confirmation", "Yes,No");
            //navigator.app.backHistory();

            if (document.getElementById('#homepage')) {
                e.preventDefault();
                navigator.app.exitApp();
                navigator.notification.confirm("Are you sure you want to exit?", onConfirm, "Confirmation", "Yes,No");
            } else {
                navigator.app.backHistory();//This line doesn't work when tried on the if function - it seems useless - maybe not supported anymore?
                //the code never gets here coz other pages are simply loaded as Ajax, and there is only 1 index.html - how to fix?
            }
        }

        function onConfirm(button) {
            if (button == 2) { //If the user selected No, then we just do nothing
                return;
            } else {
                navigator.app.exitApp(); // Otherwise we quit the app.
            }
        }
        // Handle the menu button
        function onMenuKeyDown() {}

Body:
On framework 7 application you can handle back button to back to your earlier page using mainView.router.back().

function onBackKeyDown(e) {

    if(mainView.activePage.name == 'yourhomepagename') {
        e.preventDefault();
        navigator.notification.confirm("Are you sure you want to exit?", onConfirm, "Confirmation", "Yes,No");
    } else {
        mainView.router.back({ ignoreCache: true });
    }

}


问:
Split array into pairs of varying depth
Let there is an array a[0],a[1],..,a[6]. I want to implement an algorithm that will return all sorts of various amounts of depth. To make it more understandable, consider what i have to return the algorithm for different values of the depth

```<code>depth: 1,
return:
       (a[6] - a[0]); /*the only possible case for depth = 1*/

depth: 2,
return:
       (a[1] - a[0]) + (a[6] - a[2]); /*first case*/
       (a[2] - a[0]) + (a[6] - a[3]); /*second case*/
       (a[3] - a[0]) + (a[6] - a[4]); /*third case*/
       (a[4] - a[0]) + (a[6] - a[5]); /*fourth*/

depth: 3,
return:
       (a[1] - a[0]) + (a[3] - a[2]) + (a[6] - a[4]); /*first case*/
       (a[1] - a[0]) + (a[4] - a[2]) + (a[6] - a[5]); /*second case*/
       (a[2] - a[0]) + (a[4] - a[3]) + (a[6] - a[5]); /*third case*/
</code>```

It was an example for array of length 7. I want the algorithm worked for an array of arbitrary length.

I was able to implement the algorithm using recursion. The following is the code in C++

```<code>int arr[101]; /*Original array with length N = 100*/
set <__int64> Partitions; /*Set, for accumulation of the sum of the partitions*/

void get_partitions(int start, int end, int depth, int sum) {
    if (depth == 1) {
        sum += (arr[end] - arr[start]);

        Partitions.insert(sum);
    }
    else {
        int k = end - 2 * (depth - 1);
        int new_start = start + 1;

        while (new_start <= k) {
            int current_sum = (arr[new_start] - arr[new_start - 1]);

            get_partitions((new_start + 1), end, (depth - 1), (sum + current_sum));

            new_start++;
        }
    }
}

int main() {
    get_partitions(0, 100, 5, 0);

    //processing of Partitions

    return 0;
}
</code>```

This implementation has problem of work. For an array of large dimension, program execution time is too long.

Is it possible to improve the algorithm? Are there any other implementations of this algorithm? I would be grateful for answers.

答:
You might use the following:

```<code>std::vector<std::size_t> initialize(std::size_t depth)
{
    std::vector<std::size_t> res(depth - 1);

    int i = 1;
    for (auto& e : res) {
        e = i;
        i += 2;
    }
    return res;
}

bool increase(std::vector<std::size_t>& indexes, std::size_t max)
{
    auto m = max;
    auto rit = indexes.rbegin();
    for (; rit != indexes.rend(); ++rit) {
        ++*rit;
        if (*rit + 1 != m) {
            m = *rit;
            for (auto it = rit.base(); it != indexes.end(); ++it) {
                *it = m + 2;
                m += 2;
            }
            if (m < max) {
                return true;
            }
        }
        m = *rit - 1;
    }
    return false;
}
</code>```

Demo.

Title: Split array into pairs of varying depth

Body:
Let there is an array a[0],a[1],..,a[6]. I want to implement an algorithm that will return all sorts of various amounts of depth. To make it more understandable, consider what i have to return the algorithm for different values of the depth

depth: 1,
return:
       (a[6] - a[0]); /*the only possible case for depth = 1*/

depth: 2,
return:
       (a[1] - a[0]) + (a[6] - a[2]); /*first case*/
       (a[2] - a[0]) + (a[6] - a[3]); /*second case*/
       (a[3] - a[0]) + (a[6] - a[4]); /*third case*/
       (a[4] - a[0]) + (a[6] - a[5]); /*fourth*/

depth: 3,
return:
       (a[1] - a[0]) + (a[3] - a[2]) + (a[6] - a[4]); /*first case*/
       (a[1] - a[0]) + (a[4] - a[2]) + (a[6] - a[5]); /*second case*/
       (a[2] - a[0]) + (a[4] - a[3]) + (a[6] - a[5]); /*third case*/

It was an example for array of length 7. I want the algorithm worked for an array of arbitrary length.

I was able to implement the algorithm using recursion. The following is the code in C++

int arr[101]; /*Original array with length N = 100*/
set <__int64> Partitions; /*Set, for accumulation of the sum of the partitions*/

void get_partitions(int start, int end, int depth, int sum) {
    if (depth == 1) {
        sum += (arr[end] - arr[start]);

        Partitions.insert(sum);
    }
    else {
        int k = end - 2 * (depth - 1);
        int new_start = start + 1;

        while (new_start <= k) {
            int current_sum = (arr[new_start] - arr[new_start - 1]);

            get_partitions((new_start + 1), end, (depth - 1), (sum + current_sum));

            new_start++;
        }
    }
}

int main() {
    get_partitions(0, 100, 5, 0);

    //processing of Partitions

    return 0;
}

This implementation has problem of work. For an array of large dimension, program execution time is too long.

Is it possible to improve the algorithm? Are there any other implementations of this algorithm? I would be grateful for answers.

Body:
You might use the following:

std::vector<std::size_t> initialize(std::size_t depth)
{
    std::vector<std::size_t> res(depth - 1);

    int i = 1;
    for (auto& e : res) {
        e = i;
        i += 2;
    }
    return res;
}

bool increase(std::vector<std::size_t>& indexes, std::size_t max)
{
    auto m = max;
    auto rit = indexes.rbegin();
    for (; rit != indexes.rend(); ++rit) {
        ++*rit;
        if (*rit + 1 != m) {
            m = *rit;
            for (auto it = rit.base(); it != indexes.end(); ++it) {
                *it = m + 2;
                m += 2;
            }
            if (m < max) {
                return true;
            }
        }
        m = *rit - 1;
    }
    return false;
}

Demo.


问:
How to determine path of appsettings file in web.config
I am referencing my web app's settings using a configSource attribute for the appSettings element:

```<code><appSettings configSource="c:/settings/customer-settings.config"></appSettings>
</code>```

I would now like to access this path programmatically using a Configuration object:

```<code>Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
</code>```

However the configSource path does not seem to be available?

答:
Try using the file attribute instead of configSource. configSource requires your config to live inside the application path, while file does not have this restriction.

some more info: ASP.NET web.config: configSource vs. file attributes

Body:
I am referencing my web app's settings using a configSource attribute for the appSettings element:

<appSettings configSource="c:/settings/customer-settings.config"></appSettings>

I would now like to access this path programmatically using a Configuration object:

Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");

However the configSource path does not seem to be available?


问:
emacs public/protected/private label indentation of C++ header file not working for zero offset
I cannot get zero offset for some things for my C++ header files in emacs even if I have it defined in my .emacs file.

The header file below shows a class definition inside two namespaces and most importantly the public keyword I would like to have with zero offset like below.

```<code>namespace n1
{
namespace n2 // no offset
{

class SomeClass // no offset from namespace open curly
{
public: // this line with zero offset
    SomeClass(); // offset 4
    ...
};

inline SomeClass::SomeClass() // no offset
{
}

} // n2
} // n2
</code>```

In my .emacs file I have added label like this:

```<code>(c-set-offset 'label 0)
</code>```

I used Ctrl-C Ctrl-S to find out what to modify. Other offsets I have defined in the .emacs file are working fine and also values other than 0 work for label.

When I set offset 0 for label it turns out to be 1 when hitting tab for that line. This is strange and looks like something else is overriding or adding a minimum of 1.

Can anyone explain how I can achieve what I want and maybe also an explanation what is happening currently?

Phew, this was my first question here. Thanks :)

UPDATE:

Thanks to the answers I have been able to get a bit farther, but still no solution overall, because changing the things necessary to get total offset 0 for the accessors result in other things I don't want. Thsi is where I'm currently:

```<code>(c-set-offset 'access-label 0)
</code>```

I also needed to get the .h file to be understoor as C++, so I added:

```<code>(add-to-list 'auto-mode-alist '("\\.h\\'" . c++-mode))
</code>```

This alone is not removing the 1 offset I was seeing, but it seems there is also inclass for the accessor. Setting this to 0 actually results in total 0 offset.

```<code>(c-set-offset 'inclass 0)
</code>```

Problem is that now other things such as members are with total of 0 like below:

```<code>class Foo
{
public:
Foo();
~Foo();
</code>```

To remedy this I changed topmost-intro to offset 4

```<code>(c-set-offset 'topmost-intro 4)
</code>```

Which in turn resulted in other changes for e.g. inline function declarations in the same file. All in all, I'm not sure how to tweak this the way I want it.

UPDATE2:

Added inline declaration of SomeClass ctor with no offset.

答:
You want access-label instead of label, and if C-C C-S gave you ((label 1)) that's mean you are in C mode and not in C++ mode (C mode is the default for .h files).  If this is your problem, add

```<code>// Emacs, please set these
// Local Variables: ***
// mode: c++ ***
// End: ***
</code>```

to the end of your .h file or

```<code>// -*- C++ -*-
</code>```

at the start.

Body:
I cannot get zero offset for some things for my C++ header files in emacs even if I have it defined in my .emacs file.

The header file below shows a class definition inside two namespaces and most importantly the public keyword I would like to have with zero offset like below.

namespace n1
{
namespace n2 // no offset
{

class SomeClass // no offset from namespace open curly
{
public: // this line with zero offset
    SomeClass(); // offset 4
    ...
};

inline SomeClass::SomeClass() // no offset
{
}

} // n2
} // n2

In my .emacs file I have added label like this:

(c-set-offset 'label 0)

I used Ctrl-C Ctrl-S to find out what to modify. Other offsets I have defined in the .emacs file are working fine and also values other than 0 work for label.

When I set offset 0 for label it turns out to be 1 when hitting tab for that line. This is strange and looks like something else is overriding or adding a minimum of 1.

Can anyone explain how I can achieve what I want and maybe also an explanation what is happening currently?

Phew, this was my first question here. Thanks :)

UPDATE:

Thanks to the answers I have been able to get a bit farther, but still no solution overall, because changing the things necessary to get total offset 0 for the accessors result in other things I don't want. Thsi is where I'm currently:

(c-set-offset 'access-label 0)

I also needed to get the .h file to be understoor as C++, so I added:

(add-to-list 'auto-mode-alist '("\\.h\\'" . c++-mode))

This alone is not removing the 1 offset I was seeing, but it seems there is also inclass for the accessor. Setting this to 0 actually results in total 0 offset.

(c-set-offset 'inclass 0)

Problem is that now other things such as members are with total of 0 like below:

class Foo
{
public:
Foo();
~Foo();

To remedy this I changed topmost-intro to offset 4

(c-set-offset 'topmost-intro 4)

Which in turn resulted in other changes for e.g. inline function declarations in the same file. All in all, I'm not sure how to tweak this the way I want it.

UPDATE2:

Added inline declaration of SomeClass ctor with no offset.

Body:
You want access-label instead of label, and if C-C C-S gave you ((label 1)) that's mean you are in C mode and not in C++ mode (C mode is the default for .h files).  If this is your problem, add

// Emacs, please set these
// Local Variables: ***
// mode: c++ ***
// End: ***

to the end of your .h file or

// -*- C++ -*-

at the start.


问:
CUDA/C - Using malloc in kernel functions gives strange results
I'm new to CUDA/C and new to stack overflow. This is my first question.

I'm trying to allocate memory dynamically in a kernel function, but the results are unexpected.
I read using malloc() in a kernel can lower performance a lot, but I need it anyway so I first tried with a simple int ** array just to test the possibility, then I'll actually need to allocate more complex structs.

In my main I used cudaMalloc() to allocate the space for the array of int *, and then I used malloc() for every thread in the kernel function to allocate the array for every index of the outer array. I then used another thread to check the result, but it doesn't always work.

Here's main code:

```<code>#define N_CELLE 1024*2
#define L_CELLE 512

extern "C" {

int main(int argc, char **argv) {
  int *result = (int *)malloc(sizeof(int));
  int *d_result;
  int size_numbers = N_CELLE * sizeof(int *);
  int **d_numbers;

  cudaMalloc((void **)&d_numbers, size_numbers);
  cudaMalloc((void **)&d_result, sizeof(int *));

  kernel_one<<<2, 1024>>>(d_numbers);
  cudaDeviceSynchronize();
  kernel_two<<<1, 1>>>(d_numbers, d_result);

  cudaMemcpy(result, d_result, sizeof(int), cudaMemcpyDeviceToHost);

  printf("%d\n", *result);

  cudaFree(d_numbers);
  cudaFree(d_result);
  free(result);
}

}
</code>```

I used extern "C"because I could't compile while importing my header, which is not used in this example code. I pasted it since I don't know if this may be relevant or not.

This is kernel_one code:

```<code>__global__ void kernel_one(int **d_numbers) {
  int i = threadIdx.x + blockIdx.x * blockDim.x;
  d_numbers[i] = (int *)malloc(L_CELLE*sizeof(int));
  for(int j=0; j<L_CELLE;j++)
    d_numbers[i][j] = 1;
}
</code>```

And this is kernel_two code:

```<code>__global__ void kernel_two(int **d_numbers, int *d_result) {
  int temp = 0;
  for(int i=0; i<N_CELLE; i++) {
    for(int j=0; j<L_CELLE;j++)
      temp += d_numbers[i][j];
  }
  *d_result = temp;
}
</code>```

Everything works fine (aka the count is correct) until I use less than 1024*2*512 total blocks in device memory. For example, if I #define N_CELLE 1024*4 the program starts giving "random" results, such as negative numbers.
Any idea of what the problem could be?
Thanks anyone!

答:
In-kernel memory allocation draws memory from a statically allocated runtime heap. At larger sizes, you are exceeding the size of that heap and then your two kernels are attempting to read and write from uninitialised memory. This produces a runtime error on the device and renders the results invalid.  You would already know this if you either added correct API error checking on the host side, or ran your code with the  cuda-memcheck utility.

The solution is to ensure that the heap size is set to something appropriate before trying to run a kernel. Adding something like this:

```<code> size_t heapsize = sizeof(int) * size_t(N_CELLE) * size_t(2*L_CELLE);
 cudaDeviceSetLimit(cudaLimitMallocHeapSize, heapsize);
</code>```

to your host code before any other API calls, should solve the problem.

Body:
I'm new to CUDA/C and new to stack overflow. This is my first question.

I'm trying to allocate memory dynamically in a kernel function, but the results are unexpected.
I read using malloc() in a kernel can lower performance a lot, but I need it anyway so I first tried with a simple int ** array just to test the possibility, then I'll actually need to allocate more complex structs.

In my main I used cudaMalloc() to allocate the space for the array of int *, and then I used malloc() for every thread in the kernel function to allocate the array for every index of the outer array. I then used another thread to check the result, but it doesn't always work.

Here's main code:

#define N_CELLE 1024*2
#define L_CELLE 512

extern "C" {

int main(int argc, char **argv) {
  int *result = (int *)malloc(sizeof(int));
  int *d_result;
  int size_numbers = N_CELLE * sizeof(int *);
  int **d_numbers;

  cudaMalloc((void **)&d_numbers, size_numbers);
  cudaMalloc((void **)&d_result, sizeof(int *));

  kernel_one<<<2, 1024>>>(d_numbers);
  cudaDeviceSynchronize();
  kernel_two<<<1, 1>>>(d_numbers, d_result);

  cudaMemcpy(result, d_result, sizeof(int), cudaMemcpyDeviceToHost);

  printf("%d\n", *result);

  cudaFree(d_numbers);
  cudaFree(d_result);
  free(result);
}

}

I used extern "C"because I could't compile while importing my header, which is not used in this example code. I pasted it since I don't know if this may be relevant or not.

This is kernel_one code:

__global__ void kernel_one(int **d_numbers) {
  int i = threadIdx.x + blockIdx.x * blockDim.x;
  d_numbers[i] = (int *)malloc(L_CELLE*sizeof(int));
  for(int j=0; j<L_CELLE;j++)
    d_numbers[i][j] = 1;
}

And this is kernel_two code:

__global__ void kernel_two(int **d_numbers, int *d_result) {
  int temp = 0;
  for(int i=0; i<N_CELLE; i++) {
    for(int j=0; j<L_CELLE;j++)
      temp += d_numbers[i][j];
  }
  *d_result = temp;
}

Everything works fine (aka the count is correct) until I use less than 1024*2*512 total blocks in device memory. For example, if I #define N_CELLE 1024*4 the program starts giving "random" results, such as negative numbers.
Any idea of what the problem could be?
Thanks anyone!

Body:
In-kernel memory allocation draws memory from a statically allocated runtime heap. At larger sizes, you are exceeding the size of that heap and then your two kernels are attempting to read and write from uninitialised memory. This produces a runtime error on the device and renders the results invalid.  You would already know this if you either added correct API error checking on the host side, or ran your code with the  cuda-memcheck utility.

The solution is to ensure that the heap size is set to something appropriate before trying to run a kernel. Adding something like this:

 size_t heapsize = sizeof(int) * size_t(N_CELLE) * size_t(2*L_CELLE);
 cudaDeviceSetLimit(cudaLimitMallocHeapSize, heapsize);

to your host code before any other API calls, should solve the problem.


问:
No type was found that matches the controller named 'something' MVC 5.2
I know there are already such questions, but the context there is very different probably because of the older .NET MVC versions.

I am getting the error No type was found that matches the controller named 'employee' when hitting the route "/api/employee/5" on the localhost. The entire route is like "127.0.0.1:8080/api/employee/5". The home route at "127.0.0.1:8080" works as expected.

I have configured the route in my controller.

EmployeeController.cs

```<code>[Route("api/employee")]
public class EmployeeApiController : Controller
{
    [HttpGet, Route("api/employee/{id}")]
    public ActionResult GetEmployee(long id)
    {
        return Content(
            new Employee("Bobby", "Smedley",
                         "London", "Teheran",
                         EmployeeGender.M,
                         DepartmentCode.D_2157020,
                         "12345678901").ToString(),
            "application/json");
    }

}
</code>```

I made no changes to the WebApiConfig.cs and it looks like follows.

```<code>public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}
</code>```

Does anyone know what is the issue with that?

答:
You are mixing frameworks. Decide which one you want. MVC or Web API.

The home route works because it is mapping to the default MVC route.

From the name of the controller and the configured routes the assumption here is that you want to use Web API.

You already have the Web API configured so now it is just to fix the API controller to derive from the appropriate type.

```<code>[RoutePrefix("api/employee")]
public class EmployeeApiController : ApiController { // <-- Note: API controller
    [HttpGet]
    [Route("{id:long}")] //Match GET api/employee/5
    public IHttpActionResult GetEmployee(long id) { // <-- Note: return type
        var model = new Employee("Bobby", "Smedley",
                         "London", "Teheran",
                         EmployeeGender.M,
                         DepartmentCode.D_2157020,
                         "12345678901");
        return Ok(model);
    }
}
</code>```

Body:
I know there are already such questions, but the context there is very different probably because of the older .NET MVC versions.

I am getting the error No type was found that matches the controller named 'employee' when hitting the route "/api/employee/5" on the localhost. The entire route is like "127.0.0.1:8080/api/employee/5". The home route at "127.0.0.1:8080" works as expected.

I have configured the route in my controller.

EmployeeController.cs

[Route("api/employee")]
public class EmployeeApiController : Controller
{
    [HttpGet, Route("api/employee/{id}")]
    public ActionResult GetEmployee(long id)
    {
        return Content(
            new Employee("Bobby", "Smedley",
                         "London", "Teheran",
                         EmployeeGender.M,
                         DepartmentCode.D_2157020,
                         "12345678901").ToString(),
            "application/json");
    }

}

I made no changes to the WebApiConfig.cs and it looks like follows.

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Does anyone know what is the issue with that?

Body:
You are mixing frameworks. Decide which one you want. MVC or Web API.

The home route works because it is mapping to the default MVC route.

From the name of the controller and the configured routes the assumption here is that you want to use Web API.

You already have the Web API configured so now it is just to fix the API controller to derive from the appropriate type.

[RoutePrefix("api/employee")]
public class EmployeeApiController : ApiController { // <-- Note: API controller
    [HttpGet]
    [Route("{id:long}")] //Match GET api/employee/5
    public IHttpActionResult GetEmployee(long id) { // <-- Note: return type
        var model = new Employee("Bobby", "Smedley",
                         "London", "Teheran",
                         EmployeeGender.M,
                         DepartmentCode.D_2157020,
                         "12345678901");
        return Ok(model);
    }
}


问:
Use images in Highcharts as xAxis labels
I need to create a column chart in polar coordinate (wind rose) and I'd like to have images in place of the usual xAxis labels.

Can you help in correctly center the image?

var img_path = 'https://cdn2.iconfinder.com/data/icons/navigation-set-arrows-part-two/32/Arrow_Right_Circle-48.png'

Highcharts.chart('container', {
    chart: {
        polar: true,
        type: 'column'
    },

    xAxis:{
        labels: {
            formatter: function() {
                return '';
            },
            useHTML: true
        }
    },

    series:[{
        data: [{x:1, y:4}, {x:2, y:7}, {x:3, y:2}, {x:4, y:5}, {x:5, y:8}]
    }]
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/highcharts-more.js"></script>

<div id="container"></div></code>```

答:
You need to set width and height of the image.

```<code> formatter: function() {
   return '<img src="' + img_path + '" style="width: 30px; height: 30px;" />';
 },
</code>```

Also you can adjust aligning with:

```<code>align: 'center'
</code>```

example: http://jsfiddle.net/kz8h8uw9/

Body:
You need to set width and height of the image.

 formatter: function() {
   return '<img src="' + img_path + '" style="width: 30px; height: 30px;" />';
 },

Also you can adjust aligning with:

align: 'center'

example: http://jsfiddle.net/kz8h8uw9/


问:
Operator overloading in c (not c++) is it possible?
This question arises from my need to "convert" std::string to char* form.

Preferably I would like to maintain as much code as possible and that includes plenty of "=" initialization/assignment operators.

standard c operators exist for the basic data types (int, char, float, pointers to, etc...).

Is it even possible to overload the assignment operator in c? I suppose that each data type as it's own operator so messing with one wouldn't mess with others.

Anyhow, this is just something that intrigued me as I can't find much references on how C operators are implemented.

Cheers

well, some examples are in order

```<code>std::string a_string;
a_string = "bla"
</code>```

or using standard C

```<code>char a_char_array[10];
strcpy(a_char_array,"bla");
</code>```

or

```<code>char *a_char_pointer = "bla";
</code>```

what I'm thinking about is a wa to replace these 3 use cases with a single one where I can (through a #define) switch between using char* or std::string.

I guess that everyone that really cares about performance vs coding speed has already thought about the implications of using std::string instead of char*. All of the advantages of using stl are usually often offseted (is this even a word!?) by lower performance (you can't always get what you want right??).

As I said, I have a large project and I want to see for myself what are the changes in using one method or the other.

My post title was purposely misleading as I didn't want this to become a char* vs string battle, but I guess I can't really explain what I want without some more details.

Cheers

答:
No, in C overloading of = is not possible, for a simple reason: it is well defined for (almost) all types.

You'd really have to distinguish between assignment and initialization. Whereas initialization of arrays is possible, assignment is not. If your strings are compile time determined, all is easy:

```<code>char copy[] = { "abcd" }; // initialization, ok
copy = "1234";            // assignment, error
</code>```

A trick to overcome this problem is to encapsulate a string in a struct

```<code>typedef struct mystring mystring;
struct mystring { char a[24]; };

mystring a = { "abcd" };
mystring b = a;
mystring c = { 0 };
c = b;
</code>```

This will do the right thing if you always care to initialize your variables as indicated above.

Body:
This question arises from my need to "convert" std::string to char* form.

Preferably I would like to maintain as much code as possible and that includes plenty of "=" initialization/assignment operators.

standard c operators exist for the basic data types (int, char, float, pointers to, etc...).

Is it even possible to overload the assignment operator in c? I suppose that each data type as it's own operator so messing with one wouldn't mess with others.

Anyhow, this is just something that intrigued me as I can't find much references on how C operators are implemented.

Cheers

well, some examples are in order

std::string a_string;
a_string = "bla"

or using standard C

char a_char_array[10];
strcpy(a_char_array,"bla");

or

char *a_char_pointer = "bla";

what I'm thinking about is a wa to replace these 3 use cases with a single one where I can (through a #define) switch between using char* or std::string.

I guess that everyone that really cares about performance vs coding speed has already thought about the implications of using std::string instead of char*. All of the advantages of using stl are usually often offseted (is this even a word!?) by lower performance (you can't always get what you want right??).

As I said, I have a large project and I want to see for myself what are the changes in using one method or the other.

My post title was purposely misleading as I didn't want this to become a char* vs string battle, but I guess I can't really explain what I want without some more details.

Cheers

Body:
No, in C overloading of = is not possible, for a simple reason: it is well defined for (almost) all types.

You'd really have to distinguish between assignment and initialization. Whereas initialization of arrays is possible, assignment is not. If your strings are compile time determined, all is easy:

char copy[] = { "abcd" }; // initialization, ok
copy = "1234";            // assignment, error

A trick to overcome this problem is to encapsulate a string in a struct

typedef struct mystring mystring;
struct mystring { char a[24]; };

mystring a = { "abcd" };
mystring b = a;
mystring c = { 0 };
c = b;

This will do the right thing if you always care to initialize your variables as indicated above.


问:
Fetch data from mysql database
How to pass array into where, if this array has dynamic values ?</p>

```<code>foreach($value as  $v)
{
        echo $v->acc_pkey." ";
        $account = ledger::where('ledger_group', '=', 18)->orwhere('ledger_group', '=', $v->acc_pkey)->get();
}
</code>```

答:
If I understood correctly you can use whereIn() instead. So you can have:

```<code>$values = $value->pluck('acc_pkey')->toArray();
$account = ledger::whereIn('ledger_group', $values)->get();
</code>```

Or could it be:

```<code>$account = ledger::where('ledger_group', '=', 18)
    ->orWhere(function($query) use ($values) {
        $query->whereIn('ledger_group', $values);
    })->get();
</code>```

.....

I don't know what you really have in Mind, but I guess this should suffice except this solution is against your orWhere() in the example you provided.

Title: Fetch data from mysql database

Body:
How to pass array into where, if this array has dynamic values ?

foreach($value as  $v)
{
        echo $v->acc_pkey." ";
        $account = ledger::where('ledger_group', '=', 18)->orwhere('ledger_group', '=', $v->acc_pkey)->get();
}

Body:
If I understood correctly you can use whereIn() instead. So you can have:

$values = $value->pluck('acc_pkey')->toArray();
$account = ledger::whereIn('ledger_group', $values)->get();

Or could it be:

$account = ledger::where('ledger_group', '=', 18)
    ->orWhere(function($query) use ($values) {
        $query->whereIn('ledger_group', $values);
    })->get();

.....

I don't know what you really have in Mind, but I guess this should suffice except this solution is against your orWhere() in the example you provided.


问:
Styling HTML Dropdown List
I am trying to change the appearance of a dropdown for phone number extensions on my website.
Instead of all the text being unevenly spaced, it is spaced between the extension.

For example:

```<code>(+43) Austria
(+353) Ireland
(+1) United States
</code>```

Would become:

```<code>(+43)  Austria
(+353) Ireland
(+1)   United States
</code>```

I have tried simple whitespaces (as  ) and trying to separate the (+XX) and country name apart in separate  tags but to no avail.

The whitespaces have no effect and the   and spans just show up as their written code instead. Is there any way to format the dropdown to make this work? A sample of the HTML is below (the list of countries is extensive):

```<code>    <select class="countryCodeForMobile valid" id="countryCodeForMobile" name="countryCode">
    <option value="+61">(+61) Australia</option>
    <option value="+43">(+43) Austria</option>
    <option value="+32">(+32) Belgium</option>
    <option value="+55">(+55) Brazil</option>
    <option value="+1">(+1) Canada</option>
    <option value="+33">(+33) France</option>
    <option value="+49">(+49) Germany</option>
    <option value="+353">(+353) Ireland</option>
    <option value="+39">(+39) Italy</option>
    <option value="+31">(+31) Netherlands </option>
    <option value="+64">(+64) New Zealand</option>
    <option value="+48">(+48) Poland</option>
    <option value="+351">(+351) Portugal</option>
    <option value="+27">(+27) South Africa</option>
    <option value="+34">(+34) Spain</option>
    <option value="+41">(+41) Switzerland</option>
    <option selected="selected" value="+44">(+44) United Kingdom</option>
    <option value="+1">(+1) United States</option>
    </select>
</code>```

答: I would suggest having the numbers in it's own tag and set that to desired width. See this solution.</p>

Title: Styling HTML Dropdown List

Body:
I am trying to change the appearance of a dropdown for phone number extensions on my website.
Instead of all the text being unevenly spaced, it is spaced between the extension.

For example:

(+43) Austria
(+353) Ireland
(+1) United States

Would become:

(+43)  Austria
(+353) Ireland
(+1)   United States

I have tried simple whitespaces (as  ) and trying to separate the (+XX) and country name apart in separate  tags but to no avail.

The whitespaces have no effect and the   and spans just show up as their written code instead. Is there any way to format the dropdown to make this work? A sample of the HTML is below (the list of countries is extensive):

    <select class="countryCodeForMobile valid" id="countryCodeForMobile" name="countryCode">
    <option value="+61">(+61) Australia</option>
    <option value="+43">(+43) Austria</option>
    <option value="+32">(+32) Belgium</option>
    <option value="+55">(+55) Brazil</option>
    <option value="+1">(+1) Canada</option>
    <option value="+33">(+33) France</option>
    <option value="+49">(+49) Germany</option>
    <option value="+353">(+353) Ireland</option>
    <option value="+39">(+39) Italy</option>
    <option value="+31">(+31) Netherlands </option>
    <option value="+64">(+64) New Zealand</option>
    <option value="+48">(+48) Poland</option>
    <option value="+351">(+351) Portugal</option>
    <option value="+27">(+27) South Africa</option>
    <option value="+34">(+34) Spain</option>
    <option value="+41">(+41) Switzerland</option>
    <option selected="selected" value="+44">(+44) United Kingdom</option>
    <option value="+1">(+1) United States</option>
    </select>


问:
group duplicate strings with numeric suffix python
I have a list of strings in mylist

I want to return 2 groups of (animal,animal1,animal04,animal3) and (bird,bird1,bird2)
basically these are duplicates with suffixes
I have a feeling itertool.groupby will be an elegant solution,but couldnt get to it.

I have tried

```<code>def f(a,b):
    if b.startswith(a):
        return True
    return False

mylist = 'animal animal1 animal04 animal3 bird bird1 bird2 fish insect'.split()
combos = itertools.combinations(sorted(mylist), 2)

for k,v in itertools.groupby(combos,lambda (x,y):f(x,y)):
    print list(v)
</code>```

Result :

```<code>[('animal', 'animal04'), ('animal', 'animal1'), ('animal', 'animal3')]
[('animal', 'bird'), ('animal', 'bird1'), ('animal', 'bird2'), ('animal', 'fish'), ('animal', 'insect'), ('animal04', 'animal1'), ('animal04', 'animal3'), ('animal04', 'bird'), ('animal04', 'bird1'), ('animal04', 'bird2'), ('animal04', 'fish'), ('animal04', 'insect'), ('animal1', 'animal3'), ('animal1', 'bird'), ('animal1', 'bird1'), ('animal1', 'bird2'), ('animal1', 'fish'), ('animal1', 'insect'), ('animal3', 'bird'), ('animal3', 'bird1'), ('animal3', 'bird2'), ('animal3', 'fish'), ('animal3', 'insect')]
[('bird', 'bird1'), ('bird', 'bird2')]
[('bird', 'fish'), ('bird', 'insect'), ('bird1', 'bird2'), ('bird1', 'fish'), ('bird1', 'insect'), ('bird2', 'fish'), ('bird2', 'insect'), ('fish', 'insect')]
</code>```

The first and third line looks close to my answer but i cant seem to avoid the other 2 extra lines

Accept my gratitude for help or orientation in advance.Thanks

答:
Not sure if itertools.groupby is the right tool to use... but here's one solution with regex, using re.findall:

```<code>import re

string = 'animal animal1 animal04 animal3 bird bird1 bird2 fish insect'
mylist = string.split()

items = {}
for i in sorted(mylist):
    matches = re.findall('%s[\d]+' %i, string, re.M)
    if matches:
        items[i] = [i] + matches

    elif i.isalpha():
        items[i] = [i] # non-alphabetical entries get their own entry

for k in items:
    print(items[k])
</code>```

This prints out:

```<code>['bird', 'bird1', 'bird2']
['insect']
['animal', 'animal1', 'animal04', 'animal3']
['fish']
</code>```

The pattern will look for all versions of the current word with digit suffixes and return those matches only.

Body:
I have a list of strings in mylist

I want to return 2 groups of (animal,animal1,animal04,animal3) and (bird,bird1,bird2)
basically these are duplicates with suffixes
I have a feeling itertool.groupby will be an elegant solution,but couldnt get to it.

I have tried

def f(a,b):
    if b.startswith(a):
        return True
    return False

mylist = 'animal animal1 animal04 animal3 bird bird1 bird2 fish insect'.split()
combos = itertools.combinations(sorted(mylist), 2)

for k,v in itertools.groupby(combos,lambda (x,y):f(x,y)):
    print list(v)

Result :

[('animal', 'animal04'), ('animal', 'animal1'), ('animal', 'animal3')]
[('animal', 'bird'), ('animal', 'bird1'), ('animal', 'bird2'), ('animal', 'fish'), ('animal', 'insect'), ('animal04', 'animal1'), ('animal04', 'animal3'), ('animal04', 'bird'), ('animal04', 'bird1'), ('animal04', 'bird2'), ('animal04', 'fish'), ('animal04', 'insect'), ('animal1', 'animal3'), ('animal1', 'bird'), ('animal1', 'bird1'), ('animal1', 'bird2'), ('animal1', 'fish'), ('animal1', 'insect'), ('animal3', 'bird'), ('animal3', 'bird1'), ('animal3', 'bird2'), ('animal3', 'fish'), ('animal3', 'insect')]
[('bird', 'bird1'), ('bird', 'bird2')]
[('bird', 'fish'), ('bird', 'insect'), ('bird1', 'bird2'), ('bird1', 'fish'), ('bird1', 'insect'), ('bird2', 'fish'), ('bird2', 'insect'), ('fish', 'insect')]

The first and third line looks close to my answer but i cant seem to avoid the other 2 extra lines

Accept my gratitude for help or orientation in advance.Thanks

Body:
Not sure if itertools.groupby is the right tool to use... but here's one solution with regex, using re.findall:

import re

string = 'animal animal1 animal04 animal3 bird bird1 bird2 fish insect'
mylist = string.split()

items = {}
for i in sorted(mylist):
    matches = re.findall('%s[\d]+' %i, string, re.M)
    if matches:
        items[i] = [i] + matches

    elif i.isalpha():
        items[i] = [i] # non-alphabetical entries get their own entry

for k in items:
    print(items[k])

This prints out:

['bird', 'bird1', 'bird2']
['insect']
['animal', 'animal1', 'animal04', 'animal3']
['fish']

The pattern will look for all versions of the current word with digit suffixes and return those matches only.


问:
Woocommerce - Add description to category thumbs
I have my shop set up as follows:

Shop page > Category > Subcategory > Product

The shop page shows a list of categories in a grid format, with a title and thumbnail for each category.

The Category page shows a list of categories in a grid format, with a title and thumbnail for each category.

I would like each of these grid items to also show the category description.

This is where I've got to so far (functions.php), which outputs the static text in the correct place. I can't figure out how to call the dynamic category description where the static text currently outputs.

```<code>function my_theme_woocommerce_taxonomy_archive_description() {
    echo '<div class="term-description">' . 'Code to show description here please' . '</div>';
}
add_action( 'woocommerce_after_subcategory_title', 'my_theme_woocommerce_taxonomy_archive_description');
</code>```

答:
Can you please try this

```<code>function my_theme_woocommerce_taxonomy_archive_description($category) {
    $category_id = $category->term_id;
    echo '<div class="term-description">' . category_description( $category_id ). '</div>';
}
add_action( 'woocommerce_after_subcategory_title', 'my_theme_woocommerce_taxonomy_archive_description');
</code>```

OR else try this one

```<code>add_action( 'woocommerce_after_subcategory_title','custom_add_product_description', 12);
function custom_add_product_description ($category) {
  $cat_id        =    $category->term_id;
  $prod_term    =    get_term($cat_id,'product_cat');
  $description=    $prod_term->description;

  echo '<div class="term-description">'.$description.'</div>';
}
</code>```

Try this one

```<code>function addcatagorydescription( $category ) {
   echo '<div class="term-description">' . $category->description . '</div>';
}

add_action( 'woocommerce_after_subcategory_title', 'addcatagorydescription', 10, 1 );
</code>```

Body:
I have my shop set up as follows:

Shop page > Category > Subcategory > Product

The shop page shows a list of categories in a grid format, with a title and thumbnail for each category.

The Category page shows a list of categories in a grid format, with a title and thumbnail for each category.

I would like each of these grid items to also show the category description.

This is where I've got to so far (functions.php), which outputs the static text in the correct place. I can't figure out how to call the dynamic category description where the static text currently outputs.

function my_theme_woocommerce_taxonomy_archive_description() {
    echo '
' . 'Code to show description here please' . '
';
}
add_action( 'woocommerce_after_subcategory_title', 'my_theme_woocommerce_taxonomy_archive_description');

Body:
Can you please try this

function my_theme_woocommerce_taxonomy_archive_description($category) {
    $category_id = $category->term_id;
    echo '<div class="term-description">' . category_description( $category_id ). '</div>';
}
add_action( 'woocommerce_after_subcategory_title', 'my_theme_woocommerce_taxonomy_archive_description');

OR else try this one

add_action( 'woocommerce_after_subcategory_title','custom_add_product_description', 12);
function custom_add_product_description ($category) {
  $cat_id        =    $category->term_id;
  $prod_term    =    get_term($cat_id,'product_cat');
  $description=    $prod_term->description;

  echo '<div class="term-description">'.$description.'</div>';
}

Try this one

function addcatagorydescription( $category ) {
   echo '<div class="term-description">' . $category->description . '</div>';
}

add_action( 'woocommerce_after_subcategory_title', 'addcatagorydescription', 10, 1 );


问:
VirtualBox : Access localhost:8080 in host browser
I have this PHP application where I have to open it from Ubuntu because it uses an extension. In the application folder there is application guide file which contains this instructions:

Install VirtualBox

Open VirtualBox and click file->import appliance->Browse directory file 208.ova->import

start Ubuntu server

Login Ubuntu using given username and password

open XAMPP and paste this URL into the browser
localhost:8080

I have successfully done 1-4. But when I try to access localhost:8080 it won't open. I have searched on google and some solutions say i have to use host-only adapter or NAT, but it doesn't work. My friend tried it on his laptop and it works. My host is windows 10. Can someone help me?

I am really new to VirtualBox and Ubuntu, please explain clearly on a newbie level :)

Thank you very much.

答:
Ensure you did the following after starting the XAMPP software: Press on ‘Start’ in the ‘Actions’ for Apache.

If you did this and it still doesn't work, can you show us the last entries in your Apache log file?


问:
how to avoid duplication users in my db with php
How are you all,

hope every one here is OK,

now I have a form that the admin can create users and he can delete users as will let me display the code first

this is my code

```<code>> > <?php error_reporting(E_ALL);
>
> session_start();
>   if(!isset($_SESSION['login']) ||
> $_SESSION['login']!='1' )         {
>       header("Location:loginpage.php");
>       } ?>
>
> <!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=utf-8" />
> <title>My Control panel</title> <link
> href="../css_style.css"
> rel="stylesheet" type="text/css" />
> </head>
>
>
>
> <body> <div id="werpper"> <div
> id="content">
>
> <div id="header">My control -
> Panel</div> <div id="body_cntent">
> <div id="left_side">   <p>Home and
> instructions</p>   <p><a
> href="../control_panel.php">main
> directory</a></p>   <p><a
> href="add_event.php">Add new
> event</a></p>   <p><a
> href="../editoccasion.php">Control
> Occasion's</a></p>   <p><a
> href="add_photos_and_occasion.php">Add
> Photos_occasion</a></p>   <p><a
> href="../signout.php">Sign out</a></p>
> </div> <div id="right_side">
>
> <h2>Add new user</h2>
>
> <form action="" method="post">
>
> <table width="600" border="0"
> cellpadding="5" cellspacing="0">
> <tr>
>     <td width="78">User name</td>
>     <td width="2"> </td>
>     <td width="149"><input type="text" name="uname" value="" /></td>
>     <td width="332" rowspan="5" align="left" valign="top"><p
> class="red">For Administration use
> only.</p>
>       <p>You can add or delete users from <a
> href="edit_users.php">here</a><br />
>         You can't edit any user if you like to change any user account you
> can delete the user and create it
> again with the new
> information.</p></td>   </tr>   <tr>
>     <td>Password</td>
>     <td> </td>
>     <td><input type="text" name="pass" value="" /></td>
>     </tr>   <tr>
>     <td> </td>
>     <td> </td>
>     <td><input type="submit" name="submit" value="Add user" /></td>
>     </tr>   <tr>
>     <td> </td>
>     <td> </td>
>     <td> </td>
>     </tr>   <tr>
>     <td> </td>
>     <td> </td>
>     <td align="right"> </td>
>     </tr> </table> </form>
>
> </div> </div>
>
> <div id="footer"></div> </div> </div>
>
> <?php
>       if (isset($_POST['submit'])) {
>               include_once "../config/config.php";
>               $uname = $_POST['uname'];       $pass =$_POST['pass'];
>               $check = "select * from users where id = {$uname}";         $result_check
> = $db->query($check)or die($db->error);
>
>               while ($row = $result_check -> fetch_object()) {
>                       if(num_rows == 1){
>
>               echo "error";
>
>               }else{
>               $add_user = "insert into users (id, uname, pass) values ('',
> '$uname', '$pass')";
>               $result = $db -> query($add_user) or die ("$db->error");
>               if ($result) {
>                       echo "user added successfuly";
>                       }else{
>
>               echo "There was an error please try again later";
>
>               }           }       }   } ?>
>
> </body> </html>
</code>```

all I need here to know is how to solve the problem of this code

```<code>$check = "select * from users where id = {$uname}";
        $result_check = $db->query($check)or die($db->error);

        while ($row = $result_check -> fetch_object()) {

            if(num_rows == 1){

                echo "error";

                }
</code>```

how can I avoid duplication users in my db

答:
Most DBs have some way of making columns or combinations of unique.  Simply set up a unique constraint on whichever column you want to make unique.  </p>

<p>If there are already users in there that aren't unique, you will have to cleam them out of the database first.  </p>

Body:
How are you all,

hope every one here is OK,

now I have a form that the admin can create users and he can delete users as will let me display the code first

this is my code

> > <?php error_reporting(E_ALL);
>
> session_start();
>   if(!isset($_SESSION['login']) ||
> $_SESSION['login']!='1' )         {
>       header("Location:loginpage.php");
>       } ?>
>
> <!DOCTYPE html PUBLIC "-//W3C//DTD
> XHTML 1.0 Transitional//EN"
> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
>  xmlns="http://www.w3.org/1999/xhtml">
>  <meta http-equiv="Content-Type"
> content="text/html; charset=utf-8" />
> <title>My Control panel</title> <link
> href="../css_style.css"
> rel="stylesheet" type="text/css" />
>
>
>
>
>

 id="content">
>
>
My control -
> Panel

>

Home and
> instructions

 href="../control_panel.php">main
> directory

 href="add_event.php">Add new
> event

 href="../editoccasion.php">Control
> Occasion's

 href="add_photos_and_occasion.php">Add
> Photos_occasion

 href="../signout.php">Sign out

>

>
>
Add new user

>
> <form action="" method="post">
>
>
 cellpadding="5" cellspacing="0">
>

>     User name
>
>     <input type="text" name="uname" value="" />
>
 class="red">For Administration use
> only.

>
You can add or delete users from  href="edit_users.php">here

>         You can't edit any user if you like to change any user account you
> can delete the user and create it
> again with the new
> information.

>     Password
>
>     <input type="text" name="pass" value="" />
>

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

>
>
>
>

>
>
>
>

 </form>
>
>

>
>

>
> <?php
>       if (isset($_POST['submit'])) {
>               include_once "../config/config.php";
>               $uname = $_POST['uname'];       $pass =$_POST['pass'];
>               $check = "select * from users where id = {$uname}";         $result_check
> = $db->query($check)or die($db->error);
>
>               while ($row = $result_check -> fetch_object()) {
>                       if(num_rows == 1){
>
>               echo "error";
>
>               }else{
>               $add_user = "insert into users (id, uname, pass) values ('',
> '$uname', '$pass')";
>               $result = $db -> query($add_user) or die ("$db->error");
>               if ($result) {
>                       echo "user added successfuly";
>                       }else{
>
>               echo "There was an error please try again later";
>
>               }           }       }   } ?>
>
>

all I need here to know is how to solve the problem of this code

$check = "select * from users where id = {$uname}";
        $result_check = $db->query($check)or die($db->error);

        while ($row = $result_check -> fetch_object()) {

            if(num_rows == 1){

                echo "error";

                }

how can I avoid duplication users in my db

Body:
Most DBs have some way of making columns or combinations of unique.  Simply set up a unique constraint on whichever column you want to make unique.

If there are already users in there that aren't unique, you will have to cleam them out of the database first.