Programs & Examples On #Morphic

Morphic is a user interface framework first developed for Self and later ported to Squeak Smalltalk. It is used in the Smalltalk implementations Squeak, Pharo and Cuis and in the JavaScript programming environment Lively Kernel.

What is the Record type in typescript?

  1. Can someone give a simple definition of what Record is?

A Record<K, T> is an object type whose property keys are K and whose property values are T. That is, keyof Record<K, T> is equivalent to K, and Record<K, T>[K] is (basically) equivalent to T.

  1. Is Record<K,T> merely a way of saying "all properties on this object will have type T"? Probably not all objects, since K has some purpose...

As you note, K has a purpose... to limit the property keys to particular values. If you want to accept all possible string-valued keys, you could do something like Record<string, T>, but the idiomatic way of doing that is to use an index signature like { [k: string]: T }.

  1. Does the K generic forbid additional keys on the object that are not K, or does it allow them and just indicate that their properties are not transformed to T?

It doesn't exactly "forbid" additional keys: after all, a value is generally allowed to have properties not explicitly mentioned in its type... but it wouldn't recognize that such properties exist:

declare const x: Record<"a", string>;
x.b; // error, Property 'b' does not exist on type 'Record<"a", string>'

and it would treat them as excess properties which are sometimes rejected:

declare function acceptR(x: Record<"a", string>): void;
acceptR({a: "hey", b: "you"}); // error, Object literal may only specify known properties

and sometimes accepted:

const y = {a: "hey", b: "you"};
acceptR(y); // okay
  1. With the given example:

    type ThreeStringProps = Record<'prop1' | 'prop2' | 'prop3', string>
    

    Is it exactly the same as this?:

    type ThreeStringProps = {prop1: string, prop2: string, prop3: string}
    

Yes!

Hope that helps. Good luck!

'Access-Control-Allow-Origin' issue when API call made from React (Isomorphic app)

Create-React-App has a simple way to deal with this problem: add a proxy field to the package.json file as shown below

"proxy": "http://localhost:8081",

Deserialize JSON with Jackson into Polymorphic Types - A Complete Example is giving me a compile error

A simple way to enable polymorphic serialization / deserialization via Jackson library is to globally configure the Jackson object mapper (jackson.databind.ObjectMapper) to add information, such as the concrete class type, for certain kinds of classes, such as abstract classes.

To do that, just make sure your mapper is configured correctly. For example:

Option 1: Support polymorphic serialization / deserialization for abstract classes (and Object typed classes)

jacksonObjectMapper.enableDefaultTyping(
    ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE); 

Option 2: Support polymorphic serialization / deserialization for abstract classes (and Object typed classes), and arrays of those types.

jacksonObjectMapper.enableDefaultTyping(
    ObjectMapper.DefaultTyping.NON_CONCRETE_AND_ARRAYS); 

Reference: https://github.com/FasterXML/jackson-docs/wiki/JacksonPolymorphicDeserialization

Non-Static method cannot be referenced from a static context with methods and variables

Merely for the purposes of making your program work, take the contents of your main() method and put them in a constructor:

public BookStoreApp2()
{
   // Put contents of main method here
}

Then, in your main() method. Do this:

public void main( String[] args )
{
  new BookStoreApp2();
}

Exclude Blank and NA in R

A good idea is to set all of the "" (blank cells) to NA before any further analysis.

If you are reading your input from a file, it is a good choice to cast all "" to NAs:

foo <- read.table(file="Your_file.txt", na.strings=c("", "NA"), sep="\t") # if your file is tab delimited

If you have already your table loaded, you can act as follows:

foo[foo==""] <- NA

Then to keep only rows with no NA you may just use na.omit():

foo <- na.omit(foo)

Or to keep columns with no NA:

foo <- foo[, colSums(is.na(foo)) == 0] 

How to find a parent with a known class in jQuery?

Use .parentsUntil()

$(".d").parentsUntil(".a");

Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?

The issue has been correctly identified as related to variance but the details are not correct. A purely functional list is a covariant data functor, which means if a type Sub is a subtype of Super, then a list of Sub is definitely a subtype of a list of Super.

However mutability of a list is not the basic problem here. The problem is mutability in general. The problem is well known, and is called the Covariance Problem, it was first identified I think by Castagna, and it completely and utterly destroys object orientation as a general paradigm. It is based on previously established variance rules established by Cardelli and Reynolds.

Somewhat oversimplifying, lets consider assignment of an object B of type T to an object A of type T as a mutation. This is without loss of generality: a mutation of A can be written A = f (A) where f: T -> T. The problem, of course, is that whilst functions are covariant in their codomain, they're contravariant in their domain, but with assignments the domain and codomain are the same, so assignment is invariant!

It follows, generalising, that subtypes cannot be mutated. But with object orientation mutation is fundamental, hence object orientation is intrinsically flawed.

Here's a simple example: in a purely functional setting a symmetric matrix is clearly a matrix, it is a subtype, no problem. Now lets add to matrix the ability to set a single element at coordinates (x,y) with the rule no other element changes. Now symmetric matrix is no longer a subtype, if you change (x,y) you have also changed (y,x). The functional operation is delta: Sym -> Mat, if you change one element of a symmetric matrix you get a general non-symmetric matrix back. Therefore if you included a "change one element" method in Mat, Sym is not a subtype. In fact .. there are almost certainly NO proper subtypes.

To put all this in easier terms: if you have a general data type with a wide range of mutators which leverage its generality you can be certain any proper subtype cannot possibly support all those mutations: if it could, it would be just as general as the supertype, contrary to the specification of "proper" subtype.

The fact Java prevents subtyping mutable lists fails to address the real issue: why are you using object oriented rubbish like Java when it was discredited several decades ago??

In any case there's a reasonable discussion here:

https://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)

'typeid' versus 'typeof' in C++

The primary difference between the two is the following

  • typeof is a compile time construct and returns the type as defined at compile time
  • typeid is a runtime construct and hence gives information about the runtime type of the value.

typeof Reference: http://www.delorie.com/gnu/docs/gcc/gcc_36.html

typeid Reference: https://en.wikipedia.org/wiki/Typeid

Collectors.toMap() keyMapper -- more succinct expression?

List<Person> roster = ...;

Map<String, Person> map = 
    roster
        .stream()
        .collect(
            Collectors.toMap(p -> p.getLast(), p -> p)
        );

that would be the translation, but i havent run this or used the API. most likely you can substitute p -> p, for Function.identity(). and statically import toMap(...)

Print a variable in hexadecimal in Python

A way that will fail if your input string isn't valid pairs of hex characters...:

>>> import binascii
>>> ' '.join(hex(ord(i)) for i in binascii.unhexlify('deadbeef'))
'0xde 0xad 0xbe 0xef'

jQuery find and replace string

You could do something this way:

$(document.body).find('*').each(function() {
    if($(this).hasClass('lollypops')){ //class replacing..many ways to do this :)
        $(this).removeClass('lollypops');
        $(this).addClass('marshmellows');
    }
    var tmp = $(this).children().remove(); //removing and saving children to a tmp obj
    var text = $(this).text(); //getting just current node text
    text = text.replace(/lollypops/g, "marshmellows"); //replacing every lollypops occurence with marshmellows
    $(this).text(text); //setting text
    $(this).append(tmp); //re-append 'foundlings'
});

example: http://jsfiddle.net/steweb/MhQZD/

Using braces with dynamic variable names in PHP

Wrap them in {}:

${"file" . $i} = file($filelist[$i]);

Working Example


Using ${} is a way to create dynamic variables, simple example:

${'a' . 'b'} = 'hello there';
echo $ab; // hello there

Convert an ISO date to the date format yyyy-mm-dd in JavaScript

Just crop the string:

var date = new Date("2013-03-10T02:00:00Z");
date.toISOString().substring(0, 10);

Or if you need only date out of string.

var strDate = "2013-03-10T02:00:00Z";
strDate.substring(0, 10);

How to do a logical OR operation for integer comparison in shell scripting?

This should work:

#!/bin/bash

if [ "$#" -eq 0 ] || [ "$#" -gt 1 ] ; then
    echo "hello"
fi

I'm not sure if this is different in other shells but if you wish to use <, >, you need to put them inside double parenthesis like so:

if (("$#" > 1))
 ...

Clicking submit button of an HTML form by a Javascript code

You can do :

document.forms["loginForm"].submit()

But this won't call the onclick action of your button, so you will need to call it by hand.

Be aware that you must use the name of your form and not the id to access it.

What is the maximum number of characters that nvarchar(MAX) will hold?

2^31-1 bytes. So, a little less than 2^31-1 characters for varchar(max) and half that for nvarchar(max).

nchar and nvarchar

Wpf DataGrid Add new row

Try this MSDN blog

Also, try the following example:

Xaml:

   <DataGrid AutoGenerateColumns="False" Name="DataGridTest" CanUserAddRows="True" ItemsSource="{Binding TestBinding}" Margin="0,50,0,0" >
        <DataGrid.Columns>
            <DataGridTextColumn Header="Line" IsReadOnly="True" Binding="{Binding Path=Test1}" Width="50"></DataGridTextColumn>
            <DataGridTextColumn Header="Account" IsReadOnly="True"  Binding="{Binding Path=Test2}" Width="130"></DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>
    <Button Content="Add new row" HorizontalAlignment="Left" Margin="0,10,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1"/>

CS:

 /// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        var data = new Test { Test1 = "Test1", Test2 = "Test2" };

        DataGridTest.Items.Add(data);
    }
}

public class Test
{
    public string Test1 { get; set; }
    public string Test2 { get; set; }
}

Plot two graphs in same plot in R

Idiomatic Matlab plot(x1,y1,x2,y2) can be translated in R with ggplot2 for example in this way:

x1 <- seq(1,10,.2)
df1 <- data.frame(x=x1,y=log(x1),type="Log")
x2 <- seq(1,10)
df2 <- data.frame(x=x2,y=cumsum(1/x2),type="Harmonic")

df <- rbind(df1,df2)

library(ggplot2)
ggplot(df)+geom_line(aes(x,y,colour=type))

enter image description here

Inspired by Tingting Zhao's Dual line plots with different range of x-axis Using ggplot2.

TypeError: 'dict_keys' object does not support indexing

Clearly you're passing in d.keys() to your shuffle function. Probably this was written with python2.x (when d.keys() returned a list). With python3.x, d.keys() returns a dict_keys object which behaves a lot more like a set than a list. As such, it can't be indexed.

The solution is to pass list(d.keys()) (or simply list(d)) to shuffle.

selenium - chromedriver executable needs to be in PATH

You can download ChromeDriver here: https://sites.google.com/a/chromium.org/chromedriver/downloads

Then you have multiple options:

  • add it to your system path
  • put it in the same directory as your python script
  • specify the location directly via executable_path

    driver = webdriver.Chrome(executable_path='C:/path/to/chromedriver.exe')
    

Where is the <conio.h> header file on Linux? Why can't I find <conio.h>?

That is because is does not exist, since it is bounded to Windows.

Use the standard functions from <stdio.h> instead, such as getc

The suggested ncurses library is good if you want to write console-based GUIs, but I don't think it is what you want.

Type datetime for input parameter in procedure

In this part of your SP:

IF @DateFirst <> '' and @DateLast <> ''
   set @FinalSQL  = @FinalSQL
       + '  or convert (Date,DateLog) >=     ''' + @DateFirst
       + ' and convert (Date,DateLog) <=''' + @DateLast  

you are trying to concatenate strings and datetimes.

As the datetime type has higher priority than varchar/nvarchar, the + operator, when it happens between a string and a datetime, is interpreted as addition, not as concatenation, and the engine then tries to convert your string parts (' or convert (Date,DateLog) >= ''' and others) to datetime or numeric values. And fails.

That doesn't happen if you omit the last two parameters when invoking the procedure, because the condition evaluates to false and the offending statement isn't executed.

To amend the situation, you need to add explicit casting of your datetime variables to strings:

set @FinalSQL  = @FinalSQL
    + '  or convert (Date,DateLog) >=     ''' + convert(date, @DateFirst)
    + ' and convert (Date,DateLog) <=''' + convert(date, @DateLast)

You'll also need to add closing single quotes:

