Programs & Examples On #Boxsizer

Boxsizer is a type of sizer that is used in GUIs to align and position elements inside a container, so that elements will most often be laid out in rather simple basic geometry, typically in a row or a column or several hierarchies of either.

How do I read a specified line in a text file?

        if (File.Exists(fpath))
        {

            var data = File.ReadLines(fpath);
            Console.WriteLine(data.ToArray()[14]);
        }

Looping each row in datagridview

Best aproach for me was:

  private void grid_receptie_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        int X = 1;
        foreach(DataGridViewRow row in grid_receptie.Rows)
        {
            row.Cells["NR_CRT"].Value = X;
            X++;
        }
    }

How do you create a hidden div that doesn't create a line break or horizontal space?

In addition to CMS´ answer you may want to consider putting the style in an external stylesheet and assign the style to the id, like this:

#divCheckbox {
display: none;
}

How to reload the current route with the angular 2 router

Suppose that the component's route you want to refresh is view, then use this:

this.router.routeReuseStrategy.shouldReuseRoute = function (future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot) {
  if (future.url.toString() === 'view' && curr.url.toString() === future.url.toString()) {
    return false;
  }
  return (future.routeConfig === curr.routeConfig);
}; 

you can add a debugger inside the method to know what is the exact route will come after navigate to "departments/:id/employees".

Finding the index of elements based on a condition using python list comprehension

For me it works well:

>>> import numpy as np
>>> a = np.array([1, 2, 3, 1, 2, 3])
>>> np.where(a > 2)[0]
[2 5]

ValueError: setting an array element with a sequence

From the code you showed us, the only thing we can tell is that you are trying to create an array from a list that isn't shaped like a multi-dimensional array. For example

numpy.array([[1,2], [2, 3, 4]])

or

numpy.array([[1,2], [2, [3, 4]]])

will yield this error message, because the shape of the input list isn't a (generalised) "box" that can be turned into a multidimensional array. So probably UnFilteredDuringExSummaryOfMeansArray contains sequences of different lengths.

Edit: Another possible cause for this error message is trying to use a string as an element in an array of type float:

numpy.array([1.2, "abc"], dtype=float)

That is what you are trying according to your edit. If you really want to have a NumPy array containing both strings and floats, you could use the dtype object, which enables the array to hold arbitrary Python objects:

numpy.array([1.2, "abc"], dtype=object)

Without knowing what your code shall accomplish, I can't judge if this is what you want.

How do you create a temporary table in an Oracle database?

CREATE TABLE table_temp_list_objects AS
SELECT o.owner, o.object_name FROM sys.all_objects o WHERE o.object_type ='TABLE';

pip install - locale.Error: unsupported locale setting

For Dockerfile, this works for me:

RUN locale-gen en_US.UTF-8  
ENV LANG en_US.UTF-8  
ENV LANGUAGE en_US:en  
ENV LC_ALL en_US.UTF-8  

How to install locale-gen?

docker ubuntu /bin/sh: 1: locale-gen: not found

string.split - by multiple character delimiter

Regex.Split("abc][rfd][5][,][.", @"\]\]");

Rebase array keys after unsetting elements

Got another interesting method:

$array = array('a', 'b', 'c', 'd'); 
unset($array[2]); 

$array = array_merge($array); 

Now the $array keys are reset.

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

I do this all the time, all I do is

WriteXLS::WriteXLS(
    all.dataframes,
    ExcelFileName = xl.filename,
    AdjWidth = T,
    AutoFilter = T,
    FreezeRow = 1,
    FreezeCol = 2,
    BoldHeaderRow = T,
    verbose = F,
    na = '0'
  )

and all those data frames come from here

all.dataframes <- vector()
for (obj.iter in all.objects) {
  obj.name <- obj.iter
  obj.iter <- get(obj.iter)
  if (class(obj.iter) == 'data.frame') {
      all.dataframes <- c(all.dataframes, obj.name)
}

obviously sapply routine would be better here

Modifying list while iterating

Never alter the container you're looping on, because iterators on that container are not going to be informed of your alterations and, as you've noticed, that's quite likely to produce a very different loop and/or an incorrect one. In normal cases, looping on a copy of the container helps, but in your case it's clear that you don't want that, as the container will be empty after 50 legs of the loop and if you then try popping again you'll get an exception.

What's anything BUT clear is, what behavior are you trying to achieve, if any?! Maybe you can express your desires with a while...?

i = 0
while i < len(some_list):
    print i,                         
    print some_list.pop(0),                  
    print some_list.pop(0)

Loop through properties in JavaScript object with Lodash

It would be helpful to understand why you need to do this with lodash. If you just want to check if a key exists in an object, you don't need lodash.

myObject.options.hasOwnProperty('property');

If your looking to see if a value exists, you can use _.invert

_.invert(myObject.options)[value]

Making LaTeX tables smaller?

http://en.wikibooks.org/wiki/LaTeX/Tables#Resize_tables talks about two ways to do this.

I used:

\scalebox{0.7}{
  \begin{tabular}
    ...
  \end{tabular}
}

Bower: ENOGIT Git is not installed or not in the PATH

I am also getting the same error and the solution is first to check if the Git is installed or not in the system and if not please install it.

After installation, open Git Bash or Git Shell from Windows and go to your project (same way you go in command prompt using "cd path"). Git Shell is installed by default with Github windows installation.

Then run the same bower install command. It will work as expected.

The below screenshot shows the command using Git Shell Bower install using Git Shell

Responsive timeline UI with Bootstrap3

BootFlat

You can also try BootFlat, which has a section in their documentation specifically for crafting Timelines:

enter image description here

Why is there an unexplainable gap between these inline-block div elements?

Using inline-block allows for white-space in your HTML, This usually equates to .25em (or 4px).

You can either comment out the white-space or, a more commons solution, is to set the parent's font-size to 0 and the reset it back to the required size on the inline-block elements.

How do you implement a good profanity filter?

I don't know of any good libraries for this, but whatever you do, make sure that you err in the direction of letting stuff through. I've dealt with systems that wouldn't allow me to use "mpassell" as a username, because it contains "ass" as a substring. That's a great way to alienate users!

ALTER TABLE to add a composite primary key

alter table table_name add primary key (col_name1, col_name2);

How to allow access outside localhost

for me it works using "ng serve --open --host 0.0.0.0" but there is a warning


WARNING: This is a simple server for use in testing or debugging Angular applications locally. It hasn't been reviewed for security issues.

Binding this server to an open connection can result in compromising your application or computer. Using a different host than the one passed to the "--host" flag might result in websocket connection issues. You might need to use "--disableHostCheck" if that's the case.

Box shadow for bottom side only

-webkit-box-shadow: 0 3px 5px -3px #000;
-moz-box-shadow: 0 3px 5px -3px #000;
box-shadow: 0 3px 5px -3px #000;

How to override Bootstrap's Panel heading background color?

You can simply add an id attribute to the panel. Like this

<div class="panel-heading" id="mypanelId">Hello world </div>

Then in your custom CSS file:

#mypanelId{
    background-image: none;
    background: rgba(22, 20, 100, 0.8);
    color: white;
     }

Boolean vs tinyint(1) for boolean values in MySQL

My experience when using Dapper to connect to MySQL is that it does matter. I changed a non nullable bit(1) to a nullable tinyint(1) by using the following script:

ALTER TABLE TableName MODIFY Setting BOOLEAN null;

Then Dapper started throwing Exceptions. I tried to look at the difference before and after the script. And noticed the bit(1) had changed to tinyint(1).

I then ran:

ALTER TABLE TableName CHANGE COLUMN Setting Setting BIT(1) NULL DEFAULT NULL;

Which solved the problem.

Create a File object in memory from a string in Java

The File class represents the "idea" of a file, not an actual handle to use for I/O. This is why the File class has a .exists() method, to tell you if the file exists or not. (How can you have a File object that doesn't exist?)

By contrast, constructing a new FileInputStream(new File("/my/file")) gives you an actual stream to read bytes from.

Parsing arguments to a Java command line program

Ok, thanks to Charles Goodwin for the concept. Here is the answer:

import java.util.*;
public class Test {

  public static void main(String[] args) {
     List<String> argsList  = new ArrayList<String>();  
     List<String> optsList  = new ArrayList<String>();
     List<String> doubleOptsList  = new ArrayList<String>();
     for (int i=0; i < args.length; i++) {
         switch (args[i].charAt(0)) {
         case '-':
             if (args[i].charAt(1) == '-') {
                 int len = 0;
                 String argstring = args[i].toString();
                 len = argstring.length();
                 System.out.println("Found double dash with command " +
                     argstring.substring(2, len) );
                 doubleOptsList.add(argstring.substring(2, len));           
             } else {
                 System.out.println("Found dash with command " + 
                   args[i].charAt(1) + " and value " + args[i+1] );   
                 i= i+1;
                 optsList.add(args[i]);      
             }           
         break;         
         default:            
         System.out.println("Add a default arg." );
         argsList.add(args[i]);
         break;         
         }     
     } 
  } 

}

Configuration Error: <compilation debug="true" targetFramework="4.0"> ASP.NET MVC3

I was now able to find reason behind the error guys. It's on the webhosting site settings not on my app pool or what so ever. I changed the asp.net version from 2.0 to 4.0 but I forgot to click the update button. I feel so embarrased. :( I've been struggling for days to fix this error and only to found out its on the webhosting site settings. GgrrRR.. As of now I'm facing new error but has nothing to do with this question. Anyway thanks guys for your efforts to help me. :)

Display Bootstrap Modal using javascript onClick

You don't need an onclick. Assuming you're using Bootstrap 3 Bootstrap 3 Documentation

<div class="span4 proj-div" data-toggle="modal" data-target="#GSCCModal">Clickable content, graphics, whatever</div>

<div id="GSCCModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
 <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;  </button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

If you're using Bootstrap 2, you'd follow the markup here: http://getbootstrap.com/2.3.2/javascript.html#modals

Count unique values using pandas groupby

I know it has been a while since this was posted, but I think this will help too. I wanted to count unique values and filter the groups by number of these unique values, this is how I did it:

df.groupby('group').agg(['min','max','count','nunique']).reset_index(drop=False)

Select 2 columns in one and combine them

if one of the column is number i have experienced the oracle will think '+' as sum operator instead concatenation.

eg:

select (id + name) as one from table 1; (id is numeric) 

throws invalid number exception

in such case you can || operator which is concatenation.

select (id || name) as one from table 1;

iFrame onload JavaScript event

Update

As of jQuery 3.0, the new syntax is just .on:

see this answer here and the code:

$('iframe').on('load', function() {
    // do stuff 
});

Xampp-mysql - "Table doesn't exist in engine" #1932

  1. stop mysql
  2. copy xampp\mysql\data\ib* from old server to new server
  3. start mysql

Displaying one div on top of another

Here is the jsFiddle

#backdrop{
    border: 2px solid red;
    width: 400px;
    height: 200px;
    position: absolute;
}

#curtain {
    border: 1px solid blue;
    width: 400px;
    height: 200px;
    position: absolute;
}

Use Z-index to move the one you want on top.

How to store printStackTrace into a string

call:  getStackTraceAsString(sqlEx)

public String getStackTraceAsString(Exception exc)  
{  
String stackTrace = "*** Error in getStackTraceAsString()";

ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream( baos );
exc.printStackTrace(ps);
try {
    stackTrace = baos.toString( "UTF8" ); // charsetName e.g. ISO-8859-1
    } 
catch( UnsupportedEncodingException ex )
    {
    Logger.getLogger(sss.class.getName()).log(Level.SEVERE, null, ex);
    }
ps.close();
try {
    baos.close();
    } 
catch( IOException ex )
    {
    Logger.getLogger(sss.class.getName()).log(Level.SEVERE, null, ex);
    }
return stackTrace;
}

WPF Application that only has a tray icon

You have to use the NotifyIcon control from System.Windows.Forms, or alternatively you can use the Notify Icon API provided by Windows API. WPF Provides no such equivalent, and it has been requested on Microsoft Connect several times.

