text:
Q: password and ip restriction in htaccess I am learning how to use htaccess.

*

*First I want to try how to set up username and password for the
following directory ~/public_html/55/m:
~/public_html/55/m$ ls -la
total 24
drwxr-xr-x 2 tim Domain^Users 4096 2011-12-16 21:39 .
drwxr-xr-x 3 tim Domain^Users 4096 2011-12-16 21:42 ..
-rwxr-xr-x 1 tim Domain^Users  271 2011-12-16 21:26 .htaccess
-rwxr-xr-x 1 tim Domain^Users    8 2011-12-16 21:39 .htpasswd
-rwxr-xr-x 1 tim Domain^Users  884 2011-12-16 20:02 index.html

I manually created two text files: .htaccess and .htpasswd.
Their contents are
~/public_html/55/m$ cat .htaccess
AuthUserFile /home/WIN/local/WIN/tim/public_html/55/m/.htpasswd
AuthGroupFile /dev/null
AuthName EnterPassword
AuthType Basic

Require valid-user

~/public_html/55/m$ cat .htpasswd
tim:123

But I can access the webpage without being asked to provide username
and password. I wonder why?

*Second I want to try how to restrict the ip range to access
~/public_html/55/n
~/public_html/55/n$ ls -la
total 16
drwxr-xr-x 2 tim Domain^Users 4096 2011-12-16 21:54 .
drwxr-xr-x 4 tim Domain^Users 4096 2011-12-16 21:53 ..
-rwxr-xr-x 1 tim Domain^Users  292 2011-12-16 21:53 .htaccess
-rwxr-xr-x 1 tim Domain^Users  884 2011-12-16 21:53 index.html

where I created manually the text file .htaccess whose content is:
~/public_html/55/n$ cat .htaccess
AuthUserFile /dev/null
AuthGroupFile /dev/null
AuthName AllowFromBlah
AuthType Basic

<limit GET>
order  deny,allow
deny from all
allow from xxx.edu
</Limit>

But I can access the webpage from outside the specified ip range
xxx.edu. I wonder why?
Thanks and regards!

A: Maybe .htaccess files for those directories are simply ignored using the AllowOverride directive in the virtual host configuration. From http://httpd.apache.org/docs/2.2/mod/core.html#allowoverride:

When this directive is set to None, then .htaccess files are
  completely ignored. In this case, the server will not even attempt to
  read .htaccess files in the filesystem.

