Programs & Examples On #Panda3d

Panda3D is an open source 3D Engine originally developed, and still actively maintained, by the Walt Disney VR Studio. Additional development and support for the open source community is provided by the Entertainment Technology Center of Carnegie Mellon University. http://www.panda3d.org

How do I look inside a Python object?

If you want to look at parameters and methods, as others have pointed out you may well use pprint or dir()

If you want to see the actual value of the contents, you can do

object.__dict__

Setting Elastic search limit to "unlimited"

You can use the from and size parameters to page through all your data. This could be very slow depending on your data and how much is in the index.

http://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-from-size.html

Binding IIS Express to an IP Address

Change bindingInformation=":8080:"

And remember to turn off the firewall for IISExpress

How are Anonymous inner classes used in Java?

You can use anonymous class this way

TreeSet treeSetObj = new TreeSet(new Comparator()
{
    public int compare(String i1,String i2)
    {
        return i2.compareTo(i1);
    }
});

PHP prepend leading zero before single digit number, on-the-fly

The universal tool for string formatting, sprintf:

$stamp = sprintf('%s%02s', $year, $month);

http://php.net/manual/en/function.sprintf.php

repaint() in Java

You're doing things in the wrong order.

You need to first add all JComponents to the JFrame, and only then call pack() and then setVisible(true) on the JFrame

If you later added JComponents that could change the GUI's size you will need to call pack() again, and then repaint() on the JFrame after doing so.

How to pass multiple arguments in processStartInfo?

System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = @"/c -sk server -sky exchange -pe -n CN=localhost -ir LocalMachine -is Root -ic MyCA.cer -sr LocalMachine -ss My MyAdHocTestCert.cer"

use /c as a cmd argument to close cmd.exe once its finish processing your commands

Python: converting a list of dictionaries to json

use json library

import json
json.dumps(list)

by the way, you might consider changing variable list to another name, list is the builtin function for a list creation, you may get some unexpected behaviours or some buggy code if you don't change the variable name.

How to install XCODE in windows 7 platform?

X-code is primarily made for OS-X or iPhone development on Mac systems. Versions for Windows are not available. However this might help!

There is no way to get Xcode on Windows; however you can use a different SDK like Corona instead although it will not use Objective-C (I believe it uses Lua). I have however heard that it is horrible to use.

Source: classroomm.com

Avoid browser popup blockers

The easiest way to get rid of this is to:

  1. Dont use document.open().
  2. Instead use this.document.location.href = location; where location is the url to be loaded

Ex :

<script>
function loadUrl(location)
{
this.document.location.href = location;
}</script>

<div onclick="loadUrl('company_page.jsp')">Abc</div>

This worked very well for me. Cheers

Load a bitmap image into Windows Forms using open file dialog

You should try to:

  • Create the picturebox visually in form (it's easier)
  • Set Dock property of picturebox to Fill (if you want image to fill form)
  • Set SizeMode of picturebox to StretchImage

Finally:

private void button1_Click(object sender, EventArgs e)
{
    OpenFileDialog dlg = new OpenFileDialog();
    dlg.Title = "Open Image";
    dlg.Filter = "bmp files (*.bmp)|*.bmp";
    if (dlg.ShowDialog() == DialogResult.OK)
    {                     
        PictureBox1.Image = Image.FromFile(dlg.Filename);
    }
    dlg.Dispose();
}

Working with time DURATION, not time of day

With custom format of a cell you can insert a type like this: d "days", h:mm:ss, which will give you a result like 16 days, 13:56:15 in an excel-cell.

If you would like to show the duration in hours you use the following type [h]:mm:ss, which will lead to something like 397:56:15. Control check: 16 =(397 hours -13 hours)/24

enter image description here

Condition within JOIN or WHERE

The relational algebra allows interchangeability of the predicates in the WHERE clause and the INNER JOIN, so even INNER JOIN queries with WHERE clauses can have the predicates rearrranged by the optimizer so that they may already be excluded during the JOIN process.

I recommend you write the queries in the most readable way possible.

Sometimes this includes making the INNER JOIN relatively "incomplete" and putting some of the criteria in the WHERE simply to make the lists of filtering criteria more easily maintainable.

For example, instead of:

SELECT *
FROM Customers c
INNER JOIN CustomerAccounts ca
    ON ca.CustomerID = c.CustomerID
    AND c.State = 'NY'
INNER JOIN Accounts a
    ON ca.AccountID = a.AccountID
    AND a.Status = 1

Write:

SELECT *
FROM Customers c
INNER JOIN CustomerAccounts ca
    ON ca.CustomerID = c.CustomerID
INNER JOIN Accounts a
    ON ca.AccountID = a.AccountID
WHERE c.State = 'NY'
    AND a.Status = 1

But it depends, of course.

How to resize an image with OpenCV2.0 and Python2.6

You could use the GetSize function to get those information, cv.GetSize(im) would return a tuple with the width and height of the image. You can also use im.depth and img.nChan to get some more information.

And to resize an image, I would use a slightly different process, with another image instead of a matrix. It is better to try to work with the same type of data:

size = cv.GetSize(im)
thumbnail = cv.CreateImage( ( size[0] / 10, size[1] / 10), im.depth, im.nChannels)
cv.Resize(im, thumbnail)

Hope this helps ;)

Julien

Difference between View and Request scope in managed beans

A @ViewScoped bean lives exactly as long as a JSF view. It usually starts with a fresh new GET request, or with a navigation action, and will then live as long as the enduser submits any POST form in the view to an action method which returns null or void (and thus navigates back to the same view). Once you refresh the page, or return a non-null string (even an empty string!) navigation outcome, then the view scope will end.

A @RequestScoped bean lives exactly as long a HTTP request. It will thus be garbaged by end of every request and recreated on every new request, hereby losing all changed properties.

A @ViewScoped bean is thus particularly more useful in rich Ajax-enabled views which needs to remember the (changed) view state across Ajax requests. A @RequestScoped one would be recreated on every Ajax request and thus fail to remember all changed view state. Note that a @ViewScoped bean does not share any data among different browser tabs/windows in the same session like as a @SessionScoped bean. Every view has its own unique @ViewScoped bean.

See also:

How to Validate a DateTime in C#?

Here's another variation of the solution that returns true if the string can be converted to a DateTime type, and false otherwise.

public static bool IsDateTime(string txtDate)
{
    DateTime tempDate;
    return DateTime.TryParse(txtDate, out tempDate);
}

How to convert const char* to char* in C?

First of all you should do such things only if it is really necessary - e.g. to use some old-style API with char* arguments which are not modified. If an API function modifies the string which was const originally, then this is unspecified behaviour, very likely crash.

Use cast:

(char*)const_char_ptr

How to write and save html file in python?

print('<tr><td>%04d</td>' % (i+1), file=Html_file)

How to change the type of a field?

To convert int32 to string in mongo without creating an array just add "" to your number :-)

db.foo.find( { 'mynum' : { $type : 16 } } ).forEach( function (x) {   
  x.mynum = x.mynum + ""; // convert int32 to string
  db.foo.save(x);
});

Log4net rolling daily filename with date in the file name

Using Log4Net 1.2.13 we use the following configuration settings to allow date time in the file name.

<file type="log4net.Util.PatternString" value="E:/logname-%utcdate{yyyy-MM-dd}.txt" />

Which will provide files in the following convention: logname-2015-04-17.txt

With this it's usually best to have the following to ensure you're holding 1 log per day.

<rollingStyle value="Date" />
<datePattern value="yyyyMMdd" />

If size of file is a concern the following allows 500 files of 5MB in size until a new day spawns. CountDirection allows Ascending or Descending numbering of files which are no longer current.

 <maxSizeRollBackups value="500" />
 <maximumFileSize value="5MB" />
 <rollingStyle value="Composite" />
 <datePattern value="yyyyMMdd" />
 <CountDirection value="1"/>
 <staticLogFileName value="true" />

typedef struct vs struct definitions

If you use struct without typedef, you'll always have to write

struct mystruct myvar;

It's illegal to write

mystruct myvar;

If you use the typedef you don't need the struct prefix anymore.

Play/pause HTML 5 video using JQuery

Why do you need to use jQuery? Your proposed solution works, and it's probably faster than constructing a jQuery object.

document.getElementById('videoId').play();

What's the difference between IFrame and Frame?

Inline frame is just one "box" and you can place it anywhere on your site. Frames are a bunch of 'boxes' put together to make one site with many pages.

Add line break to 'git commit -m' from the command line

Sadly, git doesn't seem to allow for any newline character in its message. There are various reasonable solutions already above, but when scripting, those are annoying. Here documents also work, but may also a bit too annoying to deal with (think yaml files)

Here is what I did:

git commit \
    --message "Subject" \
    --message "First line$(echo)Second line$(echo)Third Line"

While this is also still ugly, it allows for 'one-liners' which may be useful still. As usually the strings are variables or combined with variables, the uglynes may be kept to a minimum.

How do I move a file from one location to another in Java?

Files.move(source, target, REPLACE_EXISTING);

You can use the Files object

Read more about Files

AttributeError: 'datetime' module has no attribute 'strptime'

If I had to guess, you did this:

import datetime

at the top of your code. This means that you have to do this:

datetime.datetime.strptime(date, "%Y-%m-%d")

to access the strptime method. Or, you could change the import statement to this:

from datetime import datetime

and access it as you are.

The people who made the datetime module also named their class datetime:

#module  class    method
datetime.datetime.strptime(date, "%Y-%m-%d")

Python: Find index of minimum item in list of floats

I would use:

val, idx = min((val, idx) for (idx, val) in enumerate(my_list))

Then val will be the minimum value and idx will be its index.

Windows Forms - Enter keypress activates submit button?

Set the KeyPreview attribute on your form to True, then use the KeyPress event at your form level to detect the Enter key. On detection call whatever code you would have for the "submit" button.

Remove Object from Array using JavaScript

Use splice function on arrays. Specify the position of the start element and the length of the subsequence you want to remove.

someArray.splice(pos, 1);

How to log as much information as possible for a Java Exception?

Something that I do is to have a static method that handles all exceptions and I add the log to a JOptionPane to show it to the user, but you could write the result to a file in FileWriter wraped in a BufeeredWriter. For the main static method, to catch the Uncaught Exceptions I do:

SwingUtilities.invokeLater( new Runnable() {
    @Override
    public void run() {
        //Initializations...
    }
});


Thread.setDefaultUncaughtExceptionHandler( 
    new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException( Thread t, Throwable ex ) {
            handleExceptions( ex, true );
        }
    }
);

And as for the method:

public static void handleExceptions( Throwable ex, boolean shutDown ) {
    JOptionPane.showMessageDialog( null,
        "A CRITICAL ERROR APPENED!\n",
        "SYSTEM FAIL",
        JOptionPane.ERROR_MESSAGE );

    StringBuilder sb = new StringBuilder(ex.toString());
    for (StackTraceElement ste : ex.getStackTrace()) {
        sb.append("\n\tat ").append(ste);
    }


    while( (ex = ex.getCause()) != null ) {
        sb.append("\n");
        for (StackTraceElement ste : ex.getStackTrace()) {
            sb.append("\n\tat ").append(ste);
        }
    }

    String trace = sb.toString();

    JOptionPane.showMessageDialog( null,
        "PLEASE SEND ME THIS ERROR SO THAT I CAN FIX IT. \n\n" + trace,
        "SYSTEM FAIL",
        JOptionPane.ERROR_MESSAGE);

    if( shutDown ) {
        Runtime.getRuntime().exit( 0 );
    }
}

In you case, instead of "screaming" to the user, you could write a log like I told you before:

String trace = sb.toString();

File file = new File("mylog.txt");
FileWriter myFileWriter = null;
BufferedWriter myBufferedWriter = null;

try {
    //with FileWriter(File file, boolean append) you can writer to 
    //the end of the file
    myFileWriter = new FileWriter( file, true );
    myBufferedWriter = new BufferedWriter( myFileWriter );

    myBufferedWriter.write( trace );
}
catch ( IOException ex1 ) {
    //Do as you want. Do you want to use recursive to handle 
    //this exception? I don't advise that. Trust me...
}
finally {
    try {
        myBufferedWriter.close();
    }
    catch ( IOException ex1 ) {
        //Idem...
    }

    try {
        myFileWriter.close();
    }
    catch ( IOException ex1 ) {
        //Idem...
    }
}

I hope I have helped.

Have a nice day. :)

How to create a custom scrollbar on a div (Facebook style)

I solved this problem by adding another div as a sibling to the scrolling content div. It's height is set to the radius of the curved borders. There will be design issues if you have content that you want nudged to the very bottom, or text you want to flow into this new div, etc,. but for my UI this thin div is no problem.

The real trick is to have the following structure:

<div class="window">
 <div class="title">Some title text</div>
 <div class="content">Main content area</div>
 <div class="footer"></div>
</div>

Important CSS highlights:

  • Your CSS would define the content region with a height and overflow to allow the scrollbar(s) to appear.
  • The window class gets the same diameter corners as the title and footer
  • The drop shadow, if desired, is only given to the window class
  • The height of the footer div is the same as the radius of the bottom corners

Here's what that looks like:

Bottom right corner

Showing an image from an array of images - Javascript

Here's your problem:

if(imgArray[i] == img)

You're comparing an array element to a DOM object.

How to get back Lost phpMyAdmin Password, XAMPP

There is a batch file called resetroot.bat located in the xammp folders 'C:\xampp\mysql' run this and it will delete the phpmyadmin passwords. Then all you need to do is start the MySQL service in xamp and click the admin button.

Determine what attributes were changed in Rails after_save callback?

You just add an accessor who define what you change

class Post < AR::Base
  attr_reader :what_changed

  before_filter :what_changed?

  def what_changed?
    @what_changed = changes || []
  end

  after_filter :action_on_changes

  def action_on_changes
    @what_changed.each do |change|
      p change
    end
  end
end

Find Facebook user (url to profile page) by known email address

Maybe this is a little bit late but I found a web site which gives social media account details by know email addreess. It is https://www.fullcontact.com

You can use Person Api there and get the info.

This is a type of get : https://api.fullcontact.com/v2/person.xml?email=someone@****&apiKey=********

Also there is xml or json choice.

