Programs & Examples On #Javascript security

Check whether variable is number or string in JavaScript

@BitOfUniverse's answer is good, and I come up with a new way:

function isNum(n) {
    return !isNaN(n/0);
}

isNum('')  // false
isNum(2)   // true
isNum('2k') // false
isNum('2')  //true

I know 0 can't be dividend, but here the function works perfectly.

Moving up one directory in Python

Although this is not exactly what OP meant as this is not super simple, however, when running scripts from Notepad++ the os.getcwd() method doesn't work as expected. This is what I would do:

import os

# get real current directory (determined by the file location)
curDir, _ = os.path.split(os.path.abspath(__file__))

print(curDir) # print current directory

Define a function like this:

def dir_up(path,n): # here 'path' is your path, 'n' is number of dirs up you want to go
    for _ in range(n):
        path = dir_up(path.rpartition("\\")[0], 0) # second argument equal '0' ensures that 
                                                        # the function iterates proper number of times
    return(path)

The use of this function is fairly simple - all you need is your path and number of directories up.

print(dir_up(curDir,3)) # print 3 directories above the current one

The only minus is that it doesn't stop on drive letter, it just will show you empty string.

SUM OVER PARTITION BY

I think the query you want is this:

SELECT BrandId, SUM(ICount),
       SUM(sum(ICount)) over () as TotalCount,
       100.0 * SUM(ICount) / SUM(sum(Icount)) over () as Percentage
FROM Table 
WHERE DateId  = 20130618
group by BrandId;

This does the group by for brand. And it calculates the "Percentage". This version should produce a number between 0 and 100.

jQuery selector first td of each row

var tablefirstcolumn=$("tr").find("td:first")
alert(tablefirstcolumn+"of Each row")

How to convert string to date to string in Swift iOS?

//String to Date Convert

var dateString = "2014-01-12"
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let s = dateFormatter.dateFromString(dateString)
println(s)


//CONVERT FROM NSDate to String  

let date = NSDate()
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd" 
var dateString = dateFormatter.stringFromDate(date)
println(dateString)  

Is it possible to compile a program written in Python?

python compile on the fly when you run it.

Run a .py file by(linux): python abc.py

ImportError: No module named _ssl

Either install the supplementary packages for python-ssl using your package manager or recompile Python using -with-ssl (requires OpenSSL headers/libs installed).

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

In addition to the accepted answer, if you are using Android Studio you can

  1. invoke Android Device Monitor,
  2. select the device in the Devices tab on the left,
  3. select File Explorer tab on the right,
  4. navigate to the file you want, and
  5. click the Pull a file from the device button to save it to your local file system

Taken from Working with an emulator or device's file system

Looping through JSON with node.js

I would recommend taking advantage of the fact that nodeJS will always be ES5. Remember this isn't the browser folks you can depend on the language's implementation on being stable. That said I would recommend against ever using a for-in loop in nodeJS, unless you really want to do deep recursion up the prototype chain. For simple, traditional looping I would recommend making good use of Object.keys method, in ES5. If you view the following JSPerf test, especially if you use Chrome (since it has the same engine as nodeJS), you will get a rough idea of how much more performant using this method is than using a for-in loop (roughly 10 times faster). Here's a sample of the code:

 var keys = Object.keys( obj );
 for( var i = 0,length = keys.length; i < length; i++ ) {
     obj[ keys[ i ] ];
 }

matplotlib: Group boxplots

A simple way would be to use pandas. I adapted an example from the plotting documentation:

In [1]: import pandas as pd, numpy as np

In [2]: df = pd.DataFrame(np.random.rand(12,2), columns=['Apples', 'Oranges'] )

In [3]: df['Categories'] = pd.Series(list('AAAABBBBCCCC'))

In [4]: pd.options.display.mpl_style = 'default'

In [5]: df.boxplot(by='Categories')
Out[5]: 
array([<matplotlib.axes.AxesSubplot object at 0x51a5190>,
       <matplotlib.axes.AxesSubplot object at 0x53fddd0>], dtype=object)

pandas boxplot

How do I use an INSERT statement's OUTPUT clause to get the identity value?

You can either have the newly inserted ID being output to the SSMS console like this:

INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')

You can use this also from e.g. C#, when you need to get the ID back to your calling app - just execute the SQL query with .ExecuteScalar() (instead of .ExecuteNonQuery()) to read the resulting ID back.

Or if you need to capture the newly inserted ID inside T-SQL (e.g. for later further processing), you need to create a table variable:

DECLARE @OutputTbl TABLE (ID INT)

INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID INTO @OutputTbl(ID)
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')

