Programs & Examples On #Sector

Exposing the current state name with ui router

Its just because of the load time angular takes to give you the current state.

If you try to get the current state by using $timeout function then it will give you correct result in $state.current.name

$timeout(function(){
    $rootScope.currState = $state.current.name;
})

What is the difference between Eclipse for Java (EE) Developers and Eclipse Classic?

If you want to build Java EE applications, it's best to use Eclipse IDE for Java EE. It has editors from HTML to JSP/JSF, Javascript. It's rich for webapps development, and provide plugins and tools to develop Java EE applications easily (all bundled).

Eclipse Classic is basically the full featured Eclipse without the Java EE part.

Is there a minlength validation attribute in HTML5?

I notice that sometimes in Chrome when autofill is on and the fields are field by the autofill browser build in method, it bypasses the minlength validation rules, so in this case you will have to disable autofill by the following attribute:

autocomplete="off"

<input autocomplete="new-password" name="password" id="password" type="password" placeholder="Password" maxlength="12" minlength="6" required />

Change PictureBox's image to image from my resources?

Ken has the right solution, but you don't want to add the picturebox.Image.Load() member method.

If you do it with a Load and the ImageLocation is not set, it will fail with a "Image Location must be set" exception. If you use the picturebox.Refresh() member method, it works without the exception.

Completed code below:

public void showAnimatedPictureBox(PictureBox thePicture)
{
            thePicture.Image = Properties.Resources.hamster;
            thePicture.Refresh();
            thePicture.Visible = true;
}

It is invoked as: showAnimatedPictureBox( myPictureBox );

My XAML looks like:

    <Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:wfi="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
        xmlns:winForms="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Class="myApp.MainWindow"
        Title="myApp" Height="679.079" Width="986">

        <StackPanel Width="136" Height="Auto" Background="WhiteSmoke" x:Name="statusPanel">
            <wfi:WindowsFormsHost>
                <winForms:PictureBox x:Name="myPictureBox">
                </winForms:PictureBox>
            </wfi:WindowsFormsHost>
            <Label x:Name="myLabel" Content="myLabel" Margin="10,3,10,5" FontSize="20" FontWeight="Bold" Visibility="Hidden"/>
        </StackPanel>
</Window>

I realize this is an old post, but loading the image directly from a resource is was extremely unclear on Microsoft's site, and this was the (partial) solution I came to. Hope it helps someone!

Why I get 411 Length required error?

I had the same error when I imported web requests from fiddler captured sessions to Visual Studio webtests. Some POST requests did not have a StringHttpBody tag. I added an empty one to them and the error was gone. Add this after the Headers tag:

    <StringHttpBody ContentType="" InsertByteOrderMark="False">
  </StringHttpBody>

how to filter out a null value from spark dataframe

Here is a solution for spark in Java. To select data rows containing nulls. When you have Dataset data, you do:

Dataset<Row> containingNulls =  data.where(data.col("COLUMN_NAME").isNull())

To filter out data without nulls you do:

Dataset<Row> withoutNulls = data.where(data.col("COLUMN_NAME").isNotNull())

Often dataframes contain columns of type String where instead of nulls we have empty strings like "". To filter out such data as well we do:

Dataset<Row> withoutNullsAndEmpty = data.where(data.col("COLUMN_NAME").isNotNull().and(data.col("COLUMN_NAME").notEqual("")))

adb devices command not working

HTC One m7 running fresh Cyanogenmod 11.

Phone is connected USB and tethering my data connection.

Then I get this surprise:

cinder@ultrabook:~/temp/htc_m7/2015-11-11$ adb shell
error: insufficient permissions for device

cinder@ultrabook:~/temp/htc_m7/2015-11-11$ adb devices
List of devices attached
????????????    no permissions

SOLUTION: Turn tethering OFF on phone.

cinder@ultrabook:~/temp/htc_m7/2015-11-11$ adb devices
List of devices attached
HT36AW908858    device

Calculate age based on date of birth

declare @dateOfBirth date select @dateOfBirth = '2000-01-01'

SELECT datediff(YEAR,@dateOfBirth,getdate()) as Age

How to debug Apache mod_rewrite

Based on Ben's answer you you could do the following when running apache on Linux (Debian in my case).

First create the file rewrite-log.load

/etc/apache2/mods-availabe/rewrite-log.load

RewriteLog "/var/log/apache2/rewrite.log"
RewriteLogLevel 3

Then enter

$ a2enmod rewrite-log

followed by

$ service apache2 restart

And when you finished with debuging your rewrite rules

$ a2dismod rewrite-log && service apache2 restart

JavaScript to get rows count of a HTML table

Given a

<table id="tableId">
    <thead>
        <tr><th>Header</th></tr>
    </thead>
    <tbody>
        <tr><td>Row 1</td></tr>
        <tr><td>Row 2</td></tr>
        <tr><td>Row 3</td></tr>
    </tbody>
    <tfoot>
        <tr><td>Footer</td></tr>
    </tfoot>
</table>

and a

var table = document.getElementById("tableId");

there are two ways to count the rows:

var totalRowCount = table.rows.length; // 5
var tbodyRowCount = table.tBodies[0].rows.length; // 3

The table.rows.length returns the amount of ALL <tr> elements within the table. So for the above table it will return 5 while most people would really expect 3. The table.tBodies returns an array of all <tbody> elements of which we grab only the first one (our table has only one). When we count the rows on it, then we get the expected value of 3.

How to set 777 permission on a particular folder?

go to FileZilla and select which folder you will be give 777 permission, then right click set permission 777 and select check box, then ok.

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

I'm sad to say: We are sh*t out of luck on this one.

I'd like to refer you to the author of WhichBrowser: Everybody lies.

Basically, no browser is being honest. No matter if you use Chrome or IE, they both will tell you that they are "Mozilla Netscape" with Gecko and Safari support. Try it yourself on any of the fiddles flying around in this thread:

hims056's fiddle

Hariharan's fiddle

or any other... Try it with Chrome (which might still succeed), then try it with a recent version of IE, and you will cry. Of course, there are heuristics, to get it all right, but it will be tedious to grasp all the edge cases, and they will very likely not work anymore in a year's time.

Take your code, for example:

<div id="example"></div>
<script type="text/javascript">
txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
txt+= "<p>Browser Name: " + navigator.appName + "</p>";
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";
document.getElementById("example").innerHTML=txt;
</script>

Chrome says:

Browser CodeName: Mozilla

Browser Name: Netscape

Browser Version: 5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36

Cookies Enabled: true

Platform: Win32

User-agent header: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36

IE says:

Browser CodeName: Mozilla

Browser Name: Netscape

Browser Version: 5.0 (Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3; rv:11.0) like Gecko

Cookies Enabled: true

Platform: Win32

User-agent header: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3; rv:11.0) like Gecko

At least Chrome still has a string that contains "Chrome" with the exact version number. But, for IE you must extrapolate from the things it supports to actually figure it out (who else would boast that they support .NET or Media Center :P), and then match it against the rv: at the very end to get the version number. Of course, even such sophisticated heuristics might very likely fail as soon as IE 12 (or whatever they want to call it) comes out.

How to sum digits of an integer in java?

public static void main(String[] args) {
        int num = 321;
        int sum = 0;
        while (num > 0) {
            sum = sum + num % 10;
            num = num / 10;
        }
        System.out.println(sum); 
}

Output

6

Compare two List<T> objects for equality, ignoring order

In addition to Guffa's answer, you could use this variant to have a more shorthanded notation.

public static bool ScrambledEquals<T>(this IEnumerable<T> list1, IEnumerable<T> list2)
{
  var deletedItems = list1.Except(list2).Any();
  var newItems = list2.Except(list1).Any();
  return !newItems && !deletedItems;          
}

How to get Wikipedia content using Wikipedia's API?

<script>    
    function dowiki(place) {
        var URL = 'https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=';

        URL += "&titles=" + place;
        URL += "&rvprop=content";
        URL += "&callback=?";
        $.getJSON(URL, function (data) {
            var obj = data.query.pages;
            var ob = Object.keys(obj)[0];
            console.log(obj[ob]["extract"]);
            try{
                document.getElementById('Label11').textContent = obj[ob]["extract"];
            }
            catch (err) {
                document.getElementById('Label11').textContent = err.message;
            }

        });
    }
</script>

How to set a default value for an existing column

ALTER TABLE [dbo].[Employee] ADD  DEFAULT ('N') FOR [CityBorn]

Add an object to a python list

You need to create a copy of the list before you modify its contents. A quick shortcut to duplicate a list is this:

mylist[:]

Example:

>>> first = [1,2,3]
>>> second = first[:]
>>> second.append(4)
>>> first
[1, 2, 3]
>>> second
[1, 2, 3, 4]

And to show the default behavior that would modify the orignal list (since a name in Python is just a reference to the underlying object):

>>> first = [1,2,3]
>>> second = first
>>> second.append(4)
>>> first
[1, 2, 3, 4]
>>> second
[1, 2, 3, 4]

Note that this only works for lists. If you need to duplicate the contents of a dictionary, you must use copy.deepcopy() as suggested by others.

What does the ??!??! operator do in C?

??! is a trigraph that translates to |. So it says:

!ErrorHasOccured() || HandleError();

which, due to short circuiting, is equivalent to:

if (ErrorHasOccured())
    HandleError();

Guru of the Week (deals with C++ but relevant here), where I picked this up.

Possible origin of trigraphs or as @DwB points out in the comments it's more likely due to EBCDIC being difficult (again). This discussion on the IBM developerworks board seems to support that theory.

From ISO/IEC 9899:1999 §5.2.1.1, footnote 12 (h/t @Random832):

The trigraph sequences enable the input of characters that are not defined in the Invariant Code Set as described in ISO/IEC 646, which is a subset of the seven-bit US ASCII code set.

Transposing a 1D NumPy array

The name of the function in numpy is column_stack.

>>>a=np.array([5,4])
>>>np.column_stack(a)
array([[5, 4]])

Cannot find control with name: formControlName in angular reactive form

I tried to generate a form dynamically because the amount of questions depend on an object and for me the error was fixed when I added ngDefaultControl to my mat-form-field.

    <form [formGroup]="questionsForm">
        <ng-container *ngFor="let question of questions">
            <mat-form-field [formControlName]="question.id" ngDefaultControl>
                <mat-label>{{question.questionContent}}</mat-label>
                <textarea matInput rows="3" required></textarea>
            </mat-form-field>
        </ng-container>
        <button mat-raised-button (click)="sendFeedback()">Submit all questions</button>
    </form>

In sendFeedback() I get the value from my dynamic form by selecting the formgroup's value as such

  sendFeedbackAsAgent():void {
    if (this.questionsForm.valid) {
      console.log(this.questionsForm.value)
    }
  }

Import a file from a subdirectory?

Just an addition to these answers.

If you want to import all files from all subdirectories, you can add this to the root of your file.

import sys, os
sys.path.extend([f'./{name}' for name in os.listdir(".") if os.path.isdir(name)])

And then you can simply import files from the subdirectories just as if these files are inside the current directory.

Working example

If I have the following directory with subdirectories in my project...

.
+-- a.py
+-- b.py
+-- c.py
+-- subdirectory_a
¦   +-- d.py
¦   +-- e.py
+-- subdirectory_b
¦   +-- f.py
+-- subdirectory_c
¦   +-- g.py
+-- subdirectory_d
    +-- h.py

I can put the following code inside my a.py file

import sys, os
sys.path.extend([f'./{name}' for name in os.listdir(".") if os.path.isdir(name)])

# And then you can import files just as if these files are inside the current directory

import b
import c
import d
import e
import f
import g
import h

In other words, this code will abstract from which directory the file is coming from.

Route.get() requires callback functions but got a "object Undefined"

I got the same error. After debugging, I found that I misspelled the method name that I imported from the controller into the route file. Please check the method name.

Tomcat base URL redirection

You can do this: If your tomcat installation is default and you have not done any changes, then the default war will be ROOT.war. Thus whenever you will call http://yourserver.example.com/, it will call the index.html or index.jsp of your default WAR file. Make the following changes in your webapp/ROOT folder for redirecting requests to http://yourserver.example.com/somewhere/else:

  1. Open webapp/ROOT/WEB-INF/web.xml, remove any servlet mapping with path /index.html or /index.jsp, and save.

  2. Remove webapp/ROOT/index.html, if it exists.

  3. Create the file webapp/ROOT/index.jsp with this line of content:

    <% response.sendRedirect("/some/where"); %>
    

    or if you want to direct to a different server,

    <% response.sendRedirect("http://otherserver.example.com/some/where"); %>
    

That's it.

How to configure static content cache per folder and extension in IIS7?

You can set specific cache-headers for a whole folder in either your root web.config:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <!-- Note the use of the 'location' tag to specify which 
       folder this applies to-->
  <location path="images">
    <system.webServer>
      <staticContent>
        <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="00:00:15" />
      </staticContent>
    </system.webServer>
  </location>
</configuration>

Or you can specify these in a web.config file in the content folder:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <staticContent>
      <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="00:00:15" />
    </staticContent>
  </system.webServer>
</configuration>

I'm not aware of a built in mechanism to target specific file types.

TypeScript: correct way to do string equality?

If you know x and y are both strings, using === is not strictly necessary, but is still good practice.

Assuming both variables actually are strings, both operators will function identically. However, TS often allows you to pass an object that meets all the requirements of string rather than an actual string, which may complicate things.

Given the possibility of confusion or changes in the future, your linter is probably correct in demanding ===. Just go with that.

HTML form readonly SELECT tag/input

In addition to disabling the options that should not be selectable i wanted to actually make them dissapear from the list, but still be able to enable them should i need to later:

$("select[readonly]").find("option:not(:selected)").hide().attr("disabled",true);

This finds all select elements with a readonly attribute, then finds all options inside those selects that are not selected, then it hides them and disables them.

It is important to separate the jquery query in 2 for performance reasons, because jquery reads them from right to left, the code:

$("select[readonly] option:not(:selected)")

will first find all unselected options in the document and then filter those that are inside selects with a readonly attribute.

How to get form values in Symfony2 controller

For not mapped form fields I use $form->get('inputName')->getViewData();

How to convert int to date in SQL Server 2008

You have to first convert it into datetime, then to date.

Try this, it might be helpful:

Select Convert(DATETIME, LEFT(20130101, 8))

then convert to date.

Line Break in XML formatting?

Here is what I use when I don't have access to the source string, e.g. for downloaded HTML:

// replace newlines with <br>
public static String replaceNewlinesWithBreaks(String source) {
    return source != null ? source.replaceAll("(?:\n|\r\n)","<br>") : "";
}

For XML you should probably edit that to replace with <br/> instead.

Example of its use in a function (additional calls removed for clarity):

// remove HTML tags but preserve supported HTML text styling (if there is any)
public static CharSequence getStyledTextFromHtml(String source) {
    return android.text.Html.fromHtml(replaceNewlinesWithBreaks(source));
}

