Programs & Examples On #Pythoncard

PythonCard is a cross-platform GUI construction kit for building desktop applications using the Python language.

New to unit testing, how to write great tests?

For unit testing, I found both Test Driven (tests first, code second) and code first, test second to be extremely useful.

Instead of writing code, then writing test. Write code then look at what you THINK the code should be doing. Think about all the intended uses of it and then write a test for each. I find writing tests to be faster but more involved than the coding itself. The tests should test the intention. Also thinking about the intentions you wind up finding corner cases in the test writing phase. And of course while writing tests you might find one of the few uses causes a bug (something I often find, and I am very glad this bug did not corrupt data and go unchecked).

Yet testing is almost like coding twice. In fact I had applications where there was more test code (quantity) than application code. One example was a very complex state machine. I had to make sure that after adding more logic to it, the entire thing always worked on all previous use cases. And since those cases were quite hard to follow by looking at the code, I wound up having such a good test suite for this machine that I was confident that it would not break even after making changes, and the tests saved my ass a few times. And as users or testers were finding bugs with the flow or corner cases unaccounted for, guess what, added to tests and never happened again. This really gave users confidence in my work in addition to making the whole thing super stable. And when it had to be re-written for performance reasons, guess what, it worked as expected on all inputs thanks to the tests.

All the simple examples like function square(number) is great and all, and are probably bad candidates to spend lots of time testing. The ones that do important business logic, thats where the testing is important. Test the requirements. Don't just test the plumbing. If the requirements change then guess what, the tests must too.

Testing should not be literally testing that function foo invoked function bar 3 times. That is wrong. Check if the result and side-effects are correct, not the inner mechanics.

Dark theme in Netbeans 7 or 8

Netbeans 8

Tools -> Options -> Appearance (Look & Feel Tab)

(NetBeans -> Preferences -> Appearance (Look & Feel Tab) on OS X)

Netbeans 7.x

Tools -> Plugins -> Available -> Dark Look and Feel - Install this plugin.

Once this plugin is installed, restarting netbeans should automatically switch to Dark Metal.

There are 2 themes that comes with this plugin - Dark Metal & Dark Nimbus

In order to switch themes, use the below option :

Tools -> Options -> Miscellaneous -> Windows -> Preferred Look & Feel option

enter image description here

Uncaught Typeerror: cannot read property 'innerHTML' of null

run the code after your html structure in the body statement

    <html>
    <body>
    <p>asdasd</p>
    <p>asdasd</p>
    <p>asdasd</p>
    <script src="myfile.js"></script>
    </body>
    </html>

Testing if a site is vulnerable to Sql Injection

A login page isn't the only part of a database-driven website that interacts with the database.

Any user-editable input which is used to construct a database query is a potential entry point for a SQL injection attack. The attacker may not necessarily login to the site as an admin through this attack, but can do other things. They can change data, change server settings, etc. depending on the nature of the application's interaction with the database.

Appending a ' to an input is usually a pretty good test to see if it generates an error or otherwise produces unexpected behavior on the site. It's an indication that the user input is being used to build a raw query and the developer didn't expect a single quote, which changes the query structure.

Keep in mind that one page may be secure against SQL injection while another one may not. The login page, for example, may be hardened against such attacks. But a different page elsewhere in the site might be wide open. So, for example, if one wanted to login as an admin then one can use the SQL injection on that other page to change the admin password. Then return to the perfectly non-SQL-injectable login page and login as the admin.

how to set JAVA_OPTS for Tomcat in Windows?

This is because, the amount of memory you wish to assign for JVM is not available or may be you are assigning more than available memory. Try small size then u can see the difference.
Try:

set JAVA_OPTS=-Xms128m -Xmx512m -XX:PermSize=128m

How to create a list of objects?

I think what you're of doing here is using a structure containing your class instances. I don't know the syntax for naming structures in python, but in perl I could create a structure obj.id[x] where x is an incremented integer. Then, I could just refer back to the specific class instance I needed by referencing the struct numerically. Is this anything in the direction of what you're trying to do?

C++ -- expected primary-expression before ' '

Change

int wordLength = wordLengthFunction(string word);

to

int wordLength = wordLengthFunction(word);

Decorators with parameters?

This is a template for a function decorator that does not require () if no parameters are to be given:

import functools


def decorator(x_or_func=None, *decorator_args, **decorator_kws):
    def _decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kws):
            if 'x_or_func' not in locals() \
                    or callable(x_or_func) \
                    or x_or_func is None:
                x = ...  # <-- default `x` value
            else:
                x = x_or_func
            return func(*args, **kws)

        return wrapper

    return _decorator(x_or_func) if callable(x_or_func) else _decorator

an example of this is given below:

def multiplying(factor_or_func=None):
    def _decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            if 'factor_or_func' not in locals() \
                    or callable(factor_or_func) \
                    or factor_or_func is None:
                factor = 1
            else:
                factor = factor_or_func
            return factor * func(*args, **kwargs)
        return wrapper
    return _decorator(factor_or_func) if callable(factor_or_func) else _decorator


@multiplying
def summing(x): return sum(x)

print(summing(range(10)))
# 45


@multiplying()
def summing(x): return sum(x)

print(summing(range(10)))
# 45


@multiplying(10)
def summing(x): return sum(x)

print(summing(range(10)))
# 450

How to get date, month, year in jQuery UI datepicker?

what about that simple way)

$(document).ready ->
 $('#datepicker').datepicker( dateFormat: 'yy-mm-dd',  onSelect: (dateStr) ->
    alert dateStr # yy-mm-dd
    #OR
    alert $("#datepicker").val(); # yy-mm-dd

Add Favicon to Website

  1. This is not done in PHP. It's part of the <head> tags in a HTML page.
  2. That icon is called a favicon. According to Wikipedia:

    A favicon (short for favorites icon), also known as a shortcut icon, website icon, URL icon, or bookmark icon is a 16×16 or 32×32 pixel square icon associated with a particular website or webpage.

  3. Adding it is easy. Just add an .ico image file that is either 16x16 pixels or 32x32 pixels. Then, in the web pages, add <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"> to the <head> element.
  4. You can easily generate favicons here.

Accessing attributes from an AngularJS directive

See section Attributes from documentation on directives.

observing interpolated attributes: Use $observe to observe the value changes of attributes that contain interpolation (e.g. src="{{bar}}"). Not only is this very efficient but it's also the only way to easily get the actual value because during the linking phase the interpolation hasn't been evaluated yet and so the value is at this time set to undefined.

Bash Shell Script - Check for a flag and grab its value

You should read this getopts tutorial.

Example with -a switch that requires an argument :

#!/bin/bash

while getopts ":a:" opt; do
  case $opt in
    a)
      echo "-a was triggered, Parameter: $OPTARG" >&2
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument." >&2
      exit 1
      ;;
  esac
done

Like greybot said(getopt != getopts) :

The external command getopt(1) is never safe to use, unless you know it is GNU getopt, you call it in a GNU-specific way, and you ensure that GETOPT_COMPATIBLE is not in the environment. Use getopts (shell builtin) instead, or simply loop over the positional parameters.

Func vs. Action vs. Predicate

Func - When you want a delegate for a function that may or may not take parameters and returns a value. The most common example would be Select from LINQ:

var result = someCollection.Select( x => new { x.Name, x.Address });

Action - When you want a delegate for a function that may or may not take parameters and does not return a value. I use these often for anonymous event handlers:

button1.Click += (sender, e) => { /* Do Some Work */ }

Predicate - When you want a specialized version of a Func that evaluates a value against a set of criteria and returns a boolean result (true for a match, false otherwise). Again, these are used in LINQ quite frequently for things like Where:

var filteredResults = 
    someCollection.Where(x => x.someCriteriaHolder == someCriteria);

I just double checked and it turns out that LINQ doesn't use Predicates. Not sure why they made that decision...but theoretically it is still a situation where a Predicate would fit.

JavaScript array to CSV

If your data contains any newlines or commas, you will need to escape those first:

const escape = text =>
    text.replace(/\\/g, "\\\\")
        .replace(/\n/g, "\\n")
        .replace(/,/g, "\\,")

escaped_array = test_array.map(fields => fields.map(escape))

Then simply do:

csv = escaped_array.map(fields => fields.join(","))
                .join("\n")

If you want to make it downloadable in-browser:

dl = "data:text/csv;charset=utf-8," + csv
window.open(encodeURI(dl))

Create an empty list in python with certain size

varunl's currently accepted answer

 >>> l = [None] * 10
 >>> l
 [None, None, None, None, None, None, None, None, None, None]

Works well for non-reference types like numbers. Unfortunately if you want to create a list-of-lists you will run into referencing errors. Example in Python 2.7.6:

>>> a = [[]]*10
>>> a
[[], [], [], [], [], [], [], [], [], []]
>>> a[0].append(0)
>>> a
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]]
>>> 

As you can see, each element is pointing to the same list object. To get around this, you can create a method that will initialize each position to a different object reference.

def init_list_of_objects(size):
    list_of_objects = list()
    for i in range(0,size):
        list_of_objects.append( list() ) #different object reference each time
    return list_of_objects


>>> a = init_list_of_objects(10)
>>> a
[[], [], [], [], [], [], [], [], [], []]
>>> a[0].append(0)
>>> a
[[0], [], [], [], [], [], [], [], [], []]
>>> 

There is likely a default, built-in python way of doing this (instead of writing a function), but I'm not sure what it is. Would be happy to be corrected!

Edit: It's [ [] for _ in range(10)]

Example :

>>> [ [random.random() for _ in range(2) ] for _ in range(5)]
>>> [[0.7528051908943816, 0.4325669600055032], [0.510983236521753, 0.7789949902294716], [0.09475179523690558, 0.30216475640534635], [0.3996890132468158, 0.6374322093017013], [0.3374204010027543, 0.4514925173253973]]

iterate through a map in javascript

The callback to $.each() is passed the property name and the value, in that order. You're therefore trying to iterate over the property names in the inner call to $.each(). I think you want:

$.each(myMap, function (i, val) {
  $.each(val, function(innerKey, innerValue) {
    // ...
  });
});

In the inner loop, given an object like your map, the values are arrays. That's OK, but note that the "innerKey" values will all be numbers.

edit — Now once that's straightened out, here's the next problem:

    setTimeout(function () {

      // ...

    }, i * 6000);

The first time through that loop, "i" will be the string "partnr1". Thus, that multiplication attempt will result in a NaN. You can keep an external counter to keep track of the property count of the outer map:

var pcount = 1;
$.each(myMap, function(i, val) {
  $.each(val, function(innerKey, innerValue) {
    setTimeout(function() {
      // ...
    }, pcount++ * 6000);
  });
});

How to override maven property in command line?

See Introduction to the POM

finalName is created as:

<build>
    <finalName>${project.artifactId}-${project.version}</finalName>
</build>

One of the solutions is to add own property:

<properties>
    <finalName>${project.artifactId}-${project.version}</finalName>
</properties>
<build>
    <finalName>${finalName}</finalName>
 </build>

And now try:

mvn -DfinalName=build clean package

JavaFX - create custom button with image

A combination of previous 2 answers did the trick. Thanks. A new class which inherits from Button. Note: updateImages() should be called before showing the button.

import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;

public class ImageButton extends Button {

    public void updateImages(final Image selected, final Image unselected) {
        final ImageView iv = new ImageView(selected);
        this.getChildren().add(iv);

        iv.setOnMousePressed(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent evt) {
                iv.setImage(unselected);
            }
        });
        iv.setOnMouseReleased(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent evt) {
                iv.setImage(selected);
            }
        });

        super.setGraphic(iv);
    }
}

Add new column with foreign key constraint in one command

If you also need to add default values in case you already have some rows in the table then add DEFAULT val

ALTER TABLE one
ADD two_id int DEFAULT 123,
FOREIGN KEY(two_id) REFERENCES two(id);

openCV video saving in python

I also faced same problem but it worked when I used 'MJPG' instead of 'XVID'

I used

fourcc = cv2.VideoWriter_fourcc(*'MJPG')

instead of

fourcc = cv2.VideoWriter_fourcc(*'XVID')

Custom ImageView with drop shadow

My dirty solution:

private static Bitmap getDropShadow3(Bitmap bitmap) {

    if (bitmap==null) return null;
    int think = 6;
    int w = bitmap.getWidth();
    int h = bitmap.getHeight();

    int newW = w - (think);
    int newH = h - (think);

    Bitmap.Config conf = Bitmap.Config.ARGB_8888;
    Bitmap bmp = Bitmap.createBitmap(w, h, conf);
    Bitmap sbmp = Bitmap.createScaledBitmap(bitmap, newW, newH, false);

    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    Canvas c = new Canvas(bmp);

    // Right
    Shader rshader = new LinearGradient(newW, 0, w, 0, Color.GRAY, Color.LTGRAY, Shader.TileMode.CLAMP);
    paint.setShader(rshader);
    c.drawRect(newW, think, w, newH, paint);

    // Bottom
    Shader bshader = new LinearGradient(0, newH, 0, h, Color.GRAY, Color.LTGRAY, Shader.TileMode.CLAMP);
    paint.setShader(bshader);
    c.drawRect(think, newH, newW  , h, paint);

    //Corner
    Shader cchader = new LinearGradient(0, newH, 0, h, Color.LTGRAY, Color.LTGRAY, Shader.TileMode.CLAMP);
    paint.setShader(cchader);
    c.drawRect(newW, newH, w  , h, paint);


    c.drawBitmap(sbmp, 0, 0, null);

    return bmp;
}

result: enter image description here

Delete files older than 15 days using PowerShell

Another alternative (15. gets typed to [timespan] automatically):

ls -file | where { (get-date) - $_.creationtime -gt 15. } | Remove-Item -Verbose

Random character generator with a range of (A..Z, 0..9) and punctuation

Here is code for secure, easy, but a little bit more expensive session identifiers.

import java.security.SecureRandom;
import java.math.BigInteger;

public final class SessionIdentifierGenerator
{

  private SecureRandom random = new SecureRandom();

  public String nextSessionId()
  {
    return new BigInteger(130, random).toString(32);
  }

}

Copying files from server to local computer using SSH

that scp command must be issued on the local command-line, for putty the command is pscp.

C:\something> pscp [email protected]:/dir/of/file.txt \local\dir\

How can I return the difference between two lists?

You can use filter in the Java 8 Stream library

List<String> aList = List.of("l","e","t","'","s");
List<String> bList = List.of("g","o","e","s","t");

List<String> difference = aList.stream()
    .filter(aObject -> {
        return ! bList.contains(aObject);
      })
    .collect(Collectors.toList());

//more reduced: no curly braces, no return
List<String> difference2 = aList.stream()
    .filter(aObject -> ! bList.contains(aObject))
    .collect(Collectors.toList());

Result of System.out.println(difference);:

[e, t, s]

Detect Close windows event by jQuery

There is no specific event for capturing browser close event. But we can detect by the browser positions XY.

<script type="text/javascript">
$(document).ready(function() {
  $(document).mousemove(function(e) {
    if(e.pageY <= 5)
    {
        //this condition would occur when the user brings their cursor on address bar 
        //do something here 
    }
  });
});
</script>

Android 8.0: java.lang.IllegalStateException: Not allowed to start service Intent

I see a lot of responses that recommend just using a ForegroundService. In order to use a ForegroundService there has to be a notification associated with it. Users will see this notification. Depending on the situation, they may become annoyed with your app and uninstall it.

The easiest solution is to use the new Architecture Component called WorkManager. You can check out the documentation here: https://developer.android.com/topic/libraries/architecture/workmanager/

You just define your worker class that extends Worker.

public class CompressWorker extends Worker {

    public CompressWorker(
        @NonNull Context context,
        @NonNull WorkerParameters params) {
        super(context, params);
    }

    @Override
    public Worker.Result doWork() {

        // Do the work here--in this case, compress the stored images.
        // In this example no parameters are passed; the task is
        // assumed to be "compress the whole library."
        myCompress();

        // Indicate success or failure with your return value:
        return Result.SUCCESS;

        // (Returning RETRY tells WorkManager to try this task again
        // later; FAILURE says not to try again.)
    }
}

