Permissions for thumbnailer on device

Question: I'm developing an application for U-Touch that gets a thumbnail from a video in C++ code using libthumbnailer system library. The app does the thumbnailing perfectly in my computer, but when i try to execute that part in a device i get
(vs-thumb:5759): GLib-ERROR **: /build/buildd/glib2.0-2.41.5/./glib/gmem.c:353: overflow allocating 4294967274*8 bytes

terminate called after throwing an instance of 'std::runtime_error'
  what():  Unknown error when trying to extract video screenshot, return value was 133.
If i enter with adb shell and i try to do it by hand:
/usr/lib/arm-linux-/gnueabihf/thumbnailer/vs-thumb video.mp4 thumb.jpg

i get the error:
Error creating thumbnail: Failed to preroll.

But if i execute same console operation as su it works. So i suspect is something about the application permissions. Does anybody knows how should i configure apparmor (or any other stuff that i need) for having permissions  to execute this thumbnailer as root?
Thanks in advance
Answer: You could try to run your application with the unconfined template.
In your application manifest file you should have the following lines:
"hooks": {
    "myapp": {
        "apparmor": "myapp.json",
        "desktop": "myapp.desktop"
    }
},

Then in the myapp.json apparmor profile, use the following snippet:
{
    "policy_groups": [],
    "policy_version": 1.2,
    "template": "unconfined"
}

See: Application Confinement
Comment: Tank you very much. That worked perfectly for me with unconfined template. I have some doubts about that parameter since not sure if i will be able to use it in production environments. Anyway, that is the reason of the failure and I'm happy this works that way!
Answer: I finally found a better solution than using the unconfined template. It was easier than expected... only needed to include "video" as part of the policy group:
    "policy_groups": [
        ...
        "networking",
        "video",
        ...
    ]

If, aditionally, you need to access video files, you can also add "video_files_read" (only read video file) or "video_files" (complete access).
You can check all the available policy groups when developing an app in Ubuntu Sdk, into QtCreator, going to Publish tab and double click on app.apparmor file. You'll find a + symbol which will show you all the policies when clicked. You can find more information at http://developer.ubuntu.com/publish/apps/packaging-click-apps/

Permissions for thumbnailer on device


Receiving "Deployment Role Instances Not In Started State After 30 seconds" Azure PHP

Question: I keep receiving this message when trying to deploy a test php application into my Azure Emulator

<code>Using session id 1
Warning : Remapping public port 80 to 81 to avoid conflict during emulation.
Warning : Remapping private port 80 to 82 in role 'PhpOnAzure.Web' to avoid conf
lict during emulation.
Created: deployment16(6)
Deployment role instances not in "Started" state after 30 seconds.
Exported interface at http://127.0.0.1:81/.
C:\temp\WindowsAzurePHPApp\build/WindowsAzurePHPApp.cspkg
C:\Users\Manu>
</code>

I followed some troubleshooting off the "Building and deploying a PHP Application on Azure" tutorial (Checked CGI, also activated PHP) and didn't anywhere. Anyone else come across the same problem? My output from this code is a blank page in firefox that says connection timed out.
Answer: Do you have any other web server software running, such as Apache? IIS need control in order to function properly. The connection issue in Firefox makes me think maybe IIS is being blocked or not starting. Another possibility to look for, sometimes IIS gets confused with PHP and adds two of them to the list of modules. Check that as well


My Ajax php code not working correctly

Question: I have a code like this
ajax.js
var xmlHttp = buatObjekXmlHttp();

function buatObjekXmlHttp()
{
var obj = null;
if(window.ActiveXObject)
    obj = new ActiveXObject("Microsoft.XMLHTTP");
else
    if(window.XMLHttpRequest)
        obj = new XMLHttpRequest();
if(obj == null)
    document.write("Browser tidak mendukung XMLHttpRequest");
return obj;
}

function ambilData(sumber_data, id_elemen)
{
if(xmlHttp != null)
{
    var obj = document.getElementById(id_elemen);
    xmlHttp.open("GET", sumber_data);

    xmlHttp.onreadystatechange = function()
    {
        if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
            obj.innerHTML = xmlHttp.responseText;
    }
}
xmlHttp.send(null);
}

cekpass.php
<!DOCTYPE HTML>

    <title>
        Memeriksa Password
    </title>

    <form>
        User ID : <input type="text" name="textuser_id" id="user_id">

        Password : <input type="password" name="textpassword" id="password">

        <input value="Login" type="button" onclick="prosesData('password.php', 'id_info');">
    </form>

And this
password.php
<?php
header("Cache-Control : no-cache, must-revalidates");
header("Expires : Mon, 26 Jul 1997 00:00:00 GMT");

//Data user-id dan password
$user[] = "anton"; $pass[] = "biola";
$user[] = "ahmad"; $pass[] = "gitar";
$user[] = "dewi"; $pass[] = "piano";
$user[] = "santi"; $pass[] = "keyboard";
$user[] = "salman"; $pass[] = "perkusi";

//Peroleh variable URL
$user_id = $_GET["user_id"];
$password = $_GET["password"];

$ok = FALSE;
for($i=0; $i < count($user); $i++)
{
    if(($user_id == $user[$i]) && ($password == $pass[$i]))
    {
        $ok = TRUE;
        break;
    }
}

session_start(); //Buat sesi
$_SESSION["ok"] = $ok;

if($ok)
{
    $_SESSION["user_id"] = $user_id;
    $_SESSION["password"] = $password;
    print("OK");
}
else
    print("NOT OK");
?>

