Programs & Examples On #Webdatagrid

How do I use Node.js Crypto to create a HMAC-SHA1 hash?

Documentation for crypto: http://nodejs.org/api/crypto.html

const crypto = require('crypto')

const text = 'I love cupcakes'
const key = 'abcdeg'

crypto.createHmac('sha1', key)
  .update(text)
  .digest('hex')

OS X Terminal UTF-8 issues

Unfortunately, the Preferences dialog is not always very helpful, but by tweaking around you should be able to get everything working.

To be able to type Swedish characters in Terminal, add the following lines to your ~/.inputrc (most likely you must create this file):

set input-meta on
set output-meta on
set convert-meta off

This should do the work both with utf8 and other codings in bash, nano and many other programs. Some programs, like tmux, also depends on the locale. Then, adding for instance export LC_ALL=en_US.UTF-8 to your ~/.profile file should help, but keep in mind that a few (mainly obscure) programs require a standard locale, so if you have trouble running or compiling a program, try going back to LC_ALL=C.

Some references that may be helpful:

How do I get the number of days between two dates in JavaScript?

I had the same issue in Angular. I do the copy because else he will overwrite the first date. Both dates must have time 00:00:00 (obviously)

 /*
* Deze functie gebruiken we om het aantal dagen te bereken van een booking.
* */
$scope.berekenDagen = function ()
{
    $scope.booking.aantalDagen=0;

    /*De loper is gelijk aan de startdag van je reservatie.
     * De copy is nodig anders overschijft angular de booking.van.
     * */
    var loper = angular.copy($scope.booking.van);

    /*Zolang de reservatie beschikbaar is, doorloop de weekdagen van je start tot einddatum.*/
    while (loper < $scope.booking.tot) {
        /*Tel een dag op bij je loper.*/
        loper.setDate(loper.getDate() + 1);
        $scope.booking.aantalDagen++;
    }

    /*Start datum telt natuurlijk ook mee*/
    $scope.booking.aantalDagen++;
    $scope.infomsg +=" aantal dagen: "+$scope.booking.aantalDagen;
};

Automatically plot different colored lines

You could use a colormap such as HSV to generate a set of colors. For example:

cc=hsv(12);
figure; 
hold on;
for i=1:12
    plot([0 1],[0 i],'color',cc(i,:));
end

MATLAB has 13 different named colormaps ('doc colormap' lists them all).

Another option for plotting lines in different colors is to use the LineStyleOrder property; see Defining the Color of Lines for Plotting in the MATLAB documentation for more information.

How can I specify the default JVM arguments for programs I run from eclipse?

Yes, right click the project. Click Run as then Run Configurations. You can change the parameters passed to the JVM in the Arguments tab in the VM Arguments box.

That configuration can then be used as the default when running the project.

How can I use pickle to save a dict?

# Save a dictionary into a pickle file.
import pickle

favorite_color = {"lion": "yellow", "kitty": "red"}  # create a dictionary
pickle.dump(favorite_color, open("save.p", "wb"))  # save it into a file named save.p

# -------------------------------------------------------------
# Load the dictionary back from the pickle file.
import pickle

favorite_color = pickle.load(open("save.p", "rb"))
# favorite_color is now {"lion": "yellow", "kitty": "red"}

How to tell if string starts with a number with Python?

Try this:

if string[0] in range(10):

How do I remove lines between ListViews on Android?

There are different ways to achieve this, but I'm not sure which one is the best (I don't even know is there is a best way). I know at least two different ways to do this in a ListView:

1. Set divider to null:

1.1. Programmatically

yourListView.setDivider(null);

1.2. XML

This goes inside your ListView element.

android:divider="@null"

2. Set divider to transparent and set its height to 0 to avoid adding space between listview elements:

2.1. Programmatically:

yourListView.setDivider(new ColorDrawable(android.R.color.transparent));
yourListView.setDividerHeight(0);

2.2. XML

android:divider="@android:color/transparent"
android:dividerHeight="0dp"

OwinStartup not firing

In case you have multiple hosts using the same namespace in your solution, be sure to have them on a separate IISExpress port (and delete the .vs folder and restart vs).

Is it safe to expose Firebase apiKey to the public?

After reading this and after I did some research about the possibilities, I came up with a slightly different approach to restrict data usage by unauthorised users:

I save my users in my DB too (and save the profile data in there). So i just set the db rules like this:

".read": "auth != null && root.child('/userdata/'+auth.uid+'/userRole').exists()",
".write": "auth != null && root.child('/userdata/'+auth.uid+'/userRole').exists()"

This way only a previous saved user can add new users in the DB so there is no way anyone without an account can do operations on DB. also adding new users is posible only if the user has a special role and edit only by admin or by that user itself (something like this):

