Programs & Examples On #Applescript

AppleScript is an end user scripting language that has been available in Mac computers since System 7 Pro (7.1.1). It allows for automation of system tasks, communication between processes, and creation of workflows, amongst other functions.

How do I make a Mac Terminal pop-up/alert? Applescript?

I made a script to solve this which is here. You don't need any extra software for this. Installation:
brew install akashaggarwal7/tools/tsay
Usage:
sleep 5; tsay

Feel free to contribute!

Sending commands and strings to Terminal.app with Applescript

set up passwordless ssh (ssh-keygen, then add the key to ~/.ssh/authorized_keys on the server). Make an entry in ~/.ssh/config (on your desktop), so that when you run ssh mysqlserver, it goes to user@hostname... Or make a shell alias, like gotosql, that expands to ssh user@host -t 'mysql_client ...' to start the mysql client interactively on the server.

Then you probably do need someone else's answer to script the process after that, since I don't know how to set startup commands for mysql.

At least that keeps your ssh password out of the script!

What is causing this error - "Fatal error: Unable to find local grunt"

Being new to grunt and setting it up, I am running (perhaps foolishly) my grunt project/folder from a Google Drive so I can access the same code/builds from either my laptop or workstation.

There is a fair bit of synchronisation of the nodes_modules folders back to Google Drive and there seemed to be a conflict at some point, and the /nodes_modules/grunt folder was renamed to /nodes_modules/grunt (1)

Renaming it back by removing the (1) seemed to fix it for me.

SeekBar and media player in android

This works for me:

seekbarPlayer.setMax(mp.getDuration());
getActivity().runOnUiThread(new Runnable() {

    @Override
    public void run() {
        if(mp != null){
            seekbarPlayer.setProgress(mp.getCurrentPosition());
        }
        mHandler.postDelayed(this, 1000);
    }
});

Changing Jenkins build number

Perhaps a combination of these plugins may come in handy:

How does strcmp() work?

This code is equivalent, shorter, and more readable:

int8_t strcmp (const uint8_t* s1, const uint8_t* s2)
{
    while( (*s1!='\0') && (*s1==*s2) ){
        s1++; 
        s2++;
    }

    return (int8_t)*s1 - (int8_t)*s2;
}

We only need to test for end of s1, because if we reach the end of s2 before end of s1, the loop will terminate (since *s2 != *s1).

The return expression calculates the correct value in every case, provided we are only using 7-bit (pure ASCII) characters. Careful thought is needed to produce correct code for 8-bit characters, because of the risk of integer overflow.

How to program a fractal?

There is a great book called Chaos and Fractals that has simple example code at the end of each chapter that implements some fractal or other example. A long time ago when I read that book, I converted each sample program (in some Basic dialect) into a Java applet that runs on a web page. The applets are here: http://hewgill.com/chaos-and-fractals/

One of the samples is a simple Mandelbrot implementation.

The proxy server received an invalid response from an upstream server

This is not mentioned in you post but I suspect you are initiating an SSL connection from the browser to Apache, where VirtualHosts are configured, and Apache does a revese proxy to your Tomcat.

There is a serious bug in (some versions ?) of IE that sends the 'wrong' host information in an SSL connection (see EDIT below) and confuses the Apache VirtualHosts. In short the server name presented is the one of the reverse DNS resolution of the IP, not the one in the URL.

The workaround is to have one IP address per SSL virtual hosts/server name. Is short, you must end up with something like

1 server name == 1 IP address == 1 certificate == 1 Apache Virtual Host

EDIT

Though the conclusion is correct, the identification of the problem is better described here http://en.wikipedia.org/wiki/Server_Name_Indication

What is the benefit of zerofill in MySQL?

One example in order to understand, where the usage of ZEROFILL might be interesting:

In Germany, we have 5 digit zipcodes. However, those Codes may start with a Zero, so 80337 is a valid zipcode for munic, 01067 is a zipcode of Berlin.

As you see, any German citizen expects the zipcodes to be displayed as a 5 digit code, so 1067 looks strange.

In order to store those data, you could use a VARCHAR(5) or INT(5) ZEROFILL whereas the zerofilled integer has two big advantages:

  1. Lot lesser storage space on hard disk
  2. If you insert 1067, you still get 01067 back

Maybe this example helps understanding the use of ZEROFILL.

What are the recommendations for html <base> tag?

One thing to keep in mind:

If you develop a webpage to be displayed within UIWebView on iOS, then you have to use BASE tag. It simply won't work otherwise. Be that JavaScript, CSS, images - none of them will work with relative links under UIWebView, unless tag BASE is specified.

I've been caught by this before, till I found out.

Is it possible to start activity through adb shell?

Launch adb shell and enter the command as follows

am start -n yourpackagename/.activityname

How to use range-based for() loop with std::map?

If you only want to see the keys/values from your map and like using boost, you can use the boost adaptors with the range based loops:

for (const auto& value : myMap | boost::adaptors::map_values)
{
    std::cout << value << std::endl;
}

there is an equivalent boost::adaptors::key_values

http://www.boost.org/doc/libs/1_51_0/libs/range/doc/html/range/reference/adaptors/reference/map_values.html

HTML select drop-down with an input field

You can use input text with "list" attribute, which refers to the datalist of values.

_x000D_
_x000D_
<input type="text" name="city" list="cityname">_x000D_
    <datalist id="cityname">_x000D_
      <option value="Boston">_x000D_
      <option value="Cambridge">_x000D_
    </datalist>
_x000D_
_x000D_
_x000D_

This creates a free text input field that also has a drop-down to select predefined choices. Attribution for example and more information: https://www.w3.org/wiki/HTML/Elements/datalist

Creating temporary files in Android

You can use the cache dir using context.getCacheDir().

File temp=File.createTempFile("prefix","suffix",context.getCacheDir());

HTTP POST with URL query parameters -- good idea or not?

The REST camp have some guiding principles that we can use to standardize the way we use HTTP verbs. This is helpful when building RESTful API's as you are doing.

In a nutshell: GET should be Read Only i.e. have no effect on server state. POST is used to create a resource on the server. PUT is used to update or create a resource. DELETE is used to delete a resource.

In other words, if your API action changes the server state, REST advises us to use POST/PUT/DELETE, but not GET.

User agents usually understand that doing multiple POSTs is bad and will warn against it, because the intent of POST is to alter server state (eg. pay for goods at checkout), and you probably don't want to do that twice!

Compare to a GET which you can do an often as you like (idempotent).

How to listen state changes in react.js?

It's been a while but for future reference: the method shouldComponentUpdate() can be used.

An update can be caused by changes to props or state. These methods are called in the following order when a component is being re-rendered:

static getDerivedStateFromProps() 
shouldComponentUpdate() 
render()
getSnapshotBeforeUpdate() 
componentDidUpdate()

ref: https://reactjs.org/docs/react-component.html

How to center a checkbox in a table cell?

This should work, I am using it:

<td align="center"> <input type="checkbox" name="myTextEditBox" value="checked" ></td>

Show a div with Fancybox

You just use this and it will be helpful for you

$("#btnForm").click(function (){

$.fancybox({
    'padding':  0,
    'width':    1087,
    'height':   610,
    'type':     'iframe',
    content:   $('#divForm').show();
        });

});

how to run two commands in sudo?

For your command you also could refer to the following example:

sudo sh -c 'whoami; whoami'

What's the difference between .bashrc, .bash_profile, and .environment?

I have used Debian-family distros which appear to execute .profile, but not .bash_profile, whereas RHEL derivatives execute .bash_profile before .profile.

It seems to be a mess when you have to set up environment variables to work in any Linux OS.

Replace all non Alpha Numeric characters, New Lines, and multiple White Space with one Space

Since [^a-z0-9] character class contains all that is not alnum, it contains white characters too!

 text.replace(/[^a-z0-9]+/gi, " ");

How to delete a workspace in Perforce (using p4v)?

From the "View" menu, select "Workspaces". You'll see all of the workspaces you've created. Select the workspaces you want to delete and click "Edit" -> "Delete Workspace", or right-click and select "Delete Workspace". If the workspace is "locked" to prevent changes, you'll get an error message.

To unlock the workspace, click "Edit" (or right-click and click "Edit Workspace") to pull up the workspace editor, uncheck the "locked" checkbox, and save your changes. You can delete the workspace once it's unlocked.

In my experience, the workspace will continue to be shown in the drop-down list until you click on it, at which point p4v will figure out you've deleted it and remove it from the list.

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

Actually, I think this is the best way.

from django.core.validators import URLValidator
from django.core.exceptions import ValidationError

val = URLValidator(verify_exists=False)
try:
    val('http://www.google.com')
except ValidationError, e:
    print e

If you set verify_exists to True, it will actually verify that the URL exists, otherwise it will just check if it's formed correctly.

edit: ah yeah, this question is a duplicate of this: How can I check if a URL exists with Django’s validators?

Error handling with PHPMailer

Even if you use exceptions, it still output errors.
You have to set $MailerDebug to False wich should look like this

$mail = new PHPMailer();
$mail->MailerDebug = false;

How to fix: "No suitable driver found for jdbc:mysql://localhost/dbname" error when using pools?

I had the same problem, all you need to do is define classpath environment variable for tomcat, you can do it by adding a file, in my case C:\apache-tomcat-7.0.30\bin\setenv.bat, containing:

set "CLASSPATH=%CLASSPATH%;%CATALINA_HOME%\lib\mysql-connector-java-5.1.14-bin.jar"

then code, in my case:

Class.forName("com.mysql.jdbc.Driver").newInstance(); 
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database_name", "root", "");

works fine.

How to configure WAMP (localhost) to send email using Gmail?

If you open the php.ini file in wamp, you will find these two lines:

smtp_server
smtp_port

Add the server and port number for your host (you may need to contact them for details)

The following two lines don't exist:

auth_username
auth_password

So you will need to add them to be able to send mail from a server that requires authentication. So an example may be:

smtp_server = mail.example.com
smtp_port = 26
auth_username = [email protected]
auth_password = example_password

Get OS-level system information

If you are using Jrockit VM then here is an other way of getting VM CPU usage. Runtime bean can also give you CPU load per processor. I have used this only on Red Hat Linux to observer Tomcat performance. You have to enable JMX remote in catalina.sh for this to work.

JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://my.tomcat.host:8080/jmxrmi");
JMXConnector jmxc = JMXConnectorFactory.connect(url, null);     
MBeanServerConnection conn = jmxc.getMBeanServerConnection();       
ObjectName name = new ObjectName("oracle.jrockit.management:type=Runtime");
Double jvmCpuLoad =(Double)conn.getAttribute(name, "VMGeneratedCPULoad");

How can I add an item to a SelectList in ASP.net MVC

As this option may need in many different manners, i reached to conclusion to develop an object so that it can be used in different scenarios and in future projects

first add this class to your project

public class SelectListDefaults
{
    private IList<SelectListItem> getDefaultItems = new List<SelectListItem>();

    public SelectListDefaults()
    {
        this.AddDefaultItem("(All)", "-1");
    }
    public SelectListDefaults(string text, string value)
    {
        this.AddDefaultItem(text, value);
    }
    public IList<SelectListItem> GetDefaultItems
    {
        get
        {                
            return getDefaultItems;
        }

    }
    public void AddDefaultItem(string text, string value)
    {        
        getDefaultItems.Add(new SelectListItem() { Text = text, Value = value });                    
    }
}

Now in Controller Action you can do like this

    // Now you can do like this
    ViewBag.MainCategories = new SelectListDefaults().GetDefaultItems.Concat(new SelectList(db.MainCategories, "MainCategoryID", "Name", Request["DropDownListMainCategory"] ?? "-1"));
    // Or can change it by such a simple way
    ViewBag.MainCategories = new SelectListDefaults("Any","0").GetDefaultItems.Concat(new SelectList(db.MainCategories, "MainCategoryID", "Name", Request["DropDownListMainCategory"] ?? "0"));
    // And even can add more options
    SelectListDefaults listDefaults = new SelectListDefaults();
    listDefaults.AddDefaultItme("(Top 5)", "-5");
    // If Top 5 selected by user, you may need to do something here with db.MainCategories, or pass in parameter to method 
    ViewBag.MainCategories = listDefaults.GetDefaultItems.Concat(new SelectList(db.MainCategories, "MainCategoryID", "Name", Request["DropDownListMainCategory"] ?? "-1"));

And finally in View you will code like this.

@Html.DropDownList("DropDownListMainCategory", (IEnumerable<SelectListItem>)ViewBag.MainCategories, new { @class = "form-control", onchange = "this.form.submit();" })

Javascript : array.length returns undefined

try this

Object.keys(data).length

If IE < 9, you can loop through the object yourself with a for loop

var len = 0;
var i;

for (i in data) {
    if (data.hasOwnProperty(i)) {
        len++;
    }
}

Get current value when change select option - Angular2

There is a way to get the value from different options. check this plunker

component.html

<select class="form-control" #t (change)="callType(t.value)">
  <option *ngFor="#type of types" [value]="type">{{type}}</option>
</select>

component.ts

this.types = [ 'type1', 'type2', 'type3' ];

callType(value) {
  console.log(value);
  this.order.type = value;
}

Iterating through directories with Python

From python >= 3.5 onward, you can use **, glob.iglob(path/**, recursive=True) and it seems the most pythonic solution, i.e.:

import glob, os

for filename in glob.iglob('/pardadox-music/**', recursive=True):
    if os.path.isfile(filename): # filter dirs
        print(filename)

Output:

/pardadox-music/modules/her1.mod
/pardadox-music/modules/her2.mod
...

Notes:
1 - glob.iglob

glob.iglob(pathname, recursive=False)

Return an iterator which yields the same values as glob() without actually storing them all simultaneously.

2 - If recursive is True, the pattern '**' will match any files and zero or more directories and subdirectories.

3 - If the directory contains files starting with . they won’t be matched by default. For example, consider a directory containing card.gif and .card.gif:

>>> import glob
>>> glob.glob('*.gif') ['card.gif'] 
>>> glob.glob('.c*')['.card.gif']

4 - You can also use rglob(pattern), which is the same as calling glob() with **/ added in front of the given relative pattern.

Using an array from Observable Object with ngFor and Async Pipe Angular 2

If you don't have an array but you are trying to use your observable like an array even though it's a stream of objects, this won't work natively. I show how to fix this below assuming you only care about adding objects to the observable, not deleting them.

If you are trying to use an observable whose source is of type BehaviorSubject, change it to ReplaySubject then in your component subscribe to it like this:

Component

this.messages$ = this.chatService.messages$.pipe(scan((acc, val) => [...acc, val], []));

Html

<div class="message-list" *ngFor="let item of messages$ | async">

git: Switch branch and ignore any changes without committing

If you have made changes to files that Git also needs to change when switching branches, it won't let you. To discard working changes, use:

git reset --hard HEAD

Then, you will be able to switch branches.

Autowiring two beans implementing same interface - how to set default bean to autowire?

What about @Primary?

Indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency. If exactly one 'primary' bean exists among the candidates, it will be the autowired value. This annotation is semantically equivalent to the <bean> element's primary attribute in Spring XML.

@Primary
public class HibernateDeviceDao implements DeviceDao

Or if you want your Jdbc version to be used by default:

<bean id="jdbcDeviceDao" primary="true" class="com.initech.service.dao.jdbc.JdbcDeviceDao">

@Primary is also great for integration testing when you can easily replace production bean with stubbed version by annotating it.

Longer object length is not a multiple of shorter object length?

Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.

In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.

Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.

Creating csv file with php

Just in case if someone is wondering to save the CSV file to a specific path for email attachments. Then it can be done as follows

I know I have added a lot of comments just for newbies :)

I have added an example so that you can summarize well.

$activeUsers = /** Query to get the active users */

/** Following is the Variable to store the Users data as 
    CSV string with newline character delimiter, 

    its good idea of check the delimiter based on operating system */

$userCSVData = "Name,Email,CreatedAt\n";

/** Looping the users and appending to my earlier csv data variable */
foreach ( $activeUsers as $user ) {
    $userCSVData .= $user->name. "," . $user->email. "," . $user->created_at."\n";
}
/** Here you can use with H:i:s too. But I really dont care of my old file  */
$todayDate  = date('Y-m-d');
/** Create Filname and Path to Store */
$fileName   = 'Active Users '.$todayDate.'.csv';
$filePath   = public_path('uploads/'.$fileName); //I am using laravel helper, in case if your not using laravel then just add absolute or relative path as per your requirements and path to store the file

/** Just in case if I run the script multiple time 
    I want to remove the old file and add new file.

    And before deleting the file from the location I am making sure it exists */
if(file_exists($filePath)){
    unlink($filePath);
}
$fp = fopen($filePath, 'w+');
fwrite($fp, $userCSVData); /** Once the data is written it will be saved in the path given */
fclose($fp);

/** Now you can send email with attachments from the $filePath */

NOTE: The following is a very bad idea to increase the memory_limit and time limit, but I have only added to make sure if anyone faces the problem of connection time out or any other. Make sure to find out some alternative before sticking to it.

You have to add the following at the start of the above script.

ini_set("memory_limit", "10056M");
set_time_limit(0);
ini_set('mysql.connect_timeout', '0');
ini_set('max_execution_time', '0');

Connect over ssh using a .pem file

Use the -i option:

ssh -i mykey.pem [email protected]

As noted in this answer, this file needs to have correct permissions set. The ssh man page says:

ssh will simply ignore a private key file if it is accessible by others.

You can change the permissions with this command:

chmod go= mykey.pem

That is, set permissions for group and others equal to the empty list of permissions.

PHP - Session destroy after closing browser

You can do it using JavaScript by triggering an ajax request to server to destroy the session on onbeforeunload event fired when we closes the browse tab or window or browser.

Best way to parse command-line parameters?

I based my approach on the top answer (from dave4420), and tried to improve it by making it more general-purpose.

It returns a Map[String,String] of all command line parameters You can query this for the specific parameters you want (eg using .contains) or convert the values into the types you want (eg using toInt).