...and a further example:

textView.setText(getStyledTextFromHtml(someString));

The name 'ViewBag' does not exist in the current context

After trying all approaches, none of them worked for me since all I have was correct configurations. finally

Deleting all files from "temp" and "%temp%" from system helped to resolve this issue.

Open Run command(Windows+R) and type above strings and delete all temporary files.

.NET console application as Windows service

I use a service class that follows the standard pattern prescribed by ServiceBase, and tack on helpers to easy F5 debugging. This keeps service data defined within the service, making them easy to find and their lifetimes easy to manage.

I normally create a Windows application with the structure below. I don't create a console application; that way I don't get a big black box popping in my face every time I run the app. I stay in in the debugger where all the action is. I use Debug.WriteLine so that the messages go to the output window, which docks nicely and stays visible after the app terminates.

I usually don't bother add debug code for stopping; I just use the debugger instead. If I do need to debug stopping, I make the project a console app, add a Stop forwarder method, and call it after a call to Console.ReadKey.

public class Service : ServiceBase
{
    protected override void OnStart(string[] args)
    {
        // Start logic here.
    }

    protected override void OnStop()
    {
        // Stop logic here.
    }

    static void Main(string[] args)
    {
        using (var service = new Service()) {
            if (Environment.UserInteractive) {
                service.Start();
                Thread.Sleep(Timeout.Infinite);
            } else
                Run(service);
        }
    }
    public void Start() => OnStart(null);
}

How do I set a checkbox in razor view?

If we set "true" in model, It'll always true. But we want to set option value for my checkbox we can use this. Important in here is The name of checkbox "AllowRating", It's must name of var in model if not when we post the value not pass in Database. form of it:

@Html.CheckBox("NameOfVarInModel", true) ;

for you!

@Html.CheckBox("AllowRating", true) ;

Format numbers in thousands (K) in Excel

Non-Americans take note! If you use Excel with "." as 1000 separator, you need to replace the "," with a "." in the formula, such as:

[>=1000]€ #.##0." K";[<=-1000]-€ #.##0." K";0

The code above will display € 62.123 as "€ 62 K".

What is the meaning of <> in mysql query?

<> means NOT EQUAL TO, != also means NOT EQUAL TO. It's just another syntactic sugar. both <> and != are same.

The below two examples are doing the same thing. Query publisher table to bring results which are NOT EQUAL TO <> != USA.

SELECT pub_name,country,pub_city,estd FROM publisher WHERE country <> "USA";

SELECT pub_name,country,pub_city,estd FROM publisher WHERE country != "USA";

Run php script as daemon process

Another option is to use Upstart. It was originally developed for Ubuntu (and comes packaged with it by default), but is intended to be suitable for all Linux distros.

This approach is similar to Supervisord and daemontools, in that it automatically starts the daemon on system boot and respawns on script completion.

How to set it up:

Create a new script file at /etc/init/myphpworker.conf. Here is an example:

# Info
description "My PHP Worker"
author      "Jonathan"

# Events
start on startup
stop on shutdown

# Automatically respawn
respawn
respawn limit 20 5

# Run the script!
# Note, in this example, if your PHP script returns
# the string "ERROR", the daemon will stop itself.
script
    [ $(exec /usr/bin/php -f /path/to/your/script.php) = 'ERROR' ] && ( stop; exit 1; )
end script

Starting & stopping your daemon:

sudo service myphpworker start
sudo service myphpworker stop

Check if your daemon is running:

sudo service myphpworker status

Thanks

A big thanks to Kevin van Zonneveld, where I learned this technique from.

How to establish ssh key pair when "Host key verification failed"

Step1:$Bhargava.ssh#

ssh-keygen -R 199.95.30.220

step2:$Bhargava.ssh #

ssh-copy-id [email protected]

          Enter the the password.........

step3: Bhargava .ssh #

ssh [email protected]

Welcome to Ubuntu 14.04.3 LTS (GNU/Linux 3.13.0-68-generic x86_64) * Documentation: https://help.ubuntu.com/ Ubuntu 14.04.3 LTS server : 228839 ip : 199.95.30.220 hostname : qt.example.com System information as of Thu Mar 24 02:13:43 EDT 2016 System load: 0.67 Processes: 321 Usage of /home: 5.1% of 497.80GB Users logged in: 0 Memory usage: 53% IP address for eth0: 199.95.30.220 Swap usage: 16% IP address for docker0: 172.17.0.1 Graph this data and manage this system at: https://landscape.canonical.com/ Last login: Wed Mar 23 02:07:29 2016 from 103.200.41.50

hostname@qt:~$

html5 <input type="file" accept="image/*" capture="camera"> display as image rather than "choose file" button

You have to use Javascript Filereader for this. (Introduction into filereader-api: http://www.html5rocks.com/en/tutorials/file/dndfiles/)

Once the user have choose a image you can read the file-path of the chosen image and place it into your html.

Example:

<form id="form1" runat="server">
    <input type='file' id="imgInp" />
    <img id="blah" src="#" alt="your image" />
</form>

Javascript:

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#blah').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

$("#imgInp").change(function(){
    readURL(this);
});

Python to print out status bar and percentage

Here you can use following code as a function:

def drawProgressBar(percent, barLen = 20):
    sys.stdout.write("\r")
    progress = ""
    for i in range(barLen):
        if i < int(barLen * percent):
            progress += "="
        else:
            progress += " "
    sys.stdout.write("[ %s ] %.2f%%" % (progress, percent * 100))
    sys.stdout.flush()

With use of .format:

def drawProgressBar(percent, barLen = 20):
    # percent float from 0 to 1. 
    sys.stdout.write("\r")
    sys.stdout.write("[{:<{}}] {:.0f}%".format("=" * int(barLen * percent), barLen, percent * 100))
    sys.stdout.flush()

How to add image to canvas

In my case, I was mistaken the function parameters, which are:

context.drawImage(image, left, top);
context.drawImage(image, left, top, width, height);

If you expect them to be

context.drawImage(image, width, height);

you will place the image just outside the canvas with the same effects as described in the question.

Setting Custom ActionBar Title from Fragment

Just in case if you are having issues with the code, try putting getSupportActionBar().setTitle(title) inside onResume() of your fragment instead of onCreateView(...) i.e

In MainActivity.java :

public void setActionBarTitle(String title) {
    getSupportActionBar().setTitle(title);
}

In Fragment:

 @Override
 public void onResume(){
     super.onResume();
     ((MainActivity) getActivity()).setActionBarTitle("Your Title");
 }

Table-level backup

If you are looking to be able to restore a table after someone has mistakenly deleted rows from it you could maybe have a look at database snapshots. You could restore the table quite easily (or a subset of the rows) from the snapshot. See http://msdn.microsoft.com/en-us/library/ms175158.aspx

To show only file name without the entire directory path

(cd dir && ls)

will only output filenames in dir. Use ls -1 if you want one per line.

(Changed ; to && as per Sactiw's comment).

Checking Bash exit status of several commands efficiently

You can use @john-kugelman 's awesome solution found above on non-RedHat systems by commenting out this line in his code:

. /etc/init.d/functions

Then, paste the below code at the end. Full disclosure: This is just a direct copy & paste of the relevant bits of the above mentioned file taken from Centos 7.

Tested on MacOS and Ubuntu 18.04.


BOOTUP=color
RES_COL=60
MOVE_TO_COL="echo -en \\033[${RES_COL}G"
SETCOLOR_SUCCESS="echo -en \\033[1;32m"
SETCOLOR_FAILURE="echo -en \\033[1;31m"
SETCOLOR_WARNING="echo -en \\033[1;33m"
SETCOLOR_NORMAL="echo -en \\033[0;39m"

echo_success() {
    [ "$BOOTUP" = "color" ] && $MOVE_TO_COL
    echo -n "["
    [ "$BOOTUP" = "color" ] && $SETCOLOR_SUCCESS
    echo -n $"  OK  "
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    echo -n "]"
    echo -ne "\r"
    return 0
}

echo_failure() {
    [ "$BOOTUP" = "color" ] && $MOVE_TO_COL
    echo -n "["
    [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
    echo -n $"FAILED"
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    echo -n "]"
    echo -ne "\r"
    return 1
}

echo_passed() {
    [ "$BOOTUP" = "color" ] && $MOVE_TO_COL
    echo -n "["
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    echo -n $"PASSED"
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    echo -n "]"
    echo -ne "\r"
    return 1
}

echo_warning() {
    [ "$BOOTUP" = "color" ] && $MOVE_TO_COL
    echo -n "["
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    echo -n $"WARNING"
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    echo -n "]"
    echo -ne "\r"
    return 1
} 

What is &amp used for

My Source: http://htmlhelp.com/tools/validator/problems.html#amp

Another common error occurs when including a URL which contains an ampersand ("&"):

This is invalid:

a href="foo.cgi?chapter=1&section=2&copy=3&lang=en"

Explanation:

This example generates an error for "unknown entity section" because the "&" is assumed to begin an entity reference. Browsers often recover safely from this kind of error, but real problems do occur in some cases. In this example, many browsers correctly convert &copy=3 to ©=3, which may cause the link to fail. Since ⟨ is the HTML entity for the left-pointing angle bracket, some browsers also convert &lang=en to <=en. And one old browser even finds the entity §, converting &section=2 to §ion=2.

So the goal here is to avoid problems when you are trying to validate your website. So you should be replacing your ampersands with &amp; when writing a URL in your markup.

Note that replacing & with &amp; is only done when writing the URL in HTML, where "&" is a special character (along with "<" and ">"). When writing the same URL in a plain text email message or in the location bar of your browser, you would use "&" and not "&amp;". With HTML, the browser translates "&amp;" to "&" so the Web server would only see "&" and not "&amp;" in the query string of the request.

Hope this helps : )

Alter table to modify default value of column

ALTER TABLE {TABLE NAME}
ALTER COLUMN {COLUMN NAME} SET DEFAULT '{DEFAULT VALUES}'

example :

ALTER TABLE RESULT
ALTER COLUMN STATUS SET DEFAULT 'FAIL'

When should I use curly braces for ES6 import?

For a default export we do not use { } when we import.

For example,

File player.js

export default vx;

File index.js

import vx from './player';

File index.js

Enter image description here

File player.js

Enter image description here

If we want to import everything that we export then we use *:

Enter image description here

remove space between paragraph and unordered list

I ended up using a definition list with an unordered list inside it. It solves the issue of the unwanted space above the list without needing to change every paragraph tag.

<dl><dt>Text</dt>
<dd><ul><li>First item</li>
<li>Second item</li></ul></dd></dl>

Is there a way to follow redirects with command line cURL?

Use the location header flag:

curl -L <URL>

How to extend available properties of User.Identity

For anyone that finds this question looking for how to access custom properties in ASP.NET Core 2.1 - it's much easier: You'll have a UserManager, e.g. in _LoginPartial.cshtml, and then you can simply do (assuming "ScreenName" is a property that you have added to your own AppUser which inherits from IdentityUser):

@using Microsoft.AspNetCore.Identity

@using <namespaceWhereYouHaveYourAppUser>

@inject SignInManager<AppUser> SignInManager
@inject UserManager<AppUser> UserManager

@if (SignInManager.IsSignedIn(User)) {
    <form asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="@Url.Action("Index", "Home", new { area = "" })" 
          method="post" id="logoutForm" 
          class="form-inline my-2 my-lg-0">

        <ul class="nav navbar-nav ml-auto">
            <li class="nav-item">
                <a class="nav-link" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">
                    Hello @((await UserManager.GetUserAsync(User)).ScreenName)!
                    <!-- Original code, shows Email-Address: @UserManager.GetUserName(User)! -->
                </a>
            </li>
            <li class="nav-item">
                <button type="submit" class="btn btn-link nav-item navbar-link nav-link">Logout</button>
            </li>
        </ul>

    </form>
} else {
    <ul class="navbar-nav ml-auto">
        <li class="nav-item"><a class="nav-link" asp-area="Identity" asp-page="/Account/Register">Register</a></li>
        <li class="nav-item"><a class="nav-link" asp-area="Identity" asp-page="/Account/Login">Login</a></li>
    </ul>
}

How to print out a variable in makefile

If you don't want to modify the Makefile itself, you can use --eval to add a new target, and then execute the new target, e.g.

make --eval='print-tests: @echo TESTS $(TESTS) ' print-tests

You can insert the required TAB character in the command line using CTRL-V, TAB

example Makefile from above:

all: do-something

TESTS=
TESTS+='a'
TESTS+='b'
TESTS+='c'

do-something:
        @echo "doing something"
        @echo "running tests $(TESTS)"
        @exit 1

How can I display a list view in an Android Alert Dialog?

Isn't it smoother to make a method to be called after the creation of the EditText unit in an AlertDialog, for general use?

public static void EditTextListPicker(final Activity activity, final EditText EditTextItem, final String SelectTitle, final String[] SelectList) {
    EditTextItem.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setTitle(SelectTitle);
            builder.setItems(SelectList, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialogInterface, int item) {
                    EditTextItem.setText(SelectList[item]);
                }
            });
            builder.create().show();
            return false;
        }
    });
}

Printing HashMap In Java

map.forEach((key, value) -> System.out.println(key + " " + value));

Using java 8 features

Can a JSON value contain a multiline string

I'm not sure of your exact requirement but one possible solution to improve 'readability' is to store it as an array.

{
  "testCases" :
  {
    "case.1" :
    {
      "scenario" : "this the case 1.",
      "result" : ["this is a very long line which is not easily readble.",
                  "so i would like to write it in multiple lines.",
                  "but, i do NOT require any new lines in the output."]
    }
  }
}

}

The join in back again whenever required with

result.join(" ")

What is a Maven artifact?

I know this is an ancient thread but I wanted to add a few nuances.

There are Maven artifacts, repository manager artifacts and then there are Maven Artifacts.

A Maven artifact is just as other commenters/responders say: it is a thing that is spat out by building a Maven project. That could be a .jar file, or a .war file, or a .zip file, or a .dll, or what have you.

A repository manager artifact is a thing that is, well, managed by a repository manager. A repository manager is basically a highly performant naming service for software executables and libraries. A repository manager doesn't care where its artifacts come from (maybe they came from a Maven build, or a local file, or an Ant build, or a by-hand compilation...).

A Maven Artifact is a Java class that represents the kind of "name" that gets dereferenced by a repository manager into a repository manager artifact. When used in this sense, an Artifact is just a glorified name made up of such parts as groupId, artifactId, version, scope, classifier and so on.

To put it all together:

  • Your Maven project probably depends on several Artifacts by way of its <dependency> elements.
  • Maven interacts with a repository manager to resolve those Artifacts into files by instructing the repository manager to send it some repository manager artifacts that correspond to the internal Artifacts.
  • Finally, after resolution, Maven builds your project and produces a Maven artifact. You may choose to "turn this into" a repository manager artifact by, in turn, using whatever tool you like, sending it to the repository manager with enough coordinating information that other people can find it when they ask the repository manager for it.

