Programs & Examples On #Environment

The O/S in which a process is executed, especially settings that affect the process

Change the current directory from a Bash script

I've made a script to change directory. take a look: https://github.com/ygpark/dj

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

A good place to look at is the man page of bash. Here's an online version. Look for "INVOCATION" section.

How do I find the current machine's full hostname in C (hostname and domain information)?

I believe you are looking for:

gethostbyaddress

Just pass it the localhost IP.

There is also a gethostbyname function, that is also usefull.

How to generate .env file for laravel?

.env files are hidden by Netbeans. To show them do this:

Tools > Options > Miscellaneous > Files

Under Files Ignored be the IDE is Ignored Files Pattern:

The default is

^(CVS|SCCS|vssver.?\.scc|#.*#|%.*%|_svn)$|~$|^\.(?!(htaccess|git.+|hgignore)$).*$

Add env to the excluded-not-excluded bit

^(CVS|SCCS|vssver.?\.scc|#.*#|%.*%|_svn)$|~$|^\.(?!(env|htaccess|git.+|hgignore)$).*$

Files named .env now show.

Java system properties and environment variables

I think the difference between the two boils down to access. Environment variables are accessible by any process and Java system properties are only accessible by the process they are added to.

Also as Bohemian stated, env variables are set in the OS (however they 'can' be set through Java) and system properties are passed as command line options or set via setProperty().

Set windows environment variables with a batch file

@ECHO OFF

:: %HOMEDRIVE% = C:
:: %HOMEPATH% = \Users\Ruben
:: %system32% ??
:: No spaces in paths
:: Program Files > ProgramFiles
:: cls = clear screen
:: CMD reads the system environment variables when it starts. To re-read those variables you need to restart CMD
:: Use console 2 http://sourceforge.net/projects/console/


:: Assign all Path variables
SET PHP="%HOMEDRIVE%\wamp\bin\php\php5.4.16"
SET SYSTEM32=";%HOMEDRIVE%\Windows\System32"
SET ANT=";%HOMEDRIVE%%HOMEPATH%\Downloads\apache-ant-1.9.0-bin\apache-ant-1.9.0\bin"
SET GRADLE=";%HOMEDRIVE%\tools\gradle-1.6\bin;"
SET ADT=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\eclipse\jre\bin"
SET ADTTOOLS=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\tools"
SET ADTP=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\platform-tools"
SET YII=";%HOMEDRIVE%\wamp\www\yii\framework"
SET NODEJS=";%HOMEDRIVE%\ProgramFiles\nodejs"
SET CURL=";%HOMEDRIVE%\tools\curl_734_0_ssl"
SET COMPOSER=";%HOMEDRIVE%\ProgramData\ComposerSetup\bin"
SET GIT=";%HOMEDRIVE%\Program Files\Git\cmd"

:: Set Path variable
setx PATH "%PHP%%SYSTEM32%%NODEJS%%COMPOSER%%YII%%GIT%" /m

:: Set Java variable
setx JAVA_HOME "%HOMEDRIVE%\ProgramFiles\Java\jdk1.7.0_21" /m

PAUSE

Changing default shell in Linux

Try linux command chsh.

The detailed command is chsh -s /bin/bash. It will prompt you to enter your password. Your default login shell is /bin/bash now. You must log out and log back in to see this change.

The following is quoted from man page:

The chsh command changes the user login shell. This determines the name of the users initial login command. A normal user may only change the login shell for her own account, the superuser may change the login shell for any account

This command will change the default login shell permanently.

Note: If your user account is remote such as on Kerberos authentication (e.g. Enterprise RHEL) then you will not be able to use chsh.

How can I get the current user directory?

Messing around with environment variables or hard-coded parent folder offsets is never a good idea when there is a API to get the info you want, call SHGetSpecialFolderPath(...,CSIDL_PROFILE,...)

Environment variables in Eclipse

You can set the Hadoop home directory by sending a -Dhadoop.home.dir to the VM. To send this parameters to all your application that you execute inside eclipse, you can set them in Window->Preferences->Java->Installed JREs-> (select your JRE installation) -> Edit.. -> (set the value in the "Default VM arguments:" textbox). You can replace ${HADOOP_HOME} with the path to your Hadoop installation.

Select the JRE you use for running programs in Eclipse

Sending the value for hadoop.home.dir property as a VM argument

Windows 7 environment variable not working in path

Make sure both your System and User paths are set correctly.

Java current machine name and logged in user?

To get the currently logged in user:

System.getProperty("user.name");

To get the host name of the machine:

InetAddress.getLocalHost().getHostName();

To answer the last part of your question, the Java API says that getHostName() will return

the host name for this IP address, or if the operation is not allowed by the security check, the textual representation of the IP address.

How to find the path of the local git repository when I am possibly in a subdirectory

git rev-parse --show-toplevel

could be enough if executed within a git repo.
From git rev-parse man page:

--show-toplevel

Show the absolute path of the top-level directory.

For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":

git rev-parse --git-dir

That would give the path of the .git directory.


The OP mentions:

git rev-parse --show-prefix

which returns the local path under the git repo root. (empty if you are at the git repo root)


Note: for simply checking if one is in a git repo, I find the following command quite expressive:

git rev-parse --is-inside-work-tree

And yes, if you need to check if you are in a .git git-dir folder:

git rev-parse --is-inside-git-dir

Using Pip to install packages to Anaconda Environment

If you ONLY want to have a conda installation. Just remove all of the other python paths from your PATH variable.

Leaving only:

C:\ProgramData\Anaconda3
C:\ProgramData\Anaconda3\Scripts
C:\ProgramData\Anaconda3\Library\bin

This allows you to just use pip install * and it will install straight into your conda installation.

How to use an environment variable inside a quoted string in Bash

If unsure, you might use the 'cols' request on the terminal, and forget COLUMNS:

COLS=$(tput cols)

How do I get the path of a process in Unix / Linux

thanks : Kiwy
with AIX:

getPathByPid()
{
    if [[ -e /proc/$1/object/a.out ]]; then
        inode=`ls -i /proc/$1/object/a.out 2>/dev/null | awk '{print $1}'`
        if [[ $? -eq 0 ]]; then
            strnode=${inode}"$"
            strNum=`ls -li /proc/$1/object/ 2>/dev/null | grep $strnode | awk '{print $NF}' | grep "[0-9]\{1,\}\.[0-9]\{1,\}\."`
            if [[ $? -eq 0 ]]; then
                # jfs2.10.6.5869
                n1=`echo $strNum|awk -F"." '{print $2}'`
                n2=`echo $strNum|awk -F"." '{print $3}'`
                # brw-rw----    1 root     system       10,  6 Aug 23 2013  hd9var
                strexp="^b.*"$n1,"[[:space:]]\{1,\}"$n2"[[:space:]]\{1,\}.*$"   # "^b.*10, \{1,\}5 \{1,\}.*$"
                strdf=`ls -l /dev/ | grep $strexp | awk '{print $NF}'`
                if [[ $? -eq 0 ]]; then
                    strMpath=`df | grep $strdf | awk '{print $NF}'`
                    if [[ $? -eq 0 ]]; then
                        find $strMpath -inum $inode 2>/dev/null
                        if [[ $? -eq 0 ]]; then
                            return 0
                        fi
                    fi
                fi
            fi
        fi
    fi
    return 1
}

Setting up Eclipse with JRE Path

You can add this line to eclipse.ini :

-vm 
D:/work/Java/jdk1.6.0_13/bin/javaw.exe  <-- change to your JDK actual path
-vmargs <-- needs to be after -vm <path>

But it's worth setting JAVA_HOME and JRE_HOME anyway because it may not work as if the path environment points to a different java version.

Because the next one to complain will be Maven, etc.

About .bash_profile, .bashrc, and where should alias be written in?

.bash_profile is loaded for a "login shell". I am not sure what that would be on OS X, but on Linux that is either X11 or a virtual terminal.

.bashrc is loaded every time you run Bash. That is where you should put stuff you want loaded whenever you open a new Terminal.app window.

I personally put everything in .bashrc so that I don't have to restart the application for changes to take effect.

Error: Registry key 'Software\JavaSoft\Java Runtime Environment'\CurrentVersion'?

Other times you might have installed Java 7 and 8 both or twice, and from Add/remove programs unistall one of them and it should work.

What is Cache-Control: private?

RFC 2616, section 14.9.1:

Indicates that all or part of the response message is intended for a single user and MUST NOT be cached by a shared cache...A private (non-shared) cache MAY cache the response.


Browsers could use this information. Of course, the current "user" may mean many things: OS user, a browser user (e.g. Chrome's profiles), etc. It's not specified.

For me, a more concrete example of Cache-Control: private is that proxy servers (which typically have many users) won't cache it. It is meant for the end user, and no one else.


FYI, the RFC makes clear that this does not provide security. It is about showing the correct content, not securing content.

This usage of the word private only controls where the response may be cached, and cannot ensure the privacy of the message content.

C: How to free nodes in the linked list?

You could always do it recursively like so:

void freeList(struct node* currentNode)
{
    if(currentNode->next) freeList(currentNode->next);
    free(currentNode);
}

How to set Spinner Default by its Value instead of Position?

If you are setting the spinner values by arraylist or array you can set the spinner's selection by using the index of the value.

String myString = "some value"; //the value you want the position for

ArrayAdapter myAdap = (ArrayAdapter) mySpinner.getAdapter(); //cast to an ArrayAdapter

int spinnerPosition = myAdap.getPosition(myString);

//set the default according to value
spinner.setSelection(spinnerPosition);

see the link How to set selected item of Spinner by value, not by position?

C# Test if user has write access to a folder

Your code gets the DirectorySecurity for a given directory, and handles an exception (due to your not having access to the security info) correctly. However, in your sample you don't actually interrogate the returned object to see what access is allowed - and I think you need to add this in.

Linear regression with matplotlib / numpy

arange generates lists (well, numpy arrays); type help(np.arange) for the details. You don't need to call it on existing lists.

>>> x = [1,2,3,4]
>>> y = [3,5,7,9] 
>>> 
>>> m,b = np.polyfit(x, y, 1)
>>> m
2.0000000000000009
>>> b
0.99999999999999833

I should add that I tend to use poly1d here rather than write out "m*x+b" and the higher-order equivalents, so my version of your code would look something like this:

import numpy as np
import matplotlib.pyplot as plt

x = [1,2,3,4]
y = [3,5,7,10] # 10, not 9, so the fit isn't perfect

coef = np.polyfit(x,y,1)
poly1d_fn = np.poly1d(coef) 
# poly1d_fn is now a function which takes in x and returns an estimate for y

plt.plot(x,y, 'yo', x, poly1d_fn(x), '--k')
plt.xlim(0, 5)
plt.ylim(0, 12)

enter image description here

How do I load an org.w3c.dom.Document from XML in a string?

To manipulate XML in Java, I always tend to use the Transformer API:

import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.stream.StreamSource;

public static Document loadXMLFrom(String xml) throws TransformerException {
    Source source = new StreamSource(new StringReader(xml));
    DOMResult result = new DOMResult();
    TransformerFactory.newInstance().newTransformer().transform(source , result);
    return (Document) result.getNode();
}   

adding child nodes in treeview

May i add to Stormenet example some KISS (Keep It Simple & Stupid):

If you already have a treeView or just created an instance of it: Let's populate with some data - Ex. One parent two child's :

            treeView1.Nodes.Add("ParentKey","Parent Text");
            treeView1.Nodes["ParentKey"].Nodes.Add("Child-1 Text");
            treeView1.Nodes["ParentKey"].Nodes.Add("Child-2 Text");

Another Ex. two parent's first have two child's second one child:

            treeView1.Nodes.Add("ParentKey1","Parent-1  Text");
            treeView1.Nodes.Add("ParentKey2","Parent-2 Text");
            treeView1.Nodes["ParentKey1"].Nodes.Add("Child-1 Text");
            treeView1.Nodes["ParentKey1"].Nodes.Add("Child-2 Text");
            treeView1.Nodes["ParentKey2"].Nodes.Add("Child-3 Text");

Take if farther - sub child of child 2:

            treeView1.Nodes.Add("ParentKey1","Parent-1  Text");
            treeView1.Nodes["ParentKey1"].Nodes.Add("Child-1 Text");
            treeView1.Nodes["ParentKey1"].Nodes.Add("ChildKey2","Child-2 Text");
            treeView1.Nodes["ParentKey1"].Nodes["ChildKey2"].Nodes.Add("Child-3 Text");

As you see you can have as many child's and parent's as you want and those can have sub child's of child's and so on.... Hope i help!

'git' is not recognized as an internal or external command

If you are using GitHub for Windows (GitHub's old Git GUI that is no longer available for download, not the new Electron-based GitHub Desktop), you have an installation of Git under:

C:\Users\<YOUR USERNAME>\AppData\Local\GitHub\PortableGit_8810fd5c2c79c73adcc73fd0825f3b32fdb816e7\cmd

Expand this path, and add it to PATH.

TypeError: a bytes-like object is required, not 'str'

Encoding and decoding can solve this in Python 3:

Client Side:

>>> host='127.0.0.1'
>>> port=1337
>>> import socket
>>> s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
>>> s.connect((host,port))
>>> st='connection done'
>>> byt=st.encode()
>>> s.send(byt)
15
>>>

Server Side:

>>> host=''
>>> port=1337
>>> import socket
>>> s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
>>> s.bind((host,port))
>>> s.listen(1)
>>> conn ,addr=s.accept()
>>> data=conn.recv(2000)
>>> data.decode()
'connection done'
>>>

format a number with commas and decimals in C# (asp.net MVC3)

All that is needed is "#,0.00", c# does the rest.

Num.ToString("#,0.00"")

  • The "#,0" formats the thousand separators
  • "0.00" forces two decimal points

Get top first record from duplicate records having no unique identity

YOur best bet is to fix the datbase design and add the identioty column to the table. Why do you havea table without one in the first place? Especially one with duplicate records! Clearly the database itself needs redesigning.

And why do you have to have this in a view, why isn't your solution with the temp table a valid solution? Views are not usually a really good thing to do to a perfectly nice database.

How to work with progress indicator in flutter?

Step 1: Create Dialog

   showAlertDialog(BuildContext context){
      AlertDialog alert=AlertDialog(
        content: new Row(
            children: [
               CircularProgressIndicator(),
               Container(margin: EdgeInsets.only(left: 5),child:Text("Loading" )),
            ],),
      );
      showDialog(barrierDismissible: false,
        context:context,
        builder:(BuildContext context){
          return alert;
        },
      );
    }

Step 2:Call it

showAlertDialog(context);
await firebaseAuth.signInWithEmailAndPassword(email: email, password: password);
Navigator.pop(context);

Example With Dialog and login form

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
class DynamicLayout extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new MyWidget();
    }
  }
showAlertDialog(BuildContext context){
  AlertDialog alert=AlertDialog(
    content: new Row(
        children: [
           CircularProgressIndicator(),
           Container(margin: EdgeInsets.only(left: 5),child:Text("Loading" )),
        ],),
  );
  showDialog(barrierDismissible: false,
    context:context,
    builder:(BuildContext context){
      return alert;
    },
  );
}

  class MyWidget extends State<DynamicLayout>{
  Color color = Colors.indigoAccent;
  String title='app';
  GlobalKey<FormState> globalKey=GlobalKey<FormState>();
  String email,password;
  login() async{
   var currentState= globalKey.currentState;
   if(currentState.validate()){
        currentState.save();
        FirebaseAuth firebaseAuth=FirebaseAuth.instance;
        try {
          showAlertDialog(context);
          AuthResult authResult=await firebaseAuth.signInWithEmailAndPassword(
              email: email, password: password);
          FirebaseUser user=authResult.user;
          Navigator.pop(context);
        }catch(e){
          print(e);
        }
   }else{

   }
  }
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar:AppBar(
        title: Text("$title"),
        ) ,
          body: Container(child: Form(
            key: globalKey,
            child: Container(
              padding: EdgeInsets.all(10),
              child: Column(children: <Widget>[
              TextFormField(decoration: InputDecoration(icon: Icon(Icons.email),labelText: 'Email'),
              // ignore: missing_return
              validator:(val){
                if(val.isEmpty)
                  return 'Please Enter Your Email';
              },
              onSaved:(val){
                email=val;
              },
              ),
                TextFormField(decoration: InputDecoration(icon: Icon(Icons.lock),labelText: 'Password'),
             obscureText: true,
                  // ignore: missing_return
                  validator:(val){
                    if(val.isEmpty)
                      return 'Please Enter Your Password';
                  },
                  onSaved:(val){
                    password=val;
                  },
              ),
                RaisedButton(color: Colors.lightBlue,textColor: Colors.white,child: Text('Login'),
                  onPressed:login),
            ],)
              ,),)
         ),
    );
  }
}

enter image description here

How do I declare class-level properties in Objective-C?

properties have a specific meaning in Objective-C, but I think you mean something that's equivalent to a static variable? E.g. only one instance for all types of Foo?

To declare class functions in Objective-C you use the + prefix instead of - so your implementation would look something like:

// Foo.h
@interface Foo {
}

+ (NSDictionary *)dictionary;

// Foo.m
+ (NSDictionary *)dictionary {
  static NSDictionary *fooDict = nil;
  if (fooDict == nil) {
    // create dict
  }
  return fooDict;
}

How to make a phone call using intent in Android?

In Android for certain functionalities you need to add the permission to the Manifest file.

  1. Go to the Projects AndroidManifest.xml
  2. Click on the Permissions Tab
  3. Click on Add
  4. Select Uses Permission
  5. See the snapshot belowenter image description here

6.Save the manifest file and then run your project. Your project now should run as expected.

Correct way to import lodash

If you are using babel, you should check out babel-plugin-lodash, it will cherry-pick the parts of lodash you are using for you, less hassle and a smaller bundle.

It has a few limitations:

  • You must use ES2015 imports to load Lodash
  • Babel < 6 & Node.js < 4 aren’t supported
  • Chain sequences aren’t supported. See this blog post for alternatives.
  • Modularized method packages aren’t supported

How to recompile with -fPIC

Before compiling make sure that "rules.mk" file is included properly in Makefile or include it explicitly by:

"source rules.mk"

Proper Linq where clauses

EDIT: LINQ to Objects doesn't behave how I'd expected it to. You may well be interested in the blog post I've just written about this...


They're different in terms of what will be called - the first is equivalent to:

Collection.Where(x => x.Age == 10)
          .Where(x => x.Name == "Fido")
          .Where(x => x.Fat == true)

wheras the latter is equivalent to:

Collection.Where(x => x.Age == 10 && 
                      x.Name == "Fido" &&
                      x.Fat == true)

Now what difference that actually makes depends on the implementation of Where being called. If it's a SQL-based provider, I'd expect the two to end up creating the same SQL. If it's in LINQ to Objects, the second will have fewer levels of indirection (there'll be just two iterators involved instead of four). Whether those levels of indirection are significant in terms of speed is a different matter.