def argsToOptionMap(args:Array[String]):Map[String,String]= {
  def nextOption(
      argList:List[String], 
      map:Map[String, String]
    ) : Map[String, String] = {
    val pattern       = "--(\\w+)".r // Selects Arg from --Arg
    val patternSwitch = "-(\\w+)".r  // Selects Arg from -Arg
    argList match {
      case Nil => map
      case pattern(opt)       :: value  :: tail => nextOption( tail, map ++ Map(opt->value) )
      case patternSwitch(opt) :: tail => nextOption( tail, map ++ Map(opt->null) )
      case string             :: Nil  => map ++ Map(string->null)
      case option             :: tail => {
        println("Unknown option:"+option) 
        sys.exit(1)
      }
    }
  }
  nextOption(args.toList,Map())
}

Example:

val args=Array("--testing1","testing1","-a","-b","--c","d","test2")
argsToOptionMap( args  )

Gives:

res0: Map[String,String] = Map(testing1 -> testing1, a -> null, b -> null, c -> d, test2 -> null)

failed to open stream: No such file or directory in

you can use:

define("PATH_ROOT", dirname(__FILE__));
include_once PATH_ROOT . "/PoliticalForum/headerSite.php";

Why do I always get the same sequence of random numbers with rand()?

Seeding the rand()

void srand (unsigned int seed)

This function establishes seed as the seed for a new series of pseudo-random numbers. If you call rand before a seed has been established with srand, it uses the value 1 as a default seed.

To produce a different pseudo-random series each time your program is run, do srand (time (0))

How to get streaming url from online streaming radio station

Edited ZygD's answer for python 3.x.:

import re
import urllib.request
import string
url1 = input("Please enter a URL from Tunein Radio: ");
request = urllib.request.Request(url1);
response = urllib.request.urlopen(request);
raw_file = response.read().decode('utf-8');
API_key = re.findall(r"StreamUrl\":\"(.*?),\"",raw_file);
#print API_key;
#print "The API key is: " + API_key[0];
request2 = urllib.request.Request(str(API_key[0]));
response2 = urllib.request.urlopen(request2);
key_content = response2.read().decode('utf-8');
raw_stream_url = re.findall(r"Url\": \"(.*?)\"",key_content);
bandwidth = re.findall(r"Bandwidth\":(.*?),", key_content);
reliability = re.findall(r"lity\":(.*?),", key_content);
isPlaylist = re.findall(r"HasPlaylist\":(.*?),",key_content);
codec = re.findall(r"MediaType\": \"(.*?)\",", key_content);
tipe = re.findall(r"Type\": \"(.*?)\"", key_content);
total = 0
for element in raw_stream_url:
    total = total + 1
i = 0
print ("I found " + str(total) + " streams.");
for element in raw_stream_url:
    print ("Stream #" + str(i + 1));
    print ("Stream stats:");
    print ("Bandwidth: " + str(bandwidth[i]) + " kilobytes per second.");
    print ("Reliability: " + str(reliability[i]) + "%");
    print ("HasPlaylist: " + str(isPlaylist[i]));
    print ("Stream codec: " + str(codec[i]));
    print ("This audio stream is " + tipe[i].lower());
    print ("Pure streaming URL: " + str(raw_stream_url[i]));
i = i + 1
input("Press enter to close")

fopen deprecated warning

This is just Microsoft being cheeky. "Deprecated" implies a language feature that may not be provided in future versions of the standard language / standard libraries, as decreed by the standards committee. It does not, or should not mean, "we, unilaterally, don't think you should use it", no matter how well-founded that advice is.

Android Camera Preview Stretched

My requirements are the camera preview need to be fullscreen and keep the aspect ratio. Hesam and Yoosuf's solution was great but I do see a high zoom problem for some reason.

The idea is the same, have the preview container center in parent and increase the width or height depend on the aspect ratios until it can cover the entire screen.

One thing to note is the preview size is in landscape because we set the display orientation.

camera.setDisplayOrientation(90);

The container that we will add the SurfaceView view to:

<RelativeLayout
    android:id="@+id/camera_preview_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerInParent="true"/>

Add the preview to it's container with center in parent in your activity.

this.cameraPreview = new CameraPreview(this, camera);
cameraPreviewContainer.removeAllViews();
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
cameraPreviewContainer.addView(cameraPreview, 0, params);

Inside the CameraPreview class:

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    // If your preview can change or rotate, take care of those events here.
    // Make sure to stop the preview before resizing or reformatting it.

    if (holder.getSurface() == null) {
        // preview surface does not exist
        return;
    }

    stopPreview();

    // set preview size and make any resize, rotate or
    // reformatting changes here
    try {
        Camera.Size nativePictureSize = CameraUtils.getNativeCameraPictureSize(camera);
        Camera.Parameters parameters = camera.getParameters();
        parameters.setPreviewSize(optimalSize.width, optimalSize.height);
        parameters.setPictureSize(nativePictureSize.width, nativePictureSize.height);
        camera.setParameters(parameters);
        camera.setDisplayOrientation(90);
        camera.setPreviewDisplay(holder);
        camera.startPreview();

    } catch (Exception e){
        Log.d(TAG, "Error starting camera preview: " + e.getMessage());
    }
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
    final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);

    if (supportedPreviewSizes != null && optimalSize == null) {
        optimalSize = CameraUtils.getOptimalSize(supportedPreviewSizes, width, height);
        Log.i(TAG, "optimal size: " + optimalSize.width + "w, " + optimalSize.height + "h");
    }

    float previewRatio =  (float) optimalSize.height / (float) optimalSize.width;
    // previewRatio is height/width because camera preview size are in landscape.
    float measuredSizeRatio = (float) width / (float) height;

    if (previewRatio >= measuredSizeRatio) {
        measuredHeight = height;
        measuredWidth = (int) ((float)height * previewRatio);
    } else {
        measuredWidth = width;
        measuredHeight = (int) ((float)width / previewRatio);
    }
    Log.i(TAG, "Preview size: " + width + "w, " + height + "h");
    Log.i(TAG, "Preview size calculated: " + measuredWidth + "w, " + measuredHeight + "h");

    setMeasuredDimension(measuredWidth, measuredHeight);
}

Permutation of array

Example with primitive array:

public static void permute(int[] intArray, int start) {
    for(int i = start; i < intArray.length; i++){
        int temp = intArray[start];
        intArray[start] = intArray[i];
        intArray[i] = temp;
        permute(intArray, start + 1);
        intArray[i] = intArray[start];
        intArray[start] = temp;
    }
    if (start == intArray.length - 1) {
        System.out.println(java.util.Arrays.toString(intArray));
    }
}

public static void main(String[] args){
    int intArr[] = {1, 2, 3};
    permute(intArr, 0);
}

JavaScript global event mechanism

// display error messages for a page, but never more than 3 errors
window.onerror = function(msg, url, line) {
if (onerror.num++ < onerror.max) {
alert("ERROR: " + msg + "\n" + url + ":" + line);
return true;
}
}
onerror.max = 3;
onerror.num = 0;

cast or convert a float to nvarchar?

DECLARE @MyFloat [float]

SET @MyFloat = 1000109360.050

SELECT REPLACE (RTRIM (REPLACE (REPLACE (RTRIM ((REPLACE (CAST (CAST (@MyFloat AS DECIMAL (38 ,18 )) AS VARCHAR( max)), '0' , ' '))), ' ' , '0'), '.', ' ')), ' ','.')

The APR based Apache Tomcat Native library was not found on the java.library.path

Regarding the original question asked in the title ...

  • sudo apt-get install libtcnative-1

  • or if you are on RHEL Linux yum install tomcat-native

The documentation states you need http://tomcat.apache.org/native-doc/

  • sudo apt-get install libapr1.0-dev libssl-dev
  • or RHEL yum install apr-devel openssl-devel

Is there a way to get version from package.json in nodejs code?

I know this isn't the intent of the OP, but I just had to do this, so hope it helps the next person.

If you're using docker-compose for your CI/CD process, you can get it this way!

version:
  image: node:7-alpine
  volumes:
    - .:/usr/src/service/
  working_dir: /usr/src/service/
  command: ash -c "node -p \"require('./package.json').version.replace('\n', '')\""

for the image, you can use any node image. I use alpine because it is the smallest.

How to insert selected columns from a CSV file to a MySQL database using LOAD DATA INFILE

Example:

contents of the ae.csv file:

"Date, xpto 14"
"code","number","year","C"
"blab","15885","2016","Y"
"aeea","15883","1982","E"
"xpto","15884","1986","B"
"jrgg","15885","1400","A"

CREATE TABLE Tabletmp (  
    rec VARCHAR(9) 
);

For put only column 3:

LOAD DATA INFILE '/local/ae.csv' 
INTO TABLE Tabletmp
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 2 LINES
(@col1, @col2, @col3, @col4, @col5)
set rec = @col3;


select * from Tabletmp;
    2016
    1982
    1986
    1400

Getting attribute using XPath

Here is the snippet of getting the attribute value of "lang" with XPath and VTD-XML.

import com.ximpleware.*;
public class getAttrVal {
    public static void main(String s[]) throws VTDException{
        VTDGen vg = new VTDGen();
        if (!vg.parseFile("input.xml", false)){
            return ;
        }
        VTDNav vn = vg.getNav();
        AutoPilot ap = new AutoPilot(vn);
        ap.selectXPath("/bookstore/book/title/@lang");
        System.out.println(" lang's value is ===>"+ap.evalXPathToString());
    }
}

git ahead/behind info between master and branch?

First of all to see how many revisions you are behind locally, you should do a git fetch to make sure you have the latest info from your remote.

The default output of git status tells you how many revisions you are ahead or behind, but usually I find this too verbose:

$ git status
# On branch master
# Your branch and 'origin/master' have diverged,
# and have 2 and 1 different commit each, respectively.
#
nothing to commit (working directory clean)

I prefer git status -sb:

$ git status -sb
## master...origin/master [ahead 2, behind 1]

In fact I alias this to simply git s, and this is the main command I use for checking status.

To see the diff in the "ahead revisions" of master, I can exclude the "behind revisions" from origin/master:

git diff master..origin/master^

To see the diff in the "behind revisions" of origin/master, I can exclude the "ahead revisions" from master:

git diff origin/master..master^^

If there are 5 revisions ahead or behind it might be easier to write like this:

git diff master..origin/master~5
git diff origin/master..master~5

UPDATE

To see the ahead/behind revisions, the branch must be configured to track another branch. For me this is the default behavior when I clone a remote repository, and after I push a branch with git push -u remotename branchname. My version is 1.8.4.3, but it's been working like this as long as I remember.

As of version 1.8, you can set the tracking branch like this:

git branch --track test-branch

As of version 1.7, the syntax was different:

git branch --set-upstream test-branch

How to check if two words are anagrams

Fastest algorithm would be to map each of the 26 English characters to a unique prime number. Then calculate the product of the string. By the fundamental theorem of arithmetic, 2 strings are anagrams if and only if their products are the same.

Pandas DataFrame to List of Dictionaries

Use df.to_dict('records') -- gives the output without having to transpose externally.

In [2]: df.to_dict('records')
Out[2]:
[{'customer': 1L, 'item1': 'apple', 'item2': 'milk', 'item3': 'tomato'},
 {'customer': 2L, 'item1': 'water', 'item2': 'orange', 'item3': 'potato'},
 {'customer': 3L, 'item1': 'juice', 'item2': 'mango', 'item3': 'chips'}]

Preloading CSS Images

You could use this jQuery plugin waitForImage or you could put you images into an hidden div or (width:0 and height:0) and use onload event on images.

If you only have like 2-3 images you can bind events and trigger them in a chain so after every image you can do some code.

Nginx: Job for nginx.service failed because the control process exited

Try to debug with command:

$ service nginx configtest

Which outputs something like:

Testing nginx configuration: nginx: [emerg] unknown directive "stub_status" in /etc/nginx/sites-enabled/nginx_status:11
nginx: configuration file /etc/nginx/nginx.conf test failed

And fix those warnings

Then restart nginx

How to check whether input value is integer or float?

How about this. using the modulo operator

if(a%b==0) 
{
    System.out.println("b is a factor of a. i.e. the result of a/b is going to be an integer");
}
else
{
    System.out.println("b is NOT a factor of a");
}

Retrieving the last record in each group - MySQL

we will look at how you can use MySQL at getting the last record in a Group By of records. For example if you have this result set of posts.

id category_id post_title

1 1 Title 1

2 1 Title 2

3 1 Title 3

4 2 Title 4

5 2 Title 5

6 3 Title 6

I want to be able to get the last post in each category which are Title 3, Title 5 and Title 6. To get the posts by the category you will use the MySQL Group By keyboard.

select * from posts group by category_id

But the results we get back from this query is.

id category_id post_title

1 1 Title 1

4 2 Title 4

6 3 Title 6

The group by will always return the first record in the group on the result set.

SELECT id, category_id, post_title FROM posts WHERE id IN ( SELECT MAX(id) FROM posts GROUP BY category_id );

This will return the posts with the highest IDs in each group.

id category_id post_title

3 1 Title 3

5 2 Title 5

6 3 Title 6

Reference Click Here

Difference between BYTE and CHAR in column datatypes

Let us assume the database character set is UTF-8, which is the recommended setting in recent versions of Oracle. In this case, some characters take more than 1 byte to store in the database.

If you define the field as VARCHAR2(11 BYTE), Oracle can use up to 11 bytes for storage, but you may not actually be able to store 11 characters in the field, because some of them take more than one byte to store, e.g. non-English characters.

By defining the field as VARCHAR2(11 CHAR) you tell Oracle it can use enough space to store 11 characters, no matter how many bytes it takes to store each one. A single character may require up to 4 bytes.

How to check the Angular version?

  1. ng v
  2. ng --v

you shall see something like the following:

Angular CLI: 7.3.8
Node: 10.15.1
OS: win32 x64
Angular: 5.2.10
... animations, common, compiler, core, forms, http
... platform-browser, platform-browser-dynamic, router

Angular version is in line 4 above

Get the current user, within an ApiController action, without passing the userID as a parameter

You can also access the principal using the User property on ApiController.

So the following two statements are basically the same:

string id;
id = User.Identity.GetUserId();
id = RequestContext.Principal.Identity.GetUserId();

psycopg2: insert multiple rows with one query

Another nice and efficient approach - is to pass rows for insertion as 1 argument, which is array of json objects.

E.g. you passing argument:

[ {id: 18, score: 1}, { id: 19, score: 5} ]

It is array, which may contain any amount of objects inside. Then your SQL looks like:

INSERT INTO links (parent_id, child_id, score) 
SELECT 123, (r->>'id')::int, (r->>'score')::int 
FROM unnest($1::json[]) as r 

Notice: Your postgress must be new enough, to support json

Create dataframe from a matrix

melt() from the reshape2 package gets you close ...

library(reshape2)
(res <- melt(as.data.frame(mat), id="time"))
#   time variable value
# 1  0.0      C_0   0.1
# 2  0.5      C_0   0.2
# 3  1.0      C_0   0.3
# 4  0.0      C_1   0.3
# 5  0.5      C_1   0.4
# 6  1.0      C_1   0.5

... although you may want to post-process its results to get your preferred column names and ordering.

setNames(res[c("variable", "time", "value")], c("name", "time", "val"))
#   name time val
# 1  C_0  0.0 0.1
# 2  C_0  0.5 0.2
# 3  C_0  1.0 0.3
# 4  C_1  0.0 0.3
# 5  C_1  0.5 0.4
# 6  C_1  1.0 0.5

How do you access the value of an SQL count () query in a Java program

        <%
        try{
            Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bala","bala","bala");
            if(con == null) System.out.print("not connected");
            Statement st = con.createStatement();
            String myStatement = "select count(*) as total from locations";
            ResultSet rs = st.executeQuery(myStatement);
            int num = 0;
            while(rs.next()){
                num = (rs.getInt(1));
            }

        }
        catch(Exception e){
            System.out.println(e);  
        }

        %>

Component is part of the declaration of 2 modules

IN Angular 4. This error is considered as ng serve run time cache issue.

case:1 this error will occur, once you import the component in one module and again import in sub modules will occur.

case:2 Import one Component in wrong place and removed and replaced in Correct module, That time it consider as ng serve cache issue. Need to Stop the project and start -do again ng serve, It will work as expected.

How to disable all <input > inside a form with jQuery?

Above example is technically incorrect. Per latest jQuery, use the prop() method should be used for things like disabled. See their API page.

To disable all form elements inside 'target', use the :input selector which matches all input, textarea, select and button elements.

$("#target :input").prop("disabled", true);

If you only want the elements, use this.

$("#target input").prop("disabled", true);

How do you simulate Mouse Click in C#?

I have tried the code that Marcos posted and it didn't worked for me. Whatever i was given to the Y coordinate the cursor didn't moved on Y axis. The code below will work if you want the position of the cursor relative to the left-up corner of your desktop, not relative to your application.

    [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
    public static extern void mouse_event(long dwFlags, long dx, long dy, long cButtons, long dwExtraInfo);
    private const int MOUSEEVENTF_LEFTDOWN = 0x02;
    private const int MOUSEEVENTF_LEFTUP = 0x04;
    private const int MOUSEEVENTF_MOVE = 0x0001;

    public void DoMouseClick()
    {
        X = Cursor.Position.X;
        Y = Cursor.Position.Y;

        //move to coordinates
        pt = (Point)pc.ConvertFromString(X + "," + Y);
        Cursor.Position = pt;       

        //perform click            
        mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
        mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
    }

I only use mouse_event function to actually perform the click. You can give X and Y what coordinates you want, i used values from textbox:

            X = Convert.ToInt32(tbX.Text);
            Y = Convert.ToInt32(tbY.Text);

what is right way to do API call in react js?

1) You can use Fetch API to fetch data from Endd Points:

Example fetching all Github repose for a user

  /* Fetch GitHub Repos */
  fetchData = () => {

       //show progress bar
      this.setState({ isLoading: true });

      //fetch repos
      fetch(`https://api.github.com/users/hiteshsahu/repos`)
      .then(response => response.json())
      .then(data => {
        if (Array.isArray(data)) {
          console.log(JSON.stringify(data));
          this.setState({ repos: data ,
                         isLoading: false});
        } else {
          this.setState({ repos: [],
                          isLoading: false  
                        });
        }
      });
  };

2) Other Alternative is Axios

Using axios you can cut out the middle step of passing the results of the http request to the .json() method. Axios just returns the data object you would expect.

  import axios from "axios";

 /* Fetch GitHub Repos */
  fetchDataWithAxios = () => {

     //show progress bar
      this.setState({ isLoading: true });

      // fetch repos with axios
      axios
          .get(`https://api.github.com/users/hiteshsahu/repos`)
          .then(result => {
            console.log(result);
            this.setState({
              repos: result.data,
              isLoading: false
            });
          })
          .catch(error =>
            this.setState({
              error,
              isLoading: false
            })
          );
}

Now you can choose to fetch data using any of this strategies in componentDidMount

class App extends React.Component {
  state = {
    repos: [],
   isLoading: false
  };

  componentDidMount() {
    this.fetchData ();
  }

Meanwhile you can show progress bar while data is loading

   {this.state.isLoading && <LinearProgress />}

qmake: could not find a Qt installation of ''

I have qt4 installed. I found that using the following path worked for me, despite 'which qmake' returning /usr/bin/qmake, which is just a link to qtchooser anyway.

The following path works for me, on a 64 bit system. Running from the full path of:

/usr/lib/x86_64-linux-gnu/qt4/bin/qmake

List Highest Correlation Pairs from a Large Correlation Matrix in Pandas?

You can use DataFrame.values to get an numpy array of the data and then use NumPy functions such as argsort() to get the most correlated pairs.

But if you want to do this in pandas, you can unstack and sort the DataFrame:

import pandas as pd
import numpy as np

shape = (50, 4460)

data = np.random.normal(size=shape)

data[:, 1000] += data[:, 2000]

df = pd.DataFrame(data)

c = df.corr().abs()

s = c.unstack()
so = s.sort_values(kind="quicksort")

print so[-4470:-4460]

Here is the output:

2192  1522    0.636198
1522  2192    0.636198
3677  2027    0.641817
2027  3677    0.641817
242   130     0.646760
130   242     0.646760
1171  2733    0.670048
2733  1171    0.670048
1000  2000    0.742340
2000  1000    0.742340
dtype: float64

A full list of all the new/popular databases and their uses?

I doubt I'd use it in a mission-critical system, but Derby has always been very interesting to me.

if var == False

Python uses not instead of ! for negation.

Try

if not var: 
    print "learnt stuff"

instead

add column to mysql table if it does not exist

I'm using MySQL 5.5.19.

I like having scripts that you can run and rerun without error, especially where warnings seem to linger, showing up again later while I'm running scripts that have no errors/warnings. As far as adding fields goes, I wrote myself a procedure to make it a little less typing:

-- add fields to template table to support ignoring extra data 
-- at the top/bottom of every page
CALL addFieldIfNotExists ('template', 'firstPageHeaderEndY', 'INT NOT NULL DEFAULT 0');
CALL addFieldIfNotExists ('template', 'pageHeaderEndY', 'INT NOT NULL DEFAULT 0');
CALL addFieldIfNotExists ('template', 'pageFooterBeginY', 'INT NOT NULL DEFAULT 792');

The code to create the addFieldIfNotExists procedure is as follows:

DELIMITER $$

DROP PROCEDURE IF EXISTS addFieldIfNotExists 
$$

DROP FUNCTION IF EXISTS isFieldExisting 
$$

CREATE FUNCTION isFieldExisting (table_name_IN VARCHAR(100), field_name_IN VARCHAR(100)) 
RETURNS INT
RETURN (
    SELECT COUNT(COLUMN_NAME) 
    FROM INFORMATION_SCHEMA.columns 
    WHERE TABLE_SCHEMA = DATABASE() 
    AND TABLE_NAME = table_name_IN 
    AND COLUMN_NAME = field_name_IN
)
$$

CREATE PROCEDURE addFieldIfNotExists (
    IN table_name_IN VARCHAR(100)
    , IN field_name_IN VARCHAR(100)
    , IN field_definition_IN VARCHAR(100)
)
BEGIN

    -- http://javajon.blogspot.com/2012/10/mysql-alter-table-add-column-if-not.html

    SET @isFieldThere = isFieldExisting(table_name_IN, field_name_IN);
    IF (@isFieldThere = 0) THEN

        SET @ddl = CONCAT('ALTER TABLE ', table_name_IN);
        SET @ddl = CONCAT(@ddl, ' ', 'ADD COLUMN') ;
        SET @ddl = CONCAT(@ddl, ' ', field_name_IN);
        SET @ddl = CONCAT(@ddl, ' ', field_definition_IN);

        PREPARE stmt FROM @ddl;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;