set @FinalSQL  = @FinalSQL
    + '  or convert (Date,DateLog) >=     ''' + convert(date, @DateFirst) + ''''
    + ' and convert (Date,DateLog) <=''' + convert(date, @DateLast) + ''''

How to insert date values into table

Since dob is DATE data type, you need to convert the literal to DATE using TO_DATE and the proper format model. The syntax is:

TO_DATE('<date_literal>', '<format_model>')

For example,

SQL> CREATE TABLE t(dob DATE);

Table created.

SQL> INSERT INTO t(dob) VALUES(TO_DATE('17/12/2015', 'DD/MM/YYYY'));

1 row created.

SQL> COMMIT;

Commit complete.

SQL> SELECT * FROM t;

DOB
----------
17/12/2015

A DATE data type contains both date and time elements. If you are not concerned about the time portion, then you could also use the ANSI Date literal which uses a fixed format 'YYYY-MM-DD' and is NLS independent.

For example,

SQL> INSERT INTO t(dob) VALUES(DATE '2015-12-17');

1 row created.

500 internal server error, how to debug

Try writing all the errors to a file.

error_reporting(-1); // reports all errors
ini_set("display_errors", "1"); // shows all errors
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");

Something like that.

How do I get the file name from a String containing the Absolute file path?

The other answers didn't quite work for my specific scenario, where I am reading paths that have originated from an OS different to my current one. To elaborate I am saving email attachments saved from a Windows platform on a Linux server. The filename returned from the JavaMail API is something like 'C:\temp\hello.xls'

The solution I ended up with:

String filenameWithPath = "C:\\temp\\hello.xls";
String[] tokens = filenameWithPath.split("[\\\\|/]");
String filename = tokens[tokens.length - 1];

nginx error "conflicting server name" ignored

You have another server_name ec2-xx-xx-xxx-xxx.us-west-1.compute.amazonaws.com somewhere in the config.

Querying DynamoDB by date

Your Hash key (primary of sort) has to be unique (unless you have a range like stated by others).

In your case, to query your table you should have a secondary index.

|  ID  | DataID | Created | Data |
|------+--------+---------+------|
| hash | xxxxx  | 1234567 | blah |

Your Hash Key is ID Your secondary index is defined as: DataID-Created-index (that's the name that DynamoDB will use)

Then, you can make a query like this:

var params = {
    TableName: "Table",
    IndexName: "DataID-Created-index",
    KeyConditionExpression: "DataID = :v_ID AND Created > :v_created",
    ExpressionAttributeValues: {":v_ID": {S: "some_id"},
                                ":v_created": {N: "timestamp"}
    },
    ProjectionExpression: "ID, DataID, Created, Data"
};

ddb.query(params, function(err, data) {
    if (err) 
        console.log(err);
    else {
        data.Items.sort(function(a, b) {
            return parseFloat(a.Created.N) - parseFloat(b.Created.N);
        });
        // More code here
    }
});

Essentially your query looks like:

SELECT * FROM TABLE WHERE DataID = "some_id" AND Created > timestamp;

The secondary Index will increase the read/write capacity units required so you need to consider that. It still is a lot better than doing a scan, which will be costly in reads and in time (and is limited to 100 items I believe).

This may not be the best way of doing it but for someone used to RD (I'm also used to SQL) it's the fastest way to get productive. Since there is no constraints in regards to schema, you can whip up something that works and once you have the bandwidth to work on the most efficient way, you can change things around.

Ant: How to execute a command for each file in directory?

ant-contrib is evil; write a custom ant task.

ant-contrib is evil because it tries to convert ant from a declarative style to an imperative style. But xml makes a crap programming language.

By contrast a custom ant task allows you to write in a real language (Java), with a real IDE, where you can write unit tests to make sure you have the behavior you want, and then make a clean declaration in your build script about the behavior you want.

This rant only matters if you care about writing maintainable ant scripts. If you don't care about maintainability by all means do whatever works. :)

Jtf

Laravel - Route::resource vs Route::controller

For route controller method we have to define only one route. In get or post method we have to define the route separately.

And the resources method is used to creates multiple routes to handle a variety of Restful actions.

Here the Laravel documentation about this.

Is there a GUI design app for the Tkinter / grid geometry?

You have VisualTkinter also known as Visual Python. Development seems not active. You have sourceforge and googlecode sites. Web site is here.

On the other hand, you have PAGE that seems active and works in python 2.7 and py3k

As you indicate on your comment, none of these use the grid geometry. As far as I can say the only GUI builder doing that could probably be Komodo Pro GUI Builder which was discontinued and made open source in ca. 2007. The code was located in the SpecTcl repository.

It seems to install fine on win7 although has not used it yet. This is an screenshot from my PC:

enter image description here

By the way, Rapyd Tk also had plans to implement grid geometry as in its documentation says it is not ready 'yet'. Unfortunately it seems 'nearly' abandoned.

How to know/change current directory in Python shell?

Changing the current directory is not the way to deal with finding modules in Python.

Rather, see the docs for The Module Search Path for how Python finds which module to import.

Here is a relevant bit from Standard Modules section:

The variable sys.path is a list of strings that determines the interpreter’s search path for modules. It is initialized to a default path taken from the environment variable PYTHONPATH, or from a built-in default if PYTHONPATH is not set. You can modify it using standard list operations:

>>> import sys
>>> sys.path.append('/ufs/guido/lib/python')

In answer your original question about getting and setting the current directory:

>>> help(os.getcwd)

getcwd(...)
    getcwd() -> path

    Return a string representing the current working directory.

>>> help(os.chdir)

chdir(...)
    chdir(path)

    Change the current working directory to the specified path.

Loading all images using imread from a given folder

import os
import cv2
rootdir = "directory path"
for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        frame = cv2.imread(os.path.join(subdir, file)) 

Should IBOutlets be strong or weak under ARC?

I think that most important information is: Elements in xib are automatically in subviews of view. Subviews is NSArray. NSArray owns it's elements. etc have strong pointers on them. So in most cases you don't want to create another strong pointer (IBOutlet)

And with ARC you don't need to do anything in viewDidUnload

How to display Oracle schema size with SQL query?

You probably want

SELECT sum(bytes)
  FROM dba_segments
 WHERE owner = <<owner of schema>>

If you are logged in as the schema owner, you can also

SELECT SUM(bytes)
  FROM user_segments

That will give you the space allocated to the objects owned by the user in whatever tablespaces they are in. There may be empty space allocated to the tables that is counted as allocated by these queries.

Directory Chooser in HTML page

Can't be done in pure HTML/JavaScript for security reasons.

Selecting a file for upload is the best you can do, and even then you won't get its full original path in modern browsers.

You may be able to put something together using Java or Flash (e.g. using SWFUpload as a basis), but it's a lot of work and brings additional compatibility issues.

Another thought would be opening an iframe showing the user's C: drive (or whatever) but even if that's possible nowadays (could be blocked for security reasons, haven't tried in a long time) it will be impossible for your web site to communicate with the iframe (again for security reasons).

What do you need this for?

HTML code for an apostrophe

Here is a great reference for HTML Ascii codes:

http://www.ascii.cl/htmlcodes.htm

The code you are looking for is: &#39;

Two Divs on the same row and center align both of them

Align to the center, using display: inline-block and text-align: center.

_x000D_
_x000D_
.outerdiv_x000D_
{_x000D_
    height:100px;_x000D_
    width:500px;_x000D_
    background: red;_x000D_
    margin: 0 auto;_x000D_
    text-align: center;_x000D_
}_x000D_
_x000D_
.innerdiv_x000D_
{_x000D_
    height:40px;_x000D_
    width: 100px;_x000D_
    margin: 2px;_x000D_
    box-sizing: border-box;_x000D_
    background: green;_x000D_
    display: inline-block;_x000D_
}
_x000D_
<div class="outerdiv">_x000D_
    <div class="innerdiv"></div>_x000D_
    <div class="innerdiv"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Align to the center using display: flex and justify-content: center

_x000D_
_x000D_
.outerdiv_x000D_
{_x000D_
    height:100px;_x000D_
    width:500px;_x000D_
    background: red;_x000D_
    display: flex;_x000D_
    flex-direction: row;_x000D_
    justify-content: center;_x000D_
}_x000D_
_x000D_
.innerdiv_x000D_
{_x000D_
    height:40px;_x000D_
    width: 100px;_x000D_
    margin: 2px;_x000D_
    box-sizing: border-box;_x000D_
    background: green;_x000D_
}
_x000D_
<div class="outerdiv">_x000D_
    <div class="innerdiv"></div>_x000D_
    <div class="innerdiv"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Align to the center vertically and horizontally using display: flex, justify-content: center and align-items:center.

_x000D_
_x000D_
.outerdiv_x000D_
{_x000D_
    height:100px;_x000D_
    width:500px;_x000D_
    background: red;_x000D_
    display: flex;_x000D_
    flex-direction: row;_x000D_
    justify-content: center;_x000D_
    align-items:center;_x000D_
}_x000D_
_x000D_
.innerdiv_x000D_
{_x000D_
    height:40px;_x000D_
    width: 100px;_x000D_
    margin: 2px;_x000D_
    box-sizing: border-box;_x000D_
    background: green;_x000D_
}
_x000D_
<div class="outerdiv">_x000D_
    <div class="innerdiv"></div>_x000D_
    <div class="innerdiv"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Convert varchar to float IF ISNUMERIC

I found this very annoying bug while converting EmployeeID values with ISNUMERIC:

SELECT DISTINCT [EmployeeID],
ISNUMERIC(ISNULL([EmployeeID], '')) AS [IsNumericResult],

CASE WHEN COALESCE(NULLIF(tmpImport.[EmployeeID], ''), 'Z')
    LIKE '%[^0-9]%' THEN 'NonNumeric' ELSE 'Numeric'
END AS [IsDigitsResult]
FROM [MyTable]

This returns:

EmployeeID IsNumericResult MyCustomResult
---------- --------------- --------------
           0               NonNumeric
00000000c  0               NonNumeric
00D026858  1               NonNumeric

(3 row(s) affected)

Hope this helps!

Can you use if/else conditions in CSS?

Not in the traditional sense, but you can use classes for this, if you have access to the HTML. Consider this:

<p class="normal">Text</p>

<p class="active">Text</p>

and in your CSS file:

p.normal {
  background-position : 150px 8px;
}
p.active {
  background-position : 4px 8px;
}

That's the CSS way to do it.


Then there are CSS preprocessors like Sass. You can use conditionals there, which'd look like this:

$type: monster;
p {
  @if $type == ocean {
    color: blue;
  } @else if $type == matador {
    color: red;
  } @else if $type == monster {
    color: green;
  } @else {
    color: black;
  }
}

Disadvantages are, that you're bound to pre-process your stylesheets, and that the condition is evaluated at compile time, not run time.


A newer feature of CSS proper are custom properties (a.k.a. CSS variables). They are evaluated at run time (in browsers supporting them).

With them you could do something along the line:

:root {
  --main-bg-color: brown;
}

.one {
  background-color: var(--main-bg-color);
}

.two {
  background-color: black;
}

Finally, you can preprocess your stylesheet with your favourite server-side language. If you're using PHP, serve a style.css.php file, that looks something like this:

p {
  background-position: <?php echo (@$_GET['foo'] == 'bar')? "150" : "4"; ?>px 8px;
}

In this case, you will however have a performance impact, since caching such a stylesheet will be difficult.

How to find duplicate records in PostgreSQL

In order to make it easier I assume that you wish to apply a unique constraint only for column year and the primary key is a column named id.

In order to find duplicate values you should run,

SELECT year, COUNT(id)
FROM YOUR_TABLE
GROUP BY year
HAVING COUNT(id) > 1
ORDER BY COUNT(id);

Using the sql statement above you get a table which contains all the duplicate years in your table. In order to delete all the duplicates except of the the latest duplicate entry you should use the above sql statement.

DELETE
FROM YOUR_TABLE A USING YOUR_TABLE_AGAIN B
WHERE A.year=B.year AND A.id<B.id;

Is there a function to copy an array in C/C++?

I like the answer of Ed S., but this only works for fixed size arrays and not when the arrays are defined as pointers.

So, the C++ solution where the arrays are defined as pointers:

#include<algorithm>
...
const int bufferSize = 10;
char* origArray, newArray;
std::copy(origArray, origArray + bufferSize, newArray);

Note: No need to deduct buffersize with 1:

  1. Copies all elements in the range [first, last) starting from first and proceeding to last - 1

See: https://en.cppreference.com/w/cpp/algorithm/copy

How to replace all dots in a string using JavaScript

Here's another implementation of replaceAll. Hope it helps someone.

    String.prototype.replaceAll = function (stringToFind, stringToReplace) {
        if (stringToFind === stringToReplace) return this;
        var temp = this;
        var index = temp.indexOf(stringToFind);
        while (index != -1) {
            temp = temp.replace(stringToFind, stringToReplace);
            index = temp.indexOf(stringToFind);
        }
        return temp;
    };

Then you can use it:

var myText = "My Name is George";
var newText = myText.replaceAll("George", "Michael");

How can I position my div at the bottom of its container?

Yes you can do this without absolute positioning and without using tables (which screw with markup and such).

DEMO
This is tested to work on IE>7, chrome, FF & is a really easy thing to add to your existing layout.

<div id="container">
    Some content you don't want affected by the "bottom floating" div
    <div>supports not just text</div>

    <div class="foot">
        Some other content you want kept to the bottom
        <div>this is in a div</div>
    </div>
</div>
#container {
    height:100%;
    border-collapse:collapse;
    display : table;
}

.foot {
    display : table-row;
    vertical-align : bottom;
    height : 1px;
}

It effectively does what float:bottom would, even accounting for the issue pointed out in @Rick Reilly's answer!

Reset git proxy to default configuration

Edit .gitconfig file (Probably in your home directory of the user ~) and change the http and https proxy fields to space only

[http]
    proxy = 
[https]
    proxy = 

That worked for me in the windows.

How do you use String.substringWithRange? (or, how do Ranges work in Swift?)

It is much more simple than any of the answers here, once you find the right syntax.

I want to take away the [ and ]

let myString = "[ABCDEFGHI]"
let startIndex = advance(myString.startIndex, 1) //advance as much as you like
let endIndex = advance(myString.endIndex, -1)
let range = startIndex..<endIndex
let myNewString = myString.substringWithRange( range )

result will be "ABCDEFGHI" the startIndex and endIndex could also be used in

let mySubString = myString.substringFromIndex(startIndex)

and so on!

PS: As indicated in the remarks, there are some syntax changes in swift 2 which comes with xcode 7 and iOS9!

Please look at this page

Oracle SqlDeveloper JDK path

In your SQL Developer Bin Folder find

\sqldeveloper\bin\sqldeveloper.conf

It should be

SetJavaHome \path\to\jdk

You said it was ../../jdk originally so you could ultimatey do 1 of two things:

SetJavaHome C:\Program Files\Java\jdk1.7.0_60

This is assuming that you have JDK 1.7.60 installed in that directory; you don't want to point it to the bin folder you want the whole JDK folder.

OR

The second thing you can do is find the jdk folder in the sqldeveloper folder for me its sqldeveloper\jdk and copy and paste the contents from C:\Program Files\Java\jdk1.7.0_60. You then have to revert your change to read

SetJavaHome ../../jdk

in your sqldeveloper.conf

If all else fails you can always redownload the sqldeveloper that already contains the jdk7 all zipped up and ready for you to run at will: Download SQL Developer The file I talk about is called Windows 64-bit - zip file includes the JDK 7

How to convert string values from a dictionary, into int/float datatypes?

For python 3,

    for d in list:
        d.update((k, float(v)) for k, v in d.items())

Django download a file

If you hafe upload your file in media than:

media
example-input-file.txt

views.py

def download_csv(request):    
    file_path = os.path.join(settings.MEDIA_ROOT, 'example-input-file.txt')    
    if os.path.exists(file_path):    
        with open(file_path, 'rb') as fh:    
            response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel")    
            response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)    
            return response

urls.py

path('download_csv/', views.download_csv, name='download_csv'),

download.html

a href="{% url 'download_csv' %}" download=""

ValueError: object too deep for desired array while using convolution

You could try using scipy.ndimage.convolve it allows convolution of multidimensional images. here is the docs

Giving height to table and row in Bootstrap

What worked for me was adding a div around the content. Originally i had this. Css applied to the td had no effect.

        <td>           
             @Html.DisplayFor(modelItem => item.Message)           
        </td>

Then I wrapped the content in a div and the css worked as expected

       <td>
            <div class="largeContent">
                @Html.DisplayFor(modelItem => item.Message)
            </div>
        </td>

Rails params explained?

The params come from the user's browser when they request the page. For an HTTP GET request, which is the most common, the params are encoded in the url. For example, if a user's browser requested

http://www.example.com/?foo=1&boo=octopus

then params[:foo] would be "1" and params[:boo] would be "octopus".

In HTTP/HTML, the params are really just a series of key-value pairs where the key and the value are strings, but Ruby on Rails has a special syntax for making the params be a hash with hashes inside. For example, if the user's browser requested

http://www.example.com/?vote[item_id]=1&vote[user_id]=2

then params[:vote] would be a hash, params[:vote][:item_id] would be "1" and params[:vote][:user_id] would be "2".

The Ruby on Rails params are the equivalent of the $_REQUEST array in PHP.

How to process each output line in a loop?

You can do the following while read loop, that will be fed by the result of the grep command using the so called process substitution:

while IFS= read -r result
do
    #whatever with value $result
done < <(grep "xyz" abc.txt)

This way, you don't have to store the result in a variable, but directly "inject" its output to the loop.


Note the usage of IFS= and read -r according to the recommendations in BashFAQ/001: How can I read a file (data stream, variable) line-by-line (and/or field-by-field)?:

The -r option to read prevents backslash interpretation (usually used as a backslash newline pair, to continue over multiple lines or to escape the delimiters). Without this option, any unescaped backslashes in the input will be discarded. You should almost always use the -r option with read.

In the scenario above IFS= prevents trimming of leading and trailing whitespace. Remove it if you want this effect.

Regarding the process substitution, it is explained in the bash hackers page:

Process substitution is a form of redirection where the input or output of a process (some sequence of commands) appear as a temporary file.

Heap space out of memory

If you are using a lot of memory and facing memory leaks, then you might want to check if you are using a large number of ArrayLists or HashMaps with many elements each.

An ArrayList is implemented as a dynamic array. The source code from Sun/Oracle shows that when a new element is inserted into a full ArrayList, a new array of 1.5 times the size of the original array is created, and the elements copied over. What this means is that you could be wasting up to 50% of the space in each ArrayList you use, unless you call its trimToSize method. Or better still, if you know the number of elements you are going to insert before hand, then call the constructor with the initial capacity as its argument.

I did not examine the source code for HashMap very carefully, but at a first glance it appears that the array length in each HashMap must be a power of two, making it another implementation of a dynamic array. Note that HashSet is essentially a wrapper around HashMap.

How to validate a form with multiple checkboxes to have atleast one checked

I had to do the same thing and this is what I wrote.I made it more flexible in my case as I had multiple group of check boxes to check.

// param: reqNum number of checkboxes to select
$.fn.checkboxValidate = function(reqNum){
    var fields = this.serializeArray();
    return (fields.length < reqNum) ? 'invalid' : 'valid';
}

then you can pass this function to check multiple group of checkboxes with multiple rules.

// helper function to create error
function err(msg){
    alert("Please select a " + msg + " preference.");
}

$('#reg').submit(function(e){
    //needs at lease 2 checkboxes to be selected
    if($("input.region, input.music").checkboxValidate(2) == 'invalid'){
        err("Region and Music");
    } 
});

CSS Child vs Descendant selectors

Yes, you are correct. div p will match the following example, but div > p will not.

<div><table><tr><td><p> <!...

The first one is called descendant selector and the second one is called child selector.

Create zip file and ignore directory structure

Alternatively, you could create a temporary symbolic link to your file:

ln -s /data/to/zip/data.txt data.txt
zip /dir/to/file/newZip !$
rm !$

This works also for a directory.

How to get rid of `deprecated conversion from string constant to ‘char*’` warnings in GCC?

Here is how to do it inline in a file, so you don't have to modify your Makefile.

// gets rid of annoying "deprecated conversion from string constant blah blah" warning
#pragma GCC diagnostic ignored "-Wwrite-strings"

You can then later...

#pragma GCC diagnostic pop

Setting a property with an EventTrigger

Stopping the Storyboard can be done in the code behind, or the xaml, depending on where the need comes from.

If the EventTrigger is moved outside of the button, then we can go ahead and target it with another EventTrigger that will tell the storyboard to stop. When the storyboard is stopped in this manner it will not revert to the previous value.

Here I've moved the Button.Click EventTrigger to a surrounding StackPanel and added a new EventTrigger on the the CheckBox.Click to stop the Button's storyboard when the CheckBox is clicked. This lets us check and uncheck the CheckBox when it is clicked on and gives us the desired unchecking behavior from the button as well.

    <StackPanel x:Name="myStackPanel">

        <CheckBox x:Name="myCheckBox"
                  Content="My CheckBox" />

        <Button Content="Click to Uncheck"
                x:Name="myUncheckButton" />

        <Button Content="Click to check the box in code."
                Click="OnClick" />

        <StackPanel.Triggers>

            <EventTrigger RoutedEvent="Button.Click"
                          SourceName="myUncheckButton">
                <EventTrigger.Actions>
                    <BeginStoryboard x:Name="myBeginStoryboard">
                        <Storyboard x:Name="myStoryboard">
                            <BooleanAnimationUsingKeyFrames Storyboard.TargetName="myCheckBox"
                                                            Storyboard.TargetProperty="IsChecked">
                                <DiscreteBooleanKeyFrame KeyTime="00:00:00"
                                                         Value="False" />
                            </BooleanAnimationUsingKeyFrames>
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger.Actions>
            </EventTrigger>

            <EventTrigger RoutedEvent="CheckBox.Click"
                          SourceName="myCheckBox">
                <EventTrigger.Actions>
                    <StopStoryboard BeginStoryboardName="myBeginStoryboard" />
                </EventTrigger.Actions>
            </EventTrigger>

        </StackPanel.Triggers>
    </StackPanel>

To stop the storyboard in the code behind, we will have to do something slightly different. The third button provides the method where we will stop the storyboard and set the IsChecked property back to true through code.

We can't call myStoryboard.Stop() because we did not begin the Storyboard through the code setting the isControllable parameter. Instead, we can remove the Storyboard. To do this we need the FrameworkElement that the storyboard exists on, in this case our StackPanel. Once the storyboard is removed, we can once again set the IsChecked property with it persisting to the UI.

    private void OnClick(object sender, RoutedEventArgs e)
    {
        myStoryboard.Remove(myStackPanel);
        myCheckBox.IsChecked = true;
    }

jQuery .css("margin-top", value) not updating in IE 8 (Standards mode)

The correct format for IE8 is:

  $("#ActionBox").css({ 'margin-top': '10px' });  

with this work.

Download a div in a HTML page as pdf using javascript

Content inside a <div class='html-content'>....</div> can be downloaded as pdf with styles using jspdf & html2canvas.

You need to refer both js libraries,

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
<script type="text/javascript" src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script>

Then call below function,

//Create PDf from HTML...
function CreatePDFfromHTML() {
    var HTML_Width = $(".html-content").width();
    var HTML_Height = $(".html-content").height();
    var top_left_margin = 15;
    var PDF_Width = HTML_Width + (top_left_margin * 2);
    var PDF_Height = (PDF_Width * 1.5) + (top_left_margin * 2);
    var canvas_image_width = HTML_Width;
    var canvas_image_height = HTML_Height;

    var totalPDFPages = Math.ceil(HTML_Height / PDF_Height) - 1;

    html2canvas($(".html-content")[0]).then(function (canvas) {
        var imgData = canvas.toDataURL("image/jpeg", 1.0);
        var pdf = new jsPDF('p', 'pt', [PDF_Width, PDF_Height]);
        pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin, canvas_image_width, canvas_image_height);
        for (var i = 1; i <= totalPDFPages; i++) { 
            pdf.addPage(PDF_Width, PDF_Height);
            pdf.addImage(imgData, 'JPG', top_left_margin, -(PDF_Height*i)+(top_left_margin*4),canvas_image_width,canvas_image_height);
        }
        pdf.save("Your_PDF_Name.pdf");
        $(".html-content").hide();
    });
}

Ref: pdf genration from html canvas and jspdf.

May be this will help someone.

How to get only the last part of a path in Python?

During my current projects, I'm often passing rear parts of a path to a function and therefore use the Path module. To get the n-th part in reverse order, I'm using:

from typing import Union
from pathlib import Path

def get_single_subpath_part(base_dir: Union[Path, str], n:int) -> str:
    if n ==0:
        return Path(base_dir).name
    for _ in range(n):
        base_dir = Path(base_dir).parent
    return getattr(base_dir, "name")

path= "/folderA/folderB/folderC/folderD/"

# for getting the last part:
print(get_single_subpath_part(path, 0))
# yields "folderD"

# for the second last
print(get_single_subpath_part(path, 1))
#yields "folderC"

Furthermore, to pass the n-th part in reverse order of a path containing the remaining path, I use:

from typing import Union
from pathlib import Path

def get_n_last_subparts_path(base_dir: Union[Path, str], n:int) -> Path:
    return Path(*Path(base_dir).parts[-n-1:])

path= "/folderA/folderB/folderC/folderD/"

# for getting the last part:
print(get_n_last_subparts_path(path, 0))
# yields a `Path` object of "folderD"

# for second last and last part together 
print(get_n_last_subparts_path(path, 1))
# yields a `Path` object of "folderc/folderD"

Note that this function returns a Pathobject which can easily be converted to a string (e.g. str(path))

Remove Last Comma from a string

The problem is that you remove the last comma in the string, not the comma if it's the last thing in the string. So you should put an if to check if the last char is ',' and change it if it is.

EDIT: Is it really that confusing?

'This, is a random string'

Your code finds the last comma from the string and stores only 'This, ' because, the last comma is after 'This' not at the end of the string.

Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

your google-services.json package name must match your build.gradle applicationId (applicationId "your package name")

WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'

1) Add android.debug.obsoleteApi=true to your gradle.properties. It will show you which modules is affected by your the warning log.

2) Update these deprecated functions.

  • variant.javaCompile to variant.javaCompileProvider

  • variant.javaCompile.destinationDir to variant.javaCompileProvider.get().destinationDir

Closing Excel Application Process in C# after Data Access

excelBook.Close(); excelApp.Quit(); add end of the code, it could be enough. it is working on my code

VBA code to set date format for a specific column as "yyyy-mm-dd"

Use the range's NumberFormat property to force the format of the range like this:

Sheet1.Range("A2", "A50000").NumberFormat = "yyyy-mm-dd"

ImportError: No module named PytQt5

This probably means that python doesn't know where PyQt5 is located. To check, go into the interactive terminal and type:

import sys
print sys.path

What you probably need to do is add the directory that contains the PyQt5 module to your PYTHONPATH environment variable. If you use bash, here's how:

Type the following into your shell, and add it to the end of the file ~/.bashrc

export PYTHONPATH=/path/to/PyQt5/directory:$PYTHONPATH

where /path/to/PyQt5/directory is the path to the folder where the PyQt5 library is located.

Can scripts be inserted with innerHTML?

Krasimir Tsonev has a great solution that overcome all problems. His method doesn't need using eval, so no performance nor security problems exist. It allows you to set innerHTML string contains html with js and translate it immediately to an DOM element while also executes the js parts exist along the code. short ,simple, and works exactly as you want.

Enjoy his solution:

http://krasimirtsonev.com/blog/article/Convert-HTML-string-to-DOM-element

Important notes:

  1. You need to wrap the target element with div tag
  2. You need to wrap the src string with div tag.
  3. If you write the src string directly and it includes js parts, please take attention to write the closing script tags correctly (with \ before /) as this is a string.

How to tell bash that the line continues on the next line

In general, you can use a backslash at the end of a line in order for the command to continue on to the next line. However, there are cases where commands are implicitly continued, namely when the line ends with a token than cannot legally terminate a command. In that case, the shell knows that more is coming, and the backslash can be omitted. Some examples:

# In general
$ echo "foo" \
> "bar"
foo bar

# Pipes
$ echo foo |
> cat
foo

# && and ||
$ echo foo &&
> echo bar
foo
bar
$ false ||
> echo bar
bar

Different, but related, is the implicit continuation inside quotes. In this case, without a backslash, you are simply adding a newline to the string.

$ x="foo
> bar"
$ echo "$x"
foo
bar

With a backslash, you are again splitting the logical line into multiple logical lines.

$ x="foo\
> bar"
$ echo "$x"
foobar

JavaScript for...in vs for

The two are not the same when the array is sparse.

var array = [0, 1, 2, , , 5];

for (var k in array) {
  // Not guaranteed by the language spec to iterate in order.
  alert(k);  // Outputs 0, 1, 2, 5.
  // Behavior when loop body adds to the array is unclear.
}

for (var i = 0; i < array.length; ++i) {
  // Iterates in order.
  // i is a number, not a string.
  alert(i);  // Outputs 0, 1, 2, 3, 4, 5
  // Behavior when loop body modifies array is clearer.
}

Error in Process.Start() -- The system cannot find the file specified

You can't use a filename like iexplore by itself because the path to internet explorer isn't listed in the PATH environment variable for the system or user.

However any path entered into the PATH environment variable allows you to use just the file name to execute it.

System32 isn't special in this regard as any directory can be added to the PATH variable. Each path is simply delimited by a semi-colon.

For example I have c:\ffmpeg\bin\ and c:\nmap\bin\ in my path environment variable, so I can do things like new ProcessStartInfo("nmap", "-foo") or new ProcessStartInfo("ffplay", "-bar")

The actual PATH variable looks like this on my machine.

%SystemRoot%\system32;C:\FFPlay\bin;C:\nmap\bin;

As you can see you can use other system variables, such as %SystemRoot% to build and construct paths in the environment variable.

So - if you add a path like "%PROGRAMFILES%\Internet Explorer;" to your PATH variable you will be able to use ProcessStartInfo("iexplore");

If you don't want to alter your PATH then simply use a system variable such as %PROGRAMFILES% or %SystemRoot% and then expand it when needed in code. i.e.

string path = Environment.ExpandEnvironmentVariables(
       @"%PROGRAMFILES%\Internet Explorer\iexplore.exe");
var info = new ProcessStartInfo(path);

What is the official name for a credit card's 3 digit code?

From Wikipedia,

The Card Security Code is located on the back of MasterCard, Visa and Discover credit or debit cards and is typically a separate group of 3 digits to the right of the signature strip. On American Express cards, the Card Security Code is a printed (NOT embossed) group of four digits on the front towards the right.

The Card Security Code (CSC), sometimes called Card Verification Value (CVV or CV2), Card Verification Value Code (CVVC), Card Verification Code (CVC), Verification Code (V-Code or V Code), or Card Code Verification (CCV)[1] is a security feature for credit or debit card transactions, giving increased protection against credit card fraud.

There are actually several types of security codes:

* The first code, called CVC1 or CVV1, is encoded on the magnetic stripe of the card and used for transactions in person.
* The second code, and the most cited, is CVV2 or CVC2. This CSC (also known as a CCID or Credit Card ID) is often asked for by merchants for them to secure "card not present" transactions occurring over the Internet, by mail, fax or over the phone. In many countries in Western Europe, due to increased attempts at card fraud, it is now mandatory to provide this code when the cardholder is not present in person.
* Contactless Card and Chip cards may supply their own codes generated electronically, such as iCVV or Dynamic CVV.

The CVC should not be confused with the standard card account number appearing in embossed or printed digits. (The standard card number undergoes a separate validation algorithm called the Luhn algorithm which serves to determine whether a given card's number is appropriate.)

The CVC should not be confused with PIN codes such as MasterCard SecureCode or Visa Verified by Visa. These codes are not printed or embedded in the card but are entered at the time of transaction using a keypad.

Code for a simple JavaScript countdown timer?

Based on the solution presented by @Layton Everson I developed a counter including hours, minutes and seconds:

var initialSecs = 86400;
var currentSecs = initialSecs;

setTimeout(decrement,1000); 

function decrement() {
   var displayedSecs = currentSecs % 60;
   var displayedMin = Math.floor(currentSecs / 60) % 60;
   var displayedHrs = Math.floor(currentSecs / 60 /60);

    if(displayedMin <= 9) displayedMin = "0" + displayedMin;
    if(displayedSecs <= 9) displayedSecs = "0" + displayedSecs;
    currentSecs--;
    document.getElementById("timerText").innerHTML = displayedHrs + ":" + displayedMin + ":" + displayedSecs;
    if(currentSecs !== -1) setTimeout(decrement,1000);
}

Struct memory layout in C

You can start by reading the data structure alignment wikipedia article to get a better understanding of data alignment.

From the wikipedia article:

Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory. To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.

From 6.54.8 Structure-Packing Pragmas of the GCC documentation:

For compatibility with Microsoft Windows compilers, GCC supports a set of #pragma directives which change the maximum alignment of members of structures (other than zero-width bitfields), unions, and classes subsequently defined. The n value below always is required to be a small power of two and specifies the new alignment in bytes.

  1. #pragma pack(n) simply sets the new alignment.
  2. #pragma pack() sets the alignment to the one that was in effect when compilation started (see also command line option -fpack-struct[=] see Code Gen Options).
  3. #pragma pack(push[,n]) pushes the current alignment setting on an internal stack and then optionally sets the new alignment.
  4. #pragma pack(pop) restores the alignment setting to the one saved at the top of the internal stack (and removes that stack entry). Note that #pragma pack([n]) does not influence this internal stack; thus it is possible to have #pragma pack(push) followed by multiple #pragma pack(n) instances and finalized by a single #pragma pack(pop).

Some targets, e.g. i386 and powerpc, support the ms_struct #pragma which lays out a structure as the documented __attribute__ ((ms_struct)).

  1. #pragma ms_struct on turns on the layout for structures declared.
  2. #pragma ms_struct off turns off the layout for structures declared.
  3. #pragma ms_struct reset goes back to the default layout.

Extract time from moment js object

If you read the docs (http://momentjs.com/docs/#/displaying/) you can find this format:

moment("2015-01-16T12:00:00").format("hh:mm:ss a")

See JS Fiddle http://jsfiddle.net/Bjolja/6mn32xhu/

Simple JavaScript Checkbox Validation

If the check box's ID "Delete" then for the "onclick" event of the submit button the javascript function can be as follows:

html:
<input type="checkbox" name="Delete" value="Delete" id="Delete"></td>
<input type="button" value="Delete" name="delBtn" id="delBtn" onclick="deleteData()">

script:
<script type="text/Javascript">
    function deleteData() {
        if(!document.getElementById('Delete').checked){
            alert('Checkbox not checked');
            return false;
        }
</script>

Python int to binary string?

Python 3.6 added a new string formatting approach called formatted string literals or “f-strings”. Example:

name = 'Bob'
number = 42
f"Hello, {name}, your number is {number:>08b}"

Output will be 'Hello, Bob, your number is 00001010!'

A discussion of this question can be found here - Here

Increase days to php current Date()

The date_add() function should do what you want. In addition, check out the docs (unofficial, but the official ones are a bit sparse) for the DateTime object, it's much nicer to work with than the procedural functions in PHP.

Nullable type as a generic parameter possible?

Change the return type to Nullable<T>, and call the method with the non nullable parameter

static void Main(string[] args)
{
    int? i = GetValueOrNull<int>(null, string.Empty);
}


public static Nullable<T> GetValueOrNull<T>(DbDataRecord reader, string columnName) where T : struct
{
    object columnValue = reader[columnName];

    if (!(columnValue is DBNull))
        return (T)columnValue;

    return null;
}

How to download a Nuget package without nuget.exe or Visual Studio extension?

Based on Xavier's answer, I wrote a Google chrome extension NuTake to add links to the Nuget.org package pages.

SQL Server Installation - What is the Installation Media Folder?

For the SQL Server 2017 (Developer Edition) installation, I did the following:

  1. Open SQL Server Installation Center
  2. Click on Installation
  3. Click on New SQL Server stand-alone installation or add features to an existing installation
  4. Browse to C:\SQLServer2017Media\Developer_ENU and click OK

How to check if a URL exists or returns 404 with Java?

Based on the given answers and information in the question, this is the code you should use:

public static boolean doesURLExist(URL url) throws IOException
{
    // We want to check the current URL
    HttpURLConnection.setFollowRedirects(false);

    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

    // We don't need to get data
    httpURLConnection.setRequestMethod("HEAD");

    // Some websites don't like programmatic access so pretend to be a browser
    httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)");
    int responseCode = httpURLConnection.getResponseCode();

    // We only accept response code 200
    return responseCode == HttpURLConnection.HTTP_OK;
}

Of course tested and working.

Get index of a key in json

What you have is a string representing a JSON serialized javascript object. You need to deserialize it back a javascript object before being able to loop through its properties. Otherwise you will be looping through each individual character of this string.

var resultJSON = '{ "key1" : "watevr1", "key2" : "watevr2", "key3" : "watevr3" }';
    var result = $.parseJSON(resultJSON);
    $.each(result, function(k, v) {
        //display the key and value pair
        alert(k + ' is ' + v);
    });

or simply:

arr.forEach(function (val, index, theArray) {
    //do stuff
});

Network usage top/htop on Linux

Check bmon. It's cli, simple and has charts.

Not exactly what question asked - it doesn't split by processes, only by network interfaces.

nginx error connect to php5-fpm.sock failed (13: Permission denied)

Simple but works..

listen.owner = nginx
listen.group = nginx

chown nginx:nginx /var/run/php-fpm/php-fpm.sock

How do you find all subclasses of a given class in Java?

It should be noted as well that this will of course only find all those subclasses that exist on your current classpath. Presumably this is OK for what you are currently looking at, and chances are you did consider this, but if you have at any point released a non-final class into the wild (for varying levels of "wild") then it is entirely feasible that someone else has written their own subclass that you will not know about.

Thus if you happened to be wanting to see all subclasses because you want to make a change and are going to see how it affects subclasses' behaviour - then bear in mind the subclasses that you can't see. Ideally all of your non-private methods, and the class itself should be well-documented; make changes according to this documentation without changing the semantics of methods/non-private fields and your changes should be backwards-compatible, for any subclass that followed your definition of the superclass at least.

How to convert number of minutes to hh:mm format in TSQL?

DECLARE @Duration int

SET @Duration= 12540 /* for example big hour amount in minutes -> 209h */

SELECT CAST( CAST((@Duration) AS int) / 60 AS varchar) + ':'  + right('0' + CAST(CAST((@Duration) AS int) % 60 AS varchar(2)),2)

/* you will get hours and minutes divided by : */

Short IF - ELSE statement

The "ternary expression" x ? y : z can only be used for conditional assignment. That is, you could do something like:

String mood = inProfit() ? "happy" : "sad";

because the ternary expression is returning something (of type String in this example).

It's not really meant to be used as a short, in-line if-else. In particular, you can't use it if the individual parts don't return a value, or return values of incompatible types. (So while you could do this if both method happened to return the same value, you shouldn't invoke it for the side-effect purposes only).

So the proper way to do this would just be with an if-else block:

if (jXPanel6.isVisible()) {
    jXPanel6.setVisible(true);
}
else {
    jXPanel6.setVisible(false);
}

which of course can be shortened to

jXPanel6.setVisible(jXPanel6.isVisible());

Both of those latter expressions are, for me, more readable in that they more clearly communicate what it is you're trying to do. (And by the way, did you get your conditions the wrong way round? It looks like this is a no-op anyway, rather than a toggle).

Don't mix up low character count with readability. The key point is what is most easily understood; and mildly misusing language features is a definite way to confuse readers, or at least make them do a mental double-take.

Docker error: invalid reference format: repository name must be lowercase

"docker build -f Dockerfile -t SpringBoot-Docker ." As in the above commend, we are creating an image file for docker container. commend says create image use file(-f refer to docker file) and -t for the target of the image file we are going to push to docker. the "." represents the current directory

solution for the above problem: provide target image name in lowercase

Read file line by line using ifstream in C++

This is a general solution to loading data into a C++ program, and uses the readline function. This could be modified for CSV files, but the delimiter is a space here.

int n = 5, p = 2;

int X[n][p];

ifstream myfile;

myfile.open("data.txt");

string line;
string temp = "";
int a = 0; // row index 

while (getline(myfile, line)) { //while there is a line
     int b = 0; // column index
     for (int i = 0; i < line.size(); i++) { // for each character in rowstring
          if (!isblank(line[i])) { // if it is not blank, do this
              string d(1, line[i]); // convert character to string
              temp.append(d); // append the two strings
        } else {
              X[a][b] = stod(temp);  // convert string to double
              temp = ""; // reset the capture
              b++; // increment b cause we have a new number
        }
    }

  X[a][b] = stod(temp);
  temp = "";
  a++; // onto next row
}

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.

Get random boolean in Java

Have you tried looking at the Java Documentation?

Returns the next pseudorandom, uniformly distributed boolean value from this random number generator's sequence ... the values true and false are produced with (approximately) equal probability.

For example:

import java.util.Random;

Random random = new Random();
random.nextBoolean();

xlsxwriter: is there a way to open an existing worksheet in my workbook?

You can use the workbook.get_worksheet_by_name() feature: https://xlsxwriter.readthedocs.io/workbook.html#get_worksheet_by_name

According to https://xlsxwriter.readthedocs.io/changes.html the feature has been added on May 13, 2016.

"Release 0.8.7 - May 13 2016

-Fix for issue when inserting read-only images on Windows. Issue #352.

-Added get_worksheet_by_name() method to allow the retrieval of a worksheet from a workbook via its name.

-Fixed issue where internal file creation and modification dates were in the local timezone instead of UTC."

DB2 SQL error: SQLCODE: -206, SQLSTATE: 42703

That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:

DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87

Double check your table definition. Maybe you just missed adding something.

I also tried google-ing this problem and saw this:

http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode

How to access Spring context in jUnit tests annotated with @RunWith and @ContextConfiguration?

Since the tests will be instantiated like a Spring bean too, you just need to implement the ApplicationContextAware interface:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/services-test-config.xml"})
public class MySericeTest implements ApplicationContextAware
{

  @Autowired
  MyService service;
...
    @Override
    public void setApplicationContext(ApplicationContext context)
            throws BeansException
    {
        // Do something with the context here
    }
}

-XX:MaxPermSize with or without -XX:PermSize

If you're doing some performance tuning it's often recommended to set both -XX:PermSize and -XX:MaxPermSize to the same value to increase JVM efficiency.

Here is some information:

  1. Support for large page heap on x86 and amd64 platforms
  2. Java Support for Large Memory Pages
  3. Setting the Permanent Generation Size

You can also specify -XX:+CMSClassUnloadingEnabled to enable class unloading option if you are using CMS GC. It may help to decrease the probability of Java.lang.OutOfMemoryError: PermGen space

IIS AppPoolIdentity and file system write access permissions

Each application pool in IIs creates its own secure user folder with FULL read/write permission by default under c:\users. Open up your Users folder and see what application pool folders are there, right click, and check their rights for the application pool virtual account assigned. You should see your application pool account added already with read/write access assigned to its root and subfolders.

So that type of file storage access is automatically done and you should be able to write whatever you like there in the app pools user account folders without changing anything. That's why virtual user accounts for each application pool were created.

SQL Server Management Studio alternatives to browse/edit tables and run queries

There is an express version on SSMS that has considerably fewer features but still has the basics.

How to implement a Keyword Search in MySQL?

I will explain the method i usally prefer:

First of all you need to take into consideration that for this method you will sacrifice memory with the aim of gaining computation speed. Second you need to have a the right to edit the table structure.

1) Add a field (i usually call it "digest") where you store all the data from the table.

The field will look like:

"n-n1-n2-n3-n4-n5-n6-n7-n8-n9" etc.. where n is a single word

I achieve this using a regular expression thar replaces " " with "-". This field is the result of all the table data "digested" in one sigle string.

2) Use the LIKE statement %keyword% on the digest field:

SELECT * FROM table WHERE digest LIKE %keyword%

you can even build a qUery with a little loop so you can search for multiple keywords at the same time looking like:

SELECT * FROM table WHERE 
 digest LIKE %keyword1% AND 
 digest LIKE %keyword2% AND 
 digest LIKE %keyword3% ... 

WPF Label Foreground Color

I checked your XAML, it works fine - e.g. both labels have a gray foreground.
My guess is that you have some style which is affecting the way it looks...

Try moving your XAML to a brand-new window and see for yourself... Then, check if you have any themes or styles (in the Window.Resources for instance) which might be affecting the labels...

HRESULT: 0x80131040: The located assembly's manifest definition does not match the assembly reference

This usually happens when the version of one of the DLLs of the testing environment does not match the development environment.

Clean and Build your solution and take all your DLLs to the environment where the error is happening that should fix it

How to work offline with TFS

There are couple of little visual studio extensions for this purpose:

  1. For VS2010 & TFS 2010, try this
  2. For VS2012 & TFS 2010, use this

In case of TFS 2012, looks like there is no need for 'Go offline' extensions. I read something about a new feature called local workspace for the similar purpose.

Alternatively I had good success with Git-TF. All the goodness of git and when you are ready, you can push it to TFS.

How to load a tsv file into a Pandas DataFrame?

df = pd.read_csv('filename.csv', sep='\t', header=0)

You can load the tsv file directly into pandas data frame by specifying delimitor and header.

What is the use of static variable in C#? When to use it? Why can't I declare the static variable inside method?

Static classes don't require you to create an object of that class/instantiate them, you can prefix the C# keyword static in front of the class name, to make it static.

Remember: we're not instantiating the Console class, String class, Array Class.

class Book
{
    public static int myInt = 0;
}

public class Exercise
{
    static void Main()
    {
        Book book = new Book();
       //Use the class name directly to call the property myInt, 
      //don't use the object to access the value of property myInt

        Console.WriteLine(Book.myInt);

        Console.ReadKey();

    }
}

Getting Current time to display in Label. VB.net

Use Date.Now instead of DateTime.Now

Two models in one view in ASP MVC 3

Another option which doesn't have the need to create a custom Model is to use a Tuple<>.

@model Tuple<Person,Order>

It's not as clean as creating a new class which contains both, as per Andi's answer, but it is viable.

How can I use "." as the delimiter with String.split() in java

Have you tried escaping the dot? like this:

String[] words = line.split("\\.");

Bytes of a string in Java

There's a method called getBytes(). Use it wisely .

HTML favicon won't show on google chrome

I moved ico file to root folder and link it. It worked for me. Also, in chrome, I have to wait 30 mins to get cache cleared and new changes to take affect.

Fastest way to check if a file exist using standard C++/C++11/C?

You can use std::ifstream, funcion like is_open, fail, for example as below code (the cout "open" means file exist or not):

enter image description here

enter image description here

cited from this answer

C++ initial value of reference to non-const must be an lvalue

The &nKByte creates a temporary value, which cannot be bound to a reference to non-const.

You could change void test(float *&x) to void test(float * const &x) or you could just drop the pointer altogether and use void test(float &x); /*...*/ test(nKByte);.

How can I get the number of days between 2 dates in Oracle 11g?

  • Full days between end of month and start of today, including the last day of the month:

    SELECT LAST_DAY (TRUNC(SysDate)) - TRUNC(SysDate) + 1 FROM dual
    
  • Days between using exact time:

    SELECT SysDate - TO_DATE('2018-01-01','YYYY-MM-DD') FROM dual
    

What is the difference between angular-route and angular-ui-router?

ngRoute is a module developed by the Angular.js team which was earlier part of the Angular core.

ui-router is a framework which was made outside the Angular.js project to improve and enhance routing capabalities.

Find when a file was deleted in Git

Try:

git log --stat | grep file

flow 2 columns of text automatically with CSS

Maybe a slightly tighter version? My use case is outputting college majors given a json array of majors (data).

var count_data      = data.length;

$.each( data, function( index ){
    var column = ( index < count_data/2 ) ? 1 : 2;
    $("#column"+column).append(this.name+'<br/>');
});

<div id="majors_view" class="span12 pull-left">

  <div class="row-fluid">
    <div class="span5" id="column1"> </div>
    <div class="span5 offset1" id="column2"> </div>
  </div>

</div>

Understanding `scale` in R

It provides nothing else but a standardization of the data. The values it creates are known under several different names, one of them being z-scores ("Z" because the normal distribution is also known as the "Z distribution").

More can be found here:

http://en.wikipedia.org/wiki/Standard_score

Getting time difference between two times in PHP

<?php
$start = strtotime("12:00");
$end = // Run query to get datetime value from db
$elapsed = $end - $start;
echo date("H:i", $elapsed);
?>

clk'event vs rising_edge()

Practical example:

Imagine that you are modelling something like an I2C bus (signals called SCL for clock and SDA for data), where the bus is tri-state and both nets have a weak pull-up. Your testbench should model the pull-up resistor on the PCB with a value of 'H'.

scl <= 'H'; -- Testbench resistor pullup

Your I2C master or slave devices can drive the bus to '1' or '0' or leave it alone by assigning a 'Z'

Assigning a '1' to the SCL net will cause an event to happen, because the value of SCL changed.

  • If you have a line of code that relies on (scl'event and scl = '1'), then you'll get a false trigger.

  • If you have a line of code that relies on rising_edge(scl), then you won't get a false trigger.

Continuing the example: you assign a '0' to SCL, then assign a 'Z'. The SCL net goes to '0', then back to 'H'.

Here, going from '1' to '0' isn't triggering either case, but going from '0' to 'H' will trigger a rising_edge(scl) condition (correct), but the (scl'event and scl = '1') case will miss it (incorrect).

General Recommenation:

Use rising_edge(clk) and falling_edge(clk) instead of clk'event for all code.

close fxml window by code, javafx

  1. give your close button an fx:id, if you haven't yet: <Button fx:id="closeButton" onAction="#closeButtonAction">
  2. In your controller class:

    @FXML private javafx.scene.control.Button closeButton;
    
    @FXML
    private void closeButtonAction(){
        // get a handle to the stage
        Stage stage = (Stage) closeButton.getScene().getWindow();
        // do what you have to do
        stage.close();
    }
    

How can I add shadow to the widget in flutter?

class ShadowContainer extends StatelessWidget {
  ShadowContainer({
    Key key,
    this.margin = const EdgeInsets.fromLTRB(0, 10, 0, 8),
    this.padding = const EdgeInsets.symmetric(horizontal: 8),
    this.circular = 4,
    this.shadowColor = const Color.fromARGB(
        128, 158, 158, 158), //Colors.grey.withOpacity(0.5),
    this.backgroundColor = Colors.white,
    this.spreadRadius = 1,
    this.blurRadius = 3,
    this.offset = const Offset(0, 1),
    @required this.child,
  }) : super(key: key);

  final Widget child;
  final EdgeInsetsGeometry margin;
  final EdgeInsetsGeometry padding;
  final double circular;
  final Color shadowColor;
  final double spreadRadius;
  final double blurRadius;
  final Offset offset;
  final Color backgroundColor;

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: margin,
      padding: padding,
      decoration: BoxDecoration(
        color: backgroundColor,
        borderRadius: BorderRadius.circular(circular),
        boxShadow: [
          BoxShadow(
            color: shadowColor,
            spreadRadius: spreadRadius,
            blurRadius: blurRadius,
            offset: offset,
          ),
        ],
      ),
      child: child,
    );
  }
}

what does it mean "(include_path='.:/usr/share/pear:/usr/share/php')"?

Thats just the directories showing you where PHP was looking for your file. Make sure that cron1.php exists where you think it does. And make sure you know where dirname(__FILE__) and $_SERVER['DOCUMENT_ROOT'] are pointing where you'd expect.

This value can be adjusted in your php.ini file.

Getting number of days in a month

To find the number of days in a month, DateTime class provides a method "DaysInMonth(int year, int month)". This method returns the total number of days in a specified month.

public int TotalNumberOfDaysInMonth(int year, int month)
    {
        return DateTime.DaysInMonth(year, month);
    }

OR

int days = DateTime.DaysInMonth(2018,05);

Output :- 31

Get the device width in javascript

Based on the method Bootstrap uses to set its Responsive breakpoints, the following function returns xs, sm, md, lg or xl based on the screen width:

_x000D_
_x000D_
console.log(breakpoint());

function breakpoint() {
    let breakpoints = {
        '(min-width: 1200px)': 'xl',
        '(min-width: 992px) and (max-width: 1199.98px)': 'lg',
        '(min-width: 768px) and (max-width: 991.98px)': 'md',
        '(min-width: 576px) and (max-width: 767.98px)': 'sm',
        '(max-width: 575.98px)': 'xs',
    }

    for (let media in breakpoints) {
        if (window.matchMedia(media).matches) {
            return breakpoints[media];
        }
    }

    return null;
}
_x000D_
_x000D_
_x000D_

How can I concatenate strings in VBA?

& is always evaluated in a string context, while + may not concatenate if one of the operands is no string:

"1" + "2" => "12"
"1" + 2   => 3
1 + "2"   => 3
"a" + 2   => type mismatch

This is simply a subtle source of potential bugs and therefore should be avoided. & always means "string concatenation", even if its arguments are non-strings:

"1" & "2" => "12"
"1" &  2  => "12"
 1  & "2" => "12"
 1  &  2  => "12"
"a" &  2  => "a2"

Instagram API to fetch pictures with specific hashtags

Firstly, the Instagram API endpoint "tags" required OAuth authentication.

You can query results for a particular hashtag (snowy in this case) using the following url

It is rate limited to 5000 (X-Ratelimit-Limit:5000) per hour

https://api.instagram.com/v1/tags/snowy/media/recent

Sample response

{
  "pagination":  {
    "next_max_tag_id": "1370433362010",
    "deprecation_warning": "next_max_id and min_id are deprecated for this endpoint; use min_tag_id and max_tag_id instead",
    "next_max_id": "1370433362010",
    "next_min_id": "1370443976800",
    "min_tag_id": "1370443976800",
    "next_url": "https://api.instagram.com/v1/tags/snowy/media/recent?access_token=40480112.1fb234f.4866541998fd4656a2e2e2beaa5c4bb1&max_tag_id=1370433362010"
  },
  "meta":  {
    "code": 200
  },
  "data":  [
     {
      "attribution": null,
      "tags":  [
        "snowy"
      ],
      "type": "image",
      "location": null,
      "comments":  {
        "count": 0,
        "data":  []
      },
      "filter": null,
      "created_time": "1370418343",
      "link": "http://instagram.com/p/aK1yrGRi3l/",
      "likes":  {
        "count": 1,
        "data":  [
           {
            "username": "iri92lol",
            "profile_picture": "http://images.ak.instagram.com/profiles/profile_404174490_75sq_1370417509.jpg",
            "id": "404174490",
            "full_name": "Iri"
          }
        ]
      },
      "images":  {
        "low_resolution":  {
          "url": "http://distilleryimage1.s3.amazonaws.com/ecf272a2cdb311e2990322000a9f192c_6.jpg",
          "width": 306,
          "height": 306
        },
        "thumbnail":  {
          "url": "http://distilleryimage1.s3.amazonaws.com/ecf272a2cdb311e2990322000a9f192c_5.jpg",
          "width": 150,
          "height": 150
        },
        "standard_resolution":  {
          "url": "http://distilleryimage1.s3.amazonaws.com/ecf272a2cdb311e2990322000a9f192c_7.jpg",
          "width": 612,
          "height": 612
        }
      },
      "users_in_photo":  [],
      "caption":  {
        "created_time": "1370418353",
        "text": "#snowy",
        "from":  {
          "username": "iri92lol",
          "profile_picture": "http://images.ak.instagram.com/profiles/profile_404174490_75sq_1370417509.jpg",
          "id": "404174490",
          "full_name": "Iri"
        },
        "id": "471425773832908504"
      },
      "user_has_liked": false,
      "id": "471425689728724453_404174490",
      "user":  {
        "username": "iri92lol",
        "website": "",
        "profile_picture": "http://images.ak.instagram.com/profiles/profile_404174490_75sq_1370417509.jpg",
        "full_name": "Iri",
        "bio": "",
        "id": "404174490"
      }
    }
}

You can play around here :

https://apigee.com/console/instagram?req=%7B%22resource%22%3A%22get_tags_media_recent%22%2C%22params%22%3A%7B%22query%22%3A%7B%7D%2C%22template%22%3A%7B%22tag-name%22%3A%22snowy%22%7D%2C%22headers%22%3A%7B%7D%2C%22body%22%3A%7B%22attachmentFormat%22%3A%22mime%22%2C%22attachmentContentDisposition%22%3A%22form-data%22%7D%7D%2C%22verb%22%3A%22get%22%7D

You need to use "Authentication" as OAuth 2 and will be prompted to signin via Instagram. Post that you might have to reneter the "tag-name" in "Template" section.

All the pagination related data is available in the "pagination" parameter in the response and use it's "next_url" to query for the next set of result.

Determine if map contains a value for a key?

It already exists with find only not in that exact syntax.

if (m.find(2) == m.end() )
{
    // key 2 doesn't exist
}

If you want to access the value if it exists, you can do:

map<int, Bar>::iterator iter = m.find(2);
if (iter != m.end() )
{
    // key 2 exists, do something with iter->second (the value)
}

With C++0x and auto, the syntax is simpler:

auto iter = m.find(2);
if (iter != m.end() )
{
    // key 2 exists, do something with iter->second (the value)
}

I recommend you get used to it rather than trying to come up with a new mechanism to simplify it. You might be able to cut down a little bit of code, but consider the cost of doing that. Now you've introduced a new function that people familiar with C++ won't be able to recognize.

If you want to implement this anyway in spite of these warnings, then:

template <class Key, class Value, class Comparator, class Alloc>
bool getValue(const std::map<Key, Value, Comparator, Alloc>& my_map, int key, Value& out)
{
    typename std::map<Key, Value, Comparator, Alloc>::const_iterator it = my_map.find(key);
    if (it != my_map.end() )
    {
        out = it->second;
        return true;
    }
    return false;
}

How to remove default mouse-over effect on WPF buttons?

Just to add a very simple solution, that was good enough for me, and I think addresses the OP's issue. I used the solution in this answer except with a regular Background value instead of an image.

<Style x:Key="SomeButtonStyle" TargetType="Button">
    <Setter Property="Background" Value="Transparent" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Grid Background="{TemplateBinding Background}">
                    <ContentPresenter />
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

No re-templating beyond forcing the Background to always be the Transparent background from the templated button - mouseover no longer affects the background once this is done. Obviously replace Transparent with any preferred value.

JavaScript variable number of arguments to function

As mentioned already, you can use the arguments object to retrieve a variable number of function parameters.

If you want to call another function with the same arguments, use apply. You can even add or remove arguments by converting arguments to an array. For example, this function inserts some text before logging to console:

log() {
    let args = Array.prototype.slice.call(arguments);
    args = ['MyObjectName', this.id_].concat(args);
    console.log.apply(console, args);
}

How to ORDER BY a SUM() in MySQL?

The problem I see here is that "sum" is an aggregate function.

first, you need to fix the query itself.

Select sum(c_counts + f_counts) total, [column to group sums by]
from table
group by [column to group sums by]

then, you can sort it:

Select *
from (query above) a
order by total

EDIT: But see post by Virat. Perhaps what you want is not the sum of your total fields over a group, but just the sum of those fields for each record. In that case, Virat has the right solution.

Iterator invalidation rules

It is probably worth adding that an insert iterator of any kind (std::back_insert_iterator, std::front_insert_iterator, std::insert_iterator) is guaranteed to remain valid as long as all insertions are performed through this iterator and no other independent iterator-invalidating event occurs.

For example, when you are performing a series of insertion operations into a std::vector by using std::insert_iterator it is quite possible that these insertions will trigger vector reallocation, which will invalidate all iterators that "point" into that vector. However, the insert iterator in question is guaranteed to remain valid, i.e. you can safely continue the sequence of insertions. There's no need to worry about triggering vector reallocation at all.

This, again, applies only to insertions performed through the insert iterator itself. If iterator-invalidating event is triggered by some independent action on the container, then the insert iterator becomes invalidated as well in accordance with the general rules.

For example, this code

std::vector<int> v(10);
std::vector<int>::iterator it = v.begin() + 5;
std::insert_iterator<std::vector<int> > it_ins(v, it);

for (unsigned n = 20; n > 0; --n)
  *it_ins++ = rand();

is guaranteed to perform a valid sequence of insertions into the vector, even if the vector "decides" to reallocate somewhere in the middle of this process. Iterator it will obviously become invalid, but it_ins will continue to remain valid.

How to restart Activity in Android

If you remove the last line, you'll create new act Activity, but your old instance will still be alive.

Do you need to restart the Activity like when the orientation is changed (i.e. your state is saved and passed to onCreate(Bundle))?

If you don't, one possible workaround would be to use one extra, dummy Activity, which would be started from the first Activity, and which job is to start new instance of it. Or just delay the call to act.finish(), after the new one is started.

If you need to save most of the state, you are getting in pretty deep waters, because it's non-trivial to pass all the properties of your state, especially without leaking your old Context/Activity, by passing it to the new instance.

Please, specify what are you trying to do.

Traverse all the Nodes of a JSON Object Tree with JavaScript

I wanted to use the perfect solution of @TheHippo in an anonymous function, without use of process and trigger functions. The following worked for me, sharing for novice programmers like myself.

(function traverse(o) {
    for (var i in o) {
        console.log('key : ' + i + ', value: ' + o[i]);

        if (o[i] !== null && typeof(o[i])=="object") {
            //going on step down in the object tree!!
            traverse(o[i]);
        }
    }
  })
  (json);

How do I make a MySQL database run completely in memory?

In place of the Memory storage engine, one can consider MySQL Cluster. It is said to give similar performance but to support disk-backed operation for durability. I've not tried it, but it looks promising (and been in development for a number of years).

You can find the official MySQL Cluster documentation here.

How to ignore SSL certificate errors in Apache HttpClient 4.0

This is how I did it -

  1. Create my own MockSSLSocketFactory (Class attached below)
  2. Use it to initialise DefaultHttpClient. Proxy settings need to be provided if a proxy is used.

Initialising DefaultHTTPClient -

SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, new MockSSLSocketFactory()));
    ClientConnectionManager cm = new SingleClientConnManager(schemeRegistry);

    DefaultHttpClient httpclient = new DefaultHttpClient(cm);

Mock SSL Factory -

public class MockSSLSocketFactory extends SSLSocketFactory {

public MockSSLSocketFactory() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    super(trustStrategy, hostnameVerifier);
}

private static final X509HostnameVerifier hostnameVerifier = new X509HostnameVerifier() {
    @Override
    public void verify(String host, SSLSocket ssl) throws IOException {
        // Do nothing
    }

    @Override
    public void verify(String host, X509Certificate cert) throws SSLException {
        //Do nothing
    }

    @Override
    public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
        //Do nothing
    }

    @Override
    public boolean verify(String s, SSLSession sslSession) {
        return true; 
    }
};

private static final TrustStrategy trustStrategy = new TrustStrategy() {
    @Override
    public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        return true;
    }
};
}

If behind a proxy, need to do this -

HttpParams params = new BasicHttpParams();
    params.setParameter(AuthPNames.PROXY_AUTH_PREF, getClientAuthPrefs());

DefaultHttpClient httpclient = new DefaultHttpClient(cm, params);

httpclient.getCredentialsProvider().setCredentials(
                        new AuthScope(proxyHost, proxyPort),
                        new UsernamePasswordCredentials(proxyUser, proxyPass));

How can I store HashMap<String, ArrayList<String>> inside a list?

class Student{
    //instance variable or data members.

    Map<Integer, List<Object>> mapp = new HashMap<Integer, List<Object>>();
    Scanner s1 = new Scanner(System.in);
    String name = s1.nextLine();
    int regno ;
    int mark1;
    int mark2;
    int total;
    List<Object> list = new ArrayList<Object>();
    mapp.put(regno,list); //what wrong in this part?
    list.add(mark1);
    list.add(mark2);**
    //String mark2=mapp.get(regno)[2];
}

Using HTML5/JavaScript to generate and save a file

OK, creating a data:URI definitely does the trick for me, thanks to Matthew and Dennkster pointing that option out! Here is basically how I do it:

1) get all the content into a string called "content" (e.g. by creating it there initially or by reading innerHTML of the tag of an already built page).

2) Build the data URI:

uriContent = "data:application/octet-stream," + encodeURIComponent(content);

There will be length limitations depending on browser type etc., but e.g. Firefox 3.6.12 works until at least 256k. Encoding in Base64 instead using encodeURIComponent might make things more efficient, but for me that was ok.

3) open a new window and "redirect" it to this URI prompts for a download location of my JavaScript generated page:

newWindow = window.open(uriContent, 'neuesDokument');

That's it.

Pass Javascript Variable to PHP POST

There is a lot of ways to achieve this. In regards to the way you are asking, with a hidden form element.

create this form element inside your form:

<input type="hidden" name="total" value="">

So your form like this:

<form id="sampleForm" name="sampleForm" method="post" action="phpscript.php">
<input type="hidden" name="total" id="total" value="">
<a href="#" onclick="setValue();">Click to submit</a>
</form>

Then your javascript something like this:

<script>
function setValue(){
    document.sampleForm.total.value = 100;
    document.forms["sampleForm"].submit();
}
</script>

Rails Root directory path?

Simply by Rails.root or if you want append something we can use it like Rails.root.join('app', 'assets').to_s

Where can I find the default timeout settings for all browsers?

After the last Firefox update we had the same session timeout issue and the following setting helped to resolve it.

We can control it with network.http.response.timeout parameter.

  1. Open Firefox and type in ‘about:config’ in the address bar and press Enter.
  2. Click on the "I'll be careful, I promise!" button.
  3. Type ‘timeout’ in the search box and network.http.response.timeout parameter will be displayed.
  4. Double-click on the network.http.response.timeout parameter and enter the time value (it is in seconds) that you don't want your session not to timeout, in the box.

ReflectionException: Class ClassName does not exist - Laravel

composer update 

Above command worked for me.

Whenever you make new migration in la-ravel you need to refresh classmap in composer.json file .

How to set scope property with ng-init?

I had some trouble with $scope.$watch but after a lot of testing I found out that my data-ng-model="User.UserName" was badly named and after I changed it to data-ng-model="UserName" everything worked fine. I expect it to be the . in the name causing the issue.

Single vs Double quotes (' vs ")

I'm newbie here but I use single quote mark only when I use double quote mark inside the first one. If I'm not clear I show You example:

<p align="center" title='One quote mark at the beginning so now I can
"cite".'> ... </p>

I hope I helped.

Pass array to ajax request in $.ajax()

NOTE: Doesn't work on newer versions of jQuery.

Since you are using jQuery please use it's seralize function to serialize data and then pass it into the data parameter of ajax call:

info[0] = 'hi';
info[1] = 'hello';

var data_to_send = $.serialize(info);

$.ajax({
    type: "POST",
    url: "index.php",
    data: data_to_send,
    success: function(msg){
        $('.answer').html(msg);
    }
});

How do I add an element to a list in Groovy?

From the documentation:

We can add to a list in many ways:

assert [1,2] + 3 + [4,5] + 6 == [1, 2, 3, 4, 5, 6]
assert [1,2].plus(3).plus([4,5]).plus(6) == [1, 2, 3, 4, 5, 6]
    //equivalent method for +
def a= [1,2,3]; a += 4; a += [5,6]; assert a == [1,2,3,4,5,6]
assert [1, *[222, 333], 456] == [1, 222, 333, 456]
assert [ *[1,2,3] ] == [1,2,3]
assert [ 1, [2,3,[4,5],6], 7, [8,9] ].flatten() == [1, 2, 3, 4, 5, 6, 7, 8, 9]

def list= [1,2]
list.add(3) //alternative method name
list.addAll([5,4]) //alternative method name
assert list == [1,2,3,5,4]

list= [1,2]
list.add(1,3) //add 3 just before index 1
assert list == [1,3,2]
list.addAll(2,[5,4]) //add [5,4] just before index 2
assert list == [1,3,5,4,2]

list = ['a', 'b', 'z', 'e', 'u', 'v', 'g']
list[8] = 'x'
assert list == ['a', 'b', 'z', 'e', 'u', 'v', 'g', null, 'x']

You can also do:

def myNewList = myList << "fifth"

Set the default value in dropdownlist using jQuery

$("#dropdownList option[text='it\'s me']").attr("selected","selected"); 

React - uncaught TypeError: Cannot read property 'setState' of undefined

In ES7+ (ES2016) you can use the experimental function bind syntax operator :: to bind. It is a syntactic sugar and will do the same as Davin Tryon's answer.

You can then rewrite this.delta = this.delta.bind(this); to this.delta = ::this.delta;


For ES6+ (ES2015) you can also use the ES6+ arrow function (=>) to be able to use this.

delta = () => {
    this.setState({
        count : this.state.count + 1
    });
}

Why ? From the Mozilla doc :

Until arrow functions, every new function defined its own this value [...]. This proved to be annoying with an object-oriented style of programming.

Arrow functions capture the this value of the enclosing context [...]

Easiest way to use SVG in Android?

You can use Coil library to load svg. Just add these lines in build.gradle

// ... Coil (https://github.com/coil-kt/coil)
implementation("io.coil-kt:coil:0.12.0")
implementation("io.coil-kt:coil-svg:0.12.0")

Then Add an extension function

fun AppCompatImageView.loadSvg(url: String) {
    val imageLoader = ImageLoader.Builder(this.context)
        .componentRegistry { add(SvgDecoder([email protected])) }
        .build()

    val request = ImageRequest.Builder(this.context)
        .crossfade(true)
        .crossfade(500)
        .data(url)
        .target(this)
        .build()

    imageLoader.enqueue(request)
}

Then call this method in your activity or fragment

your_image_view.loadSvg("your_file_name.svg")

How to work with complex numbers in C?

Complex types are in the C language since C99 standard (-std=c99 option of GCC). Some compilers may implement complex types even in more earlier modes, but this is non-standard and non-portable extension (e.g. IBM XL, GCC, may be intel,... ).

You can start from http://en.wikipedia.org/wiki/Complex.h - it gives a description of functions from complex.h

This manual http://pubs.opengroup.org/onlinepubs/009604499/basedefs/complex.h.html also gives some info about macros.

To declare a complex variable, use

  double _Complex  a;        // use c* functions without suffix

or

  float _Complex   b;        // use c*f functions - with f suffix
  long double _Complex c;    // use c*l functions - with l suffix

To give a value into complex, use _Complex_I macro from complex.h:

  float _Complex d = 2.0f + 2.0f*_Complex_I;

(actually there can be some problems here with (0,-0i) numbers and NaNs in single half of complex)

Module is cabs(a)/cabsl(c)/cabsf(b); Real part is creal(a), Imaginary is cimag(a). carg(a) is for complex argument.

To directly access (read/write) real an imag part you may use this unportable GCC-extension:

 __real__ a = 1.4;
 __imag__ a = 2.0;
 float b = __real__ a;

If hasClass then addClass to parent

The reason that does not work is because this has no specific meaning inside of an if statement, you will have to go back to a level of scope where this is defined (a function).

For example:

$('#element1').click(function() {
    console.log($(this).attr('id')); // logs "element1"

    if ($('#element2').hasClass('class')) {
        console.log($(this).attr('id')); // still logs "element1"
    }
});

How can I get the source code of a Python function?

dis is your friend if the source code is not available:

>>> import dis
>>> def foo(arg1,arg2):
...     #do something with args
...     a = arg1 + arg2
...     return a
...
>>> dis.dis(foo)
  3           0 LOAD_FAST                0 (arg1)
              3 LOAD_FAST                1 (arg2)
              6 BINARY_ADD
              7 STORE_FAST               2 (a)

  4          10 LOAD_FAST                2 (a)
             13 RETURN_VALUE

How to execute command stored in a variable?

If you just do eval $cmd when we do cmd="ls -l" (interactively and in a script) we get the desired result. In your case, you have a pipe with a grep without a pattern, so the grep part will fail with an error message. Just $cmd will generate a "command not found" (or some such) message. So try use eval and use a finished command, not one that generates an error message.

What is the runtime performance cost of a Docker container?

Here's some more benchmarks for Docker based memcached server versus host native memcached server using Twemperf benchmark tool https://github.com/twitter/twemperf with 5000 connections and 20k connection rate

Connect time overhead for docker based memcached seems to agree with above whitepaper at roughly twice native speed.

Twemperf Docker Memcached

Connection rate: 9817.9 conn/s
Connection time [ms]: avg 341.1 min 73.7 max 396.2 stddev 52.11
Connect time [ms]: avg 55.0 min 1.1 max 103.1 stddev 28.14
Request rate: 83942.7 req/s (0.0 ms/req)
Request size [B]: avg 129.0 min 129.0 max 129.0 stddev 0.00
Response rate: 83942.7 rsp/s (0.0 ms/rsp)
Response size [B]: avg 8.0 min 8.0 max 8.0 stddev 0.00
Response time [ms]: avg 28.6 min 1.2 max 65.0 stddev 0.01
Response time [ms]: p25 24.0 p50 27.0 p75 29.0
Response time [ms]: p95 58.0 p99 62.0 p999 65.0

Twemperf Centmin Mod Memcached

Connection rate: 11419.3 conn/s
Connection time [ms]: avg 200.5 min 0.6 max 263.2 stddev 73.85
Connect time [ms]: avg 26.2 min 0.0 max 53.5 stddev 14.59
Request rate: 114192.6 req/s (0.0 ms/req)
Request size [B]: avg 129.0 min 129.0 max 129.0 stddev 0.00
Response rate: 114192.6 rsp/s (0.0 ms/rsp)
Response size [B]: avg 8.0 min 8.0 max 8.0 stddev 0.00
Response time [ms]: avg 17.4 min 0.0 max 28.8 stddev 0.01
Response time [ms]: p25 12.0 p50 20.0 p75 23.0
Response time [ms]: p95 28.0 p99 28.0 p999 29.0

Here's bencmarks using memtier benchmark tool

memtier_benchmark docker Memcached

4         Threads
50        Connections per thread
10000     Requests per thread
Type        Ops/sec     Hits/sec   Misses/sec      Latency       KB/sec
------------------------------------------------------------------------
Sets       16821.99          ---          ---      1.12600      2271.79
Gets      168035.07    159636.00      8399.07      1.12000     23884.00
Totals    184857.06    159636.00      8399.07      1.12100     26155.79

memtier_benchmark Centmin Mod Memcached

4         Threads
50        Connections per thread
10000     Requests per thread
Type        Ops/sec     Hits/sec   Misses/sec      Latency       KB/sec
------------------------------------------------------------------------
Sets       28468.13          ---          ---      0.62300      3844.59
Gets      284368.51    266547.14     17821.36      0.62200     39964.31
Totals    312836.64    266547.14     17821.36      0.62200     43808.90

How to make a edittext box in a dialog

Use Activtiy Context

Replace this

  final EditText input = new EditText(this);

By

  final EditText input = new EditText(MainActivity.this);  
  LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT,
                        LinearLayout.LayoutParams.MATCH_PARENT);
  input.setLayoutParams(lp);
  alertDialog.setView(input); // uncomment this line

Cause of a process being a deadlock victim

Although @Remus Rusanu's is already an excelent answer, in case one is looking forward a better insight on SQL Server's Deadlock causes and trace strategies, I would suggest you to read Brad McGehee's How to Track Down Deadlocks Using SQL Server 2005 Profiler

Reorder HTML table rows using drag-and-drop

Apparently the question poorly describes the OP's problem, but this question is the top search result for dragging to reorder table rows, so that is what I will answer. I wasn't interested in bringing in jQuery UI for something so simple, so here is a jQuery only solution:

_x000D_
_x000D_
$(".grab").mousedown(function(e) {
  var tr = $(e.target).closest("TR"),
    si = tr.index(),
    sy = e.pageY,
    b = $(document.body),
    drag;
  if (si == 0) return;
  b.addClass("grabCursor").css("userSelect", "none");
  tr.addClass("grabbed");

  function move(e) {
    if (!drag && Math.abs(e.pageY - sy) < 10) return;
    drag = true;
    tr.siblings().each(function() {
      var s = $(this),
        i = s.index(),
        y = s.offset().top;
      if (i > 0 && e.pageY >= y && e.pageY < y + s.outerHeight()) {
        if (i < tr.index())
          tr.insertAfter(s);
        else
          tr.insertBefore(s);
        return false;
      }
    });
  }

  function up(e) {
    if (drag && si != tr.index()) {
      drag = false;
      alert("moved!");
    }
    $(document).unbind("mousemove", move).unbind("mouseup", up);
    b.removeClass("grabCursor").css("userSelect", "none");
    tr.removeClass("grabbed");
  }
  $(document).mousemove(move).mouseup(up);
});
_x000D_
.grab {
  cursor: grab;
}

.grabbed {
  box-shadow: 0 0 13px #000;
}

.grabCursor,
.grabCursor * {
  cursor: grabbing !important;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <th></th>
    <th>Table Header</th>
  </tr>
  <tr>
    <td class="grab">&#9776;</td>
    <td>Table Cell 1</td>
  </tr>
  <tr>
    <td class="grab">&#9776;</td>
    <td>Table Cell 2</td>
  </tr>
  <tr>
    <td class="grab">&#9776;</td>
    <td>Table Cell 3</td>
  </tr>
</table>
_x000D_
_x000D_
_x000D_

Note si == 0 and i > 0 ignores the first row, which for me contains TH tags. Replace the alert with your "drag finished" logic.

How to customize a Spinner in Android

The most elegant and flexible solution I have found so far is here: http://android-er.blogspot.sg/2010/12/custom-arrayadapter-for-spinner-with.html

Basically, follow these steps:

  1. Create custom layout xml file for your dropdown item, let's say I will call it spinner_item.xml
  2. Create custom view class, for your dropdown Adapter. In this custom class, you need to overwrite and set your custom dropdown item layout in getView() and getDropdownView() method. My code is as below:

    public class CustomArrayAdapter extends ArrayAdapter<String>{
    
    private List<String> objects;
    private Context context;
    
    public CustomArrayAdapter(Context context, int resourceId,
         List<String> objects) {
         super(context, resourceId, objects);
         this.objects = objects;
         this.context = context;
    }
    
    @Override
    public View getDropDownView(int position, View convertView,
        ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }
    
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      return getCustomView(position, convertView, parent);
    }
    
    public View getCustomView(int position, View convertView, ViewGroup parent) {
    
    LayoutInflater inflater=(LayoutInflater) context.getSystemService(  Context.LAYOUT_INFLATER_SERVICE );
    View row=inflater.inflate(R.layout.spinner_item, parent, false);
    TextView label=(TextView)row.findViewById(R.id.spItem);
     label.setText(objects.get(position));
    
    if (position == 0) {//Special style for dropdown header
          label.setTextColor(context.getResources().getColor(R.color.text_hint_color));
    }
    
    return row;
    }
    
    }
    
  3. In your activity or fragment, make use of the custom adapter for your spinner view. Something like this:

    Spinner sp = (Spinner)findViewById(R.id.spMySpinner);
    ArrayAdapter<String> myAdapter = new CustomArrayAdapter(this, R.layout.spinner_item, options);
    sp.setAdapter(myAdapter);
    

where options is the list of dropdown item string.

Why this "Implicit declaration of function 'X'"?

summation and your other functions are defined after they're used in main, and so the compiler has made a guess about it's signature; in other words, an implicit declaration has been assumed.

You should declare the function before it's used and get rid of the warning. In the C99 specification, this is an error.

Either move the function bodies before main, or include method signatures before main, e.g.:

#include <stdio.h>

int summation(int *, int *, int *);

int main()
{
    // ...

jQuery $(this) keyword

When you perform an DOM query through jQuery like $('class-name') it actively searched the DOM for that element and returns that element with all the jQuery prototype methods attached.

When you're within the jQuery chain or event you don't have to rerun the DOM query you can use the context $(this). Like so:

$('.class-name').on('click', (evt) => {
    $(this).hide(); // does not run a DOM query
    $('.class-name').hide() // runs a DOM query
}); 

$(this) will hold the element that you originally requested. It will attach all the jQuery prototype methods again, but will not have to search the DOM again.

Some more information:

Web Performance with jQuery selectors

Quote from a web blog that doesn't exist anymore but I'll leave it in here for history sake:

In my opinion, one of the best jQuery performance tips is to minimize your use of jQuery. That is, find a balance between using jQuery and plain ol’ JavaScript, and a good place to start is with ‘this‘. Many developers use $(this) exclusively as their hammer inside callbacks and forget about this, but the difference is distinct:

When inside a jQuery method’s anonymous callback function, this is a reference to the current DOM element. $(this) turns this into a jQuery object and exposes jQuery’s methods. A jQuery object is nothing more than a beefed-up array of DOM elements.

Subclipse svn:ignore

If you are trying to share a project in SVN with Eclipse for the first time, you might want to avoid certain files to be commited. In order to do so, go to Preferences->Team->Ignored Resources. In this screen you just need to add a pattern to ignore the kind of files you don't want to commit.

Eclipse preferences

Search for executable files using find command

So if you actually want to find executable file types (e.g. scripts, ELF binaries etc.. etc..) not merely files with execution permission then you probably want to do something more like this (where the current directory . can be replaced with whatever directory you want):

 gfind . -type f -exec bash -c '[[ $(file -b "'{}'") == *" executable "* ]] ' \; -print

Or for those of you who aren't using macports (linux users) or otherwise have gnu find installed as find you want:

 find . -type f -exec bash -c '[[ $(file -b "'{}'") == *" executable "* ]] ' \; -print

Though if you are on OS X it comes with a little utility hidden somewhere called is_exec that basically bundles up that little test for you so you can shorten the command line if you find it. But this way is more flexible as you can easily replace the == test with the =~ test and use it to check for more complex properties like executable plain text files or whatever other info your file command returns.


The exact rules for quotation here are pretty opaque so I just end up working it out by trial and error but I'd love to hear the right explanation.

Assign multiple values to array in C

typedef struct{
  char array[4];
}my_array;

my_array array = { .array = {1,1,1,1} }; // initialisation

void assign(my_array a)
{
  array.array[0] = a.array[0];
  array.array[1] = a.array[1];
  array.array[2] = a.array[2];
  array.array[3] = a.array[3]; 
}

char num = 5;
char ber = 6;

int main(void)
{
  printf("%d\n", array.array[0]);
// ...

  // this works even after initialisation
  assign((my_array){ .array = {num,ber,num,ber} });

  printf("%d\n", array.array[0]);
// ....
  return 0;
}

Getting the base url of the website and globally passing it to twig in Symfony 2

Also for js/css/image urls there's handy function asset()

<img src="{{ asset('image/logo.png') }}"/>

This creates an absolute url starting with /.

<div> cannot appear as a descendant of <p>

I had a similar issue and wrapped the component in "div" instead of "p" and the error went away.

When to use dynamic vs. static libraries

A lib is a unit of code that is bundled within your application executable.

A dll is a standalone unit of executable code. It is loaded in the process only when a call is made into that code. A dll can be used by multiple applications and loaded in multiple processes, while still having only one copy of the code on the hard drive.

Dll pros: can be used to reuse/share code between several products; load in the process memory on demand and can be unloaded when not needed; can be upgraded independently of the rest of the program.

Dll cons: performance impact of the dll loading and code rebasing; versioning problems ("dll hell")

Lib pros: no performance impact as code is always loaded in the process and is not rebased; no versioning problems.

Lib cons: executable/process "bloat" - all the code is in your executable and is loaded upon process start; no reuse/sharing - each product has its own copy of the code.

How do I modify the URL without reloading the page?

This can now be done in Chrome, Safari, Firefox 4+, and Internet Explorer 10pp4+!

See this question's answer for more information: Updating address bar with new URL without hash or reloading the page

Example:

 function processAjaxData(response, urlPath){
     document.getElementById("content").innerHTML = response.html;
     document.title = response.pageTitle;
     window.history.pushState({"html":response.html,"pageTitle":response.pageTitle},"", urlPath);
 }

You can then use window.onpopstate to detect the back/forward button navigation:

window.onpopstate = function(e){
    if(e.state){
        document.getElementById("content").innerHTML = e.state.html;
        document.title = e.state.pageTitle;
    }
};

For a more in-depth look at manipulating browser history, see this MDN article.

Undo a git stash

git stash list to list your stashed changes.

git stash show to see what n is in the below commands.

git stash apply to apply the most recent stash.

git stash apply stash@{n} to apply an older stash.

https://git-scm.com/book/en/v2/Git-Tools-Stashing-and-Cleaning

Checking if jquery is loaded using Javascript

If jQuery is loading asynchronously, you can wait till it is defined, checking for it every period of time:

(function() {
    var a = setInterval( function() {
        if ( typeof window.jQuery === 'undefined' ) {
            return;
        }
        clearInterval( a );

        console.log( 'jQuery is loaded' ); // call your function with jQuery instead of this
    }, 500 );
})();

This method can be used for any variable, you are waiting to appear.

How would you implement an LRU cache in Java?

I would consider using java.util.concurrent.PriorityBlockingQueue, with priority determined by a "numberOfUses" counter in each element. I would be very, very careful to get all my synchronisation correct, as the "numberOfUses" counter implies that the element can't be immutable.

The element object would be a wrapper for the objects in the cache:

class CacheElement {
    private final Object obj;
    private int numberOfUsers = 0;

    CacheElement(Object obj) {
        this.obj = obj;
    }

    ... etc.
}

How to take screenshot of a div with JavaScript?

After hours of research, I finally found a solution to take a screenshot of an element, even if the origin-clean FLAG is set (to prevent XSS), that´s why you can even capture for example Google Maps (in my case). I wrote a universal function to get a screenshot. The only thing you need in addition is the html2canvas library (https://html2canvas.hertzen.com/).

Example:

getScreenshotOfElement($("div#toBeCaptured").get(0), 0, 0, 100, 100, function(data) {
    // in the data variable there is the base64 image
    // exmaple for displaying the image in an <img>
    $("img#captured").attr("src", "data:image/png;base64,"+data);
});

Keep in mind console.log() and alert() won´t generate output if the size of the image is great.

Function:

function getScreenshotOfElement(element, posX, posY, width, height, callback) {
    html2canvas(element, {
        onrendered: function (canvas) {
            var context = canvas.getContext('2d');
            var imageData = context.getImageData(posX, posY, width, height).data;
            var outputCanvas = document.createElement('canvas');
            var outputContext = outputCanvas.getContext('2d');
            outputCanvas.width = width;
            outputCanvas.height = height;

            var idata = outputContext.createImageData(width, height);
            idata.data.set(imageData);
            outputContext.putImageData(idata, 0, 0);
            callback(outputCanvas.toDataURL().replace("data:image/png;base64,", ""));
        },
        width: width,
        height: height,
        useCORS: true,
        taintTest: false,
        allowTaint: false
    });
}

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

I do this all the time, all I do is

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

and all those data frames come from here

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

obviously sapply routine would be better here

Spark java.lang.OutOfMemoryError: Java heap space

I suffered from this issue a lot when using dynamic resource allocation. I had thought it would utilize my cluster resources to best fit the application.

But the truth is the dynamic resource allocation doesn't set the driver memory and keeps it to its default value, which is 1G.

I resolved this issue by setting spark.driver.memory to a number that suits my driver's memory (for 32GB ram I set it to 18G).

You can set it using spark submit command as follows:

spark-submit --conf spark.driver.memory=18g

Very important note, this property will not be taken into consideration if you set it from code, according to Spark Documentation - Dynamically Loading Spark Properties:

Spark properties mainly can be divided into two kinds: one is related to deploy, like “spark.driver.memory”, “spark.executor.instances”, this kind of properties may not be affected when setting programmatically through SparkConf in runtime, or the behavior is depending on which cluster manager and deploy mode you choose, so it would be suggested to set through configuration file or spark-submit command line options; another is mainly related to Spark runtime control, like “spark.task.maxFailures”, this kind of properties can be set in either way.

Node.js https pem error: routines:PEM_read_bio:no start line

For me, the solution was to replace \\n (getting formatted into the key in a weird way) in place of \n

Replace your key: <private or public key> with key: (<private or public key>).replace(new RegExp("\\\\n", "\g"), "\n")

How to call base.base.method()?

As can be seen from previous posts, one can argue that if class functionality needs to be circumvented then something is wrong in the class architecture. That might be true, but one cannot always restructure or refactor the class structure on a large mature project. The various levels of change management might be one problem, but to keep existing functionality operating the same after refactoring is not always a trivial task, especially if time constraints apply. On a mature project it can be quite an undertaking to keep various regression tests from passing after a code restructure; there are often obscure "oddities" that show up. We had a similar problem in some cases inherited functionality should not execute (or should perform something else). The approach we followed below, was to put the base code that need to be excluded in a separate virtual function. This function can then be overridden in the derived class and the functionality excluded or altered. In this example "Text 2" can be prevented from output in the derived class.

public class Base
{
    public virtual void Foo()
    {
        Console.WriteLine("Hello from Base");
    }
}

public class Derived : Base
{
    public override void Foo()
    {
        base.Foo();
        Console.WriteLine("Text 1");
        WriteText2Func();
        Console.WriteLine("Text 3");
    }

    protected virtual void WriteText2Func()
    {  
        Console.WriteLine("Text 2");  
    }
}

public class Special : Derived
{
    public override void WriteText2Func()
    {
        //WriteText2Func will write nothing when 
        //method Foo is called from class Special.
        //Also it can be modified to do something else.
    }
}

Where's my JSON data in my incoming Django request?

html code 

file name  : view.html


    <!DOCTYPE html>
    <html>
    <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        $("#mySelect").change(function(){
            selected = $("#mySelect option:selected").text()
            $.ajax({
                type: 'POST',
                dataType: 'json',
                contentType: 'application/json; charset=utf-8',
                url: '/view/',
                data: {
                       'fruit': selected
                      },
                success: function(result) {
                        document.write(result)
                        }
        });
      });
    });
    </script>
    </head>
    <body>

    <form>
        <br>
    Select your favorite fruit:
    <select id="mySelect">
      <option value="apple" selected >Select fruit</option>
      <option value="apple">Apple</option>
      <option value="orange">Orange</option>
      <option value="pineapple">Pineapple</option>
      <option value="banana">Banana</option>
    </select>
    </form>
    </body>
    </html>

Django code:


Inside views.py


def view(request):

    if request.method == 'POST':
        print request.body
        data = request.body
        return HttpResponse(json.dumps(data))

Python Binomial Coefficient

It's a good idea to apply a recursive definition, as in Vadim Smolyakov's answer, combined with a DP (dynamic programming), but for the latter you may apply the lru_cache decorator from module functools:

import functools

@functools.lru_cache(maxsize = None)
def binom(n,k):
    if k == 0: return 1
    if n == k: return 1
    return binom(n-1,k-1)+binom(n-1,k)

What does it mean with bug report captured in android tablet?

It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.

Edit: This is what the forums say:

By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.

To disable:

/system/bin/bugmailer.sh must be deleted/renamed.

There should be a folder on your SD card called "bug reports".

Have a look at this thread: http://forum.xda-developers.com/showthread.php?t=2252948

And this one: http://forum.xda-developers.com/showthread.php?t=1405639

How to stretch a fixed number of horizontal navigation items evenly and fully across a specified container

Instead of defining the width, you could just put a margin-left on your li, so that the spacing is consistent, and just make sure the margin(s)+li fit within 900px.

nav li {
  line-height: 87px;
  float: left;
  text-align: center;
  margin-left: 35px;
}

Hope this helps.

Safely remove migration In Laravel

DO NOT run php artisan migrate:fresh that's gonna drop all the tables

How do I print out the contents of a vector?

template collection:

apply std::cout << and std::to_string

to std::vector, std::array and std::tuple

As printing a vector in cpp turned out to be surprisingly much work (at least compared to how basic this task is) and as one steps over the same problem again, when working with other container, here a more general solution ...

Template collection content

This template collection handles 3 container types: std::vector, std::array and std::tuple. It defines std::to_string() for those and makes it possible to directly print them out by std::cout << container;.

Further it defines the << operator for std::string << container. With this it gets possible to construct strings containig these container types in a compact way.

From

std::string s1 = "s1: " + std::to_string(arr) + "; " + std::to_string(vec) + "; " + std::to_string(tup);

we get to

std::string s2 = STR() << "s2: " << arr << "; " << vec << "; " << tup;

Code

You can test this code interactively: here.

#include <iostream>
#include <string>
#include <tuple>
#include <vector>
#include <array>

namespace std
{   
    // declations: needed for std::to_string(std::vector<std::tuple<int, float>>)
    std::string to_string(std::string str);
    std::string to_string(const char *str);
    template<typename T, size_t N>
    std::string to_string(std::array<T, N> const& arr);
    template<typename T>
    std::string to_string(std::vector<T> const& vec);
    template<typename... Args>
    std::string to_string(const std::tuple<Args...>& tup);
    
    std::string to_string(std::string str)
    {
        return std::string(str);
    }
    std::string to_string(const char *str)
    {
        return std::string(str);
    }

    template<typename T, size_t N>
    std::string to_string(std::array<T, N> const& arr)
    {
        std::string s="{";
        for (std::size_t t = 0; t != N; ++t)
            s += std::to_string(arr[t]) + (t+1 < N ? ", ":"");
        return s + "}";
    }

    template<typename T>
    std::string to_string(std::vector<T> const& vec)
    {
        std::string s="[";
        for (std::size_t t = 0; t != vec.size(); ++t)
            s += std::to_string(vec[t]) + (t+1 < vec.size() ? ", ":"");
        return s + "]";
    }
    
    // to_string(tuple)
    // https://en.cppreference.com/w/cpp/utility/tuple/operator%3D
    template<class Tuple, std::size_t N>
    struct TupleString
    {
        static std::string str(const Tuple& tup)
        {
            std::string out;
            out += TupleString<Tuple, N-1>::str(tup);
            out += ", ";
            out += std::to_string(std::get<N-1>(tup));
            return out;
        }
    };
    template<class Tuple>
    struct TupleString<Tuple, 1>
    {
        static std::string str(const Tuple& tup)
        {
            std::string out;
            out += std::to_string(std::get<0>(tup));
            return out;
        }
    };
    template<typename... Args>
    std::string to_string(const std::tuple<Args...>& tup)
    {
        std::string out = "(";
        out += TupleString<decltype(tup), sizeof...(Args)>::str(tup);
        out += ")";
        return out;
    }
} // namespace std


/**
 * cout: cout << continer
 */
template <typename T, std::size_t N> // cout << array
std::ostream& operator <<(std::ostream &out, std::array<T, N> &con)
{
    out <<  std::to_string(con);
    return out;
}
template <typename T, typename A> // cout << vector
std::ostream& operator <<(std::ostream &out, std::vector<T, A> &con)
{
    out <<  std::to_string(con);
    return out;
}
template<typename... Args> // cout << tuple
std::ostream& operator <<(std::ostream &out, std::tuple<Args...> &con)
{
    out <<  std::to_string(con);
    return out;
}

/**
 * Concatenate: string << continer
 */
template <class C>
std::string operator <<(std::string str, C &con)
{
    std::string out = str;
    out += std::to_string(con);
    return out;
}
#define STR() std::string("")

int main()
{
    std::array<int, 3> arr {1, 2, 3};
    std::string sArr = std::to_string(arr);
    std::cout << "std::array" << std::endl;
    std::cout << "\ttest to_string: " << sArr << std::endl;
    std::cout << "\ttest cout <<: " << arr << std::endl;
    std::cout << "\ttest string <<: " << (std::string() << arr) << std::endl;
    
    std::vector<std::string> vec {"a", "b"};
    std::string sVec = std::to_string(vec);
    std::cout << "std::vector" << std::endl;
    std::cout << "\ttest to_string: " << sVec << std::endl;
    std::cout << "\ttest cout <<: " << vec << std::endl;
    std::cout << "\ttest string <<: " << (std::string() << vec) << std::endl;
    
    std::tuple<int, std::string> tup = std::make_tuple(5, "five");
    std::string sTup = std::to_string(tup);
    std::cout << "std::tuple" << std::endl;
    std::cout << "\ttest to_string: " << sTup << std::endl;
    std::cout << "\ttest cout <<: " << tup << std::endl;
    std::cout << "\ttest string <<: " << (std::string() << tup) << std::endl;
    
    std::vector<std::tuple<int, float>> vt {std::make_tuple(1, .1), std::make_tuple(2, .2)};
    std::string sVt = std::to_string(vt);
    std::cout << "std::vector<std::tuple>" << std::endl;
    std::cout << "\ttest to_string: " << sVt << std::endl;
    std::cout << "\ttest cout <<: " << vt << std::endl;
    std::cout << "\ttest string <<: " << (std::string() << vt) << std::endl;
    
    std::cout << std::endl;
    
    std::string s1 = "s1: " + std::to_string(arr) + "; " + std::to_string(vec) + "; " + std::to_string(tup);
    std::cout << s1 << std::endl;
    
    std::string s2 = STR() << "s2: " << arr << "; " << vec << "; " << tup;
    std::cout << s2 << std::endl;

    return 0;
}

Output

std::array
    test to_string: {1, 2, 3}
    test cout <<: {1, 2, 3}
    test string <<: {1, 2, 3}
std::vector
    test to_string: [a, b]
    test cout <<: [a, b]
    test string <<: [a, b]
std::tuple
    test to_string: (5, five)
    test cout <<: (5, five)
    test string <<: (5, five)
std::vector<std::tuple>
    test to_string: [(1, 0.100000), (2, 0.200000)]
    test cout <<: [(1, 0.100000), (2, 0.200000)]
    test string <<: [(1, 0.100000), (2, 0.200000)]

s1: {1, 2, 3}; [a, b]; (5, five)
s2: {1, 2, 3}; [a, b]; (5, five)

Best way to parse RSS/Atom feeds with PHP

I would like introduce simple script to parse RSS:

$i = 0; // counter
$url = "http://www.banki.ru/xml/news.rss"; // url to parse
$rss = simplexml_load_file($url); // XML parser

// RSS items loop

print '<h2><img style="vertical-align: middle;" src="'.$rss->channel->image->url.'" /> '.$rss->channel->title.'</h2>'; // channel title + img with src

foreach($rss->channel->item as $item) {
if ($i < 10) { // parse only 10 items
    print '<a href="'.$item->link.'">'.$item->title.'</a><br />';
}

$i++;
}

Jquery array.push() not working

Your code alerts the current value of the dropdown for me, showing that it has properly pushed into the array.

Are you wanting to keep old values and append? You're recreating the array each time, meaning that the old value gets clobbered.

Here's some updated code:

var myarray = [];
$("#test").click(function() {
    myarray.push($("#drop").val());
    alert(myarray);
});

jsFiddle

How do I declare a model class in my Angular 2 component using TypeScript?

The problem lies that you haven't added Model to either the bootstrap (which will make it a singleton), or to the providers array of your component definition:

@Component({
    selector: "testWidget",
    template: "<div>This is a test and {{param1}} is my param.</div>",
    providers : [
       Model
    ]
})

export class testWidget {
    constructor(private model: Model) {}
}

And yes, you should define Model above the Component. But better would be to put it in his own file.

But if you want it to be just a class from which you can create multiple instances, you better just use new.

@Component({
    selector: "testWidget",
    template: "<div>This is a test and {{param1}} is my param.</div>"
})

export class testWidget {

    private model: Model = new Model();

    constructor() {}
}

The Eclipse executable launcher was unable to locate its companion launcher jar windows

In my case I had to redownload it, something was wrong with the one I downloaded. Its size was far much less than the one on the website.

jQuery: How to get the HTTP status code from within the $.ajax.error method?

use

   statusCode: {
    404: function() {
      alert('page not found');
    }
  }

-

$.ajax({
    type: 'POST',
    url: '/controller/action',
    data: $form.serialize(),
    success: function(data){
        alert('horray! 200 status code!');
    },
    statusCode: {
    404: function() {
      alert('page not found');
    },

    400: function() {
       alert('bad request');
   }
  }

});

Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details

This line work for me on mac or Linux.

./gradlew clean assembleDebug

Regex using javascript to return just numbers

IMO the #3 answer at this time by Chen Dachao is the right way to go if you want to capture any kind of number, but the regular expression can be shortened from:

/[-]{0,1}[\d]*[\.]{0,1}[\d]+/g

to:

/-?\d*\.?\d+/g

For example, this code:

"lin-grad.ient(217deg,rgba(255, 0, 0, -0.8), rgba(-255,0,0,0) 70.71%)".match(/-?\d*\.?\d+/g)

generates this array:

["217","255","0","0","-0.8","-255","0","0","0","70.71"]

I've butchered an MDN linear gradient example so that it fully tests the regexp and doesn't need to scroll here. I think I've included all the possibilities in terms of negative numbers, decimals, unit suffixes like deg and %, inconsistent comma and space usage, and the extra dot/period and hyphen/dash characters within the text "lin-grad.ient". Please let me know if I'm missing something. The only thing I can see that it does not handle is a badly formed decimal number like "0..8".

If you really want an array of numbers, you can convert the entire array in the same line of code:

array = whatever.match(/-?\d*\.?\d+/g).map(Number);

My particular code, which is parsing CSS functions, doesn't need to worry about the non-numeric use of the dot/period character, so the regular expression can be even simpler:

/-?[\d\.]+/g

How to use XMLReader in PHP?

For xml formatted with attributes...

data.xml:

<building_data>
<building address="some address" lat="28.902914" lng="-71.007235" />
<building address="some address" lat="48.892342" lng="-75.0423423" />
<building address="some address" lat="58.929753" lng="-79.1236987" />
</building_data>

php code:

$reader = new XMLReader();

if (!$reader->open("data.xml")) {
    die("Failed to open 'data.xml'");
}

while($reader->read()) {
  if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == 'building') {
    $address = $reader->getAttribute('address');
    $latitude = $reader->getAttribute('lat');
    $longitude = $reader->getAttribute('lng');
}

$reader->close();

How can I make visible an invisible control with jquery? (hide and show not work)

It's been more than 10 years and not sure if anyone still finding this question or answer relevant.

But a quick workaround is just to wrap the asp control within a html container

<div id="myElement" style="display: inline-block">
   <asp:TextBox ID="textBox1" runat="server"></asp:TextBox>
</div>

Whenever the Javascript Event is triggered, if it needs to be an event by the asp control, just wrap the asp control around the div container.

<div id="testG">  
   <asp:Button ID="Button2" runat="server" CssClass="btn" Text="Activate" />
</div>

The jQuery Code is below:

$(document).ready(function () {
    $("#testG").click(function () {
                $("#myElement").css("display", "none");
     });
});

How to convert char to integer in C?

The standard function atoi() will likely do what you want.

A simple example using "atoi":

#include <unistd.h>

int main(int argc, char *argv[])
{
    int useconds = atoi(argv[1]); 
    usleep(useconds);
}

Batch file. Delete all files and folders in a directory

You cannot delete everything with either rmdir or del alone:

  • rmdir /s /q does not accept wildcard params. So rmdir /s /q * will error.
  • del /s /f /q will delete all files, but empty subdirectories will remain.

My preferred solution (as I have used in many other batch files) is:

rmdir /s /q . 2>NUL

Checkboxes in web pages – how to make them bigger?

In case this can help anyone, here's simple CSS as a jumping off point. Turns it into a basic rounded square big enough for thumbs with a toggled background color.

_x000D_
_x000D_
input[type='checkbox'] {_x000D_
    -webkit-appearance:none;_x000D_
    width:30px;_x000D_
    height:30px;_x000D_
    background:white;_x000D_
    border-radius:5px;_x000D_
    border:2px solid #555;_x000D_
}_x000D_
input[type='checkbox']:checked {_x000D_
    background: #abd;_x000D_
}
_x000D_
<input type="checkbox" />
_x000D_
_x000D_
_x000D_

How can I write variables inside the tasks file in ansible

I know, it is long ago, but since the easiest answer was not yet posted I will do so for other user that might step by.

Just move the var inside the "name" block:

- name: Download apache
  vars:
    url: czxcxz
  shell: wget {{url}} 

Java Keytool error after importing certificate , "keytool error: java.io.FileNotFoundException & Access Denied"

If you are using windows8:

  1. Click start button
  2. In the search box, type command prompt
  3. From the result, right-click command prompt and click Run as administrator. Then execute the keytool command.

Decreasing height of bootstrap 3.0 navbar

After spending few hours, adding the following css class fixed my issue.

Work with Bootstrap 3.0.*

.tnav .navbar .container { height: 28px; }

Work with Bootstrap 3.3.4

.navbar-nav > li > a, .navbar-brand {
    padding-top:4px !important; 
    padding-bottom:0 !important;
    height: 28px;
}
.navbar {min-height:28px !important;}

Update Complete code to customize and decrease height of navbar with screenshot.

enter image description here

CSS:

/* navbar */
.navbar-primary .navbar { background:#9f58b5; border-bottom:none; }
.navbar-primary .navbar .nav > li > a {color: #501762;}
.navbar-primary .navbar .nav > li > a:hover {color: #fff; background-color: #8e49a3;}
.navbar-primary .navbar .nav .active > a,.navbar .nav .active > a:hover {color: #fff; background-color: #501762;}
.navbar-primary .navbar .nav li > a .caret, .tnav .navbar .nav li > a:hover .caret {border-top-color: #fff;border-bottom-color: #fff;}
.navbar-primary .navbar .nav > li.dropdown.open.active > a:hover {}
.navbar-primary .navbar .nav > li.dropdown.open > a {color: #fff;background-color: #9f58b5;border-color: #fff;}
.navbar-primary .navbar .nav > li.dropdown.open.active > a:hover .caret, .tnav .navbar .nav > li.dropdown.open > a .caret {border-top-color: #fff;}
.navbar-primary .navbar .navbar-brand {color:#fff;}
.navbar-primary .navbar .nav.pull-right {margin-left: 10px; margin-right: 0;}
.navbar-xs .navbar-primary .navbar { min-height:28px; height: 28px; }
.navbar-xs .navbar-primary .navbar .navbar-brand{ padding: 0px 12px;font-size: 16px;line-height: 28px; }
.navbar-xs .navbar-primary .navbar .navbar-nav > li > a {  padding-top: 0px; padding-bottom: 0px; line-height: 28px; }
.navbar-sm .navbar-primary .navbar { min-height:40px; height: 40px; }
.navbar-sm .navbar-primary .navbar .navbar-brand{ padding: 0px 12px;font-size: 16px;line-height: 40px; }
.navbar-sm .navbar-primary .navbar .navbar-nav > li > a {  padding-top: 0px; padding-bottom: 0px; line-height: 40px; }

Usage Code:

<div class="navbar-xs">
   <div class="navbar-primary">
       <nav class="navbar navbar-static-top" role="navigation">
          <!-- Brand and toggle get grouped for better mobile display -->
          <div class="navbar-header">
              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-8">
                 <span class="sr-only">Toggle navigation</span>
                 <span class="icon-bar"></span>
                 <span class="icon-bar"></span>
                 <span class="icon-bar"></span>
              </button>
              <a class="navbar-brand" href="#">Brand</a>
          </div>
          <!-- Collect the nav links, forms, and other content for toggling -->
          <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-8">
              <ul class="nav navbar-nav">
                  <li class="active"><a href="#">Home</a></li>
                  <li><a href="#">Link</a></li>
                   <li><a href="#">Link</a></li>
              </ul>
          </div><!-- /.navbar-collapse -->
      </nav>
  </div>
</div>

Display MessageBox in ASP

<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
    alert("Hello!");
}
</script>

</body>
</html>

Copy Paste this in an HTML file and run in any browser , this should show an alert using javascript.

Extracting specific columns in numpy array

you can also use extractedData=data([:,1],[:,9])

INSERT SELECT statement in Oracle 11G

for inserting data into table you can write

insert into tablename values(column_name1,column_name2,column_name3);

but write the column_name in the sequence as per sequence in table ...

Measuring execution time of a function in C++

Here's a function that will measure the execution time of any function passed as argument:

#include <chrono>
#include <utility>

typedef std::chrono::high_resolution_clock::time_point TimeVar;

#define duration(a) std::chrono::duration_cast<std::chrono::nanoseconds>(a).count()
#define timeNow() std::chrono::high_resolution_clock::now()

template<typename F, typename... Args>
double funcTime(F func, Args&&... args){
    TimeVar t1=timeNow();
    func(std::forward<Args>(args)...);
    return duration(timeNow()-t1);
}

Example usage:

#include <iostream>
#include <algorithm>

typedef std::string String;

//first test function doing something
int countCharInString(String s, char delim){
    int count=0;
    String::size_type pos = s.find_first_of(delim);
    while ((pos = s.find_first_of(delim, pos)) != String::npos){
        count++;pos++;
    }
    return count;
}

//second test function doing the same thing in different way
int countWithAlgorithm(String s, char delim){
    return std::count(s.begin(),s.end(),delim);
}


int main(){
    std::cout<<"norm: "<<funcTime(countCharInString,"precision=10",'=')<<"\n";
    std::cout<<"algo: "<<funcTime(countWithAlgorithm,"precision=10",'=');
    return 0;
}

Output:

norm: 15555
algo: 2976

Plot 3D data in R

Adding to the solutions of others, I'd like to suggest using the plotly package for R, as this has worked well for me.

Below, I'm using the reformatted dataset suggested above, from xyz-tripplets to axis vectors x and y and a matrix z:

x <- 1:5/10
y <- 1:5
z <- x %o% y
z <- z + .2*z*runif(25) - .1*z

library(plotly)
plot_ly(x=x,y=y,z=z, type="surface")

enter image description here

The rendered surface can be rotated and scaled using the mouse. This works fairly well in RStudio.

You can also try it with the built-in volcano dataset from R:

plot_ly(z=volcano, type="surface")

enter image description here

What does -z mean in Bash?

-z string True if the string is null (an empty string)

What does `m_` variable prefix mean?

One argument that I haven't seen yet is that a prefix such as m_ can be used to prevent name clashing with #define'd macro's.

Regex search for #define [a-z][A-Za-z0-9_]*[^(] in /usr/include/term.h from curses/ncurses.

Spring security CORS Filter

In many places, I see the answer that needs to add this code:

@Bean
public FilterRegistrationBean corsFilter() {
   UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
   CorsConfiguration config = new CorsConfiguration();
   config.setAllowCredentials(true);
   config.addAllowedOrigin("*");
   config.addAllowedHeader("*");
   config.addAllowedMethod("*");
   source.registerCorsConfiguration("/**", config);
   FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
   bean.setOrder(0); 
   return bean;
}

but in my case, it throws an unexpected class type exception. corsFilter() bean requires CorsFilter type, so I have done this changes and put this definition of bean in my config and all is OK now.

@Bean
public CorsFilter corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
}

Get class labels from Keras functional model

In addition to @Emilia Apostolova answer to get the ground truth labels, from

generator = train_datagen.flow_from_directory("train", batch_size=batch_size)

just call

y_true_labels = generator.classes

How to implement common bash idioms in Python?

Any shell has several sets of features.

  • The Essential Linux/Unix commands. All of these are available through the subprocess library. This isn't always the best first choice for doing all external commands. Look also at shutil for some commands that are separate Linux commands, but you could probably implement directly in your Python scripts. Another huge batch of Linux commands are in the os library; you can do these more simply in Python.

    And -- bonus! -- more quickly. Each separate Linux command in the shell (with a few exceptions) forks a subprocess. By using Python shutil and os modules, you don't fork a subprocess.

  • The shell environment features. This includes stuff that sets a command's environment (current directory and environment variables and what-not). You can easily manage this from Python directly.

  • The shell programming features. This is all the process status code checking, the various logic commands (if, while, for, etc.) the test command and all of it's relatives. The function definition stuff. This is all much, much easier in Python. This is one of the huge victories in getting rid of bash and doing it in Python.

  • Interaction features. This includes command history and what-not. You don't need this for writing shell scripts. This is only for human interaction, and not for script-writing.

  • The shell file management features. This includes redirection and pipelines. This is trickier. Much of this can be done with subprocess. But some things that are easy in the shell are unpleasant in Python. Specifically stuff like (a | b; c ) | something >result. This runs two processes in parallel (with output of a as input to b), followed by a third process. The output from that sequence is run in parallel with something and the output is collected into a file named result. That's just complex to express in any other language.

Specific programs (awk, sed, grep, etc.) can often be rewritten as Python modules. Don't go overboard. Replace what you need and evolve your "grep" module. Don't start out writing a Python module that replaces "grep".

The best thing is that you can do this in steps.

  1. Replace AWK and PERL with Python. Leave everything else alone.
  2. Look at replacing GREP with Python. This can be a bit more complex, but your version of GREP can be tailored to your processing needs.
  3. Look at replacing FIND with Python loops that use os.walk. This is a big win because you don't spawn as many processes.
  4. Look at replacing common shell logic (loops, decisions, etc.) with Python scripts.