Programs & Examples On #Postgis

Use this tag for PostGIS is a spatial database extension for PostgreSQL. Before using this tag, please consider whether your question might be a better fit for the Geographic Information Systems Stack Exchange site (e.g. if it's more about configuration or geodetic principles than about actual programming).

Which data type for latitude and longitude?

Use Point data type to store Longitude and Latitude in a single column:

CREATE TABLE table_name (
    id integer NOT NULL,
    name text NOT NULL,
    location point NOT NULL,
    created_on timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT table_name_pkey PRIMARY KEY (id)
)

Create an Indexing on a 'location' column :

CREATE INDEX ON table_name USING GIST(location);

GiST index is capable of optimizing “nearest-neighbor” search :

SELECT * FROM table_name ORDER BY location <-> point '(-74.013, 40.711)' LIMIT 10;

Note: The point first element is longitude and the second element is latitude.

For more info check this Query Operators.

Get PostGIS version

PostGIS_Lib_Version(); - returns the version number of the PostGIS library.

http://postgis.refractions.net/docs/PostGIS_Lib_Version.html

good postgresql client for windows?

Actually there is a freeware version of EMS's SQL Manager which is quite powerful

Create PostgreSQL ROLE (user) if it doesn't exist

My team was hitting a situation with multiple databases on one server, depending on which database you connected to, the ROLE in question was not returned by SELECT * FROM pg_catalog.pg_user, as proposed by @erwin-brandstetter and @a_horse_with_no_name. The conditional block executed, and we hit role "my_user" already exists.

Unfortunately we aren't sure of exact conditions, but this solution works around the problem:

        DO  
        $body$
        BEGIN
            CREATE ROLE my_user LOGIN PASSWORD 'my_password';
        EXCEPTION WHEN others THEN
            RAISE NOTICE 'my_user role exists, not re-creating';
        END
        $body$

It could probably be made more specific to rule out other exceptions.

XmlSerializer: remove unnecessary xsi and xsd namespaces

//Create our own namespaces for the output
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

//Add an empty namespace and empty value
ns.Add("", "");

//Create the serializer
XmlSerializer slz = new XmlSerializer(someType);

//Serialize the object with our own namespaces (notice the overload)
slz.Serialize(myXmlTextWriter, someObject, ns)

Insert Multiple Rows Into Temp Table With SQL Server 2012

Yes, SQL Server 2012 supports multiple inserts - that feature was introduced in SQL Server 2008.

That makes me wonder if you have Management Studio 2012, but you're really connected to a SQL Server 2005 instance ...

What version of the SQL Server engine do you get from SELECT @@VERSION ??

Converting string to number in javascript/jQuery

It sounds like this is referring to something else than you think. In what context are you using it?

The this keyword is usually only used within a callback function of an event-handler, when you loop over a set of elements, or similar. In that context it refers to a particular DOM-element, and can be used the way you do.

If you only want to access that particular button (outside any callback or loop) and don't have any other elements that use the btn-info class, you could do something like:

parseInt($(".btn-info").data('votevalue'), 10);

You could also assign the element an ID, and use that to select on, which is probably a safer way, if you want to be sure that only one element match your selector.

Tesseract OCR simple example

I was able to get it to work by following these instructions.

  • Download the sample code Tesseract sample code

  • Unzip it to a new location

  • Open ~\tesseract-samples-master\src\Tesseract.Samples.sln (I used Visual Studio 2017)

  • Install the Tesseract NuGet package for that project (or uninstall/reinstall as I had to) NuGet Tesseract

  • Uncomment the last two meaningful lines in Tesseract.Samples.Program.cs: Console.Write("Press any key to continue . . . "); Console.ReadKey(true);

  • Run (hit F5)

  • You should get this windows console output enter image description here

Java 8 lambda Void argument

Use Supplier if it takes nothing, but returns something.

Use Consumer if it takes something, but returns nothing.

Use Callable if it returns a result and might throw (most akin to Thunk in general CS terms).

Use Runnable if it does neither and cannot throw.

How to have Java method return generic list of any type?

You can use the old way:

public List magicalListGetter() {
    List list = doMagicalVooDooHere();

    return list;
}

or you can use Object and the parent class of everything:

public List<Object> magicalListGetter() {
    List<Object> list = doMagicalVooDooHere();

    return list;
}

Note Perhaps there is a better parent class for all the objects you will put in the list. For example, Number would allow you to put Double and Integer in there.

Why does range(start, end) not include end?

Basically in python range(n) iterates n times, which is of exclusive nature that is why it does not give last value when it is being printed, we can create a function which gives inclusive value it means it will also print last value mentioned in range.

def main():
    for i in inclusive_range(25):
        print(i, sep=" ")


def inclusive_range(*args):
    numargs = len(args)
    if numargs == 0:
        raise TypeError("you need to write at least a value")
    elif numargs == 1:
        stop = args[0]
        start = 0
        step = 1
    elif numargs == 2:
        (start, stop) = args
        step = 1
    elif numargs == 3:
        (start, stop, step) = args
    else:
        raise TypeError("Inclusive range was expected at most 3 arguments,got {}".format(numargs))
    i = start
    while i <= stop:
        yield i
        i += step


if __name__ == "__main__":
    main()

How to manage local vs production settings in Django?

I use a variation of what jpartogi mentioned above, that I find a little shorter:

import platform
from django.core.management import execute_manager 

computername = platform.node()

try:
  settings = __import__(computername + '_settings')
except ImportError: 
  import sys
  sys.stderr.write("Error: Can't find the file '%r_settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file local_settings.py does indeed exist, it's causing an ImportError somehow.)\n" % (computername, __file__))
  sys.exit(1)

if __name__ == "__main__":
  execute_manager(settings)

Basically on each computer (development or production) I have the appropriate hostname_settings.py file that gets dynamically loaded.

C# - Substring: index and length must refer to a location within the string

You need to find the position of the first /, and then calculate the portion you want:

string url = "www.example.com/aaa/bbb.jpg";
int Idx = url.IndexOf("/");
string yourValue = url.Substring(Idx + 1, url.Length - Idx - 4);

Moment.js get day name from date

With moment you can parse the date string you have:

var dt = moment(myDate.date, "YYYY-MM-DD HH:mm:ss")

That's for UTC, you'll have to convert the time zone from that point if you so desire.

Then you can get the day of the week:

dt.format('dddd');

How do I fix a NoSuchMethodError?

If you have access to change the JVM parameters, adding verbose output should allow you to see what classes are being loaded from which JAR files.

java -verbose:class <other args>

When your program is run, the JVM should dump to standard out information such as:

...

[Loaded junit.framework.Assert from file:/C:/Program%20Files/junit3.8.2/junit.jar]

...

Creating files in C++

One way to do this is to create an instance of the ofstream class, and use it to write to your file. Here's a link to a website that has some example code, and some more information about the standard tools available with most implementations of C++:

ofstream reference

For completeness, here's some example code:

// using ofstream constructors.
#include <iostream>
#include <fstream>  

std::ofstream outfile ("test.txt");

outfile << "my text here!" << std::endl;

outfile.close();

You want to use std::endl to end your lines. An alternative is using '\n' character. These two things are different, std::endl flushes the buffer and writes your output immediately while '\n' allows the outfile to put all of your output into a buffer and maybe write it later.

How to make a char string from a C macro's value?

#define TEST_FUN_NAME #FUNC_NAME

see here

What does API level mean?

This actually sums it up pretty nicely.

API Levels generally mean that as a programmer, you can communicate with the devices' built in functions and functionality. As the API level increases, functionality adds up (although some of it can get deprecated).

Choosing an API level for an application development should take at least two thing into account:

  1. Current distribution - How many devices can actually support my application, if it was developed for API level 9, it cannot run on API level 8 and below, then "only" around 60% of devices can run it (true to the date this post was made).
  2. Choosing a lower API level may support more devices but gain less functionality for your app. you may also work harder to achieve features you could've easily gained if you chose higher API level.

Android API levels can be divided to five main groups (not scientific, but what the heck):

  1. Android 1.5 - 2.3 (Cupcake to Gingerbread) - (API levels 3-10) - Android made specifically for smartphones.
  2. Android 3.0 - 3.2 (Honeycomb) (API levels 11-13) - Android made for tablets.
  3. Android 4.0 - 4.4 (KitKat) - (API levels 14-19) - A big merge with tons of additional functionality, totally revamped Android version, for both phone and tablets.
  4. Android 5.0 - 5.1 (Lollipop) - (API levels 21-22) - Material Design introduced.
  5. Android 6.0 - 6.… (Marshmallow) - (API levels 23-…) - Runtime Permissions,Apache HTTP Client Removed

Error ITMS-90717: "Invalid App Store Icon"

Invalid App Store Icon. The App Store Icon in the asset catalog in 'YourApp.app' can't be transparent nor contain an alpha channel.

Solved in Catalina

  1. copy to desktop
  2. open image in PREVIEW APP.
  3. File -> Duplicate Close the first opened preview
  4. after try to close the second duplicated image, then it will prompt to save there you will available to untick AlPHA

look into my screenshot

nvalid App Store Icon Solved in Catalina

converting date time to 24 hour format

Try this:

String dateStr = "Jul 27, 2011 8:35:29 AM";
DateFormat readFormat = new SimpleDateFormat( "MMM dd, yyyy hh:mm:ss aa");
DateFormat writeFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
    date = readFormat.parse(dateStr);
} catch (ParseException e) {
    e.printStackTrace();
}

if (date != null) {
    String formattedDate = writeFormat.format(date);
}

How to run python script in webpage

As others have pointed out, there are many web frameworks for Python.

But, seeing as you are just getting started with Python, a simple CGI script might be more appropriate:

  1. Rename your script to index.cgi. You also need to execute chmod +x index.cgi to give it execution privileges.

  2. Add these 2 lines in the beginning of the file:

#!/usr/bin/python   
print('Content-type: text/html\r\n\r')

After this the Python code should run just like in terminal, except the output goes to the browser. When you get that working, you can use the cgi module to get data back from the browser.

Note: this assumes that your webserver is running Linux. For Windows, #!/Python26/python might work instead.

Reduce size of legend area in barplot

The cex parameter will do that for you.

a <- c(3, 2, 2, 2, 1, 2 )
barplot(a, beside = T,
        col = 1:6, space = c(0, 2))
legend("topright", 
       legend = c("a", "b", "c", "d", "e", "f"), 
       fill = 1:6, ncol = 2,
       cex = 0.75)

The plot

What does the "at" (@) symbol do in Python?

What does the “at” (@) symbol do in Python?

@ symbol is a syntactic sugar python provides to utilize decorator,
to paraphrase the question, It's exactly about what does decorator do in Python?

Put it simple decorator allow you to modify a given function's definition without touch its innermost (it's closure).
It's the most case when you import wonderful package from third party. You can visualize it, you can use it, but you cannot touch its innermost and its heart.

Here is a quick example,
suppose I define a read_a_book function on Ipython

In [9]: def read_a_book():
   ...:     return "I am reading the book: "
   ...: 
In [10]: read_a_book()
Out[10]: 'I am reading the book: '

You see, I forgot to add a name to it.
How to solve such a problem? Of course, I could re-define the function as:

def read_a_book():
    return "I am reading the book: 'Python Cookbook'"

Nevertheless, what if I'm not allowed to manipulate the original function, or if there are thousands of such function to be handled.

Solve the problem by thinking different and define a new_function

def add_a_book(func):
    def wrapper():
        return func() + "Python Cookbook"
    return wrapper

Then employ it.

In [14]: read_a_book = add_a_book(read_a_book)
In [15]: read_a_book()
Out[15]: 'I am reading the book: Python Cookbook'

Tada, you see, I amended read_a_book without touching it inner closure. Nothing stops me equipped with decorator.

What's about @

@add_a_book
def read_a_book():
    return "I am reading the book: "
In [17]: read_a_book()
Out[17]: 'I am reading the book: Python Cookbook'

@add_a_book is a fancy and handy way to say read_a_book = add_a_book(read_a_book), it's a syntactic sugar, there's nothing more fancier about it.

How to remove gem from Ruby on Rails application?

You are using some sort of revision control, right? Then it should be quite simple to restore to the commit before you added the gem, or revert the one where you added it if you have several revisions after that you wish to keep.

What is console.log?

A point of confusion sometimes is that to log a text message along with the contents of one of your objects using console.log, you have to pass each one of the two as a different argument. This means that you have to separate them by commas because if you were to use the + operator to concatenate the outputs, this would implicitly call the .toString() method of your object. This in most cases is not explicitly overriden and the default implementation inherited by Object doesn't provide any useful information.

Example to try in console:

>>> var myObj = {foo: 'bar'}
undefined
>>> console.log('myObj is: ', myObj);
myObj is: Object { foo= "bar"}

whereas if you tried to concatenate the informative text message along with the object's contents you'd get:

>>> console.log('myObj is: ' + myObj);
myObj is: [object Object]

So keep in mind that console.log in fact takes as many arguments as you like.

Pull is not possible because you have unmerged files, git stash doesn't work. Don't want to commit

You can use git checkout <file> to check out the committed version of the file (thus discarding your changes), or git reset --hard HEAD to throw away any uncommitted changes for all files.

How to remove an HTML element using Javascript?

Your JavaScript is correct. Your button has type="submit" which is causing the page to refresh.

Showing empty view when ListView is empty

A programmatically solution will be:

TextView textView = new TextView(context);
textView.setId(android.R.id.empty);
textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
textView.setText("No result found");
listView.setEmptyView(textView);

Import XXX cannot be resolved for Java SE standard classes

If by chance you have deleted JRE SYSTEM LIBRARY, then go to your JRE installation and add jars from there.

Eg:- C:\Program Files (x86)\Java\jre7\lib ---add jars from here

C:\Program Files (x86)\Java\jre7\lib\ext ---add jars from here

App crashing when trying to use RecyclerView on android 5.0

I faced the same issue cause I had the RecyclerView in another layout and not on activity_main.xml.

By searching on some sites I got something and felt like sharing here

  1. Add Id to Include tag in Activity_main.xml

    <include id="includedRecyclerLayout" .... </include>

  2. call this layout before Searching view by ID in MainActivity.java

    `ConstraintLayout includedLayout = findViewById(R.id.inckudedRecyclerLayout);

    RecyclerViewrecyclerview=includedLayout.findViewById(R.id.RECYCLER_VIEW_ID)`;

