text:
Q: How do I do this in WPF ListView I have this project I like to use WPF ListView

*

*it will look like a PropertyGrid in Winform. I already found some implementation on the web, which is the best?

*from what I learn, I can only binding a class from DependencyObject, is it possible to binding a generic List or Dictionary, myClass will include name, value, type (string, double, bool, lookup list, ...). Once I binding it, it will add relate template, e.g. for lookup list, it will add combobox in celltemplate.

*further, I like to have everything in a configuration file. e.g. I have this configuration:
Name1, Value1, string
Name2, Value2, bool
Name3, Value3, lookup, N3_option1, N3_option2, N3_option3, ...
my code will read configuration file first, then from there, I read Name1/Name2/Name3 from database, show them in my ListView, from Name3, you pick value from (N3_option1, N3_option2, N3_option3, ...).
If you can point me the right direction, I will appreciate it so much.
Update:
here is 3 examples I'm looking at:
DataTemplates in Action: Building a simple PropertyGrid, WPF PropertyGrid - MVVM techniques, and WPF Property Grid.
"WPF Property Grid" is too complicate for a beginner like me. Personally, I more like "DataTemplates in Action: Building a simple PropertyGrid".
it also have code to select DataTemplate depend on DataType of each class property: bool use BooleanDataTemplate which is a checkbox; Enum use EnumDataTemplate which is a combobox.
I also like go a little further, add custom type: lookup, which will show as dropdown list, but the value list come from database. e.g.
property name: car manufacturere, value come from "SELECT LOOKUP_VALUE FROM LOOKUP WHERE LOOKUP_KEY = 'CAR_MFG'", which will return a list like: Toyota, Ford, Nissan, Honda, VW, BMW, ...
If I have > 1 lookup properties, how I can speciafy them? LookupDataTemplate1, LookupDataTemplate2, ..., then how to specify them in XAML Resources. and all DataTemplate are pre-defined in XAML, how I can do it in this case.
similar to EnumToListConverter, How I can create LookupmToListConverter1,  LookupmToListConverter2?

A: 1) I am unsure what the question here is.  You can do it with a ListView, its just a matter if it fits your data well.  It sounds reasonable given what you wrote.
2) You can make a DependencyProperty that is a List or Dictionary and bind to it that way.  You can also use the ObservableCollection<T> class (basically a list that notifies when its state changes) and bind to it.  You can also use any other class that uses INotifyPropertyChanged and bind to that.  Adding the combobox through the template sounds appropriate.
3)It sounds like you you need a class to use to read from your configuration and then display it to the list view.  These would be your view model.  You could make a class that implements INotifyPropertyChanged for this.  You'd have three fields 1)Name 2) Value, 3)Potential Values.  Name and value both would be strings.  I'm assuming Name would be a one way binding and Value would be on a two way binding on the combobox whose items are bound to the Potential Values.  You then would create an ObservableCollection<T> of these objects and bind your ListView to that.  The serializing and deserialzing to this collection should be relatively straightforward.


text:
Q: What is server side socket best practice to handle multithread broken pipe case on Linux? considering being new to C language on Linux, I've walked through socket programing scenarios where you have to handle that SIGPIPE issues and I've faced the fllowing cases:
1- catch sigaction for the process then continue, which equals ignoring the signal.
struct sigaction sginal_action;
memset(&sginal_action, 0, sizeof (sginal_action));
sginal_action.sa_handler = SIG_IGN;
sginal_action.sa_flags = SA_RESTART;
if (sigaction(SIGPIPE, &sginal_action, null)) {
    perror("signal action error");
}

2- ignore the signal over thread using
sigset_t sigpipe_mask;
sigemptyset(&sigpipe_mask);
sigaddset(&sigpipe_mask, SIGPIPE);
sigset_t saved_mask;
if (pthread_sigmask(SA_RESTART, &sigpipe_mask, &saved_mask) == -1) {
  perror("pthread_sigmask");
}

-Now every thing shall work fine but I need an answer about this test case behavior:
1- server accepted socket from user A with file discriptor int 7
2- I run lengthy SQL statement that takes 25 secondes
3- at second 20 client closed socket
4- at second 21 Linux kernel sent SIGPIPE
5- at second 22 process ignored SIGPIPE and continued working with file decriptor 7, since there is no signal any thing went wrong
6- at second 23 server accepted socket from user B with file discriptor int 7, again!
7- user B authorization takes 2 seconds shall finish at second 25 of user A.
8- the core problem starts at second 25 write(file_dsciptor, buffer, buffer_size); from both threads will write data to both user A and user B channels
9- it happens that user B is not authorized to login to server but before server close file decriptor 7 at thread B, thread A of client A writes to file decriptor 7 and client B received vital data due to the reuse of socket file descriptor 7!

My question,is that scenario wrong and will never happen?or that is possible to happen but there is a correct method to apply?and is there a C system call function to stop file_discriptor re-usage over socket connections?or what shall be done to ensure that opened channel is not conflicted with another channel, like unique file discriptor I guess?

A: (Normal) SIGPIPE is essentially a synchronous signal. You get it in response to what you did which is attempt a write into a pipe/socket/FIFO that was closed by the other side. Ignoring SIGPIPE is quite harmless since if you do that, you'll still get informed about the error the usually way synchronous errors are reported: by a failing return code and errno set to the appropriate error number (EPIPE). In this case, I think ignoring SIGPIPE while continuing to check for errors would be the best way to proceed regardless of the POSIX platform you're on.
Concerning your example, your assumption at point 5 that there will be "no signal any thing went wrong" is incorrect. There will be a signal. It just won't be a signal but an EPIPE fail on a write call.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What will happen when taps at secondary side of auto-transformer are connected together (short-circuited)? In case of Auto-transformer, there is only one winding, having three lead wires (1 for primary/input, 1 for secondary/output, and 1 common between both). At the secondary side (the output side), there are taps (sort of voltage dividers).
I have a auto-transformer with input at 220 V, and i have taps at the secondary side at 200 V and 240 V (only mentioning my required taps, there are many).
My question is, what will happen if the taps at the secondary get short-circuited (200 V tap and 240 V tap gets short)?
What will be the effect of this incidence on primary voltage and secondary voltage?
Will transformer be okay? it won't get damage or something??

A: If you put a short circuit across a portion of the winding of an autotransformer, that portion of the winding will pass excessive current, and may be damaged - just as if you had shorted turns in either winding of a normal transformer.


text:
Q: How to retrieve output variable from Firebird I have a free pascal application using Firebird. How can I retrieve the output variable from this Firebird stored procedure:
input parameters: ID (integer)
output parameters: G (integer)

begin
 if(select town.count from town where town.id=:id) then
    G = 100
 else
    G = 200;
  suspend;
end

in designer->SQL
EXECUTE PROCEDURE ID_DEV :ID RETURNING_VALUES :G

In code:
SQLQueryProc.Prepare; //here i got an error
SQLQueryProc.ParamByName('ID').Value:=res;
SQLQueryProc.ExecSQL();
SQLTransaction.CommitRetaining;
ID:=SQLQueryProc.FieldByName('G').AsInteger;

When I run my app I get an error:

Token unknown line (where :G located)

I have tried many combinations. What is the reason?

A: The RETURNING_VALUES :G clause is only valid Firebird syntax inside PSQL (so inside a stored procedure). If you want to execute the stored procedure, you should only use:
EXECUTE PROCEDURE ID_DEV :ID

As you want to have an executable stored procedure, you should also remove the SUSPEND from your stored procedure, as having a suspend-statement inside your stored procedure makes it a selectable stored procedure instead.


text:
Q: performance issue with sp large parameters in ado.net? The customer sends us a large message (e.g. xml message) and we need to save it into the database.
What we found is that when the message becomes larger, the time to pass the parameter to sp belongs long.
One message is around 500kb and we need to save it in database. From trace, we can see that the sp take 0-10ms to run. But from our c# code (a winform example), it takes around 2-3 seconds to finish.
We tried to run the c# code on sql server to remove the network issue, but the duration is almost the same.
Seems sql server has problems with large parameter.
Does anyone experienced this before?
Many Thanks


text:
Q: while running selendroid code showing this error....Exception in thread "main" org.openqa.selenium.SessionNotCreatedException Exception in thread "main" org.openqa.selenium.SessionNotCreatedException: The requested application under test is not configured in selendroid server.
io.selendroid.exceptions.SessionNotCreatedException: The requested application under test is not configured in selendroid server.
    at io.selendroid.server.model.SelendroidStandaloneDriver.createNewTestSession(SelendroidStandaloneDriver.java:205)
    at io.selendroid.server.handler.CreateSessionHandler.handle(CreateSessionHandler.java:42)
    at io.selendroid.server.SelendroidServlet.handleRequest(SelendroidServlet.java:143)
    at io.selendroid.server.BaseServlet.handleHttpRequest(BaseServlet.java:67)
    at io.selendroid.server.http.ServerHandler.channelRead(ServerHandler.java:50)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:333)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:319)
    at io.netty.handler.codec.MessageToMessageDecoder.channelRead(MessageToMessageDecoder.java:103)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:333)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:319)
    at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:163)
    at io.netty.channel.CombinedChannelDuplexHandler.channelRead(CombinedChannelDuplexHandler.java:148)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:333)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:319)
    at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:787)
    at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:125)
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:511)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:468)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:382)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:354)
    at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:116)
    at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:137)
    at java.lang.Thread.run(Thread.java:745)

A: 1.Run java -jar selendroid-standalone-0.14.0-with-dependencies.jar -aut your_apk.apk
2.Open selendroid status URL http://localhost:4444/wd/hub/status and find out your appID.
3.Use this app id to install app on your device in

SelendroidCapabilities capa = new
  SelendroidCapabilities("io.selendroid.testapp:0.8.0");


text:
Q: Русский текст в консоли Qt Creator Здравствуйте. Сначала мы учились С на dev-cpp. Там у меня была русифицирована консоль. Все производилось через изменение файла в настройках. Вот мы перешли на Qt Creator и нам зачем-то сказали все проги переписать на Qt Creator. Т.к. текст для консоли в них был на русском, Qt Creator выдает мне кракозябры. Подскажите, можно ли каким-нибудь способом включить поддержку русского текста в консоли? например, тоже подключением какого-нибудь файла.
A: Смотрите в сторону QString::fromUtf8 для Линукса , для винды это, наверное, QString::fromLocal8Bit (не пробовал если честно)
A: Мне помог следующий код, с кодировкой уж поиграйтесь сами:
#include <clocale>
#include <Windows.h>