Error: 10 $digest() iterations reached. Aborting! with dynamic sortby predicate

This happened to me after upgrading from angular 1.6 -> 1.7 when using $sce.trustAsResourceUrl() as the return value of a function called from ng-src. You can see this issue mentioned here.

In my case I had to change the following.

<source ng-src="{{trustSrc(someUrl)}}" type='video/mp4' />
trustSrc = function(url){
    return $sce.trustAsResourceUrl(url);
};

to

<source ng-src='{{trustedUrl}} type='video/mp4' />
trustedUrl = $sce.trustAsResourceUrl(someUrl);

Fatal error: Cannot use object of type stdClass as array in

if you really want an array instead you can use:

$getvidids->result_array()

which would return the same information as an associative array.

"Unknown class <MyClass> in Interface Builder file" error at runtime

In my case, the custom UIView class is in an embedded framework. I changed the custom UIView header file to "project" to "public" and include it in the master header file.

Mutex lock threads

What you need to do is to call pthread_mutex_lock to secure a mutex, like this:

pthread_mutex_lock(&mutex);

Once you do this, any other calls to pthread_mutex_lock(mutex) will not return until you call pthread_mutex_unlock in this thread. So if you try to call pthread_create, you will be able to create a new thread, and that thread will be able to (incorrectly) use the shared resource. You should call pthread_mutex_lock from within your fooAPI function, and that will cause the function to wait until the shared resource is available.

So you would have something like this:

#include <pthread.h>
#include <stdio.h>

int sharedResource = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void* fooAPI(void* param)
{
    pthread_mutex_lock(&mutex);
    printf("Changing the shared resource now.\n");
    sharedResource = 42;
    pthread_mutex_unlock(&mutex);
    return 0;
}

int main()
{
    pthread_t thread;

    // Really not locking for any reason other than to make the point.
    pthread_mutex_lock(&mutex);
    pthread_create(&thread, NULL, fooAPI, NULL);
    sleep(1);
    pthread_mutex_unlock(&mutex);

    // Now we need to lock to use the shared resource.
    pthread_mutex_lock(&mutex);
    printf("%d\n", sharedResource);
    pthread_mutex_unlock(&mutex);
}

Edit: Using resources across processes follows this same basic approach, but you need to map the memory into your other process. Here's an example using shmem:

#include <stdio.h>
#include <unistd.h>
#include <sys/file.h>
#include <sys/mman.h>
#include <sys/wait.h>

struct shared {
    pthread_mutex_t mutex;
    int sharedResource;
};

int main()
{
    int fd = shm_open("/foo", O_CREAT | O_TRUNC | O_RDWR, 0600);
    ftruncate(fd, sizeof(struct shared));

    struct shared *p = (struct shared*)mmap(0, sizeof(struct shared),
        PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);

    p->sharedResource = 0;

    // Make sure it can be shared across processes
    pthread_mutexattr_t shared;
    pthread_mutexattr_init(&shared);
    pthread_mutexattr_setpshared(&shared, PTHREAD_PROCESS_SHARED);

    pthread_mutex_init(&(p->mutex), &shared);

    int i;
    for (i = 0; i < 100; i++) {
        pthread_mutex_lock(&(p->mutex));
        printf("%d\n", p->sharedResource);
        pthread_mutex_unlock(&(p->mutex));
        sleep(1);
    }

    munmap(p, sizeof(struct shared*));
    shm_unlink("/foo");
}

Writing the program to make changes to p->sharedResource is left as an exercise for the reader. :-)

Forgot to note, by the way, that the mutex has to have the PTHREAD_PROCESS_SHARED attribute set, so that pthreads will work across processes.

How to resolve ORA 00936 Missing Expression Error?

Remove the comma?

select /*+USE_HASH( a b ) */ to_char(date, 'MM/DD/YYYY HH24:MI:SS') as LABEL,
ltrim(rtrim(substr(oled, 9, 16))) as VALUE
from rrfh a, rrf b
where ltrim(rtrim(substr(oled, 1, 9))) = 'stata kish' 
and a.xyz = b.xyz

Have a look at FROM

SELECTING from multiple tables You can include multiple tables in the FROM clause by listing the tables with a comma in between each table name

Android - how to make a scrollable constraintlayout?

To summarize, you basically wrap your android.support.constraint.ConstraintLayout view in a ScrollView within the text of the *.xml file associated with your layout.

Example activity_sign_in.xml

<?xml version="1.0" encoding="utf-8"?>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SignInActivity"> <!-- usually the name of the Java file associated with this activity -->

    <android.support.constraint.ConstraintLayout 
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/gradient"
        tools:context="app.android.SignInActivity">

        <!-- all the layout details of your page -->

    </android.support.constraint.ConstraintLayout>
</ScrollView>

Note 1: The scroll bars only appear if a wrap is needed in any way, including the keyboard popping up.

Note 2: It also wouldn't be a bad idea to make sure your ConstraintLayout is big enough to the reach the bottom and sides of any given screen, especially if you have a background, as this will ensure that there isn't odd whitespace. You can do this with spaces if nothing else.

When to use AtomicReference in Java?

Here is a use case for AtomicReference:

Consider this class that acts as a number range, and uses individual AtmomicInteger variables to maintain lower and upper number bounds.

public class NumberRange {
    // INVARIANT: lower <= upper
    private final AtomicInteger lower = new AtomicInteger(0);
    private final AtomicInteger upper = new AtomicInteger(0);

    public void setLower(int i) {
        // Warning -- unsafe check-then-act
        if (i > upper.get())
            throw new IllegalArgumentException(
                    "can't set lower to " + i + " > upper");
        lower.set(i);
    }

    public void setUpper(int i) {
        // Warning -- unsafe check-then-act
        if (i < lower.get())
            throw new IllegalArgumentException(
                    "can't set upper to " + i + " < lower");
        upper.set(i);
    }

    public boolean isInRange(int i) {
        return (i >= lower.get() && i <= upper.get());
    }
}

Both setLower and setUpper are check-then-act sequences, but they do not use sufficient locking to make them atomic. If the number range holds (0, 10), and one thread calls setLower(5) while another thread calls setUpper(4), with some unlucky timing both will pass the checks in the setters and both modifications will be applied. The result is that the range now holds (5, 4)an invalid state. So while the underlying AtomicIntegers are thread-safe, the composite class is not. This can be fixed by using a AtomicReference instead of using individual AtomicIntegers for upper and lower bounds.

public class CasNumberRange {
    // Immutable
    private static class IntPair {
        final int lower;  // Invariant: lower <= upper
        final int upper;

        private IntPair(int lower, int upper) {
            this.lower = lower;
            this.upper = upper;
        }
    }

    private final AtomicReference<IntPair> values = 
            new AtomicReference<IntPair>(new IntPair(0, 0));

    public int getLower() {
        return values.get().lower;
    }

    public void setLower(int lower) {
        while (true) {
            IntPair oldv = values.get();
            if (lower > oldv.upper)
                throw new IllegalArgumentException(
                    "Can't set lower to " + lower + " > upper");
            IntPair newv = new IntPair(lower, oldv.upper);
            if (values.compareAndSet(oldv, newv))
                return;
        }
    }

    public int getUpper() {
        return values.get().upper;
    }

    public void setUpper(int upper) {
        while (true) {
            IntPair oldv = values.get();
            if (upper < oldv.lower)
                throw new IllegalArgumentException(
                    "Can't set upper to " + upper + " < lower");
            IntPair newv = new IntPair(oldv.lower, upper);
            if (values.compareAndSet(oldv, newv))
                return;
        }
    }
}

How to pass multiple parameters to a get method in ASP.NET Core

Why not using just one controller action?

public string Get(int? id, string firstName, string lastName, string address)
{
   if (id.HasValue)
      GetById(id);
   else if (string.IsNullOrEmpty(address))
      GetByName(firstName, lastName);
   else
      GetByNameAddress(firstName, lastName, address);
}

Another option is to use attribute routing, but then you'd need to have a different URL format:

//api/person/byId?id=1
[HttpGet("byId")] 
public string Get(int id)
{
}

//api/person/byName?firstName=a&lastName=b
[HttpGet("byName")]
public string Get(string firstName, string lastName, string address)
{
}

How to clear the logs properly for a Docker container?

sudo sh -c "truncate -s 0 /var/lib/docker/containers/*/*-json.log"

MD5 is 128 bits but why is it 32 characters?

One hex digit = 1 nibble (four-bits)

Two hex digits = 1 byte (eight-bits)

MD5 = 32 hex digits

32 hex digits = 16 bytes ( 32 / 2)

16 bytes = 128 bits (16 * 8)

The same applies to SHA-1 except it's 40 hex digits long.

I hope this helps.

Java 8 Stream and operation on arrays

Be careful if you have to deal with large numbers.

int[] arr = new int[]{Integer.MIN_VALUE, Integer.MIN_VALUE};
long sum = Arrays.stream(arr).sum(); // Wrong: sum == 0

The sum above is not 2 * Integer.MIN_VALUE. You need to do this in this case.

long sum = Arrays.stream(arr).mapToLong(Long::valueOf).sum(); // Correct

laravel throwing MethodNotAllowedHttpException

well when i had these problem i faced 2 code errors

{!! Form::model(['method' => 'POST','route' => ['message.store']]) !!}

i corrected it by doing this

{!! Form::open(['method' => 'POST','route' => 'message.store']) !!}

so just to expatiate i changed the form model to open and also the route where wrongly placed in square braces.

How to check if a date is in a given range?

It's not necessary to convert to timestamp to do the comparison, given that the strings are validated as dates in 'YYYY-MM-DD' canonical format.

This test will work:

( ( $date_from_user >= $start_date ) && ( $date_from_user <= $end_date ) )

given:

$start_date     = '2009-06-17';
$end_date       = '2009-09-05';
$date_from_user = '2009-08-28';

NOTE: Comparing strings like this does allow for "non-valid" dates e.g. (December 32nd ) '2009-13-32' and for weirdly formatted strings '2009/3/3', such that a string comparison will NOT be equivalent to a date or timestamp comparison. This works ONLY if the date values in the strings are in a CONSISTENT and CANONICAL format.

EDIT to add a note here, elaborating on the obvious.

By CONSISTENT, I mean for example that the strings being compared must be in identical format: the month must always be two characters, the day must always be two characters, and the separator character must always be a dash. We can't reliably compare "strings" that aren't four character year, two character month, two character day. If we had a mix of one character and two character months in the strings, for example, we'd get unexpected result when we compared, '2009-9-30' to '2009-10-11'. We humanly see "9" as being less than "10", but a string comparison will see '2009-9' as greater than '2009-1'. We don't necessarily need to have a dash separator characters; we could just as reliably compare strings in 'YYYYMMDD' format; if there is a separator character, it has to always be there and always be the same.

By CANONICAL, I mean that a format that will result in strings that will be sorted in date order. That is, the string will have a representation of "year" first, then "month", then "day". We can't reliably compare strings in 'MM-DD-YYYY' format, because that's not canonical. A string comparison would compare the MM (month) before it compared YYYY (year) since the string comparison works from left to right.) A big benefit of the 'YYYY-MM-DD' string format is that it is canonical; dates represented in this format can reliably be compared as strings.

[ADDENDUM]

If you do go for the php timestamp conversion, be aware of the limitations.