What is a provisioning profile used for when developing iPhone applications?

Apple cares about security and as you know it is not possible to install any application on a real iOS device. Apple has several legal ways to do it:

  • When you need to test/debug an app on a real device the Development Provisioning Profile allows you to do it
  • When you publish an app you send a Distribution Provisioning Profile[About] and Apple after review reassign it by they own key

Development Provisioning Profile is stored on device and contains:

  • Application ID - application which are going to run
  • List of Development certificates - who can debug the app
  • List of devices - which devices can run this app

Xcode by default take cares about

Unable to auto-detect email address

Ran the sample of these commands:

git config --global user.email "[email protected]"

git config --global user.name "focus1"

Footnote:

[email protected] === email address used to login to your github account.

focus === your github username

How do I measure a time interval in C?

High resolution timers that provide a resolution of 1 microsecond are system-specific, so you will have to use different methods to achieve this on different OS platforms. You may be interested in checking out the following article, which implements a cross-platform C++ timer class based on the functions described below:

  • [Song Ho Ahn - High Resolution Timer][1]

Windows

The Windows API provides extremely high resolution timer functions: QueryPerformanceCounter(), which returns the current elapsed ticks, and QueryPerformanceFrequency(), which returns the number of ticks per second.

Example:

#include <stdio.h>
#include <windows.h>                // for Windows APIs

int main(void)
{
    LARGE_INTEGER frequency;        // ticks per second
    LARGE_INTEGER t1, t2;           // ticks
    double elapsedTime;

    // get ticks per second
    QueryPerformanceFrequency(&frequency);

    // start timer
    QueryPerformanceCounter(&t1);

    // do something
    // ...

    // stop timer
    QueryPerformanceCounter(&t2);

    // compute and print the elapsed time in millisec
    elapsedTime = (t2.QuadPart - t1.QuadPart) * 1000.0 / frequency.QuadPart;
    printf("%f ms.\n", elapsedTime);
}

Linux, Unix, and Mac

For Unix or Linux based system, you can use gettimeofday(). This function is declared in "sys/time.h".

Example:

#include <stdio.h>
#include <sys/time.h>                // for gettimeofday()

int main(void)
{
    struct timeval t1, t2;
    double elapsedTime;

    // start timer
    gettimeofday(&t1, NULL);

    // do something
    // ...

    // stop timer
    gettimeofday(&t2, NULL);

    // compute and print the elapsed time in millisec
    elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0;      // sec to ms
    elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0;   // us to ms
    printf("%f ms.\n", elapsedTime);
}

Class Not Found Exception when running JUnit test

Earlier, in this case, I always did mvn eclipse:eclipse and restarted my Eclipse and it worked. After migrating to GIT, it stopped working for me which is somewhat weird.

Basic problem here is Mr Eclipse does not find the compiled class. Then, I set the output folder as Project/target/test-classes which is by default generated by mvn clean install without skipping the test and proceeded with following workaround:

Option 1: Set classpath for each test case

Eclipse ->Run ->Run Configurations ->under JUnit->select mytest -> under classpath tab->Select User Entries->Advanced->Add Folder -> Select ->Apply->Run

Option 2: Create classpath variable and include it in classpath for all the test cases

Eclipse ->Windows ->Classpath Variables ->New->[Name : Junit_test_cases_cp | path : ]->ok Then go to Eclipse->Run ->Run Configurations ->JUnit->select mytest ->under classpath tab ->Select User Entries->Advanced->Add classpath variables->Select Junit_test_cases_cp->ok->Apply->Run

This is the only thing currently working for me after trying all the suggestions online.

How to run composer from anywhere?

composer.phar can be ran on its own, no need to prefix it with php. This should solve your problem (being in the difference of bash's $PATH and php's include_path).

Find an object in array?

Use Dollar which is Lo-Dash or Underscore.js for Swift:

import Dollar

let found = $.find(array) { $0.name == "Foo" }

When should I use a struct rather than a class in C#?

Whenever you:

  1. don't need polymorphism,
  2. want value semantics, and
  3. want to avoid heap allocation and the associated garbage collection overhead.

The caveat, however, is that structs (arbitrarily large) are more expensive to pass around than class references (usually one machine word), so classes could end up being faster in practice.

Listing all the folders subfolders and files in a directory using php

This code lists all directories and files in sorted order in a tree view. It's a site map generator with hyper-links to all the site resources. The full web page source is here. You'll need to change the path on the ninth line from the end.

<?php
$pathLen = 0;

function prePad($level)
{
  $ss = "";

  for ($ii = 0;  $ii < $level;  $ii++)
  {
    $ss = $ss . "|&nbsp;&nbsp;";
  }

  return $ss;
}

function myScanDir($dir, $level, $rootLen)
{
  global $pathLen;

  if ($handle = opendir($dir)) {

    $allFiles = array();

    while (false !== ($entry = readdir($handle))) {
      if ($entry != "." && $entry != "..") {
        if (is_dir($dir . "/" . $entry))
        {
          $allFiles[] = "D: " . $dir . "/" . $entry;
        }
        else
        {
          $allFiles[] = "F: " . $dir . "/" . $entry;
        }
      }
    }
    closedir($handle);

    natsort($allFiles);

    foreach($allFiles as $value)
    {
      $displayName = substr($value, $rootLen + 4);
      $fileName    = substr($value, 3);
      $linkName    = str_replace(" ", "%20", substr($value, $pathLen + 3));
      if (is_dir($fileName)) {
        echo prePad($level) . $linkName . "<br>\n";
        myScanDir($fileName, $level + 1, strlen($fileName));
      } else {
        echo prePad($level) . "<a href=\"" . $linkName . "\" style=\"text-decoration:none;\">" . $displayName . "</a><br>\n";
      }
    }
  }
}

?><!DOCTYPE HTML>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Site Map</title>
</head>

<body>
<h1>Site Map</h1>
<p style="font-family:'Courier New', Courier, monospace; font-size:small;">
<?php
  $root = '/home/someuser/www/website.com/public';

  $pathLen = strlen($root);

  myScanDir($root, 0, strlen($root)); ?>
</p>
</body>

</html>

Weird PHP error: 'Can't use function return value in write context'

Another scenario where this error is trigered due syntax error:

ucwords($variable) = $string;

How to force cp to overwrite without confirmation

you can use this command as well:

cp -ru /zzz/zzz/* /xxx/xxx

it would update your existing file with the newer one though.

Lotus Notes email as an attachment to another email

Tested vith Notes versions 6.5.x and 7.0.x From your Lotus Notes inbox

  1. Open the message
  2. Click View > Show > Page Source
  3. Copy all the data into a text file and save the file with .eml extension.
  4. Create a new message
  5. Attach the .eml file(s) and send the new message

Hop this helps. I have no client on my current machine but will test from home on 8.5.1

Best way to define private methods for a class in Objective-C

You could try defining a static function below or above your implementation that takes a pointer to your instance. It will be able to access any of your instances variables.

//.h file
@interface MyClass : Object
{
    int test;
}
- (void) someMethod: anArg;

@end


//.m file    
@implementation MyClass

static void somePrivateMethod (MyClass *myClass, id anArg)
{
    fprintf (stderr, "MyClass (%d) was passed %p", myClass->test, anArg);
}


- (void) someMethod: (id) anArg
{
    somePrivateMethod (self, anArg);
}

@end

Get width/height of SVG element

Use getBBox function

http://jsfiddle.net/Xkv3X/1/

var bBox = svg1.getBBox();
console.log('XxY', bBox.x + 'x' + bBox.y);
console.log('size', bBox.width + 'x' + bBox.height);

How to place a JButton at a desired location in a JFrame using Java

Define somewhere the consts :

private static final int BUTTON_LOCATION_X = 300;  // location x 
private static final int BUTTON_LOCATION_Y = 50;   // location y 
private static final int BUTTON_SIZE_X = 140;      // size height
private static final int BUTTON_SIZE_Y = 50;       // size width

and then below :

                JButton startButton = new JButton("Click Me To Start!");
                // startButton.setBounds(300, 50,140, 50 );
                startButton.setBounds(BUTTON_LOCATION_X
                                    , BUTTON_LOCATION_Y,
                                      BUTTON_SIZE_X, 
                                      BUTTON_SIZE_Y );
                contentPane.add(startButton);

where contentPane is the Container object that holds the entire frame :

 JFrame frame = new JFrame("Some name goes here");
 Container contentPane = frame.getContentPane();

I hope this helps , works great for me ...

How to create correct JSONArray in Java using JSONObject

Here is some code using java 6 to get you started:

JSONObject jo = new JSONObject();
jo.put("firstName", "John");
jo.put("lastName", "Doe");

JSONArray ja = new JSONArray();
ja.put(jo);

JSONObject mainObj = new JSONObject();
mainObj.put("employees", ja);

Edit: Since there has been a lot of confusion about put vs add here I will attempt to explain the difference. In java 6 org.json.JSONArray contains the put method and in java 7 javax.json contains the add method.

An example of this using the builder pattern in java 7 looks something like this:

JsonObject jo = Json.createObjectBuilder()
  .add("employees", Json.createArrayBuilder()
    .add(Json.createObjectBuilder()
      .add("firstName", "John")
      .add("lastName", "Doe")))
  .build();

Move SQL Server 2008 database files to a new folder location

You forgot to mention the name of your database (is it "my"?).

ALTER DATABASE my SET SINGLE_USER WITH ROLLBACK IMMEDIATE;

ALTER DATABASE my SET OFFLINE;

ALTER DATABASE my MODIFY FILE 
(
   Name = my_Data,
   Filename = 'D:\DATA\my.MDF'
);

ALTER DATABASE my MODIFY FILE 
(
   Name = my_Log, 
   Filename = 'D:\DATA\my_1.LDF'
);

Now here you must manually move the files from their current location to D:\Data\ (and remember to rename them manually if you changed them in the MODIFY FILE command) ... then you can bring the database back online:

ALTER DATABASE my SET ONLINE;

ALTER DATABASE my SET MULTI_USER;

This assumes that the SQL Server service account has sufficient privileges on the D:\Data\ folder. If not you will receive errors at the SET ONLINE command.

Wheel file installation

If you already have a wheel file (.whl) on your pc, then just go with the following code:

cd ../user
pip install file.whl

If you want to download a file from web, and then install it, go with the following in command line:

pip install package_name

or, if you have the url:

pip install http//websiteurl.com/filename.whl

This will for sure install the required file.

Note: I had to type pip2 instead of pip while using Python 2.

Android Material and appcompat Manifest merger failed

1.Added these codes to at the end of your app/build.gradle:

configurations.all {
   resolutionStrategy.force 'com.android.support:support-v4:28.0.0' 
   // the above lib may be old dependencies version       
    }

2.Modified sdk and tools version to 28:

compileSdkVersion 28
buildToolsVersion '28.0.3'
targetSdkVersion  28

3.In your AndroidManifest.xml file, you should add two line:

<application
    android:name=".YourApplication"
    android:appComponentFactory="AnyStrings"
    tools:replace="android:appComponentFactory"
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:largeHeap="true"
    android:theme="@style/Theme.AppCompat.Light.NoActionBar">

Or Simply

  • Go to Refactor (Studio -> Menu -> Refactor)
  • Click the Migrate to AndroidX. it's working
  • it's working.

How to create a data file for gnuplot?

Either as most people answered: the file doesn't exist / you're not specifying the path correctly.

Or, you're simply writing the syntax wrong (which you can't know unless you know what it should be like, right?, especially when in the "help" itself, it's wrong).

For gnuplot 4.6.0 on windows 7, terminal type set to windows

Make sure you specify the file's whole path to avoid looking for it where it's not (default seems to be "documents")

Make sure you use this syntax:

plot 'path\path\desireddatafile.txt'

NOT

plot "< path\path\desireddatafile.txt>"

NOR

plot "path\path\desireddatafile.txt"

also make sure your file is in the right format, like for .txt file format ANSI, not Unicode and such.

More Pythonic Way to Run a Process X Times

Personally:

for _ in range(50):
    print "Some thing"

if you don't need i. If you use Python < 3 and you want to repeat the loop a lot of times, use xrange as there is no need to generate the whole list beforehand.

How can I Convert HTML to Text in C#?

Another post suggests the HTML agility pack:

This is an agile HTML parser that builds a read/write DOM and supports plain XPATH or XSLT (you actually don't HAVE to understand XPATH nor XSLT to use it, don't worry...). It is a .NET code library that allows you to parse "out of the web" HTML files. The parser is very tolerant with "real world" malformed HTML. The object model is very similar to what proposes System.Xml, but for HTML documents (or streams).

PHP how to get local IP of system

This is an old post, but get it with this:

function getLocalIp()
{ return gethostbyname(trim(`hostname`)); }

For example:

die( getLocalIp() );

Found it on another site, do not remove the trim command because otherwise you will get the computers name.

BACKTICKS (The special quotes): It works because PHP will attempt to run whatever it's between those "special quotes" (backticks) as a shell command and returns the resulting output.

gethostbyname(trim(`hostname`));

Is very similar (but much more efficient) than doing:

$exec = exec("hostname"); //the "hostname" is a valid command in both windows and linux
$hostname = trim($exec); //remove any spaces before and after
$ip = gethostbyname($hostname); //resolves the hostname using local hosts resolver or DNS

Using Spring RestTemplate in generic method with generic parameter

As the code below shows it, it works.

public <T> ResponseWrapper<T> makeRequest(URI uri, final Class<T> clazz) {
   ResponseEntity<ResponseWrapper<T>> response = template.exchange(
        uri,
        HttpMethod.POST,
        null,
        new ParameterizedTypeReference<ResponseWrapper<T>>() {
            public Type getType() {
                return new MyParameterizedTypeImpl((ParameterizedType) super.getType(), new Type[] {clazz});
        }
    });
    return response;
}

public class MyParameterizedTypeImpl implements ParameterizedType {
    private ParameterizedType delegate;
    private Type[] actualTypeArguments;

    MyParameterizedTypeImpl(ParameterizedType delegate, Type[] actualTypeArguments) {
        this.delegate = delegate;
        this.actualTypeArguments = actualTypeArguments;
    }

    @Override
    public Type[] getActualTypeArguments() {
        return actualTypeArguments;
    }

    @Override
    public Type getRawType() {
        return delegate.getRawType();
    }

    @Override
    public Type getOwnerType() {
        return delegate.getOwnerType();
    }

}

Meaning of "n:m" and "1:n" in database design

Many to Many (n:m) One to Many (1:n)

Count number of rows per group and add result to original data frame

One simple line in base R:

df$count = table(interaction(df[, (c("name", "type"))]))[interaction(df[, (c("name", "type"))])]

Same in two lines, for clarity/efficiency:

fact = interaction(df[, (c("name", "type"))])
df$count = table(fact)[fact]

Swing/Java: How to use the getText and setText string properly

in your action performed method, call:

label1.setText(nameField.getText());

This way, when the button is clicked, label will be updated to the nameField text.

phpmyadmin "no data received to import" error, how to fix?

xampp in ubuntu

cd /opt/lampp/etc
vim php.ini

Find:
  post_max_size = 8M
  upload_max_filesize = 2M
  max_execution_time = 30
  max_input_time = 60
  memory_limit = 8M

Change to:
  post_max_size = 750M
  upload_max_filesize = 750M
  max_execution_time = 5000
  max_input_time = 5000
  memory_limit = 1000M

sudo /opt/lampp/lampp restart

Spark read file from S3 using sc.textFile ("s3n://...)

USe s3a instead of s3n. I had similar issue on a Hadoop job. After switching from s3n to s3a it worked.

e.g.

s3a://myBucket/myFile1.log

Setting a timeout for socket operations

You don't set a timeout for the socket, you set a timeout for the operations you perform on that socket.

For example socket.connect(otherAddress, timeout)

Or socket.setSoTimeout(timeout) for setting a timeout on read() operations.

See: http://docs.oracle.com/javase/7/docs/api/java/net/Socket.html

How do you scroll up/down on the console of a Linux VM

I ran into the same problem with VMWare workstation with Ubuntu guest, turns out VmWare doesn't support scrolling back up from the server view. What I did was to install x GUI, then run xterm from there. For some reason it runs the same, but lets you scroll the normal ways. Hope this helps future readers in VmWare virtual boxes.

gdb: "No symbol table is loaded"

First of all, what you have is a fully compiled program, not an object file, so drop the .o extension. Now, pay attention to what the error message says, it tells you exactly how to fix your problem: "No symbol table is loaded. Use the "file" command."

(gdb) exec-file test
(gdb) b 2
No symbol table is loaded.  Use the "file" command.
(gdb) file test
Reading symbols from /home/user/test/test...done.
(gdb) b 2
Breakpoint 1 at 0x80483ea: file test.c, line 2.
(gdb) 

Or just pass the program on the command line.

$ gdb test
GNU gdb (GDB) 7.4
Copyright (C) 2012 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
[...]
Reading symbols from /home/user/test/test...done.
(gdb) b 2
Breakpoint 1 at 0x80483ea: file test.c, line 2.
(gdb) 

How can I create a keystore?

Use this command to create debug.keystore

keytool -genkey -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android -keyalg RSA -keysize 2048 -validity 10000 -dname "CN=Android Debug,O=Android,C=US"

How to perform mouseover function in Selenium WebDriver using Java?

Based on this blog post I was able to trigger hovering using the following code with Selenium 2 Webdriver:

String javaScript = "var evObj = document.createEvent('MouseEvents');" +
                    "evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);" +
                    "arguments[0].dispatchEvent(evObj);";


((JavascriptExecutor)driver).executeScript(javaScript, webElement);

"%%" and "%/%" for the remainder and the quotient

I think it is because % has often be associated with the modulus operator in many programming languages.

It is the case, e.g., in C, C++, C# and Java, and many other languages which derive their syntax from C (C itself took it from B).

Multiple submit buttons in the same form calling different Servlets

    function gotofirst(){
        window.location = "firstServelet.java";
}
    function gotosecond(){
        window.location = "secondServelet.java";
}
<form action="FirstServlet" method="Post">
    Last Name: <input type="text" name="lastName" size="20">
    <br><br>
    <input type="submit" onclick="gotofirst()" value="FirstServlet">
    <input type="submit" onclick="gotosecond()" value="SecondServlet">
</form>

Detect home button press in android

Since you only wish for the root activity to be reshown when the app is launched, maybe you can get this behavior by changing launch modes, etc. in the manifest?

For instance, have you tried applying the android:clearTaskOnLaunch="true" attribute to your launch activity, perhaps in tandem with android:launchMode="singleInstance"?

Tasks and Back Stack is a great resource for fine-tuning this sort of behavior.

RegEx for Javascript to allow only alphanumeric

Alphanumeric with case sensitive:

if (/^[a-zA-Z0-9]+$/.test("SoS007")) {
  alert("match")
}

how to fix stream_socket_enable_crypto(): SSL operation failed with code 1

To resolve this problem you first need to check the SSL certificates of the host your are connecting to. For example using ssllabs or other ssl tools. In my case the intermediate certificate was wrong.

If the certificate is ok, make sure the openSSL on your server is up to date. Run openssl -v to check your version. Maybe your version is to old to work with the certificate.

In very rare cases you might want to disable ssl security features like verify_peer, verify_peer_name or allow_self_signed. Please be very careful with this and never use this in production. This is only an option for temporary testing.

Why does Python code use len() function instead of a length method?

met% python -c 'import this' | grep 'only one'
There should be one-- and preferably only one --obvious way to do it.

Change name of folder when cloning from GitHub?

In case you want to clone a specific branch only, then,

git clone -b <branch-name> <repo-url> <destination-folder-name>

for example,

git clone -b dev https://github.com/sferik/sign-in-with-twitter.git signin

PHP Parse error: syntax error, unexpected '?' in helpers.php 233

If you came across this error while using the command line its because you must be using php 7 to execute whatever it is you are trying to execute. What happened is that the code is trying to use an operator thats only available in php7+ and is causing a syntax error.

If you already have php 7+ on your computer try pointing the command line to the higher version of php you want to use.

export PATH=/usr/local/[php-7-folder]/bin/:$PATH

Here is the exact location that worked based off of my setup for reference:

export PATH=/usr/local/php5-7.1.4-20170506-100436/bin/:$PATH

The operator thats actually caused the break is the "null coalesce operator" you can read more about it here:

php7 New Operators

How to make a list of n numbers in Python and randomly select any number?

You can try this code

import random
N = 5
count_list = range(1,N+1)
random.shuffle(count_list)

while count_list:
    value = count_list.pop()
    # do whatever you want with 'value'

Eclipse comment/uncomment shortcut?

For those who like to customize things (and screw them up), some tips:

In "Preferences" - "General" - "Keys", type "comment" to get a full list of comment key combination in all editors. Be sure only to edit, not copy commands(because you cannot erase created ones).

For HTML files, look for those with scope "Editing HTML files". The names are confusing, yes, but the description shows more or less when each and every key is used.

At last, I am only able to define block comment in HTML here. It works for both HTML code and Javascript code(add at the beginning and the end, <!-- and --> if is HTML, and add /* and */ if is Javascript). (I remember once there may be a "line comment" key (add comments for every line) but now it is not there anymore. If someone knows how to find it and tell me, I will be very grateful.) enter image description here The category must be Edit. Source does not work.