EDIT: On Ubuntu configuration is based in /etc/apache2, other systems have their configuration based in /etc/httpd or another directory.  The Ubuntu configuration for user home directories is handled by mods-available/userdir.conf which is enabled when linked into /etc/apache2/mods-enabled.  It specifies home directories as /home/*/public_html.  The php4.conf also references the same directories.


text:
Q: Oracle 19c :: Failed to set ACL's for specified User I'm trying to install a fresh new downloaded Oracle Database 19c on my Windows 10 Home and I receive the error: Failed to set ACL's for specified User.

In the logs details I see mentioned updating registry key HKEY_LOCAL_MACHINE\SOFTWARE\Oracle\KEY_OraDB19Home1 I don't see nothing unusual there.
I followed this guide and I:

*

*run net share

*run net use \\localhost\c$

*I Stop and Disabled and the service OracleRemExecServiceV2

*I also run with PowerShell as Administrator the command setup.exe -ignorePrereq -J"-Doracle.install.db.validate.supportedOSCheck=false"

*Of course I have also created a brand new user for Oracle with a brand new password. And I also tried the Windows user within the Administrator group

*I went to regedit and on HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System I created a new DWORD value LocalAccountTokenFilterPolicy set to 1

*I disabled Windows Defender and the whole Firewall

*Then I tried the Debug mode so run from an elevated prompt I run setup.exe -debug -ignorePrereq -J"-Doracle.install.db.validate.supportedOSCheck=false" and as result I got:

native operation failed with WSE-000053: Windows application programming interface (API) SetFileSecurityW failed.

and
O/S-Error: (OS 123) The filename, directory name, or volume label syntax is incorrect.

which makes absolutely no sense to me because it looks like a Windows error.
How it can be so hard to install Oracle DB on a brand new machine with tons of CPU and RAM?
What ACL means and how to set it up?
Where am I wrong?

A: This is what makes your life miserable:

Oracle Database 19c on my Windows 10 Home

Oracle isn't/wasn't/won't (as far as I can tell) be supported on any MS Windows Home edition. True, some people made it work, but that's more matter of luck. You should upgrade operating system.
Or, maybe a better option, download one of Pre-Built Developer VMs (for Oracle VM VirtualBox).

A: Installation guide
says

Oracle Database for Windows x64 is supported on the following
  operating system versions: Windows 10 x64 - Pro, Enterprise, and
  Education editions

Oracle 19c is not supported on Windows 10 Home edition.
If you really want to have Oracle 19c on Windows, try to create a virtual machine with a supported Windows Server evaluation version. Or try to install Oracle 18 XE.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sync'ing ACL permissions in a NodeJS application using MongoDB Currently using the Node ACL module from:
https://github.com/OptimalBits/node_acl
This is working a treat but now the requirement is have to reflect any changes to our security config in our ACL layer.
What Im looking for is a clean way to iterate over the roles defined in our security config, decide whether the permissions/resources have changed and if they have update or remove them.
Here is a sample security config file, take the scenario where 'put' is removed from the resource /projectId.
"roles":{
   "itemRole":[
      {
         "roles":"owner-projectId",
         "allows":[
            {
               "resources":"/projectId",
               "permissions": ["put", "post", "patch","get","delete"]
            },
           {
               "resources":"/projectId/settings",
               "permissions": ["put"]
            }
         ]
      },
      {
         "roles":"collaborator-projectId",
         "allows":[
            {
               "resources":"/itemId",
               "permissions":["put","post", "patch","get"]
            },
            {
               "resources":"/api/resource/itemId",
               "permissions":["put", "post", "patch","get"]
            }
         ]
      },
      {
         "roles":"spectator-newId",
         "allows":[  ]
      },
      {
         "roles":"admin-newId",
         "allows":[
            {
               "resources":"/api/resource/itemId/update",
               "permissions":[ "put"]
            }
         ]
      }
   ]
}

The following query will allow me iterate over the different roles and return all the allows for that resources, these allow_* should match what is currently in the security.config:
db.getCollection('authACLresources').find(  { _bucketname: {"$regex":"allows_*"}, key: { '$in': [ 'spectator-2bc240c6ffa988260b501922' ] }})

I can then look at the different permissions and compare - just wondering if there is a better way to do this? I know the node ACL module has a method called whatResources but doesn't give you the permissions just the resources.


text:
Q: Docker buildkit, new --mount command during build and large files in the context If I have a very large file that I only need during build time, and If I use the following commands:
docker buildx build Dockerfile .

and then a line somewhere in the Dockerfile:
RUN --mount=type=bind,target=/target_path,readonly,source=large_dir_or_file

would that very large file still got send to the docker daemon? I am wondering if the --mount command offers any advantage here for the large files?
Also, if the docker context and daemon are on the same machine, are all the context files still sent/copied to a location where docker daemon can see them?
Thank you,
Daniel

A: The advantage of
RUN --mount=type=bind,target=/target_path,readonly,source=large_dir_or_file something

over
COPY large_dir_or_file /target_path
RUN something

is that the big file will not bloat the layers of your docker image.
But yes, it must be in the context and it will be sent to the docker daemon even if it is local.

A: Even if you're working locally, the docker build command always sends a copy of the context directory over its socket to the Docker daemon.  If you have a very large build context (especially over a gigabyte in size) this is the step that prints out a percentage progress at the very beginning of the build sequence.
The build context is everything in and underneath the directory you pass to docker build, less anything that's in the .dockerignore file.  This will always get sent to the Docker daemon, local or remote, whether or not any given file is actually COPYed into the image.
I'm guessing the BuildKit bind-mount option you show probably will work mechanically.  You need to make sure the large file is also in the .dockerignore file so it's not copied as part of the build context.  This will effectively prevent you from using a remote Docker daemon to build, if you or your CI system will ever do this, and it's not a typical pattern, but it should have a visible difference in build performance and more specifically in that initial "copying the build context" step.
You note in the question that this file is only used during your initial build sequence, and I'm guessing you copy the result of the build out using a multi-stage build so you have a much smaller image.  My past experience has been that operations like docker push and docker pull are unreliable with very large images, so if you can't remove this file from the final image you might need to inject it into the container in some other way.


text:
Q: Saving user photos and photos from web So i have this situation with images. In one of app stages i get all user photos from his photo library. I get them as ALAsset's. I let him choose photo he wants. Then i save his chosen photo to applications directory as full size photo with HIGH_ prefix and a thumbnail of a photo with LOW_ prefix. I need this because photos have some properties like time etc. I save those properties to SQL database with a field of photo name that begins with HIGH_ or LOW_. When i need to get photos i get properties from db and then do [UIImage imageWithContentsOfFile:photoPath]. Can someone tell me how to do it more efficient because writing and getting photos like this takes some time. And on iPhone 4 i sometimes even get memory warnings. AND another question would be, how should i save photos fetched from web?

A: I stand corrected, instead of using core data, Apple writes,

It is better, however, if you are able to store BLOBs as resources on the filesystem, and to maintain links (such as URLs or paths) to those resources. You can then load a BLOB as and when necessary.

So you are doing it correctly, but maybe you should check out transformables. Just make sure you remove images you aren't using from memory if you are getting warnings
From documentation: https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/CoreData/Articles/cdPerformance.html
Under the section 'Large Data Objects (BLOBs)"
Another way to do it with a transformable:
Which way to store data(image)? NSData, String or Transformable
In fact, perhaps transformables are for core data at least:
How should I store UIImages within my Core Data database?


text:
Q: Difference between operations & threads in Cocoa I am learning Objective-C, I will be developing a video processing application.
I am reading the developer's guide on apple and I ran into Operation objects. I just need some clarifications what the difference between operations & threads, disadvantages, advantages, use cases.
From what I read, operation is higher level of application process/task management. The NSOperationQueue can handle operation resources and concurrency.
What I don't understand is that Operation can be directly run in a thread, I am not too clear on this concept. I am not to clear on the difference between operations & threads.
Please provide me with as much information/background on the two as possible.
Thanks a lot everyone.

A: The difference between NSOperation and threads is one of abstraction. A thread is a low-level (operating system-level) construct with which to execute multiple "threads" of code concurrently. Although Cocoa provides the NSThread API, it is essentially a wrapper on the pthreads API. NSOperation is a higher-level abstraction of a task that you wish to execute. NSOperationQueue will schedule execution of a queue of NSOperations so as to maximally utilize the available CPU(s). On a multi-core system, multiple NSOperations will be executed simultaneously using a pool of threads that NSOperationQueue maintains. The advantage of using this higher-level API is that it lets you think about the "operations" you wish to perform rather than how to schedule them. The disadvantage (and hence the advantage of using NSThread directly) is that you have more control over the scheduling of the thread and communication between the thread and other threads (see -[NSObject performSelector:withObject:onThread:]). For atomic tasks, such as video processing, NSOperation is likely the best fit.


text:
Q: Force HTTPS on homepage, but force HTTP on all others I am trying to force HTTPS on my homepage, but force HTTP on all others, via .htaccess. I have tried to follow numerous other solutions, with no luck.
My homepage should be formatted as: https://example.com
Other pages should be: http://example.com/page , http://example.com/page?var=asd , etc.
My attempt:
RewriteEngine On

#Disable HTTPS for all pages
RewriteCond %{HTTPS} on
RewriteRule ^(.*)$ http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

#Enable HTTPS for homepage
RewriteCond %{HTTPS} off
RewriteRule ^$ https://%{HTTP_HOST} [R=301,L]

With both of those rules in place, the page doesn't load and I get a redirect error. With one of the rules commented out, the page loads, but isn't doing what I want. Any help would be appreciated!

A: Have it this way:
RewriteEngine On

# Enable HTTPS for homepage
RewriteCond %{REQUEST_METHOD} !POST
RewriteCond %{HTTPS} off
RewriteRule ^$ https://example.com/ [R=301,L]

# Disable HTTPS for all pages
RewriteCond %{REQUEST_METHOD} !POST
RewriteCond %{HTTPS} on
RewriteRule . http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]

Make sure to clear your browser cache before testing.


text:
Q: DecodeBase64 using apache commons I am using a java class  CryptoSHA1BASE64.java to encrypt a plain text to sha1Base64 key

String result = CryptoSHA1BASE64.hash(text);

The code of the class - CryptoSHA1BASE64.java is
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.servlet.ServletException;

public final class CryptoSHA1BASE64 {
  public static String hash(String plaintext) throws ServletException {
    MessageDigest md = null;

    try {
      md = MessageDigest.getInstance("SHA"); // SHA-1 generator instance
    } catch (NoSuchAlgorithmException e) {
      throw new ServletException(e.getMessage());
    }

    try {
      md.update(plaintext.getBytes("UTF-8")); // Message summary
      // generation
    } catch (UnsupportedEncodingException e) {
      throw new ServletException(e.getMessage());
    }

    byte raw[] = md.digest(); // Message summary reception
    try {
      String hash = new String(org.apache.commons.codec.binary.Base64.encodeBase64(raw), "UTF-8");
      return hash;
    } catch (UnsupportedEncodingException use) {
      throw new ServletException(use);
    }
  }
}

I want to decrypt the generated key back to plain text, i tried same approach i.e., the decrypt method of apache commons -

Base64.decodeBase64(key)

But, I gest some weird character instead of plain text. Any suggestions/comments would be of great help. Thanks!!!

A: Hashing algorithms are one way. You can't undigest the string to get the original text. That is why these algorithms are used for passwords before they are stored in a database for example, so that even if the database is hacked, you can't get the original text.


text:
Q: Custom columns in django_tables2 I've had a search around for this but haven't had much luck so looking for a bit of help. I'm trying to add some extra columns to a table defined by a model, using function definitions in the model. Here's what my code looks like now:
# models.py
class MyModel(models.Model):
    my_field = models.TextField()

    def my_function(self):
        # Return some calculated value based on the entry
        return my_value

# tables.py
class MyTable(tables.Table):

    my_extra_column = tables.Column(....)

    class Meta:
        model = MyModel

# views.py
table = MyTable(MyModel.objects.all())
RequestConfig(request).configure(table)
return render(request, ....)

My question is can I access my_function in the entries passed to MyTable so I can show the result of my_function in the custom my_extra_column column? I assume I need to be using accessors, but I can't see how I can access the queryset data using this. Thanks!

A: I figured it out in the end, it was actually not too hard after all :)
So using my example above, in order to add a custom column using a function in the associated model you just use accessors ...
# models.py
class MyModel(models.Model):
    my_field = models.TextField()
    my_field_2 = models.IntegerField()

    def my_function(self):
        # Return some calculated value based on the entry
        return my_value

# tables.py
class MyTable(tables.Table):

    my_extra_column = tables.Column(accessor='my_function',
         verbose_name='My calculated value')

    class Meta:
        fields = ['my_field', 'my_field_2', 'my_extra_column']
        model = MyModel

The trouble comes if and when you want to be able to sort this data, because the function won't translate into any valid field in MyModel. So you could either disable sorting on this column using ordering=False or specify a set using order_by=('field', 'field2')


text:
Q: Compact p-adic analytic groups It is a classical fact that a topological group $G$ admits the structure of $p$-adic analytic group iff it contains an open subgroup which is pro-p uniformly powerful. I was reading the related section on "Analytic pro-p groups" (second edition) of Dixon, Du Sautoy, Mann and Segal when I found a refinement of this result.
They claim in Corollary 8.34 that $G$ is a compact p-adic analytic group iff it contains an open normal pro-p uniformly powerful subgroup of finite index. They said this follows from the previous theorem and other facts regarding uniformly powerful groups but they do not name the exact proposition/lemma/theorem. I tried to look in section 4 for the possible result they refer to but without success. Could you please explain why the normality is equivalent to the compactness?
Also, I was told that if a $p$-adic analytic group is compact then it is a profinite group. Can you explain this or give a reference?

A: After I while I understood the answer: the key result regarding powerful pro-p group is theorem 3.13 of the book (not in section 4).

Theorem 3.13
  Let $G$ be a pro-p group, then $G$ has finite rank iff it is finitely generated and it has an open powerful subgroup of finite rank. In this case $G$ contains a powerful characteristic open subgroup.

For the first implication: $G$ compact p-adic analytic has a normal uniform subgroup.
If $G$ p-adic analytic contains $U$ pro-p powerful the idea is to apply theorem 3.13 to an appropriate corrected $U$: first $G/U$ must be finite ($G$ is compact and $U$ is open), take $T$ a transversal set and define $V= \bigcap_{t \in T}tVt^{-1}$. You can verify this is a normal open subgroup of $G$ and it is pro-p of finite rank (apply thm 3.9). Then by theorem 3.13 $V$ contains $W$ powerful characteristic pro-p which must have finite rank.
Now thm. 4.2 tells us that $P_k(W)$ is uniformly powerful for $k$ big enough. And since $W$ is characteristic in $V$ also $P_k(W)$ will be characteristic in $V$. Now we have $P_k(W)$ characteristic in a normal subgroup of $G$, hence it is normal in $G$ and this will be the uniform subgroup we wanted.
My first idea was that you had to modify the starting $U$ uniform to make it normal, it turned out that you needed only the fact that it is pro-p to find an appropriate subgroup  of it with the desired properties.
The inverse implication is easy: you just have to observe that the cosets form an open cover of $G$ by compact spaces to deduce $G$ is compact.
Regarding my second request: the point is that an analytic group misses only compactness to be a profinite group: by the classical theorem it contains $U$ uniformly powerful open subgroup, it is easy to see that the open subgroups of such $U$ form a basis of neighbourhoods of $1$ in $G$.
An interesting fact is that you have the group is profinite but not necessarily pro-p: an easy example is given by $\mathbb{Z}_p^{\times}\cong C_{p-1}\times (1+p\mathbb{Z}_p)\cong C_{p-1}\times \mathbb{Z}_p$. This contains $\mathbb{Z}_p$ as open subgroup of index $p-1$.


text:
Q: RESTFul way to reference resource with unique fields One of the requirements for our REST interface is that each resource be identifiable by unique fields (aside from the primary identifier). The reason for this is that we want to be able to handle bulk importing data - in which case the client can't know the system generated primary identifiers.
This means we have to be able to reference our resources by unique fields. Using a primary key our read requests look like this:
GET example.com/rest/customers/1

and to get orders related to that customer
GET example.com/rest/customers/1/orders

Now, lets assume two fields in customer identify it uniquely, name ("foo") and businessId ("bar"). Given that, I came up with the following URI to get the orders for this customer:
GET example.com/someotherpath/customers/foo,bar/orders

But I don't like that I have a different path to identify that this is a resource being accessed via unique fields. How would you structure the above query in a RESTful way using unique fields instead of the primary key?
Further, an order looks like this:
{
    <SNIP>
    "orderId" : "42"
    "_links": {
        "customer": {
            "href" : "rest/customers/1"
            "key": [ "foo", "bar" ]
        }
    },
}

Any issues with allowing client to interchangeably specify href OR key when communicating with the interface?

A: For the first bit, I just wouldn't do it. If a customer has a unique id (and they should), I wouldn't allow end users to specify N other fields that happen to also uniquely identify the customer. It's messy for the user (which field goes first?) and also messy for you on the back end.
For the second bit, the issue is: what happens when they specify both? Which takes precedence? Are they going to remember? Do you want to have to support both? It's generally a good idea to only allow one way to do any particular thing if you can get away with it.


text:
Q: Adjust mermaid diagram white space in Azure devops wiki Goal: Work flow diagram displays underneath the header text with standard spacing
Actual Results: Work flow diagram displays underneath header with a standardized amount of white space
Errors: No errors messages
Troubleshooting Steps: I attempted to follow the solution steps in this article but it makes the mermaid diagram no longer display and produces formatting error codes.
# Author Submission Workflow
::: mermaid
graph TD
A[Author sends a review to the customer success email] -->|Dynamics 365 creates a review case based on the Knowledge Base Article Review Template| B[[Automation]]
B --> D[D365 creates a review case based on the Knowledge Base Article Review Template]
B --> E[D365 places the review article in the Article Review Queue]
D -->F[Dynamics 365 creates a review case based on the Knowledge Base Article Review Template]
E -->F[A customer success agent assigns themself as the owner for the article]
F -->G[[D365 sends a notification of the new owner to the TDT email]]
G -->H[In Madcap Central, the Flare author reassigns article review from the cus success email to the assigned Owner for the review case]
H -->I[Agent completes review in Madcap Central and submit it to Flare Author]
I -->J[Agent closes the review case in D365]
J -->K[Flare author receives notification of returned review via Madcap Central email]
K -->L[Flare author implements changes in Flare and accepts the file]
L -->M[Flare author synchronizes project with source control]
:::

Markdown editor and preview side by side

A: For Azure DevOps Services' Wiki, adding this line works with your chart. It's line #3 in the full chart source below.

*

*%%{init: {"flowchart": { "useMaxWidth": false } }}%%
Full Chart Source
::: mermaid
graph TD
%%{init: {"flowchart": { "useMaxWidth": false } }}%%
A[Author sends a review to the customer success email] -->|Dynamics 365 creates a review case based on the Knowledge Base Article Review Template| B[[Automation]]
B --> D[D365 creates a review case based on the Knowledge Base Article Review Template]
B --> E[D365 places the review article in the Article Review Queue]
D -->F[Dynamics 365 creates a review case based on the Knowledge Base Article Review Template]
E -->F[A customer success agent assigns themself as the owner for the article]
F -->G[[D365 sends a notification of the new owner to the TDT email]]
G -->H[In Madcap Central, the Flare author reassigns article review from the cus success email to the assigned Owner for the review case]
H -->I[Agent completes review in Madcap Central and submit it to Flare Author]
I -->J[Agent closes the review case in D365]
J -->K[Flare author receives notification of returned review via Madcap Central email]
K -->L[Flare author implements changes in Flare and accepts the file]
L -->M[Flare author synchronizes project with source control]
:::

This was a doozy to figure out. Lots of examples that don't readily apply to, or work with, Azure DevOps Wiki. Credit to #1758 Huge white margins on img/png output of large diagrams

axilleas Jun 20, 2021
Since mermaid 8.6.0, you can use directives straight into the diagram, without fiddling with JavaScript and CSS.
%%{init: {"flowchart": { "useMaxWidth": false } }}%%
graph LR

Note: I don't have access to Azure DevOps Server so I can't say whether it works there. Plus that might depend on the version you are using.


text:
Q: Shell Scripting editor in Ubuntu 13.10 I want to do some Shell Scripting on my Ubuntu 13.10 (32-bit) desktop. How can I create Shell Scripts using the editor. Since I am not familiar with the Ubuntu editor Gedit. Is it possible to do it with Vim. If yes, then which package would be suitable for me.

A: To install vim, do sudo apt-get install vim.
You don't need any other package if you want to write shell scripts. You can use vi <filename> to write the scripts and bash <filename> to execute the scripts using bash shell, sh <filename> to execute using sh shell, dash <filename> using dash.
If you need other shells like zsh, fish, etc., you'll need to install them using sudo apt-get install zsh or whatever package-name.


text:
Q: What math tool am I suppose to use? Which math tool am I supposed to use to solve this system?**
Given these coefficients , which is the combination of $(x , y , d)$ that satisfies these equations?
$$
\left\{
\begin{aligned}
5x+7y &=d \\
2x+y&=d\\
\end{aligned}
\right.
$$

A: $
\left\{
\begin{aligned}
5x+7y &=d \\
2x+y&=d\\
\end{aligned}
\right.
$ $\Leftrightarrow $ $
\left\{
\begin{aligned}
5x+7y &=d \\
14x+7y&=7d\\
\end{aligned}
\right.
$ $\Rightarrow 9x=6d \Rightarrow x=\frac{2}{3}d \Rightarrow y=-\frac{1}{3}d$


text:
Q: Nesting in Default Route I have an applications index page that lists all my applications. The index page is also the default route. I want to nest a 'applications new' modal in the index page. This way I can render the modal while on top of the index page. However, I'm not able to nest within the default route successfully.
Here's how I think it should work

<Route name='applications' path='/applications' handler={Applications}>
  <DefaultRoute name="index" handler={ApplicationIndex}>
    <Route name='applicationNew' path='/new' handler={ApplicationNewModal}/>
  </DefaultRoute>
  <Route name="applicationShow" path=':key' handler={ApplicationShow}/>
</Route>

When I try to transition to 'applicationNew' I get an error saying that no route was found with that name

A: You need to move it to its own Route inside a Route with handler={ApplicationIndex}.
<Route name='applications' path='/applications' handler={Applications}>
  <DefaultRoute name="index" handler={ApplicationIndex} />
  <Route handler={ApplicationIndex}>
    <Route name='applicationNew' path='/new' handler={ApplicationNewModal} />
  </Route>
  <Route name="applicationShow" path=':key' handler={ApplicationShow}/>
</Route>


text:
Q: CodeIgniter Image won't work in Project I have a piece of code in a file called tester.php that is in my root folder, and one copy of it in a CI view file. The file tester.php in root folder works as it should, but the code in the view ( or model, controller , no matter where in the acual CI) wont work.
using CI 2.2.0
why is this?
result on the root tester.php:

result in CI:

full code:
$imageurl = "http://www.example.net/images/images/ABImage_clock_4.jpg";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $imageurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);

$im = imagecreatefromstring ($data);

$bg = imagecolorallocate($im, rand(1,255), rand(1,255), rand(1,255));
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);

// output text.
$font = 'arial.ttf';

for ($i = 0; $i < 70; $i++) {
    imagesetthickness($im, rand(1, 3));
    $bg = imagecolorallocate($im, rand(1,255), rand(1,255), rand(1,255));

    imagearc(
        $im,rand(1, 300), // x-coordinate of the center.
        rand(1, 300), // y-coordinate of the center.
        rand(1, 300), // The arc width.
        rand(1, 300), // The arc height.
        rand(1, 300), // The arc start angle, in degrees.
        rand(1, 300), // The arc end angle, in degrees.
        $bg // A color identifier.
    );
}

header('Content-type: image/png');
imagepng($im);
imagedestroy($im);

UPDATE
There is no errors, and the imageurl does work, so its not the image link.
THE ISSUE:
when calling the tester.php from the root folder, it works perfect:
but when using the same code in a controller, view or model, it only produces
UPDATE 2:
Controller:
class antibot_interface_controller extends CI_Controller {

    function getImage() {
        $this->load->view('tester');
    }

}

View:
    <?

$imageurl = "http://www.textbasedmafiagame.com/images/images/ABImage_clock_4.jpg";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $imageurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);

$im = imagecreatefromstring ($data);

$bg = imagecolorallocate($im, rand(1,255), rand(1,255), rand(1,255));
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);

// set background colour.

// output text.
$font = 'arial.ttf';
// imagettftext($im, 35, 0, 10, 55, $color, $font, 'ABCD');

for ($i = 0; $i < 70; $i++) {
    imagesetthickness($im, rand(1, 3));
    $bg = imagecolorallocate($im, rand(1,255), rand(1,255), rand(1,255));

    imagearc(
        $im,rand(1, 300), // x-coordinate of the center.
        rand(1, 300), // y-coordinate of the center.
        rand(1, 300), // The arc width.
        rand(1, 300), // The arc height.
        rand(1, 300), // The arc start angle, in degrees.
        rand(1, 300), // The arc end angle, in degrees.

        $bg // A color identifier.
    );
}

header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);

route:
$route['antibot/antibot_image'] = "antibot/antibot_interface_controller/getImage";

EDIT3:
I tried to remove files to check if its not working. but as far i can see it is:
$autoload['model'] = array('cartheft/garage_model');
when that model is there, the image is not showing.
when i remove that model, it will work fine.
the garage_model file:
<?

class Garage_model extends CI_model {

}

A: This demonstrates one possible way to do this using a typical MVC file pattern using Codeigniter. (Tested with Codeigniter 3.0.2 and PHP 5.6.14)
The following 'controller' is at root/application/controllers/imagetest.php

if(!defined('BASEPATH')){ exit('No direct script access allowed'); }

class Imagetest extends CI_Controller
{
  private $imageurl;
  public function __construct()
  {
    parent::__construct();
    //Using an actual image I know exists
    $this->imageurl = "http://www.rapidsriders.org/images/PAC_logos/ACA_PAC_blue_sm.jpg";
  }

  public function index()
  {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $this->imageurl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
    $data = curl_exec($ch);
    curl_close($ch);

    $im = imagecreatefromstring($data);

    $bg = imagecolorallocate($im, rand(1, 255), rand(1, 255), rand(1, 255));
    $white = imagecolorallocate($im, 255, 255, 255);
    $black = imagecolorallocate($im, 0, 0, 0);

    // output text.
    $font = 'arial.ttf';

    for($i = 0; $i < 70; $i++)
    {
      imagesetthickness($im, rand(1, 3));
      $bg = imagecolorallocate($im, rand(1, 255), rand(1, 255), rand(1, 255));

      imagearc(
        $im, rand(1, 300), // x-coordinate of the center.
        rand(1, 300), // y-coordinate of the center.
        rand(1, 300), // The arc width.
        rand(1, 300), // The arc height.
        rand(1, 300), // The arc start angle, in degrees.
        rand(1, 300), // The arc end angle, in degrees.
        $bg // A color identifier.
      );
    }
    //pass the image resource to the view file
    $image['im']= $im;
    $this->load->view('imageview', $image);
  }

}

This 'view' file is at root/application/views/imageview.php
<?php
//Because Codeigniter uses output buffering when you load a view file
//and because the GD functions are sensitive to the buffer state
//we need to make sure the output buffer is clear.
//Otherwise imagepng() will probably fail.
ob_clean();
//note use of Codeigniter output class to set header.
$this->output->set_content_type('image/png');
//This would work too, but why not utilize Codeigniter's libraries
//header('Content-type: image/png');
imagepng($im);
imagedestroy($im);

Run this with yourURL/imagetest
PLAN B:
Is a revision on my first answer.
I added some error checking and abandoned the use of a "view" for the moment.
I'm pretty sure the problem is related to output buffering so be sure to keep the line ob_clean(); just before the header is sent. I consistently get the missing image placeholder if this is omitted.
Use this code for a new version of imagetest.php
if(!defined('BASEPATH')){
  exit('No direct script access allowed');
}

class Imagetest extends CI_Controller
{
  private $imageurl;

  public function __construct()
  {
    parent::__construct();
    $this->imageurl = "http://www.textbasedmafiagame.com/images/images/ABImage_clock_4.jpg";
  }

  public function index()
  {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $this->imageurl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
    $data = curl_exec($ch);
    if($data === FALSE){
      exit('Curl error: '.curl_error($ch));
    }
    curl_close($ch);

    $im = imagecreatefromstring($data);// or die('bad url:'.$this->imageurl);

    if ($im !== false) {
      for($i = 0; $i < 70; $i++){
        imagesetthickness($im, rand(1, 3));
        $bg = imagecolorallocate($im, rand(1, 255), rand(1, 255), rand(1, 255));

        imagearc(
          $im, rand(1, 300), rand(1, 300), rand(1, 300),
          rand(1, 300), rand(1, 300), rand(1, 300), $bg);
      }
      ob_clean(); //without this the GD functions (like imagepng) tend to fail using CI
      header("Content-type: image/png");
      imagepng($im, NULL, 0, NULL);
      imagedestroy($im);
    }
    else{
      echo 'imagecreatefromstring() error.';
    }
  }
}

Put this file in the folder root/application/controllers/
Go to http://www.textbasedmafiagame.com/imagetest in your browser.


text:
Q: Class expected error. Need Help with simple program When I run this program I get these errors:
Testscore.java:26: class expected
           grade = double.parseDouble(strInput);
                          ^
Testscore.java:26: ';' expected
           grade = double.parseDouble(strInput);
                                     ^
Testscore.java:26: not a statement
           grade = double.parseDouble(strInput);
                                      ^
Testscore.java:26: ';' expected
           grade = double.parseDouble(strInput);
                                              ^
4 errors

Do I have double.parseDouble(strInput); correct??
import javax.swing.*;
import java.lang.IllegalArgumentException;

public class Testscore
{
   public static void main(String[] args)
    {
       int numberofTests = 0;

       double grade = new double[numberofTests];

       double startgrade = 0;

       String strInput;

    // Get how many tests are used

       strInput = JOptionPane.showInputDialog(null, "How many tests do you have? ");
       numberofTests = Integer.parseInt(strInput);

       grade = new double[(int) numberofTests];

       for (int index = 0; index < grade.length; index++)
       {
           strInput = JOptionPane.showInputDialog(null, "Enter Test Score." + (index + 1));
           grade = double.parseDouble(strInput);

           if (grade[index] < 0|| grade[index] > 100 )
           {
               try
                {
                   throw new InvalidTestScore();
                }

               catch (InvalidTestScore e)
               {
                   e.printlnStackTrace();
               }
           }
       }

       for (int index = 0; index < grade.length; index++ )

            {
                startgrade += grade[index];
            }

            average = startgrade/grade.length;

            System.out.print("The average is: " + average);

    }
}

A: It's Double, with capital D
Note the distinction between double and Double. the "small" double is the primitive type. The other is a class - java.lang.Double. You can invoke methods like parseDouble(..) on the class, not the primitive. The "big" double is also called "wrapper class", because it wraps the primitive type into a class.


text:
Q: controlling which JUnit tests are run by Ant I have an ant task set up like so:
<target name="unit-test" description="unit tests" depends="compile-tests">
   <mkdir dir="${build}/test"/>
   <mkdir dir="${build}/test/raw"/>
   <mkdir dir="${build}/test/reports"/>

   <!-- set up scratch database for tests -->
   <mkdir dir="${build.dbTest}" />

  <junit printsummary="yes" haltonfailure="no" maxmemory="512m" >
   <classpath>
     <pathelement path="${java.class.path}"/>
     <pathelement path="${build.classes}"/>
     <pathelement path="${build.test-classes}"/>
     <fileset dir="lib" includes="*.jar"/>
     <fileset dir="lib-test" includes="*.jar"/>
   </classpath>
   <formatter type="xml"/>
   <sysproperty key="derby.system.home" value="${build.dbTest}" />
   <batchtest fork="yes" todir="${build}/test/raw">
     <fileset dir="${src.test}">
       <include name="**/*Test.java"/>
     </fileset>
   </batchtest>
 </junit>
  <junitreport todir="${build}/test">
   <fileset dir="${build}/test/raw"/>
   <report todir="${build}/test/reports"/>
 </junitreport>