    END IF;

END;
$$

I didn't write a procedure to safely modify a column, but I think the above procedure could be easily modified to do so.

Open a file with Notepad in C#

System.Diagnostics.Process.Start( "notepad.exe", "text.txt");

How to check if another instance of the application is running

Here are some good sample applications. Below is one possible way.

public static Process RunningInstance() 
{ 
    Process current = Process.GetCurrentProcess(); 
    Process[] processes = Process.GetProcessesByName (current.ProcessName); 

    //Loop through the running processes in with the same name 
    foreach (Process process in processes) 
    { 
        //Ignore the current process 
        if (process.Id != current.Id) 
        { 
            //Make sure that the process is running from the exe file. 
            if (Assembly.GetExecutingAssembly().Location.
                 Replace("/", "\\") == current.MainModule.FileName) 

            {  
                //Return the other process instance.  
                return process; 

            }  
        }  
    } 
    //No other instance was found, return null.  
    return null;  
}


if (MainForm.RunningInstance() != null)
{
    MessageBox.Show("Duplicate Instance");
    //TODO:
    //Your application logic for duplicate 
    //instances would go here.
}

Many other possible ways. See the examples for alternatives.

First one.

Second One.

Third One

EDIT 1: Just saw your comment that you have got a console application. That is discussed in the second sample.

What is the right way to treat argparse.Namespace() as a dictionary?

Is it proper to "reach into" an object and use its dict property?

In general, I would say "no". However Namespace has struck me as over-engineered, possibly from when classes couldn't inherit from built-in types.

On the other hand, Namespace does present a task-oriented approach to argparse, and I can't think of a situation that would call for grabbing the __dict__, but the limits of my imagination are not the same as yours.

How to get changes from another branch

You can use rebase, for instance, git rebase our-team when you are on your branch featurex

It will move the start point of the branch at the end of your our-team branch, merging all changes in your featurex branch.

SQL Server: use CASE with LIKE

Add an END at last before alias name.

CASE WHEN countries LIKE '%'+@selCountry+'%' 
     THEN 'national' ELSE 'regional' 
END AS validity

For example:

SELECT CASE WHEN countries LIKE '%'+@selCountry+'%' 
       THEN 'national' ELSE 'regional' 
       END AS validity
FROM TableName

Show hide div using codebehind

There are a few ways to handle rendering/showing controls on the page and you should take note to what happens with each method.

Rendering and Visibility

There are some instances where elements on your page don't need to be rendered for the user because of some type of logic or database value. In this case, you can prevent rendering (creating the control on the returned web page) altogether. You would want to do this if the control doesn't need to be shown later on the client side because no matter what, the user viewing the page never needs to see it.

Any controls or elements can have their visibility set from the server side. If it is a plain old html element, you just need to set the runat attribute value to server on the markup page.

<div id="myDiv" runat="server"></div>

The decision to render the div or not can now be done in the code behind class like so:

myDiv.Visible = someConditionalBool;

If set to true, it will be rendered on the page and if it's false it won't be rendered at all, not even hidden.

Client Side Hiding

Hiding an element is done on the client side only. Meaning, it's rendered but it has a display CSS style set on it which instructs your browser to not show it to the user. This is beneficial when you want to hide/show things based on user input. It's important to know that the element CAN be hidden on the server side too as long as the element/control has runat=server set just as I explained in the previous example.

Hiding in the Code Behind Class

To hide an element that you want rendered to the page but hidden is another simple single line of code:

myDiv.Style["display"] = "none";

If you have a need to remove the display style server side, it can be done by removing the display style, or setting it to a different value like inline or block (values described here).

myDiv.Style.Remove("display");
// -- or --
myDiv.Style["display"] = "inline";

Hiding on the Client Side with javascript

Using plain old javascript, you can easily hide the same element in this manner

var myDivElem = document.getElementById("myDiv");
myDivElem.style.display = "none";

// then to show again
myDivElem.style.display = "";

jQuery makes hiding elements a little simpler if you prefer to use jQuery:

var myDiv = $("#<%=myDiv.ClientID%>");
myDiv.hide();

// ... and to show 
myDiv.show();

Correct way to add external jars (lib/*.jar) to an IntelliJ IDEA project

While I agree with the previous answers, it's important to note how to access the code of those external libraries.

For example to access a class in the external library, you will want to use the import keyword followed by the external library's name, continued with dot notation until the desired class is reached.

Look at the image below to see how I import CodeGenerationException class from the quickfixj library.

enter image description here

What I can do to resolve "1 commit behind master"?

Suppose currently in your branch myBranch
Do the following :-

git status

If all changes are committed

git pull origin master

If changes are not committed than

git add .

git commit -m"commit changes"

git pull origin master

Check if there are any conflicts than resolve and commit changes

git add .

git commit -m"resolved conflicts message"

And than push

git push origin myBranch

Is it possible to apply CSS to half of a character?

Now on GitHub as a Plugin!

enter image description here Feel free to fork and improve.

Demo | Download Zip | Half-Style.com (Redirects to GitHub)


  • Pure CSS for a Single Character
  • JavaScript used for automation across text or multiple characters
  • Preserves Text Accessibility for screen readers for the blind or visually impaired

Part 1: Basic Solution

Half Style on text

Demo: http://jsfiddle.net/arbel/pd9yB/1694/


This works on any dynamic text, or a single character, and is all automated. All you need to do is add a class on the target text and the rest is taken care of.

Also, the accessibility of the original text is preserved for screen readers for the blind or visually impaired.

Explanation for a single character:

Pure CSS. All you need to do is to apply .halfStyle class to each element that contains the character you want to be half-styled.

For each span element containing the character, you can create a data attribute, for example here data-content="X", and on the pseudo element use content: attr(data-content); so the .halfStyle:before class will be dynamic and you won't need to hard code it for every instance.

Explanation for any text:

Simply add textToHalfStyle class to the element containing the text.


_x000D_
_x000D_
// jQuery for automated mode_x000D_
jQuery(function($) {_x000D_
    var text, chars, $el, i, output;_x000D_
_x000D_
    // Iterate over all class occurences_x000D_
    $('.textToHalfStyle').each(function(idx, el) {_x000D_
    $el = $(el);_x000D_
    text = $el.text();_x000D_
    chars = text.split('');_x000D_
_x000D_
    // Set the screen-reader text_x000D_
    $el.html('<span style="position: absolute !important;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);">' + text + '</span>');_x000D_
_x000D_
    // Reset output for appending_x000D_
    output = '';_x000D_
_x000D_
    // Iterate over all chars in the text_x000D_
    for (i = 0; i < chars.length; i++) {_x000D_
        // Create a styled element for each character and append to container_x000D_
        output += '<span aria-hidden="true" class="halfStyle" data-content="' + chars[i] + '">' + chars[i] + '</span>';_x000D_
    }_x000D_
_x000D_
    // Write to DOM only once_x000D_
    $el.append(output);_x000D_
  });_x000D_
});
_x000D_
.halfStyle {_x000D_
    position: relative;_x000D_
    display: inline-block;_x000D_
    font-size: 80px; /* or any font size will work */_x000D_
    color: black; /* or transparent, any color */_x000D_
    overflow: hidden;_x000D_
    white-space: pre; /* to preserve the spaces from collapsing */_x000D_
}_x000D_
_x000D_
.halfStyle:before {_x000D_
    display: block;_x000D_
    z-index: 1;_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    left: 0;_x000D_
    width: 50%;_x000D_
    content: attr(data-content); /* dynamic content for the pseudo element */_x000D_
    overflow: hidden;_x000D_
    color: #f00;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<p>Single Characters:</p>_x000D_
<span class="halfStyle" data-content="X">X</span>_x000D_
<span class="halfStyle" data-content="Y">Y</span>_x000D_
<span class="halfStyle" data-content="Z">Z</span>_x000D_
<span class="halfStyle" data-content="A">A</span>_x000D_
_x000D_
<hr/>_x000D_
<p>Automated:</p>_x000D_
_x000D_
<span class="textToHalfStyle">Half-style, please.</span>
_x000D_
_x000D_
_x000D_

(JSFiddle demo)


Part 2: Advanced solution - Independent left and right parts

Half Style on text - advanced - With Text Shadow

With this solution you can style left and right parts, individually and independently.

Everything is the same, only more advanced CSS does the magic.

_x000D_
_x000D_
jQuery(function($) {_x000D_
    var text, chars, $el, i, output;_x000D_
_x000D_
    // Iterate over all class occurences_x000D_
    $('.textToHalfStyle').each(function(idx, el) {_x000D_
        $el = $(el);_x000D_
        text = $el.text();_x000D_
        chars = text.split('');_x000D_
_x000D_
        // Set the screen-reader text_x000D_
        $el.html('<span style="position: absolute !important;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);">' + text + '</span>');_x000D_
_x000D_
        // Reset output for appending_x000D_
        output = '';_x000D_
_x000D_
        // Iterate over all chars in the text_x000D_
        for (i = 0; i < chars.length; i++) {_x000D_
            // Create a styled element for each character and append to container_x000D_
            output += '<span aria-hidden="true" class="halfStyle" data-content="' + chars[i] + '">' + chars[i] + '</span>';_x000D_
        }_x000D_
_x000D_
        // Write to DOM only once_x000D_
        $el.append(output);_x000D_
    });_x000D_
});
_x000D_
.halfStyle {_x000D_
    position: relative;_x000D_
    display: inline-block;_x000D_
    font-size: 80px; /* or any font size will work */_x000D_
    color: transparent; /* hide the base character */_x000D_
    overflow: hidden;_x000D_
    white-space: pre; /* to preserve the spaces from collapsing */_x000D_
}_x000D_
_x000D_
.halfStyle:before { /* creates the left part */_x000D_
    display: block;_x000D_
    z-index: 1;_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    width: 50%;_x000D_
    content: attr(data-content); /* dynamic content for the pseudo element */_x000D_
    overflow: hidden;_x000D_
    pointer-events: none; /* so the base char is selectable by mouse */_x000D_
    color: #f00; /* for demo purposes */_x000D_
    text-shadow: 2px -2px 0px #af0; /* for demo purposes */_x000D_
}_x000D_
_x000D_
.halfStyle:after { /* creates the right part */_x000D_
    display: block;_x000D_
    direction: rtl; /* very important, will make the width to start from right */_x000D_
    position: absolute;_x000D_
    z-index: 2;_x000D_
    top: 0;_x000D_
    left: 50%;_x000D_
    width: 50%;_x000D_
    content: attr(data-content); /* dynamic content for the pseudo element */_x000D_
    overflow: hidden;_x000D_
    pointer-events: none; /* so the base char is selectable by mouse */_x000D_
    color: #000; /* for demo purposes */_x000D_
    text-shadow: 2px 2px 0px #0af; /* for demo purposes */_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<p>Single Characters:</p>_x000D_
<span class="halfStyle" data-content="X">X</span>_x000D_
<span class="halfStyle" data-content="Y">Y</span>_x000D_
<span class="halfStyle" data-content="Z">Z</span>_x000D_
<span class="halfStyle" data-content="A">A</span>_x000D_
_x000D_
<hr/>_x000D_
<p>Automated:</p>_x000D_
_x000D_
<span class="textToHalfStyle">Half-style, please.</span>
_x000D_
_x000D_
_x000D_

(JSFiddle demo)



Part 3: Mix-Match and Improve

Now that we know what is possible, let's create some variations.


-Horizontal Half Parts

  • Without Text Shadow:

    Horizontal Half Parts - No Text Shadow

  • Possibility of Text Shadow for each half part independently:

    halfStyle - Horizontal Half Parts - With Text Shadow

_x000D_
_x000D_
// jQuery for automated mode_x000D_
jQuery(function($) {_x000D_
    var text, chars, $el, i, output;_x000D_
_x000D_
    // Iterate over all class occurences_x000D_
    $('.textToHalfStyle').each(function(idx, el) {_x000D_
        $el = $(el);_x000D_
        text = $el.text();_x000D_
        chars = text.split('');_x000D_
_x000D_
        // Set the screen-reader text_x000D_
        $el.html('<span style="position: absolute !important;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);">' + text + '</span>');_x000D_
_x000D_
        // Reset output for appending_x000D_
        output = '';_x000D_
_x000D_
        // Iterate over all chars in the text_x000D_
        for (i = 0; i < chars.length; i++) {_x000D_
            // Create a styled element for each character and append to container_x000D_
            output += '<span aria-hidden="true" class="halfStyle" data-content="' + chars[i] + '">' + chars[i] + '</span>';_x000D_
        }_x000D_
_x000D_
        // Write to DOM only once_x000D_
        $el.append(output);_x000D_
    });_x000D_
});
_x000D_
.halfStyle {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  font-size: 80px; /* or any font size will work */_x000D_
  color: transparent; /* hide the base character */_x000D_
  overflow: hidden;_x000D_
  white-space: pre; /* to preserve the spaces from collapsing */_x000D_
}_x000D_
_x000D_
.halfStyle:before { /* creates the top part */_x000D_
  display: block;_x000D_
  z-index: 2;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  height: 50%;_x000D_
  content: attr(data-content); /* dynamic content for the pseudo element */_x000D_
  overflow: hidden;_x000D_
  pointer-events: none; /* so the base char is selectable by mouse */_x000D_
  color: #f00; /* for demo purposes */_x000D_
  text-shadow: 2px -2px 0px #af0; /* for demo purposes */_x000D_
}_x000D_
_x000D_
.halfStyle:after { /* creates the bottom part */_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
  z-index: 1;_x000D_
  top: 0;_x000D_
  height: 100%;_x000D_
  content: attr(data-content); /* dynamic content for the pseudo element */_x000D_
  overflow: hidden;_x000D_
  pointer-events: none; /* so the base char is selectable by mouse */_x000D_
  color: #000; /* for demo purposes */_x000D_
  text-shadow: 2px 2px 0px #0af; /* for demo purposes */_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<p>Single Characters:</p>_x000D_
<span class="halfStyle" data-content="X">X</span>_x000D_
<span class="halfStyle" data-content="Y">Y</span>_x000D_
<span class="halfStyle" data-content="Z">Z</span>_x000D_
<span class="halfStyle" data-content="A">A</span>_x000D_
_x000D_
<hr/>_x000D_
<p>Automated:</p>_x000D_
_x000D_
<span class="textToHalfStyle">Half-style, please.</span>
_x000D_
_x000D_
_x000D_

(JSFiddle demo)



-Vertical 1/3 Parts

  • Without Text Shadow:

    halfStyle - Vertical 1/3 Parts - No Text Shadow

  • Possibility of Text Shadow for each 1/3 part independently:

    halfStyle - Vertical 1/3 Parts - With Text Shadow

_x000D_
_x000D_
// jQuery for automated mode_x000D_
jQuery(function($) {_x000D_
    var text, chars, $el, i, output;_x000D_
_x000D_
    // Iterate over all class occurences_x000D_
    $('.textToHalfStyle').each(function(idx, el) {_x000D_
    $el = $(el);_x000D_
    text = $el.text();_x000D_
    chars = text.split('');_x000D_
_x000D_
    // Set the screen-reader text_x000D_
    $el.html('<span style="position: absolute !important;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);">' + text + '</span>');_x000D_
_x000D_
    // Reset output for appending_x000D_
    output = '';_x000D_
_x000D_
    // Iterate over all chars in the text_x000D_
    for (i = 0; i < chars.length; i++) {_x000D_
        // Create a styled element for each character and append to container_x000D_
        output += '<span aria-hidden="true" class="halfStyle" data-content="' + chars[i] + '">' + chars[i] + '</span>';_x000D_
    }_x000D_
_x000D_
    // Write to DOM only once_x000D_
    $el.append(output);_x000D_
  });_x000D_
});
_x000D_
.halfStyle { /* base char and also the right 1/3 */_x000D_
    position: relative;_x000D_
    display: inline-block;_x000D_
    font-size: 80px; /* or any font size will work */_x000D_
    color: transparent; /* hide the base character */_x000D_
    overflow: hidden;_x000D_
    white-space: pre; /* to preserve the spaces from collapsing */_x000D_
    color: #f0f; /* for demo purposes */_x000D_
    text-shadow: 2px 2px 0px #0af; /* for demo purposes */_x000D_
}_x000D_
_x000D_
.halfStyle:before { /* creates the left 1/3 */_x000D_
    display: block;_x000D_
    z-index: 2;_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    width: 33.33%;_x000D_
    content: attr(data-content); /* dynamic content for the pseudo element */_x000D_
    overflow: hidden;_x000D_
    pointer-events: none; /* so the base char is selectable by mouse */_x000D_
    color: #f00; /* for demo purposes */_x000D_
    text-shadow: 2px -2px 0px #af0; /* for demo purposes */_x000D_
}_x000D_
_x000D_
.halfStyle:after { /* creates the middle 1/3 */_x000D_
    display: block;_x000D_
    z-index: 1;_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    width: 66.66%;_x000D_
    content: attr(data-content); /* dynamic content for the pseudo element */_x000D_
    overflow: hidden;_x000D_
    pointer-events: none; /* so the base char is selectable by mouse */_x000D_
    color: #000; /* for demo purposes */_x000D_
    text-shadow: 2px 2px 0px #af0; /* for demo purposes */_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<p>Single Characters:</p>_x000D_
<span class="halfStyle" data-content="X">X</span>_x000D_
<span class="halfStyle" data-content="Y">Y</span>_x000D_
<span class="halfStyle" data-content="Z">Z</span>_x000D_
<span class="halfStyle" data-content="A">A</span>_x000D_
_x000D_
<hr/>_x000D_
<p>Automated:</p>_x000D_
_x000D_
<span class="textToHalfStyle">Half-style, please.</span>
_x000D_
_x000D_
_x000D_

(JSFiddle demo)



-Horizontal 1/3 Parts

  • Without Text Shadow:

    halfStyle - Horizontal 1/3 Parts - No Text Shadow

  • Possibility of Text Shadow for each 1/3 part independently:

    halfStyle - Horizontal 1/3 Parts - With Text Shadow

_x000D_
_x000D_
// jQuery for automated mode_x000D_
jQuery(function($) {_x000D_
    var text, chars, $el, i, output;_x000D_
_x000D_
    // Iterate over all class occurences_x000D_
    $('.textToHalfStyle').each(function(idx, el) {_x000D_
    $el = $(el);_x000D_
    text = $el.text();_x000D_
    chars = text.split('');_x000D_
_x000D_
    // Set the screen-reader text_x000D_
    $el.html('<span style="position: absolute !important;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);">' + text + '</span>');_x000D_
_x000D_
    // Reset output for appending_x000D_
    output = '';_x000D_
_x000D_
    // Iterate over all chars in the text_x000D_
    for (i = 0; i < chars.length; i++) {_x000D_
        // Create a styled element for each character and append to container_x000D_
        output += '<span aria-hidden="true" class="halfStyle" data-content="' + chars[i] + '">' + chars[i] + '</span>';_x000D_
    }_x000D_
_x000D_
    // Write to DOM only once_x000D_
    $el.append(output);_x000D_
  });_x000D_
});
_x000D_
.halfStyle { /* base char and also the bottom 1/3 */_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  font-size: 80px; /* or any font size will work */_x000D_
  color: transparent;_x000D_
  overflow: hidden;_x000D_
  white-space: pre; /* to preserve the spaces from collapsing */_x000D_
  color: #f0f;_x000D_
  text-shadow: 2px 2px 0px #0af; /* for demo purposes */_x000D_
}_x000D_
_x000D_
.halfStyle:before { /* creates the top 1/3 */_x000D_
  display: block;_x000D_
  z-index: 2;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  height: 33.33%;_x000D_
  content: attr(data-content); /* dynamic content for the pseudo element */_x000D_
  overflow: hidden;_x000D_
  pointer-events: none; /* so the base char is selectable by mouse */_x000D_
  color: #f00; /* for demo purposes */_x000D_
  text-shadow: 2px -2px 0px #fa0; /* for demo purposes */_x000D_
}_x000D_
_x000D_
.halfStyle:after { /* creates the middle 1/3 */_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
  z-index: 1;_x000D_
  top: 0;_x000D_
  height: 66.66%;_x000D_
  content: attr(data-content); /* dynamic content for the pseudo element */_x000D_
  overflow: hidden;_x000D_
  pointer-events: none; /* so the base char is selectable by mouse */_x000D_
  color: #000; /* for demo purposes */_x000D_
  text-shadow: 2px 2px 0px #af0; /* for demo purposes */_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<p>Single Characters:</p>_x000D_
<span class="halfStyle" data-content="X">X</span>_x000D_
<span class="halfStyle" data-content="Y">Y</span>_x000D_
<span class="halfStyle" data-content="Z">Z</span>_x000D_
<span class="halfStyle" data-content="A">A</span>_x000D_
_x000D_
<hr/>_x000D_
<p>Automated:</p>_x000D_
_x000D_
<span class="textToHalfStyle">Half-style, please.</span>
_x000D_
_x000D_
_x000D_

(JSFiddle demo)



-HalfStyle Improvement By @KevinGranger

halfStyle - KevinGranger

_x000D_
_x000D_
// jQuery for automated mode_x000D_
jQuery(function($) {_x000D_
    var text, chars, $el, i, output;_x000D_
_x000D_
    // Iterate over all class occurences_x000D_
    $('.textToHalfStyle').each(function(idx, el) {_x000D_
    $el = $(el);_x000D_
    text = $el.text();_x000D_
    chars = text.split('');_x000D_
_x000D_
    // Set the screen-reader text_x000D_
    $el.html('<span style="position: absolute !important;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);">' + text + '</span>');_x000D_
_x000D_
    // Reset output for appending_x000D_
    output = '';_x000D_
_x000D_
    // Iterate over all chars in the text_x000D_
    for (i = 0; i < chars.length; i++) {_x000D_
        // Create a styled element for each character and append to container_x000D_
        output += '<span aria-hidden="true" class="halfStyle" data-content="' + chars[i] + '">' + chars[i] + '</span>';_x000D_
    }_x000D_
_x000D_
    // Write to DOM only once_x000D_
    $el.append(output);_x000D_
  });_x000D_
});
_x000D_
body {_x000D_
    background-color: black;_x000D_
}_x000D_
_x000D_
.textToHalfStyle {_x000D_
    display: block;_x000D_
    margin: 200px 0 0 0;_x000D_
    text-align: center;_x000D_
}_x000D_
_x000D_
.halfStyle {_x000D_
    font-family: 'Libre Baskerville', serif;_x000D_
    position: relative;_x000D_
    display: inline-block;_x000D_
    width: 1;_x000D_
    font-size: 70px;_x000D_
    color: black;_x000D_
    overflow: hidden;_x000D_
    white-space: pre;_x000D_
    text-shadow: 1px 2px 0 white;_x000D_
}_x000D_
_x000D_
.halfStyle:before {_x000D_
    display: block;_x000D_
    z-index: 1;_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    width: 50%;_x000D_
    content: attr(data-content); /* dynamic content for the pseudo element */_x000D_
    overflow: hidden;_x000D_
    color: white;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<p>Single Characters:</p>_x000D_
<span class="halfStyle" data-content="X">X</span>_x000D_
<span class="halfStyle" data-content="Y">Y</span>_x000D_
<span class="halfStyle" data-content="Z">Z</span>_x000D_
<span class="halfStyle" data-content="A">A</span>_x000D_
_x000D_
<hr/>_x000D_
<p>Automated:</p>_x000D_
_x000D_
<span class="textToHalfStyle">Half-style, please.</span>
_x000D_
_x000D_
_x000D_

(JSFiddle demo)



-PeelingStyle improvement of HalfStyle by @SamTremaine

halfStyle - SamTremaine

_x000D_
_x000D_
// jQuery for automated mode_x000D_
jQuery(function($) {_x000D_
    var text, chars, $el, i, output;_x000D_
_x000D_
    // Iterate over all class occurences_x000D_
    $('.textToHalfStyle').each(function(idx, el) {_x000D_
    $el = $(el);_x000D_
    text = $el.text();_x000D_
    chars = text.split('');_x000D_
_x000D_
    // Set the screen-reader text_x000D_
    $el.html('<span style="position: absolute !important;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);">' + text + '</span>');_x000D_
_x000D_
    // Reset output for appending_x000D_
    output = '';_x000D_
_x000D_
    // Iterate over all chars in the text_x000D_
    for (i = 0; i < chars.length; i++) {_x000D_
        // Create a styled element for each character and append to container_x000D_
        output += '<span aria-hidden="true" class="halfStyle" data-content="' + chars[i] + '">' + chars[i] + '</span>';_x000D_
    }_x000D_
_x000D_
    // Write to DOM only once_x000D_
    $el.append(output);_x000D_
  });_x000D_
});
_x000D_
.halfStyle {_x000D_
    position: relative;_x000D_
    display: inline-block;_x000D_
    font-size: 68px;_x000D_
    color: rgba(0, 0, 0, 0.8);_x000D_
    overflow: hidden;_x000D_
    white-space: pre;_x000D_
    transform: rotate(4deg);_x000D_
    text-shadow: 2px 1px 3px rgba(0, 0, 0, 0.3);_x000D_
}_x000D_
_x000D_
.halfStyle:before { /* creates the left part */_x000D_
    display: block;_x000D_
    z-index: 1;_x000D_
    position: absolute;_x000D_
    top: -0.5px;_x000D_
    left: -3px;_x000D_
    width: 100%;_x000D_
    content: attr(data-content);_x000D_
    overflow: hidden;_x000D_
    pointer-events: none;_x000D_
    color: #FFF;_x000D_
    transform: rotate(-4deg);_x000D_
    text-shadow: 0px 0px 1px #000;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<p>Single Characters:</p>_x000D_
<span class="halfStyle" data-content="X">X</span>_x000D_
<span class="halfStyle" data-content="Y">Y</span>_x000D_
<span class="halfStyle" data-content="Z">Z</span>_x000D_
<span class="halfStyle" data-content="A">A</span>_x000D_
_x000D_
<hr/>_x000D_
<p>Automated:</p>_x000D_
_x000D_
<span class="textToHalfStyle">Half-style, please.</span>
_x000D_
_x000D_
_x000D_

(JSFiddle demo and on samtremaine.co.uk)



Part 4: Ready for Production

Customized different Half-Style style-sets can be used on desired elements on the same page. You can define multiple style-sets and tell the plugin which one to use.

The plugin uses data attribute data-halfstyle="[-CustomClassName-]" on the target .textToHalfStyle elements and makes all the necessary changes automatically.

So, simply on the element containing the text add textToHalfStyle class and data attribute data-halfstyle="[-CustomClassName-]". The plugin will do the rest of the job.

halfStyle - Multiple on Same Page

Also the CSS style-sets' class definitions match the [-CustomClassName-] part mentioned above and is chained to .halfStyle, so we will have .halfStyle.[-CustomClassName-]

_x000D_
_x000D_
jQuery(function($) {_x000D_
    var halfstyle_text, halfstyle_chars, $halfstyle_el, halfstyle_i, halfstyle_output, halfstyle_style;_x000D_
_x000D_
    // Iterate over all class occurrences_x000D_
    $('.textToHalfStyle').each(function(idx, halfstyle_el) {_x000D_
        $halfstyle_el = $(halfstyle_el);_x000D_
        halfstyle_style = $halfstyle_el.data('halfstyle') || 'hs-base';_x000D_
        halfstyle_text = $halfstyle_el.text();_x000D_
        halfstyle_chars = halfstyle_text.split('');_x000D_
_x000D_
        // Set the screen-reader text_x000D_
        $halfstyle_el.html('<span style="position: absolute !important;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);">' + halfstyle_text + '</span>');_x000D_
_x000D_
        // Reset output for appending_x000D_
        halfstyle_output = '';_x000D_
_x000D_
        // Iterate over all chars in the text_x000D_
        for (halfstyle_i = 0; halfstyle_i < halfstyle_chars.length; halfstyle_i++) {_x000D_
            // Create a styled element for each character and append to container_x000D_
            halfstyle_output += '<span aria-hidden="true" class="halfStyle ' + halfstyle_style + '" data-content="' + halfstyle_chars[halfstyle_i] + '">' + halfstyle_chars[halfstyle_i] + '</span>';_x000D_
        }_x000D_
_x000D_
        // Write to DOM only once_x000D_
        $halfstyle_el.append(halfstyle_output);_x000D_
    });_x000D_
});
_x000D_
/* start half-style hs-base */_x000D_
_x000D_
.halfStyle.hs-base {_x000D_
    position: relative;_x000D_
    display: inline-block;_x000D_
    font-size: 80px; /* or any font size will work */_x000D_
    overflow: hidden;_x000D_
    white-space: pre; /* to preserve the spaces from collapsing */_x000D_
    color: #000; /* for demo purposes */_x000D_
}_x000D_
_x000D_
.halfStyle.hs-base:before {_x000D_
    display: block;_x000D_
    z-index: 1;_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    width: 50%;_x000D_
    content: attr(data-content); /* dynamic content for the pseudo element */_x000D_
    pointer-events: none; /* so the base char is selectable by mouse */_x000D_
    overflow: hidden;_x000D_
    color: #f00; /* for demo purposes */_x000D_
}_x000D_
_x000D_
/* end half-style hs-base */_x000D_
_x000D_
_x000D_
/* start half-style hs-horizontal-third */_x000D_
_x000D_
.halfStyle.hs-horizontal-third { /* base char and also the bottom 1/3 */_x000D_
    position: relative;_x000D_
    display: inline-block;_x000D_
    font-size: 80px; /* or any font size will work */_x000D_
    color: transparent;_x000D_
    overflow: hidden;_x000D_
    white-space: pre; /* to preserve the spaces from collapsing */_x000D_
    color: #f0f;_x000D_
    text-shadow: 2px 2px 0px #0af; /* for demo purposes */_x000D_
}_x000D_
_x000D_
.halfStyle.hs-horizontal-third:before { /* creates the top 1/3 */_x000D_
    display: block;_x000D_
    z-index: 2;_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    height: 33.33%;_x000D_
    content: attr(data-content); /* dynamic content for the pseudo element */_x000D_
    overflow: hidden;_x000D_
    pointer-events: none; /* so the base char is selectable by mouse */_x000D_
    color: #f00; /* for demo purposes */_x000D_
    text-shadow: 2px -2px 0px #fa0; /* for demo purposes */_x000D_
}_x000D_
_x000D_
.halfStyle.hs-horizontal-third:after { /* creates the middle 1/3 */_x000D_
    display: block;_x000D_
    position: absolute;_x000D_
    z-index: 1;_x000D_
    top: 0;_x000D_
    height: 66.66%;_x000D_
    content: attr(data-content); /* dynamic content for the pseudo element */_x000D_
    overflow: hidden;_x000D_
    pointer-events: none; /* so the base char is selectable by mouse */_x000D_
    color: #000; /* for demo purposes */_x000D_
    text-shadow: 2px 2px 0px #af0; /* for demo purposes */_x000D_
}_x000D_
_x000D_
/* end half-style hs-horizontal-third */_x000D_
_x000D_
_x000D_
/* start half-style hs-PeelingStyle, by user SamTremaine on Stackoverflow.com */_x000D_
_x000D_
.halfStyle.hs-PeelingStyle {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  font-size: 68px;_x000D_
  color: rgba(0, 0, 0, 0.8);_x000D_
  overflow: hidden;_x000D_
  white-space: pre;_x000D_
  transform: rotate(4deg);_x000D_
  text-shadow: 2px 1px 3px rgba(0, 0, 0, 0.3);_x000D_
}_x000D_
_x000D_
.halfStyle.hs-PeelingStyle:before { /* creates the left part */_x000D_
  display: block;_x000D_
  z-index: 1;_x000D_
  position: absolute;_x000D_
  top: -0.5px;_x000D_
  left: -3px;_x000D_
  width: 100%;_x000D_
  content: attr(data
                  

C# An established connection was aborted by the software in your host machine

This problem appear if two software use same port for connecting to the server
try to close the port by cmd according to your operating system
then reboot your Android studio or your Eclipse or your Software.

Disable/turn off inherited CSS3 transitions

Another way to remove all transitions is with the unset keyword:

a.tags {
    transition: unset;
}

In the case of transition, unset is equivalent to initial, since transition is not an inherited property:

a.tags {
    transition: initial;
}

A reader who knows about unset and initial can tell that these solutions are correct immediately, without having to think about the specific syntax of transition.

How to submit a form with JavaScript by clicking a link?

<form id="mailajob" method="post" action="emailthijob.php">
    <input type="hidden" name="action" value="emailjob" />
    <input type="hidden" name="jid" value="<?php echo $jobid; ?>" />
</form>

<a class="emailjob" onclick="document.getElementById('mailajob').submit();">Email this job</a>

I want to add a JSONObject to a JSONArray and that JSONArray included in other JSONObject

JSONArray jsonArray = new JSONArray();

for (loop) {
    JSONObject jsonObj= new JSONObject();
    jsonObj.put("srcOfPhoto", srcOfPhoto);
    jsonObj.put("username", "name"+count);
    jsonObj.put("userid", "userid"+count);

    jsonArray.put(jsonObj.valueToString());
}

JSONObject parameters = new JSONObject();

parameters.put("action", "remove");

parameters.put("datatable", jsonArray );

parameters.put(Constant.MSG_TYPE , Constant.SUCCESS);

Why were you using an Hashmap if what you wanted was to put it into a JSONObject?

EDIT: As per http://www.json.org/javadoc/org/json/JSONArray.html

EDIT2: On the JSONObject method used, I'm following the code available at: https://github.com/stleary/JSON-java/blob/master/JSONObject.java#L2327 , that method is not deprecated.

We're storing a string representation of the JSONObject, not the JSONObject itself

Good tool to visualise database schema?

Try PHPMyAdmin which has some really nice visualisation and editing feature. I am pretty sure you can even export to exel from it.

DSO missing from command line

DSO here means Dynamic Shared Object; since the error message says it's missing from the command line, I guess you have to add it to the command line.

That is, try adding -lpthread to your command line.

What is JAVA_HOME? How does the JVM find the javac path stored in JAVA_HOME?

JAVA_HOME is a environment variable (in Unix terminologies), or a PATH variable (in Windows terminology). A lot of well behaving Java applications (which need the JDK/JRE) to run, looks up the JAVA_HOME variable for the location where the Java compiler/interpreter may be found.

File Upload In Angular?

To upload image with form fields

SaveFileWithData(article: ArticleModel,picture:File): Observable<ArticleModel> 
{

    let headers = new Headers();
    // headers.append('Content-Type', 'multipart/form-data');
    // headers.append('Accept', 'application/json');

let requestoptions = new RequestOptions({
  method: RequestMethod.Post,
  headers:headers
    });



let formData: FormData = new FormData();
if (picture != null || picture != undefined) {
  formData.append('files', picture, picture.name);
}
 formData.append("article",JSON.stringify(article));

return this.http.post("url",formData,requestoptions)
  .map((response: Response) => response.json() as ArticleModel);
} 

In my case I needed .NET Web Api in C#

// POST: api/Articles
[ResponseType(typeof(Article))]
public async Task<IHttpActionResult> PostArticle()
{
    Article article = null;
    try
    {

        HttpPostedFile postedFile = null;
        var httpRequest = HttpContext.Current.Request;

        if (httpRequest.Files.Count == 1)
        {
            postedFile = httpRequest.Files[0];
            var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
            postedFile.SaveAs(filePath);
        }
        var json = httpRequest.Form["article"];
         article = JsonConvert.DeserializeObject <Article>(json);

        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        article.CreatedDate = DateTime.Now;
        article.CreatedBy = "Abbas";

        db.articles.Add(article);
        await db.SaveChangesAsync();
    }
    catch (Exception ex)
    {
        int a = 0;
    }
    return CreatedAtRoute("DefaultApi", new { id = article.Id }, article);
}

How do I check if an HTML element is empty using jQuery?

White space and line breaks are the main issues with using :empty selector. Careful, in CSS the :empty pseudo class behaves the same way. I like this method:

if ($someElement.children().length == 0){
     someAction();
}

Find records from one table which don't exist in another

SELECT Call.ID, Call.date, Call.phone_number 
FROM Call 
LEFT OUTER JOIN Phone_Book 
  ON (Call.phone_number=Phone_book.phone_number) 
  WHERE Phone_book.phone_number IS NULL

Should remove the subquery, allowing the query optimiser to work its magic.

Also, avoid "SELECT *" because it can break your code if someone alters the underlying tables or views (and it's inefficient).

The difference between bracket [ ] and double bracket [[ ]] for accessing the elements of a list or dataframe

To help newbies navigate through the manual fog, it might be helpful to see the [[ ... ]] notation as a collapsing function - in other words, it is when you just want to 'get the data' from a named vector, list or data frame. It is good to do this if you want to use data from these objects for calculations. These simple examples will illustrate.

(x <- c(x=1, y=2)); x[1]; x[[1]]
(x <- list(x=1, y=2, z=3)); x[1]; x[[1]]
(x <- data.frame(x=1, y=2, z=3)); x[1]; x[[1]]

So from the third example:

> 2 * x[1]
  x
1 2
> 2 * x[[1]]
[1] 2

Android LinearLayout Gradient Background

Ok I have managed to solve this using a selector. See code below:

main_header.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="50dip"
    android:orientation="horizontal"
    android:background="@drawable/main_header_selector">
</LinearLayout>

main_header_selector.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
    <shape>
        <gradient
            android:angle="90"
            android:startColor="#FFFF0000"
            android:endColor="#FF00FF00"
            android:type="linear" />
    </shape>
</item>
</selector>

Hopefully this helps someone who has the same problem.

Android: Bitmaps loaded from gallery are rotated in ImageView

I have melted @Timmmm answer and @Manuel. If you do this solution, you will not get a Run Out Of Memory Exception.

This method retrieves the image orientation:

private static final int ROTATION_DEGREES = 90;
// This means 512 px
private static final Integer MAX_IMAGE_DIMENSION = 512;

public static int getOrientation(Uri photoUri) throws IOException {

    ExifInterface exif = new ExifInterface(photoUri.getPath());
    int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);

    switch (orientation) {
        case ExifInterface.ORIENTATION_ROTATE_90:
            orientation = ROTATION_DEGREES;
            break;
        case ExifInterface.ORIENTATION_ROTATE_180:
            orientation = ROTATION_DEGREES * 2;
            break;
        case ExifInterface.ORIENTATION_ROTATE_270:
            orientation = ROTATION_DEGREES * 3;
            break;
        default:
            // Default case, image is not rotated
            orientation = 0;
    }

    return orientation;
}

Therefore, you would use this method to resize image before load it on memory. In that way, you will not get a Memory Exception.

public static Bitmap getCorrectlyOrientedImage(Context context, Uri photoUri) throws IOException {
    InputStream is = context.getContentResolver().openInputStream(photoUri);
    BitmapFactory.Options dbo = new BitmapFactory.Options();
    dbo.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(is, null, dbo);
    is.close();

    int rotatedWidth, rotatedHeight;
    int orientation = getOrientation(photoUri);

    if (orientation == 90 || orientation == 270) {
        rotatedWidth = dbo.outHeight;
        rotatedHeight = dbo.outWidth;
    } else {
        rotatedWidth = dbo.outWidth;
        rotatedHeight = dbo.outHeight;
    }

    Bitmap srcBitmap;
    is = context.getContentResolver().openInputStream(photoUri);
    if (rotatedWidth > MAX_IMAGE_DIMENSION || rotatedHeight > MAX_IMAGE_DIMENSION) {
        float widthRatio = ((float) rotatedWidth) / ((float) MAX_IMAGE_DIMENSION);
        float heightRatio = ((float) rotatedHeight) / ((float) MAX_IMAGE_DIMENSION);
        float maxRatio = Math.max(widthRatio, heightRatio);

        // Create the bitmap from file
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = (int) maxRatio;
        srcBitmap = BitmapFactory.decodeStream(is, null, options);
    } else {
        srcBitmap = BitmapFactory.decodeStream(is);
    }
    is.close();

    // if the orientation is not 0, we have to do a rotation.
    if (orientation > 0) {
        Matrix matrix = new Matrix();
        matrix.postRotate(orientation);

        srcBitmap = Bitmap.createBitmap(srcBitmap, 0, 0, srcBitmap.getWidth(),
                srcBitmap.getHeight(), matrix, true);
    }

    return srcBitmap;
}

This works perfectly for me. I hope this helps somebody else

Typescript : Property does not exist on type 'object'

You probably have allProviders typed as object[] as well. And property country does not exist on object. If you don't care about typing, you can declare both allProviders and countryProviders as Array<any>:

let countryProviders: Array<any>;
let allProviders: Array<any>;

If you do want static type checking. You can create an interface for the structure and use it:

interface Provider {
    region: string,
    country: string,
    locale: string,
    company: string
}

let countryProviders: Array<Provider>;
let allProviders: Array<Provider>;

Binding objects defined in code-behind

Make your property "windowname" a DependencyProperty and keep the remaining same.

String Pattern Matching In Java

If you want to check if some string is present in another string, use something like String.contains

If you want to check if some pattern is present in a string, append and prepend the pattern with '.*'. The result will accept strings that contain the pattern.

Example: Suppose you have some regex a(b|c) that checks if a string matches ab or ac
.*(a(b|c)).* will check if a string contains a ab or ac.

A disadvantage of this method is that it will not give you the location of the match.

How do I clear a C++ array?

If only to 0 then you can use memset:

int* a = new int[6];

memset(a, 0, 6*sizeof(int));

Install specific branch from github using Npm

Tried suggested answers, but got it working only with this prefix approach:

npm i github:user/repo.git#version --save -D

How can I make a CSS glass/blur effect work for an overlay?

I was able to piece together information from everyone here and further Googling, and I came up with the following which works in Chrome and Firefox: http://jsfiddle.net/xtbmpcsu/. I'm still working on making this work for IE and Opera.

The key is putting the content inside of the div to which the filter is applied:

<div id="mask">
    <p>Lorem ipsum ...</p>
    <img src="http://www.byui.edu/images/agriculture-life-sciences/flower.jpg" />
</div>

And then the CSS:

body {
    background: #300000;
    background: linear-gradient(45deg, #300000, #000000, #300000, #000000);
    color: white;
}
#mask {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    background-color: black;
    opacity: 0.5;
}
img {
    filter: blur(10px);
    -webkit-filter: blur(10px);
    -moz-filter: blur(10px);
    -o-filter: blur(10px);
    -ms-filter: blur(10px);
    position: absolute;
    left: 100px;
    top: 100px;
    height: 300px;
    width: auto;
}

So mask has the filters applied. Also, note the use of url() for a filter with an <svg> tag for the value -- that idea came from http://codepen.io/AmeliaBR/pen/xGuBr. If you happen to minify your CSS, you might need to replace any spaces in the SVG filter markup with "%20".

So now, everything inside the mask div is blurred.

event.preventDefault() function not working in IE

If you bind the event through mootools' addEvent function your event handler will get a fixed (augmented) event passed as the parameter. It will always contain the preventDefault() method.

Try out this fiddle to see the difference in event binding. http://jsfiddle.net/pFqrY/8/

// preventDefault always works
$("mootoolsbutton").addEvent('click', function(event) {
 alert(typeof(event.preventDefault));
});

// preventDefault missing in IE
<button
  id="htmlbutton"
  onclick="alert(typeof(event.preventDefault));">
  button</button>

For all jQuery users out there you can fix an event when needed. Say that you used HTML onclick=".." and get a IE specific event that lacks preventDefault(), just use this code to get it.

e = $.event.fix(e);

After that e.preventDefault(); works fine.

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

You don't need a third party package to get this information. pypi provides simple JSON feeds for all packages under

https://pypi.org/pypi/{PKG_NAME}/json

Here's some Python code using only the standard library which gets all versions.

import json
import urllib2
from distutils.version import StrictVersion

def versions(package_name):
    url = "https://pypi.org/pypi/%s/json" % (package_name,)
    data = json.load(urllib2.urlopen(urllib2.Request(url)))
    versions = data["releases"].keys()
    versions.sort(key=StrictVersion)
    return versions

print "\n".join(versions("scikit-image"))

That code prints (as of Feb 23rd, 2015):

0.7.2
0.8.0
0.8.1
0.8.2
0.9.0
0.9.1
0.9.2
0.9.3
0.10.0
0.10.1

How to detect my browser version and operating system using JavaScript?

Detecting browser's details:

var nVer = navigator.appVersion;
var nAgt = navigator.userAgent;
var browserName  = navigator.appName;
var fullVersion  = ''+parseFloat(navigator.appVersion); 
var majorVersion = parseInt(navigator.appVersion,10);
var nameOffset,verOffset,ix;

// In Opera, the true version is after "Opera" or after "Version"
if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
 browserName = "Opera";
 fullVersion = nAgt.substring(verOffset+6);
 if ((verOffset=nAgt.indexOf("Version"))!=-1) 
   fullVersion = nAgt.substring(verOffset+8);
}
// In MSIE, the true version is after "MSIE" in userAgent
else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
 browserName = "Microsoft Internet Explorer";
 fullVersion = nAgt.substring(verOffset+5);
}
// In Chrome, the true version is after "Chrome" 
else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
 browserName = "Chrome";
 fullVersion = nAgt.substring(verOffset+7);
}
// In Safari, the true version is after "Safari" or after "Version" 
else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {
 browserName = "Safari";
 fullVersion = nAgt.substring(verOffset+7);
 if ((verOffset=nAgt.indexOf("Version"))!=-1) 
   fullVersion = nAgt.substring(verOffset+8);
}
// In Firefox, the true version is after "Firefox" 
else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
 browserName = "Firefox";
 fullVersion = nAgt.substring(verOffset+8);
}
// In most other browsers, "name/version" is at the end of userAgent 
else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) < 
          (verOffset=nAgt.lastIndexOf('/')) ) 
{
 browserName = nAgt.substring(nameOffset,verOffset);
 fullVersion = nAgt.substring(verOffset+1);
 if (browserName.toLowerCase()==browserName.toUpperCase()) {
  browserName = navigator.appName;
 }
}
// trim the fullVersion string at semicolon/space if present
if ((ix=fullVersion.indexOf(";"))!=-1)
   fullVersion=fullVersion.substring(0,ix);
if ((ix=fullVersion.indexOf(" "))!=-1)
   fullVersion=fullVersion.substring(0,ix);

majorVersion = parseInt(''+fullVersion,10);
if (isNaN(majorVersion)) {
 fullVersion  = ''+parseFloat(navigator.appVersion); 
 majorVersion = parseInt(navigator.appVersion,10);
}

document.write(''
 +'Browser name  = '+browserName+'<br>'
 +'Full version  = '+fullVersion+'<br>'
 +'Major version = '+majorVersion+'<br>'
 +'navigator.appName = '+navigator.appName+'<br>'
 +'navigator.userAgent = '+navigator.userAgent+'<br>'
)

Source JavaScript: browser name.
See JSFiddle to detect Browser Details.

Detecting OS:

// This script sets OSName variable as follows:
// "Windows"    for all versions of Windows
// "MacOS"      for all versions of Macintosh OS
// "Linux"      for all versions of Linux
// "UNIX"       for all other UNIX flavors 
// "Unknown OS" indicates failure to detect the OS

var OSName="Unknown OS";
if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";
if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";

document.write('Your OS: '+OSName);

source JavaScript: OS detection.
See JSFiddle to detect OS Details.

_x000D_
_x000D_
    var nVer = navigator.appVersion;_x000D_
    var nAgt = navigator.userAgent;_x000D_
    var browserName  = navigator.appName;_x000D_
    var fullVersion  = ''+parseFloat(navigator.appVersion); _x000D_
    var majorVersion = parseInt(navigator.appVersion,10);_x000D_
    var nameOffset,verOffset,ix;_x000D_
    _x000D_
    // In Opera, the true version is after "Opera" or after "Version"_x000D_
    if ((verOffset=nAgt.indexOf("Opera"))!=-1) {_x000D_
     browserName = "Opera";_x000D_
     fullVersion = nAgt.substring(verOffset+6);_x000D_
     if ((verOffset=nAgt.indexOf("Version"))!=-1) _x000D_
       fullVersion = nAgt.substring(verOffset+8);_x000D_
    }_x000D_
    // In MSIE, the true version is after "MSIE" in userAgent_x000D_
    else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {_x000D_
     browserName = "Microsoft Internet Explorer";_x000D_
     fullVersion = nAgt.substring(verOffset+5);_x000D_
    }_x000D_
    // In Chrome, the true version is after "Chrome" _x000D_
    else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {_x000D_
     browserName = "Chrome";_x000D_
     fullVersion = nAgt.substring(verOffset+7);_x000D_
    }_x000D_
    // In Safari, the true version is after "Safari" or after "Version" _x000D_
    else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {_x000D_
     browserName = "Safari";_x000D_
     fullVersion = nAgt.substring(verOffset+7);_x000D_
     if ((verOffset=nAgt.indexOf("Version"))!=-1) _x000D_
       fullVersion = nAgt.substring(verOffset+8);_x000D_
    }_x000D_
    // In Firefox, the true version is after "Firefox" _x000D_
    else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {_x000D_
     browserName = "Firefox";_x000D_
     fullVersion = nAgt.substring(verOffset+8);_x000D_
    }_x000D_
    // In most other browsers, "name/version" is at the end of userAgent _x000D_
    else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) < _x000D_
              (verOffset=nAgt.lastIndexOf('/')) ) _x000D_
    {_x000D_
     browserName = nAgt.substring(nameOffset,verOffset);_x000D_
     fullVersion = nAgt.substring(verOffset+1);_x000D_
     if (browserName.toLowerCase()==browserName.toUpperCase()) {_x000D_
      browserName = navigator.appName;_x000D_
     }_x000D_
    }_x000D_
    // trim the fullVersion string at semicolon/space if present_x000D_
    if ((ix=fullVersion.indexOf(";"))!=-1)_x000D_
       fullVersion=fullVersion.substring(0,ix);_x000D_
    if ((ix=fullVersion.indexOf(" "))!=-1)_x000D_
       fullVersion=fullVersion.substring(0,ix);_x000D_
    _x000D_
    majorVersion = parseInt(''+fullVersion,10);_x000D_
    if (isNaN(majorVersion)) {_x000D_
     fullVersion  = ''+parseFloat(navigator.appVersion); _x000D_
     majorVersion = parseInt(navigator.appVersion,10);_x000D_
    }_x000D_
    _x000D_
    document.write(''_x000D_
     +'Browser name  = '+browserName+'<br>'_x000D_
     +'Full version  = '+fullVersion+'<br>'_x000D_
     +'Major version = '+majorVersion+'<br>'_x000D_
     +'navigator.appName = '+navigator.appName+'<br>'_x000D_
     +'navigator.userAgent = '+navigator.userAgent+'<br>'_x000D_
    )_x000D_
_x000D_
    // This script sets OSName variable as follows:_x000D_
    // "Windows"    for all versions of Windows_x000D_
    // "MacOS"      for all versions of Macintosh OS_x000D_
    // "Linux"      for all versions of Linux_x000D_
    // "UNIX"       for all other UNIX flavors _x000D_
    // "Unknown OS" indicates failure to detect the OS_x000D_
    _x000D_
    var OSName="Unknown OS";_x000D_
    if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";_x000D_
    if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";_x000D_
    if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";_x000D_
    if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";_x000D_
    _x000D_
    document.write('Your OS: '+OSName);
_x000D_
_x000D_
_x000D_

How to preview a part of a large pandas DataFrame, in iPython notebook?

In this case, where the DataFrame is long but not too wide, you can simply slice it:

>>> df = pd.DataFrame({"A": range(1000), "B": range(1000)})
>>> df
<class 'pandas.core.frame.DataFrame'>
Int64Index: 1000 entries, 0 to 999
Data columns:
A    1000  non-null values
B    1000  non-null values
dtypes: int64(2)
>>> df[:5]
   A  B
0  0  0
1  1  1
2  2  2
3  3  3
4  4  4

ix is deprecated.

If it's both wide and long, I tend to use .ix:

>>> df = pd.DataFrame({i: range(1000) for i in range(100)})
>>> df.ix[:5, :10]
   0   1   2   3   4   5   6   7   8   9   10
0   0   0   0   0   0   0   0   0   0   0   0
1   1   1   1   1   1   1   1   1   1   1   1
2   2   2   2   2   2   2   2   2   2   2   2
3   3   3   3   3   3   3   3   3   3   3   3
4   4   4   4   4   4   4   4   4   4   4   4
5   5   5   5   5   5   5   5   5   5   5   5

Python: BeautifulSoup - get an attribute value based on the name attribute

If tdd='<td class="abc"> 75</td>'
In Beautifulsoup 

if(tdd.has_attr('class')):
   print(tdd.attrs['class'][0])


Result:  abc

How can I print a circular structure in a JSON-like format?

Try this:

var obj = {
    a: "foo",
    b: obj
};

var circular_replacer = (value) => {
    var seen = [];
    if (value != null && typeof value == "object") {
        if (seen.indexOf(value) >= 0) return;
        seen.push(value);
    }
    return value;
};

obj = circular_replacer(obj);

Is it possible to 'prefill' a google form using data from a google spreadsheet?

You can create a pre-filled form URL from within the Form Editor, as described in the documentation for Drive Forms. You'll end up with a URL like this, for example:

https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=Mike+Jones&entry.787184751=1975-05-09&entry.1381372492&entry.960923899

buildUrls()

In this example, question 1, "Name", has an ID of 726721210, while question 2, "Birthday" is 787184751. Questions 3 and 4 are blank.

You could generate the pre-filled URL by adapting the one provided through the UI to be a template, like this:

function buildUrls() {
  var template = "https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=##Name##&entry.787184751=##Birthday##&entry.1381372492&entry.960923899";
  var ss = SpreadsheetApp.getActive().getSheetByName("Sheet1");  // Email, Name, Birthday
  var data = ss.getDataRange().getValues();

  // Skip headers, then build URLs for each row in Sheet1.
  for (var i = 1; i < data.length; i++ ) {
    var url = template.replace('##Name##',escape(data[i][1]))
                      .replace('##Birthday##',data[i][2].yyyymmdd());  // see yyyymmdd below
    Logger.log(url);  // You could do something more useful here.
  }
};

This is effective enough - you could email the pre-filled URL to each person, and they'd have some questions already filled in.

betterBuildUrls()

Instead of creating our template using brute force, we can piece it together programmatically. This will have the advantage that we can re-use the code without needing to remember to change the template.

Each question in a form is an item. For this example, let's assume the form has only 4 questions, as you've described them. Item [0] is "Name", [1] is "Birthday", and so on.

We can create a form response, which we won't submit - instead, we'll partially complete the form, only to get the pre-filled form URL. Since the Forms API understands the data types of each item, we can avoid manipulating the string format of dates and other types, which simplifies our code somewhat.

(EDIT: There's a more general version of this in How to prefill Google form checkboxes?)

/**
 * Use Form API to generate pre-filled form URLs
 */
function betterBuildUrls() {
  var ss = SpreadsheetApp.getActive();
  var sheet = ss.getSheetByName("Sheet1");
  var data = ss.getDataRange().getValues();  // Data for pre-fill

  var formUrl = ss.getFormUrl();             // Use form attached to sheet
  var form = FormApp.openByUrl(formUrl);
  var items = form.getItems();

  // Skip headers, then build URLs for each row in Sheet1.
  for (var i = 1; i < data.length; i++ ) {
    // Create a form response object, and prefill it
    var formResponse = form.createResponse();

    // Prefill Name
    var formItem = items[0].asTextItem();
    var response = formItem.createResponse(data[i][1]);
    formResponse.withItemResponse(response);

    // Prefill Birthday
    formItem = items[1].asDateItem();
    response = formItem.createResponse(data[i][2]);
    formResponse.withItemResponse(response);

    // Get prefilled form URL
    var url = formResponse.toPrefilledUrl();
    Logger.log(url);  // You could do something more useful here.
  }
};

yymmdd Function

Any date item in the pre-filled form URL is expected to be in this format: yyyy-mm-dd. This helper function extends the Date object with a new method to handle the conversion.

When reading dates from a spreadsheet, you'll end up with a javascript Date object, as long as the format of the data is recognizable as a date. (Your example is not recognizable, so instead of May 9th 1975 you could use 5/9/1975.)

// From http://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/
Date.prototype.yyyymmdd = function() {
  var yyyy = this.getFullYear().toString();                                    
  var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based         
  var dd  = this.getDate().toString();             

  return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};

Is Java "pass-by-reference" or "pass-by-value"?

A reference is always a value when represented, no matter what language you use.

Getting an outside of the box view, let's look at Assembly or some low level memory management. At the CPU level a reference to anything immediately becomes a value if it gets written to memory or to one of the CPU registers. (That is why pointer is a good definition. It is a value, which has a purpose at the same time).

Data in memory has a Location and at that location there is a value (byte,word, whatever). In Assembly we have a convenient solution to give a Name to certain Location (aka variable), but when compiling the code, the assembler simply replaces Name with the designated location just like your browser replaces domain names with IP addresses.

Down to the core it is technically impossible to pass a reference to anything in any language without representing it (when it immediately becomes a value).

Lets say we have a variable Foo, its Location is at the 47th byte in memory and its Value is 5. We have another variable Ref2Foo which is at 223rd byte in memory, and its value will be 47. This Ref2Foo might be a technical variable, not explicitly created by the program. If you just look at 5 and 47 without any other information, you will see just two Values. If you use them as references then to reach to 5 we have to travel:

(Name)[Location] -> [Value at the Location]
---------------------
(Ref2Foo)[223]  -> 47
(Foo)[47]       -> 5

This is how jump-tables work.

If we want to call a method/function/procedure with Foo's value, there are a few possible way to pass the variable to the method, depending on the language and its several method invocation modes:

  1. 5 gets copied to one of the CPU registers (ie. EAX).
  2. 5 gets PUSHd to the stack.
  3. 47 gets copied to one of the CPU registers
  4. 47 PUSHd to the stack.
  5. 223 gets copied to one of the CPU registers.
  6. 223 gets PUSHd to the stack.

In every cases above a value - a copy of an existing value - has been created, it is now upto the receiving method to handle it. When you write "Foo" inside the method, it is either read out from EAX, or automatically dereferenced, or double dereferenced, the process depends on how the language works and/or what the type of Foo dictates. This is hidden from the developer until she circumvents the dereferencing process. So a reference is a value when represented, because a reference is a value that has to be processed (at language level).

Now we have passed Foo to the method:

  • in case 1. and 2. if you change Foo (Foo = 9) it only affects local scope as you have a copy of the Value. From inside the method we cannot even determine where in memory the original Foo was located.
  • in case 3. and 4. if you use default language constructs and change Foo (Foo = 11), it could change Foo globally (depends on the language, ie. Java or like Pascal's procedure findMin(x, y, z: integer;var m: integer);). However if the language allows you to circumvent the dereference process, you can change 47, say to 49. At that point Foo seems to have been changed if you read it, because you have changed the local pointer to it. And if you were to modify this Foo inside the method (Foo = 12) you will probably FUBAR the execution of the program (aka. segfault) because you will write to a different memory than expected, you can even modify an area that is destined to hold executable program and writing to it will modify running code (Foo is now not at 47). BUT Foo's value of 47 did not change globally, only the one inside the method, because 47 was also a copy to the method.
  • in case 5. and 6. if you modify 223 inside the method it creates the same mayhem as in 3. or 4. (a pointer, pointing to a now bad value, that is again used as a pointer) but this is still a local problem, as 223 was copied. However if you are able to dereference Ref2Foo (that is 223), reach to and modify the pointed value 47, say, to 49, it will affect Foo globally, because in this case the methods got a copy of 223 but the referenced 47 exists only once, and changing that to 49 will lead every Ref2Foo double-dereferencing to a wrong value.

Nitpicking on insignificant details, even languages that do pass-by-reference will pass values to functions, but those functions know that they have to use it for dereferencing purposes. This pass-the-reference-as-value is just hidden from the programmer because it is practically useless and the terminology is only pass-by-reference.

Strict pass-by-value is also useless, it would mean that a 100 Mbyte array should have to be copied every time we call a method with the array as argument, therefore Java cannot be stricly pass-by-value. Every language would pass a reference to this huge array (as a value) and either employs copy-on-write mechanism if that array can be changed locally inside the method or allows the method (as Java does) to modify the array globally (from the caller's view) and a few languages allows to modify the Value of the reference itself.

So in short and in Java's own terminology, Java is pass-by-value where value can be: either a real value or a value that is a representation of a reference.

How do I force detach Screen from another SSH session?

try with screen -d -r or screen -D -RR

What’s the best RESTful method to return total number of items in an object?

What about a new end point > /api/members/count which just calls Members.Count() and returns the result

Android basics: running code in the UI thread

None of those are precisely the same, though they will all have the same net effect.

The difference between the first and the second is that if you happen to be on the main application thread when executing the code, the first one (runOnUiThread()) will execute the Runnable immediately. The second one (post()) always puts the Runnable at the end of the event queue, even if you are already on the main application thread.

The third one, assuming you create and execute an instance of BackgroundTask, will waste a lot of time grabbing a thread out of the thread pool, to execute a default no-op doInBackground(), before eventually doing what amounts to a post(). This is by far the least efficient of the three. Use AsyncTask if you actually have work to do in a background thread, not just for the use of onPostExecute().

Push item to associative array in PHP

Curtis's answer was very close to what I needed, but I changed it up a little.

Where he used:

$options['inputs']['name'][] = $new_input['name'];

I used:

$options[]['inputs']['name'] = $new_input['name'];

Here's my actual code using a query from a DB:

while($row=mysql_fetch_array($result)){ 
    $dtlg_array[]['dt'] = $row['dt'];
    $dtlg_array[]['lat'] = $row['lat'];
    $dtlg_array[]['lng'] = $row['lng'];
}

Thanks!

Shortcut to comment out a block of code with sublime text

Ctrl-/ will insert // style commenting, for javascript, etc
Ctrl-/ will insert <!-- --> comments for HTML,
Ctrl-/ will insert # comments for Ruby,
..etc

But does not work perfectly on HTML <script> tags.

HTML <script> ..blah.. </script> tags:
Ctrl-/ twice (ie Ctrl-/Ctrl-/) will effectively comment out the line:

  • The first Ctrl-/ adds // to the beginning of the line,
    which comments out the script tag, but adds "//" text to your webpage.
  • The second Ctrl-/ then surrounds that in <!-- --> style comments, which accomplishes the task.

Ctrl--Shift-/ does not produce multi-line comments on HTML (or even single line comments), but does
add /* */ style multi-line comments in Javascript, text, and other file formats.

--

[I added as a new answer since I could not add comments.
I included this info because this is the info I was looking for, and this is the only related StackOverflow page from my search results.
I since discovered the / / trick for HTML script tags and decided to share this additional information, since it requires a slight variation of the usual catch-all (and reported above)
/ and Ctrl--Shift-/ method of commenting out one's code in sublime.]

Consider defining a bean of type 'package' in your configuration [Spring-Boot]

check the base package name.If the package has different modules that are not prefixed with base package name.

Is there an equivalent method to C's scanf in Java?

Take a look at this site, it explains two methods for reading from console in java, using Scanner or the classical InputStreamReader from System.in.

Following code is taken from cited website:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ReadConsoleSystem {
  public static void main(String[] args) {

    System.out.println("Enter something here : ");

    try{
        BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
        String s = bufferRead.readLine();

        System.out.println(s);
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }

  }
}

--

import java.util.Scanner;

public class ReadConsoleScanner {
  public static void main(String[] args) {

      System.out.println("Enter something here : ");

       String sWhatever;

       Scanner scanIn = new Scanner(System.in);
       sWhatever = scanIn.nextLine();

       scanIn.close();            
       System.out.println(sWhatever);
  }
}

Regards.

Find nginx version?

It seems that your nginx hasn't been installed correctly. Pay attention to the output of the installation commands:

sudo apt-get install nginx

To check the nginx version, you can use this command:

$ nginx -v
nginx version: nginx/0.8.54

$ nginx -V
nginx version: nginx/0.8.54
TLS SNI support enabled
configure arguments: --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-client-body-temp-path=/var/lib/nginx/body --http-fastcgi-temp-path=/var/lib/nginx/fastcgi --http-log-path=/var/log/nginx/access.log --http-proxy-temp-path=/var/lib/nginx/proxy --http-scgi-temp-path=/var/lib/nginx/scgi --http-uwsgi-temp-path=/var/lib/nginx/uwsgi --lock-path=/var/lock/nginx.lock --pid-path=/var/run/nginx.pid --with-debug --with-http_addition_module --with-http_dav_module --with-http_geoip_module --with-http_gzip_static_module --with-http_image_filter_module --with-http_realip_module --with-http_stub_status_module --with-http_ssl_module --with-http_sub_module --with-http_xslt_module --with-ipv6 --with-sha1=/usr/include/openssl --with-md5=/usr/include/openssl --with-mail --with-mail_ssl_module --add-module=/build/buildd/nginx-0.8.54/debian/modules/nginx-upstream-fair

For more information: http://nginxlibrary.com/check-nginx-version/

You can use -v parameter to display the Nginx version only, or use the -V parameter to display the version, along with the compiler version and configuration parameters.

Write a function that returns the longest palindrome in a given string

my solution is :

static string GetPolyndrom(string str)
{
    string Longest = "";

    for (int i = 0; i < str.Length; i++)
    {
        if ((str.Length - 1 - i) < Longest.Length)
        {
            break;
        }
        for (int j = str.Length - 1; j > i; j--)
        {
            string str2 = str.Substring(i, j - i + 1);
            if (str2.Length > Longest.Length)
            {
                if (str2 == str2.Reverse())
                {
                    Longest = str2;
                }
            }
            else
            {
                break;
            }
        }

    }
    return Longest;
}

How to remove leading and trailing spaces from a string

 static void Main()
    {
        // A.
        // Example strings with multiple whitespaces.
        string s1 = "He saw   a cute\tdog.";
        string s2 = "There\n\twas another sentence.";

        // B.
        // Create the Regex.
        Regex r = new Regex(@"\s+");

        // C.
        // Strip multiple spaces.
        string s3 = r.Replace(s1, @" ");
        Console.WriteLine(s3);

        // D.
        // Strip multiple spaces.
        string s4 = r.Replace(s2, @" ");
        Console.WriteLine(s4);
        Console.ReadLine();
    }

OUTPUT:

He saw a cute dog. There was another sentence. He saw a cute dog.

How to display a list using ViewBag

To put it all together, this is what it should look like:

In the controller:

List<Fund> fundList = db.Funds.ToList();
ViewBag.Funds = fundList;

Then in the view:

@foreach (var item in ViewBag.Funds)
{
    <span> @item.FundName </span>
}

Spring Boot application can't resolve the org.springframework.boot package

This answer may be out of topic for most of readers. In my case the dependency didn't update and "mvn clean" didn't work since my wifi network at the office is highly securised, leaving a "connection timed out". (same respect github pushes and pulls don't work) I just moved to teathering with my phone and it works. Stupid, out of topic for most, but it may help some very specific cases.

Flask - Calling python function on button OnClick event

Easiest solution

<button type="button" onclick="window.location.href='{{ url_for( 'move_forward') }}';">Forward</button>

how to calculate percentage in python

I know I am late, but if you want to know the easiest way, you could do a code like this:

number = 100
right_questions = 1
control = 100
c = control / number
cc = right_questions * c
print float(cc)

You can change up the number score, and right_questions. It will tell you the percent.

multiple packages in context:component-scan, spring config

The following approach is correct:

<context:component-scan base-package="x.y.z.service, x.y.z.controller" /> 

Note that the error complains about x.y.z.dao.daoservice.LoginDAO, which is not in the packages mentioned above, perhaps you forgot to add it:

<context:component-scan base-package="x.y.z.service, x.y.z.controller, x.y.z.dao" /> 

Stop handler.postDelayed()

  Boolean condition=false;  //Instance variable declaration.

 //-----------------Inside oncreate--------------------------------------------------- 
  start =(Button)findViewById(R.id.id_start);
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                starthandler();

                if(condition=true)
                {
                    condition=false;
                }


            }
        });

        stop=(Button) findViewById(R.id.id_stoplocatingsmartplug);

        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                stophandler();

            }
        });


    }