Typically I would use several where clauses if they feel like they're representing significantly different conditions (e.g. one is to do with one part of an object, and one is completely separate) and one where clause when various conditions are closely related (e.g. a particular value is greater than a minimum and less than a maximum). Basically it's worth considering readability before any slight performance difference.

How to delete migration files in Rails 3

We can use,

$ rails d migration table_name  

Which will delete the migration.

Getting multiple values with scanf()

Yes.

int minx, miny, maxx,maxy;
do {
   printf("enter four integers: ");
} while (scanf("%d %d %d %d", &minx, &miny, &maxx, &maxy)!=4);

The loop is just to demonstrate that scanf returns the number of fields succesfully read (or EOF).

How to disable the parent form when a child form is active?

While using the previously mentioned childForm.ShowDialog(this) will disable your main form, it still doesent look very disabled. However if you call Enabled = false before ShowDialog() and Enable = true after you call ShowDialog() the main form will even look like it is disabled.

var childForm = new Form();
Enabled = false;
childForm .ShowDialog(this);
Enabled = true;

How can I get the "network" time, (from the "Automatic" setting called "Use network-provided values"), NOT the time on the phone?

Now you can get time for the current location but for this you have to set the system's persistent default time zone.setTimeZone(String timeZone) which can be get from

Calendar calendar = Calendar.getInstance();
 long now = calendar.getTimeInMillis();
 TimeZone current = calendar.getTimeZone();

setAutoTimeEnabled(boolean enabled)

Sets whether or not wall clock time should sync with automatic time updates from NTP.

TimeManager timeManager = TimeManager.getInstance();
 // Use 24-hour time
 timeManager.setTimeFormat(TimeManager.FORMAT_24);

 // Set clock time to noon
 Calendar calendar = Calendar.getInstance();
 calendar.set(Calendar.MILLISECOND, 0);
 calendar.set(Calendar.SECOND, 0);
 calendar.set(Calendar.MINUTE, 0);
 calendar.set(Calendar.HOUR_OF_DAY, 12);
 long timeStamp = calendar.getTimeInMillis();
 timeManager.setTime(timeStamp);

I was looking for that type of answer I read your answer but didn't satisfied and it was bit old. I found the new solution and share it. :)

For more information visit: https://developer.android.com/things/reference/com/google/android/things/device/TimeManager.html

PostgreSQL: Drop PostgreSQL database through command line

You can run the dropdb command from the command line:

dropdb 'database name'

Note that you have to be a superuser or the database owner to be able to drop it.

You can also check the pg_stat_activity view to see what type of activity is currently taking place against your database, including all idle processes.

SELECT * FROM pg_stat_activity WHERE datname='database name';

Note that from PostgreSQL v13 on, you can disconnect the users automatically with

DROP DATABASE dbname FORCE;

or

dropdb -f dbname

Can't load AMD 64-bit .dll on a IA 32-bit platform

If you are still getting that error after installing the 64 bit JRE, it means that the JVM running Gurobi package is still using the 32 bit JRE.

Check that you have updated the PATH and JAVA_HOME globally and in the command shell that you are using. (Maybe you just need to exit and restart it.)

Check that your command shell runs the right version of Java by running "java -version" and checking that it says it is a 64bit JRE.

If you are launching the example via a wrapper script / batch file, make sure that the script is using the right JRE. Modify as required ...

how we add or remove readonly attribute from textbox on clicking radion button in cakephp using jquery?

In your Case you can write the following jquery code:

$(document).ready(function(){

   $('.staff_on_site').click(function(){

     var rBtnVal = $(this).val();

     if(rBtnVal == "yes"){
         $("#no_of_staff").attr("readonly", false); 
     }
     else{ 
         $("#no_of_staff").attr("readonly", true); 
     }
   });
});

Here is the Fiddle: http://jsfiddle.net/P4QWx/3/

HTTP Basic Authentication - what's the expected web browser experience?

If there are no credentials provided in the request headers, the following is the minimum response required for IE to prompt the user for credentials and resubmit the request.

Response.Clear();
Response.StatusCode = (Int32)HttpStatusCode.Unauthorized;
Response.AddHeader("WWW-Authenticate", "Basic");

equivalent of vbCrLf in c#

Add a reference to Microsoft.VisualBasic to your project.

Then insert the using statement

using Microsoft.VisualBasic;

Use the defined constant vbCrLf:

private const string myString = "abc" + Constants.vbCrLf;

Regular expression to get a string between two strings in Javascript