</target>

Which works pretty well for running all my tests, but running all my tests really slows down my TDD Fail-Pass-Refactor groove.  My full test suite takes about six minutes to run, which is way too long for quick response changes during TDD, especially since most of the time I only care about results from one test.  The work flow I'd like to have would be

*

*create test for new feature/bug

*run only the new test (or at most only the test class I just modified)

*write some code

*iterate 2-3 until the new tests are passing

*run full set of tests to make sure nothing else broke

*plug any broken test into the 2-3 cycle above and repeat full cycle

*when all tests pass, declare victory.

TestNG seems to have capability for grouping tests, which seems ideal (I could have a "TDD" group for the tests I'm currently working with.  Changing that when I start working on something is an acceptable level of manual configuration here), but I don't want to switch test frameworks unless I absolutely have to.  Is there any way to do something similar, or another way to achieve my desired work flow, using JUnit?

A: I use in my scripts instead of
<include name="**/*Test.java"/>

the snippet
<include name="${test}"/>

and set the property test to **/*Test.java earlier in the script. Now I can start ant, setting the property to a different value:
ant test -Dtest=**/*AcceptanceTests.java


text:
Q: Is there a way to keep Laravel route caching automated? My Laravel project would auto-cache whenever I added routes.
However, my other Laravel projects do not auto-cache, I have to manually cache the routes using php artisan route:cache.

A: Use cron job on production if u need to do it on specific period of time:
Read more here on setting it up in laravel project (it's pretty straightforward)
Then on server u add a cron job like this:
* * * * * cd /var/www/ && php artisan schedule:run >> /dev/null 2>&1

A: Same thing happened to me also when I did
php artisan optimize
I had to run optimize command whenever I added a New route.
if you want PHP to solve you problem run.
php artisan route:clear
solved my problem.


text:
Q: R Dataframe comparison which, scaling bad The idea is extracting the position of df charactes with a reference of other df, example:
L<-LETTERS[1:25]
A<-c(1:25)
df<-data.frame(L,A)
Compare<-c(LETTERS[sample(1:25, 25)])
df[] <- lapply(df, as.character)
for (i in 1:nrow(df)){
  df[i,1]<-which(df[i,1]==Compare)
}
head(df)

   L A
1 14 1
2 12 2
3  2 3

This works good but scale very bad, like all for, any ideas with apply, or dplyr?
Thanks

A: Just use match
Your data (use set.seed when providing data using sample)
df <- data.frame(L = LETTERS[1:25], A = 1:25)
set.seed(1)
Compare <- LETTERS[sample(1:25, 25)]

Solution
df$L <- match(df$L, Compare)
head(df)
#    L A
# 1 10 1
# 2 23 2
# 3 12 3
# 4 11 4
# 5  5 5
# 6 21 6


text:
Q: Display DB2 time in PHP I am inserting the time values as
<?php $time = date("H").date("i").date("s"); ?>

in DB2 database field, that has the datatype as 6 S (Length=6, Type=Signed). So for the time of 6:54 PM, i see that the value is stored as some numeric figure, like: 185,414.
I want to display back the original value in php.
How do i correctly parse the numeric time value and show that in php ?

A: Well, i went nuts figuring out the solution, which is rather as simple as removing the commas from the string, and formatting it to display like: hh:mm:ss


text:
Q: Skipping the second automatically generated quote in QtCreator When I begin my program and type
cout << "

it automatically puts the closing quote ("") and places the cursor in the middle, which is nice; however, I can't seem to find a way to get past the second one without having to move my hand to use the arrow keys, use the mouse, or put another " manually, which defeats the purpose.
My buddy said tab should skip it, but it just does an indent.

A: I am sorry if this sounds disappointing, but there is no other way than using:
a) arrow key.
b) end button on the keyboard in the regular way.
c) typing another quote.
Basically what you also mentioned yourself in the question. Even if the tab was working, you would not spare anything as you already have at least two keys with which you get over.