EDIT:

I found how to configure XML Toggle comment! The category should be Edit, too. Then you can toggle comment in **XML Editor(the one with "Design" and "Source" tabs).

enter image description here

Looping over a list in Python

Do this instead:

values = [[1,2,3],[4,5]]
for x in values:
    if len(x) == 3:
       print(x)

How do I select a sibling element using jQuery?

also if you need to select a sibling with a name rather than the class, you could use the following

var $sibling = $(this).siblings('input[name=bidbutton]');

CSS selector for "foo that contains bar"?

Only thing that comes even close is the :contains pseudo class in CSS3, but that only selects textual content, not tags or elements, so you're out of luck.

A simpler way to select a parent with specific children in jQuery can be written as (with :has()):

$('#parent:has(#child)');

Android - Dynamically Add Views into View

It looks like what you really want a ListView with a custom adapter to inflate the specified layout. Using an ArrayAdapter and the method notifyDataSetChanged() you have full control of the Views generation and rendering.

Take a look at these tutorials

Accessing the index in 'for' loops?

In your question, you write "how do I access the loop index, from 1 to 5 in this case?"

However, the index for a list runs from zero. So, then we need to know if what you actually want is the index and item for each item in a list, or whether you really want numbers starting from 1. Fortunately, in Python, it is easy to do either or both.

First, to clarify, the enumerate function iteratively returns the index and corresponding item for each item in a list.

alist = [1, 2, 3, 4, 5]

for n, a in enumerate(alist):
    print("%d %d" % (n, a))

The output for the above is then,

0 1
1 2
2 3
3 4
4 5

Notice that the index runs from 0. This kind of indexing is common among modern programming languages including Python and C.

If you want your loop to span a part of the list, you can use the standard Python syntax for a part of the list. For example, to loop from the second item in a list up to but not including the last item, you could use

for n, a in enumerate(alist[1:-1]):
    print("%d %d" % (n, a))

Note that once again, the output index runs from 0,

0 2
1 3
2 4

That brings us to the start=n switch for enumerate(). This simply offsets the index, you can equivalently simply add a number to the index inside the loop.

for n, a in enumerate(alist, start=1):
    print("%d %d" % (n, a))

for which the output is

1 1
2 2
3 3
4 4
5 5

send mail from linux terminal in one line

You can install the mail package in Ubuntu with below command.

For Ubuntu -:

$ sudo apt-get install -y mailutils

For CentOs-:

$ sudo yum install -y mailx

Test Mail command-:

$ echo "Mail test" | mail -s "Subject" [email protected]

Find a string by searching all tables in SQL Server Management Studio 2008

A bit late but hopefully useful.

Why not try some of the third party tools that can be integrated into SSMS.

I’ve worked with ApexSQL Search (100% free) with good success for both schema and data search and there is also SSMS tools pack that has this feature (not free for SQL 2012 but quite affordable).

Stored procedure above is really great; it’s just that this is way more convenient in my opinion. Also, it would require some slight modifications if you want to search for datetime columns or GUID columns and such…

Understanding Matlab FFT example

There are some misconceptions here.

Frequencies above 500 can be represented in an FFT result of length 1000. Unfortunately these frequencies are all folded together and mixed into the first 500 FFT result bins. So normally you don't want to feed an FFT a signal containing any frequencies at or above half the sampling rate, as the FFT won't care and will just mix the high frequencies together with the low ones (aliasing) making the result pretty much useless. That's why data should be low-pass filtered before being sampled and fed to an FFT.

The FFT returns amplitudes without frequencies because the frequencies depend, not just on the length of the FFT, but also on the sample rate of the data, which isn't part of the FFT itself or it's input. You can feed the same length FFT data at any sample rate, as thus get any range of frequencies out of it.

The reason the result plots ends at 500 is that, for any real data input, the frequencies above half the length of the FFT are just mirrored repeats (complex conjugated) of the data in the first half. Since they are duplicates, most people just ignore them. Why plot duplicates? The FFT calculates the other half of the result for people who feed the FFT complex data (with both real and imaginary components), which does create two different halves.

Open link in new tab or window

You can simply do that by setting target="_blank", w3schools has an example.

Adding new line of data to TextBox

Following are the ways

  1. From the code (the way you have mentioned) ->

    displayBox.Text += sent + "\r\n";
    

    or

    displayBox.Text += sent + Environment.NewLine;
    
  2. From the UI
    a) WPF

    Set TextWrapping="Wrap" and AcceptsReturn="True"   
    

    Press Enter key to the textbox and new line will be created

    b) Winform text box

    Set TextBox.MultiLine and TextBox.AcceptsReturn to true
    

Excel error HRESULT: 0x800A03EC while trying to get range with cell's name

I got the error with a space in a Sheet Name:

using (var range = _excelApp.Range["Sheet Name Had Space!$A$1"].WithComCleanup())

I fixed it by putting single quotes around Sheet Names with spaces:

using (var range = _excelApp.Range["'Sheet Name Had Space'!$A$1"].WithComCleanup())

Div width 100% minus fixed amount of pixels

The usual way to do it is as outlined by Guffa, nested elements. It's a bit sad having to add extra markup to get the hooks you need for this, but in practice a wrapper div here or there isn't going to hurt anyone.