"userdata": {
  "$userId": {
    ".write": "$userId === auth.uid || root.child('/userdata/'+auth.uid+'/userRole').val() === 'superadmin'",
   ...

Get an object's class name at runtime

The full TypeScript code

public getClassName() {
    var funcNameRegex = /function (.{1,})\(/;
    var results  = (funcNameRegex).exec(this["constructor"].toString());
    return (results && results.length > 1) ? results[1] : "";
}

google maps v3 marker info window on mouseover

Here's an example: http://duncan99.wordpress.com/2011/10/08/google-maps-api-infowindows/

marker.addListener('mouseover', function() {
    infowindow.open(map, this);
});

// assuming you also want to hide the infowindow when user mouses-out
marker.addListener('mouseout', function() {
    infowindow.close();
});

Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

In my case ; what solved my issue was.....

You may had json like this, the keys without " double quotations....

{ name: "test", phone: "2324234" }

So try any online Json Validator to make sure you have right syntax...

Json Validator Online

Create Carriage Return in PHP String?

I find the adding <br> does what is wanted.

Confusing error in R: Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings, : line 1 did not have 42 elements)

read.table wants to return a data.frame, which must have an element in each column. Therefore R expects each row to have the same number of elements and it doesn't fill in empty spaces by default. Try read.table("/PathTo/file.csv" , fill = TRUE ) to fill in the blanks.

e.g.

read.table( text= "Element1 Element2
Element5 Element6 Element7" , fill = TRUE , header = FALSE )
#        V1       V2       V3
#1 Element1 Element2         
#2 Element5 Element6 Element7

A note on whether or not to set header = FALSE... read.table tries to automatically determine if you have a header row thus:

header is set to TRUE if and only if the first row contains one fewer field than the number of columns

Ajax LARAVEL 419 POST error

You may also get that error when CSRF "token" for the active user session is out of date, even if the token was specified in ajax request.

Is it possible to declare a public variable in vba and assign a default value?

As told above, To declare global accessible variables you can do it outside functions preceded with the public keyword.

And, since the affectation is NOT PERMITTED outside the procedures, you can, for example, create a sub called InitGlobals that initializes your public variables, then you just call this subroutine at the beginning of your statements

Here is an example of it:

Public Coordinates(3) as Double
Public Heat as double
Public Weight as double

Sub InitGlobals()
    Coordinates(1)=10.5
    Coordinates(2)=22.54
    Coordinates(3)=-100.5
    Heat=25.5
    Weight=70
End Sub

Sub MyWorkSGoesHere()
    Call InitGlobals
    'Now you can do your work using your global variables initialized as you wanted them to be.
End Sub

`React/RCTBridgeModule.h` file not found

This error appeared for me after I ran pod install command for the new dependencies. Along with those, React had also been installed. Therefore probably Xcode was confused for path. I removed these lines from PodFile and error was gone. Please note that those removed from here were already linked in Xcode.

target 'app' do

  pod 'GoogleMaps'
  pod 'Firebase/Auth', '~> 6.3.0'
  pod 'Firebase/Database', '~> 6.3.0'

  # Removed four pods below and it worked.

  pod 'react-native-image-picker', :path => '../node_modules/react-native-image-picker'

  pod 'ReactNativePermissions', :path => '../node_modules/react-native-permissions'

  pod 'react-native-image-resizer', :path => '../node_modules/react-native-image-resizer'

  pod 'RNFS', :path => '../node_modules/react-native-fs'

  end

JQuery datepicker language

A quick Update, for the text "Today", the right names are:

todayText: 'Huidige', todayStatus: 'Bekijk de huidige maand',

How to POST JSON Data With PHP cURL?

$url = 'url_to_post';
$data = array("first_name" => "First name","last_name" => "last name","email"=>"[email protected]","addresses" => array ("address1" => "some address" ,"city" => "city","country" => "CA", "first_name" =>  "Mother","last_name" =>  "Lastnameson","phone" => "555-1212", "province" => "ON", "zip" => "123 ABC" ) );

$postdata = json_encode($data);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
curl_close($ch);
print_r ($result);

This code worked for me. You can try...

Download the Android SDK components for offline install

Here is how I figured it out. I am behind corporate firewall too.

Go to Chrome or your Internet Settings by clicking the wrench in Chrome --> Settings --> Under the Hood --> Network --> Change Proxy Settings

Click on LAN Settings and then Advanced. Copy the proxy server address and port.

Mostly the connection refused link occurs when trying to download SDK packages through Eclipse.

Navigate to the SDK Manager.exe and double click on it. Once it starts click on Tools --> Options and then enter the proxy server address and the Port #

Check the checkbox force https:// to http:// That's it your SDK Manager will now be able to download packages from google remote site without any issue even from behind a firewall.

I am on Windows by the way. Tried everything and this works great.

How to validate white spaces/empty spaces? [Angular 2]

If you are using Angular Reactive Forms you can create a file with a function - a validator. This will not allow only spaces to be entered.

import { AbstractControl } from '@angular/forms';
export function removeSpaces(control: AbstractControl) {
  if (control && control.value && !control.value.replace(/\s/g, '').length) {
    control.setValue('');
  }
  return null;
}

and then in your component typescript file use the validator like this for example.

this.formGroup = this.fb.group({
  name: [null, [Validators.required, removeSpaces]]
});

Compress images on client side before uploading

I read about an experiment here: http://webreflection.blogspot.com/2010/12/100-client-side-image-resizing.html

The theory is that you can use canvas to resize the images on the client before uploading. The prototype example seems to work only in recent browsers, interesting idea though...

However, I’m not sure about using canvas to compress images, but you can certainly resize them.

How to directly execute SQL query in C#?

To execute your command directly from within C#, you would use the SqlCommand class.

Quick sample code using paramaterized SQL (to avoid injection attacks) might look like this:

string queryString = "SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName, tPatDBirthday  FROM  [dbo].[TPatientRaw] WHERE tPatSName = @tPatSName";
string connectionString = "Server=.\PDATA_SQLEXPRESS;Database=;User Id=sa;Password=2BeChanged!;";

using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand command = new SqlCommand(queryString, connection);
    command.Parameters.AddWithValue("@tPatSName", "Your-Parm-Value");
    connection.Open();
    SqlDataReader reader = command.ExecuteReader();
    try
    {
        while (reader.Read())
        {
            Console.WriteLine(String.Format("{0}, {1}",
            reader["tPatCulIntPatIDPk"], reader["tPatSFirstname"]));// etc
        }
    }
    finally
    {
        // Always call Close when done reading.
        reader.Close();
    }
}

Multiple input in JOptionPane.showInputDialog

this is my solution

JTextField username = new JTextField();
JTextField password = new JPasswordField();
Object[] message = {
    "Username:", username,
    "Password:", password
};

int option = JOptionPane.showConfirmDialog(null, message, "Login", JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION) {
    if (username.getText().equals("h") && password.getText().equals("h")) {
        System.out.println("Login successful");
    } else {
        System.out.println("login failed");
    }
} else {
    System.out.println("Login canceled");
}

Download file from an ASP.NET Web API method using AngularJS

For me the Web API was Rails and client side Angular used with Restangular and FileSaver.js

Web API

module Api
  module V1
    class DownloadsController < BaseController

      def show
        @download = Download.find(params[:id])
        send_data @download.blob_data
      end
    end
  end
end

HTML

 <a ng-click="download('foo')">download presentation</a>

Angular controller

 $scope.download = function(type) {
    return Download.get(type);
  };

Angular Service

'use strict';

app.service('Download', function Download(Restangular) {

  this.get = function(id) {
    return Restangular.one('api/v1/downloads', id).withHttpConfig({responseType: 'arraybuffer'}).get().then(function(data){
      console.log(data)
      var blob = new Blob([data], {
        type: "application/pdf"
      });
      //saveAs provided by FileSaver.js
      saveAs(blob, id + '.pdf');
    })
  }
});

Determine what user created objects in SQL Server

If each user has its own SQL Server login you could try this

select 
    so.name, su.name, so.crdate 
from 
    sysobjects so 
join 
    sysusers su on so.uid = su.uid  
order by 
    so.crdate

Regex match entire words only

Get all "words" in a string

/([^\s]+)/g

Basically ^/s means break on spaces (or match groups of non-spaces)
Don't forget the g for Greedy

How to concatenate strings of a string field in a PostgreSQL 'group by' query?

As already mentioned, creating your own aggregate function is the right thing to do. Here is my concatenation aggregate function (you can find details in French):

CREATE OR REPLACE FUNCTION concat2(text, text) RETURNS text AS '
    SELECT CASE WHEN $1 IS NULL OR $1 = \'\' THEN $2
            WHEN $2 IS NULL OR $2 = \'\' THEN $1
            ELSE $1 || \' / \' || $2
            END; 
'
 LANGUAGE SQL;

CREATE AGGREGATE concatenate (
  sfunc = concat2,
  basetype = text,
  stype = text,
  initcond = ''

);

And then use it as:

SELECT company_id, concatenate(employee) AS employees FROM ...

How to escape double quotes in a title attribute

Here's a snippet of the HTML escape characters taken from a cached page on archive.org:

&#060   |   <   less than sign
&#064   |   @   at sign
&#093   |   ]   right bracket
&#123   |   {   left curly brace
&#125   |   }   right curly brace
&#133   |   …   ellipsis
&#135   |   ‡   double dagger
&#146   |   ’   right single quote
&#148   |   ”   right double quote
&#150   |   –   short dash
&#153   |   ™   trademark
&#162   |   ¢   cent sign
&#165   |   ¥   yen sign
&#169   |   ©   copyright sign
&#172   |   ¬   logical not sign
&#176   |   °   degree sign
&#178   |   ²   superscript 2
&#185   |   ¹   superscript 1
&#188   |   ¼   fraction 1/4
&#190   |   ¾   fraction 3/4
&#247   |   ÷   division sign
&#8221  |   ”   right double quote
&#062   |   >   greater than sign
&#091   |   [   left bracket
&#096   |   `   back apostrophe
&#124   |   |   vertical bar
&#126   |   ~   tilde
&#134   |   †   dagger
&#145   |   ‘   left single quote
&#147   |   “   left double quote
&#149   |   •   bullet
&#151   |   —   longer dash
&#161   |   ¡   inverted exclamation point
&#163   |   £   pound sign
&#166   |   ¦   broken vertical bar
&#171   |   «   double left than sign
&#174   |   ®   registered trademark sign
&#177   |   ±   plus or minus sign
&#179   |   ³   superscript 3
&#187   |   »   double greater-than sign
&#189   |   ½   fraction 1/2
&#191   |   ¿   inverted question mark
&#8220  |   “   left double quote
&#8212  |   —   dash

Working Copy Locked

Is your BitLocker disk encryption running? In my case, it locked the whole drive of the disk for encryption, and SVN failed with this error.

What is callback in Android?

It was discussed before here.

In computer programming, a callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time. The invocation may be immediate as in a synchronous callback or it might happen at later time, as in an asynchronous callback.

IF...THEN...ELSE using XML

I think that the thing you must keep in mind is that your XML is being processed by a machine, not a human, so it only needs to be readable for the machine.

In other words, I think you should use whatever XML schema you need to make parsing/processing the rules as efficient as possible at run time.

As far as your current schema goes, I think that the id attribute should be unique per element, so perhaps you should use a different attribute to capture the relationship among your IF, THEN, and ELSE elements.

How to decode HTML entities using jQuery?

I think that is the exact opposite of the solution chosen.

var decoded = $("<div/>").text(encodedStr).html();

Cannot read property 'style' of undefined -- Uncaught Type Error

It's currently working, I've just changed the operator > in order to work in the snippet, take a look:

_x000D_
_x000D_
window.onload = function() {_x000D_
_x000D_
  if (window.location.href.indexOf("test") <= -1) {_x000D_
    var search_span = document.getElementsByClassName("securitySearchQuery");_x000D_
    search_span[0].style.color = "blue";_x000D_
    search_span[0].style.fontWeight = "bold";_x000D_
    search_span[0].style.fontSize = "40px";_x000D_
_x000D_
  }_x000D_
_x000D_
}
_x000D_
<h1 class="keyword-title">Search results for<span class="securitySearchQuery"> "hi".</span></h1>
_x000D_
_x000D_
_x000D_

Delete rows with foreign key in PostgreSQL

One should not recommend this as a general solution, but for one-off deletion of rows in a database that is not in production or in active use, you may be able to temporarily disable triggers on the tables in question.

In my case, I'm in development mode and have a couple of tables that reference one another via foreign keys. Thus, deleting their contents isn't quite as simple as removing all of the rows from one table before the other. So, for me, it worked fine to delete their contents as follows:

ALTER TABLE table1 DISABLE TRIGGER ALL;
ALTER TABLE table2 DISABLE TRIGGER ALL;
DELETE FROM table1;
DELETE FROM table2;
ALTER TABLE table1 ENABLE TRIGGER ALL;
ALTER TABLE table2 ENABLE TRIGGER ALL;

You should be able to add WHERE clauses as desired, of course with care to avoid undermining the integrity of the database.

There's some good, related discussion at http://www.openscope.net/2012/08/23/subverting-foreign-key-constraints-in-postgres-or-mysql/

Android Device not recognized by adb

It may sound silly but in my case the USB cable was too long (even if good quality). It worked with my tablet but not with the phone. To check this, if you run on Linux run lsusb to make sure that your device is at least officially connect to the usb port.

Sort Java Collection

Use sort.

You just have to do this:

All elements in the list must implement the Comparable interface.

(Or use the version below it, as others already said.)

ImportError: No module named 'encodings'

Because this is the first result in google I just want to add the following information for anybody else having problems with jails:

Could not find platform independent libraries <prefix>
Could not find platform dependent libraries <exec_prefix>
Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ModuleNotFoundError: No module named 'encodings'

Current thread 0x00007f079b16d740 (most recent call first):
Aborted (core dumped)

When attempting to import python into your jail you both need to link the dependencies and /usr/lib/pythonX.Y to [JAIL]/usr/lib/. Hope this helps.

Why does PEP-8 specify a maximum line length of 79 characters?

Since whitespace has semantic meaning in Python, some methods of word wrapping could produce incorrect or ambiguous results, so there needs to be some limit to avoid those situations. An 80 character line length has been standard since we were using teletypes, so 79 characters seems like a pretty safe choice.

How to dynamically build a JSON object with Python?

There is already a solution provided which allows building a dictionary, (or nested dictionary for more complex data), but if you wish to build an object, then perhaps try 'ObjDict'. This gives much more control over the json to be created, for example retaining order, and allows building as an object which may be a preferred representation of your concept.

pip install objdict first.

from objdict import ObjDict

data = ObjDict()
data.key = 'value'
json_data = data.dumps()

Variable declaration in a header file

You should declare the variable in a header file:

extern int x;

and then define it in one C file:

int x;

In C, the difference between a definition and a declaration is that the definition reserves space for the variable, whereas the declaration merely introduces the variable into the symbol table (and will cause the linker to go looking for it when it comes to link time).

WordPress - Check if user is logged in

This problem is from the lazy update data request of Chrome. At the first time you go to homepage. Chrome request with empty data. Then you go to the login page and logged in. When you back home page Chrome lazy to update the cookie data request because this domain is the same with the first time you access. Solution: Add parameter for home url. That helps Chrome realizes that this request need to update cookie to call to the server.

add at dashboard page

<?php 
$track = '?track='.uniqid();
?>
<a href="<?= get_home_url(). $track ?>"> <img src="/img/logo.svg"></a>

Mixed mode assembly is built against version ‘v2.0.50727' of the runtime

Enabling the legacy from app.config didn't work for me. For unknown reasons, my application wasn't activating V2 runtime policy. I found a work around here.

Enabling the legacy from app.config is a recommended approach but in some cases it doesn't work as expected. Use the following code with in your main application to force Legacy V2 policy:

public static class RuntimePolicyHelper
{
public static bool LegacyV2RuntimeEnabledSuccessfully { get; private set; }

static RuntimePolicyHelper()
{
    ICLRRuntimeInfo clrRuntimeInfo =
        (ICLRRuntimeInfo)RuntimeEnvironment.GetRuntimeInterfaceAsObject(
            Guid.Empty, 
            typeof(ICLRRuntimeInfo).GUID);
    try
    {
        clrRuntimeInfo.BindAsLegacyV2Runtime();
        LegacyV2RuntimeEnabledSuccessfully = true;
    }
    catch (COMException)
    {
        // This occurs with an HRESULT meaning 
        // "A different runtime was already bound to the legacy CLR version 2 activation policy."
        LegacyV2RuntimeEnabledSuccessfully = false;
    }
}

[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("BD39D1D2-BA2F-486A-89B0-B4B0CB466891")]
private interface ICLRRuntimeInfo
{
    void xGetVersionString();
    void xGetRuntimeDirectory();
    void xIsLoaded();
    void xIsLoadable();
    void xLoadErrorString();
    void xLoadLibrary();
    void xGetProcAddress();
    void xGetInterface();
    void xSetDefaultStartupFlags();
    void xGetDefaultStartupFlags();

    [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
    void BindAsLegacyV2Runtime();
}
}

Pure CSS to make font-size responsive based on dynamic amount of characters

calc(42px + (60 - 42) * (100vw - 768px) / (1440 - 768));

use this equation.

For anything larger or smaller than 1440 and 768, you can either give it a static value, or apply the same approach.

The drawback with vw solution is that you cannot set a scale ratio, say a 5vw at screen resolution 1440 may ended up being 60px font-size, your idea font size, but when you shrink the window width down to 768, it may ended up being 12px, not the minimal you want. With this approach, you can set your upper boundary and lower boundary, and the font will scale itself in between.

How to cast Object to its actual type?

Implement an interface to call your function in your method
interface IMyInterface
{
 void MyinterfaceMethod();
}

IMyInterface MyObj = obj as IMyInterface;
if ( MyObj != null)
{
MyMethod(IMyInterface MyObj );
}

Rename multiple files in a folder, add a prefix (Windows)

Based on @ofer.sheffer answer, this is the CMD variant for adding an affix (this is not the question, but this page is still the #1 google result if you search affix). It is a bit different because of the extension.

for %a in (*.*) do ren "%~a" "%~na-affix%~xa"

You can change the "-affix" part.

R solve:system is exactly singular

I guess your code uses somewhere in the second case a singular matrix (i.e. not invertible), and the solve function needs to invert it. This has nothing to do with the size but with the fact that some of your vectors are (probably) colinear.

Forward request headers from nginx proxy server

If you want to pass the variable to your proxy backend, you have to set it with the proxy module.

location / {
    proxy_pass                      http://example.com;
    proxy_set_header                Host example.com;
    proxy_set_header                HTTP_Country-Code $geoip_country_code;
    proxy_pass_request_headers      on;
}

And now it's passed to the proxy backend.

In Java, how do I get the difference in seconds between 2 dates?

Just a pointer: If you're calculating the difference between two java.util.Date the approach of subtracting both dates and dividing it by 1000 is reasonable, but take special care if you get your java.util.Date reference from a Calendar object. If you do so, you need to take account of daylight savings of your TimeZone since one of the dates you're using might take place on a DST period.

That is explained on Prasoon's link, I recommend taking some time to read it.

How to horizontally align ul to center of div?

ul {
width: 90%; 
    list-style-type:none;
    margin:auto;
    padding:0;
    position:relative;
    left:5%;
}

Reading data from DataGridView in C#

string[,] myGridData = new string[dataGridView1.Rows.Count,3];

int i = 0;

foreach(DataRow row in dataGridView1.Rows)

{

    myGridData[i][0] = row.Cells[0].Value.ToString();
    myGridData[i][1] = row.Cells[1].Value.ToString();
    myGridData[i][2] = row.Cells[2].Value.ToString();

    i++;
}

Hope this helps....

Python - round up to the nearest ten

round does take negative ndigits parameter!

>>> round(46,-1)
50

may solve your case.

how to create a list of lists

First of all do not use list as a variable name- that is a builtin function.

I'm not super clear of what you're asking (a little more context would help), but maybe this is helpful-

my_list = []
my_list.append(np.genfromtxt('temp.txt', usecols=3, dtype=[('floatname','float')], skip_header=1))
my_list.append(np.genfromtxt('temp2.txt', usecols=3, dtype=[('floatname','float')], skip_header=1))

That will create a list (a type of mutable array in python) called my_list with the output of the np.getfromtext() method in the first 2 indexes.

The first can be referenced with my_list[0] and the second with my_list[1]

Count with IF condition in MySQL query

This should work:

count(if(ccc_news_comments.id = 'approved', ccc_news_comments.id, NULL))

count() only check if the value exists or not. 0 is equivalent to an existent value, so it counts one more, while NULL is like a non-existent value, so is not counted.

What is the difference between Jupyter Notebook and JupyterLab?

(I am using JupyterLab with Julia)

First thing is that Jupyter lab from my previous use offers more 'themes' which is great on the eyes, and also fontsize changes independent of the browser, so that makes it closer to that of an IDE. There are some specifics I like such as changing the 'code font size' and leaving the interface font size to be the same.

Major features that are great is

  • the drag and drop of cells so that you can easily rearrange the code
  • collapsing cells with a single mouse click and a small mark to remind of their placement

What is paramount though is the ability to have split views of the tabs and the terminal. If you use Emacs, then you probably enjoyed having multiple buffers with horizontal and vertical arrangements with one of them running a shell (terminal), and with jupyterlab this can be done, and the arrangement is made with drags and drops which in Emacs is typically done with sets of commands.

(I do not believe that there is a learning curve added to those that have not used the 'notebook' original version first. You can dive straight into this IDE experience)

What is the Difference Between read() and recv() , and Between send() and write()?

The difference is that recv()/send() work only on socket descriptors and let you specify certain options for the actual operation. Those functions are slightly more specialized (for instance, you can set a flag to ignore SIGPIPE, or to send out-of-band messages...).

Functions read()/write() are the universal file descriptor functions working on all descriptors.

INSERT IF NOT EXISTS ELSE UPDATE?

You need to set a constraint on the table to trigger a "conflict" which you then resolve by doing a replace:

CREATE TABLE data   (id INTEGER PRIMARY KEY, event_id INTEGER, track_id INTEGER, value REAL);
CREATE UNIQUE INDEX data_idx ON data(event_id, track_id);

Then you can issue:

INSERT OR REPLACE INTO data VALUES (NULL, 1, 2, 3);
INSERT OR REPLACE INTO data VALUES (NULL, 2, 2, 3);
INSERT OR REPLACE INTO data VALUES (NULL, 1, 2, 5);

The "SELECT * FROM data" will give you:

2|2|2|3.0
3|1|2|5.0

Note that the data.id is "3" and not "1" because REPLACE does a DELETE and INSERT, not an UPDATE. This also means that you must ensure that you define all necessary columns or you will get unexpected NULL values.

How can I pass a Bitmap object from one activity to another

Compress and Send Bitmap

The accepted answer will crash when the Bitmap is too large. I believe it's a 1MB limit. The Bitmap must be compressed into a different file format such as a JPG represented by a ByteArray, then it can be safely passed via an Intent.

Implementation

The function is contained in a separate thread using Kotlin Coroutines because the Bitmap compression is chained after the Bitmap is created from an url String. The Bitmap creation requires a separate thread in order to avoid Application Not Responding (ANR) errors.

Concepts Used

  • Kotlin Coroutines notes.
  • The Loading, Content, Error (LCE) pattern is used below. If interested you can learn more about it in this talk and video.
  • LiveData is used to return the data. I've compiled my favorite LiveData resource in these notes.
  • In Step 3, toBitmap() is a Kotlin extension function requiring that library to be added to the app dependencies.

Code

1. Compress Bitmap to JPG ByteArray after it has been created.

Repository.kt

suspend fun bitmapToByteArray(url: String) = withContext(Dispatchers.IO) {
    MutableLiveData<Lce<ContentResult.ContentBitmap>>().apply {
        postValue(Lce.Loading())
        postValue(Lce.Content(ContentResult.ContentBitmap(
            ByteArrayOutputStream().apply {
                try {                     
                    BitmapFactory.decodeStream(URL(url).openConnection().apply {
                        doInput = true
                        connect()
                    }.getInputStream())
                } catch (e: IOException) {
                   postValue(Lce.Error(ContentResult.ContentBitmap(ByteArray(0), "bitmapToByteArray error or null - ${e.localizedMessage}")))
                   null
                }?.compress(CompressFormat.JPEG, BITMAP_COMPRESSION_QUALITY, this)
           }.toByteArray(), "")))
        }
    }

ViewModel.kt

//Calls bitmapToByteArray from the Repository
private fun bitmapToByteArray(url: String) = liveData {
    emitSource(switchMap(repository.bitmapToByteArray(url)) { lce ->
        when (lce) {
            is Lce.Loading -> liveData {}
            is Lce.Content -> liveData {
                emit(Event(ContentResult.ContentBitmap(lce.packet.image, lce.packet.errorMessage)))
            }
            is Lce.Error -> liveData {
                Crashlytics.log(Log.WARN, LOG_TAG,
                        "bitmapToByteArray error or null - ${lce.packet.errorMessage}")
            }
        }
    })
}

2. Pass image as ByteArray via an Intent.

In this sample it's passed from a Fragment to a Service. It's the same concept if being shared between two Activities.

Fragment.kt

ContextCompat.startForegroundService(
    context!!,
    Intent(context, AudioService::class.java).apply {
        action = CONTENT_SELECTED_ACTION
        putExtra(CONTENT_SELECTED_BITMAP_KEY, contentPlayer.image)
    })

3. Convert ByteArray back to Bitmap.

Utils.kt

fun ByteArray.byteArrayToBitmap(context: Context) =
    run {
        BitmapFactory.decodeByteArray(this, BITMAP_OFFSET, size).run {
            if (this != null) this
            // In case the Bitmap loaded was empty or there is an error I have a default Bitmap to return.
            else AppCompatResources.getDrawable(context, ic_coinverse_48dp)?.toBitmap()
        }
    }

Scroll to bottom of div?

You can use the HTML DOM scrollIntoView Method like this:

var element = document.getElementById("scroll");
element.scrollIntoView();

React.js inline style best practices

I usually have scss file associated to each React component. But, I don't see reason why you wouldn't encapsulate the component with logic and look in it. I mean, you have similar thing with web components.

MySQL Error 1264: out of range value for column

Work with:

ALTER TABLE `table` CHANGE `cust_fax` `cust_fax` VARCHAR(60) NULL DEFAULT NULL; 

How can I disable the bootstrap hover color for links?

a {background-color:transparent !important;}

Convert time span value to format "hh:mm Am/Pm" using C#

Very simple by using the string format

on .ToSTring("") :

  • if you use "hh" ->> The hour, using a 12-hour clock from 01 to 12.

  • if you use "HH" ->> The hour, using a 24-hour clock from 00 to 23.

  • if you add "tt" ->> The Am/Pm designator.

exemple converting from 23:12 to 11:12 Pm :

DateTime d = new DateTime(1, 1, 1, 23, 12, 0);
var res = d.ToString("hh:mm tt");   // this show  11:12 Pm
var res2 = d.ToString("HH:mm");  // this show  23:12

Console.WriteLine(res);
Console.WriteLine(res2);

Console.Read();

wait a second that is not all you need to care about something else is the system Culture because the same code executed on windows with other langage especialy with difrent culture langage will generate difrent result with the same code

exemple of windows set to Arabic langage culture will show like that :

// 23:12 ?

? means Evening (first leter of ????) .

in another system culture depend on what is set on the windows regional and language option, it will show // 23:12 du.

you can change between different format on windows control panel under windows regional and language -> current format (combobox) and change... apply it do a rebuild (execute) of your app and watch what iam talking about.

so who can I force showing Am and Pm Words in English event if the culture of the current system isn't set to English ?

easy just by adding two lines : ->

the first step add using System.Globalization; on top of your code

and modifing the Previous code to be like this :

DateTime d = new DateTime(1, 1, 1, 23, 12, 0);
var res = d.ToString("HH:mm tt", CultureInfo.InvariantCulture); // this show  11:12 Pm

InvariantCulture => using default English Format.

another question I want to have the pm to be in Arabic or specific language, even if I use windows set to English (or other language) regional format?

Soution for Arabic Exemple :

DateTime d = new DateTime(1, 1, 1, 23, 12, 0);
var res = d.ToString("HH:mm tt", CultureInfo.CreateSpecificCulture("ar-AE")); 

this will show // 23:12 ?

event if my system is set to an English region format. you can change "ar-AE" if you want to another language format. there is a list of each language and its format.

exemples : ar ar-SA Arabic ar-BH ar-BH Arabic (Bahrain) ar-DZ ar-DZ Arabic (Algeria) ar-EG ar-EG Arabic (Egypt)

How to set 777 permission on a particular folder?

Easiest way to set permissions to 777 is to connect to Your server through FTP Application like FileZilla, right click on folder, module_installation, and click Change Permissions - then write 777 or check all permissions.

How can I check whether a numpy array is empty or not?

You can always take a look at the .size attribute. It is defined as an integer, and is zero (0) when there are no elements in the array:

import numpy as np
a = np.array([])

if a.size == 0:
    # Do something when `a` is empty

Putting text in top left corner of matplotlib plot

import matplotlib.pyplot as plt

plt.figure(figsize=(6, 6))
plt.text(0.1, 0.9, 'text', size=15, color='purple')

# or 

fig, axe = plt.subplots(figsize=(6, 6))
axe.text(0.1, 0.9, 'text', size=15, color='purple')

Output of Both

enter image description here

import matplotlib.pyplot as plt

# Build a rectangle in axes coords
left, width = .25, .5
bottom, height = .25, .5
right = left + width
top = bottom + height
ax = plt.gca()
p = plt.Rectangle((left, bottom), width, height, fill=False)
p.set_transform(ax.transAxes)
p.set_clip_on(False)
ax.add_patch(p)


ax.text(left, bottom, 'left top',
        horizontalalignment='left',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(left, bottom, 'left bottom',
        horizontalalignment='left',
        verticalalignment='bottom',
        transform=ax.transAxes)

ax.text(right, top, 'right bottom',
        horizontalalignment='right',
        verticalalignment='bottom',
        transform=ax.transAxes)

ax.text(right, top, 'right top',
        horizontalalignment='right',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(right, bottom, 'center top',
        horizontalalignment='center',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(left, 0.5 * (bottom + top), 'right center',
        horizontalalignment='right',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(left, 0.5 * (bottom + top), 'left center',
        horizontalalignment='left',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(0.5 * (left + right), 0.5 * (bottom + top), 'middle',
        horizontalalignment='center',
        verticalalignment='center',
        transform=ax.transAxes)

ax.text(right, 0.5 * (bottom + top), 'centered',
        horizontalalignment='center',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(left, top, 'rotated\nwith newlines',
        horizontalalignment='center',
        verticalalignment='center',
        rotation=45,
        transform=ax.transAxes)

plt.axis('off')

plt.show()

enter image description here

Absolute Positioning & Text Alignment

The div doesn't take up all the available horizontal space when absolutely positioned. Explicitly setting the width to 100% will solve the problem:

HTML

<div id="my-div">I want to be centered</div>?

CSS

#my-div {
   position: absolute;
   bottom: 15px;
   text-align: center;
   width: 100%;
}

?

How do I detect IE 8 with jQuery?

It is documented in jQuery API Documentation. Check for Internet Explorer with $.browser.msie and then check its version with $.browser.version.

UPDATE: $.browser removed in jQuery 1.9

The jQuery.browser() method has been deprecated since jQuery 1.3 and is removed in 1.9. If needed, it is available as part of the jQuery Migrate plugin. We recommend using feature detection with a library such as Modernizr.

System.Collections.Generic.IEnumerable' does not contain any definition for 'ToList'

I was missing System.Data.Entity dll reference and problem was solved

Check if an array contains any element of another array in JavaScript

ES6 (fastest)

const a = ['a', 'b', 'c'];
const b = ['c', 'a', 'd'];
a.some(v=> b.indexOf(v) !== -1)

ES2016

const a = ['a', 'b', 'c'];
const b = ['c', 'a', 'd'];
a.some(v => b.includes(v));

Underscore

const a = ['a', 'b', 'c'];
const b = ['c', 'a', 'd'];
_.intersection(a, b)

DEMO: https://jsfiddle.net/r257wuv5/

jsPerf: https://jsperf.com/array-contains-any-element-of-another-array

How do I fix 'ImportError: cannot import name IncompleteRead'?

This problem is caused by a mismatch between your pip installation and your requests installation.

As of requests version 2.4.0 requests.compat.IncompleteRead has been removed. Older versions of pip, e.g. from July 2014, still relied on IncompleteRead. In the current version of pip, the import of IncompleteRead has been removed.

So the one to blame is either:

  • requests, for removing public API too quickly
  • Ubuntu for updating pip too slowly

You can solve this issue, by either updating pip via Ubuntu (if there is a newer version) or by installing pip aside from Ubuntu.

What is the difference between json.dumps and json.load?

dumps takes an object and produces a string:

>>> a = {'foo': 3}
>>> json.dumps(a)
'{"foo": 3}'

load would take a file-like object, read the data from that object, and use that string to create an object:

with open('file.json') as fh:
    a = json.load(fh)

Note that dump and load convert between files and objects, while dumps and loads convert between strings and objects. You can think of the s-less functions as wrappers around the s functions:

def dump(obj, fh):
    fh.write(dumps(obj))

def load(fh):
    return loads(fh.read())

'Incorrect SET Options' Error When Building Database Project

In my case, I found that a computed column had been added to the "included columns" of an index. Later, when an item in that table was updated, the merge statement failed with that message. The merge was in a trigger, so this was hard to track down! Removing the computed column from the index fixed it.

Send JavaScript variable to PHP variable

PHP runs on the server and Javascript runs on the client, so you can't set a PHP variable to equal a Javascript variable without sending the value to the server. You can, however, set a Javascript variable to equal a PHP variable:

<script type="text/javascript">
  var foo = '<?php echo $foo ?>';
</script>

To send a Javascript value to PHP you'd need to use AJAX. With jQuery, it would look something like this (most basic example possible):

var variableToSend = 'foo';
$.post('file.php', {variable: variableToSend});

On your server, you would need to receive the variable sent in the post:

$variable = $_POST['variable'];

MySQL Workbench Edit Table Data is read only

I was getting the read-only problem even when I was selecting the primary key. I eventually figured out it was a casing problem. Apparently the PK column must be cased the same as defined in the table. using: workbench 6.3 on windows

Read-Only

SELECT leadid,firstname,lastname,datecreated FROM lead;

Allowed edit

SELECT LeadID,firstname,lastname,datecreated FROM lead;

Calling stored procedure with return value

I see the other one is closed. So basically here's the rough of my code. I think you are missing the string cmd comment. For example if my store procedure is call:DBO.Test. I would need to write cmd="DBO.test". Then do command type equal to store procedure, and blah blah blah

Connection.open();
String cmd="DBO.test"; //the command
Sqlcommand mycommand;

Using "super" in C++

I've always used "inherited" rather than super. (Probably due to a Delphi background), and I always make it private, to avoid the problem when the 'inherited' is erroneously omitted from a class but a subclass tries to use it.

class MyClass : public MyBase
{
private:  // Prevents erroneous use by other classes.
  typedef MyBase inherited;
...

My standard 'code template' for creating new classes includes the typedef, so I have little opportunity to accidentally omit it.

I don't think the chained "super::super" suggestion is a good idea- If you're doing that, you're probably tied in very hard to a particular hierarchy, and changing it will likely break stuff badly.

Remove all unused resources from an android project

Maybe useful Andround Unused Resources is a Java application that will scan your project for unused resources. Unused resources needlessly take up space, increase the build time, and clutter the IDE's autocomplete list.

To use it, ensure your working directory is the root of your Android project, and run:

java -jar AndroidUnusedResources.jar

https://code.google.com/p/android-unused-resources/

How can I switch to a tag/branch in hg?

Once you have cloned the repo, you have everything: you can then hg up branchname or hg up tagname to update your working copy.

UP: hg up is a shortcut of hg update, which also has hg checkout alias for people with git habits.

bootstrap initially collapsed element

another solution is to add toggle=false to the collapse target, this will stop it randomly opening and closing which happens if you just remove the "in"

eg

<div class="accordion-heading">
    <a class="accordion-toggle"
        data-toggle="collapse"
        data-parent="#accordion2"
        href="#collapseOne">Open!</a>
</div>
<div
    id="collapseOne"
    class="accordion-body collapse"
    data-toggle="false"
    >
    <div class="span6">
        <div class="well well-small">
            <div class="accordion-toggle">
                ...some text...
            </div>
        </div>
    </div>
    <div class="span2"></div>                            
</div>

Remove last specific character in a string c#

Try string.TrimEnd():

Something = Something.TrimEnd(',');

Read and write a String from text file

Assuming that you have moved your text file data.txt to your Xcode-project (Use drag'n'drop and check "Copy files if necessary") you can do the following just like in Objective-C:

let bundle = NSBundle.mainBundle()
let path = bundle.pathForResource("data", ofType: "txt")        
let content = NSString.stringWithContentsOfFile(path) as String

println(content) // prints the content of data.txt

Update:
For reading a file from Bundle (iOS) you can use:

let path = NSBundle.mainBundle().pathForResource("FileName", ofType: "txt")
var text = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)!
println(text)

Update for Swift 3:

let path = Bundle.main.path(forResource: "data", ofType: "txt") // file path for file "data.txt"
var text = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)!

For Swift 5

let path = Bundle.main.path(forResource: "ListAlertJson", ofType: "txt") // file path for file "data.txt"
let string = try String(contentsOfFile: path!, encoding: String.Encoding.utf8)

How do I use a custom deleter with a std::unique_ptr member?

It's possible to do this cleanly using a lambda in C++11 (tested in G++ 4.8.2).

Given this reusable typedef:

template<typename T>
using deleted_unique_ptr = std::unique_ptr<T,std::function<void(T*)>>;

You can write:

deleted_unique_ptr<Foo> foo(new Foo(), [](Foo* f) { customdeleter(f); });

For example, with a FILE*:

deleted_unique_ptr<FILE> file(
    fopen("file.txt", "r"),
    [](FILE* f) { fclose(f); });

With this you get the benefits of exception-safe cleanup using RAII, without needing try/catch noise.

MessageBodyWriter not found for media type=application/json

I think may be you should try to convert the data to json format. It can be done by using gson lib. Try something like below.

I don't know it is a best solutions or not but you could do it this way.It worked for me

example : `

@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response info(@HeaderParam("Accept") String accept) {
    Info information = new Info();
    information.setInfo("Calc Application Info");
    System.out.println(accept);
    if (!accept.equals(MediaType.APPLICATION_JSON)) {
        return Response.status(Status.ACCEPTED).entity(information).build();
    } else {
        Gson jsonConverter = new GsonBuilder().create();
        return Response.status(Status.ACCEPTED).entity(jsonConverter.toJson(information)).build();
    }
}

How to return value from an asynchronous callback function?

It makes no sense to return values from a callback. Instead, do the "foo()" work you want to do inside your callback.

Asynchronous callbacks are invoked by the browser or by some framework like the Google geocoding library when events happen. There's no place for returned values to go. A callback function can return a value, in other words, but the code that calls the function won't pay attention to the return value.

Test whether string is a valid integer

For portability to pre-Bash 3.1 (when the =~ test was introduced), use expr.

if expr "$string" : '-\?[0-9]\+$' >/dev/null
then
  echo "String is a valid integer."
else
  echo "String is not a valid integer."
fi

expr STRING : REGEX searches for REGEX anchored at the start of STRING, echoing the first group (or length of match, if none) and returning success/failure. This is old regex syntax, hence the excess \. -\? means "maybe -", [0-9]\+ means "one or more digits", and $ means "end of string".

Bash also supports extended globs, though I don't recall from which version onwards.

shopt -s extglob
case "$string" of
    @(-|)[0-9]*([0-9]))
        echo "String is a valid integer." ;;
    *)
        echo "String is not a valid integer." ;;
esac

# equivalently, [[ $string = @(-|)[0-9]*([0-9])) ]]

@(-|) means "- or nothing", [0-9] means "digit", and *([0-9]) means "zero or more digits".

Python - Passing a function into another function

A function name can become a variable name (and thus be passed as an argument) by dropping the parentheses. A variable name can become a function name by adding the parentheses.

In your example, equate the variable rules to one of your functions, leaving off the parentheses and the mention of the argument. Then in your game() function, invoke rules( v ) with the parentheses and the v parameter.

if puzzle == type1:
    rules = Rule1
else:
    rules = Rule2

def Game(listA, listB, rules):
    if rules( v ) == True:
        do...
    else:
        do...

jquery validate check at least one checkbox

make sure the input-name[] is in inverted commas in the ruleset. Took me hours to figure that part out.

$('#testform').validate({
  rules : {
    "name[]": { required: true, minlength: 1 }
  }
});

read more here... http://docs.jquery.com/Plugins/Valid...ets.2C_dots.29

How do I get the currently-logged username from a Windows service in .NET?

Modified code of Tapas's answer:

Dim searcher As New ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem")
Dim collection As ManagementObjectCollection = searcher.[Get]()
Dim username As String
For Each oReturn As ManagementObject In collection
    username = oReturn("UserName")
Next

How to add anything in <head> through jquery/javascript?

Try a javascript pure:

Library JS:

appendHtml = function(element, html) {
    var div = document.createElement('div');
    div.innerHTML = html;
    while (div.children.length > 0) {
        element.appendChild(div.children[0]);
    }
}

Type: appendHtml(document.head, '<link rel="stylesheet" type="text/css" href="http://example.com/example.css"/>');

or jQuery:

$('head').append($('<link rel="stylesheet" type="text/css" />').attr('href', 'http://example.com/example.css'));

When do items in HTML5 local storage expire?

You can try this one.

var hours = 24; // Reset when storage is more than 24hours
var now = Date.now();
var setupTime = localStorage.getItem('setupTime');
if (setupTime == null) {
     localStorage.setItem('setupTime', now)
} else if (now - setupTime > hours*60*60*1000) {
    localStorage.clear()
    localStorage.setItem('setupTime', now);
}

How do I apply a diff patch on Windows?

A BusyBox port for Windows has both a diff and patch command, but they only support unified format.

Authenticate with GitHub using a token

This worked for me using ssh:

SettingsDeveloper settingsGenerate new token.

git remote set-url origin https://[APPLICATION]:[NEW TOKEN]@github.com/[ORGANISATION]/[REPO].git

Huge performance difference when using group by vs distinct

The two queries express the same question. Apparently the query optimizer chooses two different execution plans. My guess would be that the distinct approach is executed like:

  • Copy all business_key values to a temporary table
  • Sort the temporary table
  • Scan the temporary table, returning each item that is different from the one before it

The group by could be executed like:

  • Scan the full table, storing each value of business key in a hashtable
  • Return the keys of the hashtable

The first method optimizes for memory usage: it would still perform reasonably well when part of the temporary table has to be swapped out. The second method optimizes for speed, but potentially requires a large amount of memory if there are a lot of different keys.

Since you either have enough memory or few different keys, the second method outperforms the first. It's not unusual to see performance differences of 10x or even 100x between two execution plans.

AngularJS: How to set a variable inside of a template?

It's not the best answer, but its also an option: since you can concatenate multiple expressions, but just the last one is rendered, you can finish your expression with "" and your variable will be hidden.

So, you could define the variable with:

{{f = forecast[day.iso]; ""}}

Angularjs - Pass argument to directive

<button my-directive="push">Push to Go</button>

app.directive("myDirective", function() {
    return {
        restrict : "A",
         link: function(scope, elm, attrs) {
                elm.bind('click', function(event) {

                    alert("You pressed button: " + event.target.getAttribute('my-directive'));
                });
        }
    };
});

here is what I did

I'm using directive as html attribute and I passed parameter as following in my HTML file. my-directive="push" And from the directive I retrieved it from the Mouse-click event object. event.target.getAttribute('my-directive').

How do I get a background location update every n minutes in my iOS application?

I did this in an application I'm developing. The timers don't work when the app is in the background but the app is constantly receiving the location updates. I read somewhere in the documentation (i can't seem to find it now, i'll post an update when i do) that a method can be called only on an active run loop when the app is in the background. The app delegate has an active run loop even in the bg so you dont need to create your own to make this work. [Im not sure if this is the correct explanation but thats how I understood from what i read]

First of all, add the location object for the key UIBackgroundModes in your app's info.plist. Now, what you need to do is start the location updates anywhere in your app:

    CLLocationManager locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;//or whatever class you have for managing location
    [locationManager startUpdatingLocation];

Next, write a method to handle the location updates, say -(void)didUpdateToLocation:(CLLocation*)location, in the app delegate. Then implement the method locationManager:didUpdateLocation:fromLocation of CLLocationManagerDelegate in the class in which you started the location manager (since we set the location manager delegate to 'self'). Inside this method you need to check if the time interval after which you have to handle the location updates has elapsed. You can do this by saving the current time every time. If that time has elapsed, call the method UpdateLocation from your app delegate:

NSDate *newLocationTimestamp = newLocation.timestamp;
NSDate *lastLocationUpdateTiemstamp;

int locationUpdateInterval = 300;//5 mins

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
if (userDefaults) {

        lastLocationUpdateTiemstamp = [userDefaults objectForKey:kLastLocationUpdateTimestamp];

        if (!([newLocationTimestamp timeIntervalSinceDate:lastLocationUpdateTiemstamp] < locationUpdateInterval)) {
            //NSLog(@"New Location: %@", newLocation);
            [(AppDelegate*)[UIApplication sharedApplication].delegate didUpdateToLocation:newLocation];
            [userDefaults setObject:newLocationTimestamp forKey:kLastLocationUpdateTimestamp];
        }
    }
}

This will call your method every 5 mins even when your app is in background. Imp: This implementation drains the battery, if your location data's accuracy is not critical you should use [locationManager startMonitoringSignificantLocationChanges]

Before adding this to your app, please read the Location Awareness Programming Guide

Getting "Lock wait timeout exceeded; try restarting transaction" even though I'm not using a transaction

In my instance, I was running an abnormal query to fix data. If you lock the tables in your query, then you won't have to deal with the Lock timeout:

LOCK TABLES `customer` WRITE;
update customer set account_import_id = 1;
UNLOCK TABLES;

This is probably not a good idea for normal use.

For more info see: MySQL 8.0 Reference Manual

Python: Assign Value if None Exists

Here is the easiest way I use, hope works for you,

var1 = var1 or 4

This assigns 4 to var1 only if var1 is None , False or 0

How to change button text or link text in JavaScript?

You can simply use:

document.getElementById(button_id).innerText = 'Your text here';

If you want to use HTML formatting, use the innerHTML property instead.

invalid byte sequence for encoding "UTF8"

Short Example to Solve this Problem in PHP-

$val = "E'\377'";
iconv(mb_detect_encoding($val, mb_detect_order(), true), "UTF-8", $val);

Error Detail: As POSTGRES database do not handle other than UTF-8 Characters when we try to pass above given inputs to a column its give error of "invalid byte sequence for encoding "UTF8": 0xab" .

So just convert that value into UTF-8 before insertion in POSTGRES Database.

Can't install APK from browser downloads

It shouldn't be HTTP headers if the file has been downloaded successfully and it's the same file that you can open from OI.

A shot in the dark, but could it be that you are not allowing installation from unknown sources, and that OI is somehow bypassing that?

Settings > Applications > Unknown sources...

Edit

Answer extracted from comments which worked. Ensure the Content-Type is set to application/vnd.android.package-archive

MySQL Delete all rows from table and reset ID to zero

if you want to use truncate use this:

SET FOREIGN_KEY_CHECKS = 0; 
TRUNCATE table $table_name; 
SET FOREIGN_KEY_CHECKS = 1;

How to obtain Certificate Signing Request

Follow these steps to create CSR (Code Signing Identity):

  1. On your Mac, go to the folder 'Applications' ? 'Utilities' and open 'Keychain Access.'

    enter image description here

  2. Go to 'Keychain Access' ? Certificate Assistant ? Request a Certificate from a Certificate Authority. ?

    enter image description here

  3. Fill out the information in the Certificate Information window as specified below and click "Continue."
    • In the User Email Address field, enter the email address to identify with this certificate
    • In the Common Name field, enter your name
    • In the Request group, click the "Saved to disk" option ?

    enter image description here

  4. Save the file to your hard drive.

    enter image description here


Use this CSR (.certSigningRequest) file to create project/application certificates and profiles, in Apple developer account.

Typescript input onchange event.target.value

the correct way to use in TypeScript is

  handleChange(e: React.ChangeEvent<HTMLInputElement>) {
    // No longer need to cast to any - hooray for react!
    this.setState({temperature: e.target.value});
  }

  render() {
        ...
        <input value={temperature} onChange={this.handleChange} />
        ...
    );
  }

Follow the complete class, it's better to understand:

import * as React from "react";

const scaleNames = {
  c: 'Celsius',
  f: 'Fahrenheit'
};


interface TemperatureState {
   temperature: string;
}

interface TemperatureProps {
   scale: string;

}

class TemperatureInput extends React.Component<TemperatureProps, TemperatureState> {
  constructor(props: TemperatureProps) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.state = {temperature: ''};
  }

  //  handleChange(e: { target: { value: string; }; }) {
  //    this.setState({temperature: e.target.value});  
  //  }


  handleChange(e: React.ChangeEvent<HTMLInputElement>) {
    // No longer need to cast to any - hooray for react!
    this.setState({temperature: e.target.value});
  }

  render() {
    const temperature = this.state.temperature;
    const scale = this.props.scale;
    return (
      <fieldset>
        <legend>Enter temperature in {scaleNames[scale]}:</legend>
        <input value={temperature} onChange={this.handleChange} />
      </fieldset>
    );
  }
}

export default TemperatureInput;

Stylesheet not loaded because of MIME-type

In my case I had to both make sure that the link was relative and the rel property was after the href property:

<link href="/assets/styles/iframe.css" rel="stylesheet">

How to add target="_blank" to JavaScript window.location?

window.location sets the URL of your current window. To open a new window, you need to use window.open. This should work:

function ToKey(){
    var key = document.tokey.key.value.toLowerCase();
    if (key == "smk") {
        window.open('http://www.smkproduction.eu5.org', '_blank');
    } else {
        alert("Kodi nuk është valid!");
    }
}

How to have click event ONLY fire on parent DIV, not children?

//bind `click` event handler to the `.foobar` element(s) to do work,
//then find the children of all the `.foobar` element(s)
//and bind a `click` event handler to them that stops the propagation of the event
$('.foobar').on('click', function () { ... }).children().on('click', function (event) {
    event.stopPropagation();
    //you can also use `return false;` which is the same as `event.preventDefault()` and `event.stopPropagation()` all in one (in a jQuery event handler)
});

This will stop the propagation (bubbling) of the click event on any of the children element(s) of the .foobar element(s) so the event won't reach the .foobar element(s) to fire their event handler(s).

Here is a demo: http://jsfiddle.net/bQQJP/

Oracle SQL Developer: Unable to find a JVM

The Oracle SQL developer is not supported by the 64bit JDK. To resolve this issue:

  1. Install a 32bit JDK (x86)
  2. Update your SQL developer config file (It should now point to the new 32bit JDK).
  3. Edit the sqldeveloper.conf, which can be found under {ORACLE_HOME}\sqldeveloper\sqldeveloper\bin\sqldeveloper.conf
  4. Make sure SetJavaHome is pointing to your 32bit JDK.

For example:

SetJavaHome C:\Program Files (x86) \Java\jdk1.6.0_13

how to create a cookie and add to http response from inside my service layer?

A cookie is a object with key value pair to store information related to the customer. Main objective is to personalize the customer's experience.

An utility method can be created like

private Cookie createCookie(String cookieName, String cookieValue) {
    Cookie cookie = new Cookie(cookieName, cookieValue);
    cookie.setPath("/");
    cookie.setMaxAge(MAX_AGE_SECONDS);
    cookie.setHttpOnly(true);
    cookie.setSecure(true);
    return cookie;
}

If storing important information then we should alsways put setHttpOnly so that the cookie cannot be accessed/modified via javascript. setSecure is applicable if you are want cookies to be accessed only over https protocol.

using above utility method you can add cookies to response as

Cookie cookie = createCookie("name","value");
response.addCookie(cookie);

Easy way to export multiple data.frame to multiple Excel worksheets

You can also use the openxlsx library to export multiple datasets to multiple sheets in a single workbook.The advantage of openxlsx over xlsx is that openxlsx removes the dependencies on java libraries.

Write a list of data.frames to individual worksheets using list names as worksheet names.

require(openxlsx)
list_of_datasets <- list("Name of DataSheet1" = dataframe1, "Name of Datasheet2" = dataframe2)
write.xlsx(list_of_datasets, file = "writeXLSX2.xlsx")

In Unix, how do you remove everything in the current directory and below it?

This simplest safe & general solution is probably:

find -mindepth 1 -maxdepth 1 -print0 | xargs -0 rm -rf

Using "-Filter" with a variable

Or

-like '*'+$nameregex+'*'

if you would like to use wildcards.

How to import Google Web Font in CSS file?

You can also use @font-face to link to the URLs. http://www.css3.info/preview/web-fonts-with-font-face/

Does the CMS support iframes? You might be able to throw an iframe into the top of your content, too. This would probably be slower - better to include it in your CSS.

Download and open PDF file using Ajax

This snippet is for angular js users which will face the same problem, Note that the response file is downloaded using a programmed click event. In this case , the headers were sent by server containing filename and content/type.

$http({
    method: 'POST', 
    url: 'DownloadAttachment_URL',
    data: { 'fileRef': 'filename.pdf' }, //I'm sending filename as a param
    headers: { 'Authorization': $localStorage.jwt === undefined ? jwt : $localStorage.jwt },
    responseType: 'arraybuffer',
}).success(function (data, status, headers, config) {
    headers = headers();
    var filename = headers['x-filename'];
    var contentType = headers['content-type'];
    var linkElement = document.createElement('a');
    try {
        var blob = new Blob([data], { type: contentType });
        var url = window.URL.createObjectURL(blob);

        linkElement.setAttribute('href', url);
        linkElement.setAttribute("download", filename);

        var clickEvent = new MouseEvent("click", {
            "view": window,
            "bubbles": true,
            "cancelable": false
        });
        linkElement.dispatchEvent(clickEvent);
    } catch (ex) {
        console.log(ex);
    }
}).error(function (data, status, headers, config) {
}).finally(function () {

});

How do I extract specific 'n' bits of a 32-bit unsigned integer in C?

There is a single BEXTR (Bit field extract (with register)) x86 instruction on Intel and AMD CPUs and UBFX on ARM. There are intrinsic functions such as _bextr_u32() (link requires sign-in) that allow to invoke this instruction explicitly.

They implement (source >> offset) & ((1 << n) - 1) C code: get n continuous bits from source starting at the offset bit. Here's a complete function definition that handles edge cases:

#include <limits.h>

unsigned getbits(unsigned value, unsigned offset, unsigned n)
{
  const unsigned max_n = CHAR_BIT * sizeof(unsigned);
  if (offset >= max_n)
    return 0; /* value is padded with infinite zeros on the left */
  value >>= offset; /* drop offset bits */
  if (n >= max_n)
    return value; /* all  bits requested */
  const unsigned mask = (1u << n) - 1; /* n '1's */
  return value & mask;
}

For example, to get 3 bits from 2273 (0b100011100001) starting at 5-th bit, call getbits(2273, 5, 3)—it extracts 7 (0b111).

For example, say I want the first 17 bits of the 32-bit value; what is it that I should do?

unsigned first_bits = value & ((1u << 17) - 1); // & 0x1ffff

Assuming CHAR_BIT * sizeof(unsigned) is 32 on your system.

I presume I am supposed to use the modulus operator and I tried it and was able to get the last 8 bits and last 16 bits

unsigned last8bitsvalue  = value & ((1u <<  8) - 1); // & 0xff
unsigned last16bitsvalue = value & ((1u << 16) - 1); // & 0xffff

If the offset is always zero as in all your examples in the question then you don't need the more general getbits(). There is a special cpu instruction BLSMSK that helps to compute the mask ((1 << n) - 1).

How to Generate a random number of fixed length using JavaScript?

I would go with this solution:

Math.floor(Math.random() * 899999 + 100000)

JPanel setBackground(Color.BLACK) does nothing

If your panel is 'not opaque' (transparent) you wont see your background color.

Why an interface can not implement another interface?

Interface is the class that contains an abstract method that cannot create any object.Since Interface cannot create the object and its not a pure class, Its no worth implementing it.

How to get JSON Key and Value?

$.each(result, function(key, value) {
  console.log(key+ ':' + value);
});

Formatting doubles for output in C#

The problem is that .NET will always round a double to 15 significant decimal digits before applying your formatting, regardless of the precision requested by your format and regardless of the exact decimal value of the binary number.

I'd guess that the Visual Studio debugger has its own format/display routines that directly access the internal binary number, hence the discrepancies between your C# code, your C code and the debugger.

There's nothing built-in that will allow you to access the exact decimal value of a double, or to enable you to format a double to a specific number of decimal places, but you could do this yourself by picking apart the internal binary number and rebuilding it as a string representation of the decimal value.

Alternatively, you could use Jon Skeet's DoubleConverter class (linked to from his "Binary floating point and .NET" article). This has a ToExactString method which returns the exact decimal value of a double. You could easily modify this to enable rounding of the output to a specific precision.

double i = 10 * 0.69;
Console.WriteLine(DoubleConverter.ToExactString(i));
Console.WriteLine(DoubleConverter.ToExactString(6.9 - i));
Console.WriteLine(DoubleConverter.ToExactString(6.9));

// 6.89999999999999946709294817992486059665679931640625
// 0.00000000000000088817841970012523233890533447265625
// 6.9000000000000003552713678800500929355621337890625

Difference between drop table and truncate table?

Truncating the table empties the table. Dropping the table deletes it entirely. Either one will be fast, but dropping it will likely be faster (depending on your database engine).

If you don't need it anymore, drop it so it's not cluttering up your schema.

How do I convert an enum to a list in C#?

Here for usefulness... some code for getting the values into a list, which converts the enum into readable form for the text

public class KeyValuePair
  {
    public string Key { get; set; }

    public string Name { get; set; }

    public int Value { get; set; }

    public static List<KeyValuePair> ListFrom<T>()
    {
      var array = (T[])(Enum.GetValues(typeof(T)).Cast<T>());
      return array
        .Select(a => new KeyValuePair
          {
            Key = a.ToString(),
            Name = a.ToString().SplitCapitalizedWords(),
            Value = Convert.ToInt32(a)
          })
          .OrderBy(kvp => kvp.Name)
         .ToList();
    }
  }

.. and the supporting System.String extension method:

/// <summary>
/// Split a string on each occurrence of a capital (assumed to be a word)
/// e.g. MyBigToe returns "My Big Toe"
/// </summary>
public static string SplitCapitalizedWords(this string source)
{
  if (String.IsNullOrEmpty(source)) return String.Empty;
  var newText = new StringBuilder(source.Length * 2);
  newText.Append(source[0]);
  for (int i = 1; i < source.Length; i++)
  {
    if (char.IsUpper(source[i]))
      newText.Append(' ');
    newText.Append(source[i]);
  }
  return newText.ToString();
}

Cannot get to $rootScope

You can not ask for instance during configuration phase - you can ask only for providers.

var app = angular.module('modx', []);

// configure stuff
app.config(function($routeProvider, $locationProvider) {
  // you can inject any provider here
});

// run blocks
app.run(function($rootScope) {
  // you can inject any instance here
});

See http://docs.angularjs.org/guide/module for more info.

'negative' pattern matching in python

See it in action:

matchObj = re.search("^(?!OK|\\.).*", item)

Don't forget to put .* after negative look-ahead, otherwise you couldn't get any match ;-)

Excel Define a range based on a cell value

This should be close to what you are looking for your first example:

=SUM(INDIRECT("A1:A"&B1,TRUE))

This should be close to what you are looking for your final example:

=SUM(INDIRECT("A"&1+B1&":A"&B1,TRUE))

Entity Framework Code First - two Foreign Keys from same table

You can try this too:

public class Match
{
    [Key]
    public int MatchId { get; set; }

    [ForeignKey("HomeTeam"), Column(Order = 0)]
    public int? HomeTeamId { get; set; }
    [ForeignKey("GuestTeam"), Column(Order = 1)]
    public int? GuestTeamId { get; set; }

    public float HomePoints { get; set; }
    public float GuestPoints { get; set; }
    public DateTime Date { get; set; }

    public virtual Team HomeTeam { get; set; }
    public virtual Team GuestTeam { get; set; }
}

When you make a FK column allow NULLS, you are breaking the cycle. Or we are just cheating the EF schema generator.

In my case, this simple modification solve the problem.

ln (Natural Log) in Python

Here is the correct implementation using numpy (np.log() is the natural logarithm)

import numpy as np
p = 100
r = 0.06 / 12
FV = 4000

n = np.log(1 + FV * r/ p) / np.log(1 + r)

print ("Number of periods = " + str(n))

Output:

Number of periods = 36.55539635919235

Get index of array element faster than O(n)

Is there a good reason not to use a hash? Lookups are O(1) vs. O(n) for the array.

How to get changes from another branch

  1. go to the master branch our-team

    • git checkout our-team
  2. pull all the new changes from our-team branch

    • git pull
  3. go to your branch featurex

    • git checkout featurex
  4. merge the changes of our-team branch into featurex branch

    • git merge our-team
    • or git cherry-pick {commit-hash} if you want to merge specific commits
  5. push your changes with the changes of our-team branch

    • git push

Note: probably you will have to fix conflicts after merging our-team branch into featurex branch before pushing

ORA-01031: insufficient privileges when selecting view

If the view is accessed via a stored procedure, the execute grant is insufficient to access the view. You must grant select explicitly.

How to truncate string using SQL server

You can also use the Cast() operation :

 Declare @name varchar(100);
set @name='....';
Select Cast(@name as varchar(10)) as new_name

How do I retrieve my MySQL username and password?

Unfortunately your user password is irretrievable. It has been hashed with a one way hash which if you don't know is irreversible. I recommend go with Xenph Yan above and just create an new one.

You can also use the following procedure from the manual for resetting the password for any MySQL root accounts on Windows:

  1. Log on to your system as Administrator.
  2. Stop the MySQL server if it is running. For a server that is running as a Windows service, go to the Services manager:

Start Menu -> Control Panel -> Administrative Tools -> Services

Then find the MySQL service in the list, and stop it. If your server is not running as a service, you may need to use the Task Manager to force it to stop.

  1. Create a text file and place the following statements in it. Replace the password with the password that you want to use.

    UPDATE mysql.user SET Password=PASSWORD('MyNewPass') WHERE User='root';
    FLUSH PRIVILEGES;
    

    The UPDATE and FLUSH statements each must be written on a single line. The UPDATE statement resets the password for all existing root accounts, and the FLUSH statement tells the server to reload the grant tables into memory.

  2. Save the file. For this example, the file will be named C:\mysql-init.txt.
  3. Open a console window to get to the command prompt:

    Start Menu -> Run -> cmd

  4. Start the MySQL server with the special --init-file option:

    C:\> C:\mysql\bin\mysqld-nt --init-file = C:\mysql-init.txt
    

    If you installed MySQL to a location other than C:\mysql, adjust the command accordingly.

    The server executes the contents of the file named by the --init-file option at startup, changing each root account password.

    You can also add the --console option to the command if you want server output to appear in the console window rather than in a log file.

    If you installed MySQL using the MySQL Installation Wizard, you may need to specify a --defaults-file option:

    C:\> "C:\Program Files\MySQL\MySQL Server 5.0\bin\mysqld-nt.exe" --defaults-file="C:\Program Files\MySQL\MySQL Server 5.0\my.ini" --init-file=C:\mysql-init.txt
    

    The appropriate --defaults-file setting can be found using the Services Manager:

    Start Menu -> Control Panel -> Administrative Tools -> Services

    Find the MySQL service in the list, right-click on it, and choose the Properties option. The Path to executable field contains the --defaults-file setting.

  5. After the server has started successfully, delete C:\mysql-init.txt.
  6. Stop the MySQL server, then restart it in normal mode again. If you run the server as a service, start it from the Windows Services window. If you start the server manually, use whatever command you normally use.

You should now be able to connect to MySQL as root using the new password.

Laravel Eloquent get results grouped by days

You can filter the results based on formatted date using mysql (See here for Mysql/Mariadb help) and use something like this in laravel-5.4:

Model::selectRaw("COUNT(*) views, DATE_FORMAT(created_at, '%Y %m %e') date")
    ->groupBy('date')
    ->get();

Open youtube video in Fancybox jquery

$("a.more").click(function() {
                 $.fancybox({
                  'padding'             : 0,
                  'autoScale'   : false,
                  'transitionIn'        : 'none',
                  'transitionOut'       : 'none',
                  'title'               : this.title,
                  'width'               : 680,
                  'height'              : 495,
                  'href'                : this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
                  'type'                : 'swf',    // <--add a comma here
                  'swf'                 : {'allowfullscreen':'true'} // <-- flashvars here
                  });
                 return false;

            }); 

Resetting MySQL Root Password with XAMPP on Localhost

Open the file C:\xampp\phpMyAdmin\config.inc.php in your text editor. Search for the tags below and edit accordingly

$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'password';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = true;

Where 'password' is your new password. In-between quotes.

GO to your browser and visit link http://localhost/phpmyadmin/. Click on 'GO' without your new password. It would log you in and you would be able to see the "CHANGE PASSWORD". Proceed to change your password and you are done.

Lollipop : draw behind statusBar with its color set to transparent

Here is the theme I use to accomplish this:

<style name="AppTheme" parent="@android:style/Theme.NoTitleBar">

    <!-- Default Background Screen -->
    <item name="android:background">@color/default_blue</item>
    <item name="android:windowTranslucentStatus">true</item>

</style>

Make Https call using HttpClient

For error:

The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

I think that you need to accept certificate unconditionally with following code

ServicePointManager.ServerCertificateValidationCallback += 
    (sender, cert, chain, sslPolicyErrors) => true;

as Oppositional wrote in his answer to question .NET client connecting to ssl Web API.

Linux/Unix command to determine if process is running?

You should know the PID of your process.

When you launch it, its PID will be recorded in the $! variable. Save this PID into a file.

Then you will need to check if this PID corresponds to a running process. Here's a complete skeleton script:

FILE="/tmp/myapp.pid"

if [ -f $FILE ];
then
   PID=$(cat $FILE)
else
   PID=1
fi

ps -o pid= -p $PID
if [ $? -eq 0 ]; then
  echo "Process already running."  
else
  echo "Starting process."
  run_my_app &
  echo $! > $FILE
fi

Based on the answer of peterh. The trick for knowing if a given PID is running is in the ps -o pid= -p $PID instruction.

Bootstrap 3 2-column form layout

You can use the bootstrap grid system. as Yoann said


 <div class="container">
    <div class="row">
        <form role="form">
           <div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
                        <label for="exampleInputEmail1">Email address</label>
                        <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email">
                    </div>
                    <div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
                        <label for="exampleInputEmail1">Name</label>
                        <input type="text" class="form-control" id="exampleInputEmail1" placeholder="Enter Name">
                    </div>
                    <div class="clearfix"></div>
                    <div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
                        <label for="exampleInputPassword1">Password</label>
                        <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
                    </div>
                    <div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
                        <label for="exampleInputPassword1">Confirm Password</label>
                        <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Confirm Password">
                    </div>
          </form>
         <div class="clearfix">
      </div>
    </div>
</div>

PHP Constants Containing Arrays?

I know it's a bit old question, but here is my solution:

<?php
class Constant {

    private $data = [];

    public function define($constant, $value) {
        if (!isset($this->data[$constant])) {
            $this->data[$constant] = $value;
        } else {
            trigger_error("Cannot redefine constant $constant", E_USER_WARNING);
        }
    }

    public function __get($constant) {
        if (isset($this->data[$constant])) {
            return $this->data[$constant];
        } else {
            trigger_error("Use of undefined constant $constant - assumed '$constant'", E_USER_NOTICE);
            return $constant;
        }
    }

    public function __set($constant,$value) {
        $this->define($constant, $value);
    }

}
$const = new Constant;

I defined it because I needed to store objects and arrays in constants so I installed also runkit to php so I could make the $const variable superglobal.

You can use it as $const->define("my_constant",array("my","values")); or just $const->my_constant = array("my","values");

To get the value just simply call $const->my_constant;

Convert UTF-8 to base64 string

It's a little difficult to tell what you're trying to achieve, but assuming you're trying to get a Base64 string that when decoded is abcdef==, the following should work:

byte[] bytes = Encoding.UTF8.GetBytes("abcdef==");
string base64 = Convert.ToBase64String(bytes);
Console.WriteLine(base64);

This will output: YWJjZGVmPT0= which is abcdef== encoded in Base64.

Edit:

To decode a Base64 string, simply use Convert.FromBase64String(). E.g.

string base64 = "YWJjZGVmPT0=";
byte[] bytes = Convert.FromBase64String(base64);

At this point, bytes will be a byte[] (not a string). If we know that the byte array represents a string in UTF8, then it can be converted back to the string form using:

string str = Encoding.UTF8.GetString(bytes);
Console.WriteLine(str);

This will output the original input string, abcdef== in this case.

Assert that a WebElement is not present using Selenium WebDriver with java

You can utlilize Arquillian Graphene framework for this. So example for your case could be

Graphene.element(By.linkText(text)).isPresent().apply(driver));

Is also provides you bunch of nice API's for working with Ajax, fluent waits, page objects, fragments and so on. It definitely eases a Selenium based test development a lot.

How can I write maven build to add resources to classpath?

If you place anything in src/main/resources directory, then by default it will end up in your final *.jar. If you are referencing it from some other project and it cannot be found on a classpath, then you did one of those two mistakes:

  1. *.jar is not correctly loaded (maybe typo in the path?)
  2. you are not addressing the resource correctly, for instance: /src/main/resources/conf/settings.properties is seen on classpath as classpath:conf/settings.properties

Convert string to number field

Within Crystal, you can do it by creating a formula that uses the ToNumber function. It might be a good idea to code for the possibility that the field might include non-numeric data - like so:

If NumericText ({field}) then ToNumber ({field}) else 0

Alternatively, you might find it easier to convert the field's datatype within the query used in the report.

Get selected option from select element

This worked for me:

$("#SelectedCountryId_option_selected")[0].textContent

Hex to ascii string conversion

strtol() is your friend here. The third parameter is the numerical base that you are converting.

Example:

#include <stdio.h>      /* printf */
#include <stdlib.h>     /* strtol */

int main(int argc, char **argv)
{
    long int num  = 0;
    long int num2 =0;
    char * str. = "f00d";
    char * str2 = "0xf00d";

    num = strtol( str, 0, 16);  //converts hexadecimal string to long.
    num2 = strtol( str2, 0, 0); //conversion depends on the string passed in, 0x... Is hex, 0... Is octal and everything else is decimal.

    printf( "%ld\n", num);
    printf( "%ld\n", num);
}

Redirect with CodeIgniter

Here is .htacess file that hide index file

#RewriteEngine on
#RewriteCond $1 !^(index\.php|images|robots\.txt)
#RewriteRule ^(.*)$ /index.php/$1 [L]

<IfModule mod_rewrite.c>
        RewriteEngine On
        RewriteBase /

        # Removes index.php from ExpressionEngine URLs
        RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
        RewriteCond %{REQUEST_URI} !/system/.* [NC]
        RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,NE,L]

        # Directs all EE web requests through the site index file
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

Android: Access child views from a ListView

This assumes you know the position of the element in the ListView :

  View element = listView.getListAdapter().getView(position, null, null);

Then you should be able to call getLeft() and getTop() to determine the elements on screen position.

How to configure PostgreSQL to accept all incoming connections

0.0.0.0/0 for all IPv4 addresses

::0/0 for all IPv6 addresses

all to match any IP address

samehost to match any of the server's own IP addresses

samenet to match any address in any subnet that the server is directly connected to.

e.g.

host    all             all             0.0.0.0/0            md5

How should strace be used?

Strace is a tool that tells you how your application interacts with your operating system.

It does this by telling you what OS system calls your application uses and with what parameters it calls them.

So for instance you see what files your program tries to open, and weather the call succeeds.

You can debug all sorts of problems with this tool. For instance if application says that it cannot find library that you know you have installed you strace would tell you where the application is looking for that file.

And that is just a tip of the iceberg.

EntityType has no key defined error

There are several reasons this can happen. Some of these I found here, others I discovered on my own.

  • If the property is named something other than Id, you need to add the [Key] attribute to it.
  • The key needs to be a property, not a field.
  • The key needs to be public
  • The key needs to be a CLS-compliant type, meaning unsigned types like uint, ulong etc. are not allowed.
  • This error can also be caused by configuration mistakes.

Most efficient way to get table row count

$next_id = mysql_fetch_assoc(mysql_query("SELECT MAX(id) FROM table"));
$next_id['MAX(id)']; // next auto incr id

hope it helpful :)

What do &lt; and &gt; stand for?

&lt; stands for lesser than (<) symbol and, the &gt; sign stands for greater than (>) symbol.

For more information on HTML Entities, visit this link:

https://www.w3schools.com/HTML/html_entities.asp

Disable Pinch Zoom on Mobile Web

EDIT: Because this keeps getting commented on, we all know that we shouldn't do this. The question was how do I do it, not should I do it.

Add this into your for mobile devices. Then do your widths in percentages and you'll be fine:

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />

Add this in for devices that can't use viewport too:

<meta name="HandheldFriendly" content="true" />

DateTime.Today.ToString("dd/mm/yyyy") returns invalid DateTime Value

In addition to what the other answers have said, note that the '/' character in "dd/MM/yyyy" is not a literal character: it represents the date separator of the current user's culture. Therefore, if the current culture uses yyyy-MM-dd dates, then when you call toString it will give you a date such as "31-12-2016" (using dashes instead of slashes). To force it to use slashes, you need to escape that character:

DateTime.Now.ToString("dd/MM/yyyy")     --> "19-12-2016" for a Japanese user
DateTime.Now.ToString("dd/MM/yyyy")     --> "19/12/2016" for a UK user
DateTime.Now.ToString("dd\\/MM\\/yyyy") --> "19/12/2016" independent of region

How do you remove columns from a data.frame?

rm in within can be quite useful.

within(mtcars, rm(mpg, cyl, disp, hp))
#                     drat    wt  qsec vs am gear carb
# Mazda RX4           3.90 2.620 16.46  0  1    4    4
# Mazda RX4 Wag       3.90 2.875 17.02  0  1    4    4
# Datsun 710          3.85 2.320 18.61  1  1    4    1
# Hornet 4 Drive      3.08 3.215 19.44  1  0    3    1
# Hornet Sportabout   3.15 3.440 17.02  0  0    3    2
# Valiant             2.76 3.460 20.22  1  0    3    1
# ...

May be combined with other operations.

within(mtcars, {
  mpg2=mpg^2
  cyl2=cyl^2
  rm(mpg, cyl, disp, hp)
  })
#                     drat    wt  qsec vs am gear carb cyl2    mpg2
# Mazda RX4           3.90 2.620 16.46  0  1    4    4   36  441.00
# Mazda RX4 Wag       3.90 2.875 17.02  0  1    4    4   36  441.00
# Datsun 710          3.85 2.320 18.61  1  1    4    1   16  519.84
# Hornet 4 Drive      3.08 3.215 19.44  1  0    3    1   36  457.96
# Hornet Sportabout   3.15 3.440 17.02  0  0    3    2   64  349.69
# Valiant             2.76 3.460 20.22  1  0    3    1   36  327.61
# ...

How to access local files of the filesystem in the Android emulator?

You can use the adb command which comes in the tools dir of the SDK:

adb shell

It will give you a command line prompt where you can browse and access the filesystem. Or you can extract the files you want:

adb pull /sdcard/the_file_you_want.txt

Also, if you use eclipse with the ADT, there's a view to browse the file system (Window->Show View->Other... and choose Android->File Explorer)

MySQL Insert into multiple tables? (Database normalization?)

For PDO You may do this

$stmt1 = "INSERT INTO users (username, password) VALUES('test', 'test')"; 
$stmt2 = "INSERT INTO profiles (userid, bio, homepage) VALUES('LAST_INSERT_ID(),'Hello world!', 'http://www.stackoverflow.com')";

$sth1 = $dbh->prepare($stmt1);
$sth2 = $dbh->prepare($stmt2);

BEGIN;
$sth1->execute (array ('test','test'));
$sth2->execute (array ('Hello world!','http://www.stackoverflow.com'));
COMMIT;

Official reasons for "Software caused connection abort: socket write error"

In my case, I developped the client and the server side, and I have the exception :

Cause : error marshalling arguments; nested exception is: java.net.SocketException: Software caused connection abort: socket write error

when classes in client and server are different. I don't download server's classes (Interfaces) on the client, I juste add same files in the project. But the path must be exactly the same. For example, on the server project I have java\rmi\services packages with some serviceInterface and implementations, I have to create the same package on the client project. If I change it by java/rmi/server/services for example, I get the above exception. Same exception if the interface version is different between client and server (even with an empty row added inadvertently ... I think rmi makes a sort of hash of classes to check version ... I don't know... If it could help ...

Shrinking navigation bar when scrolling down (bootstrap3)

toggleClass works too:

$(window).on("scroll", function() {
    $("nav").toggleClass("shrink", $(this).scrollTop() > 50)
});

What's the proper value for a checked attribute of an HTML checkbox?

Strictly speaking, you should put something that makes sense - according to the spec here, the most correct version is:

<input name=name id=id type=checkbox checked=checked>

For HTML, you can also use the empty attribute syntax, checked="", or even simply checked (for stricter XHTML, this is not supported).

Effectively, however, most browsers will support just about any value between the quotes. All of the following will be checked:

<input name=name id=id type=checkbox checked>
<input name=name id=id type=checkbox checked="">
<input name=name id=id type=checkbox checked="yes">
<input name=name id=id type=checkbox checked="blue">
<input name=name id=id type=checkbox checked="false">

And only the following will be unchecked:

<input name=name id=id type=checkbox>

See also this similar question on disabled="disabled".

setValue:forUndefinedKey: this class is not key value coding-compliant for the key

Check your connections in Interface Builder. You're probably referring to a non existent IBOutlet or IBAction.

MSOnline can't be imported on PowerShell (Connect-MsolService error)

After hours of searching and trying I found out that on a x64 server the MSOnline modules must be installed for x64, and some programs that need to run them are using the x86 PS version, so they will never find it.

[SOLUTION] What I did to solve the issue was:

Copy the folders called MSOnline and MSOnline Extended from the source

C:\Windows\System32\WindowsPowerShell\v1.0\Modules\

to the folder

C:\Windows\SysWOW64\WindowsPowerShell\v1.0\Modules\

And then in PS run the Import-Module MSOnline, and it will automatically get the module :D

How do I push amended commit to the remote Git repository?

The following worked for me when changing Author and Committer of a commit.

git push -f origin master

Git was smart enough to figure out that these were commits of identical deltas which only differed in the meta information section.

Both the local and remote heads pointed to the commits in question.

How to echo (or print) to the js console with php

There are much better ways to print variable's value in PHP. One of them is to use buildin var_dump() function. If you want to use var_dump(), I would also suggest to install Xdebug (from https://xdebug.org) since it generates much more readable printouts.

The idea of printing values to browser console is somewhat bizarre, but if you really want to use it, there is very useful Google Chrome extension, PHP Console, which should satisfy all your needs. You can find it at consle.com It works well also in Vivaldi and in Opera (though you will need "Download Chrome Extension" extension to install it). The extension is accompanied by PHP library you use in your code.

How do I get the current location of an iframe?

You can access the src property of the iframe but that will only give you the initially loaded URL. If the user is navigating around in the iframe via you'll need to use an HTA to solve the security problem.

http://msdn.microsoft.com/en-us/library/ms536474(VS.85).aspx

Check out the link, using an HTA and setting the "application" property of an iframe will allow you to access the document.href property and parse out all of the information you want, including DOM elements and their values if you so choose.

.htaccess 301 redirect of single page

redirect 301 /contact.php /contact-us.php

There is no point using the redirectmatch rule and then have to write your links so they are exact match. If you don't include you don't have to exclude! Just use redirect without match and then use links normally

Parse Json string in C#

json:
[{"ew":"vehicles","hws":["car","van","bike","plane","bus"]},{"ew":"countries","hws":["America","India","France","Japan","South Africa"]}]

c# code: to take only a single value, for example the word "bike".

//res=[{"ew":"vehicles","hws":["car","van","bike","plane","bus"]},{"ew":"countries","hws":["America","India","France","Japan","South Africa"]}]

         dynamic stuff1 = Newtonsoft.Json.JsonConvert.DeserializeObject(res);
         string Text = stuff1[0].hws[2];
         Console.WriteLine(Text);

output:

bike

Setting POST variable without using form

If you want to set $_POST['text'] to another value, why not use:

$_POST['text'] = $var;

on next.php?

How do you clone an Array of Objects in Javascript?

I think managed to write a generic method of deep cloning any JavaScript structure mainly using Object.create which is supported in all modern browsers. The code is like this:

function deepClone (item) {
  if (Array.isArray(item)) {
    var newArr = [];

    for (var i = item.length; i-- !== 0;) {
      newArr[i] = deepClone(item[i]);
    }

    return newArr;
  }
  else if (typeof item === 'function') {
    eval('var temp = '+ item.toString());
    return temp;
  }
  else if (typeof item === 'object')
    return Object.create(item);
  else
    return item;
}

SQL alias for SELECT statement

You could store this into a temporary table.

So instead of doing the CTE/sub query you would use a temp table.

Good article on these here http://codingsight.com/introduction-to-temporary-tables-in-sql-server/

MySQL Database won't start in XAMPP Manager-osx

maybe table innodb error after u reinstal or copy file db try to repair tbl innodb, if table cant be repair try delete db or table

xamppfiles/var/mysql/your db

or

xamppfiles/var/mysql/your db/your table

change permission folder to open folder database

before delete backup ur folder database

SQL Server default character encoding

I think this is worthy of a separate answer: although internally unicode data is stored as UTF-16 in Sql Server this is the Little Endian flavour, so if you're calling the database from an external system, you probably need to specify UTF-16LE.

How to programmatically set the ForeColor of a label to its default?

The default (when created with the designer) is:

label.ForeColor = SystemColors.ControlText;

This should respect the system color settings (e.g. these "high contrast" schemes for visual impaired).

In c, in bool, true == 1 and false == 0?

More accurately anything that is not 0 is true.

So 1 is true, but so is 2, 3 ... etc.

What does "implements" do on a class?

An interface can be thought of as just a list of method definitions (without any body). If a class wants to implement and interface, it is entering into a contract, saying that it will provide an implementation for all of the methods listed in the interface. For more information, see http://download.oracle.com/javase/tutorial/java/concepts/

Create a <ul> and fill it based on a passed array

You may also consider the following solution:

let sum = options.set0.concat(options.set1);
const codeHTML = '<ol>' + sum.reduce((html, item) => {
    return html + "<li>" + item + "</li>";
        }, "") + '</ol>';
document.querySelector("#list").innerHTML = codeHTML;

How to get the home directory in Python?

You want to use os.path.expanduser.
This will ensure it works on all platforms:

from os.path import expanduser
home = expanduser("~")

If you're on Python 3.5+ you can use pathlib.Path.home():

from pathlib import Path
home = str(Path.home())

return SQL table as JSON in python

nobody seem to have offered the option to get the JSON directly from the Postgresql server, using the postgres JSON capability https://www.postgresql.org/docs/9.4/static/functions-json.html

No parsing, looping or any memory consumption on the python side, which you may really want to consider if you're dealing with 100,000's or millions of rows.

from django.db import connection

sql = 'SELECT to_json(result) FROM (SELECT * FROM TABLE table) result)'
with connection.cursor() as cursor:
  cursor.execute(sql)
  output = cursor.fetchall()

a table like:

id, value
----------
1     3
2     7

will return a Python JSON Object

[{"id": 1, "value": 3},{"id":2, "value": 7}]

Then use json.dumps to dump as a JSON string

How do I set the default locale in the JVM?

You can use JVM args

java -Duser.country=ES -Duser.language=es -Duser.variant=Traditional_WIN

Good way of getting the user's location in Android

I scoured the internet for an updated (past year) answer using the latest location pulling methods suggested by google (to use FusedLocationProviderClient). I finally landed on this:

https://github.com/googlesamples/android-play-location/tree/master/LocationUpdates

I created a new project and copied in most of this code. Boom. It works. And I think without any deprecated lines.

Also, the simulator doesn't seem to get a GPS location, that I know of. It did get as far as reporting this in the log: "All location settings are satisfied."

And finally, in case you wanted to know (I did), you DO NOT need a google maps api key from the google developer console, if all you want is the GPS location.

Also useful is their tutorial. But I wanted a full one page tutorial/code example, and that. Their tutorial stacks but is confusing when you're new to this because you don't know what pieces you need from earlier pages.

https://developer.android.com/training/location/index.html

And finally, remember things like this:

I not only had to modify the mainActivity.Java. I also had to modify Strings.xml, androidmanifest.xml, AND the correct build.gradle. And also your activity_Main.xml (but that part was easy for me).

I needed to add dependencies like this one: implementation 'com.google.android.gms:play-services-location:11.8.0', and update the settings of my android studio SDK to include google play services. (file settings appearance system settings android SDK SDK Tools check google play services).

update: the android simulator did seem to get a location and location change events (when I changed the value in the settings of the sim). But my best and first results were on an actual device. So it's probably easiest to test on actual devices.

What is android:ems attribute in Edit Text?

An "em" is a typographical unit of width, the width of a wide-ish letter like "m" pronounced "em". Similarly there is an "en". Similarly "en-dash" and "em-dash" for – and —

-Tim Bray

Should I size a textarea with CSS width / height or HTML cols / rows attributes?

HTML rows and cols are not responsive!

So I define the size in CSS. As a tip: if you define a small size for mobiles think about using textarea:focus {};

Add some extra space here, which will only unfold the moment a user wants to actually write something

How do you handle a form change in jQuery?

If you want to check if the form data, as it is going to be sent to the server, have changed, you can serialize the form data on page load and compare it to the current form data:

$(function() {

    var form_original_data = $("#myform").serialize(); 

    $("#mybutton").click(function() {
        if ($("#myform").serialize() != form_original_data) {
            // Something changed
        }
    });

});

Does a "Find in project..." feature exist in Eclipse IDE?

yes, but you need to open the global search panel. to do so, press the binoculars icon on the top right corner of the IDE.

you can even filter searches by function identifiers, method scopes an etc...

Is there a color code for transparent in HTML?

{background-color: transparent;}

Keras, How to get the output of each layer?

Well, other answers are very complete, but there is a very basic way to "see", not to "get" the shapes.

Just do a model.summary(). It will print all layers and their output shapes. "None" values will indicate variable dimensions, and the first dimension will be the batch size.

How to Insert BOOL Value to MySQL Database

TRUE and FALSE are keywords, and should not be quoted as strings:

INSERT INTO first VALUES (NULL, 'G22', TRUE);
INSERT INTO first VALUES (NULL, 'G23', FALSE);

By quoting them as strings, MySQL will then cast them to their integer equivalent (since booleans are really just a one-byte INT in MySQL), which translates into zero for any non-numeric string. Thus, you get 0 for both values in your table.

Non-numeric strings cast to zero:

mysql> SELECT CAST('TRUE' AS SIGNED), CAST('FALSE' AS SIGNED), CAST('12345' AS SIGNED);
+------------------------+-------------------------+-------------------------+
| CAST('TRUE' AS SIGNED) | CAST('FALSE' AS SIGNED) | CAST('12345' AS SIGNED) |
+------------------------+-------------------------+-------------------------+
|                      0 |                       0 |                   12345 |
+------------------------+-------------------------+-------------------------+

But the keywords return their corresponding INT representation:

mysql> SELECT TRUE, FALSE;
+------+-------+
| TRUE | FALSE |
+------+-------+
|    1 |     0 |
+------+-------+

Note also, that I have replaced your double-quotes with single quotes as are more standard SQL string enclosures. Finally, I have replaced your empty strings for id with NULL. The empty string may issue a warning.

Simplest way to do a recursive self-join?

The Quassnoi query with a change for large table. Parents with more childs then 10: Formating as str(5) the row_number()

WITH    q AS 
        (
        SELECT  m.*, CAST(str(ROW_NUMBER() OVER (ORDER BY m.ordernum),5) AS VARCHAR(MAX)) COLLATE Latin1_General_BIN AS bc
        FROM    #t m
        WHERE   ParentID =0
        UNION ALL
        SELECT  m.*,  q.bc + '.' + str(ROW_NUMBER()  OVER (PARTITION BY m.ParentID ORDER BY m.ordernum),5) COLLATE Latin1_General_BIN
        FROM    #t m
        JOIN    q
        ON      m.parentID = q.DBID
        )
SELECT  *
FROM    q
ORDER BY
        bc

Modifying local variable from inside lambda

I know that's an old question, but if you are comfortable with a workaround, considering the fact that the external variable should be final, you can simply do this:

final int[] ordinal = new int[1];
list.forEach(s -> {
    s.setOrdinal(ordinal[0]);
    ordinal[0]++;
});

Maybe not the most elegant, or even the most correct, but it will do.

How to copy a folder via cmd?

xcopy  "C:\Documents and Settings\user\Desktop\?????????" "D:\Backup" /s /e /y /i

Probably the problem is the space.Try with quotes.

I'm getting an error "invalid use of incomplete type 'class map'

I am just providing another case where you can get this error message. The solution will be the same as Adam has mentioned above. This is from a real code and I renamed the class name.

class FooReader {
  public:
     /** Constructor */
     FooReader() : d(new FooReaderPrivate(this)) { }  // will not compile here
     .......
  private:
     FooReaderPrivate* d;
};

====== In a separate file =====
class FooReaderPrivate {
  public:
     FooReaderPrivate(FooReader*) : parent(p) { }
  private:
     FooReader* parent;
};

The above will no pass the compiler and get error: invalid use of incomplete type FooReaderPrivate. You basically have to put the inline portion into the *.cpp implementation file. This is OK. What I am trying to say here is that you may have a design issue. Cross reference of two classes may be necessary some cases, but I would say it is better to avoid them at the start of the design. I would be wrong, but please comment then I will update my posting.

Is there a method that tells my program to quit?

The actual way to end a program, is to call

raise SystemExit

It's what sys.exit does, anyway.

A plain SystemExit, or with None as a single argument, sets the process' exit code to zero. Any non-integer exception value (raise SystemExit("some message")) prints the exception value to sys.stderr and sets the exit code to 1. An integer value sets the process' exit code to the value:

$ python -c "raise SystemExit(4)"; echo $?
4