text:
Q: "the movie" vs "an amazing movie"
Did you see the movie about Dian Fossey's work with mountain gorillas?   It was an amazing film.

Why is the indefinite article, an, used in the second sentence?
It's the same film they are talking about. Is it because the descriptive adjective in front of the noun?

A:
Did you see the movie about Dian Fossey's work with mountain gorillas? It was an amazing film.

No, DaBu. Without the descriptive adjective (amazing) we would also place the indefinite article there:

Did you see the movie about Dian Fossey's work with mountain gorillas? It was a film.

It's because in the second sentence we are using the pronoun it to refer to that particular movie, and then we give a description to it (the movie): it belongs to a group of films we would call amazing. There could be hundreds of amazing films, and it is part of that multitude.
Since there are many amazing films in existence, we use the indefinite article.
We could rephrase the sentences thus, putting "the film" instead of "it":

Did you see the movie about Dian Fossey's work with mountain gorillas? The film was an amazing film.

See?
But we can make the second sentence use the with amazing film if we make "the amazing film" the unique referent to "the movie":

Did you see the movie about Dian Fossey's work with mountain gorillas? The amazing film is a 3-hour long cinematic feast.


text:
Q: Limit of a double sequence Let $A<B$ and $(a_{n,m})_{n,m\geq 1}\subset \mathbb{R}$ a double sequence satisfying:
(1) For any fixed $m\geq 1$, the sequence $(a_{m,n})_{n\geq 1}$ is strictly increasing and $\lim_{n\rightarrow \infty}a_{m,n}=B$
(2) For any fixed $n\geq 1$, the sequence $(a_{m,n})_{m\geq 1}$ is strictly decreasing and $\lim_{m\rightarrow \infty}a_{m,n}=A$
Then, it is true that there is $k\geq 0$ such that
$\lim_{m\rightarrow \infty} a_{m,m+k}=\lim_{m\rightarrow \infty} a_{m,m+k+1}\neq A,B$
or
$\lim_{m\rightarrow \infty} a_{m+k,m}=\lim_{m\rightarrow \infty} a_{m+k+1,m}\neq A,B$ ?
Thanks in advances for you comments.

A: For $A < B$ and any real number $c > 0$ the double sequence
$$
 a_{m,n} = \frac{Bm + cAn}{m + cn}
$$
satisfies the hypotheses, but
$$
 \lim_{m\to \infty} a_{m,m} = \frac{B+cA}{1+c}
$$
can take any value in $(A, B)$.
Counter-examples to your updated question are
$$
 b_{m,n} = \frac{Be^m + An}{e^m + n} \, , \quad  c_{m,n} = \frac{Bm + Ae^n}{m + e^n}
$$
where
$$
 \lim_{m\to\infty} b_{m+k,m+l} = B  \, , \quad \lim_{m\to\infty} c_{m+k,m+l} = A
$$
for all $k, l \ge 0$.


text:
Q: how to clean the libs and headers files installed in yocto sysrootdir I have  compiled  the yocto fido and i want to clean required libs in tmp/sysrootdir instlled by some recipes like qtbase-native. can anyone guide me how to do that any particular commands are present or I need to delete manually ?
Thanks!

A: I'm afraid that Yocto does not provide any build in solution for cleaning files from shared headers area like tmp/sysroots/.
Indeed please familiar with this do_clean tasks (there exist 3 of them) which are available for every recipe: http://www.yoctoproject.org/docs/2.4.1/ref-manual/ref-manual.html#ref-tasks-clean

A: The easiest way is to delete tmp/.  It will be rebuild very quickly from sstate-cache.