//-----------------Inside oncreate---------------------------------------------------

 public void starthandler()
    {

        handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {


                if(!condition)
                {
                    //Do something after 100ms 


                }

            }
        }, 5000);

    }


    public void stophandler()
    {
        condition=true;
    }

What are .a and .so files?

.a files are usually libraries which get statically linked (or more accurately archives), and
.so are dynamically linked libraries.

To do a port you will need the source code that was compiled to make them, or equivalent files on your AIX machine.

How to define servlet filter order of execution using annotations in WAR

You can indeed not define the filter execution order using @WebFilter annotation. However, to minimize the web.xml usage, it's sufficient to annotate all filters with just a filterName so that you don't need the <filter> definition, but just a <filter-mapping> definition in the desired order.

For example,

@WebFilter(filterName="filter1")
public class Filter1 implements Filter {}

@WebFilter(filterName="filter2")
public class Filter2 implements Filter {}

with in web.xml just this:

<filter-mapping>
    <filter-name>filter1</filter-name>
    <url-pattern>/url1/*</url-pattern>
</filter-mapping>
<filter-mapping>
    <filter-name>filter2</filter-name>
    <url-pattern>/url2/*</url-pattern>
</filter-mapping>

If you'd like to keep the URL pattern in @WebFilter, then you can just do like so,

@WebFilter(filterName="filter1", urlPatterns="/url1/*")
public class Filter1 implements Filter {}

@WebFilter(filterName="filter2", urlPatterns="/url2/*")
public class Filter2 implements Filter {}

but you should still keep the <url-pattern> in web.xml, because it's required as per XSD, although it can be empty:

<filter-mapping>
    <filter-name>filter1</filter-name>
    <url-pattern />
</filter-mapping>
<filter-mapping>
    <filter-name>filter2</filter-name>
    <url-pattern />
</filter-mapping>

Regardless of the approach, this all will fail in Tomcat until version 7.0.28 because it chokes on presence of <filter-mapping> without <filter>. See also Using Tomcat, @WebFilter doesn't work with <filter-mapping> inside web.xml

Windows Batch: How to add Host-Entries?

Create a new addHostEntry.bat file with the following content in it:

@echo off
TITLE Modifying your HOSTS file
COLOR F0
ECHO.

:LOOP
SET Choice=
SET /P Choice="Do you want to modify HOSTS file ? (Y/N)"

IF NOT '%Choice%'=='' SET Choice=%Choice:~0,1%

ECHO.
IF /I '%Choice%'=='Y' GOTO ACCEPTED
IF /I '%Choice%'=='N' GOTO REJECTED
ECHO Please type Y (for Yes) or N (for No) to proceed!
ECHO.
GOTO Loop


:REJECTED
ECHO Your HOSTS file was left unchanged>>%systemroot%\Temp\hostFileUpdate.log
ECHO Finished.
GOTO END


:ACCEPTED
SET NEWLINE=^& echo.
ECHO Carrying out requested modifications to your HOSTS file
FIND /C /I "mydomain.com" %WINDIR%\system32\drivers\etc\hosts
IF %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1    mydomain.com>>%WINDIR%\system32\drivers\etc\hosts
ECHO Finished
GOTO END


:END
ECHO.
ping -n 11 127.0.0.1 > nul
EXIT

Hope this helps!

Rounded corners for <input type='text' /> using border-radius.htc for IE

if you are using for certain text field then use the class

<style>
  .inputForm{
      border-radius:5px;
      -moz-border-radius:5px;
      -webkit-border-radius:5px;
   }
</style>

and in html code use

 <input type="text" class="inputForm">

or if u want to do this for all the input type text field means use

<style>
    input[type="text"]{
      border-radius:5px;
      -moz-border-radius:5px;
      -webkit-border-radius:5px;
    }
 </style>

and in html code

<input type="text" name="name">

Can a shell script set environment variables of the calling shell?

You should use modules, see http://modules.sourceforge.net/

EDIT: The modules package has not been updated since 2012 but still works ok for the basics. All the new features, bells and whistles happen in lmod this day (which I like it more): https://www.tacc.utexas.edu/research-development/tacc-projects/lmod

What use is find_package() if you need to specify CMAKE_MODULE_PATH anyway?

Command find_package has two modes: Module mode and Config mode. You are trying to use Module mode when you actually need Config mode.

Module mode

Find<package>.cmake file located within your project. Something like this:

CMakeLists.txt
cmake/FindFoo.cmake
cmake/FindBoo.cmake

CMakeLists.txt content:

list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/cmake")
find_package(Foo REQUIRED) # FOO_INCLUDE_DIR, FOO_LIBRARIES
find_package(Boo REQUIRED) # BOO_INCLUDE_DIR, BOO_LIBRARIES

include_directories("${FOO_INCLUDE_DIR}")
include_directories("${BOO_INCLUDE_DIR}")
add_executable(Bar Bar.hpp Bar.cpp)
target_link_libraries(Bar ${FOO_LIBRARIES} ${BOO_LIBRARIES})

Note that CMAKE_MODULE_PATH has high priority and may be usefull when you need to rewrite standard Find<package>.cmake file.

Config mode (install)

<package>Config.cmake file located outside and produced by install command of other project (Foo for example).

foo library:

> cat CMakeLists.txt 
cmake_minimum_required(VERSION 2.8)
project(Foo)

add_library(foo Foo.hpp Foo.cpp)
install(FILES Foo.hpp DESTINATION include)
install(TARGETS foo DESTINATION lib)
install(FILES FooConfig.cmake DESTINATION lib/cmake/Foo)

Simplified version of config file:

> cat FooConfig.cmake 
add_library(foo STATIC IMPORTED)
find_library(FOO_LIBRARY_PATH foo HINTS "${CMAKE_CURRENT_LIST_DIR}/../../")
set_target_properties(foo PROPERTIES IMPORTED_LOCATION "${FOO_LIBRARY_PATH}")

By default project installed in CMAKE_INSTALL_PREFIX directory:

> cmake -H. -B_builds
> cmake --build _builds --target install
-- Install configuration: ""
-- Installing: /usr/local/include/Foo.hpp
-- Installing: /usr/local/lib/libfoo.a
-- Installing: /usr/local/lib/cmake/Foo/FooConfig.cmake

Config mode (use)

Use find_package(... CONFIG) to include FooConfig.cmake with imported target foo:

> cat CMakeLists.txt 
cmake_minimum_required(VERSION 2.8)
project(Boo)

# import library target `foo`
find_package(Foo CONFIG REQUIRED)

add_executable(boo Boo.cpp Boo.hpp)
target_link_libraries(boo foo)
> cmake -H. -B_builds -DCMAKE_VERBOSE_MAKEFILE=ON
> cmake --build _builds
Linking CXX executable Boo
/usr/bin/c++ ... -o Boo /usr/local/lib/libfoo.a

Note that imported target is highly configurable. See my answer.

Update

Java: get greatest common divisor

Or the Euclidean algorithm for calculating the GCD...

public int egcd(int a, int b) {
    if (a == 0)
        return b;

    while (b != 0) {
        if (a > b)
            a = a - b;
        else
            b = b - a;
    }

    return a;
}

What are all the uses of an underscore in Scala?

Here are some more examples where _ is used:

val nums = List(1,2,3,4,5,6,7,8,9,10)

nums filter (_ % 2 == 0)

nums reduce (_ + _)

nums.exists(_ > 5)

nums.takeWhile(_ < 8)

In all above examples one underscore represents an element in the list (for reduce the first underscore represents the accumulator)

How do I vertical center text next to an image in html/css?

I recommend using tables with <td valign="middle"> (as inkedmn mentioned, it works in all browsers), but if you're wrapping with a link, here's how to do it (works in ugly old browsers too, like Opera 9):

<a href="/" style="display: block; vertical-align: middle;">
    <img src="/logo.png" style="vertical-align: middle;"/>
    <span style="vertical-align: middle;">Sample text</span>
</a>

How to export JSON from MongoDB using Robomongo

A Quick and dirty way: Just write your query as db.getCollection('collection').find({}).toArray() and right click Copy JSON. Paste the data in the editor of your choice.

enter image description here

How to edit my Excel dropdown list?

Attribute_Brands is a named range.

On any worksheet (tab) press F5 and type Attribute_Brands into the reference box and click on the OK button.

This will take you to the named range.

The data in it can be updated by typing new values into the cells.

The named range can be altered via the 'Insert - Name - Define' menu.

What are all codecs and formats supported by FFmpeg?

The formats and codecs supported by your build of ffmpeg can vary due the version, how it was compiled, and if any external libraries, such as libx264, were supported during compilation.

Formats (muxers and demuxers):

List all formats:

ffmpeg -formats

Display options specific to, and information about, a particular muxer:

ffmpeg -h muxer=matroska

Display options specific to, and information about, a particular demuxer:

ffmpeg -h demuxer=gif

Codecs (encoders and decoders):

List all codecs:

ffmpeg -codecs

List all encoders:

ffmpeg -encoders

List all decoders:

ffmpeg -decoders

Display options specific to, and information about, a particular encoder:

ffmpeg -h encoder=mpeg4

Display options specific to, and information about, a particular decoder:

ffmpeg -h decoder=aac

Reading the results

There is a key near the top of the output that describes each letter that precedes the name of the format, encoder, decoder, or codec:

$ ffmpeg -encoders
[…]
Encoders:
 V..... = Video
 A..... = Audio
 S..... = Subtitle
 .F.... = Frame-level multithreading
 ..S... = Slice-level multithreading
 ...X.. = Codec is experimental
 ....B. = Supports draw_horiz_band
 .....D = Supports direct rendering method 1
 ------
[…]
 V.S... mpeg4                MPEG-4 part 2

In this example V.S... indicates that the encoder mpeg4 is a Video encoder and supports Slice-level multithreading.

Also see

What is a codec and how does it differ from a format?

Getting values from query string in an url using AngularJS $location

If your $location.search() is not working, then make sure you have the following:

1) html5Mode(true) is configured in app's module config

appModule.config(['$locationProvider', function($locationProvider) {
   $locationProvider.html5Mode(true);
}]);

2) <base href="/"> is present in your HTML

<head>
  <base href="/">
  ...
</head>

References:

  1. base href="/"
  2. html5Mode

Testing if a list of integer is odd or even

--simple codes--

        #region odd / even numbers  order by desc

        //declaration of integer
        int TotalCount = 50;
        int loop;

        Console.WriteLine("\n---------Odd Numbers -------\n");

        for (loop = TotalCount; loop >= 0; loop--)
        {
            if (loop % 2 == 0)
            {
                Console.WriteLine("Even numbers : #{0}", loop);
            }
        }

        Console.WriteLine("\n---------Even Numbers -------\n");

        for (loop = TotalCount; loop >= 0; loop--)
        {
            if (loop % 2 != 0)
            {
                Console.WriteLine("odd numbers : #{0}", loop);
            }
        }

        Console.ReadLine();

        #endregion

Expression must have class type

It's a pointer, so instead try:

a->f();

Basically the operator . (used to access an object's fields and methods) is used on objects and references, so:

A a;
a.f();
A& ref = a;
ref.f();

If you have a pointer type, you have to dereference it first to obtain a reference:

A* ptr = new A();
(*ptr).f();
ptr->f();

The a->b notation is usually just a shorthand for (*a).b.

A note on smart pointers

The operator-> can be overloaded, which is notably used by smart pointers. When you're using smart pointers, then you also use -> to refer to the pointed object:

auto ptr = make_unique<A>();
ptr->f();

Unsupported operation :not writeable python

You open the variable "file" as a read only then attempt to write to it:

file = open('ValidEmails.txt','r')

Instead, use the 'w' flag.

file = open('ValidEmails.txt','w')
...
file.write(email)

How do you unit test private methods?

Sometimes, it can be good to test private declarations. Fundamentally, a compiler only has one public method: Compile( string outputFileName, params string[] sourceSFileNames ). I'm sure you understand that would be difficult to test such a method without testing each "hidden" declarations!

That's why we have created Visual T#: to make easier tests. It's a free .NET programming language (C# v2.0 compatible).

We have added '.-' operator. It just behave like '.' operator, except you can also access any hidden declaration from your tests without changing anything in your tested project.

Take a look at our web site: download it for free.

SQL Server 2005 How Create a Unique Constraint?

In the management studio diagram choose the table, right click to add new column if desired, right-click on the column and choose "Check Constraints", there you can add one.

Better way to cast object to int

You have several options:

  • (int) — Cast operator. Works if the object already is an integer at some level in the inheritance hierarchy or if there is an implicit conversion defined.

  • int.Parse()/int.TryParse() — For converting from a string of unknown format.

  • int.ParseExact()/int.TryParseExact() — For converting from a string in a specific format

  • Convert.ToInt32() — For converting an object of unknown type. It will use an explicit and implicit conversion or IConvertible implementation if any are defined.

  • as int? — Note the "?". The as operator is only for reference types, and so I used "?" to signify a Nullable<int>. The "as" operator works like Convert.To____(), but think TryParse() rather than Parse(): it returns null rather than throwing an exception if the conversion fails.

Of these, I would prefer (int) if the object really is just a boxed integer. Otherwise use Convert.ToInt32() in this case.

Note that this is a very general answer: I want to throw some attention to Darren Clark's response because I think it does a good job addressing the specifics here, but came in late and wasn't voted as well yet. He gets my vote for "accepted answer", anyway, for also recommending (int), for pointing out that if it fails (int)(short) might work instead, and for recommending you check your debugger to find out the actual runtime type.

Disabling and enabling a html input button

the disable attribute only has one parameter. if you want to reenable it you have to remove the whole thing, not just change the value.

Does Python support short-circuiting?

Yes, Python does support Short-circuit evaluation, minimal evaluation, or McCarthy evaluation for Boolean operators. It is used to reduce the number of evaluations for computing the output of boolean expression. Example -

Base Functions

def a(x):
    print('a')
    return x

def b(x):
    print('b')
    return x 

AND

if(a(True) and b(True)):
    print(1,end='\n\n')

if(a(False) and b(True)):
    print(2,end='\n\n') 

AND-OUTPUT

a
b
1

a 

OR

if(a(True) or b(False)):
    print(3,end='\n\n')

if(a(False) or b(True)):
    print(4,end='\n\n') 

OR-OUTPUT

a
3

a
b
4 

Visual Studio Code: format is not using indent settings

The number of spaces to use for formatting is taken from a different location. I'm using version 1.0 and this is what I've done to fix it (I'm assuming your using spaces instead of tabs):

At the bottom of the editor on the right hand click "Spaces: #":

status bar on the right

Then a menu will appear up top. Select "Indent Using Spaces":

select indentation type

Finally you can select by how many spaces you want your files to be indented.

select tab size

The next time you format a file you should be able to get the spacing you configured.

How can I check if string contains characters & whitespace, not just whitespace?

Simplest answer if your browser supports the trim() function

if (myString && !myString.trim()) {
    //First condition to check if string is not empty
    //Second condition checks if string contains just whitespace
}

Remove spaces from a string in VB.NET

What about Regex.Replace solution?

myStr = Regex.Replace(myStr, "\s", "")

Finding out the name of the original repository you cloned from in Git

This is quick Bash command, that you're probably searching for, will print only a basename of the remote repository:

Where you fetch from:

basename $(git remote show -n origin | grep Fetch | cut -d: -f2-)

Alternatively where you push to:

basename $(git remote show -n origin | grep Push | cut -d: -f2-)

Especially the -n option makes the command much quicker.

Plot two histograms on single chart with matplotlib

Here is a simple method to plot two histograms, with their bars side-by-side, on the same plot when the data has different sizes:

def plotHistogram(p, o):
    """
    p and o are iterables with the values you want to 
    plot the histogram of
    """
    plt.hist([p, o], color=['g','r'], alpha=0.8, bins=50)
    plt.show()

Check if a list contains an item in Ansible

Ansible has a version_compare filter since 1.6. You can do something like below in when conditional:

when: ansible_distribution_version | version_compare('12.04', '>=')

This will give you support for major & minor versions comparisons and you can compare versions using operators like:

<, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne

You can find more information about this here: Ansible - Version comparison filters

Otherwise if you have really simple case you can use what @ProfHase85 suggested

Check if an array is empty or exists

You can use jQuery's isEmptyObject() to check whether the array contains elements or not.

var testArray=[1,2,3,4,5]; 
var testArray1=[];
console.log(jQuery.isEmptyObject(testArray)); //false
console.log(jQuery.isEmptyObject(testArray1)); //true 

Source: https://api.jquery.com/jQuery.isEmptyObject/

Full width layout with twitter bootstrap

*{
   margin:0
   padding:0
}

make sure your container's width:%100

Difference between a User and a Login in SQL Server

I think this is a very useful question with good answer. Just to add my two cents from the MSDN Create a Login page:

A login is a security principal, or an entity that can be authenticated by a secure system. Users need a login to connect to SQL Server. You can create a login based on a Windows principal (such as a domain user or a Windows domain group) or you can create a login that is not based on a Windows principal (such as an SQL Server login).

Note:
To use SQL Server Authentication, the Database Engine must use mixed mode authentication. For more information, see Choose an Authentication Mode.

As a security principal, permissions can be granted to logins. The scope of a login is the whole Database Engine. To connect to a specific database on the instance of SQL Server, a login must be mapped to a database user. Permissions inside the database are granted and denied to the database user, not the login. Permissions that have the scope of the whole instance of SQL Server (for example, the CREATE ENDPOINT permission) can be granted to a login.

Calculating Covariance with Python and Numpy

Thanks to unutbu for the explanation. By default numpy.cov calculates the sample covariance. To obtain the population covariance you can specify normalisation by the total N samples like this:

Covariance = numpy.cov(a, b, bias=True)[0][1]
print(Covariance)

or like this:

Covariance = numpy.cov(a, b, ddof=0)[0][1]
print(Covariance)

Pass correct "this" context to setTimeout callback?

In browsers other than Internet Explorer, you can pass parameters to the function together after the delay:

var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);

So, you can do this:

var timeoutID = window.setTimeout(function (self) {
  console.log(self); 
}, 500, this);

This is better in terms of performance than a scope lookup (caching this into a variable outside of the timeout / interval expression), and then creating a closure (by using $.proxy or Function.prototype.bind).

The code to make it work in IEs from Webreflection:

/*@cc_on
(function (modifierFn) {
  // you have to invoke it as `window`'s property so, `window.setTimeout`
  window.setTimeout = modifierFn(window.setTimeout);
  window.setInterval = modifierFn(window.setInterval);
})(function (originalTimerFn) {
    return function (callback, timeout){
      var args = [].slice.call(arguments, 2);
      return originalTimerFn(function () { 
        callback.apply(this, args) 
      }, timeout);
    }
});
@*/