Then you schedule when you want to run it.

    OneTimeWorkRequest compressionWork = 
        new OneTimeWorkRequest.Builder(CompressWorker.class)
            .build();
    WorkManager.getInstance().enqueue(compressionWork);

Easy! There are a lot of ways you can configure workers. It supports recurring jobs and you can even do complex stuff like chaining if you need it. Hope this helps.

Converting List<Integer> to List<String>

I just wanted to chime in with an object oriented solution to the problem.

If you model domain objects, then the solution is in the domain objects. The domain here is a List of integers for which we want string values.

The easiest way would be to not convert the list at all.

That being said, in order to convert without converting, change the original list of Integer to List of Value, where Value looks something like this...

class Value {
    Integer value;
    public Integer getInt()
    {
       return value;
    }
    public String getString()
    {
       return String.valueOf(value);
    }
}

This will be faster and take up less memory than copying the List.

Good Luck!

Can I connect to SQL Server using Windows Authentication from Java EE webapp?

I was having issue with connecting to MS SQL 2005 using Windows Authentication. I was able to solve the issue with help from this and other forums. Here is what I did:

  1. Install the JTDS driver
  2. Do not use the "domain= " property in the jdbc:jtds:://[:][/][;=[;...]] string
  3. Install the ntlmauth.dll in c:\windows\system32 directory (registration of the dll was not required) on the web server machine.
  4. Change the logon identity for the Apache Tomcat service to a domain User with access to the SQL database server (it was not necessary for the user to have access to the dbo.master).

My environment: Windows XP clinet hosting Apache Tomcat 6 with MS SQL 2005 backend on Windows 2003

Adding a default value in dropdownlist after binding with database

The solution provided by Justin should work. To be sure making use of SelectedIndex property will also help.

ddlColor.DataSource = from p in db.ProductTypes
                      where p.ProductID == pID
                      orderby p.Color
                      select new { p.Color };

ddlColor.DataTextField = "Color";
ddlColor.DataBind();