On some platforms, php does not support timestamp values earlier than 1970-01-01 and/or later than 2038-01-19. (That's the nature of the unix timestamp 32-bit integer.) Later versions pf php (5.3?) are supposed to address that.

The timezone can also be an issue, if you aren't careful to use the same timezone when converting from string to timestamp and from timestamp back to string.

HTH

Getting Database connection in pure JPA setup

Hibernate 4 / 5:

Session session = entityManager.unwrap(Session.class);
session.doWork(connection -> doSomeStuffWith(connection));

How to tell if browser/tab is active

Using jQuery:

$(function() {
    window.isActive = true;
    $(window).focus(function() { this.isActive = true; });
    $(window).blur(function() { this.isActive = false; });
    showIsActive();
});

function showIsActive()
{
    console.log(window.isActive)
    window.setTimeout("showIsActive()", 2000);
}

function doWork()
{
    if (window.isActive) { /* do CPU-intensive stuff */}
}

How do you install and run Mocha, the Node.js testing module? Getting "mocha: command not found" after install

since npm 5.2.0, there's a new command "npx" included with npm that makes this much simpler, if you run:

npx mocha <args>

Note: the optional args are forwarded to the command being executed (mocha in this case)

this will automatically pick the executable "mocha" command from your locally installed mocha (always add it as a dev dependency to ensure the correct one is always used by you and everyone else).

Be careful though that if you didn't install mocha, this command will automatically fetch and use latest version, which is great for some tools (like scaffolders for example), but might not be the most recommendable for certain dependencies where you might want to pin to a specific version.

You can read more on npx here


Now, if instead of invoking mocha directly, you want to define a custom npm script, an alias that might invoke other npm binaries...

you don't want your library tests to fail depending on the machine setup (mocha as global, global mocha version, etc), the way to use the local mocha that works cross-platform is:

node node_modules/.bin/mocha

npm puts aliases to all the binaries in your dependencies on that special folder. Finally, npm will add node_modules/.bin to the PATH automatically when running an npm script, so in your package.json you can do just:

"scripts": {
  "test": "mocha"
}

and invoke it with

npm test

How to terminate a process in vbscript

Dim shll : Set shll = CreateObject("WScript.Shell")
Set Rt = shll.Exec("Notepad") : wscript.sleep 4000 : Rt.Terminate

Run the process with .Exec.

Then wait for 4 seconds.

After that kill this process.

CSS Outside Border

Try the outline property W3Schools - CSS Outline

Outline will not interfere with widths and lenghts of the elements/divs!

Please click the link I provided at the bottom to see working demos of the the different ways you can make borders, and inner/inline borders, even ones that do not disrupt the dimensions of the element! No need to add extra divs every time, as mentioned in another answer!

You can also combine borders with outlines, and if you like, box-shadows (also shown via link)

<head>
   <style type="text/css" ref="stylesheet">
      div {
        width:22px;
        height:22px;
        outline:1px solid black;
      }
   </style>
</head>
<div>
    outlined
</div>

Usually by default, 'border:' puts the border on the outside of the width, measurement, adding to the overall dimensions, unless you use the 'inset' value:

div {border: inset solid 1px black};

But 'outline:' is an extra border outside of the border, and of course still adds extra width/length to the element.

Hope this helps

PS: I also was inspired to make this for you : Using borders, outlines, and box-shadows

Run all SQL files in a directory

Use FOR. From the command prompt:

c:\>for %f in (*.sql) do sqlcmd /S <servername> /d <dbname> /E /i "%f"

What does '<?=' mean in PHP?

I hope it doesn't get deprecated. While writing <? blah code ?> is fairly unnecessary and confusable with XHTML, <?= isn't, for obvious reasons. Unfortunately I don't use it, because short_open_tag seems to be disabled more and more.

Update: I do use <?= again now, because it is enabled by default with PHP 5.4.0. See http://php.net/manual/en/language.basic-syntax.phptags.php

How to change legend title in ggplot

Just to add to the list (the other options here didn't work for me), you can also use the function update_labels for ggplot:

p <- ggplot(df, aes(x=rating, fill=cond)) + 
           geom_density(alpha=.3) + 
           xlab("NEW RATING TITLE") + 
           ylab("NEW DENSITY TITLE")
update_labels(p, list(colour="MY NEW LEGEND TITLE")

This will also allow you to change x- and y-axis labels, with separate lines:

update_labels(p, list(x="NEW X LABEL",y="NEW Y LABEL")

Validation for 10 digit mobile number and focus input field on invalid

After testing all answers without success. Some times input take alpha character also.

Here is the last full working code with only numbers input also keeping in mind backspace button key event for user if something number is incorrect.

_x000D_
_x000D_
$("#phone").keydown(function(event) {_x000D_
  k = event.which;_x000D_
  if ((k >= 96 && k <= 105) || k == 8) {_x000D_
    if ($(this).val().length == 10) {_x000D_
      if (k == 8) {_x000D_
        return true;_x000D_
      } else {_x000D_
        event.preventDefault();_x000D_
        return false;_x000D_
_x000D_
      }_x000D_
    }_x000D_
  } else {_x000D_
    event.preventDefault();_x000D_
    return false;_x000D_
  }_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input name="phone" id="phone" placeholder="Mobile Number" class="form-control" type="number" required>
_x000D_
_x000D_
_x000D_

apply drop shadow to border-top only?

In case you want to apply the shadow to the inside of the element (inset) but only want it to appear on one single side you can define a negative value to the "spread" parameter (5th parameter in the second example).

To completely remove it, make it the same size as the shadows blur (4th parameter in the second example) but as a negative value.

Also remember to add the offset to the y-position (3rd parameter in the second example) so that the following:

box-shadow:         inset 0px 4px 3px rgba(50, 50, 50, 0.75);

becomes:

box-shadow:         inset 0px 7px 3px -3px rgba(50, 50, 50, 0.75);

Check this updated fiddle: http://jsfiddle.net/FrEnY/1282/ and more on the box-shadow parameters here: http://www.w3schools.com/cssref/css3_pr_box-shadow.asp

Where can I find "make" program for Mac OS X Lion?

After upgrading to Mountain Lion using the NDK, I had the following error:

Cannot find 'make' program. Please install Cygwin make package or define the GNUMAKE variable to point to it

Error was fixed by downloading and using the latest NDK

Set Session variable using javascript in PHP

be careful when doing this, as it is a security risk. attackers could just repeatedly inject data into session variables, which is data stored on the server. this opens you to someone overloading your server with junk session data.

here's an example of code that you wouldn't want to do..

<input type="hidden" value="..." name="putIntoSession">
..
<?php
$_SESSION["somekey"] = $_POST["putIntoSession"]
?>

Now an attacker can just change the value of putIntoSession and submit the form a billion times. Boom!

If you take the approach of creating an AJAX service to do this, you'll want to make sure you enforce security to make sure repeated requests can't be made, that you're truncating the received value, and doing some basic data validation.

C++ int to byte array

I know this question already has answers but I will give my solution to this problem. I am using template function and integer constraint on it.

Here is my solution:

#include <type_traits>
#include <vector>

template <typename T,
          typename std::enable_if<std::is_arithmetic<T>::value>::type* = nullptr>
std::vector<uint8_t> splitValueToBytes(T const& value)
{
    std::vector<uint8_t> bytes;

    for (size_t i = 0; i < sizeof(value); i++)
    {
        uint8_t byte = value >> (i * 8);
        bytes.insert(bytes.begin(), byte);
    }

    return bytes;
}

Flutter - The method was called on null

You should declare your method first in void initState(), so when the first time pages has been loaded, it will init your method first, hope it can help

Finding first blank row, then writing to it

I know this is an older thread however I needed to write a function that returned the first blank row WITHIN a range. All of the code I found online actually searches the entire row (even the cells outside of the range) for a blank row. Data in ranges outside the search range was triggering a used row. This seemed to me to be a simple solution:

Function FirstBlankRow(ByVal rngToSearch As Range) As Long
   Dim R As Range
   Dim C As Range
   Dim RowIsBlank As Boolean

   For Each R In rngToSearch.Rows
      RowIsBlank = True
      For Each C In R.Cells
         If IsEmpty(C.Value) = False Then RowIsBlank = False
      Next C
      If RowIsBlank Then
         FirstBlankRow = R.Row
         Exit For
      End If
   Next R
End Function

IPhone/IPad: How to get screen width programmatically?

Take a look at UIScreen.

eg.

CGFloat width = [UIScreen mainScreen].bounds.size.width;

Take a look at the applicationFrame property if you don't want the status bar included (won't affect the width).

UPDATE: It turns out UIScreen (-bounds or -applicationFrame) doesn't take into account the current interface orientation. A more correct approach would be to ask your UIView for its bounds -- assuming this UIView has been auto-rotated by it's View controller.

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    CGFloat width = CGRectGetWidth(self.view.bounds);
}

If the view is not being auto-rotated by the View Controller then you will need to check the interface orientation to determine which part of the view bounds represents the 'width' and the 'height'. Note that the frame property will give you the rect of the view in the UIWindow's coordinate space which (by default) won't be taking the interface orientation into account.

Make Bootstrap's Carousel both center AND responsive?

Was having a very similar issue to this while using a CMS but it was not resolving with the above solution. What I did to solve it is put the following in the applicable css:

background-size: cover

and for placement purposes in case you are using bootstrap, I used:

background-position: center center /* or whatever position you wanted */

Hide axis values but keep axis tick labels in matplotlib

This works great. Just paste this before plt.show():

plt.gca().axes.get_yaxis().set_visible(False)

Boom.

Auto-scaling input[type=text] to width of value?

I solved width creating canvas and calculating size of it. its important that input value and canvas share same font features (family, size, weight...)

import calculateTextWidth from "calculate-text-width";

/*
 requires two props "value" and "font"
  - defaultFont: normal 500 14px sans-serif 
 */
const defaultText = 'calculate my width'
const textFont = 'normal 500 14px sans-serif'
const calculatedWidth = calculateTextWidth(defaultText, textFont)
console.log(calculatedWidth) // 114.37890625

GitHub: https://github.com/ozluy/calculate-text-width CodeSandbox: https://codesandbox.io/s/calculate-text-width-okr46

A TypeScript GUID class?

I found this https://typescriptbcl.codeplex.com/SourceControl/latest

here is the Guid version they have in case the link does not work later.

module System {
    export class Guid {
        constructor (public guid: string) {
            this._guid = guid;
        }

        private _guid: string;

        public ToString(): string {
            return this.guid;
        }

        // Static member
        static MakeNew(): Guid {
            var result: string;
            var i: string;
            var j: number;

            result = "";
            for (j = 0; j < 32; j++) {
                if (j == 8 || j == 12 || j == 16 || j == 20)
                    result = result + '-';
                i = Math.floor(Math.random() * 16).toString(16).toUpperCase();
                result = result + i;
            }
            return new Guid(result);
        }
    }
}

How to enable file sharing for my app?

According to apple doc:

File-Sharing Support
File-sharing support lets apps make user data files available in iTunes 9.1 and later. An app that declares its support for file sharing makes the contents of its /Documents directory available to the user. The user can then move files in and out of this directory as needed from iTunes. This feature does not allow your app to share files with other apps on the same device; that behavior requires the pasteboard or a document interaction controller object.

To enable file sharing for your app, do the following:

  1. Add the UIFileSharingEnabled key to your app’s Info.plist file, and set the value of the key to YES. (The actual key name is "Application supports iTunes file sharing")

  2. Put whatever files you want to share in your app’s Documents directory.

  3. When the device is plugged into the user’s computer, iTunes displays a File Sharing section in the Apps tab of the selected device.

  4. The user can add files to this directory or move files to the desktop.

Apps that support file sharing should be able to recognize when files have been added to the Documents directory and respond appropriately. For example, your app might make the contents of any new files available from its interface. You should never present the user with the list of files in this directory and ask them to decide what to do with those files.

For additional information about the UIFileSharingEnabled key, see Information Property List Key Reference.

What is the best way to tell if a character is a letter or number in Java without using regexes?

I don't know about best, but this seems pretty simple to me:

Character.isDigit(str.charAt(index))
Character.isLetter(str.charAt(index))

How do I set default value of select box in angularjs

After searching and trying multiple non working options to get my select default option working. I find a clean solution at: http://www.undefinednull.com/2014/08/11/a-brief-walk-through-of-the-ng-options-in-angularjs/

<select class="ajg-stereo-fader-input-name ajg-select-left"  ng-options="option.name for option in selectOptions" ng-model="inputLeft"></select>
<select class="ajg-stereo-fader-input-name ajg-select-right" ng-options="option.name for option in selectOptions" ng-model="inputRight"></select>

 scope.inputLeft =  scope.selectOptions[0];
 scope.inputRight = scope.selectOptions[1];

Why am I getting a NoClassDefFoundError in Java?

I had the same problem, and I was stock for many hours.

I found the solution. In my case, there was the static method defined due to that. The JVM can not create the another object of that class.

For example,

private static HttpHost proxy = new HttpHost(proxyHost, Integer.valueOf(proxyPort), "http");

Bootstrap : TypeError: $(...).modal is not a function

If you are using any layout page then, move script sections from bottom to head section in layout page. bcz, javascript files should be loaded first. This worked for me

Working copy XXX locked and cleanup failed in SVN

I had the same problem. Seems it has been fixed in the latest versions. I have updated my Tortoise SVN to the latest version (1.7.11) and clean up has worked well.

You can download the latest version here: downoad tortoise svn.

How to activate "Share" button in android app?

Add a Button and on click of the Button add this code:

Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND); 
sharingIntent.setType("text/plain");
String shareBody = "Here is the share content body";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));

Useful links:

For basic sharing

For customization

How to manage local vs production settings in Django?

I think the best solution is suggested by @T. Stone, but I don't know why just don't use the DEBUG flag in Django. I Write the below code for my website:

if DEBUG:
    from .local_settings import *

Always the simple solutions are better than complex ones.

How to fix nginx throws 400 bad request headers on any header testing tools?

Yes changing the error_to debug level as Emmanuel Joubaud suggested worked out (edit /etc/nginx/sites-enabled/default ):

        error_log /var/log/nginx/error.log debug;

Then after restaring nginx I got in the error log with my Python application using uwsgi:

        2017/02/08 22:32:24 [debug] 1322#1322: *1 connect to unix:///run/uwsgi/app/socket, fd:20 #2
        2017/02/08 22:32:24 [debug] 1322#1322: *1 connected
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http upstream connect: 0
        2017/02/08 22:32:24 [debug] 1322#1322: *1 posix_memalign: 0000560E1F25A2A0:128 @16
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http upstream send request
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http upstream send request body
        2017/02/08 22:32:24 [debug] 1322#1322: *1 chain writer buf fl:0 s:454
        2017/02/08 22:32:24 [debug] 1322#1322: *1 chain writer in: 0000560E1F2A0928
        2017/02/08 22:32:24 [debug] 1322#1322: *1 writev: 454 of 454
        2017/02/08 22:32:24 [debug] 1322#1322: *1 chain writer out: 0000000000000000
        2017/02/08 22:32:24 [debug] 1322#1322: *1 event timer add: 20: 60000:1486593204249
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http finalize request: -4, "/?" a:1, c:2
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http request count:2 blk:0
        2017/02/08 22:32:24 [debug] 1322#1322: *1 post event 0000560E1F2E5DE0
        2017/02/08 22:32:24 [debug] 1322#1322: *1 post event 0000560E1F2E5E40
        2017/02/08 22:32:24 [debug] 1322#1322: *1 delete posted event 0000560E1F2E5DE0
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http run request: "/?"
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http upstream check client, write event:1, "/"
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http upstream recv(): -1 (11: Resource temporarily unavailable)

Then I took a look to my uwsgi log and found out that:

        Invalid HTTP_HOST header: 'www.mysite.local'. You may need to add u'www.mysite.local' to ALLOWED_HOSTS.
        [pid: 10903|app: 0|req: 2/4] 192.168.221.2 () {38 vars in 450 bytes} [Wed Feb  8 22:32:24 2017] GET / => generated 54098 bytes in 55 msecs (HTTP/1.1 400) 4 headers in 135 bytes (1 switches on core 0)

And adding www.mysite.local to the settings.py ALLOWED_HOSTS fixed the issue :)

        ALLOWED_HOSTS = ['www.mysite.local']

Python - TypeError: 'int' object is not iterable

If the case is:

n=int(input())

Instead of -> for i in n: -> gives error- 'int' object is not iterable

Use -> for i in range(0,n): -> works fine..!

How do I filter an array with TypeScript in Angular 2?

You can check an example in Plunker over here plunker example filters

filter() {

    let storeId = 1;
    this.bookFilteredList = this.bookList
                                .filter((book: Book) => book.storeId === storeId);
    this.bookList = this.bookFilteredList; 
}

If input field is empty, disable submit button

Please try this