This way, you can put multiple values into @OutputTbl and do further processing on those. You could also use a "regular" temporary table (#temp) or even a "real" persistent table as your "output target" here.

How to decrypt a password from SQL server?

You realise that you may be making a rod for your own back for the future. The pwdencrypt() and pwdcompare() are undocumented functions and may not behave the same in future versions of SQL Server.

Why not hash the password using a predictable algorithm such as SHA-2 or better before hitting the DB?

How to copy a file to a remote server in Python using SCP or SSH?

You can use the vassal package, which is exactly designed for this.

All you need is to install vassal and do

from vassal.terminal import Terminal
shell = Terminal(["scp username@host:/home/foo.txt foo_local.txt"])
shell.run()

Also, it will save you authenticate credential and don't need to type them again and again.

spring autowiring with unique beans: Spring expected single matching bean but found 2

The issue is because you have a bean of type SuggestionService created through @Component annotation and also through the XML config . As explained by JB Nizet, this will lead to the creation of a bean with name 'suggestionService' created via @Component and another with name 'SuggestionService' created through XML .

When you refer SuggestionService by @Autowired, in your controller, Spring autowires "by type" by default and find two beans of type 'SuggestionService'

You could do the following

  1. Remove @Component from your Service and depend on mapping via XML - Easiest

  2. Remove SuggestionService from XML and autowire the dependencies - use util:map to inject the indexSearchers map.

  3. Use @Resource instead of @Autowired to pick the bean by its name .

     @Resource(name="suggestionService")
     private SuggestionService service;
    

or

    @Resource(name="SuggestionService")
    private SuggestionService service;

both should work.The third is a dirty fix and it's best to resolve the bean conflict through other ways.

php: how to get associative array key from numeric index?

If it is the first element, i.e. $array[0], you can try:

echo key($array);

If it is the second element, i.e. $array[1], you can try:

next($array);
echo key($array);

I think this method is should be used when required element is the first, second or at most third element of the array. For other cases, loops should be used otherwise code readability decreases.

How to set the Android progressbar's height?

You can set progress bar's style to this:

style="@android:style/Widget.ProgressBar.Horizontal"    

How to update Git clone

If you want to fetch + merge, run

git pull

if you want simply to fetch :

git fetch

Converting SVG to PNG using C#

When I had to rasterize svgs on the server, I ended up using P/Invoke to call librsvg functions (you can get the dlls from a windows version of the GIMP image editing program).

[DllImport("kernel32.dll", SetLastError = true)]
static extern bool SetDllDirectory(string pathname);

[DllImport("libgobject-2.0-0.dll", SetLastError = true)]
static extern void g_type_init(); 

[DllImport("librsvg-2-2.dll", SetLastError = true)]
static extern IntPtr rsvg_pixbuf_from_file_at_size(string file_name, int width, int height, out IntPtr error);

[DllImport("libgdk_pixbuf-2.0-0.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
static extern bool gdk_pixbuf_save(IntPtr pixbuf, string filename, string type, out IntPtr error, __arglist);

public static void RasterizeSvg(string inputFileName, string outputFileName)
{
    bool callSuccessful = SetDllDirectory("C:\\Program Files\\GIMP-2.0\\bin");
    if (!callSuccessful)
    {
        throw new Exception("Could not set DLL directory");
    }
    g_type_init();
    IntPtr error;
    IntPtr result = rsvg_pixbuf_from_file_at_size(inputFileName, -1, -1, out error);
    if (error != IntPtr.Zero)
    {
        throw new Exception(Marshal.ReadInt32(error).ToString());
    }
    callSuccessful = gdk_pixbuf_save(result, outputFileName, "png", out error, __arglist(null));
    if (!callSuccessful)
    {
        throw new Exception(error.ToInt32().ToString());
    }
}

How can I do an asc and desc sort using underscore.js?

Descending order using underscore can be done by multiplying the return value by -1.

//Ascending Order:
_.sortBy([2, 3, 1], function(num){
    return num;
}); // [1, 2, 3]


//Descending Order:
_.sortBy([2, 3, 1], function(num){
    return num * -1;
}); // [3, 2, 1]

If you're sorting by strings not numbers, you can use the charCodeAt() method to get the unicode value.

//Descending Order Strings:
_.sortBy(['a', 'b', 'c'], function(s){ 
    return s.charCodeAt() * -1;
});

Server certificate verification failed: issuer is not trusted

from cmd run: SVN List URL you will be provided with 3 options (r)eject, (a)ccept, (p)ermanently. enter p. This resolved issue for me

Check if my SSL Certificate is SHA1 or SHA2

Use the Linux Command Line

Use the command line, as described in this related question: How do I check if my SSL Certificate is SHA1 or SHA2 on the commandline.

Command

Here's the command. Replace www.yoursite.com:443 to fit your needs. Default SSL port is 443:

openssl s_client -connect www.yoursite.com:443 < /dev/null 2>/dev/null \
    | openssl x509 -text -in /dev/stdin | grep "Signature Algorithm"

Results

This should return something like this for the sha1:

Signature Algorithm: sha1WithRSAEncryption

or this for the newer version:

Signature Algorithm: sha256WithRSAEncryption

References

The article Why Google is Hurrying the Web to Kill SHA-1 describes exactly what you would expect and has a pretty graphic, too.

How to change sender name (not email address) when using the linux mail command for autosending mail?

It depends on what sender address you are talking about. The sender address visble in the recipients mailprogramm is extracted from the "From:" Header. which can probably easily be set from your program.

If you are talking about the SMTP envelope sender address, you can pass the -f argument to the sendmail binary. Depending on the server configuration you may not be allowed to do that with the apache user.

from the sendmail manpage :

   -f <address>
                 This  option  sets  the  address  of the envelope sender of a
                 locally-generated message (also known as  the  return  path).
                 The  option  can normally be used only by a trusted user, but
                 untrusted_set_sender can be set to allow untrusted  users  to
                 use it. [...]

Is there a way to represent a directory tree in a Github README.md?

If you are working on windows write tree /f inside the directory you want to achieve that in command prompt. This should do your job. you can copy and paste the output on markdown surrounded my triple back ticks i.e. '''{tree structure here}'''

Select All checkboxes using jQuery

Try the following simple code:

$('input[type=checkbox]').each(function() { this.checked = true; }); 

Source: How to reset all checkboxes using jQuery or pure JS?

Java : Convert formatted xml file to one line string

FileUtils.readFileToString(fileName);

link

SQL Server 2012 can't start because of a login failure

I had a similar issue that was resolved with the following:

  1. In Services.MSC click on the Log On tab and add the user with minimum privileges and password (on the service that is throwing the login error)
  2. By Starting Sql Server to run as Administrator

If the user is a domain user use Domain username and password

Detecting locked tables (locked by LOCK TABLE)

You can create your own lock with GET_LOCK(lockName,timeOut)

If you do a GET_LOCK(lockName, 0) with a 0 time out before you lock the tables and then follow that with a RELEASE_LOCK(lockName) then all other threads performing a GET_LOCK() will get a value of 0 which will tell them that the lock is being held by another thread.

However this won't work if you don't have all threads calling GET_LOCK() before locking tables. The documentation for locking tables is here

Hope that helps!

calling javascript function on OnClientClick event of a Submit button

<asp:Button ID="btnGet" runat="server" Text="Get" OnClick="btnGet_Click" OnClientClick="retun callMethod();" />
<script type="text/javascript">
    function callMethod() {
        //your logic should be here and make sure your logic code note returing function
        return false;
}
</script>

Vue template or render function not defined yet I am using neither?

In my case, I imported my component (in router) as:

import bsw from 'common-mod/src/components/webcommon/webcommon'

It is simply solved if I changed it to

import bsw from 'common-mod/src/components/webcommon/webcommon.vue'

Decode UTF-8 with Javascript

Perhaps using the textDecoder will be sufficient.

Not supported in IE though.

var decoder = new TextDecoder('utf-8'),
    decodedMessage;

decodedMessage = decoder.decode(message.data);

Handling non-UTF8 text

In this example, we decode the Russian text "??????, ???!", which means "Hello, world." In our TextDecoder() constructor, we specify the Windows-1251 character encoding, which is appropriate for Cyrillic script.

_x000D_
_x000D_
    let win1251decoder = new TextDecoder('windows-1251');
    let bytes = new Uint8Array([207, 240, 232, 226, 229, 242, 44, 32, 236, 232, 240, 33]);
    console.log(win1251decoder.decode(bytes)); // ??????, ???!
_x000D_
_x000D_
_x000D_

The interface for the TextDecoder is described here.

Retrieving a byte array from a string is equally simpel:

_x000D_
_x000D_
const decoder = new TextDecoder();
const encoder = new TextEncoder();

const byteArray = encoder.encode('Größe');
// converted it to a byte array

// now we can decode it back to a string if desired
console.log(decoder.decode(byteArray));
_x000D_
_x000D_
_x000D_

If you have it in a different encoding then you must compensate for that upon encoding. The parameter in the constructor for the TextEncoder is any one of the valid encodings listed here.

'Missing recommended icon file - The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format'

In my case, my App icon files were not in the camel case notation. For example:

My Filename: Appicon57x57

Should be: AppIcon57x57 (note the capital 'i' here)

So, in my case the solution was this:

  1. Remove all the icon files from the Asset Catalog.
  2. Rename the file as mentioned above.
  3. Add the renamed files back to the Asset Catalog again.

This should fix the problem.

How to open a file for both reading and writing?

Here's how you read a file, and then write to it (overwriting any existing data), without closing and reopening:

with open(filename, "r+") as f:
    data = f.read()
    f.seek(0)
    f.write(output)
    f.truncate()

jQuery OR Selector?

Finally I've found hack how to do it:

div:not(:not(.classA,.classB)) > span

(selects div with class classA OR classB with direct child span)

How to add a second css class with a conditional value in razor MVC 4

This:

    <div class="details @(Model.Details.Count > 0 ? "show" : "hide")">

will render this:

    <div class="details hide">

and is the mark-up I want.

Mailx send html message

It's easy, if your mailx command supports the -a (append header) option:

$ mailx -a 'Content-Type: text/html' -s "my subject" [email protected] < email.html

If it doesn't, try using sendmail:

# create a header file
$ cat mailheader
To: [email protected]
Subject: my subject
Content-Type: text/html

# send
$ cat mailheader email.html | sendmail -t

Why are iframes considered dangerous and a security risk?

The IFRAME element may be a security risk if your site is embedded inside an IFRAME on hostile site. Google "clickjacking" for more details. Note that it does not matter if you use <iframe> or not. The only real protection from this attack is to add HTTP header X-Frame-Options: DENY and hope that the browser knows its job.

In addition, IFRAME element may be a security risk if any page on your site contains an XSS vulnerability which can be exploited. In that case the attacker can expand the XSS attack to any page within the same domain that can be persuaded to load within an <iframe> on the page with XSS vulnerability. This is because content from the same origin (same domain) is allowed to access the parent content DOM (practically execute JavaScript in the "host" document). The only real protection methods from this attack is to add HTTP header X-Frame-Options: DENY and/or always correctly encode all user submitted data (that is, never have an XSS vulnerability on your site - easier said than done).

That's the technical side of the issue. In addition, there's the issue of user interface. If you teach your users to trust that URL bar is supposed to not change when they click links (e.g. your site uses a big iframe with all the actual content), then the users will not notice anything in the future either in case of actual security vulnerability. For example, you could have an XSS vulnerability within your site that allows the attacker to load content from hostile source within your iframe. Nobody could tell the difference because the URL bar still looks identical to previous behavior (never changes) and the content "looks" valid even though it's from hostile domain requesting user credentials.

If somebody claims that using an <iframe> element on your site is dangerous and causes a security risk, he does not understand what <iframe> element does, or he is speaking about possibility of <iframe> related vulnerabilities in browsers. Security of <iframe src="..."> tag is equal to <img src="..." or <a href="..."> as long there are no vulnerabilities in the browser. And if there's a suitable vulnerability, it might be possible to trigger it even without using <iframe>, <img> or <a> element, so it's not worth considering for this issue.

However, be warned that content from <iframe> can initiate top level navigation by default. That is, content within the <iframe> is allowed to automatically open a link over current page location (the new location will be visible in the address bar). The only way to avoid that is to add sandbox attribute without value allow-top-navigation. For example, <iframe sandbox="allow-forms allow-scripts" ...>. Unfortunately, sandbox also disables all plugins, always. For example, Youtube content cannot be sandboxed because Flash player is still required to view all Youtube content. No browser supports using plugins and disallowing top level navigation at the same time.

Note that X-Frame-Options: DENY also protects from rendering performance side-channel attack that can read content cross-origin (also known as "Pixel perfect Timing Attacks").

CSS-moving text from left to right

Somehow I got it to work by using margin-right, and setting it to move from right to left. http://jsfiddle.net/gXdMc/

Don't know why for this case, margin-right 100% doesn't go off the screen. :D (tested on chrome 18)

EDIT: now left to right works too http://jsfiddle.net/6LhvL/

right click context menu for datagridview

Simply drag a ContextMenu or ContextMenuStrip component into your form and visually design it, then assign it to the ContextMenu or ContextMenuStrip property of your desired control.

How to run a script at the start up of Ubuntu?

First of all, the easiest way to run things at startup is to add them to the file /etc/rc.local.

Another simple way is to use @reboot in your crontab. Read the cron manpage for details.

However, if you want to do things properly, in addition to adding a script to /etc/init.d you need to tell ubuntu when the script should be run and with what parameters. This is done with the command update-rc.d which creates a symlink from some of the /etc/rc* directories to your script. So, you'd need to do something like:

update-rc.d yourscriptname start 2

However, real init scripts should be able to handle a variety of command line options and otherwise integrate to the startup process. The file /etc/init.d/README has some details and further pointers.

Get int value from enum in C#

Question question = Question.Role;
int value = (int) question;

Will result in value == 2.

postgresql: INSERT INTO ... (SELECT * ...)

As Henrik wrote you can use dblink to connect remote database and fetch result. For example:

psql dbtest
CREATE TABLE tblB (id serial, time integer);
INSERT INTO tblB (time) VALUES (5000), (2000);

psql postgres
CREATE TABLE tblA (id serial, time integer);

INSERT INTO tblA
    SELECT id, time 
    FROM dblink('dbname=dbtest', 'SELECT id, time FROM tblB')
    AS t(id integer, time integer)
    WHERE time > 1000;

TABLE tblA;
 id | time 
----+------
  1 | 5000
  2 | 2000
(2 rows)

PostgreSQL has record pseudo-type (only for function's argument or result type), which allows you query data from another (unknown) table.

Edit:

You can make it as prepared statement if you want and it works as well:

PREPARE migrate_data (integer) AS
INSERT INTO tblA
    SELECT id, time
    FROM dblink('dbname=dbtest', 'SELECT id, time FROM tblB')
    AS t(id integer, time integer)
    WHERE time > $1;

EXECUTE migrate_data(1000);
-- DEALLOCATE migrate_data;

Edit (yeah, another):

I just saw your revised question (closed as duplicate, or just very similar to this).

If my understanding is correct (postgres has tbla and dbtest has tblb and you want remote insert with local select, not remote select with local insert as above):

psql dbtest

SELECT dblink_exec
(
    'dbname=postgres',
    'INSERT INTO tbla
        SELECT id, time
        FROM dblink
        (
            ''dbname=dbtest'',
            ''SELECT id, time FROM tblb''
        )
        AS t(id integer, time integer)
        WHERE time > 1000;'
);

I don't like that nested dblink, but AFAIK I can't reference to tblB in dblink_exec body. Use LIMIT to specify top 20 rows, but I think you need to sort them using ORDER BY clause first.

SQL how to check that two tables has exactly the same data?

I had this same issue in SQL Server and wrote this T-SQL script to automate the process (actually this is the watered-down version, mine wrote all the diff to a single table for easy reporting).

Update 'MyTable' and 'MyOtherTable' to the names of the tables you wish to compare.

DECLARE @ColName varchar(100)
DECLARE @Table1 varchar(100) = 'MyTable'
DECLARE @Table2 varchar(100) = 'MyOtherTable'


IF (OBJECT_ID('tempdb..#col') IS NOT NULL) DROP TABLE #col
SELECT  IDENTITY(INT, 1, 1) RowNum , c.name
INTO    #col
FROM    SYS.Objects o 
        JOIN SYS.columns c on o.object_id = c.object_id
WHERE   o.name = @Table1 AND NOT c.Name IN ('List','Columns','YouWantToIgnore')

DECLARE @Counter INT = (SELECT MAX(RowNum) FROM #col)

    WHILE @Counter > 0

        BEGIN
            SET @ColName = (SELECT name FROM #Col WHERE RowNum= @Counter)
                EXEC ('SELECT  t1.Identifier
                        ,t1.'+@ColName+' AS '+@Table1+@ColName+'
                        ,t2.'+@ColName+' AS '+@Table2+@ColName+'
                FROM    '+@Table1+' t1
                        LEFT JOIN '+@Table2+' t2 ON t1.Identifier = t2.Identifier 
                WHERE   t1.'+@ColName+' <> t2.'+@ColName)
            SET @Counter = @Counter - 1 
        END

How to initialize an array in Kotlin with values?

intialize array in this way : val paramValueList : Array<String?> = arrayOfNulls<String>(5)

C++ Matrix Class

For a matrix class, you want to stay away from overloading the [] operator.
See C++ FAQ 13.10

Also, search the web for some freeware Matrix classes. Worst case, they can give you guidance. Best case, less software that you have to write and debug.

updating nodejs on ubuntu 16.04

Try this:

Edit or create the file :nodesource.list

sudo gedit /etc/apt/sources.list.d/nodesource.list

Insert this text:

deb https://deb.nodesource.com/node_10.x bionic main

deb-src https://deb.nodesource.com/node_10.x bionic main

Run these commands:

curl -s https://deb.nodesource.com/gpgkey/nodesource.gpg.key | apt-key add -


sudo sh -c "echo deb https://deb.nodesource.com/node_10.x cosmic main /etc/apt/sources.list.d/nodesource.list"

sudo apt-get update

sudo apt-get install nodejs

Eclipse reported "Failed to load JNI shared library"

First, ensure that your version of Eclipse and JDK match, either both 64-bit or both 32-bit (you can't mix-and-match 32-bit with 64-bit).

Second, the -vm argument in eclipse.ini should point to the java executable. See http://wiki.eclipse.org/Eclipse.ini for examples.

If you're unsure of what version (64-bit or 32-bit) of Eclipse you have installed, you can determine that a few different ways. See How to find out if an installed Eclipse is 32 or 64 bit version?

Using SimpleXML to create an XML object from scratch

Sure you can. Eg.

<?php
$newsXML = new SimpleXMLElement("<news></news>");
$newsXML->addAttribute('newsPagePrefix', 'value goes here');
$newsIntro = $newsXML->addChild('content');
$newsIntro->addAttribute('type', 'latest');
Header('Content-type: text/xml');
echo $newsXML->asXML();
?>

Output

<?xml version="1.0"?>
<news newsPagePrefix="value goes here">
    <content type="latest"/>
</news>

Have fun.

React / JSX Dynamic Component Name

Suspose we wish to access various views with dynamic component loading.The following code gives a working example of how to accomplish this by using a string parsed from the search string of a url.

Lets assume we want to access a page 'snozberrys' with two unique views using these url paths:

'http://localhost:3000/snozberrys?aComponent'

and

'http://localhost:3000/snozberrys?bComponent'

we define our view's controller like this:

import React, { Component } from 'react';
import ReactDOM from 'react-dom'
import {
  BrowserRouter as Router,
  Route
} from 'react-router-dom'
import AComponent from './AComponent.js';
import CoBComponent sole from './BComponent.js';

const views = {
  aComponent: <AComponent />,
  console: <BComponent />
}

const View = (props) => {
  let name = props.location.search.substr(1);
  let view = views[name];
  if(view == null) throw "View '" + name + "' is undefined";
  return view;
}

class ViewManager extends Component {
  render() {
    return (
      <Router>
        <div>
          <Route path='/' component={View}/>
        </div>
      </Router>
    );
  }
}

export default ViewManager

ReactDOM.render(<ViewManager />, document.getElementById('root'));

PHP syntax question: What does the question mark and colon mean?

This is the PHP ternary operator (also known as a conditional operator) - if first operand evaluates true, evaluate as second operand, else evaluate as third operand.

Think of it as an "if" statement you can use in expressions. Can be very useful in making concise assignments that depend on some condition, e.g.

$param = isset($_GET['param']) ? $_GET['param'] : 'default';

There's also a shorthand version of this (in PHP 5.3 onwards). You can leave out the middle operand. The operator will evaluate as the first operand if it true, and the third operand otherwise. For example:

$result = $x ?: 'default';

It is worth mentioning that the above code when using i.e. $_GET or $_POST variable will throw undefined index notice and to prevent that we need to use a longer version, with isset or a null coalescing operator which is introduced in PHP7:

$param = $_GET['param'] ?? 'default';

gson throws MalformedJsonException

In the debugger you don't need to add back slashes, the input field understands the special chars.

In java code you need to escape the special chars

How to set text color in submit button?

.btn{
    font-size: 20px;
    color:black;
}

Inline list initialization in VB.NET

Use this syntax for VB.NET 2005/2008 compatibility:

Dim theVar As New List(Of String)(New String() {"one", "two", "three"})

Although the VB.NET 2010 syntax is prettier.

Python: How to get values of an array at certain index positions?

You can use index arrays, simply pass your ind_pos as an index argument as below:

a = np.array([0,88,26,3,48,85,65,16,97,83,91])
ind_pos = np.array([1,5,7])

print(a[ind_pos])
# [88,85,16]

Index arrays do not necessarily have to be numpy arrays, they can be also be lists or any sequence-like object (though not tuples).

Is gcc's __attribute__((packed)) / #pragma pack unsafe?

(The following is a very artificial example cooked up to illustrate.) One major use of packed structs is where you have a stream of data (say 256 bytes) to which you wish to supply meaning. If I take a smaller example, suppose I have a program running on my Arduino which sends via serial a packet of 16 bytes which have the following meaning:

0: message type (1 byte)
1: target address, MSB
2: target address, LSB
3: data (chars)
...
F: checksum (1 byte)

Then I can declare something like

typedef struct {
  uint8_t msgType;
  uint16_t targetAddr; // may have to bswap
  uint8_t data[12];
  uint8_t checksum;
} __attribute__((packed)) myStruct;

and then I can refer to the targetAddr bytes via aStruct.targetAddr rather than fiddling with pointer arithmetic.

Now with alignment stuff happening, taking a void* pointer in memory to the received data and casting it to a myStruct* will not work unless the compiler treats the struct as packed (that is, it stores data in the order specified and uses exactly 16 bytes for this example). There are performance penalties for unaligned reads, so using packed structs for data your program is actively working with is not necessarily a good idea. But when your program is supplied with a list of bytes, packed structs make it easier to write programs which access the contents.

Otherwise you end up using C++ and writing a class with accessor methods and stuff that does pointer arithmetic behind the scenes. In short, packed structs are for dealing efficiently with packed data, and packed data may be what your program is given to work with. For the most part, you code should read values out of the structure, work with them, and write them back when done. All else should be done outside the packed structure. Part of the problem is the low level stuff that C tries to hide from the programmer, and the hoop jumping that is needed if such things really do matter to the programmer. (You almost need a different 'data layout' construct in the language so that you can say 'this thing is 48 bytes long, foo refers to the data 13 bytes in, and should be interpreted thus'; and a separate structured data construct, where you say 'I want a structure containing two ints, called alice and bob, and a float called carol, and I don't care how you implement it' -- in C both these use cases are shoehorned into the struct construct.)

How can I resolve "Your requirements could not be resolved to an installable set of packages" error?

Run this command:

composer install --ignore-platform-reqs

or

composer update --ignore-platform-reqs

Can not get a simple bootstrap modal to work

Try skipping the p tag or replace it with a h3 tag or similar. Replace:

<p>One fine body…</p>

with

<h3>One fine body…</h3>

It worked for me, I don't know why, but it seems the p tag is somehow not fully compatible with some versions of Bootstrap.

How to convert datetime format to date format in crystal report using C#?

In selection formula try this

Date(Year({datetimefield}), Month({datetimefield}), Day({datetimefield}))

Python: Convert timedelta to int in a dataframe

Timedelta objects have read-only instance attributes .days, .seconds, and .microseconds.

Regex: Use start of line/end of line signs (^ or $) in different context

you just need to use word boundary (\b) instead of ^ and $:

\bgarp\b

Update multiple columns in SQL

I did this in MySql and it updated multiple columns in a single record, so try this if you are using MySql as your server:

"UPDATE creditor_tb SET credit_amount='" & CDbl(cur_amount) & "'
                   , totalamount_to_pay='" & current_total & "',   
        WHERE credit_id='" & lbcreditId.Text & "'". 

However, I was coding in vb.net using MySql server, but you can take it to your favorite programming language as far as you are using MySql as your server.

Is calculating an MD5 hash less CPU intensive than SHA family functions?

The real answer is : It depends

There are a couple factors to consider, the most obvious are : the cpu you are running these algorithms on and the implementation of the algorithms.

For instance, me and my friend both run the exact same openssl version and get slightly different results with different Intel Core i7 cpus.

My test at work with an Intel(R) Core(TM) i7-2600 CPU @ 3.40GHz

The 'numbers' are in 1000s of bytes per second processed.
type             16 bytes     64 bytes    256 bytes   1024 bytes   8192 bytes
md5              64257.97k   187370.26k   406435.07k   576544.43k   649827.67k
sha1             73225.75k   202701.20k   432679.68k   601140.57k   679900.50k

And his with an Intel(R) Core(TM) i7 CPU 920 @ 2.67GHz

The 'numbers' are in 1000s of bytes per second processed.
type             16 bytes     64 bytes    256 bytes   1024 bytes   8192 bytes
md5              51859.12k   156255.78k   350252.00k   513141.73k   590701.52k
sha1             56492.56k   156300.76k   328688.76k   452450.92k   508625.68k

We both are running the exact same binaries of OpenSSL 1.0.1j 15 Oct 2014 from the ArchLinux official package.

My opinion on this is that with the added security of sha1, cpu designers are more likely to improve the speed of sha1 and more programmers will be working on the algorithm's optimization than md5sum.

I guess that md5 will no longer be used some day since it seems that it has no advantage over sha1. I also tested some cases on real files and the results were always the same in both cases (likely limited by disk I/O).

md5sum of a large 4.6GB file took the exact same time than sha1sum of the same file, same goes with many small files (488 in the same directory). I ran the tests a dozen times and they were consitently getting the same results.

--

It would be very interesting to investigate this further. I guess there are some experts around that could provide a solid answer to why sha1 is getting faster than md5 on newer processors.

C# How to change font of a label

You need to create a new Font

mainForm.lblName.Font = new Font("Arial", mainForm.lblName.Font.Size);

Cannot create PoolableConnectionFactory

I had a similar error. Changing the JDBC URL to use 127.0.0.1 instead of localhost helped.

Also had tried changing entries in catalina.policy file but that did not help. The entry I changed was for - java.net.SocketPermission

JUnit assertEquals(double expected, double actual, double epsilon)

Epsilon is your "fuzz factor," since doubles may not be exactly equal. Epsilon lets you describe how close they have to be.

If you were expecting 3.14159 but would take anywhere from 3.14059 to 3.14259 (that is, within 0.001), then you should write something like

double myPi = 22.0d / 7.0d; //Don't use this in real life!
assertEquals(3.14159, myPi, 0.001);

(By the way, 22/7 comes out to 3.1428+, and would fail the assertion. This is a good thing.)

How to run a C# application at Windows startup?

its very simple

add two part in code :

1- add namespace:

using Microsoft.Win32;

2-add application to registery :

RegistryKey key=Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
key.SetValue("your_app_name", Application.ExecutablePath);

if you want delete app from registery:

key.DeleteValue("your_app_name",false);

Center text in table cell

I would recommend using CSS for this. You should create a CSS rule to enforce the centering, for example:

.ui-helper-center {
    text-align: center;
}

And then add the ui-helper-center class to the table cells for which you wish to control the alignment:

<td class="ui-helper-center">Content</td>

EDIT: Since this answer was accepted, I felt obligated to edit out the parts that caused a flame-war in the comments, and to not promote poor and outdated practices.

See Gabe's answer for how to include the CSS rule into your page.

How do I use Join-Path to combine more than two strings into a file path?

Since Join-Path can be piped a path value, you can pipe multiple Join-Path statements together:

Join-Path "C:" -ChildPath "Windows" | Join-Path -ChildPath "system32" | Join-Path -ChildPath "drivers"

It's not as terse as you would probably like it to be, but it's fully PowerShell and is relatively easy to read.

Convert ArrayList<String> to String[] array

What is happening is that stock_list.toArray() is creating an Object[] rather than a String[] and hence the typecast is failing1.

The correct code would be:

  String [] stockArr = stockList.toArray(new String[stockList.size()]);

or even

  String [] stockArr = stockList.toArray(new String[0]);

For more details, refer to the javadocs for the two overloads of List.toArray.

The latter version uses the zero-length array to determine the type of the result array. (Surprisingly, it is faster to do this than to preallocate ... at least, for recent Java releases. See https://stackoverflow.com/a/4042464/139985 for details.)

From a technical perspective, the reason for this API behavior / design is that an implementation of the List<T>.toArray() method has no information of what the <T> is at runtime. All it knows is that the raw element type is Object. By contrast, in the other case, the array parameter gives the base type of the array. (If the supplied array is big enough to hold the list elements, it is used. Otherwise a new array of the same type and a larger size is allocated and returned as the result.)


1 - In Java, an Object[] is not assignment compatible with a String[]. If it was, then you could do this:

    Object[] objects = new Object[]{new Cat("fluffy")};
    Dog[] dogs = (Dog[]) objects;
    Dog d = dogs[0];     // Huh???

This is clearly nonsense, and that is why array types are not generally assignment compatible.

Error in styles_base.xml file - android app - No resource found that matches the given name 'android:Widget.Material.ActionButton'

Download the latest "sdk platform" and "sdk build tools" of same version like 23.* for 
both from "sdk Managar".

(for reference see above hosted image from back track). Then right click on your project -> properties -> Android -> in "project build properties" select "API level" 23 or the latest one which you updated. Then clean your project once.

Note: But all three should be in same version.

How does one extract each folder name from a path?

Realise this is an old post, but I came across it looking - in the end I decided apon the below function as it sorted what I was doing at the time better than any of the above:

private static List<DirectoryInfo> SplitDirectory(DirectoryInfo parent)
{
    if (parent == null) return null;
    var rtn = new List<DirectoryInfo>();
    var di = parent;

    while (di.Name != di.Root.Name)
    {
    rtn.Add(new DirectoryInfo(di));
    di = di.Parent;
    }
    rtn.Add(new DirectoryInfo(di.Root));

    rtn.Reverse();
    return rtn;
}

Angular2 multiple router-outlet in the same template

You can not use multiple router outlets in the same template with ngIf condition. But you can use it in the way shown below:

<div *ngIf="loading">
  <span>loading true</span>
  <ng-container *ngTemplateOutlet="template"></ng-container>
</div>

<div *ngIf="!loading">
  <span>loading false</span>
  <ng-container *ngTemplateOutlet="template"></ng-container>
  </div>

  <ng-template #template>
    <router-outlet> </router-outlet>
  </ng-template>

Express: How to pass app-instance to routes from a different file?

Node.js supports circular dependencies.
Making use of circular dependencies instead of require('./routes')(app) cleans up a lot of code and makes each module less interdependent on its loading file:


app.js

var app = module.exports = express(); //now app.js can be required to bring app into any file

//some app/middleware setup, etc, including 
app.use(app.router);

require('./routes'); //module.exports must be defined before this line


routes/index.js

var app = require('../app');

app.get('/', function(req, res, next) {
  res.render('index');
});

//require in some other route files...each of which requires app independently
require('./user');
require('./blog');


-----04/2014 update-----
Express 4.0 fixed the usecase for defining routes by adding an express.router() method!
documentation - http://expressjs.com/4x/api.html#router

Example from their new generator:
Writing the route:
https://github.com/expressjs/generator/blob/master/templates/js/routes/index.js
Adding/namespacing it to the app: https://github.com/expressjs/generator/blob/master/templates/js/app.js#L24

There are still usecases for accessing app from other resources, so circular dependencies are still a valid solution.

Add item to Listview control

The first column actually refers to Text Field:

  // Add the pet to our listview
    ListViewItem lvi = new ListViewItem();
    lvi.text = pet.Name;
    lvi.SubItems.Add(pet.Type);
    lvi.SubItems.Add(pet.Age);

    listView.Items.Add(lvi);

Or you can use the Constructor

 ListViewItem lvi = new ListViewItem(pet.Name);
 lvi.SubItems.Add(pet.Type);
 ....

Apply CSS Style to child elements

This code "div.test th, td, caption {padding:40px 100px 40px 50px;}" applies a rule to all th elements which are contained by a div element with a class named test, in addition to all td elements and all caption elements.

It is not the same as "all td, th and caption elements which are contained by a div element with a class of test". To accomplish that you need to change your selectors:

'>' isn't fully supported by some older browsers (I'm looking at you, Internet Explorer).

div.test th,
div.test td,
div.test caption {
    padding: 40px 100px 40px 50px;
}

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

That query is failing and returning false.

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

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

For more information:

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

xampp MySQL does not start

Same issue on macOS and got it fixed by running the same installer again.

Whereas I COULD NOT get it fixed by

  1. Changing port
  2. Rebooting XAMPP
  3. Restarting system

Note: Make sure to select 'XAMPP Core Files' component while running the installer as by default it is not selected.

Though re-running the installer is not smart option when one has to do it every now and then. My installer is xampp-osx-7.0.13-1-installer.dmg

Update: I've got my MAMP working with this simple solution here. So, same should work for XAMPP.

how to use math.pi in java

Here is usage of Math.PI to find circumference of circle and Area First we take Radius as a string in Message Box and convert it into integer

public class circle {

    public static void main(String[] args) {
        // TODO code application logic here

        String rad;

        float radius,area,circum;

       rad = JOptionPane.showInputDialog("Enter the Radius of circle:");

        radius = Integer.parseInt(rad);
        area = (float) (Math.PI*radius*radius);
        circum = (float) (2*Math.PI*radius);

        JOptionPane.showMessageDialog(null, "Area: " + area,"AREA",JOptionPane.INFORMATION_MESSAGE);
        JOptionPane.showMessageDialog(null, "circumference: " + circum, "Circumfernce",JOptionPane.INFORMATION_MESSAGE);
    }

}

How can I get the MAC and the IP address of a connected client in PHP?

// Turn on output buffering  
ob_start();  

//Get the ipconfig details using system commond  
system('ipconfig /all');  

// Capture the output into a variable  
$mycomsys=ob_get_contents();  

// Clean (erase) the output buffer  
ob_clean();  

$find_mac = "Physical"; 
//find the "Physical" & Find the position of Physical text  

$pmac = strpos($mycomsys, $find_mac);  
// Get Physical Address  

$macaddress=substr($mycomsys,($pmac+36),17);  
//Display Mac Address  

echo $macaddress;  

This works for me on Windows, as ipconfig /all is Windows system command.

IIS: Display all sites and bindings in PowerShell

I found this question because I wanted to generate a web page with links to all the websites running on my IIS instance. I used Alexander Shapkin's answer to come up with the following to generate a bunch of links.

$hostname = "localhost"

Foreach ($Site in get-website) {
    Foreach ($Bind in $Site.bindings.collection) {
        $data = [PSCustomObject]@{
            name=$Site.name;
            Protocol=$Bind.Protocol;
            Bindings=$Bind.BindingInformation
        }
        $data.Bindings = $data.Bindings -replace '(:$)', ''
        $html = "<a href=""" + $data.Protocol + "://" + $data.Bindings + """>" + $data.name + "</a>"
        $html.Replace("*", $hostname);
    }
}

Then I paste the results into this hastily written HTML:

<html>
<style>
    a { display: block; }
</style>
{paste PowerShell results here}
</body>
</html>

How to find where gem files are installed

To complete other answers, the gem-path gem can find the installation path of a particular gem.

Installation:

gem install gem-path

Usage:

gem path rails
=> /home/cbliard/.rvm/gems/ruby-2.1.5/gems/rails-4.0.13
gem path rails '< 4'
=> /home/cbliard/.rvm/gems/ruby-2.1.5/gems/rails-3.2.21

This is really handy as you can use it to grep or edit files:

grep -R 'Internal server error' "$(gem path thin)"
subl "$(gem path thin)"

How to cast an Object to an int

If you're sure that this object is an Integer :

int i = (Integer) object;

Or, starting from Java 7, you can equivalently write:

int i = (int) object;

Beware, it can throw a ClassCastException if your object isn't an Integer and a NullPointerException if your object is null.

This way you assume that your Object is an Integer (the wrapped int) and you unbox it into an int.

int is a primitive so it can't be stored as an Object, the only way is to have an int considered/boxed as an Integer then stored as an Object.


If your object is a String, then you can use the Integer.valueOf() method to convert it into a simple int :

int i = Integer.valueOf((String) object);

It can throw a NumberFormatException if your object isn't really a String with an integer as content.


Resources :

On the same topic :

ValueError: cannot reshape array of size 30470400 into shape (50,1104,104)

In Matrix terms, the number of elements always has to equal the product of the number of rows and columns. In this particular case, the condition is not matching.

Microsoft Excel ActiveX Controls Disabled?

I want to provide an answer that worked as the only thing for me (I realize that I might be the only one ever). I had in one macro that I was calling using the ribbon. It had the following code:

colStore = new Collection

I wasn't aware that it throws an error so I was baffled and tried everything in here. The button just stopped working and I couldn't get it to work. When I noticed the error and corrected it to:

Set colStore = new Collection

It started working again. Absolutely strange if you ask me but maybe it helps someone out there who was as desperate as me.

How to set input type date's default value to today?

Very Simple, Just use server side languages like PHP,ASP,JAVA or even you can use javascript.

Here is the solution

<?php
  $timezone = "Asia/Colombo";
  date_default_timezone_set($timezone);
  $today = date("Y-m-d");
?>
<html>
  <body>
    <input type="date" value="<?php echo $today; ?>">
  </body>
</html>

How to loop through key/value object in Javascript?

Beware of properties inherited from the object's prototype (which could happen if you're including any libraries on your page, such as older versions of Prototype). You can check for this by using the object's hasOwnProperty() method. This is generally a good idea when using for...in loops:

var user = {};

function setUsers(data) {
    for (var k in data) {
        if (data.hasOwnProperty(k)) {
           user[k] = data[k];
        }
    }
}

Query Mongodb on month, day, year... of a datetime

You can find record by month, day, year etc of dates by Date Aggregation Operators, like $dayOfYear, $dayOfWeek, $month, $year etc.

As an example if you want all the orders which are created in April 2016 you can use below query.

db.getCollection('orders').aggregate(
   [
     {
       $project:
         {
           doc: "$$ROOT",
           year: { $year: "$created" },
           month: { $month: "$created" },
           day: { $dayOfMonth: "$created" }
         }
     },
     { $match : { "month" : 4, "year": 2016 } }
   ]
)

Here created is a date type field in documents, and $$ROOT we used to pass all other field to project in next stage, and give us all the detail of documents.

You can optimize above query as per your need, it is just to give an example. To know more about Date Aggregation Operators, visit the link.

How do I check if string contains substring?

You can also check if the exact word is contained in a string. E.g.:

function containsWord(haystack, needle) {
    return (" " + haystack + " ").indexOf(" " + needle + " ") !== -1;
}

Usage:

containsWord("red green blue", "red"); // true
containsWord("red green blue", "green"); // true
containsWord("red green blue", "blue"); // true
containsWord("red green blue", "yellow"); // false

This is how jQuery does its hasClass method.

Hive cast string to date dd-MM-yyyy

AFAIK you must reformat your String in ISO format to be able to cast it as a Date:

cast(concat(substr(STR_DMY,7,4), '-',
            substr(STR_DMY,1,2), '-',
            substr(STR_DMY,4,2)
           )
     as date
     ) as DT

To display a Date as a String with specific format, then it's the other way around, unless you have Hive 1.2+ and can use date_format()

=> did you check the documentation by the way?

can you add HTTPS functionality to a python flask web server?

The top-scoring answer has the right idea, but the API seems to have evolved so that it no longer works as when it was first written, in 2015.

In place of this:

from OpenSSL import SSL
context = SSL.Context(SSL.PROTOCOL_TLSv1_2)
context.use_privatekey_file('server.key')
context.use_certificate_file('server.crt')

I used this, with Python 3.7.5:

import ssl
context = ssl.SSLContext()
context.load_cert_chain('fullchain.pem', 'privkey.pem')

and then supplied the SSL context in the Flask.run call as it said:

app.run(…, ssl_context=context)

(My server.crt file is called fullchain.pem and my server.key is called privkey.pem. These files were supplied to me by my LetsEncrypt Certbot.)

Checking for empty or null List<string>

An easy way to combine myList == null || myList.Count == 0 would be to use the null coalescing operator ??:

if ((myList?.Count ?? 0) == 0) {
    //My list is null or empty
}

AND/OR in Python?

Are you looking for...

a if b else c

Or perhaps you misunderstand Python's or? True or True is True.

Activity <App Name> has leaked ServiceConnection <ServiceConnection Name>@438030a8 that was originally bound here

You mention the user switching between Activities pretty quickly. Could it be that you're calling unbindService before the service connection has been established? This may have the effect of failing to unbind, then leaking the binding.

Not entirely sure how you could handle this... Perhaps when onServiceConnected is called you could call unbindService if onDestroy has already been called. Not sure if that'll work though.


If you haven't already, you could add an onUnbind method to your service. That way you can see exactly when your classes unbind from it, and it might help with debugging.

@Override
public boolean onUnbind(Intent intent) {
    Log.d(this.getClass().getName(), "UNBIND");
    return true;
}

.htaccess - how to force "www." in a generic way?

The following should prefix 'www' to any request that doesn't have one, and redirect the edited request to the new URI.

RewriteCond "%{HTTP_HOST}" "!^www\."         [NC]
RewriteCond "%{HTTP_HOST}" "(.*)"
RewriteRule "(.*)"         "http://www.%1$1" [R=301,L]

How to reduce a huge excel file

I have worked extensively in Excel and have found the following 3 points very useful

Find if there are cells which apparently do not hold any data but Excel considers them to have data

You can find this by using the following property on a sheet

ActiveSheet.UsedRange.Rows.Count
ActiveSheet.UsedRange.Columns.Count

If this range is more than the cells on which you have data, delete the rest of the rows/columns

You will be surprised to see the amount of space it can free

Convert files to .xlsb format

XLSM format is to make Excel compliant with Open XML, but there are very few instances when we actually use the XML format of Excel. This reduces size by almost 50% if not more

Optimum way of storing information

For example if you have to save the stock price for around 10 years, and you need to save Open, High, Low, Close for a stock, this would result in (252*10) * (4) cells being used

Instead, of using separate columns for Open,High,Low,Close save them in a single column with a field separator Open:High:Low:Close

You can easily write a function to extract info from the single column whenever you want to, but it will free up almost 2/3rd space that you are currently taking up

What is this weird colon-member (" : ") syntax in the constructor?

Foo(int num): bar(num)    

This construct is called a Member Initializer List in C++.

Simply said, it initializes your member bar to a value num.


What is the difference between Initializing and Assignment inside a constructor?

Member Initialization:

Foo(int num): bar(num) {};

Member Assignment:

Foo(int num)
{
   bar = num;
}

There is a significant difference between Initializing a member using Member initializer list and assigning it an value inside the constructor body.

When you initialize fields via Member initializer list the constructors will be called once and the object will be constructed and initialized in one operation.

If you use assignment then the fields will be first initialized with default constructors and then reassigned (via assignment operator) with actual values.

As you see there is an additional overhead of creation & assignment in the latter, which might be considerable for user defined classes.

Cost of Member Initialization = Object Construction 
Cost of Member Assignment = Object Construction + Assignment

The latter is actually equivalent to:

Foo(int num) : bar() {bar = num;}

While the former is equivalent to just:

Foo(int num): bar(num){}

For an inbuilt (your code example) or POD class members there is no practical overhead.


When do you HAVE TO use Member Initializer list?

You will have(rather forced) to use a Member Initializer list if:

  • Your class has a reference member
  • Your class has a non static const member or
  • Your class member doesn't have a default constructor or
  • For initialization of base class members or
  • When constructor’s parameter name is same as data member(this is not really a MUST)

A code example:

class MyClass {
public:
  // Reference member, has to be Initialized in Member Initializer List
  int &i;
  int b;
  // Non static const member, must be Initialized in Member Initializer List
  const int k;

  // Constructor’s parameter name b is same as class data member
  // Other way is to use this->b to refer to data member
  MyClass(int a, int b, int c) : i(a), b(b), k(c) {
    // Without Member Initializer
    // this->b = b;
  }
};

class MyClass2 : public MyClass {
public:
  int p;
  int q;
  MyClass2(int x, int y, int z, int l, int m) : MyClass(x, y, z), p(l), q(m) {}
};

int main() {
  int x = 10;
  int y = 20;
  int z = 30;
  MyClass obj(x, y, z);

  int l = 40;
  int m = 50;
  MyClass2 obj2(x, y, z, l, m);

  return 0;
}
  • MyClass2 doesn't have a default constructor so it has to be initialized through member initializer list.
  • Base class MyClass does not have a default constructor, So to initialize its member one will need to use Member Initializer List.

Important points to Note while using Member Initializer Lists:

Class Member variables are always initialized in the order in which they are declared in the class.

They are not initialized in the order in which they are specified in the Member Initializer List.
In short, Member initialization list does not determine the order of initialization.

Given the above it is always a good practice to maintain the same order of members for Member initialization as the order in which they are declared in the class definition. This is because compilers do not warn if the two orders are different but a relatively new user might confuse member Initializer list as the order of initialization and write some code dependent on that.

Entity Framework Migrations renaming tables and columns

If you don't like writing/changing the required code in the Migration class manually, you can follow a two-step approach which automatically make the RenameColumn code which is required:

Step One Use the ColumnAttribute to introduce the new column name and then add-migration (e.g. Add-Migration ColumnChanged)

public class ReportPages
{
    [Column("Section_Id")]                 //Section_Id
    public int Group_Id{get;set}
}

Step-Two change the property name and again apply to same migration (e.g. Add-Migration ColumnChanged -force) in the Package Manager Console

public class ReportPages
{
    [Column("Section_Id")]                 //Section_Id
    public int Section_Id{get;set}
}

If you look at the Migration class you can see the automatically code generated is RenameColumn.

Fade In Fade Out Android Animation in Java

I really like Vitaly Zinchenkos solution since it was short.

Here is an even briefer version in kotlin for a simple fade out

viewToAnimate?.alpha = 1f
viewToAnimate?.animate()
             ?.alpha(0f)
             ?.setDuration(1000)
             ?.setInterpolator(DecelerateInterpolator())
             ?.start()

Setting dynamic scope variables in AngularJs - scope.<some_string>

Create Dynamic angular variables from results

angular.forEach(results, function (value, key) {          
  if (key != null) {                       
    $parse(key).assign($scope, value);                                
  }          
});

ps. don't forget to pass in the $parse attribute into your controller's function

How to find the minimum value of a column in R?

Since it is a numeric operation, we should be converting it to numeric form first. This operation cannot take place if the data is in factor data type.
Check the data type of the columns using str().

min(as.numeric(data[,2]))

CSS I want a div to be on top of everything

Yes, in order for the z-index to work, you'll need to give the element a position: absolute or a position: relative property.

But... pay attention to parents!

You have to go up the nodes of the elements to check if at the level of the common parent the first descendants have a defined z-index.

All other descendants can never be in the foreground if at the base there is a lower definite z-index.

In this snippet example, div1-2-1 has a z-index of 1000 but is nevertheless under the div1-1-1 which has a z-index of 3.

This is because div1-1 has a z-index greater than div1-2.

enter image description here

_x000D_
_x000D_
.div {
  
}

#div1 {
  z-index: 1;
  position: absolute;
  width: 500px;
  height: 300px;
  border: 1px solid black;
}

#div1-1 {
  z-index: 2;
  position: absolute;
  left: 230px;
  width: 200px;
  height: 200px;
  top: 31px;
  background-color: indianred;
}

#div1-1-1 {
  z-index: 3;
  position: absolute;
  top: 50px;
  width: 100px;
  height: 100px;
  background-color: burlywood;
}

#div1-2 {
  z-index: 1;
  position: absolute;
  width: 200px;
  height: 200px;
  left: 80px;
  top: 5px;
  background-color: red;
}

#div1-2-1 {
  z-index: 1000;
  position: absolute;
  left: 70px;
  width: 120px;
  height: 100px;
  top: 10px;
  color: red;
  background-color: lightyellow;
}

.blink {
  animation: blinker 1s linear infinite;
}

@keyframes blinker {
  50% {
    opacity: 0;
  }
}

.rotate {
  writing-mode: vertical-rl;
  padding-left: 50px;
  font-weight: bold;
  font-size: 20px;
}
_x000D_
<div class="div" id="div1">div1</br>z-index: 1
  <div class="div" id="div1-1">div1-1</br>z-index: 2
    <div class="div" id="div1-1-1">div1-1-1</br>z-index: 3</div>
  </div>
  
  <div class="div" id="div1-2">div1-2</br>z-index: 1</br><span class='rotate blink'><=</span>
    <div class="div" id="div1-2-1"><span class='blink'>z-index: 1000!!</span></br>div1-2-1</br><span class='blink'> because =></br>(same</br>   parent)</span></div>
  </div>
</div>
_x000D_
_x000D_
_x000D_

How to convert an IPv4 address into a integer in C#?

Multiply all the parts of the IP number by powers of 256 (256x256x256, 256x256, 256 and 1. For example:

IPv4 address : 127.0.0.1 32 bit number: = (127x256^3) + (0x256^2) + (0x256^1) + 1 = 2130706433

Roblox Admin Command Script

for i=1,#target do
    game.Players.target[i].Character:BreakJoints()
end

Is incorrect, if "target" contains "FakeNameHereSoNoStalkers" then the run code would be:

game.Players.target.1.Character:BreakJoints()

Which is completely incorrect.


c = game.Players:GetChildren()

Never use "Players:GetChildren()", it is not guaranteed to return only players.

Instead use:

c = Game.Players:GetPlayers()

if msg:lower()=="me" then
    table.insert(people, source)
    return people

Here you add the player's name in the list "people", where you in the other places adds the player object.


Fixed code:

local Admins = {"FakeNameHereSoNoStalkers"}

function Kill(Players)
    for i,Player in ipairs(Players) do
        if Player.Character then
            Player.Character:BreakJoints()
        end
    end
end

function IsAdmin(Player)
    for i,AdminName in ipairs(Admins) do
        if Player.Name:lower() == AdminName:lower() then return true end
    end
    return false
end

function GetPlayers(Player,Msg)
    local Targets = {}
    local Players = Game.Players:GetPlayers()

    if Msg:lower() == "me" then
        Targets = { Player }
    elseif Msg:lower() == "all" then
        Targets = Players
    elseif Msg:lower() == "others" then
        for i,Plr in ipairs(Players) do
            if Plr ~= Player then
                table.insert(Targets,Plr)
            end
        end
    else
        for i,Plr in ipairs(Players) do
            if Plr.Name:lower():sub(1,Msg:len()) == Msg then
                table.insert(Targets,Plr)
            end
        end
    end
    return Targets
end

Game.Players.PlayerAdded:connect(function(Player)
    if IsAdmin(Player) then
        Player.Chatted:connect(function(Msg)
            if Msg:lower():sub(1,6) == ":kill " then
                Kill(GetPlayers(Player,Msg:sub(7)))
            end
        end)
    end
end)

jquery - Click event not working for dynamically created button

You could also create the input button in this way:

var button = '<input type="button" id="questionButton" value='+variable+'> <br />';


It might be the syntax of the Button creation that is off somehow.

Understanding PIVOT function in T-SQL

    SELECT <non-pivoted column>,
    [first pivoted column] AS <column name>,
    [second pivoted column] AS <column name>,
    ...
    [last pivoted column] AS <column name>
FROM
    (<SELECT query that produces the data>)
    AS <alias for the source query>
PIVOT
(
    <aggregation function>(<column being aggregated>)
FOR
[<column that contains the values that will become column headers>]
    IN ( [first pivoted column], [second pivoted column],
    ... [last pivoted column])
) AS <alias for the pivot table>
<optional ORDER BY clause>;

USE AdventureWorks2008R2 ;
GO
SELECT DaysToManufacture, AVG(StandardCost) AS AverageCost 
FROM Production.Product
GROUP BY DaysToManufacture;

    DaysToManufacture          AverageCost
0                          5.0885
1                          223.88
2                          359.1082
4                          949.4105

    -- Pivot table with one row and five columns
SELECT 'AverageCost' AS Cost_Sorted_By_Production_Days, 
[0], [1], [2], [3], [4]
FROM
(SELECT DaysToManufacture, StandardCost 
    FROM Production.Product) AS SourceTable
PIVOT
(
AVG(StandardCost)
FOR DaysToManufacture IN ([0], [1], [2], [3], [4])
) AS PivotTable;




Here is the result set.
Cost_Sorted_By_Production_Days    0         1         2           3       4       
AverageCost                       5.0885    223.88    359.1082    NULL    949.4105

Making a PowerShell POST request if a body param starts with '@'

@Frode F. gave the right answer.

By the Way Invoke-WebRequest also prints you the 200 OK and a lot of bla, bla, bla... which might be useful but I still prefer the Invoke-RestMethod which is lighter.

Also, keep in mind that you need to use | ConvertTo-Json for the body only, not the header:

$body = @{
 "UserSessionId"="12345678"
 "OptionalEmail"="[email protected]"
} | ConvertTo-Json

$header = @{
 "Accept"="application/json"
 "connectapitoken"="97fe6ab5b1a640909551e36a071ce9ed"
 "Content-Type"="application/json"
} 

Invoke-RestMethod -Uri "http://MyServer/WSVistaWebClient/RESTService.svc/member/search" -Method 'Post' -Body $body -Headers $header | ConvertTo-HTML

and you can then append a | ConvertTo-HTML at the end of the request for better readability

How to find topmost view controller on iOS

@implementation UIWindow (Extensions)

- (UIViewController*) topMostController
{
    UIViewController *topController = [self rootViewController];

    while (topController.presentedViewController) {
        topController = topController.presentedViewController;
    }

    return topController;
}

@end

Dart/Flutter : Converting timestamp

How to implement:

import 'package:intl/intl.dart';

getCustomFormattedDateTime(String givenDateTime, String dateFormat) {
    // dateFormat = 'MM/dd/yy';
    final DateTime docDateTime = DateTime.parse(givenDateTime);
    return DateFormat(dateFormat).format(docDateTime);
}

How to call:

getCustomFormattedDateTime('2021-02-15T18:42:49.608466Z', 'MM/dd/yy');

Result:

02/15/21

Above code solved my problem. I hope, this will also help you. Thanks for asking this question.

Is there a way to programmatically scroll a scroll view to a specific edit text?

Que:Is there a way to programmatically scroll a scroll view to a specific edittext?

Ans:Nested scroll view in recyclerview last position added record data.

adapter.notifyDataSetChanged();
nested_scroll.setScrollY(more Detail Recycler.getBottom());

Is there a way to programmatically scroll a scroll view to a specific edit text?

Losing scope when using ng-include

As @Renan mentioned, ng-include creates a new child scope. This scope prototypically inherits (see dashed lines below) from the HomeCtrl scope. ng-model="lineText" actually creates a primitive scope property on the child scope, not HomeCtrl's scope. This child scope is not accessible to the parent/HomeCtrl scope:

ng-include scope

To store what the user typed into HomeCtrl's $scope.lines array, I suggest you pass the value to the addLine function:

 <form ng-submit="addLine(lineText)">

In addition, since lineText is owned by the ngInclude scope/partial, I feel it should be responsible for clearing it:

 <form ng-submit="addLine(lineText); lineText=''">

Function addLine() would thus become:

$scope.addLine = function(lineText) {
    $scope.chat.addLine(lineText);
    $scope.lines.push({
        text: lineText
    });
};

Fiddle.

Alternatives:

  • define an object property on HomeCtrl's $scope, and use that in the partial: ng-model="someObj.lineText; fiddle
  • not recommended, this is more of a hack: use $parent in the partial to create/access a lineText property on the HomeCtrl $scope:  ng-model="$parent.lineText"; fiddle

It is a bit involved to explain why the above two alternatives work, but it is fully explained here: What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

I don't recommend using this in the addLine() function. It becomes much less clear which scope is being accessed/manipulated.

How to build a Horizontal ListView with RecyclerView?

If you wish to use the Horizontal Recycler View to act as a ViewPager then it's possible now with the help of LinearSnapHelper which is added in Support Library version 24.2.0.

Firstly Add RecyclerView to your Activity/Fragment

<android.support.v7.widget.RecyclerView
        android:layout_below="@+id/sign_in_button"
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:id="@+id/blog_list"
        android:layout_height="match_parent">
    </android.support.v7.widget.RecyclerView>

In my case I have used a CardView inside the RecyclerView

blog_row.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView 

    xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_margin="15dp"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:orientation="vertical">

            <com.android.volley.toolbox.NetworkImageView
                android:id="@+id/imageBlogPost"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:adjustViewBounds="true"
                android:paddingBottom="15dp"
                android:src="@drawable/common_google_signin_btn_text_light_normal" />

            <TextView
                android:id="@+id/TitleTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
               android:layout_marginBottom="20dp"

                android:text="Post Title Here"
                android:textSize="16sp" />

            <TextView
                android:id="@+id/descriptionTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Post Description Here"
                android:paddingBottom="15dp"
                android:textSize="14sp" />
        </LinearLayout>

    </android.support.v7.widget.CardView>

In your Activity/Fragment

    private RecyclerView mBlogList;




 LinearLayoutManager layoutManager
                    = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
            mBlogList = (RecyclerView) findViewById(R.id.blog_list);

            mBlogList.setHasFixedSize(true);
            mBlogList.setLayoutManager(layoutManager);

LinearSnapHelper snapHelper = new LinearSnapHelper() {
            @Override
            public int findTargetSnapPosition(RecyclerView.LayoutManager lm, int velocityX, int velocityY) {
                View centerView = findSnapView(lm);
                if (centerView == null)
                    return RecyclerView.NO_POSITION;

                int position = lm.getPosition(centerView);
                int targetPosition = -1;
                if (lm.canScrollHorizontally()) {
                    if (velocityX < 0) {
                        targetPosition = position - 1;
                    } else {
                        targetPosition = position + 1;
                    }
                }

                if (lm.canScrollVertically()) {
                    if (velocityY < 0) {
                        targetPosition = position - 1;
                    } else {
                        targetPosition = position + 1;
                    }
                }

                final int firstItem = 0;
                final int lastItem = lm.getItemCount() - 1;
                targetPosition = Math.min(lastItem, Math.max(targetPosition, firstItem));
                return targetPosition;
            }
        };
        snapHelper.attachToRecyclerView(mBlogList);

Last Step is to set adapter to RecyclerView

mBlogList.setAdapter(firebaseRecyclerAdapter);

Include PHP file into HTML file

You would have to configure your webserver to utilize PHP as handler for .html files. This is typically done by modifying your with AddHandler to include .html along with .php.

Note that this could have a performance impact as this would cause ALL .html files to be run through PHP handler even if there is no PHP involved. So you might strongly consider using .php extension on these files and adding a redirect as necessary to route requests to specific .html URL's to their .php equivalents.

How can I combine two HashMap objects containing the same types?

If you know you don't have duplicate keys, or you want values in map2 to overwrite values from map1 for duplicate keys, you can just write

map3 = new HashMap<>(map1);
map3.putAll(map2);

If you need more control over how values are combined, you can use Map.merge, added in Java 8, which uses a user-provided BiFunction to merge values for duplicate keys. merge operates on individual keys and values, so you'll need to use a loop or Map.forEach. Here we concatenate strings for duplicate keys:

map3 = new HashMap<>(map1);
for (Map.Entry<String, String> e : map2.entrySet())
    map3.merge(e.getKey(), e.getValue(), String::concat);
//or instead of the above loop
map2.forEach((k, v) -> map3.merge(k, v, String::concat));

If you know you don't have duplicate keys and want to enforce it, you can use a merge function that throws an AssertionError:

map2.forEach((k, v) ->
    map3.merge(k, v, (v1, v2) ->
        {throw new AssertionError("duplicate values for key: "+k);}));

Taking a step back from this specific question, the Java 8 streams library provides toMap and groupingBy Collectors. If you're repeatedly merging maps in a loop, you may be able to restructure your computation to use streams, which can both clarify your code and enable easy parallelism using a parallel stream and concurrent collector.

Does Java have a path joining method?

One way is to get system properties that give you the path separator for the operating system, this tutorial explains how. You can then use a standard string join using the file.separator.

The following artifacts could not be resolved: javax.jms:jms:jar:1.1

You import one dependency, and this dependency is dependent on com.sun.jmx:jmxri:jar:1.2.1 and others, but com.sun.jmx:jmxri:jar:1.2.1 cannot be found in central repository,

so you'd better try to import another version.

Here suppose your dependency may be log4j, and you can try to import log4j:log4j:jar:1.2.13.

What is std::move(), and when should it be used?

Here is a full example, using std::move for a (simple) custom vector

Expected output:

 c: [10][11]
 copy ctor called
 copy of c: [10][11]
 move ctor called
 moved c: [10][11]

Compile as:

  g++ -std=c++2a -O2 -Wall -pedantic foo.cpp

Code:

#include <iostream>
#include <algorithm>

template<class T> class MyVector {
private:
    T *data;
    size_t maxlen;
    size_t currlen;
public:
    MyVector<T> () : data (nullptr), maxlen(0), currlen(0) { }
    MyVector<T> (int maxlen) : data (new T [maxlen]), maxlen(maxlen), currlen(0) { }

    MyVector<T> (const MyVector& o) {
        std::cout << "copy ctor called" << std::endl;
        data = new T [o.maxlen];
        maxlen = o.maxlen;
        currlen = o.currlen;
        std::copy(o.data, o.data + o.maxlen, data);
    }

    MyVector<T> (const MyVector<T>&& o) {
        std::cout << "move ctor called" << std::endl;
        data = o.data;
        maxlen = o.maxlen;
        currlen = o.currlen;
    }

    void push_back (const T& i) {
        if (currlen >= maxlen) {
            maxlen *= 2;
            auto newdata = new T [maxlen];
            std::copy(data, data + currlen, newdata);
            if (data) {
                delete[] data;
            }
            data = newdata;
        }
        data[currlen++] = i;
    }

    friend std::ostream& operator<<(std::ostream &os, const MyVector<T>& o) {
        auto s = o.data;
        auto e = o.data + o.currlen;;
        while (s < e) {
            os << "[" << *s << "]";
            s++;
        }
        return os;
    }
};

int main() {
    auto c = new MyVector<int>(1);
    c->push_back(10);
    c->push_back(11);
    std::cout << "c: " << *c << std::endl;
    auto d = *c;
    std::cout << "copy of c: " << d << std::endl;
    auto e = std::move(*c);
    delete c;
    std::cout << "moved c: " << e << std::endl;
}

Bash script - variable content as a command to run

You just need to do:

#!/bin/bash
count=$(cat last_queries.txt | wc -l)
$(perl test.pl test2 $count)

However, if you want to call your Perl command later, and that's why you want to assign it to a variable, then:

#!/bin/bash
count=$(cat last_queries.txt | wc -l)
var="perl test.pl test2 $count" # You need double quotes to get your $count value substituted.

...stuff...

eval $var

As per Bash's help:

~$ help eval
eval: eval [arg ...]
    Execute arguments as a shell command.

    Combine ARGs into a single string, use the result as input to the shell,
    and execute the resulting commands.

    Exit Status:
    Returns exit status of command or success if command is null.

how to align text vertically center in android

Try to put android:gravity="center_vertical|right" inside parent LinearLayout else as you are inside RelativeLayout you can put android:layout_centerInParent="true" inside your scrollView.

Reset Windows Activation/Remove license key

On Windows XP -

  1. Reboot into "Safe mode with Command Prompt"
  2. Type "explorer" in the command prompt that comes up and push [Enter]
  3. Click on Start>Run, and type the following :

    rundll32.exe syssetup,SetupOobeBnk

Reboot, and login as normal.

This will reset the 30 day timer for activation back to 30 days so you can enter in the key normally.

Java - Relative path of a file in a java web application

You may be able to simply access a pre-arranged file path on the system. This is preferable since files added to the webapp directory might be lost or the webapp may not be unpacked depending on system configuration.

In our server, we define a system property set in the App Server's JVM which points to the "home directory" for our app's external data. Of course this requires modification of the App Server's configuration (-DAPP_HOME=... added to JVM_OPTS at startup), we do it mainly to ease testing of code run outside the context of an App Server.

You could just as easily retrieve a path from the servlet config:

<web-app>
<context-param>
    <param-name>MyAppHome</param-name>
    <param-value>/usr/share/myapp</param-value>
</context-param>
...
</web-app>

Then retrieve this path and use it as the base path to read the file supplied by the client.

public class MyAppConfig implements ServletContextListener {

    // NOTE: static references are not a great idea, shown here for simplicity
    static File appHome;
    static File customerDataFile;

    public void contextInitialized(ServletContextEvent e) {

        appHome = new File(e.getServletContext().getInitParameter("MyAppHome"));
        File customerDataFile = new File(appHome, "SuppliedFile.csv");
    }
}

class DataProcessor {
    public void processData() {
        File dataFile = MyAppConfig.customerDataFile;
        // ...
    }
}

As I mentioned the most likely problem you'll encounter is security restrictions. Nothing guarantees webapps can ready any files above their webapp root. But there are generally simple methods for granting exceptions for specific paths to specific webapps.

Regardless of the code in which you then need to access this file, since you are running within a web application you are guaranteed this is initialized first, and can stash it's value somewhere convenient for the rest of your code to refer to, as in my example or better yet, just simply pass the path as a paramete to the code which needs it.

Binary numbers in Python

'''
I expect the intent behind this assignment was to work in binary string format.
This is absolutely doable.
'''

def compare(bin1, bin2):
    return bin1.lstrip('0') == bin2.lstrip('0')

def add(bin1, bin2):
    result = ''
    blen = max((len(bin1), len(bin2))) + 1
    bin1, bin2 = bin1.zfill(blen), bin2.zfill(blen)
    carry_s = '0'
    for b1, b2 in list(zip(bin1, bin2))[::-1]:
        count = (carry_s, b1, b2).count('1')
        carry_s = '1' if count >= 2 else '0'
        result += '1' if count % 2 else '0'
    return result[::-1]

if __name__ == '__main__':
    print(add('101', '100'))

I leave the subtraction func as an exercise for the reader.

Convert UTC/GMT time to local time

I had the problem with it being in a data set being pushed across the wire (webservice to client) that it would automatically change because the DataColumn's DateType field was set to local. Make sure you check what the DateType is if your pushing DataSets across.

If you don't want it to change, set it to Unspecified

How to write a shell script that runs some commands as superuser and some commands not as superuser, without having to babysit it?

You should run your entire script as superuser. If you want to run some command as non-superuser, use "-u" option of sudo:

#!/bin/bash

sudo -u username command1
command2
sudo -u username command3
command4

When running as root, sudo doesn't ask for a password.

Automate scp file transfer using a shell script

why don't you try this?

password="your password"
username="username"
Ip="<IP>"
sshpass -p "$password" scp /<PATH>/final.txt $username@$Ip:/root/<PATH>

Drawing Circle with OpenGL

#include <Windows.h>
#include <GL/glu.h>
#include <GL/glut.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define window_width  1080  
#define window_height 720 
void drawFilledSun(){
    //static float angle;
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();
    glTranslatef(0, 0, -10);
    int i, x, y;
    double radius = 0.30;
    //glColor3ub(253, 184, 19);     
    glColor3ub(255, 0, 0);
    double twicePi = 2.0 * 3.142;
    x = 0, y = 0;
    glBegin(GL_TRIANGLE_FAN); //BEGIN CIRCLE
    glVertex2f(x, y); // center of circle
    for (i = 0; i <= 20; i++)   {
        glVertex2f (
            (x + (radius * cos(i * twicePi / 20))), (y + (radius * sin(i * twicePi / 20)))
            );
    }
    glEnd(); //END
}
void DrawCircle(float cx, float cy, float r, int num_segments) {
    glBegin(GL_LINE_LOOP);
    for (int ii = 0; ii < num_segments; ii++)   {
        float theta = 2.0f * 3.1415926f * float(ii) / float(num_segments);//get the current angle 
        float x = r * cosf(theta);//calculate the x component 
        float y = r * sinf(theta);//calculate the y component 
        glVertex2f(x + cx, y + cy);//output vertex 
    }
    glEnd();
}
void main_loop_function() {
    int c;
    drawFilledSun();
    DrawCircle(0, 0, 0.7, 100);
    glutSwapBuffers();
    c = getchar();
}
void GL_Setup(int width, int height) {
    glViewport(0, 0, width, height);
    glMatrixMode(GL_PROJECTION);
    glEnable(GL_DEPTH_TEST);
    gluPerspective(45, (float)width / height, .1, 100);
    glMatrixMode(GL_MODELVIEW);
}
int main(int argc, char** argv) {
    glutInit(&argc, argv);
    glutInitWindowSize(window_width, window_height);
    glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
    glutCreateWindow("GLUT Example!!!");
    glutIdleFunc(main_loop_function);
    GL_Setup(window_width, window_height);
    glutMainLoop();
}

This is what I did. I hope this helps. Two types of circle are here. Filled and unfilled.

Add days Oracle SQL

If you want to add N days to your days. You can use the plus operator as follows -

SELECT ( SYSDATE + N ) FROM DUAL;

Should I use the datetime or timestamp data type in MySQL?

TIMESTAMP is 4 bytes Vs 8 bytes for DATETIME.

http://dev.mysql.com/doc/refman/5.0/en/storage-requirements.html

But like scronide said it does have a lower limit of the year 1970. It's great for anything that might happen in the future though ;)

Drawing a line/path on Google Maps

This can be done by using intents too:

  final Intent intent = new Intent(Intent.ACTION_VIEW,
    Uri.parse(
            "http://maps.google.com/maps?" +
            "saddr="+YOUR_START_LONGITUDE+","+YOUR_START_LATITUDE+"&daddr="YOUR_END_LONGITUDE+","+YOUR_END_LATITUDE));
         intent.setClassName(
          "com.google.android.apps.maps",
          "com.google.android.maps.MapsActivity");
   startActivity(intent);

How do you send an HTTP Get Web Request in Python?

In Python, you can use urllib2 (http://docs.python.org/2/library/urllib2.html) to do all of that work for you.

Simply enough:

import urllib2
f =  urllib2.urlopen(url)
print f.read() 

Will print the received HTTP response.

To pass GET/POST parameters the urllib.urlencode() function can be used. For more information, you can refer to the Official Urllib2 Tutorial

How do I add my bot to a channel?

Are you using the right chat_id and including your bot's token after "bot" in the address? (api.telegram.org/bottoken/sendMessage)

This page explains a few things about sending (down in "sendMessage" section) - basic stuff, but I often forget the basics.

To quote:

In order to use the sendMessage method we need to use the proper chat_id.

First things first let's send the /start command to our bot via a Telegram client.

After sent this command let's perform a getUpdates commands.

curl -s \
-X POST \ https://api.telegram.org/bot<token>/getUpdates \ | jq .

The response will be like the following

{   "result": [
     {
       "message": {
        "text": "/start",
         "date": 1435176541,
         "chat": {
           "username": "yourusername",
           "first_name": "yourfirstname",
           "id": 65535
         },
         "from": {
           "username": "yourusername",
           "first_name": "yourfirstname",
           "id": 65535
         },
         "message_id": 1
       },
       "update_id": 714636917
     }    ],   "ok": true }

We are interested in the property result.message[0].chat.id, save this information elsewhere.

Please note that this is only an example, you may want to set up some automatism to handle those informations Now how we can send a message ? It's simple let's check out this snippet.

curl -s \
-X POST \ https://api.telegram.org/bot<token>/sendMessage \
-d text="A message from your bot" \
-d chat_id=65535 \ | jq .

Where chat_id is the piece of information saved before.

I hope that helps.

Understanding the grid classes ( col-sm-# and col-lg-# ) in Bootstrap 3

The best way to understand is to simply think from top to bottom ( Large Desktops to Mobile Phones)

Firstly, as B3 is mobile first so if you use xs then the columns will be same from Large desktops to xs ( i recommend using xs or sm as this will keep everything the way you want on every screen size )

Secondly if you want to give different width to columns on different devices or resolutions, than you can add multiple classes e.g

the above will change the width according to the screen resolutions, REMEMBER i am keeping the total columns in each class = 12

I hope my answer would help!

Include another JSP file

What you're doing is a static include. A static include is resolved at compile time, and may thus not use a parameter value, which is only known at execution time.

What you need is a dynamic include:

<jsp:include page="..." />

Note that you should use the JSP EL rather than scriptlets. It also seems that you're implementing a central controller with index.jsp. You should use a servlet to do that instead, and dispatch to the appropriate JSP from this servlet. Or better, use an existing MVC framework like Stripes or Spring MVC.

Javascript - Open a given URL in a new tab by clicking a button

Open in new tab using javascript

 <button onclick="window.open('https://www.our-url.com')" id="myButton" 
 class="btn request-callback" >Explore More  </button>

How to simulate key presses or a click with JavaScript?

you can raise the click event on an element by doing

// this must be done after input1 exists in the DOM
var element = document.getElementById("input1");

if (element) element.click();

Example here

difference between new String[]{} and new String[] in java

String array=new String[]; and String array=new String[]{}; both are invalid statement in java.

It will gives you an error that you are trying to assign String array to String datatype. More specifically error is like this Type mismatch: cannot convert from String[] to String

How to display line numbers in 'less' (GNU)

You can set an enviroment variable to always have these options apply to all less'd file:

export LESS='-RS#3NM~g'

Recommended SQL database design for tags or tagging

If you are using a database that supports map-reduce, like couchdb, storing tags in a plain text field or list field is indeed the best way. Example:

tagcloud: {
  map: function(doc){ 
    for(tag in doc.tags){ 
      emit(doc.tags[tag],1) 
    }
  }
  reduce: function(keys,values){
    return values.length
  }
}

Running this with group=true will group the results by tag name, and even return a count of the number of times that tag was encountered. It's very similar to counting the occurrences of a word in text.

JavaScript hard refresh of current page

Try to use:

location.reload(true);

When this method receives a true value as argument, it will cause the page to always be reloaded from the server. If it is false or not specified, the browser may reload the page from its cache.

More info:

Java: recommended solution for deep cloning/copying an instance

For deep cloning (clones the entire object hierarchy):

  • commons-lang SerializationUtils - using serialization - if all classes are in your control and you can force implementing Serializable.

  • Java Deep Cloning Library - using reflection - in cases when the classes or the objects you want to clone are out of your control (a 3rd party library) and you can't make them implement Serializable, or in cases you don't want to implement Serializable.

For shallow cloning (clones only the first level properties):

I deliberately omitted the "do-it-yourself" option - the API's above provide a good control over what to and what not to clone (for example using transient, or String[] ignoreProperties), so reinventing the wheel isn't preferred.

jQuery add image inside of div tag

In addition to Manjeet Kumar's post (he didn't have the declaration)

var image = document.createElement("IMG");
image.alt = "Alt information for image";
image.setAttribute('class', 'photo');
image.src="/images/abc.jpg";
$(#TheDiv).html(image);

C# - insert values from file into two arrays

string[] lines = File.ReadAllLines("sample.txt"); List<string> list1 = new List<string>(); List<string> list2 = new List<string>();  foreach (var line in lines) {     string[] values = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);     list1.Add(values[0]);     list2.Add(values[1]);  } 

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

what about that simple way)

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

How to get request URL in Spring Boot RestController

Allows getting any URL on your system, not just a current one.

import org.springframework.hateoas.mvc.ControllerLinkBuilder
...
ControllerLinkBuilder linkBuilder = ControllerLinkBuilder.linkTo(methodOn(YourController.class).getSomeEntityMethod(parameterId, parameterTwoId))

URI methodUri = linkBuilder.Uri()
String methodUrl = methodUri.getPath()

Using .htaccess to make all .html pages to run as .php files?

here put this in your .htaccess

AddType application/x-httpd-php .php .htm .html

more info on this page

Program to find largest and second largest number in array

Getting the second largest number from an array is pretty easy in python, I have done with simple steps and put various ways of test cases and it gave the right answer every time. PS. I know it's for c but I just gave a simple solution to the question if done in python

n = int(input()) #taking number of elements in array
arr = map(int, input().split()) #taking differet elements
l=[]
s=set()
for i in arr: #putting all the elemnents in set to remove any duplicate number
    s.add(i)
for j in s:  #putting all element from the set in the list to sort and get the second largest number
    l.append(j)
l.sort()
c=len(l)
print(l[c-2]) #printing second largest number

How to count check-boxes using jQuery?

You could do:

var numberOfChecked = $('input:checkbox:checked').length;
var totalCheckboxes = $('input:checkbox').length;
var numberNotChecked = totalCheckboxes - numberOfChecked;

EDIT

Or even simple

var numberNotChecked = $('input:checkbox:not(":checked")').length;

Parallel.ForEach vs Task.Factory.StartNew

I did a small experiment of running a method "1,000,000,000 (one billion)" times with "Parallel.For" and one with "Task" objects.

I measured the processor time and found Parallel more efficient. Parallel.For divides your task in to small work items and executes them on all the cores parallely in a optimal way. While creating lot of task objects ( FYI TPL will use thread pooling internally) will move every execution on each task creating more stress in the box which is evident from the experiment below.

I have also created a small video which explains basic TPL and also demonstrated how Parallel.For utilizes your core more efficiently http://www.youtube.com/watch?v=No7QqSc5cl8 as compared to normal tasks and threads.

Experiment 1

Parallel.For(0, 1000000000, x => Method1());

Experiment 2

for (int i = 0; i < 1000000000; i++)
{
    Task o = new Task(Method1);
    o.Start();
}

Processor time comparison

What does 'COLLATE SQL_Latin1_General_CP1_CI_AS' do?

The COLLATE keyword specify what kind of character set and rules (order, confrontation rules) you are using for string values.

For example in your case you are using Latin rules with case insensitive (CI) and accent sensitive (AS)

You can refer to this Documentation

Combine multiple JavaScript files into one JS file

Script grouping is counterproductive, you should load them in parallel using something like http://yepnopejs.com/ or http://headjs.com

HTML5 <video> element on Android

Try h.264 in an mp4 container. I've had much success with it on my Droid X. I've been using zencoder.com for format conversions.

Change button background color using swift language

After you connect the UIButton that you want to change its background as an OUtlet to your ViewController.swift file you can use the following:

 yourUIButton.backgroundColor = UIColor.blue

How to use Tomcat 8.5.x and TomEE 7.x with Eclipse?

There is a patch for Eclipse:
https://bugs.eclipse.org/bugs/attachment.cgi?id=262418&action=edit

Download this patch and put it to the plugins directory of your Eclipse installation. It will replace the default "org.eclipse.jst.server.tomcat.core_1.1.800.v201602282129.jar".

NOTE
After you add this patch you must choose "Apache Tomcat v9.0" when adding a server runtime environment in the Eclipse (Preferences > Server > Runtime Environments).
I.e. this patch allows you to select either Tomcat version 9.x or Tomcat version 8.5.x when adding Apache Tomcat v.9.0 runtime environment.


More details on can be found on the related bug report page: https://bugs.eclipse.org/bugs/show_bug.cgi?id=494936

How do I copy a string to the clipboard?

You can use the excellent pandas, which has a built in clipboard support, but you need to pass through a DataFrame.

import pandas as pd
df=pd.DataFrame(['Text to copy'])
df.to_clipboard(index=False,header=False)

Where can I find jenkins restful api reference?

Jenkins has a link to their REST API in the bottom right of each page. This link appears on every page of Jenkins and points you to an API output for the exact page you are browsing. That should provide some understanding into how to build the API URls.

You can additionally use some wrapper, like I do, in Python, using http://jenkinsapi.readthedocs.io/en/latest/

Here is their website: https://wiki.jenkins-ci.org/display/JENKINS/Remote+access+API

sed edit file in place

Note that on OS X you might get strange errors like "invalid command code" or other strange errors when running this command. To fix this issue try

sed -i '' -e "s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g" <file>

This is because on the OSX version of sed, the -i option expects an extension argument so your command is actually parsed as the extension argument and the file path is interpreted as the command code. Source: https://stackoverflow.com/a/19457213

Check if String / Record exists in DataTable

Use the Find method if item_manuf_id is a primary key:

var result = dtPs.Rows.Find("some value");

If you only want to know if the value is in there then use the Contains method.

if (dtPs.Rows.Contains("some value"))
{
  ...
}

Primary key restriction applies to Contains aswell.

how does multiplication differ for NumPy Matrix vs Array classes?

The main reason to avoid using the matrix class is that a) it's inherently 2-dimensional, and b) there's additional overhead compared to a "normal" numpy array. If all you're doing is linear algebra, then by all means, feel free to use the matrix class... Personally I find it more trouble than it's worth, though.

For arrays (prior to Python 3.5), use dot instead of matrixmultiply.

E.g.

import numpy as np
x = np.arange(9).reshape((3,3))
y = np.arange(3)

print np.dot(x,y)

Or in newer versions of numpy, simply use x.dot(y)

Personally, I find it much more readable than the * operator implying matrix multiplication...

For arrays in Python 3.5, use x @ y.

Convert RGBA PNG to RGB with PIL

import numpy as np
import PIL

def convert_image(image_file):
    image = Image.open(image_file) # this could be a 4D array PNG (RGBA)
    original_width, original_height = image.size

    np_image = np.array(image)
    new_image = np.zeros((np_image.shape[0], np_image.shape[1], 3)) 
    # create 3D array

    for each_channel in range(3):
        new_image[:,:,each_channel] = np_image[:,:,each_channel]  
        # only copy first 3 channels.

    # flushing
    np_image = []
    return new_image

What is the best way to give a C# auto-property an initial value?

Sometimes I use this, if I don't want it to be actually set and persisted in my db:

class Person
{
    private string _name; 
    public string Name 
    { 
        get 
        {
            return string.IsNullOrEmpty(_name) ? "Default Name" : _name;
        } 

        set { _name = value; } 
    }
}

Obviously if it's not a string then I might make the object nullable ( double?, int? ) and check if it's null, return a default, or return the value it's set to.

Then I can make a check in my repository to see if it's my default and not persist, or make a backdoor check in to see the true status of the backing value, before saving.

Hope that helps!

How to iterate a table rows with JQuery and access some cell values?

do this:

$("tr.item").each(function(i, tr) {
    var value = $("span.value", tr).text();
    var quantity = $("input.quantity", tr).val();
});

How to diff a commit with its parent?

Use git show $COMMIT. It'll show you the log message for the commit, and the diff of that particular commit.

How do I include inline JavaScript in Haml?

:javascript
    $(document).ready( function() {
      $('body').addClass( 'test' );
    } );

Docs: http://haml.info/docs/yardoc/file.REFERENCE.html#javascript-filter

How to place and center text in an SVG rectangle

An easy solution to center text horizontally and vertically in SVG:

  1. Set the position of the text to the absolute center of the element in which you want to center it:

    • If it's the parent, you could just do x="50%" y ="50%".
    • If it's another element, x would be the x of that element + half its width (and similar for y but with the height).
  2. Use the text-anchor property to center the text horizontally with the value middle:

    middle

    The rendered characters are aligned such that the geometric middle of the resulting rendered text is at the initial current text position.

  3. Use the dominant-baseline property to center the text vertically with the value middle (or depending on how you want it to look like, you may want to do central)

Here is a simple demo:

_x000D_
_x000D_
<svg width="200" height="100">_x000D_
  <rect x="0" y="0" width="200" height="100" stroke="red" stroke-width="3px" fill="white"/>_x000D_
  <text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle">TEXT</text>    _x000D_
</svg>
_x000D_
_x000D_
_x000D_

How do I align a label and a textarea?

Try this:

textarea { vertical-align: top; }? 

is there a 'block until condition becomes true' function in java?

Lock-free solution(?)

I had the same issue, but I wanted a solution that didn't use locks.

Problem: I have at most one thread consuming from a queue. Multiple producer threads are constantly inserting into the queue and need to notify the consumer if it's waiting. The queue is lock-free so using locks for notification causes unnecessary blocking in producer threads. Each producer thread needs to acquire the lock before it can notify the waiting consumer. I believe I came up with a lock-free solution using LockSupport and AtomicReferenceFieldUpdater. If a lock-free barrier exists within the JDK, I couldn't find it. Both CyclicBarrier and CoundDownLatch use locks internally from what I could find.

This is my slightly abbreviated code. Just to be clear, this code will only allow one thread to wait at a time. It could be modified to allow for multiple awaiters/consumers by using some type of atomic collection to store multiple owner (a ConcurrentMap may work).

I have used this code and it seems to work. I have not tested it extensively. I suggest you read the documentation for LockSupport before use.

/* I release this code into the public domain.
 * http://unlicense.org/UNLICENSE
 */

import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.util.concurrent.locks.LockSupport;

/**
 * A simple barrier for awaiting a signal.
 * Only one thread at a time may await the signal.
 */
public class SignalBarrier {
    /**
     * The Thread that is currently awaiting the signal.
     * !!! Don't call this directly !!!
     */
    @SuppressWarnings("unused")
    private volatile Thread _owner;

    /** Used to update the owner atomically */
    private static final AtomicReferenceFieldUpdater<SignalBarrier, Thread> ownerAccess =
        AtomicReferenceFieldUpdater.newUpdater(SignalBarrier.class, Thread.class, "_owner");

    /** Create a new SignalBarrier without an owner. */
    public SignalBarrier() {
        _owner = null;
    }

    /**
     * Signal the owner that the barrier is ready.
     * This has no effect if the SignalBarrer is unowned.
     */
    public void signal() {
        // Remove the current owner of this barrier.
        Thread t = ownerAccess.getAndSet(this, null);

        // If the owner wasn't null, unpark it.
        if (t != null) {
            LockSupport.unpark(t);
        }
    }

    /**
     * Claim the SignalBarrier and block until signaled.
     *
     * @throws IllegalStateException If the SignalBarrier already has an owner.
     * @throws InterruptedException If the thread is interrupted while waiting.
     */
    public void await() throws InterruptedException {
        // Get the thread that would like to await the signal.
        Thread t = Thread.currentThread();

        // If a thread is attempting to await, the current owner should be null.
        if (!ownerAccess.compareAndSet(this, null, t)) {
            throw new IllegalStateException("A second thread tried to acquire a signal barrier that is already owned.");
        }

        // The current thread has taken ownership of this barrier.
        // Park the current thread until the signal. Record this
        // signal barrier as the 'blocker'.
        LockSupport.park(this);
        // If a thread has called #signal() the owner should already be null.
        // However the documentation for LockSupport.unpark makes it clear that
        // threads can wake up for absolutely no reason. Do a compare and set
        // to make sure we don't wipe out a new owner, keeping in mind that only
        // thread should be awaiting at any given moment!
        ownerAccess.compareAndSet(this, t, null);

        // Check to see if we've been unparked because of a thread interrupt.
        if (t.isInterrupted())
            throw new InterruptedException();
    }

    /**
     * Claim the SignalBarrier and block until signaled or the timeout expires.
     *
     * @throws IllegalStateException If the SignalBarrier already has an owner.
     * @throws InterruptedException If the thread is interrupted while waiting.
     *
     * @param timeout The timeout duration in nanoseconds.
     * @return The timeout minus the number of nanoseconds that passed while waiting.
     */
    public long awaitNanos(long timeout) throws InterruptedException {
        if (timeout <= 0)
            return 0;
        // Get the thread that would like to await the signal.
        Thread t = Thread.currentThread();

        // If a thread is attempting to await, the current owner should be null.
        if (!ownerAccess.compareAndSet(this, null, t)) {
            throw new IllegalStateException("A second thread tried to acquire a signal barrier is already owned.");
        }

        // The current thread owns this barrier.
        // Park the current thread until the signal. Record this
        // signal barrier as the 'blocker'.
        // Time the park.
        long start = System.nanoTime();
        LockSupport.parkNanos(this, timeout);
        ownerAccess.compareAndSet(this, t, null);
        long stop = System.nanoTime();

        // Check to see if we've been unparked because of a thread interrupt.
        if (t.isInterrupted())
            throw new InterruptedException();

        // Return the number of nanoseconds left in the timeout after what we
        // just waited.
        return Math.max(timeout - stop + start, 0L);
    }
}

To give a vague example of usage, I'll adopt james large's example:

SignalBarrier barrier = new SignalBarrier();

Consumer thread (singular, not plural!):

try {
    while(!conditionIsTrue()) {
        barrier.await();
    }
    doSomethingThatRequiresConditionToBeTrue();
} catch (InterruptedException e) {
    handleInterruption();
}

Producer thread(s):

doSomethingThatMakesConditionTrue();
barrier.signal();

Difference between break and continue in PHP?

break will exit the loop, while continue will start the next cycle of the loop immediately.

How can I check what version/edition of Visual Studio is installed programmatically?

You can get the VS product version by running the following command.

"C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe" -property catalog_productDisplayVersion

What is the (best) way to manage permissions for Docker shared volumes?

To share folder between docker host and docker container, try below command

$ docker run -v "$(pwd):$(pwd)" -i -t ubuntu

The -v flag mounts the current working directory into the container. When the host directory of a bind-mounted volume doesn’t exist, Docker will automatically create this directory on the host for you,

However, there are 2 problems we have here:

  1. You cannot write to the volume mounted if you were non-root user because the shared file will be owned by other user in host,
  2. You shouldn't run the process inside your containers as root but even if you run as some hard-coded user it still won't match the user on your laptop/Jenkins,

Solution:

Container: create a user say 'testuser', by default user id will be starting from 1000,

Host: create a group say 'testgroup' with group id 1000, and chown the directory to the new group(testgroup

time.sleep -- sleeps thread or process?

The thread will block, but the process is still alive.

In a single threaded application, this means everything is blocked while you sleep. In a multithreaded application, only the thread you explicitly 'sleep' will block and the other threads still run within the process.

How can I take an UIImage and give it a black border?

You can add border to the UIImageView, and then change the size of the UIimageView according to the image size:

#import <QuartzCore/QuartzCore.h>


// adding border to the imageView
[imageView.layer setBorderColor: [[UIColor whiteColor] CGColor]];
[imageView.layer setBorderWidth: 2.0];

// resize the imageView to fit the image size
CGSize size = [image size];
float factor = size.width / self.frame.size.width;
if (factor < size.height / self.frame.size.height) {
    factor = size.height / self.frame.size.height;
}

CGRect rect = CGRectMake(0, 0, size.width/factor, size.height/factor);
imageView.frame = rect;

Make sure you to set the origin of the imageView to the center

How to send custom headers with requests in Swagger UI?

I ended up here because I was trying to conditionally add header parameters in Swagger UI, based on my own [Authentication] attribute I added to my API method. Following the hint that @Corcus listed in a comment, I was able to derive my solution, and hopefully it will help others.

Using Reflection, it's checking if the method nested down in apiDescription has the desired attribute (MyApiKeyAuthenticationAttribute, in my case). If it does, I can append my desired header parameters.

public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription) {
    if (operation.parameters == null)
        operation.parameters = new List<Parameter>();


    var attributes = ((System.Web.Http.Controllers.ReflectedHttpActionDescriptor)
        ((apiDescription.ActionDescriptor).ActionBinding.ActionDescriptor)).MethodInfo
        .GetCustomAttributes(false);
    if(attributes != null && attributes.Any()) {
        if(attributes.Where(x => x.GetType() 
            == typeof(MyApiKeyAuthenticationAttribute)).Any()) {

            operation.parameters.Add(new Parameter {
                name = "MyApiKey",
                @in = "header",
                type = "string",
                description = "My API Key",
                required = true
            });
            operation.parameters.Add(new Parameter {
                name = "EID",
                @in = "header",
                type = "string",
                description = "Employee ID",
                required = true
            });
        }
    }


}

JavaScript/jQuery - "$ is not defined- $function()" error

You need to include the jQuery library on your page.

You can download jQuery here and host it yourself or you can link from an external source like from Google or Microsoft.

Google's:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

Microsoft's:

<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.6.2.min.js">

How to make GREP select only numeric values?

grep will print any lines matching the pattern you provide. If you only want to print the part of the line that matches the pattern, you can pass the -o option:

-o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.

Like this:

echo 'Here is a line mentioning 99% somewhere' | grep -o '[0-9]+'

How can I increment a date by one day in Java?

Let's clarify the use case: You want to do calendar arithmetic and start/end with a java.util.Date.

Some approaches:

  1. Convert to string and back with SimpleDateFormat: This is an inefficient solution.
  2. Convert to LocalDate: You would lose any time-of-day information.
  3. Convert to LocalDateTime: This involves more steps and you need to worry about timezone.
  4. Convert to epoch with Date.getTime(): This is efficient but you are calculating with milliseconds.

Consider using java.time.Instant:

Date _now = new Date();
Instant _instant = _now.toInstant().minus(5, ChronoUnit.DAYS);
Date _newDate = Date.from(_instant);

Deleting multiple elements from a list

You can use remove, too.

delete_from_somelist = []
for i in [int(0), int(2)]:
     delete_from_somelist.append(somelist[i])
for j in delete_from_somelist:
     newlist = somelist.remove(j)

@HostBinding and @HostListener: what do they do and what are they for?

One thing that adds confusion to this subject is the idea of decorators is not made very clear, and when we consider something like...

@HostBinding('attr.something') 
get something() { 
    return this.somethingElse; 
 }

It works, because it is a get accessor. You couldn't use a function equivalent:

@HostBinding('attr.something') 
something() { 
    return this.somethingElse; 
 }

Otherwise, the benefit of using @HostBinding is it assures change detection is run when the bound value changes.

How to terminate a thread when main program ends?

Daemon threads are killed ungracefully so any finalizer instructions are not executed. A possible solution is to check is main thread is alive instead of infinite loop.

E.g. for Python 3:

while threading.main_thread().isAlive():
    do.you.subthread.thing()
gracefully.close.the.thread()

See Check if the Main Thread is still alive from another thread.

How does one convert a grayscale image to RGB in OpenCV (Python)?

Try this:

import cv2
import cv

color_img = cv2.cvtColor(gray_img, cv.CV_GRAY2RGB)

I discovered, while using opencv, that some of the constants are defined in the cv2 module, and other in the cv module.

New features in java 7

Language changes:

-Project Coin (small changes)
-switch on Strings
-try-with-resources
-diamond operator

Library changes:

-new abstracted file-system API (NIO.2) (with support for virtual filesystems)
-improved concurrency libraries
-elliptic curve encryption
-more incremental upgrades

Platform changes:

-support for dynamic languages

Below is the link explaining the newly added features of JAVA 7 , the explanation is crystal clear with the possible small examples for each features :

http://radar.oreilly.com/2011/09/java7-features.html

python pandas extract year from datetime: df['year'] = df['date'].year is not working

When to use dt accessor

A common source of confusion revolves around when to use .year and when to use .dt.year.

The former is an attribute for pd.DatetimeIndex objects; the latter for pd.Series objects. Consider this dataframe:

df = pd.DataFrame({'Dates': pd.to_datetime(['2018-01-01', '2018-10-20', '2018-12-25'])},
                  index=pd.to_datetime(['2000-01-01', '2000-01-02', '2000-01-03']))

The definition of the series and index look similar, but the pd.DataFrame constructor converts them to different types:

type(df.index)     # pandas.tseries.index.DatetimeIndex
type(df['Dates'])  # pandas.core.series.Series

The DatetimeIndex object has a direct year attribute, while the Series object must use the dt accessor. Similarly for month:

df.index.month               # array([1, 1, 1])
df['Dates'].dt.month.values  # array([ 1, 10, 12], dtype=int64)

A subtle but important difference worth noting is that df.index.month gives a NumPy array, while df['Dates'].dt.month gives a Pandas series. Above, we use pd.Series.values to extract the NumPy array representation.

ERROR 1049 (42000): Unknown database 'mydatabasename'

mysql -uroot -psecret mysql < mydatabase.sql

What is the significance of 1/1/1753 in SQL Server?

1752 was the year of Britain switching from the Julian to the Gregorian calendar. I believe two weeks in September 1752 never happened as a result, which has implications for dates in that general area.

An explanation: http://uneasysilence.com/archive/2007/08/12008/ (Internet Archive version)

Best way to convert an ArrayList to a string

An elegant way to deal with trailing separation characters is to use Class Separator

StringBuilder buf = new StringBuilder();
Separator sep = new Separator("\t");
for (String each: list) buf.append(sep).append(each);
String s = buf.toString();

The toString method of Class Separator returns the separater, except for the first call. Thus we print the list without trailing (or in this case) leading separators.

How to exit from Python without traceback?

The following code will not raise an exception and will exit without a traceback:

import os
os._exit(1)

See this question and related answers for more details. Surprised why all other answers are so overcomplicated.

Most efficient way to convert an HTMLCollection to an Array

var arr = Array.prototype.slice.call( htmlCollection )

will have the same effect using "native" code.

Edit

Since this gets a lot of views, note (per @oriol's comment) that the following more concise expression is effectively equivalent:

var arr = [].slice.call(htmlCollection);

But note per @JussiR's comment, that unlike the "verbose" form, it does create an empty, unused, and indeed unusable array instance in the process. What compilers do about this is outside the programmer's ken.

Edit

Since ECMAScript 2015 (ES 6) there is also Array.from:

var arr = Array.from(htmlCollection);

Edit

ECMAScript 2015 also provides the spread operator, which is functionally equivalent to Array.from (although note that Array.from supports a mapping function as the second argument).

var arr = [...htmlCollection];

I've confirmed that both of the above work on NodeList.

A performance comparison for the mentioned methods: http://jsben.ch/h2IFA

border-radius not working

in your div class="social-box" css

use

            float:right 

instead of

             float:left

Modifying a file inside a jar

Java jar files are the same format as zip files - so if you have a zip file utility that would let you modify an archive, you have your foot in the door. Second problem is, if you want to recompile a class or something, you probably will just have to re-build the jar; but a text file or something (xml, for instance) should be easily enough modified.

notifyDataSetChange not working from custom adapter

In my case I simply forget to add in my fragment mRecyclerView.setAdapter(adapter)

How to find the last day of the month from date?

There is also the built in PHP function cal_days_in_month()?

"This function will return the number of days in the month of year for the specified calendar." http://php.net/manual/en/function.cal-days-in-month.

echo cal_days_in_month(CAL_GREGORIAN, 11, 2009); 
// = 30

VB.NET Empty String Array

Something like:

Dim myArray(9) as String

Would give you an array of 10 String references (each pointing to Nothing).

If you're not sure of the size at declaration time, you can declare a String array like this:

Dim myArray() as String

And then you can point it at a properly-sized array of Strings later:

ReDim myArray(9) as String

ZombieSheep is right about using a List if you don't know the total size and you need to dynamically populate it. In VB.NET that would be:

Dim myList as New List(Of String)
myList.Add("foo")
myList.Add("bar")

And then to get an array from that List:

myList.ToArray()

@Mark

Thanks for the correction.

Get a Div Value in JQuery

$('#myDiv').text()

Although you'd be better off doing something like:

_x000D_
_x000D_
var txt = $('#myDiv p').text();_x000D_
alert(txt);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="myDiv"><p>Some Text</p></div>
_x000D_
_x000D_
_x000D_

Make sure you're linking to your jQuery file too :)

user authentication libraries for node.js?

A few years have passed and I'd like to introduce my authentication solution for Express. It's called Lockit. You can find the project on GitHub and a short intro at my blog.

So what are the differences to the existing solutions?

  • easy to use: set up your DB, npm install, require('lockit'), lockit(app), done
  • routes already built-in (/signup, /login, /forgot-password, etc.)
  • views already built-in (based on Bootstrap but you can easily use your own views)
  • it supports JSON communication for your AngularJS / Ember.js single page apps
  • it does NOT support OAuth and OpenID. Only username and password.
  • it works with several databases (CouchDB, MongoDB, SQL) out of the box
  • it has tests (I couldn't find any tests for Drywall)
  • it is actively maintained (compared to everyauth)
  • email verification and forgot password process (send email with token, not supported by Passport)
  • modularity: use only what you need
  • flexibility: customize all the things

Take a look at the examples.

Query an XDocument for elements by name at any depth

I am using XPathSelectElements extension method which works in the same way to XmlDocument.SelectNodes method:

using System;
using System.Xml.Linq;
using System.Xml.XPath; // for XPathSelectElements

namespace testconsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            XDocument xdoc = XDocument.Parse(
                @"<root>
                    <child>
                        <name>john</name>
                    </child>
                    <child>
                        <name>fred</name>
                    </child>
                    <child>
                        <name>mark</name>
                    </child>
                 </root>");

            foreach (var childElem in xdoc.XPathSelectElements("//child"))
            {
                string childName = childElem.Element("name").Value;
                Console.WriteLine(childName);
            }
        }
    }
}

Angular Material: mat-select not selecting default

A very simple way to achieve this is using a formControl with a default value, inside a FormGroup (optional) for example. This is an example using an unit selector to an area input:

ts

H_AREA_UNIT = 1;
M_AREA_UNIT = 2;

exampleForm: FormGroup;

this.exampleForm = this.formBuilder.group({
  areaUnit: [this.H_AREA_UNIT],
});

html

<form [formGroup]="exampleForm">
 <mat-form-field>
   <mat-label>Unit</mat-label>
   <mat-select formControlName="areaUnit">
     <mat-option [value]="H_AREA_UNIT">h</mat-option>
     <mat-option [value]="M_AREA_UNIT">m</mat-option>
   </mat-select>
 </mat-form-field>
</form>

"The system cannot find the file C:\ProgramData\Oracle\Java\javapath\java.exe"

Updating the PATH Environment Variable

If you do not set the PATH variable, you need to specify the full path to the executable file every time you run it, such as:

C:\> "C:\Program Files\Java\jdk1.8.0\bin\javac" MyClass.java


It is useful to set the PATH variable permanently so it will persist after rebooting.
To set the PATH variable permanently, add the full path of the jdk1.8.0\bin directory to the PATH variable. Typically, this full path looks something like
C:\Program Files\Java\jdk1.8.0\bin.
Set the PATH variable as follows on Microsoft Windows:

  • Click Start, then Control Panel, then System.
  • Click Advanced, then Environment Variables.
  • Add the location of the bin folder of the JDK installation to the PATH variable in System Variables.
    The following is a typical value for the PATH variable:

    C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files\Java\jdk1.8.0\bin

    Note:

  • The PATH environment variable is a series of directories separated by semicolons (;) and is not case-sensitive. Microsoft Windows looks for programs in the PATH directories in order, from left to right.

  • You should only have one bin directory for a JDK in the path at a time. Those following the first instance are ignored.

  • If you are not sure where to add the JDK path, append it.

The new path takes effect in each new command window you open after setting the PATH variable.

Paste text on Android Emulator

I got tired of this problem so I just made this alias to handle it:

alias ap="pbpaste | xargs adb shell input text"

Then when you open a new terminal window, typing "ap" will paste whatever is on your clipboard into the emulator's actively selected text field.

Setup

Simply add this to your profile (for most users that's ~/.bash_profile for zsh users that's ~/.zshrc) to make the alias available everywhere. Alternatively, if you're a bash user (the default for MacOS), then you can run the following command in the terminal to set it up for you:

echo "alias ap='pbpaste | xargs adb shell input text'" >> ~/.bash_profile && source ~/.bash_profile

CSS - Overflow: Scroll; - Always show vertical scroll bar?

Try the following code to display scroll bar always on your page,

::-webkit-scrollbar {
  -webkit-appearance: none;
  width: 10px;
}

::-webkit-scrollbar-thumb {
  border-radius: 5px;
  background-color: rgba(0,0,0,.5);
  -webkit-box-shadow: 0 0 1px rgba(255,255,255,.5);
}

this will always show the vertical and horizontal scroll bar on your page. If you need only a vertical scroll bar then put overflow-x: hidden