setlocale(LC_ALL, "PL_pl.UTF-8");
SetConsoleCP(CP_UTF8);
SetConsoleOutputCP(CP_UTF8);


text:
Q: Failed to invoke one service from another service using DNS for services in kubernetes I have set up a AWS kops cluster for Kubernetes, i have multiple microservices where in each application need to interact with one another.
Scenario: My ta2carbon app tries to invoke a function in ta1carbon app through service(dns) name.
Result: It is failing with timeout error by trying to hit to port 80 (but configured port -3000)
my nodejs app console log,
    apiUrl: http://ta1carbon/api/app1/app1Func2
{ Error: connect ETIMEDOUT 100.66.7.165:80
    at Object._errnoException (util.js:992:11)
    at _exceptionWithHostPort (util.js:1014:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1186:14)
  code: 'ETIMEDOUT',
  errno: 'ETIMEDOUT',
  syscall: 'connect',
  address: '100.66.7.165',
  port: 80 }

same error logs for curl, when i tried to curl my ta1carbon app inside ta2carbon pod.
root@ta2carbon-5fdcfb97cc-8j4nl:/home/appHome# curl -i http://ta1carbon/api/app1/app1Func2
curl: (7) Failed to connect to ta1carbon port 80: Connection timed out

but my defined port in service.yaml is 3000 not 80!
below are the yml configurations for service for both microservices.
ta1carbon service yaml
apiVersion: v1
kind: Service
metadata:
  name: ta1carbon
  labels:
    app: ta1carbon
spec:
  ports:
  - port: 3000
    targetPort: 3000
  type: ClusterIP
  selector:
    app: ta1carbon

ta2carbon service yaml
apiVersion: v1
kind: Service
metadata:
  name: ta2carbon
  labels:
    app: ta2carbon
spec:
  ports:
  - port: 3001
    targetPort: 3001
  type: ClusterIP
  selector:
    app: ta2carbon

And below is the describe service details for both ta1carbon and ta2 carbon.
kubectl describe service ta1carbon
Name:              ta1carbon
Namespace:         default
Labels:            app=ta1carbon
Annotations:       <none>
Selector:          app=ta1carbon
Type:              ClusterIP
IP:                100.66.7.165
Port:              <unset>  3000/TCP
TargetPort:        3000/TCP
Endpoints:         100.96.1.13:3000
Session Affinity:  None
Events:            <none>

kubectl describe service ta2carbon
Name:              ta2carbon
Namespace:         default
Labels:            app=ta2carbon
Annotations:       <none>
Selector:          app=ta2carbon
Type:              ClusterIP
IP:                100.67.129.126
Port:              <unset>  3001/TCP
TargetPort:        3001/TCP
Endpoints:         100.96.1.12:3001
Session Affinity:  None
Events:            <none>

So based on what i observe, for the url http://ta1carbon/api/app1/app1Func2
service dns ta1carbon is being resolved in to 100.67.24.69:80 resulting in timeout.
but however if i curl in to 100.67.24.69:3000 from inside ta2carbon pod i get a success response
Also if i change my service yaml - port: 80 and deploy and test again i get success response
i am finding this behaviour in kubernetes quite weird, not sure weather i am making mistake or with environment.
My query is -
why is it resolving service ta1carbon in to 100.67.24.69:80 and timing out, when the port should have been 3000!
Any input on this will be much appreciated. please let me know what is missing in this.

A: DNS resolves a doman name to an IP address, not an IP address + port.
There are two potential solutions:

*

*Modify your application source to issue API requests to http://ta1carbon:3000

*Set the port on your ta1carbon service to 80.
I recommend going with option 2. In this scenario, you are taking advantage of the power of Kubernetes services. Kubernetes will expose the service on port 80, but send requests to the pods backing the service on port 3000 (because of the targetPort: 3000).


text:
Q: WPF Ribbon and ViewModel I am trying to switch from TabControl to Ribbon.
When using TabControl, I bound my UserControl's to TabItem.Content. It was enough to load my user controls while switching between tab items.
Now with WPF Ribbon controls, I will have RibbonButton. How should I load my user control with  it? Should I handle a Click() event or what?

A: AFAIK the ribbon control is used primarily with in a RibbonWindow. This means your top level window must change to that type. You can then bind the RibbonWindow ribbon's (that you make with in the window) content to your user control.
Here is the MSDN.
http://msdn.microsoft.com/en-us/library/system.windows.controls.ribbon.ribbon%28v=vs.110%29.aspx
As you can see they use the ribbon control with in the RibbonWindow. I know this was a requirement before and I did not think it would change considering it is an entirely different layout than a traditional window.


text:
Q: How to get file root value from html form or php I want to save directory root value of file to database.
ex:
I have file with directory c:\xampp\htdocs\myproject\app\views\index.php  , but i just want get myproject\app\views\index.php.
I want to get value from the input type file, is it possible ?
This is how proccess I want to build, but the value not like I want.

i want when user click choose file in <input type='file' />, i want default directory open in "myproject" . it's not about uploading file, i just want make validation from directory root value. in some case i have 2 file with same name "index.php", but one of file located in myproject\view\dir1\index.php and another one in myproject\view\dir2\index.php.
so that sets it apart is the root directory.
thanks for help me.

A: You can use the follwing:
\Yii::$app->basePath will give like D:\xampp\htdocs\advanced\backend
\Yii::$app->request->BaseUrl will give like localhost\advanced\backend\web\
You may store the image using \Yii::$app->basePath and show it using \Yii::$app->request->BaseUrl
Hope it helps

A: Please google the followings. Also search in stackoverflow
$_SERVER['DOCUMENT_ROOT'] dirname(__FILE__);


text:
Q: set checkStorageTask to null in analytics.js I am working on a chrome extension and I want to use google analytics to track user data. I am trying to implement analytics.js/Universal Analytics in the same fashion as this tutorial and this tutorial and spent days trying to figure out why it wasn't working for me. Countless articles and online forums have suggested the only modifications I needed to make were setting the checkProtocolTask to null and setting the page when sending a pageview. Running analytics_debug.js, it gives me the error "Cookie write failed. Storage not available, aborting hit." All of the answers to this error online suggest a problem with the cookieDomain, but I tried various different possibilities and nothing worked for me. It was only when I tried setting checkStorageTask to null as well that it finally worked for me. But why did I need to do this, when I haven't found any other evidence of anyone else needing to do this to get analytics to work in an extension?
The checkStorageTask aborts the request if the tracker is configured to use cookies but the user's browser has cookies disabled. After some more research I discovered it is possible for a chrome extension to have it's own cookies, with the domain pointing to the extension ID, as shown in the answer to this question. Is it a problem with my browser individually, then? Or is it a larger problem that I just can't see? Any ideas are greatly appreciated!


text:
Q: Right Angle Circuitry This question concerns the article Right Angle Circuitry.
Having passed a grad E&M course, I feel like this should make perfect sense to me and I should be able to answer all the questions it raises. Sadly that is not yet the case.
What are the answers to all the unanswered questions here?
In particular:

*

*Why does the circuit in Figure 8 not act as a transformer?

*Is it possible to extract energy from a toroid with capacitor plates as shown in Figure 9? If not, why not?

*Have structures like that in Figure 10 ever been used in practice as transmission lines?

*Last question in the article: Is it possible to create "insulating electric circuitry which conducts only displacement current"?

A: *

*The figure 8 object does not have a magnetic flux through it at any time, so it doesn't have a changing magnetic flux, so it doesn't have an EMF.

*Yes, it is possible with AC current--- in fact it is routine! You take the EMF and feed it to a small capacitor. Circuits don't have to close to conduct AC current, or else capacitors wouldn't be very useful circuit elements.

*The structure of figure 10 is nothing but a particular restriction of the E and B fields so that the electric fields mostly go in one material, and the magnetic fields in another. The transmission lines we have do the same thing, with the E and B in the space around the wire. Electricity is a property of the fields in the space around the materials, not of the materials themselves. The trick in the page is that they are using iron which channels magnetic fields inside it so effectively, so that the space-property becomes a material property.

*There is nothing strange about conducting displacement current--- it happens every time you use a capacitor. If you take a normal electronic device with at least one capacitor on every path from power to ground (I am sure this is true in every complex enough device you own) then it will not conduct DC current, so it is "insulating" in this sense, but it conducts the AC currents just fine.

A: I'll take a stab at your first two questions:
1.)  The circuit does not act as a transformer because there is no linking current.  The "A-field flux" is there, but no traveling charge.  Putting in a ring of copper (as he does in other pics) allows the A-field to generate current which would link to the next core.
2.)  Yes, but not in any practical sense as shown.  The capacitor plates need to be very close together, as they would be in a commercial cap.


text:
Q: React not rendering simple component I'm new to React thus the question.
I'm trying to render a basic React component. This is my index.html
<!DOCTYPE html>

    <title>React</title>

This is my index.js
import React from 'react';
import 'babel-polyfill';
import { render } from 'react-dom';
import './styles/style.css';
import  '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import Layout from './components/Layout';

React.render(<Layout />, document.getElementById("root"));

This is my Layout component.
import React from 'react';
import {render } from 'react-dom';

class Layout extends React.Component{
  render(){
    return(

This is home now

    );
  }
}
export default Layout;

This is the error I see on the console,
Uncaught TypeError: _react2.default.render is not a function

When I start the dev server, I see a blank page with nothing getting rendered. Any help appreciated.

A: The way you import the render function inside index.js from react-dom changes the way you invoke it.
import { render } from 'react-dom';

Here you just import the render method from the react-dom object. So to use it you would say
render(<Layout />, document.getElementById("root"));


text:
Q: Why does max_used_connections status not get refreshed automatically once it reaches max_connections, even though the Threads_connected falls down I always wonder, why does the max_used_connections value not come down, once it reaches the peak value of max_connections?
I always flush the status and bring down this value to avoid DB connection refused errors and warning messages in the error log:
=====
121112 14:04:36 [Warning] Too many connections
121112 14:04:36 [Warning] Too many connections
121112 14:04:36 [Warning] Too many connections
121112 14:04:36 [Warning] Too many connections
121112 14:04:36 [Warning] Too many connections
121112 14:04:36 [Warning] Too many connections
121112 14:04:36 [Warning] Too many connections
=======

