Programs & Examples On #Has one

How to upgrade docker-compose to latest version

If you have homebrew you can also install via brew

$ brew install docker-compose

This is a good way to install on a Mac OS system

Jquery, checking if a value exists in array or not

    if ($.inArray('yourElement', yourArray) > -1)
    {
        //yourElement in yourArray
        //code here

    }

Reference: Jquery Array

The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0.

How to pass data from 2nd activity to 1st activity when pressed back? - android

From your FirstActivity call the SecondActivity using startActivityForResult() method.

For example:

Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);

In your SecondActivity set the data which you want to return back to FirstActivity. If you don't want to return back, don't set any.

For example: In secondActivity if you want to send back data:

Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(Activity.RESULT_OK,returnIntent);
finish();

If you don't want to return data:

Intent returnIntent = new Intent();
setResult(Activity.RESULT_CANCELED, returnIntent);
finish();

Now in your FirstActivity class write following code for the onActivityResult() method.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1) {
        if(resultCode == Activity.RESULT_OK){
            String result=data.getStringExtra("result");
        }
        if (resultCode == Activity.RESULT_CANCELED) {
            //Write your code if there's no result
        }
    }
}

Convert nullable bool? to bool

bool? a = null;
bool b = Convert.toBoolean(a); 

How to update/refresh specific item in RecyclerView

if you are creating one object and adding it to the list that you use in your adapter , when you change one element of your list in the adapter all of your other items change too in other words its all about references and your list doesn't hold separate copies of that single object.

Parsing a CSV file using NodeJS

The node-csv project that you are referencing is completely sufficient for the task of transforming each row of a large portion of CSV data, from the docs at: http://csv.adaltas.com/transform/:

csv()
  .from('82,Preisner,Zbigniew\n94,Gainsbourg,Serge')
  .to(console.log)
  .transform(function(row, index, callback){
    process.nextTick(function(){
      callback(null, row.reverse());
    });
});

From my experience, I can say that it is also a rather fast implementation, I have been working with it on data sets with near 10k records and the processing times were at a reasonable tens-of-milliseconds level for the whole set.

Rearding jurka's stream based solution suggestion: node-csv IS stream based and follows the Node.js' streaming API.

How to query data out of the box using Spring data JPA by both Sort and Pageable?

There are two ways to achieve this:

final PageRequest page1 = new PageRequest(
  0, 20, Direction.ASC, "lastName", "salary"
);

final PageRequest page2 = new PageRequest(
  0, 20, new Sort(
    new Order(Direction.ASC, "lastName"), 
    new Order(Direction.DESC, "salary")
  )
);

dao.findAll(page1);

As you can see the second form is more flexible as it allows to define different direction for every property (lastName ASC, salary DESC).

Two-dimensional array in Swift

From the docs:

You can create multidimensional arrays by nesting pairs of square brackets, where the name of the base type of the elements is contained in the innermost pair of square brackets. For example, you can create a three-dimensional array of integers using three sets of square brackets:

var array3D: [[[Int]]] = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]

When accessing the elements in a multidimensional array, the left-most subscript index refers to the element at that index in the outermost array. The next subscript index to the right refers to the element at that index in the array that’s nested one level in. And so on. This means that in the example above, array3D[0] refers to [[1, 2], [3, 4]], array3D[0][1] refers to [3, 4], and array3D[0][1][1] refers to the value 4.

Using PHP with Socket.io

If you want to use socket.io together with php this may be your answer!

project website:

elephant.io

they are also on github:

https://github.com/wisembly/elephant.io

Elephant.io provides a socket.io client fully written in PHP that should be usable everywhere in your project.

It is a light and easy to use library that aims to bring some real-time functionality to a PHP application through socket.io and websockets for actions that could not be done in full javascript.

example from the project website (communicate with websocket server through php)

php server

use ElephantIO\Client as Elephant;

$elephant = new Elephant('http://localhost:8000', 'socket.io', 1, false, true, true);

$elephant->init();
$elephant->send(
    ElephantIOClient::TYPE_EVENT,
    null,
    null,
    json_encode(array('name' => 'foo', 'args' => 'bar'))
);
$elephant->close();

echo 'tryin to send `bar` to the event `foo`';

socket io server

var io = require('socket.io').listen(8000);

io.sockets.on('connection', function (socket) {
  console.log('user connected!');

  socket.on('foo', function (data) {
    console.log('here we are in action event and data is: ' + data);
  });
});

Java, How do I get current index/key in "for each" loop

###################################################
###################################################
###################################################
AVOID THIS
###################################################
###################################################
###################################################

/*for (Song s: songList){
    System.out.println(s + "," + songList.indexOf(s); 
}*/

it is possible in linked list.

you have to make toString() in song class. if you don't it will print out reference of the song.

probably irrelevant for you by now. ^_^

Why use String.Format?

One reason it is not preferable to write the string like 'string +"Value"+ string' is because of Localization. In cases where localization is occurring we want the localized string to be correctly formatted, which could be very different from the language being coded in.

For example we need to show the following error in different languages:

MessageBox.Show(String.Format(ErrorManager.GetError("PIDV001").Description, proposalvalue.ProposalSource)

where

'ErrorCollector.GetError("ERR001").ErrorDescription' returns a string like "Your ID {0} is not valid". This message must be localized in many languages. In that case we can't use + in C#. We need to follow string.format.

In Perl, how to remove ^M from a file?

In vi hit :.

Then s/Control-VControl-M//g.

Control-V Control-M are obviously those keys. Don't spell it out.

How to edit log message already committed in Subversion?

When you run this command,

svn propedit svn:log --revprop -r NNN 

and just in case you see this message:

DAV request failed; it's possible that the repository's pre-revprop-change hook either failed or is non-existent

Its because Subversion doesn’t allow you to modify log messages because they are unversioned and will be lost permanently.

Unix-hosted SVN

Go to the hooks directory on your Subversion server (replace ~/svn/reponame with the directory of your repository)

cd ~/svn/reponame/hooks

Remove the extension

mv pre-revprop-change.tmpl pre-revprop-change

Make it executable (cannot do chmod +x!)

chmod 755 pre-revprop-change

Source

Windows-hosted SVN

The template files in the hooks directory cannot be used as they are Unix-specific. You need to copy a Windows batch file pre-revprop-change.bat to the hooks directory, e.g. the one provided here.

How to 'insert if not exists' in MySQL?

Here is a PHP function that will insert a row only if all the specified columns values don't already exist in the table.

  • If one of the columns differ, the row will be added.

  • If the table is empty, the row will be added.

  • If a row exists where all the specified columns have the specified values, the row won't be added.

    function insert_unique($table, $vars)
    {
      if (count($vars)) {
        $table = mysql_real_escape_string($table);
        $vars = array_map('mysql_real_escape_string', $vars);
    
        $req = "INSERT INTO `$table` (`". join('`, `', array_keys($vars)) ."`) ";
        $req .= "SELECT '". join("', '", $vars) ."' FROM DUAL ";
        $req .= "WHERE NOT EXISTS (SELECT 1 FROM `$table` WHERE ";
    
        foreach ($vars AS $col => $val)
          $req .= "`$col`='$val' AND ";
    
        $req = substr($req, 0, -5) . ") LIMIT 1";
    
        $res = mysql_query($req) OR die();
        return mysql_insert_id();
      }
    
      return False;
    }
    

Example usage :

<?php
insert_unique('mytable', array(
  'mycolumn1' => 'myvalue1',
  'mycolumn2' => 'myvalue2',
  'mycolumn3' => 'myvalue3'
  )
);
?>

How to send a message to a particular client with socket.io

You can refer to socket.io rooms. When you handshaked socket - you can join him to named room, for instance "user.#{userid}".

After that, you can send private message to any client by convenient name, for instance:

io.sockets.in('user.125').emit('new_message', {text: "Hello world"})

In operation above we send "new_message" to user "125".

thanks.

Difference between `Optional.orElse()` and `Optional.orElseGet()`

Take these two scenarios:

Optional<Foo> opt = ...
Foo x = opt.orElse( new Foo() );
Foo y = opt.orElseGet( Foo::new );

If opt doesn't contain a value, the two are indeed equivalent. But if opt does contain a value, how many Foo objects will be created?

P.s.: of course in this example the difference probably wouldn't be measurable, but if you have to obtain your default value from a remote web service for example, or from a database, it suddenly becomes very important.

How to enable Google Play App Signing

This guide is oriented to developers who already have an application in the Play Store. If you are starting with a new app the process it's much easier and you can follow the guidelines of paragraph "New apps" from here

Prerequisites that 99% of developers already have :

  1. Android Studio

  2. JDK 8 and after installation you need to setup an environment variable in your user space to simplify terminal commands. In Windows x64 you need to add this : C:\Program Files\Java\{JDK_VERSION}\bin to the Path environment variable. (If you don't know how to do this you can read my guide to add a folder to the Windows 10 Path environment variable).

Step 0: Open Google Play developer console, then go to Release Management -> App Signing.

enter image description here

Accept the App Signing TOS.

enter image description here

Step 1: Download PEPK Tool clicking the button identical to the image below

enter image description here

Step 2: Open a terminal and type:

java -jar PATH_TO_PEPK --keystore=PATH_TO_KEYSTORE --alias=ALIAS_YOU_USE_TO_SIGN_APK --output=PATH_TO_OUTPUT_FILE --encryptionkey=GOOGLE_ENCRYPTION_KEY

Legend:

  • PATH_TO_PEPK = Path to the pepk.jar you downloaded in Step 1, could be something like C:\Users\YourName\Downloads\pepk.jar for Windows users.
  • PATH_TO_KEYSTORE = Path to keystore which you use to sign your release APK. Could be a file of type *.keystore or *.jks or without extension. Something like C:\Android\mykeystore or C:\Android\mykeystore.keystore etc...
  • ALIAS_YOU_USE_TO_SIGN_APK = The name of the alias you use to sign the release APK.
  • PATH_TO_OUTPUT_FILE = The path of the output file with .pem extension, something like C:\Android\private_key.pem
  • GOOGLE_ENCRYPTION_KEY = This encryption key should be always the same. You can find it in the App Signing page, copy and paste it. Should be in this form: eb10fe8f7c7c9df715022017b00c6471f8ba8170b13049a11e6c09ffe3056a104a3bbe4ac5a955f4ba4fe93fc8cef27558a3eb9d2a529a2092761fb833b656cd48b9de6a

Example:

java -jar "C:\Users\YourName\Downloads\pepk.jar" --keystore="C:\Android\mykeystore" --alias=myalias --output="C:\Android\private_key.pem" --encryptionkey=eb10fe8f7c7c9df715022017b00c6471f8ba8170b13049a11e6c09ffe3056a104a3bbe4ac5a955f4ba4fe93fc8cef27558a3eb9d2a529a2092761fb833b656cd48b9de6a

Press Enter and you will need to provide in order:

  1. The keystore password
  2. The alias password

If everything has gone OK, you now will have a file in PATH_TO_OUTPUT_FILE folder called private_key.pem.

Step 3: Upload the private_key.pem file clicking the button identical to the image below

enter image description here

Step 4: Create a new keystore file using Android Studio.

YOU WILL NEED THIS KEYSTORE IN THE FUTURE TO SIGN THE NEXT RELEASES OF YOUR APP, DON'T FORGET THE PASSWORDS

Open one of your Android projects (choose one at random). Go to Build -> Generate Signed APK and press Create new.

enter image description here

Now you should fill the required fields.

Key store path represent the new keystore you will create, choose a folder and a name using the 3 dots icon on the right, i choosed C:\Android\upload_key.jks (.jks extension will be added automatically)

NOTE: I used upload as the new alias name but if you previously used the same keystore with different aliases to sign different apps, you should choose the same aliases name you had previously in the original keystore.

enter image description here

Press OK when finished, and now you will have a new upload_key.jks keystore. You can close Android Studio now.

Step 5: We need to extract the upload certificate from the newly created upload_key.jks keystore. Open a terminal and type:

keytool -export -rfc -keystore UPLOAD_KEYSTORE_PATH -alias UPLOAD_KEYSTORE_ALIAS -file PATH_TO_OUTPUT_FILE

Legend:

  • UPLOAD_KEYSTORE_PATH = The path of the upload keystore you just created. In this case was C:\Android\upload_key.jks.
  • UPLOAD_KEYSTORE_ALIAS = The new alias associated with the upload keystore. In this case was upload.
  • PATH_TO_OUTPUT_FILE = The path to the output file with .pem extension. Something like C:\Android\upload_key_public_certificate.pem.

Example:

keytool -export -rfc -keystore "C:\Android\upload_key.jks" -alias upload -file "C:\Android\upload_key_public_certificate.pem"

Press Enter and you will need to provide the keystore password.

Now if everything has gone OK, you will have a file in the folder PATH_TO_OUTPUT_FILE called upload_key_public_certificate.pem.

Step 6: Upload the upload_key_public_certificate.pem file clicking the button identical to the image below

enter image description here

Step 7: Click ENROLL button at the end of the App Signing page.

enter image description here

Now every new release APK must be signed with the upload_key.jks keystore and aliases created in Step 4, prior to be uploaded in the Google Play Developer console.

More Resources:

Q&A

Q: When i upload the APK signed with the new upload_key keystore, Google Play show an error like : You uploaded an unsigned APK. You need to create a signed APK.

A: Check to sign the APK with both signatures (V1 and V2) while building the release APK. Read here for more details.

UPDATED

The step 4,5,6 are to create upload key which is optional for existing apps

"Upload key (optional for existing apps): A new key you generate during your enrollment in the program. You will use the upload key to sign all future APKs prior to uploading them to the Play Console." https://support.google.com/googleplay/android-developer/answer/7384423

Using regular expression in css?

there is another simple way to select particular elements in css too...

#s1, #s2, #s3 {
    // set css attributes here
}

if you only have a few elements to choose from, and dont want to bother with classes, this will work easily too.

How do I print part of a rendered HTML page in JavaScript?

You could use a print stylesheet, but this will affect all print functions.

You could try having a print stylesheet externalally, and it is included via JavaScript when a button is pressed, and then call window.print(), then after that remove it.

Getting all types in a namespace via reflection

Here's a fix for LoaderException errors you're likely to find if one of the types sublasses a type in another assembly:

// Setup event handler to resolve assemblies
AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(CurrentDomain_ReflectionOnlyAssemblyResolve);

Assembly a = System.Reflection.Assembly.ReflectionOnlyLoadFrom(filename);
a.GetTypes();
// process types here

// method later in the class:
static Assembly CurrentDomain_ReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args)
{
    return System.Reflection.Assembly.ReflectionOnlyLoad(args.Name);
}

That should help with loading types defined in other assemblies.

Hope that helps!