If you must do it without extra elements (eg. when you don't have control of the page markup), you can use box-sizing, which has pretty decent but not complete or simple browser support. Likely more fun than having to rely on scripting though.

python: [Errno 10054] An existing connection was forcibly closed by the remote host

This can be caused by the two sides of the connection disagreeing over whether the connection timed out or not during a keepalive. (Your code tries to reused the connection just as the server is closing it because it has been idle for too long.) You should basically just retry the operation over a new connection. (I'm surprised your library doesn't do this automatically.)

Replace NA with 0 in a data frame column

First, here's some sample data:

set.seed(1)
dat <- data.frame(one = rnorm(15),
                 two = sample(LETTERS, 15),
                 three = rnorm(15),
                 four = runif(15))
dat <- data.frame(lapply(dat, function(x) { x[sample(15, 5)] <- NA; x }))
head(dat)
#          one  two       three      four
# 1         NA    M  0.80418951 0.8921983
# 2  0.1836433    O -0.05710677        NA
# 3 -0.8356286    L  0.50360797 0.3899895
# 4         NA    E          NA        NA
# 5  0.3295078    S          NA 0.9606180
# 6 -0.8204684 <NA> -1.28459935 0.4346595

Here's our replacement:

dat[["four"]][is.na(dat[["four"]])] <- 0
head(dat)
#          one  two       three      four
# 1         NA    M  0.80418951 0.8921983
# 2  0.1836433    O -0.05710677 0.0000000
# 3 -0.8356286    L  0.50360797 0.3899895
# 4         NA    E          NA 0.0000000
# 5  0.3295078    S          NA 0.9606180
# 6 -0.8204684 <NA> -1.28459935 0.4346595

Alternatively, you can, of course, write dat$four[is.na(dat$four)] <- 0

How to fix itunes could not connect to the iphone because an invalid response was received from the device?

Try resetting your network settings

Settings -> General -> Reset -> Reset Network Settings

And try deleting the contents of your mac/pc lockdown folder. Here's the link, follow the steps on "Reset the Lockdown folder".

http://support.apple.com/kb/ts2529

This one worked for me.

How to get the current location in Google Maps Android API v2?

the accepted answer works but some of the used methods are now deprecated so I think it is best if I answer this question with updated methods.

this is answer is completely from this guide on google developers

so here is step by step guide:

  1. implement all this in your map activity

    MapActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks

  2. in your onCreate:

    private GoogleMap mMap;
    private Context context;
    private TextView txtStartPoint,txtEndPoint;
    private GoogleApiClient mGoogleApiClient;
    private Location mLastKnownLocation;
    private LatLng mDefaultLocation;
    private CameraPosition mCameraPosition;
    private boolean mLocationPermissionGranted;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    context = this;
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */,
                    this /* OnConnectionFailedListener */)
            .addConnectionCallbacks(this)
            .addApi(LocationServices.API)
            .addApi(Places.GEO_DATA_API)
            .addApi(Places.PLACE_DETECTION_API)
            .build();
    mGoogleApiClient.connect();
    }
    
  3. in your onConnected :

    SupportMapFragment mapFragment = (SupportMapFragment)     getSupportFragmentManager()
            .findFragmentById(map);
    mapFragment.getMapAsync(this);
    
  4. in your onMapReady :

    @Override
    public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    
    // Do other setup activities here too, as described elsewhere in this tutorial.
    
    // Turn on the My Location layer and the related control on the map.
    updateLocationUI();
    
    // Get the current location of the device and set the position of the map.
    getDeviceLocation();
    }
    
  5. and these two are methods in onMapReady :

    private void updateLocationUI() {
      if (mMap == null) {
        return;
    }
    
    if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
            android.Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        mLocationPermissionGranted = true;
    }
    
    if (mLocationPermissionGranted) {
        mMap.setMyLocationEnabled(true);
        mMap.getUiSettings().setMyLocationButtonEnabled(true);
    } else {
        mMap.setMyLocationEnabled(false);
        mMap.getUiSettings().setMyLocationButtonEnabled(false);
        mLastKnownLocation = null;
    }
    }
    
    private void getDeviceLocation() {
    if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
            android.Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        mLocationPermissionGranted = true;
    }
    
    if (mLocationPermissionGranted) {
        mLastKnownLocation = LocationServices.FusedLocationApi
                .getLastLocation(mGoogleApiClient);
    }
    
    // Set the map's camera position to the current location of the device.
    float DEFAULT_ZOOM = 15;
    if (mCameraPosition != null) {
        mMap.moveCamera(CameraUpdateFactory.newCameraPosition(mCameraPosition));
    } else if (mLastKnownLocation != null) {
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
                new LatLng(mLastKnownLocation.getLatitude(),
                        mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
    } else {
        Log.d("pouya", "Current location is null. Using defaults.");
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM));
        mMap.getUiSettings().setMyLocationButtonEnabled(false);
    }
    }
    

this is very fast , smooth and effective. hope this helps

UICollectionView - dynamic cell height?

I followed the steps mentioned in this SO and everything is fine except when my Collection View has less data (text) to make it wide enough. Checking the documentation in systemLyaoutSizeFittingSize, I have this solution so my cell take up the width as I requested:

- (CGSize)calculateSizeForSizingCell:(UICollectionViewCell *)sizingCell width:(CGFloat)width {
    CGRect frame = sizingCell.frame;
    frame.size.width = width;
    sizingCell.frame = frame;
    [sizingCell setNeedsLayout];
    [sizingCell layoutIfNeeded];

    CGSize size = [sizingCell systemLayoutSizeFittingSize:UILayoutFittingCompressedSize
                        withHorizontalFittingPriority:UILayoutPriorityRequired
                              verticalFittingPriority:UILayoutPriorityFittingSizeLevel];
    return size;
}

Hope this would help someone.

- (CGSize)systemLayoutSizeFittingSize:(CGSize)targetSize NS_AVAILABLE_IOS(6_0);

Apple doc:

Equivalent to sending -systemLayoutSizeFittingSize:withHorizontalFittingPriority:verticalFittingPriority: with UILayoutPriorityFittingSizeLevel for both priorities.

While the default value is "pretty low" according to Apple's doc:

When you send -[UIView systemLayoutSizeFittingSize:], the size fitting most closely to the target size (the argument) is computed. UILayoutPriorityFittingSizeLevel is the priority level with which the view wants to conform to the target size in that computation. It's quite low. It is generally not appropriate to make a constraint at exactly this priority. You want to be higher or lower.

So my change of default behavior is to enforce the width (horizontal fitting) with UILayoutPriorityRequired.

How do I set up cron to run a file just once at a specific time?

You really want to use at. It is exactly made for this purpose.

echo /usr/bin/the_command options | at now + 1 day

However if you don't have at, or your hosting company doesn't provide access to it, you can have a cron job include code that makes sure it only runs once.

Set up a cron entry with a very specific time:

0 0 2 12 * /home/adm/bin/the_command options

Next /home/adm/bin/the_command needs to either make sure it only runs once.

#! /bin/bash

COMMAND=/home/adm/bin/the_command
DONEYET="${COMMAND}.alreadyrun"

export PATH=/usr/bin:$PATH

if [[ -f $DONEYET ]]; then
  exit 1
fi
touch "$DONEYET"

# Put the command you want to run exactly once here:
echo 'You will only get this once!' | mail -s 'Greetings!' [email protected]

Getting the class name of an instance?

To get instance classname:

type(instance).__name__

or

instance.__class__.__name__

both are the same

Enable SQL Server Broker taking too long

Enabling SQL Server Service Broker requires a database lock. Stop the SQL Server Agent and then execute the following:

USE master ;
GO

ALTER DATABASE [MyDatabase] SET ENABLE_BROKER ;
GO

Change [MyDatabase] with the name of your database in question and then start SQL Server Agent.

If you want to see all the databases that have Service Broker enabled or disabled, then query sys.databases, for instance:

SELECT
    name, database_id, is_broker_enabled
FROM sys.databases

What is an index in SQL?

An index is used to speed up the performance of queries. It does this by reducing the number of database data pages that have to be visited/scanned.

In SQL Server, a clustered index determines the physical order of data in a table. There can be only one clustered index per table (the clustered index IS the table). All other indexes on a table are termed non-clustered.

Using multiprocessing.Process with a maximum number of simultaneous processes

I think Semaphore is what you are looking for, it will block the main process after counting down to 0. Sample code:

from multiprocessing import Process
from multiprocessing import Semaphore
import time

def f(name, sema):
    print('process {} starting doing business'.format(name))
    # simulate a time-consuming task by sleeping
    time.sleep(5)
    # `release` will add 1 to `sema`, allowing other 
    # processes blocked on it to continue
    sema.release()

if __name__ == '__main__':
    concurrency = 20
    total_task_num = 1000
    sema = Semaphore(concurrency)
    all_processes = []
    for i in range(total_task_num):
        # once 20 processes are running, the following `acquire` call
        # will block the main process since `sema` has been reduced
        # to 0. This loop will continue only after one or more 
        # previously created processes complete.
        sema.acquire()
        p = Process(target=f, args=(i, sema))
        all_processes.append(p)
        p.start()

    # inside main process, wait for all processes to finish
    for p in all_processes:
        p.join()

The following code is more structured since it acquires and releases sema in the same function. However, it will consume too much resources if total_task_num is very large:

from multiprocessing import Process
from multiprocessing import Semaphore
import time

def f(name, sema):
    print('process {} starting doing business'.format(name))
    # `sema` is acquired and released in the same
    # block of code here, making code more readable,
    # but may lead to problem.
    sema.acquire()
    time.sleep(5)
    sema.release()

if __name__ == '__main__':
    concurrency = 20
    total_task_num = 1000
    sema = Semaphore(concurrency)
    all_processes = []
    for i in range(total_task_num):
        p = Process(target=f, args=(i, sema))
        all_processes.append(p)
        # the following line won't block after 20 processes
        # have been created and running, instead it will carry 
        # on until all 1000 processes are created.
        p.start()

    # inside main process, wait for all processes to finish
    for p in all_processes:
        p.join()

The above code will create total_task_num processes but only concurrency processes will be running while other processes are blocked, consuming precious system resources.

Meaning of *& and **& in C++

This *& in theory as well as in practical its possible and called as reference to pointer variable. and it's act like same. This *& combination is used in as function parameter for 'pass by' type defining. unlike ** can also be used for declaring a double pointer variable.
The passing of parameter is divided into pass by value, pass by reference, pass by pointer. there are various answer about "pass by" types available. however the basic we require to understand for this topic is.

pass by reference --> generally operates on already created variable refereed while passing to function e.g fun(int &a);

pass by pointer --> Operates on already initialized 'pointer variable/variable address' passing to function e.g fun(int* a);

auto addControl = [](SomeLabel** label, SomeControl** control) {
    *label = new SomeLabel;
    *control = new SomeControl;
    // few more operation further.
};

addControl(&m_label1,&m_control1);
addControl(&m_label2,&m_control2);
addControl(&m_label3,&m_control3);

in the above example(this is the real life problem i came across) i am trying to init few pointer variable from the lambda function and for that we need to pass it by double pointer, so that comes with d-referencing of pointer for its all usage inside of that lambda + while passing pointer in function which takes double pointer, you need to pass reference to the pointer variable.

so with this same thing reference to the pointer variable, *& this combination helps. in below given way for the same example i have mentioned above.

auto addControl = [](SomeLabel*& label, SomeControl*& control) {
        label = new SomeLabel;
        control = new SomeControl;
        // few more operation further.
    };

addControl(m_label1,m_control1);
addControl(m_label2,m_control2);
addControl(m_label3,m_control3);

so here you can see that you neither require d-referencing nor we require to pass reference to pointer variable while passing in function, as current pass by type is already reference to pointer.

Hope this helps :-)

Android Overriding onBackPressed()

Best and most generic way to control the music is to create a mother Activity in which you override startActivity(Intent intent) - in it you put shouldPlay=true, and onBackPressed() - in it you put shouldPlay = true. onStop - in it you put a conditional mediaPlayer.stop with shouldPlay as condition

Then, just extend the mother activity to all other activities, and no code duplicating is needed.

Adding a custom header to HTTP request using angular.js

For me the following explanatory snippet worked. Perhaps you shouldn't use ' for header name?

{
   headers: { 
      Authorization: "Basic " + getAuthDigest(), 
      Accept: "text/plain" 
   }
}

I'm using $http.ajax(), though I wouldn't expect that to be a game changer.

How to get controls in WPF to fill available space?

Well, I figured it out myself, right after posting, which is the most embarassing way. :)

It seems every member of a StackPanel will simply fill its minimum requested size.

In the DockPanel, I had docked things in the wrong order. If the TextBox or ListBox is the only docked item without an alignment, or if they are the last added, they WILL fill the remaining space as wanted.

I would love to see a more elegant method of handling this, but it will do.

converting numbers in to words C#

