Programs & Examples On #Xml schema collection

Appending a line break to an output file in a shell script

You can do that without an I/O redirection:

sed -i 's/$/\n/' filename

You can also use this command to append a newline to a list of files:

find dir -name filepattern | xargs sed -i 's/$/\n/' filename

For echo, some shells implement it as a shell builtin command. It might not accept the -e option. If you still want to use echo, try to find where the echo binary file is, using which echo. In most cases, it is located in /bin/echo, so you can use /bin/echo -e "\n" to echo a new line.

Rails raw SQL example

I know this is old... But I was having the same problem today and found a solution:

Model.find_by_sql

If you want to instantiate the results:

Client.find_by_sql("
  SELECT * FROM clients
  INNER JOIN orders ON clients.id = orders.client_id
  ORDER BY clients.created_at desc
")
# => [<Client id: 1, first_name: "Lucas" >, <Client id: 2, first_name: "Jan">...]

Model.connection.select_all('sql').to_hash

If you just want a hash of values:

Client.connection.select_all("SELECT first_name, created_at FROM clients
   WHERE id = '1'").to_hash
# => [
  {"first_name"=>"Rafael", "created_at"=>"2012-11-10 23:23:45.281189"},
  {"first_name"=>"Eileen", "created_at"=>"2013-12-09 11:22:35.221282"}
]

Result object:

select_all returns a result object. You can do magic things with it.

result = Post.connection.select_all('SELECT id, title, body FROM posts')
# Get the column names of the result:
result.columns
# => ["id", "title", "body"]

# Get the record values of the result:
result.rows
# => [[1, "title_1", "body_1"],
      [2, "title_2", "body_2"],
      ...
     ]

# Get an array of hashes representing the result (column => value):
result.to_hash
# => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
      {"id" => 2, "title" => "title_2", "body" => "body_2"},
      ...
     ]

# ActiveRecord::Result also includes Enumerable.
result.each do |row|
  puts row['title'] + " " + row['body']
end

Sources:

  1. ActiveRecord - Findinig by SQL.
  2. Ruby on Rails - Active Record Result .

Can't access RabbitMQ web management interface after fresh install

If on Windows and installed using chocolatey make sure firewall is allowing the default ports for it:

netsh advfirewall firewall add rule name="RabbitMQ Management" dir=in action=allow protocol=TCP localport=15672
netsh advfirewall firewall add rule name="RabbitMQ" dir=in action=allow protocol=TCP localport=5672

for the remote access.

show dbs gives "Not Authorized to execute command" error

Create a user like this:

db.createUser(
      {
        user: "myUserAdmin",
        pwd: "abc123",
        roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
      }
    )

Then connect it following this:

mongo --port 27017 -u "myUserAdmin" -p "abc123" --authenticationDatabase "admin"

Check the manual :

https://docs.mongodb.org/manual/tutorial/enable-authentication/

Best way to test for a variable's existence in PHP; isset() is clearly broken

Try using

unset($v)

It seems the only time a variable is not set is when it is specifically unset($v). It sounds like your meaning of 'existence' is different than PHP's definition. NULL is certainly existing, it is NULL.

Include jQuery in the JavaScript Console

I'm a rebel.

Solution: don't use jQuery. jQuery is a library to abstract the DOM inconcistencies across the browsers. Since you're in your own console, you don't need this kind of abstraction.

For your example:

$$('element').length

($$ is an alias to document.querySelectorAll in the console.)

For any other example: I'm sure I can find anything. Especially if you're using a modern browser (Chrome, FF, Safari, Opera).

Besides, knowing how the DOM works wouldn't hurt anyone, it would only increase your level of jQuery (yes, learning more about javascript makes you better at jQuery).

Reading and writing environment variables in Python?

Use os.environ[str(DEBUSSY)] for both reading and writing (http://docs.python.org/library/os.html#os.environ).

As for reading, you have to parse the number from the string yourself of course.

Elasticsearch error: cluster_block_exception [FORBIDDEN/12/index read-only / allow delete (api)], flood stage disk watermark exceeded

Only changing the settings with the following command did not work in my environment:

curl -XPUT -H "Content-Type: application/json" http://localhost:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'

I had to also ran the Force Merge API command:

curl -X POST "localhost:9200/my-index-000001/_forcemerge?pretty"

ref: Force Merge API

How to loop over directories in Linux?

The technique I use most often is find | xargs. For example, if you want to make every file in this directory and all of its subdirectories world-readable, you can do:

find . -type f -print0 | xargs -0 chmod go+r
find . -type d -print0 | xargs -0 chmod go+rx

The -print0 option terminates with a NULL character instead of a space. The -0 option splits its input the same way. So this is the combination to use on files with spaces.

You can picture this chain of commands as taking every line output by find and sticking it on the end of a chmod command.

If the command you want to run as its argument in the middle instead of on the end, you have to be a bit creative. For instance, I needed to change into every subdirectory and run the command latemk -c. So I used (from Wikipedia):

find . -type d -depth 1 -print0 | \
    xargs -0 sh -c 'for dir; do pushd "$dir" && latexmk -c && popd; done' fnord

This has the effect of for dir $(subdirs); do stuff; done, but is safe for directories with spaces in their names. Also, the separate calls to stuff are made in the same shell, which is why in my command we have to return back to the current directory with popd.

Go to next item in ForEach-Object

You may want to use the Continue statement to continue with the innermost loop.

Excerpt from PowerShell help file:

In a script, the continue statement causes program flow to move immediately to the top of the innermost loop controlled by any of these statements:

  • for
  • foreach
  • while

XPath selecting a node with some attribute value equals to some other node's attribute value

This XPath is specific to the code snippet you've provided. To select <child> with id as #grand you can write //child[@id='#grand'].

To get age //child[@id='#grand']/@age

Hope this helps

org.apache.jasper.JasperException: Unable to compile class for JSP:

Please remove the servlet jar from web project,as any how, the application/web server already had.

How to remove an element from the flow?

Floating it will reorganise the flow but position: absolute is the only way to completely remove it from the flow of the document.

Change the location of the ~ directory in a Windows install of Git Bash

I faced exactly the same issue. My home drive mapped to a network drive. Also

  1. No Write access to home drive
  2. No write access to Git bash profile
  3. No admin rights to change environment variables from control panel.

However below worked from command line and I was able to add HOME to environment variables.

rundll32 sysdm.cpl,EditEnvironmentVariables

How to change theme for AlertDialog

I"m not sure how Arve's solution would work in a custom Dialog with builder where the view is inflated via a LayoutInflator.

The solution should be to insert the the ContextThemeWrapper in the inflator through cloneInContext():

View sensorView = LayoutInflater.from(context).cloneInContext(
     new ContextThemeWrapper(context, R.style.AppTheme_DialogLight)
).inflate(R.layout.dialog_fingerprint, null);

'App not Installed' Error on Android

Primarily for older phones

I only encountered the App not installed error when trying to install an apk on my phone which runs on 4.4.2 aka KitKat, but my friend did not encounter this error on his phone which runs on 6+. I tried the other solutions such as removing the old/debug version of the app because the apk was a release version, clearing the debug app's data, and even clearing all of my cached data. Then, finally I realized all I had to do was select both signature versions when building my signed apk.

enter image description here

Before I only had V2 (Full APK Signature) selected, but after selecting V1 Jar Signature as well, I was able to successfully install my signed APK on my 4.4.2 device. Hope this helps others!

C/C++ maximum stack size of program

(Added 26 Sept. 2020)

On 24 Oct. 2009, as @pixelbeat first pointed out here, Bruno Haible empirically discovered the following default thread stack sizes for several systems. He said that in a multithreaded program, "the default thread stack size is:"

- glibc i386, x86_64    7.4 MB
- Tru64 5.1             5.2 MB
- Cygwin                1.8 MB
- Solaris 7..10           1 MB
- MacOS X 10.5          460 KB
- AIX 5                  98 KB
- OpenBSD 4.0            64 KB
- HP-UX 11               16 KB

Note that the above units are all in MB and KB (base 1000 numbers), NOT MiB and KiB (base 1024 numbers). I've proven this to myself by verifying the 7.4 MB case.

He also stated that:

32 KB is more than you can safely allocate on the stack in a multithreaded program

And he said:

And the default stack size for sigaltstack, SIGSTKSZ, is

  • only 16 KB on some platforms: IRIX, OSF/1, Haiku.
  • only 8 KB on some platforms: glibc, NetBSD, OpenBSD, HP-UX, Solaris.
  • only 4 KB on some platforms: AIX.

Bruno

He wrote the following simple Linux C program to empirically determine the above values. You can run it on your system today to quickly see what your maximum thread stack size is, or you can run it online on GDBOnline here: https://onlinegdb.com/rkO9JnaHD.

Explanation: It simply creates a single new thread, so as to check the thread stack size and NOT the program stack size, in case they differ, then it has that thread repeatedly allocate 128 bytes of memory on the stack (NOT the heap), using the Linux alloca() call, after which it writes a 0 to the first byte of this new memory block, and then it prints out how many total bytes it has allocated. It repeats this process, allocating 128 more bytes on the stack each time, until the program crashes with a Segmentation fault (core dumped) error. The last value printed is the estimated maximum thread stack size allowed for your system.

Important note: alloca() allocates on the stack: even though this looks like dynamic memory allocation onto the heap, similar to a malloc() call, alloca() does NOT dynamically allocate onto the heap. Rather, alloca() is a specialized Linux function to "pseudo-dynamically" (I'm not sure what I'd call this, so that's the term I chose) allocate directly onto the stack as though it was statically-allocated memory. Stack memory used and returned by alloca() is scoped at the function-level, and is therefore "automatically freed when the function that called alloca() returns to its caller." That's why its static scope isn't exited and memory allocated by alloca() is NOT freed each time a for loop iteration is completed and the end of the for loop scope is reached. See man 3 alloca for details. Here's the pertinent quote (emphasis added):

DESCRIPTION
The alloca() function allocates size bytes of space in the stack frame of the caller. This temporary space is automatically freed when the function that called alloca() returns to its caller.

RETURN VALUE
The alloca() function returns a pointer to the beginning of the allocated space. If the allocation causes stack overflow, program behavior is undefined.

Here is Bruno Haible's program from 24 Oct. 2009, copied directly from the GNU mailing list here:

Again, you can run it live online here.

// By Bruno Haible
// 24 Oct. 2009
// Source: https://lists.gnu.org/archive/html/bug-coreutils/2009-10/msg00262.html

// =============== Program for determining the default thread stack size =========

#include <alloca.h>
#include <pthread.h>
#include <stdio.h>
void* threadfunc (void*p) {
  int n = 0;
  for (;;) {
    printf("Allocated %d bytes\n", n);
    fflush(stdout);
    n += 128;
    *((volatile char *) alloca(128)) = 0;
  }
}

int main()
{
  pthread_t thread;
  pthread_create(&thread, NULL, threadfunc, NULL);
  for (;;) {}
}

When I run it on GDBOnline using the link above, I get the exact same results each time I run it, as both a C and a C++17 program. It takes about 10 seconds or so to run. Here are the last several lines of the output:

Allocated 7449856 bytes
Allocated 7449984 bytes
Allocated 7450112 bytes
Allocated 7450240 bytes
Allocated 7450368 bytes
Allocated 7450496 bytes
Allocated 7450624 bytes
Allocated 7450752 bytes
Allocated 7450880 bytes
Segmentation fault (core dumped)

So, the thread stack size is ~7.45 MB for this system, as Bruno mentioned above (7.4 MB).

I've made a few changes to the program, mostly just for clarity, but also for efficiency, and a bit for learning.

Summary of my changes:

  1. [learning] I passed in BYTES_TO_ALLOCATE_EACH_LOOP as an argument to the threadfunc() just for practice passing in and using generic void* arguments in C.

  2. [efficiency] I made the main thread sleep instead of wastefully spinning.

  3. [clarity] I added more-verbose variable names, such as BYTES_TO_ALLOCATE_EACH_LOOP and bytes_allocated.

  4. [clarity] I changed this:

     *((volatile char *) alloca(128)) = 0;
    

    to this:

     volatile uint8_t * byte_buff = 
             (volatile uint8_t *)alloca(BYTES_TO_ALLOCATE_EACH_LOOP);
     byte_buff[0] = 0;
    

Here is my modified test program, which does exactly the same thing as Bruno's, and even has the same results:

You can run it online here, or download it from my repo here. If you choose to run it locally from my repo, here's the build and run commands I used for testing:

  1. Build and run it as a C program:

     mkdir -p bin && \
     gcc -Wall -Werror -g3 -O3 -std=c11 -pthread -o bin/tmp \
     onlinegdb--empirically_determine_max_thread_stack_size_GS_version.c && \
     time bin/tmp
    
  2. Build and run it as a C++ program:

     mkdir -p bin && \
     g++ -Wall -Werror -g3 -O3 -std=c++17 -pthread -o bin/tmp \
     onlinegdb--empirically_determine_max_thread_stack_size_GS_version.c && \
     time bin/tmp
    

It takes < 0.5 seconds to run locally on a fast computer with a thread stack size of ~7.4 MB.

Here's the program:

// =============== Program for determining the default thread stack size =========

// Modified by Gabriel Staples, 26 Sept. 2020

// Originally by Bruno Haible
// 24 Oct. 2009
// Source: https://lists.gnu.org/archive/html/bug-coreutils/2009-10/msg00262.html

#include <alloca.h>
#include <pthread.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <unistd.h> // sleep

/// Thread function to repeatedly allocate memory within a thread, printing
/// the total memory allocated each time, until the program crashes. The last
/// value printed before the crash indicates how big a thread's stack size is.
void* threadfunc(void* bytes_to_allocate_each_loop)
{
    const uint32_t BYTES_TO_ALLOCATE_EACH_LOOP =
            *(uint32_t*)bytes_to_allocate_each_loop;

    uint32_t bytes_allocated = 0;
    while (true)
    {
        printf("bytes_allocated = %u\n", bytes_allocated);
        fflush(stdout);
        // NB: it appears that you don't necessarily need `volatile` here,
        // but you DO definitely need to actually use (ex: write to) the
        // memory allocated by `alloca()`, as we do below, or else the
        // `alloca()` call does seem to get optimized out on some systems,
        // making this whole program just run infinitely forever without
        // ever hitting the expected segmentation fault.
        volatile uint8_t * byte_buff =
                (volatile uint8_t *)alloca(BYTES_TO_ALLOCATE_EACH_LOOP);
        byte_buff[0] = 0;
        bytes_allocated += BYTES_TO_ALLOCATE_EACH_LOOP;
    }
}

int main()
{
    const uint32_t BYTES_TO_ALLOCATE_EACH_LOOP = 128;

    pthread_t thread;
    pthread_create(&thread, NULL, threadfunc,
                   (void*)(&BYTES_TO_ALLOCATE_EACH_LOOP));
    while (true)
    {
        const unsigned int SLEEP_SEC = 10000;
        sleep(SLEEP_SEC);
    }

    return 0;
}

Sample output (same results as Bruno Haible's original program):

bytes_allocated = 7450240                                                                                                                                                        
bytes_allocated = 7450368                                                                                                                                                        
bytes_allocated = 7450496                                                                                                                                                        
bytes_allocated = 7450624                                                                                                                                                        
bytes_allocated = 7450752                                                                                                                                                        
bytes_allocated = 7450880                                                                                                                                                        
Segmentation fault (core dumped) 

How can I use "." as the delimiter with String.split() in java

You might be interested in the StringTokenizer class. However, the java docs advise that you use the .split method as StringTokenizer is a legacy class.

CSS: how to position element in lower right?

Set the CSS position: relative; on the box. This causes all absolute positions of objects inside to be relative to the corners of that box. Then set the following CSS on the "Bet 5 days ago" line:

position: absolute;
bottom: 0;
right: 0;

If you need to space the text farther away from the edge, you could change 0 to 2px or similar.

Using routes in Express-js

So, after I created my question, I got this related list on the right with a similar issue: Organize routes in Node.js.

The answer in that post linked to the Express repo on GitHub and suggests to look at the 'route-separation' example.

This helped me change my code, and I now have it working. - Thanks for your comments.

My implementation ended up looking like this;

I require my routes in the app.js:

var express = require('express')
  , site = require('./site')
  , wiki = require('./wiki');

And I add my routes like this:

app.get('/', site.index);
app.get('/wiki/:id', wiki.show);
app.get('/wiki/:id/edit', wiki.edit);

I have two files called wiki.js and site.js in the root of my app, containing this:

exports.edit = function(req, res) {

    var wiki_entry = req.params.id;

    res.render('wiki/edit', {
        title: 'Editing Wiki',
        wiki: wiki_entry
    })
}

How to read xml file contents in jQuery and display in html elements?

_x000D_
_x000D_
 $.get("/folder_name/filename.xml", function (xml) {_x000D_
 var xmlInnerhtml = xml.documentElement.innerHTML;_x000D_
 });
_x000D_
_x000D_
_x000D_

Subdomain on different host

UPDATE - I do not have Total DNS enabled at GoDaddy because the domain is hosted at DiscountASP. As such, I could not add an A Record and that is why GoDaddy was only offering to forward my subdomain to a different site. I finally realized that I had to go to DiscountASP to add the A Record to point to DreamHost. Now waiting to see if it all works!

Of course, use the stinkin' IP! I'm not sure why that wasn't registering for me. I guess their helper text example of pointing to another url was throwing me off.

Thanks for both of the replies. I 'got it' as soon as I read Bryant's response which was first but Saif kicked it up a notch and added a little more detail.

Thanks!

CSS to select/style first word

What you are looking for is a pseudo-element that doesn't exist. There is :first-letter and :first-line, but no :first-word.

You can of course do this with JavaScript. Here's some code I found that does this: http://www.dynamicsitesolutions.com/javascript/first-word-selector/

How do I make a https post in Node Js without any third party module?

For example, like this:

const querystring = require('querystring');
const https = require('https');

var postData = querystring.stringify({
    'msg' : 'Hello World!'
});

var options = {
  hostname: 'posttestserver.com',
  port: 443,
  path: '/post.php',
  method: 'POST',
  headers: {
       'Content-Type': 'application/x-www-form-urlencoded',
       'Content-Length': postData.length
     }
};

var req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });
});