A lookahead (that (?= part) does not consume any input. It is a zero-width assertion (as are boundary checks and lookbehinds).

You want a regular match here, to consume the cow portion. To capture the portion in between, you use a capturing group (just put the portion of pattern you want to capture inside parenthesis):

cow(.*)milk

No lookaheads are needed at all.

How to subtract days from a plain Date?

I find a problem with the getDate()/setDate() method is that it too easily turns everything into milliseconds, and the syntax is sometimes hard for me to follow.

Instead I like to work off the fact that 1 day = 86,400,000 milliseconds.

So, for your particular question:

today = new Date()
days = 86400000 //number of milliseconds in a day
fiveDaysAgo = new Date(today - (5*days))

Works like a charm.

I use this method all the time for doing rolling 30/60/365 day calculations.

You can easily extrapolate this to create units of time for months, years, etc.

wget command to download a file and save as a different filename

You would use the command Mechanical snail listed. Notice the uppercase O. Full command line to use could be:

wget www.examplesite.com/textfile.txt --output-document=newfile.txt

or

wget www.examplesite.com/textfile.txt -O newfile.txt

Hope that helps.

How to get response from S3 getObject in Node.js?

When doing a getObject() from the S3 API, per the docs the contents of your file are located in the Body property, which you can see from your sample output. You should have code that looks something like the following

const aws = require('aws-sdk');
const s3 = new aws.S3(); // Pass in opts to S3 if necessary

var getParams = {
    Bucket: 'abc', // your bucket name,
    Key: 'abc.txt' // path to the object you're looking for
}

s3.getObject(getParams, function(err, data) {
    // Handle any error and exit
    if (err)
        return err;

  // No error happened
  // Convert Body from a Buffer to a String

  let objectData = data.Body.toString('utf-8'); // Use the encoding necessary
});

You may not need to create a new buffer from the data.Body object but if you need you can use the sample above to achieve that.

Specified argument was out of the range of valid values. Parameter name: site

  • Navigate to Control Panel > Programs > Programs and Features and repair the IIS Express.
  • Restart the visual studio.

To turn on the IIS is not recommended as other comments suggests if you are not using your system as a live server. For development purpose only IIS Express is adequate.

Currency format for display

The problem with taking a given number and displaying it with .ToString("C", culture) is that it effectively changes the amount to the default currency of the given culture. If you have a given amount, the ISO currency code of that amount, and you want to display it for a given culture, I would recommend just creating a decimal extension method like the one below. This will not automatically assume that the currency is in the default currency of the culture:

public static string ToFormattedCurrencyString(
    this decimal currencyAmount,
    string isoCurrencyCode,
CultureInfo userCulture)
{
    var userCurrencyCode = new RegionInfo(userCulture.Name).ISOCurrencySymbol;

    if (userCurrencyCode == isoCurrencyCode)
    {
        return currencyAmount.ToString("C", userCulture);
    }

    return string.Format(
        "{0} {1}", 
        isoCurrencyCode, 
        currencyAmount.ToString("N2", userCulture));
}

This will either use the local currency symbol or the ISO currency code with the amount -- whichever is more appropriate. More on the topic in this blog post.

git rebase fatal: Needed a single revision

git submodule deinit --all -f worked for me.

SQL select max(date) and corresponding value

Ah yes, that is how it is intended in SQL. You get the Max of every column seperately. It seems like you want to return values from the row with the max date, so you have to select the row with the max date. I prefer to do this with a subselect, as the queries keep compact easy to read.

SELECT TrainingID, CompletedDate, Notes
FROM HR_EmployeeTrainings ET 
WHERE (ET.AvantiRecID IS NULL OR ET.AvantiRecID = @avantiRecID) 
AND CompletedDate in 
   (Select Max(CompletedDate) from HR_EmployeeTrainings B
    where B.TrainingID = ET.TrainingID)

If you also want to match by AntiRecID you should include that in the subselect as well.

Add/remove class with jquery based on vertical scroll?

Add some transition effect to it if you like:

http://jsbin.com/boreme/17/edit?html,css,js

.clearHeader {
  height:50px;
  background:lightblue;
  position:fixed;
  top:0;
  left:0;
  width:100%;

  -webkit-transition: background 2s; /* For Safari 3.1 to 6.0 */
  transition: background 2s;
}

.clearHeader.darkHeader {
 background:#000;
}

Best C/C++ Network Library

Aggregated List of Libraries

Adjust icon size of Floating action button (fab)

As your content is 24dp x 24dp you should use 24dp icon. And then set android:scaleType="center" in your ImageButton to avoid auto resize.

What is the difference between AF_INET and PF_INET in socket programming?

Checking the header file solve's the problem. One can check for there system compiler.

For my system , AF_INET == PF_INET

AF == Address Family And PF == Protocol Family

Protocol families, same as address families.

enter image description here

Change the image source on rollover using jQuery

$('img.over').each(function(){
    var t=$(this);
    var src1= t.attr('src'); // initial src
    var newSrc = src1.substring(0, src1.lastIndexOf('.'));; // let's get file name without extension
    t.hover(function(){
        $(this).attr('src', newSrc+ '-over.' + /[^.]+$/.exec(src1)); //last part is for extension   
    }, function(){
        $(this).attr('src', newSrc + '.' + /[^.]+$/.exec(src1)); //removing '-over' from the name
    });
});

You may want to change the class of images from first line. If you need more image classes (or different path) you may use

$('img.over, #container img, img.anotherOver').each(function(){

and so on.

It should work, I didn't test it :)

Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\

mysqli_select_db() should have 2 parameters, the connection link and the database name -

mysqli_select_db($con, 'phpcadet') or die(mysqli_error($con));

Using mysqli_error in the die statement will tell you exactly what is wrong as opposed to a generic error message.

Clearing localStorage in javascript?

localStorage.clear();

or

window.localStorage.clear();

to clear particular item

window.localStorage.removeItem("item_name");

To remove particular value by id :

var item_detail = JSON.parse(localStorage.getItem("key_name")) || [];           
            $.each(item_detail, function(index, obj){
                if (key_id == data('key')) {
                    item_detail.splice(index,1);
                    localStorage["key_name"] = JSON.stringify(item_detail);
                    return false;
                }
            });

Python copy files to a new directory and rename if file name already exists

I always use the time-stamp - so its not possible, that the file exists already:

import os
import shutil
import datetime

now = str(datetime.datetime.now())[:19]
now = now.replace(":","_")

src_dir="C:\\Users\\Asus\\Desktop\\Versand Verwaltung\\Versand.xlsx"
dst_dir="C:\\Users\\Asus\\Desktop\\Versand Verwaltung\\Versand_"+str(now)+".xlsx"
shutil.copy(src_dir,dst_dir)

Callback to a Fragment from a DialogFragment

Updated:

I made a library based on my gist code that generates those casting for you by using @CallbackFragment and @Callback.

https://github.com/zeroarst/callbackfragment.

And the example give you the example that send a callback from a fragment to another fragment.

Old answer:

I made a BaseCallbackFragment and annotation @FragmentCallback. It currently extends Fragment, you can change it to DialogFragment and will work. It checks the implementations with the following order: getTargetFragment() > getParentFragment() > context (activity).

Then you just need to extend it and declare your interfaces in your fragment and give it the annotation, and the base fragment will do the rest. The annotation also has a parameter mandatory for you to determine whether you want to force the fragment to implement the callback.

public class EchoFragment extends BaseCallbackFragment {

    private FragmentInteractionListener mListener;

    @FragmentCallback
    public interface FragmentInteractionListener {
        void onEcho(EchoFragment fragment, String echo);
    }
}

https://gist.github.com/zeroarst/3b3f32092d58698a4568cdb0919c9a93

Updating the value of data attribute using jQuery

$('.toggle img').data('block', 'something').attr('src', 'something.jpg');

Get last 5 characters in a string

The accepted answer of this post will cause error in the case when the string length is lest than 5. So i have a better solution. We can use this simple code :

If(str.Length <= 5, str, str.Substring(str.Length - 5))

You can test it with variable length string.

    Dim str, result As String
    str = "11!"
    result = If(str.Length <= 5, str, str.Substring(str.Length - 5))
    MessageBox.Show(result)
    str = "I will be going to school in 2011!"
    result = If(str.Length <= 5, str, str.Substring(str.Length - 5))
    MessageBox.Show(result)

Another simple but efficient solution i found :

str.Substring(str.Length - Math.Min(5, str.Length))

Can you use a trailing comma in a JSON object?

Use JSON5. Don't use JSON.

  • Objects and arrays can have trailing commas
  • Object keys can be unquoted if they're valid identifiers
  • Strings can be single-quoted
  • Strings can be split across multiple lines
  • Numbers can be hexadecimal (base 16)
  • Numbers can begin or end with a (leading or trailing) decimal point.
  • Numbers can include Infinity and -Infinity.
  • Numbers can begin with an explicit plus (+) sign.
  • Both inline (single-line) and block (multi-line) comments are allowed.

http://json5.org/

https://github.com/aseemk/json5

Fastest Way to Find Distance Between Two Lat/Long Points

I needed to solve similar problem (filtering rows by distance from single point) and by combining original question with answers and comments, I came up with solution which perfectly works for me on both MySQL 5.6 and 5.7.

SELECT 
    *,
    (6371 * ACOS(COS(RADIANS(56.946285)) * COS(RADIANS(Y(coordinates))) 
    * COS(RADIANS(X(coordinates)) - RADIANS(24.105078)) + SIN(RADIANS(56.946285))
    * SIN(RADIANS(Y(coordinates))))) AS distance
FROM places
WHERE MBRContains
    (
    LineString
        (
        Point (
            24.105078 + 15 / (111.320 * COS(RADIANS(56.946285))),
            56.946285 + 15 / 111.133
        ),
        Point (
            24.105078 - 15 / (111.320 * COS(RADIANS(56.946285))),
            56.946285 - 15 / 111.133
        )
    ),
    coordinates
    )
HAVING distance < 15
ORDER By distance

coordinates is field with type POINT and has SPATIAL index
6371 is for calculating distance in kilometres
56.946285 is latitude for central point
24.105078 is longitude for central point
15 is maximum distance in kilometers

In my tests, MySQL uses SPATIAL index on coordinates field to quickly select all rows which are within rectangle and then calculates actual distance for all filtered places to exclude places from rectangles corners and leave only places inside circle.

This is visualisation of my result:

map

Gray stars visualise all points on map, yellow stars are ones returned by MySQL query. Gray stars inside corners of rectangle (but outside circle) were selected by MBRContains() and then deselected by HAVING clause.

How to check if a variable is set in Bash?

Using [[ -z "$var" ]] is the easiest way to know if a variable was set or not, but that option -z doesn't distinguish between an unset variable and a variable set to an empty string:

$ set=''
$ [[ -z "$set" ]] && echo "Set" || echo "Unset" 
Unset
$ [[ -z "$unset" ]] && echo "Set" || echo "Unset"
Unset

It's best to check it according to the type of variable: env variable, parameter or regular variable.

For a env variable:

[[ $(env | grep "varname=" | wc -l) -eq 1 ]] && echo "Set" || echo "Unset"

For a parameter (for example, to check existence of parameter $5):

[[ $# -ge 5 ]] && echo "Set" || echo "Unset"

For a regular variable (using an auxiliary function, to do it in an elegant way):

function declare_var {
   declare -p "$1" &> /dev/null
}
declare_var "var_name" && echo "Set" || echo "Unset"

Notes:

  • $#: gives you the number of positional parameters.
  • declare -p: gives you the definition of the variable passed as a parameter. If it exists, returns 0, if not, returns 1 and prints an error message.
  • &> /dev/null: suppresses output from declare -p without affecting its return code.

Android studio: emulator is running but not showing up in Run App "choose a running device"

in your device you want to run app on Go to settings About device >> Build number triple clicks or more and back to settings you will found "Developer options" appear go to and click on "USB debugging" Done

How to print strings with line breaks in java

Use String buffer.

  final StringBuffer mText = new StringBuffer("SHOP MA\n"
        + "----------------------------\n"
        + "Pannampitiya\n"
        + "09-10-2012 harsha  no: 001\n"
        + "No  Item  Qty  Price  Amount\n"
        + "1 Bread 1 50.00  50.00\n"
        + "____________________________\n");

How to check empty object in angular 2 template using *ngIf

This should do what you want:

<div class="comeBack_up" *ngIf="(previous_info | json) != ({} | json)">

or shorter

<div class="comeBack_up" *ngIf="(previous_info | json) != '{}'">

Each {} creates a new instance and ==== comparison of different objects instances always results in false. When they are convert to strings === results to true

Plunker example

Conda command is not recognized on Windows 10

Even I got the same problem when I've first installed Anaconda. It said 'conda' command not found.

So I've just setup two values[added two new paths of Anaconda] system environment variables in the PATH variable which are: C:\Users\mshas\Anaconda2\ & C:\Users\mshas\Anaconda2\Scripts

Lot of people forgot to add the second variable which is "Scripts" just add that then 'conda' command works.

How to upload files in asp.net core?

Fileservice.cs:

public class FileService : IFileService
{
    private readonly IWebHostEnvironment env;

    public FileService(IWebHostEnvironment env)
    {
        this.env = env;
    }

    public string Upload(IFormFile file)
    {
        var uploadDirecotroy = "uploads/";
        var uploadPath = Path.Combine(env.WebRootPath, uploadDirecotroy);

        if (!Directory.Exists(uploadPath))
            Directory.CreateDirectory(uploadPath);

        var fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
        var filePath = Path.Combine(uploadPath, fileName);

        using (var strem = File.Create(filePath))
        {
            file.CopyTo(strem);
        }
        return fileName;
    }
}

IFileService:

namespace studentapps.Services
{
    public interface IFileService
    {
        string Upload(IFormFile file);
    }
}

StudentController:

[HttpGet]
public IActionResult Create()
{
    var student = new StudentCreateVM();
    student.Colleges = dbContext.Colleges.ToList();
    return View(student);
}

[HttpPost]
public IActionResult Create([FromForm] StudentCreateVM vm)
{
    Student student = new Student()
    {
        DisplayImage = vm.DisplayImage.FileName,
        Name = vm.Name,
        Roll_no = vm.Roll_no,
        CollegeId = vm.SelectedCollegeId,
    };


    if (ModelState.IsValid)
    {
        var fileName = fileService.Upload(vm.DisplayImage);
        student.DisplayImage = fileName;
        getpath = fileName;

        dbContext.Add(student);
        dbContext.SaveChanges();
        TempData["message"] = "Successfully Added";
    }
    return RedirectToAction("Index");
}

How to host a Node.Js application in shared hosting

You can run node.js server on a typical shared hosting with Linux, Apache and PHP (LAMP). I have successfully installed it, even with NPM, Express and Grunt working fine. Follow the steps:

1) Create a new PHP file on the server with the following code and run it:

<?php
//Download and extract the latest node
exec('curl http://nodejs.org/dist/latest/node-v0.10.33-linux-x86.tar.gz | tar xz');
//Rename the folder for simplicity
exec('mv node-v0.10.33-linux-x86 node');

2) The same way install your node app, e.g. jt-js-sample, using npm:

<?php
exec('node/bin/npm install jt-js-sample');

3) Run the node app from PHP:

<?php
//Choose JS file to run
$file = 'node_modules/jt-js-sample/index.js';
//Spawn node server in the background and return its pid
$pid = exec('PORT=49999 node/bin/node ' . $file . ' >/dev/null 2>&1 & echo $!');
//Wait for node to start up
usleep(500000);
//Connect to node server using cURL
$curl = curl_init('http://127.0.0.1:49999/');
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//Get the full response
$resp = curl_exec($curl);
if($resp === false) {
    //If couldn't connect, try increasing usleep
    echo 'Error: ' . curl_error($curl);
} else {
    //Split response headers and body
    list($head, $body) = explode("\r\n\r\n", $resp, 2);
    $headarr = explode("\n", $head);
    //Print headers
    foreach($headarr as $headval) {
        header($headval);
    }
    //Print body
    echo $body;
}
//Close connection
curl_close($curl);
//Close node server
exec('kill ' . $pid);

Voila! Have a look at the demo of a node app on PHP shared hosting.

EDIT: I started a Node.php project on GitHub.

How do I fix maven error The JAVA_HOME environment variable is not defined correctly?

My JDK is installed at C:\Program Files\Java\jdk1.8.0_144\.
I had set JAVA_HOME= C:\Program Files\Java\jdk1.8.0_144\, and I was getting this error:

The JAVA_HOME environment variable is not defined correctly
This environment variable is needed to run this program
NB: JAVA_HOME should point to a JDK not a JRE

When I changed the JAVA_HOME to C:\Program Files\Java\jdk1.8.0_144\jre, the issue got fixed.
I am not sure how.

Convert MySQL to SQlite

I found the perfect solution

First, you need this script (put it into a file called 'mysql-to-sqlite.sh'):

#!/bin/bash
if [ "x$1" == "x" ]; then
  echo "Usage: $0 <dumpname>"
  exit
fi

cat $1 |
grep -v ' KEY "' |
grep -v ' UNIQUE KEY "' |
grep -v ' PRIMARY KEY ' |
sed '/^SET/d' |
sed 's/ unsigned / /g' |
sed 's/ auto_increment/ primary key autoincrement/g' |
sed 's/ smallint([0-9]*) / integer /g' |
sed 's/ tinyint([0-9]*) / integer /g' |
sed 's/ int([0-9]*) / integer /g' |
sed 's/ character set [^ ]* / /g' |
sed 's/ enum([^)]*) / varchar(255) /g' |
sed 's/ on update [^,]*//g' |
sed 's/\\r\\n/\\n/g' |
sed 's/\\"/"/g' |
perl -e 'local $/;$_=<>;s/,\n\)/\n\)/gs;print "begin;\n";print;print "commit;\n"' |
perl -pe '
if (/^(INSERT.+?)\(/) {
  $a=$1;
  s/\\'\''/'\'\''/g;
  s/\\n/\n/g;
  s/\),\(/\);\n$a\(/g;
}
' > $1.sql
cat $1.sql | sqlite3 $1.db > $1.err
ERRORS=`cat $1.err | wc -l`
if [ $ERRORS == 0 ]; then
  echo "Conversion completed without error. Output file: $1.db"
  rm $1.sql
  rm $1.err
else
  echo "There were errors during conversion.  Please review $1.err and $1.sql for details."
fi

Then, dump a copy of your database:

you@prompt:~$ mysqldump -u root -p --compatible=ansi --skip-opt generator > dumpfile

And now, run the conversion:

you@prompt:~$ mysql-to-sqlite.sh dumpfile

And if all goes well, you should now have a dumpfile.db which can be used via sqlite3.

you@prompt:~$ sqlite3 dumpfile.db 
SQLite version 3.6.10
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .tables
dg_cities                 dg_forms                  dg_surnames             
dg_counties               dg_provinces              dg_user_accounts        
dg_countries              dg_provinces_netherlands
dg_first_names            dg_states

How to send an HTTPS GET Request in C#

Simple Get Request using HttpClient Class

using System.Net.Http;

class Program
{
   static void Main(string[] args)
    {
        HttpClient httpClient = new HttpClient();
        var result = httpClient.GetAsync("https://www.google.com").Result;
    }

}

Shell script "for" loop syntax

If the seq command available on your system:

for i in `seq 2 $max`
do
  echo "output: $i"
done

If not, then use poor man's seq with perl:

seq=`perl -e "\$,=' ';print 2..$max"`
for i in $seq
do
  echo "output: $i"
done

Watch those quote marks.

What is the "proper" way to cast Hibernate Query.list() to List<Type>?

I found the best solution here, the key of this issue is the addEntity method

public static void testSimpleSQL() {
    final Session session = sessionFactory.openSession();
    SQLQuery q = session.createSQLQuery("select * from ENTITY");
    q.addEntity(Entity.class);
    List<Entity> entities = q.list();
    for (Entity entity : entities) {
        System.out.println(entity);
    }
}

Has an event handler already been added?

If I understand your problem correctly you may have bigger issues. You said that other objects may subscribe to these events. When the object is serialized and deserialized the other objects (the ones that you don't have control of) will lose their event handlers.

If you're not worried about that then keeping a reference to your event handler should be good enough. If you are worried about the side-effects of other objects losing their event handlers, then you may want to rethink your caching strategy.

Add 10 seconds to a Date

timeObject.setSeconds(timeObject.getSeconds() + 10)

Creating columns in listView and add items

Your first problem is that you are passing -3 to the 2nd parameter of Columns.Add. It needs to be -2 for it to auto-size the column. Source: http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.columns.aspx (look at the comments on the code example at the bottom)

private void initListView()
{
    // Add columns
    lvRegAnimals.Columns.Add("Id", -2,HorizontalAlignment.Left);
    lvRegAnimals.Columns.Add("Name", -2, HorizontalAlignment.Left);
    lvRegAnimals.Columns.Add("Age", -2, HorizontalAlignment.Left);
}

You can also use the other overload, Add(string). E.g:

lvRegAnimals.Columns.Add("Id");
lvRegAnimals.Columns.Add("Name");
lvRegAnimals.Columns.Add("Age");

Reference for more overloads: http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.columnheadercollection.aspx

Second, to add items to the ListView, you need to create instances of ListViewItem and add them to the listView's Items collection. You will need to use the string[] constructor.

var item1 = new ListViewItem(new[] {"id123", "Tom", "24"});
var item2 = new ListViewItem(new[] {person.Id, person.Name, person.Age});
lvRegAnimals.Items.Add(item1);
lvRegAnimals.Items.Add(item2);

You can also store objects in the item's Tag property.

item2.Tag = person;

And then you can extract it

var person = item2.Tag as Person;

Let me know if you have any questions and I hope this helps!

VBA Print to PDF and Save with Automatic File Name

Hopefully this is self explanatory enough. Use the comments in the code to help understand what is happening. Pass a single cell to this function. The value of that cell will be the base file name. If the cell contains "AwesomeData" then we will try and create a file in the current users desktop called AwesomeData.pdf. If that already exists then try AwesomeData2.pdf and so on. In your code you could just replace the lines filename = Application..... with filename = GetFileName(Range("A1"))

Function GetFileName(rngNamedCell As Range) As String
    Dim strSaveDirectory As String: strSaveDirectory = ""
    Dim strFileName As String: strFileName = ""
    Dim strTestPath As String: strTestPath = ""
    Dim strFileBaseName As String: strFileBaseName = ""
    Dim strFilePath As String: strFilePath = ""
    Dim intFileCounterIndex As Integer: intFileCounterIndex = 1

    ' Get the users desktop directory.
    strSaveDirectory = Environ("USERPROFILE") & "\Desktop\"
    Debug.Print "Saving to: " & strSaveDirectory

    ' Base file name
    strFileBaseName = Trim(rngNamedCell.Value)
    Debug.Print "File Name will contain: " & strFileBaseName

    ' Loop until we find a free file number
    Do
        If intFileCounterIndex > 1 Then
            ' Build test path base on current counter exists.
            strTestPath = strSaveDirectory & strFileBaseName & Trim(Str(intFileCounterIndex)) & ".pdf"
        Else
            ' Build test path base just on base name to see if it exists.
            strTestPath = strSaveDirectory & strFileBaseName & ".pdf"
        End If

        If (Dir(strTestPath) = "") Then
            ' This file path does not currently exist. Use that.
            strFileName = strTestPath
        Else
            ' Increase the counter as we have not found a free file yet.
            intFileCounterIndex = intFileCounterIndex + 1
        End If

    Loop Until strFileName <> ""

    ' Found useable filename
    Debug.Print "Free file name: " & strFileName
    GetFileName = strFileName

End Function

The debug lines will help you figure out what is happening if you need to step through the code. Remove them as you see fit. I went a little crazy with the variables but it was to make this as clear as possible.

In Action

My cell O1 contained the string "FileName" without the quotes. Used this sub to call my function and it saved a file.

Sub Testing()
    Dim filename As String: filename = GetFileName(Range("o1"))

    ActiveWorkbook.Worksheets("Sheet1").Range("A1:N24").ExportAsFixedFormat Type:=xlTypePDF, _
                                              filename:=filename, _
                                              Quality:=xlQualityStandard, _
                                              IncludeDocProperties:=True, _
                                              IgnorePrintAreas:=False, _
                                              OpenAfterPublish:=False
End Sub

Where is your code located in reference to everything else? Perhaps you need to make a module if you have not already and move your existing code into there.

Java POI : How to read Excel cell value and not the formula computing it?

For formula cells, excel stores two things. One is the Formula itself, the other is the "cached" value (the last value that the forumla was evaluated as)

If you want to get the last cached value (which may no longer be correct, but as long as Excel saved the file and you haven't changed it it should be), you'll want something like:

 for(Cell cell : row) {
     if(cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
        System.out.println("Formula is " + cell.getCellFormula());
        switch(cell.getCachedFormulaResultType()) {
            case Cell.CELL_TYPE_NUMERIC:
                System.out.println("Last evaluated as: " + cell.getNumericCellValue());
                break;
            case Cell.CELL_TYPE_STRING:
                System.out.println("Last evaluated as \"" + cell.getRichStringCellValue() + "\"");
                break;
        }
     }
 }

return, return None, and no return at all?

As other have answered, the result is exactly the same, None is returned in all cases.

The difference is stylistic, but please note that PEP8 requires the use to be consistent:

Be consistent in return statements. Either all return statements in a function should return an expression, or none of them should. If any return statement returns an expression, any return statements where no value is returned should explicitly state this as return None, and an explicit return statement should be present at the end of the function (if reachable).

Yes:

def foo(x):
    if x >= 0:
        return math.sqrt(x)
    else:
        return None

def bar(x):
    if x < 0:
        return None
    return math.sqrt(x)

No:

def foo(x):
    if x >= 0:
        return math.sqrt(x)

def bar(x):
    if x < 0:
        return
    return math.sqrt(x)

https://www.python.org/dev/peps/pep-0008/#programming-recommendations


Basically, if you ever return non-None value in a function, it means the return value has meaning and is meant to be caught by callers. So when you return None, it must also be explicit, to convey None in this case has meaning, it is one of the possible return values.

If you don't need return at all, you function basically works as a procedure instead of a function, so just don't include the return statement.

If you are writing a procedure-like function and there is an opportunity to return earlier (i.e. you are already done at that point and don't need to execute the remaining of the function) you may use empty an returns to signal for the reader it is just an early finish of execution and the None value returned implicitly doesn't have any meaning and is not meant to be caught (the procedure-like function always returns None anyway).

C# - Winforms - Global Variables

If you're using Visual C#, all you need to do is add a class in Program.cs inheriting Form and change all the inherited class from Form to your class in every Form*.cs.

//Program.cs
public class Forms : Form
{
    //Declare your global valuables here.
}

//Form1.cs
public partial class Form1 : Forms    //Change from Form to Forms
{
    //...
}

Of course, there might be a way to extending the class Form without modifying it. If that's the case, all you need to do is extending it! Since all the forms are inheriting it by default, so all the valuables declared in it will become global automatically! Good luck!!!

jQuery's jquery-1.10.2.min.map is triggering a 404 (Not Found)

  1. Download the map file and the uncompressed version of jQuery.
    Put them with the minified version:

    JavaScript

  2. Include minified version into your HTML:

    HTML

  3. Check in Google Chrome:

    Google Chrome

  4. Read Introduction to JavaScript Source Maps

  5. Get familiar with Debugging JavaScript

Oracle Sql get only month and year in date datatype

Easiest solution is to create the column using the correct data type: DATE

For example:

  1. Create table:

    create table test_date (mydate date);

  2. Insert row:

    insert into test_date values (to_date('01-01-2011','dd-mm-yyyy'));

To get the month and year, do as follows:

select to_char(mydate, 'MM-YYYY') from test_date;

Your result will be as follows: 01-2011

Another cool function to use is "EXTRACT"

select extract(year from mydate) from test_date;

This will return: 2011

C# Listbox Item Double Click Event

WinForms

Add an event handler for the Control.DoubleClick event for your ListBox, and in that event handler open up a MessageBox displaying the selected item.

E.g.:

 private void ListBox1_DoubleClick(object sender, EventArgs e)
 {
     if (ListBox1.SelectedItem != null)
     {
         MessageBox.Show(ListBox1.SelectedItem.ToString());
     }
 }

Where ListBox1 is the name of your ListBox.

Note that you would assign the event handler like this:

ListBox1.DoubleClick += new EventHandler(ListBox1_DoubleClick);

WPF
Pretty much the same as above, but you'd use the MouseDoubleClick event instead:

ListBox1.MouseDoubleClick += new RoutedEventHandler(ListBox1_MouseDoubleClick);

And the event handler:

 private void ListBox1_MouseDoubleClick(object sender, RoutedEventArgs e)
 {
     if (ListBox1.SelectedItem != null)
     {
         MessageBox.Show(ListBox1.SelectedItem.ToString());
     }
 }

Edit: Sisya's answer checks to see if the double-click occurred over an item, which would need to be incorporated into this code to fix the issue mentioned in the comments (MessageBox shown if ListBox is double-clicked while an item is selected, but not clicked over an item).

Hope this helps!

Visual Studio 2013 Install Fails: Program Compatibility Mode is on (Windows 10)

Copy the installation files into your hard drive. Rename the installer file name to vs_professional.exe for professional edition. Enjoy.

How to Remove the last char of String in C#?

If this is something you need to do a lot in your application, or you need to chain different calls, you can create an extension method:

public static String TrimEnd(this String str, int count)
{
    return str.Substring(0, str.Length - count);
}

and call it:

string oldString = "...Hello!";
string newString = oldString.Trim(1); //returns "...Hello"

or chained:

string newString = oldString.Substring(3).Trim(1);  //returns "Hello"

How to pass in password to pg_dump?

$ PGPASSWORD="mypass" pg_dump -i -h localhost -p 5432 -U username -F c -b -v -f dumpfilename.dump databasename

Html.Partial vs Html.RenderPartial & Html.Action vs Html.RenderAction

@Html.Partial and @Html.RenderPartial are used when your Partial view model is correspondence of parent model, we don't need to create any action method to call this.

@Html.Action and @Html.RenderAction are used when your partial view model are independent from parent model, basically it is used when you want to display any widget type content on page. You must create an action method which returns a partial view result while calling the method from view.

How to select a div element in the code-behind page?

id + runat="server" leads to accessible at the server

What are these attributes: `aria-labelledby` and `aria-hidden`

Aria is used to improve the user experience of visually impaired users. Visually impaired users navigate though application using screen reader software like JAWS, NVDA,.. While navigating through the application, screen reader software announces content to users. Aria can be used to add content in the code which helps screen reader users understand role, state, label and purpose of the control

Aria does not change anything visually. (Aria is scared of designers too).

aria-hidden:

aria-hidden attribute is used to hide content for visually impaired users who navigate through application using screen readers (JAWS, NVDA,...).

aria-hidden attribute is used with values true, false.

How To Use:

<i class = "fa fa-books" aria-hidden = "true"></i>

using aria-hidden = "true" on the <i> hides content to screen reader users with no visual change in the application.

aria-label

aria-label attribute is used to communicate the label to screen reader users. Usually search input field does not have visual label (thanks to designers). aria-label can be used to communicate the label of control to screen reader users

How To Use:

<input type = "edit" aria-label = "search" placeholder = "search">

There is no visual change in application. But screen readers can understand the purpose of control

aria-labelledby

Both aria-label and aria-labelledby is used to communicate the label. But aria-labelledby can be used to reference any label already present in the page whereas aria-label is used to communicate the label which i not displayed visually

Approach 1:

<span id = "sd"> Search </span>

<input type = "text" aria-labelledby = "sd">

aria-labelledby can also be used to combine two labels for screen reader users

Approach 2:

<span id = "de"> Billing Address </span>

<span id = "sd"> First Name </span>

<input type = "text" aria-labelledby = "de sd">

Jquery Ajax Call, doesn't call Success or Error

Try to encapsulate the ajax call into a function and set the async option to false. Note that this option is deprecated since jQuery 1.8.

function foo() {
    var myajax = $.ajax({
        type: "POST",
        url: "CHService.asmx/SavePurpose",
        dataType: "text",
        data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
        contentType: "application/json; charset=utf-8",
        async: false, //add this
    });
    return myajax.responseText;
}

You can do this also:

$.ajax({
    type: "POST",
    url: "CHService.asmx/SavePurpose",
    dataType: "text",
    data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
    contentType: "application/json; charset=utf-8",
    async: false, //add this
}).done(function ( data ) {
        Success = true;
}).fail(function ( data ) {
       Success = false;
});

You can read more about the jqXHR jQuery Object

CSS word-wrapping in div

As Andrew said, your text should be doing just that.

There is one instance that I can think of that will behave in the manner you suggest, and that is if you have the whitespace property set.

See if you don't have the following in your CSS somewhere:

white-space: nowrap

That will cause text to continue on the same line until interrupted by a line break.

OK, my apologies, not sure if edited or added the mark-up afterwards (didn't see it at first).

The overflow-x property is what's causing the scroll bar to appear. Remove that and the div will adjust to as high as it needs to be to contain all your text.

Custom seekbar (thumb size, color and background)

  • First at all, use android:splitTrack="false" for the transparency problem of your thumb.

  • For the seekbar.png, you have to use a 9 patch. It would be good for the rounded border and the shadow of your image.

How to create custom spinner like border around the spinner with down triangle on the right side?

You can achieve the following by using a single line in your spinner declaration in XML: enter image description here

Just add this: style="@android:style/Widget.Holo.Light.Spinner"

This is a default generated style in android. It doesn't contain borders around it though. For that you'd better search something on google.

Hope this helps.

UPDATE: AFter a lot of digging I got something which works well for introducing border around spinner.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:bottom="8dp"
        android:top="8dp">
        <shape>
            <solid android:color="@android:color/white" />
            <corners android:radius="4dp" />
            <stroke
                android:width="2dp"
                android:color="#9E9E9E" />
            <padding
                android:bottom="16dp"
                android:left="8dp"
                android:right="16dp"
                android:top="16dp" />
        </shape>
    </item>
</layer-list>

Place this in the drawable folder and use it as a background for spinner. Like this:

<RelativeLayout
        android:id="@+id/speaker_relative_layout"
        android:layout_width="0dp"
        android:layout_height="70dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="16dp"
        android:background="@drawable/spinner_style"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <Spinner
            android:id="@+id/select_speaker_spinner"
            style="@style/Widget.AppCompat.DropDownItem.Spinner"
            android:layout_width="match_parent"
            android:layout_height="70dp"
            android:entries="@array/select_speaker_spinner_array"
            android:spinnerMode="dialog" />

    </RelativeLayout>

What good technology podcasts are out there?

Not hardcore technology but I really enjoy Drunk and Retired. It's like you're talking to your programmer buddy mixed in with life stuff.

HTTP Get with 204 No Content: Is that normal

204 No Content

The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant.

According to the RFC part for the status code 204, it seems to me a valid choice for a GET request.

A 404 Not Found, 200 OK with empty body and 204 No Content have completely different meaning, sometimes we can't use proper status code but bend the rules and they will come back to bite you one day or later. So, if you can use proper status code, use it!

I think the choice of GET or POST is very personal as both of them will do the work but I would recommend you to keep a POST instead of a GET, for two reasons:

  • You want the other part (the servlet if I understand correctly) to perform an action not retrieve some data from it.
  • By default GET requests are cacheable if there are no parameters present in the URL, a POST is not.

Class JavaLaunchHelper is implemented in both ... libinstrument.dylib. One of the two will be used. Which one is undefined

To solve this issue, I downgraded to JDK version 1.7.0_21. then I used this little bash script to change the version I use.

function setjdk() {
  if [ $# -ne 0 ]; then
   removeFromPath '/System/Library/Frameworks/JavaVM.framework/Home/bin'
   if [ -n "${JAVA_HOME+x}" ]; then
    removeFromPath $JAVA_HOME
   fi
   export JAVA_HOME=`/usr/libexec/java_home -v $@`
   export PATH=$JAVA_HOME/bin:$PATH
  fi
 }

 function removeFromPath() {
  export PATH=$(echo $PATH | sed -E -e "s;:$1;;" -e "s;$1:?;;")
 }

Once you have the bash script in your zshrc/bshrc file, just call setJdk 1.7.0_21 and you're good to go.

How to generate a Dockerfile from an image?

Update Dec 2018 to BMW's answer

chenzj/dfimage - as described on hub.docker.com regenerates Dockerfile from other images. So you can use it as follows:

docker pull chenzj/dfimage
alias dfimage="docker run -v /var/run/docker.sock:/var/run/docker.sock --rm chenzj/dfimage"
dfimage IMAGE_ID > Dockerfile

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=0, data=null} to activity

I had this error message show up for me because I was using the network on the main thread and new versions of Android have a "strict" policy to prevent that. To get around it just throw whatever network connection call into an AsyncTask.

Example:

    AsyncTask<CognitoCachingCredentialsProvider, Integer, Void> task = new AsyncTask<CognitoCachingCredentialsProvider, Integer, Void>() {

        @Override
        protected Void doInBackground(CognitoCachingCredentialsProvider... params) {
            AWSSessionCredentials creds = credentialsProvider.getCredentials();
            String id = credentialsProvider.getCachedIdentityId();
            credentialsProvider.refresh();
            Log.d("wooohoo", String.format("id=%s, token=%s", id, creds.getSessionToken()));
            return null;
        }
    };

    task.execute(credentialsProvider);

TypeScript: Creating an empty typed container array

I know this is an old question but I recently faced a similar issue which couldn't be solved by this way, as I had to return an empty array of a specific type.

I had

return [];

where [] was Criminal[] type.

Neither return: Criminal[] []; nor return []: Criminal[]; worked for me.

At first glance I solved it by creating a typed variable (as you correctly reported) just before returning it, but (I don't know how JavaScript engines work) it may create overhead and it's less readable.

For thoroughness I'll report this solution in my answer too:

let temp: Criminal[] = [];
return temp;

Eventually I found TypeScript type casting, which allowed me to solve the problem in a more concise and readable (and maybe efficient) way:

return <Criminal[]>[];

Hope this will help future readers!

Get Filename Without Extension in Python

No need for regex. os.path.splitext is your friend:

os.path.splitext('1.1.1.jpg')
>>> ('1.1.1', '.jpg')

How to delete a record in Django models?

if you want to delete one instance then write the code

entry= Account.objects.get(id= 5)
entry.delete()

if you want to delete all instance then write the code

entries= Account.objects.all()
entries.delete()

webpack: Module not found: Error: Can't resolve (with relative path)

I met this problem with typescript but forgot to add ts and tsx suffix to resolve entry.

module.exports = {
  ...
  resolve: {
    extensions: ['.js', '.jsx', '.ts', '.tsx'],
  },
};

This does the job for me

How to change the commit author for one specific commit?

Interactive rebase off of a point earlier in the history than the commit you need to modify (git rebase -i <earliercommit>). In the list of commits being rebased, change the text from pick to edit next to the hash of the one you want to modify. Then when git prompts you to change the commit, use this:

git commit --amend --author="Author Name <[email protected]>" --no-edit

For example, if your commit history is A-B-C-D-E-F with F as HEAD, and you want to change the author of C and D, then you would...

  1. Specify git rebase -i B (here is an example of what you will see after executing the git rebase -i B command)
    • if you need to edit A, use git rebase -i --root
  2. Change the lines for both C and D from pick to edit
  3. Exit the editor (for vim, this would be pressing Esc and then typing :wq).
  4. Once the rebase started, it would first pause at C
  5. You would git commit --amend --author="Author Name <[email protected]>"
  6. Then git rebase --continue
  7. It would pause again at D
  8. Then you would git commit --amend --author="Author Name <[email protected]>" again
  9. git rebase --continue
  10. The rebase would complete.
  11. Use git push -f to update your origin with the updated commits.

Creating a button in Android Toolbar

I have added text in ToolBar :

menu_skip.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">

    <item
        android:id="@+id/action_settings"
        android:title="@string/text_skip"
        app:showAsAction="never" />
</menu>

MainActivity.java

@Override
boolean onCreateOptionsMenu(Menu menu) {
    inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_otp_skip, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        // action with ID action_refresh was selected
        case R.id.menu_item_skip:
            Toast.makeText(this, "Skip selected", Toast.LENGTH_SHORT)
                    .show();
            break;
        default:
            break;
    }
    return true;
}

Is unsigned integer subtraction defined behavior?

The result of a subtraction generating a negative number in an unsigned type is well-defined:

  1. [...] A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type. (ISO/IEC 9899:1999 (E) §6.2.5/9)

As you can see, (unsigned)0 - (unsigned)1 equals -1 modulo UINT_MAX+1, or in other words, UINT_MAX.

Note that although it does say "A computation involving unsigned operands can never overflow", which might lead you to believe that it applies only for exceeding the upper limit, this is presented as a motivation for the actual binding part of the sentence: "a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type." This phrase is not restricted to overflow of the upper bound of the type, and applies equally to values too low to be represented.

How to uninstall a package installed with pip install --user

Be careful though, for those who using pip install --user some_pkg inside a virtual environment.

$ path/to/python -m venv ~/my_py_venv
$ source ~/my_py_venv/bin/activate
(my_py_venv) $ pip install --user some_pkg
(my_py_venv) $ pip uninstall some_pkg
WARNING: Skipping some_pkg as it is not installed.
(my_py_venv) $ pip list
# Even `pip list` will not properly list the `some_pkg` in this case

In this case, you have to deactivate the current virtual environment, then use the corresponding python/pip executable to list or uninstall the user site packages:

(my_py_venv) $ deactivate
$ path/to/python -m pip list
$ path/to/python -m pip uninstall some_pkg

Note that this issue was reported few years ago. And it seems that the current conclusion is: --user is not valid inside a virtual env's pip, since a user location doesn't really make sense for a virtual environment.

How to add not null constraint to existing column in MySQL

Would like to add:

After update, such as

ALTER TABLE table_name modify column_name tinyint(4) NOT NULL;

If you get

ERROR 1138 (22004): Invalid use of NULL value

Make sure you update the table first to have values in the related column (so it's not null)

Does Spring Data JPA have any way to count entites using method name resolving?

Thanks you all! Now it's work. DATAJPA-231

It will be nice if was possible to create count…By… methods just like find…By ones. Example:

public interface UserRepository extends JpaRepository<User, Long> {

   public Long /*or BigInteger */ countByActiveTrue();
}

How do I run two commands in one line in Windows CMD?

If you want to create a cmd shortcut (for example on your desktop) add /k parameter (/k means keep, /c will close window):

cmd /k echo hello && cd c:\ && cd Windows

ReactNative: how to center text?

Set these styles to image component: { textAlignVertical: "center", textAlign: "center" }

Append text to textarea with javascript

Use event delegation by assigning the onclick to the <ol>. Then pass the event object as the argument, and using that, grab the text from the clicked element.

_x000D_
_x000D_
function addText(event) {_x000D_
    var targ = event.target || event.srcElement;_x000D_
    document.getElementById("alltext").value += targ.textContent || targ.innerText;_x000D_
}
_x000D_
<textarea id="alltext"></textarea>_x000D_
_x000D_
<ol onclick="addText(event)">_x000D_
  <li>Hello</li>_x000D_
  <li>World</li>_x000D_
  <li>Earthlings</li>_x000D_
</ol>
_x000D_
_x000D_
_x000D_

Note that this method of passing the event object works in older IE as well as W3 compliant systems.

JsonParseException: Unrecognized token 'http': was expecting ('true', 'false' or 'null')

It might be obvious, but make sure that you are sending to the parser URL object not a String containing www adress. This will not work:

    ObjectMapper mapper = new ObjectMapper();
    String www = "www.sample.pl";
    Weather weather = mapper.readValue(www, Weather.class);

But this will:

    ObjectMapper mapper = new ObjectMapper();
    URL www = new URL("http://www.oracle.com/");
    Weather weather = mapper.readValue(www, Weather.class);

How create a new deep copy (clone) of a List<T>?

Straight forward simple way to copy any generic list :

List<whatever> originalCopy=new List<whatever>();//create new list
originalCopy.AddRange(original);//perform copy of original list

Apply style ONLY on IE

@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {
   #myElement {
        /* Enter your style code */
   }
}

Explanation: It is a Microsoft-specific media query. Using -ms-high-contrast property specific to Microsoft IE, it will only be parsed in Internet Explorer 10 or greater. I have used both the valid values of the media query, so it will be parsed by IE only, whether the user has high contrast enabled or not.

MVC 5 Access Claims Identity User Data

You can also do this:

//Get the current claims principal
var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;
var claims = identity.Claims;

Update

To provide further explanation as per comments.

If you are creating users within your system as follows:

UserManager<applicationuser> userManager = new UserManager<applicationuser>(new UserStore<applicationuser>(new SecurityContext()));
ClaimsIdentity identity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

You should automatically have some Claims populated relating to you Identity.

To add customized claims after a user authenticates you can do this as follows:

var user = userManager.Find(userName, password);
identity.AddClaim(new Claim(ClaimTypes.Email, user.Email));

The claims can be read back out as Darin has answered above or as I have.

The claims are persisted when you call below passing the identity in:

AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = persistCookie }, identity);

Bootstrap: How do I identify the Bootstrap version?

Shoud be stated on the top of the page.

Something like.

/* =========================================================
 * bootstrap-modal.js v1.4.0
 * http://twitter.github.com/bootstrap/javascript.html#modal
 * =========================================================
 * Copyright 2011 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================= */

How do I pass multiple ints into a vector at once?

You can do it with initializer list:

std::vector<unsigned int> array;

// First argument is an iterator to the element BEFORE which you will insert:
// In this case, you will insert before the end() iterator, which means appending value
// at the end of the vector.
array.insert(array.end(), { 1, 2, 3, 4, 5, 6 });

Make text wrap in a cell with FPDF?

Text Wrap:

The MultiCell is used for print text with multiple lines. It has the same atributes of Cell except for ln and link.

$pdf->MultiCell( 200, 40, $reportSubtitle, 1);

Line Height:

What multiCell does is to spread the given text into multiple cells, this means that the second parameter defines the height of each line (individual cell) and not the height of all cells (collectively).

MultiCell(float w, float h, string txt [, mixed border [, string align [, boolean fill]]])

You can read the full documentation here.

What is the difference between Subject and BehaviorSubject?

BehaviourSubject

BehaviourSubject will return the initial value or the current value on Subscription

var bSubject= new Rx.BehaviorSubject(0);  // 0 is the initial value

bSubject.subscribe({
  next: (v) => console.log('observerA: ' + v)  // output initial value, then new values on `next` triggers
});

bSubject.next(1);  // output new value 1 for 'observer A'
bSubject.next(2);  // output new value 2 for 'observer A', current value 2 for 'Observer B' on subscription

bSubject.subscribe({
  next: (v) => console.log('observerB: ' + v)  // output current value 2, then new values on `next` triggers
});

bSubject.next(3);

With output:

observerA: 0
observerA: 1
observerA: 2
observerB: 2
observerA: 3
observerB: 3

Subject

Subject does not return the current value on Subscription. It triggers only on .next(value) call and return/output the value

var subject = new Rx.Subject();

subject.next(1); //Subjects will not output this value

subject.subscribe({
  next: (v) => console.log('observerA: ' + v)
});
subject.subscribe({
  next: (v) => console.log('observerB: ' + v)
});

subject.next(2);
subject.next(3);

With the following output on the console:

observerA: 2
observerB: 2
observerA: 3
observerB: 3

How to get the selected item from ListView?

Using setOnItemClickListener is the correct answer, but if you have a keyboard you can change selection even with arrows (no click is performed), so, you need to implement also setOnItemSelectedListener :

myListView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
     MyObject tmp=(MyObject) adapterView.getItemAtPosition(position);
         }
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
                // your stuff
            }
        });

Java - Best way to print 2D array?

@Ashika's answer works fantastically if you want (0,0) to be represented in the top, left corner, per normal CS convention. If however you would prefer to use normal mathematical convention and put (0,0) in the lower left hand corner, you could use this:

LinkedList<String> printList = new LinkedList<String>();
for (char[] row: array) {
    printList.addFirst(Arrays.toString(row));;
}
while (!printList.isEmpty())
    System.out.println(printList.removeFirst());

This used LIFO (Last In First Out) to reverse the order at print time.

Eclipse: "'Periodic workspace save.' has encountered a pro?blem."

Solved it by setting workspace on a local folder, and set data from import project, from existing resources.

How to configure Git post commit hook

Hope this helps: http://nrecursions.blogspot.in/2014/02/how-to-trigger-jenkins-build-on-git.html

It's just a matter of using curl to trigger a Jenkins job using the git hooks provided by git.
The command

curl http://localhost:8080/job/someJob/build?delay=0sec

can run a Jenkins job, where someJob is the name of the Jenkins job.

Search for the hooks folder in your hidden .git folder. Rename the post-commit.sample file to post-commit. Open it with Notepad, remove the : Nothing line and paste the above command into it.

That's it. Whenever you do a commit, Git will trigger the post-commit commands defined in the file.

Creating a UICollectionView programmatically

For Swift 2.0

Instead of implementing the methods that are required to draw the CollectionViewCells:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
    {
        return CGSizeMake(50, 50);
    }

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets
    {
        return UIEdgeInsetsMake(5, 5, 5, 5); //top,left,bottom,right
    }

Use UICollectionViewFlowLayout

func createCollectionView() {
    let flowLayout = UICollectionViewFlowLayout()

    // Now setup the flowLayout required for drawing the cells
    let space = 5.0 as CGFloat

    // Set view cell size
    flowLayout.itemSize = CGSizeMake(50, 50)

    // Set left and right margins
    flowLayout.minimumInteritemSpacing = space

    // Set top and bottom margins
    flowLayout.minimumLineSpacing = space

    // Finally create the CollectionView
    let collectionView = UICollectionView(frame: CGRectMake(10, 10, 300, 400), collectionViewLayout: flowLayout)

    // Then setup delegates, background color etc.
    collectionView?.dataSource = self
    collectionView?.delegate = self
    collectionView?.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "cellID")
    collectionView?.backgroundColor = UIColor.whiteColor()
    self.view.addSubview(collectionView!)
}