public static string NumberToWords(int number)
{
    if (number == 0)
        return "zero";

    if (number < 0)
        return "minus " + NumberToWords(Math.Abs(number));

    string words = "";

    if ((number / 1000000) > 0)
    {
        words += NumberToWords(number / 1000000) + " million ";
        number %= 1000000;
    }

    if ((number / 1000) > 0)
    {
        words += NumberToWords(number / 1000) + " thousand ";
        number %= 1000;
    }

    if ((number / 100) > 0)
    {
        words += NumberToWords(number / 100) + " hundred ";
        number %= 100;
    }

    if (number > 0)
    {
        if (words != "")
            words += "and ";

        var unitsMap = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
        var tensMap = new[] { "zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };

        if (number < 20)
            words += unitsMap[number];
        else
        {
            words += tensMap[number / 10];
            if ((number % 10) > 0)
                words += "-" + unitsMap[number % 10];
        }
    }

    return words;
}

Clear data in MySQL table with PHP?

MySQLI example where $con is the database connection variable and table name is: mytable.

mysqli_query($con,'TRUNCATE TABLE mytable');

Convert XmlDocument to String

you can use xmlDoc.InnerXml property to get xml in string

Include another HTML file in a HTML file

Using just HTML it is not possible to include HTML file in another HTML file. But here is a very easy method to do this. Using this JS library you can easy do that. Just use this code:

<script> include('path/to/file.html', document.currentScript) </script>

How to see log files in MySQL?

Here is a simple way to enable them. In mysql we need to see often 3 logs which are mostly needed during any project development.

  • The Error Log. It contains information about errors that occur while the server is running (also server start and stop)

  • The General Query Log. This is a general record of what mysqld is doing (connect, disconnect, queries)

  • The Slow Query Log. ?t consists of "slow" SQL statements (as indicated by its name).

By default no log files are enabled in MYSQL. All errors will be shown in the syslog (/var/log/syslog).

To Enable them just follow below steps:

step1: Go to this file (/etc/mysql/conf.d/mysqld_safe_syslog.cnf) and remove or comment those line.

step2: Go to mysql conf file (/etc/mysql/my.cnf) and add following lines

To enable error log add following

[mysqld_safe]
log_error=/var/log/mysql/mysql_error.log

[mysqld]
log_error=/var/log/mysql/mysql_error.log

To enable general query log add following

general_log_file        = /var/log/mysql/mysql.log
general_log             = 1

To enable Slow Query Log add following

log_slow_queries       = /var/log/mysql/mysql-slow.log
long_query_time = 2
log-queries-not-using-indexes

step3: save the file and restart mysql using following commands

service mysql restart

To enable logs at runtime, login to mysql client (mysql -u root -p) and give:

SET GLOBAL general_log = 'ON';
SET GLOBAL slow_query_log = 'ON';

Finally one thing I would like to mention here is I read this from a blog. Thanks. It works for me.

Click here to visit the blog

Failed to open/create the internal network Vagrant on Windows10

I have Windows 8.1 and had this problem with VirtualBox 5.0.16.105871. I tried every suggestion I found here, virtual box site, and other forums. None worked for me. I had this error when tried to start a VM with host-only interface:

Failed to open a session for the virtual machine LinuxVMDev0.

Failed to open/create the internal network 'HostInterfaceNetworking-VirtualBox Host-Only Ethernet Adapter' (VERR_INTNET_FLT_IF_NOT_FOUND).

Failed to attach the network LUN (VERR_INTNET_FLT_IF_NOT_FOUND).

Result Code: E_FAIL (0x80004005)
Component: ConsoleWrap
Interface: IConsole {872da645-4a9b-1727-bee2-5585105b9eed}

Finally the only solution that worked for me was:

  1. Uninstall 5.0.16
  2. Install version 4.3.36 that did not have this problem (at least in my PC)
  3. Without uninstalling 4.3.36, install version 5.0.16 in the default way

(Always installing as Administrator, i.e. running the installer as administrator).

That worked for me after trying different solution during days.

How to write PNG image to string with the PIL?

save() can take a file-like object as well as a path, so you can use an in-memory buffer like a StringIO:

buf = StringIO.StringIO()
im.save(buf, format='JPEG')
jpeg = buf.getvalue()

Getting last day of the month in a given string date

Java 8 and above:

import java.time.LocalDate;
import java.time.Year;

static int lastDayOfMonth(int Y, int M) {
    return LocalDate.of(Y, M, 1).getMonth().length(Year.of(Y).isLeap());
}

subject to Basil Bourque's comment

import java.time.YearMonth;

int lastDayOfMonth = YearMonth.of(Y, M).lengthOfMonth();

Converting pixels to dp

This should give you the conversion dp to pixels:

public static int dpToPx(int dp)
{
    return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
}

This should give you the conversion pixels to dp:

public static int pxToDp(int px)
{
    return (int) (px / Resources.getSystem().getDisplayMetrics().density);
}

How do I launch a Git Bash window with particular working directory using a script?

Let yet add up to the answer from @Drew Noakes:

Target:

"C:\Program Files\Git\git-bash.exe" --cd=C:\GitRepo

The cd param should be one of the options how to specify the working directory.

Also notice, that I have not any --login param there: Instead, I use another extra app, dedicated just for SSH keys: Pageant (PuTTY authentication agent).

Start in:

C:\GitRepo

The same possible way, as @Drew Noakes mentioned/shown here sooner, I use it too.

Shortcut key:

Ctrl + Alt + B

Such shortcuts are another less known feature in Windows. But there is a restriction: To let the shortcut take effect, it must be placed somewhere on the User's subdirectory: The Desktop is fine.

If you do not want it visible, yet still activatable, place this .lnk file i.e. to the quick launch folder, as that dir is purposed for such shortcuts. (no matter whether displayed on the desktop) #76080 #3619355

"\Application Data\Microsoft\Internet Explorer\Quick Launch\"

Where's the DateTime 'Z' format specifier?

I was dealing with DateTimeOffset and unfortunately the "o" prints out "+0000" not "Z".

So I ended up with:

dateTimeOffset.UtcDateTime.ToString("o")

ORA-00060: deadlock detected while waiting for resource

You can get deadlocks on more than just row locks, e.g. see this. The scripts may be competing for other resources, such as index blocks.

I've gotten around this in the past by engineering the parallelism in such a way that different instances are working on portions of the workload that are less likely to affect blocks that are close to each other; for example, for an update of a large table, instead of setting up the parallel slaves using something like MOD(n,10), I'd use TRUNC(n/10) which mean that each slave worked on a contiguous set of data.

There are, of course, much better ways of splitting up a job for parallelism, e.g. DBMS_PARALLEL_EXECUTE.

Not sure why you're getting "PL/SQL successfully completed", perhaps your scripts are handling the exception?

How to push object into an array using AngularJS

A couple of answers that should work above but this is how i would write it.

Also, i wouldn't declare controllers inside templates. It's better to declare them on your routes imo.

add-text.tpl.html

<div ng-controller="myController">
    <form ng-submit="addText(myText)">
        <input type="text" placeholder="Let's Go" ng-model="myText">
        <button type="submit">Add</button>
    </form>
    <ul>
        <li ng-repeat="text in arrayText">{{ text }}</li>
    </ul>
</div>

app.js

(function() {

    function myController($scope) {
        $scope.arrayText = ['hello', 'world'];
        $scope.addText = function(myText) {
             $scope.arrayText.push(myText);     
        };
    }

    angular.module('app', [])
        .controller('myController', myController);

})();

What does the ">" (greater-than sign) CSS selector mean?

( child selector) was introduced in css2. div p{ } select all p elements decedent of div elements, whereas div > p selects only child p elements, not grand child, great grand child on so on.

<style>
  div p{  color:red  }       /* match both p*/
  div > p{  color:blue  }    /* match only first p*/

</style>

<div>
   <p>para tag, child and decedent of p.</p>
   <ul>
       <li>
            <p>para inside list. </p>
       </li>
   </ul>
</div>

For more information on CSS Ce[lectors and their use, check my blog, css selectors and css3 selectors

Insert if not exists Oracle

Coming late to the party, but...

With oracle 11.2.0.1 there is a semantic hint that can do this: IGNORE_ROW_ON_DUPKEY_INDEX

Example:

insert /*+ IGNORE_ROW_ON_DUPKEY_INDEX(customer_orders,pk_customer_orders) */
  into customer_orders
       (order_id, customer, product)
values (    1234,     9876,  'K598')
     ;

UPDATE: Although this hint works (if you spell it correctly), there are better approaches which don't require Oracle 11R2:

First approach—direct translation of above semantic hint:

begin
  insert into customer_orders
         (order_id, customer, product)
  values (    1234,     9876,  'K698')
  ;
  commit;
exception
  when DUP_VAL_ON_INDEX
  then ROLLBACK;
end;

Second aproach—a lot faster than both above hints when there's a lot of contention:

begin
    select count (*)
    into   l_is_matching_row
    from   customer_orders
    where  order_id = 1234
    ;

    if (l_is_matching_row = 0)
    then
      insert into customer_orders
             (order_id, customer, product)
      values (    1234,     9876,  'K698')
      ;
      commit;
    end if;
exception
  when DUP_VAL_ON_INDEX
  then ROLLBACK;
end;

PHP simple foreach loop with HTML

This will work although when embedding PHP in HTML it is better practice to use the following form:

<table>
    <?php foreach($array as $key=>$value): ?>
    <tr>
        <td><?= $key; ?></td>
    </tr>
    <?php endforeach; ?>
</table>

You can find the doc for the alternative syntax on PHP.net

Why is 2 * (i * i) faster than 2 * i * i in Java?

(Editor's note: this answer is contradicted by evidence from looking at the asm, as shown by another answer. This was a guess backed up by some experiments, but it turned out not to be correct.)


When the multiplication is 2 * (i * i), the JVM is able to factor out the multiplication by 2 from the loop, resulting in this equivalent but more efficient code:

int n = 0;
for (int i = 0; i < 1000000000; i++) {
    n += i * i;
}
n *= 2;

but when the multiplication is (2 * i) * i, the JVM doesn't optimize it since the multiplication by a constant is no longer right before the n += addition.

Here are a few reasons why I think this is the case:

  • Adding an if (n == 0) n = 1 statement at the start of the loop results in both versions being as efficient, since factoring out the multiplication no longer guarantees that the result will be the same
  • The optimized version (by factoring out the multiplication by 2) is exactly as fast as the 2 * (i * i) version

Here is the test code that I used to draw these conclusions:

public static void main(String[] args) {
    long fastVersion = 0;
    long slowVersion = 0;
    long optimizedVersion = 0;
    long modifiedFastVersion = 0;
    long modifiedSlowVersion = 0;

    for (int i = 0; i < 10; i++) {
        fastVersion += fastVersion();
        slowVersion += slowVersion();
        optimizedVersion += optimizedVersion();
        modifiedFastVersion += modifiedFastVersion();
        modifiedSlowVersion += modifiedSlowVersion();
    }

    System.out.println("Fast version: " + (double) fastVersion / 1000000000 + " s");
    System.out.println("Slow version: " + (double) slowVersion / 1000000000 + " s");
    System.out.println("Optimized version: " + (double) optimizedVersion / 1000000000 + " s");
    System.out.println("Modified fast version: " + (double) modifiedFastVersion / 1000000000 + " s");
    System.out.println("Modified slow version: " + (double) modifiedSlowVersion / 1000000000 + " s");
}

private static long fastVersion() {
    long startTime = System.nanoTime();
    int n = 0;
    for (int i = 0; i < 1000000000; i++) {
        n += 2 * (i * i);
    }
    return System.nanoTime() - startTime;
}

private static long slowVersion() {
    long startTime = System.nanoTime();
    int n = 0;
    for (int i = 0; i < 1000000000; i++) {
        n += 2 * i * i;
    }
    return System.nanoTime() - startTime;
}

private static long optimizedVersion() {
    long startTime = System.nanoTime();
    int n = 0;
    for (int i = 0; i < 1000000000; i++) {
        n += i * i;
    }
    n *= 2;
    return System.nanoTime() - startTime;
}

private static long modifiedFastVersion() {
    long startTime = System.nanoTime();
    int n = 0;
    for (int i = 0; i < 1000000000; i++) {
        if (n == 0) n = 1;
        n += 2 * (i * i);
    }
    return System.nanoTime() - startTime;
}

private static long modifiedSlowVersion() {
    long startTime = System.nanoTime();
    int n = 0;
    for (int i = 0; i < 1000000000; i++) {
        if (n == 0) n = 1;
        n += 2 * i * i;
    }
    return System.nanoTime() - startTime;
}

And here are the results:

Fast version: 5.7274411 s
Slow version: 7.6190804 s
Optimized version: 5.1348007 s
Modified fast version: 7.1492705 s
Modified slow version: 7.2952668 s

In Oracle, is it possible to INSERT or UPDATE a record through a view?

YES, you can Update and Insert into view and that edit will be reflected on the original table....
BUT
1-the view should have all the NOT NULL values on the table
2-the update should have the same rules as table... "updating primary key related to other foreign key.. etc"...

:not(:empty) CSS selector is not working?

Since placeholder disappear on input, you can use:

input:placeholder-shown{
    //rules for not empty input
}

Which MIME type to use for a binary file that's specific to my program?

I'd recommend application/octet-stream as RFC2046 says "The "octet-stream" subtype is used to indicate that a body contains arbitrary binary data" and "The recommended action for an implementation that receives an "application/octet-stream" entity is to simply offer to put the data in a file[...]".

I think that way you will get better handling from arbitrary programs, that might barf when encountering your unknown mime type.

Recursive sub folder search and return files in a list python

I will translate John La Rooy's list comprehension to nested for's, just in case anyone else has trouble understanding it.

result = [y for x in os.walk(PATH) for y in glob(os.path.join(x[0], '*.txt'))]

Should be equivalent to:

import glob
import os

result = []

for x in os.walk(PATH):
    for y in glob.glob(os.path.join(x[0], '*.txt')):
        result.append(y)

Here's the documentation for list comprehension and the functions os.walk and glob.glob.

What is a reasonable code coverage % for unit tests (and why)?

It depends greatly on your application. For example, some applications consist mostly of GUI code that cannot be unit tested.

How to detect query which holds the lock in Postgres?

This modification of a_horse_with_no_name's answer will give you the blocking queries in addition to just the blocked sessions:

SELECT
    activity.pid,
    activity.usename,
    activity.query,
    blocking.pid AS blocking_id,
    blocking.query AS blocking_query
FROM pg_stat_activity AS activity
JOIN pg_stat_activity AS blocking ON blocking.pid = ANY(pg_blocking_pids(activity.pid));

How do you clear the console screen in C?

just type clrscr(); function in void main().

as example:

void main()
{
clrscr();
printf("Hello m fresher in programming c.");
getch();
}

clrscr();

function easy to clear screen.

jQuery how to find an element based on a data-attribute value?

$("ul").find("li[data-slide='" + current + "']");

I hope this may work better

thanks

How to convert string to Title Case in Python?

def camelCase(st):
    s = st.title()
    d = "".join(s.split())
    d = d.replace(d[0],d[0].lower())
    return d

How to find the kafka version in linux

When you install Kafka in Centos7 with confluent :

yum install confluent-platform-oss-2.11

You can see the version of Kafka with :

yum deplist confluent-platform-oss-2.11

You can read : confluent-kafka-2.11 >= 0.10.2.1

How to check if a string is null in python

Try this:

if cookie and not cookie.isspace():
    # the string is non-empty
else:
    # the string is empty

The above takes in consideration the cases where the string is None or a sequence of white spaces.

How to show all rows by default in JQuery DataTable

Use:

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
    iDisplayLength: -1
});

Or if using 1.10+

$('#example').dataTable({
    paging: false
});

The option you should use is iDisplayLength:

$('#adminProducts').dataTable({
  'iDisplayLength': 100
});

$('#table').DataTable({
   "lengthMenu": [ [5, 10, 25, 50, -1], [5, 10, 25, 50, "All"] ]
});

It will Load by default all entries.

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
    iDisplayLength: -1
});

Or if using 1.10+

$('#example').dataTable({
    paging: false
});

If you want to load by default 25 not all do this.

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
});

What are your favorite extension methods for C#? (codeplex.com/extensionoverflow)

DateTimeExtensions

Examples:

DateTime firstDayOfMonth = DateTime.Now.First();
DateTime lastdayOfMonth = DateTime.Now.Last();
DateTime lastFridayInMonth = DateTime.Now.Last(DayOfWeek.Friday);
DateTime nextFriday = DateTime.Now.Next(DayOfWeek.Friday);
DateTime lunchTime = DateTime.Now.SetTime(11, 30);
DateTime noonOnFriday = DateTime.Now.Next(DayOfWeek.Friday).Noon();
DateTime secondMondayOfMonth = DateTime.Now.First(DayOfWeek.Monday).Next(DayOfWeek.Monday).Midnight();

Set Content-Type to application/json in jsp file

You can do via Page directive.

For example:

<%@ page language="java" contentType="application/json; charset=UTF-8"
    pageEncoding="UTF-8"%>
  • contentType="mimeType [ ;charset=characterSet ]" | "text/html;charset=ISO-8859-1"