mysql> select version();show variables like "%max_connections%";show global status
         like "%Max_used%";show status like "%thread%";
            +--------------+
            | version()    |
            +--------------+
            | 5.1.52-2-log |
            +--------------+
            1 row in set (0.00 sec)

            +-----------------+-------+
            | Variable_name   | Value |
            +-----------------+-------+
            | max_connections | 150   |
            +-----------------+-------+
             1 row in set (0.00 sec)

            +----------------------+-------+
            | Variable_name        | Value |
            +----------------------+-------+
            | Max_used_connections | 151   |
            +----------------------+-------+
            1 row in set (0.00 sec)

            +----------------------------+-------+
            | Variable_name              | Value |
            +----------------------------+-------+
            | Com_show_thread_statistics | 0     |
            | Delayed_insert_threads     | 0     |
            | Slow_launch_threads        | 0     |
            | Threads_cached             | 89    |
            | Threads_connected          | 2     |
            | Threads_created            | 1344  |
            | Threads_running            | 2     |
            +----------------------------+-------+
            7 rows in set (0.00 sec)

mysql> show variables like "%thread_cache%";
            +-------------------+-------+
            | Variable_name     | Value |
            +-------------------+-------+
            | thread_cache_size | 90    |
            +-------------------+-------+
            1 row in set (0.00 sec)

Here is the Aborted Connections Status:
mysql> show global status like "%Aborted%";
            +------------------+----------+
            | Variable_name    | Value    |
            +------------------+----------+
            | Aborted_clients  | 119      |
            | Aborted_connects | 43855304 |
            +------------------+----------+
            2 rows in set (0.00 sec)

*

*I observed in some scenarios that the max_used_connections value comes down dynamically, once the threads_connected falls down.

*Is this only an indication variable to increase the max_connections? Posting this query for better understanding. Any detailed explanations please?
I read somewhere thread_cache_size should be greater than max_connections, what will be the impact if it is less ?
Max_used_connections

The maximum number of connections that have been in use simultaneously since the server started.

A: It doesn't come down because it isn't supposed to come down.
Max_used_connections is a status variable, and is defined as "the maximum number of connections that have been in use simultaneously since the server started."
It turns out, you can also reset the value to the current number of connections using FLUSH STATUS.
But that isn't a "partial solution" to anything because it doesn't change anything.  The only thing you are accomplishing with FLUSH STATUS is sort-of baselining the value of an information-only status variable: resetting the value you see, down to the current value of the status variable Threads_connected -- the current number of connections.
This action doesn't change anything about the server's behavior.  If you're seeing a change in behavior after doing that, it's coincidental.
mysql> SHOW STATUS LIKE 'Threads_connected';
+-------------------+-------+
| Variable_name     | Value |
+-------------------+-------+
| Threads_connected | 225   |
+-------------------+-------+
1 row in set (0.00 sec)

The above would be a more useful value for you to watch, while troubleshooting.  It shows the current count.
But addressing your problem, you either have an application that does not properly release its connections -- which needs to be fixed elsewhere, not in MySQL -- or you may be right -- you need to increase the value of the max_connections global variable -- after you consider what's written in C.5.2.7 Too many connections.  That page also explains why your output above shows a Max_used_connections of 151 compared to max_connections of 150.
Setting thread_cache_size to a value larger than max_connections seems like tremendously unhelpful advice... the cache can't possibly grow larger than max_connections and even a cache anywhere close to that size could only make sense if you have a tremendous amount of churn on your threads... which, in a well-behaved application, won't be the case.


text:
Q: How to simply serve a bundled PDF? I've a really simply html file with only a simple link
Get the file

I want, for example on Windows, user can see the pdf in Adobe Reader as if downloaded and opened from browser.
But when I launch nw.exe C:\Node-WebKit-Project and click on the link, on the console I see this:

Resource interpreted as Document but transferred with MIME type
  application/pdf: "file:///C:/Node-WebKit-Project/output.pdf".

How to allow opening of pdf ?

A: e.g create a link in your app.
Set a on click event handler on this link.
Set a data attribute with the URL of the pdf file.
Then use gui.Shell.openExternal() method to open the pdf with the system default application.
html code:
...

...

javascript code:
...
$('#pdfLink').on('click', function () {
  gui.Shell.openExternal($(this).data('href'));
});
...

A: A partial answer is to make sure that you have the following in your package.json file
"webkit": {
  "plugin": true
}

source: https://github.com/rogerwang/node-webkit/wiki/Third-party-browser-plugins
However, you then have to make sure that either the PDF viewer plugin is pre-installed on the system, or bundled with the app. I've not tested any of this.


text: Q: How to best resolve elusive python segmentation fault? I have a python code running on crontab every 15 minute since three years. During the last year however the script have terminated twice with segmentation fault. I've managed to track down the problem to calling wget using Popen from the subprocesses module but fail to move on from there. Now failing twice in this many runs may sound like nothing to cry about, however it still annoys me quite, thus any advice on how to proceed from here to resolve the issue are greatly appreciated.


text:
Q: Autodesk Viewer GPS Functionality I was wondering if there is any support for GPS functionality for the autodesk 3D viewers, or if there is going to be support in the future.
I am asking this question because we would like to use GPS specific data in the viewer gathered from drone inspections 3D models. To give an example you could render a Google Map with the correct coordinates provided from the 3D drone scan.
Think a little like this:


text:
Q: Relative Topology and clopen sets Problem: Suppose $A \subset M$ is connected where $M$ is a metric space. Show that $A, \emptyset $ are the only subsets of $A$ that are clopen relative to $A$.
My thoughts:
The empty set is always open and closed.
Since $M$ is closed and open, and $A=A \cap M$, then $A$ is open relative to $A$ (and similarly closed).
Now supposing there was another clopen set $U \neq \emptyset, A$, Then I am imagining I need to use $U$ and $U^c$ to show that there is a separation of $A$. My definition of a separation is that $A = U \cup U^C$ where  $U \cap closure(U^c) = \emptyset$ and $closure(U) \cap U^c = \emptyset$ which would contradict that $A$ is connected.
If $U$ is clopen relative to $A$, then there exists $V$ open in $M$ with $U=V \cap A$, and $W$ closed with $U=W\cap A$, how can I show
$U \cap closure(U^c) = \emptyset$ and $closure(U) \cap U^c = \emptyset$ ?
Edit: Worth noting this problem has been asked many times but not with relative topology :)

A: You don't need to use closure, and as you are working relative to $A$, you can forget about $M$ and work in $A$.
Suppose you have a clopen $U\subset A$. Then $U^c$ (relative to $A$) is also clopen. We now have $A=U\cup U^c$, with $U\cap U^c=\varnothing$. As both $U$ and $U^c$ are open and $A$ is connected, this means $U=\varnothing$ or $U^c=\varnothing$. Thus $U=\varnothing$ or $U=A$.

A: Note: I'm going to use a bar over a set to represent closure. (Thus the closure of $U$ is $\overline U$.) Also, complements will always be relative to $A$, but open/closedness relative to $M$ (matching the usage in your question).
$U^c = V^c \cap A$, so $U^c \subset V^c$, thus $\overline {U^c} \subset \overline {V^c} =V^c$ (since $V^c$ is closed). Thus $\overline {U^c} \cap V = \varnothing$, so $\overline {U^c} \cap U = \overline {U^c} \cap V \cap A = \varnothing$.
Similarly, since $U \subset W$, $\overline {U} \subset \overline {W} =W$, so $\overline U \cap W^c = \varnothing$. $U^c = W^c \cap A$, thus $\overline {U} \cap U^c = \overline {U} \cap W^c \cap A = \varnothing$.


text:
Q: Small problem with reg exps in python So I have one variable that has all the code from some file. I need to remove all comments from this file. One of my regexp lines is this
x=re.sub('\/\*.*\*\/','',x,re.M,re.S);
What I want this to be doing is to remove all multi line comments. For some odd reason though, its skipping two instances of */, and removing everything up to the third instance of */.
I'm pretty sure the reason is this third instance of */ has code after it, while the first two are by themselves on the line. I'm not sure why this matters, but I'm pretty sure thats why.
Any ideas?

A: .* will always match as many characters as possible. Try (.*?) - most implementations should try to match as few characters as possible then (should work without the brackets but not sure right now). So your whole pattern should look like this: \/\*.*?\*\/ or \/\*(.*?)\*\/

A: The expression .* is greedy, meaning that it will attempt to match as many characters as possible. Instead, use (.*?) which will stop matching characters as soon as possible.

A: The regular expression is "greedy" and when presented with several stopping points will take the farthest one. Regex has some patterns to help control this, in particular the

(?&gt!...)