text:
Q: Cannot show legend in Sencha Chart I've implemented a Chart that needs to be populated after its creation.
Here is a snip of the object i created:
       MyApp.views.chartPanel = new Ext.chart.Panel({
       id: 'chartPanel',
       title: 'Pie Chart',
       items: {
            cls: 'pie1',
            theme: 'Demo',
            store: null,
            shadow: false,
            animate: false,
            insetPadding: 20,
            legend: {
                position: 'top'
            },

.....

    pass: function(id) {
            MyApp.views.chartPanel.items.items[0].bindStore(getData(id));

        }

The pass function is invoked and chart is populated but i cannot see the legend that is shown only if the users double-click on the window and resets the chart.
How can i correctly show the legend?

A: Add the following in your series config:
series: [{
    type: 'pie',
    ....
    showInLegend: true,
    label: {
        field: 'name'
    }
}]


text:
Q: Connection refused while web scraping using HTMLUnit I am trying to build a java application to scrape a website using HTMLUnit. After extracting some data the application encounters following exception -
java.lang.RuntimeException: org.apache.http.conn.HttpHostConnectException: Connection to siteURL refused.
If I run application again, it is able to extract some data again before failing with the same exception. Probably the server see lot of requests from same client IP and refuses connection for a request.
Also, when application encounters this problem, I am able to connect to the site using a browser.
How can I overcome this problem? In web scraping applications how are such problems approached and resolved?

A: This is how I debug such issues :
Download Fiddler
By default, fiddler listens on port 8888, all you have to do, is configure webClient to use fiddler as proxy & then all requests being sent can be seen (analyzed, modified & re-sent too) in fiddler.
    client.getOptions().setProxyConfig(new ProxyConfig("127.0.0.1", 8888));

From what I can say from my previous experience is that the target site blocks after some-time, you can try adding a pause or rotating proxies & user-agents. You can also try clearing cookies.


text:
Q: Parsing anchor tag and tbody with ElementTree This is with reference to - Iterate over python dictionary to retrieve only required rows
My HTML is being formatted by external application as below -
When I process this HTML input with below code
        from xml.etree import ElementTree as ET

        s = """

            Release
            REFDB
            URL

            3.7.3

12345

232323

4343454

5454554

http://google.com

http://test12213.com

            3.7.4

456789

54545

5454545

545454

            http://foo.com

        """
        def find_version(ver):
            table = ET.XML(s)
            rows = iter(table)
            headers = [col.text for col in next(rows)]
            for row in rows:
                values = [col.text for col in row]
                out = dict(zip(headers, values))
                if out['Release'] == ver:
                    return out

            return None

        res = find_version('3.7.3')
        if res:
            for x in res.items():
                print(' - '.join(x))
        else:
            print ('Version not found')

I get below output:
trs: [<Element 'th' at 0x0431CDE0>, <Element 'th' at 0x0431CE40>, <Element 'th' at 0x0431CEA0>]
ths: []
tds: []
out: OrderedDict()
Traceback (most recent call last):
  File "parse_html.py", line 141, in <module>
    res = find_version(ver)
  File "parse_html.py", line 136, in find_version
    if out['Release'] == ver:
KeyError: 'Release'

A: Without comment - see code and print() results.
from xml.etree import ElementTree as ET

s = '''

            Release
            REFDB
            URL

            3.7.3
            12345
            http://google.com

            3.7.4
            456789
            http://foo.com

'''

# --- functions ---

def find_version(ver):
    table = ET.XML(s)

    #rows = iter(table)
    #trs = list(next(rows))
    trs = table.getchildren()[0].getchildren()
    print('trs:', trs)

    #ths = [th.text for th in iter(trs[0])]
    ths = [th.text for th in trs[0].getchildren()]
    print('ths:', ths)

    for tr in trs[1:]:
        tds = []
        #for col in iter(tr):
        for col in tr.getchildren():
            text = " ".join(col.itertext()).strip()
            tds.append(text)
        print('tds:', tds)

        out = dict(zip(ths, tds))
        print('out:', out)

        if out['Release'] == ver:
            return out

# --- main ---

res = find_version('3.7.3')

if res:
    for key, val in res.items():
        print(key, '-', val)
else:
    print ('Version not found')

Result
trs: [<Element 'tr' at 0x7f26d73005e8>, <Element 'tr' at 0x7f26d7300e08>, <Element 'tr' at 0x7f26d7300868>]
ths: ['Release', 'REFDB', 'URL']
tds: ['3.7.3', '12345', 'http://google.com']
out: {'URL': 'http://google.com', 'REFDB': '12345', 'Release': '3.7.3'}
URL - http://google.com
REFDB - 12345
Release - 3.7.3

EDIT: Version for new HTML.
I skiped getchildren() but it works the same way using only indexes. And it's shorter. But it's more readable using findall()
from xml.etree import ElementTree as ET

s = '''

            Release
            REFDB
            URL

            3.7.3

12345

232323

4343454

5454554

http://google.com

http://test12213.com

            3.7.4

456789

54545

5454545

545454

            http://foo.com

'''

# --- functions ---

def find_version(ver):
    table = ET.XML(s)

    # headers
    #ths = [th.text for th in table[0][0]]
    ths = [th.text for th in table.findall('.//th')]
    #print('ths:', ths)

    # rows
    #for tr in table[1]:
    for tr in table.findall('.//tbody/tr'):
        data = []

        # first col
        data.append(tr[0].text)

        # second col
        data.append([x.text for x in tr[1]])

        # third col
        temp = []
        for x in tr[2]:
            if x.tag == 'a':
                temp.append(x.text)
            else:
                temp.append(x[0].text)
        data.append(temp)

        #print('data:', data)

        # dictionary
        out = dict(zip(ths, data))
        #print('out:', out)

        if out['Release'] == ver:
            return out

# --- main ---

res = find_version('3.7.3')

if res:
    for key, val in res.items():
        print(key, '-', val)
else:
    print ('Version not found')

Result
Release - 3.7.3
REFDB - ['12345', '232323', '4343454', '5454554']
URL - ['http://google.com', 'http://test12213.com']

A: I put your input data in "data.xml" in the same folder, then you could try the following code, it works in my computer (It doesn't have enough exception check, but it should be enough to show the right way)
from xml.etree import ElementTree as ET

filename = "data.xml"
tree = ET.ElementTree(file=filename)

def find_version(ver, tree):
    table = tree.getroot()
    print table
    headers = []
    for tbody in table:
            for tr in tbody:
                    values = []
                    value_flag = True
                    for elem in tr.iter():
                            if elem.tag == 'th':
                                    headers.append(elem.text)
                                    value_flag = False
                            elif elem.tag == 'td':
                                    if not elem.text:
                                            values.append(elem[0].text)
                                    else:
                                            values.append(elem.text)
                    if value_flag:
                            out = dict(zip(headers, values))
                            if out['Release'] == ver:
                                    return out

res = find_version('3.7.3', tree)
if res:
    print res
    for x in res.items():
            print(' - '.join(x))
else:
    print ('Version not found')

Output:
Release - 3.7.3
URL - http://google.com
REFDB - 12345

~


text:
Q: How to destroy variable when change URL (any browser) in JavaScript or Jquery Today use this Code but this code some time not properly work
Problem : Page refresh then call unload() but some time user change URL directly at that time not call unload() because website change...
So, How to solve it in all Browser. Please Help Me
<html>
    <head>
        <script type="text/JavaScript">
            function unload(){
                alert("My Page unLoad - Destroy Variable");
            }

            function load() {
                alert("My Page Load");
            }
        </script>
    </head>

    <body onLoad="load()">
        <script type="text/javascript">
            window.onbeforeunload = unload();
        </script>
    </body>
</html>

A: HTTP is stateless, so on every new page the variables will begin in their uninitialised state, and all code set to run on load (ie. not in an event handler) will run.
If you are using localstorage:
Check this question on how to detect changes in the url: How to detect URL changes with jQuery
Then use this to destroy it:
 window.localStorage.removeItem(key);


text:
Q: Creating Android layout with java code in android How can I add one TextView with the image in this.I want to add a TextView below the imageView.
   public View getView(int position, View convertView, ViewGroup parent) {
     ImageView imageView;

   if (convertView == null) {
        imageView = new ImageView(mContext);
       imageView.setLayoutParams(new GridView.LayoutParams(400, 400));
       imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setPadding(8, 8, 8, 8);
        } else {
      imageView = (ImageView) convertView;
   }

     imageView.setImageResource(mThumbIds[position]);

     return imageView;
    }

A:      LinearLayout LL = new LinearLayout(this);
     LL.setOrientation(LinearLayout.VERTICAL);

     LayoutParams LLParams = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);

     LL.setLayoutParams(LLParams);

           ImageView imageView = new ImageView(mContext);

           //....your imageview code.......

           TextView textView = new TextView(mContext);

           //....your textview code.......

     LL.addView(imageview);
     LL.addView(textview);

A: You should use the xml layout editor to create your Grid's row and use an inflater to retrive the View Java's object. Programmatically, something like
LinearLayout parent = new LinearLayout(context);

parent.setLayoutParams(new GridView.LayoutParams(400, 400));
parent.setOrientation(LinearLayout.VERTICAL);

TextView textView = new TextView(context);
textView.setId(1)
ImageView imageView = new ImageView(mContext);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
imageView.setId(0);

parent.addView(imageView);
parent.addView(textView);

should do it.
parent is what your getView will return. Of course you will have to change the cast from ImageView to LinearLayout. you can use findViewById with 0 and 1, to retrieve respectively the ImageView and the TextView, or getChildAt(0) and getChildAt(1) to do the same thing


text:
Q: Как объединить 60000 файлов в один файл? В директории есть порядка 60000 текстовых файлов, их надо объединить в один файл.
Команда:
cat * > all.txt

не срабатывает:
-bash: /bin/cat: Argument list too long

Попробовал через:
find ./ -name '*.txt' | xargs grep '' > ../all.txt

но столкнулся с тем, что в all.txt записывается и путь, и название файла:
.//file1.txt:row1
.//file1.txt:row2
...

Какие еще могут быть варианты?

A: touch ../all.txt
find ./ -name "*.txt" | xargs cat >> ../all.txt

То есть cat каждого файла по отдельности, а не сразу всех в одной команде cat.

A: воспроизводим ситуацию (у меня получилось с чуть большим количеством файлов):
$ for i in $(seq 1 600000); do echo $i > $i.txt; done
$ ls | wc -l
600000
$ cat *.txt > spisok
bash: /bin/cat: Argument list too long

будем добавлять содержимое в файл, который не подпадает под маску *.txt — это полезное условие, которое помогает избежать некоторых неприятностей.
очень быстро и наиболее оптимально, вероятно, сделать примерно так (wc -l файл — это подсчёт количества строк в файле):
$ find -name \*.txt -exec cat {} > spisok +
$ wc -l spisok
600000 spisok
$ head -n 3 spisok
200784
59591
584250

хм. файлы читались явно не по алфавитном порядку.
если так не пойдёт, то придётся применить менее оптимальное решение с сортировкой и командой xargs:
$ find -name \*.txt | sort | xargs -I{} cat {} > spisok
$ wc -l spisok
600000 spisok
$ head -n 3 spisok
100000
100001
100002

теперь файлы читаются (и записываются) по (алфавитному) порядку.


text:
Q: How to disable Ctrl+U using Javascript I just want to disable Ctrl+U and Ctrl+C event. The primary purpose of doing this is, preventing users from downloading any image or copying content from my website easily i.e. pressing Ctrl+U for viewing my webpage's source code or pressing Ctrl+C for copying content directly from my webpage.
Currently, I am using this piece of code but it disables my entire keyboard
 <script>
    /*function check(e)
    {
    alert(e.keyCode);
    }*/
    document.onkeydown = function(e) {
            if (e.ctrlKey && (e.keyCode === 67 || e.keyCode === 86 || e.keyCode === 85 || e.keyCode === 117)) {//Alt+c, Alt+v will also be disabled sadly.
                alert('not allowed');
            }
            return false;
    };
    </script>

A: This is finally what I got to disable Ctrl+U:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
document.onkeydown = function(e) {
        if (e.ctrlKey &&
            (e.keyCode === 67 ||
             e.keyCode === 86 ||
             e.keyCode === 85 ||
             e.keyCode === 117)) {
            return false;
        } else {
            return true;
        }
};
$(document).keypress("u",function(e) {
  if(e.ctrlKey)
  {
return false;
}
else
{
return true;
}
});
</script>

A: Its simple just use the following code it will disable only Ctrl+U while Ctrl+C, Ctrl+V, Ctrl+S etc will works fine:
<script>
document.onkeydown = function(e) {
        if (e.ctrlKey &&
            (e.keyCode === 85 )) {
            return false;
        }
};
</script>

A: Your problem is the return statement.
Though I would suggest you use addEventListener and the like, this is a working copy of your code:
document.onkeydown = function(e) {
        if (e.ctrlKey &&
            (e.keyCode === 67 ||
             e.keyCode === 86 ||
             e.keyCode === 85 ||
             e.keyCode === 117)) {
            alert('not allowed');
            return false;
        } else {
            return true;
        }
};

A: try check this link from jsfiddle.
js

shortcut.add("Ctrl+U",function(){
     alert('Sorry\nNo CTRL+U is allowed. Be creative!')
    }),

it will simple show and error when you try to hit Ctrl+U on your keybord
But check the link, there is alot of code

A: This will Disable Ctrl + U and Right-click (make sure it's at the top of all your code) :
<!-- Disable CTRL U and Right Click -->
<script>
  document.onkeydown = function(e) {
    if (e.ctrlKey && e.keyCode === 85) {
      return false;
    }
  };
</script>
<body oncontextmenu="return false;"></body>

<!-- disable CTRL U and Right Click -->

A: To disable right click
document.addEventListener('contextmenu', event => event.preventDefault());

To disable F12 options
document.onkeypress = function (event) {
event = (event || window.event);
if (event.keyCode == 123) {
return false;
}
}

document.onmousedown = function (event) {
event = (event || window.event);
if (event.keyCode == 123) {
return false;
}
}
document.onkeydown = function (event) {
event = (event || window.event);
if (event.keyCode == 123) {
return false;
}
}

To Disable ctrl+c, ctrl+u
jQuery(document).ready(function($){
$(document).keydown(function(event) {
var pressedKey = String.fromCharCode(event.keyCode).toLowerCase();

if (event.ctrlKey && (pressedKey == "c" || pressedKey == "u")) {
alert('Sorry, This Functionality Has Been Disabled!');
//disable key press porcessing
return false;
}
});
});

A: you can use the below script
<script>
/*function check(e)
{
alert(e.keyCode);
}*/
 document.onkeydown = function(e) {
    if (e.ctrlKey && (e.keyCode === 67 || e.keyCode === 86 || e.keyCode === 85 ||     e.keyCode === 117 || e.keycode === 17 || e.keycode === 85)) {//ctrl+u Alt+c, Alt+v will also be disabled sadly.
        alert('not allowed');
    }
    return false;
};
</script>

A: Its simple just use the following code it will disable only Ctrl+U while Ctrl+C, Ctrl+V, Ctrl+S etc will works fine: but it will disable your page source too.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript" language="javascript"> $(function () { $(this).bind("contextmenu", function (e) { e.preventDefault(); }); }); </script>
   <script>
document.onkeydown = function(e) {
        if (e.ctrlKey &&
            (e.keyCode === 85 )) {
            return false;
        }
};
</script>


text:
Q: Using Cell Reference in Query formula - Google Sheets I have the following Query formula populating for items next to "Fruits".
=QUERY(Sheet1!$A$2:$C,"SELECT B, C WHERE A = 'Fruits' ",1)

I'd like to substitute the "Fruits" text value with a reference to a specific cell, like A2.
That way if I change the value in A2 from "Fruits" to "Fruit", I don't need to update the QUERY Formula
Here's a link to a sample sheet.
Thanks for your help.

A: Use below formula-
=QUERY(Sheet1!$A$2:$C,"SELECT B, C WHERE A = '" & A2 & "'",1)

A: I found the solution by playing around a bit. This is what worked:
=QUERY(Sheet1!$A$2:$C,"SELECT B, C WHERE A = '"&A2&"' ",1)


text:
Q: Is python parameters' default value accepted by args or kwargs? I found a strange instance when I try to make a testing decorator. code like this:
def doublefunc(fn):
    def warpped(*arg, **kwargs):
        arg = (i if type(i) is not int else i*2 for i in arg)
        for k, v in kwargs.iteritems():
            kwargs[k] = v *2 if type(v) is int else v
        return fn(*arg, **kwargs)
    return warpped

@doublefunc
def add(x, y, m, z=10, v='bbaa'):
    print 'x=%s, y=%s, m=%s, z=%s, v=%s' % (x, y, m, z, v)
    return x + y + z

when I call function like this:
print add(1, 1, 'teststring')

The returned value is 14 but not 24. That means the default value of parameter z in function add, is not accepted in decorator function inner. Why?

A: This is tricky, but you can get unpassed default arguments with some use of the inspect module
import inspect

def get_unpassed_defaults(fn, args, kwargs):
        args_len = len(args) + len(kwargs)
        argspec = inspect.getargspec(fn)

        defaults = argspec.defaults
        default_names = argspec.args[-len(defaults):]

        number_of_args = len(argspec.args)
        number_of_positional_args = number_of_args - len(argspec.defaults)
        number_of_kwargs = number_of_args - number_of_positional_args
        number_of_kwargs_passed_as_positional = len(args) - number_of_positional_args

        default_values = defaults[number_of_kwargs_passed_as_positional:]
        default_names = default_names[number_of_kwargs_passed_as_positional:]
        defaults_dict = dict(zip(default_names, default_values))

        for kwarg_name in kwargs:
            if kwarg_name in defaults_dict:
                defaults_dict.pop(kwarg_name)

        return defaults_dict

And then leverage this in doublefunc:
def doublefunc(fn):
    def wrapped(*arg, **kwargs):
        unpassed_defaults = get_unpassed_defaults(fn, arg, kwargs)
        kwargs.update(unpassed_defaults)

        arg = (i if type(i) is not int else i*2 for i in arg)
        for k, v in kwargs.iteritems():
            kwargs[k] = v *2 if type(v) is int else v

        return fn(*arg, **kwargs)
    return wrapped

@doublefunc
def add(x, y, m, z=10, v='bbaa'):
    print 'x=%s, y=%s, m=%s, z=%s, v=%s' % (x, y, m, z, v)
    return x + y + z

print add(1, 1, "teststring", v=3)

Gives:
x=2, y=2, m=teststring, z=20, v=6
24

A: The reason for this is that decorator function doesn't look for inner attributes (in this case default kwargs) of wrapped function. If you still want to do this then you just have to play with dictionaries.

Won't work with Python 2 because there is no getfullargspec method, so for that follow @Nolen Royalty's answer

For Python 3
>>> import inspect
>>> def doublefunc(fn):
        def wrapped(*arg, **kwargs):
            defaults = (inspect.getfullargspec(fn).kwonlydefaults)
            defaults.update(kwargs)
            kwargs = defaults
            arg = (i if type(i) is not int else i*2 for i in arg)
            for k, v in kwargs.items():
                kwargs[k] = v *2 if type(v) is int else v
            return fn(*arg, **kwargs)
        return wrapped

>>> @doublefunc
def add(x, y, m, *args, z=10, v='bbaa'):
    print('x={0}, y={1}, m= {2}, z={3}, v={4}'.format(x,y,m,z,v))
    return x + y + z

>>> print(add(1, 1, 'teststring', v=1))

Result:
x=2, y=2, m= teststring, z=20, v=2
24


text:
Q: how to disable past date in calendar extendar in asp.net? I want to know how to disable pasts date in calendar extender in asp.net Code behind. I want to do it code behind without using java scripts.

A: You can set the  StartDate property:
protected void Page_Load(object sender, EventArgs e)
{
      CalendarExtender1.StartDate = DateTime.Today;
}

http://www.advancesharp.com/blog/1002/disable-dates-in-ajax-calendarextender

A: Try to add this on page load:
Calendar1.StartDate = DateTime.Now;

A: The solution was a matter of search far from your end. Anyways here is the total solution
ASPX
<asp:CalendarExtenderID="Calendar1"runat="server"
Enabled="True" TargetControlID="TextBox1"Format="dd/MM/yyyy" ></asp:CalendarExtender>

CS
protected void Page_Load(object sender, EventArgs e)
{
    Calendar1.StartDate = DateTime.Now;   //to disable past Date
}

Documentation on Datetime:- https://msdn.microsoft.com/en-us/library/system.datetime(v=vs.110).aspx
Hope that helps you


text:
Q: Facebook feed with php and javascript I would like to share dynamic image with description on Facebook using PHP and Javascript. I have image.php which is generating image.
below code is generating image:
imagejpeg($jpg_image,$filename_result);

and javascript code for facebook calling is
 var obj = {
                method: 'feed',
                link: 'www.mysite.com',
                picture: 'image.php',
                name: 'Title',
                caption: 'Caption URL',
                description: 'Description'
            };

        FB.ui(obj, callback);

I want my image.php to return image to facebook dialog without creating file on server and calling like http..../myimage.jpg


text:
Q: "quotient" function for a specific system of representatives Let $X$ and $Y$ be two sets and $f: X \to Y$. Let $\sim$ be an equivalence relation on $X$. Please note that $f$ is not assumed to be compatible with $\sim$. Let $p: X \to X/\sim$ be the canonical projection to the quotient set. Let $r$ be a system of representatives, i.e. $r : X/\sim \to X$ such that, for any equivalence class $c \in X/\sim, r(c) \in c$.
Let $f_r = f \circ r \circ p$. Does someone know a standard terminology for this kind of object? I'd like to say something like "quotient of $f$ by $r$", "reduction of $f$ by $r$", etc.
Although I use this in a non-purely mathematical paper (about voting theory), I find it would be better to get inspiration from standard mathematical terminology if possible. Also, if there is no standard word for this, I would appreciate any suggestion that would help me not to break mathematical customs (for example, I suspect that "quotient" could be misleading).


text:
Q: Removing Texlive From Ubuntu 16.04 LTS (Installed using terminal, apt-get)
I am using TexLive 2015 and I would like to move on to 2016 or even better 2017. I read on internet that uninstalling and doing a fresh install is a better idea than upgrading TexLive, is it true?
Anyways I started looking for the ways to see how I can uninsntall TexLive from my ubuntu 16.04 LTS (64 bit) and I found this:
Open the link
I had installed Texlive using terminal so the path is \usr\share\texlive and not \usr\local\texlive as suggested in the above link.
My question is to uninstall TexLive, is it necessary to go through all those steps?
If yes, the only change I need to make in those commands is changing the path from \usr\local\texlive to \usr\share\texlive or I should change something more?
Thanks

A: Well as it turns out, to do the job of removing TexLive, one simply needs to:
sudo apt-get purge texlive-*
sudo apt-get autoremove
sudo apt-get autoclean

As suggested here
That's all!


text:
Q: Woocommerce variations as a list Is there away to list all variations of a product instead of using the dropdown.
each one showing its own image, name and qty, like the attache image.

thanks in advances


text:
Q: ValueError: Input 0 of layer sequential is incompatible with the layer: : expected min_ndim=4, found ndim=2. Full shape received: [None, 1]     file_list = []
    class_list = []

    DATADIR = "C://Users//SB//Python_Programs//Image_Classifications//Data"

    # All the categories you want your neural network to detect
    CATEGORIES = ["DealBills", "RX"]

    # The size of the images that your neural network will use
    IMG_SIZE = 299

    # Checking or all images in the data folder
    for category in CATEGORIES :
        path = os.path.join(DATADIR, category)
        for img in os.listdir(path):
            img_array = cv2.imread(os.path.join(path, img), cv2.IMREAD_GRAYSCALE)

    training_data = []

    def create_training_data():
        for category in CATEGORIES :
            path = os.path.join(DATADIR, category)
            class_num = CATEGORIES.index(category)
            for img in os.listdir(path):
                try :
                    img_array = cv2.imread(os.path.join(path, img), cv2.IMREAD_GRAYSCALE)
                    new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
                    training_data.append([new_array, class_num])
                except Exception as e:
                    pass

    create_training_data()

    random.shuffle(training_data)

    X = [] #features
    y = [] #labels

    for features, label in training_data:
        X.append(features)
        y.append(label)

    X = np.array(X).reshape(-1, IMG_SIZE, IMG_SIZE, 1)

    # Creating the files containing all the information about your model
    pickle_out = open("X.pickle", "wb")
    pickle.dump(X, pickle_out)
    pickle_out.close()

    pickle_out = open("y.pickle", "wb")
    pickle.dump(y, pickle_out)
    pickle_out.close()

    pickle_in = open("X.pickle", "rb")
    X = pickle.load(pickle_in)

    # Opening the files about data
    X = pickle.load(open("X.pickle", "rb"))
    y = pickle.load(open("y.pickle", "rb"))

    # normalizing data (a pixel goes from 0 to 255)
    X = X/255.0

    # Building the model
    model = Sequential()
    # 3 convolutional layers
    #model.add(Conv2D(32, (3, 3), input_shape = X.shape[1:]))
    model.add(Conv2D(32, (3, 3), input_shape = (299,299,1)))
    model.add(Activation("relu"))
    model.add(MaxPooling2D(pool_size=(2,2)))

    model.add(Conv2D(32, (3, 3)))
    model.add(Activation("relu"))
    model.add(MaxPooling2D(pool_size=(2,2)))

    model.add(Conv2D(64, (3, 3)))
    model.add(Activation("relu"))
    model.add(MaxPooling2D(pool_size=(2,2)))
    model.add(Dropout(0.25))

    # 2 hidden layers
    model.add(Flatten())
    model.add(Dense(128))
    model.add(Activation("relu"))

    model.add(Dense(128))
    model.add(Activation("relu"))

    # The output layer with 13 neurons, for 13 classes
    model.add(Dense(13))
    model.add(Activation("softmax"))

    # Compiling the model using some basic parameters
    model.compile(loss="sparse_categorical_crossentropy",
                    optimizer="adam",
                    metrics=["accuracy"])

    y = np.array(y)
    #X = np.array(X)

    #X = X.reshape(-1,IMG_SIZE,IMG_SIZE,1)

    # Training the model, with 40 iterations
    # validation_split corresponds to the percentage of images used for the validation phase compared to all the images
    history = model.fit(X, y, batch_size=10, epochs=20, validation_split=0.1)

    # Saving the model
    model_json = model.to_json()
    with open("model.json", "w") as json_file :
        json_file.write(model_json)

    model.save_weights("model.h5")
    print("Saved model to disk")

    model.save('CNN.model')

    ###
    # Printing a graph showing the accuracy changes during the training phase
    #print(history.history.keys())
    #plt.figure(1)
    #plt.plot(history.history['acc'])
    #plt.plot(history.history['val_acc'])
    #plt.title('model accuracy')
    #plt.ylabel('accuracy')
    #plt.xlabel('epoch')
    #plt.legend(['train', 'validation'], loc='upper left')
    ###

    CATEGORIES = ["DealBills", "RX"]
    def prepare(file):
        IMG_SIZE = 299
        img_array = cv2.imread(file, cv2.IMREAD_GRAYSCALE)
        new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
        return new_array.reshape(-1, IMG_SIZE, IMG_SIZE, 1)
    model = tf.keras.models.load_model("CNN.model")

    image = 'C://Users//SB//Python_Programs//Image_Classifications//Datasets//Images//DealBill//42979929_25.jpg' #your image path

    prediction = model.predict([image])
    prediction = list(prediction[0])
    print(CATEGORIES[prediction.index(max(prediction))])

Query - Please find above code. I am getting error
"ValueError: Input 0 of layer sequential is incompatible with the layer: : expected min_ndim=4, found ndim=2. Full shape received: [None, 1]" for line prediction = model.predict([image])

Can anybody please help, I am trying to build model for Document images like different forms, invoices to classify #different documents.

A: Tensorflow.Keras Conv2D expects input of shape 4-Dimension but in this case input is of shape 2D.
Conv2D Inputshape
4+D tensor with shape: batch_shape + (channels, rows, cols) if data_format='channels_first'
or 4+D tensor with shape: batch_shape + (rows, cols, channels) if data_format='channels_last'.
Add extra dimension to your input data
data = tf.expand_dims(data, axis =-1)


text:
Q: Calling SELECT * on a primary key versus an attribute in SQL I am currently studying for a final and have a question about one of the practice problems.
The problem states:
Consider the following two SQL queries over the relation R(A,B) where attribute A is the primary key.
Query 1: SELECT * FROM R WHERE B > 50 OR B <= 50
Query 2: SELECT * FROM R WHERE A > 50 OR A <= 50
Which is correct?
a. Queries 1 and 2 return all the records in R
b. Query 2 returns all the records in R, but Query 1 may not
The official answer says that b is correct, but I wanted to know why. I understand that a primary key must be unique, meaning Query 2 should return every record. But wouldn't query 1 also return every record even if there were duplicate B values?

A: The correct answer is the second, because A is a primary key and a primary key cannot be null, so
A > 50 OR A <= 50

will always be true, while the following:
B > 50 OR B <= 50

might be NULL if B is NULL
NULL > 50 OR NULL <= 50 ---> NULL

and rows whenever B is null won't be returned.

A: The only reason I can see why query 1 would not return some of the records is if column (or attribute as you call it) B is nullable.
When comparing null to any value in any rdbms I know you will never get correct results, since null is by definition an unknown value.
for example, if you add to your where clause and null = null you will get no results at all.
So any record where B is null would not be returned from the first query.
This cannot be the case for column A since it's the primary key, and a primary key can not be nullable by definition.

A: Absolutely not. What if there's a row with B null? It's not said that attribute B has to be not null, so query 1 will not return all rows with an empty (null) B value.
Instead, A is not nullable because it's the primary key.


text:
Q: Oracle 10g for Windows does not start up on system boot We have an Oracle 10g Enterprise Edition installation (10.2.0.1.0) on a Windows Server 2003 virtual machine. It was initially created with Virtual Server 2005 R2 SP1 but has now been migrated to Windows Server 2008 Hyper-V.
The services start on system boot, but the instance does not start up. This problem was actually occurring on Virtual Server after a migration from one server to another, but I managed to fix it then with:
oradim -edit -sid ORCL -startmode auto

However, this now has no effect.
oradim.log (in %OracleHome%\database\oradim.log) says:
Thu Jun 10 14:14:48 2010
C:\oracle\product\10.2.0\db_3\bin\oradim.exe -startup -sid orcl -usrpwd * -log oradim.log -nocheck 0
Thu Jun 10 14:14:48 2010
ORA-12560: TNS:protocol adapter error

sqlnet.log in the same folder has:
Fatal NI connect error 12560, connecting to:
 (DESCRIPTION=(ADDRESS=(PROTOCOL=BEQ)(PROGRAM=oracle)(ARGV0=oracleorcl)(ARGS='(DESCRIPTION=(LOCAL=YES)(ADDRESS=(PROTOCOL=beq)))'))(CONNECT_DATA=(SID=orcl)(CID=(PROGRAM=C:\oracle\product\10.2.0\db_3\bin\oradim.exe)(HOST=ORACLE-VM)(USER=SYSTEM))))

  VERSION INFORMATION:
        TNS for 32-bit Windows: Version 10.2.0.1.0 - Production
        Oracle Bequeath NT Protocol Adapter for 32-bit Windows: Version 10.2.0.1.0 - Production
  Time: 10-JUN-2010 14:14:48
  Tracing not turned on.
  Tns error struct:
    ns main err code: 12560
    TNS-12560: TNS:protocol adapter error
    ns secondary err code: 0
    nt main err code: 530
    TNS-00530: Protocol adapter error
    nt secondary err code: 2
    nt OS err code: 0

The ORA_ORCL_AUTOSTART registry value is set to TRUE, so it should be auto-starting - and you can see that it's trying to. The problem also occurs when stopping and restarting the OracleServiceORCL service.
I've enabled SQL*Net tracing which shows:
[10-JUN-2010 15:09:33.919] snlpcss: entry
[10-JUN-2010 15:09:34.419] snlpcss: Unable to spawn Oracle oracle     (DESCRIPTION=(LOCAL=YES)(ADDRESS=(PROTOCOL=beq))) orcl, error 2.
[10-JUN-2010 15:09:34.419] snlpcall: exit

On a hunch that error 2 is Windows error 2 (file not found) I tried restarting the service with Process Monitor watching oradim.exe, but this appears to delay things just enough that it always works.
Right now I have a horrible hack where I've created a Scheduled Task to run oradim -startup -sid ORCL when the Administrator account logs on, and set the VM to auto-logon. I'd still like to work out why it's not working.

A: It might be worth, for a test, adding a dependency to the service.  I'm wondering whether it's trying to start too early.  I've seen a similar problem in the past, and cannot remember what we did to fix it, but we now use the Oracle agent / Grid Control to bring the services up (i.e.: Agent => Auto start, Oracle => Manual, Etc).

A: run tnsping .
go to directory with parameters file sqlnet.ora
edit files tnsnames.ora & listener.ora
correct (HOST = your_db_host_name) to value returned by hostname command
run services.msc
restart oracle listener service named OracleOra....Listener & instance service named OracleService....


text:
Q: Function name in parentheses after function call in Python I ran into these lines of code in the QPYTHON Android app. They are part of a sample that uses the Bottle module to create a simple Web server that seems to work fine.
app = Bottle()
app.route('/', method='GET')(home)
app.route('/__exit', method=['GET','HEAD'])(__exit)
app.route('/__ping', method=['GET','HEAD'])(__ping)
app.route('/assets/<filepath:path>', method='GET')(server_static)

Now, I know that all the functions in parentheses after the call have already been wrapped with the @route decorator above this. For example:
@route('/__ping')
def __ping():
    return "ok"

But I have no idea what putting things in parentheses after other things does in Python, and after trying a hundred different permutations of "functions in parentheses after functions" I gave up.
I throw myself on the mercy of the Exchange.

A: This:
app.route('/', method='GET')(home)

... Is the same as this:
func = app.route('/', method='GET')
func(home)

In other words, app.route(...) returns a function, which is then called.

A: def a():
    def b(arg):
        return arg * 2
    return b

print(a()(5))

c = a()
print(c(5))

Output:
10
10

You are basically providing an argument for the function within the function, a.k.a inner function


text:
Q: Apache  RewriteRule unexpected behaviour when two rules match URL at one moment (add path info postfix) I'm playing with apache rewrite_mod (Apache/2.2.17 Win32) and encounter very weird behave of rewriteRule.

My script primarily rewrite infinite filter parameters named f1 .. f<infinity> from nice url and in loop adding them as query variables, add path as query, and page number.

It works flawlessly, but if I add one another rule (last rule in script)
RewriteRule   ^(.+)\.html$                       /index.php?path=$1.html [QSA]

which is for another cases, it change execution of rewriterule at start of script.

Input URL:
http://testing.loc/some/thing/index0-f1-nice-cars-f2-planes-f3-karts-f4-bike.html

Expected result in PHP after all rewrites:
$_SERVER[QUERY_STRING] => path=some/thing/&page=0&f1=nice-cars&f2=planes&f3=karts&f4=bike
$_SERVER[SCRIPT_NAME] => /index.php

Script look like this (next part is flawlessly functional):
# from: some/thing/index0-f1-nice-cars-f2-planes-f3-karts-f4-bike.html
# to:   some/thing/index0.html?f=-f1-nice-cars-f2-planes-f3-karts-f4-bike

RewriteRule   ^(.*/?index[0-9]*)((?:-f[0-9]+-.+?)+)\.html$   /$1.html?f=$2 [QSA]

# from: some/thing/index0.html?f=-f1-nice-cars-f2-planes-f3-karts-f4-bike
# to    index.php?path=some/thing/&page=0&f=-f1-nice-cars-f2-planes-f3-karts-f4-bike

#              (   $1   )     (  $2  )
RewriteRule   ^(.+/{0,1})index([0-9]*)\.html$    /index.php?path=$1&page=$2 [QSA]

# while in f is something like "f1-nice-cars" (for example)
# remove "f1-nice-cars" from f and add as query "f1=nice-cars"

#                              (%1)    (   %2  ) ( %3)(       %4       )
RewriteCond   %{QUERY_STRING} ^(.*)&f=-(f[0-9]+)-(.+?)((?:-f[0-9]+-.+)*)$
RewriteRule   ^index\.php$                       /index.php?%1&%2=%3&f=%4 [L]

# remove empty "f=" from query

RewriteCond   %{QUERY_STRING} ^(.*)&f=$
RewriteRule   ^index\.php$                       /index.php?%1

here, after rules is url in shape:
index.php?path=some/thing/&page=0&f1=nice-cars&f2=planes&f3=karts&f4=bike

Without next rule in script is everything perfectly functional. But if I add it, this rule itself do nothing, but rewrite_mod add something more to subtitution at start of script.
# rewrite rule for other paths without filters

RewriteRule   ^(.+)\.html$                       /index.php?path=$1.html [QSA]

Actually after run all script result is:
index.php?path=/some/thing/index0.html/some/thing/index0&f1=nice-cars&f2=planes&f3=karts&f4=bike

A: I found resolution of this problem.
When 2 rules match URL at one pass of .htaccess, then apache rewrite_mod use method "add path info postfix" (its something like bug or feature), which ruin path of request. So when I added flag [L] to that 2 rules, result is OK.
I thinked that apache pass .htaccess sequentially and does not matter on next rules...


text:
Q: Change what "ttt_radio traitor" says in GMod I want ttt_radio traitor to say something else than [name] is a traitor!
I've seen people do it with ttt_radio imwith where they changed it to I see [name]. How do I do it?

A: I think they just used the see name.
The console command used to send a quickchat is "ttt_radio". You need to supply which quickchat text to send by adding its name, for example: "ttt_radio help" to send the "Help!" chat. Binding that to a key could look like:
bind "h" "ttt_radio help"

Entered into the console of course. These are the possible quickchat names:
Name    Text
yes     Yes.
no      No.
help    Help!
imwith  I'm with (player you aim at).
see     I see (player you aim at).
traitor (player you aim at) is the traitor!
suspect (player you aim at) acts suspicious.
check   Anyone still alive?

Source: http://ttt.badking.net/help
So basically you have to bind "key" "ttt_radio name" in the console and it shouts the text when you press that key

A: Old question, but you can change the binds for things like this in /directory_path_to_game/lang/english.lua (if you're running a server with a foreign language, then substitute english.lua for *language*.lua) and it should be located on L.quick_traitor.


text:
Q: Angular JS : creating table with json I've created an application in angular-JS for creating table with dynamic columns from json
For example the JSON structure returning from a service is in the structure where the others field of the main JSON contains another JSON array which is the additional columns,
so all together there will be four additional dynamic columns i.e File 1, File 2, File 3, File 4 each object has value for the corresponding File field, sometime present sometime not present.
$scope.getColumns = function()
{
    //console.log( $scope.datas[0].others[0]);
  $scope.datas.resultsOrder = new Array();
     for ( var i = 0; i < $scope.datas.length; i++)
     {
       for ( var j = 0; j < $scope.datas[i].others.length; j++)
        {
        if (countInstances($scope.datas.resultsOrder, $scope.datas[i].others[j].id) < countInstances(
                    $scope.datas[i].others, $scope.datas[i].others[j].id)){
           $scope.datas.resultsOrder.push($scope.datas[i].others[j].id);
         }
        }
      }
$scope.datas.resultsOrder.sort(function(a, b){
    return a.localeCompare(b);
  });
return $scope.datas.resultsOrder;
}

I've shown the tables with the dynamic columns perfectly using javascript help, but can anyone please tell me some other way for creating the above dynamic table through angular js in a simple way, since in my code I've used javascript complex logic for the creation of dynamic columns which is as shown below
My JS-Fiddle is given below
Demo

A: This wll create an object called columns where the properties are the names of the dynamic columns ('File 1', 'File 2' etc.)
Controller:
$scope.columns = {};

angular.forEach( $scope.datas, function(data){

    angular.forEach( data.others, function(other){

        // Set the 'File x' property for each item in the others array
        data[other.id] = other.value;

        // Add the dyanmic column to the columns object
        $scope.columns[other.id] = null;
    });
});

View:

        {{column}}

....

{{val[column]}}

Fiddle


text:
Q: How can I pass the URL value into my combobox? I have the following URL: https://localhost:27635/Student/Create?PersonId=1
I also have a combobox filled with Persons which the user can use to select a Person. How can I set the combobox to have by default the PersonId from the URL?
This is the combobox code:
@Html.DropDownListFor(
    x => x.PersonId,
    new SelectList(Model.Persons, "Id", "Fullname", Model.PersonId),
    "-- Select --", new { @class = "form-control" }
)

It contains PersonIds, displaying the full name.
The reason I want to use a combobox instead of saving the value from the URL directly is because I want to allow the user to change.
Another thing im curious about is if its possible to have the default -- Select -- show up if the URL id is incorrect and not in the combobox.
Thanks

A: hello you can properly use something like the following post
basically there is an overload to the SelectList function you can find it in this link
so SelectList will take following
items (IEnumerable) - The items used to build each SelectListItem of the list.
dataValueField (String) - The data value field. Used to match the Value property of the corresponding SelectListItem.
dataTextField (String) - The data text field. Used to match the Text property of the corresponding SelectListItem.
dataGroupField (String) - The data group field. Used to match the Group property of the corresponding SelectListItem.
selectedValue (Object) - The selected value. Used to match the Selected property of the corresponding SelectListItem.
here is an example:
    @Html.DropDownListFor(
    m => m.CountryId, // Specifies where to store selected country Id
                      // It needs to be null for the default selection to work!

    new SelectList(Model.Countries, // IEnumerable<Country>, contains all countries loaded from a database
                   "Id",   // Use Country.Id as a data source for the values of dropdown items
                   "Name", // Use Country.Name as a data source for the text of dropdown items
                   13 // Specifies Australia (which has ID of 13) as the element selected by default
                   ),

    // Text of option that prompts user to select
    "- Please select your country -"
)