How to reset selected file with input tag file type in Angular 2?

I am using a a very simple aproach. After a file has been uploaded, i shortly remove the input control, using *ngIf. That will cause the input field being removed from the dom and re-added, consequencely it is a new control, and therefore it is emply:

_x000D_
_x000D_
showUploader: boolean = true;

async upload($event) {
  await dosomethingwiththefile();
  this.showUploader = false;
  setTimeout(() =>{ this.showUploader = true }, 100);
}
_x000D_
<input type="file" (change)="upload($event)" *ngIf="showUploader">
_x000D_
_x000D_
_x000D_

How to get a user's time zone?

Swift 4, 4.2 & 5

var timeZone : String = String()

override func viewDidLoad() {
    super.viewDidLoad()
    timeZone = getCurrentTimeZone()
    print(timeZone)
}

func getCurrentTimeZone() -> String {
        let localTimeZoneAbbreviation: Int = TimeZone.current.secondsFromGMT()
        let items = (localTimeZoneAbbreviation / 3600)
        return "\(items)"
}

org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]A child container failed during start

I had a similar error and fixed it by following steps: 1. Under Servers project (which gets created itself when you add Apache Tomcat Server in Eclipse), open server.xml 2. Comment out the line

<Context docBase=... />

How do I parse JSON in Android?

  1. Writing JSON Parser Class

    public class JSONParser {
    
        static InputStream is = null;
        static JSONObject jObj = null;
        static String json = "";
    
        // constructor
        public JSONParser() {}
    
        public JSONObject getJSONFromUrl(String url) {
    
            // Making HTTP request
            try {
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
    
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
    
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                json = sb.toString();
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }
    
            // try parse the string to a JSON object
            try {
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }
    
            // return JSON String
            return jObj;
    
        }
    }
    
  2. Parsing JSON Data
    Once you created parser class next thing is to know how to use that class. Below i am explaining how to parse the json (taken in this example) using the parser class.

    2.1. Store all these node names in variables: In the contacts json we have items like name, email, address, gender and phone numbers. So first thing is to store all these node names in variables. Open your main activity class and declare store all node names in static variables.

    // url to make request
    private static String url = "http://api.9android.net/contacts";
    
    // JSON Node names
    private static final String TAG_CONTACTS = "contacts";
    private static final String TAG_ID = "id";
    private static final String TAG_NAME = "name";
    private static final String TAG_EMAIL = "email";
    private static final String TAG_ADDRESS = "address";
    private static final String TAG_GENDER = "gender";
    private static final String TAG_PHONE = "phone";
    private static final String TAG_PHONE_MOBILE = "mobile";
    private static final String TAG_PHONE_HOME = "home";
    private static final String TAG_PHONE_OFFICE = "office";
    
    // contacts JSONArray
    JSONArray contacts = null;
    

    2.2. Use parser class to get JSONObject and looping through each json item. Below i am creating an instance of JSONParser class and using for loop i am looping through each json item and finally storing each json data in variable.

    // Creating JSON Parser instance
    JSONParser jParser = new JSONParser();
    
    // getting JSON string from URL
    JSONObject json = jParser.getJSONFromUrl(url);
    
        try {
        // Getting Array of Contacts
        contacts = json.getJSONArray(TAG_CONTACTS);
    
        // looping through All Contacts
        for(int i = 0; i < contacts.length(); i++){
            JSONObject c = contacts.getJSONObject(i);
    
            // Storing each json item in variable
            String id = c.getString(TAG_ID);
            String name = c.getString(TAG_NAME);
            String email = c.getString(TAG_EMAIL);
            String address = c.getString(TAG_ADDRESS);
            String gender = c.getString(TAG_GENDER);
    
            // Phone number is agin JSON Object
            JSONObject phone = c.getJSONObject(TAG_PHONE);
            String mobile = phone.getString(TAG_PHONE_MOBILE);
            String home = phone.getString(TAG_PHONE_HOME);
            String office = phone.getString(TAG_PHONE_OFFICE);
    
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    

How to reset db in Django? I get a command 'reset' not found error

reset has been replaced by flush with Django 1.5, see:

python manage.py help flush

Change color when hover a font awesome icon?

if you want to change only the colour of the flag on hover use this:

http://jsfiddle.net/uvamhedx/

_x000D_
_x000D_
.fa-flag:hover {_x000D_
    color: red;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
_x000D_
<i class="fa fa-flag fa-3x"></i>
_x000D_
_x000D_
_x000D_

GitHub: How to make a fork of public repository private?

Just go to https://github.com/new/import .

GitHub Import

In the section "Your old repository's clone URL" paste the repo URL you want and in "Privacy" select Private.

How to source virtualenv activate in a Bash script

You should use multiple commands in one line. for example:

os.system(". Projects/virenv/bin/activate && python Projects/virenv/django-project/manage.py runserver")

when you activate your virtual environment in one line, I think it forgets for other command lines and you can prevent this by using multiple commands in one line. It worked for me :)

Open Excel file for reading with VBA without display

The problem with both iDevlop's and Ashok's answers is that the fundamental problem is an Excel design flaw (apparently) in which the Open method fails to respect the Application.ScreenUpdating setting of False. Consequently, setting it to False is of no benefit to this problem.

If Patrick McDonald's solution is too burdensome due to the overhead of starting a second instance of Excel, then the best solution I've found is to minimize the time that the opened workbook is visible by re-activating the original window as quickly as possible:

Dim TempWkBk As Workbook
Dim CurrentWin As Window

Set CurrentWin = ActiveWindow
Set TempWkBk = Workbooks.Open(SomeFilePath)
CurrentWin.Activate      'Allows only a VERY brief flash of the opened workbook
TempWkBk.Windows(1).Visible = False 'Only necessary if you also need to prevent
                                    'the user from manually accessing the opened
                                    'workbook before it is closed.

'Operate on the new workbook, which is not visible to the user, then close it...

MySQL Error: #1142 - SELECT command denied to user

I run into this problem as well, the case with me was incorrect naming . I was migrating from local server to online server. my SQL command had "database.tablename.column" structure. the name of database in online server was different. for example my code was "pet.item.name" while it needed to be "pet_app.item.name" changing database name solved my problem.

AutoComplete TextBox in WPF

You can find one in the WPF Toolkit, which is also available via NuGet.

This article demos how to create a textbox which can auto-suggest items at runtime based on input, in this case, disk drive folders. WPF AutoComplete Folder TextBox

Also take a look at this nice Reusable WPF Autocomplete TextBox, it was for me very usable.

/usr/bin/codesign failed with exit code 1

I just came across this error, and here's what I found out in case this helps anyone: I discovered that you can right click the error message in Xcode and choose expand to get more details, including a description of the problem.

In my case, I had two copies of my developer certificate with the same name in different keychain files, and Xcode couldn't figure out which one to use.

Python PIP Install throws TypeError: unsupported operand type(s) for -=: 'Retry' and 'int'

check for network issues, to bypass the exception case code

In my case, I was using a custom index, that index had no route and such would trigger the exception case code. The exception case bug still exists and still masks the real issue, however I was able to work around this by testing the connectivity with other tools such as nc -vzw1 myindex.example.org 443 and retrying when the network was up.

How can I Convert HTML to Text in C#?

Try the easy and usable way: just call StripHTML(WebBrowserControl_name);

 public string StripHTML(WebBrowser webp)
        {
            try
            {
                doc.execCommand("SelectAll", true, null);
                IHTMLSelectionObject currentSelection = doc.selection;

                if (currentSelection != null)
                {
                    IHTMLTxtRange range = currentSelection.createRange() as IHTMLTxtRange;
                    if (range != null)
                    {
                        currentSelection.empty();
                        return range.text;
                    }
                }
            }
            catch (Exception ep)
            {
                //MessageBox.Show(ep.Message);
            }
            return "";

        }

Omitting all xsi and xsd namespaces when serializing an object in .NET?

XmlSerializer sr = new XmlSerializer(objectToSerialize.GetType());
TextWriter xmlWriter = new StreamWriter(filename);
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
sr.Serialize(xmlWriter, objectToSerialize, namespaces);

Filter LogCat to get only the messages from My Application in Android?

If you are using Eclipse, press the green + sign in the logCat window below and put your package name (com.example.yourappname) in the by Application Name box. Also, choose any name comfortable to you in Filter Name box and click ok. You will see only messages related to your application when the filter you just added is chosen from the left pane in the logCat.

Correct way to write loops for promise.

Here's another method (ES6 w/std Promise). Uses lodash/underscore type exit criteria (return === false). Note that you could easily add an exitIf() method in options to run in doOne().

const whilePromise = (fnReturningPromise,options = {}) => { 
    // loop until fnReturningPromise() === false
    // options.delay - setTimeout ms (set to 0 for 1 tick to make non-blocking)
    return new Promise((resolve,reject) => {
        const doOne = () => {
            fnReturningPromise()
            .then((...args) => {
                if (args.length && args[0] === false) {
                    resolve(...args);
                } else {
                    iterate();
                }
            })
        };
        const iterate = () => {
            if (options.delay !== undefined) {
                setTimeout(doOne,options.delay);
            } else {
                doOne();
            }
        }
        Promise.resolve()
        .then(iterate)
        .catch(reject)
    })
};

Intent.putExtra List

 //To send from the activity that is calling another activity via myIntent

    myIntent.putExtra("id","10");
    startActivity(myIntent);

    //To receive from another Activity

            Bundle bundle = getIntent().getExtras();
            String id=bundle.getString("id");

How to have css3 animation to loop forever

add this styles

animation-iteration-count:infinite;

Using tr to replace newline with space

Best guess is you are on windows and your line ending settings are set for windows. See this topic: How to change line-ending settings

or use:

tr '\r\n' ' '

How can I solve the error LNK2019: unresolved external symbol - function?

In my case, set the cpp file to "C/C++ compiler" in "property"->"general", resolve the LNK2019 error.

What is the iOS 6 user agent string?

Some more:

Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_3 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B329 Safari/8536.25

Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_4 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B350 Safari/8536.25

How do I remove a library from the arduino environment?

I had to look for them in C:\Users\Dell\AppData\Local\Arduino15\

I had to take help from the "date created" and "date modified" attributes to identify which libraries to delete.

But the names still show in the IDE... But it is something I can live with for now.

How to select specific form element in jQuery?

although it is invalid html but you can use selector context to limit your selector in your case it would be like :

$("input[name='name']" , "#form2").val("Hello World! ");

http://api.jquery.com/jquery/#selector-context

How to configure log4j to only keep log files for the last seven days?

My script based on @dogbane's answer

/etc/cron.daily/hbase

#!/bin/sh
find /var/log/hbase -type f -name "phoenix-hbase-server.log.[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]" -exec bzip2 {} ";"
find /var/log/hbase -type f -regex ".*.out.[0-9][0-9]?" -exec bzip2 {} ";"
find /var/log/hbase -type f -mtime +7 -name "*.bz2" -exec rm -f {} ";"

/etc/cron.daily/tomcat

#!/bin/sh
find /opt/tomcat/log/ -type f -mtime +1 -name "*.[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9].*log" -exec bzip2 {} ";"
find /opt/tomcat/log/ -type f -mtime +1 -name "*.[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9].txt" -exec bzip2 {} ";"
find /opt/tomcat/log/ -type f -mtime +7 -name "*.bz2" -exec rm -f {} ";"

because Tomcat rotate needs one day delay.

maven command line how to point to a specific settings.xml for a single command?

You can simply use:

mvn --settings YourOwnSettings.xml clean install

or

mvn -s YourOwnSettings.xml clean install

Can I bind an array to an IN() condition?

For me the sexier solution is to construct a dynamic associative array & use it

// A dirty array sent by user
$dirtyArray = ['Cecile', 'Gilles', 'Andre', 'Claude'];

// we construct an associative array like this
// [ ':name_0' => 'Cecile', ... , ':name_3' => 'Claude' ]
$params = array_combine(
    array_map(
        // construct param name according to array index
        function ($v) {return ":name_{$v}";},
        // get values of users
        array_keys($dirtyArray)
    ),
    $dirtyArray
);

// construct the query like `.. WHERE name IN ( :name_1, .. , :name_3 )`
$query = "SELECT * FROM user WHERE name IN( " . implode(",", array_keys($params)) . " )";
// here we go
$stmt  = $db->prepare($query);
$stmt->execute($params);

How to list all methods for an object in Ruby?

Suppose User has_many Posts:

u = User.first
u.posts.methods
u.posts.methods - Object.methods

Eventviewer eventid for lock and unlock

Security Settings -> Advanced Audit Policy -> System Audit -> Logon/Logoff -> Audit Other Logon/Off Events -> On Success

Enables the following:

4800 - workstation locked
4801 - workstation unlocked
4802 - screensaver invoke
4803 - screensaver dismissed

Windows 10 professional

Python Graph Library

I second zweiterlinde's suggestion to use python-graph. I've used it as the basis of a graph-based research project that I'm working on. The library is well written, stable, and has a good interface. The authors are also quick to respond to inquiries and reports.

How do I create a message box with "Yes", "No" choices and a DialogResult?

This simple code worked for me. I grabbed it from MSDN here:

https://social.msdn.microsoft.com/Forums/en-US/d1092a96-96b0-4ca4-b716-0c8e55e42ee9/how-can-i-manage-messagebox-result-?forum=Vsexpressvcs

if (System.Windows.Forms.MessageBox.Show
            ("Are you sure you want to add the audit?", "Add",
            System.Windows.Forms.MessageBoxButtons.YesNo, 
            System.Windows.Forms.MessageBoxIcon.Question)
            ==System.Windows.Forms.DialogResult.Yes)                
        // Do stuff after 'YES is clicked'
        else
        // DO stuff after 'NO is clicked'

Display Adobe pdf inside a div

may be you can do by using AJAX or jquery...
just send that file url on one page and then open like normally open pdf file in that page and use ajax.

1)so as soon as user will click on the button. then u call that function in which u above tast. So by this way there will be only one page and by that you can show as many pdf without refreshing page.

2) if u don't have many pdf and if u don't know then just upload that file on google docs and then just put the share link file....and then just use ajax or jquery.