which matches the following expression only if it is Not preceeded by a match of the pattern in parens. (put in a pointy brace for &gt in the above - I don't know the forum convention for getting on in my answer).
(?*...) was not in Python 2.4 but is a good choice if you are using a later version.


text:
Q: Windows Batch script to get substring of filenames in a folder I would like to loop through a folder and obtain only the last 13 characters of the file names. Part of what I did is as follows:
for /r . %%g in (*.pdf) do (
    set var=%%~g
    echo %var:~-13%
)

The problem I have is that it is only printing one file name for all the files in the folder. E.g I have the following file names as input :
ARC_1384343086954570285.pdf,
ARC_1384343288950263728.pdf,
ARC_1384343297950370887.pdf.

The output comes out as :
950370887.pdf
950370887.pdf
950370887.pdf

A: Any time you set a variable inside of a for loop, you have to use delayedexpansion to access it.
setlocal enabledelayedexpansion
for /r . %%g in (*.pdf) do (
    set var=%%~g
    echo !var:~-13!
)


text:
Q: Upgrading from 10.04 to 16.04 I have Ubuntu 10.04 and I want to install 16.04.
I have created a USB using a lot of programs, even the one came with the distro; when I try to install 16.04 the monitor shows all it is supposed to show, but without brightness like it is turned off.
Only with a specific boot and a lot of imagination to confuse the system he authorizes me to install Ubuntu.
My question is:
Is it possible to install 16.04 or another version from the desktop from the terminal or something?
Or this can only be done from outside?
mia@mia-laptop:~$ lspci -k

00:00.0 Host bridge: Intel Corporation Mobile 4 Series Chipset Memory Controller Hub (rev 09)
    Kernel driver in use: agpgart-intel
    Kernel modules: intel-agp

00:02.0 VGA compatible controller: Intel Corporation Mobile 4 Series Chipset Integrated Graphics Controller (rev 09)
    Kernel driver in use: i915
    Kernel modules: i915

00:02.1 Display controller: Intel Corporation Mobile 4 Series Chipset Integrated Graphics Controller (rev 09)

00:1a.0 USB Controller: Intel Corporation 82801I (ICH9 Family) USB UHCI Controller #4 (rev 03)
    Kernel driver in use: uhci_hcd

00:1a.1 USB Controller: Intel Corporation 82801I (ICH9 Family) USB UHCI Controller #5 (rev 03)
    Kernel driver in use: uhci_hcd

00:1a.7 USB Controller: Intel Corporation 82801I (ICH9 Family) USB2 EHCI Controller #2 (rev 03)
    Kernel driver in use: ehci_hcd

00:1b.0 Audio device: Intel Corporation 82801I (ICH9 Family) HD Audio Controller (rev 03)
    Kernel driver in use: HDA Intel
    Kernel modules: snd-hda-intel

00:1c.0 PCI bridge: Intel Corporation 82801I (ICH9 Family) PCI Express Port 1 (rev 03)
    Kernel driver in use: pcieport
    Kernel modules: shpchp

00:1c.1 PCI bridge: Intel Corporation 82801I (ICH9 Family) PCI Express Port 2 (rev 03)
    Kernel driver in use: pcieport
    Kernel modules: shpchp

00:1c.2 PCI bridge: Intel Corporation 82801I (ICH9 Family) PCI Express Port 3 (rev 03)
    Kernel driver in use: pcieport
    Kernel modules: shpchp

00:1d.0 USB Controller: Intel Corporation 82801I (ICH9 Family) USB UHCI Controller #1 (rev 03)
    Kernel driver in use: uhci_hcd

00:1d.1 USB Controller: Intel Corporation 82801I (ICH9 Family) USB UHCI Controller #2 (rev 03)
    Kernel driver in use: uhci_hcd

00:1d.2 USB Controller: Intel Corporation 82801I (ICH9 Family) USB UHCI Controller #3 (rev 03)
    Kernel driver in use: uhci_hcd

00:1d.3 USB Controller: Intel Corporation 82801I (ICH9 Family) USB UHCI Controller #6 (rev 03)
    Kernel driver in use: uhci_hcd

00:1d.7 USB Controller: Intel Corporation 82801I (ICH9 Family) USB2 EHCI Controller #1 (rev 03)
    Kernel driver in use: ehci_hcd

00:1e.0 PCI bridge: Intel Corporation 82801 Mobile PCI Bridge (rev 93)

00:1f.0 ISA bridge: Intel Corporation ICH9M LPC Interface Controller (rev 03)
    Kernel modules: iTCO_wdt

00:1f.2 IDE interface: Intel Corporation ICH9M/M-E 2 port SATA IDE Controller (rev 03)
    Kernel driver in use: ata_piix

00:1f.3 SMBus: Intel Corporation 82801I (ICH9 Family) SMBus Controller (rev 03)
    Kernel modules: i2c-i801

00:1f.5 IDE interface: Intel Corporation ICH9M/M-E 2 port SATA IDE Controller (rev 03)
    Kernel driver in use: ata_piix

04:00.0 Network controller: Atheros Communications Inc. AR928X Wireless Network Adapter (PCI-Express) (rev 01)
    Kernel driver in use: ath9k
    Kernel modules: ath9k

05:00.0 Ethernet controller: Broadcom Corporation NetLink BCM5784M Gigabit Ethernet PCIe (rev 10)
    Kernel driver in use: tg3
    Kernel modules: tg3

A: As an exercise, can you try install ubuntu 14.04 first? Anyway, AFAIK it is not possible to upgrade directly to 14.04 or 16.04 directly, no matters what. You have to jump want step at a time, first to 12.04, 14.04 and then 16.04.
Regarding 16.04, if you do not have much experience with Linux and Ubuntu, I would suggest not to try it. It is still not official and may have bugs here and there. You will not know what the problems really are.
Last but not least, I did not have succeed with any of the bootable USB creator recommended by Canonical. The one I find every easy to use is Yumi (the Windows version). I haven't tried the Linux version http://www.pendrivelinux.com/downloads/YUMI/ubuntu/yumi_0.0.1-1_all.deb

A: I have installed Ubuntu 16 via a key bottable: it is a bad idea, it is highly instable for the moment!
Ubuntu 14 is the most stable for me, or you may try the 15.
For answer to your question: for upgrading your version by terminal, you can, see related post:
Upgrading from the command line?
But i offen reinstall ubuntu via USB key, it seems safer to me...


text:
Q: Arpeggio can't go back after a catch Here's a simple code to understand:
def line(): return _(r".+")
def start(): return [line, (line, line)], EOF

parser = ParserPython(start, debug=True)

input_expr = """
A
B
"""

parse_tree = parser.parse(input_expr)

Here, in the rule start, it should try first to catch a line and if it doesn't work, try to catch two lines instead. But looks like Arpeggio doesn't have that capability. And I get arpeggio.NoMatch: Expected EOF at position (3, 1) => ' A *B '.

A: Arpeggio is based on PEG formalism and it never backtracks a successful ordered choice match.
A quote from the Wikipedia PEG article:

The fundamental difference between context-free grammars and parsing expression grammars is that the PEG's choice operator is ordered. If the first alternative succeeds, the second alternative is ignored.

So you have to be careful when ordering your RHS rule references in an ordered choice. The rule of the thumb would be to put more specific matches at the front. In your case line line is more specific and should be tried first.


text:
Q: How can I manage my questions asked before I'm registered? I can't edit or comment now. I guess it's because I changed my computer.
How can I get back the control again?

A: If you have links to the questions then flag one of them (assuming they're all linked to the same account) and ask a moderator to merge that account with your registered one.
Or email "team@stackoverflow.com"

A: Just for the archives: given that accounts are now associated automatically, I guess it's no longer an issue for those who're smart enough to use the same OpenID to log in.
Or, even when not registered, there's an option to get the cookie back† using the account recovery, through the Forgot your login information? link.
† See Jeff's comment here

A: You need to login with the same account as you did before changing computer.


text:
Q: asp.net load server side url but don't open page or window I am trying to load URL from server side and the url is an API that sends SMS.
My problem is I need to load the url but that should not open a page or any window when that is triggered.
string url = "http://xxxxx.xxxxx.com/api/sendmsg.php?user=xxxx&pass=xxxx&sender=xxx&phone=xxxxxxxxxxx&text=this%20is%20test%20sms&priority=ndnd&stype=normal";
string s = "window.open('" + url + "', 'popup_window', 'width=300,height=100,left=100,top=100,resizable=yes');";
ClientScript.RegisterStartupScript(this.GetType(), "script", s, true);

A: Well, you could send an ajax GET request from the client, although I don't understand why you are not calling this URL from the server side instead.
This would be server side:
using(WebClient client = new WebClient ())
{
    string url = "http://xxxxx.xxxxx.com/api/sendmsg.php?user=xxxx&pass=xxxx&sender=xxx&phone=xxxxxxxxxxx&text=this%20is%20test%20sms&priority=ndnd&stype=normal";
    client.DownloadString(url);
}

If you choose do it on client side, you can use this code:
string url = "http://xxxxx.xxxxx.com/api/sendmsg.php?user=xxxx&pass=xxxx&sender=xxx&phone=xxxxxxxxxxx&text=this%20is%20test%20sms&priority=ndnd&stype=normal";
string s = "var xmlHttp = new XMLHttpRequest();";
s += "xmlHttp.open('GET'," + url + ", false);";
s += "xmlHttp.send(null);";

ClientScript.RegisterStartupScript(this.GetType(), "script", s, true);

A: instead of using window.open, You can use iframe with display:none and then change url of this iframe.
Please find the code below.
Using RegisterStartupScript
ASPX

Code behind
protected void Page_Load(object sender, EventArgs e)
{
    string url = "updateDiv(\"\");";

        ClientScript.RegisterStartupScript(this.GetType(), "script", url, true);
    }

Another approach during pageload
ASPX

Code behind
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string iframeString = "";

            myCustomDiv.InnerHtml=iframeString;
        }
    }

A: If you want it to open in the current window,
 then replace the 'popup_window' with '_self'

A: There's a whole slew of ways to accomplish this  task:

*

*Use AJAX to send a GET or POST request to this URL.  This is easily done via the regular browser api or via JQuery.

*You can load an iframe which is set to have minimal width/height, or just no display.

*You could just add an img tag to the page, with the src attribute set to the url of your API.  If you use this option, then it would be best to find a way to hide the image not found icon.
The browser is designed to send requests, so it has many ways to do so, all of which will have their own properties and trade-offs.  I recommend looking into the many ways to accomplish this and choose which best fits your particular use case.  Good luck!


text:
Q: Array hierarchy for pagination I'm having problems with this table which has brought by coding to a little stop.
I have an mysql table which i need to create an array out of. In this example i am looking at islenska-stig1 which has the ID 9 and no parent_id.
INSERT INTO `posts` (`id`, `parent_id`, `category`, `position`, `post_slug`, `titill`) VALUES
(9, 0, 3, 0, 'islenska-stig1', 'Íslenska stig 1'),
(10, 0, 3, 0, 'islenska-stig2', 'Íslenska stig 2'),
(19, 9, 3, 0, 'kafli1', 'Kafli 1'),
(20, 9, 3, 0, 'kafli2', 'Kafli 2',),
(21, 19, 3, 0, 'serhljodar', '1.1 Serhljodar'),
(22, 19, 3, 0, 'samhljodar', '1.2. Samhljóðar'),
(23, 19, 3, 0, 'malnotkun', '1.3 Málnotkun'),
(24, 21, 3, 1, 'aefing1', 'Æfing 1'),
(26, 21, 3, 3, 'prof1', 'Próf 1');

This information i need to convert into an array which i can use to paginate (next, last from current slug). The array i'm trying to set up looks something like this:
Array
(
    [0] => islenska-stig1
    [1] => kafli1
    [2] => serhljodar
    [3] => aefing1
    [4] => prof1
    [5] => samhljodar
    [6] => malnotkun
    [7] => kafli2
)

The array then loops over when i open array[7] or kafli2.
Any suggestion's withouth having to open multiple connections to the database?
ADDED to explain the following

The array then loops over when i open array[7] or kafli2.

As i see it i otherwise populate more data from the query, that is children's of kafli2 (ID#20) or create a new pagination array.
Option one
Array
(
    [0] => islenska-stig1
    [1] => kafli2
    [2] => ...
)

Option two
Array
(
    [0] => islenska-stig1
    [1] => kafli1
    [2] => serhljodar
    [3] => aefing1
    [4] => prof1
    [5] => samhljodar
    [6] => malnotkun
    [7] => kafli2
    [8] => ...
)