ddlColor.Items.Insert(0, new ListItem("Select Color", ""); 
ddlColor.SelectedIndex = 0;

avrdude: stk500v2_ReceiveMessage(): timeout

I was running this code from Arduino setup , got same error resolve after changing
serial port to COM13
GO TO Option
tool>> serial port>> COM132

What's the PowerShell syntax for multiple values in a switch statement?

Supports entering y|ye|yes and case insensitive.

switch -regex ($someString.ToLower()) {
        "^y(es?)?$" {
            "You entered Yes." 
        }
        default { "You entered No." }
}

what are the .map files used for in Bootstrap 3.x?

Have you ever found yourself wishing you could keep your client-side code readable and more importantly debuggable even after you've combined and minified it, without impacting performance? Well now you can through the magic of source maps.

This article explains Source Maps using a practical approach.

Properties order in Margin

Just because @MartinCapodici 's comment is awesome I write here as an answer to give visibility.

All clockwise:

  • WPF start West (left->top->right->bottom)
  • Netscape (ie CSS) start North (top->right->bottom->left)

Downloading video from YouTube

You can check out libvideo. It's much more up-to-date than YoutubeExtractor, and is fast and clean to use.

ORA-28000: the account is locked error getting frequently

Solution 01

Account Unlock by using below query :

SQL> select USERNAME,ACCOUNT_STATUS from dba_users where username='ABCD_DEV';    
USERNAME             ACCOUNT_STATUS
-------------------- --------------------------------
ABCD_DEV       LOCKED

SQL> alter user ABCD_DEV account unlock;    
User altered.

SQL> select USERNAME,ACCOUNT_STATUS from dba_users where username='ABCD_DEV';    
USERNAME             ACCOUNT_STATUS
-------------------- --------------------------------
ABCD_DEV       OPEN

Solution 02

Check PASSWORD_LIFE_TIME parameter by using below query :

SELECT resource_name, limit FROM dba_profiles WHERE profile = 'DEFAULT' AND resource_type = 'PASSWORD';

RESOURCE_NAME                    LIMIT
-------------------------------- ------------------------------
FAILED_LOGIN_ATTEMPTS            10
PASSWORD_LIFE_TIME               10
PASSWORD_REUSE_TIME              10
PASSWORD_REUSE_MAX               UNLIMITED
PASSWORD_VERIFY_FUNCTION         NULL
PASSWORD_LOCK_TIME               1
PASSWORD_GRACE_TIME              7
INACTIVE_ACCOUNT_TIME            UNLIMITED

Change the parameter using below query

ALTER PROFILE DEFAULT LIMIT PASSWORD_LIFE_TIME UNLIMITED;

size of struct in C

Aligning to 6 bytes is not weird, because it is aligning to addresses multiple to 4.

So basically you have 34 bytes in your structure and the next structure should be placed on the address, that is multiple to 4. The closest value after 34 is 36. And this padding area counts into the size of the structure.

Specify JDK for Maven to use

I say you setup the JAVA_HOME environment variable like Pascal is saying: In Cygwin if you use bash as your shell should be:

export JAVA_HOME=/cygdrive/c/pathtothejdk

It never harms to also prepend the java bin directory path to the PATH environment variable with:

export PATH=${JAVA_HOME}/bin:${PATH}

Also add maven-enforce-plugin to make sure the right JDK is used. This is a good practice for your pom.

<build>
 <plugins>
   <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-enforcer-plugin</artifactId>
      <executions>
        <execution>
          <id>enforce-versions</id>
          <goals>
            <goal>enforce</goal>
          </goals>
          <configuration>
            <rules>
              <requireJavaVersion>
                <version>1.6</version>
              </requireJavaVersion>
            </rules>
          </configuration>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>

Please, see Maven Enforcer plugin – Usage.

How can I compare time in SQL Server?

Your compare will work, but it will be slow because the dates are converted to a string for each row. To efficiently compare two time parts, try:

declare @first datetime
set @first = '2009-04-30 19:47:16.123'
declare @second datetime
set @second = '2009-04-10 19:47:16.123'

select (cast(@first as float) - floor(cast(@first as float))) -
       (cast(@second as float) - floor(cast(@second as float)))
       as Difference

Long explanation: a date in SQL server is stored as a floating point number. The digits before the decimal point represent the date. The digits after the decimal point represent the time.

So here's an example date:

declare @mydate datetime
set @mydate = '2009-04-30 19:47:16.123'

Let's convert it to a float:

declare @myfloat float
set @myfloat = cast(@mydate as float)
select @myfloat
-- Shows 39931,8244921682

Now take the part after the digit, i.e. the time:

set @myfloat = @myfloat - floor(@myfloat) 
select @myfloat
-- Shows 0,824492168212601

Convert it back to a datetime:

declare @mytime datetime
set @mytime = convert(datetime,@myfloat)
select @mytime
-- Shows 1900-01-01 19:47:16.123

The 1900-01-01 is just the "zero" date; you can display the time part with convert, specifying for example format 108, which is just the time:

select convert(varchar(32),@mytime,108)
-- Shows 19:47:16

Conversions between datetime and float are pretty fast, because they're basically stored in the same way.

How to check if multiple array keys exists

Surprisingly array_keys_exist doesn't exist?! In the interim that leaves some space to figure out a single line expression for this common task. I'm thinking of a shell script or another small program.

Note: each of the following solutions use concise […] array declaration syntax available in php 5.4+

array_diff + array_keys

if (0 === count(array_diff(['story', 'message', '…'], array_keys($source)))) {
  // all keys found
} else {
  // not all
}

(hat tip to Kim Stacks)

This approach is the most brief I've found. array_diff() returns an array of items present in argument 1 not present in argument2. Therefore an empty array indicates all keys were found. In php 5.5 you could simplify 0 === count(…) to be simply empty(…).

array_reduce + unset

if (0 === count(array_reduce(array_keys($source), 
    function($in, $key){ unset($in[array_search($key, $in)]); return $in; }, 
    ['story', 'message', '…'])))
{
  // all keys found
} else {
  // not all
}

Harder to read, easy to change. array_reduce() uses a callback to iterate over an array to arrive at a value. By feeding the keys we're interested in the $initial value of $in and then removing keys found in source we can expect to end with 0 elements if all keys were found.

The construction is easy to modify since the keys we're interested in fit nicely on the bottom line.

array_filter & in_array

if (2 === count(array_filter(array_keys($source), function($key) { 
        return in_array($key, ['story', 'message']); }
    )))
{
  // all keys found
} else {
  // not all
}

Simpler to write than the array_reduce solution but slightly tricker to edit. array_filter is also an iterative callback that allows you to create a filtered array by returning true (copy item to new array) or false (don't copy) in the callback. The gotchya is that you must change 2 to the number of items you expect.

This can be made more durable but verge's on preposterous readability:

$find = ['story', 'message'];
if (count($find) === count(array_filter(array_keys($source), function($key) use ($find) { return in_array($key, $find); })))
{
  // all keys found
} else {
  // not all
}

How can I get the baseurl of site?

Try this:

string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority + 
    Request.ApplicationPath.TrimEnd('/') + "/";

Intellij idea subversion checkout error: `Cannot run program "svn"`

I solved this by uncheking the "Use command-line client" option from Subversion settings.

This works with version 1.6 and 1.7 only. See @Vic's answer for SVN version 1.8.

How to implement and do OCR in a C# project?

If anyone is looking into this, I've been trying different options and the following approach yields very good results. The following are the steps to get a working example:

  1. Add .NET Wrapper for tesseract to your project. It can be added via NuGet package Install-Package Tesseract(https://github.com/charlesw/tesseract).
  2. Go to the Downloads section of the official Tesseract project (https://code.google.com/p/tesseract-ocr/ EDIT: It's now located here: https://github.com/tesseract-ocr/langdata).
  3. Download the preferred language data, example: tesseract-ocr-3.02.eng.tar.gz English language data for Tesseract 3.02.
  4. Create tessdata directory in your project and place the language data files in it.
  5. Go to Properties of the newly added files and set them to copy on build.
  6. Add a reference to System.Drawing.
  7. From .NET Wrapper repository, in the Samples directory copy the sample phototest.tif file into your project directory and set it to copy on build.
  8. Create the following two files in your project (just to get started):

Program.cs

using System;
using Tesseract;
using System.Diagnostics;

namespace ConsoleApplication
{
    class Program
    {
        public static void Main(string[] args)
        {
            var testImagePath = "./phototest.tif";
            if (args.Length > 0)
            {
                testImagePath = args[0];
            }

            try
            {
                var logger = new FormattedConsoleLogger();
                var resultPrinter = new ResultPrinter(logger);
                using (var engine = new TesseractEngine(@"./tessdata", "eng", EngineMode.Default))
                {
                    using (var img = Pix.LoadFromFile(testImagePath))
                    {
                        using (logger.Begin("Process image"))
                        {
                            var i = 1;
                            using (var page = engine.Process(img))
                            {
                                var text = page.GetText();
                                logger.Log("Text: {0}", text);
                                logger.Log("Mean confidence: {0}", page.GetMeanConfidence());

                                using (var iter = page.GetIterator())
                                {
                                    iter.Begin();
                                    do
                                    {
                                        if (i % 2 == 0)
                                        {
                                            using (logger.Begin("Line {0}", i))
                                            {
                                                do
                                                {
                                                    using (logger.Begin("Word Iteration"))
                                                    {
                                                        if (iter.IsAtBeginningOf(PageIteratorLevel.Block))
                                                        {
                                                            logger.Log("New block");
                                                        }
                                                        if (iter.IsAtBeginningOf(PageIteratorLevel.Para))
                                                        {
                                                            logger.Log("New paragraph");
                                                        }
                                                        if (iter.IsAtBeginningOf(PageIteratorLevel.TextLine))
                                                        {
                                                            logger.Log("New line");
                                                        }
                                                        logger.Log("word: " + iter.GetText(PageIteratorLevel.Word));
                                                    }
                                                } while (iter.Next(PageIteratorLevel.TextLine, PageIteratorLevel.Word));
                                            }
                                        }
                                        i++;
                                    } while (iter.Next(PageIteratorLevel.Para, PageIteratorLevel.TextLine));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Trace.TraceError(e.ToString());
                Console.WriteLine("Unexpected Error: " + e.Message);
                Console.WriteLine("Details: ");
                Console.WriteLine(e.ToString());
            }
            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }



        private class ResultPrinter
        {
            readonly FormattedConsoleLogger logger;

            public ResultPrinter(FormattedConsoleLogger logger)
            {
                this.logger = logger;
            }

            public void Print(ResultIterator iter)
            {
                logger.Log("Is beginning of block: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Block));
                logger.Log("Is beginning of para: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Para));
                logger.Log("Is beginning of text line: {0}", iter.IsAtBeginningOf(PageIteratorLevel.TextLine));
                logger.Log("Is beginning of word: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Word));
                logger.Log("Is beginning of symbol: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Symbol));

                logger.Log("Block text: \"{0}\"", iter.GetText(PageIteratorLevel.Block));
                logger.Log("Para text: \"{0}\"", iter.GetText(PageIteratorLevel.Para));
                logger.Log("TextLine text: \"{0}\"", iter.GetText(PageIteratorLevel.TextLine));
                logger.Log("Word text: \"{0}\"", iter.GetText(PageIteratorLevel.Word));
                logger.Log("Symbol text: \"{0}\"", iter.GetText(PageIteratorLevel.Symbol));
            }
        }
    }
}

FormattedConsoleLogger.cs

using System;
using System.Collections.Generic;
using System.Text;
using Tesseract;

namespace ConsoleApplication
{
    public class FormattedConsoleLogger
    {
        const string Tab = "    ";
        private class Scope : DisposableBase
        {
            private int indentLevel;
            private string indent;
            private FormattedConsoleLogger container;

            public Scope(FormattedConsoleLogger container, int indentLevel)
            {
                this.container = container;
                this.indentLevel = indentLevel;
                StringBuilder indent = new StringBuilder();
                for (int i = 0; i < indentLevel; i++)
                {
                    indent.Append(Tab);
                }
                this.indent = indent.ToString();
            }

            public void Log(string format, object[] args)
            {
                var message = String.Format(format, args);
                StringBuilder indentedMessage = new StringBuilder(message.Length + indent.Length * 10);
                int i = 0;
                bool isNewLine = true;
                while (i < message.Length)
                {
                    if (message.Length > i && message[i] == '\r' && message[i + 1] == '\n')
                    {
                        indentedMessage.AppendLine();
                        isNewLine = true;
                        i += 2;
                    }
                    else if (message[i] == '\r' || message[i] == '\n')
                    {
                        indentedMessage.AppendLine();
                        isNewLine = true;
                        i++;
                    }
                    else
                    {
                        if (isNewLine)
                        {
                            indentedMessage.Append(indent);
                            isNewLine = false;
                        }
                        indentedMessage.Append(message[i]);
                        i++;
                    }
                }

                Console.WriteLine(indentedMessage.ToString());

            }

            public Scope Begin()
            {
                return new Scope(container, indentLevel + 1);
            }

            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    var scope = container.scopes.Pop();
                    if (scope != this)
                    {
                        throw new InvalidOperationException("Format scope removed out of order.");
                    }
                }
            }
        }

        private Stack<Scope> scopes = new Stack<Scope>();

        public IDisposable Begin(string title = "", params object[] args)
        {
            Log(title, args);
            Scope scope;
            if (scopes.Count == 0)
            {
                scope = new Scope(this, 1);
            }
            else
            {
                scope = ActiveScope.Begin();
            }
            scopes.Push(scope);
            return scope;
        }

        public void Log(string format, params object[] args)
        {
            if (scopes.Count > 0)
            {
                ActiveScope.Log(format, args);
            }
            else
            {
                Console.WriteLine(String.Format(format, args));
            }
        }

        private Scope ActiveScope
        {
            get
            {
                var top = scopes.Peek();
                if (top == null) throw new InvalidOperationException("No current scope");
                return top;
            }
        }
    }
}

PHPExcel Make first row bold

Try this for range of cells:

$from = "A1"; // or any value
$to = "B5"; // or any value
$objPHPExcel->getActiveSheet()->getStyle("$from:$to")->getFont()->setBold( true );

or single cell

$cell_name = "A1";
$objPHPExcel->getActiveSheet()->getStyle( $cell_name )->getFont()->setBold( true );

hope that helps

How do I install Python libraries in wheel format?

Simple steps to install python in Ubuntu:

  1. Download Python

    $ cd /usr/src 
    $ wget  https://www.python.org/ftp/python/3.6.0/Python-3.6.0.tgz
    
  2. Extract the downloaded package

    $ sudo tar xzf Python-3.6.0.tgz
    
  3. Compile Python source

    $ cd Python-3.6.0
    $ sudo ./configure
    $ sudo make altinstall 
    

    Note make altinstall is used to prevent replacing the default python binary file /usr/bin/python.

  4. check the python version

    # python3.6 -V
    

Git diff against a stash

@Magne's answer is the only one to (very late) date that answers the most flexible/useful interpretation of the question, but its a fair bit more complicated than necessary. Rather than committing and resetting, just stash your working copy, compare, then unstash.

git stash save "temp"
git diff stash@{0} stash@{1}
git stash pop

That shows you the differences between the top of the stash stack and your working folder by temporarily making your working folder changes become the top of the stash stack (stash@{0}), moving the original top down one (stash@{1}) then comparing using the original top in the 'new set' position so you see the changes that would result from applying it on top of your current work.

"But what if I don't have any current work?" Then you are in the normal boring case. Just use @Amber's answer

git stash show

or @czerasz's answer

git diff stash@{0}

or admit that stashing and unstashing is fast and easy anyway, just unstash the changes and inspect them. If you don't want them at the moment throw them (the current index/working folder changes) away. In full that's

git stash apply
git diff
git reset
git checkout

Get the _id of inserted document in Mongo database in NodeJS

You could use async functions to get _id field automatically without manipulating data object:

async function save() {
  const data = {
    name: "John"
  }

  await db.collection('users').insertOne(data)

  return data
}

Returns data:

{
  _id: '5dbff150b407cc129ab571ca',
  name: 'John'
}

File path to resource in our war/WEB-INF folder?

There's a couple ways of doing this. As long as the WAR file is expanded (a set of files instead of one .war file), you can use this API:

ServletContext context = getContext();
String fullPath = context.getRealPath("/WEB-INF/test/foo.txt");

http://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/ServletContext.html#getRealPath(java.lang.String)

That will get you the full system path to the resource you are looking for. However, that won't work if the Servlet Container never expands the WAR file (like Tomcat). What will work is using the ServletContext's getResource methods.

ServletContext context = getContext();
URL resourceUrl = context.getResource("/WEB-INF/test/foo.txt");

or alternatively if you just want the input stream:

InputStream resourceContent = context.getResourceAsStream("/WEB-INF/test/foo.txt");

http://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/ServletContext.html#getResource(java.lang.String)

The latter approach will work no matter what Servlet Container you use and where the application is installed. The former approach will only work if the WAR file is unzipped before deployment.

EDIT: The getContext() method is obviously something you would have to implement. JSP pages make it available as the context field. In a servlet you get it from your ServletConfig which is passed into the servlet's init() method. If you store it at that time, you can get your ServletContext any time you want after that.

Changing the page title with Jquery

$(document).prop('title', 'test');

This is simply a JQuery wrapper for:

document.title = 'test';

To add a > periodically you can do:

function changeTitle() {
    var title = $(document).prop('title'); 
    if (title.indexOf('>>>') == -1) {
        setTimeout(changeTitle, 3000);  
        $(document).prop('title', '>'+title);
    }
}

changeTitle();

Difference between numpy dot() and Python 3.5+ matrix multiplication @

My experience with MATMUL and DOT

I was constantly getting "ValueError: Shape of passed values is (200, 1), indices imply (200, 3)" when trying to use MATMUL. I wanted a quick workaround and found DOT to deliver the same functionality. I don't get any error using DOT. I get the correct answer

with MATMUL

X.shape
>>>(200, 3)

type(X)

>>>pandas.core.frame.DataFrame

w

>>>array([0.37454012, 0.95071431, 0.73199394])

YY = np.matmul(X,w)

>>>  ValueError: Shape of passed values is (200, 1), indices imply (200, 3)"

with DOT

YY = np.dot(X,w)
# no error message
YY
>>>array([ 2.59206877,  1.06842193,  2.18533396,  2.11366346,  0.28505879, …

YY.shape

>>> (200, )

How to check if a file exists in Go?

basicly


package main

import (
    "fmt"
    "os"
)

func fileExists(path string) bool {
    _, err := os.Stat(path)
    return !os.IsNotExist(err)
}

func main() {

    var file string = "foo.txt"
    exist := fileExists(file)
    
    if exist {
        fmt.Println("file exist")
    } else {

        fmt.Println("file not exists")
    }

}

run example

other way

with os.Open

package main

import (
    "fmt"
    "os"
)

func fileExists(path string) bool {
    _, err := os.Open(path) // For read access.
    return err == nil

}

func main() {

    fmt.Println(fileExists("d4d.txt"))

}


run it

What's the best way to limit text length of EditText in Android

EditText editText = new EditText(this);
int maxLength = 3;    
editText.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLength)});

INSERT VALUES WHERE NOT EXISTS

You could do this using an IF statement:

IF NOT EXISTS 
    (   SELECT  1
        FROM    tblSoftwareTitles 
        WHERE   Softwarename = @SoftwareName 
        AND     SoftwareSystemType = @Softwaretype
    )
    BEGIN
        INSERT tblSoftwareTitles (SoftwareName, SoftwareSystemType) 
        VALUES (@SoftwareName, @SoftwareType) 
    END;

You could do it without IF using SELECT

INSERT  tblSoftwareTitles (SoftwareName, SoftwareSystemType) 
SELECT  @SoftwareName,@SoftwareType
WHERE   NOT EXISTS 
        (   SELECT  1
            FROM    tblSoftwareTitles 
            WHERE   Softwarename = @SoftwareName 
            AND     SoftwareSystemType = @Softwaretype
        );

Both methods are susceptible to a race condition, so while I would still use one of the above to insert, but you can safeguard duplicate inserts with a unique constraint:

CREATE UNIQUE NONCLUSTERED INDEX UQ_tblSoftwareTitles_Softwarename_SoftwareSystemType
    ON tblSoftwareTitles (SoftwareName, SoftwareSystemType);

Example on SQL-Fiddle


ADDENDUM

In SQL Server 2008 or later you can use MERGE with HOLDLOCK to remove the chance of a race condition (which is still not a substitute for a unique constraint).

MERGE tblSoftwareTitles WITH (HOLDLOCK) AS t
USING (VALUES (@SoftwareName, @SoftwareType)) AS s (SoftwareName, SoftwareSystemType) 
    ON s.Softwarename = t.SoftwareName 
    AND s.SoftwareSystemType = t.SoftwareSystemType
WHEN NOT MATCHED BY TARGET THEN 
    INSERT (SoftwareName, SoftwareSystemType) 
    VALUES (s.SoftwareName, s.SoftwareSystemType);

Example of Merge on SQL Fiddle

How do I get the function name inside a function in PHP?

The accurate way is to use the __FUNCTION__ predefined magic constant.

Example:

class Test {
    function MethodA(){
        echo __FUNCTION__;
    }
}

Result: MethodA.

how to set cursor style to pointer for links without hrefs

Use CSS cursor: pointer if I remember correctly.

Either in your CSS file:

.link_cursor
{
    cursor: pointer;
}

Then just add the following HTML to any elements you want to have the link cursor: class="link_cursor" (the preferred method.)

Or use inline CSS:

<a style="cursor: pointer;">

Finding the indices of matching elements in list in Python

if you're doing a lot of this kind of thing you should consider using numpy.

In [56]: import random, numpy

In [57]: lst = numpy.array([random.uniform(0, 5) for _ in range(1000)]) # example list

In [58]: a, b = 1, 3

In [59]: numpy.flatnonzero((lst > a) & (lst < b))[:10]
Out[59]: array([ 0, 12, 13, 15, 18, 19, 23, 24, 26, 29])

In response to Seanny123's question, I used this timing code:

import numpy, timeit, random

a, b = 1, 3

lst = numpy.array([random.uniform(0, 5) for _ in range(1000)])

def numpy_way():
    numpy.flatnonzero((lst > 1) & (lst < 3))[:10]

def list_comprehension():
    [e for e in lst if 1 < e < 3][:10]

print timeit.timeit(numpy_way)
print timeit.timeit(list_comprehension)

The numpy version is over 60 times faster.

Why is using onClick() in HTML a bad practice?

If you are using jQuery then:

HTML:

 <a id="openMap" href="/map/">link</a>

JS:

$(document).ready(function() {
    $("#openMap").click(function(){
        popup('/map/', 300, 300, 'map');
        return false;
    });
});

This has the benefit of still working without JS, or if the user middle clicks the link.

It also means that I could handle generic popups by rewriting again to:

HTML:

 <a class="popup" href="/map/">link</a>

JS:

$(document).ready(function() {
    $(".popup").click(function(){
        popup($(this).attr("href"), 300, 300, 'map');
        return false;
    });
});

This would let you add a popup to any link by just giving it the popup class.

This idea could be extended even further like so:

HTML:

 <a class="popup" data-width="300" data-height="300" href="/map/">link</a>

JS:

$(document).ready(function() {
    $(".popup").click(function(){
        popup($(this).attr("href"), $(this).data('width'), $(this).data('height'), 'map');
        return false;
    });
});

I can now use the same bit of code for lots of popups on my whole site without having to write loads of onclick stuff! Yay for reusability!

It also means that if later on I decide that popups are bad practice, (which they are!) and that I want to replace them with a lightbox style modal window, I can change:

popup($(this).attr("href"), $(this).data('width'), $(this).data('height'), 'map');

to

myAmazingModalWindow($(this).attr("href"), $(this).data('width'), $(this).data('height'), 'map');

and all my popups on my whole site are now working totally differently. I could even do feature detection to decide what to do on a popup, or store a users preference to allow them or not. With the inline onclick, this requires a huge copy and pasting effort.

could not extract ResultSet in hibernate

For MySql take in mind that it's not a good idea to write camelcase. For example if the schema is like that:

CREATE TABLE IF NOT EXISTS `task`(
    `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    `teaching_hours` DECIMAL(5,2) DEFAULT NULL,
    `isActive` BOOLEAN DEFAULT FALSE,
    `is_validated` BOOLEAN DEFAULT FALSE,
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

You must be very careful cause isActive column will translate to isactive. So in your Entity class is should be like this:

 @Basic
 @Column(name = "isactive", nullable = true)
 public boolean isActive() {
     return isActive;
 }
 public void setActive(boolean active) {
     isActive = active;
 }

That was my problem at least that got me your error

This has nothing to do with MySql which is case insensitive, but rather is a naming strategy that spring will use to translate your tables. For more refer to this post

What is Gradle in Android Studio?

The Android Studio build system is based on Gradle, and the Android Gradle plugin adds several features that are specific to building Android apps. Although the Android plugin is typically updated in lock-step with Android Studio, the plugin (and the rest of the Gradle system) can run independent of Android Studio and be updated separately.

For more details you can refer:

  1. https://developer.android.com/studio/releases/gradle-plugin?gclid=Cj0KCQiAlZH_BRCgARIsAAZHSBndmJC_myjKnuCBZbe7u9nyzMjbFGES2SVvedq4nxyqdqJnqq0xxlAaAvGMEALw_wcB&gclsrc=aw.ds
  2. https://gradle.org/

How do I set Java's min and max heap size through environment variables?

You can't do it using environment variables directly. You need to use the set of "non standard" options that are passed to the java command. Run: java -X for details. The options you're looking for are -Xmx and -Xms (this is "initial" heap size, so probably what you're looking for.)

Some products like Ant or Tomcat might come with a batch script that looks for the JAVA_OPTS environment variable, but it's not part of the Java runtime. If you are using one of those products, you may be able to set the variable like:

set JAVA_OPTS="-Xms128m -Xmx256m"  

You can also take this approach with your own command line like:

set JAVA_OPTS="-Xms128m -Xmx256m"  
java ${JAVA_OPTS} MyClass

How can I convert a dictionary into a list of tuples?

d = {'John':5, 'Alex':10, 'Richard': 7}
list = []
for i in d:
   k = (i,d[i])
   list.append(k)

print list

Break statement in javascript array map method

That's not possible using the built-in Array.prototype.map. However, you could use a simple for-loop instead, if you do not intend to map any values:

var hasValueLessThanTen = false;
for (var i = 0; i < myArray.length; i++) {
  if (myArray[i] < 10) {
    hasValueLessThanTen = true;
    break;
  }
}

Or, as suggested by @RobW, use Array.prototype.some to test if there exists at least one element that is less than 10. It will stop looping when some element that matches your function is found:

var hasValueLessThanTen = myArray.some(function (val) { 
  return val < 10;
});

Check if value is zero or not null in python

The simpler way:

h = ''
i = None
j = 0
k = 1
print h or i or j or k

Will print 1

print k or j or i or h

Will print 1

Read a text file line by line in Qt

QFile inputFile(QString("/path/to/file"));
inputFile.open(QIODevice::ReadOnly);
if (!inputFile.isOpen())
    return;

QTextStream stream(&inputFile);
QString line = stream.readLine();
while (!line.isNull()) {
    /* process information */

    line = stream.readLine();
};

How to make primary key as autoincrement for Room Persistence lib

add @PrimaryKey(autoGenerate = true)

@Entity
public class User {

    @PrimaryKey(autoGenerate = true)
    private int id;

    @ColumnInfo(name = "full_name")
    private String name;

    @ColumnInfo(name = "phone")
    private String phone;

    public User(){
    }

    //type-1
    public User(String name, String phone) {
        this.name = name;
        this.phone = phone;
    }

    //type-2
    public User(int id, String name, String phone) {
        this.id = id;
        this.name = name;
        this.phone = phone;
    }

}

while storing data

 //type-1
 db.userDao().InsertAll(new User(sName,sPhone)); 

 //type-2
 db.userDao().InsertAll(new User(0,sName,sPhone)); 

type-1

If you are not passing value for primary key, by default it will 0 or null.

type-2

Put null or zero for the id while creating object (my case user object)

If the field type is long or int (or its TypeConverter converts it to a long or int), Insert methods treat 0 as not-set while inserting the item.

If the field's type is Integer or Long (Object) (or its TypeConverter converts it to an Integer or a Long), Insert methods treat null as not-set while inserting the item.

Difference between a Seq and a List in Scala

In Java terms, Scala's Seq would be Java's List, and Scala's List would be Java's LinkedList.

Note that Seq is a trait, which is equivalent to Java's interface, but with the equivalent of up-and-coming defender methods. Scala's List is an abstract class that is extended by Nil and ::, which are the concrete implementations of List.

So, where Java's List is an interface, Scala's List is an implementation.

Beyond that, Scala's List is immutable, which is not the case of LinkedList. In fact, Java has no equivalent to immutable collections (the read only thing only guarantees the new object cannot be changed, but you still can change the old one, and, therefore, the "read only" one).

Scala's List is highly optimized by compiler and libraries, and it's a fundamental data type in functional programming. However, it has limitations and it's inadequate for parallel programming. These days, Vector is a better choice than List, but habit is hard to break.

Seq is a good generalization for sequences, so if you program to interfaces, you should use that. Note that there are actually three of them: collection.Seq, collection.mutable.Seq and collection.immutable.Seq, and it is the latter one that is the "default" imported into scope.

There's also GenSeq and ParSeq. The latter methods run in parallel where possible, while the former is parent to both Seq and ParSeq, being a suitable generalization for when parallelism of a code doesn't matter. They are both relatively newly introduced, so people doesn't use them much yet.

Convert Datetime column from UTC to local time in select statement

Well if you store the data as UTC date in the database you can do something as simple as

select 
 [MyUtcDate] + getdate() - getutcdate()
from [dbo].[mytable]

this was it's always local from the point of the server and you are not fumbling with AT TIME ZONE 'your time zone name', if your database get moved to another time zone like a client installation a hard coded time zone might bite you.

Extracting extension from filename in Python

You can use a split on a filename:

f_extns = filename.split(".")
print ("The extension of the file is : " + repr(f_extns[-1]))

This does not require additional library

Adding css class through aspx code behind

Syntax:

controlName.CssClass="CSS Class Name";

Example:

txtBank.CssClass = "csError";

Django request get parameters

You may also use:

request.POST.get('section','') # => [39]
request.POST.get('MAINS','') # => [137] 
request.GET.get('section','') # => [39]
request.GET.get('MAINS','') # => [137]

Using this ensures that you don't get an error. If the POST/GET data with any key is not defined then instead of raising an exception the fallback value (second argument of .get() will be used).

Convert data.frame column format from character to factor

You could use dplyr::mutate_if() to convert all character columns or dplyr::mutate_at() for select named character columns to factors:

library(dplyr)

# all character columns to factor:
df <- mutate_if(df, is.character, as.factor)

# select character columns 'char1', 'char2', etc. to factor:
df <- mutate_at(df, vars(char1, char2), as.factor)

In Java, can you modify a List while iterating through it?

Java 8's stream() interface provides a great way to update a list in place.

To safely update items in the list, use map():

List<String> letters = new ArrayList<>();

// add stuff to list

letters = letters.stream().map(x -> "D").collect(Collectors.toList());

To safely remove items in place, use filter():


letters.stream().filter(x -> !x.equals("A")).collect(Collectors.toList());

How to enable native resolution for apps on iPhone 6 and 6 Plus?

You can add a launch screen file that appears to work for multiple screen sizes. I just added the MainStoryboard as a launch screen file and that stopped the app from scaling. I think I will need to add a permanent launch screen later, but that got the native resolution up and working quickly. In Xcode, go to your target, general and add the launch screen file there.

Launch Screen File

ActionLink htmlAttributes

Replace the desired hyphen with an underscore; it will automatically be rendered as a hyphen:

@Html.ActionLink("Edit", "edit", "markets",
    new { id = 1 },
    new {@class="ui-btn-right", data_icon="gear"})

becomes:

<form action="markets/Edit/1" class="ui-btn-right" data-icon="gear" .../>

Aggregate function in SQL WHERE-Clause

Another solution is to Move the aggregate fuction to Scalar User Defined Function

Create Your Function:

CREATE FUNCTION getTotalSalesByProduct(@ProductName VARCHAR(500))
RETURNS INT
AS
BEGIN

DECLARE @TotalAmount INT

SET @TotalAmount = (select SUM(SaleAmount) FROM Sales where Product=@ProductName)

RETURN @TotalAmount

END

Use Function in Where Clause

SELECT ProductName, SUM(SaleAmount) AS TotalSales
FROM Sales
WHERE dbo.getTotalSalesByProduct(ProductName)  > 1000
GROUP BY Product

References:

1. 2.

Hope helps someone.

Display the current time and date in an Android application

String currentDateandTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
Toast.makeText(getApplicationContext(), currentDateandTime, Toast.LENGTH_SHORT).show();

Server.UrlEncode vs. HttpUtility.UrlEncode

I had significant headaches with these methods before, I recommend you avoid any variant of UrlEncode, and instead use Uri.EscapeDataString - at least that one has a comprehensible behavior.

Let's see...

HttpUtility.UrlEncode(" ") == "+" //breaks ASP.NET when used in paths, non-
                                  //standard, undocumented.
Uri.EscapeUriString("a?b=e") == "a?b=e" // makes sense, but rarely what you
                                        // want, since you still need to
                                        // escape special characters yourself

But my personal favorite has got to be HttpUtility.UrlPathEncode - this thing is really incomprehensible. It encodes:

  • " " ==> "%20"
  • "100% true" ==> "100%%20true" (ok, your url is broken now)
  • "test A.aspx#anchor B" ==> "test%20A.aspx#anchor%20B"
  • "test A.aspx?hmm#anchor B" ==> "test%20A.aspx?hmm#anchor B" (note the difference with the previous escape sequence!)

It also has the lovelily specific MSDN documentation "Encodes the path portion of a URL string for reliable HTTP transmission from the Web server to a client." - without actually explaining what it does. You are less likely to shoot yourself in the foot with an Uzi...

In short, stick to Uri.EscapeDataString.

How do I finish the merge after resolving my merge conflicts?

How do I finish the merge after resolving my merge conflicts?

With Git 2.12 (Q1 2017), you will have the more natural command:

git merge --continue

See commit c7d227d (15 Dec 2016) by Jeff King (peff).
See commit 042e290, commit c261a87, commit 367ff69 (14 Dec 2016) by Chris Packham (cpackham).
(Merged by Junio C Hamano -- gitster -- in commit 05f6e1b, 27 Dec 2016)

See 2.12 release notes.

merge: add '--continue' option as a synonym for 'git commit'

Teach 'git merge' the --continue option which allows 'continuing' a merge by completing it.
The traditional way of completing a merge after resolving conflicts is to use 'git commit'.
Now with commands like 'git rebase' and 'git cherry-pick' having a '--continue' option adding such an option to 'git merge' presents a consistent UI.

JavaScript isset() equivalent

Reference to SOURCE

    module.exports = function isset () {
  //  discuss at: http://locutus.io/php/isset/
  // original by: Kevin van Zonneveld (http://kvz.io)
  // improved by: FremyCompany
  // improved by: Onno Marsman (https://twitter.com/onnomarsman)
  // improved by: Rafal Kukawski (http://blog.kukawski.pl)
  //   example 1: isset( undefined, true)
  //   returns 1: false
  //   example 2: isset( 'Kevin van Zonneveld' )
  //   returns 2: true

  var a = arguments
  var l = a.length
  var i = 0
  var undef

  if (l === 0) {
    throw new Error('Empty isset')
  }

  while (i !== l) {
    if (a[i] === undef || a[i] === null) {
      return false
    }
    i++
  }

  return true
}

phpjs.org is mostly retired in favor of locutus Here is the new link http://locutus.io/php/var/isset

Saving any file to in the database, just convert it to a byte array?

Confirming I was able to use the answer posted by MadBoy and edited by Otiel on both MS SQL Server 2012 and 2014 in addition to the versions previously listed using varbinary(MAX) columns.

If you are wondering why you cannot "Filestream" (noted in a separate answer) as a datatype in the SQL Server table designer or why you cannot set a column's datatype to "Filestream" using T-SQL, it is because FILESTREAM is a storage attribute of the varbinary(MAX) datatype. It is not a datatype on its own.

See these articles on setting up and enabling FILESTREAM on a database: https://msdn.microsoft.com/en-us/library/cc645923(v=sql.120).aspx

http://www.kodyaz.com/t-sql/default-filestream-filegroup-is-not-available-in-database.aspx

Once configured, a filestream enabled varbinary(max) column can be added as so:

ALTER TABLE TableName

ADD ColumnName varbinary(max) FILESTREAM NULL

GO

What are the best PHP input sanitizing functions?

Database Input - How to prevent SQL Injection

  1. Check to make sure data of type integer, for example, is valid by ensuring it actually is an integer
    • In the case of non-strings you need to ensure that the data actually is the correct type
    • In the case of strings you need to make sure the string is surrounded by quotes in the query (obviously, otherwise it wouldn't even work)
  2. Enter the value into the database while avoiding SQL injection (mysql_real_escape_string or parameterized queries)
  3. When Retrieving the value from the database be sure to avoid Cross Site Scripting attacks by making sure HTML can't be injected into the page (htmlspecialchars)

You need to escape user input before inserting or updating it into the database. Here is an older way to do it. You would want to use parameterized queries now (probably from the PDO class).

$mysql['username'] = mysql_real_escape_string($clean['username']);
$sql = "SELECT * FROM userlist WHERE username = '{$mysql['username']}'";
$result = mysql_query($sql);

Output from database - How to prevent XSS (Cross Site Scripting)

Use htmlspecialchars() only when outputting data from the database. The same applies for HTML Purifier. Example:

$html['username'] = htmlspecialchars($clean['username'])

And Finally... what you requested

I must point out that if you use PDO objects with parameterized queries (the proper way to do it) then there really is no easy way to achieve this easily. But if you use the old 'mysql' way then this is what you would need.

function filterThis($string) {
    return mysql_real_escape_string($string);
}

Python - Locating the position of a regex match in a string?

You could use .find("is"), it would return position of "is" in the string

or use .start() from re

>>> re.search("is", String).start()
2

Actually its match "is" from "This"

If you need to match per word, you should use \b before and after "is", \b is the word boundary.

>>> re.search(r"\bis\b", String).start()
5
>>>

for more info about python regular expressions, docs here

SQL not a single-group group function

Well the problem simply-put is that the SUM(TIME) for a specific SSN on your query is a single value, so it's objecting to MAX as it makes no sense (The maximum of a single value is meaningless).

Not sure what SQL database server you're using but I suspect you want a query more like this (Written with a MSSQL background - may need some translating to the sql server you're using):

SELECT TOP 1 SSN, SUM(TIME)
FROM downloads
GROUP BY SSN
ORDER BY 2 DESC

This will give you the SSN with the highest total time and the total time for it.

Edit - If you have multiple with an equal time and want them all you would use:

SELECT
SSN, SUM(TIME)
FROM downloads
GROUP BY SSN
HAVING SUM(TIME)=(SELECT MAX(SUM(TIME)) FROM downloads GROUP BY SSN))

Get Android Phone Model programmatically

String deviceName = android.os.Build.MODEL; // returns model name 

String deviceManufacturer = android.os.Build.MANUFACTURER; // returns manufacturer

Use Following method to get model & manufacturer programmatically

  public String getDeviceName() {
        String manufacturer = Build.MANUFACTURER;
        String model = Build.MODEL;
        if (model.toLowerCase().startsWith(manufacturer.toLowerCase())) {
            return capitalize(model);
        } else {
            return capitalize(manufacturer) + " " + model;
        }
    }


    private String capitalize(String s) {
    if (s == null || s.length() == 0) {
        return "";
    }
    char first = s.charAt(0);
    if (Character.isUpperCase(first)) {
        return s;
    } else {
        return Character.toUpperCase(first) + s.substring(1);
    }

Combining two sorted lists in Python

Long story short, unless len(l1 + l2) ~ 1000000 use:

L = l1 + l2
L.sort()

merge vs. sort comparison

Description of the figure and source code can be found here.

The figure was generated by the following command:

$ python make-figures.py --nsublists 2 --maxn=0x100000 -s merge_funcs.merge_26 -s merge_funcs.sort_builtin

python modify item in list, save back in list

For Python 3:

ListOfStrings = []
ListOfStrings.append('foo')
ListOfStrings.append('oof')
for idx, item in enumerate(ListOfStrings):
if 'foo' in item:
    ListOfStrings[idx] = "bar"

When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?

Use dynamic_cast for converting pointers/references within an inheritance hierarchy.

Use static_cast for ordinary type conversions.

Use reinterpret_cast for low-level reinterpreting of bit patterns. Use with extreme caution.

Use const_cast for casting away const/volatile. Avoid this unless you are stuck using a const-incorrect API.

How to Implement DOM Data Binding in JavaScript

Bind any html input

<input id="element-to-bind" type="text">

define two functions:

function bindValue(objectToBind) {
var elemToBind = document.getElementById(objectToBind.id)    
elemToBind.addEventListener("change", function() {
    objectToBind.value = this.value;
})
}

function proxify(id) { 
var handler = {
    set: function(target, key, value, receiver) {
        target[key] = value;
        document.getElementById(target.id).value = value;
        return Reflect.set(target, key, value);
    },
}
return new Proxy({id: id}, handler);
}

use the functions:

var myObject = proxify('element-to-bind')
bindValue(myObject);

How do I revert to a previous package in Anaconda?

I know it was not available at the time, but now you could also use Anaconda navigator to install a specific version of packages in the environments tab.

How to check if an email address exists without sending an email?

Other answers here discuss the various problems with trying to do this. I thought I'd show how you might try this in case you wanted to learn by doing it yourself.

You can connect to an mail server via telnet to ask whether an email address exists. Here's an example of testing an email address for stackoverflow.com:

C:\>nslookup -q=mx stackoverflow.com
Non-authoritative answer:
stackoverflow.com       MX preference = 40, mail exchanger = STACKOVERFLOW.COM.S9B2.PSMTP.com
stackoverflow.com       MX preference = 10, mail exchanger = STACKOVERFLOW.COM.S9A1.PSMTP.com
stackoverflow.com       MX preference = 20, mail exchanger = STACKOVERFLOW.COM.S9A2.PSMTP.com
stackoverflow.com       MX preference = 30, mail exchanger = STACKOVERFLOW.COM.S9B1.PSMTP.com

C:\>telnet STACKOVERFLOW.COM.S9A1.PSMTP.com 25
220 Postini ESMTP 213 y6_35_0c4 ready.  CA Business and Professions Code Section 17538.45 forbids use of this system for unsolicited electronic mail advertisements.

helo hi
250 Postini says hello back

mail from: <[email protected]>
250 Ok

rcpt to: <[email protected]>
550-5.1.1 The email account that you tried to reach does not exist. Please try
550-5.1.1 double-checking the recipient's email address for typos or
550-5.1.1 unnecessary spaces. Learn more at
550 5.1.1 http://mail.google.com/support/bin/answer.py?answer=6596 w41si3198459wfd.71

Lines prefixed with numeric codes are responses from the SMTP server. I added some blank lines to make it more readable.

Many mail servers will not return this information as a means to prevent against email address harvesting by spammers, so you cannot rely on this technique. However you may have some success at cleaning out some obviously bad email addresses by detecting invalid mail servers, or having recipient addresses rejected as above.

Note too that mail servers may blacklist you if you make too many requests of them.


In PHP I believe you can use fsockopen, fwrite and fread to perform the above steps programmatically:

$smtp_server = fsockopen("STACKOVERFLOW.COM.S9A1.PSMTP.com", 25, $errno, $errstr, 30);
fwrite($smtp_server, "helo hi\r\n");
fwrite($smtp_server, "mail from: <[email protected]>\r\n");
fwrite($smtp_server, "rcpt to: <[email protected]>\r\n");

AJAX cross domain call

You can use the technology CORS to configure both servers (the server where the Javascript is running and the external API server)

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

p.s.: the answer https://stackoverflow.com/a/37384641/6505594 is also suggesting this approach, and it's opening the external API server to everyone else to call it.

How are SSL certificate server names resolved/Can I add alternative names using keytool?

How host name verification should be done is defined in RFC 6125, which is quite recent and generalises the practice to all protocols, and replaces RFC 2818, which was specific to HTTPS. (I'm not even sure Java 7 uses RFC 6125, which might be too recent for this.)

From RFC 2818 (Section 3.1):

If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.

[...]

In some cases, the URI is specified as an IP address rather than a hostname. In this case, the iPAddress subjectAltName must be present in the certificate and must exactly match the IP in the URI.

Essentially, the specific problem you have comes from the fact that you're using IP addresses in your CN and not a host name. Some browsers might work because not all tools follow this specification strictly, in particular because "most specific" in RFC 2818 isn't clearly defined (see discussions in RFC 6215).

If you're using keytool, as of Java 7, keytool has an option to include a Subject Alternative Name (see the table in the documentation for -ext): you could use -ext san=dns:www.example.com or -ext san=ip:10.0.0.1.

EDIT:

You can request a SAN in OpenSSL by changing openssl.cnf (it will pick the copy in the current directory if you don't want to edit the global configuration, as far as I remember, or you can choose an explicit location using the OPENSSL_CONF environment variable).

Set the following options (find the appropriate sections within brackets first):

[req]
req_extensions = v3_req

[ v3_req ]
subjectAltName=IP:10.0.0.1
# or subjectAltName=DNS:www.example.com

There's also a nice trick to use an environment variable for this (rather in than fixing it in a configuration file) here: http://www.crsr.net/Notes/SSL.html

Set max-height on inner div so scroll bars appear, but not on parent div

If you make

overflow: hidden in the outer div and overflow-y: scroll in the inner div it will work.

http://jsfiddle.net/C8MuZ/11/

How do I run Python code from Sublime Text 2?

I solved this problem :

> Preferences –> Browse Packages –> Default 

Open the exec.py file, near line 41-42, the code should look like this :

for k, v in proc_env.iteritems():
    proc_env[k] = os.path.expandvars(v).encode(sys.getfilesystemencoding())

then delete it or edit it as :

try:    
    for k, v in proc_env.iteritems():
        proc_env[k] = os.path.expandvars(v).encode(sys.getfilesystemencoding())
except:
    print 'foobar'

Can I create a One-Time-Use Function in a Script or Stored Procedure?

In scripts you have more options and a better shot at rational decomposition. Look into SQLCMD mode (Query Menu -> SQLCMD mode), specifically the :setvar and :r commands.

Within a stored procedure your options are very limited. You can't create define a function directly with the body of a procedure. The best you can do is something like this, with dynamic SQL:

create proc DoStuff
as begin

  declare @sql nvarchar(max)

  /*
  define function here, within a string
  note the underscore prefix, a good convention for user-defined temporary objects
  */
  set @sql = '
    create function dbo._object_name_twopart (@object_id int)
    returns nvarchar(517) as
    begin
      return 
        quotename(object_schema_name(@object_id))+N''.''+
        quotename(object_name(@object_id))
    end
  '

  /*
  create the function by executing the string, with a conditional object drop upfront
  */
  if object_id('dbo._object_name_twopart') is not null drop function _object_name_twopart
  exec (@sql)

  /*
  use the function in a query
  */
  select object_id, dbo._object_name_twopart(object_id) 
  from sys.objects
  where type = 'U'

  /*
  clean up
  */
  drop function _object_name_twopart

end
go

This approximates a global temporary function, if such a thing existed. It's still visible to other users. You could append the @@SPID of your connection to uniqueify the name, but that would then require the rest of the procedure to use dynamic SQL too.

Modulo operator with negative values

a % b

in c++ default:

(-7/3) => -2
-2 * 3 => -6
so a%b => -1

(7/-3) => -2
-2 * -3 => 6
so a%b => 1

in python:

-7 % 3 => 2
7 % -3 => -2

in c++ to python:

(b + (a%b)) % b

Oracle 11g SQL to get unique values in one column of a multi-column query

Eric Petroelje almost has it right:

SELECT * FROM TableA
WHERE ROWID IN ( SELECT MAX(ROWID) FROM TableA GROUP BY Language )

Note: using ROWID (row unique id), not ROWNUM (which gives the row number within the result set)

How to show all privileges from a user in oracle?

Another useful resource:

http://psoug.org/reference/roles.html

  • DBA_SYS_PRIVS
  • DBA_TAB_PRIVS
  • DBA_ROLE_PRIVS

Could not reserve enough space for object heap to start JVM

According to this post this error message means:

Heap size is larger than your computer's physical memory.

Edit: Heap is not the only memory that is reserved, I suppose. At least there are other JVM settings like PermGenSpace that ask for the memory. With heap size 128M and a PermGenSpace of 64M you already fill the space available.

Why not downsize other memory settings to free up space for the heap?

How can git be installed on CENTOS 5.5?

From source? From the repos? The easiest way is to use the repos: sudo yum install git should do it. It may first be necessary to set up an additional repo such as EPEL first if git is not provided by the main repos.

If you want to install from source, you can try these instructions. If you have yum-utils installed it's actually easier than that, too**:

sudo yum build-dep git
wget http://kernel.org/pub/software/scm/git/<latest-git-source>.tar.gz
tar -xvjf <latest-git>.tar.gz
cd <git>
make (possibly a ./configure before this)
sudo make install

**Substitute the portions enclosed in <> with the paths you need. Exact procedure may vary slightly as I have not compiled git from source, personally (there may be a configure script, for example). If you have no idea what I'm talking about, then you may want to just install from the repo as per my first suggestion.

did you specify the right host or port? error on Kubernetes

I was getting an error when running

sudo kubectl get pods
The connection to the server localhost:8080 was refused - did you specify the right host or port?

Finally for my environment this command parameter works

sudo kubectl --kubeconfig /etc/kubernetes/admin.conf get pods

when executing kubectl as non root.

Disable cross domain web security in Firefox

Best Firefox Addon to disable CORS as of September 2016: https://github.com/fredericlb/Force-CORS/releases

You can even configure it by Referrers (Website).

Get value when selected ng-option changes

Best practise is to create an object (always use a . in ng-model)

In your controller:

var myObj: {
     ngModelValue: null
};

and in your template:

<select 
    ng-model="myObj.ngModelValue" 
    ng-options="o.id as o.name for o in options">
</select>

Now you can just watch

myObj.ngModelValue

or you can use the ng-change directive like so:

<select 
    ng-model="myObj.ngModelValue" 
    ng-options="o.id as o.name for o in options"
    ng-change="myChangeCallback()">
</select>

The egghead.io video "The Dot" has a really good overview, as does this very popular stack overflow question: What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

/usr/bin/codesign failed with exit code 1

Another reason, Check your Developer account is connected with xCode

enter image description here

How to indent/format a selection of code in Visual Studio Code with Ctrl + Shift + F

This should be able to set to whatever keybindings you want for indent/outdent here:

Menu FilePreferencesKeyboard Shortcuts

editor.action.indentLines

editor.action.outdentLines

How do I build a graphical user interface in C++?

There are plenty of free portable GUI libraries, each with its own strengths and weaknesses:

Especially Qt has nice tutorials and tools which help you getting started. Enjoy!

Note, however, that you should avoid platform specific functionality such as the Win32 API or MFC. That ties you unnecessarily on a specific platform with almost no benefits.

Where can I set path to make.exe on Windows?

here I'm providing solution to setup terraform enviroment variable in windows to beginners.

  1. Download the terraform package from portal either 32/64 bit version.
  2. make a folder in C drive in program files if its 32 bit package you have to create folder inside on programs(x86) folder or else inside programs(64 bit) folder.
  3. Extract a downloaded file in this location or copy terraform.exe file into this folder. copy this path location like C:\Programfile\terraform\
  4. Then got to Control Panel -> System -> System settings -> Environment Variables

Open system variables, select the path > edit > new > place the terraform.exe file location like > C:\Programfile\terraform\

and Save it.

  1. Open new terminal and now check the terraform.

How to count the number of observations in R like Stata command count

You can also use the filter function from the dplyr package which returns rows with matching conditions.

> library(dplyr)

> nrow(filter(aaa, sex == 1 & group1 == 2))
[1] 3
> nrow(filter(aaa, sex == 1 & group2 == "A"))
[1] 2

using extern template (C++11)

You should only use extern template to force the compiler to not instantiate a template when you know that it will be instantiated somewhere else. It is used to reduce compile time and object file size.

For example:

// header.h

template<typename T>
void ReallyBigFunction()
{
    // Body
}

// source1.cpp

#include "header.h"
void something1()
{
    ReallyBigFunction<int>();
}

// source2.cpp

#include "header.h"
void something2()
{
    ReallyBigFunction<int>();
}

This will result in the following object files:

source1.o
    void something1()
    void ReallyBigFunction<int>()    // Compiled first time

source2.o
    void something2()
    void ReallyBigFunction<int>()    // Compiled second time

If both files are linked together, one void ReallyBigFunction<int>() will be discarded, resulting in wasted compile time and object file size.

To not waste compile time and object file size, there is an extern keyword which makes the compiler not compile a template function. You should use this if and only if you know it is used in the same binary somewhere else.

Changing source2.cpp to:

// source2.cpp

#include "header.h"
extern template void ReallyBigFunction<int>();
void something2()
{
    ReallyBigFunction<int>();
}

Will result in the following object files:

source1.o
    void something1()
    void ReallyBigFunction<int>() // compiled just one time

source2.o
    void something2()
    // No ReallyBigFunction<int> here because of the extern

When both of these will be linked together, the second object file will just use the symbol from the first object file. No need for discard and no wasted compile time and object file size.

This should only be used within a project, like in times when you use a template like vector<int> multiple times, you should use extern in all but one source file.

This also applies to classes and function as one, and even template member functions.

Why doesn't TFS get latest get the latest?

Most of the issues I've seen with developers complaining that Get Latest doesn't do what they expect stem from the fact that they're performing a Get Latest from Solution Explorer rather than from Source Control Explorer. Solution Explorer only gets the files that are part of the solution and ignores anything that may be required by files within the solution, and therefore part of source control, whereas Source Control explorer compares your local workspace against the repository on the server to determine which files are needed.

overlay opaque div over youtube iframe

Note that the wmode=transparent fix only works if it's first so

http://www.youtube.com/embed/K3j9taoTd0E?wmode=transparent&rel=0

Not

http://www.youtube.com/embed/K3j9taoTd0E?rel=0&wmode=transparent

how to print a string to console in c++

All you have to do is add:

#include <string>
using namespace std;

at the top. (BTW I know this was posted in 2013 but I just wanted to answer)

align right in a table cell with CSS

Use

text-align: right

The text-align CSS property describes how inline content like text is aligned in its parent block element. text-align does not control the alignment of block elements itself, only their inline content.

See

text-align

<td class='alnright'>text to be aligned to right</td>

<style>
    .alnright { text-align: right; }
</style>

Remove composer

During the installation you got a message Composer successfully installed to: ... this indicates where Composer was installed. But you might also search for the file composer.phar on your system.

Then simply:

  1. Delete the file composer.phar.
  2. Delete the Cache Folder:
    • Linux: /home/<user>/.composer
    • Windows: C:\Users\<username>\AppData\Roaming\Composer

That's it.

Python regex findall

you can replace your pattern with

regex = ur"\[P\]([\w\s]+)\[\/P\]"

Android: android.content.res.Resources$NotFoundException: String resource ID #0x5

Just wanted to point out another reason this error can be thrown is if you defined a string resource for one translation of your app but did not provide a default string resource.

Example of the Issue:

As you can see below, I had a string resource for a Spanish string "get_started". It can still be referenced in code, but if the phone is not in Spanish it will have no resource to load and crash when calling getString().

values-es/strings.xml

<string name="get_started">SIGUIENTE</string>

Reference to resource

textView.setText(getString(R.string.get_started)

Logcat:

06-11 11:46:37.835    7007-7007/? E/AndroidRuntime? FATAL EXCEPTION: main
Process: com.app.test PID: 7007
android.content.res.Resources$NotFoundException: String resource ID #0x7f0700fd
        at android.content.res.Resources.getText(Resources.java:299)
        at android.content.res.Resources.getString(Resources.java:385)
        at com.juvomobileinc.tigousa.ui.signin.SignInFragment$4.onClick(SignInFragment.java:188)
        at android.view.View.performClick(View.java:4780)
        at android.view.View$PerformClick.run(View.java:19866)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5254)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Solution to the Issue

Preventing this is quite simple, just make sure that you always have a default string resource in values/strings.xml so that if the phone is in another language it will always have a resource to fall back to.

values/strings.xml

<string name="get_started">Get Started</string>

values-en/strings.xml

<string name="get_started">Get Started</string>

values-es/strings.xml

<string name="get_started">Siguiente</string>

values-de/strings.xml

<string name="get_started">Ioslegen</string>

MySQL Select all columns from one table and some from another table

Using alias for referencing the tables to get the columns from different tables after joining them.

Select tb1.*, tb2.col1, tb2.col2 from table1 tb1 JOIN table2 tb2 on tb1.Id = tb2.Id

Call function with setInterval in jQuery?

To write the best code, you "should" use the latter approach, with a function reference:

var refreshId = setInterval(function() {}, 5000);

or

function test() {}
var refreshId = setInterval(test, 5000);

but your approach of

function test() {}
var refreshId = setInterval("test()", 5000);

is basically valid, too (as long as test() is global).

Note that there is no such thing really as "in jQuery". You're still writing the Javascript language; you're just using some pre-made functions that are the jQuery library.

mysql is not recognised as an internal or external command,operable program or batch

In my case, I resolved it by adding this path C:\xampp\mysql\bin to system variables path and then restarted pash/cmd.

Note: Click me if you don't know how to set the path and system variables.

How to exclude a directory from ant fileset, based on directories contents

This is possible by using "**" pattern as following.

<exclude name="maindir/**/incomplete.flag"/>

the above 'exclude' will exclude all directories completely which contains incomplete.flag file.

javascript remove "disabled" attribute from html input

Set the element's disabled property to false:

document.getElementById('my-input-id').disabled = false;

If you're using jQuery, the equivalent would be:

$('#my-input-id').prop('disabled', false);

For several input fields, you may access them by class instead:

var inputs = document.getElementsByClassName('my-input-class');
for(var i = 0; i < inputs.length; i++) {
    inputs[i].disabled = false;
}

Where document could be replaced with a form, for instance, to find only the elements inside that form. You could also use getElementsByTagName('input') to get all input elements. In your for iteration, you'd then have to check that inputs[i].type == 'text'.

How do I get the calling method name and type using reflection?

Technically, you can use StackTrace, but this is very slow and will not give you the answers you expect a lot of the time. This is because during release builds optimizations can occur that will remove certain method calls. Hence you can't be sure in release whether stacktrace is "correct" or not.

Really, there isn't any foolproof or fast way of doing this in C#. You should really be asking yourself why you need this and how you can architect your application, so you can do what you want without knowing which method called it.

What is a regex to match ONLY an empty string?

Wow, ya'll are overthinking it. It's as simple as the following. Besides, many of those answers aren't understood by the RE2 dialect used by C and golang.

^$

Range of values in C Int and Long 32 - 64 bits

In fact, unsigned int on most modern processors (ARM, Intel/AMD, Alpha, SPARC, Itanium ,PowerPC) will have a range of 0 to 2^32 - 1 which is 4,294,967,295 = 0xffffffff because int (both signed and unsigned) will be 32 bits long and the largest one is as stated.

(unsigned short will have maximal value 2^16 - 1 = 65,535 )

(unsigned) long long int will have a length of 64 bits (long int will be enough under most 64 bit Linuxes, etc, but the standard promises 64 bits for long long int). Hence these have the range 0 to 2^64 - 1 = 18446744073709551615

Unable to load DLL 'SQLite.Interop.dll'

In short

To get this to work also with NCrunch I had to add the Interop.dll versions provided with the NuGet package as additional files in NCrunch configuration.

My case

I had a C# solution with one project directly depending on SQLite (a helper library) and a unit test project that used this helper library. I had installed System.Data.SQLite.Core version 1.0.97.0 as a NuGet package.

In my case the workaround provided by Marin got it working in Visual Studio and in CI as well. However this would still provide errors in NCrunch.

In NCrunch configuration I added the following path in "Additional files to include" under the unit test projects settings:

..\packages\System.Data.SQLite.Core.1.0.97.0\build\net45\**.dll

How to filter by IP address in Wireshark?

You can also limit the filter to only part of the ip address.

E.G. To filter 123.*.*.* you can use ip.addr == 123.0.0.0/8. Similar effects can be achieved with /16 and /24.

See WireShark man pages (filters) and look for Classless InterDomain Routing (CIDR) notation.

... the number after the slash represents the number of bits used to represent the network.

DATEDIFF function in Oracle

Just subtract the two dates:

select date '2000-01-02' - date '2000-01-01' as dateDiff
from dual;

The result will be the difference in days.

More details are in the manual:
https://docs.oracle.com/cd/E11882_01/server.112/e41084/sql_elements001.htm#i48042

TypeError: can't use a string pattern on a bytes-like object in re.findall()

The problem is that your regex is a string, but html is bytes:

>>> type(html)
<class 'bytes'>

Since python doesn't know how those bytes are encoded, it throws an exception when you try to use a string regex on them.

You can either decode the bytes to a string:

html = html.decode('ISO-8859-1')  # encoding may vary!
title = re.findall(pattern, html)  # no more error

Or use a bytes regex:

regex = rb'<title>(,+?)</title>'
#        ^

In this particular context, you can get the encoding from the response headers:

with urllib.request.urlopen(url) as response:
    encoding = response.info().get_param('charset', 'utf8')
    html = response.read().decode(encoding)

See the urlopen documentation for more details.

go to character in vim

:goto 21490 will take you to the 21490th byte in the buffer.

Run Command Line & Command From VBS

The problem is on this line:

oShell.run "cmd.exe /C copy "S:Claims\Sound.wav" "C:\WINDOWS\Media\Sound.wav"

Your first quote next to "S:Claims" ends the string; you need to escape the quotes around your files with a second quote, like this:

oShell.run "cmd.exe /C copy ""S:\Claims\Sound.wav"" ""C:\WINDOWS\Media\Sound.wav"" "

You also have a typo in S:Claims\Sound.wav, should be S:\Claims\Sound.wav.

I also assume the apostrophe before Dim oShell and after Set oShell = Nothing are typos as well.

Redirect pages in JSP?

Extending @oopbase's answer with return; statement.

Let's consider a use case of traditional authentication system where we store login information into the session. On each page we check for active session like,

/* Some Import Statements here. */

if(null == session || !session.getAttribute("is_login").equals("1")) {
    response.sendRedirect("http://domain.com/login");
}

// ....

session.getAttribute("user_id");

// ....
/* Some More JSP+Java+HTML code here */

It looks fine at first glance however; It has one issue. If your server has expired session due to time limit and user is trying to access the page he might get error if you have not written your code in try..catch block or handled if(null != session.getAttribute("attr_name")) everytime.

So by putting a return; statement I stopped further execution and forced to redirect page to certain location.

if(null == session || !session.getAttribute("is_login").equals("1")) {
    response.sendRedirect("http://domain.com/login");
    return;
}

Note that Use of redirection may vary based on the requirements. Nowadays people don't use such authentication system. (Modern approach - Token Based Authentication) It's just an simple example to understand where and how to place redirection(s).

Printing prime numbers from 1 through 100

The book seems to be "C++ for Engineers and Scientists" written by Gary Bronson (googled it).
Is this a possible answer? IMHO it's surprising.

I had to read the question (from the book) a few times. My interpretation:
For each number N: 2 <= N < 100 check whether it's prime.
How? For each divisor D: 2 <= D < sqrt(N) ,
if D divides N, N is not prime, if D > sqrt(N), N is prime.

Give it a try:

N = 2, sqrt(2) ˜ 1.41, D = 2, 2 < 1.41 ?  no 2 > 1.41 ? yes 2 is prime.  
N = 3, sqrt(3) ˜ 1.73, D = 2, 2 < 1.73 ?  no 2 > 1.73 ? yes 3 is prime.  
N = 4, sqrt(4) = 2.00, D = 2, 2 < 2.00 ?  no 2 > 2.00 ?  no 4 is not prime.  
N = 5, sqrt(5) ˜ 2.24, D = 2, 2 < 2.24 ? yes 5 % 2 > 0? yes  
                       D = 3, 3 < 2.24 ?  no 3 > 2.24 ? yes 5 is prime.    
N = 6, sqrt(6) ˜ 2.45, D = 2, 2 < 2.45 ? yes 6 % 2 = 0  2 > 2.45 ? no 6 is not prime.

As far as I can see, that's how the primes should be found,
not with a sieve (much, much faster),
but with: the answer is in the question! Surprising?

Speed? primes < 400,000 : less than 10 seconds (on my watch, a rolex, I bought it on the market, the seller said it was a real one, a real one for the price of two baguettes, with 12 real diamonds as well).
Let's count the primes (I'm not going to show code ;) : 664579 primes < 10,000,000 : 5 seconds.

#include "stdafx.h"
#include <math.h>
#include <iostream>
using namespace std;
int main()
{
    double rt;
    for (int d = 2, n = 2; n < 100; d = 2, n++)
    {
        for (rt = sqrt(n); d < rt; d++)
            if (n % d == 0) break;
        if (d > rt) cout << n << " ";
    }
    getchar();  // 25 primes :-)
}

Deleted an earlier answer with (like other answers) a prime-sieve.
Hopefully I get my next "Necromancer" badge soon.

I asked the author: In your book: "C++ for E&S" is an exercise about prime numbers,[xrcs]...[/xrcs]. Seven years ago it was asked at: SO/q/5200879
A few days ago I gave an answer: SO/a/49199435
Do you think it is a reasonable solution, or perhaps the solution.

He replied: Peter, I never really have a specific solution in mind when I am making up the exercises,
so I can’t say I had your exact solution in mind. The joy of C++ is that one can come up with really creative solutions and great code, as, on first glance, it looks like you have done.
Thanks for sending it!
Dr. Bronson

I went to https://youtu.be/1175axY2Vvw

PS. A sieve: https://pastebin.com/JMdTxbeJ

How to output a comma delimited list in jinja python template?

And using the joiner from http://jinja.pocoo.org/docs/dev/templates/#joiner

{% set comma = joiner(",") %}
{% for user in userlist %}
    {{ comma() }}<a href="/profile/{{ user }}/">{{ user }}</a>
{% endfor %}  

It's made for this exact purpose. Normally a join or a check of forloop.last would suffice for a single list, but for multiple groups of things it's useful.

A more complex example on why you would use it.

{% set pipe = joiner("|") %}
{% if categories %} {{ pipe() }}
    Categories: {{ categories|join(", ") }}
{% endif %}
{% if author %} {{ pipe() }}
    Author: {{ author() }}
{% endif %}
{% if can_edit %} {{ pipe() }}
    <a href="?action=edit">Edit</a>
{% endif %}

Slick.js: Get current and total slides (ie. 3/5)

I had an issue with multiple slides. version 1.8.1

if slidesToShow and slidesToScroll more than 1

trick is in slick.slickGetOption('slidesToShow');

$(".your-selector").on('init reInit afterChange', function(event, slick, currentSlide, nextSlide){
    var i = (currentSlide ? currentSlide : 0) + 1;
    var slidesToShow = slick.slickGetOption('slidesToShow');
    var curPage = parseInt((i-1)/slidesToShow) + 1;
    var lastPage =  parseInt((slick.slideCount-1)/slidesToShow) + 1;
    $('.your-selector').text(curPage);
    $('.your-selector').text(lastPage);
});

Note curPage and lastPage is separate. I had to color them differently.

Based on top-voted answer

How to convert .pem into .key?

CA's don't ask for your private keys! They only asks for CSR to issue a certificate for you.

If they have your private key, it's possible that your SSL certificate will be compromised and end up being revoked.

Your .key file is generated during CSR generation and, most probably, it's somewhere on your PC where you generated the CSR.

That's why private key is called "Private" - because nobody can have that file except you.

Transition color fade on hover?

For having a trasition effect like a highlighter just to highlight the text and fade off the bg color, we used the following:

_x000D_
_x000D_
.field-error {_x000D_
    color: #f44336;_x000D_
    padding: 2px 5px;_x000D_
    position: absolute;_x000D_
    font-size: small;_x000D_
    background-color: white;_x000D_
}_x000D_
_x000D_
.highlighter {_x000D_
    animation: fadeoutBg 3s; /***Transition delay 3s fadeout is class***/_x000D_
    -moz-animation: fadeoutBg 3s; /* Firefox */_x000D_
    -webkit-animation: fadeoutBg 3s; /* Safari and Chrome */_x000D_
    -o-animation: fadeoutBg 3s; /* Opera */_x000D_
}_x000D_
_x000D_
@keyframes fadeoutBg {_x000D_
    from { background-color: lightgreen; } /** from color **/_x000D_
    to { background-color: white; } /** to color **/_x000D_
}_x000D_
_x000D_
@-moz-keyframes fadeoutBg { /* Firefox */_x000D_
    from { background-color: lightgreen; }_x000D_
    to { background-color: white; }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes fadeoutBg { /* Safari and Chrome */_x000D_
    from { background-color: lightgreen; }_x000D_
    to { background-color: white; }_x000D_
}_x000D_
_x000D_
@-o-keyframes fadeoutBg { /* Opera */_x000D_
    from { background-color: lightgreen; }_x000D_
    to { background-color: white; }_x000D_
}
_x000D_
<div class="field-error highlighter">File name already exists.</div>
_x000D_
_x000D_
_x000D_

Default background color of SVG root element

Found this works in Safari. SVG only colors in with background-color where an element's bounding box covers. So, give it a border (stroke) with a zero pixel boundary. It fills in the whole thing for you with your background-color.

<svg style='stroke-width: 0px; background-color: blue;'> </svg>

Apply style ONLY on IE

As well as a conditional comment could also use CSS Browser Selector http://rafael.adm.br/css_browser_selector/ as this will allow you to target specific browsers. You can then set your CSS as

.ie .actual-form table {
    width: 100%
    }

This will also allow you to target specific browsers within your main stylesheet without the need for conditional comments.

Working with UTF-8 encoding in Python source

In the source header you can declare:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
....

It is described in the PEP 0263:

Then you can use UTF-8 in strings:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

u = 'idzie waz waska drózka'
uu = u.decode('utf8')
s = uu.encode('cp1250')
print(s)

This declaration is not needed in Python 3 as UTF-8 is the default source encoding (see PEP 3120).

In addition, it may be worth verifying that your text editor properly encodes your code in UTF-8. Otherwise, you may have invisible characters that are not interpreted as UTF-8.

standard size for html newsletter template

Bdizzle,

I would recommend that you read this link

You will see that Newsletters can have different widths, There seems to be no major standard, What is recommended is that the width will be about 95% of the page width, as different browsers use the extra margins differently. You will also find that email readers have problems when reading css so applying the guide lines in this tutorial might help you save some time and trouble-shooting down the road.

Be happy, Julian

How to install libusb in Ubuntu

you can creat symlink to your libusb after locate it in your system :

sudo ln -s /lib/x86_64-linux-gnu/libusb-1.0.so.0 /usr/lib/libusbx-1.0.so.0.1.0 

sudo ln -s /lib/x86_64-linux-gnu/libusb-1.0.so.0 /usr/lib/libusbx-1.0.so

Intel HAXM installation error - This computer does not support Intel Virtualization Technology (VT-x)

I am sorry, I forget to answer this question. After few days of googling I found, that problem was caused by hyperthreading (or hyper - v). I decided to edit my boot.ini file with option to start up windows with hyperthreading turned off. I followed this tutorial and now everything works perfect

How schedule build in Jenkins?

Jenkins uses Cron Expressions.

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

How to disable compiler optimizations in gcc?

You can also control optimisations internally with #pragma GCC push_options

#pragma GCC push_options
/* #pragma GCC optimize ("unroll-loops") */     

.... code here .....

#pragma GCC pop_options

Inverse of a matrix using numpy

Inverse of a matrix using python and numpy:

>>> import numpy as np
>>> b = np.array([[2,3],[4,5]])
>>> np.linalg.inv(b)
array([[-2.5,  1.5],
       [ 2. , -1. ]])

Not all matrices can be inverted. For example singular matrices are not Invertable:

>>> import numpy as np
>>> b = np.array([[2,3],[4,6]])
>>> np.linalg.inv(b)

LinAlgError: Singular matrix

Solution to singular matrix problem:

try-catch the Singular Matrix exception and keep going until you find a transform that meets your prior criteria AND is also invertable.

Intuition for why matrix inversion can't always be done; like in singular matrices:

Imagine an old overhead film projector that shines a bright light through film onto a white wall. The pixels in the film are projected to the pixels on the wall.

If I stop the film projection on a single frame, you will see the pixels of the film on the wall and I ask you to regenerate the film based on what you see. That's easy, you say, just take the inverse of the matrix that performed the projection. An Inverse of a matrix is the reversal of the projection.

Now imagine if the projector was corrupted, and I put a distorted lens in front of the film. Now multiple pixels are projected to the same spot on the wall. I asked you again to "undo this operation with the matrix inverse". You say: "I can't because you destroyed information with the lens distortion, I can't get back to where we were, because the matrix is either Singular or Degenerate."

A matrix that can be used to transform some data into other data is invertable only if the process can be reversed with no loss of information. If your matrix can't be inverted, perhaps you are defining your projection using a guess-and-check methodology rather than using a process that guarantees a non-corrupting transform.

If you're using a heuristic or anything less than perfect mathematical precision, then you'll have to define another process to manage and quarantine distortions so that programming by Brownian motion can resume.

Source:

http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.inv.html#numpy.linalg.inv

How can my iphone app detect its own version number?

You can use the infoDictionary which gets the version details from info.plist of you app. This code works for swift 3. Just call this method and display the version in any preferred UI element.

Swift-3  

func getVersion() -> String {
    let dictionary = Bundle.main.infoDictionary!
    let version = dictionary["CFBundleShortVersionString"] as! String
    let build = dictionary["CFBundleVersion"] as! String
    return "v\(version).\(build)"
}

Rename all files in directory from $filename_h to $filename_half?

for f in *.png; do
  fnew=`echo $f | sed 's/_h.png/_half.png/'`
  mv $f $fnew
done

Access-Control-Allow-Origin: * in tomcat

I was setting up cors.support.credentials to true along with cors.allowed.origins as *, which won't work.

When cors.allowed.origins is * , then cors.support.credentials should be false (default value or shouldn't be set explicitly).

https://tomcat.apache.org/tomcat-7.0-doc/config/filter.html

C++ "Access violation reading location" Error

You haven't posted the findvertex method, but Access Reading Violation with an offset like 0x00000048 means that the Vertex* f; in your getCost function is receiving null, and when trying to access the member adj in the null Vertex pointer (that is, in f), it is offsetting to adj (in this case, 72 bytes ( 0x48 bytes in decimal )), it's reading near the 0 or null memory address.

Doing a read like this violates Operating-System protected memory, and more importantly means whatever you're pointing at isn't a valid pointer. Make sure findvertex isn't returning null, or do a comparisong for null on f before using it to keep yourself sane (or use an assert):

assert( f != null ); // A good sanity check

EDIT:

If you have a map for doing something like a find, you can just use the map's find method to make sure the vertex exists:

Vertex* Graph::findvertex(string s)
{
    vmap::iterator itr = map1.find( s );
    if ( itr == map1.end() )
    {
        return NULL;
    }
    return itr->second;
}

Just make sure you're still careful to handle the error case where it does return NULL. Otherwise, you'll keep getting this access violation.

How to get response as String using retrofit without using GSON or any other library in android

** Update ** A scalars converter has been added to retrofit that allows for a String response with less ceremony than my original answer below.

Example interface --

public interface GitHubService {
    @GET("/users/{user}")
    Call<String> listRepos(@Path("user") String user);
}

Add the ScalarsConverterFactory to your retrofit builder. Note: If using ScalarsConverterFactory and another factory, add the scalars factory first.

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(ScalarsConverterFactory.create())
    // add other factories here, if needed.
    .build();

You will also need to include the scalars converter in your gradle file --

implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'

--- Original Answer (still works, just more code) ---

I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject land. I suspect your specific problem might be better solved using a custom gson TypeAdapter or a retrofit Converter if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -

First, if you are using Retrofit 2, you should start using the Call API. Instead of sending an object to convert as the type parameter, use ResponseBody from okhttp --

public interface GitHubService {
    @GET("/users/{user}")
    Call<ResponseBody> listRepos(@Path("user") String user);
}

then you can create and execute your call --

GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Response<ResponseBody> response) {
        try {
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(Throwable t) {
        e.printStackTrace();
    }
});

Note The code above calls string() on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream() instead. See the ResponseBody docs.

LaTeX: Prevent line break in a span of text

Use \nolinebreak

\nolinebreak[number]

The \nolinebreak command prevents LaTeX from breaking the current line at the point of the command. With the optional argument, number, you can convert the \nolinebreak command from a demand to a request. The number must be a number from 0 to 4. The higher the number, the more insistent the request is.

Source: http://www.personal.ceu.hu/tex/breaking.htm#nolinebreak

Giving multiple URL patterns to Servlet Filter

If an URL pattern starts with /, then it's relative to the context root. The /Admin/* URL pattern would only match pages on http://localhost:8080/EMS2/Admin/* (assuming that /EMS2 is the context path), but you have them actually on http://localhost:8080/EMS2/faces/Html/Admin/*, so your URL pattern never matches.

You need to prefix your URL patterns with /faces/Html as well like so:

<url-pattern>/faces/Html/Admin/*</url-pattern>

You can alternatively also just reconfigure your web project structure/configuration so that you can get rid of the /faces/Html path in the URLs so that you can just open the page by for example http://localhost:8080/EMS2/Admin/Upload.xhtml.

Your filter mapping syntax is all fine. However, a simpler way to specify multiple URL patterns is to just use only one <filter-mapping> with multiple <url-pattern> entries:

<filter-mapping>
    <filter-name>LoginFilter</filter-name>
    <url-pattern>/faces/Html/Employee/*</url-pattern>
    <url-pattern>/faces/Html/Admin/*</url-pattern>
    <url-pattern>/faces/Html/Supervisor/*</url-pattern>
</filter-mapping>

Primary key or Unique index?

The choice of when to use a surrogate primary key as opposed to a natural key is tricky. Answers such as, always or never, are rarely useful. I find that it depends on the situation.

As an example, I have the following tables:

CREATE TABLE toll_booths (
    id            INTEGER       NOT NULL PRIMARY KEY,
    name          VARCHAR(255)  NOT NULL,
    ...
    UNIQUE(name)
)

CREATE TABLE cars (
    vin           VARCHAR(17)   NOT NULL PRIMARY KEY,
    license_plate VARCHAR(10)   NOT NULL,
    ...
    UNIQUE(license_plate)
)

CREATE TABLE drive_through (
    id            INTEGER       NOT NULL PRIMARY KEY,
    toll_booth_id INTEGER       NOT NULL REFERENCES toll_booths(id),
    vin           VARCHAR(17)   NOT NULL REFERENCES cars(vin),
    at            TIMESTAMP     DEFAULT CURRENT_TIMESTAMP NOT NULL,
    amount        NUMERIC(10,4) NOT NULL,
    ...
    UNIQUE(toll_booth_id, vin)
)

We have two entity tables (toll_booths and cars) and a transaction table (drive_through). The toll_booth table uses a surrogate key because it has no natural attribute that is not guaranteed to change (the name can easily be changed). The cars table uses a natural primary key because it has a non-changing unique identifier (vin). The drive_through transaction table uses a surrogate key for easy identification, but also has a unique constraint on the attributes that are guaranteed to be unique at the time the record is inserted.

http://database-programmer.blogspot.com has some great articles on this particular subject.

double free or corruption (!prev) error in c program

1 - Your malloc() is wrong.
2 - You are overstepping the bounds of the allocated memory
3 - You should initialize your allocated memory

Here is the program with all the changes needed. I compiled and ran... no errors or warnings.

#include <stdio.h>
#include <stdlib.h> //malloc
#include <math.h>  //sine
#include <string.h>

#define TIME 255
#define HARM 32

int main (void) {
    double sineRads;
    double sine;
    int tcount = 0;
    int hcount = 0;
    /* allocate some heap memory for the large array of waveform data */
    double *ptr = malloc(sizeof(double) * TIME);
     //memset( ptr, 0x00, sizeof(double) * TIME);  may not always set double to 0
    for( tcount = 0; tcount < TIME; tcount++ )
    {
         ptr[tcount] = 0; 
    }

    tcount = 0;
    if (NULL == ptr) {
        printf("ERROR: couldn't allocate waveform memory!\n");
    } else {
        /*evaluate and add harmonic amplitudes for each time step */
        for(tcount = 0; tcount < TIME; tcount++){
            for(hcount = 0; hcount <= HARM; hcount++){
                sineRads = ((double)tcount / (double)TIME) * (2*M_PI); //angular frequency
                sineRads *= (hcount + 1); //scale frequency by harmonic number
                sine = sin(sineRads); 
                ptr[tcount] += sine; //add to other results for this time step
            }
        }
        free(ptr);
        ptr = NULL;     
    }
    return 0;
}

Is a new line = \n OR \r\n?

The given answer is far from complete. In fact, it is so far from complete that it tends to lead the reader to believe that this answer is OS dependent when it isn't. It also isn't something which is programming language dependent (as some commentators have suggested). I'm going to add more information in order to make this more clear. First, lets give the list of current new line variations (as in, what they've been since 1999):

  • \r\n is only used on Windows Notepad, the DOS command line, most of the Windows API and in some (older) Windows apps.
  • \n is used for all other systems, applications and the Internet.

You'll notice that I've put most Windows apps in the \n group which may be slightly controversial but before you disagree with this statement, please grab a UNIX formatted text file and try it in 10 web friendly Windows applications of your choice (which aren't listed in my exceptions above). What percentage of them handled it just fine? You'll find that they (practically) all implement auto detection of line endings or just use \n because, while Windows may use \r\n, the Internet uses \n. Therefore, it is best practice for applications to use \n alone if you want your output to be Internet friendly.

PHP also defines a newline character called PHP_EOL. This constant is set to the OS specific newline string for the machine PHP is running on (\r\n for Windows and \n for everything else). This constant is not very useful for webpages and should be avoided for HTML output or for writing most text to files. It becomes VERY useful when we move to command line output from PHP applications because it will allow your application to output to a terminal Window in a consistent manner across all supported OSes.

If you want your PHP applications to work from any server they are placed on, the two biggest things to remember are that you should always just use \n unless it is terminal output (in which case you use PHP_EOL) and you should also ALWAYS use / for your path separator (not \).

The even longer explanation:

An application may choose to use whatever line endings it likes regardless of the default OS line ending style. If I want my text editor to print a newline every time it encounters a period that is no harder than using the \n to represent a newline because I'm interpreting the text as I display it anyway. IOW, I'm fiddling around with measuring the width of each character so it knows where to display the next so it is very simple to add a statement saying that if the current char is a period then perform a newline action (or if it is a \n then display a period).

Aside from the null terminator, no character code is sacred and when you write a text editor or viewer you are in charge of translating the bits in your file into glyphs (or carriage returns) on the screen. The only thing that distinguishes a control character such as the newline from other characters is that most font sets don't include them (meaning they don't have a visual representation available).

That being said, if you are working at a higher level of abstraction then you probably aren't making your own textbox controls. If this is the case then you're stuck with whatever line ending that control makes available to you. Even in this case it is a simple matter to automatically detect the line ending style of any string and make the conversion before you load your text into the control and then undo it when you read from that control. Meaning, that if you're a desktop application dev and your application doesn't recognize \n as a newline then it isn't a very friendly application and you really have no excuse because it isn't hard to make it the right way. It also means that whomever wrote Notepad should be ashamed of himself because it really is very easy to do much better and so many people suffer through using it every day.

How do I plot list of tuples in Python?

As others have answered, scatter() or plot() will generate the plot you want. I suggest two refinements to answers that are already here:

  1. Use numpy to create the x-coordinate list and y-coordinate list. Working with large data sets is faster in numpy than using the iteration in Python suggested in other answers.

  2. Use pyplot to apply the logarithmic scale rather than operating directly on the data, unless you actually want to have the logs.

    import matplotlib.pyplot as plt
    import numpy as np
    
    data = [(2, 10), (3, 100), (4, 1000), (5, 100000)]
    data_in_array = np.array(data)
    '''
    That looks like array([[     2,     10],
                           [     3,    100],
                           [     4,   1000],
                           [     5, 100000]])
    '''
    
    transposed = data_in_array.T
    '''
    That looks like array([[     2,      3,      4,      5],
                           [    10,    100,   1000, 100000]])
    '''    
    
    x, y = transposed 
    
    # Here is the OO method
    # You could also the state-based methods of pyplot
    fig, ax = plt.subplots(1,1) # gets a handle for the AxesSubplot object
    ax.plot(x, y, 'ro')
    ax.plot(x, y, 'b-')
    ax.set_yscale('log')
    fig.show()
    

result

I've also used ax.set_xlim(1, 6) and ax.set_ylim(.1, 1e6) to make it pretty.

I've used the object-oriented interface to matplotlib. Because it offers greater flexibility and explicit clarity by using names of the objects created, the OO interface is preferred over the interactive state-based interface.

How to Change color of Button in Android when Clicked?

hai the most easiest way is this:

add this code to mainactivity.java

public void start(View view) {

  stop.setBackgroundResource(R.color.red);
 start.setBackgroundResource(R.color.yellow);
}

public void stop(View view) {
stop.setBackgroundResource(R.color.yellow);
start.setBackgroundResource(R.color.red);
}

and then in your activity main

    <button android:id="@+id/start" android:layout_height="wrap_content" android:layout_width="wrap_content" android:onclick="start" android:text="Click">

</button><button android:id="@+id/stop" android:layout_height="wrap_content" android:layout_width="wrap_content" android:onclick="stop" android:text="Click">

or follow along this tutorial

How to get the first element of the List or Set?

See the javadoc

of List

list.get(0);

or Set

set.iterator().next();

and check the size before using the above methods by invoking isEmpty()

!list_or_set.isEmpty()

Object of class stdClass could not be converted to string - laravel

This is easy all you need to do is something like this Grab your contents like this

  $result->get(filed1) = 'some modification';
  $result->get(filed2) = 'some modification2';

Pretty-Printing JSON with PHP

Classic case for a recursive solution. Here's mine:

class JsonFormatter {
    public static function prettyPrint(&$j, $indentor = "\t", $indent = "") {
        $inString = $escaped = false;
        $result = $indent;

        if(is_string($j)) {
            $bak = $j;
            $j = str_split(trim($j, '"'));
        }

        while(count($j)) {
            $c = array_shift($j);
            if(false !== strpos("{[,]}", $c)) {
                if($inString) {
                    $result .= $c;
                } else if($c == '{' || $c == '[') {
                    $result .= $c."\n";
                    $result .= self::prettyPrint($j, $indentor, $indentor.$indent);
                    $result .= $indent.array_shift($j);
                } else if($c == '}' || $c == ']') {
                    array_unshift($j, $c);
                    $result .= "\n";
                    return $result;
                } else {
                    $result .= $c."\n".$indent;
                } 
            } else {
                $result .= $c;
                $c == '"' && !$escaped && $inString = !$inString;
                $escaped = $c == '\\' ? !$escaped : false;
            }
        }

        $j = $bak;
        return $result;
    }
}

Usage:

php > require 'JsonFormatter.php';
php > $a = array('foo' => 1, 'bar' => 'This "is" bar', 'baz' => array('a' => 1, 'b' => 2, 'c' => '"3"'));
php > print_r($a);
Array
(
    [foo] => 1
    [bar] => This "is" bar
    [baz] => Array
        (
            [a] => 1
            [b] => 2
            [c] => "3"
        )

)
php > echo JsonFormatter::prettyPrint(json_encode($a));
{
    "foo":1,
    "bar":"This \"is\" bar",
    "baz":{
        "a":1,
        "b":2,
        "c":"\"3\""
    }
}

Cheers

Calling Member Functions within Main C++

If you want to make your code work as above, the function printInformation() needs to be declared and implemented as a static function.

If, on the other hand, it is supposed to print information about a specific object, you need to create the object first.

Finding local maxima/minima with Numpy in a 1D numpy array

Another approach (more words, less code) that may help:

The locations of local maxima and minima are also the locations of the zero crossings of the first derivative. It is generally much easier to find zero crossings than it is to directly find local maxima and minima.

Unfortunately, the first derivative tends to "amplify" noise, so when significant noise is present in the original data, the first derivative is best used only after the original data has had some degree of smoothing applied.

Since smoothing is, in the simplest sense, a low pass filter, the smoothing is often best (well, most easily) done by using a convolution kernel, and "shaping" that kernel can provide a surprising amount of feature-preserving/enhancing capability. The process of finding an optimal kernel can be automated using a variety of means, but the best may be simple brute force (plenty fast for finding small kernels). A good kernel will (as intended) massively distort the original data, but it will NOT affect the location of the peaks/valleys of interest.

Fortunately, quite often a suitable kernel can be created via a simple SWAG ("educated guess"). The width of the smoothing kernel should be a little wider than the widest expected "interesting" peak in the original data, and its shape will resemble that peak (a single-scaled wavelet). For mean-preserving kernels (what any good smoothing filter should be) the sum of the kernel elements should be precisely equal to 1.00, and the kernel should be symmetric about its center (meaning it will have an odd number of elements.

Given an optimal smoothing kernel (or a small number of kernels optimized for different data content), the degree of smoothing becomes a scaling factor for (the "gain" of) the convolution kernel.

Determining the "correct" (optimal) degree of smoothing (convolution kernel gain) can even be automated: Compare the standard deviation of the first derivative data with the standard deviation of the smoothed data. How the ratio of the two standard deviations changes with changes in the degree of smoothing cam be used to predict effective smoothing values. A few manual data runs (that are truly representative) should be all that's needed.

All the prior solutions posted above compute the first derivative, but they don't treat it as a statistical measure, nor do the above solutions attempt to performing feature preserving/enhancing smoothing (to help subtle peaks "leap above" the noise).

Finally, the bad news: Finding "real" peaks becomes a royal pain when the noise also has features that look like real peaks (overlapping bandwidth). The next more-complex solution is generally to use a longer convolution kernel (a "wider kernel aperture") that takes into account the relationship between adjacent "real" peaks (such as minimum or maximum rates for peak occurrence), or to use multiple convolution passes using kernels having different widths (but only if it is faster: it is a fundamental mathematical truth that linear convolutions performed in sequence can always be convolved together into a single convolution). But it is often far easier to first find a sequence of useful kernels (of varying widths) and convolve them together than it is to directly find the final kernel in a single step.

Hopefully this provides enough info to let Google (and perhaps a good stats text) fill in the gaps. I really wish I had the time to provide a worked example, or a link to one. If anyone comes across one online, please post it here!

Find oldest/youngest datetime object in a list

The datetime module has its own versions of min and max as available methods. https://docs.python.org/2/library/datetime.html

Checking cin input stream produces an integer

I prefer to use <limits> to check for an int until it is passed.

#include <iostream>
#include <limits> //std::numeric_limits

using std::cout, std::endl, std::cin;

int main() {
    int num;
    while(!(cin >> num)){  //check the Input format for integer the right way
        cin.clear();
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        cout << "Invalid input.  Reenter the number: ";
      };

    cout << "output= " << num << endl;

    return 0;
}

Equivalent function for DATEADD() in Oracle

Not my answer :

I wasn't too happy with the answers above and some additional searching yielded this :

SELECT SYSDATE AS current_date,

       SYSDATE + 1 AS plus_1_day,

       SYSDATE + 1/24 AS plus_1_hours,

       SYSDATE + 1/24/60 AS plus_1_minutes,

       SYSDATE + 1/24/60/60 AS plus_1_seconds

FROM   dual;

which I found very helpful. From http://sqlbisam.blogspot.com/2014/01/add-date-interval-to-date-or-dateadd.html

jQuery .get error response function?

You can get detail error by using responseText property.

$.ajaxSetup({
error: function(xhr, status, error) {
alert("An AJAX error occured: " + status + "\nError: " + error + "\nError detail: " + xhr.responseText);
     } 
    });

How to remove all the null elements inside a generic list in one go?

You'll probably want the following.

List<EmailParameterClass> parameterList = new List<EmailParameterClass>{param1, param2, param3...};
parameterList.RemoveAll(item => item == null);

How to draw an empty plot?

How about something like:

plot.new()

Count number of occurrences for each unique value

You should change the query to:

SELECT time_col, COUNT(time_col) As Count
FROM time_table
WHERE activity_col = 3
GROUP BY time_col

This vl works correctly.

Stuck at ".android/repositories.cfg could not be loaded."

Windows 10 Solution:

For me this issue was due to downloading and creating an AVD using Android Studio and then trying to use that virtual device with the Ionic command line. I resolved this by deleting all existing emulators and creating a new one from the command line.

(the avdmanager file typically lives in C:\Users\\Android\sdk\tools\bin)

List existing emulators: avdmanager list avd

Delete an existing emulator: avdmanager delete avd -n emulator_name

Add system image: sdkmanager "system-images;android-24;default;x86_64"

Create new emulator: sdkmanager "system-images;android-27;google_apis_playstore;x86"

Get folder up one level

Also you can use dirname(__DIR__, $level) for access any folding level without traversing

How do I create an abstract base class in JavaScript?

Do you mean something like this:

function Animal() {
  //Initialization for all Animals
}

//Function and properties shared by all instances of Animal
Animal.prototype.init=function(name){
  this.name=name;
}
Animal.prototype.say=function(){
    alert(this.name + " who is a " + this.type + " says " + this.whattosay);
}
Animal.prototype.type="unknown";

function Cat(name) {
    this.init(name);

    //Make a cat somewhat unique
    var s="";
    for (var i=Math.ceil(Math.random()*7); i>=0; --i) s+="e";
    this.whattosay="Me" + s +"ow";
}
//Function and properties shared by all instances of Cat    
Cat.prototype=new Animal();
Cat.prototype.type="cat";
Cat.prototype.whattosay="meow";


function Dog() {
    //Call init with same arguments as Dog was called with
    this.init.apply(this,arguments);
}

Dog.prototype=new Animal();
Dog.prototype.type="Dog";
Dog.prototype.whattosay="bark";
//Override say.
Dog.prototype.say = function() {
        this.openMouth();
        //Call the original with the exact same arguments
        Animal.prototype.say.apply(this,arguments);
        //or with other arguments
        //Animal.prototype.say.call(this,"some","other","arguments");
        this.closeMouth();
}

Dog.prototype.openMouth=function() {
   //Code
}
Dog.prototype.closeMouth=function() {
   //Code
}

var dog = new Dog("Fido");
var cat1 = new Cat("Dash");
var cat2 = new Cat("Dot");


dog.say(); // Fido the Dog says bark
cat1.say(); //Dash the Cat says M[e]+ow
cat2.say(); //Dot the Cat says M[e]+ow


alert(cat instanceof Cat) // True
alert(cat instanceof Dog) // False
alert(cat instanceof Animal) // True

Play a Sound with Python

For Windows, you can use winsound. It's built in

import winsound

winsound.PlaySound('sound.wav', winsound.SND_FILENAME)

You should be able to use ossaudiodev for linux:

from wave import open as waveOpen
from ossaudiodev import open as ossOpen
s = waveOpen('tada.wav','rb')
(nc,sw,fr,nf,comptype, compname) = s.getparams( )
dsp = ossOpen('/dev/dsp','w')
try:
  from ossaudiodev import AFMT_S16_NE
except ImportError:
  from sys import byteorder
  if byteorder == "little":
    AFMT_S16_NE = ossaudiodev.AFMT_S16_LE
  else:
    AFMT_S16_NE = ossaudiodev.AFMT_S16_BE
dsp.setparameters(AFMT_S16_NE, nc, fr)
data = s.readframes(nf)
s.close()
dsp.write(data)
dsp.close()

(Credit for ossaudiodev: Bill Dandreta http://mail.python.org/pipermail/python-list/2004-October/288905.html)

make: *** No rule to make target `all'. Stop

Your makefile should ideally be named makefile, not make. Note that you can call your makefile anything you like, but as you found, you then need the -f option with make to specify the name of the makefile. Using the default name of makefile just makes life easier.

How to use git merge --squash?

git checkout YOUR_RELEASE_BRANCH
git pull
git checkout -b A_NEW_BRANCH
git merge --squash YOUR_BRANCH_WITH_MULTIPLE_COMMITS
git commit -am "squashing all commits into one"
git push --set-upstream origin A_NEW_BRANCH

Python json.loads shows ValueError: Extra data

If you want to solve it in a two-liner you can do it like this:

with open('data.json') as f:
    data = [json.loads(line) for line in f]

Pandas aggregate count distinct

'nunique' is an option for .agg() since pandas 0.20.0, so:

df.groupby('date').agg({'duration': 'sum', 'user_id': 'nunique'})

How to read a file without newlines?

I think this is the best option.

temp = [line.strip() for line in file.readlines()]

How to enable TLS 1.2 support in an Android application (running on Android 4.1 JB)

I have some additions to above mentioned answers Its infact a hack mentioned by Jesse Wilson from okhttp, square here. According to this hack, i had to rename my SSLSocketFactory variable to

private SSLSocketFactory delegate;

This is my TLSSocketFactory class

public class TLSSocketFactory extends SSLSocketFactory {

private SSLSocketFactory delegate;

public TLSSocketFactory() throws KeyManagementException, NoSuchAlgorithmException {
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, null, null);
    delegate = context.getSocketFactory();
}

@Override
public String[] getDefaultCipherSuites() {
    return delegate.getDefaultCipherSuites();
}

@Override
public String[] getSupportedCipherSuites() {
    return delegate.getSupportedCipherSuites();
}

@Override
public Socket createSocket() throws IOException {
    return enableTLSOnSocket(delegate.createSocket());
}

@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
    return enableTLSOnSocket(delegate.createSocket(s, host, port, autoClose));
}

@Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
    return enableTLSOnSocket(delegate.createSocket(host, port));
}

@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
    return enableTLSOnSocket(delegate.createSocket(host, port, localHost, localPort));
}

@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
    return enableTLSOnSocket(delegate.createSocket(host, port));
}

@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
    return enableTLSOnSocket(delegate.createSocket(address, port, localAddress, localPort));
}

private Socket enableTLSOnSocket(Socket socket) {
    if(socket != null && (socket instanceof SSLSocket)) {
        ((SSLSocket)socket).setEnabledProtocols(new String[] {"TLSv1.1", "TLSv1.2"});
    }
    return socket;
}
}

and this is how i used it with okhttp and retrofit

 OkHttpClient client=new OkHttpClient();
    try {
        client = new OkHttpClient.Builder()
                .sslSocketFactory(new TLSSocketFactory())
                .build();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(URL)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

How to remove foreign key constraint in sql server?

Depending on the DB you are using there's a syntax or another.

If you're using Oracle you have to put what the other users told you:

ALTER TABLE table_name DROP CONSTRAINT fk_name;

But if you use MySQL then this will give you a syntax error, instead you can type:

ALTER TABLE table_name DROP INDEX fk_name;

Draw a connecting line between two elements

Cytoscape supports this with its Architecture example which supports dragging elements.

For creating connections, there is the edgehandles extension. It does not yet support editing existing connections. Question.

For editing connection shapes, there is the edge-editing extension. Demo.

The edit-editation extension seems promising, however there is no demo yet.

ORA-00918: column ambiguously defined in SELECT *

A query's projection can only have one instance of a given name. As your WHERE clause shows, you have several tables with a column called ID. Because you are selecting * your projection will have several columns called ID. Or it would have were it not for the compiler hurling ORA-00918.

The solution is quite simple: you will have to expand the projection to explicitly select named columns. Then you can either leave out the duplicate columns, retaining just (say) COACHES.ID or use column aliases: coaches.id as COACHES_ID.

Perhaps that strikes you as a lot of typing, but it is the only way. If it is any comfort, SELECT * is regarded as bad practice in production code: explicitly named columns are much safer.

How do I install Composer on a shared hosting?

SIMPLE SOLUTION (tested on Red Hat):

run command: curl -sS https://getcomposer.org/installer | php

to use it: php composer.phar

SYSTEM WIDE SOLLUTION (tested on Red Hat):

run command: mv composer.phar /usr/local/bin/composer

to use it: composer update

now you can call composer from any directory.

Source: http://www.agix.com.au/install-composer-on-centosredhat/

How does bitshifting work in Java?

When you shift right 2 bits you drop the 2 least significant bits. So:

x = 00101011

x >> 2

// now (notice the 2 new 0's on the left of the byte)
x = 00001010

This is essentially the same thing as dividing an int by 2, 2 times.

In Java

byte b = (byte) 16;
b = b >> 2;
// prints 4
System.out.println(b);

Bootstrap 3 - 100% height of custom div inside column

My solution was to make all the parents 100% and set a specific percentage for each row:

html, body,div[class^="container"] ,.column {
    height: 100%;
}

.row0 {height: 10%;}
.row1 {height: 40%;}
.row2 {height: 50%;}

How to change background and text colors in Sublime Text 3

Steps I followed for an overall dark theme including file browser:

  1. Goto Preferences->Theme...
  2. Choose Adaptive.sublime-theme

When creating a service with sc.exe how to pass in context parameters?

If you tried all of the above and still can't pass args to your service, if your service was written in C/C++, here's what could be the problem: when you start your service through "sc start arg1 arg2...", SC calls your service's ServiceMain function directly with those args. But when Windows start your service (at boot time, for example), it's your service's main function (_tmain) that's called, with params from the registry's "binPath".

How can I align two divs horizontally?

Add a class to each of the divs:

_x000D_
_x000D_
.source, .destination {_x000D_
    float: left;_x000D_
    width: 48%;_x000D_
    margin: 0;_x000D_
    padding: 0;_x000D_
}_x000D_
.source {_x000D_
    margin-right: 4%;_x000D_
}
_x000D_
<div class="source">_x000D_
    <span>source list</span>_x000D_
    <select size="10">_x000D_
        <option />_x000D_
        <option />_x000D_
        <option />_x000D_
    </select>_x000D_
</div>_x000D_
<div class="destination">_x000D_
    <span>destination list</span>_x000D_
    <select size="10">_x000D_
        <option />_x000D_
        <option />_x000D_
        <option />_x000D_
    </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

That's a generic percentages solution - using pixel-based widths is usually much more reliable. You'll probably want to change the various margin/padding sizes too.

You can also optionally wrap the HTML in a container div, and use this CSS:

.container {
  overflow: hidden;
}

This will ensure subsequent content does not wrap around the floated elements.

Use of #pragma in C

#pragma is used to do something implementation-specific in C, i.e. be pragmatic for the current context rather than ideologically dogmatic.

The one I regularly use is #pragma pack(1) where I'm trying to squeeze more out of my memory space on embedded solutions, with arrays of structures that would otherwise end up with 8 byte alignment.

Pity we don't have a #dogma yet. That would be fun ;)

What is the standard Python docstring format?

It's Python; anything goes. Consider how to publish your documentation. Docstrings are invisible except to readers of your source code.

People really like to browse and search documentation on the web. To achieve that, use the documentation tool Sphinx. It's the de-facto standard for documenting Python projects. The product is beautiful - take a look at https://python-guide.readthedocs.org/en/latest/ . The website Read the Docs will host your docs for free.

PHP FPM - check if running

Here is how you can do it with a socket on php-fpm 7

install socat
apt-get install socat

#!/bin/sh

  if echo /dev/null | socat UNIX:/var/run/php/php7.0-fpm.sock - ; then
    echo "$home/run/php-fpm.sock connect OK"
  else
    echo "$home/run/php-fpm.sock connect ERROR"
  fi

You can also check if the service is running like this.

service php7.0-fpm status | grep running

It will return

Active: active (running) since Sun 2017-04-09 12:48:09 PDT; 48s ago

Apache gives me 403 Access Forbidden when DocumentRoot points to two different drives

You did not need

Options Indexes FollowSymLinks MultiViews Includes ExecCGI
AllowOverride All
Order Allow,Deny
Allow from all
Require all granted

the only thing what you need is...

Require all granted

...inside the directory section.

See Apache 2.4 upgrading side:

http://httpd.apache.org/docs/2.4/upgrading.html

javascript /jQuery - For Loop

.each() should work for you. http://api.jquery.com/jQuery.each/ or http://api.jquery.com/each/ or you could use .map.

var newArray = $(array).map(function(i) {
    return $('#event' + i, response).html();
});

Edit: I removed the adding of the prepended 0 since it is suggested to not use that.

If you must have it use

var newArray = $(array).map(function(i) {
    var number = '' + i;
    if (number.length == 1) {
        number = '0' + number;
    }   
    return $('#event' + number, response).html();
});

How to include view/partial specific styling in AngularJS

I know this question is old now, but after doing a ton of research on various solutions to this problem, I think I may have come up with a better solution.

UPDATE 1: Since posting this answer, I have added all of this code to a simple service that I have posted to GitHub. The repo is located here. Feel free to check it out for more info.

UPDATE 2: This answer is great if all you need is a lightweight solution for pulling in stylesheets for your routes. If you want a more complete solution for managing on-demand stylesheets throughout your application, you may want to checkout Door3's AngularCSS project. It provides much more fine-grained functionality.

In case anyone in the future is interested, here's what I came up with:

1. Create a custom directive for the <head> element:

app.directive('head', ['$rootScope','$compile',
    function($rootScope, $compile){
        return {
            restrict: 'E',
            link: function(scope, elem){
                var html = '<link rel="stylesheet" ng-repeat="(routeCtrl, cssUrl) in routeStyles" ng-href="{{cssUrl}}" />';
                elem.append($compile(html)(scope));
                scope.routeStyles = {};
                $rootScope.$on('$routeChangeStart', function (e, next, current) {
                    if(current && current.$$route && current.$$route.css){
                        if(!angular.isArray(current.$$route.css)){
                            current.$$route.css = [current.$$route.css];
                        }
                        angular.forEach(current.$$route.css, function(sheet){
                            delete scope.routeStyles[sheet];
                        });
                    }
                    if(next && next.$$route && next.$$route.css){
                        if(!angular.isArray(next.$$route.css)){
                            next.$$route.css = [next.$$route.css];
                        }
                        angular.forEach(next.$$route.css, function(sheet){
                            scope.routeStyles[sheet] = sheet;
                        });
                    }
                });
            }
        };
    }
]);

This directive does the following things:

  1. It compiles (using $compile) an html string that creates a set of <link /> tags for every item in the scope.routeStyles object using ng-repeat and ng-href.
  2. It appends that compiled set of <link /> elements to the <head> tag.
  3. It then uses the $rootScope to listen for '$routeChangeStart' events. For every '$routeChangeStart' event, it grabs the "current" $$route object (the route that the user is about to leave) and removes its partial-specific css file(s) from the <head> tag. It also grabs the "next" $$route object (the route that the user is about to go to) and adds any of its partial-specific css file(s) to the <head> tag.
  4. And the ng-repeat part of the compiled <link /> tag handles all of the adding and removing of the page-specific stylesheets based on what gets added to or removed from the scope.routeStyles object.

Note: this requires that your ng-app attribute is on the <html> element, not on <body> or anything inside of <html>.

2. Specify which stylesheets belong to which routes using the $routeProvider:

app.config(['$routeProvider', function($routeProvider){
    $routeProvider
        .when('/some/route/1', {
            templateUrl: 'partials/partial1.html', 
            controller: 'Partial1Ctrl',
            css: 'css/partial1.css'
        })
        .when('/some/route/2', {
            templateUrl: 'partials/partial2.html',
            controller: 'Partial2Ctrl'
        })
        .when('/some/route/3', {
            templateUrl: 'partials/partial3.html',
            controller: 'Partial3Ctrl',
            css: ['css/partial3_1.css','css/partial3_2.css']
        })
}]);

This config adds a custom css property to the object that is used to setup each page's route. That object gets passed to each '$routeChangeStart' event as .$$route. So when listening to the '$routeChangeStart' event, we can grab the css property that we specified and append/remove those <link /> tags as needed. Note that specifying a css property on the route is completely optional, as it was omitted from the '/some/route/2' example. If the route doesn't have a css property, the <head> directive will simply do nothing for that route. Note also that you can even have multiple page-specific stylesheets per route, as in the '/some/route/3' example above, where the css property is an array of relative paths to the stylesheets needed for that route.

3. You're done Those two things setup everything that was needed and it does it, in my opinion, with the cleanest code possible.

Hope that helps someone else who might be struggling with this issue as much as I was.

How to Insert Double or Single Quotes

Or Select range and Format cells > Custom \"@\"