Then implement the UICollectionViewDataSource methods as required:

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 20;
    }
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    var cell:UICollectionViewCell=collectionView.dequeueReusableCellWithReuseIdentifier("collectionCell", forIndexPath: indexPath) as UICollectionViewCell;
    cell.backgroundColor = UIColor.greenColor();
    return cell;
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

Folder structure for a Node.js project

There is a discussion on GitHub because of a question similar to this one: https://gist.github.com/1398757

You can use other projects for guidance, search in GitHub for:

  • ThreeNodes.js - in my opinion, seems to have a specific structure not suitable for every project;
  • lighter - an more simple structure, but lacks a bit of organization;

And finally, in a book (http://shop.oreilly.com/product/0636920025344.do) suggests this structure:

+-- index.html
+-- js/
¦   +-- main.js
¦   +-- models/
¦   +-- views/
¦   +-- collections/
¦   +-- templates/
¦   +-- libs/
¦       +-- backbone/
¦       +-- underscore/
¦       +-- ...
+-- css/
+-- ...

View a specific Git commit

git show <revhash>

Documentation here. Or if that doesn't work, try Google Code's GIT Documentation

oracle plsql: how to parse XML and insert into table

CREATE OR REPLACE PROCEDURE ADDEMP
    (xml IN CLOB)
AS
BEGIN
    INSERT INTO EMPLOYEE (EMPID,EMPNAME,EMPDETAIL,CREATEDBY,CREATED)
    SELECT 
        ExtractValue(column_value,'/ROOT/EMPID') AS EMPID
       ,ExtractValue(column_value,'/ROOT/EMPNAME') AS EMPNAME
       ,ExtractValue(column_value,'/ROOT/EMPDETAIL') AS EMPDETAIL
       ,ExtractValue(column_value,'/ROOT/CREATEDBY') AS CREATEDBY
       ,ExtractValue(column_value,'/ROOT/CREATEDDATE') AS CREATEDDATE
    FROM   TABLE(XMLSequence( XMLType(xml))) XMLDUMMAY;

    COMMIT;
END;

Convert double to BigDecimal and set BigDecimal Precision

The reason of such behaviour is that the string that is printed is the exact value - probably not what you expected, but that's the real value stored in memory - it's just a limitation of floating point representation.

According to javadoc, BigDecimal(double val) constructor behaviour can be unexpected if you don't take into consideration this limitation:

The results of this constructor can be somewhat unpredictable. One might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding.

So in your case, instead of using

double val = 77.48;
new BigDecimal(val);

use

BigDecimal.valueOf(val);

Value that is returned by BigDecimal.valueOf is equal to that resulting from invocation of Double.toString(double).

javax.websocket client simple example

Have a look at this Java EE 7 examples from Arun Gupta.

I forked it on github.

Main

/**
 * @author Arun Gupta
 */
public class Client {

    final static CountDownLatch messageLatch = new CountDownLatch(1);

    public static void main(String[] args) {
        try {
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            String uri = "ws://echo.websocket.org:80/";
            System.out.println("Connecting to " + uri);
            container.connectToServer(MyClientEndpoint.class, URI.create(uri));
            messageLatch.await(100, TimeUnit.SECONDS);
        } catch (DeploymentException | InterruptedException | IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

ClientEndpoint

/**
 * @author Arun Gupta
 */
@ClientEndpoint
public class MyClientEndpoint {
    @OnOpen
    public void onOpen(Session session) {
        System.out.println("Connected to endpoint: " + session.getBasicRemote());
        try {
            String name = "Duke";
            System.out.println("Sending message to endpoint: " + name);
            session.getBasicRemote().sendText(name);
        } catch (IOException ex) {
            Logger.getLogger(MyClientEndpoint.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @OnMessage
    public void processMessage(String message) {
        System.out.println("Received message in client: " + message);
        Client.messageLatch.countDown();
    }

    @OnError
    public void processError(Throwable t) {
        t.printStackTrace();
    }
}

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

You can also use

lblExamlple.ForeColor = System.Drawing.Color.FromArgb(0,255,0);

SQL Server copy all rows from one table into another i.e duplicate table

try this single command to both delete and insert the data:

DELETE MyTable
    OUTPUT DELETED.Col1, DELETED.COl2,...
        INTO MyBackupTable

working sample:

--set up the tables
DECLARE @MyTable table (col1 int, col2 varchar(5))
DECLARE @MyBackupTable table (col1 int, col2 varchar(5))
INSERT INTO @MyTable VALUES (1,'A')
INSERT INTO @MyTable VALUES (2,'B')
INSERT INTO @MyTable VALUES (3,'C')
INSERT INTO @MyTable VALUES (4,'D')

--single command that does the delete and inserts
DELETE @MyTable
    OUTPUT DELETED.Col1, DELETED.COl2
        INTO @MyBackupTable

--show both tables final values
select * from @MyTable
select * from @MyBackupTable

OUTPUT:

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(4 row(s) affected)
col1        col2
----------- -----

(0 row(s) affected)

col1        col2
----------- -----
1           A
2           B
3           C
4           D

(4 row(s) affected)

Kill detached screen session

add this to your ~/.bashrc:

alias cleanscreen="screen -ls | tail -n +2 | head -n -2 | awk '{print $1}'| xargs -I{} screen -S {} -X quit"

Then use cleanscreen to clean all screen session.

Convert a list to a dictionary in Python

You can also try this approach save the keys and values in different list and then use dict method

data=['test1', '1', 'test2', '2', 'test3', '3', 'test4', '4']

keys=[]
values=[]
for i,j in enumerate(data):
    if i%2==0:
        keys.append(j)
    else:
        values.append(j)

print(dict(zip(keys,values)))

output:

{'test3': '3', 'test1': '1', 'test2': '2', 'test4': '4'}

"for" vs "each" in Ruby

It looks like there is no difference, for uses each underneath.

$ irb
>> for x in nil
>> puts x
>> end
NoMethodError: undefined method `each' for nil:NilClass
    from (irb):1
>> nil.each {|x| puts x}
NoMethodError: undefined method `each' for nil:NilClass
    from (irb):4

Like Bayard says, each is more idiomatic. It hides more from you and doesn't require special language features. Per Telemachus's Comment

for .. in .. sets the iterator outside the scope of the loop, so

for a in [1,2]
  puts a
end

leaves a defined after the loop is finished. Where as each doesn't. Which is another reason in favor of using each, because the temp variable lives a shorter period.

How to add System.Windows.Interactivity to project?

If you are working with MVVM Light you have to use the System.Windows.Interactivity Version 4.0 (the NuGet .dll wont work) that you can find under :

PathToProjectFolder\Software\packages\MvvmLightLibs.5.4.1.1\lib\net45\System.Windows.Interactivity.dll

Just add this .dll manually as Reference and it should be fine.

How to skip over an element in .map()?

Why not just use a forEach loop?

_x000D_
_x000D_
let arr = ['a', 'b', 'c', 'd', 'e'];_x000D_
let filtered = [];_x000D_
_x000D_
arr.forEach(x => {_x000D_
  if (!x.includes('b')) filtered.push(x);_x000D_
});_x000D_
_x000D_
console.log(filtered)   // filtered === ['a','c','d','e'];
_x000D_
_x000D_
_x000D_

Or even simpler use filter:

const arr = ['a', 'b', 'c', 'd', 'e'];
const filtered = arr.filter(x => !x.includes('b')); // ['a','c','d','e'];

MySQL and PHP - insert NULL rather than empty string

All you have to do is: $variable =NULL; // and pass it in the insert query. This will store the value as NULL in mysql db

How to return first 5 objects of Array in Swift?

I slightly changed Markus' answer to update it for the latest Swift version, as var inside your method declaration is no longer supported:

extension Array {
    func takeElements(elementCount: Int) -> Array {
        if (elementCount > count) {
            return Array(self[0..<count])
        }
        return Array(self[0..<elementCount])
    }
}

How to reload current page?

This is the most simple solution if you just need to refresh the entire page

   refreshPage() {
    window.location.reload();
   }

TypeError: $.browser is undefined

just put the $.browser code in your js

var matched, browser;

jQuery.uaMatch = function( ua ) {
    ua = ua.toLowerCase();

    var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
        /(webkit)[ \/]([\w.]+)/.exec( ua ) ||
        /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
        /(msie) ([\w.]+)/.exec( ua ) ||
        ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
        [];

    return {
        browser: match[ 1 ] || "",
        version: match[ 2 ] || "0"
    };
};

matched = jQuery.uaMatch( navigator.userAgent );
browser = {};

if ( matched.browser ) {
    browser[ matched.browser ] = true;
    browser.version = matched.version;
}

// Chrome is Webkit, but Webkit is also Safari.
if ( browser.chrome ) {
    browser.webkit = true;
} else if ( browser.webkit ) {
    browser.safari = true;
}

jQuery.browser = browser;

ASP.NET Identity DbContext confusion

If you drill down through the abstractions of the IdentityDbContext you'll find that it looks just like your derived DbContext. The easiest route is Olav's answer, but if you want more control over what's getting created and a little less dependency on the Identity packages have a look at my question and answer here. There's a code example if you follow the link, but in summary you just add the required DbSets to your own DbContext subclass.

Launch Pycharm from command line (terminal)

Update: My answer no longer works as of PyCharm 2018.X

On MacOS, I have this alias in my bashrc:

alias pycharm="open -a /Applications/PyCharm*.app"

I can use it like this: pycharm <project dir or file>

The advantage of launching PyCharm this way is that you can open the current dir in PyCharm using pycharm . (unlike /Applications/PyCharm*.app/Contents/MacOS/pycharm . which opens the PyCharm application dir instead)


Update: I switched to JetBrains Toolbox to install PyCharm. Finding PyCharm has gotten a bit more complex, but so far I was lucky with this monster:

alias pycharm="open -a \"\$(ls -r  /Applications/apps/PyCharm*/*/*/PyCharm*.app | head -n 1 | sed 's/:$//')\""

kill a process in bash

Old post, but I just ran into a very similar problem. After some experimenting, I found that you can do this with a single command:

kill $(ps aux | grep <process_name> | grep -v "grep" | cut -d " " -f2)

In OP's case, <process_name> would be "gedit file.txt".

"Could not run curl-config: [Errno 2] No such file or directory" when installing pycurl

I had this issue on Mac and it was related to the openssl package being an older version of what it was required by pycurl. pycurl can use other ssl libraries rather than openssl as per my understanding of it. Verify which ssl library you're using and update as it is very likely to fix the issue.

I fixed this by:

  • running brew upgrade
  • downloaded the latest pycurl-x.y.z.tar.gz from http://pycurl.io/
  • extracted the package above and change directory into it
  • ran python setup.py --with-openssl install as openssl is the library I have installed. If you're ssl library is either gnutls or nss then will have to use --with-gnutls or --with-nss accordingly. You'll be able to find more installation info in their github repository.

How to get DropDownList SelectedValue in Controller in MVC

Thanks - this helped me to understand better ansd solve a problem I had. The JQuery provided to get the text of selectedItem did NOT wwork for me I changed it to

$(function () {
  $("#SelectedVender").on("change", function () {
   $("#SelectedvendorText").val($(**"#SelectedVender option:selected"**).text());
  });
});

Convert timedelta to total seconds

You can use mx.DateTime module

import mx.DateTime as mt

t1 = mt.now() 
t2 = mt.now()
print int((t2-t1).seconds)

How to remove files and directories quickly via terminal (bash shell)

So I was looking all over for a way to remove all files in a directory except for some directories, and files, I wanted to keep around. After much searching I devised a way to do it using find.

find -E . -regex './(dir1|dir2|dir3)' -and -type d -prune -o -print -exec rm -rf {} \;

Essentially it uses regex to select the directories to exclude from the results then removes the remaining files. Just wanted to put it out here in case someone else needed it.

cannot convert 'std::basic_string<char>' to 'const char*' for argument '1' to 'int system(const char*)'

The addition of a string literal with an std::string yields another std::string. system expects a const char*. You can use std::string::c_str() for that:

string name = "john";
string tmp = " quickscan.exe resolution 300 selectscanner jpg showui showprogress filename '"+name+".jpg'"
system(tmp.c_str());

How to scroll to bottom in react?

import React, {Component} from 'react';

export default class ChatOutPut extends Component {

    constructor(props) {
        super(props);
        this.state = {
            messages: props.chatmessages
        };
    }
    componentDidUpdate = (previousProps, previousState) => {
        if (this.refs.chatoutput != null) {
            this.refs.chatoutput.scrollTop = this.refs.chatoutput.scrollHeight;
        }
    }
    renderMessage(data) {
        return (
            <div key={data.key}>
                {data.message}
            </div>
        );
    }
    render() {
        return (
            <div ref='chatoutput' className={classes.chatoutputcontainer}>
                {this.state.messages.map(this.renderMessage, this)}
            </div>
        );
    }
}

Plotting time-series with Date labels on x-axis

I like ggplot too.

Here's one example:

df1 = data.frame(
date_id = c('2017-08-01', '2017-08-02', '2017-08-03', '2017-08-04'),          
nation = c('China', 'USA', 'China', 'USA'), 
value = c(4.0, 5.0, 6.0, 5.5))

ggplot(df1, aes(date_id, value, group=nation, colour=nation))+geom_line()+xlab(label='dates')+ylab(label='value')

enter image description here

Numpy: Divide each row by a vector element

Here you go. You just need to use None (or alternatively np.newaxis) combined with broadcasting:

In [6]: data - vector[:,None]
Out[6]:
array([[0, 0, 0],
       [0, 0, 0],
       [0, 0, 0]])

In [7]: data / vector[:,None]
Out[7]:
array([[1, 1, 1],
       [1, 1, 1],
       [1, 1, 1]])

How to return a value from pthread threads in C?

if you're uncomfortable with returning addresses and have just a single variable eg. an integer value to return, you can even typecast it into (void *) before passing it, and then when you collect it in the main, again typecast it into (int). You have the value without throwing up ugly warnings.

Failed to open the HAX device! HAX is not working and emulator runs in emulation mode emulator

I had this error and the other fixes didn't help me, but changing the CPU type the emulator used did get it working.

Create a new emulator and try using mips or arm for the cpu selection

What HTTP status response code should I use if the request is missing a required parameter?

I Usually go for 422 (Unprocessable entity) if something in the required parameters didn't match what the API endpoint required (like a too short password) but for a missing parameter i would go for 406 (Unacceptable).

Get the IP address of the machine

// Use a HTTP request to a well known server that echo's back the public IP address void GetPublicIP(CString & csIP) { // Initialize COM bool bInit = false; if (SUCCEEDED(CoInitialize(NULL))) { // COM was initialized bInit = true;

    // Create a HTTP request object
    MSXML2::IXMLHTTPRequestPtr HTTPRequest;
    HRESULT hr = HTTPRequest.CreateInstance("MSXML2.XMLHTTP");
    if (SUCCEEDED(hr))
    {
        // Build a request to a web site that returns the public IP address
        VARIANT Async;
        Async.vt = VT_BOOL;
        Async.boolVal = VARIANT_FALSE;
        CComBSTR ccbRequest = L"http://whatismyipaddress.com/";

        // Open the request
        if (SUCCEEDED(HTTPRequest->raw_open(L"GET",ccbRequest,Async)))
        {
            // Send the request
            if (SUCCEEDED(HTTPRequest->raw_send()))
            {
                // Get the response
                CString csRequest = HTTPRequest->GetresponseText();

                // Parse the IP address
                CString csMarker = "<!-- contact us before using a script to get your IP address -->";
                int iPos = csRequest.Find(csMarker);
                if (iPos == -1)
                    return;
                iPos += csMarker.GetLength();
                int iPos2 = csRequest.Find(csMarker,iPos);
                if (iPos2 == -1)
                    return;

                // Build the IP address
                int nCount = iPos2 - iPos;
                csIP = csRequest.Mid(iPos,nCount);
            }
        }
    }
}

// Unitialize COM
if (bInit)
    CoUninitialize();

}

XML Schema minOccurs / maxOccurs default values

New, expanded answer to an old, commonly asked question...

Default Values

  • Occurrence constraints minOccurs and maxOccurs default to 1.

Common Cases Explained

<xsd:element name="A"/>

means A is required and must appear exactly once.


<xsd:element name="A" minOccurs="0"/>

means A is optional and may appear at most once.


 <xsd:element name="A" maxOccurs="unbounded"/>

means A is required and may repeat an unlimited number of times.


 <xsd:element name="A" minOccurs="0" maxOccurs="unbounded"/>

means A is optional and may repeat an unlimited number of times.


See Also

  • W3C XML Schema Part 0: Primer

    In general, an element is required to appear when the value of minOccurs is 1 or more. The maximum number of times an element may appear is determined by the value of a maxOccurs attribute in its declaration. This value may be a positive integer such as 41, or the term unbounded to indicate there is no maximum number of occurrences. The default value for both the minOccurs and the maxOccurs attributes is 1. Thus, when an element such as comment is declared without a maxOccurs attribute, the element may not occur more than once. Be sure that if you specify a value for only the minOccurs attribute, it is less than or equal to the default value of maxOccurs, i.e. it is 0 or 1. Similarly, if you specify a value for only the maxOccurs attribute, it must be greater than or equal to the default value of minOccurs, i.e. 1 or more. If both attributes are omitted, the element must appear exactly once.

  • W3C XML Schema Part 1: Structures Second Edition

    <element
      maxOccurs = (nonNegativeInteger | unbounded)  : 1
      minOccurs = nonNegativeInteger : 1
      >
    
    </element>
    

Different CURRENT_TIMESTAMP and SYSDATE in oracle

  1. SYSDATE, systimestamp return datetime of server where database is installed. SYSDATE - returns only date, i.e., "yyyy-mm-dd". systimestamp returns date with time and zone, i.e., "yyyy-mm-dd hh:mm:ss:ms timezone"
  2. now() returns datetime at the time statement execution, i.e., "yyyy-mm-dd hh:mm:ss"
  3. CURRENT_DATE - "yyyy-mm-dd", CURRENT_TIME - "hh:mm:ss", CURRENT_TIMESTAMP - "yyyy-mm-dd hh:mm:ss timezone". These are related to a record insertion time.

Checking Value of Radio Button Group via JavaScript?

Try:


var selectedVal;

for( i = 0; i < document.form_name.gender.length; i++ )
{
  if(document.form_name.gender[i].checked)
    selectedVal = document.form_name.gender[i].value; //male or female
    break;
  }
}

kill -3 to get java thread dump

Steps that you should follow if you want the thread dump of your StandAlone Java Process

Step 1: Get the Process ID for the shell script calling the java program

linux$ ps -aef | grep "runABCD"

user1  **8535**  4369   0   Mar 25 ?           0:00 /bin/csh /home/user1/runABCD.sh

user1 17796 17372   0 08:15:41 pts/49      0:00 grep runABCD

Step 2: Get the Process ID for the Child which was Invoked by the runABCD. Use the above PID to get the childs.

linux$ ps -aef | grep **8535**

user1  **8536**  8535   0   Mar 25 ?         126:38 /apps/java/jdk/sun4/SunOS5/1.6.0_16/bin/java -cp /home/user1/XYZServer

user1  8535  4369   0   Mar 25 ?           0:00 /bin/csh /home/user1/runABCD.sh

user1 17977 17372   0 08:15:49 pts/49      0:00 grep 8535

Step 3: Get the JSTACK for the particular process. Get the Process id of your XYSServer process. i.e. 8536

linux$ jstack **8536** > threadDump.log

Bash foreach loop

If they all have the same extension (for example .jpg), you can use this:

for picture in  *.jpg ; do
    echo "the next file is $picture"
done

(This solution also works if the filename has spaces)

TypeError: 'function' object is not subscriptable - Python

You can use this:

bankHoliday= [1, 0, 1, 1, 2, 0, 0, 1, 0, 0, 0, 2] #gives the list of bank holidays in each month

def bank_holiday(month):
   month -= 1#Takes away the numbers from the months, as months start at 1 (January) not at 0. There is no 0 month.
   print(bankHoliday[month])

bank_holiday(int(input("Which month would you like to check out: ")))

Return outside function error in Python

It basically occours when you return from a loop you can only return from function

How Big can a Python List Get?

According to the source code, the maximum size of a list is PY_SSIZE_T_MAX/sizeof(PyObject*).

PY_SSIZE_T_MAX is defined in pyport.h to be ((size_t) -1)>>1

On a regular 32bit system, this is (4294967295 / 2) / 4 or 536870912.

Therefore the maximum size of a python list on a 32 bit system is 536,870,912 elements.

As long as the number of elements you have is equal or below this, all list functions should operate correctly.

Fatal error: Call to undefined function mb_detect_encoding()

Under Windows / WAMP there doesn't seem to be any php_mbstring.dll dependencies on the GD2 extension, the MySQL extensions, nor on external dlls/libs:

deplister.exe ext\php_mbstring.dll

php5ts.dll,OK
MSVCR110.dll,OK
KERNEL32.dll,OK

deplister.exe ext\php_gd2.dll

php5ts.dll,OK
USER32.dll,OK
GDI32.dll,OK
KERNEL32.dll,OK
MSVCR110.dll,OK

Whatever php_mbstring already needs, it's built-in (statically compiled right into the DLL).

Call to undefined function mb_detect_encoding()

This error is also very specific and deterministic...

The function mb_detect_encoding() didn't fail because php_gd, php_mysql, php_mysqli, or another extension was not loaded; it simply was NOT found.

I'm guessing that all the answers that are reported as valid (for Windows / WAMP), that say to load other extensions, to change php.ini extension_dir paths (if this one was wrong to begin with, NO extensions would load), etc, work more due to a) un-commenting the extension = php_mbstring.dll line, or b) restarting Apache or the computer (for changes to take effect).

On Windows, most of the time the problem is that php_mbstring.dll is either:

  • Blocked by Windows. Unblock it by right-clicking it, check Properties.

  • Or PHP can't load php_mbstring.dll due to another version getting loaded (e.g., from some improper PHP DLLs install into C:\Windows\system32), some version mismatch, missing run-time DLLs, etc. Check Apache's and PHP's error log files first for clues.

More in-depth answer here: Call to undefined function mb_detect_encoding

HTML image bottom alignment inside DIV container

Set the parent div as position:relative and the inner element to position:absolute; bottom:0

Optimal number of threads per core

speaking from computation and memory bound point of view (scientific computing) 4000 threads will make application run really slow. Part of the problem is a very high overhead of context switching and most likely very poor memory locality.

But it also depends on your architecture. From where I heard Niagara processors are suppose to be able to handle multiple threads on a single core using some kind of advanced pipelining technique. However I have no experience with those processors.

Difference between x86, x32, and x64 architectures?

Hans and DarkDust answer covered i386/i686 and amd64/x86_64, so there's no sense in revisiting them. This answer will focus on X32, and provide some info learned after a X32 port.

x32 is an ABI for amd64/x86_64 CPUs using 32-bit integers, longs and pointers. The idea is to combine the smaller memory and cache footprint from 32-bit data types with the larger register set of x86_64. (Reference: Debian X32 Port page).

x32 can provide up to about 30% reduction in memory usage and up to about 40% increase in speed. The use cases for the architecture are:

  • vserver hosting (memory bound)
  • netbooks/tablets (low memory, performance)
  • scientific tasks (performance)

x32 is a somewhat recent addition. It requires kernel support (3.4 and above), distro support (see below), libc support (2.11 or above), and GCC 4.8 and above (improved address size prefix support).

For distros, it was made available in Ubuntu 13.04 or Fedora 17. Kernel support only required pointer to be in the range from 0x00000000 to 0xffffffff. From the System V Application Binary Interface, AMD64 (With LP64 and ILP32 Programming Models), Section 10.4, p. 132 (its the only sentence):

10.4 Kernel Support
Kernel should limit stack and addresses returned from system calls between 0x00000000 to 0xffffffff.

When booting a kernel with the support, you must use syscall.x32=y option. When building a kernel, you must include the CONFIG_X86_X32=y option. (Reference: Debian X32 Port page and X32 System V Application Binary Interface).


Here is some of what I have learned through a recent port after the Debian folks reported a few bugs on us after testing:

  • the system is a lot like X86
  • the preprocessor defines __x86_64__ (and friends) and __ILP32__, but not __i386__/__i686__ (and friends)
  • you cannot use __ILP32__ alone because it shows up unexpectedly under Clang and Sun Studio
  • when interacting with the stack, you must use the 64-bit instructions pushq and popq
  • once a register is populated/configured from 32-bit data types, you can perform the 64-bit operations on them, like adcq
  • be careful of the 0-extension that occurs on the upper 32-bits.

If you are looking for a test platform, then you can use Debian 8 or above. Their wiki page at Debian X32 Port has all the information. The 3-second tour: (1) enable X32 in the kernel at boot; (2) use debootstrap to install the X32 chroot environment, and (3) chroot debian-x32 to enter into the environment and test your software.

findViewById in Fragment

1) Declare your layout file.

public View onCreateView(LayoutInflater inflater,ViewGroup container, 
                                 Bundle savedInstanceState) {
    return inflate(R.layout.myfragment, container, false);
}

2)Then, get the id of your view

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    TextView nameView = (TextView) view.findViewById(R.id.textview1);
}

Laravel: How do I parse this json data in view blade?

If your data is coming from a model you can do:

App\Http\Controller\SomeController

public function index(MyModel $model)
{
    return view('index', [
        'data' => $model->all()->toJson(),
    ]);
}

index.blade.php

@push('footer-scripts')
  <script>
    (function(global){
      var data = {!! $data !!};
      console.log(data);
      // [{..}]
    })(window);
  </script>
@endpush

In HTML5, should the main navigation be inside or outside the <header> element?

It's completely up to you. You can either put them in the header or not, as long as the elements within them are internal navigation elements only (i.e. don't link to external sites such as a twitter or facebook account) then it's fine.