text:
Q: Elasticsearch 6.2 start a localhost http node in unit test My goal is to start a localhost elasticsearch node in my junit test, so I can index some docs and also test search queries through high level rest client(e.g. making http calls to localhost ES node). I'm using Elasticsearch 6.2.
Here is the code I tried
    String clusterName = "test";
    Settings settings = Settings.builder()
            .put("path.home", ES_WORKING_DIR)
            .build();
    new Node(settings).start();

and this is the error message I got..
java.lang.IllegalStateException: Unsupported transport.type []

at __randomizedtesting.SeedInfo.seed([74752622FDACDD5:AB9FD863FD5A2A5F]:0)
at org.elasticsearch.common.network.NetworkModule.getTransportSupplier(NetworkModule.java:212)
at org.elasticsearch.node.Node.<init>(Node.java:427)
at org.elasticsearch.node.Node.<init>(Node.java:246)
at org.elasticsearch.node.Node.<init>(Node.java:242)

Basically, I'm not sure what parameters to set in Settings.
Thanks in advance.

A: These are no longer supported by elastic, but they work for Junit test purposes
I have the following
For 5.6.7
Settings.Builder nodeSettings = Settings.builder()
            .put("cluster.name", "my-integration-test")
            .put("http.enabled", "true")
            .put("path.data", dataDirectory)
            .put("path.home", "/")
            .put("transport.type", "netty4")
            .put("network.host", "_local_")
            .put("transport.tcp.port", "19200-19400")
            .put("http.port", "19200-19400")
            .put("discovery.type", "single-node");

    LOG.info("Starting up embedded Elasticsearch");
    node = new LocalNode(nodeSettings.build(), Arrays.asList(Netty4Plugin.class,
            ReindexPlugin.class));
    node.start();

For elastic 6.8.3
        Settings.Builder nodeSettings = Settings.builder()
            .put("cluster.name", "integration-test")
            .put("node.name", "node-test")
            .put("path.data", dataDirectory)
            .put("path.home", "/")
            .put("transport.type", "netty4")
            .put("network.host", "127.0.0.1")
            .put("http.port", "19200");

    LOG.info("Starting up embedded Elasticsearch");
    node = new LocalNode(nodeSettings.build(), Arrays.asList(Netty4Plugin.class,
            ReindexPlugin.class,
            CommonAnalysisPlugin.class));

        node.start();

where
private static class LocalNode extends Node {

    LocalNode(Settings settings, Collection<Class<? extends Plugin>> classpathPlugins) {
        super(new Environment(settings, null), classpathPlugins, true);
    }

    @Override
    protected void registerDerivedNodeNameWithLogger(final String s) {}

}

For 6.8.x you will need
    <dependency>
        <groupId>org.codelibs.elasticsearch.module</groupId>
        <artifactId>analysis-common</artifactId>
        <version>6.8.2</version>
    </dependency>


text:
Q: My NVidia mobile graphics with Haswell CPU won't work I installed Ubuntu on my Lenovo Y410P (Haswell CPU, NVidia GT750M, Windows 8 and UEFI) and after boot the screen just turned off instead of showing Unity. I messed around  lot, and with nomodeset could sometimes get a display to come up, but it was the wrong size. I was so confused that I uninstalled, but Windows is dreadful and not able to do everything I do in Ubuntu. The OS I used was stock Ubuntu 13.04, which I would prefer to use, although elementaryOS 0.2 (12.04.2 derivative) is also acceptable. Any ideas?
(Sorry for posting this new question but I am so confused and can't find any answers elsewhere.
Edit: So now I reinstalled with 12.04.2, on my phone now but will try nomodeset to install when I get home.

A: Press function and the up arrow key (brightness). I had the same issue on my Y510p and discovered by accident that the screen brightness defaults to off upon boot.

A: Yo.. I got it to work..
It's the problem with the Nvidia graphics card.

*

*Download and install Nvidia graphics card from Nvidia website or wherever.

*What you need to do is remove the Nouveau (Intel driver) which is clashing with Nvidia during load (I think that's the problem because I check my logs it seems that it's unable to load Nvidia) so.
sudo apt-get --purge remove xserver-xorg-video-nouveau

then restart your machine. WALLA!
also, i had mesa installed as well beforehand to get glx to get me what I need.
from https://help.ubuntu.com/community/BinaryDriverHowto/Nvidia


text:
Q: how to reference an asset in a library project In a class belonging to a Library project I call:
webview.loadUrl("file:///android_asset/info.html", null);

Unfortunately, this only works if I duplicate the file info.html into the Application's project asset folder as well.
Is there a way to tell an Android library code: "look for this file in the library's assets folder, not in the application's assets folder" ?

A: This answer is out of date, the gradle build system and AAR files support assets.

From the Android Docs:

Library projects cannot include raw assets
The tools do not support the use of raw asset files (saved in the assets/ directory) in a library project. Any asset resources used by an application must be stored in the assets/ directory of the application project itself. However, resource files saved in the res/ directory are supported.

If you want to include files from a Library project, you'll need to put it in the resources instead of the assets. If you're trying to load HTML files from your library project into a WebView, this means that you'll have to go a more roundabout method than the usual asset URL. Instead you'll have to read the resource data and use something like loadData.

A: I confirm that Daniel Grant's approach works for at least the following situation: target project does NOT have an asset folder (or the folder is empty, so you can safely delete it).
I did not setup any variable.
Simply setup a LinkSource as follows (just an example)
    Linked folder location: /home/matthew/workspace_moonblink/assetsForAdvocacy/assets
    Folder name : assets
The "assetsForAdvocacy" is a Java project, (created with New- Project - Java Project) with empty src folder, and a new folder named "assets", which now provides the entire assets folder for the target project.
This is a fairly straightforward way within Eclipse to provide assets re-use across many different projects IF they do not already have assets, good enough to get going with. I would probably want to enhance it to become a content provider in the long run, but that is a lot more development.
My project accesses the assets with the following code:
    String advocacyFolderInAssets = "no_smoking/"; //a folder underneath assets/
    String fn =advocacyFolderInAssets+imageFilename;
    Bitmap pristineBitmapForAdvocacy = getBitmapFromAsset(context, fn);
I use Motodev Studio 3.1.0 on Ubuntu. It would not let me 'merge' a new assets folder in the new assets-only project onto an existing assets folder in the target project.

A: This is now possible using the Gradle build system.
Testing with Android Studio 0.5.0 and v0.9 of the Android Gradle plugin, I've found that files such as
MyLibProject/src/main/assets/test.html

are correctly packaged in the final application and can be accessed at runtime via the expected URL:
file:///android_asset/test.html

A: You can achieve this by creating a symbolic link in the project's asset folder that points to the directory in the library project.
Then you can access as below:
webview.loadUrl("file:///android_asset/folder_in_a_libary_project/info.html", null);

A: Okay. Ive been stressing out and losing sleep about this for a while. Im the type of person that loves API creation, and HATES complicated integration.
There arent many solutions around on the internet, so im quite proud of what Ive discovered with a bit of Eclipse Hackery.
It turns out that when you put a file in the Android Lib's /assets folder. The target apk will capture this and place it on the root of the APK archive. Thus, making general access fail.
This can be resolved by simply creating a Raw Java Library, and placing all assets in there, ie (JAVALIB)/assets/fileX.txt.
You can in turn then include this as a Java Build Path Folder Source in
Project > Properties > Java Build Path > Source > Link Source.

*

*Link Source

*Click on Variables. and Add New Variable, ie VAR_NAME_X. location : ../../(relative_path_to_assets_project)

*Click Ok

Now, when you build and run your app, the assets folder in the APK will contain your (GLOBAL Library) files as you intended.
No need to reconfigure android internals or nothing. Its all capable within a few clicks of Eclipse.

A: If you want to use a setup where multiple derivate products are created from one library you might consider using svn:externals or similar solution in your SCM system. This will also do the trick that static assets like online help may be versioned seperately from the android source code.

A: I found this older question, it might help you, too.
This is the official way Google uses to archive this (from the above post): Link


text:
Q: strange behaviour of cout? In a long assignment I found a miraculous behaviour of cout!!
`
for(i=0; i<ndel; i++)
    {
        cin>>a;
        head=Delete(head, a);
        cout<<"Deleting ";
        cout<<a<<endl;
            //cout<<"Deleting "<<a<<endl; /*this gives seg error*/

        printInts(head);
    }

`

The code works fine with
 cout<<a<<endl;

but gives a segmentation fault with
cout<<"Deleting "<<a<<endl;

Here's my Delete function:
node* Delete(node *T, int a)
{
    if(a==1 && T!=NULL)
    {
        T->flag=0;
        return T;
    }
    int arr[50];
    int n, i, tr_num; /* tr_num is the index of array corresponding to last node not to be deleted if the no. to be del is leaf*/
    node *tr, *ptr;  /*tr istracker on last pointer that cannot be deleted if it encounters leaf*/
    node *pth[50];
    n=find_binary(arr, a);
    tr=T;
    ptr=T;
    pth[0]=T;
    tr_num=0;
    for(i=0; i<n-1; i++)
    {
        if(arr[n-2-i]==0)
        {
            if(ptr->left==NULL)
            {
                return T;
            }
            ptr=ptr->left;
            pth[i+1]=ptr;

            if((ptr->flag==1 && (ptr->right!=NULL || ptr->left!=NULL)) || (ptr->right!=NULL && ptr->left!=NULL))
            {
                tr_num=i+1;
                tr=ptr;
            }
        }

        if(arr[n-2-i]==1)
        {
            if(ptr->right==NULL)
            {
                return T;
            }
            ptr=ptr->right;
            pth[i+1]=ptr;

            if((ptr->flag==1 && (ptr->right!=NULL || ptr->left!=NULL)) || (ptr->right!=NULL && ptr->left!=NULL))
            {
                tr_num=i+1;
                tr=ptr;
            }
        }
    }
    ptr->flag=0;
    if(ptr->left==NULL && ptr->right==NULL)
    {
        for(i=n-1; i>=tr_num+1; i--)
        {
            delete pth[i];
            pth[i]=NULL;
        }
        if(arr[n-tr_num-2]==1)
        {
            pth[tr_num]->right=NULL;
        }
        else if(arr[n-tr_num-2]==0)
        {
            pth[tr_num]->left=NULL;
        }

    }

    return T;
}

Here's the find binary code..
int find_binary(int arr[], int num)
{
    int i=0;

    while(num!=0)
    {
        arr[i]=num%2;
        num=num/2;
        i++;
    }
return i;
}

In another instance:
I have a function with prototype
node * search(node *T, int a);

calling this function in main
    cout<<search(BT, 7);

works!
But
node *ptr=search(BT, 7);

gives segmentation error!! I am clueless why, because the similar assignment works completely fine in my delete function but in main it gives segmentation error!!
Note: node is a structure.
I compile using g++


text:
Q: Nginx stops responding after a while. Possible pagespeed fault? If anyone could please help me out with this issue, I'd be VERY grateful!
Running EasyEngine with nginx/1.8.0 and PageSpeed 1.9.32.4-7251. Almost every day, after a certain time I assume, the website stops responding and I have to restart the nginx service remotely. Monit doesn't catch the fault.
I think this excerpt from error.log is connected.
What could be causing the problem? How can I remedy this?
2015/12/28 06:35:17 [info] 28791#0: [ngx_pagespeed 1.9.32.4-7251] No threading detected. Own threads: 1 Rewrite, 1 Expensive Rewrite.
2015/12/28 06:35:18 [alert] 30740#0: *0 open socket #19 left in connection 4
2015/12/28 06:35:18 [alert] 30740#0: *50008 open socket #3 left in connection 5
2015/12/28 06:35:18 [alert] 30740#0: *50009 open socket #28 left in connection 6
2015/12/28 06:35:18 [alert] 30740#0: *50010 open socket #31 left in connection 7
2015/12/28 06:35:18 [alert] 30740#0: *0 open socket #29 left in connection 8
2015/12/28 06:35:18 [alert] 30740#0: *0 open socket #32 left in connection 9
2015/12/28 06:35:18 [alert] 30740#0: *50011 open socket #34 left in connection 10
....
2015/12/28 06:35:18 [alert] 30740#0: *0 open socket #822 left in connection 536
2015/12/28 06:35:18 [alert] 30740#0: *50298 open socket #824 left in connection 537
2015/12/28 06:35:18 [alert] 30740#0: *0 open socket #825 left in connection 538
2015/12/28 06:35:18 [alert] 30740#0: *50299 open socket #827 left in connection 539
2015/12/28 06:35:18 [alert] 30740#0: *0 open socket #828 left in connection 540
2015/12/28 06:35:18 [alert] 30740#0: *50300 open socket #830 left in connection 541
2015/12/28 06:35:18 [alert] 30740#0: *0 open socket #831 left in connection 542
2015/12/28 06:35:18 [alert] 30740#0: *50301 open socket #833 left in connection 543
2015/12/28 06:35:18 [alert] 30740#0: *0 open socket #834 left in connection 544
2015/12/28 06:35:18 [alert] 30740#0: *50302 open socket #836 left in connection 545
2015/12/28 06:35:18 [alert] 30740#0: *0 open socket #837 left in connection 546
2015/12/28 06:35:18 [alert] 30740#0: *50303 open socket #839 left in connection 547
2015/12/28 06:35:18 [alert] 30740#0: *0 open socket #840 left in connection 548
2015/12/28 06:35:18 [alert] 30740#0: *50304 open socket #842 left in connection 549
2015/12/28 06:35:18 [alert] 30740#0: *0 open socket #843 left in connection 550
2015/12/28 06:35:18 [alert] 30740#0: *50305 open socket #845 left in connection 551
2015/12/28 06:35:18 [alert] 30740#0: *0 open socket #846 left in connection 552
2015/12/28 06:35:18 [alert] 30740#0: *50306 open socket #848 left in connection 553
2015/12/28 06:35:18 [alert] 30740#0: *0 open socket #849 left in connection 554
2015/12/28 06:35:18 [alert] 30740#0: *50307 open socket #851 left in connection 555
2015/12/28 06:35:18 [alert] 30740#0: *0 open socket #852 left in connection 556
2015/12/28 06:35:18 [alert] 30740#0: *50308 open socket #854 left in connection 557
2015/12/28 06:35:18 [alert] 30740#0: *0 open socket #855 left in connection 558
2015/12/28 06:35:18 [alert] 30740#0: aborting
2015/12/28 06:35:18 [alert] 30740#0: [ngx_pagespeed 1.9.32.4-7251] [1228/063519:FATAL:categorized_refcount.h(118)] Check failed: ref_counts_[category] >= 0 (-1 vs. 0)0
nginx: worker process is shutting down() [0x551419]
nginx: worker process is shutting down() [0x54e432]
nginx: worker process is shutting down() [0x5a6333]
nginx: worker process is shutting down() [0x58e22c]
nginx: worker process is shutting down() [0x58e35d]
nginx: worker process is shutting down() [0x61ca27]
nginx: worker process is shutting down() [0x57c200]
nginx: worker process is shutting down() [0x69e04e]
nginx: worker process is shutting down(net_instaweb::NgxRewriteDriverFactory::~NgxRewriteDriverFactory()+0x1b) [0x516c8b]
nginx: worker process is shutting down(net_instaweb::NgxRewriteDriverFactory::~NgxRewriteDriverFactory()+0x9) [0x516e09]
nginx: worker process is shutting down() [0x50dee6]
nginx: worker process is shutting down(ngx_destroy_pool+0x1e) [0x42b14e]
nginx: worker process is shutting down() [0x44a39b]
nginx: worker process is shutting down() [0x44a54a]
nginx: worker process is shutting down(ngx_spawn_process+0x170) [0x448ec0]
nginx: worker process is shutting down(ngx_master_process_cycle+0x716) [0x44b986]
nginx: worker process is shutting down(main+0x77f) [0x428d0f]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf5) [0x7f400f1eaec5]
nginx: worker process is shutting down() [0x4292cf]