How can I manually generate a .pyc file from a .py file

It's been a while since I last used Python, but I believe you can use py_compile:

import py_compile
py_compile.compile("file.py")

Preview an image before it is uploaded

Please take a look at the sample code below:

_x000D_
_x000D_
function readURL(input) {_x000D_
  if (input.files && input.files[0]) {_x000D_
    var reader = new FileReader();_x000D_
    _x000D_
    reader.onload = function(e) {_x000D_
      $('#blah').attr('src', e.target.result);_x000D_
    }_x000D_
    _x000D_
    reader.readAsDataURL(input.files[0]); // convert to base64 string_x000D_
  }_x000D_
}_x000D_
_x000D_
$("#imgInp").change(function() {_x000D_
  readURL(this);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form runat="server">_x000D_
  <input type='file' id="imgInp" />_x000D_
  <img id="blah" src="#" alt="your image" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

Also, you can try this sample here.

AngularJs ReferenceError: angular is not defined

You should put the include angular line first, before including any other js file

Understanding `scale` in R

log simply takes the logarithm (base e, by default) of each element of the vector.
scale, with default settings, will calculate the mean and standard deviation of the entire vector, then "scale" each element by those values by subtracting the mean and dividing by the sd. (If you use scale(x, scale=FALSE), it will only subtract the mean but not divide by the std deviation.)

Note that this will give you the same values

   set.seed(1)
   x <- runif(7)

   # Manually scaling
   (x - mean(x)) / sd(x)

   scale(x)

How to implement common bash idioms in Python?

Any shell has several sets of features.

  • The Essential Linux/Unix commands. All of these are available through the subprocess library. This isn't always the best first choice for doing all external commands. Look also at shutil for some commands that are separate Linux commands, but you could probably implement directly in your Python scripts. Another huge batch of Linux commands are in the os library; you can do these more simply in Python.

    And -- bonus! -- more quickly. Each separate Linux command in the shell (with a few exceptions) forks a subprocess. By using Python shutil and os modules, you don't fork a subprocess.

  • The shell environment features. This includes stuff that sets a command's environment (current directory and environment variables and what-not). You can easily manage this from Python directly.

  • The shell programming features. This is all the process status code checking, the various logic commands (if, while, for, etc.) the test command and all of it's relatives. The function definition stuff. This is all much, much easier in Python. This is one of the huge victories in getting rid of bash and doing it in Python.

  • Interaction features. This includes command history and what-not. You don't need this for writing shell scripts. This is only for human interaction, and not for script-writing.

  • The shell file management features. This includes redirection and pipelines. This is trickier. Much of this can be done with subprocess. But some things that are easy in the shell are unpleasant in Python. Specifically stuff like (a | b; c ) | something >result. This runs two processes in parallel (with output of a as input to b), followed by a third process. The output from that sequence is run in parallel with something and the output is collected into a file named result. That's just complex to express in any other language.

Specific programs (awk, sed, grep, etc.) can often be rewritten as Python modules. Don't go overboard. Replace what you need and evolve your "grep" module. Don't start out writing a Python module that replaces "grep".

The best thing is that you can do this in steps.

  1. Replace AWK and PERL with Python. Leave everything else alone.
  2. Look at replacing GREP with Python. This can be a bit more complex, but your version of GREP can be tailored to your processing needs.
  3. Look at replacing FIND with Python loops that use os.walk. This is a big win because you don't spawn as many processes.
  4. Look at replacing common shell logic (loops, decisions, etc.) with Python scripts.

Django: Redirect to previous page after login

You can also do this

<input type="hidden" name="text" value="{% url 'dashboard' %}" />

Java : Sort integer array without using Arrays.sort()

Bubble sort can be used here:

 //Time complexity: O(n^2)
public static int[] bubbleSort(final int[] arr) {

    if (arr == null || arr.length <= 1) {
        return arr;
    }

    for (int i = 0; i < arr.length; i++) {
        for (int j = 1; j < arr.length - i; j++) {
            if (arr[j - 1] > arr[j]) {
                arr[j] = arr[j] + arr[j - 1];
                arr[j - 1] = arr[j] - arr[j - 1];
                arr[j] = arr[j] - arr[j - 1];
            }
        }
    }

    return arr;
}

Centering floating divs within another div

display: inline-block; won't work in any of IE browsers. Here is what I used.

// change the width of #boxContainer to 
// 1-2 pixels higher than total width of the boxes inside:

#boxContainer {         
    width: 800px; 
    height: auto;
    text-align: center;
    margin-left: auto;
    margin-right: auto;
}

#Box{
    width: 240px; 
    height: 90px;
    background-color: #FFF;
    float: left;
    margin-left: 10px;
    margin-right: 10px;
}

Java: object to byte[] and byte[] to object converter (for Tokyo Cabinet)

You can use ObjectMapper

        ObjectMapper objectMapper = new ObjectMapper();
        ObjectClass object = objectMapper.readValue(data, ObjectClass.class);

@Scope("prototype") bean scope not creating new bean

use request scope @Scope("request") to get bean for each request, or @Scope("session") to get bean for each session 'user'

ITextSharp HTML to PDF?

The above code will certainly help in converting HTML to PDF but will fail if the the HTML code has IMG tags with relative paths. iTextSharp library does not automatically convert relative paths to absolute ones.

I tried the above code and added code to take care of IMG tags too.

You can find the code here for your reference: http://www.am22tech.com/html-to-pdf/

How to clone ArrayList and also clone its contents?

Here is a solution using a generic template type:

public static <T> List<T> copyList(List<T> source) {
    List<T> dest = new ArrayList<T>();
    for (T item : source) { dest.add(item); }
    return dest;
}

(How) can I count the items in an enum?

There's not really a good way to do this, usually you see an extra item in the enum, i.e.

enum foobar {foo, bar, baz, quz, FOOBAR_NR_ITEMS};

So then you can do:

int fuz[FOOBAR_NR_ITEMS];

Still not very nice though.

But of course you do realize that just the number of items in an enum is not safe, given e.g.

enum foobar {foo, bar = 5, baz, quz = 20};

the number of items would be 4, but the integer values of the enum values would be way out of the array index range. Using enum values for array indexing is not safe, you should consider other options.

edit: as requested, made the special entry stick out more.

How to read lines of a file in Ruby

I'm partial to the following approach for files that have headers:

File.open(file, "r") do |fh|
    header = fh.readline
    # Process the header
    while(line = fh.gets) != nil
        #do stuff
    end
end

This allows you to process a header line (or lines) differently than the content lines.

How do I programmatically set the value of a select box element using JavaScript?

I tried the above JavaScript/jQuery-based solutions, such as:

$("#leaveCode").val("14");

and

var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;

in an AngularJS app, where there was a required <select> element.

None of them works, because the AngularJS form validation is not fired. Although the right option was selected (and is displayed in the form), the input remained invalid (ng-pristine and ng-invalid classes still present).

To force the AngularJS validation, call jQuery change() after selecting an option:

$("#leaveCode").val("14").change();

and

var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;
$(leaveCode).change();

Is there a way to get a collection of all the Models in your Rails app?

The Rails implements the method descendants, but models not necessarily ever inherits from ActiveRecord::Base, for example, the class that includes the module ActiveModel::Model will have the same behavior as a model, just doesn't will be linked to a table.

So complementing what says the colleagues above, the slightest effort would do this:

Monkey Patch of class Class of the Ruby:

class Class
  def extends? constant
    ancestors.include?(constant) if constant != self
  end
end

and the method models, including ancestors, as this:

The method Module.constants returns (superficially) a collection of symbols, instead of constants, so, the method Array#select can be substituted like this monkey patch of the Module:

class Module

  def demodulize
    splitted_trail = self.to_s.split("::")
    constant = splitted_trail.last

    const_get(constant) if defines?(constant)
  end
  private :demodulize

  def defines? constant, verbose=false
    splitted_trail = constant.split("::")
    trail_name = splitted_trail.first

    begin
      trail = const_get(trail_name) if Object.send(:const_defined?, trail_name)
      splitted_trail.slice(1, splitted_trail.length - 1).each do |constant_name|
        trail = trail.send(:const_defined?, constant_name) ? trail.const_get(constant_name) : nil
      end
      true if trail
    rescue Exception => e
      $stderr.puts "Exception recovered when trying to check if the constant \"#{constant}\" is defined: #{e}" if verbose
    end unless constant.empty?
  end

  def has_constants?
    true if constants.any?
  end

  def nestings counted=[], &block
    trail = self.to_s
    collected = []
    recursivityQueue = []

    constants.each do |const_name|
      const_name = const_name.to_s
      const_for_try = "#{trail}::#{const_name}"
      constant = const_for_try.constantize

      begin
        constant_sym = constant.to_s.to_sym
        if constant && !counted.include?(constant_sym)
          counted << constant_sym
          if (constant.is_a?(Module) || constant.is_a?(Class))
            value = block_given? ? block.call(constant) : constant
            collected << value if value

            recursivityQueue.push({
              constant: constant,
              counted: counted,
              block: block
            }) if constant.has_constants?
          end
        end
      rescue Exception
      end

    end

    recursivityQueue.each do |data|
      collected.concat data[:constant].nestings(data[:counted], &data[:block])
    end

    collected
  end

end

Monkey patch of String.

class String
  def constantize
    if Module.defines?(self)
      Module.const_get self
    else
      demodulized = self.split("::").last
      Module.const_get(demodulized) if Module.defines?(demodulized)
    end
  end
end

And, finally, the models method

def models
  # preload only models
  application.config.eager_load_paths = model_eager_load_paths
  application.eager_load!

  models = Module.nestings do |const|
    const if const.is_a?(Class) && const != ActiveRecord::SchemaMigration && (const.extends?(ActiveRecord::Base) || const.include?(ActiveModel::Model))
  end
end

private

  def application
    ::Rails.application
  end

  def model_eager_load_paths
    eager_load_paths = application.config.eager_load_paths.collect do |eager_load_path|
      model_paths = application.config.paths["app/models"].collect do |model_path|
        eager_load_path if Regexp.new("(#{model_path})$").match(eager_load_path)
      end
    end.flatten.compact
  end

max(length(field)) in mysql

SELECT  name, LENGTH(name) AS mlen
FROM    mytable
ORDER BY
        mlen DESC
LIMIT 1

Return an empty Observable

Several ways to create an Empty Observable:

They just differ on how you are going to use it further (what events it will emit after: next, complete or do nothing) e.g.:

  • Observable.never() - emits no events and never ends.
  • Observable.empty() - emits only complete.
  • Observable.of({}) - emits both next and complete (Empty object literal passed as an example).

Use it on your exact needs)

TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

In my case, I forgot to add my component in the Declaration array of app.module.ts, and voila! the issue was fixed.