The MIME type and character encoding the JSP file uses for the response it sends to the client. You can use any MIME type or character set that are valid for the JSP container. The default MIME type is text/html, and the default character set is ISO-8859-1.

Differences between Octave and MATLAB?

Octave is basically an open source version of MATLAB. It was written to be just that. MATLAB has a very nice GUI which makes it a bit easier to use but the next stable release of OCTAVE will also have a GUI, which I have tested in the unstable release, and looks fantastic. Octave is much more buggy because it was developed and maintained by a group of volunteers, where the development of MATLAB is funded by millions of dollars by industry. I'm still a student and am using a student version of MATLAB, but I am thinking of going over to Octave once the stable version with the GUI is released.

MATLAB is probably a lot more powerful than Octave, and the algorithms run faster, but for most applications, Octave is more than adequate and is, in my opinion' an amazing tool that is completely free, where Octave is completely free.

I would say use MATLAB while you can use the academic version, but the switch to Octave should be seamless as they use the exact same syntax.

Lastly, there is the issue of SIMULINK. If you want to do simulation or control system design (there are probably a million other uses) SIMULINK is fantastic and comes with MATLAB. I don't think any other comes close to this, although Scilab is apparently a 'good' open source alternative, I haven't tried it.

Peace.

How schedule build in Jenkins?

Jenkins uses Cron Expressions.

You can simply schedule hourly builds by just typing@hourly.

calling java methods in javascript code

When it is on server side, use web services - maybe RESTful with JSON.

  • create a web service (for example with Tomcat)
  • call its URL from JavaScript (for example with JQuery or dojo)

When Java code is in applet you can use JavaScript bridge. The bridge between the Java and JavaScript programming languages, known informally as LiveConnect, is implemented in Java plugin. Formerly Mozilla-specific LiveConnect functionality, such as the ability to call static Java methods, instantiate new Java objects and reference third-party packages from JavaScript, is now available in all browsers.

Below is example from documentation. Look at methodReturningString.

Java code:

public class MethodInvocation extends Applet {
    public void noArgMethod() { ... }
    public void someMethod(String arg) { ... }
    public void someMethod(int arg) { ... }
    public int  methodReturningInt() { return 5; }
    public String methodReturningString() { return "Hello"; }
    public OtherClass methodReturningObject() { return new OtherClass(); }
}

public class OtherClass {
    public void anotherMethod();
}

Web page and JavaScript code:

<applet id="app"
        archive="examples.jar"
        code="MethodInvocation" ...>
</applet>
<script language="javascript">
    app.noArgMethod();
    app.someMethod("Hello");
    app.someMethod(5);
    var five = app.methodReturningInt();
    var hello = app.methodReturningString();
    app.methodReturningObject().anotherMethod();
</script>

java.lang.ClassNotFoundException: javax.servlet.jsp.jstl.core.Config

Add JSTL library as dependency to your project (javax.servlet.jsp.jstl.core.Config is a part of this package). For example, if you were using Gradle, you could write in a build.gradle:

dependencies {
    compile 'javax.servlet:jstl:1.2'
}

Python urllib2 Basic Auth Problem

The problem could be that the Python libraries, per HTTP-Standard, first send an unauthenticated request, and then only if it's answered with a 401 retry, are the correct credentials sent. If the Foursquare servers don't do "totally standard authentication" then the libraries won't work.

Try using headers to do authentication:

import urllib2, base64

request = urllib2.Request("http://api.foursquare.com/v1/user")
base64string = base64.b64encode('%s:%s' % (username, password))
request.add_header("Authorization", "Basic %s" % base64string)   
result = urllib2.urlopen(request)

Had the same problem as you and found the solution from this thread: http://forums.shopify.com/categories/9/posts/27662

Chart won't update in Excel (2007)

I faced the same issue. The issue is due to restriction in no. of calculated formulas in your sheet. you can solved it using two ways:

Manual force re-calculate:

Press SHEFT + F9

Macro to force re-calculate: add below code to the end of the function which changes the data

Activesheet.Calculate

I found the solution of it: From excel options make sure to change the calculation options as below. It changed sometimes to manual after heavy work in excel.

Auto Calculation

How to get all elements which name starts with some string?

You can use getElementsByName("input") to get a collection of all the inputs on the page. Then loop through the collection, checking the name on the way. Something like this:

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>

</head>
<body>

  <input name="q1_a" type="text" value="1A"/>
  <input name="q1_b" type="text" value="1B"/>
  <input name="q1_c" type="text" value="1C"/>
  <input name="q2_d" type="text" value="2D"/>

  <script type="text/javascript">
  var inputs = document.getElementsByTagName("input");
  for (x = 0 ; x < inputs.length ; x++){
    myname = inputs[x].getAttribute("name");
    if(myname.indexOf("q1_")==0){
      alert(myname);
      // do more stuff here
       }
    }
    </script>
</body>
</html>

Demo

Uncaught TypeError: Cannot read property 'value' of null

add "MainContent_" to ID value!

Example: (Error)

document.getElementById("Password").value = text;

(ok!)

document.getElementById("**MainContent_**Password").value = text;

Could not load type from assembly error

If you have one project referencing another project (such as a 'Windows Application' type referencing a 'Class Library') and both have the same Assembly name, you'll get this error. You can either strongly name the referenced project or (even better) rename the assembly of the referencing project (under the 'Application' tab of project properties in VS).

How to clear https proxy setting of NPM?

npm config delete proxy -g

worked for me.

-g was important as initially it was set with that option. You can check configurations set with :

npm config list

How to change UINavigationBar background color from the AppDelegate

You can use [[UINavigationBar appearance] setTintColor:myColor];

Since iOS 7 you need to set [[UINavigationBar appearance] setBarTintColor:myColor]; and also [[UINavigationBar appearance] setTranslucent:NO].

[[UINavigationBar appearance] setBarTintColor:myColor];
[[UINavigationBar appearance] setTranslucent:NO];

Disable text input history

<input type="text" autocomplete="off"/>

Should work. Alternatively, use:

<form autocomplete="off" … >

for the entire form (see this related question).

How to get a list of installed android applications and pick one to run

private static boolean isThisASystemPackage(Context context, PackageInfo  packageInfo ) {
        try {
            PackageInfo sys = context.getPackageManager().getPackageInfo("android", PackageManager.GET_SIGNATURES);
            return (packageInfo != null && packageInfo.signatures != null &&
                    sys.signatures[0].equals(packageInfo.signatures[0]));
        } catch (NameNotFoundException e) {
            return false;
        }
    }

How do I set environment variables from Java?

You can pass parameters into your initial java process with -D:

java -cp <classpath> -Dkey1=value -Dkey2=value ...

Unexpected token < in first line of HTML

I had the same issue. I published the angular/core application on iis.

To change the Identity of the application pool solved my issue. Now the Identity is LocalSystem

Container is running beyond memory limits

I had a really similar issue using HIVE in EMR. None of the extant solutions worked for me -- ie, none of the mapreduce configurations worked for me; and neither did setting yarn.nodemanager.vmem-check-enabled to false.

However, what ended up working was setting tez.am.resource.memory.mb, for example:

hive -hiveconf tez.am.resource.memory.mb=4096

Another setting to consider tweaking is yarn.app.mapreduce.am.resource.mb

How to use enums in C++

You can use a trick to use scopes as you wish, just declare enum in such way:

struct Days 
{
   enum type
   {
      Saturday,Sunday,Tuesday,Wednesday,Thursday,Friday
   };
};

Days::type day = Days::Saturday;
if (day == Days::Saturday)

How to find out the number of CPUs using python

These give you the hyperthreaded CPU count

  1. multiprocessing.cpu_count()
  2. os.cpu_count()

These give you the virtual machine CPU count

  1. psutil.cpu_count()
  2. numexpr.detect_number_of_cores()

Only matters if you works on VMs.

Java abstract interface

It's not necessary, it's optional, just as public on interface methods.

See the JLS on this:

http://java.sun.com/docs/books/jls/second_edition/html/interfaces.doc.html

9.1.1.1 abstract Interfaces Every interface is implicitly abstract. This modifier is obsolete and should not be used in new programs.

And

9.4 Abstract Method Declarations

[...]

For compatibility with older versions of the Java platform, it is permitted but discouraged, as a matter of style, to redundantly specify the abstract modifier for methods declared in interfaces.

It is permitted, but strongly discouraged as a matter of style, to redundantly specify the public modifier for interface methods.

How to make a countdown timer in Android?

public class Scan extends AppCompatActivity {
int minute;
long min;
TextView tv_timer;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_scan2);
    tv_timer=findViewById(R.id.tv_timer);
    minute=Integer.parseInt("Your time in string form like 10");
    min= minute*60*1000;
    counter(min);
}
private void counter(long min) {
    CountDownTimer timer = new CountDownTimer(min, 1000) {
        public void onTick(long millisUntilFinished) {
            int seconds = (int) (millisUntilFinished / 1000) % 60;
            int minutes = (int) ((millisUntilFinished / (1000 * 60)) % 60);
            int hours = (int) ((millisUntilFinished / (1000 * 60 * 60)) % 24);
            tv_timer.setText(String.format("%d:%d:%d", hours, minutes, seconds));
        }
        public void onFinish() {
            Toast.makeText(getApplicationContext(), "Your time has been completed",
                    Toast.LENGTH_LONG).show();
        }
    };
    timer.start();
}

}

Loop through an array of strings in Bash?

None of those answers include a counter...

#!/bin/bash
## declare an array variable
declare -a array=("one" "two" "three")

# get length of an array
arraylength=${#array[@]}

# use for loop to read all values and indexes
for (( i=1; i<${arraylength}+1; i++ ));
do
  echo $i " / " ${arraylength} " : " ${array[$i-1]}
done

Output:

1  /  3  :  one
2  /  3  :  two
3  /  3  :  three

How to use multiple conditions (With AND) in IIF expressions in ssrs

Could you try this out?

=IIF((Fields!OpeningStock.Value=0) AND (Fields!GrossDispatched.Value=0) AND 
(Fields!TransferOutToMW.Value=0) AND (Fields!TransferOutToDW.Value=0) AND 
(Fields!TransferOutToOW.Value=0) AND (Fields!NetDispatched.Value=0) AND (Fields!QtySold.Value=0) 
AND (Fields!StockAdjustment.Value=0) AND (Fields!ClosingStock.Value=0),True,False)

Note: Setting Hidden to False will make the row visible

Double quotes within php script echo

if you need to access your variables for an echo statement within your quotes put your variable inside curly brackets

echo "i need to open my lock with its: {$array['key']}";

How to fix curl: (60) SSL certificate: Invalid certificate chain

Another cause of this can be duplicate keys in your KeyChain. I've seen this problem on two macs where there were duplicate "DigiCert High Assurance EV Root CA". One was in the login keychain, the other in the system one. Removing the certificate from the login keychain solved the problem.

This affected Safari browser as well as git on the command line.

How to include (source) R script in other scripts

Here is a function I wrote. It wraps the base::source function to store a list of sourced files in a global environment list named sourced. It will only re-source a file if you provide a .force=TRUE argument to the call to source. Its argument signature is otherwise identical to the real source() so you don't need to rewrite your scripts to use this.

warning("overriding source with my own function FYI")
source <- function(path, .force=FALSE, ...) {
  library(tools)
  path <- tryCatch(normalizePath(path), error=function(e) path)
  m<-md5sum(path)

  go<-TRUE
  if (!is.vector(.GlobalEnv$sourced)) {
    .GlobalEnv$sourced <- list()
  }
  if(! is.null(.GlobalEnv$sourced[[path]])) {
    if(m == .GlobalEnv$sourced[[path]]) {
      message(sprintf("Not re-sourcing %s. Override with:\n  source('%s', .force=TRUE)", path, path))
      go<-FALSE
    }
    else {
      message(sprintf('re-sourcing %s as it has changed from: %s to: %s', path, .GlobalEnv$sourced[[path]], m))
      go<-TRUE
    }
  } 
  if(.force) {
    go<-TRUE
    message("  ...forcing.")
  }
  if(go) {
    message(sprintf("sourcing %s", path))
    .GlobalEnv$sourced[path] <- m
    base::source(path, ...)
  }
}

It's pretty chatty (lots of calls to message()) so you can take those lines out if you care. Any advice from veteran R users is appreciated; I'm pretty new to R.

MVC pattern on Android

There is not an implemented MVC architecture, but a set of libraries / examples exists to implement an MVP (model–view–presenter) architecture.

Please, check these links:

Google added an example of an Android architecture MVP:

Start ssh-agent on login

Tried couple solutions from many sources but all seemed like too much trouble. Finally I found the easiest one :)

If you're not yet familiar with zsh and oh-my-zsh then install it. You will love it :)

Then edit .zshrc

vim ~/.zshrc

find plugins section and update it to use ssh-agent like so:

plugins=(ssh-agent git)

And that's all! You'll have ssh-agent up and running every time you start your shell

Error using eclipse for Android - No resource found that matches the given name

I actually has this problem once with a path issue referring another project :

I had this in my default.properties:

android.library.reference.1=..\\MyProject_Core\\

Which I fixed like this:

android.library.reference.1=../MyProject_Core/

My colleague created the above with Windows but only the version below worked on my Mac.

Does C# have extension properties?

Because I recently needed this, I looked at the source of the answer in:

c# extend class by adding properties

and created a more dynamic version:

public static class ObjectExtenders
{
    static readonly ConditionalWeakTable<object, List<stringObject>> Flags = new ConditionalWeakTable<object, List<stringObject>>();

    public static string GetFlags(this object objectItem, string key)
    {
        return Flags.GetOrCreateValue(objectItem).Single(x => x.Key == key).Value;
    }

    public static void SetFlags(this object objectItem, string key, string value)
    {
        if (Flags.GetOrCreateValue(objectItem).Any(x => x.Key == key))
        {
            Flags.GetOrCreateValue(objectItem).Single(x => x.Key == key).Value = value;
        }
        else
        {
            Flags.GetOrCreateValue(objectItem).Add(new stringObject()
            {
                Key = key,
                Value = value
            });
        }
    }

    class stringObject
    {
        public string Key;
        public string Value;
    }
}