<!DOCTYPE html>
<html>
  <head>
    <title>Jquery</title>
    <meta charset="utf-8">       
    <script src='http://code.jquery.com/jquery-1.7.1.min.js'></script>
  </head>

  <body>

    <input type="text" id="message" value="" />
    <input type="button" id="sendButton" value="Send">

    <script>
    $(document).ready(function(){  

      var checkField;

      //checking the length of the value of message and assigning to a variable(checkField) on load
      checkField = $("input#message").val().length;  

      var enableDisableButton = function(){         
        if(checkField > 0){
          $('#sendButton').removeAttr("disabled");
        } 
        else {
          $('#sendButton').attr("disabled","disabled");
        }
      }        

      //calling enableDisableButton() function on load
      enableDisableButton();            

      $('input#message').keyup(function(){ 
        //checking the length of the value of message and assigning to the variable(checkField) on keyup
        checkField = $("input#message").val().length;
        //calling enableDisableButton() function on keyup
        enableDisableButton();
      });
    });
    </script>
  </body>
</html>

ssl.SSLError: tlsv1 alert protocol version

The only thing you have to do is to install requests[security] in your virtualenv. You should not have to use Python 3 (it should work in Python 2.7). Moreover, if you are using a recent version of macOS, you don't have to use homebrew to separately install OpenSSL either.

$ virtualenv --python=/usr/bin/python tempenv  # uses system python
$ . tempenv/bin/activate
$ pip install requests
$ python
>>> import ssl
>>> ssl.OPENSSL_VERSION
'OpenSSL 0.9.8zh 14 Jan 2016'  # this is the built-in openssl
>>> import requests
>>> requests.get('https://api.github.com/users/octocat/orgs')
requests.exceptions.SSLError: HTTPSConnectionPool(host='api.github.com', port=443): Max retries exceeded with url: /users/octocat/orgs (Caused by SSLError(SSLError(1, u'[SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:590)'),))
$ pip install 'requests[security]'
$ python  # install requests[security] and try again
>>> import requests
>>> requests.get('https://api.github.com/users/octocat/orgs')
<Response [200]>

requests[security] allows requests to use the latest version of TLS when negotiating the connection. The built-in openssl on macOS supports TLS v1.2.

Before you install your own version of OpenSSL, ask this question: how is Google Chrome loading https://github.com?

Chrome - ERR_CACHE_MISS

Yes, this is a current issue in Chrome. There is an issue report here.

The fix will appear in 40.x.y.z versions.

Until then? I don't think you can resolve the issue yourself. But you can ignore it. The shown error is only related to the dev tools and does not influence the behavior of your website. If you have any other problems they are not related to this error.

omp parallel vs. omp parallel for

There are obviously plenty of answers, but this one answers it very nicely (with source)

#pragma omp for only delegates portions of the loop for different threads in the current team. A team is the group of threads executing the program. At program start, the team consists only of a single member: the master thread that runs the program.

To create a new team of threads, you need to specify the parallel keyword. It can be specified in the surrounding context:

#pragma omp parallel
{
   #pragma omp for
   for(int n = 0; n < 10; ++n)
   printf(" %d", n);
}

and:

What are: parallel, for and a team

The difference between parallel, parallel for and for is as follows:

A team is the group of threads that execute currently. At the program beginning, the team consists of a single thread. A parallel construct splits the current thread into a new team of threads for the duration of the next block/statement, after which the team merges back into one. for divides the work of the for-loop among the threads of the current team.

It does not create threads, it only divides the work amongst the threads of the currently executing team. parallel for is a shorthand for two commands at once: parallel and for. Parallel creates a new team, and for splits that team to handle different portions of the loop. If your program never contains a parallel construct, there is never more than one thread; the master thread that starts the program and runs it, as in non-threading programs.

https://bisqwit.iki.fi/story/howto/openmp/

VBA, if a string contains a certain letter

Not sure if this is what you're after, but it will loop through the range that you gave it and if it finds an "A" it will remove it from the cell. I'm not sure what oldStr is used for...

Private Sub foo()
Dim myString As String
RowCount = WorksheetFunction.CountA(Range("A:A"))

For i = 2 To RowCount
    myString = Trim(Cells(i, 1).Value)
    If InStr(myString, "A") > 0 Then
        Cells(i, 1).Value = Left(myString, InStr(myString, "A"))
    End If
Next
End Sub

How to compile and run a C/C++ program on the Android system

If you want to compile and run Java/C/C++ apps directly on your Android device, I recommend the Terminal IDE environment from Google Play. It's a very slick package to develop and compile Android APKs, Java, C and C++ directly on your device. The interface is all command line and "vi" based, so it has real Linux feel. It comes with the gnu C/C++ implementation.

Additionally, there is a telnet and telnet server application built in, so you can do all the programming with your PC and big keyboard, but working on the device. No root permission is needed.

Windows 7 SDK installation failure

Uninstalling all C++ redistributables and unchecking the C++ option worked for me. Note that I have VS2010 SP1, and VS2012 installed already.

Spring Boot - How to log all requests and responses with exceptions in single place?

If you are seeing only part of your request payload, you need to call the setMaxPayloadLength function as it defaults to showing only 50 characters in your request body. Also, setting setIncludeHeaders to false is a good idea if you don't want to log your auth headers!

@Bean
public CommonsRequestLoggingFilter requestLoggingFilter() {
    CommonsRequestLoggingFilter loggingFilter = new CommonsRequestLoggingFilter();
    loggingFilter.setIncludeClientInfo(false);
    loggingFilter.setIncludeQueryString(false);
    loggingFilter.setIncludePayload(true);
    loggingFilter.setIncludeHeaders(false);
    loggingFilter.setMaxPayloadLength(500);
    return loggingFilter;
}

NPM clean modules

You can take advantage of the 'npm cache' command which downloads the package tarball and unpacks it into the npm cache directory.

The source can then be copied in.

Using ideas gleaned from https://groups.google.com/forum/?fromgroups=#!topic/npm-/mwLuZZkHkfU I came up with the following node script. No warranties, YMMV, etcetera.

var fs = require('fs'),
path = require('path'),
exec = require('child_process').exec,
util = require('util');

var packageFileName = 'package.json';
var modulesDirName = 'node_modules';
var cacheDirectory = process.cwd();
var npmCacheAddMask = 'npm cache add %s@%s; echo %s';
var sourceDirMask = '%s/%s/%s/package';
var targetDirMask = '%s/node_modules/%s';

function deleteFolder(folder) {
    if (fs.existsSync(folder)) {
        var files = fs.readdirSync(folder);
        files.forEach(function(file) {
            file = folder + "/" + file;
            if (fs.lstatSync(file).isDirectory()) {
                deleteFolder(file);
            } else {
                fs.unlinkSync(file);
            }
        });
        fs.rmdirSync(folder);
    }
}

function downloadSource(folder) {
    var packageFile = path.join(folder, packageFileName);
    if (fs.existsSync(packageFile)) {
        var data = fs.readFileSync(packageFile);
        var package = JSON.parse(data);

        function getVersion(data) {
            var version = data.match(/-([^-]+)\.tgz/);
            return version[1];
        }

        var callback = function(error, stdout, stderr) {
            var dependency = stdout.trim();
            var version = getVersion(stderr);
            var sourceDir = util.format(sourceDirMask, cacheDirectory, dependency, version);
            var targetDir = util.format(targetDirMask, folder, dependency);
            var modulesDir = folder + '/' + modulesDirName;

            if (!fs.existsSync(modulesDir)) {
                fs.mkdirSync(modulesDir);
            }

            fs.renameSync(sourceDir, targetDir);
            deleteFolder(cacheDirectory + '/' + dependency);
            downloadSource(targetDir);
        };

        for (dependency in package.dependencies) {
            var version = package.dependencies[dependency];
            exec(util.format(npmCacheAddMask, dependency, version, dependency), callback);
        }
    }
}

if (!fs.existsSync(path.join(process.cwd(), packageFileName))) {
    console.log(util.format("Unable to find file '%s'.", packageFileName));
    process.exit();
}

deleteFolder(path.join(process.cwd(), modulesDirName));
process.env.npm_config_cache = cacheDirectory;
downloadSource(process.cwd());

Is it possible to decompile a compiled .pyc file into a .py file?

Yes, it is possible.

There is a perfect open-source Python (.PYC) decompiler, called Decompyle++ https://github.com/zrax/pycdc/

Decompyle++ aims to translate compiled Python byte-code back into valid and human-readable Python source code. While other projects have achieved this with varied success, Decompyle++ is unique in that it seeks to support byte-code from any version of Python.

Chosen Jquery Plugin - getting selected values

$("#select-id").chosen().val()

How do I find the index of a character in a string in Ruby?

str="abcdef"

str.index('c') #=> 2 #String matching approach
str=~/c/ #=> 2 #Regexp approach 
$~ #=> #<MatchData "c">

Hope it helps. :)

Keras model.summary() result - Understanding the # of Parameters

I feed a 514 dimensional real-valued input to a Sequential model in Keras. My model is constructed in following way :

    predictivemodel = Sequential()
    predictivemodel.add(Dense(514, input_dim=514, W_regularizer=WeightRegularizer(l1=0.000001,l2=0.000001), init='normal'))
    predictivemodel.add(Dense(257, W_regularizer=WeightRegularizer(l1=0.000001,l2=0.000001), init='normal'))
    predictivemodel.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy'])

When I print model.summary() I get following result:

Layer (type)    Output Shape  Param #     Connected to                   
================================================================
dense_1 (Dense) (None, 514)   264710      dense_input_1[0][0]              
________________________________________________________________
activation_1    (None, 514)   0           dense_1[0][0]                    
________________________________________________________________
dense_2 (Dense) (None, 257)   132355      activation_1[0][0]               
================================================================
Total params: 397065
________________________________________________________________ 

For the dense_1 layer , number of params is 264710. This is obtained as : 514 (input values) * 514 (neurons in the first layer) + 514 (bias values)

For dense_2 layer, number of params is 132355. This is obtained as : 514 (input values) * 257 (neurons in the second layer) + 257 (bias values for neurons in the second layer)

How do I recognize "#VALUE!" in Excel spreadsheets?

This will return TRUE for #VALUE! errors (ERROR.TYPE = 3) and FALSE for anything else.

=IF(ISERROR(A1),ERROR.TYPE(A1)=3)

Why there is this "clear" class before footer?

Most likely, as mentioned by others, it is a class carrying the css values:

.clear{clear: both;} 

in order to prevent any more page elements from extending into the footer element. It is a quick and easy way of making sure that pages with columns of varying heights don't cause the footer to render oddly, by possibly setting its top position at the end of a shorter column.

In many cases it is not necessary, but if you are using best-practice standards it is a good idea to use, if you are floating page elements left and right. It functions with page elements similar to the way a horizontal rule works with text, to ensure proper and complete sepperation.

Android Fatal signal 11 (SIGSEGV) at 0x636f7d89 (code=1). How can it be tracked down?

If you are using vitamio library and this fatal error occur.

Then make sure that in your project gradle targetSdkVersion must be less than 23.

thanks.

how to insert date and time in oracle?

You are doing everything right by using a to_date function and specifying the time. The time is there in the database. The trouble is just that when you select a column of DATE datatype from the database, the default format mask doesn't show the time. If you issue a

alter session set nls_date_format = 'dd/MON/yyyy hh24:mi:ss'

or something similar including a time component, you will see that the time successfully made it into the database.

How to get the last characters in a String in Java, regardless of String size

StringUtils.substringAfterLast("abcd: efg: 1006746", ": ") = "1006746";

As long as the format of the string is fixed you can use substringAfterLast.

What is the difference between static_cast<> and C style casting?

See A comparison of the C++ casting operators.

However, using the same syntax for a variety of different casting operations can make the intent of the programmer unclear.

Furthermore, it can be difficult to find a specific type of cast in a large codebase.

the generality of the C-style cast can be overkill for situations where all that is needed is a simple conversion. The ability to select between several different casting operators of differing degrees of power can prevent programmers from inadvertently casting to an incorrect type.

string to string array conversion in java

Splitting an empty string with String.split() returns a single element array containing an empty string. In most cases you'd probably prefer to get an empty array, or a null if you passed in a null, which is exactly what you get with org.apache.commons.lang3.StringUtils.split(str).

import org.apache.commons.lang3.StringUtils;

StringUtils.split(null)       => null
StringUtils.split("")         => []
StringUtils.split("abc def")  => ["abc", "def"]
StringUtils.split("abc  def") => ["abc", "def"]
StringUtils.split(" abc ")    => ["abc"]

Another option is google guava Splitter.split() and Splitter.splitToList() which return an iterator and a list correspondingly. Unlike the apache version Splitter will throw an NPE on null:

import com.google.common.base.Splitter;

Splitter SPLITTER = Splitter.on(',').trimResults().omitEmptyStrings();

SPLITTER.split("a,b,   c , , ,, ")     =>  [a, b, c]
SPLITTER.split("")                     =>  []
SPLITTER.split("  ")                   =>  []
SPLITTER.split(null)                   =>  NullPointerException

If you want a list rather than an iterator then use Splitter.splitToList().

Create list or arrays in Windows Batch