They tend to get placed in a header simply because that's where navigation often goes, but it's not set in stone.

You can read more about it at HTML5 Doctor.

Change variable name in for loop using R

You could use assign, but using assign (or get) is often a symptom of a programming structure that is not very R like. Typically, lists or matrices allow cleaner solutions.

  • with a list:

    A <- lapply (1 : 10, function (x) d + rnorm (3))
    
  • with a matrix:

    A <- matrix (rep (d, each = 10) + rnorm (30), nrow = 10)
    

Python locale error: unsupported locale setting

More permanent solution would be to fill the missing values, in the output shown by command: locale

Output from locale is:

 $ locale
LANG=en_US.utf8
LANGUAGE=
LC_CTYPE="en_US.utf8"
LC_NUMERIC=es_ES.utf8
LC_TIME=es_ES.utf8
LC_COLLATE="en_US.utf8"
LC_MONETARY=es_ES.utf8
LC_MESSAGES="en_US.utf8"
LC_PAPER=es_ES.utf8
LC_NAME="en_US.utf8"
LC_ADDRESS="en_US.utf8"
LC_TELEPHONE="en_US.utf8"
LC_MEASUREMENT=es_ES.utf8
LC_IDENTIFICATION="en_US.utf8"
LC_ALL=

To Fill the missing values edit ~/.bashrc :

 $ vim ~/.bashrc