nginx: worker process is shutting down() [0x551419]
nginx: worker process is shutting down() [0x508810]
nginx: worker process is shutting down() [0x54e514]
nginx: worker process is shutting down() [0x5a6333]
nginx: worker process is shutting down() [0x58e22c]
nginx: worker process is shutting down() [0x58e35d]
nginx: worker process is shutting down() [0x61ca27]
nginx: worker process is shutting down() [0x57c200]
nginx: worker process is shutting down() [0x69e04e]
nginx: worker process is shutting down(net_instaweb::NgxRewriteDriverFactory::~NgxRewriteDriverFactory()+0x1b) [0x516c8b]
nginx: worker process is shutting down(net_instaweb::Ngx


text:
Q: Flex 3: Top align Image and Label In Adobe Flex 3, I have an HBox containing an Image and a Label:
<mx:HBox width="240" verticalAlign="top" horizontalGap="8">
    <mx:Image width="46" source="@Embed(source='/assets/blah.swf')"/>
    <mx:Label text="Blah."/>
</mx:HBox>

My Goal is to align the top edge of the Image and the top edge of the Label (the top of capital characters within the Label, that is). However, no matter what properties and styles I fiddle with, a constant "padding" (in quotes because paddingTop is zero) of some 6 pixels remains above the Label, setting its top edge below the Image's. Does anyone know why?
Thanks, Simon
edit:
paddingTop is not doing the trick. I'm seeing the same behaviour on this:
<mx:HBox width="240" verticalAlign="top" paddingTop="0">
    <mx:Canvas width="46" height="46" backgroundColor="red" paddingTop="0"/>
    <mx:Label text="Blah." paddingTop="0"/>
</mx:HBox>

I also verified that there's no global stylesheet interfering with any of those classes.
edit 2:
From the mx.core.UITextField source code (Flex 3.2.0) which is used internally by Label, ll. 159:

    /*
        The width and height of the TextField are 4 pixels greater than
        the textWidth and textHeight.
    */

and also
   public function get measuredHeight():Number
   {
   (...)
       return textHeight + TEXT_HEIGHT_PADDING;
   (...)
   }

Then I set my Label's paddingTop to -4, and voilà, problem solved! It's not really a clean solution, though...

A: I've just been fiddling around with this and it seems you have to actually set the paddingTop to zero for the Label, because if you don't declare any padding it will use the component's built-in padding, so it won't be zero.
This seemed to be working when I ran the example.
Edit: Dirty, but fixed, right? ;)


text:
Q: Configuring BCM4360 (MacBook Air) on FreeBSD to connect to WiFi I just installed FreeBSD 12.1 RELEASE on my MacBook Air 13-inch Early 2015, and one of the notable problems is the lack of WiFi due to the bwn kernel module not being loaded. I loaded it and told the /boot/loader.conf to load it at boot, rebooted, and it did not work. I checked ifconfig but only loopback was shown.
Output of pciconf -lv says the network adapter is a BCM4360 802.11ac Wireless Network Adapter. How can I configure it to work?

A: Have you taken a look at the manual page for bwn(4)1? It mentions that bwn devices need firmware to be loaded.
Installing firmware
Firmware for those devices is available as a port called net/bwn-firmware-kmod. Due to license reasons, there is no binary package available for this port via pkg(8), so it has to be installed from ports(7) by the user with something like:
cd /usr/ports/net/bwn-firmware-kmod && make install

Please refer to the Using the Ports Collection chapter of the FreeBSD Handbook for more details on how to work with ports.
What if I do not have network connection on the machine at all?
Of course, it gets tricky to do it if you do not have access to the network from that machine. In this case, you could do the following:
On another FreeBSD machine which is connected to the network, run the following command.
cd /usr/ports/net/bwn-firmware-kmod && make -DFORCE_PACKAGE package

This command will generate a package (which will be located in /usr/ports/head/net/bwn-firmware-kmod/work/pkg/bwn-firmware-kmod-0.1.2.txz) for you.
It can be then copied to the disconnected laptop (with a USB stick for example) and installed with tar -x -f ./bwn-firmware-kmod-0.1.2.txz2.

1: Assuming that bwm is just a typo.
2: It would be much better to install the package with pkg but the real pkg(8) which is the package manager on FreeBSD has to be bootstrapped with pkg(7). It is doable without network connection, but probably unnecessarily complicated in your case.

A: The bwn-firmware-kmod-port does not appear to support BCM4360 at the moment: https://unix.stackexchange.com/a/465292/243368


text:
Q: Tiny VM based on immutable data structures? Is there any "tiny" VM (for any programming language) where the main data structures visible to the user (lists, arrays, maps, sets, etc.) are immutable as in Clojure or Haskell?
By "tiny" I mean a VM where implementation simplicity, brevity and portability are key points: think Lua or TinyScheme.

A: I'm not sure how it aligns with your "key points", but you might take a look at Pixie.  Pixie implements a VM in RPython.  One of its claims is a small footprint of just over 10MB for the compiled VM + standard libs.  The language is a lisp based (loosely) on Clojure.  It appears to maintain Clojure's policy of immutable by default, and definitely has implementations of Clojure's persistent datatypes.

A: Owl Lisp
A "purely functional Scheme". The VM is 1600 lines of C.