Use images instead of radio buttons

  • Wrap radio and image in <label>
  • Hide radio button (Don't use display:none or visibility:hidden since such will impact accessibility)
  • Target the image next to the hidden radio using Adjacent sibling selector +

_x000D_
_x000D_
/* HIDE RADIO */
[type=radio] { 
  position: absolute;
  opacity: 0;
  width: 0;
  height: 0;
}

/* IMAGE STYLES */
[type=radio] + img {
  cursor: pointer;
}

/* CHECKED STYLES */
[type=radio]:checked + img {
  outline: 2px solid #f00;
}
_x000D_
<label>
  <input type="radio" name="test" value="small" checked>
  <img src="http://placehold.it/40x60/0bf/fff&text=A">
</label>

<label>
  <input type="radio" name="test" value="big">
  <img src="http://placehold.it/40x60/b0f/fff&text=B">
</label>
_x000D_
_x000D_
_x000D_

Don't forget to add a class to your labels and in CSS use that class instead.


Custom styles and animations

Here's an advanced version using the <i> element and the :after pseudo:

CSS custom radio and checkbox

_x000D_
_x000D_
body{color:#444;font:100%/1.4 sans-serif;}


/* CUSTOM RADIO & CHECKBOXES
   http://stackoverflow.com/a/17541916/383904 */
.rad,
.ckb{
  cursor: pointer;
  user-select: none;
  -webkit-user-select: none;
  -webkit-touch-callout: none;
}
.rad > input,
.ckb > input{ /* HIDE ORG RADIO & CHECKBOX */
  position: absolute;
  opacity: 0;
  width: 0;
  height: 0;
}
/* RADIO & CHECKBOX STYLES */
/* DEFAULT <i> STYLE */
.rad > i,
.ckb > i{ 
  display: inline-block;
  vertical-align: middle;
  width:  16px;
  height: 16px;
  border-radius: 50%;
  transition: 0.2s;
  box-shadow: inset 0 0 0 8px #fff;
  border: 1px solid gray;
  background: gray;
}
/* CHECKBOX OVERWRITE STYLES */
.ckb > i {
  width: 25px;
  border-radius: 3px;
}
.rad:hover > i{ /* HOVER <i> STYLE */
  box-shadow: inset 0 0 0 3px #fff;
  background: gray;
}
.rad > input:checked + i{ /* (RADIO CHECKED) <i> STYLE */
  box-shadow: inset 0 0 0 3px #fff;
  background: orange;
}
/* CHECKBOX */
.ckb > input + i:after{
  content: "";
  display: block;
  height: 12px;
  width:  12px;
  margin: 2px;
  border-radius: inherit;
  transition: inherit;
  background: gray;
}
.ckb > input:checked + i:after{ /* (RADIO CHECKED) <i> STYLE */
  margin-left: 11px;
  background:  orange;
}
_x000D_
<label class="rad">
  <input type="radio" name="rad1" value="a">
  <i></i> Radio 1
</label>
<label class="rad">
  <input type="radio" name="rad1" value="b" checked>
  <i></i> Radio 2
</label>

<br>

<label class="ckb">
  <input type="checkbox" name="ckb1" value="a" checked>
  <i></i> Checkbox 1
</label>
<label class="ckb">
  <input type="checkbox" name="ckb2" value="b">
  <i></i> Checkbox 2
</label>
_x000D_
_x000D_
_x000D_

How do I hide anchor text without hiding the anchor?

How about display: none;

That hides anything.

Recursive directory listing in DOS

You can get the parameters you are asking for by typing:

dir /?

For the full list, try:

dir /s /b /a:d

.htaccess: where is located when not in www base dir

. (dot) files are hidden by default on Unix/Linux systems. Most likely, if you know they are .htaccess files, then they are probably in the root folder for the website.

If you are using a command line (terminal) to access, then they will only show up if you use:

ls -a

If you are using a GUI application, look for a setting to "show hidden files" or something similar.

If you still have no luck, and you are on a terminal, you can execute these commands to search the whole system (may take some time):

cd /
find . -name ".htaccess"

This will list out any files it finds with that name.

using jquery $.ajax to call a PHP function

You may use my library that does that automatically, I've been improving it for the past 2 years http://phery-php-ajax.net

Phery::instance()->set(array(
   'phpfunction' => function($data){
      /* Do your thing */
      return PheryResponse::factory(); // do your dom manipulation, return JSON, etc
   }
))->process();

The javascript would be simple as

phery.remote('phpfunction');

You can pass all the dynamic javascript part to the server, with a query builder like chainable interface, and you may pass any type of data back to the PHP. For example, some functions that would take too much space in the javascript side, could be called in the server using this (in this example, mcrypt, that in javascript would be almost impossible to accomplish):

function mcrypt(variable, content, key){
  phery.remote('mcrypt_encrypt', {'var': variable, 'content': content, 'key':key || false});
}

//would use it like (you may keep the key on the server, safer, unless it's encrypted for the user)
window.variable = '';
mcrypt('variable', 'This must be encoded and put inside variable', 'my key');

and in the server

Phery::instance()->set(array(
  'mcrypt_encrypt' => function($data){
     $r = new PheryResponse;

     $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
     $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
     $encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $data['key'] ? : 'my key', $data['content'], MCRYPT_MODE_ECB, $iv);
     return $r->set_var($data['variable'], $encrypted);
     // or call a callback with the data, $r->call($data['callback'], $encrypted);
  }
))->process();

Now the variable will have the encrypted data.

SQL JOIN and different types of JOINs

Interestingly most other answers suffer from these two problems:

I've recently written an article on the topic: A Probably Incomplete, Comprehensive Guide to the Many Different Ways to JOIN Tables in SQL, which I'll summarise here.

First and foremost: JOINs are cartesian products

This is why Venn diagrams explain them so inaccurately, because a JOIN creates a cartesian product between the two joined tables. Wikipedia illustrates it nicely:

enter image description here

The SQL syntax for cartesian products is CROSS JOIN. For example:

SELECT *

-- This just generates all the days in January 2017
FROM generate_series(
  '2017-01-01'::TIMESTAMP,
  '2017-01-01'::TIMESTAMP + INTERVAL '1 month -1 day',
  INTERVAL '1 day'
) AS days(day)

-- Here, we're combining all days with all departments
CROSS JOIN departments

Which combines all rows from one table with all rows from the other table:

Source:

+--------+   +------------+
| day    |   | department |
+--------+   +------------+
| Jan 01 |   | Dept 1     |
| Jan 02 |   | Dept 2     |
| ...    |   | Dept 3     |
| Jan 30 |   +------------+
| Jan 31 |
+--------+

Result:

+--------+------------+
| day    | department |
+--------+------------+
| Jan 01 | Dept 1     |
| Jan 01 | Dept 2     |
| Jan 01 | Dept 3     |
| Jan 02 | Dept 1     |
| Jan 02 | Dept 2     |
| Jan 02 | Dept 3     |
| ...    | ...        |
| Jan 31 | Dept 1     |
| Jan 31 | Dept 2     |
| Jan 31 | Dept 3     |
+--------+------------+

If we just write a comma separated list of tables, we'll get the same:

-- CROSS JOINing two tables:
SELECT * FROM table1, table2

INNER JOIN (Theta-JOIN)

An INNER JOIN is just a filtered CROSS JOIN where the filter predicate is called Theta in relational algebra.

For instance:

SELECT *

-- Same as before
FROM generate_series(
  '2017-01-01'::TIMESTAMP,
  '2017-01-01'::TIMESTAMP + INTERVAL '1 month -1 day',
  INTERVAL '1 day'
) AS days(day)

-- Now, exclude all days/departments combinations for
-- days before the department was created
JOIN departments AS d ON day >= d.created_at

Note that the keyword INNER is optional (except in MS Access).

(look at the article for result examples)

EQUI JOIN

A special kind of Theta-JOIN is equi JOIN, which we use most. The predicate joins the primary key of one table with the foreign key of another table. If we use the Sakila database for illustration, we can write:

SELECT *
FROM actor AS a
JOIN film_actor AS fa ON a.actor_id = fa.actor_id
JOIN film AS f ON f.film_id = fa.film_id

This combines all actors with their films.

Or also, on some databases:

SELECT *
FROM actor
JOIN film_actor USING (actor_id)
JOIN film USING (film_id)

The USING() syntax allows for specifying a column that must be present on either side of a JOIN operation's tables and creates an equality predicate on those two columns.

NATURAL JOIN

Other answers have listed this "JOIN type" separately, but that doesn't make sense. It's just a syntax sugar form for equi JOIN, which is a special case of Theta-JOIN or INNER JOIN. NATURAL JOIN simply collects all columns that are common to both tables being joined and joins USING() those columns. Which is hardly ever useful, because of accidental matches (like LAST_UPDATE columns in the Sakila database).

Here's the syntax:

SELECT *
FROM actor
NATURAL JOIN film_actor
NATURAL JOIN film

OUTER JOIN

Now, OUTER JOIN is a bit different from INNER JOIN as it creates a UNION of several cartesian products. We can write:

-- Convenient syntax:
SELECT *
FROM a LEFT JOIN b ON <predicate>

-- Cumbersome, equivalent syntax:
SELECT a.*, b.*
FROM a JOIN b ON <predicate>
UNION ALL
SELECT a.*, NULL, NULL, ..., NULL
FROM a
WHERE NOT EXISTS (
  SELECT * FROM b WHERE <predicate>
)

No one wants to write the latter, so we write OUTER JOIN (which is usually better optimised by databases).

Like INNER, the keyword OUTER is optional, here.

OUTER JOIN comes in three flavours:

  • LEFT [ OUTER ] JOIN: The left table of the JOIN expression is added to the union as shown above.
  • RIGHT [ OUTER ] JOIN: The right table of the JOIN expression is added to the union as shown above.
  • FULL [ OUTER ] JOIN: Both tables of the JOIN expression are added to the union as shown above.

All of these can be combined with the keyword USING() or with NATURAL (I've actually had a real world use-case for a NATURAL FULL JOIN recently)

Alternative syntaxes

There are some historic, deprecated syntaxes in Oracle and SQL Server, which supported OUTER JOIN already before the SQL standard had a syntax for this:

-- Oracle
SELECT *
FROM actor a, film_actor fa, film f
WHERE a.actor_id = fa.actor_id(+)
AND fa.film_id = f.film_id(+)

-- SQL Server
SELECT *
FROM actor a, film_actor fa, film f
WHERE a.actor_id *= fa.actor_id
AND fa.film_id *= f.film_id

Having said so, don't use this syntax. I just list this here so you can recognise it from old blog posts / legacy code.

Partitioned OUTER JOIN

Few people know this, but the SQL standard specifies partitioned OUTER JOIN (and Oracle implements it). You can write things like this:

WITH

  -- Using CONNECT BY to generate all dates in January
  days(day) AS (
    SELECT DATE '2017-01-01' + LEVEL - 1
    FROM dual
    CONNECT BY LEVEL <= 31
  ),

  -- Our departments
  departments(department, created_at) AS (
    SELECT 'Dept 1', DATE '2017-01-10' FROM dual UNION ALL
    SELECT 'Dept 2', DATE '2017-01-11' FROM dual UNION ALL
    SELECT 'Dept 3', DATE '2017-01-12' FROM dual UNION ALL
    SELECT 'Dept 4', DATE '2017-04-01' FROM dual UNION ALL
    SELECT 'Dept 5', DATE '2017-04-02' FROM dual
  )
SELECT *
FROM days 
LEFT JOIN departments 
  PARTITION BY (department) -- This is where the magic happens
  ON day >= created_at

Parts of the result:

+--------+------------+------------+
| day    | department | created_at |
+--------+------------+------------+
| Jan 01 | Dept 1     |            | -- Didn't match, but still get row
| Jan 02 | Dept 1     |            | -- Didn't match, but still get row
| ...    | Dept 1     |            | -- Didn't match, but still get row
| Jan 09 | Dept 1     |            | -- Didn't match, but still get row
| Jan 10 | Dept 1     | Jan 10     | -- Matches, so get join result
| Jan 11 | Dept 1     | Jan 10     | -- Matches, so get join result
| Jan 12 | Dept 1     | Jan 10     | -- Matches, so get join result
| ...    | Dept 1     | Jan 10     | -- Matches, so get join result
| Jan 31 | Dept 1     | Jan 10     | -- Matches, so get join result

The point here is that all rows from the partitioned side of the join will wind up in the result regardless if the JOIN matched anything on the "other side of the JOIN". Long story short: This is to fill up sparse data in reports. Very useful!

SEMI JOIN

Seriously? No other answer got this? Of course not, because it doesn't have a native syntax in SQL, unfortunately (just like ANTI JOIN below). But we can use IN() and EXISTS(), e.g. to find all actors who have played in films:

SELECT *
FROM actor a
WHERE EXISTS (
  SELECT * FROM film_actor fa
  WHERE a.actor_id = fa.actor_id
)

The WHERE a.actor_id = fa.actor_id predicate acts as the semi join predicate. If you don't believe it, check out execution plans, e.g. in Oracle. You'll see that the database executes a SEMI JOIN operation, not the EXISTS() predicate.

enter image description here

ANTI JOIN

This is just the opposite of SEMI JOIN (be careful not to use NOT IN though, as it has an important caveat)

Here are all the actors without films:

SELECT *
FROM actor a
WHERE NOT EXISTS (
  SELECT * FROM film_actor fa
  WHERE a.actor_id = fa.actor_id
)

Some folks (especially MySQL people) also write ANTI JOIN like this:

SELECT *
FROM actor a
LEFT JOIN film_actor fa
USING (actor_id)
WHERE film_id IS NULL

I think the historic reason is performance.

LATERAL JOIN

OMG, this one is too cool. I'm the only one to mention it? Here's a cool query:

SELECT a.first_name, a.last_name, f.*
FROM actor AS a
LEFT OUTER JOIN LATERAL (
  SELECT f.title, SUM(amount) AS revenue
  FROM film AS f
  JOIN film_actor AS fa USING (film_id)
  JOIN inventory AS i USING (film_id)
  JOIN rental AS r USING (inventory_id)
  JOIN payment AS p USING (rental_id)
  WHERE fa.actor_id = a.actor_id -- JOIN predicate with the outer query!
  GROUP BY f.film_id
  ORDER BY revenue DESC
  LIMIT 5
) AS f
ON true

It will find the TOP 5 revenue producing films per actor. Every time you need a TOP-N-per-something query, LATERAL JOIN will be your friend. If you're a SQL Server person, then you know this JOIN type under the name APPLY

SELECT a.first_name, a.last_name, f.*
FROM actor AS a
OUTER APPLY (
  SELECT f.title, SUM(amount) AS revenue
  FROM film AS f
  JOIN film_actor AS fa ON f.film_id = fa.film_id
  JOIN inventory AS i ON f.film_id = i.film_id
  JOIN rental AS r ON i.inventory_id = r.inventory_id
  JOIN payment AS p ON r.rental_id = p.rental_id
  WHERE fa.actor_id = a.actor_id -- JOIN predicate with the outer query!
  GROUP BY f.film_id
  ORDER BY revenue DESC
  LIMIT 5
) AS f

OK, perhaps that's cheating, because a LATERAL JOIN or APPLY expression is really a "correlated subquery" that produces several rows. But if we allow for "correlated subqueries", we can also talk about...

MULTISET

This is only really implemented by Oracle and Informix (to my knowledge), but it can be emulated in PostgreSQL using arrays and/or XML and in SQL Server using XML.

MULTISET produces a correlated subquery and nests the resulting set of rows in the outer query. The below query selects all actors and for each actor collects their films in a nested collection:

SELECT a.*, MULTISET (
  SELECT f.*
  FROM film AS f
  JOIN film_actor AS fa USING (film_id)
  WHERE a.actor_id = fa.actor_id
) AS films
FROM actor

As you have seen, there are more types of JOIN than just the "boring" INNER, OUTER, and CROSS JOIN that are usually mentioned. More details in my article. And please, stop using Venn diagrams to illustrate them.

Angular2 Exception: Can't bind to 'routerLink' since it isn't a known native property

In general, whenever you get an error like Can't bind to 'xxx' since it isn't a known native property, the most likely cause is forgetting to specify a component or a directive (or a constant that contains the component or the directive) in the directives metadata array. Such is the case here.

Since you did not specify RouterLink or the constant ROUTER_DIRECTIVES – which contains the following:

export const ROUTER_DIRECTIVES = [RouterOutlet, RouterLink, RouterLinkWithHref, 
  RouterLinkActive];

– in the directives array, then when Angular parses

<a [routerLink]="['RoutingTest']">Routing Test</a>

it doesn't know about the RouterLink directive (which uses attribute selector routerLink). Since Angular does know what the a element is, it assumes that [routerLink]="..." is a property binding for the a element. But it then discovers that routerLink is not a native property of a elements, hence it throws the exception about the unknown property.


I've never really liked the ambiguity of the syntax. I.e., consider

<something [whatIsThis]="..." ...>

Just by looking at the HTML we can't tell if whatIsThis is

  • a native property of something
  • a directive's attribute selector
  • a input property of something

We have to know which directives: [...] are specified in the component's/directive's metadata in order to mentally interpret the HTML. And when we forget to put something into the directives array, I feel this ambiguity makes it a bit harder to debug.

How do I crop an image in Java?

File fileToWrite = new File(filePath, "url");

BufferedImage bufferedImage = cropImage(fileToWrite, x, y, w, h);

private BufferedImage cropImage(File filePath, int x, int y, int w, int h){

    try {
        BufferedImage originalImgage = ImageIO.read(filePath);

        BufferedImage subImgage = originalImgage.getSubimage(x, y, w, h);



        return subImgage;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

turn typescript object into json string

If you're using fs-extra, you can skip the JSON.stringify part with the writeJson function:

const fsExtra = require('fs-extra');

fsExtra.writeJson('./package.json', {name: 'fs-extra'})
.then(() => {
  console.log('success!')
})
.catch(err => {
  console.error(err)
})

Move cursor to end of file in vim

Try doing SHIFT + G and you will be at the end of the page, but you can't edit yet. Go to the top by doing G + G

Convert string to Date in java

String str_date="13-09-2011";
DateFormat formatter ; 
Date date ; 
formatter = new SimpleDateFormat("dd-MM-yyyy");
date = (Date)formatter.parse(str_date); 
System.out.println("Today is " +date.getTime());

Try this

How to install beautiful soup 4 with python 2.7 on windows

easy_install BeautifulSoup4

or

easy_install BeautifulSoup 

to install easy_install

http://pypi.python.org/pypi/setuptools#files

How to keep indent for second line in ordered lists via CSS?

Update

This answer is outdated. You can do this a lot more simply, as pointed out in another answer below:

ul {
  list-style-position: outside;
}

See https://www.w3schools.com/cssref/pr_list-style-position.asp

Original Answer

I'm surprised to see this hasn't been solved yet. You can make use of the browser's table layout algorithm (without using tables) like this:

ol {
    counter-reset: foo;
    display: table;
}

ol > li {
    counter-increment: foo;
    display: table-row;
}

ol > li::before {
    content: counter(foo) ".";
    display: table-cell; /* aha! */
    text-align: right;
}

Demo: http://jsfiddle.net/4rnNK/1/

enter image description here

To make it work in IE8, use the legacy :before notation with one colon.

How do I make Java register a string input with spaces?

This is a sample implementation of taking input in java, I added some fault tolerance on just the salary field to show how it's done. If you notice, you also have to close the input stream .. Enjoy :-)

/* AUTHOR: MIKEQ
 * DATE: 04/29/2016
 * DESCRIPTION: Take input with Java using Scanner Class, Wow, stunningly fun. :-) 
 * Added example of error check on salary input.
 * TESTED: Eclipse Java EE IDE for Web Developers. Version: Mars.2 Release (4.5.2) 
 */

import java.util.Scanner;

public class userInputVersion1 {

    public static void main(String[] args) {

    System.out.println("** Taking in User input **");

    Scanner input = new Scanner(System.in);
    System.out.println("Please enter your name : ");
    String s = input.nextLine(); // getting a String value (full line)
    //String s = input.next(); // getting a String value (issues with spaces in line)

    System.out.println("Please enter your age : ");
    int i = input.nextInt(); // getting an integer

    // version with Fault Tolerance:
    System.out.println("Please enter your salary : ");
    while (!input.hasNextDouble())
    {
        System.out.println("Invalid input\n Type the double-type number:");
        input.next();
    }
    double d = input.nextDouble();    // need to check the data type?

    System.out.printf("\nName %s" +
            "\nAge: %d" +
            "\nSalary: %f\n", s, i, d);

    // close the scanner
    System.out.println("Closing Scanner...");
    input.close();
    System.out.println("Scanner Closed.");      
}
}

Autocomplete syntax for HTML or PHP in Notepad++. Not auto-close, autocompelete

Go to:

Settings -> Preferences You will see a dialog box. There click the Auto-completion tab where you can set the auto complete option.See image below: Follow it

If your code not detected automatically then you choose your coding language form Language menu

How to remove \xa0 from string in Python?

Try using .strip() at the end of your line line.strip() worked well for me

How to write a shell script that runs some commands as superuser and some commands not as superuser, without having to babysit it?

File sutest

#!/bin/bash
echo "uid is ${UID}"
echo "user is ${USER}"
echo "username is ${USERNAME}"

run it: `./sutest' gives me

uid is 500
user is stephenp
username is stephenp

but using sudo: sudo ./sutest gives

uid is 0
user is root
username is stephenp

So you retain the original user name in $USERNAME when running as sudo. This leads to a solution similar to what others posted:

#!/bin/bash
sudo -u ${USERNAME} normal_command_1
root_command_1
root_command_2
sudo -u ${USERNAME} normal_command_2
# etc.

Just sudo to invoke your script in the first place, it will prompt for the password once.


I originally wrote this answer on Linux, which does have some differences with OS X

OS X (I'm testing this on Mountain Lion 10.8.3) has an environment variable SUDO_USER when you're running sudo, which can be used in place of USERNAME above, or to be more cross-platform the script could check to see if SUDO_USER is set and use it if so, or use USERNAME if that's set.

Changing the original script for OS X, it becomes...

#!/bin/bash
sudo -u ${SUDO_USER} normal_command_1
root_command_1
root_command_2
sudo -u ${SUDO_USER} normal_command_2
# etc.

A first stab at making it cross-platform could be...

#!/bin/bash
#
# set "THE_USER" to SUDO_USER if that's set,
#  else set it to USERNAME if THAT is set,
#   else set it to the string "unknown"
# should probably then test to see if it's "unknown"
#
THE_USER=${SUDO_USER:-${USERNAME:-unknown}}

sudo -u ${THE_USER} normal_command_1
root_command_1
root_command_2
sudo -u ${THE_USER} normal_command_2
# etc.

how to set JAVA_OPTS for Tomcat in Windows?

Try

set JAVA_OPTS=%JAVA_OPTS% -Xms512M -Xmx1024M

DD/MM/YYYY Date format in Moment.js

This actually worked for me:

moment(mydate).format('L');

What is a Windows Handle?

Think of the window in Windows as being a struct that describes it. This struct is an internal part of Windows and you don't need to know the details of it. Instead, Windows provides a typedef for pointer to struct for that struct. That's the "handle" by which you can get hold on the window.,

How do I remove the top margin in a web page?

I tried almost every online technique, but i still got the top space in my website, when ever i open it with opera mini mobile phone browser, so i decided to try fix it on my own, and i got it right!

i realize when even you display a page in a single layout, it fits the website to the screen, and some css functions are disabled, since margin, padding, float and position functions are disabled automatically when you fit to screen, and the body always add inbuilt padding at the top. so i decieded to look for at least one function that works, guess what? "display". let me show you how!

<html>
<head>
<style>
body {
display: inline;
}

#top {
display: inline-block;
}
</style>
</head>
<body>
<div id="top">

<!-- your code goes here! -->

eg: <div id="header"></div>
<div id="container"></div> and so on..

<!-- your code goes here! -->

</div>
</body>
</html>

If you notice, the body{display:inline;} removes the inbuilt padding in the body, but without #top{display:inline-block;}, the div still wont display well, so you must include the <div id="top"> element before any code on your page! so simple.. hope this helps? you can thank me if it works, http://www.facebook.com/exploxi

Permission denied (publickey). fatal: The remote end hung up unexpectedly while pushing back to git repository

Googled "Permission denied (publickey). fatal: The remote end hung up unexpectedly", first result an exact SO dupe:

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly which links here in the accepted answer (from the original poster, no less): http://help.github.com/linux-set-up-git/

Javascript: How to remove the last character from a div or a string?

Are u sure u want to remove only last character. What if the user press backspace from the middle of the word.. Its better to get the value from the field and replace the divs html. On keyup

$("#div").html($("#input").val());

Forking / Multi-Threaded Processes | Bash

Let me try example

for x in 1 2 3 ; do { echo a $x ; sleep 1 ; echo b $x ; } &  done ; sleep 10

And use jobs to see what's running.

Effectively use async/await with ASP.NET Web API

I am not very sure whether it will make any difference in performance of my API.

Bear in mind that the primary benefit of asynchronous code on the server side is scalability. It won't magically make your requests run faster. I cover several "should I use async" considerations in my article on async ASP.NET.

I think your use case (calling other APIs) is well-suited for asynchronous code, just bear in mind that "asynchronous" does not mean "faster". The best approach is to first make your UI responsive and asynchronous; this will make your app feel faster even if it's slightly slower.

As far as the code goes, this is not asynchronous:

public Task<BackOfficeResponse<List<Country>>> ReturnAllCountries()
{
  var response = _service.Process<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
  return Task.FromResult(response);
}

You'd need a truly asynchronous implementation to get the scalability benefits of async:

public async Task<BackOfficeResponse<List<Country>>> ReturnAllCountriesAsync()
{
  return await _service.ProcessAsync<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
}

Or (if your logic in this method really is just a pass-through):

public Task<BackOfficeResponse<List<Country>>> ReturnAllCountriesAsync()
{
  return _service.ProcessAsync<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
}

Note that it's easier to work from the "inside out" rather than the "outside in" like this. In other words, don't start with an asynchronous controller action and then force downstream methods to be asynchronous. Instead, identify the naturally asynchronous operations (calling external APIs, database queries, etc), and make those asynchronous at the lowest level first (Service.ProcessAsync). Then let the async trickle up, making your controller actions asynchronous as the last step.

And under no circumstances should you use Task.Run in this scenario.

How do I divide in the Linux console?

I also had the same problem. It's easy to divide integer numbers but decimal numbers are not that easy. if you have 2 numbers like 3.14 and 2.35 and divide the numbers then, the code will be Division=echo 3.14 / 2.35 | bc echo "$Division" the quotes are different. Don't be confused, it's situated just under the esc button on your keyboard. THE ONLY DIFFERENCE IS THE | bc and also here echo works as an operator for the arithmetic calculations in stead of printing. So, I had added echo "$Division" for printing the value. Let me know if it works for you. Thank you.

Example: Communication between Activity and Service using Messaging

Everything is fine.Good example of activity/service communication using Messenger.

One comment : the method MyService.isRunning() is not required.. bindService() can be done any number of times. no harm in that.

If MyService is running in a different process then the static function MyService.isRunning() will always return false. So there is no need of this function.

C# error: Use of unassigned local variable

The compiler doesn't know that the Environment.Exit() is going to terminate the program; it just sees you executing a static method on a class. Just initialize queue to null when you declare it.

Queue queue = null;

How do I change the owner of a SQL Server database?

This is a prompt to create a bunch of object, such as sp_help_diagram (?), that do not exist.

This should have nothing to do with the owner of the db.

JavaScript: function returning an object

Both styles, with a touch of tweaking, would work.

The first method uses a Javascript Constructor, which like most things has pros and cons.

 // By convention, constructors start with an upper case letter
function MakePerson(name,age) {
  // The magic variable 'this' is set by the Javascript engine and points to a newly created object that is ours.
  this.name = name;
  this.age = age;
  this.occupation = "Hobo";
}
var jeremy = new MakePerson("Jeremy", 800);

On the other hand, your other method is called the 'Revealing Closure Pattern' if I recall correctly.

function makePerson(name2, age2) {
  var name = name2;
  var age = age2;

  return {
    name: name,
    age: age
  };
}

Free tool to Create/Edit PNG Images?

ImageMagick and GD can handle PNGs too; heck, you could even do stuff with nothing but gdk-pixbuf. Are you looking for a graphical editor, or scriptable/embeddable libraries?

Swift apply .uppercaseString to only the first letter of a string

Add this line in viewDidLoad() method.

 txtFieldName.autocapitalizationType = UITextAutocapitalizationType.words

Share data between html pages

Well, you can actually send data via JavaScript - but you should know that this is the #1 exploit source in web pages as it's XSS :)

I personally would suggest to use an HTML formular instead and modify the javascript data on the server side.

But if you want to share between two pages (I assume they are not both on localhost, because that won't make sense to share between two both-backend-driven pages) you will need to specify the CORS headers to allow the browser to send data to the whitelisted domains.

These two links might help you, it shows the example via Node backend, but you get the point how it works:

Link 1

And, of course, the CORS spec:

Link 2

~Cheers

What is the difference between DTR/DSR and RTS/CTS flow control?

  • DTR - Data Terminal Ready
  • DSR - Data Set Ready
  • RTS - Request To Send
  • CTS - Clear To Send

There are multiple ways of doing things because there were never any protocols built into the standards. You use whatever ad-hoc "standard" your equipment implements.

Just based on the names, RTS/CTS would seem to be a natural fit. However, it's backwards from the needs that developed over time. These signals were created at a time when a terminal would batch-send a screen full of data, but the receiver might not be ready, thus the need for flow control. Later the problem would be reversed, as the terminal couldn't keep up with data coming from the host, but the RTS/CTS signals go the wrong direction - the interface isn't orthogonal, and there's no corresponding signals going the other way. Equipment makers adapted as best they could, including using the DTR and DSR signals.

EDIT

To add a bit more detail, its a two level hierarchy so "officially" both must happen for communication to take place. The behavior is defined in the original CCITT (now ITU-T) standard V.28.

enter image description here

The DCE is a modem connecting between the terminal and telephone network. In the telephone network was another piece of equipment which split off to the data network, eg. X.25.

The modem has three states: Powered off, Ready (Data Set Ready is true), and connected (Data Carrier Detect)

The terminal can't do anything until the modem is connected.

When the modem wants to send data, it raises RTS and the modem grants the request with CTS. The modem lowers CTS when its internal buffer is full.

So nostalgic!

MySQL error: key specification without a key length

You can specify the key length in the alter table request, something like:

alter table authors ADD UNIQUE(name_first(20), name_second(20));

Delete with Join in MySQL

I'm more used to the subquery solution to this, but I have not tried it in MySQL:

DELETE  FROM posts
WHERE   project_id IN (
            SELECT  project_id
            FROM    projects
            WHERE   client_id = :client_id
        );

ls command: how can I get a recursive full-path listing, one line per file?

Run a bash command with the following format:

find /path -type f -exec ls -l \{\} \;

Find rows that have the same value on a column in MySQL

select email from mytable group by email having count(*) >1

How do I POST urlencoded form data with $http without jQuery?

All of these look like overkill (or don't work)... just do this:

$http.post(loginUrl, `username=${ encodeURIComponent(username) }` +
                     `&password=${ encodeURIComponent(password) }` +
                     '&grant_type=password'
).success(function (data) {

Difference between <? super T> and <? extends T> in Java

You can go through all the answers above to understand why the .add() is restricted to '<?>', '<? extends>', and partly to '<? super>'.

But here's the conclusion of it all if you want to remember it, and dont want to go exploring the answer every time:

List<? extends A> means this will accept any List of A and subclass of A. But you cannot add anything to this list. Not even objects of type A.

List<? super A> means this will accept any list of A and superclass of A. You can add objects of type A and its subclasses.

In Python, how do I create a string of n characters in one line of code?

Why "one line"? You can fit anything onto one line.

Assuming you want them to start with 'a', and increment by one character each time (with wrapping > 26), here's a line:

>>> mkstring = lambda(x): "".join(map(chr, (ord('a')+(y%26) for y in range(x))))
>>> mkstring(10)
'abcdefghij'
>>> mkstring(30)
'abcdefghijklmnopqrstuvwxyzabcd'

changing textbox border colour using javascript

document.getElementById("fName").style.borderColor="";

is all you need to change the border color back.

To change the border size, use element.style.borderWidth = "1px".

Force file download with php using header()

the htaccess solution

<filesmatch "\.(?i:doc|odf|pdf|cer|txt)$">
  Header set Content-Disposition attachment
</FilesMatch>

you can read this page: https://www.techmesto.com/force-files-to-download-using-htaccess/

Is it possible to forward-declare a function in Python?

If you kick-start your script through the following:

if __name__=="__main__":
   main()

then you probably do not have to worry about things like "forward declaration". You see, the interpreter would go loading up all your functions and then start your main() function. Of course, make sure you have all the imports correct too ;-)

Come to think of it, I've never heard such a thing as "forward declaration" in python... but then again, I might be wrong ;-)

Convert audio files to mp3 using ffmpeg

For batch processing with files in folder aiming for 190 VBR and file extension = .mp3 instead of .ac3.mp3 you can use the following code

Change .ac3 to whatever the source audio format is.

ffmpeg mp3 settings

for f in *.ac3 ; do ffmpeg -i "$f" -acodec libmp3lame -q:a 2 "${f%.*}.mp3"; done

Where does Android app package gets installed on phone

An application when installed on a device or on an emulator will install at:

/data/data/APP_PACKAGE_NAME

The APK itself is placed in the /data/app/ folder.

These paths, however, are in the System Partition and to access them, you will need to have root. This is for a device. On the emulator, you can see it in your logcat (DDMS) in the File Explorer tab

By the way, it only shows the package name that is defined in your Manifest.XML under the package="APP_PACKAGE_NAME" attribute. Any other packages you may have created in your project in Eclipse do not show up here.

If Radio Button is selected, perform validation on Checkboxes

function validateDays() {
    if (document.getElementById("option1").checked == true) {
        alert("You have selected Option 1");
    }
    else if (document.getElementById("option2").checked == true) {
        alert("You have selected Option 2");
    }
    else if (document.getElementById("option3").checked == true) {
        alert("You have selected Option 3");
    }
    else {
        // DO NOTHING
        }
    }

Accessing a property in a parent Component

You could:

  • Define a userStatus parameter for the child component and provide the value when using this component from the parent:

    @Component({
      (...)
    })
    export class Profile implements OnInit {
      @Input()
      userStatus:UserStatus;
    
      (...)
    }
    

    and in the parent:

    <profile [userStatus]="userStatus"></profile>
    
  • Inject the parent into the child component:

    @Component({
      (...)
    })
    export class Profile implements OnInit {
      constructor(app:App) {
        this.userStatus = app.userStatus;
      }
    
      (...)
    }
    

    Be careful about cyclic dependencies between them.

How to iterate through a list of dictionaries in Jinja template?

As a sidenote to @Navaneethan 's answer, Jinja2 is able to do "regular" item selections for the list and the dictionary, given we know the key of the dictionary, or the locations of items in the list.

Data:

parent_dict = [{'A':'val1','B':'val2', 'content': [["1.1", "2.2"]]},{'A':'val3','B':'val4', 'content': [["3.3", "4.4"]]}]

in Jinja2 iteration:

{% for dict_item in parent_dict %}
   This example has {{dict_item['A']}} and {{dict_item['B']}}:
       with the content --
       {% for item in dict_item['content'] %}{{item[0]}} and {{item[1]}}{% endfor %}.
{% endfor %}

The rendered output:

This example has val1 and val2:
    with the content --
    1.1 and 2.2.

This example has val3 and val4:
   with the content --
   3.3 and 4.4.

Merging two arrayLists into a new arrayList, with no duplicates and in order, in Java

**Add elements in Final arraylist,**
**This will Help you sure**

import java.util.ArrayList;
import java.util.List;

public class NonDuplicateList {

public static void main(String[] args) {

    List<String> l1 = new ArrayList<String>();
    l1.add("1");l1.add("2");l1.add("3");l1.add("4");l1.add("5");l1.add("6");
    List<String> l2 = new ArrayList<String>();
    l2.add("1");l2.add("7");l2.add("8");l2.add("9");l2.add("10");l2.add("3");
    List<String> l3 = new ArrayList<String>();
    l3.addAll(l1);
    l3.addAll(l2);
    for (int i = 0; i < l3.size(); i++) {
        for (int j=i+1; j < l3.size(); j++) {
             if(l3.get(i) == l3.get(j)) {
                 l3.remove(j);
            }
        }
    }
    System.out.println(l3);
}

}

Output : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Google Apps Script to open a URL

There really isn't a need to create a custom click event as suggested in the bountied answer or to show the url as suggested in the accepted answer.

window.open(url)1 does open web pages automatically without user interaction, provided pop- up blockers are disabled(as is the case with Stephen's answer)

openUrl.html

<!DOCTYPE html>
<html>
  <head>
   <base target="_blank">
    <script>
     var url1 ='https://stackoverflow.com/a/54675103';
     var winRef = window.open(url1);
     winRef ? google.script.host.close() : window.alert('Allow popup to redirect you to '+url1) ;
     window.onload=function(){document.getElementById('url').href = url1;}
    </script>
  </head>
  <body>
    Kindly allow pop ups</br>
    Or <a id='url'>Click here </a>to continue!!!
  </body>
</html>

code.gs:

function modalUrl(){
  SpreadsheetApp.getUi()
   .showModalDialog(
     HtmlService.createHtmlOutputFromFile('openUrl').setHeight(50),
     'Opening StackOverflow'
   )
}    

How to make <label> and <input> appear on the same line on an HTML form?

What you were missing was the float: left; here is an example just done in the HTML

<div id="form">
<form action="" method="post" name="registration" class="register">
    <fieldset>
        <label for="Student" style="float: left">Name:</label>
        <input name="Student" />
        <label for="Matric_no" style="float: left">Matric number:</label>
        <input name="Matric_no" />
        <label for="Email" style="float: left">Email:</label>
        <input name="Email" />
        <label for="Username" style="float: left">Username:</label>
        <input name="Username" />
        <label for="Password" style="float: left">Password:</label>
        <input name="Password" type="password" />
        <input name="regbutton" type="button" class="button" value="Register" />
    </fieldset>
</form>

The more efficient way to do this is to add a class to the labels and set the float: left; to the class in CSS

JOIN queries vs multiple queries

This question is old, but is missing some benchmarks. I benchmarked JOIN against its 2 competitors:

  • N+1 queries
  • 2 queries, the second one using a WHERE IN(...) or equivalent

The result is clear: on MySQL, JOIN is much faster. N+1 queries can drop the performance of an application drastically:

JOIN vs WHERE IN vs N+1

That is, unless you select a lot of records that point to a very small number of distinct, foreign records. Here is a benchmark for the extreme case:

JOIN vs N+1 - all records pointing to the same foreign record

This is very unlikely to happen in a typical application, unless you're joining a -to-many relationship, in which case the foreign key is on the other table, and you're duplicating the main table data many times.

Takeaway:

  • For *-to-one relationships, always use JOIN
  • For *-to-many relationships, a second query might be faster

See my article on Medium for more information.

How to send a pdf file directly to the printer using JavaScript?

a function to house the print trigger...

function printTrigger(elementId) {
    var getMyFrame = document.getElementById(elementId);
    getMyFrame.focus();
    getMyFrame.contentWindow.print();
}

an button to give the user access...

(an onClick on an a or button or input or whatever you wish)

<input type="button" value="Print" onclick="printTrigger('iFramePdf');" />
an iframe pointing to your PDF...

<iframe id="iFramePdf" src="myPdfUrl.pdf" style="dispaly:none;"></iframe>

More : http://www.fpdf.org/en/script/script36.php

Cursor inside cursor

I don't fully understand what was the problem with the "update current of cursor" but it is solved by using the fetch statement twice for the inner cursor:

FETCH NEXT FROM INNER_CURSOR

WHILE (@@FETCH_STATUS <> -1)
BEGIN

UPDATE CONTACTS
SET INDEX_NO = @COUNTER
WHERE CURRENT OF INNER_CURSOR

SET @COUNTER = @COUNTER + 1

FETCH NEXT FROM INNER_CURSOR
FETCH NEXT FROM INNER_CURSOR
END

How can I change an element's class with JavaScript?

Working JavaScript code:

<div id="div_add" class="div_add">Add class from Javascript</div>
<div id="div_replace" class="div_replace">Replace class from Javascript</div>
<div id="div_remove" class="div_remove">Remove class from Javascript</div>
<button onClick="div_add_class();">Add class from Javascript</button>
<button onClick="div_replace_class();">Replace class from Javascript</button>
<button onClick="div_remove_class();">Remove class from Javascript</button>
<script type="text/javascript">
    function div_add_class()
    {
        document.getElementById("div_add").className += " div_added";
    }
    function div_replace_class()
    {
        document.getElementById("div_replace").className = "div_replaced";
    }
    function div_remove_class()
    {
        document.getElementById("div_remove").className = "";
    }
</script>

You can download a working code from this link.

AJAX post error : Refused to set unsafe header "Connection"

Remove these two lines:

xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");

XMLHttpRequest isn't allowed to set these headers, they are being set automatically by the browser. The reason is that by manipulating these headers you might be able to trick the server into accepting a second request through the same connection, one that wouldn't go through the usual security checks - that would be a security vulnerability in the browser.

Check time difference in Javascript

grab the input values after form submission in php

$start_time = $_POST('start_time');
$end_time =$_POST('end_time');
$start = $start_time;
$end = $end_time;
$datetime1 = new DateTime($end);
$datetime2 = new DateTime($start);
//echo $datetime1->format('H:i:s');
$interval = $datetime1->diff($datetime2);
$elapsed = $interval->format('%h:%i');
$time = explode(":",$elapsed);
$hours = $time[0];
$minutes = $time[1];
$tminutes = $minutes + ($hours*60);

the variable $tminutes is total diff in minutes , working hour is $hour . this code is for php use this logic and convert this code to js

Center/Set Zoom of Map to cover all visible Markers?

You need to use the fitBounds() method.

var markers = [];//some array
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
 bounds.extend(markers[i]);
}

map.fitBounds(bounds);

Documentation from developers.google.com/maps/documentation/javascript:

fitBounds(bounds[, padding])

Parameters:

`bounds`:  [`LatLngBounds`][1]|[`LatLngBoundsLiteral`][1]
`padding` (optional):  number|[`Padding`][1]

Return Value: None

Sets the viewport to contain the given bounds.
Note: When the map is set to display: none, the fitBounds function reads the map's size as 0x0, and therefore does not do anything. To change the viewport while the map is hidden, set the map to visibility: hidden, thereby ensuring the map div has an actual size.

How do I set an ASP.NET Label text from code behind on page load?

protected void Page_Load(object sender, EventArgs e)
{
    myLabel.Text = "My text";
}

this is the base of ASP.Net, thinking in controls, not html flow.

Consider following a course, or reading a beginner book... and first, forget what you did in php :)

Typing the Enter/Return key using Python and Selenium

Java/JavaScript:

You could probably do it this way also, non-natively:

public void triggerButtonOnEnterKeyInTextField(String textFieldId, String clickableButId)
{
    ((JavascriptExecutor) driver).executeScript(
        "   elementId = arguments[0];
            buttonId = arguments[1];
            document.getElementById(elementId)
                .addEventListener("keyup", function(event) {
                    event.preventDefault();
                    if (event.keyCode == 13) {
                        document.getElementById(buttonId).click();
                    }
                });",

        textFieldId,
        clickableButId);
}

how to get login option for phpmyadmin in xampp

Step 1:

Locate phpMyAdmin installation path.

Step 2:

Open phpMyAdmin/config.inc.php in your favourite text editor. Copy config.sample.inc.php to config.inc.php if it's missing.

Step 3:

Search for $cfg['Servers'][$i]['auth_type'] = 'config';

Replace it with $cfg['Servers'][$i]['auth_type'] = 'cookie';

(Built-in) way in JavaScript to check if a string is a valid number

You could make use of types, like with the flow library, to get static, compile time checking. Of course not terribly useful for user input.

// @flow

function acceptsNumber(value: number) {
  // ...
}

acceptsNumber(42);       // Works!
acceptsNumber(3.14);     // Works!
acceptsNumber(NaN);      // Works!
acceptsNumber(Infinity); // Works!
acceptsNumber("foo");    // Error!

Converting PHP result array to JSON

$result = mysql_query($query) or die("Data not found."); 
$rows=array(); 
while($r=mysql_fetch_assoc($result))
{ 
$rows[]=$r;
}
header("Content-type:application/json"); 
echo json_encode($rows);

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

I have figured it out lol. for the button do .setBounds(0, 0, 220, 30) The .setBounds layout is like this (int x, int y, int width, int height)

Why is the Visual Studio 2015/2017/2019 Test Runner not discovering my xUnit v2 tests

I've been struggling with this all afternoon whilst working with an ASP Core project and xUnit 2.2.0. The solution for me was adding a reference to Microsoft.DotNet.InternalAbstractions

I found this out when trying to run the test project manually with dotnet test which failed but reported that InternalAbstractions was missing. I did not see this error in the test output window when the auto discovery failed. The only info I saw in the discovery window was a return code, which didn't mean anything to me at the time, but in hindsight was probably indicating an error.

int object is not iterable?

Side note: if you want to get the sum of all digits, you can simply do

print sum(int(digit) for digit in raw_input('Enter a number:'))

Linear Layout and weight in Android

Plus you need to add this android:layout_width="0dp" for children views [Button views] of LinerLayout

jQuery: serialize() form and other parameters

Following Rory McCrossan answer, if you want to send an array of integer (almost for .NET), this is the code:

// ...

url: "MyUrl",       //  For example --> @Url.Action("Method", "Controller")
method: "post",
traditional: true,  
data: 
    $('#myForm').serialize() +
    "&param1="xxx" +
    "&param2="33" +
    "&" + $.param({ paramArray: ["1","2","3"]}, true)
,             

// ...

Maven: How to run a .java file from command line passing arguments

You could run: mvn exec:exec -Dexec.args="arg1".

This will pass the argument arg1 to your program.

You should specify the main class fully qualified, for example, a Main.java that is in a package test would need

mvn exec:java  -Dexec.mainClass=test.Main

By using the -f parameter, as decribed here, you can also run it from other directories.

mvn exec:java -Dexec.mainClass=test.Main -f folder/pom.xm

For multiple arguments, simply separate them with a space as you would at the command line.

mvn exec:java -Dexec.mainClass=test.Main -Dexec.args="arg1 arg2 arg3"

For arguments separated with a space, you can group using 'argument separated with space' inside the quotation marks.

mvn exec:java -Dexec.mainClass=test.Main -Dexec.args="'argument separated with space' 'another one'"

Android device does not show up in adb list

I had similar problem with my "Xiaomi Redmi Note 4" and tried almost 10 solutions I found over internet, but none of them helped my case. I've posted this answer to help someones like myself.

Installing "Intel USB Driver for Android Devices" totally solved my problem. It's described completely here.

Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine

I found a solution for this problem. The issue I described in my question occured basically due to the incompatibility of the Microsoft.Jet.OLEDB.4.0 driver in 64 bit OS.

So if we are using Microsoft.Jet.OLEDB.4.0 driver in a 64 bit server, we have to force our application to build in in 32 bit mode (This is the answer I found when I did an extensive search for this known issue) and that causes other part of my code to break.

Fortunately, now Microsoft has released a 64 bit compatible 2010 Office System Driver which can be used as replacement for the traditional Microsoft.Jet.OLEDB.4.0 driver. It works both in 32 bit as well as 64 bit servers. I have used it for Excel file manipulation and it worked fine for me in both the environments. But this driver is in BETA.

You can download this driver from Microsoft Access Database Engine 2010 Redistributable

jQuery - adding elements into an array

Try this, at the end of the each loop, ids array will contain all the hexcodes.

var ids = [];

    $(document).ready(function($) {
    var $div = $("<div id='hexCodes'></div>").appendTo(document.body), code;
    $(".color_cell").each(function() {
        code = $(this).attr('id');
        ids.push(code);
        $div.append(code + "<br />");
    });



});

How to concatenate columns in a Postgres SELECT?

With string type columns like character(2) (as you mentioned later), the displayed concatenation just works because, quoting the manual:

[...] the string concatenation operator (||) accepts non-string input, so long as at least one input is of a string type, as shown in Table 9.8. For other cases, insert an explicit coercion to text [...]

Bold emphasis mine. The 2nd example (select a||', '||b from foo) works for any data types since the untyped string literal ', ' defaults to type text making the whole expression valid in any case.

For non-string data types, you can "fix" the 1st statement by casting at least one argument to text. (Any type can be cast to text):

SELECT a::text || b AS ab FROM foo;

Judging from your own answer, "does not work" was supposed to mean "returns NULL". The result of anything concatenated to NULL is NULL. If NULL values can be involved and the result shall not be NULL, use concat_ws() to concatenate any number of values (Postgres 9.1 or later):

SELECT concat_ws(', ', a, b) AS ab FROM foo;

Or concat() if you don't need separators:

SELECT concat(a, b) AS ab FROM foo;

No need for type casts here since both functions take "any" input and work with text representations.

More details (and why COALESCE is a poor substitute) in this related answer:

Regarding update in the comment

+ is not a valid operator for string concatenation in Postgres (or standard SQL). It's a private idea of Microsoft to add this to their products.

There is hardly any good reason to use character(n) (synonym: char(n)). Use text or varchar. Details:

How to manually trigger validation with jQuery validate?

As written in the documentation, the way to trigger form validation programmatically is to invoke validator.form()

var validator = $( "#myform" ).validate();
validator.form();

string sanitizer for filename

Making a small adjustment to Tor Valamo's solution to fix the problem noticed by Dominic Rodger, you could use:

// Remove anything which isn't a word, whitespace, number
// or any of the following caracters -_~,;[]().
// If you don't need to handle multi-byte characters
// you can use preg_replace rather than mb_ereg_replace
// Thanks @Lukasz Rysiak!
$file = mb_ereg_replace("([^\w\s\d\-_~,;\[\]\(\).])", '', $file);
// Remove any runs of periods (thanks falstro!)
$file = mb_ereg_replace("([\.]{2,})", '', $file);

Android: Internet connectivity change listener

This should work:

public class ConnectivityChangeActivity extends Activity {

    private BroadcastReceiver networkChangeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d("app","Network connectivity change");
        }
    };

    @Override
    protected void onResume() {
        super.onResume();

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(networkChangeReceiver, intentFilter);
    }

    @Override
    protected void onPause() {
        super.onPause();

        unregisterReceiver(networkChangeReceiver);
    }
}

Removing an element from an Array (Java)

okay, thx a lot now i use sth like this:

public static String[] removeElements(String[] input, String deleteMe) {
    if (input != null) {
        List<String> list = new ArrayList<String>(Arrays.asList(input));
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).equals(deleteMe)) {
                list.remove(i);
            }
        }
        return list.toArray(new String[0]);
    } else {
        return new String[0];
    }
}

Android Studio - Gradle sync project failed

Update for 2018:

I have faced this issue recently and it was resolved by updating android studio & updating gradle when prompted then rebuilding the project

Align button to the right

<div class="container-fluid">
  <div class="row">
    <h3 class="one">Text</h3>
    <button class="btn btn-secondary ml-auto">Button</button>
  </div>
</div>

.ml-auto is Bootstraph 4's non-flexbox way of aligning things.

Eclipse gives “Java was started but returned exit code 13”

Check you PATH environment variable once. Make sure the correct location of your JDK is specified there.

Eclipse fonts and background color

... on a Mac, Preferences' is under the main 'Aptana Studio 3' menu rather than the 'Windows' menu as mentioned above.

How to do case insensitive search in Vim

put this command in your vimrc file

set ic 

always do case insensitive search

How to read data From *.CSV file using javascript?

$(function() {

      $("#upload").bind("click", function() {
            var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.xlsx)$/;
            if (regex.test($("#fileUpload").val().toLowerCase())) {
              if (typeof(FileReader) != "undefined") {
                var reader = new FileReader();
                reader.onload = function(e) {
                    var customers = new Array();
                    var rows = e.target.result.split("\r\n");
                    for (var i = 0; i < rows.length - 1; i++) {
                      var cells = rows[i].split(",");
                      if (cells[0] == "" || cells[0] == undefined) {
                        var s = customers[customers.length - 1];
                        s.Ord.push(cells[2]);
                      } else {
                        var dt = customers.find(x => x.Number === cells[0]);
                        if (dt == undefined) {
                          if (cells.length > 1) {
                            var customer = {};
                            customer.Number = cells[0];
                            customer.Name = cells[1];
                            customer.Ord = new Array();

                            customer.Ord.push(cells[2]);
                            customer.Point_ID = cells[3];
                            customer.Point_Name = cells[4];
                            customer.Point_Type = cells[5];
                            customer.Set_ORD = cells[6];
                            customers.push(customer);
                          }
                        } else {
                          var dtt = dt;
                          dtt.Ord.push(cells[2]);

                        }
                      }
                    }

Select DataFrame rows between two dates

I prefer not to alter the df.

An option is to retrieve the index of the start and end dates:

import numpy as np   
import pandas as pd

#Dummy DataFrame
df = pd.DataFrame(np.random.random((30, 3)))
df['date'] = pd.date_range('2017-1-1', periods=30, freq='D')

#Get the index of the start and end dates respectively
start = df[df['date']=='2017-01-07'].index[0]
end = df[df['date']=='2017-01-14'].index[0]

#Show the sliced df (from 2017-01-07 to 2017-01-14)
df.loc[start:end]

which results in:

     0   1   2       date
6  0.5 0.8 0.8 2017-01-07
7  0.0 0.7 0.3 2017-01-08
8  0.8 0.9 0.0 2017-01-09
9  0.0 0.2 1.0 2017-01-10
10 0.6 0.1 0.9 2017-01-11
11 0.5 0.3 0.9 2017-01-12
12 0.5 0.4 0.3 2017-01-13
13 0.4 0.9 0.9 2017-01-14

What is correct media query for IPad Pro?

/* ----------- iPad Pro ----------- */
/* Portrait and Landscape */
@media only screen 
  and (min-width: 1024px) 
  and (max-height: 1366px) 
  and (-webkit-min-device-pixel-ratio: 1.5) {
}

/* Portrait */
@media only screen 
  and (min-width: 1024px) 
  and (max-height: 1366px) 
  and (orientation: portrait) 
  and (-webkit-min-device-pixel-ratio: 1.5) {
}

/* Landscape */
@media only screen 
  and (min-width: 1024px) 
  and (max-height: 1366px) 
  and (orientation: landscape) 
  and (-webkit-min-device-pixel-ratio: 1.5) {

}

I don't have an iPad Pro but this works for me in the Chrome simulator.

What is the best way to manage a user's session in React?

I would avoid using component state since this could be difficult to manage and prone to issues that can be difficult to troubleshoot.

You should use either cookies or localStorage for persisting a user's session data. You can also use a closure as a wrapper around your cookie or localStorage data.

Here is a simple example of a UserProfile closure that will hold the user's name.

var UserProfile = (function() {
  var full_name = "";

  var getName = function() {
    return full_name;    // Or pull this from cookie/localStorage
  };

  var setName = function(name) {
    full_name = name;     
    // Also set this in cookie/localStorage
  };

  return {
    getName: getName,
    setName: setName
  }

})();

export default UserProfile;

When a user logs in, you can populate this object with user name, email address etc.

import UserProfile from './UserProfile';

UserProfile.setName("Some Guy");

Then you can get this data from any component in your app when needed.

import UserProfile from './UserProfile';

UserProfile.getName();

Using a closure will keep data outside of the global namespace, and make it is easily accessible from anywhere in your app.

Does VBA have Dictionary Structure?

VBA has the collection object:

    Dim c As Collection
    Set c = New Collection
    c.Add "Data1", "Key1"
    c.Add "Data2", "Key2"
    c.Add "Data3", "Key3"
    'Insert data via key into cell A1
    Range("A1").Value = c.Item("Key2")

The Collection object performs key-based lookups using a hash so it's quick.


You can use a Contains() function to check whether a particular collection contains a key:

Public Function Contains(col As Collection, key As Variant) As Boolean
    On Error Resume Next
    col(key) ' Just try it. If it fails, Err.Number will be nonzero.
    Contains = (Err.Number = 0)
    Err.Clear
End Function

Edit 24 June 2015: Shorter Contains() thanks to @TWiStErRob.

Edit 25 September 2015: Added Err.Clear() thanks to @scipilot.

How do I profile memory usage in Python?

Disclosure:

  • Applicable on Linux only
  • Reports memory used by the current process as a whole, not individual functions within

But nice because of its simplicity:

import resource
def using(point=""):
    usage=resource.getrusage(resource.RUSAGE_SELF)
    return '''%s: usertime=%s systime=%s mem=%s mb
           '''%(point,usage[0],usage[1],
                usage[2]/1024.0 )

Just insert using("Label") where you want to see what's going on. For example

print(using("before"))
wrk = ["wasting mem"] * 1000000
print(using("after"))

>>> before: usertime=2.117053 systime=1.703466 mem=53.97265625 mb
>>> after: usertime=2.12023 systime=1.70708 mem=60.8828125 mb

C char array initialization

I'm not sure but I commonly initialize an array to "" in that case I don't need worry about the null end of the string.

main() {
    void something(char[]);
    char s[100] = "";

    something(s);
    printf("%s", s);
}

void something(char s[]) {
    // ... do something, pass the output to s
    // no need to add s[i] = '\0'; because all unused slot is already set to '\0'
}

How to get the current time as datetime

func getCurrentDate() -> Date {
    let date = Date()
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    let dateInString  = dateFormatter.string(from: date)
    let dateinDate = dateFormatter.date(from: dateInString)
    return dateinDate!
}

C#: Printing all properties of an object

Don't think so. I've always had to write them or use someone else's work to get that info. Has to be reflection as far as i'm aware.

EDIT:
Check this out. I was investigating some debugging on long object graphs and noticed this when i Add Watches, VS throws in this class: Mscorlib_CollectionDebugView<>. It's an internal type for displaying collections nicely for viewing in the watch windows/code debug modes. Now coz it's internal you can reference it, but u can use Reflector to copy (from mscorlib) the code and have your own (the link above has a copy/paste example). Looks really useful.

Set UITableView content inset permanently

This is how it can be fixed easily through Storyboard (iOS 11 and Xcode 9.1):

Select Table View > Size Inspector > Content Insets: Never

HTML5 <video> element on Android

This might not exactly answer your question, but we're using the 3GP or 3GP2 file format. Better even to use the rtsp protocol, but the Android browser will also recognize the 3GP file format.

You can use something like

self.location = URL_OF_YOUR_3GP_FILE

to trigger the video player. The file will be streamed and after playback ends, handling is returned to the browser.

For me this solves a lot of problems with current video tag implementation on android devices.

Warning: The method assertEquals from the type Assert is deprecated

this method also encounter a deprecate warning:

org.junit.Assert.assertEquals(float expected,float actual) //deprecated

It is because currently junit prefer a third parameter rather than just two float variables input.

The third parameter is delta:

public static void assertEquals(double expected,double actual,double delta) //replacement

this is mostly used to deal with inaccurate Floating point calculations

for more information, please refer this problem: Meaning of epsilon argument of assertEquals for double values

Axios get access to response header fields

According to official docs:

This may help if you want the HTTP headers that the server responded with. All header names are lower cased and can be accessed using the bracket notation. Example: response.headers['content-type'] will give something like: headers: {},

RESTful Authentication

First and foremost, a RESTful web service is STATELESS (or in other words, SESSIONLESS). Therefore, a RESTful service does not have and should not have a concept of session or cookies involved. The way to do authentication or authorization in the RESTful service is by using the HTTP Authorization header as defined in the RFC 2616 HTTP specifications. Every single request should contain the HTTP Authorization header, and the request should be sent over an HTTPs (SSL) connection. This is the correct way to do authentication and to verify the authorization of requests in a HTTP RESTful web services. I have implemented a RESTful web service for the Cisco PRIME Performance Manager application at Cisco Systems. And as part of that web service, I have implemented authentication/authorization as well.

URL to load resources from the classpath in Java

If you have tomcat on the classpath, it's as simple as:

TomcatURLStreamHandlerFactory.register();

This will register handlers for "war" and "classpath" protocols.

How to host a Node.Js application in shared hosting

A2 Hosting permits node.js on their shared hosting accounts. I can vouch that I've had a positive experience with them.

Here are instructions in their KnowledgeBase for installing node.js using Apache/LiteSpeed as a reverse proxy: https://www.a2hosting.com/kb/installable-applications/manual-installations/installing-node-js-on-managed-hosting-accounts . It takes about 30 minutes to set up the configuration, and it'll work with npm, Express, MySQL, etc.

See a2hosting.com.

Align vertically using CSS 3

There is a simple way to align vertically and horizontally a div in css.

Just put a height to your div and apply this style

.hv-center {
    margin: auto;
    position: absolute;
    top: 0; left: 0; bottom: 0; right: 0;
}

Hope this helped.

What's the difference between utf8_general_ci and utf8_unicode_ci?

Some details (PL)

As we can read here (Peter Gulutzan) there is difference on sorting/comparing polish letter "L" (L with stroke - html esc: &#321;) (lower case: "l" - html esc: &#322;) - we have following assumption:

utf8_polish_ci      L greater than L and less than M
utf8_unicode_ci     L greater than L and less than M
utf8_unicode_520_ci L equal to L
utf8_general_ci     L greater than Z

In polish language letter L is after letter L and before M. No one of this coding is better or worse - it depends of your needs.

How to print a string in C++

#include <iostream>
std::cout << someString << "\n";

or

printf("%s\n",someString.c_str());

Is there any difference between DECIMAL and NUMERIC in SQL Server?

They are the same. Numeric is functionally equivalent to decimal.

MSDN: decimal and numeric

Javascript document.getElementById("id").value returning null instead of empty string when the element is an empty text box

This demo is returning correctly for me in Chrome 14, FF3 and FF5 (with Firebug):

var mytextvalue = document.getElementById("mytext").value;
console.log(mytextvalue == ''); // true
console.log(mytextvalue == null); // false

and changing the console.log to alert, I still get the desired output in IE6.

How can I select the first day of a month in SQL?

Starting with SQL Server 2012:

SELECT DATEADD(DAY,1,EOMONTH(@mydate,-1))

Use a LIKE statement on SQL Server XML Datatype

Yet another option is to cast the XML as nvarchar, and then search for the given string as if the XML vas a nvarchar field.

SELECT * 
FROM Table
WHERE CAST(Column as nvarchar(max)) LIKE '%TEST%'

I love this solution as it is clean, easy to remember, hard to mess up, and can be used as a part of a where clause.

EDIT: As Cliff mentions it, you could use:

...nvarchar if there's characters that don't convert to varchar

Script to Change Row Color when a cell changes text

I used GENEGC's script, but I found it quite slow.

It is slow because it scans whole sheet on every edit.

So I wrote way faster and cleaner method for myself and I wanted to share it.

function onEdit(e) {
    if (e) { 
        var ss = e.source.getActiveSheet();
        var r = e.source.getActiveRange(); 

        // If you want to be specific
        // do not work in first row
        // do not work in other sheets except "MySheet"
        if (r.getRow() != 1 && ss.getName() == "MySheet") {

            // E.g. status column is 2nd (B)
            status = ss.getRange(r.getRow(), 2).getValue();

            // Specify the range with which You want to highlight
            // with some reading of API you can easily modify the range selection properties
            // (e.g. to automatically select all columns)
            rowRange = ss.getRange(r.getRow(),1,1,19);

            // This changes font color
            if (status == 'YES') {
                rowRange.setFontColor("#999999");
            } else if (status == 'N/A') {
                rowRange.setFontColor("#999999");
            // DEFAULT
            } else if (status == '') { 
                rowRange.setFontColor("#000000");
            }   
        }
    }
}

Node - was compiled against a different Node.js version using NODE_MODULE_VERSION 51

I have hit this error twice in an electron app and it turned out the problem was that some modules need to be used from the main process rather than the render process. The error occurred using pdf2json and also node-canvas. Moving the code that required those modules from index.htm (the render process) to main.js (the main process) fixed the error and the app rebuilt and ran perfectly. This will not fix the problem in all cases but it is the first thing to check if you are writing an electron app and run into this error.

Why doesn't "System.out.println" work in Android?

I'll leave this for further visitors as for me it was something about the main thread being unable to System.out.println.

public class LogUtil {

private static String log = "";
private static boolean started = false;
public static void print(String s) {
    //Start the thread unless it's already running
    if(!started) {
        start();
    }
    //Append a String to the log
    log += s;
}

public static void println(String s) {
    //Start the thread unless it's already running
    if(!started) {
        start();
    }
    //Append a String to the log with a newline.
    //NOTE: Change to print(s + "\n") if you don't want it to trim the last newline.
    log += (s.endsWith("\n") )? s : (s + "\n");
}

private static void start() {
    //Creates a new Thread responsible for showing the logs.
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            while(true) {
                //Execute 100 times per second to save CPU cycles.
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //If the log variable has any contents...
                if(!log.isEmpty()) {
                    //...print it and clear the log variable for new data.
                    System.out.print(log);
                    log = "";
                }
            }
        }
    });
    thread.start();
    started = true;
}
}

Usage: LogUtil.println("This is a string");

Escaping single quote in PHP when inserting into MySQL

I had the same problem and I solved it like this:

$text = str_replace("'", "\'", $YourContent);

There is probably a better way to do this, but it worked for me and it should work for you too.

Print series of prime numbers in python

Adding to the accepted answer, further optimization can be achieved by using a list to store primes and printing them after generation.

import math
Primes_Upto = 101
Primes = [2]
for num in range(3,Primes_Upto,2):
    if all(num%i!=0 for i in Primes):
       Primes.append(num)
for i in Primes:
    print i

How do I bind a List<CustomObject> to a WPF DataGrid?

Actually, to properly support sorting, filtering, etc. a CollectionViewSource should be used as a link between the DataGrid and the list, like this:

<Window.Resources>
  <CollectionViewSource x:Key="ItemCollectionViewSource" CollectionViewType="ListCollectionView"/>
</Window.Resources>   

The DataGrid line looks like this:

<DataGrid
  DataContext="{StaticResource ItemCollectionViewSource}"
  ItemsSource="{Binding}"
  AutoGenerateColumns="False">  

In the code behind, you link CollectionViewSource with your link.

CollectionViewSource itemCollectionViewSource;
itemCollectionViewSource = (CollectionViewSource)(FindResource("ItemCollectionViewSource"));
itemCollectionViewSource.Source = itemList;

For detailed example see my article on CoedProject: http://www.codeproject.com/Articles/683429/Guide-to-WPF-DataGrid-formatting-using-bindings

Use async await with Array.map

There's another solution for it if you are not using native Promises but Bluebird.

You could also try using Promise.map(), mixing the array.map and Promise.all

In you case:

  var arr = [1,2,3,4,5];

  var results: number[] = await Promise.map(arr, async (item): Promise<number> => {
    await callAsynchronousOperation(item);
    return item + 1;
  });

How do I add target="_blank" to a link within a specified div?

Using jQuery:

 $('#link_other a').each(function(){
  $(this).attr('target', '_BLANK');
 });

SyntaxError: missing ) after argument list

You had a unescaped " in the onclick handler, escape it with \"

$('#contentData').append("<div class='media'><div class='media-body'><h4 class='media-heading'>" + v.Name + "</h4><p>" + v.Description + "</p><a class='btn' href='" + type + "'  onclick=\"(canLaunch('" + v.LibraryItemId + " '))\">View &raquo;</a></div></div>")

Checking to see if a DateTime variable has had a value assigned

DateTime is value type, so it can not never be null. If you think DateTime? ( Nullable ) you can use:

DateTime? something = GetDateTime();
bool isNull = (something == null);
bool isNull2 = !something.HasValue;

MessageBox with YesNoCancel - No & Cancel triggers same event

Just to add a bit to Darin's example, the below will show an icon with the boxes. http://msdn.microsoft.com/en-us/library/system.windows.forms.messagebox(v=vs.110).aspx

Dim result = MessageBox.Show("Message To Display", "MessageBox Title", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)

If result = DialogResult.Cancel Then

    MessageBox.Show("Cancel Button Pressed", "MessageBox Title",MessageBoxButtons.OK , MessageBoxIcon.Exclamation)

ElseIf result = DialogResult.No Then

    MessageBox.Show("No Button Pressed", "MessageBox Title", MessageBoxButtons.OK, MessageBoxIcon.Error)

ElseIf result = DialogResult.Yes Then

    MessageBox.Show("Yes Button Pressed", "MessageBox Title", MessageBoxButtons.OK, MessageBoxIcon.Information)

End If

Can I change the checkbox size using CSS?

My reputation is slightly too low to post comments, but I made a modification to Jack Miller's code above in order to get it to not change size when you check and uncheck it. This was causing text alignment problems for me.

_x000D_
_x000D_
    input[type=checkbox] {
        width: 17px;
        -webkit-appearance: none;
        -moz-appearance: none;
        height: 17px;
        border: 1px solid black;
    }

    input[type=checkbox]:checked {
        background-color: #F58027;
    }

    input[type=checkbox]:checked:after {
        margin-left: 4px;
        margin-top: -1px;
        width: 4px;
        height: 12px;
        border: solid white;
        border-width: 0 2px 2px 0;
        -webkit-transform: rotate(45deg);
        -moz-transform: rotate(45deg);
        -ms-transform: rotate(45deg);
        transform: rotate(45deg);
        content: "";
        display: inline-block;
    }
    input[type=checkbox]:after {
        margin-left: 4px;
        margin-top: -1px;
        width: 4px;
        height: 12px;
        border: solid white;
        border-width: 0;
        -webkit-transform: rotate(45deg);
        -moz-transform: rotate(45deg);
        -ms-transform: rotate(45deg);
        transform: rotate(45deg);
        content: "";
        display: inline-block;
    }
_x000D_
<label><input type="checkbox"> Test</label>
_x000D_
_x000D_
_x000D_

How to convert a NumPy array to PIL image applying matplotlib colormap

The method described in the accepted answer didn't work for me even after applying changes mentioned in its comments. But the below simple code worked:

import matplotlib.pyplot as plt
plt.imsave(filename, np_array, cmap='Greys')

np_array could be either a 2D array with values from 0..1 floats o2 0..255 uint8, and in that case it needs cmap. For 3D arrays, cmap will be ignored.

javac: file not found: first.java Usage: javac <options> <source files>

Seems like you have your path right. But what is your working directory? on command prompt run:

javac -version

this should show your java version. if it doesnt, you have not set java in path correctly.

navigate to C:

cd \

Then:

javac -sourcepath users\AccName\Desktop -d users\AccName\Desktop first.java

-sourcepath is the complete path to your .java file, -d is the path/directory you want your .class files to be, then finally the file you want compiled (first.java).

Adding Permissions in AndroidManifest.xml in Android Studio?

You can only type them manually, but the content assist helps you there, so it is pretty easy.

Add this line

<uses-permission android:name="android.permission."/> 

and hit ctrl + space after the dot (or cmd + space on Mac). If you need an explanation for the permission, you can hit ctrl + q.

How can I detect when the mouse leaves the window?

If you are using jQuery then how about this short and sweet code -

$(document).mouseleave(function () {
    console.log('out');
});

This event will trigger whenever the mouse is not in your page as you want. Just change the function to do whatever you want.

And you could also use:

$(document).mouseenter(function () {
    console.log('in');
});

To trigger when the mouse enters back to the page again.

Source: https://stackoverflow.com/a/16029966/895724

Why do I get java.lang.AbstractMethodError when trying to load a blob in the db?

The problem is due to older version of ojdbc - ojdbc14.

Place the latest version of ojdbc jar file in your application or shared library. (Only one version should be there and it should be the latest one) As of today - ojdbc6.jar

Check the application libraries and shared libraries on server.

Python Write bytes to file

Write bytes and Create the file if not exists:

f = open('./put/your/path/here.png', 'wb')
f.write(data)
f.close()

wb means open the file in write binary mode.

A JSONObject text must begin with '{' at 1 [character 2 line 1] with '{' error

I had similar issue due to a small mistake, when i was trying to convert a List to json. If a List is converted to json it will return JSONArray not JSONObject.

How to Sort a List<T> by a property in the object

Doing it without Linq as you said:

public class Order : IComparable
{
    public DateTime OrderDate { get; set; }
    public int OrderId { get; set; }

    public int CompareTo(object obj)
    {
        Order orderToCompare = obj as Order;
        if (orderToCompare.OrderDate < OrderDate || orderToCompare.OrderId < OrderId)
        {
            return 1;
        }
        if (orderToCompare.OrderDate > OrderDate || orderToCompare.OrderId > OrderId)
        {
            return -1;
        }

        // The orders are equivalent.
        return 0;
    }
}

Then just call .sort() on your list of Orders

Excel Define a range based on a cell value

Say you have number 1,2,3,4,5,6, in cell A1,A2,A3,A4,A5,A6 respectively. in cell A7 we calculate the sum of A1:Ax. x is specified in cell B1 (in this case, x can be any number from 1 to 6). in cell A7, you can write the following formular:

=SUM(A1:INDIRECT(CONCATENATE("A",B1)))

CONCATENATE will give you the index of the cell Ax(if you put 3 in B1, CONCATENATE("A",B1)) gives A3).

INDIRECT convert "A3" to a index.

see this link Using the value in a cell as a cell reference in a formula?

Possible to make labels appear when hovering over a point in matplotlib?

A slight edit on an example provided in http://matplotlib.org/users/shell.html:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_title('click on points')

line, = ax.plot(np.random.rand(100), '-', picker=5)  # 5 points tolerance


def onpick(event):
    thisline = event.artist
    xdata = thisline.get_xdata()
    ydata = thisline.get_ydata()
    ind = event.ind
    print('onpick points:', *zip(xdata[ind], ydata[ind]))


fig.canvas.mpl_connect('pick_event', onpick)

plt.show()

This plots a straight line plot, as Sohaib was asking

When to use %r instead of %s in Python?

Use the %r for debugging, since it displays the "raw" data of the variable, but the others are used for displaying to users.

That's how %r formatting works; it prints it the way you wrote it (or close to it). It's the "raw" format for debugging. Here \n used to display to users doesn't work. %r shows the representation if the raw data of the variable.

months = "\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
print "Here are the months: %r" % months

Output:

Here are the months: '\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug'

Check this example from Learn Python the Hard Way.

Under which circumstances textAlign property works in Flutter?

You can use the container, It will help you to set the alignment.

Widget _buildListWidget({Map reminder}) {
return Container(
  color: Colors.amber,
  alignment: Alignment.centerLeft,
  padding: EdgeInsets.all(20),
  height: 80,
  child: Column(
    mainAxisAlignment: MainAxisAlignment.center,
    crossAxisAlignment: CrossAxisAlignment.center,
    children: <Widget>[
      Container(
        alignment: Alignment.centerLeft,
        child: Text(
          reminder['title'],
          textAlign: TextAlign.left,
          style: TextStyle(
            fontSize: 16,
            color: Colors.black,
            backgroundColor: Colors.blue,
            fontWeight: FontWeight.normal,
          ),
        ),
      ),
      Container(
        alignment: Alignment.centerRight,
        child: Text(
          reminder['Date'],
          textAlign: TextAlign.right,
          style: TextStyle(
            fontSize: 12,
            color: Colors.grey,
            backgroundColor: Colors.blue,
            fontWeight: FontWeight.normal,
          ),
        ),
      ),
    ],
  ),
);
}

What is the Oracle equivalent of SQL Server's IsNull() function?

coalesce is supported in both Oracle and SQL Server and serves essentially the same function as nvl and isnull. (There are some important differences, coalesce can take an arbitrary number of arguments, and returns the first non-null one. The return type for isnull matches the type of the first argument, that is not true for coalesce, at least on SQL Server.)

Calculating Time Difference

Here is a piece of code to do so:

def(StringChallenge(str1)):

#str1 = str1[1:-1]
h1 = 0
h2 = 0
m1 = 0
m2 = 0

def time_dif(h1,m1,h2,m2):
    if(h1 == h2):
        return m2-m1
    else:
        return ((h2-h1-1)*60 + (60-m1) + m2)
count_min = 0

if str1[1] == ':':
    h1=int(str1[:1])
    m1=int(str1[2:4])
else:
    h1=int(str1[:2])
    m1=int(str1[3:5])

if str1[-7] == '-':
    h2=int(str1[-6])
    m2=int(str1[-4:-2])
else:
    h2=int(str1[-7:-5])
    m2=int(str1[-4:-2])

if h1 == 12:
    h1 = 0
if h2 == 12:
    h2 = 0

if "am" in str1[:8]:
    flag1 = 0
else:
    flag1= 1

if "am" in str1[7:]:
    flag2 = 0
else:
    flag2 = 1

if flag1 == flag2:
    if h2 > h1 or (h2 == h1 and m2 >= m1):
        count_min += time_dif(h1,m1,h2,m2)
    else:
        count_min += 1440 - time_dif(h2,m2,h1,m1)
else:
    count_min += (12-h1-1)*60
    count_min += (60 - m1)
    count_min += (h2*60)+m2


return count_min

Cannot use a leading ../ to exit above the top directory

What this means is that your web page is referring to content which is in the folder one level up from your page, but your page is already in the website's root folder, so the relative path is invalid. Judging by your exception message it looks like an image control is causing the problem.

You must have something like:

<asp:Image ImageUrl="..\foo.jpg" />

But since the page itself is in the root folder of the website, it cannot refer to content one level up, which is what the leading ..\ is doing.

Copy Data from a table in one Database to another separate database

Don't forget to insert SET IDENTITY_INSERT MobileApplication1 ON to the top, else you will get an error. This is for SQL Server

SET IDENTITY_INSERT MOB.MobileApplication1 ON
INSERT INTO [SERVER1].DB.MOB.MobileApplication1 m
      (m.MobileApplicationDetailId,
       m.MobilePlatformId)
SELECT ma.MobileApplicationId,
       ma.MobilePlatformId 
FROM [SERVER2].DB.MOB.MobileApplication2 ma

Postgresql, update if row with some unique value exists, else insert

Firstly It tries insert. If there is a conflict on url column then it updates content and last_analyzed fields. If updates are rare this might be better option.

INSERT INTO URLs (url, content, last_analyzed)
VALUES
    (
        %(url)s,
        %(content)s,
        NOW()
    ) 
ON CONFLICT (url) 
DO
UPDATE
SET content=%(content)s, last_analyzed = NOW();

Best way to check for "empty or null value"

To check for null and empty:

coalesce(string, '') = ''

To check for null, empty and spaces (trim the string)

coalesce(TRIM(string), '') = ''

Hashmap does not work with int, char

Generics only support object types, not primitives. Unlike C++ templates, generics don't involve code generatation and there is only one HashMap code regardless of the number of generic types of it you use.

Trove4J gets around this by pre-generating selected collections to use primitives and supports TCharIntHashMap which to can wrap to support the Map<Character, Integer> if you need to.

TCharIntHashMap: An open addressed Map implementation for char keys and int values.

The input is not a valid Base-64 string as it contains a non-base 64 character

I arranged a similar context as you described and I faced the same error. I managed to get it working by removing the " from the beginning and the end of the content and by replacing \/ with /.

Here is the code snippet:

var result = client.Execute(request);
var response = result.Content
    .Substring(1, result.Content.Length - 2)
    .Replace(@"\/","/");
byte[] d = Convert.FromBase64String(response);

As an alternative, you might consider using XML for the response format:

[WebGet(UriTemplate = "ReadFile/Convert", ResponseFormat = WebMessageFormat.Xml)]  
public string ExportToExcel() { //... }

On the client side:

request.AddHeader("Accept", "application/xml");
request.AddHeader("Content-Type", "application/xml");
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/xml"; };

var result = client.Execute(request);
var doc = new System.Xml.XmlDocument();
doc.LoadXml(result.Content);
var xml = doc.InnerText;
byte[] d = Convert.FromBase64String(xml);

Safely remove migration In Laravel

I accidentally created two times create_users_table. It overrided some classes and turned rollback into ErrorException.

What you need to do is find autoload_classmap.php in vendor/composer folder and look for the specific line of code such as

'CreateUsersTable' => $baseDir . '/app/database/migrations/2013_07_04_014051_create_users_table.php',

and edit path. Then your rollback should be fine.

Pros/cons of using redux-saga with ES6 generators vs redux-thunk with ES2017 async/await

I will add my experience using saga in production system in addition to the library author's rather thorough answer.

Pro (using saga):

  • Testability. It's very easy to test sagas as call() returns a pure object. Testing thunks normally requires you to include a mockStore inside your test.

  • redux-saga comes with lots of useful helper functions about tasks. It seems to me that the concept of saga is to create some kind of background worker/thread for your app, which act as a missing piece in react redux architecture(actionCreators and reducers must be pure functions.) Which leads to next point.

  • Sagas offer independent place to handle all side effects. It is usually easier to modify and manage than thunk actions in my experience.

Con:

  • Generator syntax.

  • Lots of concepts to learn.

  • API stability. It seems redux-saga is still adding features (eg Channels?) and the community is not as big. There is a concern if the library makes a non backward compatible update some day.

How do I find out what License has been applied to my SQL Server installation?

This shows the licence type and number of licences:

SELECT SERVERPROPERTY('LicenseType'), SERVERPROPERTY('NumLicenses')

How can I get list of values from dict?

out: dict_values([{1:a, 2:b}])

in:  str(dict.values())[14:-3]    
out: 1:a, 2:b

Purely for visual purposes. Does not produce a useful product... Only useful if you want a long dictionary to print in a paragraph type form.

How to decode viewstate

Here's an online ViewState decoder:

http://ignatu.co.uk/ViewStateDecoder.aspx

Edit: Unfortunatey, the above link is dead - here's another ViewState decoder (from the comments):

http://viewstatedecoder.azurewebsites.net/

How do I choose grid and block dimensions for CUDA kernels?

The answers above point out how the block size can impact performance and suggest a common heuristic for its choice based on occupancy maximization. Without wanting to provide the criterion to choose the block size, it would be worth mentioning that CUDA 6.5 (now in Release Candidate version) includes several new runtime functions to aid in occupancy calculations and launch configuration, see

CUDA Pro Tip: Occupancy API Simplifies Launch Configuration

One of the useful functions is cudaOccupancyMaxPotentialBlockSize which heuristically calculates a block size that achieves the maximum occupancy. The values provided by that function could be then used as the starting point of a manual optimization of the launch parameters. Below is a little example.

#include <stdio.h>

/************************/
/* TEST KERNEL FUNCTION */
/************************/
__global__ void MyKernel(int *a, int *b, int *c, int N) 
{ 
    int idx = threadIdx.x + blockIdx.x * blockDim.x; 

    if (idx < N) { c[idx] = a[idx] + b[idx]; } 
} 

/********/
/* MAIN */
/********/
void main() 
{ 
    const int N = 1000000;

    int blockSize;      // The launch configurator returned block size 
    int minGridSize;    // The minimum grid size needed to achieve the maximum occupancy for a full device launch 
    int gridSize;       // The actual grid size needed, based on input size 

    int* h_vec1 = (int*) malloc(N*sizeof(int));
    int* h_vec2 = (int*) malloc(N*sizeof(int));
    int* h_vec3 = (int*) malloc(N*sizeof(int));
    int* h_vec4 = (int*) malloc(N*sizeof(int));

    int* d_vec1; cudaMalloc((void**)&d_vec1, N*sizeof(int));
    int* d_vec2; cudaMalloc((void**)&d_vec2, N*sizeof(int));
    int* d_vec3; cudaMalloc((void**)&d_vec3, N*sizeof(int));

    for (int i=0; i<N; i++) {
        h_vec1[i] = 10;
        h_vec2[i] = 20;
        h_vec4[i] = h_vec1[i] + h_vec2[i];
    }

    cudaMemcpy(d_vec1, h_vec1, N*sizeof(int), cudaMemcpyHostToDevice);
    cudaMemcpy(d_vec2, h_vec2, N*sizeof(int), cudaMemcpyHostToDevice);

    float time;
    cudaEvent_t start, stop;
    cudaEventCreate(&start);
    cudaEventCreate(&stop);
    cudaEventRecord(start, 0);

    cudaOccupancyMaxPotentialBlockSize(&minGridSize, &blockSize, MyKernel, 0, N); 

    // Round up according to array size 
    gridSize = (N + blockSize - 1) / blockSize; 

    cudaEventRecord(stop, 0);
    cudaEventSynchronize(stop);
    cudaEventElapsedTime(&time, start, stop);
    printf("Occupancy calculator elapsed time:  %3.3f ms \n", time);

    cudaEventRecord(start, 0);

    MyKernel<<<gridSize, blockSize>>>(d_vec1, d_vec2, d_vec3, N); 

    cudaEventRecord(stop, 0);
    cudaEventSynchronize(stop);
    cudaEventElapsedTime(&time, start, stop);
    printf("Kernel elapsed time:  %3.3f ms \n", time);

    printf("Blocksize %i\n", blockSize);

    cudaMemcpy(h_vec3, d_vec3, N*sizeof(int), cudaMemcpyDeviceToHost);

    for (int i=0; i<N; i++) {
        if (h_vec3[i] != h_vec4[i]) { printf("Error at i = %i! Host = %i; Device = %i\n", i, h_vec4[i], h_vec3[i]); return; };
    }

    printf("Test passed\n");

}

EDIT

The cudaOccupancyMaxPotentialBlockSize is defined in the cuda_runtime.h file and is defined as follows:

template<class T>
__inline__ __host__ CUDART_DEVICE cudaError_t cudaOccupancyMaxPotentialBlockSize(
    int    *minGridSize,
    int    *blockSize,
    T       func,
    size_t  dynamicSMemSize = 0,
    int     blockSizeLimit = 0)
{
    return cudaOccupancyMaxPotentialBlockSizeVariableSMem(minGridSize, blockSize, func, __cudaOccupancyB2DHelper(dynamicSMemSize), blockSizeLimit);
}

The meanings for the parameters is the following

minGridSize     = Suggested min grid size to achieve a full machine launch.
blockSize       = Suggested block size to achieve maximum occupancy.
func            = Kernel function.
dynamicSMemSize = Size of dynamically allocated shared memory. Of course, it is known at runtime before any kernel launch. The size of the statically allocated shared memory is not needed as it is inferred by the properties of func.
blockSizeLimit  = Maximum size for each block. In the case of 1D kernels, it can coincide with the number of input elements.

Note that, as of CUDA 6.5, one needs to compute one's own 2D/3D block dimensions from the 1D block size suggested by the API.

Note also that the CUDA driver API contains functionally equivalent APIs for occupancy calculation, so it is possible to use cuOccupancyMaxPotentialBlockSize in driver API code in the same way shown for the runtime API in the example above.

How to validate a url in Python? (Malformed or not)

Not directly relevant, but often it's required to identify whether some token CAN be a url or not, not necessarily 100% correctly formed (ie, https part omitted and so on). I've read this post and did not find the solution, so I am posting my own here for the sake of completeness.

def get_domain_suffixes():
    import requests
    res=requests.get('https://publicsuffix.org/list/public_suffix_list.dat')
    lst=set()
    for line in res.text.split('\n'):
        if not line.startswith('//'):
            domains=line.split('.')
            cand=domains[-1]
            if cand:
                lst.add('.'+cand)
    return tuple(sorted(lst))

domain_suffixes=get_domain_suffixes()

def reminds_url(txt:str):
    """
    >>> reminds_url('yandex.ru.com/somepath')
    True
    
    """
    ltext=txt.lower().split('/')[0]
    return ltext.startswith(('http','www','ftp')) or ltext.endswith(domain_suffixes)

Elegant way to check for missing packages and install them?

Thought I'd contribute the one I use:

testin <- function(package){if (!package %in% installed.packages())    
install.packages(package)}
testin("packagename")

Commit history on remote repository

I'm not sure when filtering was added but it's a way to exclude the object blobs if you only want to fetch the history/ref-logs:

git clone --filter=blob:none --no-checkout --single-branch --branch master git://some.repo.git .
git log

Proper way to use **kwargs in Python

Using **kwargs and default values is easy. Sometimes, however, you shouldn't be using **kwargs in the first place.

In this case, we're not really making best use of **kwargs.

class ExampleClass( object ):
    def __init__(self, **kwargs):
        self.val = kwargs.get('val',"default1")
        self.val2 = kwargs.get('val2',"default2")

The above is a "why bother?" declaration. It is the same as

class ExampleClass( object ):
    def __init__(self, val="default1", val2="default2"):
        self.val = val
        self.val2 = val2

When you're using **kwargs, you mean that a keyword is not just optional, but conditional. There are more complex rules than simple default values.

When you're using **kwargs, you usually mean something more like the following, where simple defaults don't apply.

class ExampleClass( object ):
    def __init__(self, **kwargs):
        self.val = "default1"
        self.val2 = "default2"
        if "val" in kwargs:
            self.val = kwargs["val"]
            self.val2 = 2*self.val
        elif "val2" in kwargs:
            self.val2 = kwargs["val2"]
            self.val = self.val2 / 2
        else:
            raise TypeError( "must provide val= or val2= parameter values" )

How to print values separated by spaces instead of new lines in Python 2.7

First of all print isn't a function in Python 2, it is a statement.

To suppress the automatic newline add a trailing ,(comma). Now a space will be used instead of a newline.

Demo:

print 1,
print 2

output:

1 2

Or use Python 3's print() function:

from __future__ import print_function
print(1, end=' ') # default value of `end` is '\n'
print(2)

As you can clearly see print() function is much more powerful as we can specify any string to be used as end rather a fixed space.

Open mvc view in new window from controller

@Html.ActionLink("linkText", "Action", new {controller="Controller"}, new {target="_blank",@class="edit"})

   script below will open the action view url in a new window

<script type="text/javascript">
    $(function (){
        $('a.edit').click(function () {
            var url = $(this).attr('href');
            window.open(url, "popupWindow", "width=600,height=800,scrollbars=yes");
            });
            return false;
        });   
</script>

How do I skip a header from CSV files in Spark?

It's an option that you pass to the read() command:

context = new org.apache.spark.sql.SQLContext(sc)

var data = context.read.option("header","true").csv("<path>")

How to convert text column to datetime in SQL

This works:

SELECT STR_TO_DATE(dateColumn, '%c/%e/%Y %r') FROM tabbleName WHERE 1

Microsoft Visual C++ 14.0 is required (Unable to find vcvarsall.bat)

Binary install it the simple way!

I can't believe no one has suggested this already - use the binary-only option for pip. For example, for mysqlclient:

pip install --only-binary :all: mysqlclient

Many packages don't create a build for every single release which forces your pip to build from source. If you're happy to use the latest pre-compiled binary version, use --only-binary :all: to allow pip to use an older binary version.

How to expand a list to function arguments in Python

Try the following:

foo(*values)

This can be found in the Python docs as Unpacking Argument Lists.