Add the following lines after the above command (suppose you want en_US.UTF-8 to be your language):

export LANGUAGE="en_US.UTF-8"
export LC_ALL="en_US.UTF-8"

If this file is ReadOnly you would be needing to follow the steps mentioned by The GeekyBoy. The answer given by Dr Beco in Superuser has details relating to saving readonly files.

After saving the file do:

$ source ~/.bashrc

Now you wont be facing the same problem anymore.

Python Graph Library

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

#ifdef in C#

#if DEBUG
bool bypassCheck=TRUE_OR_FALSE;//i will decide depending on what i am debugging
#else
bool bypassCheck = false; //NEVER bypass it
#endif

Make sure you have the checkbox to define DEBUG checked in your build properties.

Mockito match any class argument

There is another way to do that without cast:

when(a.method(Matchers.<Class<A>>any())).thenReturn(b);

This solution forces the method any() to return Class<A> type and not its default value (Object).

Where is the Postgresql config file: 'postgresql.conf' on Windows?

On my machine:

C:\Program Files\PostgreSQL\8.4\data\postgresql.conf

How do I make curl ignore the proxy?

You should use $no_proxy env variable (lower-case). Please consult https://wiki.archlinux.org/index.php/proxy_settings for examples.

Also, there was a bug at curl long time ago http://sourceforge.net/p/curl/bugs/185/ , maybe you are using an ancient curl version that includes this bug.