Owl Lisp is a purely functional dialect of Scheme. It is based on the
  applicable subset of R7RS standard, extending it mainly with threads
  and data structures necessary for purely functional operation. Owl can
  be used on most UNIX-like systems, such as Linux, BSDs and OS X.
  Programs are typically compiled via C to standalone binaries, so Owl
  isn't needed to run programs written in it.
Owl project originally got started both as an attempt to extend R5RS
  Scheme with some necessary features, such as threads and modules, and
  as an experiment on how being purely functional influences the runtime
  and use of an applicative order purely functional language. While
  things have been added to Scheme, Owl tries to keep the core language
  as simple as possible.
Implementationwise the goal was to get a small portable system which
  could be used to ship programs easily. This is currently accomplished
  by using a small register-based virtual machine, which can be extended
  with program-specific instructions to reduce interpretive overhead.

*

*https://haltp.org/n/owl

*https://github.com/aoh/owl-lisp
ClojureC

Compiler for the Clojure programming language that targets C
  as a backend. It is based on ClojureScript ... Before you can run
  anything make sure you have GLib 2 and the Boehm-Demers-Weiser garbage
  collector installed.

*

*https://github.com/schani/clojurec
TinyClojure

TinyClojure is a project to build a small, easily embeddable version
  of Clojure/ClojureScript in portable C++. In many ways it is my
  attempt to create a Clojure equivalent of TinyScheme.
...
ClojureC is good, but the build process is complex, and
  there are external library dependencies ... The focus with TinyClojure's development is to make it the easiest way
  to embed Clojure within any application. Tiny Clojure consists of one
  header file, one source file, no external dependencies, and the
  extension and embedding interface is as simple as it is possible to
  be.

*

*https://github.com/WillDetlor/TinyClojure/


text:
Q: How to create sort method in Dart? Given a List<String> of months, how do I create my own sort method in Dart?
Consider this relevant link.
The sorting order would be:
["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]

Example
Given:
List<String> months = ["October", "January", "July"];

The expected output is:
["January", "July", "October"]

A: You can make use of the List.sort method.
With the sorting order you provided, you can use indexOf to get an integer value that represent the sorting "weight" and then use num.compareTo to return a negative value if element a should appear before element b, i.e. the indexOf value is smaller, and a positive value if it should appear after element b:
const List<String> sortingOrder = ['January', 'February', 'March', 'April',
  'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

List<String> months = ['October', 'January', 'July'];
months.sort((a, b) => sortingOrder.indexOf(a).compareTo(sortingOrder.indexOf(b)));

print(months); // [January, July, October]

This way, you can obviously very easily create any kind of sorting order that sorts different kinds of values.


text:
Q: Rails Console: User will not save - Stack level too deep I've run into an error in the Rails console. I'm using the latest version of Rails and Pry. I am attempting to generate a user. I am able to set values within user attributes, but am unable to save them. Maybe User.new is looping somewhere? Here's the attribute-related code of my model:
require 'bcrypt'
class User < ActiveRecord::Base

attr_accessible :first_name, :last_name, :description, :profile_photo, :password, :password_confirmation, :email
attr_reader :password

has_secure_password

validates_presence_of :email, :session_token, :first_name, :last_name, :password_digest
validates_uniqueness_of :email
validates :password, length: { minimum: 6, maximum: 20 }

before_validation :reset_session_token!, on: :create
before_save :encrypt_new_password

This is my users migration:
class CreateUsers < ActiveRecord::Migration
def change
 create_table :users do |t|
  t.string  :email, unique: true, null: false
  t.string  :password_digest, null: false
  t.string  :first_name, null: false
  t.string  :last_name, null: false
  t.string  :description, limit: 400
  t.string  :session_token, null: false
  t.attachment :profile_photo
  t.integer :profile_photo_id
  t.datetime :profile_photo_updated_at

  t.timestamps
end

  add_index :users, :email
  add_index :users, :first_name
  add_index :users, :last_name
  add_index :users, :session_token
  add_index :users, :created_at
 end
end

And here's my Rails console error after trying to create a user via User.new(values) then .save, or User.create(values), or u = User.new then u.value = value then u.save.
[10] pry(User):1> u.save
(0.2ms)  BEGIN
(0.2ms)  ROLLBACK
SystemStackError: stack level too deep
from /Users/joecase/.rvm/gems/ruby-2.1.0/gems/pry-0.9.12.6/lib/pry/pry_instance.rb:328
[11] pry(User):1> u.errors
=> #<ActiveModel::Errors:0x0000010527ccb0
@base=
#<User id: nil, email: "joecase@nyu.edu", password_digest: "111111", first_name: "Joe", last_name: "Case", description: nil, session_token: "CVnrsyyTwoOp9TZkqmVfTw", profile_photo_file_name: nil, profile_photo_content_type: nil, profile_photo_file_size: nil, profile_photo_updated_at: nil, profile_photo_id: nil, created_at: nil, updated_at: nil>,
@messages={}>

[12] pry(User):1> u.errors.full_messages
=> []

ANY help would be appreciated. Thank you in advance.
encrypt_new_password:
def encrypt_new_password
  return if password.blank?
  self.hashed_password = encrypt(password)
end

reset_session_token:
 def reset_session_token
   self.session_token ||= SecureRandom.urlsafe_base64(16)
   save!
 end

A: Most likely, the problem would be in the the call back function before_save :encrypt_new_password.
If the function :encrypt_new_password tries to update and save the user record you will face this problem, would be great if you can edit your question and post the :encrypt_new_password
function as it is the function most likely causing the infinite callbacks.
Looking at the two provided functions for the callbacks, the problem is in the function of the callback for the validation.
def reset_session_token
   self.session_token ||= SecureRandom.urlsafe_base64(16)
   save!
end

before validations you save which would validate and before validations you save and so on. So try to hash out the save! call it should be saved, if not try to make it an after_validation callback.

A: Maybe there is some confusion that you are calling in callback reset_session_token! but defined method without a excalmation mark? No other idea though.


text:
Q: Deploying first app to VPS, struggling with capistrano I'm trying to deploy my first app to a VPS ubuntu 12.10, using capsitrano, and following the RailsCasts "Deploying to a VPS" videocast.
One more question, i haven't added an nginx config, nor a unicorn config file. Can i go without them? ( I will want to config nginx trough console.)
My deploy.rb file
require "bundler/capistrano"

set :application, "picurwebaruhaz"

set :scm, "git"
set :repository,  "git://github.com/gwuix2/picurwebaruhaz.git"
set :branch, "master"
set :user, "gwuix2"
set :deploy_to, "/home/#{user}/#{application}"

default_run_options[:pty] = true

# set :scm, :git # You can set :scm explicitly or Capistrano will make an intelligent guess based on known version control directory names
# Or: `accurev`, `bzr`, `cvs`, `darcs`, `git`, `mercurial`, `perforce`, `subversion` or `none`

role :web, "198.211.117.84"                          # Your HTTP server, Apache/etc
role :app, "198.211.117.84"                          # This may be the same as your `Web` server
role :db,  "198.211.117.84", :primary => true # This is where Rails migrations will run
role :db,  "198.211.117.84"

# if you want to clean up old releases on each deploy uncomment this:
after "deploy:restart", "deploy:cleanup"

# if you're still using the script/reaper helper you will need
# these http://github.com/rails/irs_process_scripts

# If you are using Passenger mod_rails uncomment this:
 namespace :deploy do
   task :start do ; end
   task :stop do ; end
   task :restart, :roles => :app, :except => { :no_release => true } do
     run "#{try_sudo} touch #{File.join(current_path,'tmp','restart.txt')}"
   end
 end

I get the following error:
  * executing "cd /home/gwuix2/picurwebaruhaz/releases/20130322113243 && bundle install --gemfile /home/gwuix2/picurwebaruhaz/releases/20130322113243/Gemfile --path /home/gwuix2/picurwebaruhaz/shared/bundle --deployment --quiet --without development test"
    servers: ["198.211.117.84"]
    [198.211.117.84] executing command
 ** [out :: 198.211.117.84] sh: 1: bundle: not found
    command finished in 357ms
*** [deploy:update_code] rolling back
  * executing "rm -rf /home/gwuix2/picurwebaruhaz/releases/20130322113243; true"
    servers: ["198.211.117.84"]
    [198.211.117.84] executing command
    command finished in 384ms
failed: "sh -c 'cd /home/gwuix2/picurwebaruhaz/releases/20130322113243 && bundle install --gemfile /home/gwuix2/picurwebaruhaz/releases/20130322113243/Gemfile --path /home/gwuix2/picurwebaruhaz/shared/bundle --deployment --quiet --without development test'" on 198.211.117.84

Edit:
Here is my app:
APP ON GITHUB https://github.com/gwuix2/picurwebaruhaz
Edit_2:
If I SSH into the server and run $ gem install bundler, it installs, but when I run:
 gwuix2@picurbolt:~$ sudo gem install bundler sudo: gem: command not
 found

any suggestions?
Can't figure it out myself.

A: deploy.rb needs:
require "rvm/capistrano"
require "bundler/capistrano"

A: Try running bundler command without sudo:
gwuix2@picurbolt:~$ gem install bundler sudo: gem: command not found


text:
Q: PDO search fails with multiple numbers I'm trying to search a database using either a name OR a reference number (in the format ABC/X/012345/XX).
The name searches appear perfectly, as do reference number searches if I look for ABC or XX.
But if I search for the full reference number, no matches are found. The problem also happens with a partial reference number search containing more than one number (e.g. ABC/X/01 or even just 01).
I don't get an error message and the 'Sorry, your search returned no results' message isn't displayed, which would seem to suggest it's finding the correct entries, just not displaying them.
Can anyone spot where I'm going wrong? Thanks!
$search = $_POST['search'];

$search_term = "%".$search."%";

try {
    $DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
    $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    $STH = $DBH->prepare('SELECT user_id, name FROM users WHERE name LIKE :search_term OR ref_number LIKE :search_term');
    $STH->bindParam(':search_term', $search_term, PDO::PARAM_STR);
    $STH->execute();
    $STH->setFetchMode(PDO::FETCH_ASSOC);
    if ($STH->fetchColumn() > 0) {
        while($row = $STH->fetch()) {
        echo "".$row['name']."
";
        }
    } else {
        echo '
Sorry, your search returned no results.
';
    }
}

catch(PDOException $e) {
    echo $e->getMessage();
}

A: PDOStatement::fetchColumn($index = 0) fetches a whole row and returns the $indexth column's value. If you want to test how many rows your query returns, use PDOStatement::rowCount()


text:
Q: Rails hide controller name i have match ":id" => "people#show" in my routes.rb
now i can access http://localhost:3000/1
but,in views <%= link_to 'Show', people %> it will generate http://localhost:3000/people/1 ,
i want to it to be http://localhost:3000/1

A: You could do something like this to ensure that only numeric ids are matched:

match '/:id' => 'people#show', :constraints => {:id => /\d+/}

A good alternative might be to use some kind of identifier, even if it's not the controller name: http://localhost:3000/p/1. This will at least ensure that if you add other controllers and actions you don't end up having to change your routing structure.

A: You could write a custom route to match that in config/routes.rb. At the bottom of your routes.rb file you will have a route like match ':controller(/:action(/:id(.:format)))'
or something like resources :people. You might have to write a route that matches the route type you want.

A: You have to create a named route.
match ':id' => 'people#show', :as => :person

And fix your views to use your new method person_path(user_id).


text:
Q: Hibernate and Glassfish : Class is not mapped First my apologies :

*

*For my bad english : I'm french so my vocabulary might be limited...

*If my problem has already be solved earlier. I searched through a lot of topic but couldn't find my answer.

I'm new to EJB and Hibernate and I'm trying to run a basic program which at some point uses a Hibernate Query to check if an entry is present in my database.
I'm "hot-deploying" it from Eclipse (Juno) to my GlassFish domain (Glassfish V3), and my database is a 5.5.28 MySQL server.
My problem is : when i use the Query.creatyQuery method to get the result I want, i get the org.hibernate.hql.internal.ast.QuerySyntaxException: class is not mapped.
The problem is... it IS mapped. I'm using "annotation mapping" method... so no Hibernate hbm.xml mapping file involved. I tested it within a local Java Application, with the same exact syntax in my query, and it gave me the correct result.
I assume I forgot something while deploying but I really can't figure out what...
Here are the options I tested / facts I assume :

*

*If the exception occurs at that time of the query process, it means that my hibernate.cfg.xml file is found and correctly read (So I think that the required libraries from hibernate I placed in lib directories of Glassfish, as well as my JDBC driver).

*I tried to use .class.getName() to check wether or not I'm using the good class name in my query (I do know it's the class name that must be  used inside the query and not the correponding table in my database). It gave me the class name I expected, and didn't solve my problem.
Now for my code:
Login.java (package session)
package session;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;

import org.hibernate.Query;
import org.hibernate.Session;

import entity.*;

@Stateless
@LocalBean
public class Login {

    public Login() {
    }

    public boolean confirmerLogin(String pseudo, String mdp){
        Session s = HibernateUtils.getSession();
        Query q = s.createQuery("From Joueur where pseudo ='"+pseudo+"'");
        if(q.list().size()>=1)
        return true;
        else
        return false;
    }

}

The method confirmerLogin() return true or false wether the argument  is found or not in my database.
Joueur.java (package entity)
package entity;

import java.io.Serializable;
import javax.persistence.*;

@Entity
public class Joueur implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int idJoueur;
private String mdp;
private String pseudo;

public Joueur() {
}

public int getIdJoueur() {
    return this.idJoueur;
}

public void setIdJoueur(int idJoueur) {
    this.idJoueur = idJoueur;
}

public String getMdp() {
    return this.mdp;
}

public void setMdp(String mdp) {
    this.mdp = mdp;
}

public String getPseudo() {
    return this.pseudo;
}

public void setPseudo(String pseudo) {
    this.pseudo = pseudo;
}

}