req.on('error', (e) => {
  console.error(e);
});

req.write(postData);
req.end();

How do I hide the bullets on my list for the sidebar?

You have a selector ul on line 252 which is setting list-style: square outside none (a square bullet). You'll have to change it to list-style: none or just remove the line.

If you only want to remove the bullets from that specific instance, you can use the specific selector for that list and its items as follows:

ul#groups-list.items-list { list-style: none }

Using onBackPressed() in Android Fragments

requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                Log.w("a","")
            }
        })

How do I watch a file for changes?

Since I have it installed globally, my favorite approach is to use nodemon. If your source code is in src, and your entry point is src/app.py, then it's as easy as:

nodemon -w 'src/**' -e py,html --exec python src/app.py

... where -e py,html lets you control what file types to watch for changes.

Can we have multiple "WITH AS" in single sql - Oracle SQL

You can do this as:

WITH abc AS( select
             FROM ...)
, XYZ AS(select
         From abc ....) /*This one uses "abc" multiple times*/
  Select 
  From XYZ....   /*using abc, XYZ multiple times*/

jquery/javascript convert date string to date

Use moment js for any date operation.

https://momentjs.com/

_x000D_
_x000D_
console.log(moment("Sunday, February 28, 2010").format('MM/DD/YYYY'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

SystemError: Parent module '' not loaded, cannot perform relative import

If you go one level up in running the script in the command line of your bash shell, the issue will be resolved. To do this, use cd .. command to change the working directory in which your script will be running. The result should look like this:

[username@localhost myProgram]$

rather than this:

[username@localhost app]$

Once you are there, instead of running the script in the following format:

python3 mymodule.py

Change it to this:

python3 app/mymodule.py

This process can be repeated once again one level up depending on the structure of your Tree diagram. Please also include the compilation command line that is giving you that mentioned error message.

How to list files in a directory in a C program?

An example, available for POSIX compliant systems :

/*
 * This program displays the names of all files in the current directory.
 */

#include <dirent.h> 
#include <stdio.h> 

int main(void) {
  DIR *d;
  struct dirent *dir;
  d = opendir(".");
  if (d) {
    while ((dir = readdir(d)) != NULL) {
      printf("%s\n", dir->d_name);
    }
    closedir(d);
  }
  return(0);
}

Beware that such an operation is platform dependant in C.

Source : http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1046380353&id=1044780608

C error: Expected expression before int

By C89, variable can only be defined at the top of a block.

if (a == 1)
    int b = 10;   // it's just a statement, syntacitially error 

if (a == 1)
{                  // refer to the beginning of a local block 
    int b = 10;    // at the top of the local block, syntacitially correct
}                  // refer to the end of a local block

if (a == 1)
{
    func();
    int b = 10;    // not at the top of the local block, syntacitially error, I guess
}

How do you set the width of an HTML Helper TextBox in ASP.NET MVC?

Don't use the length parameter as it will not work with all browsers. The best way is to set a style on the input tag.

<input style="width:100px" />

ALTER TABLE, set null in not null column, PostgreSQL 9.1

First, Set :
ALTER TABLE person ALTER COLUMN phone DROP NOT NULL;

Redirect in Spring MVC

Try this, it should work if you have configured your view resolver properly

 return "redirect:/index.html";

How to run Unix shell script from Java code?

I would say that it is not in the spirit of Java to run a shell script from Java. Java is meant to be cross platform, and running a shell script would limit its use to just UNIX.

With that said, it's definitely possible to run a shell script from within Java. You'd use exactly the same syntax you listed (I haven't tried it myself, but try executing the shell script directly, and if that doesn't work, execute the shell itself, passing the script in as a command line parameter).

Export MySQL database using PHP only

Here is my code, This will backup MySQL database and store it in the specified path.

<?php
function backup_mysql_database($options){
$mtables = array(); $contents = "-- Database: `".$options['db_to_backup']."` --\n";

$mysqli = new mysqli($options['db_host'], $options['db_uname'], $options['db_password'], $options['db_to_backup']);
if ($mysqli->connect_error) {
    die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}

$results = $mysqli->query("SHOW TABLES");

while($row = $results->fetch_array()){
    if (!in_array($row[0], $options['db_exclude_tables'])){
        $mtables[] = $row[0];
    }
}

foreach($mtables as $table){
    $contents .= "-- Table `".$table."` --\n";

    $results = $mysqli->query("SHOW CREATE TABLE ".$table);
    while($row = $results->fetch_array()){
        $contents .= $row[1].";\n\n";
    }

    $results = $mysqli->query("SELECT * FROM ".$table);
    $row_count = $results->num_rows;
    $fields = $results->fetch_fields();
    $fields_count = count($fields);

    $insert_head = "INSERT INTO `".$table."` (";
    for($i=0; $i < $fields_count; $i++){
        $insert_head  .= "`".$fields[$i]->name."`";
            if($i < $fields_count-1){
                    $insert_head  .= ', ';
                }
    }
    $insert_head .=  ")";
    $insert_head .= " VALUES\n";        

    if($row_count>0){
        $r = 0;
        while($row = $results->fetch_array()){
            if(($r % 400)  == 0){
                $contents .= $insert_head;
            }
            $contents .= "(";
            for($i=0; $i < $fields_count; $i++){
                $row_content =  str_replace("\n","\\n",$mysqli->real_escape_string($row[$i]));

                switch($fields[$i]->type){
                    case 8: case 3:
                        $contents .=  $row_content;
                        break;
                    default:
                        $contents .= "'". $row_content ."'";
                }
                if($i < $fields_count-1){
                        $contents  .= ', ';
                    }
            }
            if(($r+1) == $row_count || ($r % 400) == 399){
                $contents .= ");\n\n";
            }else{
                $contents .= "),\n";
            }
            $r++;
        }
    }
}

if (!is_dir ( $options['db_backup_path'] )) {
        mkdir ( $options['db_backup_path'], 0777, true );
 }

$backup_file_name = $options['db_to_backup'] . " sql-backup- " . date( "d-m-Y--h-i-s").".sql";

$fp = fopen($options['db_backup_path'] . '/' . $backup_file_name ,'w+');
if (($result = fwrite($fp, $contents))) {
    echo "Backup file created '--$backup_file_name' ($result)"; 
}
fclose($fp);
return $backup_file_name;
}

$options = array(
    'db_host'=> 'localhost',  //mysql host
    'db_uname' => 'root',  //user
    'db_password' => '', //pass
    'db_to_backup' => 'attendance', //database name
    'db_backup_path' => '/htdocs', //where to backup
    'db_exclude_tables' => array() //tables to exclude
);
$backup_file_name=backup_mysql_database($options);

Looping over elements in jQuery

if you want to use the each function, it should look like this:

$('#formId').children().each( 
  function(){
    //access to form element via $(this)
  }
);

Just switch out the closing curly bracket for a close paren. Thanks for pointing it out, jobscry, you saved me some time.

Auto Generate Database Diagram MySQL

This http://code.google.com/p/database-diagram/ will reverse engineer your database. Just do an export 'structure only' then paste the SQL into the tool.

C# - Making a Process.Start wait until the process has start-up

First of all: I know this is rather old but there still is not an accepted answer, so perhaps my approach will help someone else. :)

What I did to solve this is:

process.Start();

while (true)
{
    try
    {
        var time = process.StartTime;
        break;
    }
    catch (Exception) {}
}

The association var time = process.StartTime will throw an exception as long as process did not start. So once it passes, it is safe to assume process is running and to work with it further. I am using this to wait for java process to start up, since it takes some time. This way it should be independent on what machine the application is running rather than using Thread.Sleep().

I understand this is not very clean solution, but the only one that should be performance independent I could think of.

What is the difference between an expression and a statement in Python?

Expressions only contain identifiers, literals and operators, where operators include arithmetic and boolean operators, the function call operator () the subscription operator [] and similar, and can be reduced to some kind of "value", which can be any Python object. Examples:

3 + 5
map(lambda x: x*x, range(10))
[a.x for a in some_iterable]
yield 7

Statements (see 1, 2), on the other hand, are everything that can make up a line (or several lines) of Python code. Note that expressions are statements as well. Examples:

# all the above expressions
print 42
if x: do_y()
return
a = 7

Get Locale Short Date Format using javascript

This depends on the browser's toLocaleDateString() implementation. For example in chrome you will get something like: Tuesday, January DD, YYYY

How to make a deep copy of Java ArrayList

public class Person{

    String s;
    Date d;
    ...

    public Person clone(){
        Person p = new Person();
        p.s = this.s.clone();
        p.d = this.d.clone();
        ...
        return p;
    }
}

In your executing code:

ArrayList<Person> clone = new ArrayList<Person>();
for(Person p : originalList)
    clone.add(p.clone());

Run all SQL files in a directory

The easiest way I found included the following steps (the only requirement is it to be in Win7+):

  • open the folder in Explorer
  • select all script files
  • press Shift
  • right click the selection and select "Copy as path"
  • go to SQL Server Management Studio
  • create a new query
  • Query Menu, "SQLCMD mode"
  • paste the list, then Ctrl+H, replace '"C:\' (or whatever the drive letter) with ':r "C:' (i.e. prefix the lines with ':r ')
  • run the query

It sounds long, but in reality is very fast.. (it sounds long as I described even the smallest steps)

assignment operator overloading in c++

this might be helpful:

// Operator overloading in C++
//assignment operator overloading
#include<iostream>
using namespace std;

class Employee
{
private:
int idNum;
double salary;
public:
Employee ( ) {
    idNum = 0, salary = 0.0;
}

void setValues (int a, int b);
void operator= (Employee &emp );

};

void Employee::setValues ( int idN , int sal )
{

salary = sal; idNum = idN;

}

void Employee::operator = (Employee &emp)  // Assignment operator overloading function
{
salary = emp.salary;
}

int main ( )
{

Employee emp1;
emp1.setValues(10,33);
Employee emp2;
emp2 = emp1; // emp2 is calling object using assignment operator

}

jQuery removing '-' character from string

$mylabel.text( $mylabel.text().replace('-', '') );

Since text() gets the value, and text( "someValue" ) sets the value, you just place one inside the other.

Would be the equivalent of doing:

var newValue = $mylabel.text().replace('-', '');
$mylabel.text( newValue );

EDIT:

I hope I understood the question correctly. I'm assuming $mylabel is referencing a DOM element in a jQuery object, and the string is in the content of the element.

If the string is in some other variable not part of the DOM, then you would likely want to call the .replace() function against that variable before you insert it into the DOM.

Like this:

var someVariable = "-123456";
$mylabel.text( someVariable.replace('-', '') );

or a more verbose version:

var someVariable = "-123456";
someVariable = someVariable.replace('-', '');
$mylabel.text( someVariable );

Help needed with Median If in Excel

Expanding on Brian Camire's Answer:

Using =MEDIAN(IF($A$1:$A$6="Airline",$B$1:$B$6,"")) with CTRL+SHIFT+ENTER will include blank cells in the calculation. Blank cells will be evaluated as 0 which results in a lower median value. The same is true if using the average funtion. If you don't want to include blank cells in the calculation, use a nested if statement like so:

=MEDIAN(IF($A$1:$A$6="Airline",IF($B$1:$B$6<>"",$B$1:$B$6)))

Don't forget to press CTRL+SHIFT+ENTER to treat the formula as an "array formula".

sqlalchemy filter multiple columns

You can simply call filter multiple times:

query = meta.Session.query(User).filter(User.firstname.like(searchVar1)). \
                                 filter(User.lastname.like(searchVar2))

Asynchronously load images with jQuery

Using jQuery you may simply change the "src" attribute to "data-src". The image won't be loaded. But the location is stored with the tag. Which I like.

<img class="loadlater" data-src="path/to/image.ext"/>

A Simple piece of jQuery copies data-src to src, which will start loading the image when you need it. In my case when the page has finished loading.

$(document).ready(function(){
    $(".loadlater").each(function(index, element){
        $(element).attr("src", $(element).attr("data-src"));
    });
});

I bet the jQuery code could be abbreviated, but it is understandable this way.

Exception from HRESULT: 0x800A03EC Error

Check your start indexes. Its start from 1 not 0 for Microsoft.Office.Interop.Excel range objects. I had received same error because of my loop start value.

How to add screenshot to READMEs in github repository?

Even though there is already an accepted answer I would like to add another way to upload images to readme on GitHub.

  • You need to create issue in your repo
  • Drag and drop in the comment area your image
  • After link for the image is generated insert it to your readme

More details you can find here

How to create a stacked bar chart for my DataFrame using seaborn?

You could use pandas plot as @Bharath suggest:

import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)