Hope that helps.

Loading all images using imread from a given folder

You can also use matplotlib for this, try this out:

import matplotlib.image as mpimg

def load_images(folder):
    images = []
    for filename in os.listdir(folder):
        img = mpimg.imread(os.path.join(folder, filename))
        if img is not None:
            images.append(img)
    return images

Correct way of looping through C++ arrays

Add a stopping value to the array:

#include <iostream>
using namespace std;

int main ()
{
   string texts[] = {"Apple", "Banana", "Orange", ""};
   for( unsigned int a = 0; texts[a].length(); a = a + 1 )
   {
       cout << "value of a: " << texts[a] << endl;
   }

   return 0;
}

Clearing UIWebview cache

Swift 3.

// Remove all cache 
URLCache.shared.removeAllCachedResponses()

// Delete any associated cookies     
if let cookies = HTTPCookieStorage.shared.cookies {
    for cookie in cookies {
        HTTPCookieStorage.shared.deleteCookie(cookie)
    }
}

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

This will find "Mark Sagal" in Student.txt. Assuming Student.txt contains

Student.txt

Amir Amiri
Mark Sagal
Juan Delacruz

Main.java

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        final String file = "Student.txt";
        String line = null;
        ArrayList<String> fileContents = new ArrayList<>();

        try {
            FileReader fReader = new FileReader(file);
            BufferedReader fileBuff = new BufferedReader(fReader);
            while ((line = fileBuff.readLine()) != null) {
                fileContents.add(line);
            }
            fileBuff.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        System.out.println(fileContents.contains("Mark Sagal"));
    }
}

login failed for user 'sa'. The user is not associated with a trusted SQL Server connection. (Microsoft SQL Server, Error: 18452) in sql 2008

  1. Go to services.msc from run prompt.
  2. Restart the services of SQL server(MSSQLSERVER)
  3. Restart the services of SQL server(SQLEXPRESS)

100% Min Height CSS layout

First you should create a div with id='footer' after your content div and then simply do this.

Your HTML should look like this:

<html>
    <body>
        <div id="content">
            ...
        </div>
        <div id="footer"></div>
    </body>
</html>

And the CSS:

?html, body {
    height: 100%;   
}
#content {
    height: 100%;
}
#footer {
    clear: both;        
}

Auto-expanding layout with Qt-Designer

I've tried to find a "fit to screen" property but there is no such.

But setting widget's "maximumSize" to a "some big number" ( like 2000 x 2000 ) will automatically fit the widget to the parent widget space.

What is the benefit of using "SET XACT_ABORT ON" in a stored procedure?

In my opinion SET XACT_ABORT ON was made obsolete by the addition of BEGIN TRY/BEGIN CATCH in SQL 2k5. Before exception blocks in Transact-SQL it was really difficult to handle errors and unbalanced procedures were all too common (procedures that had a different @@TRANCOUNT at exit compared to entry).

With the addition of Transact-SQL exception handling is much easier to write correct procedures that are guaranteed to properly balance the transactions. For instance I use this template for exception handling and nested transactions:

create procedure [usp_my_procedure_name]
as
begin
    set nocount on;
    declare @trancount int;
    set @trancount = @@trancount;
    begin try
        if @trancount = 0
            begin transaction
        else
            save transaction usp_my_procedure_name;

        -- Do the actual work here

lbexit:
        if @trancount = 0   
            commit;
    end try
    begin catch
        declare @error int, @message varchar(4000), @xstate int;
        select @error = ERROR_NUMBER(), @message = ERROR_MESSAGE(), @xstate = XACT_STATE();
        if @xstate = -1
            rollback;
        if @xstate = 1 and @trancount = 0
            rollback
        if @xstate = 1 and @trancount > 0
            rollback transaction usp_my_procedure_name;

        raiserror ('usp_my_procedure_name: %d: %s', 16, 1, @error, @message) ;
    end catch   
end
go

It allows me to write atomic procedures that rollback only their own work in case of recoverable errors.

One of the main issues Transact-SQL procedures face is data purity: sometimes the parameters received or the data in the tables are just plain wrong, resulting in duplicate key errors, referential constrain errors, check constrain errors and so on and so forth. After all, that's exactly the role of these constrains, if these data purity errors would be impossible and all caught by the business logic, the constrains would be all obsolete (dramatic exaggeration added for effect). If XACT_ABORT is ON then all these errors result in the entire transaction being lost, as opposed to being able to code exception blocks that handle the exception gracefully. A typical example is trying to do an INSERT and reverting to an UPDATE on PK violation.

Python TypeError: not enough arguments for format string

Note that the % syntax for formatting strings is becoming outdated. If your version of Python supports it, you should write:

instr = "'{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}'".format(softname, procversion, int(percent), exe, description, company, procurl)

This also fixes the error that you happened to have.

Python script to copy text to clipboard

GTK3:

#!/usr/bin/python3

from gi.repository import Gtk, Gdk


class Hello(Gtk.Window):

    def __init__(self):
        super(Hello, self).__init__()
        clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
        clipboard.set_text("hello world", -1)
        Gtk.main_quit()


def main():
    Hello()
    Gtk.main()

if __name__ == "__main__":
    main()

What is the first character in the sort order used by Windows Explorer?

From my testing, there are three criteria for sorting characters as described below. Aside from this, shorter strings are sorted above longer strings that start with the same characters.

Note: This testing only looked at the first character sorting and did not look into edge cases described by this answer, which found that, for all characters after the first character, numbers take precedence over symbols (i.e. the order is 1. Symbols 2. Numbers 3. Letters for first character, 1. Numbers 2. Symbols 3. Letters after). This answer also indicated that the Unicode/ASCII layer of sorting might not be entirely consistent. I'll update this answer if I get time to look into these edge cases.

Note: It's important to note that sorting order might be subject to change as described by this answer. It is not clear to me though the extent to which this actually ever changes. I've done this testing and found it to be valid on both Windows 7 and Windows 10.


Symbols
Latin (ordered by Unicode value (U+xxxx))
Greek (ordered by Unicode value (U+xxxx))
Cyrillic (ordered by Unicode value (U+xxxx))
Hebrew (ordered by Unicode value (U+xxxx))
Arabic (ordered by Unicode value (U+xxxx))

Numbers
Latin (ordered by Unicode value (U+xxxx))
Greek (ordered by Unicode value (U+xxxx))
Cyrillic (ordered by Unicode value (U+xxxx))
Hebrew (ordered by Unicode value (U+xxxx))
Arabic (ordered by Unicode value (U+xxxx))

Letters
Latin (ordered by Unicode value (U+xxxx))
Greek (ordered by Unicode value (U+xxxx))
Cyrillic (ordered by Unicode value (U+xxxx))
Hebrew (ordered by Unicode value (U+xxxx))
Arabic (ordered by Unicode value (U+xxxx))

enter image description here


Sorting Rule Sequence vs Observed Order

It's worth noting that there are really two ways of looking at this. Ultimately, what you have are sorting rules that are applied in a certain order, in turn, this produces an observed order. The ordering of older rules becomes nested under the ordering of newer rules. This means that the first rule applied is the last rule observed, while the last rule applied is the first or topmost rule observed.

Sorting Rule Sequence

1.) Sort on Unicode Value (U+xxxx)
2.) Sort on culture/language
3.) Sort on Type (Symbol, Number, Letter)

Observed Order

  • The highest level of grouping is by type in the following order...

    1.) Symbols
    2.) Numbers
    3.) Letters

    Therefore, any symbol from any language comes before any number from any language, while any letter from any language appears after all symbols and numbers.

  • The second level of grouping is by culture/language. The following order seems to apply for this:

    Latin
    Greek
    Cyrillic
    Hebrew
    Arabic

  • The lowest rule observed is Unicode order, so items within a type-language group are ordered by Unicode value (U+xxxx).


Adapted from here: https://superuser.com/a/971721/496260

How to do a scatter plot with empty circles in Python?

In matplotlib 2.0 there is a parameter called fillstyle which allows better control on the way markers are filled. In my case I have used it with errorbars but it works for markers in general http://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.errorbar.html

fillstyle accepts the following values: [‘full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’ | ‘none’]

There are two important things to keep in mind when using fillstyle,

1) If mfc is set to any kind of value it will take priority, hence, if you did set fillstyle to 'none' it would not take effect. So avoid using mfc in conjuntion with fillstyle

2) You might want to control the marker edge width (using markeredgewidth or mew) because if the marker is relatively small and the edge width is thick, the markers will look like filled even though they are not.

Following is an example using errorbars:

myplot.errorbar(x=myXval, y=myYval, yerr=myYerrVal, fmt='o', fillstyle='none', ecolor='blue',  mec='blue')

Print array elements on separate lines in Bash?

You could use a Bash C Style For Loop to do what you want.

my_array=(one two three)