Then, Hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.password">********</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/bgwpf</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
    <mapping class="entity.Joueur"/>
</session-factory>
</hibernate-configuration>

And finally the exception :
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
INFO: HHH000412: Hibernate Core {4.1.8.Final}
INFO: HHH000206: hibernate.properties not found
INFO: HHH000021: Bytecode provider name : javassist
INFO: HHH000043: Configuring from resource: hibernate.cfg.xml
INFO: HHH000040: Configuration resource: hibernate.cfg.xml
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
INFO: HHH000041: Configured SessionFactory: null
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
INFO: HHH000115: Hibernate connection pool size: 20
INFO: HHH000006: Autocommit mode: false
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/bgwpf]
INFO: HHH000046: Connection properties: {user=root, password=****}

INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLInnoDBDialect
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
INFO: HHH000397: Using ASTQueryTranslatorFactory

    WARNING: A system exception occurred during an invocation on EJB Login method public boolean session.Login.confirmerLogin(java.lang.String,java.lang.String)
javax.ejb.EJBException
at com.sun.ejb.containers.BaseContainer.processSystemException(BaseContainer.java:5119)
at com.sun.ejb.containers.BaseContainer.completeNewTx(BaseContainer.java:5017)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4805)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2004)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1955)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:198)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:84)
at $Proxy98.confirmerLogin(Unknown Source)
at session.__EJB31_Generated__Login__Intf____Bean__.confirmerLogin(Unknown Source)
at ValiderLogin.doGet(ValiderLogin.java:26)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:734)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1523)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:188)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:641)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:97)
at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:85)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:185)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:325)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:226)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:165)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:791)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:693)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:954)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:170)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:135)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:102)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:88)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:53)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57)
at com.sun.grizzly.ContextTask.run(ContextTask.java:69)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309)
at java.lang.Thread.run(Thread.java:722)

Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: Joueur is not mapped [From Joueur where pseudo ='']
at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:180)
at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:110)
at org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:93)
at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:324)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3291)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3180)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:706)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:562)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:299)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:247)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:248)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:183)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:105)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:168)
at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:221)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:199)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1735)
at session.Login.confirmerLogin(Login.java:22)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1056)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1128)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:5292)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:615)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:797)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:567)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doAround(SystemInterceptorProxy.java:157)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:139)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:858)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:797)
at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:367)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:5264)
at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:5252)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:190)
... 30 more

By the way, don't mind the comparison with an empty string (where pseudo =''), I get the same error with a not-null value.
I don't think there's other files involved but I will post anything else you could need.
Thanks in advance for your help!

A: The exception QuerySyntaxException is thrown when there is syntax error in SQL query. While using HQL you always have to use Classname instead of tablename. Also HQL queries are mostly case insensitive except for Java class names and properties.
HQL Documentation: link

With the exception of names of Java classes and properties, queries
  are case-insensitive. So SeLeCT is the same as sELEct is the same as
  SELECT, but org.hibernate.eg.FOO and org.hibernate.eg.Foo are
  different, as are foo.barSet and foo.BARSET.

But in your case you seem to be using correct case. Could you modify the query as below and check?
  public boolean confirmerLogin(String pseudo, String mdp){
        Session s = HibernateUtils.getSession();
        Query q = s.createQuery("from Joueur j where j.pseudo=:pseudo");
        q.setParameter("pseudo", pseudo);
        if(q.list().size()>=1)
        return true;
        else
        return false;
    }

Let me know if that works.

A: Ok, I did some tests and researches and here is what I found :
First, the DTD : I thought the version of the DTD could be the same as the version of Hibernate, but it isn't the case. The last version of the DTD is currently 3.0. The last modifications done on the DTD can be found in the Hibernate Migration Guide 3.6.
My DTD version being 3.0, my problem doesn't come from it.
Then I compared the declarations in hbm.xml file auto-generated by Eclipse with the annotations I have on my entity (Joueur.java).
I missed almost half of them, but they were all optional. I had high hopes when I noticed that I had forgotten the annotation Table(name=""), but it didn't do the trick either...
I have no clue for further researches, plus I already found the answer to my problem, even if it means using xml files instead of annotations which I prefer. I'll assume GlassFish doesn't handle annotations regarding Hibernate entities yet...
So I'm going to tag my question as answered, but if by chance anyone has a solution, please let me now!
Thank you Satya and Viral Patel for your suggestions!


text:
Q: I've exercised for two months Some native speakers think this sentence is wrong:

I've exercised for two months.

They say it's wrong because it means I've been exercising 24*7 nonstop for two months.
This reason, however, doesn't convince me completely.
Another similar sentence

I've worked for two months.

doesn't mean I've been working 24*7 nonstop for two months.
So, what's the real problem with it?

A: If someone says "I've exercised for two months" I understand it to mean the person started exercising two months ago and is still doing it, but not 24/7, because that would be impossible, wouldn't it. You need to sleep, eat, etc. The same applies to "I've worked for two months." I've worked/been working at my current job for three years, that doesn't mean 24/7, it means I began working there in 2019 and I still work there.

A: Context is always important.
These "native speakers" are wrong.  "I've exercised for two months." would not mean without a break, but rather that you had been doing regular exercise.
I would actually be more likely to use "I've been exercising", as one use of the continuous aspect is to refer to repeated actions.  Naturally, there would be some context:

You're running well!
Yeah, I've been exercising for two months now, and it's really made a difference.
What kind of exercises do you do?
...


text:
Q: Why paths of length return 0 using Pytorch? This function return error which is same as below while the paths is correct. Am I misunderstanding how paths works? (This snippet is from github-repo)
paths = paths[::skip_frame]

ValueError: slice step cannot be zero

Here is the main function:
 def make_gif(paths, gif_path, max_frame=50, prefix=""):
      import imagei

paths.sort()
skip_frame = len(paths) // max_frame

paths = paths[::skip_frame]

images = [imageio.imread(path) for path in paths]
max_h, max_w, max_c = np.max(
        np.array([image.shape for image in images]), 0)

Here is how function called:
parser = argparse.ArgumentParser()
parser.add_argument("--model_name", type=str)
parser.add_argument("--max_frame", type=int, default=50)
parser.add_argument("--output", type=str, default="sampe.gif")
parser.add_argument("--title", type=str, default="")

if __name__ == "__main__":
    args = parser.parse_args()

    paths = glob(f"./logs/{args.model_name}/networks/*.png")

    make_gif(paths, args.output,
            max_frame=args.max_frame,
            prefix=f"{args.title}\n" if args.title else "")

A: You get this error because your skip_frame is zero. Make sure it's value is at least one.


text:
Q: When I use mplot3D, why get error: NameError: name 'plot_trisurf' is not defined I try to use mplot3D to draw some 3D pictures:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
...
plot_trisurf(X, Y, Z1)

Then my computer will tell me that
NameError: name 'plot_trisurf' is not defined

Why this happen?  I thought I have imported it already.

A: plot_trisurf is a method from the Axes3D class. In python, in order to call a class method, you usually need to provide the class or an instance of it.
In this case the class instance would be your axes object. This is usually called ax. The correct call would therefore be (as seen on the matplotlib trisurf example):
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = fig.gca(projection='3d')
...
ax.plot_trisurf(x, y, z)
plt.show()