Output:

enter image description here

Updated:

from matplotlib.colors import ListedColormap df.set_index('App')\ .reindex_axis(df.set_index('App').sum().sort_values().index, axis=1)\ .T.plot(kind='bar', stacked=True, colormap=ListedColormap(sns.color_palette("GnBu", 10)), figsize=(12,6))

Updated Pandas 0.21.0+ reindex_axis is deprecated, use reindex

from matplotlib.colors import ListedColormap

df.set_index('App')\
  .reindex(df.set_index('App').sum().sort_values().index, axis=1)\
  .T.plot(kind='bar', stacked=True,
          colormap=ListedColormap(sns.color_palette("GnBu", 10)), 
          figsize=(12,6))

Output:

enter image description here

MySQL JOIN the most recent row only?

It's a good idea that logging actual data into "customer_data" table. With this data you can select all data from "customer_data" table as you wish.

Abstraction VS Information Hiding VS Encapsulation

Abstraction is hiding details of implementation as you put it.

You abstract something to a high enough point that you'll only have to do something very simple to perform an action.

Information hiding is hiding implementation details. Programming is hard. You can have a lot of things to deal with and handle. There can be variables you want/need to keep very close track of. Hiding information ensures that no one accidentally breaks something by using a variable or method you exposed publicly.

These 2 concepts are very closely tied together in object-oriented programming.

Find a string within a cell using VBA

I simplified your code to isolate the test for "%" being in the cell. Once you get that to work, you can add in the rest of your code.

Try this:

Option Explicit


Sub DoIHavePercentSymbol()
   Dim rng As Range

   Set rng = ActiveCell

   Do While rng.Value <> Empty
        If InStr(rng.Value, "%") = 0 Then
            MsgBox "I know nothing about percentages!"
            Set rng = rng.Offset(1)
            rng.Select
        Else
            MsgBox "I contain a % symbol!"
            Set rng = rng.Offset(1)
            rng.Select
        End If
   Loop

End Sub

InStr will return the number of times your search text appears in the string. I changed your if test to check for no matches first.

The message boxes and the .Selects are there simply for you to see what is happening while you are stepping through the code. Take them out once you get it working.

Passing an array using an HTML form hidden element

You can do it like this:

<input type="hidden" name="result" value="<?php foreach($postvalue as $value) echo $postvalue.","; ?>">

Byte and char conversion in Java

A character in Java is a Unicode code-unit which is treated as an unsigned number. So if you perform c = (char)b the value you get is 2^16 - 56 or 65536 - 56.

Or more precisely, the byte is first converted to a signed integer with the value 0xFFFFFFC8 using sign extension in a widening conversion. This in turn is then narrowed down to 0xFFC8 when casting to a char, which translates to the positive number 65480.

From the language specification:

5.1.4. Widening and Narrowing Primitive Conversion

First, the byte is converted to an int via widening primitive conversion (§5.1.2), and then the resulting int is converted to a char by narrowing primitive conversion (§5.1.3).


To get the right point use char c = (char) (b & 0xFF) which first converts the byte value of b to the positive integer 200 by using a mask, zeroing the top 24 bits after conversion: 0xFFFFFFC8 becomes 0x000000C8 or the positive number 200 in decimals.


Above is a direct explanation of what happens during conversion between the byte, int and char primitive types.

If you want to encode/decode characters from bytes, use Charset, CharsetEncoder, CharsetDecoder or one of the convenience methods such as new String(byte[] bytes, Charset charset) or String#toBytes(Charset charset). You can get the character set (such as UTF-8 or Windows-1252) from StandardCharsets.

Is there a concise way to iterate over a stream with indices in Java 8?

If you need the index in the forEach then this provides a way.

  public class IndexedValue {

    private final int    index;
    private final Object value;

    public IndexedValue(final int index, final Object value) { 
        this.index = index;
        this.value = value;
    }

    public int getIndex() {
        return index;
    }

    public Object getValue() {
        return value;
    }
}

Then use it as follows.

@Test
public void withIndex() {
    final List<String> list = Arrays.asList("a", "b");
    IntStream.range(0, list.size())
             .mapToObj(index -> new IndexedValue(index, list.get(index)))
             .forEach(indexValue -> {
                 System.out.println(String.format("%d, %s",
                                                  indexValue.getIndex(),
                                                  indexValue.getValue().toString()));
             });
}

How to detect when a UIScrollView has finished scrolling

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self stoppedScrolling];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (!decelerate) {
        [self stoppedScrolling];
    }
}

- (void)stoppedScrolling {
    // ...
}

How do I tell if a variable has a numeric value in Perl?

Usually number validation is done with regular expressions. This code will determine if something is numeric as well as check for undefined variables as to not throw warnings:

sub is_integer {
   defined $_[0] && $_[0] =~ /^[+-]?\d+$/;
}

sub is_float {
   defined $_[0] && $_[0] =~ /^[+-]?\d+(\.\d+)?$/;
}

Here's some reading material you should look at.

How to kill a process in MacOS?

I just now searched for this as I'm in a similar situation, and instead of kill -9 698 I tried sudo kill 428 where 428 was the pid of the process I'm trying to kill. It worked cleanly for me, in the absence of the hyphen '-' character. I hope it helps!

Printing long int value in C

Use printf("%ld",a);

Have a look at format specifiers for printf

Android WebView, how to handle redirects in app instead of opening a browser

Just adding a default custom WebViewClient will do. This makes the WebView handle any loaded urls itself.

mWebView.setWebViewClient(new WebViewClient());

Return multiple values from a function, sub or type?

You can also use a variant array as the return result to return a sequence of arbitrary values:

Function f(i As Integer, s As String) As Variant()
    f = Array(i + 1, "ate my " + s, Array(1#, 2#, 3#))
End Function

Sub test()
    result = f(2, "hat")
    i1 = result(0)
    s1 = result(1)
    a1 = result(2)
End Sub

Ugly and bug prone because your caller needs to know what's being returned to use the result, but occasionally useful nonetheless.

Disable scrolling in an iPhone web application?

'self.webView.scrollView.bounces = NO;'

Just add this one line in the 'viewDidLoad' of the mainViewController.m file of your application. you can open it in the Xcode and add it .

This should make the page without any rubberband bounces still enabling the scroll in the app view.

What is the difference between Hibernate and Spring Data JPA

I disagree SpringJPA makes live easy. Yes, it provides some classes and you can make some simple DAO fast, but in fact, it's all you can do. If you want to do something more than findById() or save, you must go through hell:

  • no EntityManager access in org.springframework.data.repository classes (this is basic JPA class!)
  • own transaction management (hibernate transactions disallowed)
  • huge problems with more than one datasources configuration
  • no datasource pooling (HikariCP must be in use as third party library)

Why own transaction management is an disadvantage? Since Java 1.8 allows default methods into interfaces, Spring annotation based transactions, simple doesn't work.

Unfortunately, SpringJPA is based on reflections, and sometimes you need to point a method name or entity package into annotations (!). That's why any refactoring makes big crash. Sadly, @Transactional works for primary DS only :( So, if you have more than one DataSources, remember - transactions works just for primary one :)

What are the main differences between Hibernate and Spring Data JPA?

Hibernate is JPA compatibile, SpringJPA Spring compatibile. Your HibernateJPA DAO can be used with JavaEE or Hibernate Standalone, when SpringJPA can be used within Spring - SpringBoot for example

When should we not use Hibernate or Spring Data JPA? Also, when may Spring JDBC template perform better than Hibernate / Spring Data JPA?

Use Spring JDBC only when you need to use much Joins or when you need to use Spring having multiple datasource connections. Generally, avoid JPA for Joins.

But my general advice, use fresh solution—Daobab (http://www.daobab.io). Daobab is my Java and any JPA engine integrator, and I believe it will help much in your tasks :)

Android AlertDialog Single Button

Its very simple

new AlertDialog.Builder(this).setView(input).setPositiveButton("ENTER",            
                        new DialogInterface.OnClickListener()                      
                        {   public void onClick(DialogInterface di,int id)     
                            {
                                output.setText(input.getText().toString());
                            }
                        }
                     )
        .create().show();

In case you wish to read the full program see here: Program to take input from user using dialog and output to screen

How can I put strings in an array, split by new line?

An alternative to Davids answer which is faster (way faster) is to use str_replace and explode.

$arrayOfLines = explode("\n",
                    str_replace(["\r\n","\n\r","\r"],"\n",$str)
            );

What's happening is:
Since line breaks can come in different forms, I str_replace \r\n, \n\r, and \r with \n instead (and original \n are preserved).
Then explode on \n and you have all the lines in an array.

I did a benchmark on the src of this page and split the lines 1000 times in a for loop and:
preg_replace took an avg of 11 seconds
str_replace & explode took an avg of about 1 second

More detail and bencmark info on my forum

Pandas: Subtracting two date columns and the result being an integer

I feel that the overall answer does not handle if the dates 'wrap' around a year. This would be useful in understanding proximity to a date being accurate by day of year. In order to do these row operations, I did the following. (I had this used in a business setting in renewing customer subscriptions).

def get_date_difference(row, x, y):
    try:
        # Calcuating the smallest date difference between the start and the close date
        # There's some tricky logic in here to calculate for determining date difference
        # the other way around (Dec -> Jan is 1 month rather than 11)

        sub_start_date = int(row[x].strftime('%j')) # day of year (1-366)
        close_date = int(row[y].strftime('%j')) # day of year (1-366)

        later_date_of_year = max(sub_start_date, close_date) 
        earlier_date_of_year = min(sub_start_date, close_date)
        days_diff = later_date_of_year - earlier_date_of_year

# Calculates the difference going across the next year (December -> Jan)
        days_diff_reversed = (365 - later_date_of_year) + earlier_date_of_year
        return min(days_diff, days_diff_reversed)

    except ValueError:
        return None

Then the function could be:

dfAC_Renew['date_difference'] = dfAC_Renew.apply(get_date_difference, x = 'customer_since_date', y = 'renewal_date', axis = 1)

Imported a csv-dataset to R but the values becomes factors

for me the solution was to include skip = 0 (number of rows to skip at the top of the file. Can be set >0)

mydata <- read.csv(file = "file.csv", header = TRUE, sep = ",", skip = 22)

Adding form action in html in laravel

I wanted to store a post in my application, so I created a controller of posts (PostsController) with the resources included:

php artisan make:controller PostsController --resource

The controller was created with all the methods needed to do a CRUD app, then I added the following code to the web.php in the routes folder :

Route::resource('posts', 'PostsController');

I solved the form action problem by doing this:

  1. I checked my routing list by doing php artisan route:list
  2. I searched for the route name of the store method in the result table in the terminal and I found it under the name of posts.store
  3. I added this to the action attribute of my form: action="{{route('posts.store')}}" instead of action="??what to write here??"

Deleting rows from parent and child tables

Two possible approaches.

  1. If you have a foreign key, declare it as on-delete-cascade and delete the parent rows older than 30 days. All the child rows will be deleted automatically.

  2. Based on your description, it looks like you know the parent rows that you want to delete and need to delete the corresponding child rows. Have you tried SQL like this?

      delete from child_table
          where parent_id in (
               select parent_id from parent_table
                    where updd_tms != (sysdate-30)
    

    -- now delete the parent table records

    delete from parent_table
    where updd_tms != (sysdate-30);
    

---- Based on your requirement, it looks like you might have to use PL/SQL. I'll see if someone can post a pure SQL solution to this (in which case that would definitely be the way to go).

declare
    v_sqlcode number;
    PRAGMA EXCEPTION_INIT(foreign_key_violated, -02291);
begin
    for v_rec in (select parent_id, child id from child_table
                         where updd_tms != (sysdate-30) ) loop

    -- delete the children
    delete from child_table where child_id = v_rec.child_id;

    -- delete the parent. If we get foreign key violation, 
    -- stop this step and continue the loop
    begin
       delete from parent_table
          where parent_id = v_rec.parent_id;
    exception
       when foreign_key_violated
         then null;
    end;
 end loop;
end;
/

JavaScript by reference vs. by value

Yes, Javascript always passes by value, but in an array or object, the value is a reference to it, so you can 'change' the contents.

But, I think you already read it on SO; here you have the documentation you want:

http://snook.ca/archives/javascript/javascript_pass

Getting the closest string match

This problem turns up all the time in bioinformatics. The accepted answer above (which was great by the way) is known in bioinformatics as the Needleman-Wunsch (compare two strings) and Smith-Waterman (find an approximate substring in a longer string) algorithms. They work great and have been workhorses for decades.

But what if you have a million strings to compare? That's a trillion pairwise comparisons, each of which is O(n*m)! Modern DNA sequencers easily generate a billion short DNA sequences, each about 200 DNA "letters" long. Typically, we want to find, for each such string, the best match against the human genome (3 billion letters). Clearly, the Needleman-Wunsch algorithm and its relatives will not do.

This so-called "alignment problem" is a field of active research. The most popular algorithms are currently able to find inexact matches between 1 billion short strings and the human genome in a matter of hours on reasonable hardware (say, eight cores and 32 GB RAM).

Most of these algorithms work by quickly finding short exact matches (seeds) and then extending these to the full string using a slower algorithm (for example, the Smith-Waterman). The reason this works is that we are really only interested in a few close matches, so it pays off to get rid of the 99.9...% of pairs that have nothing in common.

How does finding exact matches help finding inexact matches? Well, say we allow only a single difference between the query and the target. It is easy to see that this difference must occur in either the right or left half of the query, and so the other half must match exactly. This idea can be extended to multiple mismatches and is the basis for the ELAND algorithm commonly used with Illumina DNA sequencers.

There are many very good algorithms for doing exact string matching. Given a query string of length 200, and a target string of length 3 billion (the human genome), we want to find any place in the target where there is a substring of length k that matches a substring of the query exactly. A simple approach is to begin by indexing the target: take all k-long substrings, put them in an array and sort them. Then take each k-long substring of the query and search the sorted index. Sort and search can be done in O(log n) time.

But storage can be a problem. An index of the 3 billion letter target would need to hold 3 billion pointers and 3 billion k-long words. It would seem hard to fit this in less than several tens of gigabytes of RAM. But amazingly we can greatly compress the index, using the Burrows-Wheeler transform, and it will still be efficiently queryable. An index of the human genome can fit in less than 4 GB RAM. This idea is the basis of popular sequence aligners such as Bowtie and BWA.

Alternatively, we can use a suffix array, which stores only the pointers, yet represents a simultaneous index of all suffixes in the target string (essentially, a simultaneous index for all possible values of k; the same is true of the Burrows-Wheeler transform). A suffix array index of the human genome will take 12 GB of RAM if we use 32-bit pointers.

The links above contain a wealth of information and links to primary research papers. The ELAND link goes to a PDF with useful figures illustrating the concepts involved, and shows how to deal with insertions and deletions.

Finally, while these algorithms have basically solved the problem of (re)sequencing single human genomes (a billion short strings), DNA sequencing technology improves even faster than Moore's law, and we are fast approaching trillion-letter datasets. For example, there are currently projects underway to sequence the genomes of 10,000 vertebrate species, each a billion letters long or so. Naturally, we will want to do pairwise inexact string matching on the data...

R dplyr: Drop multiple columns

We can try

iris %>% 
      select_(.dots= setdiff(names(.),drop.cols))

Xcode 10 Error: Multiple commands produce

For dependency projects managed by cocoapods, solved the problem by providing a local podspec to exclude info.plist from sources. Take godzippa as an example

Podfile pod 'Godzippa', :podspec => "venders/godzippa.podspec"

venders/godzippa.podspec s.source_files = 'Sources/*.{h,m}'

Convert month name to month number in SQL Server

I know this may be a bit too late but the most efficient way of doing this through a CTE as follows:

 WITH Months AS
    (
       SELECT 1 x
       UNION all
       SELECT x + 1
       FROM Months
       WHERE x < 12

     )
     SELECT x AS MonthNumber, DateName( month , DateAdd( month , x , -1 ))            AS MonthName FROM Months

Set initially selected item in Select list in Angular2

If you use

<select [ngModel]="object">
    <option *ngFor="let object of objects" [ngValue]="object">{{object.name}}</option>
</select>

You need to set the property object in you components class to the item from objects that you want to have pre-selected.

class MyComponent {
  object;
  objects = [{name: 'a'}, {name: 'b'}, {name: 'c'}];
  constructor() {
    this.object = this.objects[1];
  }
}

Get JavaScript object from array of objects by value of property

jsObjects.find(x => x.b === 6)

From MDN:

The find() method returns a value in the array, if an element in the array satisfies the provided testing function. Otherwise undefined is returned.


Side note: methods like find() and arrow functions are not supported by older browsers (like IE), so if you want to support these browsers, you should transpile your code using Babel.

How to know/change current directory in Python shell?

You can use the os module.

>>> import os
>>> os.getcwd()
'/home/user'
>>> os.chdir("/tmp/")
>>> os.getcwd()
'/tmp'

But if it's about finding other modules: You can set an environment variable called PYTHONPATH, under Linux would be like

export PYTHONPATH=/path/to/my/library:$PYTHONPATH

Then, the interpreter searches also at this place for imported modules. I guess the name would be the same under Windows, but don't know how to change.

edit

Under Windows:

set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib

(taken from http://docs.python.org/using/windows.html)

edit 2

... and even better: use virtualenv and virtualenv_wrapper, this will allow you to create a development environment where you can add module paths as you like (add2virtualenv) without polluting your installation or "normal" working environment.

http://virtualenvwrapper.readthedocs.org/en/latest/command_ref.html

JQuery to load Javascript file dynamically

Yes, use getScript instead of document.write - it will even allow for a callback once the file loads.

You might want to check if TinyMCE is defined, though, before including it (for subsequent calls to 'Add Comment') so the code might look something like this:

$('#add_comment').click(function() {
    if(typeof TinyMCE == "undefined") {
        $.getScript('tinymce.js', function() {
            TinyMCE.init();
        });
    }
});

Assuming you only have to call init on it once, that is. If not, you can figure it out from here :)

Log record changes in SQL server in an audit table

This is the code with two bug fixes. The first bug fix was mentioned by Royi Namir in the comment on the accepted answer to this question. The bug is described on StackOverflow at Bug in Trigger Code. The second one was found by @Fandango68 and fixes columns with multiples words for their names.

ALTER TRIGGER [dbo].[TR_person_AUDIT]
ON [dbo].[person]
FOR UPDATE
AS
           DECLARE @bit            INT,
                   @field          INT,
                   @maxfield       INT,
                   @char           INT,
                   @fieldname      VARCHAR(128),
                   @TableName      VARCHAR(128),
                   @PKCols         VARCHAR(1000),
                   @sql            VARCHAR(2000),
                   @UpdateDate     VARCHAR(21),
                   @UserName       VARCHAR(128),
                   @Type           CHAR(1),
                   @PKSelect       VARCHAR(1000)


           --You will need to change @TableName to match the table to be audited.
           -- Here we made GUESTS for your example.
           SELECT @TableName = 'PERSON'

           SELECT @UserName = SYSTEM_USER,
                  @UpdateDate = CONVERT(NVARCHAR(30), GETDATE(), 126)

           -- Action
           IF EXISTS (
                  SELECT *
                  FROM   INSERTED
              )
               IF EXISTS (
                      SELECT *
                      FROM   DELETED
                  )
                   SELECT @Type = 'U'
               ELSE
                   SELECT @Type = 'I'
           ELSE
               SELECT @Type = 'D'

           -- get list of columns
           SELECT * INTO #ins
           FROM   INSERTED

           SELECT * INTO #del
           FROM   DELETED

           -- Get primary key columns for full outer join
           SELECT @PKCols = COALESCE(@PKCols + ' and', ' on') 
                  + ' i.[' + c.COLUMN_NAME + '] = d.[' + c.COLUMN_NAME + ']'
           FROM   INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk,
                  INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
           WHERE  pk.TABLE_NAME = @TableName
                  AND CONSTRAINT_TYPE = 'PRIMARY KEY'
                  AND c.TABLE_NAME = pk.TABLE_NAME
                  AND c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME

           -- Get primary key select for insert
           SELECT @PKSelect = COALESCE(@PKSelect + '+', '') 
                  + '''<[' + COLUMN_NAME 
                  + ']=''+convert(varchar(100),
           coalesce(i.[' + COLUMN_NAME + '],d.[' + COLUMN_NAME + ']))+''>'''
           FROM   INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk,
                  INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
           WHERE  pk.TABLE_NAME = @TableName
                  AND CONSTRAINT_TYPE = 'PRIMARY KEY'
                  AND c.TABLE_NAME = pk.TABLE_NAME
                  AND c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME

           IF @PKCols IS NULL
           BEGIN
               RAISERROR('no PK on table %s', 16, -1, @TableName)

               RETURN
           END

           SELECT @field = 0,
                  -- @maxfield = MAX(COLUMN_NAME) 
                  @maxfield = -- FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @TableName


                  MAX(
                      COLUMNPROPERTY(
                          OBJECT_ID(TABLE_SCHEMA + '.' + @TableName),
                          COLUMN_NAME,
                          'ColumnID'
                      )
                  )
           FROM   INFORMATION_SCHEMA.COLUMNS
           WHERE  TABLE_NAME = @TableName






           WHILE @field < @maxfield
           BEGIN
               SELECT @field = MIN(
                          COLUMNPROPERTY(
                              OBJECT_ID(TABLE_SCHEMA + '.' + @TableName),
                              COLUMN_NAME,
                              'ColumnID'
                          )
                      )
               FROM   INFORMATION_SCHEMA.COLUMNS
               WHERE  TABLE_NAME = @TableName
                      AND COLUMNPROPERTY(
                              OBJECT_ID(TABLE_SCHEMA + '.' + @TableName),
                              COLUMN_NAME,
                              'ColumnID'
                          ) > @field

               SELECT @bit = (@field - 1)% 8 + 1

               SELECT @bit = POWER(2, @bit - 1)

               SELECT @char = ((@field - 1) / 8) + 1





               IF SUBSTRING(COLUMNS_UPDATED(), @char, 1) & @bit > 0
                  OR @Type IN ('I', 'D')
               BEGIN
                   SELECT @fieldname = COLUMN_NAME
                   FROM   INFORMATION_SCHEMA.COLUMNS
                   WHERE  TABLE_NAME = @TableName
                          AND COLUMNPROPERTY(
                                  OBJECT_ID(TABLE_SCHEMA + '.' + @TableName),
                                  COLUMN_NAME,
                                  'ColumnID'
                              ) = @field



                   SELECT @sql = 
                          '
           insert into Audit (    Type, 
           TableName, 
           PK, 
           FieldName, 
           OldValue, 
           NewValue, 
           UpdateDate, 
           UserName)
           select ''' + @Type + ''',''' 
                          + @TableName + ''',' + @PKSelect
                          + ',''' + @fieldname + ''''
                          + ',convert(varchar(1000),d.' + @fieldname + ')'
                          + ',convert(varchar(1000),i.' + @fieldname + ')'
                          + ',''' + @UpdateDate + ''''
                          + ',''' + @UserName + ''''
                          + ' from #ins i full outer join #del d'
                          + @PKCols
                          + ' where i.' + @fieldname + ' <> d.' + @fieldname 
                          + ' or (i.' + @fieldname + ' is null and  d.'
                          + @fieldname
                          + ' is not null)' 
                          + ' or (i.' + @fieldname + ' is not null and  d.' 
                          + @fieldname
                          + ' is null)' 



                   EXEC (@sql)
               END
           END

What is a NoReverseMatch error, and how do I fix it?

And make sure your route in the list of routes:

./manage.py show_urls | grep path_or_name

https://github.com/django-extensions/django-extensions

How do I add a Maven dependency in Eclipse?

Open the pom.xml file.

under the project tag add <dependencies> as another tag, and google for the Maven dependencies. I used this to search.

So after getting the dependency create another tag dependency inside <dependencies> tag.

So ultimately it will look something like this.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>doc-examples</groupId>
  <artifactId>lambda-java-example</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>lambda-java-example</name>
  <dependencies>
      <!-- https://mvnrepository.com/artifact/com.amazonaws/aws-lambda-java-core -->
    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-lambda-java-core</artifactId>
        <version>1.0.0</version>
    </dependency>
  </dependencies>
</project>

Hope it helps.

Regarding Java switch statements - using return and omitting breaks in each case

Though the question is old enough it still can be referenced nowdays.

Semantically that is exactly what Java 12 introduced (https://openjdk.java.net/jeps/325), thus, exactly in that simple example provided I can't see any problem or cons.

xcode library not found

If your library file is called libGoogleAnalytics.a you need to put -lGoogleAnalytics so make sure the .a file is named as you'd expect

HorizontalScrollView within ScrollView Touch Handling

It wasn't working well for me. I changed it and now it works smoothly. If anyone interested.

public class ScrollViewForNesting extends ScrollView {
    private final int DIRECTION_VERTICAL = 0;
    private final int DIRECTION_HORIZONTAL = 1;
    private final int DIRECTION_NO_VALUE = -1;

    private final int mTouchSlop;
    private int mGestureDirection;

    private float mDistanceX;
    private float mDistanceY;
    private float mLastX;
    private float mLastY;

    public ScrollViewForNesting(Context context, AttributeSet attrs,
            int defStyle) {
        super(context, attrs, defStyle);

        final ViewConfiguration configuration = ViewConfiguration.get(context);
        mTouchSlop = configuration.getScaledTouchSlop();
    }

    public ScrollViewForNesting(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public ScrollViewForNesting(Context context) {
        this(context,null);
    }    


    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {      
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mDistanceY = mDistanceX = 0f;
                mLastX = ev.getX();
                mLastY = ev.getY();
                mGestureDirection = DIRECTION_NO_VALUE;
                break;
            case MotionEvent.ACTION_MOVE:
                final float curX = ev.getX();
                final float curY = ev.getY();
                mDistanceX += Math.abs(curX - mLastX);
                mDistanceY += Math.abs(curY - mLastY);
                mLastX = curX;
                mLastY = curY;
                break;
        }

        return super.onInterceptTouchEvent(ev) && shouldIntercept();
    }


    private boolean shouldIntercept(){
        if((mDistanceY > mTouchSlop || mDistanceX > mTouchSlop) && mGestureDirection == DIRECTION_NO_VALUE){
            if(Math.abs(mDistanceY) > Math.abs(mDistanceX)){
                mGestureDirection = DIRECTION_VERTICAL;
            }
            else{
                mGestureDirection = DIRECTION_HORIZONTAL;
            }
        }

        if(mGestureDirection == DIRECTION_VERTICAL){
            return true;
        }
        else{
            return false;
        }
    }
}

How do I get a value of a <span> using jQuery?

     $('span id').text(); worked with me

Ping site and return result in PHP

ping is available on almost every OS. So you could make a system call and fetch the result.

How to use confirm using sweet alert?

inside your save button click add this code :

$("#btnSave").click(function (e) {
  e.preventDefault();
  swal("Are you sure?", {
    buttons: {
      yes: {
        text: "Yes",
        value: "yes"
      },
      no: {
        text: "No",
        value: "no"
      }
    }
  }).then((value) => {
    if (value === "yes") {
      // Add Your Custom Code for CRUD
    }
    return false;
  });
});

Multiple contexts with the same path error running web service in Eclipse using Tomcat

In eclipse using tomcat you just open this server.xml file and find Context tag and here you see your context name is more then one you just delete useless contexts and restart your server it will working....

enter image description here

instanceof Vs getClass( )

Do you want to match a class exactly, e.g. only matching FileInputStream instead of any subclass of FileInputStream? If so, use getClass() and ==. I would typically do this in an equals, so that an instance of X isn't deemed equal to an instance of a subclass of X - otherwise you can get into tricky symmetry problems. On the other hand, that's more usually useful for comparing that two objects are of the same class than of one specific class.

Otherwise, use instanceof. Note that with getClass() you will need to ensure you have a non-null reference to start with, or you'll get a NullPointerException, whereas instanceof will just return false if the first operand is null.

Personally I'd say instanceof is more idiomatic - but using either of them extensively is a design smell in most cases.

Why does Git say my master branch is "already up to date" even though it is not?

Just a friendly reminder if you have files locally that aren't in github and yet your git status says

Your branch is up to date with 'origin/master'. nothing to commit, working tree clean

It can happen if the files are in .gitignore

Try running

cat .gitignore 

and seeing if these files show up there. That would explain why git doesn't want to move them to the remote.

Android getText from EditText field

You can simply get the text in editText by applying below code:

EditText editText=(EditText)findViewById(R.id.vnosZadeve);
String text=editText.getText().toString();

then you can toast string text!

Happy coding!

load csv into 2D matrix with numpy for plotting

You can read a CSV file with headers into a NumPy structured array with np.genfromtxt. For example:

import numpy as np

csv_fname = 'file.csv'
with open(csv_fname, 'w') as fp:
    fp.write("""\
"A","B","C","D","E","F","timestamp"
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291111964948E12
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291113113366E12
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291120650486E12
""")

# Read the CSV file into a Numpy record array
r = np.genfromtxt(csv_fname, delimiter=',', names=True, case_sensitive=True)
print(repr(r))

which looks like this:

array([(611.88243, 9089.5601, 5133., 864.07514, 1715.37476, 765.22777, 1.29111196e+12),
       (611.88243, 9089.5601, 5133., 864.07514, 1715.37476, 765.22777, 1.29111311e+12),
       (611.88243, 9089.5601, 5133., 864.07514, 1715.37476, 765.22777, 1.29112065e+12)],
      dtype=[('A', '<f8'), ('B', '<f8'), ('C', '<f8'), ('D', '<f8'), ('E', '<f8'), ('F', '<f8'), ('timestamp', '<f8')])

You can access a named column like this r['E']:

array([1715.37476, 1715.37476, 1715.37476])

Note: this answer previously used np.recfromcsv to read the data into a NumPy record array. While there was nothing wrong with that method, structured arrays are generally better than record arrays for speed and compatibility.

How to use Python to login to a webpage and retrieve cookies for later usage?

import urllib, urllib2, cookielib

username = 'myuser'
password = 'mypassword'

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://www.example.com/login.php', login_data)
resp = opener.open('http://www.example.com/hiddenpage.php')
print resp.read()

resp.read() is the straight html of the page you want to open, and you can use opener to view any page using your session cookie.

How to Get XML Node from XDocument

The .Elements operation returns a LIST of XElements - but what you really want is a SINGLE element. Add this:

XElement Contacts = (from xml2 in XMLDoc.Elements("Contacts").Elements("Node")
                    where xml2.Element("ID").Value == variable
                    select xml2).FirstOrDefault();

This way, you tell LINQ to give you the first (or NULL, if none are there) from that LIST of XElements you're selecting.

Marc

Get Country of IP Address with PHP

Here's an example using http://www.geoplugin.net/json.gp

$ip = $_SERVER['REMOTE_ADDR'];
$details = json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip={$ip}"));
echo $details;

What should my Objective-C singleton look like?

How about

static MyClass *gInstance = NULL;

+ (MyClass *)instance
{
    if (gInstance == NULL) {
        @synchronized(self)
        {
            if (gInstance == NULL)
                gInstance = [[self alloc] init];
        }
    }

    return(gInstance);
}

So you avoid the synchronization cost after initialization?

What does "hard coded" mean?

The antonym of Hard-Coding is Soft-Coding. For a better understanding of Hard Coding, I will introduce both terms.

  • Hard-coding: feature is coded to the system not allowing for configuration;
  • Parametric: feature is configurable via table driven, or properties files with limited parametric values ;
  • Soft-coding: feature uses “engines” that derive results based on any number of parametric values (e.g. business rules in BRE); rules are coded but exist as parameters in system, written in script form

Examples:

// firstName has a hard-coded value of "hello world"
string firstName = "hello world";

// firstName has a non-hard-coded provided as input
Console.WriteLine("first name :");
string firstName = Console.ReadLine();

A hard-coded constant[1]:

float areaOfCircle(int radius)
{
    float area = 0;
    area = 3.14*radius*radius;  //  3.14 is a hard-coded value
    return area;
}

Additionally, hard-coding and soft-coding could be considered to be anti-patterns[2]. Thus, one should strive for balance between hard and soft-coding.

  1. Hard CodingHard coding” is a well-known antipattern against which most web development books warns us right in the preface. Hard coding is the unfortunate practice in which we store configuration or input data, such as a file path or a remote host name, in the source code rather than obtaining it from a configuration file, a database, a user input, or another external source.

    The main problem with hard code is that it only works properly in a certain environment, and at any time the conditions change, we need to modify the source code, usually in multiple separate places.

  2. Soft Coding
    If we try very hard to avoid the pitfall of hard coding, we can easily run into another antipattern called “soft coding”, which is its exact opposite.

    In soft coding, we put things that should be in the source code into external sources, for example we store business logic in the database. The most common reason why we do so, is the fear that business rules will change in the future, therefore we will need to rewrite the code.

    In extreme cases, a soft coded program can become so abstract and convoluted that it is almost impossible to comprehend it (especially for new team members), and extremely hard to maintain and debug.

Sources and Citations:

1: Quora: What does hard-coded something mean in computer programming context?
2: Hongkiat: The 10 Coding Antipatterns You Must Avoid

Further Reading:

Software Engineering SE: Is it ever a good idea to hardcode values into our applications?
Wikipedia: Hardcoding
Wikipedia: Soft-coding

How to delete file from public folder in laravel 5.1

For Delete files from the public folders, we can use the File::delete function into the Laravel. For use File need to use File into the controller OR We can use \File. This consider the root of the file.

// Delete a single file
File::delete($filename);

For delete Multiple files

// Delete multiple files
File::delete($file1, $file2, $file3);

Delete an array of Files

// Delete an array of files
$files = array($file1, $file2);
File::delete($files);

Checking Date format from a string in C#

Use an array of valid dates format, check docs:

string[] formats = { "d/MM/yyyy", "dd/MM/yyyy" };
DateTime parsedDate;
var isValidFormat= DateTime.TryParseExact(inputString, formats, new CultureInfo("en-US"), DateTimeStyles.None, out parsedDate);

if(isValidFormat)
{
    string.Format("{0:d/MM/yyyy}", parsedDate);
}
else
{
    // maybe throw an Exception
}

Download an SVN repository?

.NET utility for downloading google code project files(SVN). Also has Git support. Requires .Net 2.0

http://downloadsvn.codeplex.com/

java.lang.UnsupportedClassVersionError: Unsupported major.minor version 51.0 (unable to load class frontend.listener.StartupListener)

What is your output when you do java -version? This will tell you what version the running JVM is.

The Unsupported major.minor version 51.0 error could mean:

  • Your server is running a lower Java version then the one used to compile your Servlet and vice versa

Either way, uninstall all JVM runtimes including JDK and download latest and re-install. That should fix any Unsupported major.minor error as you will have the lastest JRE and JDK (Maybe even newer then the one used to compile the Servlet)

See: http://www.java.com/en/download/manual.jsp (7 Update 25 )

and here: http://www.oracle.com/technetwork/java/javase/downloads/index.html (Java Platform (JDK) 7u25)

for the latest version of the JRE and JDK respectively.

EDIT:

Most likely your code was written in Java7 however maybe it was done using Java7update4 and your system is running Java7update3. Thus they both are effectively the same major version but the minor versions differ. Only the larger minor version is backward compatible with the lower minor version.

Edit 2 : If you have more than one jdk installed on your pc. you should check that Apache Tomcat is using the same one (jre) you are compiling your programs with. If you installed a new jdk after installing apache it normally won't select the new version.

How to make java delay for a few seconds?

 new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    if (getActivity() != null)
                        getActivity().runOnUiThread(() -> tvCovidAlert.startAnimation(animBounce));
                }
            }, DELAY_TIME_MILI_SECONDS);

How to update multiple columns in single update statement in DB2

For the sake of completeness and the edge case of wanting to update all columns of a row, you can do the following, but consider that the number and types of the fields must match.

Using a data structure

exec sql UPDATE TESTFILE
         SET ROW = :DataDs
         WHERE CURRENT OF CURSOR; //If using a cursor for update

Source: rpgpgm.com

SQL only

UPDATE t1 SET ROW = (SELECT *
                     FROM   t2
                     WHERE  t2.c3 = t1.c3)

Source: ibm.com

Write objects into file with Node.js

could you try doing JSON.stringify(obj);

Like this

 var stringify = JSON.stringify(obj);
fs.writeFileSync('./data.json', stringify , 'utf-8'); 

Python Pandas: How to read only first n rows of CSV files in?

If you only want to read the first 999,999 (non-header) rows:

read_csv(..., nrows=999999)

If you only want to read rows 1,000,000 ... 1,999,999

read_csv(..., skiprows=1000000, nrows=999999)

nrows : int, default None Number of rows of file to read. Useful for reading pieces of large files*

skiprows : list-like or integer Row numbers to skip (0-indexed) or number of rows to skip (int) at the start of the file

and for large files, you'll probably also want to use chunksize:

chunksize : int, default None Return TextFileReader object for iteration

pandas.io.parsers.read_csv documentation

Position absolute but relative to parent

Incase someone wants to postion a child div directly under a parent

#father {
   position: relative;
}

#son1 {
   position: absolute;
   top: 100%;
}

Working demo Codepen

How can I pass a class member function as a callback?

A simple solution "workaround" still is to create a class of virtual functions "interface" and inherit it in the caller class. Then pass it as a parameter "could be in the constructor" of the other class that you want to call your caller class back.

DEFINE Interface:

class CallBack 
{
   virtual callMeBack () {};
};

This is the class that you want to call you back:

class AnotherClass ()
{
     public void RegisterMe(CallBack *callback)
     {
         m_callback = callback;
     }

     public void DoSomething ()
     {
        // DO STUFF
        // .....
        // then call
        if (m_callback) m_callback->callMeBack();
     }
     private CallBack *m_callback = NULL;
};

And this is the class that will be called back.

class Caller : public CallBack
{
    void DoSomthing ()
    {
    }

    void callMeBack()
    {
       std::cout << "I got your message" << std::endl;
    }
};

Ignore cells on Excel line graph

if the data is the result of a formula, then it will never be empty (even if you set it to ""), as having a formula is not the same as an empty cell

There are 2 methods, depending on how static the data is.

The easiest fix is to clear the cells that return empty strings, but that means you will have to fix things if data changes

the other fix involves a little editing of the formula, so instead of setting it equal to "", you set it equal to NA().
For example, if you have =IF(A1=0,"",B1/A1), you would change that to =IF(A1=0,NA(),B1/A1).
This will create the gaps you desire, and will also reflect updates to the data so you don't have to keep fixing it every time

How can I format a number into a string with leading zeros?

Rather simple:

Key = i.ToString("D2");

D stands for "decimal number", 2 for the number of digits to print.

Validating parameters to a Bash script

#!/bin/sh
die () {
    echo >&2 "$@"
    exit 1
}

[ "$#" -eq 1 ] || die "1 argument required, $# provided"
echo $1 | grep -E -q '^[0-9]+$' || die "Numeric argument required, $1 provided"

while read dir 
do
    [ -d "$dir" ] || die "Directory $dir does not exist"
    rm -rf "$dir"
done <<EOF
~/myfolder1/$1/anotherfolder 
~/myfolder2/$1/yetanotherfolder 
~/myfolder3/$1/thisisafolder
EOF

edit: I missed the part about checking if the directories exist at first, so I added that in, completing the script. Also, have addressed issues raised in comments; fixed the regular expression, switched from == to eq.

This should be a portable, POSIX compliant script as far as I can tell; it doesn't use any bashisms, which is actually important because /bin/sh on Ubuntu is actually dash these days, not bash.

What is a raw type and why shouldn't we use it?

Here's another case where raw types will bite you:

public class StrangeClass<T> {
  @SuppressWarnings("unchecked")
  public <X> X getSomethingElse() {
    return (X)"Testing something else!";
  }

  public static void main(String[] args) {
    final StrangeClass<String> withGeneric    = new StrangeClass<>();
    final StrangeClass         withoutGeneric = new StrangeClass();
    final String               value1,
                               value2;

    // Compiles
    value1 = withGeneric.getSomethingElse();

    // Produces compile error:
    // incompatible types: java.lang.Object cannot be converted to java.lang.String
    value2 = withoutGeneric.getSomethingElse();
  }
}

This is counter-intuitive because you'd expect the raw type to only affect methods bound to the class type parameter, but it actually also affects generic methods with their own type parameters.

As was mentioned in the accepted answer, you lose all support for generics within the code of the raw type. Every type parameter is converted to its erasure (which in the above example is just Object).

Can media queries resize based on a div element instead of the screen?

A Media Query inside of an iframe can function as an element query. I've successfully implement this. The idea came from a recent post about Responsive Ads by Zurb. No Javascript!

Sites not accepting wget user agent header

I created a ~/.wgetrc file with the following content (obtained from askapache.com but with a newer user agent, because otherwise it didn’t work always):

header = Accept-Language: en-us,en;q=0.5
header = Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
header = Connection: keep-alive
user_agent = Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:40.0) Gecko/20100101 Firefox/40.0
referer = /
robots = off

Now I’m able to download from most (all?) file-sharing (streaming video) sites.

How do I get the path of a process in Unix / Linux

The below command search for the name of the process in the running process list,and redirect the pid to pwdx command to find the location of the process.

ps -ef | grep "abc" |grep -v grep| awk '{print $2}' | xargs pwdx

Replace "abc" with your specific pattern.

Alternatively, if you could configure it as a function in .bashrc, you may find in handy to use if you need this to be used frequently.

ps1() { ps -ef | grep "$1" |grep -v grep| awk '{print $2}' | xargs pwdx; }

For eg:

[admin@myserver:/home2/Avro/AvroGen]$ ps1 nifi

18404: /home2/Avro/NIFI

Hope this helps someone sometime.....

Passing struct to function

This is how to pass the struct by reference. This means that your function can access the struct outside of the function and modify its values. You do this by passing a pointer to the structure to the function.

#include <stdio.h>
/* card structure definition */
struct card
{
    int face; // define pointer face
}; // end structure card

typedef struct card Card ;

/* prototype */
void passByReference(Card *c) ;

int main(void)
{
    Card c ;
    c.face = 1 ;
    Card *cptr = &c ; // pointer to Card c

    printf("The value of c before function passing = %d\n", c.face);
    printf("The value of cptr before function = %d\n",cptr->face);

    passByReference(cptr);

    printf("The value of c after function passing = %d\n", c.face);

    return 0 ; // successfully ran program
}

void passByReference(Card *c)
{
    c->face = 4;
}

This is how you pass the struct by value so that your function receives a copy of the struct and cannot access the exterior structure to modify it. By exterior I mean outside the function.

#include <stdio.h>


/* global card structure definition */
struct card
{
    int face ; // define pointer face
};// end structure card

typedef struct card Card ;

/* function prototypes */
void passByValue(Card c);

int main(void)
{
    Card c ;
    c.face = 1;

    printf("c.face before passByValue() = %d\n", c.face);

    passByValue(c);

    printf("c.face after passByValue() = %d\n",c.face);
    printf("As you can see the value of c did not change\n");
    printf("\nand the Card c inside the function has been destroyed"
        "\n(no longer in memory)");
}


void passByValue(Card c)
{
    c.face = 5;
}

Check div is hidden using jquery

You can check the CSS display property:

if ($('#car').css('display') == 'none') {
    alert('Car 2 is hidden');
}

Here is a demo: http://jsfiddle.net/YjP4K/

How to prevent Screen Capture in Android

For Java users write this line above your setContentView(R.layout.activity_main);

getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);

For kotlin users

window.setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE)

Easily measure elapsed time

time(NULL) returns the number of seconds elapsed since 01/01/1970 at 00:00 (the Epoch). So the difference between the two values is the number of seconds your processing took.

int t0 = time(NULL);
doSomthing();
doSomthingLong();
int t1 = time(NULL);

printf ("time = %d secs\n", t1 - t0);

You can get finer results with getttimeofday(), which return the current time in seconds, as time() does and also in microseconds.

Regex to match any character including new lines

If you don't want add the /s regex modifier (perhaps you still want . to retain its original meaning elsewhere in the regex), you may also use a character class. One possibility:

[\S\s]

a character which is not a space or is a space. In other words, any character.

You can also change modifiers locally in a small part of the regex, like so:

(?s:.)

Select arrow style change

You can also try this:

Heres a Picture of it!

And also run code snippet!

CSS and then HTML:

_x000D_
_x000D_
           #select-category {
            font-size: 100%;
            padding: 10px;
            padding-right: 180px;
            margin-left: 30px;
            border-radius: 1000000px;
            border: 1px solid #707070;
            outline: none;
            -webkit-appearance: none;
            -moz-appearance: none;
            background: transparent;
            background-image: url("data:image/svg+xml;utf8,<svg fill='black' height='34' viewBox='0 0 24 24' width='24' xmlns='http://www.w3.org/2000/svg'><path d='M7 10l5 5 5-5z'/><path d='M0 0h24v24H0z' fill='none'/></svg>");
            background-repeat: no-repeat;
            background-position-x: 100%;
            background-position-y: 5px;
            margin-right: 2rem;
        }
_x000D_
                <select id="select-category">
                    <option>Category</option>
                    <option>Category 2</option>
                    <option>Category 3</option>
                    <option>Category 4</option>
                    <option>Category 5</option>
                    <option>Category 6</option>
                    <option>Category 7</option>
                    <option>Category 8</option>
                    <option>Category 9</option>
                    <option>Category 10</option>
                    <option>Category 11</option>
                    <option>Category 12</option>
                </select>
_x000D_
_x000D_
_x000D_

How to crop an image using C#?

use bmp.SetResolution(image.HorizontalResolution, image .VerticalResolution);

this may be necessary to do even if you implement best answer here especially if your image is real great and resolutions are not exactly 96.0

My test example:

    static Bitmap LoadImage()
    {
        return (Bitmap)Bitmap.FromFile( @"e:\Tests\d_bigImage.bmp" ); // here is large image 9222x9222 pixels and 95.96 dpi resolutions
    }

    static void TestBigImagePartDrawing()
    {
        using( var absentRectangleImage = LoadImage() )
        {
            using( var currentTile = new Bitmap( 256, 256 ) )
            {
                currentTile.SetResolution(absentRectangleImage.HorizontalResolution, absentRectangleImage.VerticalResolution);

                using( var currentTileGraphics = Graphics.FromImage( currentTile ) )
                {
                    currentTileGraphics.Clear( Color.Black );
                    var absentRectangleArea = new Rectangle( 3, 8963, 256, 256 );
                    currentTileGraphics.DrawImage( absentRectangleImage, 0, 0, absentRectangleArea, GraphicsUnit.Pixel );
                }

                currentTile.Save(@"e:\Tests\Tile.bmp");
            }
        }
    }

Is there an arraylist in Javascript?

Just use array.push(something);. Javascript arrays are like ArrayLists in this respect - they can be treated like they have a flexible length (unlike java arrays).

What is the difference between dynamic and static polymorphism in Java?

Method overloading is a compile time polymorphism, let's take an example to understand the concept.

class Person                                            //person.java file
{
    public static void main ( String[] args )
    {
      Eat e = new Eat();
       e.eat(noodle);                                //line 6
    }

   void eat (Noodles n)      //Noodles is a object    line 8                     
   {

   }
   void eat ( Pizza p)           //Pizza is a object
  {

  }

}

In this example, Person has a eat method which represents that he can either eat Pizza or Noodles. That the method eat is overloaded when we compile this Person.java the compiler resolves the method call " e.eat(noodles) [which is at line 6] with the method definition specified in line 8 that is it method which takes noodles as parameter and the entire process is done by Compiler so it is Compile time Polymorphism. The process of replacement of the method call with method definition is called as binding, in this case, it is done by the compiler so it is called as early binding.

Unable to connect with remote debugger

Inculding all impressive answers the expert developers specially Ribamar Santos provided, if you didn't get it working, you must check something more tricky!

Something like Airplane mode of your (emulated) phone! Or your network status of Emulator (Data status and Voice status on Cellular tab of Emulator configuration) that might be manipulated to don't express network! for some emulation needs!

I've overcome to this problem by this trick! It was a bit breathtaking debug to find this hole!

"Too many characters in character literal error"

You cannot treat == or || as chars, since they are not chars, but a sequence of chars.

You could make your switch...case work on strings instead.

Unable to install boto3

Don't use sudo in a virtual environment because it ignores the environment's variables and therefore sudo pip refers to your global pip installation.

So with your environment activated, rerun pip install boto3 but without sudo.

Get IPv4 addresses from Dns.GetHostEntry()

    public Form1()
    {
        InitializeComponent();

        string myHost = System.Net.Dns.GetHostName();
        string myIP = null;

        for (int i = 0; i <= System.Net.Dns.GetHostEntry(myHost).AddressList.Length - 1; i++)
        {
            if (System.Net.Dns.GetHostEntry(myHost).AddressList[i].IsIPv6LinkLocal == false)
            {
                myIP = System.Net.Dns.GetHostEntry(myHost).AddressList[i].ToString();
            }
        }
    }

Declare myIP and myHost in public Variable and use in any function of the form.

What's the difference between .so, .la and .a library files?

.so files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.

.a files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar command -- a predecessor of tar that's now just used for making libraries) of the original .o object files.

.la files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?

Static and dynamic libraries each have pros and cons.

Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.

Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.

Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.

Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.

Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.

Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.

Dynamic libraries are especially useful for system libraries, like libc. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.

PHP, display image with Header()

Browsers make their best guess with the data they receive. This works for markup (which Websites often get wrong) and other media content. A program that receives a file can often figure out what its received regardless of the MIME content type it's been told.

This isn't something you should rely on however. It's recommended you always use the correct MIME content.

java.lang.ClassNotFoundException: org.apache.jsp.index_jsp

I also lost a half of day trying to fix this.

It appeared that root was my project pom.xml file with dependency:

    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.1</version>
        <scope>provided</scope>
    </dependency>

Other members of the team had no problems. At the end it appeared, that I got newer tomcat which has different version of jsp-api provided (in tomcat 7.0.60 and above it will be jsp-api 2.2).

So in this case, options would be:

a) installing different (older/newer) tomcat like (Exactly what I did, because team is on older version)
b) changing dependency scope to 'compile'
c) update whole project dependencies to the actual version of Tomcat/lib provided APIs
d) put matching version of the jsp-api.jar in {tomcat folder}/lib

How to retrieve a recursive directory and file list from PowerShell excluding some files and folders?

Recently, I explored the possibilities to parameterize the folder to scan through and the place where the result of recursive scan will be stored. At the end, I also did summarize the number of folders scanned and number of files inside as well. Sharing it with community in case it may help other developers.

    ##Script Starts
    #read folder to scan and file location to be placed

    $whichFolder = Read-Host -Prompt 'Which folder to Scan?'  
    $whereToPlaceReport = Read-Host -Prompt 'Where to place Report'
    $totalFolders = 1
    $totalFiles = 0

    Write-Host "Process started..."

    #IMP separator ? : used as a file in window cannot contain this special character in the file name

    #Get Foldernames into Variable for ForEach Loop
    $DFSFolders = get-childitem -path $whichFolder | where-object {$_.Psiscontainer -eq "True"} |select-object name ,fullName

    #Below Logic for Main Folder
    $mainFiles = get-childitem -path "C:\Users\User\Desktop" -file
    ("Folder Path" + "?" + "Folder Name" + "?" + "File Name " + "?"+ "File Length" )| out-file "$whereToPlaceReport\Report.csv" -Append

    #Loop through folders in main Directory
    foreach($file in $mainFiles)
    {

    $totalFiles = $totalFiles + 1
    ("C:\Users\User\Desktop" + "?" + "Main Folder" + "?"+ $file.name + "?" + $file.length ) | out-file "$whereToPlaceReport\Report.csv" -Append
    }


    foreach ($DFSfolder in $DFSfolders)
    {
    #write the folder name in begining
    $totalFolders = $totalFolders + 1

    write-host " Reading folder C:\Users\User\Desktop\$($DFSfolder.name)"
    #$DFSfolder.fullName | out-file "C:\Users\User\Desktop\PoC powershell\ok2.csv" -Append
    #For Each Folder obtain objects in a specified directory, recurse then filter for .sft file type, obtain the filename, then group, sort and eventually show the file name and total incidences of it.

    $files = get-childitem -path "$whichFolder\$($DFSfolder.name)" -recurse

    foreach($file in $files)
    {
    $totalFiles = $totalFiles + 1
    ($DFSfolder.fullName + "?" + $DFSfolder.name + "?"+ $file.name + "?" + $file.length ) | out-file "$whereToPlaceReport\Report.csv" -Append
    }

    }


    # If running in the console, wait for input before closing.
    if ($Host.Name -eq "ConsoleHost")
    {

    Write-Host "" 
    Write-Host ""
    Write-Host ""

    Write-Host  "                            **Summary**"  -ForegroundColor Red
    Write-Host  "                            ------------" -ForegroundColor Red

    Write-Host  "                           Total Folders Scanned = $totalFolders "  -ForegroundColor Green
    Write-Host  "                           Total Files   Scanned = $totalFiles "     -ForegroundColor Green

    Write-Host "" 
    Write-Host "" 
        Write-Host "I have done my Job,Press any key to exit" -ForegroundColor white
        $Host.UI.RawUI.FlushInputBuffer()   # Make sure buffered input doesn't "press a key" and skip the ReadKey().
        $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyUp") > $null
    }

##Output

enter image description here

##Bat Code to run above powershell command

@ECHO OFF
SET ThisScriptsDirectory=%~dp0
SET PowerShellScriptPath=%ThisScriptsDirectory%MyPowerShellScript.ps1
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%PowerShellScriptPath%""' -Verb RunAs}";

Print: Entry, ":CFBundleIdentifier", Does Not Exist

I'v tried all of these solutions but the one that has worked for me is:

  1. run react-native upgrade
  2. open xcode
  3. run the application in xCode
  4. works fine!

iOS 8 removed "minimal-ui" viewport property, are there other "soft fullscreen" solutions?

I want to comment/partially answer/share my thoughts. I am using the overflow-y:scroll technique for a big upcoming project of mine. Using it has two MAJOR advantages.

a) You can use a drawer with action buttons from the bottom of the screen; if the document scrolls and the bottom bar disappears, tapping on a button located at the bottom of the screen will first make the bottom bar appear, and then be clickable. Also, the way this thing works, causes trouble with modals that have buttons at the far bottom.

b) When using an overflown element, the only things that are repainted in case of major css changes are the ones in the viewable screen. This gave me a huge performance boost when using javascript to alter css of multiple elements on the fly. For example, if you have a list of 20 elements you need repainted and only two of them are on-screen in the overflown element, only those are repainted while the rest are repainted when scrolling. Without it all 20 elements are repainted.

..of course it depends on the project and if you need any of the functionality I mentioned. Google uses overflown elements for gmail to use the functionality I described on a). Imo, it's worth the while, even considering the small height in older iphones (372px as you said).

CSS to hide INPUT BUTTON value text

overflow:hidden and padding-left are working fine for me.

For Firefox:

width:12px;
height:20px;
background-image:url(images/arrow.gif);
color:transparent;
overflow:hidden;
border:0;

For the IEs:

padding-left:1000px;

SQL Case Sensitive String Compare

You can also convert that attribute as case sensitive using this syntax :

ALTER TABLE Table1
ALTER COLUMN Column1 VARCHAR(200)
COLLATE SQL_Latin1_General_CP1_CS_AS

Now your search will be case sensitive.

If you want to make that column case insensitive again, then use

ALTER TABLE Table1
ALTER COLUMN Column1 VARCHAR(200)
COLLATE SQL_Latin1_General_CP1_CI_AS

Maven in Eclipse: step by step installation

First install maven in your system and set Maven environment variables

  1. M2_HOME: ....\apache-maven-3.0.5 \ maven installed path
  2. M2_Repo: D:\maven_repo \If change maven repo location
  3. M2: %M2_HOME%\bin

Steps to Configures maven on Eclipse IDE:

  • Select Window -> Preferences Note: If Maven option is not present, then add maven 3 to eclipse or install it.
  • Add the Maven location of your system

To check maven is configured properly:

  • Open Eclipse and click on Windows -> Preferences

  • Choose Maven from left panel, and select installations.

  • Click on Maven -> "User Settings" option form left panel, to check local repository location.

Create two threads, one display odd & other even numbers

Below is the code which uses lock on a shared object which has the number to be printed. It guarantees the sequence also unlike the above solution.

public class MultiThreadPrintNumber {
  int i = 1;

  public synchronized void printNumber(String threadNm) throws InterruptedException{

      if(threadNm.equals("t1")){
        if(i%2 == 1){
          System.out.println(Thread.currentThread().getName()+"--"+ i++);
          notify();
        } else {
          wait();
        }
      } else if(threadNm.equals("t2")){
        if(i%2 == 0){
          System.out.println(Thread.currentThread().getName()+"--"+ i++);
          notify();
        } else {
          wait();
        }
      }

    }

  public static void main(String[] args) {
    final MultiThreadPrintNumber obj = new MultiThreadPrintNumber();
    Thread t1 = new Thread(new Runnable() {

      @Override
      public void run() {
        try {
          while(obj.i <= 10){

            obj.printNumber(Thread.currentThread().getName());
          }
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        System.out.println("done t1");
      }
    });
    Thread t2 = new Thread(new Runnable() {

      @Override
      public void run() {
        try {
          while(obj.i <=10){
            obj.printNumber(Thread.currentThread().getName());
          }
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        System.out.println("done t2");
      }
    });

    t1.setName("t1");
    t2.setName("t2");
    t1.start();
    t2.start();
  }
}

The output will look like: t1--1 t2--2 t1--3 t2--4 t1--5 t2--6 t1--7 t2--8 t1--9 t2--10 done t2 done t1

create a text file using javascript

From a web page this cannot work since IE restricts the use of that object.

How to check if an object is a list or tuple (but not string)?

Generally speaking, the fact that a function which iterates over an object works on strings as well as tuples and lists is more feature than bug. You certainly can use isinstance or duck typing to check an argument, but why should you?

That sounds like a rhetorical question, but it isn't. The answer to "why should I check the argument's type?" is probably going to suggest a solution to the real problem, not the perceived problem. Why is it a bug when a string is passed to the function? Also: if it's a bug when a string is passed to this function, is it also a bug if some other non-list/tuple iterable is passed to it? Why, or why not?

I think that the most common answer to the question is likely to be that developers who write f("abc") are expecting the function to behave as though they'd written f(["abc"]). There are probably circumstances where it makes more sense to protect developers from themselves than it does to support the use case of iterating across the characters in a string. But I'd think long and hard about it first.

Get ASCII value at input word

char ch='A';

System.out.println((int)ch);

What is the difference between .NET Core and .NET Standard Class Library project types?

Another way of explaining the difference could be with real world examples, as most of us mere mortals will use existing tools and frameworks (Xamarin, Unity, etc.) to do the job.

So, with .NET Framework you have all the .NET tools to work with, but you can only target Windows applications (UWP, Windows Forms, ASP.NET, etc.). Since .NET Framework is closed source there isn't much to do about it.

With .NET Core you have fewer tools, but you can target the main desktop platforms (Windows, Linux, and Mac). This is specially useful in ASP.NET Core applications, since you can now host ASP.NET on Linux (cheaper hosting prices). Now, since .NET Core was open sourced, it's technically possible to develop libraries for other platforms. But since there aren't frameworks that support it, I don't think that's a good idea.

With .NET Standard you have even fewer tools, but you can target all/most platforms. You can target mobile thanks to Xamarin, and you can even target game consoles thanks to Mono/Unity. It's also possible to target web clients with the UNO platform and Blazor (although both are kind of experimental right now).

In a real-world application you may need to use all of them. For example, I developed a point of sale application that had the following architecture:

Shared both server and slient:

  • A .NET Standard library that handles the models of my application.
  • A .NET Standard library that handles the validation of data sent by the clients.

Since it's a .NET Standard library, it can be used in any other project (client and server).

Also a nice advantage of having the validation on a .NET standard library since I can be sure the same validation is applied on the server and the client. Server is mandatory, while client is optional and useful to reduce traffic.

Server side (Web API):

  • A .NET Standard (could be .NET Core as well) library that handles all the database connections.

  • A .NET Core project that handles the Rest API and makes use of the database library.

As this is developed in .NET Core, I can host the application on a Linux server.

Client side (MVVM with WPF + Xamarin.Forms Android/iOS):

  • A .NET Standard library that handles the client API connection.

  • A .NET Standard library that handles the ViewModels logic. It is used in all the views.

  • A .NET Framework WPF application that handles the WPF views for a windows application. WPF applications can be .NET core now, although they only work on Windows currently. AvaloniaUI is a good alternative for making desktop GUI applications for other desktop platforms.

  • A .NET Standard library that handles Xamarin forms views.

  • A Xamarin Android and Xamarin iOS project.

So you can see that there's a big advantage here on the client side of the application, since I can reuse both .NET Standard libraries (client API and ViewModels) and just make views with no logic for the WPF, Xamarin and iOS applications.

unable to set private key file: './cert.pem' type PEM

I have a similar situation, but I use the key and the certificate in different files.

in my case you can check the matching of the key and the lock by comparing the hashes (see https://michaelheap.com/curl-58-unable-to-set-private-key-file-server-key-type-pem/). This helped me to identify inconsistencies.

How to concat string + i?

For versions prior to R2014a...

One easy non-loop approach would be to use genvarname to create a cell array of strings:

>> N = 5;
>> f = genvarname(repmat({'f'}, 1, N), 'f')

f = 

    'f1'    'f2'    'f3'    'f4'    'f5'

For newer versions...

The function genvarname has been deprecated, so matlab.lang.makeUniqueStrings can be used instead in the following way to get the same output:

>> N = 5;
>> f = strrep(matlab.lang.makeUniqueStrings(repmat({'f'}, 1, N), 'f'), '_', '')

 f =
   1×5 cell array

     'f1'    'f2'    'f3'    'f4'    'f5'

What does this format means T00:00:00.000Z?

As one person may have already suggested,

I passed the ISO 8601 date string directly to moment like so...

`moment.utc('2019-11-03T05:00:00.000Z').format('MM/DD/YYYY')`

or

`moment('2019-11-03T05:00:00.000Z').utc().format('MM/DD/YYYY')`

either of these solutions will give you the same result.

`console.log(moment('2019-11-03T05:00:00.000Z').utc().format('MM/DD/YYYY')) // 11/3/2019`

How can I apply a border only inside a table?

If you are doing what I believe you are trying to do, you'll need something a little more like this:

table {
  border-collapse: collapse;
}
table td, table th {
  border: 1px solid black;
}
table tr:first-child th {
  border-top: 0;
}
table tr:last-child td {
  border-bottom: 0;
}
table tr td:first-child,
table tr th:first-child {
  border-left: 0;
}
table tr td:last-child,
table tr th:last-child {
  border-right: 0;
}

jsFiddle Demo

The problem is that you are setting a 'full border' around all the cells, which make it appear as if you have a border around the entire table.

Cheers.

EDIT: A little more info on those pseudo-classes can be found on quirksmode, and, as to be expected, you are pretty much S.O.L. in terms of IE support.

How to delete parent element using jQuery

Use parents() instead of parent():

$("a").click(function(event) {
  event.preventDefault();
  $(this).parents('.li').remove();
});

Update TextView Every Second

If you want to show time on textview then better use Chronometer or TextClock

Using Chronometer:This was added in API 1. It has lot of option to customize it.

Your xml

<Chronometer
    android:id="@+id/chronometer"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="30sp" />

Your activity

Chronometer mChronometer=(Chronometer) findViewById(R.id.chronometer);
mChronometer.setBase(SystemClock.elapsedRealtime());
mChronometer.start();

Using TextClock: This widget is introduced in API level 17. I personally like Chronometer.

Your xml

<TextClock
    android:id="@+id/textClock"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="30dp"
    android:format12Hour="hh:mm:ss a"
    android:gravity="center_horizontal"
    android:textColor="#d41709"
    android:textSize="44sp"
    android:textStyle="bold" />

Thats it, you are done.

You can use any of these two widgets. This will make your life easy.

how to get program files x86 env variable?

Another relevant environment variable is:

%ProgramW6432%

So, on a 64-bit machine running in 32-bit (WOW64) mode:

  • echo %programfiles% ==> C:\Program Files (x86)
  • echo %programfiles(x86)% ==> C:\Program Files (x86)
  • echo %ProgramW6432% ==> C:\Program Files

From Wikipedia:

The %ProgramFiles% variable points to the Program Files directory, which stores all the installed programs of Windows and others. The default on English-language systems is "C:\Program Files". In 64-bit editions of Windows (XP, 2003, Vista), there are also %ProgramFiles(x86)%, which defaults to "C:\Program Files (x86)", and %ProgramW6432%, which defaults to "C:\Program Files". The %ProgramFiles% itself depends on whether the process requesting the environment variable is itself 32-bit or 64-bit (this is caused by Windows-on-Windows 64-bit redirection).

Reference: http://en.wikipedia.org/wiki/Environment_variable

gzip: stdin: not in gzip format tar: Child returned status 1 tar: Error is not recoverable: exiting now

Just click first on that link and go to HTML page where actual downloads or mirrors are.

Its really misleading to have full link which ends in .tgz when it actually leads to HTML page where real download links are. I had this problem downloading Apache Spark and wget-ing it into Ubuntu.

https://spark.apache.org/downloads.html

What does SQL clause "GROUP BY 1" mean?

In addition to grouping by the field name, you may also group by ordinal, or position of the field within the table. 1 corresponds to the first field (regardless of name), 2 is the second, and so on.

This is generally ill-advised if you're grouping on something specific, since the table/view structure may change. Additionally, it may be difficult to quickly comprehend what your SQL query is doing if you haven’t memorized the table fields.

If you are returning a unique set, or quickly performing a temporary lookup, this is nice shorthand syntax to reduce typing. If you plan to run the query again at some point, I’d recommend replacing those to avoid future confusion and unexpected complications (due to scheme changes).

What exactly does the T and Z mean in timestamp?

The T doesn't really stand for anything. It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time.

The Z stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).

Both characters are just static letters in the format, which is why they are not documented by the datetime.strftime() method. You could have used Q or M or Monty Python and the method would have returned them unchanged as well; the method only looks for patterns starting with % to replace those with information from the datetime object.

Meaning of @classmethod and @staticmethod for beginner?

One would use @classmethod when he/she would want to change the behaviour of the method based on which subclass is calling the method. remember we have a reference to the calling class in a class method.

While using static you would want the behaviour to remain unchanged across subclasses

Example:

class Hero:

  @staticmethod
  def say_hello():
     print("Helllo...")

  @classmethod
  def say_class_hello(cls):
     if(cls.__name__=="HeroSon"):
        print("Hi Kido")
     elif(cls.__name__=="HeroDaughter"):
        print("Hi Princess")

class HeroSon(Hero):
  def say_son_hello(self):
     print("test  hello")



class HeroDaughter(Hero):
  def say_daughter_hello(self):
     print("test  hello daughter")


testson = HeroSon()

testson.say_class_hello() #Output: "Hi Kido"

testson.say_hello() #Outputs: "Helllo..."

testdaughter = HeroDaughter()

testdaughter.say_class_hello() #Outputs: "Hi Princess"

testdaughter.say_hello() #Outputs: "Helllo..."

How do I write good/correct package __init__.py files

Your __init__.py should have a docstring.

Although all the functionality is implemented in modules and subpackages, your package docstring is the place to document where to start. For example, consider the python email package. The package documentation is an introduction describing the purpose, background, and how the various components within the package work together. If you automatically generate documentation from docstrings using sphinx or another package, the package docstring is exactly the right place to describe such an introduction.

For any other content, see the excellent answers by firecrow and Alex Martelli.

How do I join two lists in Java?

Off the top of my head, I can shorten it by one line:

List<String> newList = new ArrayList<String>(listOne);
newList.addAll(listTwo);

Disabling user input for UITextfield in swift

Swift 4.2 / Xcode 10.1:

Just uncheck behavior Enabled in your storyboard -> attributes inspector.

Is there a macro to conditionally copy rows to another worksheet?

If this is just a one-off exercise, as an easier alternative, you could apply filters to your source data, and then copy and paste the filtered rows into your new worksheet?

Delete the first three rows of a dataframe in pandas

df.drop(df.index[[0,2]])

Pandas uses zero based numbering, so 0 is the first row, 1 is the second row and 2 is the third row.

java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/JsonFactory

The requested jar is probably not jackson-annotations-x.y.z.jar but jackson-core-x.y.z.jar which could be found here: http://www.java2s.com/Code/Jar/j/Downloadjacksoncore220rc1jar.htm

Displaying Total in Footer of GridView and also Add Sum of columns(row vise) in last Column

Sample Code: To set Footer text programatically

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
      if (e.Row.RowType == DataControlRowType.Footer)
      {
         Label lbl = (Label)e.Row.FindControl("lblTotal");
         lbl.Text = grdTotal.ToString("c");
      }
   }

UPDATED CODE:

  decimal sumFooterValue = 0;
  protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
         string sponsorBonus = ((Label)e.Row.FindControl("Label2")).Text;
         string pairingBonus = ((Label)e.Row.FindControl("Label3")).Text;
         string staticBonus = ((Label)e.Row.FindControl("Label4")).Text;
         string leftBonus = ((Label)e.Row.FindControl("Label5")).Text;
         string rightBonus = ((Label)e.Row.FindControl("Label6")).Text;
         decimal totalvalue = Convert.ToDecimal(sponsorBonus) + Convert.ToDecimal(pairingBonus) + Convert.ToDecimal(staticBonus) + Convert.ToDecimal(leftBonus) + Convert.ToDecimal(rightBonus);
         e.Row.Cells[6].Text = totalvalue.ToString();
         sumFooterValue += totalvalue; 
        }

    if (e.Row.RowType == DataControlRowType.Footer)
        {
           Label lbl = (Label)e.Row.FindControl("lblTotal");
           lbl.Text = sumFooterValue.ToString();
        }

   }

In .aspx Page

 <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" 
        AutoGenerateColumns="False" DataKeyNames="ID" CellPadding="4" 
        ForeColor="#333333" GridLines="None" ShowFooter="True" 
                onrowdatabound="GridView1_RowDataBound">
        <RowStyle BackColor="#EFF3FB" />
        <Columns>
            <asp:TemplateField HeaderText="Report Date" SortExpression="reportDate">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("reportDate") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" 
                        Text='<%# Bind("reportDate", "{0:dd MMMM yyyy}") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Sponsor Bonus" SortExpression="sponsorBonus">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("sponsorBonus") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label2" runat="server" 
                        Text='<%# Bind("sponsorBonus", "{0:0.00}") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Pairing Bonus" SortExpression="pairingBonus">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("pairingBonus") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label3" runat="server" 
                        Text='<%# Bind("pairingBonus", "{0:c}") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Static Bonus" SortExpression="staticBonus">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("staticBonus") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label4" runat="server" Text='<%# Bind("staticBonus") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Left Bonus" SortExpression="leftBonus">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox5" runat="server" Text='<%# Bind("leftBonus") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label5" runat="server" Text='<%# Bind("leftBonus") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Right Bonus" SortExpression="rightBonus">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox6" runat="server" Text='<%# Bind("rightBonus") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label6" runat="server" Text='<%# Bind("rightBonus") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Total" SortExpression="total">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox7" runat="server"></asp:TextBox>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:Label ID="lbltotal" runat="server" Text="Label"></asp:Label>
                </FooterTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label7" runat="server"></asp:Label>
                </ItemTemplate>
                <ItemStyle Width="100px" />

            </asp:TemplateField>
        </Columns>
        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <EditRowStyle BackColor="#2461BF" />
        <AlternatingRowStyle BackColor="White" />            
    </asp:GridView>

My Blog - Asp.net Gridview Article

Force browser to clear cache

Update 2012

This is an old question but I think it needs a more up to date answer because now there is a way to have more control of website caching.

In Offline Web Applications (which is really any HTML5 website) applicationCache.swapCache() can be used to update the cached version of your website without the need for manually reloading the page.

This is a code example from the Beginner's Guide to Using the Application Cache on HTML5 Rocks explaining how to update users to the newest version of your site:

// Check if a new cache is available on page load.
window.addEventListener('load', function(e) {

  window.applicationCache.addEventListener('updateready', function(e) {
    if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
      // Browser downloaded a new app cache.
      // Swap it in and reload the page to get the new hotness.
      window.applicationCache.swapCache();
      if (confirm('A new version of this site is available. Load it?')) {
        window.location.reload();
      }
    } else {
      // Manifest didn't changed. Nothing new to server.
    }
  }, false);

}, false);

See also Using the application cache on Mozilla Developer Network for more info.

Update 2016

Things change quickly on the Web. This question was asked in 2009 and in 2012 I posted an update about a new way to handle the problem described in the question. Another 4 years passed and now it seems that it is already deprecated. Thanks to cgaldiolo for pointing it out in the comments.

Currently, as of July 2016, the HTML Standard, Section 7.9, Offline Web applications includes a deprecation warning:

This feature is in the process of being removed from the Web platform. (This is a long process that takes many years.) Using any of the offline Web application features at this time is highly discouraged. Use service workers instead.

So does Using the application cache on Mozilla Developer Network that I referenced in 2012:

Deprecated
This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time.

See also Bug 1204581 - Add a deprecation notice for AppCache if service worker fetch interception is enabled.

Can You Get A Users Local LAN IP Address Via JavaScript?

Now supported in internal-ip!

An RTCPeerConnection can be used. In browsers like Chrome where a getUserMedia permission is required, we can just detect available input devices and request for them.

const internalIp = async () => {
    if (!RTCPeerConnection) {
        throw new Error("Not supported.")
    }

    const peerConnection = new RTCPeerConnection({ iceServers: [] })

    peerConnection.createDataChannel('')
    peerConnection.createOffer(peerConnection.setLocalDescription.bind(peerConnection), () => { })

    peerConnection.addEventListener("icecandidateerror", (event) => {
        throw new Error(event.errorText)
    })

    return new Promise(async resolve => {
        peerConnection.addEventListener("icecandidate", async ({candidate}) => {
            peerConnection.close()
            
            if (candidate && candidate.candidate) {
                const result = candidate.candidate.split(" ")[4]
                if (result.endsWith(".local")) {
                    const inputDevices = await navigator.mediaDevices.enumerateDevices()
                    const inputDeviceTypes = inputDevices.map(({ kind }) => kind)

                    const constraints = {}

                    if (inputDeviceTypes.includes("audioinput")) {
                        constraints.audio = true
                    } else if (inputDeviceTypes.includes("videoinput")) {
                        constraints.video = true
                    } else {
                        throw new Error("An audio or video input device is required!")
                    }

                    const mediaStream = await navigator.mediaDevices.getUserMedia(constraints)
                    mediaStream.getTracks().forEach(track => track.stop())
                    resolve(internalIp())
                }
                resolve(result)
            }
        })
    })
}

What is the difference between `Enum.name()` and `Enum.toString()`?

Use toString() when you want to present information to a user (including a developer looking at a log). Never rely in your code on toString() giving a specific value. Never test it against a specific string. If your code breaks when someone correctly changes the toString() return, then it was already broken.

If you need to get the exact name used to declare the enum constant, you should use name() as toString may have been overridden.

Global variables in R

I found a solution for how to set a global variable in a mailinglist posting via assign:

a <- "old"
test <- function () {
   assign("a", "new", envir = .GlobalEnv)
}
test()
a  # display the new value

TypeError: Cannot read property "0" from undefined

Looks like what you're trying to do is access property '0' of an undefined value in your 'data' array. If you look at your while statement, it appears this is happening because you are incrementing 'i' by 1 for each loop. Thus, the first time through, you will access, 'data[1]', but on the next loop, you'll access 'data[2]' and so on and so forth, regardless of the length of the array. This will cause you to eventually hit an array element which is undefined, if you never find an item in your array with property '0' which is equal to 'name'.

Ammend your while statement to this...

for(var iIndex = 1; iIndex <= data.length; iIndex++){
    if (data[iIndex][0] === name){
         break;
    };
    Logger.log(data[i][0]);
 };

Raw_Input() Is Not Defined

For Python 3.x, use input(). For Python 2.x, use raw_input(). Don't forget you can add a prompt string in your input() call to create one less print statement. input("GUESS THAT NUMBER!").

ERROR Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies

Just Add AjaxControlToolkit.dll to your Reference folder.

On your Project Solution

Right Click on Reference Folder  > Add Reference > browse  AjaxControlToolkit.dll .

Then build.

Regards

Can I calculate z-score with R?

if x is a vector with raw scores then scale(x) is a vector with standardized scores.

Or manually: (x-mean(x))/sd(x)

Getting the value of an attribute in XML

This is more of an xpath question, but like this, assuming the context is the parent element:

<xsl:value-of select="name/@attribute1" />

Count number of occurrences for each unique value

Yes, you can use GROUP BY:

SELECT time,
       activities,
       COUNT(*)
FROM table
GROUP BY time, activities;

What is the best way to convert seconds into (Hour:Minutes:Seconds:Milliseconds) time?

For .Net <= 4.0 Use the TimeSpan class.

TimeSpan t = TimeSpan.FromSeconds( secs );

string answer = string.Format("{0:D2}h:{1:D2}m:{2:D2}s:{3:D3}ms", 
                t.Hours, 
                t.Minutes, 
                t.Seconds, 
                t.Milliseconds);

(As noted by Inder Kumar Rathore) For .NET > 4.0 you can use

TimeSpan time = TimeSpan.FromSeconds(seconds);

//here backslash is must to tell that colon is
//not the part of format, it just a character that we want in output
string str = time .ToString(@"hh\:mm\:ss\:fff");

(From Nick Molyneux) Ensure that seconds is less than TimeSpan.MaxValue.TotalSeconds to avoid an exception.

SessionTimeout: web.xml vs session.maxInactiveInterval()

Now, i'm being told that this will terminate the session (or is it all sessions?) in the 15th minute of use, regardless their activity.

This is wrong. It will just kill the session when the associated client (webbrowser) has not accessed the website for more than 15 minutes. The activity certainly counts, exactly as you initially expected, seeing your attempt to solve this.

The HttpSession#setMaxInactiveInterval() doesn't change much here by the way. It does exactly the same as <session-timeout> in web.xml, with the only difference that you can change/set it programmatically during runtime. The change by the way only affects the current session instance, not globally (else it would have been a static method).


To play around and experience this yourself, try to set <session-timeout> to 1 minute and create a HttpSessionListener like follows:

@WebListener
public class HttpSessionChecker implements HttpSessionListener {

    public void sessionCreated(HttpSessionEvent event) {
        System.out.printf("Session ID %s created at %s%n", event.getSession().getId(), new Date());
    }

    public void sessionDestroyed(HttpSessionEvent event) {
        System.out.printf("Session ID %s destroyed at %s%n", event.getSession().getId(), new Date());
    }

}

(if you're not on Servlet 3.0 yet and thus can't use @WebListener, then register in web.xml as follows):

<listener>
    <listener-class>com.example.HttpSessionChecker</listener-class>
</listener>

Note that the servletcontainer won't immediately destroy sessions after exactly the timeout value. It's a background job which runs at certain intervals (e.g. 5~15 minutes depending on load and the servletcontainer make/type). So don't be surprised when you don't see destroyed line in the console immediately after exactly one minute of inactivity. However, when you fire a HTTP request on a timed-out-but-not-destroyed-yet session, it will be destroyed immediately.

See also:

How to load a controller from another controller in codeigniter?

While the methods above might work, here is a very good method.

Extend the core controller with a MY controller, then extend this MY controller for all your other controllers. For example, you could have:

class MY_Controller extends CI_Controller {
    public function is_logged()
    {
        //Your code here
    }
public function logout()
    {
        //Your code here
    }
}

Then your other controllers could then extend this as follows:

class Another_Controller extends MY_Controller {
    public function show_home()
    {
         if (!$this->is_logged()) {
           return false;
         }
    }
public function logout()
    {
        $this->logout();
    }
}

How can I adjust DIV width to contents

You could try using float:left; or display:inline-block;.

Both of these will change the element's behaviour from defaulting to 100% width to defaulting to the natural width of its contents.

However, note that they'll also both have an impact on the layout of the surrounding elements as well. I would suggest that inline-block will have less of an impact though, so probably best to try that first.

JQuery/Javascript: check if var exists

I suspect there are many answers like this on SO but here you go:

if ( typeof pagetype !== 'undefined' && pagetype == 'textpage' ) {
  ...
}

Difference between static STATIC_URL and STATIC_ROOT on Django

STATICFILES_DIRS: You can keep the static files for your project here e.g. the ones used by your templates.

STATIC_ROOT: leave this empty, when you do manage.py collectstatic, it will search for all the static files on your system and move them here. Your static file server is supposed to be mapped to this folder wherever it is located. Check it after running collectstatic and you'll find the directory structure django has built.

--------Edit----------------

As pointed out by @DarkCygnus, STATIC_ROOT should point at a directory on your filesystem, the folder should be empty since it will be populated by Django.

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

or

STATIC_ROOT = '/opt/web/project/static_files'

--------End Edit -----------------

STATIC_URL: '/static/' is usually fine, it's just a prefix for static files.

ASP.NET custom error page - Server.GetLastError() is null

OK, I found this post: http://msdn.microsoft.com/en-us/library/aa479319.aspx

with this very illustrative diagram:

diagram
(source: microsoft.com)

in essence, to get at those exception details i need to store them myself in Global.asax, for later retrieval on my custom error page.

it seems the best way is to do the bulk of the work in Global.asax, with the custom error pages handling helpful content rather than logic.

how to set windows service username and password through commandline

In PowerShell, the "sc" command is an alias for the Set-Content cmdlet. You can workaround this using the following syntax:

sc.exe config Service obj= user password= pass

Specyfying the .exe extension, PowerShell bypasses the alias lookup.

HTH

How to Enable ActiveX in Chrome?

This could be pretty ugly, but doesn't Chrome use the NPAPI for plugins like Safari? In that case, you could write a wrapper plugin with the NPAPI that made the appropriate ActiveX creation and calls to run the plugin. If you do a lot of scripting against those plugins, you might have to be a bit of work to proxy those calls through to the wrapped ActiveX control.

Find the greatest number in a list of numbers

    #Ask for number input
first = int(raw_input('Please type a number: '))
second = int(raw_input('Please type a number: '))
third = int(raw_input('Please type a number: '))
fourth = int(raw_input('Please type a number: '))
fifth = int(raw_input('Please type a number: '))
sixth = int(raw_input('Please type a number: '))
seventh = int(raw_input('Please type a number: '))
eighth = int(raw_input('Please type a number: '))
ninth = int(raw_input('Please type a number: '))
tenth = int(raw_input('Please type a number: '))

    #create a list for variables
sorted_list = [first, second, third, fourth, fifth, sixth, seventh, 
              eighth, ninth, tenth]
odd_numbers = []

    #filter list and add odd numbers to new list
for value in sorted_list:
    if value%2 != 0:
        odd_numbers.append(value)
print 'The greatest odd number you typed was:', max(odd_numbers)

How to get the index of an element in an IEnumerable?

This can get really cool with an extension (functioning as a proxy), for example:

collection.SelectWithIndex(); 
// vs. 
collection.Select((item, index) => item);

Which will automagically assign indexes to the collection accessible via this Index property.

Interface:

public interface IIndexable
{
    int Index { get; set; }
}

Custom extension (probably most useful for working with EF and DbContext):

public static class EnumerableXtensions
{
    public static IEnumerable<TModel> SelectWithIndex<TModel>(
        this IEnumerable<TModel> collection) where TModel : class, IIndexable
    {
        return collection.Select((item, index) =>
        {
            item.Index = index;
            return item;
        });
    }
}

public class SomeModelDTO : IIndexable
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }

    public int Index { get; set; }
}

// In a method
var items = from a in db.SomeTable
            where a.Id == someValue
            select new SomeModelDTO
            {
                Id = a.Id,
                Name = a.Name,
                Price = a.Price
            };

return items.SelectWithIndex()
            .OrderBy(m => m.Name)
            .Skip(pageStart)
            .Take(pageSize)
            .ToList();

Execute method on startup in Spring

What we have done was extending org.springframework.web.context.ContextLoaderListener to print something when the context starts.

public class ContextLoaderListener extends org.springframework.web.context.ContextLoaderListener
{
    private static final Logger logger = LoggerFactory.getLogger( ContextLoaderListener.class );

    public ContextLoaderListener()
    {
        logger.info( "Starting application..." );
    }
}

Configure the subclass then in web.xml:

<listener>
    <listener-class>
        com.mycomp.myapp.web.context.ContextLoaderListener
    </listener-class>
</listener>

How to comment a block in Eclipse?

For single line comment just use // and for multiline comments use /* your code here */

How to set Google Chrome in WebDriver

Mac OS: You have to install ChromeDriver first:

brew cask install chromedriver

It will be copied to /usr/local/bin/chromedriver. Then you can use it in java code classes.

Javascript event handler with parameters

let obj = MyObject();

elem.someEvent( function(){ obj.func(param) } );

//calls the MyObject.func, passing the param.

onKeyPress Vs. onKeyUp and onKeyDown

The onkeypress event works for all the keys except ALT, CTRL, SHIFT, ESC in all browsers where as onkeydown event works for all keys. Means onkeydown event captures all the keys.

How to pad a string to a fixed length with spaces in Python?

Just whipped this up for my problem, it just adds a space until the length of string is more than the min_length you give it.

def format_string(str, min_length):
    while len(str) < min_length:
        str += " "
    return str

How can I check the current status of the GPS receiver?

I know this is a little late. However why not use the NMEAListener if you want to know if you have a fix. From what I've read, the NMEAListener will give you the NMEA sentences and from there you pick the correct sentence.

The RMC sentence contains the fix status which is either A for OK or V for warning. The GGA sentence contains the Fix Quality (0 invalid, 1 GPS or 2 DGPS)

I can't offer you any java code as I'm only just starting out with Android, but I have done a GPS library in C# for Windows apps, which I'm looking to use with Xamarin. I only came across this thread because I was looking for provider information.

From what I've read so far about the Location object I'm not all that comfortable about methods like getAccuracy() and hasAccuracy(). I'm used to extracting from the NMEA sentences HDOP and VDOP values to determine how accurate my fixes are. Its quite common to have a fix, but have a lousy HDOP which means your horizontal accuracy is not very good at all. For example sitting at your desk debugging with an external Bluetooth GPS device hard up against a window, you are quite likely to get a fix, but very poor HDOP and VDOP. Place your GPS device in a flower pot outside or something similar or add an external aerial to the GPS and immediately you get good HDOP and VDOP values.

Check if xdebug is working

Run

php -m -c

in your terminal, and then look for [Zend Modules]. It should be somewhere there if it is loaded!

NB

If you're using Ubuntu, it may not show up here because you need to add the xdebug settings from /etc/php5/apache2/php.ini into /etc/php5/cli/php.ini. Mine are

[xdebug]
zend_extension = /usr/lib/php5/20121212/xdebug.so
xdebug.remote_enable=on
xdebug.remote_handler=dbgp
xdebug.remote_mode=req
xdebug.remote_host=localhost
xdebug.remote_port=9000

how to convert milliseconds to date format in android?

fun convertLongToTimeWithLocale(){
    val dateAsMilliSecond: Long = 1602709200000
    val date = Date(dateAsMilliSecond)
    val language = "en"
    val formattedDateAsDigitMonth = SimpleDateFormat("dd/MM/yyyy", Locale(language))
    val formattedDateAsShortMonth = SimpleDateFormat("dd MMM yyyy", Locale(language))
    val formattedDateAsLongMonth = SimpleDateFormat("dd MMMM yyyy", Locale(language))
    Log.d("month as digit", formattedDateAsDigitMonth.format(date))
    Log.d("month as short", formattedDateAsShortMonth.format(date))
    Log.d("month as long", formattedDateAsLongMonth.format(date))
}

output:

month as digit: 15/10/2020
month as short: 15 Oct 2020 
month as long : 15 October 2020

You can change the value defined as 'language' due to your require. Here is the all language codes: Java language codes

C# Syntax - Example of a Lambda Expression - ForEach() over Generic List

public static void Each<T>(this IEnumerable<T> items, Action<T> action) {
foreach (var item in items) {
    action(item);
} }

... and call it thusly:

myList.Each(x => { x.Enabled = false; });

Nginx: Permission denied for nginx on Ubuntu

Nginx needs to run by command 'sudo /etc/init.d/nginx start'

Starting of Tomcat failed from Netbeans

Also, it is very likely, that problem with proxy settings.

Any who didn't overcome Tomact starting problrem, - try in NetBeans choose No Proxy in the Tools -> Options -> General tab.

It helped me.