for ((i=0; i < ${#my_array[@]}; i++ )); do echo "${my_array[$i]}"; done
one
two
three

NodeJS: How to get the server's port?

below a simple http server and how to get the listening port

var http = require("http");
             function onRequest(request, response) {
               console.log("Request received.");
               response.writeHead(200, {"Content-Type": "text/plain"});
               response.write("Hello World");
               response.end();
             }

             var server =http.createServer(onRequest).listen(process.env.PORT, function(){
            console.log('Listening on port '); //Listening on port 8888
        });

then get the server port by using :

console.log('Express server started on port %s', server.address().port);

How to know installed Oracle Client is 32 bit or 64 bit?

A simple way to find this out in Windows is to run SQLPlus from your Oracle homes's bin directory and then check Task Manager. If it is a 32-bit version of SQLPlus, you'll see a process on the Processes tab that looks like this:

sqlplus.exe *32

If it is 64-bit, the process will look like this:

sqlplus.exe

Facebook login "given URL not allowed by application configuration"

I was getting this problem while using a tunnel because I:

  1. had the tunnel url:port set in the FB app settings
  2. but was accessing the local server by pointing my browser to "http://localhost:3000"

once i started punching the tunnel url:port into the browser, i was good to go.

i'm using Rails and Facebooker, but might help others just the same.

Using $setValidity inside a Controller

A better and optimised solution to display multiple validation messages for a single element would be like this.

<div ng-messages="myForm.file.$error" ng-show="myForm.file.$touched">
 <span class="error" ng-message="required"> <your message> </span>
 <span class="error" ng-message="size"> <your message> </span>
 <span class="error" ng-message="filetype"> <your message> </span>
</div>

Controller Code should be the one suggested by @ Ben Lesh

initialize a const array in a class initializer in C++

ISO standard C++ doesn't let you do this. If it did, the syntax would probably be:

a::a(void) :
b({2,3})
{
    // other initialization stuff
}

Or something along those lines. From your question it actually sounds like what you want is a constant class (aka static) member that is the array. C++ does let you do this. Like so:

#include <iostream>

class A 
{
public:
    A();
    static const int a[2];
};

const int A::a[2] = {0, 1};

A::A()
{
}

int main (int argc, char * const argv[]) 
{
    std::cout << "A::a => " << A::a[0] << ", " << A::a[1] << "\n";
    return 0;
}

The output being:

A::a => 0, 1

Now of course since this is a static class member it is the same for every instance of class A. If that is not what you want, ie you want each instance of A to have different element values in the array a then you're making the mistake of trying to make the array const to begin with. You should just be doing this:

#include <iostream>

class A 
{
public:
    A();
    int a[2];
};

A::A()
{
    a[0] = 9; // or some calculation
    a[1] = 10; // or some calculation
}

int main (int argc, char * const argv[]) 
{
    A v;
    std::cout << "v.a => " << v.a[0] << ", " << v.a[1] << "\n";
    return 0;
}

Foreign key referencing a 2 columns primary key in SQL Server

The key is "the order of the column should be the same"

Example:

create Table A (
    A_ID char(3) primary key,
    A_name char(10) primary key,
    A_desc desc char(50)
)

create Table B (
    B_ID char(3) primary key,
    B_A_ID char(3),
    B_A_Name char(10),
    constraint [Fk_B_01] foreign key (B_A_ID,B_A_Name) references A(A_ID,A_Name)
)

the column order on table A should be --> A_ID then A_Name; defining the foreign key should follow the same order as well.

How to parse json string in Android?

Below is the link which guide in parsing JSON string in android.

http://www.ibm.com/developerworks/xml/library/x-andbene1/?S_TACT=105AGY82&S_CMP=MAVE

Also according to your json string code snippet must be something like this:-

JSONObject mainObject = new JSONObject(yourstring);

JSONObject universityObject = mainObject.getJSONObject("university");
JSONString name = universityObject.getString("name");  
JSONString url = universityObject.getString("url");

Following is the API reference for JSOnObject: https://developer.android.com/reference/org/json/JSONObject.html#getString(java.lang.String)

Same for other object.

Most efficient method to groupby on an array of objects

Below function allow to groupBy (and sum values - what OP need) of arbitrary fields. In solution we define cmp function to compare two object according to grouped fields. In let w=... we create copy of subset object x fields. In y[sumBy]=+y[sumBy]+(+x[sumBy]) we use '+' to cast string to number.

function groupBy(data, fields, sumBy='Value') {
  let r=[], cmp= (x,y) => fields.reduce((a,b)=> a && x[b]==y[b], true);
  data.forEach(x=> {
    let y=r.find(z=>cmp(x,z));
    let w= [...fields,sumBy].reduce((a,b) => (a[b]=x[b],a), {})
    y ? y[sumBy]=+y[sumBy]+(+x[sumBy]) : r.push(w);
  });
  return r;
}

_x000D_
_x000D_
const d = [ _x000D_
    { Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" },_x000D_
    { Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10" },_x000D_
    { Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15" },_x000D_
    { Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20" },_x000D_
    { Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" },_x000D_
    { Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30" },_x000D_
    { Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: "35" },_x000D_
    { Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: "40" }_x000D_
];_x000D_
_x000D_
_x000D_
_x000D_
function groupBy(data, fields, sumBy='Value') {_x000D_
  let r=[], cmp= (x,y) => fields.reduce((a,b)=> a && x[b]==y[b], true);_x000D_
  data.forEach(x=> {_x000D_
    let y=r.find(z=>cmp(x,z));_x000D_
    let w= [...fields,sumBy].reduce((a,b) => (a[b]=x[b],a), {})_x000D_
    y ? y[sumBy]=+y[sumBy]+(+x[sumBy]) : r.push(w);_x000D_
  });_x000D_
  return r;_x000D_
}_x000D_
_x000D_
_x000D_
// TEST_x000D_
let p=(t,o) => console.log(t, JSON.stringify(o));_x000D_
console.log('GROUP BY:');_x000D_
_x000D_
p('Phase', groupBy(d,['Phase']) );_x000D_
p('Step', groupBy(d,['Step']) );_x000D_
p('Phase-Step', groupBy(d,['Phase', 'Step']) );_x000D_
p('Phase-Task', groupBy(d,['Phase', 'Task']) );_x000D_
p('Step-Task', groupBy(d,['Step', 'Task']) );_x000D_
p('Phase-Step-Task', groupBy(d,['Phase','Step', 'Task']) );
_x000D_
_x000D_
_x000D_

Remove a JSON attribute

The selected answer would work for as long as you know the key itself that you want to delete but if it should be truly dynamic you would need to use the [] notation instead of the dot notation.

For example:

var keyToDelete = "key1";
var myObj = {"test": {"key1": "value", "key2": "value"}}

//that will not work.
delete myObj.test.keyToDelete 

instead you would need to use:

delete myObj.test[keyToDelete];

Substitute the dot notation with [] notation for those values that you want evaluated before being deleted.

Best way to show a loading/progress indicator?

ProgressDialog is deprecated from Android Oreo. Use ProgressBar instead

ProgressDialog progress = new ProgressDialog(this);
progress.setTitle("Loading");
progress.setMessage("Wait while loading...");
progress.setCancelable(false); // disable dismiss by tapping outside of the dialog
progress.show();
// To dismiss the dialog
progress.dismiss();

OR

ProgressDialog.show(this, "Loading", "Wait while loading...");

Read more here.

By the way, Spinner has a different meaning in Android. (It's like the select dropdown in HTML)

Split long commands in multiple lines through Windows batch file

You can break up long lines with the caret ^ as long as you remember that the caret and the newline following it are completely removed. So, if there should be a space where you're breaking the line, include a space. (More on that below.)

Example:

copy file1.txt file2.txt

would be written as:

copy file1.txt^
 file2.txt

PHP passing $_GET in linux command prompt

Sometimes you don't have the option of editing the php file to set $_GET to the parameters passed in, and sometimes you can't or don't want to install php-cgi.

I found this to be the best solution for that case:

php -r '$_GET["key"]="value"; require_once("script.php");' 

This avoids altering your php file and lets you use the plain php command. If you have php-cgi installed, by all means use that, but this is the next best thing. Thought this options was worthy of mention

the -r means run the php code in the string following. you set the $_GET value manually there, and then reference the file you want to run.

Its worth noting you should run this in the right folder, often but not always the folder the php file is in. Requires statements will use the location of your command to resolve relative urls, NOT the location of the file

jQuery multiple events to trigger the same function

You can use bind method to attach function to several events. Just pass the event names and the handler function as in this code:

$('#foo').bind('mouseenter mouseleave', function() {
  $(this).toggleClass('entered');
});

Another option is to use chaining support of jquery api.

How to align an image dead center with bootstrap

You can use margin property with the bootstrap img class.

.name-of-class .img-responsive { margin: 0 auto; }

Parsing time string in Python

datetime.datetime.strptime has problems with timezone parsing. Have a look at the dateutil package:

>>> from dateutil import parser
>>> parser.parse("Tue May 08 15:14:45 +0800 2012")
datetime.datetime(2012, 5, 8, 15, 14, 45, tzinfo=tzoffset(None, 28800))

Styling multi-line conditions in 'if' statements?

Here's what I do, remember that "all" and "any" accepts an iterable, so I just put a long condition in a list and let "all" do the work.

condition = [cond1 == 'val1', cond2 == 'val2', cond3 == 'val3', cond4 == 'val4']

if all(condition):
   do_something

mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in

That query is failing and returning false.

Put this after mysqli_query() to see what's going on.

if (!$check1_res) {
    printf("Error: %s\n", mysqli_error($con));
    exit();
}

For more information:

http://www.php.net/manual/en/mysqli.error.php

Copying from one text file to another using Python

Safe and memory-saving:

with open("out1.txt", "w") as fw, open("in.txt","r") as fr: 
    fw.writelines(l for l in fr if "tests/file/myword" in l)

It doesn't create temporary lists (what readline and [] would do, which is a non-starter if the file is huge), all is done with generator comprehensions, and using with blocks ensure that the files are closed on exit.

Error: EACCES: permission denied, access '/usr/local/lib/node_modules'

For linux / ubuntu if the command

npm install -g <package_name>

npm WARN deprecated [email protected]: Please note that v5.0.1+ of superagent removes User-Agent header by default, therefore you may need to add it yourself (e.g. GitHub blocks requests without a User-Agent header).  This notice will go away with v5.0.2+ once it is released.

npm ERR! path ../lib/node_modules/<package_name>/bin/..

npm ERR! code EACCES

npm ERR! errno -13

npm ERR! syscall symlink

npm ERR! Error: EACCES: permission denied, symlink '../lib/node_modules
/<package_name>/bin/..' -> '/usr/local/bin/<package_name>'

npm ERR!  { [Error: EACCES: permission denied, symlink '../lib/node_modules/<package_name>/bin/..' -> '/usr/local/bin/<package_name>']

npm ERR!   cause:
npm ERR!    { Error: EACCES: permission denied, symlink '../lib/node_modules/<package_name>/bin/..' -> '/usr/local/bin/<package_name>'

npm ERR!      errno: -13,

npm ERR!      code: 'EACCES',

npm ERR!      syscall: 'symlink',

npm ERR!      path: '../lib/node_modules/<package_name>/bin/..',
npm ERR!      dest: '/usr/local/bin/ionic' },

npm ERR!   stack:
npm ERR!    'Error: EACCES: permission denied, symlink \'../lib/node_modules/ionic/bin/ionic\' -> \'/usr/local/bin/ionic\'',

npm ERR!   errno: -13,

npm ERR!   code: 'EACCES',

npm ERR!   syscall: 'symlink',

npm ERR!   path: '../lib/node_modules/<package-name>/bin/<package-name>',

npm ERR!   dest: '/usr/local/bin/<package-name>' }

npm ERR! 

npm ERR! The operation was rejected by your operating system.

npm ERR! It is likely you do not have the permissions to access this file as the current user

npm ERR! 

npm ERR! If you believe this might be a permissions issue, please double-check the

npm ERR! permissions of the file and its containing directories, or try running

npm ERR! the command again as root/Administrator (though this is not recommended).


npm ERR! A complete log of this run can be found in:

npm ERR!     /home/User/.npm/_logs/2019-07-29T01_20_10_566Z-debug.log

Fix : Install with root permissions

sudo npm install <package_name> -g

Python: find position of element in array

There is a built in method for doing this:

numpy.where()

You can find out more about it in the excellent detailed documentation.

dll missing in JDBC

You have to make sure your DLL is in the classpath.

One such way to do so is to put the path to the DLL in PATH environment variable.

Other option is to add it to the VM arguments in the variable LD_LIBRARY_PATH, like this:

java -Djava.library.path=/path/to/my/dll -cp /my/classpath/goes/here MainClass

What is the way of declaring an array in JavaScript?

If you are creating an array whose main feature is it's length, rather than the value of each index, defining an array as var a=Array(length); is appropriate.

eg-

String.prototype.repeat= function(n){
    n= n || 1;
    return Array(n+1).join(this);
}

How to hide Table Row Overflow?

wrap the table in a div with class="container"

div.container {
    width: 100%;
    overflow-x: auto;
}

then

#table_id tr td {
   white-space:nowrap;
}

result

overflow effect

About catching ANY exception

You can but you probably shouldn't:

try:
    do_something()
except:
    print "Caught it!"

However, this will also catch exceptions like KeyboardInterrupt and you usually don't want that, do you? Unless you re-raise the exception right away - see the following example from the docs:

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except IOError as (errno, strerror):
    print "I/O error({0}): {1}".format(errno, strerror)
except ValueError:
    print "Could not convert data to an integer."
except:
    print "Unexpected error:", sys.exc_info()[0]
    raise

Parse JSON String into List<string>

Try this:

using System;
using Newtonsoft.Json;
using System.Collections.Generic;
public class Program
{
    public static void Main()
    {
        List<Man> Men = new List<Man>();

        Man m1 = new Man();
        m1.Number = "+1-9169168158";
        m1.Message = "Hello Bob from 1";
        m1.UniqueCode = "0123";
        m1.State = 0;

        Man m2 = new Man();
        m2.Number = "+1-9296146182";
        m2.Message = "Hello Bob from 2";
        m2.UniqueCode = "0125";
        m2.State = 0;

        Men.AddRange(new Man[] { m1, m2 });

        string result = JsonConvert.SerializeObject(Men);
        Console.WriteLine(result);  

        List<Man> NewMen = JsonConvert.DeserializeObject<List<Man>>(result);
        foreach(Man m in NewMen) Console.WriteLine(m.Message);
    }
}
public class Man
{
    public string Number{get;set;}
    public string Message {get;set;}
    public string UniqueCode {get;set;}
    public int State {get;set;}
}

Why in C++ do we use DWORD rather than unsigned int?

For myself, I would assume unsigned int is platform specific. Integer could be 8 bits, 16 bits, 32 bits or even 64 bits.

DWORD in the other hand, specifies its own size, which is Double Word. Word are 16 bits so DWORD will be known as 32 bit across all platform

invalid types 'int[int]' for array subscript

int myArray[10][10][10];

should be

int myArray[10][10][10][10];

Can I draw rectangle in XML?

Yes you can and here is one I made earlier:

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/listview_background_shape">
    <stroke android:width="2dp" android:color="#ff207d94" />
    <padding android:left="2dp"
        android:top="2dp"
        android:right="2dp"
        android:bottom="2dp" />
    <corners android:radius="5dp" />
    <solid android:color="#ffffffff" />
</shape>

You can create a new XML file inside the drawable folder, and add the above code, then save it as rectangle.xml.

To use it inside a layout you would set the android:background attribute to the new drawable shape. The shape we have defined does not have any dimensions, and therefore will take the dimensions of the View that is defined in the layout.

So putting it all together:

<View
    android:id="@+id/myRectangleView"
    android:layout_width="200dp"
    android:layout_height="50dp"
    android:background="@drawable/rectangle"/>

Finally; you can set this rectangle to be the background of any View, although for ImageViews you would use android:src. This means you could use the rectangle as the background for ListViews, TextViews...etc.

Python handling socket.error: [Errno 104] Connection reset by peer

You can try to add some time.sleep calls to your code.

It seems like the server side limits the amount of requests per timeunit (hour, day, second) as a security issue. You need to guess how many (maybe using another script with a counter?) and adjust your script to not surpass this limit.

In order to avoid your code from crashing, try to catch this error with try .. except around the urllib2 calls.

What is difference between CrudRepository and JpaRepository interfaces in Spring Data JPA?

JpaRepository extends PagingAndSortingRepository which in turn extends CrudRepository.

Their main functions are:

Because of the inheritance mentioned above, JpaRepository will have all the functions of CrudRepository and PagingAndSortingRepository. So if you don't need the repository to have the functions provided by JpaRepository and PagingAndSortingRepository , use CrudRepository.

Remove scrollbars from textarea

For MS IE 10 you'll probably find you need to do the following:

-ms-overflow-style: none

See the following:

https://msdn.microsoft.com/en-us/library/hh771902(v=vs.85).aspx

Adding up BigDecimals using Streams

This post already has a checked answer, but the answer doesn't filter for null values. The correct answer should prevent null values by using the Object::nonNull function as a predicate.

BigDecimal result = invoiceList.stream()
    .map(Invoice::total)
    .filter(Objects::nonNull)
    .filter(i -> (i.getUnit_price() != null) && (i.getQuantity != null))
    .reduce(BigDecimal.ZERO, BigDecimal::add);

This prevents null values from attempting to be summed as we reduce.

AngularJS - Building a dynamic table based on a json

<table class="table table-striped table-condensed table-hover">
    <thead>
    <tr>
        <th ng-repeat="header in headers | filter:headerFilter | orderBy:headerOrder" width="{{header.width}}">{{header.label}}</th>
    </tr>
    </thead>
    <tbody>
    <tr ng-repeat="user in users" ng-class-odd="'trOdd'" ng-class-even="'trEven'" ng-dblclick="rowDoubleClicked(user)">
        <td ng-repeat="(key,val) in user | orderBy:userOrder(key)">{{val}}</td>
    </tr>
    </tbody>
    <tfoot>

    </tfoot>
</table>

refer this https://gist.github.com/ebellinger/4399082

running a command as a super user from a python script

I tried all the solutions, but did not work. Wanted to run long running tasks with Celery but for these I needed to run sudo chown command with subprocess.call().

This is what worked for me:

To add safe environment variables, in command line, type:

export MY_SUDO_PASS="user_password_here"

To test if it's working type:

echo $MY_SUDO_PASS
 > user_password_here

To run it at system startup add it to the end of this file:

nano ~/.bashrc  

#.bashrc
...
existing_content:

  elif [ -f /etc/bash_completion ]; then
    . /etc/bash_completion
  fi
fi
...

export MY_SUDO_PASS="user_password_here"

You can add all your environment variables passwords, usernames, host, etc here later.

If your variables are ready you can run:

To update:

echo $MY_SUDO_PASS | sudo -S apt-get update

Or to install Midnight Commander

echo $MY_SUDO_PASS | sudo -S apt-get install mc

To start Midnight Commander with sudo

echo $MY_SUDO_PASS | sudo -S mc

Or from python shell (or Django/Celery), to change directory ownership recursively:

python
>> import subprocess
>> subprocess.call('echo $MY_SUDO_PASS | sudo -S chown -R username_here /home/username_here/folder_to_change_ownership_recursivley', shell=True)

Hope it helps.

Basic text editor in command prompt?

You can install vim/vi for windows and set windows PATH variable and open it in command line.

git error: failed to push some refs to remote

Well if none of the above answers are working and if you have messed up something with ssh-add lately. Try

ssh-add -D

Execute specified function every X seconds

You can do this easily by adding a Timer to your form (from the designer) and setting it's Tick-function to run your isonline-function.

vertical-align: middle doesn't work

You must wrap your element in a table-cell, within a table using display.

Like this:

<div>
  <span class='twoline'>Two line text</span>
  <span class='float'>Float right</span>
</div>

and

.float {
    display: table-cell;
    vertical-align: middle;
    text-align: right;
}
.twoline {
    width: 50px;
    display: table-cell;
}
div {
    display: table;
    border: solid 1px blue;
    width: 500px;
    height: 100px;
}

Shown here: http://jsfiddle.net/e8ESb/7/

Error - is not marked as serializable

Leaving my specific solution of this for prosperity, as it's a tricky version of this problem:

Type 'System.Linq.Enumerable+WhereSelectArrayIterator[T...] was not marked as serializable

Due to a class with an attribute IEnumerable<int> eg:

[Serializable]
class MySessionData{
    public int ID;
    public IEnumerable<int> RelatedIDs; //This can be an issue
}

Originally the problem instance of MySessionData was set from a non-serializable list:

MySessionData instance = new MySessionData(){ 
    ID = 123,
    RelatedIDs = nonSerizableList.Select<int>(item => item.ID)
};

The cause here is the concrete class that the Select<int>(...) returns, has type data that's not serializable, and you need to copy the id's to a fresh List<int> to resolve it.

RelatedIDs = nonSerizableList.Select<int>(item => item.ID).ToList();

Why isn't textarea an input[type="textarea"]?

Maybe this is going a bit too far back but…

Also, I’d like to suggest that multiline text fields have a different type (e.g. “textarea") than single-line fields ("text"), as they really are different types of things, and imply different issues (semantics) for client-side handling.

Marc Andreessen, 11 October 1993

Creating a JSON response using Django and Python

In View use this:

form.field.errors|striptags

for getting validation messages without html

MySQL: Fastest way to count number of rows

A count(*) statement with a where condition on the primary key returned the row count much faster for me avoiding full table scan.

SELECT COUNT(*) FROM ... WHERE <PRIMARY_KEY> IS NOT NULL;

This was much faster for me than

SELECT COUNT(*) FROM ...

jQuery If DIV Doesn't Have Class "x"

I think the author was looking for:

$(this).not('.selected')

String's Maximum length in Java - calling length() method

apparently it's bound to an int, which is 0x7FFFFFFF (2147483647).

Get type of a generic parameter in Java with reflection

The quick answer the the Question is no you can't, because of Java generic type erasure.

The longer answer would be that if you have created your list like this:

new ArrayList<SpideMan>(){}

Then in this case the generic type is preserved in the generic superclass of the new anonymous class above.

Not that I recommend doing this with lists, but it is a listener implementation:

new Listener<Type>() { public void doSomething(Type t){...}}

And since extrapolating the generic types of super classes and super interfaces change between JVMs, the generic solution is not as straight forward as some answers might suggest.

Here is now I did it.

Python RuntimeWarning: overflow encountered in long scalars

Here's an example which issues the same warning:

import numpy as np
np.seterr(all='warn')
A = np.array([10])
a=A[-1]
a**a

yields

RuntimeWarning: overflow encountered in long_scalars

In the example above it happens because a is of dtype int32, and the maximim value storable in an int32 is 2**31-1. Since 10**10 > 2**32-1, the exponentiation results in a number that is bigger than that which can be stored in an int32.

Note that you can not rely on np.seterr(all='warn') to catch all overflow errors in numpy. For example, on 32-bit NumPy

>>> np.multiply.reduce(np.arange(21)+1)
-1195114496

while on 64-bit NumPy:

>>> np.multiply.reduce(np.arange(21)+1)
-4249290049419214848

Both fail without any warning, although it is also due to an overflow error. The correct answer is that 21! equals

In [47]: import math

In [48]: math.factorial(21)
Out[50]: 51090942171709440000L

According to numpy developer, Robert Kern,

Unlike true floating point errors (where the hardware FPU sets a flag whenever it does an atomic operation that overflows), we need to implement the integer overflow detection ourselves. We do it on the scalars, but not arrays because it would be too slow to implement for every atomic operation on arrays.

So the burden is on you to choose appropriate dtypes so that no operation overflows.

Remove multiple objects with rm()

Another variation you can try is(expanding @mnel's answer) if you have many temp'x'.

here "n" could be the number of temp variables present

rm(list = c(paste("temp",c(1:n),sep="")))

Android - Share on Facebook, Twitter, Mail, ecc

String message = "This is testing."
Intent shareText = new Intent(Intent.ACTION_SEND);
shareText .setType("text/plain");
shareText .putExtra(Intent.EXTRA_TEXT, message);

startActivity(Intent.createChooser(shareText , "Title of the dialog the system will open"));

disabling spring security in spring boot app

security.ignored is deprecated since Spring Boot 2.

For me simply extend the Annotation of your Application class did the Trick:

@SpringBootApplication(exclude = SecurityAutoConfiguration.class)

How to connect to a secure website using SSL in Java with a pkcs12 file?

I cannot comment because of the 50pts threshhold, but I don't think that the answer provided in https://stackoverflow.com/a/537344/1341220 is correct. What you are actually describing is how you insert server certificates into the systems default truststore:

$JAVA_HOME/jre/lib/security/cacerts, password: changeit)

This works, indeed, but it means that you did not really specify a trust store local to your project, but rather accepted the certificate universially in your system.

You actually never use your own truststore that you defined here:

System.setProperty("javax.net.ssl.trustStore", "myTrustStore");
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");

Scale an equation to fit exact page width

The graphicx package provides the command \resizebox{width}{height}{object}:

\documentclass{article}
\usepackage{graphicx}
\begin{document}
\hrule
%%%
\makeatletter%
\setlength{\@tempdima}{\the\columnwidth}% the, well columnwidth
\settowidth{\@tempdimb}{(\ref{Equ:TooLong})}% the width of the "(1)"
\addtolength{\@tempdima}{-\the\@tempdimb}% which cannot be used for the math
\addtolength{\@tempdima}{-1em}%
% There is probably some variable giving the required minimal distance
% between math and label, but because I do not know it I used 1em instead.
\addtolength{\@tempdima}{-1pt}% distance must be greater than "1em"
\xdef\Equ@width{\the\@tempdima}% space remaining for math
\begin{equation}%
\resizebox{\Equ@width}{!}{$\displaystyle{% to get everything inside "big"
 A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z}$}%
\label{Equ:TooLong}%
\end{equation}%
\makeatother%
%%%
\hrule
\end{document}

How do I specify different Layouts in the ASP.NET MVC 3 razor ViewStart file?

You could put a _ViewStart.cshtml file inside the /Views/Public folder which would override the default one in the /Views folder and specify the desired layout:

@{
    Layout = "~/Views/Shared/_PublicLayout.cshtml";
}

By analogy you could put another _ViewStart.cshtml file inside the /Views/Staff folder with:

@{
    Layout = "~/Views/Shared/_StaffLayout.cshtml";
}

You could also specify which layout should be used when returning a view inside a controller action but that's per action:

return View("Index", "~/Views/Shared/_StaffLayout.cshtml", someViewModel);

Yet another possibility is a custom action filter which would override the layout. As you can see many possibilities to achieve this. Up to you to choose which one fits best in your scenario.


UPDATE:

As requested in the comments section here's an example of an action filter which would choose a master page:

public class LayoutInjecterAttribute : ActionFilterAttribute
{
    private readonly string _masterName;
    public LayoutInjecterAttribute(string masterName)
    {
        _masterName = masterName;
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);
        var result = filterContext.Result as ViewResult;
        if (result != null)
        {
            result.MasterName = _masterName;
        }
    }
}

and then decorate a controller or an action with this custom attribute specifying the layout you want:

[LayoutInjecter("_PublicLayout")]
public ActionResult Index()
{
    return View();
}

Java 256-bit AES Password-Based Encryption

After reading through erickson's suggestions, and gleaning what I could from a couple other postings and this example here, I've attempted to update Doug's code with the recommended changes. Feel free to edit to make it better.

  • Initialization Vector is no longer fixed
  • encryption key is derived using code from erickson
  • 8 byte salt is generated in setupEncrypt() using SecureRandom()
  • decryption key is generated from the encryption salt and password
  • decryption cipher is generated from decryption key and initialization vector
  • removed hex twiddling in lieu of org.apache.commons codec Hex routines

Some notes: This uses a 128 bit encryption key - java apparently won't do 256 bit encryption out-of-the-box. Implementing 256 requires installing some extra files into the java install directory.

Also, I'm not a crypto person. Take heed.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.InvalidParameterSpecException;
import java.security.spec.KeySpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

public class Crypto
{
    String mPassword = null;
    public final static int SALT_LEN = 8;
    byte [] mInitVec = null;
    byte [] mSalt = null;
    Cipher mEcipher = null;
    Cipher mDecipher = null;
    private final int KEYLEN_BITS = 128; // see notes below where this is used.
    private final int ITERATIONS = 65536;
    private final int MAX_FILE_BUF = 1024;

    /**
     * create an object with just the passphrase from the user. Don't do anything else yet 
     * @param password
     */
    public Crypto (String password)
    {
        mPassword = password;
    }

    /**
     * return the generated salt for this object
     * @return
     */
    public byte [] getSalt ()
    {
        return (mSalt);
    }

    /**
     * return the initialization vector created from setupEncryption
     * @return
     */
    public byte [] getInitVec ()
    {
        return (mInitVec);
    }

    /**
     * debug/print messages
     * @param msg
     */
    private void Db (String msg)
    {
        System.out.println ("** Crypt ** " + msg);
    }

    /**
     * this must be called after creating the initial Crypto object. It creates a salt of SALT_LEN bytes
     * and generates the salt bytes using secureRandom().  The encryption secret key is created 
     * along with the initialization vectory. The member variable mEcipher is created to be used
     * by the class later on when either creating a CipherOutputStream, or encrypting a buffer
     * to be written to disk.
     *  
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     * @throws NoSuchPaddingException
     * @throws InvalidParameterSpecException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     * @throws UnsupportedEncodingException
     * @throws InvalidKeyException
     */
    public void setupEncrypt () throws NoSuchAlgorithmException, 
                                                           InvalidKeySpecException, 
                                                           NoSuchPaddingException, 
                                                           InvalidParameterSpecException, 
                                                           IllegalBlockSizeException, 
                                                           BadPaddingException, 
                                                           UnsupportedEncodingException, 
                                                           InvalidKeyException
    {
        SecretKeyFactory factory = null;
        SecretKey tmp = null;

        // crate secureRandom salt and store  as member var for later use
         mSalt = new byte [SALT_LEN];
        SecureRandom rnd = new SecureRandom ();
        rnd.nextBytes (mSalt);
        Db ("generated salt :" + Hex.encodeHexString (mSalt));

        factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");

        /* Derive the key, given password and salt. 
         * 
         * in order to do 256 bit crypto, you have to muck with the files for Java's "unlimted security"
         * The end user must also install them (not compiled in) so beware. 
         * see here:  http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml
         */
        KeySpec spec = new PBEKeySpec (mPassword.toCharArray (), mSalt, ITERATIONS, KEYLEN_BITS);
        tmp = factory.generateSecret (spec);
        SecretKey secret = new SecretKeySpec (tmp.getEncoded(), "AES");

        /* Create the Encryption cipher object and store as a member variable
         */
        mEcipher = Cipher.getInstance ("AES/CBC/PKCS5Padding");
        mEcipher.init (Cipher.ENCRYPT_MODE, secret);
        AlgorithmParameters params = mEcipher.getParameters ();

        // get the initialization vectory and store as member var 
        mInitVec = params.getParameterSpec (IvParameterSpec.class).getIV();

        Db ("mInitVec is :" + Hex.encodeHexString (mInitVec));
    }



    /**
     * If a file is being decrypted, we need to know the pasword, the salt and the initialization vector (iv). 
     * We have the password from initializing the class. pass the iv and salt here which is
     * obtained when encrypting the file initially.
     *   
     * @param initvec
     * @param salt
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     * @throws NoSuchPaddingException
     * @throws InvalidKeyException
     * @throws InvalidAlgorithmParameterException
     * @throws DecoderException
     */
    public void setupDecrypt (String initvec, String salt) throws NoSuchAlgorithmException, 
                                                                                       InvalidKeySpecException, 
                                                                                       NoSuchPaddingException, 
                                                                                       InvalidKeyException, 
                                                                                       InvalidAlgorithmParameterException, 
                                                                                       DecoderException
    {
        SecretKeyFactory factory = null;
        SecretKey tmp = null;
        SecretKey secret = null;

        // since we pass it as a string of input, convert to a actual byte buffer here
        mSalt = Hex.decodeHex (salt.toCharArray ());
       Db ("got salt " + Hex.encodeHexString (mSalt));

        // get initialization vector from passed string
        mInitVec = Hex.decodeHex (initvec.toCharArray ());
        Db ("got initvector :" + Hex.encodeHexString (mInitVec));


        /* Derive the key, given password and salt. */
        // in order to do 256 bit crypto, you have to muck with the files for Java's "unlimted security"
        // The end user must also install them (not compiled in) so beware. 
        // see here: 
      // http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml
        factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec spec = new PBEKeySpec(mPassword.toCharArray (), mSalt, ITERATIONS, KEYLEN_BITS);

        tmp = factory.generateSecret(spec);
        secret = new SecretKeySpec(tmp.getEncoded(), "AES");

        /* Decrypt the message, given derived key and initialization vector. */
        mDecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        mDecipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(mInitVec));
    }


    /**
     * This is where we write out the actual encrypted data to disk using the Cipher created in setupEncrypt().
     * Pass two file objects representing the actual input (cleartext) and output file to be encrypted.
     * 
     * there may be a way to write a cleartext header to the encrypted file containing the salt, but I ran
     * into uncertain problems with that. 
     *  
     * @param input - the cleartext file to be encrypted
     * @param output - the encrypted data file
     * @throws IOException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     */
    public void WriteEncryptedFile (File input, File output) throws 
                                                                                          IOException, 
                                                                                          IllegalBlockSizeException, 
                                                                                          BadPaddingException
    {
        FileInputStream fin;
        FileOutputStream fout;
        long totalread = 0;
        int nread = 0;
        byte [] inbuf = new byte [MAX_FILE_BUF];

        fout = new FileOutputStream (output);
        fin = new FileInputStream (input);

        while ((nread = fin.read (inbuf)) > 0 )
        {
            Db ("read " + nread + " bytes");
            totalread += nread;

            // create a buffer to write with the exact number of bytes read. Otherwise a short read fills inbuf with 0x0
            // and results in full blocks of MAX_FILE_BUF being written. 
            byte [] trimbuf = new byte [nread];
            for (int i = 0; i < nread; i++)
                trimbuf[i] = inbuf[i];

            // encrypt the buffer using the cipher obtained previosly
            byte [] tmp = mEcipher.update (trimbuf);

            // I don't think this should happen, but just in case..
            if (tmp != null)
                fout.write (tmp);
        }

        // finalize the encryption since we've done it in blocks of MAX_FILE_BUF
        byte [] finalbuf = mEcipher.doFinal ();
        if (finalbuf != null)
            fout.write (finalbuf);

        fout.flush();
        fin.close();
        fout.close();

        Db ("wrote " + totalread + " encrypted bytes");
    }


    /**
     * Read from the encrypted file (input) and turn the cipher back into cleartext. Write the cleartext buffer back out
     * to disk as (output) File.
     * 
     * I left CipherInputStream in here as a test to see if I could mix it with the update() and final() methods of encrypting
     *  and still have a correctly decrypted file in the end. Seems to work so left it in.
     *  
     * @param input - File object representing encrypted data on disk 
     * @param output - File object of cleartext data to write out after decrypting
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     * @throws IOException
     */
    public void ReadEncryptedFile (File input, File output) throws 
                                                                                                                                            IllegalBlockSizeException, 
                                                                                                                                            BadPaddingException, 
                                                                                                                                            IOException
    {
        FileInputStream fin; 
        FileOutputStream fout;
        CipherInputStream cin;
        long totalread = 0;
        int nread = 0;
        byte [] inbuf = new byte [MAX_FILE_BUF];

        fout = new FileOutputStream (output);
        fin = new FileInputStream (input);

        // creating a decoding stream from the FileInputStream above using the cipher created from setupDecrypt()
        cin = new CipherInputStream (fin, mDecipher);

        while ((nread = cin.read (inbuf)) > 0 )
        {
            Db ("read " + nread + " bytes");
            totalread += nread;

            // create a buffer to write with the exact number of bytes read. Otherwise a short read fills inbuf with 0x0
            byte [] trimbuf = new byte [nread];
            for (int i = 0; i < nread; i++)
                trimbuf[i] = inbuf[i];

            // write out the size-adjusted buffer
            fout.write (trimbuf);
        }

        fout.flush();
        cin.close();
        fin.close ();       
        fout.close();   

        Db ("wrote " + totalread + " encrypted bytes");
    }


    /**
     * adding main() for usage demonstration. With member vars, some of the locals would not be needed
     */
    public static void main(String [] args)
    {

        // create the input.txt file in the current directory before continuing
        File input = new File ("input.txt");
        File eoutput = new File ("encrypted.aes");
        File doutput = new File ("decrypted.txt");
        String iv = null;
        String salt = null;
        Crypto en = new Crypto ("mypassword");

        /*
         * setup encryption cipher using password. print out iv and salt
         */
        try
      {
          en.setupEncrypt ();
          iv = Hex.encodeHexString (en.getInitVec ()).toUpperCase ();
          salt = Hex.encodeHexString (en.getSalt ()).toUpperCase ();
      }
      catch (InvalidKeyException e)
      {
          e.printStackTrace();
      }
      catch (NoSuchAlgorithmException e)
      {
          e.printStackTrace();
      }
      catch (InvalidKeySpecException e)
      {
          e.printStackTrace();
      }
      catch (NoSuchPaddingException e)
      {
          e.printStackTrace();
      }
      catch (InvalidParameterSpecException e)
      {
          e.printStackTrace();
      }
      catch (IllegalBlockSizeException e)
      {
          e.printStackTrace();
      }
      catch (BadPaddingException e)
      {
          e.printStackTrace();
      }
      catch (UnsupportedEncodingException e)
      {
          e.printStackTrace();
      }

        /*
         * write out encrypted file
         */
        try
      {
          en.WriteEncryptedFile (input, eoutput);
          System.out.printf ("File encrypted to " + eoutput.getName () + "\niv:" + iv + "\nsalt:" + salt + "\n\n");
      }
      catch (IllegalBlockSizeException e)
      {
          e.printStackTrace();
      }
      catch (BadPaddingException e)
      {
          e.printStackTrace();
      }
      catch (IOException e)
      {
          e.printStackTrace();
      }


        /*
         * decrypt file
         */
        Crypto dc = new Crypto ("mypassword");
        try
      {
          dc.setupDecrypt (iv, salt);
      }
      catch (InvalidKeyException e)
      {
          e.printStackTrace();
      }
      catch (NoSuchAlgorithmException e)
      {
          e.printStackTrace();
      }
      catch (InvalidKeySpecException e)
      {
          e.printStackTrace();
      }
      catch (NoSuchPaddingException e)
      {
          e.printStackTrace();
      }
      catch (InvalidAlgorithmParameterException e)
      {
          e.printStackTrace();
      }
      catch (DecoderException e)
      {
          e.printStackTrace();
      }

        /*
         * write out decrypted file
         */
        try
      {
          dc.ReadEncryptedFile (eoutput, doutput);
          System.out.println ("decryption finished to " + doutput.getName ());
      }
      catch (IllegalBlockSizeException e)
      {
          e.printStackTrace();
      }
      catch (BadPaddingException e)
      {
          e.printStackTrace();
      }
      catch (IOException e)
      {
          e.printStackTrace();
      }
   }


}

How to pass optional parameters while omitting some other optional parameters?

You can specify multiple method signatures on the interface then have multiple method overloads on the class method:

interface INotificationService {
    error(message: string, title?: string, autoHideAfter?: number);
    error(message: string, autoHideAfter: number);
}

class MyNotificationService implements INotificationService {
    error(message: string, title?: string, autoHideAfter?: number);
    error(message: string, autoHideAfter?: number);
    error(message: string, param1?: (string|number), param2?: number) {
        var autoHideAfter: number,
            title: string;

        // example of mapping the parameters
        if (param2 != null) {
            autoHideAfter = param2;
            title = <string> param1;
        }
        else if (param1 != null) {
            if (typeof param1 === "string") {
                title = param1;
            }
            else {
                autoHideAfter = param1;
            }
        }

        // use message, autoHideAfter, and title here
    }
}

Now all these will work:

var service: INotificationService = new MyNotificationService();
service.error("My message");
service.error("My message", 1000);
service.error("My message", "My title");
service.error("My message", "My title", 1000);

...and the error method of INotificationService will have the following options:

Overload intellisense

Playground

How to Check if value exists in a MySQL database

SELECT
    IF city='C7'
    THEN city
    ELSE 'somethingelse'
    END as `city`
FROM `table` WHERE `city` = 'c7'

Download a file by jQuery.Ajax

I have created little function as workaround solution (inspired by @JohnCulviner plugin):

// creates iframe and form in it with hidden field,
// then submit form with provided data
// url - form url
// data - data to form field
// input_name - form hidden input name

function ajax_download(url, data, input_name) {
    var $iframe,
        iframe_doc,
        iframe_html;

    if (($iframe = $('#download_iframe')).length === 0) {
        $iframe = $("<iframe id='download_iframe'" +
                    " style='display: none' src='about:blank'></iframe>"
                   ).appendTo("body");
    }

    iframe_doc = $iframe[0].contentWindow || $iframe[0].contentDocument;
    if (iframe_doc.document) {
        iframe_doc = iframe_doc.document;
    }

    iframe_html = "<html><head></head><body><form method='POST' action='" +
                  url +"'>" +
                  "<input type=hidden name='" + input_name + "' value='" +
                  JSON.stringify(data) +"'/></form>" +
                  "</body></html>";

    iframe_doc.open();
    iframe_doc.write(iframe_html);
    $(iframe_doc).find('form').submit();
}

Demo with click event:

$('#someid').on('click', function() {
    ajax_download('/download.action', {'para1': 1, 'para2': 2}, 'dataname');
});

Meaning of end='' in the statement print("\t",end='')?

See the documentation for the print function: print()

The content of end is printed after the thing you want to print. By default it contains a newline ("\n") but it can be changed to something else, like an empty string.

Manually adding a Userscript to Google Chrome

Update 2016: seems to be working again.

Update August 2014: No longer works as of recent Chrome versions.


Yeah, the new state of affairs sucks. Fortunately it's not so hard as the other answers imply.

  1. Browse in Chrome to chrome://extensions
  2. Drag the .user.js file into that page.

Voila. You can also drag files from the downloads footer bar to the extensions tab.

Chrome will automatically create a manifest.json file in the extensions directory that Brock documented.

<3 Freedom.

Write lines of text to a file in R

fileConn<-file("output.txt")
writeLines(c("Hello","World"), fileConn)
close(fileConn)

c++ and opencv get and set pixel color to Mat

I would not use .at for performance reasons.

Define a struct:

//#pragma pack(push, 2) //not useful (see comments below)
struct RGB {
    uchar blue;
    uchar green;
    uchar red;  };

And then use it like this on your cv::Mat image:

RGB& rgb = image.ptr<RGB>(y)[x];

image.ptr(y) gives you a pointer to the scanline y. And iterate through the pixels with loops of x and y

get Context in non-Activity class

If your class is non-activity class, and creating an instance of it from the activiy, you can pass an instance of context via constructor of the later as follows:

class YourNonActivityClass{

// variable to hold context
private Context context;

//save the context recievied via constructor in a local variable

public YourNonActivityClass(Context context){
    this.context=context;
}

}

You can create instance of this class from the activity as follows:

new YourNonActivityClass(this);

Easiest way to toggle 2 classes in jQuery

Toggle between two classes 'A' and 'B' with Jquery.

$('#selecor_id').toggleClass("A B");

Regular expression for floating point numbers

[+-]?(([1-9][0-9]*)|(0))([.,][0-9]+)?

[+-]? - optional leading sign

(([1-9][0-9]*)|(0)) - integer without leading zero, including single zero

([.,][0-9]+)? - optional fractional part

Why can't I define a static method in a Java interface?

Why can't I define a static method in a Java interface?

All methods in an interface are explicitly abstract and hence you cannot define them as static because static methods cannot be abstract.

ExecuteReader: Connection property has not been initialized

I like to place all my sql connections in using statements. I think they look cleaner, and they clean up after themselves when your done with them. I also recommend parameterizing every query, not only is it much safer but it is easier to maintain if you need to come back and make changes.

// create/open connection
using (SqlConnection conn = new SqlConnection("Data Source=Si-6\\SQLSERVER2005;Initial Catalog=rags;Integrated Security=SSPI")
{
    try
    {
        conn.Open();

        // initialize command
        using (SqlCommand cmd = conn.CreateCommand())
        {

            // generate query with parameters
            with cmd
            {
                .CommandType = CommandType.Text;
                .CommandText = "insert into time(project,iteration) values(@name, @iteration)";
                .Parameters.Add(new SqlParameter("@name", this.name1.SelectedValue));
                .Parameters.Add(new SqlParameter("@iteration", this.iteration.SelectedValue));
                .ExecuteNonQuery();
            }
        }
    }
    catch (Exception)
    {
        //throw;
    }
    finally
    {
        if (conn != null && conn.State == ConnectionState.Open)
        {
            conn.Close;
        }
    }
}

How do I center floated elements?

I think the best way is using margin instead of display.

I.e.:

.pagination a {
    margin-left: auto;
    margin-right: auto;
    width: 30px;
    height: 30px;    
    background: url(/images/structure/pagination-button.png);
}

Check the result and the code:

http://cssdeck.com/labs/d9d6ydif

Double vs. BigDecimal?

BigDecimal is Oracle's arbitrary-precision numerical library. BigDecimal is part of the Java language and is useful for a variety of applications ranging from the financial to the scientific (that's where sort of am).

There's nothing wrong with using doubles for certain calculations. Suppose, however, you wanted to calculate Math.Pi * Math.Pi / 6, that is, the value of the Riemann Zeta Function for a real argument of two (a project I'm currently working on). Floating-point division presents you with a painful problem of rounding error.

BigDecimal, on the other hand, includes many options for calculating expressions to arbitrary precision. The add, multiply, and divide methods as described in the Oracle documentation below "take the place" of +, *, and / in BigDecimal Java World:

http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html

The compareTo method is especially useful in while and for loops.

Be careful, however, in your use of constructors for BigDecimal. The string constructor is very useful in many cases. For instance, the code

BigDecimal onethird = new BigDecimal("0.33333333333");

utilizes a string representation of 1/3 to represent that infinitely-repeating number to a specified degree of accuracy. The round-off error is most likely somewhere so deep inside the JVM that the round-off errors won't disturb most of your practical calculations. I have, from personal experience, seen round-off creep up, however. The setScale method is important in these regards, as can be seen from the Oracle documentation.

Why can't I find SQL Server Management Studio after installation?

It appears that SQL Server 2008 R2 can be downloaded with or without the management tools. I honestly have NO IDEA why someone would not want the management tools. But either way, the options are here:

http://www.microsoft.com/sqlserver/en/us/editions/express.aspx

and the one for 64 bit WITH the management tools (management studio) is here:

http://www.microsoft.com/sqlserver/en/us/editions/express.aspx

From the first link I presented, the 3rd and 4th include the management studio for 32 and 64 bit respectively.

DB query builder toArray() laravel 4

Please note, the option presented below is apparently no longer supported as of Laravel 5.4 (thanks @Alex).

In Laravel 5.3 and below, there is a method to set the fetch mode for select queries.

In this case, it might be more efficient to do:

DB::connection()->setFetchMode(PDO::FETCH_ASSOC);
$result = DB::table('user')->where('name',=,'Jhon')->get();

That way, you won't waste time creating objects and then converting them back into arrays.

ArrayList initialization equivalent to array initialization

This is how it is done using the fluent interface of the op4j Java library (1.1. was released Dec '10) :-

List<String> names = Op.onListFor("Ryan", "Julie", "Bob").get();

It's a very cool library that saves you a tonne of time.

Possible to extend types in Typescript?

You can also do:

export type UserEvent = Event & { UserId: string; };

Merging two CSV files using Python

When I'm working with csv files, I often use the pandas library. It makes things like this very easy. For example:

import pandas as pd

a = pd.read_csv("filea.csv")
b = pd.read_csv("fileb.csv")
b = b.dropna(axis=1)
merged = a.merge(b, on='title')
merged.to_csv("output.csv", index=False)

Some explanation follows. First, we read in the csv files:

>>> a = pd.read_csv("filea.csv")
>>> b = pd.read_csv("fileb.csv")
>>> a
   title  stage    jan    feb
0   darn  3.001  0.421  0.532
1     ok  2.829  1.036  0.751
2  three  1.115  1.146  2.921
>>> b
   title    mar    apr    may       jun  Unnamed: 5
0   darn  0.631  1.321  0.951    1.7510         NaN
1     ok  1.001  0.247  2.456    0.3216         NaN
2  three  0.285  1.283  0.924  956.0000         NaN

and we see there's an extra column of data (note that the first line of fileb.csv -- title,mar,apr,may,jun, -- has an extra comma at the end). We can get rid of that easily enough:

>>> b = b.dropna(axis=1)
>>> b
   title    mar    apr    may       jun
0   darn  0.631  1.321  0.951    1.7510
1     ok  1.001  0.247  2.456    0.3216
2  three  0.285  1.283  0.924  956.0000

Now we can merge a and b on the title column:

>>> merged = a.merge(b, on='title')
>>> merged
   title  stage    jan    feb    mar    apr    may       jun
0   darn  3.001  0.421  0.532  0.631  1.321  0.951    1.7510
1     ok  2.829  1.036  0.751  1.001  0.247  2.456    0.3216
2  three  1.115  1.146  2.921  0.285  1.283  0.924  956.0000

and finally write this out:

>>> merged.to_csv("output.csv", index=False)

producing:

title,stage,jan,feb,mar,apr,may,jun
darn,3.001,0.421,0.532,0.631,1.321,0.951,1.751
ok,2.829,1.036,0.751,1.001,0.247,2.456,0.3216
three,1.115,1.146,2.921,0.285,1.283,0.924,956.0

How do I trim whitespace from a string?

If you want to trim specified number of spaces from left and right, you could do this:

def remove_outer_spaces(text, num_of_leading, num_of_trailing):
    text = list(text)
    for i in range(num_of_leading):
        if text[i] == " ":
            text[i] = ""
        else:
            break

    for i in range(1, num_of_trailing+1):
        if text[-i] == " ":
            text[-i] = ""
        else:
            break
    return ''.join(text)

txt1 = "   MY name is     "
print(remove_outer_spaces(txt1, 1, 1))  # result is: "  MY name is    "
print(remove_outer_spaces(txt1, 2, 3))  # result is: " MY name is  "
print(remove_outer_spaces(txt1, 6, 8))  # result is: "MY name is"

Convert to binary and keep leading zeros in Python

Use the format() function:

>>> format(14, '#010b')
'0b00001110'

The format() function simply formats the input following the Format Specification mini language. The # makes the format include the 0b prefix, and the 010 size formats the output to fit in 10 characters width, with 0 padding; 2 characters for the 0b prefix, the other 8 for the binary digits.

This is the most compact and direct option.

If you are putting the result in a larger string, use an formatted string literal (3.6+) or use str.format() and put the second argument for the format() function after the colon of the placeholder {:..}:

>>> value = 14
>>> f'The produced output, in binary, is: {value:#010b}'
'The produced output, in binary, is: 0b00001110'
>>> 'The produced output, in binary, is: {:#010b}'.format(value)
'The produced output, in binary, is: 0b00001110'

As it happens, even for just formatting a single value (so without putting the result in a larger string), using a formatted string literal is faster than using format():

>>> import timeit
>>> timeit.timeit("f_(v, '#010b')", "v = 14; f_ = format")  # use a local for performance
0.40298633499332936
>>> timeit.timeit("f'{v:#010b}'", "v = 14")
0.2850222919951193

But I'd use that only if performance in a tight loop matters, as format(...) communicates the intent better.

If you did not want the 0b prefix, simply drop the # and adjust the length of the field:

>>> format(14, '08b')
'00001110'

Error sending json in POST to web API service

I had all my settings covered in the accepted answer. The problem I had was that I was trying to update the Entity Framework entity type "Task" like:

public IHttpActionResult Post(Task task)

What worked for me was to create my own entity "DTOTask" like:

public IHttpActionResult Post(DTOTask task)

The source was not found, but some or all event logs could not be searched

Launch Developer command line "As an Administrator". This account has full access to Security log

ReCaptcha API v2 Styling

Late to the party, but maybe my solution will help somebody.

I haven't found any solution that works on a responsive website when the viewport changes or the layout is fluid.

So I've created a jQuery script for django-cms that is dynamically adapting to a changing viewport. I'm going to update this response as soon as I have the need for a modern variant of it that is more modular and has no jQuery dependency.


html

<div class="g-recaptcha" data-sitekey="{site_key}" data-size={size}> 
</div> 


css

.g-recaptcha { display: none; }

.g-recaptcha.g-recaptcha-initted { 
    display: block; 
    overflow: hidden; 
}

.g-recaptcha.g-recaptcha-initted > * {
    transform-origin: top left;
}


js

window.djangoReCaptcha = {
    list: [],
    setup: function() {
        $('.g-recaptcha').each(function() {
            var $container = $(this);
            var config = $container.data();

            djangoReCaptcha.init($container, config);
        });

        $(window).on('resize orientationchange', function() {
            $(djangoReCaptcha.list).each(function(idx, el) {
                djangoReCaptcha.resize.apply(null, el);
            });
        });
    },
    resize: function($container, captchaSize) {
        scaleFactor = ($container.width() / captchaSize.w);
        $container.find('> *').css({
            transform: 'scale(' + scaleFactor + ')',
            height: (captchaSize.h * scaleFactor) + 'px'
        });
    },
    init: function($container, config) {
        grecaptcha.render($container.get(0), config);

        var captchaSize, scaleFactor;
        var $iframe = $container.find('iframe').eq(0);

        $iframe.on('load', function() {
            $container.addClass('g-recaptcha-initted');
            captchaSize = captchaSize || { w: $iframe.width() - 2, h: $iframe.height() };
            djangoReCaptcha.resize($container, captchaSize);
            djangoReCaptcha.list.push([$container, captchaSize]);
        });
    },
    lateInit: function(config) {
        var $container = $('.g-recaptcha.g-recaptcha-late').eq(0).removeClass('.g-recaptcha-late');
        djangoReCaptcha.init($container, config);
    }
};

window.djangoReCaptchaSetup = window.djangoReCaptcha.setup;

Convert string to title case with JavaScript

here's another solution using css (and javascript, if the text you want to transform is in uppercase):

html

<span id='text'>JOHN SMITH</span>

js

var str = document.getElementById('text').innerHtml;
var return_text = str.toLowerCase();

css

#text{text-transform:capitalize;}

How to set a Header field on POST a form?

In fact a better way to do it to save a cookie on the client side. Then the cookie is automatically sent with every page header for that particular domain.

In node-js, you can set up and use cookies with cookie-parser.

an example:

res.cookie('token', "xyz....", { httpOnly: true });

Now you can access this :

app.get('/',function(req, res){
 var token = req.cookies.token
});

Note that httpOnly:true ensures that the cookie is usually not accessible manually or through javascript and only browser can access it. If you want to send some headers or security tokens with a form post, and not through ajax, in most situation this can be considered a secure way. Although make sure that the data is sent over secure protocol /ssl if you are storing some sensitive user related info which is usually the case.

Git push error pre-receive hook declined

In my case, my team lead to created a repo(repo was empty) and assign me as developer so when I pushed to the code directly to master the error I was facing ! [remote rejected] master -> master (pre-receive hook declined) So how it was fixed that he assigned to me as maintainer so I was able to push the code directly to the master.

Auto generate function documentation in Visual Studio

Make that "three single comment-markers"

In C# it's ///

which as default spits out:

/// <summary>
/// 
/// </summary>
/// <returns></returns>

Here's some tips on editing VS templates.

Linux: copy and create destination dir if it does not exist

This is very late but it may help a rookie somewhere. If you need to 'auto' create folders rsync should be your best friend. rsync /path/to/sourcefile /path/to/tragetdir/thatdoestexist/

What is the difference between "Form Controls" and "ActiveX Control" in Excel 2010?

Google is full of information on this. As Hans Passant said, Form controls are built in to Excel whereas ActiveX controls are loaded separately.

Generally you'll use Forms controls, they're simpler. ActiveX controls allow for more flexible design and should be used when the job just can't be done with a basic Forms control.

Many user's computers by default won't trust ActiveX, and it will be disabled; this sometimes needs to be manually added to the trust center. ActiveX is a microsoft-based technology and, as far as I'm aware, is not supported on the Mac. This is something you'll have to also consider, should you (or anyone you provide a workbook to) decide to use it on a Mac.

Error: No default engine was specified and no extension was provided

If all that's needed is to send html code inline in the code, we can use below

var app = express();
app.get('/test.html', function (req, res) {
   res.header('Content-Type', 'text/html').send("<html>my html code</html>");
});

How can I access iframe elements with Javascript?

If you have the HTML

<form name="formname" .... id="form-first">
    <iframe id="one" src="iframe2.html">
    </iframe>
</form>

and JavaScript

function iframeRef( frameRef ) {
    return frameRef.contentWindow
        ? frameRef.contentWindow.document
        : frameRef.contentDocument
}

var inside = iframeRef( document.getElementById('one') )

inside is now a reference to the document, so you can do getElementsByTagName('textarea') and whatever you like, depending on what's inside the iframe src.

JOptionPane Yes or No window

For better understand how it works!

int n = JOptionPane.showConfirmDialog(null, "Yes No Cancel", "YesNoCancel", JOptionPane.YES_NO_CANCEL_OPTION);
    if(n == 0)
        {
        JOptionPane.showConfirmDialog(null, "You pressed YES\n"+"Pressed value is = "+n);
        }
    else if(n == 1)
        {
        JOptionPane.showConfirmDialog(null, "You pressed NO\n"+"Pressed value is = "+n);
        }
    else if (n == 2)
        {
        JOptionPane.showConfirmDialog(null, "You pressed CANCEL\n"+"Pressed value is = "+n);
        }
    else if (n == -1)
        {
        JOptionPane.showConfirmDialog(null, "You pressed X\n"+"Pressed value is = "+n);
        }

OR

int n = JOptionPane.showConfirmDialog(null, "Yes No Cancel", "YesNoCancel", JOptionPane.YES_NO_CANCEL_OPTION);
    switch (n) {
        case 0:
            JOptionPane.showConfirmDialog(null, "You pressed YES\n"+"Pressed value is = "+n);
            break;
        case 1:
            JOptionPane.showConfirmDialog(null, "You pressed NO\n"+"Pressed value is = "+n);
            break;
        case 2:
            JOptionPane.showConfirmDialog(null, "You pressed CANCEL\n"+"Pressed value is = "+n);
            break;
        case -1:
            JOptionPane.showConfirmDialog(null, "You pressed X\n"+"Pressed value is = "+n);
            break;
        default:
            break;
    }

Spark RDD to DataFrame python

I liked Arun's answer better but there is a tiny problem and I could not comment or edit the answer. sparkContext does not have createDeataFrame, sqlContext does (as Thiago mentioned). So:

from pyspark.sql import SQLContext

# assuming the spark environemnt is set and sc is spark.sparkContext 
sqlContext = SQLContext(sc)
schemaPeople = sqlContext.createDataFrame(RDDName)
schemaPeople.createOrReplaceTempView("RDDName")

jQuery select by attribute using AND and OR operators

First find the condition that occurs in all situations, then filter the special conditions:

$('[myc="blue"]')
    .filter('[myid="1"],[myid="3"]');

org.hibernate.MappingException: Unknown entity: annotations.Users

Add the following code to hibernate.cfg.xml

  <property name="hibernate.c3p0.min_size">5</property>
  <property name="hibernate.c3p0.max_size">20</property>
  <property name="hibernate.c3p0.timeout">300</property>
  <property name="hibernate.c3p0.max_statements">50</property>
  <property name="hibernate.c3p0.idle_test_period">3000</property>

How do I make a PHP form that submits to self?

Your submit button doesn't have a name. Add name="submit" to your submit button.

If you view source on the form in the browser, you'll see how it submits to self - the form's action attribute will contain the name of the current script - therefore when the form submits, it submits to itself. Edit for vanity sake!

SSRS Field Expression to change the background color of the Cell

=IIF(Fields!ADPAction.Value.ToString().ToUpper().Contains("FAIL"),"Red","White")

Also need to convert to upper case for comparision is binary test.

How to get PID by process name?

If your OS is Unix base use this code:

import os
def check_process(name):
    output = []
    cmd = "ps -aef | grep -i '%s' | grep -v 'grep' | awk '{ print $2 }' > /tmp/out"
    os.system(cmd % name)
    with open('/tmp/out', 'r') as f:
        line = f.readline()
        while line:
            output.append(line.strip())
            line = f.readline()
            if line.strip():
                output.append(line.strip())

    return output

Then call it and pass it a process name to get all PIDs.

>>> check_process('firefox')
['499', '621', '623', '630', '11733']

How to fix "containing working copy admin area is missing" in SVN?

First of all checkout the project into your system in a folder. Then remove the .svn folder from conflict project and copy the .svn folder from new checkout folder and paste into your working copy folder. Then problem is solved.

PostgreSQL - fetch the row which has the Max value for a column

I think you've got one major problem here: there's no monotonically increasing "counter" to guarantee that a given row has happened later in time than another. Take this example:

timestamp   lives_remaining   user_id   trans_id
10:00       4                 3         5
10:00       5                 3         6
10:00       3                 3         1
10:00       2                 3         2

You cannot determine from this data which is the most recent entry. Is it the second one or the last one? There is no sort or max() function you can apply to any of this data to give you the correct answer.

Increasing the resolution of the timestamp would be a huge help. Since the database engine serializes requests, with sufficient resolution you can guarantee that no two timestamps will be the same.

Alternatively, use a trans_id that won't roll over for a very, very long time. Having a trans_id that rolls over means you can't tell (for the same timestamp) whether trans_id 6 is more recent than trans_id 1 unless you do some complicated math.

When should you use a class vs a struct in C++?

Structs (PODs, more generally) are handy when you're providing a C-compatible interface with a C++ implementation, since they're portable across language borders and linker formats.

If that's not a concern to you, then I suppose the use of the "struct" instead of "class" is a good communicator of intent (as @ZeroSignal said above). Structs also have more predictable copying semantics, so they're useful for data you intend to write to external media or send across the wire.

Structs are also handy for various metaprogramming tasks, like traits templates that just expose a bunch of dependent typedefs:

template <typename T> struct type_traits {
  typedef T type;
  typedef T::iterator_type iterator_type;
  ...
};

...But that's really just taking advantage of struct's default protection level being public...

How to hide command output in Bash

.SILENT:

Type " .SILENT: " in the beginning of your script without colons.

How does Git handle symbolic links?

"Editor's" note: This post may contain outdated information. Please see comments and this question regarding changes in Git since 1.6.1.

Symlinked directories:

It's important to note what happens when there is a directory which is a soft link. Any Git pull with an update removes the link and makes it a normal directory. This is what I learnt hard way. Some insights here and here.

Example

Before

 ls -l
 lrwxrwxrwx 1 admin adm   29 Sep 30 15:28 src/somedir -> /mnt/somedir

git add/commit/push

It remains the same

After git pull AND some updates found

 drwxrwsr-x 2 admin adm 4096 Oct  2 05:54 src/somedir

How can I concatenate two arrays in Java?

An easy, but inefficient, way to do this (generics not included):

ArrayList baseArray = new ArrayList(Arrays.asList(array1));
baseArray.addAll(Arrays.asList(array2));
String concatenated[] = (String []) baseArray.toArray(new String[baseArray.size()]);

Navigate to another page with a button in angular 2

you can change

    this.router.routeReuseStrategy.shouldReuseRoute = () => false;

at the component level in constructor like bellow

    constructor(private router: Router) {
            this.router.routeReuseStrategy.shouldReuseRoute = () => false; 
}

How do I escape a single quote ( ' ) in JavaScript?

You can escape a ' in JavaScript like \'

Determining Referer in PHP

Using $_SERVER['HTTP_REFERER']

The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.

if (!empty($_SERVER['HTTP_REFERER'])) {
    header("Location: " . $_SERVER['HTTP_REFERER']);
} else {
    header("Location: index.php");
}
exit;

How to wait 5 seconds with jQuery?

The Underscore library also provides a "delay" function:

_.delay(function(msg) { console.log(msg); }, 5000, 'Hello');

opening a window form from another form programmatically

I would do it like this:

var form2 = new Form2();
form2.Show();

and to close current form I would use

this.Hide(); instead of

this.close();

check out this Youtube channel link for easy start-up tutorials you might find it helpful if u are a beginner

Setting the default ssh key location

man ssh gives me this options would could be useful.

-i identity_file Selects a file from which the identity (private key) for RSA or DSA authentication is read. The default is ~/.ssh/identity for protocol version 1, and ~/.ssh/id_rsa and ~/.ssh/id_dsa for pro- tocol version 2. Identity files may also be specified on a per- host basis in the configuration file. It is possible to have multiple -i options (and multiple identities specified in config- uration files).

So you could create an alias in your bash config with something like

alias ssh="ssh -i /path/to/private_key"

I haven't looked into a ssh configuration file, but like the -i option this too could be aliased

-F configfile Specifies an alternative per-user configuration file. If a configuration file is given on the command line, the system-wide configuration file (/etc/ssh/ssh_config) will be ignored. The default for the per-user configuration file is ~/.ssh/config.

Clear data in MySQL table with PHP?

Actually I believe the MySQL optimizer carries out a TRUNCATE when you DELETE all rows.

Python - Extracting and Saving Video Frames

After a lot of research on how to convert frames to video I have created this function hope this helps. We require opencv for this:

import cv2
import numpy as np
import os

def frames_to_video(inputpath,outputpath,fps):
   image_array = []
   files = [f for f in os.listdir(inputpath) if isfile(join(inputpath, f))]
   files.sort(key = lambda x: int(x[5:-4]))
   for i in range(len(files)):
       img = cv2.imread(inputpath + files[i])
       size =  (img.shape[1],img.shape[0])
       img = cv2.resize(img,size)
       image_array.append(img)
   fourcc = cv2.VideoWriter_fourcc('D', 'I', 'V', 'X')
   out = cv2.VideoWriter(outputpath,fourcc, fps, size)
   for i in range(len(image_array)):
       out.write(image_array[i])
   out.release()


inputpath = 'folder path'
outpath =  'video file path/video.mp4'
fps = 29
frames_to_video(inputpath,outpath,fps)

change the value of fps(frames per second),input folder path and output folder path according to your own local locations

How to append in a json file in Python?

json_obj=json.dumps(a_dict, ensure_ascii=False)

Warning message: In `...` : invalid factor level, NA generated

The warning message is because your "Type" variable was made a factor and "lunch" was not a defined level. Use the stringsAsFactors = FALSE flag when making your data frame to force "Type" to be a character.

> fixed <- data.frame("Type" = character(3), "Amount" = numeric(3))
> str(fixed)
'data.frame':   3 obs. of  2 variables:
 $ Type  : Factor w/ 1 level "": NA 1 1
 $ Amount: chr  "100" "0" "0"
> 
> fixed <- data.frame("Type" = character(3), "Amount" = numeric(3),stringsAsFactors=FALSE)
> fixed[1, ] <- c("lunch", 100)
> str(fixed)
'data.frame':   3 obs. of  2 variables:
 $ Type  : chr  "lunch" "" ""
 $ Amount: chr  "100" "0" "0"

JQuery Validate Dropdown list

Easiest way to get it done is by adding required into your select

Select the best option
<br/>

<select name="dd1" id="dd1" required>
<option value="none">None</option>
<option value="o1">option 1</option>
<option value="o2">option 2</option>
<option value="o3">option 3</option>
</select> 

<br/><br/>?

How to stop a setTimeout loop?

Try something like this in case you want to stop the loop from inside the function:

let timer = setInterval(function(){
  // Have some code to do something

  if(/*someStopCondition*/){ 
    clearInterval(timer)
  }
},1000);

You can also wrap this inside a another function, just make sure you have a timer variable and use clearInterval(theTimerVariable) to stop the loop

C# windows application Event: CLR20r3 on application start

.NET has two CLRs 2.0 and 4.0. CLR 2.0 works till .NET framework 3.5. CLR 4.0 works from .NET 4.0 onwards. Its possible that your solution is using a different CLR than your reference assemblies. In your local development environment, you might have both the CLRs and hence you did not faced any problem. However when you moved to deployment environments, they might have a single CLR only and you got this error.

I want to show all tables that have specified column name

SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name,*
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID 
WHERE c.name LIKE '%YOUR_COLUMN%' 
ORDER BY schema_name, table_name;

In depth article by SQL Authority

How to make a vertical line in HTML

You can use hr (horizontal line) tag and than rotate it 90 degree with css below

hr {   
    transform:rotate(90deg);
    -o-transform:rotate(90deg);
    -moz-transform:rotate(90deg);
    -webkit-transform:rotate(90deg);
}

http://jsfiddle.net/haykaghabekyan/0c969bm6/1/

How to write into a file in PHP?

$fp = fopen('lidn.txt', 'w');
fwrite($fp, 'Cats chase');
fwrite($fp, 'mice');
fclose($fp);

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

Using Position Relative/Absolute within a TD?

With regards to your second attempt, did you try using vertical align ? Either

<td valign="bottom">

or with css

vertical-align:bottom

Unable to find valid certification path to requested target - error even after cert imported

Unfortunately - it could be many things - and lots of app servers and other java 'wrappers' are prone to play with properties and their 'own' take on keychains and what not. So it may be looking at something totally different.

Short of truss-ing - I'd try:

java -Djavax.net.debug=all -Djavax.net.ssl.trustStore=trustStore ...

to see if that helps. Instead of 'all' one can also set it to 'ssl', key manager and trust manager - which may help in your case. Setting it to 'help' will list something like below on most platforms.

Regardless - do make sure you fully understand the difference between the keystore (in which you have the private key and cert you prove your own identity with) and the trust store (which determines who you trust) - and the fact that your own identity also has a 'chain' of trust to the root - which is separate from any chain to a root you need to figure out 'who' you trust.

all            turn on all debugging
ssl            turn on ssl debugging

The   following can be used with ssl:
    record       enable per-record tracing
    handshake    print each handshake message
    keygen       print key generation data
    session      print session activity
    defaultctx   print default SSL initialization
    sslctx       print SSLContext tracing
    sessioncache print session cache tracing
    keymanager   print key manager tracing
    trustmanager print trust manager tracing
    pluggability print pluggability tracing

    handshake debugging can be widened with:
    data         hex dump of each handshake message
    verbose      verbose handshake message printing

    record debugging can be widened with:
    plaintext    hex dump of record plaintext
    packet       print raw SSL/TLS packets

Source: # See http://download.oracle.com/javase/1.5.0/docs/guide/security/jsse/JSSERefGuide.html#Debug

cannot find module "lodash"

Be sure to install lodash in the required folder. This is probably your C:\gwsk directory.

If that folder has a package.json file, it is also best to add --save behind the install command.

$ npm install lodash --save

The package.json file holds information about the project, but to keep it simple, it holds your project dependencies.

The save command will add the installed module to the project dependencies.

If the package.json file exists, and if it contains the lodash dependency you could try to remove the node_modules folder and run following command:

$ npm cache clean    
$ npm install

The first command will clean the npm cache. (just to be sure) The second command will install all (missing) dependencies of the project.

Hope this helps you understand the node package manager a little bit more.

Heatmap in matplotlib with pcolor?

This is late, but here is my python implementation of the flowingdata NBA heatmap.

updated:1/4/2014: thanks everyone

# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>

# ------------------------------------------------------------------------
# Filename   : heatmap.py
# Date       : 2013-04-19
# Updated    : 2014-01-04
# Author     : @LotzJoe >> Joe Lotz
# Description: My attempt at reproducing the FlowingData graphic in Python
# Source     : http://flowingdata.com/2010/01/21/how-to-make-a-heatmap-a-quick-and-easy-solution/
#
# Other Links:
#     http://stackoverflow.com/questions/14391959/heatmap-in-matplotlib-with-pcolor
#
# ------------------------------------------------------------------------

import matplotlib.pyplot as plt
import pandas as pd
from urllib2 import urlopen
import numpy as np
%pylab inline

page = urlopen("http://datasets.flowingdata.com/ppg2008.csv")
nba = pd.read_csv(page, index_col=0)

# Normalize data columns
nba_norm = (nba - nba.mean()) / (nba.max() - nba.min())

# Sort data according to Points, lowest to highest
# This was just a design choice made by Yau
# inplace=False (default) ->thanks SO user d1337
nba_sort = nba_norm.sort('PTS', ascending=True)

nba_sort['PTS'].head(10)

# Plot it out
fig, ax = plt.subplots()
heatmap = ax.pcolor(nba_sort, cmap=plt.cm.Blues, alpha=0.8)

# Format
fig = plt.gcf()
fig.set_size_inches(8, 11)

# turn off the frame
ax.set_frame_on(False)

# put the major ticks at the middle of each cell
ax.set_yticks(np.arange(nba_sort.shape[0]) + 0.5, minor=False)
ax.set_xticks(np.arange(nba_sort.shape[1]) + 0.5, minor=False)

# want a more natural, table-like display
ax.invert_yaxis()
ax.xaxis.tick_top()

# Set the labels

# label source:https://en.wikipedia.org/wiki/Basketball_statistics
labels = [
    'Games', 'Minutes', 'Points', 'Field goals made', 'Field goal attempts', 'Field goal percentage', 'Free throws made', 'Free throws attempts', 'Free throws percentage',
    'Three-pointers made', 'Three-point attempt', 'Three-point percentage', 'Offensive rebounds', 'Defensive rebounds', 'Total rebounds', 'Assists', 'Steals', 'Blocks', 'Turnover', 'Personal foul']

# note I could have used nba_sort.columns but made "labels" instead
ax.set_xticklabels(labels, minor=False)
ax.set_yticklabels(nba_sort.index, minor=False)

# rotate the
plt.xticks(rotation=90)

ax.grid(False)

# Turn off all the ticks
ax = plt.gca()

for t in ax.xaxis.get_major_ticks():
    t.tick1On = False
    t.tick2On = False
for t in ax.yaxis.get_major_ticks():
    t.tick1On = False
    t.tick2On = False

The output looks like this: flowingdata-like nba heatmap

There's an ipython notebook with all this code here. I've learned a lot from 'overflow so hopefully someone will find this useful.

Twitter - How to embed native video from someone else's tweet into a New Tweet or a DM

I found a faster way of embedding:

  • Just copy the link.
  • Paste the link and remove the "?s=19" part and add "/video/1"
  • That's it.

Iif equivalent in C#

VB.NET:

If(someBool, "true", "false")

C#

someBool ? "true" : "false";

JavaScript error: "is not a function"

I received this error when I copied a class object using JSON.parse and JSON.stringify() which removed the function like:

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
  // Method
  calcArea() {
    return this.height * this.width;
  }
}

const square = new Rectangle(10, 10);

console.log('area of square: ', square.calcArea());

const squareCopy = JSON.parse(JSON.stringify(square));

// Will throw an exception since calcArea() is no longer function 
console.log('area of square copy: ', squareCopy.calcArea());

What datatype should be used for storing phone numbers in SQL Server 2005?

I'm probably missing the obvious here, but wouldn't a varchar just long enough for your longest expected phone number work well?

If I am missing something obvious, I'd love it if someone would point it out...

Difference between dangling pointer and memory leak

A dangling pointer points to memory that has already been freed. The storage is no longer allocated. Trying to access it might cause a Segmentation fault.

Common way to end up with a dangling pointer:

char *func()
{
   char str[10];
   strcpy(str, "Hello!");
   return str; 
}
//returned pointer points to str which has gone out of scope. 

You are returning an address which was a local variable, which would have gone out of scope by the time control was returned to the calling function. (Undefined behaviour)

Another common dangling pointer example is an access of a memory location via pointer, after free has been explicitly called on that memory.

int *c = malloc(sizeof(int));
free(c);
*c = 3; //writing to freed location!

A memory leak is memory which hasn't been freed, there is no way to access (or free it) now, as there are no ways to get to it anymore. (E.g. a pointer which was the only reference to a memory location dynamically allocated (and not freed) which points somewhere else now.)

void func(){
    char *ch = malloc(10);
}
//ch not valid outside, no way to access malloc-ed memory

Char-ptr ch is a local variable that goes out of scope at the end of the function, leaking the dynamically allocated 10 bytes.

Looping through array and removing items, without breaking for loop

Here is another example for the proper use of splice. This example is about to remove 'attribute' from 'array'.

for (var i = array.length; i--;) {
    if (array[i] === 'attribute') {
        array.splice(i, 1);
    }
}

JSON order mixed up

For those who're using maven, please try com.github.tsohr/json

<!-- https://mvnrepository.com/artifact/com.github.tsohr/json -->
<dependency>
    <groupId>com.github.tsohr</groupId>
    <artifactId>json</artifactId>
    <version>0.0.1</version>
</dependency>

It's forked from JSON-java but switch its map implementation with LinkedHashMap which @lemiorhan noted above.

Python: How to pip install opencv2 with specific version 2.4.9?

python -m pip install opencv-python

which will install opencv based on your current python

.ssh directory not being created

Is there a step missing?

Yes. You need to create the directory:

mkdir ${HOME}/.ssh

Additionally, SSH requires you to set the permissions so that only you (the owner) can access anything in ~/.ssh:

% chmod 700 ~/.ssh

Should the .ssh dir be generated when I use the ssh-keygen command?

No. This command generates an SSH key pair but will fail if it cannot write to the required directory:

% ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/xxx/.ssh/id_rsa): /Users/tmp/does_not_exist
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
open /Users/tmp/does_not_exist failed: No such file or directory.
Saving the key failed: /Users/tmp/does_not_exist.

Once you've created your keys, you should also restrict who can read those key files to just yourself:

% chmod -R go-wrx ~/.ssh/*

Why an inline "background-image" style doesn't work in Chrome 10 and Internet Explorer 8?

u must specify the width and height also

 <section class="bg-solid-light slideContainer strut-slide-0" style="background-image: url(https://accounts.icharts.net/stage/icharts-images/chartbook-images/Chart1457601371484.png); background-repeat: no-repeat;width: 100%;height: 100%;" >

Integrating the ZXing library directly into my Android application

Put

compile 'com.google.zxing:core:2.3.0' 

into your Gradle dependencies. As easy as that. Prior to using Android Studio and Gradle build system.

Printing hexadecimal characters in C

Try something like this:

int main()
{
    printf("%x %x %x %x %x %x %x %x\n",
        0xC0, 0xC0, 0x61, 0x62, 0x63, 0x31, 0x32, 0x33);
}

Which produces this:

$ ./foo 
c0 c0 61 62 63 31 32 33

subsampling every nth entry in a numpy array

You can use numpy's slicing, simply start:stop:step.

>>> xs
array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
>>> xs[1::4]
array([2, 2, 2])

This creates a view of the the original data, so it's constant time. It'll also reflect changes to the original array and keep the whole original array in memory:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2]         # O(1), constant time
>>> b[:] = 0           # modifying the view changes original array
>>> a                  # original array is modified
array([0, 2, 0, 4, 0])

so if either of the above things are a problem, you can make a copy explicitly:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2].copy()  # explicit copy, O(n)
>>> b[:] = 0           # modifying the copy
>>> a                  # original is intact
array([1, 2, 3, 4, 5])

This isn't constant time, but the result isn't tied to the original array. The copy also contiguous in memory, which can make some operations on it faster.