how to refresh Select2 dropdown menu after ajax loading different content?

select2 has the placeholder parameter. Use that one

$("#state").select2({
   placeholder: "Choose a Country"
 });

Javascript: Uncaught TypeError: Cannot call method 'addEventListener' of null

Your code is in the <head> => runs before the elements are rendered, so document.getElementById('compute'); returns null, as MDN promise...

element = document.getElementById(id);
element is a reference to an Element object, or null if an element with the specified ID is not in the document.

MDN

Solutions:

  1. Put the scripts in the bottom of the page.
  2. Call the attach code in the load event.
  3. Use jQuery library and it's DOM ready event.

What is the jQuery ready event and why is it needed?
(why no just JavaScript's load event):

While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers...
...

ready docs

Best way to include CSS? Why use @import?

There is not really much difference in adding a css stylesheet in the head versus using the import functionality. Using @import is generally used for chaining stylesheets so that one can be easily extended. It could be used to easily swap different color layouts for example in conjunction with some general css definitions. I would say the main advantage / purpose is extensibility.

I agree with xbonez comment as well in that portability and maintainability are added benefits.

What does -> mean in Python function definitions?

def function(arg)->123:

It's simply a return type, integer in this case doesn't matter which number you write.

like Java :

public int function(int args){...}

But for Python (how Jim Fasarakis Hilliard said) the return type it's just an hint, so it's suggest the return but allow anyway to return other type like a string..

Truncating all tables in a Postgres database

Just execute the query bellow:

DO $$ DECLARE
    r RECORD;
BEGIN
    FOR r IN (SELECT tablename FROM pg_tables WHERE schemaname = current_schema()) LOOP
        EXECUTE 'TRUNCATE TABLE ' || quote_ident(r.tablename) || '';
    END LOOP;
END $$;

How to check whether a Button is clicked by using JavaScript

This will do it

<input id="button" type="submit" name="button" onclick="myFunction();" value="enter"/>

<script>
function myFunction(){
    alert("You button was pressed");
};   
</script>

How to fix org.hibernate.LazyInitializationException - could not initialize proxy - no Session

What is wrong here is that your session management configuration is set to close session when you commit transaction. Check if you have something like:

<property name="current_session_context_class">thread</property>

in your configuration.

In order to overcome this problem you could change the configuration of session factory or open another session and only than ask for those lazy loaded objects. But what I would suggest here is to initialize this lazy collection in getModelByModelGroup itself and call:

Hibernate.initialize(subProcessModel.getElement());

when you are still in active session.

And one last thing. A friendly advice. You have something like this in your method:

for (Model m : modelList) {
    if (m.getModelType().getId() == 3) {
        model = m;
        break;
    }
}

Please insted of this code just filter those models with type id equal to 3 in the query statement just couple of lines above.

Some more reading:

session factory configuration

problem with closed session

Swift how to sort array of custom objects by property value

If you are going to be sorting this array in more than one place, it may make sense to make your array type Comparable.

class MyImageType: Comparable, Printable {
    var fileID: Int

    // For Printable
    var description: String {
        get {
            return "ID: \(fileID)"
        }
    }

    init(fileID: Int) {
        self.fileID = fileID
    }
}

// For Comparable
func <(left: MyImageType, right: MyImageType) -> Bool {
    return left.fileID < right.fileID
}

// For Comparable
func ==(left: MyImageType, right: MyImageType) -> Bool {
    return left.fileID == right.fileID
}

let one = MyImageType(fileID: 1)
let two = MyImageType(fileID: 2)
let twoA = MyImageType(fileID: 2)
let three = MyImageType(fileID: 3)

let a1 = [one, three, two]

// return a sorted array
println(sorted(a1)) // "[ID: 1, ID: 2, ID: 3]"

var a2 = [two, one, twoA, three]

// sort the array 'in place'
sort(&a2)
println(a2) // "[ID: 1, ID: 2, ID: 2, ID: 3]"

Overlay with spinner

Here is an Pure CSS endless spinner. Position absolute, to place the buttons on top of each other.

_x000D_
_x000D_
button {
            position: absolute;
            width: 150px;
            font-size: 120%;
            padding: 5px;
            background: #B52519;
            color: #EAEAEA;
            border: none;
            margin: 50px;
            border-radius: 5px;
            display: flex;
            align-content: center;
            justify-content: center;
            transition: all 0.5s;
            cursor: pointer;
        }

        #orderButton:hover {
            color: #c8c8c8;
        }

        #orderLoading {
            animation: rotation 1s infinite linear;
            height: 20px;
            width: 20px;
            display: flex;
            justify-content: center;
            align-items: center;
            border-radius: 100%;
            border: 2px solid;
            border-style: outset;
            color: #fff;
        }

        @keyframes rotation {
            from {
                transform: rotate(0deg);
            }
            to {
                transform: rotate(360deg);
            }
        }
_x000D_
<button><div id="orderLoading"></div></button>
<button id="orderButton" onclick="this.style.visibility= 'hidden';">Order!</button>
_x000D_
_x000D_
_x000D_

Haversine Formula in Python (Bearing and Distance between two GPS points)

Here's a numpy vectorized implementation of the Haversine Formula given by @Michael Dunn, gives a 10-50 times improvement over large vectors.

from numpy import radians, cos, sin, arcsin, sqrt

def haversine(lon1, lat1, lon2, lat2):
    """
    Calculate the great circle distance between two points 
    on the earth (specified in decimal degrees)
    """

    #Convert decimal degrees to Radians:
    lon1 = np.radians(lon1.values)
    lat1 = np.radians(lat1.values)
    lon2 = np.radians(lon2.values)
    lat2 = np.radians(lat2.values)

    #Implementing Haversine Formula: 
    dlon = np.subtract(lon2, lon1)
    dlat = np.subtract(lat2, lat1)

    a = np.add(np.power(np.sin(np.divide(dlat, 2)), 2),  
                          np.multiply(np.cos(lat1), 
                                      np.multiply(np.cos(lat2), 
                                                  np.power(np.sin(np.divide(dlon, 2)), 2))))
    c = np.multiply(2, np.arcsin(np.sqrt(a)))
    r = 6371

    return c*r

Opening a remote machine's Windows C drive

If it's not the Home edition of XP, you can use \\servername\c$

Mark Brackett's comment:

Note that you need to be an Administrator on the local machine, as the share permissions are locked down

What is the maximum possible length of a query string?

RFC 2616 (Hypertext Transfer Protocol — HTTP/1.1) states there is no limit to the length of a query string (section 3.2.1). RFC 3986 (Uniform Resource Identifier — URI) also states there is no limit, but indicates the hostname is limited to 255 characters because of DNS limitations (section 2.3.3).