I have code on GitHub which uses System.Windows.Forms NotifyIcon Component from within a WPF application, the code can be viewed at https://github.com/wilson0x4d/Mubox/blob/master/Mubox.QuickLaunch/AppWindow.xaml.cs

Here are the summary bits:

Create a WPF Window with ShowInTaskbar=False, and which is loaded in a non-Visible State.

At class-level:

private System.Windows.Forms.NotifyIcon notifyIcon = null;

During OnInitialize():

notifyIcon = new System.Windows.Forms.NotifyIcon();
notifyIcon.Click += new EventHandler(notifyIcon_Click);
notifyIcon.DoubleClick += new EventHandler(notifyIcon_DoubleClick);
notifyIcon.Icon = IconHandles["QuickLaunch"];

During OnLoaded():

notifyIcon.Visible = true;

And for interaction (shown as notifyIcon.Click and DoubleClick above):

void notifyIcon_Click(object sender, EventArgs e)
{
    ShowQuickLaunchMenu();
}

From here you can resume the use of WPF Controls and APIs such as context menus, pop-up windows, etc.

It's that simple. You don't exactly need a WPF Window to host to the component, it's just the most convenient way to introduce one into a WPF App (as a Window is generally the default entry point defined via App.xaml), likewise, you don't need a WPF Wrapper or 3rd party control, as the SWF component is guaranteed present in any .NET Framework installation which also has WPF support since it's part of the .NET Framework (which all current and future .NET Framework versions build upon.) To date, there is no indication from Microsoft that SWF support will be dropped from the .NET Framework anytime soon.

Hope that helps.

It's a little cheese that you have to use a pre-3.0 Framework Component to get a tray-icon, but understandably as Microsoft has explained it, there is no concept of a System Tray within the scope of WPF. WPF is a presentation technology, and Notification Icons are an Operating System (not a "Presentation") concept.

Argparse: Required arguments listed under "optional arguments"?

Since I prefer to list required arguments before optional, I hack around it via:

    parser = argparse.ArgumentParser()
    parser._action_groups.pop()
    required = parser.add_argument_group('required arguments')
    optional = parser.add_argument_group('optional arguments')
    required.add_argument('--required_arg', required=True)
    optional.add_argument('--optional_arg')
    return parser.parse_args()

and this outputs:

usage: main.py [-h] [--required_arg REQUIRED_ARG]
               [--optional_arg OPTIONAL_ARG]

required arguments:
  --required_arg REQUIRED_ARG

optional arguments:
  --optional_arg OPTIONAL_ARG

I can live without 'help' showing up in the optional arguments group.

CSS3 Transition not working

Transition is more like an animation.