I want to make simple login using ajax with javascript, not with database but with array, if it's correct, it will link to another page, but the problem is, when i put correct answer it always said i'm wrong :( can someone tell me what went wrong with my code :( I'm still new :(
Answer: Your url is malformed. Remove unnecessary spaces by changing
var url = sumber_data + "?user_id = " + elemen_user_id.value + "&password = " + elemen_password.value;
to
var url = sumber_data + "?user_id=" + elemen_user_id.value + "&password=" + elemen_password.value;
Comment: Ma god, so it just because of space O.O thnx you very much for the help :)
Answer: Rather than go into possible solutions to yur matching array index problem, I'm just going to show you a solution that wil work.
<?php
header("Cache-Control : no-cache, must-revalidates");
header("Expires : Mon, 26 Jul 1997 00:00:00 GMT");

//Data user-id dan password
$user["anton"] = "biola";
$user["ahmad"] = "gitar";
$user["dewi"] = "piano";
$user["santi"] = "keyboard";
$user["salman"] = "perkusi";

//Peroleh variable URL
$user_id = $_GET["user_id"];
$password = $_GET["password"];

$ok = FALSE;
if($user[$user_id] === $password){
    $ok = TRUE;
}

session_start(); //Buat sesi
$_SESSION["ok"] = $ok;

if($ok)
{
    $_SESSION["user_id"] = $user_id;
    $_SESSION["password"] = $password;
    print("OK");
}
else
    print("NOT OK");
?>

This is no more insecure than your existing method and it works.
Comment: It's working too, and more short, thnx a lot :) but i can only thumb up, can't checklist more than 1 answerr, sorry :( but thnx very much for the help and insight to the new method, it's great :)

My Ajax php code not working correctly


How can I improve the performance of HDF5 reading data?

Question: What I need is to get the unique date value as soon as possible.
I use the code df = store.df.date.drop_duplicates() to retrieve. This line of code takes 6 seconds. However, if I use mysql and save the same data to mysql, I use mysql for the date column After indexing, using sql:select distinct date from table, it only takes 80ms to retrieve the unique date value, which is 60 times faster than HDF5.
Is there any way to make the function read_unique_date read HDF5 faster than MySQL uses indexes?
My code is as follows:
import pandas as pd
import numpy as np
from itertools import product
from time import time

def generate_data():
    np.random.seed(202108)

    # date = pd.date_range(start="19900101", end="20210723", freq="D")
    #The above is my original code, you can use the following code to speed up the operation.
    date = pd.date_range(start="20210101", end="20210723", freq="D")
    date = pd.DataFrame(date, columns=["date"])

    # code = pd.DataFrame(range(5000), columns=["code"])
    #The above is my original code, you can use the following code to speed up the operation.
    code = pd.DataFrame(range(50), columns=["code"])

    # generate product of the two columns:
    df = pd.DataFrame(product(date["date"], code["code"]), columns=["date", "code"])
    df['data'] = np.random.random(len(df))
    return df

def save_data(filename, df):
    store = pd.HDFStore(filename)
    store['df'] = df
    store.close()
    return

def read_unique_date(file_name):
    store = pd.HDFStore(file_name)
    start = time()
    df = store.df.date.drop_duplicates()
    store.close()
    stop = time()
    print(stop - start)
    return df

def main():
    path = 'd:\\'
    file = 'large data.h5'
    file_name = path + file
    df = generate_data()
    save_data(file_name, df)
    df1 = read_unique_date(file_name)
    print(df1)
    return df1

if __name__ == '__main__':
    main()

The result is:
0.015624761581420898
0       2021-01-01
50      2021-01-02
100     2021-01-03
150     2021-01-04
200     2021-01-05
           ...
9950    2021-07-19
10000   2021-07-20
10050   2021-07-21
10100   2021-07-22
10150   2021-07-23
Name: date, Length: 204, dtype: datetime64[ns]

%timeit df1 = read_unique_date(file_name)
16.9 ms ± 200 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

The result of my original code:
%timeit df1 = read_unique_date(file_name)
4.89 s ± 119 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Answer: The short answer is that HDF5 simply does not have indexes apart from the keys to datasets (dataset names) and contiguous array indices. So the only lookup operations directly from a file that you can expect to perform sublinearly is retrieving the Nth value in an dataset. To find unique values directly from a file HDF5 has to read the whole file. You might be able to cook up something messy but functional with HDF5 groups and references but then you're just implementing indexing yourself and I don't advise going that route.
On the otherhand Pandas uses hashtables, trees and binary search to speed up various lookup operations. You could load the data into a dataframe for the queries. But generally you want to move to a proper database at some point. Pandas and HDF5 can only take you so far.
Comment: Thank you for your answer, it seems that I need to choose another database such as MongoDB.
Answer: pandas has a method named read_hdf documented here. You can simply read your stored .h5 saying:
read_df = pd.read_hdf('./large data.h5')

and you can access read_df as a pandas data frame.
Now if you'd ask me, it would not be a great idea to store a file and read it again for periodical loop use. I'd keep the data in the form of a data frame and write it only when necessary (i.e. I need the space in the memory or I need to update the database with some shared access). I would say strategizing the write and read should be considered to optimize the code run.
btw, your code crashed my debug at:
    df = pd.DataFrame(product(date["date"], code["code"]), columns=["date", "code"])

you might want to look into it again.
Comment: The data generated by generate_data() is about the same size as my real data, and these codes can run normally in my debug environment. My usage scenario is to write data once and read it many times. Therefore, your usage scenario is different from mine.
Answer: Your code is running as-is so it is difficult to tell what you are trying to get at here without an example of the output you desire. Your nearly 1.8 GB of data that is generated by this code is not relevant to your issue unless I am missing something and this is really a performance related question. If the following does not solve your issue, I recommend you significantly pare down your generated data and provide an example of the desired output so people can help you without having to assume what you are trying to get to.
Taking a guess as to what you are wanting, I think the issue lies in how you are eliminating duplicates. You are dropping duplicates from the series of dates contained within the dataframe setting df equal to this pared down series. Instead, I believe what you want is to drop duplicates from the dataframe using df.drop_duplicates() and specifying the date column as the subset.
Example: df.drop_duplicates(subset="date").
Does this solve your issue?
Comment: I modified my code. What I need is to use `HDF5` like `mysql` to make the speed `60 times` faster than the current `df = store.df.date.drop_duplicates()`.
Comment: I think your edits will help to draw out the solution if one exists. It could just be a performance difference between the two. I'm unfamiliar with SQL and how it works and have not really gotten deep into fine tuning performance in my tinkering. Sorry I can't be of more assistance.
Comment: Anyway, Thanks at all.


Nilpotent thickenings flat over the base

Question: Let $R$ be a Noetherian commutative ring, $A$ a flat $R$-algebra of finite type, $I\subset A$ an ideal such that $A/I$ is $R$-flat.

For $n\ge 1$, is $A/I^n$ also $R$-flat?

In a similar vein, suppose $M$ is a finite $A$-module which is $R$-flat and consider the annihilator ideal $\text{Ann}_A(M)$ of $M$ in $A$.

Is $A/\text{Ann}_A(M)$ flat over $R$?
Answer: The answer to your first question is negative. Take $R=\mathbb{Z}$, consider $J=(2x,x^2)\subseteq\mathbb{Z}[x]$ and $A=\mathbb{Z}[x]/J$. Lastly, let $I=(x+J)\subseteq A$. Then $A/I\cong\mathbb{Z}$ is flat over $\mathbb{Z}$, but as $I^2=0$ we have $A/I^2\cong A$, which isn't flat, as it is isomorphic to $\mathbb{Z}\oplus(\mathbb{Z}/2\mathbb{Z})$ as a $\mathbb{Z}$-module.


Initial value of a Core Data Entities properties?

Question: I have several core data entities that contains a bunch of empty NSString properties.
I parse some XML and set the properties I can get a hold of and would like to set the "empty" ones to "n/a" as in "not available". So if my XML does not contain the values it sort of tidy up the Entity by giving it a "n/a" string I can test for later on, also should one of these make it to a UILabel it will not display (null) .. which leads me to my question:
I do this to test if the property on the Entity is already sat, is nil or is empty:
    for(NSString *s in allPossibleStrings) {

        if([[f valueForKey:s] isKindOfClass:[NSString class]] && [[f valueForKey:s] isEqualToString:@""]) {
            [f setValue:@"n/a" forKey:s];
        }
        if ([[f valueForKey:s] isKindOfClass:[NSString class]] && [f valueForKey:s] == nil) {
            [f setValue:@"n/a" forKey:s];
        }
    }

It turns out however that I still end up with a lot of values being displayed as (null).
So I was thinking can the property be something else than @"" empty or (nil)
I believe the NSManagedObject should be KVC compliant so I did a test where I copied my NSManagedObject property by property, only difference is that is is a subclass of just NSObject instead of NSManagedObject.
Sadly this behaves in the exact same way. It also leaves values as (null)
Hope someone can pick up on where I go wrong with these string tests :)
Thank You
Comment: `[[f valueForKey:s] isKindOfClass:[NSString class]] && [f valueForKey:s] == nil` This makes no sense. If `[f valueForKey:s]` is `nil`, then the first message is a message to `nil`, so it will simply return `NO` (see http://developer.apple.com/mac/library/documentation/cocoa/conceptual/ObjectiveC/Articles/ocObjectsClasses.html#//apple_ref/doc/uid/TP30001163-CH11-SW7 ). That makes the entire expression false, so the statement that this condition controls will never execute.
Comment: Hi Peter. Yes! of course:) If I combine Your answer and Kendalls answer it should be: "if object isKindOfClass:NSString && isEqualToString @""...set it to @"n/a" or if object is kindOfClass:NSNull set it to @"n/a". This gives me some knowledge I can use in the future. Thanks you both.
Answer: You could set the default property value of your entity to "N/A" (that's a good practice, because you might want to use sqlite for iPhone app shipping, and it doesn't work well with null values because sqlite and cocoa don't have the same vision of "null") and set "optional" to "No".
 if([[f valueForKey:s] isKindOfClass:[NSString class]] && [[f valueForKey:s] isEqualToString:@"NA"]) {
       //Tell your program to know that it's null if it needs to know
    }

Cheers
Comment: Hi Julien. Thank you. I guess I could remove the issue completely by doing that:)
Answer: What is allPossibleStrings? You could do this to get to all the properties:
NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyEntityName" inManagedObjectContext:moc];

for (NSString *attr in [entity attributesByName]) {
    [object setValue:@"n/a" forKey:attr];
}

Comment: Hi Jaanus. Thank you. It is a list of the properties I am "allowed" to change. There are values in there that must not be overwritten or changed, so I keep an array of strings for the values I can change in a category.
Answer: The issue is that when something is nil, what you can get back from any managed object property (not just strings) is an NSNull object.  So if you check also for isKindOfClass:[NSNull class] I think your code will do what you want.


Who would one hire to make a cabinet door that matches existing cabinets?

Question: Who would one hire to make a cabinet door that matches existing cabinets?
Is this even plausible, something a carpenter or cabinet maker would entertain?
I bought some nice cabs from a relatively big name brand, but I need doors for a framed-in area and I would like these door to match in style and paint.
Is this possible and if paint matching is a pain, is it reasonable to ask the manufacturer for paint specification (they're big, but contactable and responsive, but sadly do not do custom sized doors)?
Answer: Carpenters don't usually do custom cabinetry--it requires a special skillset and some specialized tools. Some do, of course, and if you find a high-caliber handyperson he or she could probably get the job done.
A better bet is probably a local custom cabinet shop. They'll have the tooling required to match your design, edge profile, etc., and they'll be more likely to have the products on hand to create the wood finish to match your existing. They're also likely to be more expensive than the handyperson due to overhead costs.
Certainly ask your cabinet seller what they can tell you about finish products. A good cabinet shop won't need it, but it's probably helpful to have anyway. Otherwise just leave one of your doors with the shop while they do your project.
Answer: You can usually buy replacement doors either from the manufacturer (if they have direct-to-public sales) or through one of their distributors. The upside is that it will be a perfect match, the downside is the usually high cost. You'll need to know who made the cabinets which isn't always an easy thing to find out. I've replicated doors on several occasions but it's not something most guys want to fool with due to the various bits, tools, and templates you might need. Not so bad for simpler doors, a real bugger on complex ones. Only for no-longer-available designs or where there's no time to source a new one; buy new if you can.
Phil
Phil


Difference between from .. import and from . import

Question: What is the difference between these imports in Python and when would you use these? How many dots "." can we use?
from something import this
from .. import this
from . import this

Comment: (one dot)`.` is from current directory and (two dots)`..` from upper directory
Comment: If you importing from another file in the module, then you use the `.` and `..` to indicate relative directory. You could also do `from ../../.. import something`
Comment: Please see the documentation: https://docs.python.org/3/reference/import.html#package-relative-imports
Answer: Explanation
Imagine we have the following structure:
| my_package
| __init__.py
|___ inner_package
    | __init__.py
    | foo.py
    | bar.py
    |___ even_more_inner_package
        | inner_foo.py
        |___ __init__.py
| main.py

The first from something import this imports from the top application package, meaning that if we wanted to import something from inner_package anywhere in our files, we would have to do it like this:
from my_package.inner_package import foo

The second and the third import statements are also known as relative imports, which works exactly as folders:
The second statement from .. import something means "From the upper package, import something". Imagine that we are inside inner_foo.py, which is inside my_package.inner_package.even_more_inner_package, we can do the following to import bar.py:
# This statement goes one package up and looks for bar
from .. import bar

The final from . import something statements means "From this current package, import something". If we were writing the code from bar.py and wanted to import foo.py we could use:
from . import foo

Note
You cannot use relative import from .. on the top level package. In this example, executing from .. import my_package inside main.py  will raise an ImportError.
Comment: Thank you! Do you think it is better than defining an absolute path?
Comment: It would recommend it, but I personally like the absolutes paths whenever possible though, because I think it is more visual to see the entire packages than just dots everywhere, but its just my  opinion.
Answer: This is called relative imports. A relative import specifies the resource to be imported relative to the current location—that is, the location where the import statement is.
A single dot means that the module or package referenced is in the same directory as the current location. Two dots mean that it is in the parent directory of the current location—that is, the directory above. Three dots mean that it is in the grandparent directory, and so on.
Assume:
└── project
    ├── package1
    │   ├── module1.py
    │   └── module2.py
    └── package2
        ├── __init__.py
        ├── module3.py
        ├── module4.py
        └── subpackage1
            └── module5.py

Assume file contents:
package1/module2.py contains a function, function1.

package2/__init__.py contains a class, class1.

package2/subpackage1/module5.py contains a function, function2.

You can import function1 into the package1/module1.py file this way:
from .module2 import function1

You can import class1 and function2 into the package2/module3.py file this way:
from . import class1
from .subpackage1.module5 import function2

A good source: Absolute vs Relative imports


Why does calling to_json output javascript that is filled with

Question: In my controller action I am doing:
@user = user.to_json

Then in my view I am doing:

And the resulting html is like:
[{"user":{"age":8,....

Why does it contain " everywhere?
In irb it outputs just fine like:
[{\"user\":{\"age\":8,...

Answer: In Rails 3 all output in the views is escaped by default. You used to have to call h(..) to escape stuff.
You can tell Rails that really what you are outputting is safe and rails doesn't need to worry about it by calling html_safe:

The reason for this is this data often comes from your users (people post forms for example), and they can include malicious stuff that you would then output, leading to XSS attacks and the like. Rails 3 took a (somewhat controversial) approach of being extra cautious here.
Here is a good blog post from Yehuda about html_safe and what's really going on
Answer: Try the raw method?
<%= raw @user %>


Finite-state Machines: Number of Possible Answers

Question: I'm wondering if there is an equation that gives the number of possible configurations of any given finite-state machine built to handle n inputs and m states.
How many possible solutions are there to any given process when using a finite-state machine to describe it?
I'm asking because I have a problem to solve using finite-state machines and I want to know if there is only one possible solution or many.
[Problem]
Build a finite state machine that produces an output of 1 if the input X, which can take the value 0 or 1, was 101 over the last three clock cycles.  X is updated each clock cycle.  There are four possible states S0, S1, S2, and S3.
Answer: The number of configurations in a FSM is the number of states. It has no memory or context to differentiate being-in-state-X-now from being-in-state-X-then.
Are you talking about the potential paths through the states? i.e. the output sequence it emits as it transitions or, equivalently, the inputs which result in a termination state? These are potentially infinite, depending on the machine.
FSMs are very, very simple. If you're not sure whether you can use them, perhaps you don't have a clear description of the problem.
What is the actual problem?
Comment: If this is homework, please tag it as such. There are four states, as you said. The answer to your questions is: how many graphs can be drawn with 4 vertices? There are 4*4 directed pairs so there are 2^(4*4) possible machines.
Comment: I posted the problem above.

I'm just curious to know how many possible maps can be drawn to describe the finite state machine.  Infinite, one, or some number in between?
Comment: Ah, I see. I should have applied graph theory.  Thanks.


Jenkinsfile conditions in Stage phase

Question: should it possible to define several conditions in a Stage phase of Jenkins file??
Let me to explain my problem: I want to publishHtml in my Jenkins pipeline only if a condition is valid:
        stage(Documentation)
       {
        agent any
        steps
        {
         sh"./documents.sh "     //This generate the documentation of several modules

         if(firstModule) { //Is it possible to publishHTML only if documentation of this module was generated???

             publishHTML (target: [
              allowMissing: false,
              alwaysLinkToLastBuild: false,
              keepAll: true,
              reportDir: "${env.WORKSPACE}/firstModule//html",
              reportFiles: 'index.html',
              reportName: "Fist Module Documentation"
            ])

         }

         if(secondModule) { //Is it possible to publishHTML only if documentation of this module was generated???
         publishHTML (target: [
              allowMissing: false,
              alwaysLinkToLastBuild: false,
              keepAll: true,
              reportDir: "${env.WORKSPACE}/secondModule/html",
              reportFiles: 'index.html',
              reportName: "Second Modul Documentation"
            ])
         }
     }

I don't know if firstModule was built or not... this is what I would like to know.
I don't want to create different stages, but just one "Documentation" visible in the jenkins view.
Thank for your suggestion.
Prisco
Answer: it sounds like you want to publish documentation for firstModule only if "${env.WORKSPACE}/firstModule/html/index.html exists.
instead of:
if(firstModule) {

try:
script {
   if (fileExists("${env.WORKSPACE}/firstModule/html/index.html")) {
     # publishHTML and whatnot
   }
}

Jenkinsfile conditions in Stage phase


problems with calling server socket accept method with an infinite timeout

Question: I created a server socket on my side. I don't know when client connects to me.
Calling a serverSocket.accept() in my application without setting any socket timeout would solve my problem of accepting the client at any point of time. I am doing this in a separate thread, so this wouldn't block another part of my application.
My concern is since accept() blocks till it gets a call from a client wouldn't this consume any resources, may be like if I don't get a call from the client side program for about a week.
Is there any other way of accepting the client side connection. I don't have any information on when client calls for a socket connection, except that it calls at some point.
Answer: There is no problem with calling accept on a different thread. The thread will be blocked in the call to accept and will not be scheduled by the operating system until a connection in inbound. Practically, if you don't get a connection the entire week your thread will not run on the CPU during this time.
Therefore, it will not consume any CPU resources and only a bit of memory.
Comment: 'But how will the JVM know there is a connection inbound' - because accept() returns. 'may be internally some other thread within the JVM should be constantly hitting the socket to see if there are any inbound connections' - not on any OS I have ever used.  The thread that called accept() is made ready by a signal from a kernel thread running the TCP stack. The kernel threads are, in turn, made ready by signals from the NIC driver and so, originally, from a hardware interrupt.  No polling.  Like @Tudor says - if nothing tries to connect, nothing will be happening.
Comment: or so we hope ;) It depends on the JVM implementation and perhaps OS (for scheduling). I agree with your post Tudor.
Comment: But how will the JVM know there is a connection inbound, may be internally some other thread within the JVM should be constantly hitting the socket to see if there are any inbound connections which might consume resources


In Need For Speed: World, is there any gameplay difference between the Lustra, React and Glint packages?

Question: NFS:W, after you painstakingly reach level 5, offers you a whooping choice of three performance upgrade packs: Lustra, React and Glint.
As much as I'd rather get a new ride -- something that was far easier in NFS:MW -- I'll have to consider getting a package instead (mainly for pursuit purposes).
Which one exactly? Is there any gameplay difference at all? They all cost the same and all upgrade car stats by the same -- this fake choice kind of puzzles me.
Comment: This really annoys me too; as far as I can tell the differences are just cosmetic, but I have no way to be sure.  Fortunately, they're bringing "slot-based performance customization" in a future update: http://www.needforspeed.com/post/new-roads-rides-and-modes-coming-need-speed-world?cat=44
Comment: Obviously I can't get a new car because I didn't pay the $20 to unlock levels 11-50...
Answer: ZoogieZork's comment and the offical blog post seem to imply that no, there is no gameplay difference indeed. Not yet, anyway.


Preserve order of attributes when modifying with minidom

Question: Is there a way I can preserve the original order of attributes when processing XML with minidom?
Say I have: <color red="255" green="255" blue="233" />
when I modify this with minidom the attributes are rearranged alphabetically blue, green, and red. I'd like to preserve the original order.
I am processing the file by looping through the elements returned by elements = doc.getElementsByTagName('color') and then I do assignments like this e.attributes["red"].value = "233".
Answer: To keep the attribute order I made this slight modification in minidom:
from collections import OrderedDict

In the Element class :
__init__(...)
    self._attrs = OrderedDict()
    #self._attrs = {}
writexml(...)
    #a_names.sort()

Now this will only work with Python 2.7+
And I'm not sure if it actually works => Use at your own risks...
And please note that you should not rely on attribute order:
Note that the order of attribute specifications in a start-tag or empty-element tag is not significant.
Comment: Still works on Python 3.2, replace  `a_names = sorted(attrs.keys())` by `a_names = attrs.keys()`
Comment: How did you modify the Element class?
Answer:
Is there a way I can preserve the original order of attributes when processing XML with minidom?

With minidom no, the datatype used to store attributes is an unordered dictionary. pxdom can do it, though it is considerably slower.
Answer: It is clear that xml attribute are not ordered.
I just have found this strange behavior !
It seems that this related to a sort added in xml.dom.minidom.Element.writexml function !!
class Element(Node):
... snip ...

    def writexml(self, writer, indent="", addindent="", newl=""):
        # indent = current indentation
        # addindent = indentation to add to higher levels
        # newl = newline string
        writer.write(indent+"<" + self.tagName)

        attrs = self._get_attributes()
        a_names = attrs.keys()
        a_names.sort()
--------^^^^^^^^^^^^^^
        for a_name in a_names:
            writer.write(" %s=\"" % a_name)
            _write_data(writer, attrs[a_name].value)
            writer.write("\"")

Removing the line restore a behavior which keep the order of the original document.
It is a good idea when you have to check with diff tools that there is not a mistake in your code.
Answer: Before Python 2.7, I used following hotpatching:
class _MinidomHooker(object):
    def __enter__(self):
        minidom.NamedNodeMap.keys_orig = minidom.NamedNodeMap.keys
        minidom.NamedNodeMap.keys = self._NamedNodeMap_keys_hook
        return self

    def __exit__(self, *args):
        minidom.NamedNodeMap.keys = minidom.NamedNodeMap.keys_orig
        del minidom.NamedNodeMap.keys_orig

    @staticmethod
    def _NamedNodeMap_keys_hook(node_map):
        class OrderPreservingList(list):
            def sort(self):
                pass
        return OrderPreservingList(node_map.keys_orig())

Used this way:
with _MinidomHooker():
    document.writexml(...)

Disclaimer:

thou shall not rely on the order of attributes.
mutating the NamedNodeMap class is not thread safe.
hotpatching is evil.
Answer: You guys can put up as many disclaimers you want.
While reordering the attributes has no meaning for the program it does have a meaning for the programmer/user.
For Fredrick it was important to have the RGB order since that is how the order of the colors is.
For me it is the name attribute in particular.
Compare
<field name="url" type="string" indexed="true" stored="true" required="true" multiValued="false"/>
<field name="forkortelse" type="string" indexed="true" stored="true" required="false" multiValued="false" />
<field name="kortform" type="text_general" indexed="true" stored="true" required="false" multiValued="false" />
<field name="dato" type="date" indexed="true" stored="true" required="false" multiValued="false" />
<field name="nummer" type="int" indexed="true" stored="true" required="false" multiValued="false" />
<field name="kilde" type="string" indexed="true" stored="true" required="false" multiValued="false" />
<field name="tittel" type="text_general" indexed="true" stored="true" multiValued="true"/>

Against
<field indexed="true" multiValued="false" name="forkortelse" required="false" stored="true" type="string"/>
<field indexed="true" multiValued="false" name="kortform" required="false" stored="true" type="text_general"/>
<field indexed="true" multiValued="false" name="dato" required="false" stored="true" type="date"/>
<field indexed="true" multiValued="false" name="nummer" required="false" stored="true" type="int"/>
<field indexed="true" multiValued="false" name="kilde" required="false" stored="true" type="string"/>
<field an_optional_attr="OMG!" an_optional_attr2="OMG!!" indexed="true" name="tittel" stored="true" type="text_general"/>

While it is not impossible to read it is not as easy. The name is the important attribute. Hiding the name field way back is no good. What if the name was 15 attributes to the left where 7 of the attributes in front was optional?
The point is that the reordering is a bigger problem than what the acsending ordering gives in return. It messes with the way the programmer thinks or how the functionality is supposed to work. At least the ordering should be configurable/optional.
Excuse my poor english. It is not my main language.
Comment: What you are saying here is not unreasonable. But it is not an answer to the question.
Comment: i don't understand
Comment: I totally agree with what you are saying, but this should really be a comment, even though it is too large for one.
Answer: 1.Custom your own 'Element.writexml' method.
from 'minidom.py' copy Element's writexml code to your own file.
rename it to writexml_nosort,
delete 'a_names.sort()' (python 2.7)
or change 'a_names = sorted(attrs.keys())' to 'a_names = attrs.keys()'(python 3.4)
change the Element's method to your own:
minidom.Element.writexml = writexml_nosort;
2.custom your favorite order:
right_order = ['a', 'b', 'c', 'a1', 'b1']
3.adjust your element 's _attrs
node._attrs = OrderedDict( [(k,node._attrs[k]) for k in right_order ]  )
Answer: The attributes are ordered in minidom while writing with writexlm function in class Element.
It is done like this:
a-name = sorted(attrs.keys())

You can change this to
a-name = list(attrs.keys())

For Idle I had to change the file in
/usr/lib/python3.6/xml/dom. It seems that Idle does not follow the sys.path order.
Don't forget to make a back-up first.
Answer:
Is there a way I can preserve the original order of attributes when processing XML with
  minidom?

Yes. From Python 3.8, the original attribute order is preserved when serializing the XML document.
See https://docs.python.org/3/library/xml.dom.minidom.html#xml.dom.minidom.Node.writexml.
Answer: I've ended up using the lxml library instead of minidom.


How do I click a usercontrols child in designer?

Question: I'm having a bit of trouble with creating one of my custom controls.
What I've got is a listbox within a usercontrol, and I need to be able to click on the lists items while still in the designer. This would make it act much like the tabcontrol.
I haven't dealt much with usercontrols but I've tried catching some overide events without success.
    protected override void OnClick(EventArgs e)
    {
        if (DesignMode)
        {
            InvokeOnClick(listBox1, e);
        }
        base.OnClick(e);
    }

I haven't been able to find anything on the web.. Any ideas on how I can do this?
Thanks in advance =)
Comment: I assume you're talking about WinForms, but you might want to clarify. I'm having a hard time imagining why this would be useful - can you explain why you need this behavior?
Comment: I've created an assistant usercontrol for the tabcontrol that allows you to view tabs and change tabs of the tabcontrol via the list. It uses binding source etc. Much like the options window of Visual Studio.
Answer: @Bradley: thanks for pointing me in the right direction
You will need to write a ControlDesigner class, then use it in a [Designer( ... )] attribute on your UserControl.
See the example here:
http://msdn.microsoft.com/en-us/library/sycctd1z(v=VS.90).aspx
For the actual click:
http://msdn.microsoft.com/en-us/library/system.windows.forms.design.controldesigner.gethittest(v=VS.90).aspx
The ControlDesigner has a protected bool GetHitTest(Point point) method - you can implement this in your ControlDesigner and return true when you want your control to handle a click, based on the click's location on the screen.
Comment: Thanks, that really led me in the right direction! Once I implemented the gethittest I was able to receive click events on all the children on the control. I then used the boolean DesignMode to check if in design mode and got the index of the listitem. Thanks!
Answer: I found this link that says you need to implement a custom designer to get the desired behavior, and explains how to make it happen.
http://social.msdn.microsoft.com/Forums/pl-PL/winforms/thread/0b6ed0cb-907c-4733-b245-ae5d0b0e6606
Comment: Thanks for your help! I could only award winner to one answer, but thanks for pointing sq33G in the right way. I +1'd you to say the least.
Answer: You may be able to get away with catching the MouseDown event in the custom control and forwarding it on to the inner control.  I'm not sure how MouseDown behaves in design mode though.
Comment: Thats kind of what I was attempting to do, but I don't know enough about working with usercontrols to get it to work.


C# Structure that sorts key pairs and is accessible?

Question: Noob here. I've been scouring the internet for days, and cannot find a decent structure that auto-sorts data (like SortedSet), while still allowing that data to be accessible (like List). Here's what I have:
A list containing 100,000 nodes, added and modified regularly.
List<Nodes> nodes;

The node object, containing data I need to access/change
public class Node (string name, int index){ doSomething(); }

I don't wish to be vague, but can't sort the actual list because the index is a history of when nodes were added. Thus, I want to use a structure that auto-sorts KeyValuePair pairs(where string is the name to be sorted by, and int is the index as it is found in my list of nodes), but I must be able to access the value. Here's what I want to do:
// Add a node to the list, then to the structure
int index = nodes.Count;
nodes.Add(new Node("someName", index));
someStructure.Add("someName", index);

// Give name to structure, which returns int value for use in finding node
node[someStructure.findValueOf("someName"))].doSomething();

This would tell the node with the name "someName" to doSomething();
I am positive that I am missing something. I've tried using SortedSet, SortedList, Dictionary, etc. In each case, I can't retrieve the sorted object. What is the purpose of auto-sorting if I can't find out where they are at? Please help my poor life.
Comment: At 100k nodes, you might as well think about using a Database as storage.  That is a lot of data to just store in memory. Much less retrieve every start. And DB queries can usually do all the sorting and filtering you will ever need.
Comment: Yeah and you could use Code First Entity Framework if you don't like mucking about with T-SQL.
Comment: Nodes are actually tiny. One string, one int, and 2 Lists that won't generally exceed 100 or so ints.
Answer: You are looking for a SortedDictionary.
As per the documentation: Represents a collection of key/value pairs that are sorted on the key. Although, as some comments say, those 100k objects would be better kept in a database...
Link: https://msdn.microsoft.com/en-us/library/f7fta44c(v=vs.110).aspx
Comment: Certainly close, but I cannot access the data in the SortedDictionary (I think). I'm looking for a structure with some sort of getValue method, so that I can use a binary search to find the key and return the value. I'm sure there's a way to do this with most structures but I'm blind to it.
Comment: If you need to use the data as a key, then keep two SortedDictionaries ¯\\_(ツ)_/¯
Answer: You can use SortedList and LINQ:
SortedList<int,string> list = new SortedList<int, string>();

list.Add(1, "name1");
list.Add(2, "name2");;

var c = list.Select(x => x.Value == "name2").FirstOrDefault();

However I agree with a Christopher's comment about using db.


How should I connect a furnace fan to a start capacitor?

Question: I have an old squirrel cage that works but capacitor is missing. The motor has 3 wires (red/white/blue). How do I hook this up with a run/start cap?
Comment: If you get this running, I have been told to be sure to load the fan by restricting the inlet orifice. The motor on an unloaded fan will over-speed and overheat. I once ruined the motor on a water fan by running it without the water carrying pad in place.
Answer: You need to determine if the motor actually uses a capacitor. Look on the motor for a picture of the wiring required. The capacitor size is usually shown. The motor you have may be a shaded pole, split phase, or have a capacitor  inside the motor housing. "GOOGLE" the motor number of the motor for more motor information. You may have a 2 speed motor that does not require a capacitor. Then as @Jim Stewart said, make sure you check the motor amperage and restrict the air  inlet so as not to overload the motor. A clamp-on "amprobe" type gadget would be helpful.
Comment: What causes over-current in these motors? If one would *over*load the motor that would cause over-current, right? Does under-loading leading to over-speeding cause damage to the bearings (without over-amperage) or maybe wreck the motor by causing the armature to hit the fixed parts?
Comment: To Jim Stewart; an electric motor can be easily overloaded when used with an impeller that has the capability to move a fluid in excess of what it was designed to move. For example, If a fan blower is removed from the furnace/air-handler the result is usually that the fan will overload since the resistance to flow has been removed; the ducts resistance is no longer present. and the fan will try to move more air than it normally will when a resistance is applied. Thus , the motor will draw more amperage and will usually overload. The same is true if the impeller is moving almost any fluid.
Comment: Ran out of space: Most  unloaded motors can only run at the RPM it was designed to run at, thus at a no load speed the motor runs at it's design speed with no ill effects. I said most motors since there are a lot of pretty smart electricians that would take me "to task " if I said all motors since there are some that will keep increasing speed until they self destruct.


Snap Framework: Custom snaplet handler won't render template

Question: I'm just getting started with writing custom snaplets and hit a road block.  I have the following basic snaplet which has a "roles" template located in the "snaplets/admin-pg/snaplets/heist/templates". Can someone tell me why the handleUsers function does not render the "roles" template?  I get a  "No handler accepted '/pgadmin/users' " error. I'm sure I'm missing something very basic.  Thanks.
My main app is defined as follows.  It is an instance of HasHeist
data App = App
    { _heist :: Snaplet (Heist App)
    , _pgadmin :: Snaplet (Admin App)
    }

My initializtion code for the snaplet in the main App ("Site.hs") is:
h <- nestSnaplet "" heist $ heistInit "templates"
z <- nestSnaplet "pgadmin" pgadmin $ adminPGInit h

Custom snaplet code...
data Admin b = Admin { name :: String}

adminPGInit :: HasHeist a => Snaplet (Heist a) -> SnapletInit a (Admin a)
adminPGInit h = makeSnaplet "admin-pg" description datadir $ do
  config <- getSnapletUserConfig
  fp <- getSnapletFilePath
  addTemplatesAt h "" fp
  addRoutes [ ("/users", handleUsers)
            , ("/foo", handleFoo)]

  return $ Admin "Admin Snaplet"
    where
      description = "PostgreSQL Admin"
      datadir = Just $ liftM (++"/resources") getDataDir

handleUsers :: HasHeist b => Handler b (Admin b) ()
handleUsers = do
  render "roles"

handleFoo :: HasHeist b => Handler b (Admin b) ()
handleFoo = writeBS "foo from admin"

Answer: Use addTemplates instead of addTemplatesAt.  You can see from the source code that it's slightly different from what you have here.
Also, an irrelevant detail, you don't need a type parameter on the Admin data type.  Since it does not use b, you don't need it as a type parameter.
Answer: Along with changing addTemplatesAt to AddTemplates as mightybyte suggested, I also had to change the handleUsers function to:
handleUsers = do
  rURL <- getSnapletRootURL
  render $ rURL `BS.append` "/roles"

The rootURL for the custom snaplet is "pgadmin" which has to be included in the template name when calling render.
Comment: I think if you change 'nestSnaplet "pgadmin"' to 'nestSnaplet ""' you won't need to do this.
Comment: Yes, that also works, and for my case it's a reasonable solution since I know all the routes of the base snaplet and subsnaplet in advance and can avoid route conflicts.  When building a standalone snaplet to be used by others this would be a problem because of potential route conflicts with the main app.


How can I get FULL html code via Webkit.net

Question: The website use ajax to load some data.When DocumentCompleted,I only get the html code without ajax data.
How to get the ajax data through webkit.net?
Thanks.
Comment: Webkit.net would have to be able to interpret JavaScript, which I doubt it can.
Answer: I've just recently fought with this myself and have what should be a working solution. I've not tried it with ajax, but I have used it after creating and appending DOM elements from C# and it produces the full code where DocumentText only produces the original unmodified HTML.
<code>var fullHTML = webKitBrowser1.StringByEvaluatingJavaScriptFromString("document.getElementsByTagName('html')[0].outerHTML")
</code>
The only limitation to this method that I've seen is that it does not include the doctype tag if there is one, but everything else is there.


Odd order moments of a symmetrical distribution

Question: Is it true that for every symmetrical distribution all odd-order moments are equal to zero?
If yes, how would I be able to prove such a thing?
Answer: I'm going to assume you mean (1) symmetric about $0$, and (2) distributions for which the odd-order moments actually exist.  Under these assumptions, yes.
In the continuous case, the $n$th moment for a distribution with pdf $f(x)$ exists and is $$\int_{-\infty}^{\infty} x^n f(x) \,dx,$$
exactly when the integral converges.  So, what does it mean for the integral to converge?
Remember that we define $\int_{-\infty}^{\infty} x^n f(x) \,dx$ to be $$ \int_{-\infty}^0 x^n f(x) \, dx + \int_0^{\infty} x^n f(x) \, dx.$$  (Well, we could choose some point other than $0$ to split the integral, but $0$ works fine.)  Convergence of $\int_{-\infty}^{\infty} x^n f(x) \,dx$ is equivalent to the convergence of both of these integrals.  Existence of the $n$th odd-order moment, then, is equivalent to $\int_{-\infty}^0 x^n f(x) \, dx$ and $\int_0^{\infty} x^n f(x) \, dx$ both being finite.
Suppose $\int_0^{\infty} x^n f(x) \, dx = A$.  If we let $u = -x$, then $$\int_{-\infty}^0 x^n f(x) \, dx = \int_{\infty}^0 (-u)^n f(-u) \, (-du) = (-1)^n \int_0^{\infty} u^n f(-u) \, du = - \int_0^{\infty} u^n f(u) \, du  = -A,$$
where the first step is legitimate because the integral converges and the third step follows because $n$ is odd and $f$ is symmetric about the origin.
Thus, if the $n$th odd-order moment exists, it is equal to $\int_{-\infty}^{\infty} x^n f(x) \,dx = -A + A = 0.$
The discrete case for $n$ odd is analogous.
Comment: The Wikipedia article referenced restricts itself to integrals over finite intervals $(-A, A)$.  So please considering editing your answer a little to make it more clear that the $n$-th order moment, $n$ odd, exists exactly when  $\int_0^{\infty} x^n f(x) dx$, $n$ odd, has finite value (or converges); and if the moment exists, it has value $0$.
Comment: And what about the neither-absolutely-continuous-neither-discrete case?
Comment: @Dilip: I can certainly make my answer more precise on that count.
Comment: @Didier: I skipped that, didn't I?  I suppose to handle all cases the answer would need to be rewritten in measure-theoretic terms.  My rustiness with the measure-theory approach to probability, though, makes me concerned that I would make too many mistakes were I to try to revise my answer along those lines.  So I think I'll leave my answer as is and acknowledge (via this comment) that I've skipped the case you mention.
Comment: @Mike Spivey: thanks for your answer:) if it's not symmmetric around 0, if e.g. i want to consider the odd-order central moments around a mean value m, with p(i) being a function symmetric around m=125 for i 0-256 (discrete case). does it still hold that these odd-order central moments are all equal to zero?
Comment: @nikos: No.  For instance, in your example $E[X^1] = m = 125$, not $0$.  The higher-order odd moments will be more complicated, but in general they will not be equal to $0$ (or $m$, either, I believe).
Comment: @Mike Spivey: I see...and if i have the following specific problem: let i be a discrete random variable and p(i), i=0,1,...,255 the corresponding histogram and it is given that: for i=0 to 20 the height of the histogram is $C/2$, for i=21 to 234 the height is $C$ and for i=235 to 255 the height is $C/2$. In that occasion is it true that all odd-order moments around the mean value m are all equal to zero. And if yes how can i prove it?
Comment: @nikos: Yes; all odd-order moments around the mean value $m$ will be $0$.  To prove it, do a variable transformation.  If $X$ is your random variable, let $Y = X-m$.  Then $Y$ is symmetric about $0$.  Then, for $n$ odd, $E[(X-m)^n] = E[Y^n] = 0$, by the argument in my answer above.  (And my apologies for misunderstanding your first comment; you did say "central moment," and I missed it.)
Comment: that was superb!
Answer: I think it's easier than arguments about integrals and sums.  Saying a random variable $X$ has a symmetric distribution means that $X$ and $-X$ have the same distribution.  This means that for any function $f$, if $E[f(X)]$ exists then so does $E[f(-X)]$ and they are equal.  So take $f(x) = x^n$ with $n$ odd.  If $X$ has an $n$th moment, then $E[X^n]$ exists and so $$E[X^n] = E[(-X)^n] = E[(-1)^n X^n] = E[-(X^n)] = -E[X^n]$$ which means $E[X^n] = 0$.
Comment: @kaka: we must not be using the same definition of "symmetric distribution". Mine is "X and -X are identically distributed". What is yours?
Comment: @ Nate Eldredge: It is not necessary to have $E[X]=0$ for a symmetric distribution.
Comment: What does "If $X$ has a $n$th moment, then $E[X^n]$ exists" mean?  I was taught that the $n$th moment of $X$ was _defined_ as the value of $E[X^n]$ if $E[X^n]$ exists, and was undefined otherwise.  The reason I requested @MikeSpivey to revise his answer was to confront this notion of existence of $E[X^n]$, which is obvious to those well-versed in the measure-theoretic approach to probability, but is confusing to beginning students as the OP nikos might well be.  See also [the discussion here](http://math.stackexchange.com/q/64651/15941).
Comment: @Nate Eldredge : Your solution is nice. But how to prove it for $E[X]\neq0$. Since distributions of $X$ and $-X$ are equal only for zero-mean distribution.
Comment: @kaka: the question is about symmetric distributions, so we necessarily have  $E[X]=0$ if it exists. (Take $n=1$ in my answer!)


Attic Wiring Using 12-3 and 12-2 pulling from ceiling outlet

Question: I am adding attic lights, and will be pulling power from the garage's constant power ceiling outlet. The switch will be close the the attic ladder opening. There will be 3 lights daisy chained in the attic. With the middle light in the series being closest to the power source, I am planning on using 12-3 to send power to the switch via the middle light.
Question: The outlet box has 12-2 and now I am not sure how to draw the power from the box to the switch (without having to go from the ceiling outlet box all the way to the switch, just to go all the way back down the daisy chained lights.) Am I missing something to make this work? Or is there only one option?
Answer: Your question leaves me a bit unclear about the relationship of the various parts:

I'd assume that a ceiling outlet (floor of the attic) would be closer to the hatch/switch than the light above is. In which case Run 12/2 from the outlet to the switch, and 12/2 from the switch to the lights.

If it appears to actually make sense for reasons I can't see without a diagram, run power on 12/2 from the outlet to the middle light, then run 12/3 from the middle light to the switch location. Connect the middle light to red/white. Connect black from the outlet to black(and white to white, and grounds all connected is assumed to be obvious.) If that path passes through one of the other lights, connect the light to red/white. Connect the switch to red/black. If the path to the switch does not pass through a light, run 12/2 from the closest light to it, and connect the black of that cable to the red (and white to white, and grounds all connected is assumed to be obvious.)

given the usual relative prices of 12/2 and 12/3, it might cost less to use more wire to make a longer run from the outlet to the switch, and not have to buy any 12/3, wiring it as in the first point.
Answer: Use the Black Wire for the hot (phase), white for neutral, These are on the existing plug. Run the 3 conductor wire between all of the lights. Connect the lights from white neutral to red power. Connect a switch somewhere convenient from the black to red. Be sure you connect all the safety grounds. You can use a 12X2 to power the system. Depending on your breaker you may be able to use #14 wire if it is a 15A breaker, if not stay with the #12.


Apache2 installation : libaprutil-1.so.0 => not found

Question: I was installing apache2 on Ubuntu 13.10, but after installation I tried to run apache showin error:
$ sudo ./httpd start
./httpd: error while loading shared libraries: libaprutil-1.so.0: cannot open shared object file: No such file or directory

I tried solutions given on web, none of them working, please help!!
$ ldd httpd
    linux-vdso.so.1 =>  (0x00007ffff05fe000)
    libpcre.so.1 => /usr/local/lib/libpcre.so.1 (0x00007f60741a5000)
    libaprutil-1.so.0 => not found
    libapr-1.so.0 => /usr/local/apr/lib/libapr-1.so.0 (0x00007f6073f71000)
    libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f6073d54000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f607398c000)
    libuuid.so.1 => /lib/x86_64-linux-gnu/libuuid.so.1 (0x00007f6073786000)
    libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f6073582000)
    /lib64/ld-linux-x86-64.so.2 (0x00007f60743d9000)

Comment: Wrong community buddy try here http://askubuntu.com/
Answer: This issue was probably resolved, but you were probably missing the package libapr1: Apache Portable Runtime library.
For Debian based operating systems such as Ubuntu, run:
sudo apt-get install libapr1

For Fedora based systems the package is apr-util:
sudo yum install apr-util

or
sudo dnf install apr-util

Then try running apache again.
Comment: Thank you. Used the fedora command for RHEL 8.
Answer: You shouldn't invoke httpd directly.  Most distributions provide a script that sets up the environment, including shared library path -- such as apachectl or apachectl2 or the sysv-init script.
Comment: yes I tried apachectl, same problem                                 $ sudo ./apachectl start
/usr/local/apache2/bin/httpd: error while loading shared libraries: libaprutil-1.so.0: cannot open shared object file: No such file or directory
Comment: /usr/local implies you built it yourself.  Looks like you don't have a usable aprutil in your shared library path, and there's no packager responsible for it but you.

Install something that satisfied the dependency.


Reflecting an array in Java

Question: I am new in Java and have a task to write some application. Faced one problem which can not pass :(
The issue is to update an array element through reflection (app selecting public array to update dinamicaly depending on string app reading from file):
First, i have reflected boolean variables as follows:
activity = activityName(activities[i].substring(0,activities[i].lastIndexOf('.', activities[i].length() - 4)));
Field field = refClass.getField(activity);
Object obj = field;
field.setBoolean(obj, true);

And that worked for me well. But now i need to use arrays instead of regular variables, and tried to make as follows:
activity = activityName(activities[i].substring(0, activities[i].lastIndexOf('.',  activities[i].length() - 4)));
Field field = refClass.getField(activity);
Object field_act = field;
field_act.setBoolean(field_act, LMKStorage.currentLmkSlot, true);

And getting exception "Argument not an array". :(
In field_act.setBoolean(field_act, LMKStorage.currentLmkSlot, true);, field_act is boolean[] i am getting with .getField(activity), LMKStorage.currentLmkSlot is int to determine which position of an array to set and "true" is value to set. The field_act i have to get 100% is an array, because i have not non-array static variables in refClass.
so far i have got studing books i have.But still nothing. Tried to google any examples to update array elements... nothing usefull for me.
Please advice.
Comment: why are you using the `field_act` variable instead of `field`? `Object` doesn't have a `setBoolean` method. Can you post your actual code?
Comment: I'm a little confused by your working example. Your obj variable is the field representation object? obj should be some instance of your refClass.
Comment: Actually, i tried many ways, and `field` was too.                   `activity = activityName(activities[i].substring(0, activities[i].lastIndexOf('.', activities[i].length() - 4)));
Field field = refClass.getField(activity);
Object field_act = field;
Array.setBoolean(field, LMKStorage.currentLmkSlot, true);  Just tried to use `field` which is `Field` type and got:  java.lang.IllegalArgumentException: Argument is not an array
Comment: Can't you just retrieve the array with `Field.get`, cast it to a `boolean[]`, and set the value in that?
Comment: Sorry, for mistakes in formating posts, i am first time here and experimenting to get my posts nice.
Answer: For arrays, use java.lang.reflect.Array instead of java.lang.reflect.Field.
Object field_act = field.get(obj);
Array.setBoolean(field_act, LMKStorage.currentLmkSlot, true);

Comment: Yess, You are correct that was my mistake while asking question. The correct code is:      Array.setBoolean(field_act, LMKStorage.currentLmkSlot, true);
Comment: Then the mistake is in your code. You should replace `Object field_act = field;` with the line `Object field_act = field.get(obj);`.

Reflecting an array in Java


options menu not inflating correctly in page change in view pager

Question: I have a view pager with each fragment having its own options menu which is inflated when the fragment comes is current one in the view pager however, it is not working as expected. Sometimes the correct options menu appears sometimes the adjacent fragments menu appears. I have read from other SO posts and other sites that it is due to view pager holding the current page and the two adjacent pages to be in "current" view thus, the options menu are gobbled together as one or something like that which creates the problem. I have solved the gobbling problem by calling menu.clear() before inflating the new menu. but the menu is still not correctly loaded correctly sometimes(well most of the times, actually).
Some suggestions have been made on other sites to change the view pager classes but I am not sure if that is the correct way. Can anyone please help direct to a solution or give some advice on how to go around this problem.
Code I am using:
<code>@Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

       menu.clear();

       inflater.inflate(R.menu.A_fragment_optionmenu, menu);

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
   /* switch (item.getItemId()) {
        case R.id.insert_tag:

            FragmentTransaction trans = getFragmentManager().beginTransaction();
            trans.replace(R.id.buy_root_frame, new B_insert_tags());
            trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
            trans.addToBackStack(null);
            trans.commit();

            return true;
        default:

    }*/
return super.onOptionsItemSelected(item);
}
</code>
Comment: Try [Fragment.getUserVisibleHint](https://developer.android.com/reference/android/app/Fragment.html#getUserVisibleHint())
Comment: how to use that it only gets called by view pager adapter and I cannot send any info to oncreateoptionsmenu there is no link, how to create that link?
Comment: ok used onprepareoptionsmenu on the activity where view pager was and then used on pageselected to inflate the right menu. works but with a small lag (unnoticeable though).
Answer: ok used onprepareoptionsmenu on the activity where view pager was and then used on pageselected to inflate the right menu. works but with a small lag (unnoticeable though).


Keep django pagination and search filters when submitting form on same page

Question: I have a view which has a list of all customers on one side, which also has working pagination and search/ filter functionality.
Where I am stuck is, if I have a form & button on my list to select a customer to view on the other side of the page, and it clears my current pagination page and any filters applied to the customer list when I run the function to pick up the selected customer.
How can I have a form action = "{% url 'some_function' %}" and keep the pagination and search.
http://localhost:8000/clients/clean?page=8&search_term=nsw
Current view:
def customer_list_clean(request, selected = None):
    if selected != None:
       selected = Client_Customer.objects.get(id = selected)
    try:
        msg = request.GET['search_term']
    except:
        msg = ""
    clients = Client_Customer.objects.distinct().filter(Q(customer_name__contains = msg) |
                                                        Q(physical_address__street_address__contains = msg) |
                                                        Q(physical_address__suburb__suburb__contains = msg) |
                                                        Q(physical_address__suburb__post_code__contains = msg) |
                                                        Q(physical_address__suburb__region__state_abb__contains = msg)
                                                        ).order_by('customer_name')
    if msg:
        messages.success(request, (f"Customer records filtered by: {msg}"))
    found = clients.count()
    if clients.filter(confirmed= False).count()>0:
        messages.info(request, (f"Some customers records have not been validated!"))
    #Pagination
    page = request.GET.get('page', 1)
    paginator = Paginator(clients, 25)
    try:
        clients = paginator.page(page)
    except PageNotAnInteger:
        clients = paginator.page(1)
    except EmptyPage:
        clients = paginator.page(paginator.num_pages)
    if selected != None:
         context ={'clients':clients, 'found':found, 'msg':msg, 'selected':selected}
    else:
         context ={'clients':clients, 'found':found, 'msg':msg}
    return render(request, 'clients/client_list_clean.html',context)

Clients are displayed in a table (nothing special)
client_list_clean.html
{%extends 'base.html'%}
  {%block body%}

Admin | Edit Customers

({{found}} records found)

      <form action = "{% url 'clients:customer_list_clean' %}"  enctype="multipart/form-data" class="form-inline my-2 my-lg-0">

        <input class="form-control mr-sm-2" type="search" placeholder="Search records" aria-label="Search" name = "search_term">
        <button class="btn btn-outline-info my-2 my-sm-0" type="submit">Search / Clear</button>
      </form>

      {%include 'client_pagination.html'%}

          Customer <button class="btn btn-outline-info my-2 my-sm-0" type="button">Asc</button> <button class="btn btn-outline-info my-2 my-sm-0" type="button">Desc</button>
          Type
          Address
          <button class="btn btn-outline-info my-2 my-sm-0" type="button">Asc</button> <button class="btn btn-outline-info my-2 my-sm-0" type="button">Desc</button>
          Details

        {% for client in clients %}

            {% if client.confirmed == False %}
              {{client.customer_name}}
              {{client.client_type}}

              {% for add in client.physical_address_set.all %}
              {{add}}

                <form class="" action="{% url 'clients:customer_list_clean' %}" enctype="multipart/form-data"  >
                  <button class="btn btn-outline-info my-2 my-sm-0" type="submit">View</button>
                </form>

              {% endfor %}
            {% else %}
              {{client.customer_name}}
              {{client.client_type}}
              {% for add in client.physical_address_set.all %}
              {{add}}
              Something
              {% endfor %}
            {% endif %}

        {% endfor %}

Merge Stuff

some merge stuff

          {{selected.customer_name}}

Detail stuff

Some stuff

  {%endblock body  %}

Pagination is in another template and "included" on the html page
pagination.html:
{% if clients.has_other_pages %}

  {% if clients.number >= 11 %}

FIRST

  {% endif %}
  {% if clients.has_previous %}

        «
        Previous

  {% else %}

        «
        Previous

  {% endif %}

  {% if clients.number|add:'-9' > 1 %}

- 10

  {% endif %}

  {% for i in clients.paginator.page_range %}
      {% if clients.number == i %}

          {{ i }}(current)

        {% elif i > clients.number|add:'-10' and i < clients.number|add:'10' %}

{{ i }}

      {% endif %}
  {% endfor %}

  {% if clients.paginator.num_pages > clients.number|add:'9' %}

+ 10

  {% endif %}

  {% if clients.has_next %}

        »
        Next

    {% else %}

        »
        Next

  {% endif %}

  {% endif %}

Answer: It's all good, I worked it out.
Using an a tag instead of a form to add an additional term to the url.
View

views.py
try:
    print(request.GET['selected'])
except:
    pass

I am yet to do something with the selected id, but I now have it in the function none the less.


Dead or Alive: Dimensions Control Mechanism

Question: In the recently released title for the Nintendo 3DS, some of the video previews seem to suggest that the characters are controlled by "selecting" combinations on the touch screen, rather than in the traditional manner for beat'em'ups.
Is this the case? Does DOA:Dimensions not have "normal" controls?
Comment: If this game is anything like the other games in the series, it's a "Fighting" game, not a "Beat 'em up".
Answer: Both the 3DS versions of DoA: Dimensions and Street Fighter IV seem to be making use of a control method similar to this. Note that it's in addition to normal controls though. So you can still play the game completely manually if you prefer, but there's the option of touching the special move "shortcuts" on the screen as well.
Comment: Having played SSF4, the controls come in handy. I do enjoy fighters on home consoles and at first I thought the idea of using a touch pad seemed cheap. It still feels kind of cheap but there are "cooldowns" for tapping moves on the touchpad which makes this style less cheap. As for DOA, it looks like it will play exactly like the consoles, just a little bit of ease by adding touchscreen controls since a full controller is out of the question. /rant. sorry :S
Answer: Now that it's out, this can be answered definitively.
In DoAD, you can perform combos the old-fashioned way, or by tapping it on the bottom screen. If you're playing with buttons, the bottom screen highlights your combo sequence(s) as you enter the commands. Overall I find the user interface much nicer than Street Fighter's.
Unlike Street Fighter IV, there is no segregation between touchscreen / button control in online play. If someone is entering commands with the touchscreen an icon pops up on their side of the screen, so you know if they're doing it, but you can't forbid it like you can in SFIV. Realistically this probably doesn't matter, but some portions of the Internet are up in arms about it.


Weblogic does not support EJB3?

Question: I use WebLogic Server 10.3.5.0 and I experienced no problems using EJB 2.x on it, but I want to deploy EJB3 and it does not work. I'm new to java ee , but I read a lot of information, I didn't find the answer. What I try:
1. Create my simple Calculator application
package test;

import javax.ejb.Remote;
import java.lang.annotation.*;

@Remote
public interface Calculator {

    public int add(int x, int y);
}

package test;

import javax.ejb.Stateless;
import javax.ejb.Remote;

@Stateless(name="CalculatorBean", mappedName="EJBCalculatorBean")
@Remote(Calculator.class)
public class CalculatorBean {

    public int add(int x, int y){
        return x + y;
    }

}

Here's my ejb-jar.xml:
<?xml version="1.0"?>

<ejb-jar xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/j2ee/ejb-jar_3_0.xsd"
version="3.0" xmlns="http://java.sun.com/xml/ns/javaee">

  <enterprise-beans>

    <session>
      <ejb-name>Calculator</ejb-name>
      <remote>test.Calculator</remote>
      <ejb-class>test.CalculatorBean</ejb-class>
      <session-type>Stateless</session-type>
      <transaction-type>Container</transaction-type>
    </session>
  </enterprise-beans>

  <assembly-descriptor>

    <container-transaction>
        <method>
            <ejb-name>Calculator</ejb-name>
            <method-name>*</method-name>
        </method>
        <trans-attribute>NotSupported</trans-attribute>
    </container-transaction>
  </assembly-descriptor>

</ejb-jar>

and my weblogic-ejb-jar.xml:
<?xml version="1.0"?>
<!DOCTYPE weblogic-ejb-jar PUBLIC
'-//BEA Systems, Inc.//DTD WebLogic 6.0.0 EJB//EN'
'http://www.bea.com/servers/wls600/dtd/weblogic-ejb-jar.dtd'>

<weblogic-ejb-jar>

    <weblogic-enterprise-bean>
        <ejb-name>Calculator</ejb-name>
        <jndi-name>EJBCalculatorBean</jndi-name>
    </weblogic-enterprise-bean>

</weblogic-ejb-jar>

I also have a very simple application.xml. I packed it into an exploded EAR folder, then I installed it from the weblogic console. When I tried to "activate changes" it failed with the message that the server is missing the home interface.

As far as I know EJB3 does not require home interface.
In EJB3 I don't have to specify any ejb information into my descriptors. Annotation have to provide the information for the server.

Am I right? And what can be the problem?
I also tried to use appc tool but it also missed the home interface.
Thx in advance!
I cleaned up all EJB entries from my ejb-jar.xml and weblogic-ejb-jar.xml and finnaly it worked. The problem is that I cannot access my bean from client running on different JVM.
Here's my client code:
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import test.Calculator;

public class Test {

    ;

    /**
     * @param args
     */
    public static void main(String[] args) {

        {
            try

            {
            Hashtable<String, String> env = new Hashtable<String, String>();
            env.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
            env.put(Context.SECURITY_PRINCIPAL,"myuser");
            env.put(Context.SECURITY_CREDENTIALS, "mypassword");
            env.put(Context.PROVIDER_URL,"t3://myweblogic:7001");
            InitialContext ctx = new InitialContext(env);

            System.out.println("Initial Context created");

            Calculator calculator  = (Calculator)ctx.lookup("EJBCalculatorBean#test.Calculator");

            System.out.println("lookup successful");
            System.out.println("Calling EJB method . . .");
            System.out.println(calculator.add(3, 6));
            System.out.println("Output will be in Managed server console");
            }

            catch (Exception e)
            {
            e.printStackTrace();
            }

    }
    }
}

A have the wlclient.jar;javax.ejb.jar;calculator.jar on my classpath. calculator.jar is the one I deployed to the server(it contains the Calculator.class and theCalculatorBean.class)
This client works fine when I run in the same JVM the weblogic uses, but in different JVM this error comes:
Caused by: java.lang.ClassNotFoundException
        ... 24 more
javax.naming.NamingException: Unhandled exception in lookup [Root exception is org.omg.CORBA.MARSHAL:   vmcid: SUN  minor code: 257 completed: Maybe]
        at weblogic.corba.j2ee.naming.Utils.wrapNamingException(Utils.java:83)
        at weblogic.corba.j2ee.naming.ContextImpl.lookup(ContextImpl.java:291)
        at weblogic.corba.j2ee.naming.ContextImpl.lookup(ContextImpl.java:227)
        at javax.naming.InitialContext.lookup(InitialContext.java:392)
        at Test.main(Test.java:37)

What can be the problem?
Comment: Have you tried `CalculatorBean` implement `Calculator`
Comment: Thx Nayan, it was part of the solution.
Comment: @Mike82: When you say you "cleaned up all EJB entries" from ejb-jar.xml and weblogic-ejb-jar.xml, what exactly do you mean? Did you remove the bean declarations? Please give more detail – I am experiencing a similiar problem.
Answer: Weblogic 10.3.5 does support EJB3.
Did you try to call your SimpleCalculator bean from the Test window in the Console? This way you can verify that it works correctly.
W.r.t. deployment, just place the .ear file into the DOMAIN_HOMES/applications/my_domain/ folder and it will get deployed automatically, you do not have to go through the Console deployment every time.
After you test the SimpleCalculator bean in the console, you can then try the lookup, does it work this time?

Weblogic does not support EJB3?


Can I pour concrete if it's raining out?

Question: I have 6 bags of concrete that I need to mix and pour for 2 deck piers.
It's raining lightly outside.
Should I reschedule or just do it and cover with plastic when we're done?
Answer: If you're manually mixing under cover (garage, gazebo, kitchen fly) and only dumping when ready, then no problem.
Definitely cover in case of heavier rain.  Its never a bad idea to slow cure concrete, anyway.  Plastic can make flat work look bad (plastic wrinkles), but for deck piers, no problem.
Now get to work and quit stalling by playing on the computer ;-)
Answer: If it is lightly raining you have nothing to worry about especially for piers.  Extra water just raises the cure time.  I would try to wipe off any standing water after you are done.
Answer: Heavy rain: Not advisable, but has been done (you end up working the finished side up more, as the rain and runoff can ding the finish.
Light rain: Cover the work area if possible. If it is a foundation or other project with a form: No problem.
In general: allow lots of cure time, and wait until the concrete is cold to the touch (it is usually very slightly warm while it is curing)


react js unexpected token error

Question: I am a new one who is learning react, i am also not familiar with JavaScript. This is the 1 week that i am trying to import react. I added CDN script tag into my index.html at last.
normally i can add xml tag into js files, but when i try to create component, system returns error.
can anyone explain me what is my mistake?
here is the  index.html and my code.

I have no idea what is going on when i try to write React.blabla, how system finds React components and how system imports it. i am familiar to Java. thanks in advance.
Comment: Could you please edit your post and include your code instead of images ?
Comment: Using create-react-app (https://github.com/facebook/create-react-app) ?
Answer: in line 14, {} is an object. A property in an object has a name an a value:
<code>{name: value}
</code>
However, your object has only the value but no name
<code>{formatName(user)}
</code>
Answer: <code>const element = React.createElement(
  'h1',
  {className: 'button'},
  formatName(user)
);
</code>
See here: https://codesandbox.io/s/myvm10lj5y

react js unexpected token error