While the specifications do not specify any maximum length, practical limits are imposed by web browser and server software. Based on research which is unfortunately no longer available on its original site (it leads to a shady seeming loan site) but which can still be found at Internet Archive Of Boutell.com:

  • Microsoft Internet Explorer (Browser)
    Microsoft states that the maximum length of a URL in Internet Explorer is 2,083 characters, with no more than 2,048 characters in the path portion of the URL. Attempts to use URLs longer than this produced a clear error message in Internet Explorer.

  • Microsoft Edge (Browser)
    The limit appears to be around 81578 characters. See URL Length limitation of Microsoft Edge

  • Chrome
    It stops displaying the URL after 64k characters, but can serve more than 100k characters. No further testing was done beyond that.

  • Firefox (Browser)
    After 65,536 characters, the location bar no longer displays the URL in Windows Firefox 1.5.x. However, longer URLs will work. No further testing was done after 100,000 characters.

  • Safari (Browser)
    At least 80,000 characters will work. Testing was not tried beyond that.

  • Opera (Browser)
    At least 190,000 characters will work. Stopped testing after 190,000 characters. Opera 9 for Windows continued to display a fully editable, copyable and pasteable URL in the location bar even at 190,000 characters.

  • Apache (Server)
    Early attempts to measure the maximum URL length in web browsers bumped into a server URL length limit of approximately 4,000 characters, after which Apache produces a "413 Entity Too Large" error. The current up to date Apache build found in Red Hat Enterprise Linux 4 was used. The official Apache documentation only mentions an 8,192-byte limit on an individual field in a request.

  • Microsoft Internet Information Server (Server)
    The default limit is 16,384 characters (yes, Microsoft's web server accepts longer URLs than Microsoft's web browser). This is configurable.

  • Perl HTTP::Daemon (Server)
    Up to 8,000 bytes will work. Those constructing web application servers with Perl's HTTP::Daemon module will encounter a 16,384 byte limit on the combined size of all HTTP request headers. This does not include POST-method form data, file uploads, etc., but it does include the URL. In practice this resulted in a 413 error when a URL was significantly longer than 8,000 characters. This limitation can be easily removed. Look for all occurrences of 16x1024 in Daemon.pm and replace them with a larger value. Of course, this does increase your exposure to denial of service attacks.

How to force a checkbox and text on the same line?

It wont break if you wrap each item in a div. Check out my fiddle with the link below. I made the width of the fieldset 125px and made each item 50px wide. You'll see the label and checkbox remain side by side on a new line and don't break.

<fieldset>
<div class="item">
    <input type="checkbox" id="a">
    <label for="a">a</label>
</div>
<div class="item">
   <input type="checkbox" id="b">
<!-- depending on width, a linebreak can occur here. -->
    <label for="b">bgf bh fhg fdg hg dg gfh dfgh</label>
</div>
<div class="item">
    <input type="checkbox" id="c">
    <label for="c">c</label>
</div>
</fieldset>

http://jsfiddle.net/t5dwp7pg/1/

How do you add Boost libraries in CMakeLists.txt?

Put this in your CMakeLists.txt file (change any options from OFF to ON if you want):

set(Boost_USE_STATIC_LIBS OFF) 
set(Boost_USE_MULTITHREADED ON)  
set(Boost_USE_STATIC_RUNTIME OFF) 
find_package(Boost 1.45.0 COMPONENTS *boost libraries here*) 

if(Boost_FOUND)
    include_directories(${Boost_INCLUDE_DIRS}) 
    add_executable(progname file1.cxx file2.cxx) 
    target_link_libraries(progname ${Boost_LIBRARIES})
endif()

Obviously you need to put the libraries you want where I put *boost libraries here*. For example, if you're using the filesystem and regex library you'd write:

find_package(Boost 1.45.0 COMPONENTS filesystem regex)

What does the star operator mean, in a function call?

In a function call the single star turns a list into seperate arguments (e.g. zip(*x) is the same as zip(x1,x2,x3) if x=[x1,x2,x3]) and the double star turns a dictionary into seperate keyword arguments (e.g. f(**k) is the same as f(x=my_x, y=my_y) if k = {'x':my_x, 'y':my_y}.

In a function definition it's the other way around: the single star turns an arbitrary number of arguments into a list, and the double start turns an arbitrary number of keyword arguments into a dictionary. E.g. def foo(*x) means "foo takes an arbitrary number of arguments and they will be accessible through the list x (i.e. if the user calls foo(1,2,3), x will be [1,2,3])" and def bar(**k) means "bar takes an arbitrary number of keyword arguments and they will be accessible through the dictionary k (i.e. if the user calls bar(x=42, y=23), k will be {'x': 42, 'y': 23})".

Pass parameter to controller from @Html.ActionLink MVC 4

You are using a wrong overload of the Html.ActionLink helper. What you think is routeValues is actually htmlAttributes! Just look at the generated HTML, you will see that this anchor's href property doesn't look as you expect it to look.

Here's what you are using:

@Html.ActionLink(
    "Reply",                                                  // linkText
    "BlogReplyCommentAdd",                                    // actionName
    "Blog",                                                   // routeValues
    new {                                                     // htmlAttributes
        blogPostId = blogPostId, 
        replyblogPostmodel = Model, 
        captchaValid = Model.AddNewComment.DisplayCaptcha 
    }
)

and here's what you should use:

@Html.ActionLink(
    "Reply",                                                  // linkText
    "BlogReplyCommentAdd",                                    // actionName
    "Blog",                                                   // controllerName
    new {                                                     // routeValues
        blogPostId = blogPostId, 
        replyblogPostmodel = Model, 
        captchaValid = Model.AddNewComment.DisplayCaptcha 
    },
    null                                                      // htmlAttributes
)

Also there's another very serious issue with your code. The following routeValue:

replyblogPostmodel = Model

You cannot possibly pass complex objects like this in an ActionLink. So get rid of it and also remove the BlogPostModel parameter from your controller action. You should use the blogPostId parameter to retrieve the model from wherever this model is persisted, or if you prefer from wherever you retrieved the model in the GET action:

public ActionResult BlogReplyCommentAdd(int blogPostId, bool captchaValid)
{
    BlogPostModel model = repository.Get(blogPostId);
    ...
}

As far as your initial problem is concerned with the wrong overload I would recommend you writing your helpers using named parameters:

@Html.ActionLink(
    linkText: "Reply",
    actionName: "BlogReplyCommentAdd",
    controllerName: "Blog",
    routeValues: new {
        blogPostId = blogPostId, 
        captchaValid = Model.AddNewComment.DisplayCaptcha
    },
    htmlAttributes: null
)

Now not only that your code is more readable but you will never have confusion between the gazillions of overloads that Microsoft made for those helpers.

String parsing in Java with delimiter tab "\t" using split

String[] columnDetail = new String[11];
columnDetail = column.split("\t", -1); // unlimited
OR
columnDetail = column.split("\t", 11); // if you are sure about limit.
 * The {@code limit} parameter controls the number of times the
 * pattern is applied and therefore affects the length of the resulting
 * array.  If the limit <i>n</i> is greater than zero then the pattern
 * will be applied at most <i>n</i>&nbsp;-&nbsp;1 times, the array's
 * length will be no greater than <i>n</i>, and the array's last entry
 * will contain all input beyond the last matched delimiter.  If <i>n</i>
 * is non-positive then the pattern will be applied as many times as
 * possible and the array can have any length.  If <i>n</i> is zero then
 * the pattern will be applied as many times as possible, the array can
 * have any length, and trailing empty strings will be discarded.

How can I add a help method to a shell script?

For a quick single option solution, use if

If you only have a single option to check and it will always be the first option ($1) then the simplest solution is an if with a test ([). For example:

if [ "$1" == "-h" ] ; then
    echo "Usage: `basename $0` [-h]"
    exit 0
fi

Note that for posix compatibility = will work as well as ==.

Why quote $1?

The reason the $1 needs to be enclosed in quotes is that if there is no $1 then the shell will try to run if [ == "-h" ] and fail because == has only been given a single argument when it was expecting two:

$ [ == "-h" ]
bash: [: ==: unary operator expected

For anything more complex use getopt or getopts

As suggested by others, if you have more than a single simple option, or need your option to accept an argument, then you should definitely go for the extra complexity of using getopts.

As a quick reference, I like The 60 second getopts tutorial.

You may also want to consider the getopt program instead of the built in shell getopts. It allows the use of long options, and options after non option arguments (e.g. foo a b c --verbose rather than just foo -v a b c). This Stackoverflow answer explains how to use GNU getopt.

jeffbyrnes mentioned that the original link died but thankfully the way back machine had archived it.

How to use '-prune' option of 'find' in sh?

Show everything including dir itself but not its long boring contents:

find . -print -name dir -prune

Android: java.lang.SecurityException: Permission Denial: start Intent

I was running into the same issue and wanted to avoid adding the intent filter as you described. After some digging, I found an xml attribute android:exported that you should add to the activity you would like to be called.

It is by default set to false if no intent filter added to your activity, but if you do have an intent filter it gets set to true.

here is the documentation http://developer.android.com/guide/topics/manifest/activity-element.html#exported

tl;dr: addandroid:exported="true" to your activity in your AndroidManifest.xml file and avoid adding the intent-filter :)

How do I automatically set the $DISPLAY variable for my current session?

Your vncserver have a configuration file somewher that set the display number. To do it automaticaly, one solution is to parse this file, extract the number and set it correctly. A simpler (better) is to have this display number set in a config script and use it in both your VNC server config and in your init scripts.

How to uncheck a checkbox in pure JavaScript?

Recommended, without jQuery:

Give your <input> an ID and refer to that. Also, remove the checked="" part of the <input> tag if you want the checkbox to start out unticked. Then it's:

document.getElementById("my-checkbox").checked = true;

Pure JavaScript, with no Element ID (#1):

var inputs = document.getElementsByTagName('input');

for(var i = 0; i<inputs.length; i++){

  if(typeof inputs[i].getAttribute === 'function' && inputs[i].getAttribute('name') === 'copyNewAddrToBilling'){

    inputs[i].checked = true;

    break;

  }
}

Pure Javascript, with no Element ID (#2):

document.querySelectorAll('.text input[name="copyNewAddrToBilling"]')[0].checked = true;

document.querySelector('.text input[name="copyNewAddrToBilling"]').checked = true;

Note that the querySelectorAll and querySelector methods are supported in these browsers: IE8+, Chrome 4+, Safari 3.1+, Firefox 3.5+ and all mobile browsers.

If the element may be missing, you should test for its existence, e.g.:

var input = document.querySelector('.text input[name="copyNewAddrToBilling"]');
if (!input) { return; }

With jQuery:

$('.text input[name="copyNewAddrToBilling"]').prop('checked', true);

Regex: Remove lines containing "help", etc

If you're on Windows, try findstr. Third-party tools are not needed:

findstr /V /L "searchstring" inputfile.txt > outputfile.txt

It supports regex's too! Just read the tool's help findstr /?.

P.S. If you want to work with big, huge files (like 400 MB log files) a text editor is not very memory-efficient, so, as someone already pointed out, command-line tools are the way to go. But there's no grep on Windows, so...

I just ran this on a 1 GB log file, and it literally took 3 seconds.

Passing data to a bootstrap modal

Bootstrap 4.0 gives an option to modify modal data using jquery: https://getbootstrap.com/docs/4.0/components/modal/#varying-modal-content

Here is the script tag on the docs :

$('#exampleModal').on('show.bs.modal', function (event) {
  var button = $(event.relatedTarget) // Button that triggered the modal
  var recipient = button.data('whatever') // Extract info from data-* attributes
  // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
  // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
  var modal = $(this)
  modal.find('.modal-title').text('New message to ' + recipient)
  modal.find('.modal-body input').val(recipient)
})

It works for the most part. Only call to modal was not working. Here is a modification on the script that works for me:

$(document).on('show.bs.modal', '#exampleModal',function(event){
... // same as in above script
})

How to set table name in dynamic SQL query?

Try this:

/* Variable Declaration */
DECLARE @EmpID AS SMALLINT
DECLARE @SQLQuery AS NVARCHAR(500)
DECLARE @ParameterDefinition AS NVARCHAR(100)
DECLARE @TableName AS NVARCHAR(100)
/* set the parameter value */
SET @EmpID = 1001
SET @TableName = 'tblEmployees'
/* Build Transact-SQL String by including the parameter */
SET @SQLQuery = 'SELECT * FROM ' + @TableName + ' WHERE EmployeeID = @EmpID' 
/* Specify Parameter Format */
SET @ParameterDefinition =  '@EmpID SMALLINT'
/* Execute Transact-SQL String */
EXECUTE sp_executesql @SQLQuery, @ParameterDefinition, @EmpID

Command for restarting all running docker containers?

For me its now :

docker restart $(docker ps -a -q)

What is the point of the diamond operator (<>) in Java 7?

In theory, the diamond operator allows you to write more compact (and readable) code by saving repeated type arguments. In practice, it's just two confusing chars more giving you nothing. Why?

  1. No sane programmer uses raw types in new code. So the compiler could simply assume that by writing no type arguments you want it to infer them.
  2. The diamond operator provides no type information, it just says the compiler, "it'll be fine". So by omitting it you can do no harm. At any place where the diamond operator is legal it could be "inferred" by the compiler.

IMHO, having a clear and simple way to mark a source as Java 7 would be more useful than inventing such strange things. In so marked code raw types could be forbidden without losing anything.

Btw., I don't think that it should be done using a compile switch. The Java version of a program file is an attribute of the file, no option at all. Using something as trivial as

package 7 com.example;

could make it clear (you may prefer something more sophisticated including one or more fancy keywords). It would even allow to compile sources written for different Java versions together without any problems. It would allow introducing new keywords (e.g., "module") or dropping some obsolete features (multiple non-public non-nested classes in a single file or whatsoever) without losing any compatibility.

Django ManyToMany filter()

another way to do this is by going through the intermediate table. I'd express this within the Django ORM like this:

UserZone = User.zones.through

# for a single zone
users_in_zone = User.objects.filter(
  id__in=UserZone.objects.filter(zone=zone1).values('user'))

# for multiple zones
users_in_zones = User.objects.filter(
  id__in=UserZone.objects.filter(zone__in=[zone1, zone2, zone3]).values('user'))

it would be nice if it didn't need the .values('user') specified, but Django (version 3.0.7) seems to need it.

the above code will end up generating SQL that looks something like:

SELECT * FROM users WHERE id IN (SELECT user_id FROM userzones WHERE zone_id IN (1,2,3))

which is nice because it doesn't have any intermediate joins that could cause duplicate users to be returned

Warning: mysqli_query() expects at least 2 parameters, 1 given. What?

The issue is that you're not saving the mysqli connection. Change your connect to:

$aVar = mysqli_connect('localhost','tdoylex1_dork','dorkk','tdoylex1_dork');

And then include it in your query:

$query1 = mysqli_query($aVar, "SELECT name1 FROM users
    ORDER BY RAND()
    LIMIT 1");
$aName1 = mysqli_fetch_assoc($query1);
$name1 = $aName1['name1'];

Also don't forget to enclose your connections variables as strings as I have above. This is what's causing the error but you're using the function wrong, mysqli_query returns a query object but to get the data out of this you need to use something like mysqli_fetch_assoc http://php.net/manual/en/mysqli-result.fetch-assoc.php to actually get the data out into a variable as I have above.

How to declare a global variable in a .js file

Have you tried it?

If you do:

var HI = 'Hello World';

In global.js. And then do:

alert(HI);

In js1.js it will alert it fine. You just have to include global.js prior to the rest in the HTML document.

The only catch is that you have to declare it in the window's scope (not inside any functions).

You could just nix the var part and create them that way, but it's not good practice.

use std::fill to populate vector with increasing numbers

There is another option - without using iota. For_each + lambda expression can be used:

vector<int> ivec(10); // the vector of size 10
int i = 0;            // incrementor
for_each(ivec.begin(), ivec.end(), [&](int& item) { ++i; item += i;});

Two important things why it's working:

  1. Lambda captures outer scope [&] which means that i will be available inside expression
  2. item passed as a reference, therefore, it is mutable inside the vector

How to use graphics.h in codeblocks?

  • Open the file graphics.h using either of Sublime Text Editor or Notepad++,from the include folder where you have installed Codeblocks.
  • Goto line no 302
  • Delete the line and paste int left=0, int top=0, int right=INT_MAX, int bottom=INT_MAX, in that line.
  • Save the file and start Coding.