It can probably be improved a lot (naming, dynamic instead of string), I currently use this in CF 3.5 together with a hacky ConditionalWeakTable (https://gist.github.com/Jan-WillemdeBruyn/db79dd6fdef7b9845e217958db98c4d4)

Convert objective-c typedef to its string equivalent

I like the #define way of doing this:

// Place this in your .h file, outside the @interface block

typedef enum {
    JPG,
    PNG,
    GIF,
    PVR
} kImageType;
#define kImageTypeArray @"JPEG", @"PNG", @"GIF", @"PowerVR", nil

// Place this in the .m file, inside the @implementation block
// A method to convert an enum to string
-(NSString*) imageTypeEnumToString:(kImageType)enumVal
{
    NSArray *imageTypeArray = [[NSArray alloc] initWithObjects:kImageTypeArray];
    return [imageTypeArray objectAtIndex:enumVal];
}

source (source no longer available)

Spring MVC: difference between <context:component-scan> and <annotation-driven /> tags?

<mvc:annotation-driven /> means that you can define spring beans dependencies without actually having to specify a bunch of elements in XML or implement an interface or extend a base class. For example @Repository to tell spring that a class is a Dao without having to extend JpaDaoSupport or some other subclass of DaoSupport. Similarly @Controller tells spring that the class specified contains methods that will handle Http requests without you having to implement the Controller interface or extend a subclass that implements the controller.

When spring starts up it reads its XML configuration file and looks for <bean elements within it if it sees something like <bean class="com.example.Foo" /> and Foo was marked up with @Controller it knows that the class is a controller and treats it as such. By default, Spring assumes that all the classes it should manage are explicitly defined in the beans.XML file.

Component scanning with <context:component-scan base-package="com.mycompany.maventestwebapp" /> is telling spring that it should search the classpath for all the classes under com.mycompany.maventestweapp and look at each class to see if it has a @Controller, or @Repository, or @Service, or @Component and if it does then Spring will register the class with the bean factory as if you had typed <bean class="..." /> in the XML configuration files.

In a typical spring MVC app you will find that there are two spring configuration files, a file that configures the application context usually started with the Spring context listener.

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

And a Spring MVC configuration file usually started with the Spring dispatcher servlet. For example.

<servlet>
        <servlet-name>main</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>main</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

Spring has support for hierarchical bean factories, so in the case of the Spring MVC, the dispatcher servlet context is a child of the main application context. If the servlet context was asked for a bean called "abc" it will look in the servlet context first, if it does not find it there it will look in the parent context, which is the application context.

Common beans such as data sources, JPA configuration, business services are defined in the application context while MVC specific configuration goes not the configuration file associated with the servlet.

Hope this helps.

Using floats with sprintf() in embedded C

Yes, and no. Despite what some other replies have said, the C compiler is required to perform conversions for sprintf(), and all other variadic functions, as follows:

  • char => int
  • short => int
  • float => double

(and signed/unsigned variants of the above integral types)

It does this precisely because sprintf() (and the other print()-family functions) would be unusable without it. (Of course, they're pretty unusable as it is.)

But you cannot assume any other conversions, and your code will have undefined behaviour - read: crash! - if you do it.

What is the LD_PRELOAD trick?

As many people mentioned, using LD_PRELOAD to preload library. BTW, you can CHECK if the setting is available by ldd command.

Example: suppose you need to preload your own libselinux.so.1.

> ldd /bin/ls
    ...
    libselinux.so.1 => /lib/x86_64-linux-gnu/libselinux.so.1 (0x00007f3927b1d000)
    libacl.so.1 => /lib/x86_64-linux-gnu/libacl.so.1 (0x00007f3927914000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f392754f000)
    libpcre.so.3 => /lib/x86_64-linux-gnu/libpcre.so.3 (0x00007f3927311000)
    libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f392710c000)
    /lib64/ld-linux-x86-64.so.2 (0x00007f3927d65000)
    libattr.so.1 => /lib/x86_64-linux-gnu/libattr.so.1 (0x00007f3926f07000)

Thus, set your preload environment:

  export LD_PRELOAD=/home/patric/libselinux.so.1

Check your library again:

>ldd /bin/ls
    ...
    libselinux.so.1 =>
    /home/patric/libselinux.so.1 (0x00007fb9245d8000)
    ...

Faking an RS232 Serial Port

I use com0com - With Signed Driver, on windows 7 x64 to emulate COM3 AND COM4 as a pair.

Then i use COM Dataport Emulator to recieve from COM4.

Then i open COM3 with the app im developping (c#) and send data to COM3.

The data sent thru COM3 is received by COM4 and shown by 'COM Dataport Emulator' who can also send back a response (not automated).

So with this 2 great programs i managed to emulate Serial RS-232 comunication.

Hope it helps.

Both programs are free!!!!!

Putting -moz-available and -webkit-fill-available in one width (css property)

CSS will skip over style declarations it doesn't understand. Mozilla-based browsers will not understand -webkit-prefixed declarations, and WebKit-based browsers will not understand -moz-prefixed declarations.

Because of this, we can simply declare width twice:

elem {
    width: 100%;
    width: -moz-available;          /* WebKit-based browsers will ignore this. */
    width: -webkit-fill-available;  /* Mozilla-based browsers will ignore this. */
    width: fill-available;
}

The width: 100% declared at the start will be used by browsers which ignore both the -moz and -webkit-prefixed declarations or do not support -moz-available or -webkit-fill-available.

How to add "Maven Managed Dependencies" library in build path eclipse?

Likely quite simple but best way is to edit manually the file .classpath at the root of your project folder with something like

<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
        <attributes>
            <attribute name="maven.pomderived" value="true"/>
            <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
        </attributes>
    </classpathentry>

when you want to have jar in your WEB-IN/lib folder (case for a web app)

Asp.Net WebApi2 Enable CORS not working with AspNet.WebApi.Cors 5.2.3

Hope this helps someone in the future. My problem was that I was following the same tutorial as the OP to enable global CORS. However, I also set an Action specific CORS rule in my AccountController.cs file:

[EnableCors(origins: "", headers: "*", methods: "*")]

and was getting errors about the origin cannot be null or empty string. BUT the error was happening in the Global.asax.cs file of all places. Solution is to change it to:

[EnableCors(origins: "*", headers: "*", methods: "*")]

notice the * in the origins? Missing that was what was causing the error in the Global.asax.cs file.

Hope this helps someone.

javax.xml.bind.UnmarshalException: unexpected element. Expected elements are (none)

One of the reasons for this error is the use of the jaxb implementation from the jdk. I am not sure why such a problem can appear in pretty simple xml parsing situations. You may use the latest version of the jaxb library from a public maven repository:

http://mvnrepository.com

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.2.12</version>
</dependency>

How to add Android Support Repository to Android Studio?

You are probably hit by this bug which prevents the Android Gradle Plugin from automatically adding the "Android Support Repository" to the list of Gradle repositories. The work-around, as mentioned in the bug report, is to explicitly add the m2repository directory as a local Maven directory in the top-level build.gradle file as follows:

allprojects {
    repositories {
        // Work around https://code.google.com/p/android/issues/detail?id=69270.
        def androidHome = System.getenv("ANDROID_HOME")
        maven {
            url "$androidHome/extras/android/m2repository/"
        }
    }
}

File.Move Does Not Work - File Already Exists

If you don't have the option to delete the already existing file in the new location, but still need to move and delete from the original location, this renaming trick might work:

string newFileLocation = @"c:\test\Test\SomeFile.txt";

while (File.Exists(newFileLocation)) {
    newFileLocation = newFileLocation.Split('.')[0] + "_copy." + newFileLocation.Split('.')[1];
}
File.Move(@"c:\test\SomeFile.txt", newFileLocation);

This assumes the only '.' in the file name is before the extension. It splits the file in two before the extension, attaches "_copy." in between. This lets you move the file, but creates a copy if the file already exists or a copy of the copy already exists, or a copy of the copy of the copy exists... ;)

Opposite of append in jquery

Use the remove() method:

$(this).children("ul").remove();

How to use RecyclerView inside NestedScrollView?

nestedScrollView.setNestedScrollingEnabled(true);

mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            //...
        }
    });


<androidx.core.widget.NestedScrollView
    android:id="@+id/nested"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true"
    android:layout_below="@id/appBarLayout_orders"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"> 

    <androidx.constraintlayout.widget.ConstraintLayout ...

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recycler"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"/>

Has anyone ever got a remote JMX JConsole to work?

You need to also make sure that your machine name resolves to the IP that JMX is binding to; NOT localhost nor 127.0.0.1. For me, it has helped to put an entry into hosts that explicitly defines this.

How do I reverse a C++ vector?

Often the reason you want to reverse the vector is because you fill it by pushing all the items on at the end but were actually receiving them in reverse order. In that case you can reverse the container as you go by using a deque instead and pushing them directly on the front. (Or you could insert the items at the front with vector::insert() instead, but that would be slow when there are lots of items because it has to shuffle all the other items along for every insertion.) So as opposed to:

std::vector<int> foo;
int nextItem;
while (getNext(nextItem)) {
    foo.push_back(nextItem);
}
std::reverse(foo.begin(), foo.end());

You can instead do:

std::deque<int> foo;
int nextItem;
while (getNext(nextItem)) {
    foo.push_front(nextItem);
}
// No reverse needed - already in correct order

How to store a large (10 digits) integer?

A wrapper class java.lang.Long can store 10 digit easily.

   Long phoneNumber = 1234567890;

It can store more than that also.

Documentation:

public final class Long extends Number implements Comparable<Long> {
    /**
     * A constant holding the minimum value a {@code long} can
     * have, -2<sup>63</sup>.
     */
    @Native public static final long MIN_VALUE = 0x8000000000000000L;

    /**
     * A constant holding the maximum value a {@code long} can
     * have, 2<sup>63</sup>-1.
     */
    @Native public static final long MAX_VALUE = 0x7fffffffffffffffL;
}

This means it can store values of range 9,223,372,036,854,775,807 to -9,223,372,036,854,775,808.

Best way to work with dates in Android SQLite

SQLite can use text, real, or integer data types to store dates. Even more, whenever you perform a query, the results are shown using format %Y-%m-%d %H:%M:%S.

Now, if you insert/update date/time values using SQLite date/time functions, you can actually store milliseconds as well. If that's the case, the results are shown using format %Y-%m-%d %H:%M:%f. For example:

sqlite> create table test_table(col1 text, col2 real, col3 integer);
sqlite> insert into test_table values (
            strftime('%Y-%m-%d %H:%M:%f', '2014-03-01 13:01:01.123'),
            strftime('%Y-%m-%d %H:%M:%f', '2014-03-01 13:01:01.123'),
            strftime('%Y-%m-%d %H:%M:%f', '2014-03-01 13:01:01.123')
        );
sqlite> insert into test_table values (
            strftime('%Y-%m-%d %H:%M:%f', '2014-03-01 13:01:01.126'),
            strftime('%Y-%m-%d %H:%M:%f', '2014-03-01 13:01:01.126'),
            strftime('%Y-%m-%d %H:%M:%f', '2014-03-01 13:01:01.126')
        );
sqlite> select * from test_table;
2014-03-01 13:01:01.123|2014-03-01 13:01:01.123|2014-03-01 13:01:01.123
2014-03-01 13:01:01.126|2014-03-01 13:01:01.126|2014-03-01 13:01:01.126

Now, doing some queries to verify if we are actually able to compare times:

sqlite> select * from test_table /* using col1 */
           where col1 between 
               strftime('%Y-%m-%d %H:%M:%f', '2014-03-01 13:01:01.121') and
               strftime('%Y-%m-%d %H:%M:%f', '2014-03-01 13:01:01.125');
2014-03-01 13:01:01.123|2014-03-01 13:01:01.123|2014-03-01 13:01:01.123

You can check the same SELECT using col2 and col3 and you will get the same results. As you can see, the second row (126 milliseconds) is not returned.

Note that BETWEEN is inclusive, therefore...

sqlite> select * from test_table 
            where col1 between 
                 /* Note that we are using 123 milliseconds down _here_ */
                strftime('%Y-%m-%d %H:%M:%f', '2014-03-01 13:01:01.123') and
                strftime('%Y-%m-%d %H:%M:%f', '2014-03-01 13:01:01.125');

... will return the same set.

Try playing around with different date/time ranges and everything will behave as expected.

What about without strftime function?

sqlite> select * from test_table /* using col1 */
           where col1 between 
               '2014-03-01 13:01:01.121' and
               '2014-03-01 13:01:01.125';
2014-03-01 13:01:01.123|2014-03-01 13:01:01.123|2014-03-01 13:01:01.123

What about without strftime function and no milliseconds?

sqlite> select * from test_table /* using col1 */
           where col1 between 
               '2014-03-01 13:01:01' and
               '2014-03-01 13:01:02';
2014-03-01 13:01:01.123|2014-03-01 13:01:01.123|2014-03-01 13:01:01.123
2014-03-01 13:01:01.126|2014-03-01 13:01:01.126|2014-03-01 13:01:01.126

What about ORDER BY?

sqlite> select * from test_table order by 1 desc;
2014-03-01 13:01:01.126|2014-03-01 13:01:01.126|2014-03-01 13:01:01.126
2014-03-01 13:01:01.123|2014-03-01 13:01:01.123|2014-03-01 13:01:01.123
sqlite> select * from test_table order by 1 asc;
2014-03-01 13:01:01.123|2014-03-01 13:01:01.123|2014-03-01 13:01:01.123
2014-03-01 13:01:01.126|2014-03-01 13:01:01.126|2014-03-01 13:01:01.126

Works just fine.

Finally, when dealing with actual operations within a program (without using the sqlite executable...)

BTW: I'm using JDBC (not sure about other languages)... the sqlite-jdbc driver v3.7.2 from xerial - maybe newer revisions change the behavior explained below... If you are developing in Android, you don't need a jdbc-driver. All SQL operations can be submitted using the SQLiteOpenHelper.

JDBC has different methods to get actual date/time values from a database: java.sql.Date, java.sql.Time, and java.sql.Timestamp.

The related methods in java.sql.ResultSet are (obviously) getDate(..), getTime(..), and getTimestamp() respectively.

For example:

Statement stmt = ... // Get statement from connection
ResultSet rs = stmt.executeQuery("SELECT * FROM TEST_TABLE");
while (rs.next()) {
    System.out.println("COL1 : "+rs.getDate("COL1"));
    System.out.println("COL1 : "+rs.getTime("COL1"));
    System.out.println("COL1 : "+rs.getTimestamp("COL1"));
    System.out.println("COL2 : "+rs.getDate("COL2"));
    System.out.println("COL2 : "+rs.getTime("COL2"));
    System.out.println("COL2 : "+rs.getTimestamp("COL2"));
    System.out.println("COL3 : "+rs.getDate("COL3"));
    System.out.println("COL3 : "+rs.getTime("COL3"));
    System.out.println("COL3 : "+rs.getTimestamp("COL3"));
}
// close rs and stmt.

Since SQLite doesn't have an actual DATE/TIME/TIMESTAMP data type all these 3 methods return values as if the objects were initialized with 0:

new java.sql.Date(0)
new java.sql.Time(0)
new java.sql.Timestamp(0)

So, the question is: how can we actually select, insert, or update Date/Time/Timestamp objects? There's no easy answer. You can try different combinations, but they will force you to embed SQLite functions in all the SQL statements. It's far easier to define an utility class to transform text to Date objects inside your Java program. But always remember that SQLite transforms any date value to UTC+0000.

In summary, despite the general rule to always use the correct data type, or, even integers denoting Unix time (milliseconds since epoch), I find much easier using the default SQLite format ('%Y-%m-%d %H:%M:%f' or in Java 'yyyy-MM-dd HH:mm:ss.SSS') rather to complicate all your SQL statements with SQLite functions. The former approach is much easier to maintain.

TODO: I will check the results when using getDate/getTime/getTimestamp inside Android (API15 or better)... maybe the internal driver is different from sqlite-jdbc...

UIViewController viewDidLoad vs. viewWillAppear: What is the proper division of labor?

Initially used only ViewDidLoad with tableView. On testing with loss of Wifi, by setting device to airplane mode, realized that the table did not refresh with return of Wifi. In fact, there appears to be no way to refresh tableView on the device even by hitting the home button with background mode set to YES in -Info.plist.

My solution:

-(void) viewWillAppear: (BOOL) animated { [self.tableView reloadData];}

Android Studio : How to uninstall APK (or execute adb command) automatically before Run or Debug?

I am using Android Studio 2.1.2. I had same requirement as OP. Though above two answer seemed to help everyone, it did not work for me . I am sharing what worked for me.

Go to main menu/Run/Edit Configuration . Select app under Android Application on the left.This should open multi-tabbed pane . Select General tab ( would be default), click green + sing at the bottom ( below text Before launch: Gradle -awake ...).

A drop down will appear, select Gradle-aware-make option. Another text box will pop up. enter :app:uninstallAll in this text box . (You can use ctrl + space to use autocomplete todetermine right target without typing everything . And also helps you choose the right app name that is avaiable for you). and set apply/ok. Relaunch your app.

Note : Every time you launch your app now , this new target will try to uninstall your app from your emulator or device. So if your testing device is not available, your launc will probably fail while uninstalling but will continue to start your emulator. So Either start your emulator first, or re-lauch after first fail again ( as first launch will start emulator though uninstall fails).

Generate random string/characters in JavaScript

How about this below... this will produce the really random values:

function getRandomStrings(length) {
  const value = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const randoms = [];
  for(let i=0; i < length; i++) {
     randoms.push(value[Math.floor(Math.random()*value.length)]);
  }
  return randoms.join('');
}

But if you looking for a shorter syntax one in ES6:

const getRandomStrings = length => Math.random().toString(36).substr(-length);

CONVERT Image url to Base64

View this answer: https://stackoverflow.com/a/20285053/5065874 by @HaNdTriX

Basically, he implemented this function:

function toDataUrl(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.onload = function() {
        var reader = new FileReader();
        reader.onloadend = function() {
            callback(reader.result);
        }
        reader.readAsDataURL(xhr.response);
    };
    xhr.open('GET', url);
    xhr.responseType = 'blob';
    xhr.send();
}

And in your case, you can use it like this:

toDataUrl(imagepath, function(myBase64) {
    console.log(myBase64); // myBase64 is the base64 string
});

How to implement endless list with RecyclerView?

@kushal @abdulaziz

Why not use this logic instead?

public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
    int totalItemCount, lastVisibleItemPosition;

    if (dy > 0) {
      totalItemCount = _layoutManager.getItemCount();
      lastVisibleItemPosition = _layoutManager.findLastVisibleItemPosition();

      if (!_isLastItem) {
        if ((totalItemCount - 1) == lastVisibleItemPosition) {
          LogUtil.e("end_of_list");

          _isLastItem = true;
        }
      }
    }
  }

Extracting Nupkg files using command line

NuPKG files are just zip files, so anything that can process a zip file should be able to process a nupkg file, i.e, 7zip.

How much should a function trust another function

Typically this is bad practice. Since it is possible to call addEdge before addNode and have a NullPointerException (NPE) thrown, addEdge should check if the result is null and throw a more descriptive Exception. In my opinion, the only time it is acceptable not to check for nulls is when you expect the result to never be null, in which case, an NPE is plenty descriptive.

Call PHP function from jQuery?

AJAX does the magic:

$(document).ready(function(

    $.ajax({ url: 'script.php?argument=value&foo=bar' });

));

How to make node.js require absolute? (instead of relative)

I like to make a new node_modules folder for shared code, then let node and require do what it does best.

for example:

- node_modules // => these are loaded from your package.json
- app
  - node_modules // => add node-style modules
    - helper.js
  - models
    - user
    - car
- package.json
- .gitignore

For example, if you're in car/index.js you can require('helper') and node will find it!

How node_modules Work

node has a clever algorithm for resolving modules that is unique among rival platforms.

If you require('./foo.js') from /beep/boop/bar.js, node will look for ./foo.js in /beep/boop/foo.js. Paths that start with a ./ or ../ are always local to the file that calls require().

If however you require a non-relative name such as require('xyz') from /beep/boop/foo.js, node searches these paths in order, stopping at the first match and raising an error if nothing is found:

/beep/boop/node_modules/xyz
/beep/node_modules/xyz
/node_modules/xyz

For each xyz directory that exists, node will first look for a xyz/package.json to see if a "main" field exists. The "main" field defines which file should take charge if you require() the directory path.

For example, if /beep/node_modules/xyz is the first match and /beep/node_modules/xyz/package.json has:

{
  "name": "xyz",
  "version": "1.2.3",
  "main": "lib/abc.js"
}

then the exports from /beep/node_modules/xyz/lib/abc.js will be returned by require('xyz').

If there is no package.json or no "main" field, index.js is assumed:

/beep/node_modules/xyz/index.js

How to clear cache in Yarn?

Run yarn cache clean.


Run yarn help cache in your bash, and you will see:

Usage: yarn cache [ls|clean] [flags]

Options: -h, --help output usage information -V, --version output the version number --offline
--prefer-offline
--strict-semver
--json
--global-folder [path]
--modules-folder [path] rather than installing modules into the node_modules folder relative to the cwd, output them here
--packages-root [path] rather than storing modules into a global packages root, store them here
--mutex [type][:specifier] use a mutex to ensure only one yarn instance is executing

Visit http://yarnpkg.com/en/docs/cli/cache for documentation about this command.

Safe String to BigDecimal conversion

Here is how I would do it:

public String cleanDecimalString(String input, boolean americanFormat) {
    if (americanFormat)
        return input.replaceAll(",", "");
    else
        return input.replaceAll(".", "");
}

Obviously, if this were going in production code, it wouldn't be that simple.

I see no issue with simply removing the commas from the String.

Difference between logical addresses, and physical addresses?

A logical address is the address at which an item (memory cell, storage element, network host) appears to reside from the perspective of an executing application program.

MySQL Workbench - Connect to a Localhost

Sounds like you only installed the MySQL Client Tools (MySQL Workbench). You have to install the MySQL Database server, configure and start it.

http://dev.mysql.com/downloads/

You probably want the MySQL Community Server download.

What is the best way to insert source code examples into a Microsoft Word document?

I absolutely hate and despise working for free for Microsoft, given how after all those billions of dollars they STILL do not to have proper guides about stuff like this with screenshots on their damn website.

Anyways, here is a quick guide in Word 2010, using Notepad++ for syntax coloring, and a TextBox which can be captioned:

  1. Choose Insert / Text Box / Simple Text Box
    01word
  2. A default text box is inserted
    02word
  3. Switch to NPP, choose the language for syntax coloring of your code, go to Plugins / NPPExport / Copy RTF to clipboard
    03npp
  4. Switch back to word, and paste into the text box - it may be too small ...
    04word
  5. ... so you may have to change its size
    05word
  6. Having selected the text box, right-click on it, then choose Insert Caption ...
    06word
  7. In the Caption menu, if you don't have one already, click New Label, and set the new label to "Code", click OK ...
    07word
  8. ... then in the Caption dialog, switch the label to Code, and hit OK
    08word
  9. Finally, type your caption in the newly created caption box
    09word

How to pass parameters to ThreadStart method in Thread?

here is the perfect way...

private void func_trd(String sender)
{

    try
    {
        imgh.LoadImages_R_Randomiz(this, "01", groupBox, randomizerB.Value); // normal code

        ThreadStart ts = delegate
        {
            ExecuteInForeground(sender);
        };

        Thread nt = new Thread(ts);
        nt.IsBackground = true;

        nt.Start();

    }
    catch (Exception)
    {

    }
}

private void ExecuteInForeground(string name)
{
     //whatever ur function
    MessageBox.Show(name);
}

How to get number of rows using SqlDataReader in C#

to complete of Pit answer and for better perfromance : get all in one query and use NextResult method.

using (var sqlCon = new SqlConnection("Server=127.0.0.1;Database=MyDb;User Id=Me;Password=glop;"))
{
    sqlCon.Open();
    var com = sqlCon.CreateCommand();
    com.CommandText = "select * from BigTable;select @@ROWCOUNT;";
    using (var reader = com.ExecuteReader())
    {
        while(reader.read()){
            //iterate code
        }
        int totalRow = 0 ;
        reader.NextResult(); // 
        if(reader.read()){
            totalRow = (int)reader[0];
        }
    }
    sqlCon.Close();
}

Python and pip, list all versions of a package that's available?

You can use this small Python 3 script (using only standard library modules) to grab the list of available versions for a package from PyPI using JSON API and print them in reverse chronological order. Unlike some other Python solutions posted here, this doesn't break on loose versions like django's 2.2rc1 or uwsgi's 2.0.17.1:

#!/usr/bin/env python3

import json
import sys
from urllib import request    
from pkg_resources import parse_version    

def versions(pkg_name):
    url = f'https://pypi.python.org/pypi/{pkg_name}/json'
    releases = json.loads(request.urlopen(url).read())['releases']
    return sorted(releases, key=parse_version, reverse=True)    

if __name__ == '__main__':
    print(*versions(sys.argv[1]), sep='\n')

Save the script and run it with the package name as an argument, e.g.:

python versions.py django
3.0a1
2.2.5
2.2.4
2.2.3
2.2.2
2.2.1
2.2
2.2rc1
...

jquery loop on Json data using $.each

Have you converted your data from string to JavaScript object?

You can do it with data = eval('(' + string_data + ')'); or, which is safer, data = JSON.parse(string_data); but later will only works in FF 3.5 or if you include json2.js

jQuery since 1.4.1 also have function for that, $.parseJSON().

But actually, $.getJSON() should give you already parsed json object, so you should just check everything thoroughly, there is little mistake buried somewhere, like you might have forgotten to quote something in json, or one of the brackets is missing.

How to convert int[] into List<Integer> in Java?

Also from guava libraries... com.google.common.primitives.Ints:

List<Integer> Ints.asList(int...)

Writing a new line to file in PHP (line feed)

PHP_EOL is a predefined constant in PHP since PHP 4.3.10 and PHP 5.0.2. See the manual posting:

Using this will save you extra coding on cross platform developments.

IE.

$data = 'some data'.PHP_EOL;
$fp = fopen('somefile', 'a');
fwrite($fp, $data);

If you looped through this twice you would see in 'somefile':

some data
some data

Prevent redirect after form is submitted

Using Ajax

Using the jQuery Ajax request method you can post the email data to a script (submit.php). Using the success callback option to animate elements after the script is executed.

note - I would suggest utilizing the ajax Response Object to make sure the script executed successfully.

$(function() {
    $('.submit').click(function() {
        $.ajax({
            type: 'POST',
            url: 'submit.php',
            data: 'password=p4ssw0rt',
            error: function()
            {
               alert("Request Failed");
            },
            success: function(response)
            {  
               //EXECUTE ANIMATION HERE
            } // this was missing
        });
        return false;
    }); 
})

How to print the ld(linker) search path

Mac version: $ ld -v 2, don't know how to get detailed paths. output

Library search paths:
    /usr/lib
    /usr/local/lib
Framework search paths:
    /Library/Frameworks/
    /System/Library/Frameworks/

How do you serialize a model instance in Django?

.values() is what I needed to convert a model instance to JSON.

.values() documentation: https://docs.djangoproject.com/en/3.0/ref/models/querysets/#values

Example usage with a model called Project.

Note: I'm using Django Rest Framework

    @csrf_exempt
    @api_view(["GET"])
    def get_project(request):
        id = request.query_params['id']
        data = Project.objects.filter(id=id).values()
        if len(data) == 0:
            return JsonResponse(status=404, data={'message': 'Project with id {} not found.'.format(id)})
        return JsonResponse(data[0])

Result from a valid id:

{
    "id": 47,
    "title": "Project Name",
    "description": "",
    "created_at": "2020-01-21T18:13:49.693Z",
}

How can I detect if this dictionary key exists in C#?

I use a Dictionary and because of the repetetiveness and possible missing keys, I quickly patched together a small method:

 private static string GetKey(IReadOnlyDictionary<string, string> dictValues, string keyValue)
 {
     return dictValues.ContainsKey(keyValue) ? dictValues[keyValue] : "";
 }

Calling it:

var entry = GetKey(dictList,"KeyValue1");

Gets the job done.