i prefer jquery if u don't have use AJAX.

How to fix: /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

this problem can be solved by installing the latest libstdc++.

$ sudo add-apt-repository ppa:ubuntu-toolchain-r/test
$ sudo apt-get update
$ sudo apt-get install libstdc++6-7-dbg

write newline into a file

To write text (rather than raw bytes) to a file you should consider using FileWriter. You should also wrap it in a BufferedWriter which will then give you the newLine method.

To write each word on a new line, use String.split to break your text into an array of words.

So here's a simple test of your requirement:

public static void main(String[] args) throws Exception {
    String nodeValue = "i am mostafa";

    // you want to output to file
    // BufferedWriter writer = new BufferedWriter(new FileWriter(file3, true));
    // but let's print to console while debugging
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));

    String[] words = nodeValue.split(" ");
    for (String word: words) {
        writer.write(word);
        writer.newLine();
    }
    writer.close();
}

The output is:

i
am
mostafa

Best way to convert pdf files to tiff files

1) Install GhostScript

2) Install ImageMagick

3) Create "Convert-to-TIFF.bat" (Windows XP, Vista, 7) and use the following line:

for %%f in (%*) DO "C:\Program Files\ImageMagick-6.6.4-Q16\convert.exe" -density 300 -compress lzw %%f %%f.tiff

Dragging any number of single-page PDF files onto this file will convert them to compressed TIFFs, at 300 DPI.