@echo off
setlocal
set "list=a b c d"
(
 for %%i in (%list%) do (
  echo(%%i
  echo(
 )
)>file.txt

You don't need - actually, can't "declare" variables in batch. Assigning a value to a variable creates it, and assigning an empty string deletes it. Any variable name that doesn't have an assigned value HAS a value of an empty string. ALL variables are strings - WITHOUT exception. There ARE operations that appear to perform (integer) mathematical functions, but they operate by converting back and forth from strings.

Batch is sensitive to spaces in variable names, so your assignment as posted would assign the string "A B C D" - including the quotes, to the variable "list " - NOT including the quotes, but including the space. The syntax set "var=string" is used to assign the value string to var whereas set var=string will do the same thing. Almost. In the first case, any stray trailing spaces after the closing quote are EXCLUDED from the value assigned, in the second, they are INCLUDED. Spaces are a little hard to see when printed.

ECHO echoes strings. Clasically, it is followed by a space - one of the default separators used by batch (the others are TAB, COMMA, SEMICOLON - any of these do just as well BUT TABS often get transformed to a space-squence by text-editors and the others have grown quirks of their own over the years.) Other characters following the O in ECHO have been found to do precisely what the documented SPACE should do. DOT is common. Open-parenthesis ( is probably the most useful since the command

ECHO.%emptyvalue%

will produce a report of the ECHO state (ECHO is on/off) whereas

ECHO(%emptyvalue%

will produce an empty line.

The problem with ECHO( is that the result "looks" unbalanced.

What's the difference between a mock & stub?

A Mock is just testing behaviour, making sure certain methods are called. A Stub is a testable version (per se) of a particular object.

What do you mean an Apple way?

How to toggle font awesome icon on click?

You can change the code by using class definition for the i element:

<a href="javascript:void"><i class="fa fa-plus-circle"></i>Category 1</a>

Then you can switch the classes rapresenting the plus/minus state using toggleClass with multiple classes:

$('#category-tabs li a').click(function(){
    $(this).next('ul').slideToggle('500');
    $(this).find('i').toggleClass('fa-plus-circle fa-minus-circle');
});

Demo: http://jsfiddle.net/Zcn2u/

Python integer division yields float

According to Python3 documentation,python when divided by integer,will generate float despite expected to be integer.

For exclusively printing integer,use floor division method. Floor division is rounding off zero and removing decimal point. Represented by //

Hence,instead of 2/2 ,use 2//2

You can also import division from __future__ irrespective of using python2 or python3.

Hope it helps!

Html5 Placeholders with .NET MVC 3 Razor EditorFor extension?

I use this way with Resource file (don't need Prompt anymore !)

@Html.TextBoxFor(m => m.Name, new 
{
     @class = "form-control",
     placeholder = @Html.DisplayName(@Resource.PleaseTypeName),
     autofocus = "autofocus",
     required = "required"
})

Method to find string inside of the text file. Then getting the following lines up to a certain limit

When you are reading the file, have you considered reading it line by line? This would allow you to check if your line contains the file as your are reading, and you could then perform whatever logic you needed based on that?

Scanner scanner = new Scanner("Student.txt");
String currentLine;

while((currentLine = scanner.readLine()) != null)
{
    if(currentLine.indexOf("Your String"))
    {
         //Perform logic
    }
}

You could use a variable to hold the line number, or you could also have a boolean indicating if you have passed the line that contains your string:

Scanner scanner = new Scanner("Student.txt");
String currentLine;
int lineNumber = 0;
Boolean passedLine = false;
while((currentLine = scanner.readLine()) != null)
{
    if(currentLine.indexOf("Your String"))
    {
         //Do task
         passedLine = true;
    }
    if(passedLine)
    {
       //Do other task after passing the line.
    }
    lineNumber++;
}

How to split data into trainset and testset randomly?

You can try this approach

import pandas
import sklearn
csv = pandas.read_csv('data.csv')
train, test = sklearn.cross_validation.train_test_split(csv, train_size = 0.5)

UPDATE: train_test_split was moved to model_selection so the current way (scikit-learn 0.22.2) to do it is this:

import pandas
import sklearn
csv = pandas.read_csv('data.csv')
train, test = sklearn.model_selection.train_test_split(csv, train_size = 0.5)

jQuery: How to capture the TAB keypress within a Textbox

Edit: Since your element is dynamically inserted, you have to use delegated on() as in your example, but you should bind it to the keydown event, because as @Marc comments, in IE the keypress event doesn't capture non-character keys:

$("#parentOfTextbox").on('keydown', '#textbox', function(e) { 
  var keyCode = e.keyCode || e.which; 

  if (keyCode == 9) { 
    e.preventDefault(); 
    // call custom function here
  } 
});

Check an example here.

How do I get the current time only in JavaScript

_x000D_
_x000D_
const date = Date().slice(16,21);_x000D_
console.log(date);
_x000D_
_x000D_
_x000D_

How do I install package.json dependencies in the current directory using npm

In my case I need to do

sudo npm install  

my project is inside /var/www so I also need to set proper permissions.

How to make primary key as autoincrement for Room Persistence lib

@Entity(tableName = "user")
data class User(

@PrimaryKey(autoGenerate = true)  var id: Int?,
       var name: String,
       var dob: String,
       var address: String,
       var gender: String
)
{
    constructor():this(null,
        "","","","")
}

library not found for -lPods

Are you opening the workspace (that was generated by CocoaPods) instead of the xcodeproj?

Update int column in table with unique incrementing values

simple query would be, just set a variable to some number you want. then update the column you need by incrementing 1 from that number. for all the rows it'll update each row id by incrementing 1

SET @a  = 50000835 ;  
UPDATE `civicrm_contact` SET external_identifier = @a:=@a+1 
WHERE external_identifier IS NULL;

SQL Insert Query Using C#

class Program
{
    static void Main(string[] args)
    {
        string connetionString = null;
        SqlConnection connection;
        SqlCommand command;
        string sql = null;

        connetionString = "Data Source=Server Name;Initial Catalog=DataBaseName;User ID=UserID;Password=Password";
        sql = "INSERT INTO LoanRequest(idLoanRequest,RequestDate,Pickupdate,ReturnDate,EventDescription,LocationOfEvent,ApprovalComments,Quantity,Approved,EquipmentAvailable,ModifyRequest,Equipment,Requester)VALUES('5','2016-1-1','2016-2-2','2016-3-3','DescP','Loca1','Appcoment','2','true','true','true','4','5')";
        connection = new SqlConnection(connetionString);

        try
        {
            connection.Open();
            Console.WriteLine(" Connection Opened ");
            command = new SqlCommand(sql, connection);                
            SqlDataReader dr1 = command.ExecuteReader();         

            connection.Close();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Can not open connection ! ");
        }
    }
}

Java :Add scroll into text area

My naive assumption was that the size of scroll pane will be determined automatically...

The only solution that actually worked for me was explicitly seeting bounds of JScrollPane:

import javax.swing.*;

public class MyFrame extends JFrame {

    public MyFrame()
    {
        setBounds(100, 100, 491, 310);
        getContentPane().setLayout(null);

        JTextArea textField = new JTextArea();
        textField.setEditable(false);

        String str = "";
        for (int i = 0; i < 50; ++i)
            str += "Some text\n";
        textField.setText(str);

        JScrollPane scroll = new JScrollPane(textField);
        scroll.setBounds(10, 11, 455, 249);                     // <-- THIS

        getContentPane().add(scroll);
        setLocationRelativeTo ( null );
    }
}

Maybe it will help some future visitors :)

Safe Area of Xcode 9

Safe Area is a layout guide (Safe Area Layout Guide).
The layout guide representing the portion of your view that is unobscured by bars and other content. In iOS 11+, Apple is deprecating the top and bottom layout guides and replacing them with a single safe area layout guide.

When the view is visible onscreen, this guide reflects the portion of the view that is not covered by other content. The safe area of a view reflects the area covered by navigation bars, tab bars, toolbars, and other ancestors that obscure a view controller's view. (In tvOS, the safe area incorporates the screen's bezel, as defined by the overscanCompensationInsets property of UIScreen.) It also covers any additional space defined by the view controller's additionalSafeAreaInsets property. If the view is not currently installed in a view hierarchy, or is not yet visible onscreen, the layout guide always matches the edges of the view.

For the view controller's root view, the safe area in this property represents the entire portion of the view controller's content that is obscured, and any additional insets that you specified. For other views in the view hierarchy, the safe area reflects only the portion of that view that is obscured. For example, if a view is entirely within the safe area of its view controller's root view, the edge insets in this property are 0.

According to Apple, Xcode 9 - Release note
Interface Builder uses UIView.safeAreaLayoutGuide as a replacement for the deprecated Top and Bottom layout guides in UIViewController. To use the new safe area, select Safe Area Layout Guides in the File inspector for the view controller, and then add constraints between your content and the new safe area anchors. This prevents your content from being obscured by top and bottom bars, and by the overscan region on tvOS. Constraints to the safe area are converted to Top and Bottom when deploying to earlier versions of iOS.

enter image description here


Here is simple reference as a comparison (to make similar visual effect) between existing (Top & Bottom) Layout Guide and Safe Area Layout Guide.

Safe Area Layout: enter image description here

AutoLayout

enter image description here


How to work with Safe Area Layout?

Follow these steps to find solution:

  • Enable 'Safe Area Layout', if not enabled.
  • Remove 'all constraint' if they shows connection with with Super view and re-attach all with safe layout anchor. OR Double click on a constraint and edit connection from super view to SafeArea anchor

Here is sample snapshot, how to enable safe area layout and edit constraint.

enter image description here

Here is result of above changes

enter image description here


Layout Design with SafeArea
When designing for iPhone X, you must ensure that layouts fill the screen and aren't obscured by the device's rounded corners, sensor housing, or the indicator for accessing the Home screen.

enter image description here

Most apps that use standard, system-provided UI elements like navigation bars, tables, and collections automatically adapt to the device's new form factor. Background materials extend to the edges of the display and UI elements are appropriately inset and positioned.

enter image description here

For apps with custom layouts, supporting iPhone X should also be relatively easy, especially if your app uses Auto Layout and adheres to safe area and margin layout guides.

enter image description here


Here is sample code (Ref from: Safe Area Layout Guide):
If you create your constraints in code use the safeAreaLayoutGuide property of UIView to get the relevant layout anchors. Let’s recreate the above Interface Builder example in code to see how it looks:

Assuming we have the green view as a property in our view controller:

private let greenView = UIView()

We might have a function to set up the views and constraints called from viewDidLoad:

private func setupView() {
  greenView.translatesAutoresizingMaskIntoConstraints = false
  greenView.backgroundColor = .green
  view.addSubview(greenView)
}

Create the leading and trailing margin constraints as always using the layoutMarginsGuide of the root view:

 let margins = view.layoutMarginsGuide
    NSLayoutConstraint.activate([
      greenView.leadingAnchor.constraint(equalTo: margins.leadingAnchor),
      greenView.trailingAnchor.constraint(equalTo: margins.trailingAnchor)
 ])

Now unless you are targeting iOS 11 only you will need to wrap the safe area layout guide constraints with #available and fall back to top and bottom layout guides for earlier iOS versions:

if #available(iOS 11, *) {
  let guide = view.safeAreaLayoutGuide
  NSLayoutConstraint.activate([
   greenView.topAnchor.constraintEqualToSystemSpacingBelow(guide.topAnchor, multiplier: 1.0),
   guide.bottomAnchor.constraintEqualToSystemSpacingBelow(greenView.bottomAnchor, multiplier: 1.0)
   ])

} else {
   let standardSpacing: CGFloat = 8.0
   NSLayoutConstraint.activate([
   greenView.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor, constant: standardSpacing),
   bottomLayoutGuide.topAnchor.constraint(equalTo: greenView.bottomAnchor, constant: standardSpacing)
   ])
}


Result:

enter image description here


Following UIView extension, make it easy for you to work with SafeAreaLayout programatically.

extension UIView {

  // Top Anchor
  var safeAreaTopAnchor: NSLayoutYAxisAnchor {
    if #available(iOS 11.0, *) {
      return self.safeAreaLayoutGuide.topAnchor
    } else {
      return self.topAnchor
    }
  }

  // Bottom Anchor
  var safeAreaBottomAnchor: NSLayoutYAxisAnchor {
    if #available(iOS 11.0, *) {
      return self.safeAreaLayoutGuide.bottomAnchor
    } else {
      return self.bottomAnchor
    }
  }

  // Left Anchor
  var safeAreaLeftAnchor: NSLayoutXAxisAnchor {
    if #available(iOS 11.0, *) {
      return self.safeAreaLayoutGuide.leftAnchor
    } else {
      return self.leftAnchor
    }
  }

  // Right Anchor
  var safeAreaRightAnchor: NSLayoutXAxisAnchor {
    if #available(iOS 11.0, *) {
      return self.safeAreaLayoutGuide.rightAnchor
    } else {
      return self.rightAnchor
    }
  }

}

Here is sample code in Objective-C:


Here is Apple Developer Official Documentation for Safe Area Layout Guide


Safe Area is required to handle user interface design for iPhone-X. Here is basic guideline for How to design user interface for iPhone-X using Safe Area Layout

TortoiseSVN icons overlay not showing after updating to Windows 10

Windows explorer allots 15 custom overlay icons (Windows reserves 4, so effectively only 11 overlay icons) - they are shared between multiple applications (Google drive, One drive, Tortoise SVN). If you have multiple applications installed - the first ones in list will display their icons, rest of applications won’t.

Problem is described deeper in: https://tortoisesvn.net/faq.html#ovlnotall.

Open registry editor in:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers

Rename icons which are not important to you to start from ‘z_’ prefix (will be last in list, will not be used after that).

regedit snapshoot

Windows restart might be needed, as just restart explorer does not work. But in my case icons appeared to be correct after some time. (10-20 minutes ?).

Setting maxlength of textbox with JavaScript or jQuery

You can make it like this:

$('#inputID').keypress(function () {
    var maxLength = $(this).val().length;
    if (maxLength >= 5) {
        alert('You cannot enter more than ' + maxLength + ' chars');
        return false;
    }
});

How do I do a HTTP GET in Java?

If you dont want to use external libraries, you can use URL and URLConnection classes from standard Java API.

An example looks like this:

String urlString = "http://wherever.com/someAction?param1=value1&param2=value2....";
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
// Do what you want with that stream

Order by in Inner Join

I found this to be an issue when joining but you might find this blog useful in understanding how Joins work in the back. How Joins Work..

[Edited] @Shree Thank you for pointing that out. On the paragraph of Merge Join. It mentions on how joins work...

Like hash join, merge join consists of two steps. First, both tables of the join are sorted on the join attribute. This can be done with just two passes through each table via an external merge sort. Finally, the result tuples are generated as the next ordered element is pulled from each table and the join attributes are compared

.

Prevent WebView from displaying "web page not available"

try this shouldOverrideUrlLoading , before redirect to another url check for internet conncetion based on that page should be loaded or not.

jQuery datepicker years shown

Adding to what @Shog9 posted, you can also restrict dates individually in the beforeShowDay: callback function.

You supply a function that takes a date and returns a boolean array:

"$(".selector").datepicker({ beforeShowDay: nationalDays}) 
natDays = [[1, 26, 'au'], [2, 6, 'nz'], [3, 17, 'ie'], [4, 27, 'za'], 
[5, 25, 'ar'], [6, 6, 'se'], [7, 4, 'us'], [8, 17, 'id'], [9, 7, 
'br'], [10, 1, 'cn'], [11, 22, 'lb'], [12, 12, 'ke']]; 
function nationalDays(date) { 
    for (i = 0; i < natDays.length; i++) { 
      if (date.getMonth() == natDays[i][0] - 1 && date.getDate() == 
natDays[i][1]) { 
        return [false, natDays[i][2] + '_day']; 
      } 
    } 
  return [true, '']; 
} 

How to change font-color for disabled input?

This works for making disabled select options act as headers. It doesnt remove the default text shadow of the :disabled option but it does remove the hover effect. In IE you wont get the font color but at least the text-shadow is gone. Here is the html and css:

_x000D_
_x000D_
select option.disabled:disabled{color: #5C3333;background-color: #fff;font-weight: bold;}_x000D_
select option.disabled:hover{color:  #5C3333 !important;background-color: #fff;}_x000D_
select option:hover{color: #fde8c4;background-color: #5C3333;}
_x000D_
<select>_x000D_
     <option class="disabled" disabled>Header1</option>_x000D_
     <option>Item1</option>_x000D_
     <option>Item1</option>_x000D_
     <option>Item1</option>_x000D_
     <option class="disabled" disabled>Header2</option>_x000D_
     <option>Item2</option>_x000D_
     <option>Item2</option>_x000D_
     <option>Item2</option>_x000D_
     <option class="disabled" disabled>Header3</option>_x000D_
     <option>Item3</option>_x000D_
     <option>Item3</option>_x000D_
     <option>Item3</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

copying all contents of folder to another folder using batch file?

I see a lot of answers suggesting the use of xcopy. But this is unnecessary. As the question clearly mentions that the author wants THE CONTENT IN THE FOLDER not the folder itself to be copied in this case we can -:

copy "C:\Folder1" *.*  "D:\Folder2"

Thats all xcopy can be used for if any subdirectory exists in C:\Folder1

Ruby send JSON request

uri = URI('https://myapp.com/api/v1/resource')
req = Net::HTTP::Post.new(uri, 'Content-Type' => 'application/json')
req.body = {param1: 'some value', param2: 'some other value'}.to_json
res = Net::HTTP.start(uri.hostname, uri.port) do |http|
  http.request(req)
end

Is there a built-in function to print all the current properties and values of an object?

Just try beeprint.

It will help you not only with printing object variables, but beautiful output as well, like this:

class(NormalClassNewStyle):
  dicts: {
  },
  lists: [],
  static_props: 1,
  tupl: (1, 2)

How to create a directory using Ansible

Directory can be created using file module only, as directory is nothing but a file.

# create a directory if it doesn't exist
- file:
    path: /etc/some_directory
    state: directory
    mode: 0755
    owner: foo
    group: foo

How to deal with "java.lang.OutOfMemoryError: Java heap space" error?

VM arguments worked for me in eclipse. If you are using eclipse version 3.4, do the following

go to Run --> Run Configurations --> then select the project under maven build --> then select the tab "JRE" --> then enter -Xmx1024m.

Alternatively you could do Run --> Run Configurations --> select the "JRE" tab --> then enter -Xmx1024m

This should increase the memory heap for all the builds/projects. The above memory size is 1 GB. You can optimize the way you want.

Python data structure sort list alphabetically

Python has a built-in function called sorted, which will give you a sorted list from any iterable you feed it (such as a list ([1,2,3]); a dict ({1:2,3:4}, although it will just return a sorted list of the keys; a set ({1,2,3,4); or a tuple ((1,2,3,4))).

>>> x = [3,2,1]
>>> sorted(x)
[1, 2, 3]
>>> x
[3, 2, 1]

Lists also have a sort method that will perform the sort in-place (x.sort() returns None but changes the x object) .

>>> x = [3,2,1]
>>> x.sort()
>>> x
[1, 2, 3]

Both also take a key argument, which should be a callable (function/lambda) you can use to change what to sort by.
For example, to get a list of (key,value)-pairs from a dict which is sorted by value you can use the following code:

>>> x = {3:2,2:1,1:5}
>>> sorted(x.items(), key=lambda kv: kv[1])  # Items returns a list of `(key,value)`-pairs
[(2, 1), (3, 2), (1, 5)]

How to call servlet through a JSP page

You can use RequestDispatcher as you usually use it in Servlet:

<%@ page contentType="text/html"%>
<%@ page import = "javax.servlet.RequestDispatcher" %>
<%
     RequestDispatcher rd = request.getRequestDispatcher("/yourServletUrl");
     request.setAttribute("msg","HI Welcome");
     rd.forward(request, response);
%>

Always be aware that don't commit any response before you use forward, as it will lead to IllegalStateException.

Convert MySql DateTime stamp into JavaScript's Date format

Some of the answers given here are either overcomplicated or just will not work (at least, not in all browsers). If you take a step back, you can see that the MySQL timestamp has each component of time in the same order as the arguments required by the Date() constructor.

All that's needed is a very simple split on the string:

// Split timestamp into [ Y, M, D, h, m, s ]
var t = "2010-06-09 13:12:01".split(/[- :]/);

// Apply each element to the Date function
var d = new Date(Date.UTC(t[0], t[1]-1, t[2], t[3], t[4], t[5]));

console.log(d);
// -> Wed Jun 09 2010 14:12:01 GMT+0100 (BST)

Fair warning: this assumes that your MySQL server is outputting UTC dates (which is the default, and recommended if there is no timezone component of the string).

How can I insert into a BLOB column from an insert statement in sqldeveloper?

  1. insert into mytable(id, myblob) values (1,EMPTY_BLOB);
  2. SELECT * FROM mytable mt where mt.id=1 for update
  3. Click on the Lock icon to unlock for editing
  4. Click on the ... next to the BLOB to edit
  5. Select the appropriate tab and click open on the top left.
  6. Click OK and commit the changes.

ASP.NET MVC Html.DropDownList SelectedValue

This is how I fixed this problem:

I had the following:

Controller:

ViewData["DealerTypes"] = Helper.SetSelectedValue(listOfValues, selectedValue) ;

View

<%=Html.DropDownList("DealerTypes", ViewData["DealerTypes"] as SelectList)%>

Changed by the following:

View

<%=Html.DropDownList("DealerTypesDD", ViewData["DealerTypes"] as SelectList)%>

It appears that the DropDown must not have the same name has the ViewData name :S weird but it worked.

Passing data to a jQuery UI Dialog

jQuery provides a method which store data for you, no need to use a dummy attribute or to find workaround to your problem.

Bind the click event:

$('a[href*=/Booking.aspx/Change]').bind('click', function(e) {
    e.preventDefault();
    $("#dialog-confirm")
        .data('link', this)  // The important part .data() method
        .dialog('open');
});

And your dialog:

$("#dialog-confirm").dialog({
    autoOpen: false,
    resizable: false,
    height:200,
    modal: true,
    buttons: {
        Cancel: function() {
            $(this).dialog('close');
        },
        'Delete': function() {
            $(this).dialog('close');
            var path = $(this).data('link').href; // Get the stored result
            $(location).attr('href', path);
        }
    }
});

Error "The connection to adb is down, and a severe error has occurred."

It worked for me to start my AVD emulator first (from the AVD manager), and then to run my program. The other stuff mentioned here.

(Restarting the ADB server didn't work though.)

how does Request.QueryString work?

The Request object is the entire request sent out to some server. This object comes with a QueryString dictionary that is everything after '?' in the URL.

Not sure exactly what you were looking for in an answer, but check out http://en.wikipedia.org/wiki/Query_string

Closing JFrame with button click

You cat use setVisible () method of JFrame (and set visibility to false) or dispose () method which is more similar to close operation.

How to pass a null variable to a SQL Stored Procedure from C#.net code

Use DBNull.Value Better still, make your stored procedure parameters have defaults of NULL. Or use a Nullable<DateTime> parameter if the parameter will sometimes be a valid DateTime object

Select NOT IN multiple columns

Another mysteriously unknown RDBMS. Your Syntax is perfectly fine in PostgreSQL. Other query styles may perform faster (especially the NOT EXISTS variant or a LEFT JOIN), but your query is perfectly legit.

Be aware of pitfalls with NOT IN, though, when involving any NULL values:

Variant with LEFT JOIN:

SELECT *
FROM   friend f
LEFT   JOIN likes l USING (id1, id2)
WHERE  l.id1 IS NULL;

See @Michal's answer for the NOT EXISTS variant.
A more detailed assessment of four basic variants:

Printing the last column of a line in a file

Execute this on the file:

awk 'ORS=NR%3?" ":"\n"' filename

and you'll get what you're looking for.

Automatically plot different colored lines

Late answer, but two things to add:

  • For information on how to change the 'ColorOrder' property and how to set a global default with 'DefaultAxesColorOrder', see the "Appendix" at the bottom of this post.
  • There is a great tool on the MATLAB Central File Exchange to generate any number of visually distinct colors, if you have the Image Processing Toolbox to use it. Read on for details.

The ColorOrder axes property allows MATLAB to automatically cycle through a list of colors when using hold on/all (again, see Appendix below for how to set/get the ColorOrder for a specific axis or globally via DefaultAxesColorOrder). However, by default MATLAB only specifies a short list of colors (just 7 as of R2013b) to cycle through, and on the other hand it can be problematic to find a good set of colors for more data series. For 10 plots, you obviously cannot rely on the default ColorOrder.

A great way to define N visually distinct colors is with the "Generate Maximally Perceptually-Distinct Colors" (GMPDC) submission on the MATLAB Central File File Exchange. It is best described in the author's own words:

This function generates a set of colors which are distinguishable by reference to the "Lab" color space, which more closely matches human color perception than RGB. Given an initial large list of possible colors, it iteratively chooses the entry in the list that is farthest (in Lab space) from all previously-chosen entries.

For example, when 25 colors are requested:

25 "maximally perceptually-distinct colors"

The GMPDC submission was chosen on MathWorks' official blog as Pick of the Week in 2010 in part because of the ability to request an arbitrary number of colors (in contrast to MATLAB's built in 7 default colors). They even made the excellent suggestion to set MATLAB's ColorOrder on startup to,

distinguishable_colors(20)

Of course, you can set the ColorOrder for a single axis or simply generate a list of colors to use in any way you like. For example, to generate 10 "maximally perceptually-distinct colors" and use them for 10 plots on the same axis (but not using ColorOrder, thus requiring a loop):

% Starting with X of size N-by-P-by-2, where P is number of plots
mpdc10 = distinguishable_colors(10) % 10x3 color list
hold on
for ii=1:size(X,2),
    plot(X(:,ii,1),X(:,ii,2),'.','Color',mpdc10(ii,:));
end

The process is simplified, requiring no for loop, with the ColorOrder axis property:

% X of size N-by-P-by-2
mpdc10 = distinguishable_colors(10)
ha = axes; hold(ha,'on')
set(ha,'ColorOrder',mpdc10)    % --- set ColorOrder HERE ---
plot(X(:,:,1),X(:,:,2),'-.')   % loop NOT needed, 'Color' NOT needed. Yay!

APPENDIX

To get the ColorOrder RGB array used for the current axis,

get(gca,'ColorOrder')

To get the default ColorOrder for new axes,

get(0,'DefaultAxesColorOrder')

Example of setting new global ColorOrder with 10 colors on MATLAB start, in startup.m:

set(0,'DefaultAxesColorOrder',distinguishable_colors(10))

How do I make a text input non-editable?

<input type="text" value="3" class="field left" readonly>

No styling necessary.

See <input> on MDN https://developer.mozilla.org/en/docs/Web/HTML/Element/input#Attributes

White space at top of page

There could be many reasons that you are getting white space as mentioned above. Suppose if you have empty div element with HTML Entities also cause the error.
Example

<div class="sample">&nbsp;</div>

Remove HTML Entities

<div class="sample"></div>

How to Remove the last char of String in C#?

YourString = YourString.Remove(YourString.Length - 1);

Find the smallest positive integer that does not occur in a given sequence

This is might help you, it should work fine!

public static int sol(int[] A)
{
    boolean flag =false;
    for(int i=1; i<=1000000;i++ ) {
        for(int j=0;j<A.length;j++) {
            if(A[j]==i) {
                flag = false;
                break;
            }else {
                flag = true;
            }
        }
        if(flag) {
            return i;
        }
    }
    return 1;
}

JS Client-Side Exif Orientation: Rotate and Mirror JPEG Images

I am using mixed solution (php+css).

Containers are needed for:

  • div.imgCont2 container needed to rotate;
  • div.imgCont1 container needed to zoomOut - width:150%;
  • div.imgCont container needed for scrollbars, when image is zoomOut.

.

<?php
    $image_url = 'your image url.jpg';
    $exif = @exif_read_data($image_url,0,true);
    $orientation = @$exif['IFD0']['Orientation'];
?>

<style>
.imgCont{
    width:100%;
    overflow:auto;
}
.imgCont2[data-orientation="8"]{
    transform:rotate(270deg);
    margin:15% 0;
}
.imgCont2[data-orientation="6"]{
    transform:rotate(90deg);
    margin:15% 0;
}
.imgCont2[data-orientation="3"]{
    transform:rotate(180deg);
}
img{
    width:100%;
}
</style>

<div class="imgCont">
  <div class="imgCont1">
    <div class="imgCont2" data-orientation="<?php echo($orientation) ?>">
      <img src="<?php echo($image_url) ?>">
    </div>
  </div>
</div>

Convert JsonNode into POJO

If you're using org.codehaus.jackson, this has been possible since 1.6. You can convert a JsonNode to a POJO with ObjectMapper#readValue: http://jackson.codehaus.org/1.9.4/javadoc/org/codehaus/jackson/map/ObjectMapper.html#readValue(org.codehaus.jackson.JsonNode, java.lang.Class)


    ObjectMapper mapper = new ObjectMapper();
    JsonParser jsonParser = mapper.getJsonFactory().createJsonParser("{\"foo\":\"bar\"}");
    JsonNode tree = jsonParser.readValueAsTree();
    // Do stuff to the tree
    mapper.readValue(tree, Foo.class);

Where is a log file with logs from a container?

A container's logs can be found in :

/var/lib/docker/containers/<container id>/<container id>-json.log

(if you use the default log format which is json)

Go doing a GET request and building the Querystring

Use r.URL.Query() when you appending to existing query, if you are building new set of params use the url.Values struct like so

package main

import (
    "fmt"
    "log"
    "net/http"
    "net/url"
    "os"
)

func main() {
    req, err := http.NewRequest("GET","http://api.themoviedb.org/3/tv/popular", nil)
    if err != nil {
        log.Print(err)
        os.Exit(1)
    }

    // if you appending to existing query this works fine 
    q := req.URL.Query()
    q.Add("api_key", "key_from_environment_or_flag")
    q.Add("another_thing", "foo & bar")

    // or you can create new url.Values struct and encode that like so
    q := url.Values{}
    q.Add("api_key", "key_from_environment_or_flag")
    q.Add("another_thing", "foo & bar")

    req.URL.RawQuery = q.Encode()

    fmt.Println(req.URL.String())
    // Output:
    // http://api.themoviedb.org/3/tv/popularanother_thing=foo+%26+bar&api_key=key_from_environment_or_flag
}

How do I do a case-insensitive string comparison?

Section 3.13 of the Unicode standard defines algorithms for caseless matching.

X.casefold() == Y.casefold() in Python 3 implements the "default caseless matching" (D144).

Casefolding does not preserve the normalization of strings in all instances and therefore the normalization needs to be done ('å' vs. 'a°'). D145 introduces "canonical caseless matching":

import unicodedata

def NFD(text):
    return unicodedata.normalize('NFD', text)

def canonical_caseless(text):
    return NFD(NFD(text).casefold())

NFD() is called twice for very infrequent edge cases involving U+0345 character.

Example:

>>> 'å'.casefold() == 'a°'.casefold()
False
>>> canonical_caseless('å') == canonical_caseless('a°')
True

There are also compatibility caseless matching (D146) for cases such as '?' (U+3392) and "identifier caseless matching" to simplify and optimize caseless matching of identifiers.

Performance of FOR vs FOREACH in PHP

It's 2020 and stuffs had greatly evolved with php 7.4 and opcache.

Here is the OP^ benchmark, ran as unix CLI, without the echo and html parts.

Test ran locally on a regular computer.

php -v

PHP 7.4.6 (cli) (built: May 14 2020 10:02:44) ( NTS )

Modified benchmark script:

<?php 
 ## preperations; just a simple environment state

  $test_iterations = 100;
  $test_arr_size = 1000;

  // a shared function that makes use of the loop; this should
  // ensure no funny business is happening to fool the test
  function test($input)
  {
    //echo '<!-- '.trim($input).' -->';
  }

  // for each test we create a array this should avoid any of the
  // arrays internal representation or optimizations from getting
  // in the way.

  // normal array
  $test_arr1 = array();
  $test_arr2 = array();
  $test_arr3 = array();
  // hash tables
  $test_arr4 = array();
  $test_arr5 = array();

  for ($i = 0; $i < $test_arr_size; ++$i)
  {
    mt_srand();
    $hash = md5(mt_rand());
    $key = substr($hash, 0, 5).$i;

    $test_arr1[$i] = $test_arr2[$i] = $test_arr3[$i] = $test_arr4[$key] = $test_arr5[$key]
      = $hash;
  }

  ## foreach

  $start = microtime(true);
  for ($j = 0; $j < $test_iterations; ++$j)
  {
    foreach ($test_arr1 as $k => $v)
    {
      test($v);
    }
  }
  echo 'foreach '.(microtime(true) - $start)."\n";  

  ## foreach (using reference)

  $start = microtime(true);
  for ($j = 0; $j < $test_iterations; ++$j)
  {
    foreach ($test_arr2 as &$value)
    {
      test($value);
    }
  }
  echo 'foreach (using reference) '.(microtime(true) - $start)."\n";

  ## for

  $start = microtime(true);
  for ($j = 0; $j < $test_iterations; ++$j)
  {
    $size = count($test_arr3);
    for ($i = 0; $i < $size; ++$i)
    {
      test($test_arr3[$i]);
    }
  }
  echo 'for '.(microtime(true) - $start)."\n";  

  ## foreach (hash table)

  $start = microtime(true);
  for ($j = 0; $j < $test_iterations; ++$j)
  {
    foreach ($test_arr4 as $k => $v)
    {
      test($v);
    }
  }
  echo 'foreach (hash table) '.(microtime(true) - $start)."\n";

  ## for (hash table)

  $start = microtime(true);
  for ($j = 0; $j < $test_iterations; ++$j)
  {
    $keys = array_keys($test_arr5);
    $size = sizeOf($test_arr5);
    for ($i = 0; $i < $size; ++$i)
    {
      test($test_arr5[$keys[$i]]);
    }
  }
  echo 'for (hash table) '.(microtime(true) - $start)."\n";

Output:

foreach 0.0032877922058105
foreach (using reference) 0.0029420852661133
for 0.0025191307067871
foreach (hash table) 0.0035080909729004
for (hash table) 0.0061779022216797

As you can see the evolution is insane, about 560 time faster than reported in 2012.

On my machines and servers, following my numerous experiments, basics for loops are the fastest. This is even clearer using nested loops ($i $j $k..)

It is also the most flexible in usage, and has a better readability from my view.

Cannot serve WCF services in IIS on Windows 8

For Windows Server 2012, the solution is very similar to faester's (see above). From the Server Manager, click on Add roles and features, select the appropriate server, then select Features. Under .NET Framework 4.5 Features, you'll see WCF Services, and under that, you'll find HTTP Activation.

Eclipse hangs on loading workbench

I didn't try all these. I restarted by laptop/machine . And everything was back to normal after that.

How to run a script file remotely using SSH

You can do:

ssh user@host 'bash -s' < /path/script.sh

JQuery post JSON object to a server

It is also possible to use FormData(). But you need to set contentType as false:

var data = new FormData();
data.append('name', 'Bob'); 

function sendData() {
    $.ajax({
        url: '/helloworld',
        type: 'POST',
        contentType: false,
        data: data,
        dataType: 'json'
    });
}

Returning a value from thread?

Threads do not really have return values. However, if you create a delegate, you can invoke it asynchronously via the BeginInvoke method. This will execute the method on a thread pool thread. You can get any return value from such as call via EndInvoke.

Example:

static int GetAnswer() {
   return 42;
}

...

Func<int> method = GetAnswer;
var res = method.BeginInvoke(null, null); // provide args as needed
var answer = method.EndInvoke(res);

GetAnswer will execute on a thread pool thread and when completed you can retrieve the answer via EndInvoke as shown.

IF...THEN...ELSE using XML

<IF>
    <CONDITIONS>
        <CONDITION field="time" from="5pm" to="9pm"></CONDITION>
    </CONDITIONS>
    <RESULTS><...some actions defined.../></RESULTS>
    <ELSE>
        <RESULTS><...some other actions defined.../></RESULTS>        
    </ELSE>
</IF>

Here's my take on it. This will allow you to have multiple conditions.

Disable Auto Zoom in Input "Text" tag - Safari on iPhone

After a while of while trying I came up with this solution

// set font-size to 16px to prevent zoom 
input.addEventListener("mousedown", function (e) {
  e.target.style.fontSize = "16px";
});

// change font-size back to its initial value so the design will not break
input.addEventListener("focus", function (e) {
  e.target.style.fontSize = "";
});

On "mousedown" it sets font-size of input to 16px. This will prevent the zooming. On focus event it changes font-size back to initial value.

Unlike solutions posted before, this will let you set the font-size of the input to whatever you want.

SQL Case Sensitive String Compare

Select * from a_table where attribute = 'k' COLLATE Latin1_General_CS_AS 

Did the trick.

How to change the icon of .bat file programmatically?

One of the way you can achieve this is:

  1. Create an executable Jar file
  2. Create a batch file to run the above jar and launch the desktop java application.
  3. Use Batch2Exe converter and covert to batch file to Exe.
  4. During above conversion, you can change the icon to that of your choice.(must of valid .ico file)
  5. Place the short cut for the above exe on desktop.

Now your java program can be opened in a fancy way just like any other MSWindows apps.! :)

How can I compile my Perl script so it can be executed on systems without perl installed?

On MaxOSX there may be perlcc. Type man perlcc. On my system (10.6.8) it's in /usr/bin. YMMV

See http://search.cpan.org/~nwclark/perl-5.8.9/utils/perlcc.PL

VBA Object doesn't support this property or method

Object doesn't support this property or method.

Think of it like if anything after the dot is called on an object. It's like a chain.

An object is a class instance. A class instance supports some properties defined in that class type definition. It exposes whatever intelli-sense in VBE tells you (there are some hidden members but it's not related to this). So after each dot . you get intelli-sense (that white dropdown) trying to help you pick the correct action.

(you can start either way - front to back or back to front, once you understand how this works you'll be able to identify where the problem occurs)

Type this much anywhere in your code area

Dim a As Worksheets
a.

you get help from VBE, it's a little dropdown called Intelli-sense

enter image description here

It lists all available actions that particular object exposes to any user. You can't see the .Selection member of the Worksheets() class. That's what the error tells you exactly.

Object doesn't support this property or method.

If you look at the example on MSDN

Worksheets("GRA").Activate
iAreaCount = Selection.Areas.Count

It activates the sheet first then calls the Selection... it's not connected together because Selection is not a member of Worksheets() class. Simply, you can't prefix the Selection

What about

Sub DisplayColumnCount()
    Dim iAreaCount As Integer
    Dim i As Integer

    Worksheets("GRA").Activate
    iAreaCount = Selection.Areas.Count

    If iAreaCount <= 1 Then
        MsgBox "The selection contains " & Selection.Columns.Count & " columns."
    Else
        For i = 1 To iAreaCount
        MsgBox "Area " & i & " of the selection contains " & _
        Selection.Areas(i).Columns.Count & " columns."
        Next i
    End If
End Sub

from HERE

Find out the history of SQL queries

    select v.SQL_TEXT,
           v.PARSING_SCHEMA_NAME,
           v.FIRST_LOAD_TIME,
           v.DISK_READS,
           v.ROWS_PROCESSED,
           v.ELAPSED_TIME,
           v.service
      from v$sql v
where to_date(v.FIRST_LOAD_TIME,'YYYY-MM-DD hh24:mi:ss')>ADD_MONTHS(trunc(sysdate,'MM'),-2)

where clause is optional. You can sort the results according to FIRST_LOAD_TIME and find the records up to 2 months ago.

How do you convert a DataTable into a generic list?

A more 'magic' way, and doesn't need .NET 3.5.

If, for example, DBDatatable was returning a single column of Guids (uniqueidentifier in SQL) then you could use:

Dim gList As New List(Of Guid)
gList.AddRange(DirectCast(DBDataTable.Select(), IEnumerable(Of Guid)))

dropzone.js - how to do something after ALL files are uploaded

EDIT: There is now a queuecomplete event that you can use for exactly that purpose.


Previous answer:

Paul B.'s answer works, but an easier way to do so, is by checking if there are still files in the queue or uploading whenever a file completes. This way you don't have to keep track of the files yourself:

Dropzone.options.filedrop = {
  init: function () {
    this.on("complete", function (file) {
      if (this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) {
        doSomething();
      }
    });
  }
};

Hibernate show real SQL

select this_.code from true.employee this_ where this_.code=? is what will be sent to your database.

this_ is an alias for that instance of the employee table.

Getting all file names from a folder using C#

I would recommend you google 'Read objects in folder'. You might need to create a reader and a list and let the reader read all the object names in the folder and add them to the list in n loops.

Making a request to a RESTful API using python

Using requests:

import requests
url = 'http://ES_search_demo.com/document/record/_search?pretty=true'
data = '''{
  "query": {
    "bool": {
      "must": [
        {
          "text": {
            "record.document": "SOME_JOURNAL"
          }
        },
        {
          "text": {
            "record.articleTitle": "farmers"
          }
        }
      ],
      "must_not": [],
      "should": []
    }
  },
  "from": 0,
  "size": 50,
  "sort": [],
  "facets": {}
}'''
response = requests.post(url, data=data)

Depending on what kind of response your API returns, you will then probably want to look at response.text or response.json() (or possibly inspect response.status_code first). See the quickstart docs here, especially this section.

How to get the path of a running JAR file?

Other answers seem to point to the code source which is Jar file location which is not a directory.

Use

return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParentFile();

How to format a UTC date as a `YYYY-MM-DD hh:mm:ss` string using NodeJS?

Use the method provided in the Date object as follows:

var ts_hms = new Date();

console.log(
    ts_hms.getFullYear() + '-' + 
    ("0" + (ts_hms.getMonth() + 1)).slice(-2) + '-' + 
    ("0" + (ts_hms.getDate())).slice(-2) + ' ' +
    ("0" + ts_hms.getHours()).slice(-2) + ':' +
    ("0" + ts_hms.getMinutes()).slice(-2) + ':' +
    ("0" + ts_hms.getSeconds()).slice(-2));

It looks really dirty, but it should work fine with JavaScript core methods

Application Error - The connection to the server was unsuccessful. (file:///android_asset/www/index.html)

Remove the external scripts in your index.html

Change this:

<script src="http://code.highcharts.com/highcharts-more.js"></script>

to

<script src="project_folder/highcharts-more.js"></script>

Google Play Services GCM 9.2.0 asks to "update" back to 9.0.0

Your target SDK might be higher than SDK of the device, change that. For example, your device is running API 23 but your target SDK is 25. Change 25 to 23.

What is the best comment in source code you have ever encountered?

//open lid


//take sh!t


//close lid

Comments for a File open, data dump, file close...

Get single listView SelectedItem

Sometimes using only the line below throws me an Exception,

String text = listView1.SelectedItems[0].Text; 

so I use this code below:

private void listView1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    if (listView1.SelectedIndices.Count <= 0) 
    { 
        return; 
    } 
    int intselectedindex = listView1.SelectedIndices[0]; 
    if (intselectedindex >= 0) 
    {
        String text = listView1.Items[intselectedindex].Text;

        //do something
        //MessageBox.Show(listView1.Items[intselectedindex].Text); 
    } 
}

How to save as a new file and keep working on the original one in Vim?

The following command will create a copy in a new window. So you can continue see both original file and the new file.

:w {newfilename} | sp #

Is there a method for String conversion to Title Case?

Sorry I am a beginner so my coding habit sucks!

public class TitleCase {

    String title(String sent)
    {   
        sent =sent.trim();
        sent = sent.toLowerCase();
        String[] str1=new String[sent.length()];
        for(int k=0;k<=str1.length-1;k++){
            str1[k]=sent.charAt(k)+"";
    }

        for(int i=0;i<=sent.length()-1;i++){
            if(i==0){
                String s= sent.charAt(i)+"";
                str1[i]=s.toUpperCase();
                }
            if(str1[i].equals(" ")){
                String s= sent.charAt(i+1)+"";
                str1[i+1]=s.toUpperCase();
                }

            System.out.print(str1[i]);
            }

        return "";
        }

    public static void main(String[] args) {
        TitleCase a = new TitleCase();
        System.out.println(a.title("   enter your Statement!"));
    }
}

Objective-C implicit conversion loses integer precision 'NSUInteger' (aka 'unsigned long') to 'int' warning

Change key in Project > Build Setting "typecheck calls to printf/scanf : NO"

Explanation : [How it works]

Check calls to printf and scanf, etc., to make sure that the arguments supplied have types appropriate to the format string specified, and that the conversions specified in the format string make sense.

Hope it work

Other warning

objective c implicit conversion loses integer precision 'NSUInteger' (aka 'unsigned long') to 'int

Change key "implicit conversion to 32Bits Type > Debug > *64 architecture : No"

[caution: It may void other warning of 64 Bits architecture conversion].

What is the standard Python docstring format?

I suggest using Vladimir Keleshev's pep257 Python program to check your docstrings against PEP-257 and the Numpy Docstring Standard for describing parameters, returns, etc.

pep257 will report divergence you make from the standard and is called like pylint and pep8.

How to encrypt String in Java

Like many of the guys have already told, you should use a standard cypher that is overly used like DES or AES.

A simple example of how you can encrypt and decrypt a string in java using AES.

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class EncryptorDemo {

    public static String encrypt(String key, String randomVector, String value) {
        try {
            IvParameterSpec iv = new IvParameterSpec(randomVector.getBytes("UTF-8"));
            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            byte[] encrypted = cipher.doFinal(value.getBytes());
            System.out.println("encrypted text: "  + Base64.encodeBase64String(encrypted));
            return Base64.encodeBase64String(encrypted);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String decrypt(String key, String randomVector, String encrypted) {
        try {
            IvParameterSpec iv = new IvParameterSpec(randomVector.getBytes("UTF-8"));
            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] originalText = cipher.doFinal(Base64.decodeBase64(encrypted));
            System.out.println("decrypted text: "  + new String(originalText));
            return new String(originalText);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        String key = "JavasEncryptDemo"; // 128 bit key
        String randomVector = "RandomJavaVector"; // 16 bytes IV
        decrypt(key, randomVector, encrypt(key, randomVector, "Anything you want to encrypt!"));

    }
}

Colorized grep -- viewing the entire file with highlighted matches

I use rcg from "Linux Server Hacks", O'Reilly. It's perfect for what you want and can highlight multiple expressions each with different colours.

#!/usr/bin/perl -w
#
#       regexp coloured glasses - from Linux Server Hacks from O'Reilly
#
#       eg .rcg "fatal" "BOLD . YELLOW . ON_WHITE"  /var/adm/messages
#
use strict;
use Term::ANSIColor qw(:constants);

my %target = ( );

while (my $arg = shift) {
        my $clr = shift;

        if (($arg =~ /^-/) | !$clr) {
                print "Usage: rcg [regex] [color] [regex] [color] ...\n";
                exit(2);
        }

        #
        # Ugly, lazy, pathetic hack here. [Unquote]
        #
        $target{$arg} = eval($clr);

}

my $rst = RESET;

while(<>) {
        foreach my $x (keys(%target)) {
                s/($x)/$target{$x}$1$rst/g;
        }
        print
}

foreach for JSON array , syntax

You can use the .forEach() method of JavaScript for looping through JSON.

_x000D_
_x000D_
var datesBooking = [_x000D_
    {"date": "04\/24\/2018"},_x000D_
      {"date": "04\/25\/2018"}_x000D_
    ];_x000D_
    _x000D_
    datesBooking.forEach(function(data, index) {_x000D_
      console.log(data);_x000D_
    });
_x000D_
_x000D_
_x000D_

mysql query: SELECT DISTINCT column1, GROUP BY column2

Try the following:

SELECT DISTINCT(ip), name, COUNT(name) nameCnt, 
time, price, SUM(price) priceSum
FROM tablename 
WHERE time >= $yesterday AND time <$today 
GROUP BY ip, name

Printing Mongo query output to a file while in the mongo shell

It may be useful to you to simply increase the number of results that get displayed

In the mongo shell > DBQuery.shellBatchSize = 3000

and then you can select all the results out of the terminal in one go and paste into a text file.

It is what I am going to do :)

(from : https://stackoverflow.com/a/3705615/1290746)

Convert the first element of an array to a string in PHP

Convert array to a string in PHP:

Use the PHP join function like this:

$my_array = array(4,1,8);

print_r($my_array);
Array
(
    [0] => 4
    [1] => 1
    [2] => 8
)

$result_string = join(',' , $my_array);
echo $result_string;

Which delimits the items in the array by comma into a string:

4,1,8

How to set a session variable when clicking a <a> link

    session_start();
    if(isset($_SESSION['current'])){
         $_SESSION['oldlink']=$_SESSION['current'];
    }else{
         $_SESSION['oldlink']='no previous page';
    }
    $_SESSION['current']=$_SERVER['PHP_SELF'];

Maybe this is what you're looking for? It will remember the old link/page you're coming from (within your website).

Put that piece on top of each page.

If you want to make it 'refresh proof' you can add another check:

   if(isset($_SESSION['current']) && $_SESSION['current']!=$_SERVER['PHP_SELF'])

This will make the page not remember itself.

UPDATE: Almost the same as @Brandon though... Just use a php variable, I know this looks like a security risk, but when done correct it isn't.

 <a href="home.php?a=register">Register Now!</a>

PHP:

 if(isset($_GET['a']) /*you can validate the link here*/){
    $_SESSION['link']=$_GET['a'];
 }

Why even store the GET in a session? Just use it. Please tell me why you do not want to use GET. « Validate for more security. I maybe can help you with a better script.

Do AJAX requests retain PHP Session info?

Well, not always. Using cookies, you are good. But the "can I safely rely on the id being present" urged me to extend the discussion with an important point (mostly for reference, as the visitor count of this page seems quite high).

PHP can be configured to maintain sessions by URL-rewriting, instead of cookies. (How it's good or bad (<-- see e.g. the topmost comment there) is a separate question, let's now stick to the current one, with just one side-note: the most prominent issue with URL-based sessions -- the blatant visibility of the naked session ID -- is not an issue with internal Ajax calls; but then, if it's turned on for Ajax, it's turned on for the rest of the site, too, so there...)

In case of URL-rewriting (cookieless) sessions, Ajax calls must take care of it themselves that their request URLs are properly crafted. (Or you can roll your own custom solution. You can even resort to maintaining sessions on the client side, in less demanding cases.) The point is the explicit care needed for session continuity, if not using cookies:

  1. If the Ajax calls just extract URLs verbatim from the HTML (as received from PHP), that should be OK, as they are already cooked (umm, cookified).

  2. If they need to assemble request URIs themselves, the session ID needs to be added to the URL manually. (Check here, or the page sources generated by PHP (with URL-rewriting on) to see how to do it.)


From OWASP.org:

Effectively, the web application can use both mechanisms, cookies or URL parameters, or even switch from one to the other (automatic URL rewriting) if certain conditions are met (for example, the existence of web clients without cookies support or when cookies are not accepted due to user privacy concerns).

From a Ruby-forum post:

When using php with cookies, the session ID will automatically be sent in the request headers even for Ajax XMLHttpRequests. If you use or allow URL-based php sessions, you'll have to add the session id to every Ajax request url.

Plot width settings in ipython notebook

If you're not in an ipython notebook (like the OP), you can also just declare the size when you declare the figure:

width = 12
height = 12
plt.figure(figsize=(width, height))

How to convert array to a string using methods other than JSON?

readable output!

echo json_encode($array);     //outputs--->    "name1":"value1",  "name2":"value2",  ...

OR

echo print_r($array, true);

Setting max width for body using Bootstrap

I don't know if this was pointed out here. The settings for .container width have to be set on the Bootstrap website. I personally did not have to edit or touch anything within CSS files to tune my .container size which is 1600px. Under Customize tab, there are three sections responsible for media and the responsiveness of the web:

  • Media queries breakpoints
  • Grid system
  • Container sizes

Besides Media queries breakpoints, which I believe most people refer to, I've also changed @container-desktop to (1130px + @grid-gutter-width) and @container-large-desktop to (1530px + @grid-gutter-width). Now, the .container changes its width if my browser is scaled up to ~1600px and ~1200px. Hope it can help.

fatal: The current branch master has no upstream branch

Please try this scenario

git push -f --set-upstream origin master

Can I invoke an instance method on a Ruby module without including it?

Not sure if someone still needs it after 10 years but I solved it using eigenclass.

module UsefulThings
  def useful_thing_1
    "thing_1"
  end

  class << self
    include UsefulThings
  end
end

class A
  include UsefulThings
end

class B
  extend UsefulThings
end

UsefulThings.useful_thing_1 # => "thing_1"
A.new.useful_thing_1 # => "thing_1"
B.useful_thing_1 # => "thing_1"

Regex for Comma delimited list

This one will reject extraneous commas at the start or end of the line, if that's important to you.

((, )?(^)?(possible|value|patterns))*

Replace possible|value|patterns with a regex that matches your allowed values.

MVVM Passing EventArgs As Command Parameter

As an adaption of @Mike Fuchs answer, here's an even smaller solution. I'm using the Fody.AutoDependencyPropertyMarker to reduce some of the boiler plate.

The Class

public class EventCommand : TriggerAction<DependencyObject>
{
    [AutoDependencyProperty]
    public ICommand Command { get; set; }

    protected override void Invoke(object parameter)
    {
        if (Command != null)
        {
            if (Command.CanExecute(parameter))
            {
                Command.Execute(parameter);
            }
        }
    }
}

The EventArgs

public class VisibleBoundsArgs : EventArgs
{
    public Rect VisibleVounds { get; }

    public VisibleBoundsArgs(Rect visibleBounds)
    {
        VisibleVounds = visibleBounds;
    }
}

The XAML

<local:ZoomableImage>
   <i:Interaction.Triggers>
      <i:EventTrigger EventName="VisibleBoundsChanged" >
         <local:EventCommand Command="{Binding VisibleBoundsChanged}" />
      </i:EventTrigger>
   </i:Interaction.Triggers>
</local:ZoomableImage>

The ViewModel

public ICommand VisibleBoundsChanged => _visibleBoundsChanged ??
                                        (_visibleBoundsChanged = new RelayCommand(obj => SetVisibleBounds(((VisibleBoundsArgs)obj).VisibleVounds)));

How to read input from console in a batch file?

The code snippet in the linked proposed duplicate reads user input.

ECHO A current build of Test Harness exists.
set /p delBuild=Delete preexisting build [y/n]?: 

The user can type as many letters as they want, and it will go into the delBuild variable.

how to convert numeric to nvarchar in sql command

If the culture of the result doesn't matters or we're only talking of integer values, CONVERT or CAST will be fine.

However, if the result must match a specific culture, FORMAT might be the function to go:

DECLARE @value DECIMAL(19,4) = 1505.5698
SELECT CONVERT(NVARCHAR, @value)        -->  1505.5698
SELECT FORMAT(@value, 'N2', 'en-us')    --> 1,505.57
SELECT FORMAT(@value, 'N2', 'de-de')    --> 1.505,57

For more information on FORMAT see here.

Of course, formatting the result should be a matter of the UI layer of the software.

System.Data.OracleClient requires Oracle client software version 8.1.7

Oracle Client version 11 cannot connect to 8i databases. You will need a client in version 10 at most.

How to increment an iterator by 2?

We can use both std::advance as well as std::next, but there's a difference between the two.

advance modifies its argument and returns nothing. So it can be used as:

vector<int> v;
v.push_back(1);
v.push_back(2);
auto itr = v.begin();
advance(itr, 1);          //modifies the itr
cout << *itr<<endl        //prints 2

next returns a modified copy of the iterator:

vector<int> v;
v.push_back(1);
v.push_back(2);
cout << *next(v.begin(), 1) << endl;    //prints 2

how to check if the input is a number or not in C?

You can use a function like strtol() which will convert a character array to a long.

It has a parameter which is a way to detect the first character that didn't convert properly. If this is anything other than the end of the string, then you have a problem.

See the following program for an example:

#include <stdio.h>
#include <stdlib.h>

int main( int argc, char *argv[]) {
    int i;
    long val;
    char *next;

    // Process each argument given.

    for (i = 1; i < argc; i++) {
        // Get value with failure detection.

        val = strtol (argv[i], &next, 10);

        // Check for empty string and characters left after conversion.

        if ((next == argv[i]) || (*next != '\0')) {
            printf ("'%s' is not valid\n", argv[i]);
        } else {
            printf ("'%s' gives %ld\n", argv[i], val);
        }
    }

    return 0;
}

Running this, you can see it in operation:

pax> testprog hello "" 42 12.2 77x

'hello' is not valid
'' is not valid
'42' gives 42
'12.2' is not valid
'77x' is not valid

Check OS version in Swift?

Swift 5

We dont need to create extension since ProcessInfo gives us the version info. You can see sample code for iOS as below.

let os = ProcessInfo().operatingSystemVersion

switch (os.majorVersion, os.minorVersion, os.patchVersion) {
case (let x, _, _) where x < 8:
    print("iOS < 8.0.0")

case (8, 0, _):
    print("iOS >= 8.0.0, < 8.1.0")

case (8, _, _):
    print("iOS >= 8.1.0, < 9.0")

case (9, _, _):
    print("iOS >= 9.0.0")

default:
    print("iOS >= 10.0.0")
}

Reference: http://nshipster.com/swift-system-version-checking/