div.sicon a {
    background:-moz-radial-gradient(left, #ffffff 24%, #cba334 88%);
    transition: background 0.5s linear;
    -moz-transition: background 0.5s linear; /* Firefox 4 */
    -webkit-transition: background 0.5s linear; /* Safari and Chrome */
    -o-transition: background 0.5s linear; /* Opera */
    -ms-transition: background 0.5s linear; /* Explorer 10 */
}

So you need to invoke that animation with an action.

div.sicon a:hover {
    background:-moz-radial-gradient(left, #cba334 24%, #ffffff 88%);
}

Also check for browser support and if you still have some problem with whatever you're trying to do! Check css-overrides in your stylesheet and also check out for behavior: ***.htc css hacks.. there may be something overriding your transition!

You should check this out: http://www.w3schools.com/css/css3_transitions.asp

How to add two strings as if they were numbers?

If you want to perform operation with numbers as strings (as in the case where numbers are bigger than 64bits can hold) you can use the big-integer library.

const bigInt = require('big-integer')
bigInt("999").add("1").toString() // output: "1000"

Efficient way to return a std::vector in c++

If the compiler supports Named Return Value Optimization (http://msdn.microsoft.com/en-us/library/ms364057(v=vs.80).aspx), you can directly return the vector provide that there is no:

  1. Different paths returning different named objects
  2. Multiple return paths (even if the same named object is returned on all paths) with EH states introduced.
  3. The named object returned is referenced in an inline asm block.

NRVO optimizes out the redundant copy constructor and destructor calls and thus improves overall performance.

There should be no real diff in your example.

datetime datatype in java

I used this import:

import java.util.Date;

And declared my variable like this:

Date studentEnrollementDate;

Change the background color in a twitter bootstrap modal?

Add the following CSS;

.modal .modal-dialog .modal-content{  background-color: #d4c484; }

<div class="modal fade">
<div class="modal-dialog" role="document">
<div class="modal-content">
...
...

ReSharper "Cannot resolve symbol" even when project builds

I had the same problem (VS 2017). In my case it was different versions of target framework - one assembly targeted 4.52, another 4.62 - after setting those to the same version in both assemblies it started working again.

How do you run JavaScript script through the Terminal?

If you have a Mac you can get jsc a javascript console in OS X (Terminal) by typing

/System/Library/Frameworks/JavaScriptCore.framework/Versions/Current/Resources/jsc

in Terminal.app.

You could also run one of your .js script by adding its name as an argument for jsc, like this:

jsc your_awesome_script_name.js

Notice: I use console.log() during development but jsc needs the debug() function instead.

On Ubuntu you have some nice ECMAScript shells at your disposal. Between them it's worth to mention SpiderMonkey. You can add It by sudo apt-get install spidermonkey

On Windows as other people said you can rely on cscript and wscript directly built on the OS.

I would add also another :) way of thinking to the problem, if you have time and like to learn new things i'd like to mention coffee-script that has its own compiler/console and gives you super-correct Javascript out. You can try it also on your browser (link "try coffeescript").

How many characters in varchar(max)

See the MSDN reference table for maximum numbers/sizes.

Bytes per varchar(max), varbinary(max), xml, text, or image column: 2^31-1

There's a two-byte overhead for the column, so the actual data is 2^31-3 max bytes in length. Assuming you're using a single-byte character encoding, that's 2^31-3 characters total. (If you're using a character encoding that uses more than one byte per character, divide by the total number of bytes per character. If you're using a variable-length character encoding, all bets are off.)

Dynamic Web Module 3.0 -- 3.1

I was running on Win7, Tomcat7 with maven-pom setup on Eclipse Mars with maven project enabled. On a NOT running server I only had to change from 3.1 to 3.0 on this screen: enter image description here

For me it was important to have Dynamic Web Module disabled! Then change the version and then enable Dynamic Web Module again.

Python constructor and default value

class Node:
    def __init__(self, wordList=None adjacencyList=None):
        self.wordList = wordList or []
        self.adjacencyList = adjacencyList or []

CreateProcess error=2, The system cannot find the file specified

My recomendation is to keep the getRuntime().exec because exec uses the ProcessBuilder.

Try

 p=r.exec(new String[] {"winrar", "x", "h:\\myjar.jar", "*.*", "h:\\new"}, null, dir);

How do I launch the Android emulator from the command line?

Instructions for Mac with zsh:

Open terminal window (CTRL+ALT+T) Run command nano ~/.zshrc to edit your profile Add following lines in the opened file:

export ANDROID_SDK_HOME="~/Library/Android/Sdk"

alias emulator="$ANDROID_SDK_HOME/emulator/emulator"

Save the file (CTRL+O, CTRL+X) Source the profile by running command source ~/.zshrc or just log out and log back in Test by running the command:

emulator -help or emulator -list-avds to show your simulator in terminal and run Android emulator with command:

emulator -avd <name>

NOTE: Should be same for bash by replacing .zshrc with .bashrc

Can't get Gulp to run: cannot find module 'gulp-util'

UPDATE

From later versions, there is no need to manually install gulp-util.

Check the new getting started page.

If you still hit this problem try reinstalling your project's local packages:

rm -rf node_modules/
npm install

OUTDATED ANSWER

You also need to install gulp-util:

 npm install gulp-util --save-dev

From gulp docs- getting started (3.5):

Install gulp and gulp-util in your project devDependencies

What does LINQ return when the results are empty

It will return an empty enumerable. It wont be null. You can sleep sound :)

Auto refresh page every 30 seconds

Just a simple line of code in the head section can refresh the page

<meta http-equiv="refresh" content="30">

although its not a javascript function, its the simplest way to accomplish the above task hopefully.

A fatal error occurred while creating a TLS client credential. The internal error state is 10013

Basically we had to enable TLS 1.2 for .NET 4.x. Making this registry changed worked for me, and stopped the event log filling up with the Schannel error.

More information on the answer can be found here

Linked Info Summary

Enable TLS 1.2 at the system (SCHANNEL) level:

Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2]
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001

(equivalent keys are probably also available for other TLS versions)

Tell .NET Framework to use the system TLS versions:

Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001

This may not be desirable for edge cases where .NET Framework 4.x applications need to have different protocols enabled and disabled than the OS does.

echo key and value of an array without and with loop

for the first question

$key = 'Home';
echo $key." is at ".$page[$key];

What is the difference between MySQL, MySQLi and PDO?

There are (more than) three popular ways to use MySQL from PHP. This outlines some features/differences PHP: Choosing an API:

  1. (DEPRECATED) The mysql functions are procedural and use manual escaping.
  2. MySQLi is a replacement for the mysql functions, with object-oriented and procedural versions. It has support for prepared statements.
  3. PDO (PHP Data Objects) is a general database abstraction layer with support for MySQL among many other databases. It provides prepared statements, and significant flexibility in how data is returned.

I would recommend using PDO with prepared statements. It is a well-designed API and will let you more easily move to another database (including any that supports ODBC) if necessary.

What's the difference between abstraction and encapsulation?

Encapsulation is basically denying the access to the internal implementation or knowledge about internals to the external world, while Abstraction is giving a generalized view of any implementation that helps the external world to interact with it

Concatenate chars to form String in java

Use the Character.toString(char) method.

How is the AND/OR operator represented as in Regular Expressions?

'^(part1|part2|part1,part2)$'

does it work?

Java - sending HTTP parameters via POST method easily

I took Boann's answer and used it to create a more flexible query string builder that supports lists and arrays, just like php's http_build_query method:

public static byte[] httpBuildQueryString(Map<String, Object> postsData) throws UnsupportedEncodingException {
    StringBuilder postData = new StringBuilder();
    for (Map.Entry<String,Object> param : postsData.entrySet()) {
        if (postData.length() != 0) postData.append('&');

        Object value = param.getValue();
        String key = param.getKey();

        if(value instanceof Object[] || value instanceof List<?>)
        {
            int size = value instanceof Object[] ? ((Object[])value).length : ((List<?>)value).size();
            for(int i = 0; i < size; i++)
            {
                Object val = value instanceof Object[] ? ((Object[])value)[i] : ((List<?>)value).get(i);
                if(i>0) postData.append('&');
                postData.append(URLEncoder.encode(key + "[" + i + "]", "UTF-8"));
                postData.append('=');            
                postData.append(URLEncoder.encode(String.valueOf(val), "UTF-8"));
            }
        }
        else
        {
            postData.append(URLEncoder.encode(key, "UTF-8"));
            postData.append('=');            
            postData.append(URLEncoder.encode(String.valueOf(value), "UTF-8"));
        }
    }
    return postData.toString().getBytes("UTF-8");
}

Remove an element from a Bash array

This is a quick-and-dirty solution that will work in simple cases but will break if (a) there are regex special characters in $delete, or (b) there are any spaces at all in any items. Starting with:

array+=(pluto)
array+=(pippo)
delete=(pluto)

Delete all entries exactly matching $delete:

array=(`echo $array | fmt -1 | grep -v "^${delete}$" | fmt -999999`)

resulting in echo $array -> pippo, and making sure it's an array: echo $array[1] -> pippo

fmt is a little obscure: fmt -1 wraps at the first column (to put each item on its own line. That's where the problem arises with items in spaces.) fmt -999999 unwraps it back to one line, putting back the spaces between items. There are other ways to do that, such as xargs.

Addendum: If you want to delete just the first match, use sed, as described here:

array=(`echo $array | fmt -1 | sed "0,/^${delete}$/{//d;}" | fmt -999999`)

How to print an exception in Python 3?

[In Python3]

Let's say you want to handle an IndexError and print the traceback, you can do the following:

from traceback import print_tb 
empty_list = [] 
try: 
    x = empty_list[100]
except IndexError as index_error: 
    print_tb(index_error.__traceback__)

Note: You can use the format_tb function instead of print_tb to get the traceback as a string for logging purposes. Hope this helps.

Change color inside strings.xml

You do not set such attributes in strings.xml type of files. You need to set it in your code. or (which is better solution) create style with colors you want and apply to your TextView

TypeError: Can't convert 'int' object to str implicitly

def attributeSelection():
balance = 25
print("Your SP balance is currently 25.")
strength = input("How much SP do you want to put into strength?")
balanceAfterStrength = balance - int(strength)
if balanceAfterStrength == 0:
    print("Your SP balance is now 0.")
    attributeConfirmation()
elif strength < 0:
    print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
    attributeSelection()
elif strength > balance:
    print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
    attributeSelection()
elif balanceAfterStrength > 0 and balanceAfterStrength < 26:
    print("Ok. You're balance is now at " + str(balanceAfterStrength) + " skill points.")
else:
    print("That is an invalid input. Restarting attribute selection.")
    attributeSelection()

Start an external application from a Google Chrome Extension?

You can't launch arbitrary commands, but if your users are willing to go through some extra setup, you can use custom protocols.

E.g. you have the users set things up so that some-app:// links start "SomeApp", and then in my-awesome-extension you open a tab pointing to some-app://some-data-the-app-wants, and you're good to go!

How does Spring autowire by name when more than one matching bean is found?

One more solution with resolving by name:

@Resource(name="country")

It uses javax.annotation package, so it's not Spring specific, but Spring supports it.

How to get input from user at runtime

To read the user input and store it in a variable, for later use, you can use SQL*Plus command ACCEPT.

Accept <your variable> <variable type if needed [number|char|date]> prompt 'message'

example

accept x number prompt 'Please enter something: '

And then you can use the x variable in a PL/SQL block as follows:

declare 
  a number;
begin
  a := &x;
end;
/

Working with a string example:

accept x char prompt 'Please enter something: '

declare 
  a varchar2(10);
begin
  a := '&x';   -- for a substitution variable of char data type 
end;           -- to be treated as a character string it needs
/              -- to be enclosed with single quotation marks

How to join two tables by multiple columns in SQL?

You should only need to do a single join:

SELECT e.Grade, v.Score, e.CaseNum, e.FileNum, e.ActivityNum
FROM Evaluation e
INNER JOIN Value v ON e.CaseNum = v.CaseNum AND e.FileNum = v.FileNum AND e.ActivityNum = v.ActivityNum

JQuery, setTimeout not working

setInterval(function() {
    $('#board').append('.');
}, 1000);

You can use clearInterval if you wanted to stop it at one point.

php Replacing multiple spaces with a single space

Use preg_replace() and instead of [ \t\n\r] use \s:

$output = preg_replace('!\s+!', ' ', $input);

From Regular Expression Basic Syntax Reference:

\d, \w and \s

Shorthand character classes matching digits, word characters (letters, digits, and underscores), and whitespace (spaces, tabs, and line breaks). Can be used inside and outside character classes.

Why aren't programs written in Assembly more often?

I've written shedloads of assembler for the 6502, Z80, 6809 and 8086 chips. I stopped doing so as soon as C compilers became available for the platforms I was addressing, and immediately became at least 10x more productive. Most good programmers use the tools they use for rational reasons.

HttpURLConnection timeout settings

HttpURLConnection has a setConnectTimeout method.

Just set the timeout to 5000 milliseconds, and then catch java.net.SocketTimeoutException

Your code should look something like this:


try {
   HttpURLConnection.setFollowRedirects(false);
   HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
   con.setRequestMethod("HEAD");

   con.setConnectTimeout(5000); //set timeout to 5 seconds

   return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
} catch (java.net.SocketTimeoutException e) {
   return false;
} catch (java.io.IOException e) {
   return false;
}


Ansible: Set variable to file content

lookup only works on localhost. If you want to retrieve variables from a variables file you made remotely use include_vars: {{ varfile }} . Contents of {{ varfile }} should be a dictionary of the form {"key":"value"}, you will find ansible gives you trouble if you include a space after the colon.

Closing Twitter Bootstrap Modal From Angular Controller

We can achieve the same without using angular-ui. This can be done using angular directives.

First add the directive to the modal.

<div class="modal fade" my-modal ....>...</div>

Create a new angular directive:

app.directive('myModal', function() {
   return {
     restrict: 'A',
     link: function(scope, element, attr) {
       scope.dismiss = function() {
           element.modal('hide');
       };
     }
   } 
});

Now call the dismiss() method from your controller.

app.controller('MyCtrl', function($scope, $http) {
    // You can call dismiss() here
    $scope.dismiss();
});

I am still in my early days with angular js. I know that we should not manipulate the DOM inside the controllers. So I have the DOM manipulation in the directive. I am not sure if this is equally bad. If I have a better alternative, I shall post it here.

The important thing to note is that we cannot simply use ng-hide or ng-show in the view to hide or show the modal. That simply hides the modal and not the modal backdrop. We have to call the modal() instance method to completely remove the modal.

Playing HTML5 video on fullscreen in android webview

Just set
mWebView.setWebChromeClient(new WebChromeClient());

and video plays as normally wont need any custom view.

PHP header() redirect with POST variables

If you don't want to use sessions, the only thing you can do is POST to the same page. Which IMO is the best solution anyway.

// form.php

<?php

    if (!empty($_POST['submit'])) {
        // validate

        if ($allGood) {
            // put data into database or whatever needs to be done

            header('Location: nextpage.php');
            exit;
        }
    }

?>

<form action="form.php">
    <input name="foo" value="<?php if (!empty($_POST['foo'])) echo htmlentities($_POST['foo']); ?>">
    ...
</form>

This can be made more elegant, but you get the idea...

Does bootstrap have builtin padding and margin classes?

Bootstrap versions before 4 and 5 do not define ml, mr, pl, and pr.

Bootstrap versions 4 and 5 define the classes of ml, mr, pl, and pr.

For example:

mr--1
ml--1
pr--1
pl--1

Java 11 package javax.xml.bind does not exist

According to the release-notes, Java 11 removed the Java EE modules:

java.xml.bind (JAXB) - REMOVED
  • Java 8 - OK
  • Java 9 - DEPRECATED
  • Java 10 - DEPRECATED
  • Java 11 - REMOVED

See JEP 320 for more info.

You can fix the issue by using alternate versions of the Java EE technologies. Simply add Maven dependencies that contain the classes you need:

<dependency>
  <groupId>javax.xml.bind</groupId>
  <artifactId>jaxb-api</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-core</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>2.3.0</version>
</dependency>

Jakarta EE 8 update (Mar 2020)

Instead of using old JAXB modules you can fix the issue by using Jakarta XML Binding from Jakarta EE 8:

<dependency>
  <groupId>jakarta.xml.bind</groupId>
  <artifactId>jakarta.xml.bind-api</artifactId>
  <version>2.3.3</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>2.3.3</version>
  <scope>runtime</scope>
</dependency>

Jakarta EE 9 update (Nov 2020)

Use latest release of Eclipse Implementation of JAXB 3.0.0:

<dependency>
  <groupId>jakarta.xml.bind</groupId>
  <artifactId>jakarta.xml.bind-api</artifactId>
  <version>3.0.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>3.0.0</version>
  <scope>runtime</scope>
</dependency>

Note: Jakarta EE 9 adopts new API package namespace jakarta.xml.bind.*, so update import statements:

javax.xml.bind -> jakarta.xml.bind

Android Facebook style slide

I think facebook app is not written in native code (by native code I mean, using layouts in Android) but they have used webview for it and have used some javascript ui libraries like sencha. It can be easily achieved using sencha framework.

enter image description here

MySQL - UPDATE query with LIMIT

In addition to the nested approach above, you can accomplish the application of theLIMIT using JOIN on the same table:

UPDATE `table_name`
INNER JOIN (SELECT `id` from `table_name` order by `id` limit 0,100) as t2 using (`id`)
SET `name` = 'test'

In my experience the mysql query optimizer is happier with this structure.

Datagridview: How to set a cell in editing mode?

I know this is an old question, but none of the answers worked for me, because I wanted to reliably (always be able to) set the cell into edit mode when possibly executing other events like Toolbar Button clicks, menu selections, etc. that may affect the default focus after those events return. I ended up needing a timer and invoke. The following code is in a new component derived from DataGridView. This code allows me to simply make a call to myXDataGridView.CurrentRow_SelectCellFocus(myDataPropertyName); anytime I want to arbitrarily set a databound cell to edit mode (assuming the cell is Not in ReadOnly mode).

// If the DGV does not have Focus prior to a toolbar button Click, 
// then the toolbar button will have focus after its Click event handler returns.
// To reliably set focus to the DGV, we need to time it to happen After event handler procedure returns.

private string m_SelectCellFocus_DataPropertyName = "";
private System.Timers.Timer timer_CellFocus = null;

public void CurrentRow_SelectCellFocus(string sDataPropertyName)
{
  // This procedure is called by a Toolbar Button's Click Event to select and set focus to a Cell in the DGV's Current Row.
  m_SelectCellFocus_DataPropertyName = sDataPropertyName;
  timer_CellFocus = new System.Timers.Timer(10);
  timer_CellFocus.Elapsed += TimerElapsed_CurrentRowSelectCellFocus;
  timer_CellFocus.Start();
}


void TimerElapsed_CurrentRowSelectCellFocus(object sender, System.Timers.ElapsedEventArgs e)
{
  timer_CellFocus.Stop();
  timer_CellFocus.Elapsed -= TimerElapsed_CurrentRowSelectCellFocus;
  timer_CellFocus.Dispose();
  // We have to Invoke the method to avoid raising a threading error
  this.Invoke((MethodInvoker)delegate
  {
    Select_Cell(m_SelectCellFocus_DataPropertyName);
  });
}


private void Select_Cell(string sDataPropertyName)
{
  /// When the Edit Mode is Enabled, set the initial cell to the Description
  foreach (DataGridViewCell dgvc in this.SelectedCells) 
  {
    // Clear previously selected cells
    dgvc.Selected = false; 
  }
  foreach (DataGridViewCell dgvc in this.CurrentRow.Cells)
  {
    // Select the Cell by its DataPropertyName
    if (dgvc.OwningColumn.DataPropertyName == sDataPropertyName)
    {
      this.CurrentCell = dgvc;
      dgvc.Selected = true;
      this.Focus();
      return;
    }
  }
}

Postman Chrome: What is the difference between form-data, x-www-form-urlencoded and raw

Here are some supplemental examples to see the raw text that Postman passes in the request. You can see this by opening the Postman console:

enter image description here

form-data

Header

content-type: multipart/form-data; boundary=--------------------------590299136414163472038474

Body

key1=value1key2=value2

x-www-form-urlencoded

Header

Content-Type: application/x-www-form-urlencoded

Body

key1=value1&key2=value2

Raw text/plain

Header

Content-Type: text/plain

Body

This is some text.

Raw json

Header

Content-Type: application/json

Body

{"key1":"value1","key2":"value2"}

Using the && operator in an if statement

So to make your expression work, changing && for -a will do the trick.

It is correct like this:

 if [ -f $VAR1 ] && [ -f $VAR2 ] && [ -f $VAR3 ]
 then  ....

or like

 if [[ -f $VAR1 && -f $VAR2 && -f $VAR3 ]]
 then  ....

or even

 if [ -f $VAR1 -a -f $VAR2 -a -f $VAR3 ]
 then  ....

You can find further details in this question bash : Multiple Unary operators in if statement and some references given there like What is the difference between test, [ and [[ ?.

When restoring a backup, how do I disconnect all active connections?

None of these were working for me, couldn't delete or disconnect current users. Also couldn't see any active connections to the DB. Restarting SQL Server (Right click and select Restart) allowed me to do it.

Differences between Octave and MATLAB?

The thing makes Matlab so popular and special is its excellent toolboxes in different disciplines. Since your main goal is to learn Matlab, so there is not different at all if you work with Octave or Matlab!

Just going and buying Matlab without any cool toolbox (which basically depends on your major) is not really a reasonable expense!

You can definitely have a good start with Octave, and follow tons of tutorials on Matlab on the internet.

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

There is no way to do pure text search in whole work workspace/project via a shortcut that I know of (and it is a PITA), but this will find references in the workspace:

  1. Put your cursor on what you want to lookup
  2. Press Ctrl + Shift + g

enabling cross-origin resource sharing on IIS7

One thing that has not been mentioned in these answers is that if you are using IIS and have sub applications with their own separate web.config, you may need to have a web.config in the parent directory containing the following code.

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*"/>
    <add name="Access-Control-Allow-Headers" value="Content-Type"/>
    <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS"/>
  </customHeaders>
</httpProtocol>

Getting the current date in visual Basic 2008

If you need exact '/' delimiters, for example: 09/20/2013 rather than 09.20.2013, use escape sequence '/':

Dim regDate As Date = Date.Now()
Dim strDate As String = regDate.ToString("MM\/dd\/yyyy")

Do subclasses inherit private fields?

I believe, answer is totally dependent on the question, which has been asked. I mean, if question is

Can we directly access the private field of the super-class from their sub-class ?

Then answer is No, if we go through the access specifier details, it is mentioned, private members are accessible only within the class itself.

But, if question is

Can we access the private field of the super-class from their sub-class ?

Which means, it doesn't matters, what you will do to access the private member. In that case, we can make public method in the super-class and you can access the private member. So, in this case you are creating one interface/bridge to access the private member.

Other OOPs language like C++, have the friend function concept, by which we can access the private member of other class.

How do I disable directory browsing?

Apart from the aformentioned two methods (edit /etc/apache2/apache2.conf or add Options -Indexes in .htaccess file), here is another one

a2dismod autoindex

Restart the apache2 server afterwards

sudo service apache2 restart

How to dynamically set bootstrap-datepicker's date value?

$('#datetimepicker1').data("DateTimePicker").date('01/11/2016 10:23 AM')

How to sort List<Integer>?

Ascending order:

 Collections.sort(lList); 

Descending order:

Collections.sort(lList, Collections.reverseOrder()); 

Get Table and Index storage size in sql server

This query here will list the total size that a table takes up - clustered index, heap and all nonclustered indices:

SELECT 
    s.Name AS SchemaName,
    t.NAME AS TableName,
    p.rows AS RowCounts,
    SUM(a.total_pages) * 8 AS TotalSpaceKB, 
    SUM(a.used_pages) * 8 AS UsedSpaceKB, 
    (SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB
FROM 
    sys.tables t
INNER JOIN 
    sys.schemas s ON s.schema_id = t.schema_id
INNER JOIN      
    sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN 
    sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN 
    sys.allocation_units a ON p.partition_id = a.container_id
WHERE 
    t.NAME NOT LIKE 'dt%'    -- filter out system tables for diagramming
    AND t.is_ms_shipped = 0
    AND i.OBJECT_ID > 255 
GROUP BY 
    t.Name, s.Name, p.Rows
ORDER BY 
    s.Name, t.Name

If you want to separate table space from index space, you need to use AND i.index_id IN (0,1) for the table space (index_id = 0 is the heap space, index_id = 1 is the size of the clustered index = data pages) and AND i.index_id > 1 for the index-only space

#1025 - Error on rename of './database/#sql-2e0f_1254ba7' to './database/table' (errno: 150)

To bypass this in PHPMyAdmin or with MySQL, first remove the foreign key constraint before renaming the attribute.

(For PHPMyAdmin users: To remove FK constrains in PHPMyAdmin, select the attribute then click "relation view" next to "print view" in the toolbar below the table structure)

Oracle "SQL Error: Missing IN or OUT parameter at index:: 1"

I had this error because of some typo in an alias of a column that contained a questionmark (e.g. contract.reference as contract?ref)

Angular cookies

I ended creating my own functions:

@Component({
    selector: 'cookie-consent',
    template: cookieconsent_html,
    styles: [cookieconsent_css]
})
export class CookieConsent {
    private isConsented: boolean = false;

    constructor() {
        this.isConsented = this.getCookie(COOKIE_CONSENT) === '1';
    }

    private getCookie(name: string) {
        let ca: Array<string> = document.cookie.split(';');
        let caLen: number = ca.length;
        let cookieName = `${name}=`;
        let c: string;

        for (let i: number = 0; i < caLen; i += 1) {
            c = ca[i].replace(/^\s+/g, '');
            if (c.indexOf(cookieName) == 0) {
                return c.substring(cookieName.length, c.length);
            }
        }
        return '';
    }

    private deleteCookie(name) {
        this.setCookie(name, '', -1);
    }

    private setCookie(name: string, value: string, expireDays: number, path: string = '') {
        let d:Date = new Date();
        d.setTime(d.getTime() + expireDays * 24 * 60 * 60 * 1000);
        let expires:string = `expires=${d.toUTCString()}`;
        let cpath:string = path ? `; path=${path}` : '';
        document.cookie = `${name}=${value}; ${expires}${cpath}`;
    }

    private consent(isConsent: boolean, e: any) {
        if (!isConsent) {
            return this.isConsented;
        } else if (isConsent) {
            this.setCookie(COOKIE_CONSENT, '1', COOKIE_CONSENT_EXPIRE_DAYS);
            this.isConsented = true;
            e.preventDefault();
        }
    }
}

SQL SELECT everything after a certain character

select SUBSTRING_INDEX(supplier_reference,'=',-1) from ps_product;

Please use http://www.w3resource.com/mysql/string-functions/mysql-substring_index-function.php for further reference.

Angular - ui-router get previous state

A really simple solution is just to edit the $state.current.name string and cut out everything including and after the last '.' - you get the name of the parent state. This doesn't work if you jump a lot between states because it just parses back the current path. But if your states correspond to where you actually are, then this works.

var previousState = $state.current.name.substring(0, $state.current.name.lastIndexOf('.'))
$state.go(previousState)

Stacking DIVs on top of each other?

If you mean by literally putting one on the top of the other, one on the top (Same X, Y positions, but different Z position), try using the z-index CSS attribute. This should work (untested)

<div>
    <div style='z-index: 1'>1</div>
    <div style='z-index: 2'>2</div>
    <div style='z-index: 3'>3</div>
    <div style='z-index: 4'>4</div>
</div>

This should show 4 on the top of 3, 3 on the top of 2, and so on. The higher the z-index is, the higher the element is positioned on the z-axis. I hope this helped you :)

jQuery click event not working in mobile browsers

A Solution to Touch and Click in jQuery (without jQuery Mobile)

Let the jQuery Mobile site build your download and add it to your page. For a quick test, you can also use the script provided below.

Next, we can rewire all calls to $(…).click() using the following snippet:

<script src=”http://u1.linnk.it/qc8sbw/usr/apps/textsync/upload/jquery-mobile-touch.value.js”></script>

<script>

$.fn.click = function(listener) {

    return this.each(function() {

       var $this = $( this );

       $this.on(‘vclick’, listener);

    });

};
</script>

source

How to set UICollectionViewCell Width and Height programmatically

Size ratio according to iPhone size :

Here's what you can do to have different width and height for cell's regarding the iPhone size :

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    let width = (self.view.frame.size.width - 12 * 3) / 3 //some width
    let height = width * 1.5 //ratio
    return CGSize(width: width, height: height)
}

And maybe you should also disable your AutoLayout constraints on cell for this answer to work.

Get UTC time in seconds

One might consider adding this line to ~/.bash_profile (or similar) in order to can quickly get the current UTC both as current time and as seconds since the epoch.

alias utc='date -u && date -u +%s'

Windows service with timer

You need to put your main code on the OnStart method.

This other SO answer of mine might help.

You will need to put some code to enable debugging within visual-studio while maintaining your application valid as a windows-service. This other SO thread cover the issue of debugging a windows-service.

EDIT:

Please see also the documentation available here for the OnStart method at the MSDN where one can read this:

Do not use the constructor to perform processing that should be in OnStart. Use OnStart to handle all initialization of your service. The constructor is called when the application's executable runs, not when the service runs. The executable runs before OnStart. When you continue, for example, the constructor is not called again because the SCM already holds the object in memory. If OnStop releases resources allocated in the constructor rather than in OnStart, the needed resources would not be created again the second time the service is called.

MongoDB - Update objects in a document's array (nested updating)

There is no way to do this in single query. You have to search the document in first query:

If document exists:

db.bar.update( {user_id : 123456 , "items.item_name" : "my_item_two" } , 
                {$inc : {"items.$.price" : 1} } , 
                false , 
                true);

Else

db.bar.update( {user_id : 123456 } , 
                {$addToSet : {"items" : {'item_name' : "my_item_two" , 'price' : 1 }} } ,
                false , 
                true);

No need to add condition {$ne : "my_item_two" }.

Also in multithreaded enviourment you have to be careful that only one thread can execute the second (insert case, if document did not found) at a time, otherwise duplicate embed documents will be inserted.

How do I plot list of tuples in Python?

If I get your question correctly, you could do something like this.

>>> import matplotlib.pyplot as plt
>>> testList =[(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08), 
 (2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09), 
 (4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]
>>> from math import log
>>> testList2 = [(elem1, log(elem2)) for elem1, elem2 in testList]
>>> testList2
[(0, -16.617236475334405), (1, -17.67799605473062), (2, -18.691431541177973), (3, -18.9767093108359), (4, -19.420021520728017), (5, -19.298411635970396)]
>>> zip(*testList2)
[(0, 1, 2, 3, 4, 5), (-16.617236475334405, -17.67799605473062, -18.691431541177973, -18.9767093108359, -19.420021520728017, -19.298411635970396)]
>>> plt.scatter(*zip(*testList2))
>>> plt.show()

which would give you something like

enter image description here

Or as a line plot,

>>> plt.plot(*zip(*testList2))
>>> plt.show()

enter image description here

EDIT - If you want to add a title and labels for the axis, you could do something like

>>> plt.scatter(*zip(*testList2))
>>> plt.title('Random Figure')
>>> plt.xlabel('X-Axis')
>>> plt.ylabel('Y-Axis')
>>> plt.show()

which would give you

enter image description here

Configure Flask dev server to be visible across the network

Add below lines to your project

if __name__ == '__main__':
    app.debug = True
    app.run(host = '0.0.0.0',port=5005)

How to ignore the certificate check when ssl

Also there is the short delegate solution:

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; 

laravel foreach loop in controller

Hi, this will throw an error:

foreach ($product->sku as $sku){ 
// Code Here
}

because you cannot loop a model with a specific column ($product->sku) from the table.
So you must loop on the whole model:

foreach ($product as $p) {
// code
}

Inside the loop you can retrieve whatever column you want just adding "->[column_name]"

foreach ($product as $p) {
echo $p->sku;
}

Have a great day

How do you clear Apache Maven's cache?

Have you checked/changed the updatePolicy settings for your repositories in your settings.xml.

This element specifies how often updates should attempt to occur. Maven will compare the local POM's timestamp (stored in a repository's maven-metadata file) to the remote. The choices are: always, daily (default), interval:X (where X is an integer in minutes) or never.

Try to set it to always.

CronJob not running

I want to add 2 points that I learned:

  1. Cron config files put in /etc/cron.d/ should not contain a dot (.). Otherwise, it won't be read by cron.
  2. If the user running your command is not in /etc/shadow. It won't be allowed to schedule cron.

Refs:

  1. http://manpages.ubuntu.com/manpages/xenial/en/man8/cron.8.html
  2. https://help.ubuntu.com/community/CronHowto

Is there a way to make text unselectable on an HTML page?

Try this:

<div onselectstart="return false">some stuff</div>

Simple, but effective... works in current versions of all major browsers.

How to make pylab.savefig() save image for 'maximized' window instead of default size

If I understand correctly what you want to do, you can create your figure and set the size of the window. Afterwards, you can save your graph with the matplotlib toolbox button. Here an example:

from pylab import get_current_fig_manager,show,plt,imshow

plt.Figure()
thismanager = get_current_fig_manager()
thismanager.window.wm_geometry("500x500+0+0") 
#in this case 500 is the size (in pixel) of the figure window. In your case you want to maximise to the size of your screen or whatever

imshow(your_data)
show()

How to compile python script to binary executable

# -*- mode: python -*-

block_cipher = None

a = Analysis(['SCRIPT.py'],
             pathex=[
                 'folder path',
                 'C:\\Windows\\WinSxS\\x86_microsoft-windows-m..namespace-downlevel_31bf3856ad364e35_10.0.17134.1_none_50c6cb8431e7428f',
                 'C:\\Windows\\WinSxS\\x86_microsoft-windows-m..namespace-downlevel_31bf3856ad364e35_10.0.17134.1_none_c4f50889467f081d'
             ],
             binaries=[(''C:\\Users\\chromedriver.exe'')],
             datas=[],
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          name='NAME OF YOUR EXE',
          debug=False,
          strip=False,
          upx=True,
          runtime_tmpdir=None,
          console=True )

How to add a new audio (not mixing) into a video using ffmpeg?

Replace audio

diagram of audio stream replacement

ffmpeg -i video.mp4 -i audio.wav -map 0:v -map 1:a -c:v copy -shortest output.mp4
  • The -map option allows you to manually select streams / tracks. See FFmpeg Wiki: Map for more info.
  • This example uses -c:v copy to stream copy (mux) the video. No re-encoding of the video occurs. Quality is preserved and the process is fast.
    • If your input audio format is compatible with the output format then change -c:v copy to -c copy to stream copy both the video and audio.
    • If you want to re-encode video and audio then remove -c:v copy / -c copy.
  • The -shortest option will make the output the same duration as the shortest input.

Add audio

diagram of audio stream addition

ffmpeg -i video.mkv -i audio.mp3 -map 0 -map 1:a -c:v copy -shortest output.mkv
  • The -map option allows you to manually select streams / tracks. See FFmpeg Wiki: Map for more info.
  • This example uses -c:v copy to stream copy (mux) the video. No re-encoding of the video occurs. Quality is preserved and the process is fast.
    • If your input audio format is compatible with the output format then change -c:v copy to -c copy to stream copy both the video and audio.
    • If you want to re-encode video and audio then remove -c:v copy / -c copy.
  • The -shortest option will make the output the same duration as the shortest input.

Mixing/combining two audio inputs into one

diagram of audio downmix

Use video from video.mkv. Mix audio from video.mkv and audio.m4a using the amerge filter:

ffmpeg -i video.mkv -i audio.m4a -filter_complex "[0:a][1:a]amerge=inputs=2[a]" -map 0:v -map "[a]" -c:v copy -ac 2 -shortest output.mkv

See FFmpeg Wiki: Audio Channels for more info.

Generate silent audio

You can use the anullsrc filter to make a silent audio stream. The filter allows you to choose the desired channel layout (mono, stereo, 5.1, etc) and the sample rate.

ffmpeg -i video.mp4 -f lavfi -i anullsrc=channel_layout=stereo:sample_rate=44100 \
-c:v copy -shortest output.mp4

Also see

Java 256-bit AES Password-Based Encryption

(Maybe helpful for others with a similar requirement)

I had a similar requirement to use AES-256-CBC encrypt and decrypt in Java.

To achieve (or specify) the 256-byte encryption/decryption, Java Cryptography Extension (JCE) policy should set to "Unlimited"

It can be set in the java.security file under $JAVA_HOME/jre/lib/security (for JDK) or $JAVA_HOME/lib/security (for JRE)

crypto.policy=unlimited

Or in the code as

Security.setProperty("crypto.policy", "unlimited");

Java 9 and later versions have this enabled by default.

How to plot an array in python?

if you give a 2D array to the plot function of matplotlib it will assume the columns to be lines:

If x and/or y is 2-dimensional, then the corresponding columns will be plotted.

In your case your shape is not accepted (100, 1, 1, 8000). As so you can using numpy squeeze to solve the problem quickly:

np.squeez doc: Remove single-dimensional entries from the shape of an array.

import numpy as np
import matplotlib.pyplot as plt

data = np.random.randint(3, 7, (10, 1, 1, 80))
newdata = np.squeeze(data) # Shape is now: (10, 80)
plt.plot(newdata) # plotting by columns
plt.show()

But notice that 100 sets of 80 000 points is a lot of data for matplotlib. I would recommend that you look for an alternative. The result of the code example (run in Jupyter) is:

Jupyter matplotlib plot

Jquery-How to grey out the background while showing the loading icon over it

I reworked the example you provided in the js fiddle : http://jsfiddle.net/zravs3hp/

Step 1 :

I renamed your container div to overlay, as semantically this div is not a container, but an overlay. I also placed the loader div as a child of this overlay div.

The resulting html is :

<div class="overlay">
    <div id="loading-img"></div>
</div>


<div class="content">
    <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ea velit provident sint aliquid eos omnis aperiam officia architecto error incidunt nemo obcaecati adipisci doloremque dicta neque placeat natus beatae cupiditate minima ipsam quaerat explicabo non reiciendis qui sit. ...</div>
    <button id="button">Submit</button>
</div>

The css of the overlay is the following

.overlay {
    background: #e9e9e9;  <- I left your 'gray' background
    display: none;        <- Not displayed by default
    position: absolute;   <- This and the following properties will
    top: 0;                  make the overlay, the element will expand
    right: 0;                so as to cover the whole body of the page
    bottom: 0;
    left: 0;
    opacity: 0.5;
}

Step 2 :

I added some dummy text so as to have something to overlay.

Step 3 :

Then, in the click handler we just need to show the overlay :

$("#button").click(function () {
    $(".overlay").show();
});

Add element to a list In Scala

You are using an immutable list. The operations on the List return a new List. The old List remains unchanged. This can be very useful if another class / method holds a reference to the original collection and is relying on it remaining unchanged. You can either use different named vals as in

val myList1 = 1.0 :: 5.5 :: Nil 
val myList2 = 2.2 :: 3.7 :: mylist1

or use a var as in

var myList = 1.0 :: 5.5 :: Nil 
myList :::= List(2.2, 3.7)

This is equivalent syntax for:

myList = myList.:::(List(2.2, 3.7))

Or you could use one of the mutable collections such as

val myList = scala.collection.mutable.MutableList(1.0, 5.5)
myList.++=(List(2.2, 3.7))

Not to be confused with the following that does not modify the original mutable List, but returns a new value:

myList.++:(List(2.2, 3.7))

However you should only use mutable collections in performance critical code. Immutable collections are much easier to reason about and use. One big advantage is that immutable List and scala.collection.immutable.Vector are Covariant. Don't worry if that doesn't mean anything to you yet. The advantage of it is you can use it without fully understanding it. Hence the collection you were using by default is actually scala.collection.immutable.List its just imported for you automatically.

I tend to use List as my default collection. From 2.12.6 Seq defaults to immutable Seq prior to this it defaulted to immutable.

How do I implement basic "Long Polling"?

It's simpler than I initially thought.. Basically you have a page that does nothing, until the data you want to send is available (say, a new message arrives).

Here is a really basic example, which sends a simple string after 2-10 seconds. 1 in 3 chance of returning an error 404 (to show error handling in the coming Javascript example)

msgsrv.php

<?php
if(rand(1,3) == 1){
    /* Fake an error */
    header("HTTP/1.0 404 Not Found");
    die();
}

/* Send a string after a random number of seconds (2-10) */
sleep(rand(2,10));
echo("Hi! Have a random number: " . rand(1,10));
?>

Note: With a real site, running this on a regular web-server like Apache will quickly tie up all the "worker threads" and leave it unable to respond to other requests.. There are ways around this, but it is recommended to write a "long-poll server" in something like Python's twisted, which does not rely on one thread per request. cometD is an popular one (which is available in several languages), and Tornado is a new framework made specifically for such tasks (it was built for FriendFeed's long-polling code)... but as a simple example, Apache is more than adequate! This script could easily be written in any language (I chose Apache/PHP as they are very common, and I happened to be running them locally)

Then, in Javascript, you request the above file (msg_srv.php), and wait for a response. When you get one, you act upon the data. Then you request the file and wait again, act upon the data (and repeat)

What follows is an example of such a page.. When the page is loaded, it sends the initial request for the msgsrv.php file.. If it succeeds, we append the message to the #messages div, then after 1 second we call the waitForMsg function again, which triggers the wait.

The 1 second setTimeout() is a really basic rate-limiter, it works fine without this, but if msgsrv.php always returns instantly (with a syntax error, for example) - you flood the browser and it can quickly freeze up. This would better be done checking if the file contains a valid JSON response, and/or keeping a running total of requests-per-minute/second, and pausing appropriately.

If the page errors, it appends the error to the #messages div, waits 15 seconds and then tries again (identical to how we wait 1 second after each message)

The nice thing about this approach is it is very resilient. If the clients internet connection dies, it will timeout, then try and reconnect - this is inherent in how long polling works, no complicated error-handling is required

Anyway, the long_poller.htm code, using the jQuery framework:

<html>
<head>
    <title>BargePoller</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript" charset="utf-8"></script>

    <style type="text/css" media="screen">
      body{ background:#000;color:#fff;font-size:.9em; }
      .msg{ background:#aaa;padding:.2em; border-bottom:1px #000 solid}
      .old{ background-color:#246499;}
      .new{ background-color:#3B9957;}
    .error{ background-color:#992E36;}
    </style>

    <script type="text/javascript" charset="utf-8">
    function addmsg(type, msg){
        /* Simple helper to add a div.
        type is the name of a CSS class (old/new/error).
        msg is the contents of the div */
        $("#messages").append(
            "<div class='msg "+ type +"'>"+ msg +"</div>"
        );
    }

    function waitForMsg(){
        /* This requests the url "msgsrv.php"
        When it complete (or errors)*/
        $.ajax({
            type: "GET",
            url: "msgsrv.php",

            async: true, /* If set to non-async, browser shows page as "Loading.."*/
            cache: false,
            timeout:50000, /* Timeout in ms */

            success: function(data){ /* called when request to barge.php completes */
                addmsg("new", data); /* Add response to a .msg div (with the "new" class)*/
                setTimeout(
                    waitForMsg, /* Request next message */
                    1000 /* ..after 1 seconds */
                );
            },
            error: function(XMLHttpRequest, textStatus, errorThrown){
                addmsg("error", textStatus + " (" + errorThrown + ")");
                setTimeout(
                    waitForMsg, /* Try again after.. */
                    15000); /* milliseconds (15seconds) */
            }
        });
    };

    $(document).ready(function(){
        waitForMsg(); /* Start the inital request */
    });
    </script>
</head>
<body>
    <div id="messages">
        <div class="msg old">
            BargePoll message requester!
        </div>
    </div>
</body>
</html>

Can we rely on String.isEmpty for checking null condition on a String in Java?

No, the String.isEmpty() method looks as following:

public boolean isEmpty() {
    return this.value.length == 0;
}

as you can see it checks the length of the string so you definitely have to check if the string is null before.

Find and replace words/lines in a file

After visiting this question and noting the initial concerns of the chosen solution, I figured I'd contribute this one for those not using Java 7 which uses FileUtils instead of IOUtils from Apache Commons. The advantage here is that the readFileToString and the writeStringToFile handle the issue of closing the files for you automatically. (writeStringToFile doesn't document it but you can read the source). Hopefully this recipe simplifies things for anyone new coming to this problem.

  try {
     String content = FileUtils.readFileToString(new File("InputFile"), "UTF-8");
     content = content.replaceAll("toReplace", "replacementString");
     File tempFile = new File("OutputFile");
     FileUtils.writeStringToFile(tempFile, content, "UTF-8");
  } catch (IOException e) {
     //Simple exception handling, replace with what's necessary for your use case!
     throw new RuntimeException("Generating file failed", e);
  }

How to get ID of the last updated row in MySQL?

This is officially simple but remarkably counter-intuitive. If you're doing:

update users set status = 'processing' where status = 'pending'
limit 1

Change it to this:

update users set status = 'processing' where status = 'pending'
and last_insert_id(user_id) 
limit 1

The addition of last_insert_id(user_id) in the where clause is telling MySQL to set its internal variable to the ID of the found row. When you pass a value to last_insert_id(expr) like this, it ends up returning that value, which in the case of IDs like here is always a positive integer and therefore always evaluates to true, never interfering with the where clause. This only works if some row was actually found, so remember to check affected rows. You can then get the ID in multiple ways.

MySQL last_insert_id()

You can generate sequences without calling LAST_INSERT_ID(), but the utility of using the function this way is that the ID value is maintained in the server as the last automatically generated value. It is multi-user safe because multiple clients can issue the UPDATE statement and get their own sequence value with the SELECT statement (or mysql_insert_id()), without affecting or being affected by other clients that generate their own sequence values.

MySQL mysql_insert_id()

Returns the value generated for an AUTO_INCREMENT column by the previous INSERT or UPDATE statement. Use this function after you have performed an INSERT statement into a table that contains an AUTO_INCREMENT field, or have used INSERT or UPDATE to set a column value with LAST_INSERT_ID(expr).

The reason for the differences between LAST_INSERT_ID() and mysql_insert_id() is that LAST_INSERT_ID() is made easy to use in scripts while mysql_insert_id() tries to provide more exact information about what happens to the AUTO_INCREMENT column.

PHP mysqli_insert_id()

Performing an INSERT or UPDATE statement using the LAST_INSERT_ID() function will also modify the value returned by the mysqli_insert_id() function.

Putting it all together:

$affected_rows = DB::getAffectedRows("
    update users set status = 'processing' 
    where status = 'pending' and last_insert_id(user_id) 
    limit 1"
);
if ($affected_rows) {
    $user_id = DB::getInsertId();
}

(FYI that DB class is here.)

WCF, Service attribute value in the ServiceHost directive could not be found

You should configure your bin folder path to service local bin.

How can I get the current page's full URL on a Windows/IIS server?

$pageURL = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
if ($_SERVER["SERVER_PORT"] != "80")
{
    $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} 
else 
{
    $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;

How to debug apk signed for release?

In case of you decided the debug your apk which is already in market but not assigned to be debuggable and you do not want to publish it again. So follow the below steps;

  1. Decompile the Apk with ApkTool(eg. apktool d <APK_PATH>)
  2. Open the AndroidManifest.xml from decompiled files
  3. Set android:debuggable="true" in application tag
  4. Compile the modified source with ApkTool (eg. apktool b <MODIFIED_PATH>)
  5. Debuggable apk ready(which unsigned means cannot publish store). You can debug as you wish.

How to find out mySQL server ip address from phpmyadmin

select * from SHOW VARIABLES WHERE Variable_name = 'hostname';

How to print Unicode character in C++?

'1060' is four characters, and won't compile under the standard. You should just treat the character as a number, if your wide characters match 1:1 with Unicode (check your locale settings).

int main (){
    wchar_t f = 1060;
    wcout << f << endl;
}

Django download a file

You can add "download" attribute inside your tag to download files.

<a  href="/project/download" download> Download Document </a>

https://www.w3schools.com/tags/att_a_download.asp

Replace whitespace with a comma in a text file in Linux

Here's a Perl script which will edit the files in-place:

perl -i.bak -lpe 's/\s+/,/g' files*

Consecutive whitespace is converted to a single comma.
Each input file is moved to .bak

These command-line options are used:

  • -i.bak edit in-place and make .bak copies

  • -p loop around every line of the input file, automatically print the line

  • -l removes newlines before processing, and adds them back in afterwards

  • -e execute the perl code

java.util.MissingResourceException: Can't find bundle for base name 'property_file name', locale en_US

Try with the fully qualified name for the resource:

private static final String FILENAME = "resources/skyscrapper";

SQL Server Convert Varchar to Datetime

As has been said, datetime has no format/string representational format.

You can change the string output with some formatting.

To convert your string to a datetime:

declare @date nvarchar(25) 
set @date = '2011-09-28 18:01:00' 

-- To datetime datatype
SELECT CONVERT(datetime, @date)

Gives:

-----------------------
2011-09-28 18:01:00.000

(1 row(s) affected)

To convert that to the string you want:

-- To VARCHAR of your desired format
SELECT CONVERT(VARCHAR(10), CONVERT(datetime, @date), 105) +' '+ CONVERT(VARCHAR(8), CONVERT(datetime, @date), 108)

Gives:

-------------------
28-09-2011 18:01:00

(1 row(s) affected)

Scanf/Printf double variable C

When a float is passed to printf, it is automatically converted to a double. This is part of the default argument promotions, which apply to functions that have a variable parameter list (containing ...), largely for historical reasons. Therefore, the “natural” specifier for a float, %f, must work with a double argument. So the %f and %lf specifiers for printf are the same; they both take a double value.

When scanf is called, pointers are passed, not direct values. A pointer to float is not converted to a pointer to double (this could not work since the pointed-to object cannot change when you change the pointer type). So, for scanf, the argument for %f must be a pointer to float, and the argument for %lf must be a pointer to double.

JPA Query.getResultList() - use in a generic way

I had the same problem and a simple solution that I found was:

List<Object[]> results = query.getResultList();
for (Object[] result: results) {
    SomeClass something = (SomeClass)result[1];
    something.doSomething;
}

I know this is defenitly not the most elegant solution nor is it best practice but it works, at least for me.

Why is Github asking for username/password when following the instructions on screen and pushing a new repo?

If you're using HTTPS, check to make sure that your URL is correct. For example:

$ git clone https://github.com/wellle/targets.git
Cloning into 'targets'...
Username for 'https://github.com': ^C

$ git clone https://github.com/wellle/targets.vim.git
Cloning into 'targets.vim'...
remote: Counting objects: 2182, done.
remote: Total 2182 (delta 0), reused 0 (delta 0), pack-reused 2182
Receiving objects: 100% (2182/2182), 595.77 KiB | 0 bytes/s, done.
Resolving deltas: 100% (1044/1044), done.

Best data type to store money values in MySQL

You can use DECIMAL or NUMERIC both are same

The DECIMAL and NUMERIC types store exact numeric data values. These types are used when it is important to preserve exact precision, for example with monetary data. In MySQL, NUMERIC is implemented as DECIMAL, so the following remarks about DECIMAL apply equally to NUMERIC. : MySQL

i.e. DECIMAL(10,2)

Example settings

Good read

CSS disable hover effect

Do this Html and the CSS is in the head tag. Just make a new class and in the css use this code snippet:

pointer-events:none;

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .buttonDisabled {
        pointer-events: none;
      }
    </style>
  </head>
  <body>
    <button class="buttonDisabled">Not-a-button</button>
  </body>
</html>

What is {this.props.children} and when you should use it?

I assume you're seeing this in a React component's render method, like this (edit: your edited question does indeed show that):

_x000D_
_x000D_
class Example extends React.Component {_x000D_
  render() {_x000D_
    return <div>_x000D_
      <div>Children ({this.props.children.length}):</div>_x000D_
      {this.props.children}_x000D_
    </div>;_x000D_
  }_x000D_
}_x000D_
_x000D_
class Widget extends React.Component {_x000D_
  render() {_x000D_
    return <div>_x000D_
      <div>First <code>Example</code>:</div>_x000D_
      <Example>_x000D_
        <div>1</div>_x000D_
        <div>2</div>_x000D_
        <div>3</div>_x000D_
      </Example>_x000D_
      <div>Second <code>Example</code> with different children:</div>_x000D_
      <Example>_x000D_
        <div>A</div>_x000D_
        <div>B</div>_x000D_
      </Example>_x000D_
    </div>;_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
  <Widget/>,_x000D_
  document.getElementById("root")_x000D_
);
_x000D_
<div id="root"></div>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
_x000D_
_x000D_
_x000D_

children is a special property of React components which contains any child elements defined within the component, e.g. the divs inside Example above. {this.props.children} includes those children in the rendered result.

...what are the situations to use the same

You'd do it when you want to include the child elements in the rendered output directly, unchanged; and not if you didn't.

How to copy data to clipboard in C#

My Experience with this issue using WPF C# coping to clipboard and System.Threading.ThreadStateException is here with my code that worked correctly with all browsers:

Thread thread = new Thread(() => Clipboard.SetText("String to be copied to clipboard"));
thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
thread.Start(); 
thread.Join();

credits to this post here

But this works only on localhost, so don't try this on a server, as it's not going to work.

On server-side, I did it by using zeroclipboard. The only way, after a lot of research.

How to convert string to integer in C#

string varString = "15";
int i = int.Parse(varString);

or

int varI;
string varString = "15";
int.TryParse(varString, out varI);

int.TryParse is safer since if you put something else in varString (for example "fsfdsfs") you would get an exception. By using int.TryParse when string can't be converted into int it will return 0.

Lazy Loading vs Eager Loading

Lazy loading will produce several SQL calls while Eager loading may load data with one "more heavy" call (with joins/subqueries).

For example, If there is a high ping between your web and sql servers you would go with Eager loading instead of loading related items 1-by-1 with lazy Loading.

Can I use multiple "with"?

Yes - just do it this way:

WITH DependencedIncidents AS
(
  ....
),  
lalala AS
(
  ....
)

You don't need to repeat the WITH keyword

Decode Base64 data in Java

No need to use commons--Sun ships a base64 encoder with Java. You can import it as such:

import sun.misc.BASE64Decoder;

And then use it like this:

BASE64Decoder decoder = new BASE64Decoder();
byte[] decodedBytes = decoder.decodeBuffer(encodedBytes);

Where encodedBytes is either a java.lang.String or a java.io.InputStream. Just beware that the sun.* classes are not "officially supported" by Sun.

EDIT: Who knew this would be the most controversial answer I'd ever post? I do know that sun.* packages are not supported or guaranteed to continue existing, and I do know about Commons and use it all the time. However, the poster asked for a class that that was "included with Sun Java 6," and that's what I was trying to answer. I agree that Commons is the best way to go in general.

EDIT 2: As amir75 points out below, Java 6+ ships with JAXB, which contains supported code to encode/decode Base64. Please see Jeremy Ross' answer below.

Best way to store passwords in MYSQL database

Hashing algorithms such as sha1 and md5 are not suitable for password storing. They are designed to be very efficient. This means that brute forcing is very fast. Even if a hacker obtains a copy of your hashed passwords, it is pretty fast to brute force it. If you use a salt, it makes rainbow tables less effective, but does nothing against brute force. Using a slower algorithm makes brute force ineffective. For instance, the bcrypt algorithm can be made as slow as you wish (just change the work factor), and it uses salts internally to protect against rainbow tables. I would go with such an approach or similar (e.g. scrypt or PBKDF2) if I were you.

Getting the last revision number in SVN?

If you have the misfortune of needing to do this from a Windows batch file, here is the incantation you are looking for:

set REV=unknown
for /f "usebackq tokens=1,2 delims=: " %%A in (`svn info`) do if "%%A" == "Revision" set REV=%%B
echo Current SVN revision is %REV%

This runs "svn info", iterating through each line of generated output. It uses a colon as a delimiter between the first and second token on the line. When the first token is "Revision" it sets the environment variable REV to the second token.

Can't connect to MySQL server on '127.0.0.1' (10061) (2003)

I was facing the same problem, but what I did not realise is that I did not have the MySQL Server installed. You must simply install the MySQL Server.

In order to install the MySQL server, you must run the "MySql Installer" and then press the "Add" button and then choose the "MySQL Server" in the tree.

After doing that, run you workbench again and you'll notice that there'll already be a connection configured. Hopefully, you'll be able to create a new connection or as many connections as you want.

Set value to currency in <input type="number" />

In the end I made a jQuery plugin that will format the <input type="number" /> appropriately for me. I also noticed on some mobile devices the min and max attributes don't actually prevent you from entering lower or higher numbers than specified, so the plugin will account for that too. Below is the code and an example:

_x000D_
_x000D_
(function($) {_x000D_
  $.fn.currencyInput = function() {_x000D_
    this.each(function() {_x000D_
      var wrapper = $("<div class='currency-input' />");_x000D_
      $(this).wrap(wrapper);_x000D_
      $(this).before("<span class='currency-symbol'>$</span>");_x000D_
      $(this).change(function() {_x000D_
        var min = parseFloat($(this).attr("min"));_x000D_
        var max = parseFloat($(this).attr("max"));_x000D_
        var value = this.valueAsNumber;_x000D_
        if(value < min)_x000D_
          value = min;_x000D_
        else if(value > max)_x000D_
          value = max;_x000D_
        $(this).val(value.toFixed(2)); _x000D_
      });_x000D_
    });_x000D_
  };_x000D_
})(jQuery);_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('input.currency').currencyInput();_x000D_
});
_x000D_
.currency {_x000D_
  padding-left:12px;_x000D_
}_x000D_
_x000D_
.currency-symbol {_x000D_
  position:absolute;_x000D_
  padding: 2px 5px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<input type="number" class="currency" min="0.01" max="2500.00" value="25.00" />
_x000D_
_x000D_
_x000D_

Passing a String by Reference in Java?

For someone who are more curious

class Testt {
    static void Display(String s , String varname){
        System.out.println(varname + " variable data = "+ s + " :: address hashmap =  " + s.hashCode());
    }

    static void changeto(String s , String t){
        System.out.println("entered function");
        Display(s , "s");
        s = t ;
        Display(s,"s");
        System.out.println("exiting function");
    }

    public static void main(String args[]){
        String s =  "hi" ;
        Display(s,"s");
        changeto(s,"bye");
        Display(s,"s");
    }
}

Now by running this above code you can see how address hashcodes change with String variable s . a new object is allocated to variable s in function changeto when s is changed

How do I perform an insert and return inserted identity with Dapper?

The InvalidCastException you are getting is due to SCOPE_IDENTITY being a Decimal(38,0).

You can return it as an int by casting it as follows:

string sql = @"
INSERT INTO [MyTable] ([Stuff]) VALUES (@Stuff);
SELECT CAST(SCOPE_IDENTITY() AS INT)";

int id = connection.Query<int>(sql, new { Stuff = mystuff}).Single();

"Integer number too large" error message for 600851475143

You need 40 bits to represent the integer literal 600851475143. In Java, the maximum integer value is 2^31-1 however (i.e. integers are 32 bit, see http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Integer.html).

This has nothing to do with function. Try using a long integer literal instead (as suggested in the other answers).

How to write ternary operator condition in jQuery?

I'd do (added caching):

var bbx = $("#blackbox");
 bbx.css('background-color') === 'rgb(255, 192, 203)' ? bbx.css('background','black') : bbx.css('background','pink')

wroking fiddle (new AGAIN): http://jsfiddle.net/6nar4/37/

I had to change the first operator as css() returns the rgb value of the color

imagecreatefromjpeg and similar functions are not working in PHP

As mentioned before, you might need GD library installed.

On a shell, check your php version first:
php -v

Then install accordingly. In my system (Linux-Ubuntu) it's php version 7.0:
sudo apt-get install php7.0-gd

Restart your webserver:
systemctl restart apache2

You should now have GD library installed and enabled.

sorting and paging with gridview asp.net

I found a much easier way, which allows you to still use the built in sorting/paging of the standard gridview...

create 2 labels. set them to be visible = false. I called mine lblSort1 and lblSortDirection1

then code 2 simple events... the page sorting, which writes to the text of the invisible labels, and the page index changing, which uses them...

Private Sub gridview_Sorting(sender As Object, e As GridViewSortEventArgs) Handles gridview.Sorting
lblSort1.Text = e.SortExpression
lblSortDirection1.Text = e.SortDirection
End Sub

Private Sub gridview_PageIndexChanging(sender As Object, e As GridViewPageEventArgs) Handles gridview.PageIndexChanging
    gridview.Sort(lblSort1.Text, CInt(lblSortDirection1.Text))
End Sub

this is a little sloppier than using global variables, but I've found with asp especially that global vars are, well, unreliable...

What are the differences between delegates and events?

What a great misunderstanding between events and delegates!!! A delegate specifies a TYPE (such as a class, or an interface does), whereas an event is just a kind of MEMBER (such as fields, properties, etc). And, just like any other kind of member an event also has a type. Yet, in the case of an event, the type of the event must be specified by a delegate. For instance, you CANNOT declare an event of a type defined by an interface.

Concluding, we can make the following Observation: the type of an event MUST be defined by a delegate. This is the main relation between an event and a delegate and is described in the section II.18 Defining events of ECMA-335 (CLI) Partitions I to VI:

In typical usage, the TypeSpec (if present) identifies a delegate whose signature matches the arguments passed to the event’s fire method.

However, this fact does NOT imply that an event uses a backing delegate field. In truth, an event may use a backing field of any different data structure type of your choice. If you implement an event explicitly in C#, you are free to choose the way you store the event handlers (note that event handlers are instances of the type of the event, which in turn is mandatorily a delegate type---from the previous Observation). But, you can store those event handlers (which are delegate instances) in a data structure such as a List or a Dictionary or any other else, or even in a backing delegate field. But don’t forget that it is NOT mandatory that you use a delegate field.

IF a cell contains a string

=IFS(COUNTIF(A1,"*cats*"),"cats",COUNTIF(A1,"*22*"),"22",TRUE,"none")

installing requests module in python 2.7 windows

On windows 10 run cmd.exe with admin rights then type :

1) cd \Python27\scripts

2) pip install requests

It should work. My case was with python 2.7

ReferenceError: fetch is not defined

If it has to be accessible with a global scope

global.fetch = require("node-fetch");

This is a quick dirty fix, please try to eliminate this usage in production code.

What are advantages of Artificial Neural Networks over Support Vector Machines?

We should also consider that the SVM system can be applied directly to non-metric spaces, such as the set of labeled graphs or strings. In fact, the internal kernel function can be generalized properly to virtually any kind of input, provided that the positive definiteness requirement of the kernel is satisfied. On the other hand, to be able to use an ANN on a set of labeled graphs, explicit embedding procedures must be considered.

Markdown and including multiple files

IMHO, You can get your result by concatenating your input *.md files like:

$ pandoc -s -o outputDoc.pdf inputDoc1.md inputDoc2.md outputDoc3.md

Flatten list of lists

Flatten the list to "remove the brackets" using a nested list comprehension. This will un-nest each list stored in your list of lists!

list_of_lists = [[180.0], [173.8], [164.2], [156.5], [147.2], [138.2]]
flattened = [val for sublist in list_of_lists for val in sublist]

Nested list comprehensions evaluate in the same manner that they unwrap (i.e. add newline and tab for each new loop. So in this case:

flattened = [val for sublist in list_of_lists for val in sublist]

is equivalent to:

flattened = []
for sublist in list_of_lists:
    for val in sublist:
        flattened.append(val)

The big difference is that the list comp evaluates MUCH faster than the unraveled loop and eliminates the append calls!

If you have multiple items in a sublist the list comp will even flatten that. ie

>>> list_of_lists = [[180.0, 1, 2, 3], [173.8], [164.2], [156.5], [147.2], [138.2]]
>>> flattened  = [val for sublist in list_of_lists for val in sublist]
>>> flattened 
[180.0, 1, 2, 3, 173.8, 164.2, 156.5, 147.2,138.2]

Calling functions in a DLL from C++

Might be useful: https://www.codeproject.com/Articles/6299/Step-by-Step-Calling-C-DLLs-from-VC-and-VB-Part-4

For the example above with "GetWelcomeMessage" you might need to specify "__stdcall" in the typedef field before the function name if getting error after calling imported function.

Change a branch name in a Git repo

If you're currently on the branch you want to rename:

git branch -m new_name 

Or else:

git branch -m old_name new_name 

You can check with:

git branch -a

As you can see, only the local name changed Now, to change the name also in the remote you must do:

git push origin :old_name

This removes the branch, then upload it with the new name:

git push origin new_name

Source: https://web.archive.org/web/20150929104013/http://blog.changecong.com:80/2012/10/rename-a-remote-branch-on-github

How do you format code on save in VS Code

No need to add commands anymore. For those who are new to Visual Studio Code and searching for an easy way to format code on saving, kindly follow the below steps.

  1. Open Settings by pressing [Cmd+,] in Mac or using the below screenshot.

VS Code - Open Settings Command Image

  1. Type 'format' in the search box and enable the option 'Format On Save'.

enter image description here

You are done. Thank you.

How to loop through a JSON object with typescript (Angular2)

Assuming your json object from your GET request looks like the one you posted above simply do:

let list: string[] = [];

json.Results.forEach(element => {
    list.push(element.Id);
});

Or am I missing something that prevents you from doing it this way?

Having both a Created and Last Updated timestamp columns in MySQL 4.0

My web host is stuck on version 5.1 of mysql so anyone like me that doesn't have the option of upgrading can follow these directions:

http://joegornick.com/2009/12/30/mysql-created-and-modified-date-fields/

Removing ul indentation with CSS

-webkit-padding-start: 0;

will remove padding added by webkit engine

Multi-statement Table Valued Function vs Inline Table Valued Function

Internally, SQL Server treats an inline table valued function much like it would a view and treats a multi-statement table valued function similar to how it would a stored procedure.

When an inline table-valued function is used as part of an outer query, the query processor expands the UDF definition and generates an execution plan that accesses the underlying objects, using the indexes on these objects.

For a multi-statement table valued function, an execution plan is created for the function itself and stored in the execution plan cache (once the function has been executed the first time). If multi-statement table valued functions are used as part of larger queries then the optimiser does not know what the function returns, and so makes some standard assumptions - in effect it assumes that the function will return a single row, and that the returns of the function will be accessed by using a table scan against a table with a single row.

Where multi-statement table valued functions can perform poorly is when they return a large number of rows and are joined against in outer queries. The performance issues are primarily down to the fact that the optimiser will produce a plan assuming that a single row is returned, which will not necessarily be the most appropriate plan.

As a general rule of thumb we have found that where possible inline table valued functions should be used in preference to multi-statement ones (when the UDF will be used as part of an outer query) due to these potential performance issues.

How to move an element into another element?

What about a JavaScript solution?

// Declare a fragment:
var fragment = document.createDocumentFragment();

// Append desired element to the fragment:
fragment.appendChild(document.getElementById('source'));

// Append fragment to desired element:
document.getElementById('destination').appendChild(fragment);

Check it out.

How to set a DateTime variable in SQL Server 2008?

Try using Select instead of Print

DECLARE @Test AS DATETIME 

SET @Test = '2011-02-15'

Select @Test

How to filter an array of objects based on values in an inner array with jq?

Very close! In your select expression, you have to use a pipe (|) before contains.

This filter produces the expected output.

. - map(select(.Names[] | contains ("data"))) | .[] .Id

The jq Cookbook has an example of the syntax.

Filter objects based on the contents of a key

E.g., I only want objects whose genre key contains "house".

$ json='[{"genre":"deep house"}, {"genre": "progressive house"}, {"genre": "dubstep"}]'
$ echo "$json" | jq -c '.[] | select(.genre | contains("house"))'
{"genre":"deep house"}
{"genre":"progressive house"}

Colin D asks how to preserve the JSON structure of the array, so that the final output is a single JSON array rather than a stream of JSON objects.

The simplest way is to wrap the whole expression in an array constructor:

$ echo "$json" | jq -c '[ .[] | select( .genre | contains("house")) ]'
[{"genre":"deep house"},{"genre":"progressive house"}]

You can also use the map function:

$ echo "$json" | jq -c 'map(select(.genre | contains("house")))'
[{"genre":"deep house"},{"genre":"progressive house"}]

map unpacks the input array, applies the filter to every element, and creates a new array. In other words, map(f) is equivalent to [.[]|f].

Laravel password validation rule

Sounds like a good job for regular expressions.

Laravel validation rules support regular expressions. Both 4.X and 5.X versions are supporting it :

This might help too:

http://www.regular-expressions.info/unicode.html

Get selected key/value of a combo box using jQuery

$("#elementName option").text(); 

This will give selected text of Combo-Box.

$("#elementName option").val();

This will give selected value associated selected item in Combo-Box.

$("#elementName option").length;

It will give the multi-select combobox values in the array and length will give number of element of the array.

Note:#elementName is id the Combo-box.

"An access token is required to request this resource" while accessing an album / photo with Facebook php sdk

Well, you are having a valid access token to access your information and not others( this is because you got logged in and you have given permission to access your information). But the picture owner has not done the same (logged in + permission ) and so you are getting a violation error.

To obtain permission see this link and decide what kind of informations you want from any user and decide the permissions. Later on embed this in your code. (In the login function call)

Thanks

How can I work with command line on synology?

I use GateOne from the synocommunity.

Go into settings in Package Center and add http://packages.synocommunity.com/ as a package source. Then you should be able to add it easily via Package Center.

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

PostgreSQL psql terminal command

Use \x Example from postgres manual:

    postgres=# \x
    postgres=# SELECT * FROM pg_stat_statements ORDER BY total_time DESC LIMIT 3;
    -[ RECORD 1 ]------------------------------------------------------------
    userid     | 10
    dbid       | 63781
    query      | UPDATE branches SET bbalance = bbalance + $1 WHERE bid = $2;
    calls      | 3000
    total_time | 20.716706
    rows       | 3000
    -[ RECORD 2 ]------------------------------------------------------------
    userid     | 10
    dbid       | 63781
    query      | UPDATE tellers SET tbalance = tbalance + $1 WHERE tid = $2;
    calls      | 3000
    total_time | 17.1107649999999
    rows       | 3000
    -[ RECORD 3 ]------------------------------------------------------------
    userid     | 10
    dbid       | 63781
    query      | UPDATE accounts SET abalance = abalance + $1 WHERE aid = $2;
    calls      | 3000
    total_time | 0.645601
    rows       | 3000

How to color the Git console?

In your ~/.gitconfig file, simply add this:

[color]
  ui = auto

It takes care of all your git commands.

MYSQL Sum Query with IF Condition

Try with a CASE in this way :

SUM(CASE 
    WHEN PaymentType = "credit card" 
    THEN TotalAmount 
    ELSE 0 
END) AS CreditCardTotal,

Should give what you are looking for ...

CSS: create white glow around image

Use simple CSS3 (not supported in IE<9)

img
{
    box-shadow: 0px 0px 5px #fff;
}

This will put a white glow around every image in your document, use more specific selectors to choose which images you'd like the glow around. You can change the color of course :)

If you're worried about the users that don't have the latest versions of their browsers, use this:

img
{
-moz-box-shadow: 0 0 5px #fff;
-webkit-box-shadow: 0 0 5px #fff;
box-shadow: 0px 0px 5px #fff;
}

For IE you can use a glow filter (not sure which browsers support it)

img
{
    filter:progid:DXImageTransform.Microsoft.Glow(Color=white,Strength=5);
}

Play with the settings to see what suits you :)

HTML not loading CSS file

_x000D_
_x000D_
<link href="style.css" rel="stylesheet" type="text/css"/>
_x000D_
_x000D_
_x000D_

VBA test if cell is in a range

Here is another option to see if a cell exists inside a range. In case you have issues with the Intersect solution as I did.

If InStr(range("NamedRange").Address, range("IndividualCell").Address) > 0 Then
    'The individual cell exists in the named range
Else
    'The individual cell does not exist in the named range
End If

InStr is a VBA function that checks if a string exists within another string.

https://msdn.microsoft.com/en-us/vba/language-reference-vba/articles/instr-function

Append key/value pair to hash with << in Ruby

I had to do a similar thing but I needed to add values with same keys. When I use merge or update I can't push values with same keys. So I had to use array of hashes.

    my_hash_static = {:header =>{:company => 'xx', :usercode => 'xx', :password => 'xx',
                      :type=> 'n:n', :msgheader => from}, :body=>[]}
    my_hash_dynamic = {:mp=>{:msg=>message, :no=>phones} }        
    my_hash_full = my_hash_static[:body].push my_hash_dynamic

How to set combobox default value?

You can do something like this:

    public myform()
    {
         InitializeComponent(); // this will be called in ComboBox ComboBox = new System.Windows.Forms.ComboBox();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'myDataSet.someTable' table. You can move, or remove it, as needed.
        this.myTableAdapter.Fill(this.myDataSet.someTable);
        comboBox1.SelectedItem = null;
        comboBox1.SelectedText = "--select--";           
    }

Check if string is in a pandas dataframe

You should check the value of your line of code like adding checking length of it.

if(len(a['Names'].str.contains('Mel'))>0):
    print("Name Present")

Looping through array and removing items, without breaking for loop

Auction.auctions = Auction.auctions.filter(function(el) {
  return --el["seconds"] > 0;
});

C# Select elements in list as List of string

List<string> empnames = (from e in emplist select e.Enaame).ToList();

Or

string[] empnames = (from e in emplist select e.Enaame).ToArray();

Etc...

How to scan multiple paths using the @ComponentScan annotation?

@ComponentScan uses string array, like this:

@ComponentScan({"com.my.package.first","com.my.package.second"})

When you provide multiple package names in only one string, Spring interprets this as one package name, and thus can't find it.

How to remove a character at the end of each line in unix

You can use sed:

sed 's/,$//' file > file.nocomma

and to remove whatever last character:

sed 's/.$//' file > file.nolast

How to round 0.745 to 0.75 using BigDecimal.ROUND_HALF_UP?

Never construct BigDecimals from floats or doubles. Construct them from ints or strings. floats and doubles loose precision.

This code works as expected (I just changed the type from double to String):

public static void main(String[] args) {
  String doubleVal = "1.745";
  String doubleVal1 = "0.745";
  BigDecimal bdTest = new BigDecimal(  doubleVal);
  BigDecimal bdTest1 = new BigDecimal(  doubleVal1 );
  bdTest = bdTest.setScale(2, BigDecimal.ROUND_HALF_UP);
  bdTest1 = bdTest1.setScale(2, BigDecimal.ROUND_HALF_UP);
  System.out.println("bdTest:"+bdTest); //1.75
  System.out.println("bdTest1:"+bdTest1);//0.75, no problem
}

Syntax for async arrow function

Basic Example

folder = async () => {
    let fold = await getFold();
    //await localStorage.save('folder');
    return fold;
  };

Selenium WebDriver: I want to overwrite value in field instead of appending to it with sendKeys using Java

Okay, it is a few days ago... In my current case, the answer from ZloiAdun does not work for me, but brings me very close to my solution...

Instead of:

element.sendKeys(Keys.chord(Keys.CONTROL, "a"), "55");

the following code makes me happy:

element.sendKeys(Keys.HOME, Keys.chord(Keys.SHIFT, Keys.END), "55");

So I hope that helps somebody!

What does the keyword Set actually do in VBA?

In your case, it will produce an error. :-)

Set assigns an object reference. For all other assignments the (implicit, optional, and little-used) Let statement is correct:

Set object = New SomeObject
Set object = FunctionReturningAnObjectRef(SomeArgument)

Let i = 0
Let i = FunctionReturningAValue(SomeArgument)

' or, more commonly '

i = 0
i = FunctionReturningAValue(SomeArgument)

Why do I get the error "Unsafe code may only appear if compiling with /unsafe"?

Search your code for unsafe blocks or statements. These are only valid is compiled with /unsafe.

Python Request Post with param data

Assign the response to a value and test the attributes of it. These should tell you something useful.

response = requests.post(url,params=data,headers=headers)
response.status_code
response.text
  • status_code should just reconfirm the code you were given before, of course

How to use onSaveInstanceState() and onRestoreInstanceState()?

  • onSaveInstanceState() is a method used to store data before pausing the activity.

Description : Hook allowing a view to generate a representation of its internal state that can later be used to create a new instance with that same state. This state should only contain information that is not persistent or can not be reconstructed later. For example, you will never store your current position on screen because that will be computed again when a new instance of the view is placed in its view hierarchy.

  • onRestoreInstanceState() is method used to retrieve that data back.

Description : This method is called after onStart() when the activity is being re-initialized from a previously saved state, given here in savedInstanceState. Most implementations will simply use onCreate(Bundle) to restore their state, but it is sometimes convenient to do it here after all of the initialization has been done or to allow subclasses to decide whether to use your default implementation. The default implementation of this method performs a restore of any view state that had previously been frozen by onSaveInstanceState(Bundle).

Consider this example here:
You app has 3 edit boxes where user was putting in some info , but he gets a call so if you didn't use the above methods what all he entered will be lost.
So always save the current data in onPause() method of Activity as a bundle & in onResume() method call the onRestoreInstanceState() method .

Please see :

How to use onSavedInstanceState example please

http://www.how-to-develop-android-apps.com/tag/onrestoreinstancestate/

Difference between add(), replace(), and addToBackStack()

Here is a picture that shows the difference between add() and replace()

enter image description here

So add() method keeps on adding fragments on top of the previous fragment in FragmentContainer.

While replace() methods clears all the previous Fragment from Containers and then add it in FragmentContainer.

What is addToBackStack

addtoBackStack method can be used with add() and replace methods. It serves a different purpose in Fragment API.

What is the purpose?

Fragment API unlike Activity API does not come with Back Button navigation by default. If you want to go back to the previous Fragment then the we use addToBackStack() method in Fragment. Let's understand both

Case 1:

getSupportFragmentManager()
            .beginTransaction()
            .add(R.id.fragmentContainer, fragment, "TAG")
            .addToBackStack("TAG")
            .commit();

enter image description here

Case 2:

getSupportFragmentManager()
            .beginTransaction()
            .add(R.id.fragmentContainer, fragment, "TAG")
            .commit();

enter image description here

How can labels/legends be added for all chart types in chart.js (chartjs.org)?

  1. The legend is part of the default options of the ChartJs library. So you do not need to explicitly add it as an option.

  2. The library generates the HTML. It is merely a matter of adding that to the your page. For example, add it to the innerHTML of a given DIV. (Edit the default options if you are editing the colors, etc)


<div>
    <canvas id="chartDiv" height="400" width="600"></canvas>
    <div id="legendDiv"></div>
</div>

<script>
   var data = {
        labels: ["January", "February", "March", "April", "May", "June", "July"],
        datasets: [
            {
                label: "The Flash's Speed",
                fillColor: "rgba(220,220,220,0.2)",
                strokeColor: "rgba(220,220,220,1)",
                pointColor: "rgba(220,220,220,1)",
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(220,220,220,1)",
                data: [65, 59, 80, 81, 56, 55, 40]
            },
            {
                label: "Superman's Speed",
                fillColor: "rgba(151,187,205,0.2)",
                strokeColor: "rgba(151,187,205,1)",
                pointColor: "rgba(151,187,205,1)",
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(151,187,205,1)",
                data: [28, 48, 40, 19, 86, 27, 90]
            }
        ]
    };

    var myLineChart = new Chart(document.getElementById("chartDiv").getContext("2d")).Line(data);
    document.getElementById("legendDiv").innerHTML = myLineChart.generateLegend();
</script>

Select multiple columns using Entity Framework

You either want to select an anonymous type:

var dataset2 = from recordset 
               in entities.processlists 
               where recordset.ProcessName == processname 
               select new 
               {
                recordset.ServerName, 
                recordset.ProcessID, 
                recordset.Username
               };

But you cannot cast that to another type, so I guess you want something like this:

var dataset2 = from recordset 
               in entities.processlists 
               where recordset.ProcessName == processname 

               // Select new concrete type
               select new PInfo
               {
                ServerName = recordset.ServerName, 
                ProcessID = recordset.ProcessID, 
                Username = recordset.Username
               };

Using underscores in Java variables and method names

sunDoesNotRecommendUnderscoresBecauseJavaVariableAndFunctionNamesTendToBeLongEnoughAsItIs();

as_others_have_said_consistency_is_the_important_thing_here_so_chose_whatever_you_think_is_more_readable();

Hiding an Excel worksheet with VBA

Just wanted to add a little more detail to the answers given. You can also use

sheet.Visible = False

to hide and

sheet.Visible = True

to unhide.

Source

Right Align button in horizontal LinearLayout

You should use the Relativelayout instead of Linearlayout as main layout. If you use Relativelayout as main then easily handle the button on right side because relative layout provide us alignParent right, left,top and bottom.